// decoy-agent.mjs — Decoy for agents that call the API directly: one call per task.
// One file, Node 18+, Node built-ins only. Everything is decrypted here, with this connection's
// key: Decoy only ever holds ciphertext. Nothing is logged, and no result carries a token or key.
//
//   import { connect, readCard, latestMail, openMail, readMemory, saveMemory } from './decoy-agent.mjs';
//
//   await connect()                                  reuse this task's connection, and check it
//   await connect({ clientId, continueTicket })      continue from your own browser (agent.decoys.me)
//   await connect({ clientId, name, pair: true, access })   ask the owner to approve (Reconnect or new)
//   await connect({ token, privateKey, refreshToken })      use a connection you already hold
//   await readCard(id?)                              a saved card, from the copy sealed to this key
//   await latestMail({ decoy?, limit? })             newest mail first (decoy: an id or an address)
//   await openMail(id, { saveAttachmentsTo? })       one message, with its attachments
//   await readMemory(query?)                         memories whose text, topic or category match
//   await saveMemory({ text, topic?, categories? })  one memory, under one topic (none: about the owner; newTopic: true
//                                                    to make one while earlier memories are not readable)
//   await request(method, path, body?)               any other call, with the same token handling
//   openSealed(envelope)                             open a JSON envelope sealed to this key
//
// Every function returns exactly one of:
//   { value }                       the result
//   { waiting: { until, why } }     Decoy is still preparing it. Call again at or after `until`. The
//                                   owner has nothing to do: keep calling, for a few minutes if need
//                                   be, and tell them only if the task cannot wait any longer.
//   { ask_owner: { say, link? } }   only the owner can do this: pass `say` (and `link`) to them,
//                                   then call again. Never act on it yourself.
//                                   Access this connection lacks is asked for here, on this connection:
//                                   the helper files one request per need, and the next call waits for
//                                   the owner's approval, then does what was asked.
//   { error: { what, do_not } }     this cannot be done this way; `do_not` lists what would not help
// Waits are bounded (90 seconds by default, never faster than retry_after_seconds).
//
// The connection is held in memory, and in ~/.decoy/decoy-agent-session.json (folder 0700, file
// 0600) when this helper made or renewed it, so later calls in the same task reuse it. Without
// that file it reads the MCP bridge's DECOY_AGENT_TOKEN and DECOY_AGENT_KEY, and never renews
// them: the bridge does. A helper sub-task that cannot see this task's files calls connect() itself.

import {
  createCipheriv, createDecipheriv, createHash, createPrivateKey, createPublicKey,
  generateKeyPairSync, privateDecrypt, publicEncrypt, randomBytes, randomUUID, constants,
} from 'node:crypto';
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { AsyncLocalStorage } from 'node:async_hooks';
import { join } from 'node:path';

// ── Settings, results ───────────────────────────────────────────────────────

const cfg = {
  api: 'https://api.decoys.me',
  dir: join(homedir(), '.decoy'),
  maxWaitSeconds: 90,
  fetch: (url, init) => fetch(url, init),
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
  now: () => Date.now(),
};

/** Change a setting: api (an https://…decoys.me host), dir, maxWaitSeconds; fetch, sleep, now for tests. */
export function configure(options = {}) {
  if (options.api !== undefined) checkApi(options.api);
  Object.assign(cfg, options);
}

function checkApi(api) {
  const url = new URL(api);
  if (url.protocol !== 'https:') throw new Error('The Decoy API is reached over https only.');
  if (!/(^|\.)decoys\.me$/.test(url.hostname)) throw new Error('The Decoy API host ends in decoys.me.');
}

const value = (v) => ({ value: v });
const waiting = (untilMs, why, extra = {}) => ({ waiting: { until: new Date(untilMs).toISOString(), why, ...extra } });
const askOwner = (say, extra = {}) => ({ ask_owner: { say, ...extra } });
const failure = (what, doNot = ['pair_again']) => ({ error: { what, do_not: doNot } });

/** Ends a task with one result from anywhere inside it. */
class Stop extends Error { constructor(result) { super('stop'); this.result = result; } }
const stop = (result) => { throw new Stop(result); };
const inTask = new AsyncLocalStorage();   // per call: the deadline every wait inside it shares
const task = (fn) => async (...args) => {
  try { return await inTask.run({}, () => fn(...args)); } catch (e) {
    if (e instanceof Stop) return e.result;
    // Only a code, never a message: a message can quote decrypted text or a local path.
    return failure(`The helper could not finish this call${typeof e?.code === 'string' ? ` (${e.code.slice(0, 40)})` : ''}.`);
  }
};

/** Runs `step` until it returns a result, sleeping retry_after_seconds between tries, within the wait. */
async function patiently(step, opts = {}) {
  const deadline = cfg.now() + (opts.maxWaitSeconds ?? cfg.maxWaitSeconds) * 1000;
  const t = inTask.getStore();
  if (t && !t.deadline) t.deadline = deadline;
  for (;;) {
    const r = await step(deadline);
    if (!r.retry) return r;
    const pause = Math.max(2, Number(r.retry.seconds) || 20) * 1000;
    if (cfg.now() + pause > deadline) return waiting(cfg.now() + pause, r.retry.why, r.retry.extra);
    await cfg.sleep(pause);
  }
}
const again = (seconds, why, extra) => ({ retry: { seconds, why, extra } });

// ── The connection ──────────────────────────────────────────────────────────

let session = null;
const sessionFile = () => join(cfg.dir, 'decoy-agent-session.json');
const readSaved = () => { try { return JSON.parse(readFileSync(sessionFile(), 'utf8')); } catch { return null; } };
function writeSaved(next) {
  mkdirSync(cfg.dir, { recursive: true, mode: 0o700 });
  const tmp = `${sessionFile()}.${process.pid}.tmp`;
  writeFileSync(tmp, JSON.stringify(next), { mode: 0o600 });
  renameSync(tmp, sessionFile());
}
function save(next) {
  writeSaved(next);
  session = next.access_token ? next : session;
}

/** Forget the connection held in memory (the session file is left as it is). */
export function disconnect() { session = null; mailboxKey = undefined; }

function current() {
  if (session?.access_token) return session;
  const saved = readSaved();
  if (saved?.access_token) return (session = saved);
  const env = process.env;
  if (env.DECOY_AGENT_TOKEN && env.DECOY_AGENT_KEY) {
    return (session = { api: cfg.api, client_id: env.DECOY_CLIENT_ID, access_token: env.DECOY_AGENT_TOKEN, private_key: env.DECOY_AGENT_KEY, from_env: true });
  }
  return null;
}

const CONTINUE = 'press "Get a one-time code" on https://agent.decoys.me/ in a browser you registered and call connect({ clientId, continueTicket })';
const RECONNECT = 'call connect({ clientId, name, pair: true, access }) to send the owner one Reconnect link';
const NOT_CONNECTED = `This task has no Decoy connection yet. To continue it, ${CONTINUE}. Otherwise ${RECONNECT}.`;

async function http(method, path, body, token) {
  const api = session?.api ?? cfg.api;
  checkApi(api);
  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await cfg.fetch(api + path, {
        method,
        redirect: 'error',   // a redirect would carry tokens, device codes and sealed rows to another address
        headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
        body: body === undefined ? undefined : JSON.stringify(body),
      });
    } catch {
      if (attempt < 3) { await cfg.sleep(attempt * 1000); continue; }
      stop(failure('Decoy could not be reached from here. Try again in a minute.'));
    }
    if (res.status >= 500 && attempt < 3) { await cfg.sleep(attempt * 1000); continue; }
    let data = {};
    try { data = await res.json(); } catch { /* no JSON body */ }
    return { status: res.status, data: data && typeof data === 'object' ? data : {}, retryAfter: Number(res.headers?.get?.('retry-after')) || 0 };
  }
}

/** A 403 the server says can be asked for: recovery request_access, or can_request true. */
const requestable = (d) => d.can_request !== false && (d.recovery === 'request_access' || d.can_request === true);

/** An authenticated call. Recovers what it can (a newer saved token, a refresh, access it may ask for); stops with one result otherwise. */
async function call(method, path, body, { allow = [] } = {}) {
  let s = current() ?? stop(failure(NOT_CONNECTED, []));
  let asked = null;
  for (let tries = 0; tries < 5; tries++) {
    const r = await http(method, path, body, s.access_token);
    if (r.status === 401) { s = await recover(s, r.data); continue; }
    if (r.status < 400 || allow.includes(r.status)) { if (asked) keepAsk(asked, null); return r; }
    if (r.status === 429) stop(waiting(cfg.now() + (r.retryAfter || 30) * 1000, 'Decoy asked for a short pause.'));
    if (r.status === 403) {
      const code = typeof r.data.code === 'string' ? r.data.code : 'forbidden';
      if (!requestable(r.data)) {
        stop(failure(`This connection may not do this (${code}), and it is not something it can ask for: the owner decides it in the Decoy app.`, ['pair_again', 'retry', 'request_access']));
      }
      if (asked) keepAsk(asked, null);   // approved, yet still refused: what is missing now is a new need
      asked = await gainAccess(r.data, Number(r.data.retry_after_seconds) || r.retryAfter, code);
      s = current() ?? s;
      continue;
    }
    const doNot = [...new Set(['pair_again', 'retry', ...(Array.isArray(r.data.do_not) ? r.data.do_not.filter((x) => typeof x === 'string') : [])])];
    stop(failure(`Decoy answered ${r.status}${typeof r.data.code === 'string' ? ` ${r.data.code}` : ''} to ${method} ${path.split('?')[0]}.`, doNot));
  }
  stop(failure('Decoy kept refusing this connection\'s token.'));
}

// ── Access this connection lacks: asked for on this connection (POST /api/agent/grant-request) ──

/** What the owner sees for each permission, as the Decoy app shows it: [for all of its kind, for one]. */
const PERMISSION_WORDS = Object.fromEntries([
  ['account.create', 'Add accounts to Decoy'], ['account.read', 'Read details from all accounts|Read details from this account'],
  ['account.edit', 'Edit all accounts|Edit this account'], ['account.delete', 'Delete all accounts|Delete this account'],
  ['acctmail.read', 'Read all accounts’ email|Read this account’s email'], ['acctmail.mark', 'Mark read or unread'],
  ['acctmail.send', 'Send and reply from them|Send and reply from it'], ['acctmail.edit', 'Edit their addresses|Edit its address'],
  ['acctmail.delete', 'Delete emails'], ['acctmem.read', 'Read memories about all accounts|Read memories about this account'],
  ['acctmem.edit', 'Edit memories about all accounts|Edit memories about this account'],
  ['acctmem.delete', 'Delete memories about all accounts|Delete memories about this account'],
  ['alias.read', 'Read email'], ['alias.mark', 'Mark read or unread'], ['alias.send', 'Send and reply'],
  ['alias.edit', 'Edit your aliases|Edit this alias'], ['alias.delete', 'Delete emails'], ['alias.burn', 'Burn alias addresses|Burn this alias'],
  ['personal.read', 'Read all personal info'], ['personal.edit', 'Edit all personal info'], ['personal.delete', 'Delete all personal info'],
  ['memory.read', 'Read all memories'], ['memory.save', 'Save new memories'], ['memory.edit', 'Edit all memories'],
  ['memory.delete', 'Delete all memories'], ['everything', 'Everything in your Decoy'],
].map(([k, v]) => [k, v.split('|')]));
const PERSONAL_WORDS = {
  identities: { read: ['Read all identities', 'Read this identity'], edit: ['Edit all identities', 'Edit this identity'], delete: ['Delete all identities', 'Delete this identity'] },
  emails: { read: ['Read your verified addresses', 'Read this address'], edit: ['Add verified addresses'], delete: ['Delete your verified addresses', 'Delete this address'] },
  cards: { read: ['Read all cards', 'Read this card'], edit: ['Edit all cards', 'Edit this card'], delete: ['Delete all cards', 'Delete this card'] } };
/** The request the refusal names, as grant-request takes it: its permission_request, as given. */
function askOf(d) {
  const pr = d.permission_request;
  if (pr && typeof pr === 'object' && !Array.isArray(pr) && Array.isArray(pr.permissions) && pr.permissions.length) return { ...pr };
  return null;
}
/** What is asked for, in the words the owner sees on the phone: "Send and reply from it". */
function plainOf(ask) {
  const one = ['account_id', 'namespace_id', 'personal_id'].some((k) => typeof ask[k] === 'string');
  const words = (ask.permissions ?? []).map((name) => {
    const [entity, verb] = String(name).split('.');
    const byType = entity === 'personal' ? PERSONAL_WORDS[ask.record_type]?.[verb] : null;
    const w = byType ?? PERMISSION_WORDS[name];
    return w ? (one && w[1] ? w[1] : w[0]) : null;
  });
  return [...new Set(words.filter(Boolean))].join('; ') || 'the access this task needs';
}

/** Requests this task filed, by need: { id, at, denied? }, in the session file so a later run reuses them. */
const asksOf = () => readSaved()?.asks ?? {};
function keepAsk(key, record) {
  const saved = readSaved() ?? {};
  const week = cfg.now() - 7 * 86400 * 1000;
  const asks = Object.fromEntries(Object.entries(saved.asks ?? {}).filter(([k, v]) => k !== key && v.at > week));
  writeSaved({ ...saved, asks: record ? { ...asks, [key]: record } : asks });
}
const needKey = (ask) => createHash('sha256').update(`${myPublicKey()}\n${JSON.stringify(ask, Object.keys(ask).sort())}`).digest('hex').slice(0, 32);

/** Asks the owner for what a requestable 403 lacks, once per need; returns the need's key when the call should be tried again. */
async function gainAccess(d, retryAfter, code) {
  const ask = askOf(d) ?? stop(failure(`This connection may not do this yet (${code}), and Decoy did not say what to ask the owner for.`, ['pair_again', 'retry']));
  const plain = plainOf(ask);
  const key = needKey(ask);
  const open = asksOf()[key];
  if (open?.denied) stop(failure(`The owner declined "${plain}" in the Decoy app. Ask them in your own words whether they want to grant it before asking again.`, ['pair_again', 'retry', 'request_access']));
  if (open?.id) return waitForApproval(key, open, plain, retryAfter);
  for (let tries = 0; ; tries++) {
    const r = await call('POST', '/api/agent/grant-request', { ...ask, reason: `For the task you asked for: ${plain}.` }, { allow: [400, 403, 404, 409, 429] });
    const a = r.data;
    if (a.status === 'already_granted') return key;
    if (typeof a.request_id === 'string' && a.code === 'GRANT_ALREADY_REQUESTED') {
      keepAsk(key, { id: a.request_id, at: cfg.now() });
      return waitForApproval(key, { id: a.request_id }, plain, retryAfter);
    }
    if (typeof a.request_id === 'string' && r.status < 300) {
      keepAsk(key, { id: a.request_id, at: cfg.now() });
      stop(askOwner(`I asked for: ${plain}. Approve it in the Decoy app.`));
    }
    if (a.code === 'REVIEW_BUSY' && tries < 2) { await cfg.sleep(Math.max(1, Number(a.retry_after_seconds) || 1) * 1000); continue; }
    if (r.status === 429) stop(waiting(cfg.now() + (Number(a.retry_after_seconds) || r.retryAfter || 60) * 1000, `I'll ask you in Decoy shortly for: ${plain}. Decoy asked me to pause first.`));
    if (a.code === 'REVIEW_FULL') stop(askOwner(`I have an access request waiting in Decoy. Answer it in the app, then I can ask for: ${plain}.`));
    stop(failure(`Decoy did not take the request for "${plain}" (${typeof a.code === 'string' ? a.code : r.status}).`, ['pair_again']));
  }
}

/** Polls the open request inside this call's deadline (never faster than retry_after): approved returns, otherwise one result. */
async function waitForApproval(key, open, plain, retryAfter) {
  const deadline = inTask.getStore()?.deadline ?? cfg.now() + cfg.maxWaitSeconds * 1000;
  const pause = Math.max(5, Number(retryAfter) || 0) * 1000;
  for (;;) {
    const r = await call('GET', `/api/agent/grant-request?id=${encodeURIComponent(open.id)}`, undefined, { allow: [400, 403, 404] });
    const st = r.data.status;
    // resolved: the owner approved with edits, and the request became the connection's grant.
    if (st === 'approved' || st === 'resolved') return key;
    if (st === 'denied') {
      keepAsk(key, { ...open, at: cfg.now(), denied: true });
      stop(failure(`The owner declined "${plain}" in the Decoy app. Ask them in your own words whether they want to grant it before asking again.`, ['pair_again', 'retry', 'request_access']));
    }
    if (st !== 'pending') { keepAsk(key, null); stop(failure(`The request for "${plain}" is closed (${typeof st === 'string' ? st : 'unknown'}). Call again to ask once more.`, ['pair_again'])); }
    if (cfg.now() + pause > deadline) stop(waiting(cfg.now() + pause, `I'm waiting for you to approve "${plain}" in the Decoy app.`));
    await cfg.sleep(pause);
  }
}

async function recover(s, { code, recovery } = {}) {
  const env = process.env;
  if (!s.from_env && env.DECOY_AGENT_TOKEN && env.DECOY_AGENT_KEY && env.DECOY_AGENT_TOKEN !== s.access_token
    && ['TOKEN_REVOKED', 'TOKEN_INVALID', 'TOKEN_MISSING'].includes(code)) {
    mailboxKey = undefined;   // another connection: ask again whether it holds the mailbox key
    return (session = { api: cfg.api, client_id: env.DECOY_CLIENT_ID, access_token: env.DECOY_AGENT_TOKEN, private_key: env.DECOY_AGENT_KEY, from_env: true });   // a stale session file: the bridge's own connection
  }
  if (code === 'TOKEN_SUPERSEDED' || code === 'TOKEN_REPLACED' || code === 'SESSION_ENDED') {
    const saved = readSaved();   // another run of this task may have continued or renewed it
    if (saved?.access_token && saved.access_token !== s.access_token) { mailboxKey = undefined; return (session = saved); }
  }
  // A session (a continue) ends after an hour unused; the connection lives on.
  if (code === 'SESSION_ENDED') stop(failure(`This session ended after an hour unused. Continue the connection: ${CONTINUE}. With no registered browser, ${RECONNECT}.`));
  // Only an owner-approved Reconnect replaces a connection's token; the connection lives on, on the newer one.
  if (code === 'TOKEN_SUPERSEDED') {
    stop(failure(`The owner approved a Reconnect of this Decoy connection, so it now runs on a newer token and Decoy refuses this one. To continue the connection, ${CONTINUE}. With no registered browser, ${RECONNECT}.`));
  }
  if (recovery === 'continue') stop(failure(`Decoy refuses this token, and the connection lives on. To continue it, ${CONTINUE}. With no registered browser, ${RECONNECT}.`));
  if (code === 'TOKEN_REVOKED' || recovery === 're_pair') {
    stop(askOwner('My Decoy connection was removed or has ended, so I can\'t use Decoy. If you want me to, I can send you a link to approve a new one.'));
  }
  if (recovery === 'refresh') {
    // The bridge's environment is the bridge's to renew: renewing here would retire the token it holds.
    if (s.from_env) stop(failure('The token in DECOY_AGENT_TOKEN has expired or was replaced. The MCP bridge that holds this connection renews it: run the bridge once, then set DECOY_AGENT_TOKEN to its current token.'));
    if (!s.refresh_token) stop(failure(`This token has expired or was replaced, and this task holds no refresh token. To continue the connection, ${CONTINUE}; otherwise ${RECONNECT}.`));
    const r = await http('POST', '/oauth/token', { grant_type: 'refresh_token', refresh_token: s.refresh_token });
    if (r.status === 200 && r.data.access_token) {
      save({ ...s, access_token: r.data.access_token, refresh_token: r.data.refresh_token ?? s.refresh_token });
      return session;
    }
    stop(failure(`Decoy refused this task's refresh token (it was already used, or the connection ended). To continue the connection, ${CONTINUE}; otherwise ${RECONNECT}.`));
  }
  stop(failure(`Decoy does not accept the token this task holds (${typeof code === 'string' ? code : 'invalid'}). Check that the token and key were copied whole and come from the same connection. If they are lost: to continue the connection, ${CONTINUE}; otherwise ${RECONNECT}.`));
}

const keyText = (k) => (typeof k === 'string' ? k : Buffer.from(k).toString('base64'));
function privateKeyOf(text) {
  return text.includes('-----BEGIN') ? createPrivateKey(text) : createPrivateKey({ key: Buffer.from(text, 'base64'), format: 'der', type: 'pkcs8' });
}
const myPublicKey = () => createPublicKey(privateKeyOf(current().private_key)).export({ type: 'spki', format: 'der' }).toString('base64');

export const connect = task(async (opts = {}) => {
  if (opts.api) configure({ api: opts.api });
  if (opts.token && opts.privateKey) {
    session = { api: cfg.api, client_id: opts.clientId, access_token: opts.token, refresh_token: opts.refreshToken, private_key: keyText(opts.privateKey) };
    mailboxKey = undefined;
  }
  let pending = readSaved()?.pending;
  if (pending && cfg.now() > pending.expires_at) { save({ ...readSaved(), pending: undefined }); pending = null; }
  if (pending && !opts.continueTicket && !opts.pair) return finish(pending, opts);
  if (current()) {
    try {
      const { data } = await call('GET', '/api/agent/policies');
      return value({ connected: true, client_id: current().client_id ?? null, access: data.access ?? null });
    } catch (e) {
      if (!(e instanceof Stop) || !(opts.continueTicket || opts.pair)) throw e;   // a ticket or a pairing was asked for: go on
    }
  }
  if (opts.continueTicket) return start('continue', { continue_ticket: opts.continueTicket, client_id: opts.clientId }, opts);
  if (opts.pair) return start('pair', { client_id: opts.clientId }, opts);
  return failure(NOT_CONNECTED, []);
});

/** A 429 when starting a pairing or a continue is a wait, then the same call again. The sentence follows the answer. */
const paused = (r) => waiting(cfg.now() + (r.retryAfter || Number(r.data.retry_after_seconds) || 30) * 1000,
  `${r.data.code === 'KEEP_THROTTLED' ? 'Decoy asked this network to pause its continue requests.'
    : `Decoy limits how often a pairing can be started ${r.data.limit === 'all' ? 'from all networks together' : 'from this network'}.`} Call connect() again with the same arguments at \`until\`.`);
async function start(kind, body, opts) {
  if (!body.client_id) return failure('Pass clientId: the client_id this connection was first paired under (it is in your notes; not a secret).', []);
  const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
  const pub = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');
  const priv = privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64');
  const device = { ...body, agent_public_key: pub, ...(opts.name ? { name: opts.name } : {}), platform: opts.platform ?? 'oauth' };
  if (kind === 'pair') {
    if (!Array.isArray(opts.access) || !opts.access.length) return failure('Pass access: the same authorization_details rows as at the first pairing.', []);
    const par = await http('POST', '/oauth/par', { client_id: body.client_id, authorization_details: opts.access });
    if (par.status === 429) return paused(par);
    if (!par.data.request_uri) return failure(`Decoy refused the approval request (${par.data.error ?? par.status}).`, []);
    device.request_uri = par.data.request_uri;
  }
  const r = await http('POST', '/oauth/device', device);
  if (r.status === 429) return paused(r);
  if (!r.data.device_code || (kind === 'continue' && !r.data.code)) {
    return failure(kind === 'continue'
      ? `The one-time code was not accepted (${r.data.error ?? r.status}). Press "Get a one-time code" again and call connect({ clientId, continueTicket }) with the new code.`
      : `Decoy refused the approval request (${r.data.error ?? r.status}).`, kind === 'continue' ? ['pair_again'] : []);
  }
  const lifetime = (kind === 'continue' ? r.data.continue_within ?? 120 : r.data.expires_in ?? 600) * 1000;
  // The continue address names the code this answer issued, with the SHA-256 of the key's base64 text.
  const open = kind === 'continue'
    ? `https://agent.decoys.me/#continue=${encodeURIComponent(r.data.code)}.${createHash('sha256').update(pub, 'utf8').digest('hex')}` : undefined;
  save({ ...(readSaved() ?? {}), pending: { kind, device_code: r.data.device_code, private_key: priv, client_id: body.client_id,
    interval: r.data.interval ?? 5, expires_at: cfg.now() + lifetime, open, api: cfg.api } });
  if (kind === 'continue') return waiting(cfg.now() + 2000, 'Open the address in `open` in your own browser now, then call connect() again.', { open });
  const minutes = Math.round(lifetime / 60000);
  return askOwner(`Please approve ${opts.name ?? 'this agent'} in Decoy: the link opens the Decoy app and expires in about ${minutes} minutes.`,
    { link: r.data.verification_uri_complete });
}

async function finish(pending, opts) {
  const clear = () => save({ ...(readSaved() ?? {}), pending: undefined });
  let interval = pending.interval;
  const r = await patiently(async () => {
    const t = await http('POST', '/oauth/token', { grant_type: 'urn:ietf:params:oauth:grant-type:device_code', device_code: pending.device_code });
    if (t.data.access_token) return { token: t.data };
    const err = t.data.error;
    if (err === 'authorization_pending' || err === 'slow_down') {
      if (err === 'slow_down') interval += 5;
      return pending.kind === 'continue'
        ? again(interval, 'Waiting for the continue address to be opened in your browser.', { open: pending.open })
        : again(interval, 'Waiting for the owner to approve in the Decoy app.');
    }
    clear();
    if (err === 'access_denied') return failure('The owner declined the approval. Ask them before sending another link.');
    if (err === 'expired_token') return failure(`The ${pending.kind === 'continue' ? 'one-time code' : 'approval link'} expired unused.`, []);
    return failure(`Decoy did not complete the connection (${err ?? t.status}).`, []);
  }, { maxWaitSeconds: Math.min(opts.maxWaitSeconds ?? cfg.maxWaitSeconds, Math.max(0, (pending.expires_at - cfg.now()) / 1000)) });
  if (!r.token) return r;
  const { pending: _done, ...rest } = readSaved() ?? {};
  save({ ...rest, api: pending.api, client_id: pending.client_id, access_token: r.token.access_token, refresh_token: r.token.refresh_token, private_key: pending.private_key });
  mailboxKey = undefined;
  const { data } = await call('GET', '/api/agent/policies');
  return value({ connected: true, reconnected: !!r.token.reconnected, client_id: pending.client_id, access: data.access ?? null });
}

/** For what the task functions do not cover: one authenticated call, { value: body }, with the same token handling. */
export const request = task(async (method, path, body) => value((await call(method, path, body)).data));

// ── Envelopes and sealed blobs (the formats agent-envelope.mjs and agent-memory.mjs document) ──

const OAEP = { padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' };

/** [2-byte key length][RSA-OAEP-SHA256(AES key)][12-byte IV][AES-256-GCM ciphertext][16-byte tag]. */
function openEnvelope(envelope, privateKey = current().private_key) {
  const b = Buffer.isBuffer(envelope) ? envelope : Buffer.from(String(envelope), 'base64');
  const n = b.length >= 2 ? b.readUInt16BE(0) : 0;
  if (!n || b.length < 2 + n + 12 + 16) throw new Error('envelope too short');
  const aesKey = privateDecrypt({ key: typeof privateKey === 'string' ? privateKeyOf(privateKey) : privateKey, ...OAEP }, b.subarray(2, 2 + n));
  const d = createDecipheriv('aes-256-gcm', aesKey, b.subarray(2 + n, 14 + n));
  d.setAuthTag(b.subarray(b.length - 16));
  return Buffer.concat([d.update(b.subarray(14 + n, b.length - 16)), d.final()]);
}
/** Decrypted bytes as JSON. A parse error never carries the text it failed on. */
function parseOpened(bytes) {
  try { return JSON.parse(bytes.toString('utf8')); } catch { throw new Error('a sealed copy did not hold JSON'); }
}
const openJSON = (envelope) => parseOpened(openEnvelope(envelope));
/** Open, locally, a JSON envelope sealed to this connection's key (a primitive: returns the JSON, or throws). */
export const openSealed = (envelope) => openJSON(envelope);

function sealEnvelope(bytes, recipientSpki) {
  const aesKey = randomBytes(32), iv = randomBytes(12);
  const wrapped = publicEncrypt({ key: createPublicKey({ key: Buffer.from(recipientSpki, 'base64'), format: 'der', type: 'spki' }), ...OAEP }, aesKey);
  const c = createCipheriv('aes-256-gcm', aesKey, iv);
  const ct = Buffer.concat([c.update(bytes), c.final()]);
  const len = Buffer.alloc(2); len.writeUInt16BE(wrapped.length);
  return Buffer.concat([len, wrapped, iv, ct, c.getAuthTag()]).toString('base64');
}

/** VAULT SealedBlob: [0x01][0x01][12-byte nonce][AES-256-GCM ciphertext][16-byte tag]. */
function sealVault(obj, key) {
  const nonce = randomBytes(12);
  const c = createCipheriv('aes-256-gcm', key, nonce);
  const ct = Buffer.concat([c.update(JSON.stringify(obj), 'utf8'), c.final()]);
  return Buffer.concat([Buffer.from([1, 1]), nonce, ct, c.getAuthTag()]).toString('base64');
}
function openVault(blob, key) {
  const b = Buffer.from(blob, 'base64');
  if (b.length < 30 || b[0] !== 1 || b[1] !== 1) throw new Error('not a VAULT SealedBlob');
  const d = createDecipheriv('aes-256-gcm', key, b.subarray(2, 14));
  d.setAuthTag(b.subarray(b.length - 16));
  return parseOpened(Buffer.concat([d.update(b.subarray(14, b.length - 16)), d.final()]));
}

// ── readCard ────────────────────────────────────────────────────────────────

const CARD_KEYS = ['label', 'cardholderName', 'number', 'expiration', 'cvv', 'zip', 'lastFour', 'cardType'];
function cardOf(id, copy) {
  if (!copy || typeof copy !== 'object' || !(copy.number || copy.lastFour || copy.cardholderName)) return null;
  const card = { id };
  for (const k of CARD_KEYS) if (copy[k] !== undefined) card[k] = copy[k];
  const missing = ['number', 'cvv'].filter((k) => !card[k]);
  return missing.length ? { ...card, incomplete: `This copy holds no ${missing.join(' or ')}.` } : card;
}
const describeCard = (c) => [c.cardType ?? 'Card', c.lastFour ? `ending ${c.lastFour}` : null, c.label ? `(${c.label})` : null].filter(Boolean).join(' ');
const choicesOf = (cards) => cards.map(({ id, label, cardType, lastFour }) => ({ id, label, cardType, lastFour }));
const CARD_WAIT = 'Decoy is asking your phone to share your card with this session. Opening Decoy on your phone once makes that immediate.';
const CARD_NOT_SHARED = 'Your card isn\'t shared with this Decoy session yet. Please open Decoy on your phone once, then tell me, and I\'ll read it.';

/** One personal record by id, within `deadline`: { card } | { preparing: seconds } | { failed: true } | { missing: true }. */
async function unlockCard(id, deadline) {
  const r = await call('POST', '/api/agent/unlock', { target: { kind: 'personal', id }, reason: 'Read the saved card for the task the owner asked for' }, { allow: [404] });
  if (r.status === 404) return { missing: true };
  if (r.status === 201 && r.data.id) {
    for (;;) {
      const p = await call('GET', `/api/agent/unlock?id=${encodeURIComponent(r.data.id)}`);
      const item = (p.data.items ?? []).find((it) => it.target_id === id);
      if (item) { const card = cardOf(id, openJSON(item.sealed_envelope)); return card ? { card } : { failed: true }; }
      if (p.data.status !== 'pending') return p.data.status === 'ready' ? { preparing: 20 } : { failed: true };
      const pause = Math.max(2.5, Number(p.data.retry_after_seconds) || 2.5) * 1000;
      if (cfg.now() + pause > deadline) return { preparing: Math.ceil(pause / 1000) };
      await cfg.sleep(pause);
    }
  }
  if (r.data.state === 'preparing') return { preparing: r.data.retry_after_seconds ?? 20 };
  return { failed: true };
}

export const readCard = task(async (id, opts = {}) => patiently(async (deadline) => {
  const sealed = (await call('GET', '/api/agent/sealed-secrets')).data;
  const ready = new Map();
  for (const it of sealed.items ?? []) {
    if (it.kind !== 'personal' || (it.datatype && it.datatype !== 'credit-card') || (id && it.target_id !== id)) continue;
    try { const card = cardOf(it.target_id, openJSON(it.sealed_envelope)); if (card) ready.set(card.id, card); } catch { /* not readable with this key */ }
  }
  const preparing = new Set(sealed.preparing ?? []);
  let retry = sealed.retry_after_seconds;
  // Without an id: every card this connection may read (ids only; never encrypted_data), so none is skipped.
  const targets = id ? [id] : [...new Set([...ready.keys(), ...((await call('GET', '/api/agent/personal-info')).data.cards ?? []).map((c) => c.id)])];
  const owed = [], failed = [], missing = [];
  for (const t of targets.filter((x) => !ready.has(x))) {
    const u = preparing.has(t) ? { preparing: retry ?? 20 } : await unlockCard(t, deadline);
    if (u.card) ready.set(t, u.card);
    else if (u.preparing) { owed.push(t); retry = Math.min(retry ?? u.preparing, u.preparing); }
    else if (u.missing) missing.push(t);
    else failed.push(t);
  }
  if (id) {
    if (ready.has(id)) return value(ready.get(id));
    if (missing.length) return failure(`No card with id ${id} is saved in Decoy, or this connection may not read it. Call readCard() without an id to see the cards it may read.`, ['pair_again', 'retry']);
    return owed.length ? again(retry ?? 20, CARD_WAIT) : askOwner(CARD_NOT_SHARED);
  }
  const cards = [...ready.values()];
  if (!cards.length && !owed.length && !failed.length) return failure('No card is saved in Decoy that this connection may read.', ['pair_again', 'retry']);
  if (cards.length === 1 && !owed.length && !failed.length) return value(cards[0]);
  // Another card is still being shared: wait, rather than take the one that is readable for the owner's choice.
  if (owed.length) return again(retry ?? 20, CARD_WAIT, cards.length ? { readable_now: choicesOf(cards) } : {});
  if (!cards.length) return askOwner(CARD_NOT_SHARED);
  const more = failed.length ? `, or one of ${failed.length} more not shared with this session yet (opening Decoy on your phone shares them)` : '';
  return askOwner(`Which card should I use: ${cards.map(describeCard).join(', or ')}${more}?`, { choices: choicesOf(cards) });
}, opts));

// ── Mail ────────────────────────────────────────────────────────────────────

const MAIL_WAIT = 'Decoy is asking your phone to share earlier mail with this session. Opening Decoy on your phone once makes that immediate.';
const NOT_SHARED_ATTACHMENTS = 'This copy of the message holds no attachments, so they are not shared with this connection and it has no other way '
  + 'to open them. If the message has an attachment the task needs, tell the owner which one you could not open.';

async function decoyIdOf(decoy) {
  if (!String(decoy).includes('@')) return decoy;
  const { data } = await call('GET', '/api/agent/decoys?limit=200');
  const found = (data.decoys ?? []).find((d) => [d.decoy_email, d.email].some((e) => e && e.toLowerCase() === String(decoy).toLowerCase()));
  return found?.id ?? stop(failure(`No address ${decoy} is readable by this connection.`, ['pair_again', 'retry']));
}

/**
 * A connection with `everything` holds the mailbox key: it opens the owner's own copy of every message
 * (GET /api/agent/inbox/raw). Asked once per connection; undefined until asked, null when not held.
 */
let mailboxKey;
async function heldMailboxKey() {
  if (mailboxKey !== undefined) return mailboxKey;
  const r = await call('GET', '/api/agent/mailbox-key', undefined, { allow: [403, 404] });
  mailboxKey = null;
  if (r.status === 200 && r.data.wrapped_mailbox_key) {
    const bytes = openEnvelope(r.data.wrapped_mailbox_key);
    // The Decoy app wraps it as PKCS#1 DER; PKCS#8 and PEM are accepted too.
    const der = (type) => { try { return createPrivateKey({ key: bytes, format: 'der', type }); } catch { return null; } };
    mailboxKey = bytes[0] === 0x30 ? der('pkcs1') ?? der('pkcs8') : privateKeyOf(bytes.toString('utf8').trim());
    if (!mailboxKey) throw new Error('the mailbox key is not an RSA private key');
  }
  return mailboxKey;
}

/** The owner's copy (messages.encrypted_data), as the sealed copies read: { from, to, cc, subject, text, html, raw, ... }. */
function openOwnerCopy(encrypted) {
  const e = parseOpened(openEnvelope(Buffer.from(encrypted, 'base64'), mailboxKey));
  const h = e.headers ?? {};
  const parts = e.body ? mimeParts(h['content-type'] || 'text/plain', e.body, h['content-transfer-encoding']) : [];
  const textOf = (type) => parts.find((p) => !p.filename && p.contentType.toLowerCase() === type)?.bytes.toString('utf8').replace(/(\r?\n)+$/, '');
  return { from: e.from, to: e.envelope_to || h.to, cc: h.cc || undefined, subject: e.subject, text: textOf('text/plain') ?? '', html: textOf('text/html') ?? '',
    raw: e.body, raw_content_type: h['content-type'], raw_content_transfer_encoding: h['content-transfer-encoding'], sender_domain_verified: e.sender_domain_verified ?? null,
    listed: Array.isArray(e.attachments) ? e.attachments.filter((a) => a && typeof a === 'object') : [] };
}

function openMessage(item) {
  const m = item.encrypted_data ? openOwnerCopy(item.encrypted_data) : openJSON(item.sealed_envelope);
  const parts = m.raw ? mimeParts(m.raw_content_type ?? 'text/plain', m.raw, m.raw_content_transfer_encoding) : [];
  return { m, files: parts.filter((p) => p.filename), shared: Boolean(m.raw) && item.attachments !== 'not_shared' };
}

const summary = (item, { m, files, shared }) => ({
  id: item.message_id, decoy_id: item.decoy_id, received_at: item.received_at, ...(item.direction ? { direction: item.direction } : {}),
  from: m.from, to: m.to, subject: m.subject, sender_domain_verified: m.sender_domain_verified ?? null,
  attachments: m.listed?.length ? m.listed.map((a) => String(a.filename ?? 'attachment')) : shared ? files.map((f) => f.filename) : item.encrypted_data ? [] : 'not_shared',
});

export const latestMail = task(async ({ decoy, limit = 10 } = {}, opts = {}) => {
  const decoyId = decoy ? await decoyIdOf(decoy) : null;
  const n = String(Math.min(Math.max(1, Math.floor(Number(limit) || 10)), 200));
  if (await heldMailboxKey()) {
    const { data } = await call('GET', `/api/agent/inbox/raw?${new URLSearchParams({ limit: n, ...(decoyId ? { decoy_id: decoyId } : {}) })}`);
    return value({ messages: (data.messages ?? []).map((item) => {
      try { return summary(item, openMessage(item)); } catch { return { id: item.message_id, decoy_id: item.decoy_id, received_at: item.received_at, unreadable: true }; }
    }) });
  }
  return patiently(async () => {
    const { data } = await call('GET', `/api/agent/inbox/sealed?${new URLSearchParams({ limit: n, ...(decoyId ? { decoy_id: decoyId } : {}) })}`);
    const state = decoyId ? data.history?.[decoyId] : data.mail;
    const items = data.items ?? [];
    if (!items.length && state?.state === 'preparing') return again(state.retry_after_seconds ?? 30, MAIL_WAIT);
    const messages = items.map((item) => {
      try { return summary(item, openMessage(item)); } catch { return { id: item.message_id, decoy_id: item.decoy_id, received_at: item.received_at, unreadable: true }; }
    });
    const note = state?.state === 'preparing' ? 'Earlier mail is still being shared with this session; more may appear.'
      : state?.state === 'failed' ? 'Some earlier mail is not shared with this session.' : undefined;
    const rest = Array.isArray(data.remaining_message_ids) ? data.remaining_message_ids.length : 0;
    return value({ messages, ...(note ? { note } : {}), ...(data.truncated || rest ? { truncated: true, more: rest } : {}),
      ...(data.too_large?.length ? { too_large: data.too_large.length } : {}) });
  }, opts);
});

/** A file name safe to write: no path, no control or odd characters, at most 100 characters, unique in `taken`. */
function safeName(name, taken) {
  const cleaned = String(name ?? '').split(/[\\/]/).pop().replace(/[^\w.-]+/g, '_').replace(/^[.]+/, '') || 'attachment';
  const dot = cleaned.lastIndexOf('.');
  const ext = dot > 0 && cleaned.length - dot <= 10 ? cleaned.slice(dot) : '';
  const base = (ext ? cleaned.slice(0, dot) : cleaned).slice(0, 100 - ext.length) || 'attachment';
  let out = base + ext;
  for (let i = 2; taken.has(out.toLowerCase()); i++) out = `${base.slice(0, 100 - ext.length - String(i).length - 1)}-${i}${ext}`;
  taken.add(out.toLowerCase());
  return out;
}

function attachmentsOut(id, files, folder) {
  const taken = new Set();
  const prefix = String(id).replace(/[^\w-]/g, '').slice(0, 8) || 'message';
  return files.map((f) => {
    const filename = safeName(f.filename, taken);
    const base = { filename, contentType: f.contentType, size: f.bytes.length };
    if (!folder) return { ...base, base64: f.bytes.toString('base64') };
    const path = join(folder, `${prefix}-${filename}`);
    try {
      mkdirSync(folder, { recursive: true, mode: 0o700 });
      writeFileSync(path, f.bytes, { mode: 0o600 });
    } catch (e) {
      stop(failure(`An attachment could not be saved to the folder given${typeof e?.code === 'string' ? ` (${e.code})` : ''}. Call again without saveAttachmentsTo to get its bytes.`, ['pair_again', 'retry']));
    }
    return { ...base, path };
  });
}

/** A file the owner's copy lists but keeps apart (a large mail): one stored row, or parts joined to its size. */
async function keptApart(messageId, a) {
  const row = async (aid) => {
    const r = await call('GET', `/api/agent/inbox/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(aid)}`, undefined, { allow: [403, 404] });
    return r.status === 200 && typeof r.data.encrypted_data === 'string' ? openEnvelope(Buffer.from(r.data.encrypted_data, 'base64'), mailboxKey) : null;
  };
  try {
    if (!Array.isArray(a.parts) || !a.parts.length) return a.id ? await row(String(a.id)) : null;
    if (!Number.isSafeInteger(a.size) || a.size < 0) return null;   // a join that cannot be checked is refused
    const chunks = [];
    let n = 0;
    for (const p of a.parts) {
      const b = await row(String(p));
      if (!b || n + b.length > a.size) return null;
      chunks.push(b); n += b.length;
    }
    return n === a.size ? Buffer.concat(chunks) : null;
  } catch (e) { if (e instanceof Stop) throw e; return null; }
}

/** The owner's copy's files: each listed file from the MIME, inline, or fetched; never an empty stand-in. */
async function ownerFiles(id, m, files) {
  if (!m.listed.length) return { files, missed: [] };
  const inMime = new Map(files.filter((f) => f.bytes.length).map((f) => [f.filename, f]));
  const out = [], missed = [];
  for (const a of m.listed) {
    const filename = String(a.filename ?? 'attachment');
    let bytes = inMime.get(filename)?.bytes;
    inMime.delete(filename);
    if (!bytes?.length && typeof a.content === 'string' && a.content) bytes = Buffer.from(a.content, 'base64');
    if (!bytes?.length && a.size !== 0) bytes = await keptApart(id, a);
    if (bytes?.length || a.size === 0) out.push({ filename, contentType: String(a.content_type ?? 'application/octet-stream'), bytes: bytes ?? Buffer.alloc(0) });
    else missed.push(filename);
  }
  return { files: [...out, ...inMime.values()], missed };
}

async function opened(id, item, opts) {
  const o = openMessage(item);
  const { m } = o;
  let missed = [];
  if (item.encrypted_data) ({ files: o.files, missed } = await ownerFiles(id, m, o.files));
  return value({ id, decoy_id: item.decoy_id, received_at: item.received_at, ...(item.direction ? { direction: item.direction } : {}),
    from: m.from, to: m.to, cc: m.cc, subject: m.subject, sender_domain_verified: m.sender_domain_verified ?? null, text: m.text, html: m.html,
    attachments: o.shared || o.files.length ? attachmentsOut(id, o.files, opts.saveAttachmentsTo) : [],
    ...(missed.length ? { attachments_note: `Could not open ${missed.join(', ')}: it is stored apart from the message, and Decoy did not return it. Tell the owner which attachment you could not open.` } : {}),
    ...(item.encrypted_data || o.shared ? {} : { attachments_not_shared: NOT_SHARED_ATTACHMENTS }),
    ...(m.truncated ? { truncated: true } : {}) });
}

export const openMail = task(async (id, opts = {}) => {
  if (await heldMailboxKey()) {
    const { data } = await call('GET', `/api/agent/inbox/raw?message_ids=${encodeURIComponent(id)}`);
    const item = (data.messages ?? []).find((i) => i.message_id === id);
    return item ? opened(id, item, opts) : failure('No message with this id is in the owner\'s mail.', ['pair_again', 'retry']);
  }
  return patiently(async () => {
    const { data } = await call('GET', `/api/agent/inbox/sealed?message_ids=${encodeURIComponent(id)}`);
    const item = (data.items ?? []).find((i) => i.message_id === id);
    if (item) return opened(id, item, opts);
    if ((data.too_large ?? []).some((t) => t === id || t?.message_id === id)) return failure('This message is too large for any read by this connection.', ['pair_again', 'retry']);
    const st = data.messages?.[id] ?? {};
    if (st.state === 'preparing') return again(st.retry_after_seconds ?? 30, MAIL_WAIT);
    if (st.state === 'failed') return askOwner('An email I need isn\'t shared with this Decoy session yet. Please open Decoy on your phone once, then tell me.');
    if (st.state === 'not_shared') return failure('Sent mail is never shared with agents; only received mail is.', ['pair_again', 'retry']);
    if (st.state === 'outside_window') return failure('This message is older than the mail the owner\'s phone shares with agents.', ['pair_again', 'retry']);
    return failure('No message with this id is readable by this connection.', ['pair_again', 'retry']);
  }, opts);
});

// ── A small MIME reader: finds the parts of `raw` that are files ────────────

function headersOf(text) {
  const out = {};
  for (const line of text.replace(/\r?\n[ \t]+/g, ' ').split(/\r?\n/)) {
    const i = line.indexOf(':');
    if (i > 0) out[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim();
  }
  return out;
}
function param(header = '', name) {
  const ext = header.match(new RegExp(`;\\s*${name}\\*=(?:"([^"]*)"|([^;]+))`, 'i'));   // RFC 2231: charset''percent-encoded
  if (ext) { const v = (ext[1] ?? ext[2]).trim(); try { return decodeURIComponent(v.replace(/^[^']*'[^']*'/, '')); } catch { return v; } }
  const m = header.match(new RegExp(`;\\s*${name}=(?:"([^"]*)"|([^;]+))`, 'i'));
  return m ? decodeWords((m[1] ?? m[2]).trim()) : undefined;
}
/** RFC 2047 encoded words, e.g. =?UTF-8?B?…?= */
const decodeWords = (s) => s.replace(/=\?([^?]+)\?([BQ])\?([^?]*)\?=/gi, (_, _charset, enc, text) => (enc.toUpperCase() === 'B'
  ? Buffer.from(text, 'base64') : Buffer.from(text.replace(/_/g, ' ').replace(/=([0-9A-F]{2})/gi, (_m, h) => String.fromCharCode(parseInt(h, 16))), 'latin1')).toString('utf8'));
function decodeBody(body, encoding = '') {
  const e = encoding.toLowerCase();
  if (e === 'base64') return Buffer.from(body.replace(/\s+/g, ''), 'base64');
  if (e === 'quoted-printable') return Buffer.from(body.replace(/=\r?\n/g, '').replace(/=([0-9A-F]{2})/gi, (_m, h) => String.fromCharCode(parseInt(h, 16))), 'latin1');
  return Buffer.from(body, 'latin1');
}
function mimeParts(contentType, body, encoding, depth = 0) {
  const boundary = /^multipart\//i.test(contentType) ? param(contentType, 'boundary') : undefined;
  if (!boundary || depth > 8) return [{ contentType: contentType.split(';')[0].trim(), bytes: decodeBody(String(body), encoding) }];
  const sections = String(body).split(`--${boundary}`).slice(1);
  return sections.flatMap((section) => {
    if (section.startsWith('--')) return [];
    const raw = section.replace(/^\r?\n/, '');
    const split = raw.search(/\r?\n\r?\n/);
    const h = headersOf(split < 0 ? raw : raw.slice(0, split));
    const content = split < 0 ? '' : raw.slice(split).replace(/^\r?\n\r?\n/, '').replace(/\r?\n$/, '');
    const type = h['content-type'] ?? 'text/plain';
    const parts = mimeParts(type, content, h['content-transfer-encoding'], depth + 1);
    const filename = param(h['content-disposition'], 'filename') ?? param(type, 'name');
    const isFile = filename || /^attachment/i.test(h['content-disposition'] ?? '');
    return isFile && parts.length === 1 ? [{ ...parts[0], filename: filename ?? 'attachment' }] : parts;
  });
}

// ── Memory (the formats of agent-memory.mjs and https://www.decoys.me/docs/memory.md) ──

const USER = 'default_user';
const normal = (name) => String(name ?? '').normalize('NFKC').toLowerCase().replace(/\s+/g, ' ').trim().replace(/^["'“”‘’`]+|["'“”‘’`]+$/g, '').trim();
const memoryKeyId = (key) => createHash('sha256').update(key).digest().subarray(0, 8).toString('hex');
const ORDER = ['v', 'row_id', 'entity', 'observation', 'relation', 'endpoints', 'about', 'categories', 'about_hint', 'metadata'];
const canonical = (v) => Object.fromEntries([...ORDER.filter((k) => v[k] !== undefined), ...Object.keys(v).filter((k) => !ORDER.includes(k) && v[k] !== undefined)].map((k) => [k, v[k]]));

/** The row key wrapped to every other connection whose memory grant reaches the row (as agent-memory.mjs granteeWraps). */
const granteeWraps = (grantees, value, key) => (grantees ?? []).flatMap((g) => { const via = reasonsFor(g.selectors, value); return via.length ? [{ token_id: g.token_id, via, wrapped_key: sealEnvelope(key, g.public_key) }] : []; });

function reasonsFor(selectors, value) {   // the reasons a connection with these selectors reads this plaintext by
  const about = value.about ?? [], via = [];
  const s = { all: false, categories: [], topics: [], account_ids: [], account_wildcard: false, ...(selectors ?? {}) };
  if (s.all) via.push('all');
  if (value.observation) {
    for (const c of new Set(value.categories ?? [])) if (s.categories.includes(c)) via.push(`category:${c}`);
    for (const t of about) if (t.startsWith('topic:') && s.topics.includes(t)) via.push(t);
  } else if (value.entity && s.topics.includes(`topic:${value.row_id}`)) via.push(`topic:${value.row_id}`);
  else if (value.relation) {
    const ends = [...new Set((value.endpoints ?? []).filter((e) => e !== 'user'))];
    if (ends.length && ends.every((e) => s.topics.includes(e))) via.push(ends.length === 1 ? ends[0] : `and:${ends.join('+')}`);
  }
  return via;
}

function newRow(body, keys) {
  const id = randomUUID();
  const plain = canonical({ v: 2, row_id: id, ...body });
  const key = randomBytes(32);
  const wraps = granteeWraps(keys.grantees, plain, key);
  return {
    id, kid: memoryKeyId(key), ciphertext: sealVault(plain, key),
    owner_wrap: Buffer.concat([Buffer.from([1, 2]), Buffer.from(sealEnvelope(Buffer.from(key.toString('base64'), 'utf8'), keys.owner), 'base64')]).toString('base64'),
    self_wrap: sealEnvelope(key, keys.self),
    ...(keys.reads ? { self_via: reasonsFor(keys.reads, plain) } : {}),   // saving gives no access: kept for the reads it holds
    ...(wraps.length ? { grantee_wraps: wraps } : {}),
  };
}

/** Each served row this key opens: { row, value }. Rows it cannot open are skipped. */
function openRows(rows) {
  return (rows ?? []).flatMap((row) => {
    try {
      const key = openEnvelope(row.wrapped_key);
      if (key.length !== 32 || memoryKeyId(key) !== row.kid) return [];
      const v = openVault(row.ciphertext, key);
      return v && v.v === 2 && v.row_id === row.id ? [{ row, value: v }] : [];
    } catch { return []; }
  });
}

/** Topics, same-name ones once under the oldest id (as the app shows them): [{ id, name }]. */
function topicsOf(opened) {
  const all = [];
  for (const { row, value: v } of opened) {
    if (v.entity && typeof v.entity.name === 'string' && typeof v.entity.entityType === 'string' && v.entity.name !== USER && v.entity.entityType !== 'account') {
      all.push({ id: `topic:${row.id}`, name: v.entity.name, at: row.created_at ?? '￿' });
    }
    const label = (v.about ?? []).find((a) => typeof a === 'string' && a.startsWith('topic:'));
    if (v.observation && label && v.observation.entityName && v.observation.entityName !== USER) all.push({ id: label, name: v.observation.entityName, at: row.created_at ?? '￿' });
  }
  const byName = new Map();
  for (const t of all.sort((a, b) => a.at.localeCompare(b.at) || a.id.localeCompare(b.id))) if (!byName.has(normal(t.name))) byName.set(normal(t.name), { id: t.id, name: t.name });
  return [...byName.values()];
}
function memoriesOf(opened) {
  return opened.filter(({ value: v }) => v.observation && typeof v.observation.content === 'string').map(({ row, value: v }) => {
    const label = (v.about ?? []).find((a) => typeof a === 'string' && a.startsWith('topic:'));
    const account = (v.about ?? []).find((a) => typeof a === 'string' && a.startsWith('account:'));
    return { id: row.id, text: v.observation.content, topic: label ? { id: label, name: v.observation.entityName } : null,
      categories: v.categories ?? [], ...(account ? { accountId: account.slice(8) } : {}), mine: row.mine ?? false };
  });
}

/** What the read says is not readable yet: counted, uncounted (a category, topic or account grant), or given up on. */
function owedOf(d) {
  const preparing = (d.preparing?.length ?? 0) + (d.preparing_others ?? 0);
  const failed = (d.failed?.length ?? 0) + (d.failed_others ?? 0);
  return { preparing, unknown: d.preparing_unknown === true, failed, failedUnknown: d.failed_unknown === true,
    // failed_unknown alone never changes (a connection with the vault key always reads it), so it does not hold a save back.
    waiting: preparing > 0 || d.preparing_unknown === true, any: preparing > 0 || failed > 0 || d.preparing_unknown === true };
}
function memoryNote(o) {
  if (o.preparing) return `${o.preparing} earlier memories are still being shared with this session; they are saved, not missing.`;
  if (o.unknown) return 'Memories reached through a category, topic or account grant may still be being shared with this session; a short list does not mean there are no more.';
  if (o.failed) return 'Some earlier memories are not shared with this session.';
  if (o.failedUnknown) return 'Memories reached through a category, topic or account grant may not be shared with this session; a short list does not mean there are no more.';
  return undefined;
}
const MEMORY_WAIT = 'Decoy is asking your phone to share earlier memories with this session; they are saved, not missing. Opening Decoy on your phone once makes that immediate.';

export const readMemory = task(async (query, opts = {}) => patiently(async () => {
  const { data } = await call('GET', '/api/agent/context/memories');
  const opened = openRows(data.memories);
  const memories = memoriesOf(opened);
  const owed = owedOf(data);
  if (!memories.length && owed.waiting) return again(data.retry_after_seconds ?? 30, MEMORY_WAIT);
  const terms = normal(query ?? '').split(' ').filter(Boolean);
  const matches = memories.filter((m) => terms.every((t) => normal(`${m.text} ${m.topic?.name ?? ''} ${m.categories.join(' ')}`).includes(t)));
  const note = memoryNote(owed);
  return value({ memories: matches, topics: topicsOf(opened), total: memories.length, ...(note ? { note } : {}) });
}, opts));

export const saveMemory = task(async ({ text, topic, categories = [], type = '', link, newTopic = false } = {}, opts = {}) => {
  const content = String(text ?? '').trim();
  if (!content) return failure('A memory needs text.', []);
  if (topic && typeof topic === 'object' && !(topic.id && topic.name)) return failure('Pass topic as a name ("Travel"), or as { id, name } from readMemory or your notes; leave it out for a fact about the owner.', []);
  if (topic && ['default_user', 'user', 'you', 'me'].includes(normal(typeof topic === 'object' ? topic.name : topic))) {
    return failure('The owner is not a topic: name what the memory is about ("Travel", "Home network").', []);
  }
  return patiently(async () => {
    const [{ data }, { data: g }] = [await call('GET', '/api/agent/context/memories'), await call('GET', '/api/agent/context/memory-grantees')];
    if (!g.owner_public_key) return askOwner('Please finish setting up Decoy in the app, so I can save memories there.');
    const opened = openRows(data.memories);
    let t = !topic ? null : typeof topic === 'object' ? { id: topic.id.startsWith('topic:') ? topic.id : `topic:${topic.id}`, name: topic.name.trim() }
      : topicsOf(opened).find((x) => normal(x.name) === normal(topic));
    const owed = owedOf(data);
    // A topic is reused by name among the memories this key reads. While some are not readable, a
    // topic of that name may exist unseen: never make a second one without the owner's say-so.
    if (topic && !t && !newTopic && owed.any) {
      const hold = `Until then I can't tell whether you already have a topic named "${topic}", so I'm holding this memory. Or tell me to save it under a new topic of that name.`;
      if (owed.waiting) return again(data.retry_after_seconds ?? 30, `${MEMORY_WAIT} ${hold}`);
      return askOwner(`Some of your earlier memories aren't shared with this Decoy session. Opening Decoy on your phone once shares them. ${hold}`);
    }
    if (memoriesOf(opened).some((m) => (t ? m.topic && normal(m.topic.name) === normal(t.name) : !m.topic && !m.accountId) && normal(m.text) === normal(content))) {
      return value({ already_saved: true, topic: t ?? null });
    }
    const keys = { owner: g.owner_public_key, self: myPublicKey(), grantees: g.grantees, reads: g.self?.selectors };
    const rows = [];
    const created = !!topic && !t;
    if (created) {
      const name = String(topic).normalize('NFKC').replace(/\s+/g, ' ').trim().slice(0, 200);
      const entity = newRow({ entity: { name, entityType: String(type) }, about: [] }, keys);
      t = { id: `topic:${entity.id}`, name };
      const from = link?.topic;
      rows.push(entity, newRow({
        relation: { from: from ? from.name : USER, to: name, relationType: String(link?.relationType ?? '').trim() || (from ? 'includes' : 'is interested in') },
        endpoints: [from ? from.id : 'user', t.id], about: [],
      }, keys));
    }
    const cats = [...new Set(categories)];
    const memory = newRow({ observation: { entityName: t ? t.name : USER, content }, about: [t ? t.id : 'user'], ...(cats.length ? { categories: cats } : {}) }, keys);
    await call('POST', '/api/agent/context/memories', { rows: [...rows, memory] });
    const check = await call('GET', '/api/agent/context/memories');
    const verified = memoriesOf(openRows(check.data.memories)).some((m) => m.id === memory.id && m.text === content);
    return value({ id: memory.id, topic: t ?? null, created_topic: created, verified });
  }, opts);
});
