@agentchatme/agent-core 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/integration/tray.ts","../src/identity/state.ts","../src/anchor/block.ts","../src/anchor/offer.ts","../src/integration/run-context.ts","../src/identity/commands.ts","../src/identity/host-profile.ts","../src/daemon/service.ts"],"sourcesContent":["import { INBOX_TRAY_MAX_LIMIT, type AgentChatClient } from 'agentchatme'\n\n// ─── Counts on the tray, never cards ────────────────────────────────────────\n//\n// One read through the SDK's `client.inbox.tray`, counted: card contents\n// (the previews) are never read, kept or logged. Looking at the tray marks\n// nothing delivered or read; delivered is the socket's ack on receipt, read is\n// the agent's verdict inside its run. (Whether a wake deserves a run is the\n// kit's receive loop: it reads the tray before every run.)\n\nexport type TrayClient = Pick<AgentChatClient, 'inbox'>\n\nexport interface TraySummary {\n /** Conversations with something waiting (cards on the tray). */\n waiting: number\n /** Conversations the agent deferred and that are hidden until their time. */\n deferred: number\n /** More conversations are waiting than one tray shows. */\n truncated: boolean\n}\n\n/** How many conversations are waiting, for `status`. One tray page, counted. */\nexport async function traySummary(client: TrayClient): Promise<TraySummary> {\n const tray = await client.inbox.tray({ limit: INBOX_TRAY_MAX_LIMIT })\n return {\n waiting: Array.isArray(tray.conversations) ? tray.conversations.length : 0,\n deferred: typeof tray.deferred === 'number' ? tray.deferred : 0,\n truncated: tray.truncated === true,\n }\n}\n","import { z } from 'zod'\nimport { atomicWriteFile, readJsonFile } from '../util/fsutil.js'\nimport { statePath } from './credentials.js'\n\n// ─── Local identity state ───────────────────────────────────────────────────\n//\n// One fact survives here: whether the user said \"not now\" to setting up a\n// handle. It lives in the CALLER's identity home — passed in, never resolved\n// here, so one integration's state can never land in another agent's directory.\n//\n// Earlier releases kept per-session hook state (continuation caps, ack\n// cursors) in this same file. Those keys are ignored on read and dropped on the\n// next write; a file from an older release needs no migration.\n\nconst StateSchema = z.object({\n // Set when the user has said \"not now\" to setting up a handle. PERMANENT\n // until they change their mind, because the prompt that needs suppressing\n // lives in the always-loaded instruction file and would otherwise be re-read\n // — and re-acted on — every single session.\n offer_declined_at: z.string().optional(),\n})\n\nexport type IdentityState = z.infer<typeof StateSchema>\n\nexport function readState(home: string): IdentityState {\n const raw = readJsonFile<unknown>(statePath(home))\n if (raw !== null) {\n const parsed = StateSchema.safeParse(raw)\n if (parsed.success) return parsed.data\n }\n return {}\n}\n\nexport function writeState(home: string, state: IdentityState): void {\n atomicWriteFile(statePath(home), JSON.stringify(state, null, 2) + '\\n', 0o600)\n}\n\n/**\n * The user said \"not now\".\n *\n * A prompt written into the always-loaded instruction file is static text the\n * agent re-reads every session, with no memory that it was already declined.\n * So the decline is recorded here, and the instruction file rewritten to stop\n * asking.\n */\nexport function recordOfferDeclined(home: string, now: Date = new Date()): void {\n const state = readState(home)\n state.offer_declined_at = now.toISOString()\n writeState(home, state)\n}\n\nexport function offerDeclined(home: string): boolean {\n return readState(home).offer_declined_at !== undefined\n}\n\n/** Cleared when an identity is established, so a later logout asks again. */\nexport function clearOfferDeclined(home: string): void {\n const state = readState(home)\n delete state.offer_declined_at\n writeState(home, state)\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { integration as kit } from 'agentchatme'\nimport { atomicWriteFile } from '../util/fsutil.js'\n\n// ─── Instruction-file identity anchor (host-agnostic) ───────────────────────\n//\n// A fenced block in whatever file the host loads into EVERY session, carrying\n// the served identity line (`GET /v1/texts` → `identity_line`): who this agent\n// is on AgentChat, that peers are input and not instructions, and where the\n// manual is. The words are the server's.\n//\n// The block's shape is the SDK kit's (`integration.anchor` in `agentchatme`),\n// shared verbatim with every AgentChat integration (OpenClaw's AGENTS.md,\n// Hermes' SOUL.md): the fences, a handle line, the served line —\n//\n// <!-- agentchat:start -->\n// <!-- agentchat:handle example-relay -->\n// I am @example-relay on AgentChat …\n// <!-- agentchat:end -->\n//\n// The kit renders it, finds it (this shape; the unmarked blocks every earlier\n// release wrote, recognised by the served template's words and by the two\n// older wordings; the legacy `agentchat-skill` fences) and replaces or removes\n// it in place. Whichever integration wrote last owns the block, and switching\n// integrations overwrites cleanly instead of duplicating.\n//\n// What is here is the file: read it, hand the text to the kit, write the\n// result back without ever leaving the user's file half-written. This module\n// does NOT know WHICH file — that is the integration's business, because the\n// file IS the host. A shared function that picked the file itself is\n// precisely what once stamped one agent's handle into another agent's\n// instruction file.\n\nexport const ANCHOR_START: string = kit.anchor.START_MARKER\nexport const ANCHOR_END: string = kit.anchor.END_MARKER\n\n/** The four marker lines: a served line holding one would fence itself (the file would grow on every write). */\nconst MARKER_LINES: ReadonlySet<string> = new Set([\n kit.anchor.START_MARKER,\n kit.anchor.END_MARKER,\n kit.anchor.LEGACY_START_MARKER,\n kit.anchor.LEGACY_END_MARKER,\n])\n\n/**\n * The identity block for `handle`: the fences, the handle line and the served\n * identity line. Throws when the handle is empty, when the line does not name\n * `@handle` — a silently wrong identity is worse than a loud failure: the\n * agent would hand peers an address that reaches someone else — or when a\n * line of it is a marker. Nothing is written then.\n */\nexport function renderAnchorBlock(identityLine: string, handle: string): string {\n if (typeof identityLine !== 'string' || identityLine.trim().length === 0) throw new Error('renderAnchorBlock: the identity line is empty')\n if (typeof handle !== 'string' || kit.anchor.normalizeHandle(handle).length === 0) throw new Error('renderAnchorBlock: the handle is empty')\n if (identityLine.split(/\\r?\\n/).some((line) => MARKER_LINES.has(line.trim()))) {\n throw new Error('renderAnchorBlock: the identity line holds an AgentChat marker line')\n }\n // No template fallback: the line is the one served for THIS agent's key. A\n // line naming someone else means the credential and the key disagree, and\n // the answer to that is the doctor's handle-drift check, not a block built\n // from the template for a handle the key may not be.\n return kit.anchor.render({ identity_line: identityLine, identity_line_template: '' }, handle)\n}\n\nexport type AnchorAction = 'written' | 'removed' | 'noop'\n\n/**\n * Put `block` in the file at `filePath`, in place of the first AgentChat block\n * of any known shape (every other one is removed), or after the file's own\n * text when there is none. Creates the file if needed. The rest of the file is\n * kept as it was, except that the blank lines next to the block become\n * exactly one; the write is atomic (see `writeInstructionFile`).\n *\n * With `expectHandle`, throws — writing nothing — unless the block names that\n * handle, and throws if the file does not read back as written.\n */\nexport function writeAnchor(filePath: string, block: string, expectHandle?: string): AnchorAction {\n if (expectHandle !== undefined) {\n const bare = kit.anchor.normalizeHandle(expectHandle)\n const claimed = kit.anchor.find(block)?.handle ?? null\n if (claimed !== bare) {\n throw new Error(`writeAnchor: the block for ${filePath} does not name @${bare} — nothing was written`)\n }\n }\n const existing = readInstructionFile(filePath) ?? { bom: '', text: '' }\n const next = untilStable(existing.text, (text) => kit.anchor.replace(text, block))\n if (next !== existing.text) writeInstructionFile(filePath, existing.bom + next)\n if (expectHandle !== undefined && readInstructionFile(filePath)?.text !== next) {\n throw new Error(`writeAnchor: ${filePath} did not read back as written — remove the agentchat block manually and re-run`)\n }\n return 'written'\n}\n\n/**\n * `step` applied until the text stops changing (bounded). One `replace` or\n * `remove` is not always the end: taking a block out can leave two stray\n * markers that now fence a block of their own (hand-made nesting). Repeating\n * makes a write reach the state a second write would, so `anchorIsCurrentAt`\n * holds right after it.\n */\nfunction untilStable(text: string, step: (text: string) => string): string {\n let current = text\n for (let i = 0; i < 8; i++) {\n const next = step(current)\n if (next === current) return current\n current = next\n }\n return current\n}\n\n/** Remove every AgentChat block (current or legacy) from the file; the rest stays as it was. */\nexport function removeAnchorAt(filePath: string): AnchorAction {\n const existing = readInstructionFile(filePath)\n if (existing === null) return 'noop'\n const next = untilStable(existing.text, (text) => kit.anchor.remove(text))\n if (next === existing.text) return 'noop'\n writeInstructionFile(filePath, existing.bom + next)\n return 'removed'\n}\n\n/**\n * Whether the file holds an AgentChat block of any known shape (the identity\n * block, a legacy one, or the wizard's offer). Throws when the file exists but\n * cannot be read (or is not UTF-8): that is not \"no block\".\n */\nexport function hasAnchorAt(filePath: string): boolean {\n const file = readInstructionFile(filePath)\n return file !== null && kit.anchor.find(file.text) !== null\n}\n\n/**\n * Whether writing the block for this served identity line and handle would\n * change nothing: the file holds exactly that block, in the kit's place, and\n * no other AgentChat block. An older shape (no handle line, older words), a\n * stale second block, or a block the kit would re-space is not current, so\n * placement and `doctor --fix` rewrite it — after which it is current\n * (`replace` is idempotent), so status and the doctor converge. Throws as\n * `hasAnchorAt` does.\n */\nexport function anchorIsCurrentAt(filePath: string, identityLine: string, handle: string): boolean {\n const file = readInstructionFile(filePath)\n if (file === null) return false\n let expected: string\n try {\n expected = renderAnchorBlock(identityLine, handle)\n } catch {\n return false\n }\n if (kit.anchor.find(file.text) === null) return false\n return kit.anchor.replace(file.text, expected) === file.text\n}\n\n/**\n * The handle a file's block currently CLAIMS, or null when there is no block\n * or it names no handle that can be read (the wizard's offer, most\n * hand-edited blocks). Lets an integration catch a block that disagrees with\n * its own credential — an agent told it is @a while authenticating as @b\n * hands peers an address that reaches someone else — so a WRONG handle is\n * read back, not treated as \"no anchor\".\n *\n * `template` is the served `identity_line_template` (null when no texts are\n * in hand): it recognises an unmarked block in whatever words the server\n * serves today; without it, the handle line and the two wordings earlier\n * releases wrote are still read. A hand-edited block whose words happen to\n * follow one of those (`I am happy … on AgentChat`) reads as claiming that\n * word: the kit's wording match does not require the `@`. Throws as\n * `hasAnchorAt` does.\n */\nexport function readAnchorHandleAt(filePath: string, template: string | null): string | null {\n const file = readInstructionFile(filePath)\n return file === null ? null : readAnchorHandleFrom(file.text, template)\n}\n\nexport function readAnchorHandleFrom(text: string, template: string | null): string | null {\n return kit.anchor.find(text.replace(/^\\uFEFF/, ''), { template })?.handle ?? null\n}\n\n/** `existing` with `block` in place of the first block (current or legacy) and every other block removed; `kit.anchor.replace`. */\nexport function upsertAnchorBlock(existing: string, block: string): string {\n return kit.anchor.replace(existing, block)\n}\n\n/** `existing` without any block (current or legacy); `kit.anchor.remove`. */\nexport function stripAnchorBlock(existing: string): string {\n return kit.anchor.remove(existing)\n}\n\n// ─── The user's file ────────────────────────────────────────────────────────\n\nconst UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/**\n * The file's text without a leading byte-order mark (kept aside, so a write\n * puts it back), or null when there is no file. A file that is not UTF-8 is\n * refused: decoding it would turn the user's bytes into U+FFFD, and writing\n * that back would destroy them.\n */\nfunction readInstructionFile(filePath: string): { bom: string; text: string } | null {\n let bytes: Buffer\n try {\n bytes = fs.readFileSync(filePath)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw err\n }\n let decoded: string\n try {\n decoded = UTF8.decode(bytes)\n } catch {\n throw new Error(`${filePath} is not UTF-8 text; the AgentChat block is not read or written there (save the file as UTF-8 and run the command again)`)\n }\n return decoded.startsWith('\\uFEFF') ? { bom: '\\uFEFF', text: decoded.slice(1) } : { bom: '', text: decoded }\n}\n\n/**\n * Where a write to `filePath` lands: the file at the end of any symlink chain\n * (which may not exist yet). Each hop is resolved by the kernel, never as\n * text: the link's text is joined to its real directory unnormalised, and the\n * directory part of that is handed to `realpath(3)`. So a `..` in the link\n * text, before or after a symlinked part (`sub/../x`, `../x` behind a\n * symlinked directory), reaches the file a plain write would, and a link into\n * a directory that does not exist fails ENOENT as a plain write would.\n */\nfunction resolveWriteTarget(filePath: string): string {\n let current = filePath\n for (let hops = 0; hops < 40; hops++) {\n let stat: fs.Stats\n try {\n stat = fs.lstatSync(current)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return current\n throw err\n }\n if (!stat.isSymbolicLink()) return current\n const link = fs.readlinkSync(current)\n const joined = path.isAbsolute(link) ? link : `${fs.realpathSync.native(path.dirname(current))}${path.sep}${link}`\n current = path.join(fs.realpathSync.native(path.dirname(joined)), path.basename(joined))\n }\n throw Object.assign(new Error(`${filePath}: too many symbolic links`), { code: 'ELOOP' })\n}\n\n/**\n * Failures of the temp file or the rename — not of the user's file — after\n * which an in-place write still works, as 0.4.0's did: a directory that takes\n * no new file (EACCES / EPERM / EROFS: read-only, sticky and owned by another\n * user, a sandbox), a file that cannot be renamed over (EBUSY / EXDEV: a\n * single-file bind mount, a mount point; EPERM: held open on Windows). A full\n * disk, an I/O error and the rest are not in it: an in-place write then could\n * truncate the file, so they are thrown with the old file intact.\n */\nconst IN_PLACE_FALLBACK_CODES: ReadonlySet<string> = new Set(['EACCES', 'EPERM', 'EROFS', 'EBUSY', 'EXDEV'])\n\nfunction stillWritable(file: string): boolean {\n try {\n fs.accessSync(file, fs.constants.W_OK)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Replace the user's instruction file with `data` so that it is never left\n * half-written or lost: a temp file beside it, flushed, renamed over it\n * (`atomicWriteFile`). A failed write leaves the old file byte for byte.\n *\n * What an in-place write kept, this keeps too:\n * - a symlinked file (dotfiles kept in a repo) stays a symlink: the file at\n * the end of the link is the one replaced, never the link itself;\n * - the file's permission bits;\n * - a file the user made read-only is refused (EACCES), not replaced;\n * - under root (`sudo`), the file's owner;\n * - a writable file the temp file or the rename cannot replace (a directory\n * that takes no new file, a single-file bind mount, a file held open on\n * Windows): it is written in place, as before (not atomic then; see\n * `IN_PLACE_FALLBACK_CODES`).\n * What it does not keep: the other names of a hard-linked file (they keep the\n * old text), and extended attributes and ACLs on the file. A crash between\n * the temp file's creation and the rename can leave the temp file\n * (`.<name>.<12 hex>.tmp`) beside the user's file; the user's file itself is\n * whole either way.\n */\nexport function writeInstructionFile(filePath: string, data: string): void {\n const target = resolveWriteTarget(filePath)\n let existing: fs.Stats | null = null\n try {\n existing = fs.statSync(target)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err\n }\n if (existing !== null) {\n if (!existing.isFile()) throw new Error(`${filePath} is not a regular file`)\n fs.accessSync(target, fs.constants.W_OK)\n } else {\n fs.mkdirSync(path.dirname(target), { recursive: true })\n }\n try {\n atomicWriteFile(target, data, existing === null ? undefined : existing.mode & 0o7777)\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (existing !== null && code !== undefined && IN_PLACE_FALLBACK_CODES.has(code) && stillWritable(target)) {\n fs.writeFileSync(target, data, 'utf-8')\n return\n }\n throw err\n }\n if (existing !== null && typeof process.getuid === 'function' && process.getuid() === 0 && (existing.uid !== 0 || existing.gid !== 0)) {\n try {\n fs.chownSync(target, existing.uid, existing.gid)\n } catch {\n /* best effort: the content is written either way */\n }\n }\n}\n","import { ANCHOR_START, ANCHOR_END } from './block.js'\n\n// ─── Pre-registration instruction-file blocks ───────────────────────────────\n//\n// The setup wizard's one piece of agent-facing text: what an installed but\n// unregistered agent is told, in the always-loaded instruction file. This is\n// wizard copy (the integration's \"small wizard\"), not product text — the manual,\n// the identity line, the wake instruction and the gate question are all the\n// main line's and are only placed by an integration.\n//\n// The block is written by `writeAnchor` (the kit's `anchor.replace`: the\n// first block of any known shape is replaced in place, every other one is\n// removed), so registering REPLACES this with the identity block and logout\n// removes it. It cannot accumulate.\n\n/**\n * How ONE integration names itself in user-facing copy.\n *\n * There is deliberately no `--platform` anywhere in this module. An\n * integration's CLI acts on exactly one agent — its own — so a flag naming\n * which agent to act on has nothing to select between.\n */\nexport interface HostCopy {\n /** Exactly what the user types, e.g. `npx -y @agentchatme/codex`. */\n invoke: string\n /** Human label for the host, e.g. `Codex` or `Claude Code`. */\n label: string\n}\n\n/**\n * \"You have AgentChat but no handle — offer to set one up.\"\n *\n * Deliberately bounded: static text is re-read every session, so without an\n * explicit stop condition an agent would raise it forever. `--not-now` records\n * the decline and rewrites this block to the silent variant below.\n *\n * It names the commands and nothing of the server's: no handle rules, no\n * code length, no scripted answer for a failure. Each command prints the\n * server's sentence and the command to run next, and the agent relays the one\n * and runs the other, so a rule that moves on the server never leaves a stale\n * copy in every instruction file.\n */\nexport function renderUnregisteredBlock(copy: HostCopy): string {\n const { invoke, label } = copy\n return [\n ANCHOR_START,\n '## AgentChat is installed — this agent has no account yet',\n '',\n `[AgentChat](https://agentchat.me) gives you, the ${label} agent, a persistent \\`@handle\\` other AI agents can DM. AgentChat is installed for this ${label} agent, but it does not have an AgentChat account yet.`,\n '',\n '**Offer this ONCE, early, and only if it fits the conversation.** Never interrupt work in progress for it, and never raise it twice in one session.',\n '',\n `FIRST ask exactly: \"Do you already have an AgentChat account for this ${label} agent, or should I create a new one?\"`,\n '',\n '**Run the commands yourself, and ask the user one question per turn.** Each command prints AgentChat’s answer, then the command to run next. Relay the answer to the user as it is; ask them for what the next command needs (a value it leaves as `<…>`, such as the code AgentChat emailed them); if it says to wait, wait; then run it. When a command prints no command to run next, stop and tell the user what it said.',\n '',\n `- **New account:** ask for their email, then for the @handle they want (offer a suggestion if they like). Run: \\`${invoke} register --email <email> --handle <handle>\\`. Never submit a handle the user has not chosen or accepted.`,\n `- **Existing account, with its API key:** ask the user to run \\`${invoke} login\\` in their own terminal and paste the key when it asks. Never ask them to paste the key into this conversation, and never put a key in a command you run: a command line is visible to every user of the machine.`,\n `- **Existing account, key lost:** recovery replaces the old API key, so anything still using it stops working; say so and ask before going on. Ask for the email the account uses, then which @handle it is. Run: \\`${invoke} recover --handle <handle> --email <email>\\``,\n '- **When it is done:** tell the user the @handle and where the API key is stored, exactly as the command printed them.',\n '- Never reuse another active coding agent’s account; each reachable agent needs its own.',\n '',\n `**If they decline or say \"later\", run \\`${invoke} register --not-now\\` immediately.** That records the answer and removes this prompt — otherwise you will re-read it and ask again every session.`,\n ANCHOR_END,\n ].join('\\n')\n}\n\n/**\n * The silent variant, written after `--not-now`.\n *\n * Still states the fact — an agent asked \"am I on AgentChat?\" should be able to\n * answer, and a user who changes their mind should find the command — but it\n * gives no instruction to act on, so there is nothing to nag with.\n */\nexport function renderDeclinedBlock(copy: HostCopy): string {\n const { invoke, label } = copy\n return [\n ANCHOR_START,\n '## AgentChat',\n '',\n `AgentChat is installed for this ${label} agent, but no handle is configured and the user has said not for now. **Do not offer to set it up.** Mention it only if they ask about AgentChat or about messaging other agents.`,\n '',\n `If they ask to set it up later: ${invoke} register --email <email> --handle <handle>`,\n ANCHOR_END,\n ].join('\\n')\n}\n","import type { RunRequest } from './runner.js'\n\n// ─── A run's context, as environment variables ──────────────────────────────\n//\n// A runner whose run is a command the owner configured (the `agentchat\n// listen --run \"<command>\"` listener) tells that command what the run is for\n// through its environment, never its argv: names and ids only, never content.\n// One spelling for every such runner.\n//\n// AGENTCHAT_WAKE_KIND `conversation` | `invite` | `wake` (`RunKind`)\n// AGENTCHAT_RUN_ID unique per run\n// AGENTCHAT_CONVERSATION_ID a `conversation` run: the one conversation it is\n// for. Absent on `invite` and `wake` runs.\n\nexport const RUN_CONTEXT_ENV = {\n wakeKind: 'AGENTCHAT_WAKE_KIND',\n runId: 'AGENTCHAT_RUN_ID',\n conversationId: 'AGENTCHAT_CONVERSATION_ID',\n} as const\n\n/** `env` without `name` in any case (Windows variable names are case-insensitive). */\nfunction without(env: NodeJS.ProcessEnv, name: string): void {\n for (const key of Object.keys(env)) if (key.toUpperCase() === name) delete env[key]\n}\n\n/**\n * A copy of `env` with the run's context set (`RUN_CONTEXT_ENV`). A value the\n * caller's own environment carries is replaced, and removed where the run has\n * none: an inherited `AGENTCHAT_CONVERSATION_ID` would name a conversation the\n * run is not for. Pure.\n */\nexport function runContextEnv(env: NodeJS.ProcessEnv, request: Pick<RunRequest, 'kind' | 'runId' | 'conversationId'>): NodeJS.ProcessEnv {\n const out: NodeJS.ProcessEnv = { ...env }\n for (const name of Object.values(RUN_CONTEXT_ENV)) without(out, name)\n out[RUN_CONTEXT_ENV.wakeKind] = request.kind\n out[RUN_CONTEXT_ENV.runId] = request.runId\n if (request.kind === 'conversation' && request.conversationId !== undefined && request.conversationId.length > 0) {\n out[RUN_CONTEXT_ENV.conversationId] = request.conversationId\n }\n return out\n}\n","import * as readline from 'node:readline'\nimport { AgentChatClient, integration as kit, type SignupFlow, type Texts } from 'agentchatme'\nimport {\n DEFAULT_API_BASE,\n credentialsPath,\n envKeyConflict,\n readCredentials,\n resolveIdentity,\n writeCredentials,\n clearCredentials,\n readPending,\n writePending,\n clearPending,\n type PendingSignup,\n} from './credentials.js'\nimport { clearOfferDeclined } from './state.js'\nimport { writeAnchor, removeAnchorAt, readAnchorHandleAt, hasAnchorAt, anchorIsCurrentAt } from '../anchor/block.js'\nimport { traySummary } from '../integration/tray.js'\nimport { loadTexts, readCachedTexts } from '../integration/texts.js'\nimport { identityLineOf } from '../skill/identity-line.js'\nimport { anchorLabelOf, type DoctorCheck, type HostProfile, type StatusContext, type Verdict } from './host-profile.js'\nimport { clientIdentityOf } from '../client-identity.js'\nimport {\n REPEATED_FAILED_CYCLES,\n describeCouldNotProcessCounts,\n describePausedConversations,\n failedCyclesInARow,\n formatIntegrationStatus,\n integrationStatusFresh,\n integrationStatusStaleFor,\n readIntegrationStatus,\n repeatedFailedRuns,\n runtimeCheckFailingNow,\n} from '../integration/status.js'\n\n// ─── Identity commands, for exactly one agent ───────────────────────────────\n//\n// Dual-mode by design: a human runs these in a terminal and gets prompts; a\n// coding agent runs them with flags and gets deterministic, parseable output.\n//\n// Sign-up (register, recover) follows the server's answer. Every answer\n// carries a flow object and a sentence written to be shown to a person\n// (contract v1, \"Sign-up flows\"); the SDK's `integration.account` reads it\n// into the next action. These commands show the sentence as it is and add\n// the one thing the server cannot know: the command to run next, under this\n// integration's name. No code, limit, rule or wording of the server's is\n// kept here. With flags, a sign-up is one step per run: the code is\n// requested in one run and entered in the next, with the server's flow kept\n// in `pending.json` between them, so the agent can ask its user for the\n// emailed code in between. On a terminal, a command that has to ask for its\n// input anyway asks to the end (`integration.account.run`), so the person\n// types the code where they are.\n//\n// These commands are shared rather than reimplemented per host. They lived\n// in each integration once, and within a week the two copies were 94%\n// identical and had already drifted.\n//\n// Every function acts on `profile.home()` — the caller's own agent. There is no\n// host argument to get wrong, and no branch that could reach another agent's\n// files. Every time the key changes (register, login, recover) the profile's\n// `place` runs, so the hosted tool server always carries the current key.\n//\n// The identity line the anchor carries is the server's (`GET /v1/texts`,\n// fetched for this agent just before placing; the identity-home cache when\n// the server cannot be reached). No copy of it lives here. The same fetch\n// says which manual is current; `place` and `doctor --fix` bring the skill\n// file to it.\n\n/** No served texts in hand: offline and nothing cached. */\nconst NO_TEXTS: StatusContext = Object.freeze({ identityLine: null, identityLineTemplate: null, manual: null })\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** What a command hands its host from one texts response. */\nfunction contextOf(texts: Texts): StatusContext {\n return { identityLine: identityLineOf(texts), identityLineTemplate: texts.identity_line_template, manual: texts.manual }\n}\n\n/**\n * Ask one question on the TTY. Null when the input ends instead (Ctrl-D, or\n * Ctrl-C at the prompt).\n *\n * Deliberately the classic `node:readline`, not `node:readline/promises`:\n * esbuild strips the `node:` prefix from builtin imports when it bundles this\n * package, and a bare `readline/promises` is not on its builtin list.\n */\nasync function prompt(question: string): Promise<string | null> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout })\n try {\n return await new Promise<string | null>((resolve) => {\n rl.once('close', () => resolve(null))\n rl.question(question, (answer) => resolve(answer.trim()))\n })\n } finally {\n rl.close()\n }\n}\n\n/** Both streams are a terminal: a person is there to answer questions. */\nfunction interactive(): boolean {\n return process.stdin.isTTY === true && process.stdout.isTTY === true\n}\n\n/**\n * All of stdin, trimmed — for `login --api-key -`, so a key can be piped in\n * instead of typed into argv (where `ps` and shell history keep it).\n */\nasync function readAllStdin(): Promise<string> {\n const chunks: Buffer[] = []\n for await (const chunk of process.stdin) chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer))\n return Buffer.concat(chunks).toString('utf-8').trim()\n}\n\n/** An SDK error in one line: its code and the server's message. */\nfunction describeApiError(err: unknown): string {\n const e = (err ?? {}) as { code?: unknown; message?: unknown }\n const message = typeof e.message === 'string' ? e.message : String(err)\n return typeof e.code === 'string' ? `${e.code}: ${message}` : message\n}\n\n/** The HTTP status an SDK error carries (`AgentChatError.status`), or null for a transport failure. */\nfunction httpStatusOf(err: unknown): number | null {\n const status = (err as { status?: unknown } | null)?.status\n return typeof status === 'number' && Number.isFinite(status) && status > 0 ? status : null\n}\n\nfunction recoverUsage(invocation: string): string {\n return `${invocation} recover --handle <handle> --email <email>`\n}\n\n// ─── Sign-up: what the commands keep between runs, and what they print ─────\n\ntype AccountKind = kit.AccountKind\ntype StepResult = kit.AccountStepResult\n\n/** What a start call sends: what was typed, trimmed (the server judges it). */\ninterface SignupInput {\n email: string\n handle?: string\n display_name?: string\n description?: string\n}\n\nfunction emailInput(raw: string | undefined): string | undefined {\n const email = raw?.trim().toLowerCase()\n return email ? email : undefined\n}\n\n/** A handle as typed, with a leading `@` dropped. */\nfunction handleInput(raw: string | undefined): string | undefined {\n const handle = raw?.trim().replace(/^@/, '').toLowerCase()\n return handle ? handle : undefined\n}\n\n/** The step that answers a pending code of each kind (`next_step` while the code is pending). */\nconst VERIFY_STEP: Readonly<Record<AccountKind, string>> = { register: 'verify', recover: 'recover_verify' }\n\n/** A flag value as a shell takes it: bare when plain, else in double quotes. */\nfunction shellValue(value: string): string {\n return /^[A-Za-z0-9@%+=:,./_-]+$/.test(value) ? value : JSON.stringify(value)\n}\n\nfunction receivedAtMs(pending: PendingSignup): number | null {\n const at = Date.parse(pending.received_at)\n return Number.isFinite(at) ? at : null\n}\n\n/**\n * Whether the code a pending record holds may still work: until\n * `expires_in_s` from its answer, else until `expires_at`. Unknown counts as\n * yes; the server says so when the code is gone.\n */\nfunction codeMayWork(pending: PendingSignup, now = Date.now()): boolean {\n const received = receivedAtMs(pending)\n if (pending.flow.expires_in_s !== undefined && received !== null) return received + pending.flow.expires_in_s * 1000 > now\n if (pending.flow.expires_at !== undefined) {\n const at = Date.parse(pending.flow.expires_at)\n if (Number.isFinite(at)) return at > now\n }\n return true\n}\n\n/** Seconds left of the pending answer's `resend_after_s`: until a new code may be sent to that email (0: now). */\nfunction resendLeftS(pending: PendingSignup | null, now = Date.now()): number {\n if (pending === null || pending.flow.resend_after_s === undefined) return 0\n const received = receivedAtMs(pending)\n if (received === null) return 0\n return Math.max(0, Math.ceil((pending.flow.resend_after_s * 1000 - (now - received)) / 1000))\n}\n\n/** \"Run `cmd`\", after a wait when there is one. */\nfunction runLine(command: string, waitS = 0): string {\n return waitS > 0 ? `Wait ${waitS} s, then run \\`${command}\\`` : `Run \\`${command}\\``\n}\n\n/**\n * One question of `integration.account.run`, asked on the terminal. Its\n * labels are the SDK's; the choices around them (\"new\", y/N) are ours.\n */\nasync function askOnTerminal(question: kit.AccountQuestion): Promise<kit.AccountAnswer> {\n if (question.field === 'new_code') {\n const answer = await prompt('Send a new code? [y/N] ')\n return answer !== null && /^y(es)?$/i.test(answer) ? { answer: 'new_code' } : { answer: 'cancel' }\n }\n const choices =\n question.handles !== undefined && question.handles.length > 0 ? ` (${question.handles.map((h) => `@${h}`).join(', ')})` : ''\n const hint = question.field === 'code' ? ' (or \"new\" for a new code)' : ''\n const answer = await prompt(`${question.label ?? question.field}${choices}${hint}: `)\n if (answer === null) return { answer: 'cancel' }\n if (question.field === 'code') return answer.toLowerCase() === 'new' ? { answer: 'new_code' } : { answer: 'value', value: answer }\n return { answer: 'value', value: (question.field === 'handle' ? handleInput(answer) : emailInput(answer)) ?? '' }\n}\n\nconst NEXT_HINT =\n 'Open a new session for the hosted AgentChat tools to pick up the key; the integration daemon follows the credential on its own.'\n\nexport interface RegisterOpts {\n email?: string\n handle?: string\n displayName?: string\n description?: string\n /** The code from the verification email — the completion leg. */\n code?: string\n apiBase?: string\n}\n\nexport interface RecoverOpts {\n /** The email the agent registered with. */\n email?: string\n /**\n * Which agent on that email to re-key. When omitted it defaults to this\n * agent's stored handle, then to a prompt on a TTY; without one the\n * server is asked by email alone, and names the handles to choose from\n * when the email backs several agents.\n */\n handle?: string\n /** The code from the recovery email — the completion leg. */\n code?: string\n apiBase?: string\n}\n\nexport interface DoctorOpts {\n fix?: boolean\n}\n\nexport interface IdentityCommands {\n runRegister(opts: RegisterOpts): Promise<number>\n runLogin(opts: { apiKey?: string; apiBase?: string }): Promise<number>\n runRecover(opts: RecoverOpts): Promise<number>\n runStatus(opts: { json?: boolean }): Promise<number>\n runLogout(): number\n runDoctor(opts?: DoctorOpts): Promise<number>\n}\n\n/** Build the identity command set for one coding agent. */\nexport function createIdentityCommands(profile: HostProfile): IdentityCommands {\n const invocation = (): string => profile.invocation()\n const LABEL = profile.label\n const clientIdentity = clientIdentityOf(profile.client)\n\n /**\n * The refusal when an exported `AGENTCHAT_API_KEY` is not the key this\n * home holds, with what to do; null when there is no such split. Nothing\n * that acts as this agent adopts the exported key: it would quietly make\n * every command, and every placement `doctor --fix` writes, another agent\n * (found in testing). The listener of `@agentchatme/cli` refuses the\n * same split.\n */\n function envKeyRefusal(): string | null {\n const conflict = envKeyConflict(profile.home())\n if (conflict === null) return null\n return `${conflict}. Unset AGENTCHAT_API_KEY, or, to sign this home in with that key on purpose: printenv AGENTCHAT_API_KEY | ${invocation()} login --api-key -`\n }\n\n /**\n * One attempt, 5 s — for `status`, `doctor` and the texts fetch, which must\n * answer in seconds on a black-holed network (the SDK's default ramp is 4\n * attempts of up to 15 s).\n */\n const apiClient = (apiKey: string, apiBase: string): AgentChatClient =>\n new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5_000, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } })\n\n /** How the sign-up calls reach the server (never retried: a second call could send a second code). */\n const accountOptions = (apiBase: string): kit.AccountCallOptions => ({ clientIdentity, apiBase, timeoutMs: 15_000 })\n\n /**\n * The served texts for this agent: fetched now (one attempt, 5 s), else the\n * cached ones, else null (offline and never fetched). Fetched ONCE per\n * command: the identity line and the announced manual are handed to the\n * host's `place`, `extraStatus` and `extraDoctorChecks`, which must not\n * fetch again. The CLI never writes an identity line it did not get from\n * the server.\n */\n async function served(apiKey: string, apiBase: string): Promise<StatusContext> {\n const loaded = await loadTexts({ home: profile.home(), runtime: profile.client.runtime, client: apiClient(apiKey, apiBase), timeoutMs: 5_000 })\n return loaded === null ? NO_TEXTS : contextOf(loaded.texts)\n }\n\n /** The host's extra `status` lines, with the texts already fetched. */\n async function printExtraStatus(context: StatusContext): Promise<void> {\n if (profile.extraStatus === undefined) return\n try {\n for (const line of await profile.extraStatus(context)) console.log(line)\n } catch (err) {\n console.log(` (host status failed: ${err instanceof Error ? err.message : String(err)})`)\n }\n }\n\n /**\n * Place the integration for THIS agent's new key: the identity line, the\n * manual, the hosted tool server with the key. A profile without `place`\n * gets the anchor alone (the identity line in its instruction file).\n */\n async function placeIdentity(handle: string, apiKey: string, apiBase: string): Promise<string[]> {\n const { identityLine, manual } = await served(apiKey, apiBase)\n if (profile.place !== undefined) {\n try {\n return await profile.place(handle, apiKey, identityLine, manual)\n } catch (err) {\n return [` placement FAILED — ${String(err)}; repair with \\`${invocation()} doctor --fix\\``]\n }\n }\n return writeOurAnchor(handle, identityLine)\n }\n\n /** Write THIS agent's anchor. Only ever touches `profile.anchorFile()`. */\n function writeOurAnchor(handle: string, identityLine: string | null): string[] {\n if (profile.anchorFile === undefined) return []\n const file = profile.anchorFile()\n const label = anchorLabelOf(profile)\n // A host that wires itself separately must not be handed an identity block\n // before that wiring exists — it would announce a handle with nothing\n // listening. Once an anchor is already there, keep it current regardless.\n try {\n if (profile.isWired !== undefined && !profile.isWired() && !hasAnchorAt(file)) return []\n if (identityLine === null) {\n return [\n ` ${label}: identity line not written — GET /v1/texts could not be reached and nothing is cached; run \\`${invocation()} doctor --fix\\` once online`,\n ]\n }\n writeAnchor(file, profile.renderAnchor(identityLine, handle), handle)\n return [` ${label}: @${handle} → ${file}`]\n } catch (err) {\n return [` ${label}: FAILED — ${String(err)}`]\n }\n }\n\n // ─── Sign-up ──────────────────────────────────────────────────────────────\n\n /** The command that starts `kind` again, sending `input`; `blank` leaves that field for the person to fill in. */\n function startCommand(kind: AccountKind, input: SignupInput, blank?: 'email' | 'handle'): string {\n const email = blank === 'email' ? '<email>' : shellValue(input.email)\n const handle = blank === 'handle' ? '<handle>' : input.handle !== undefined ? shellValue(input.handle) : null\n if (kind === 'recover') return `${invocation()} recover${handle !== null ? ` --handle ${handle}` : ''} --email ${email}`\n return [\n `${invocation()} register --email ${email} --handle ${handle ?? '<handle>'}`,\n ...(input.display_name !== undefined ? [`--display-name ${shellValue(input.display_name)}`] : []),\n ...(input.description !== undefined ? [`--description ${shellValue(input.description)}`] : []),\n ].join(' ')\n }\n\n /** The command that answers a pending code: with `code`, or a placeholder of the server's `code_length`. */\n function codeCommand(kind: AccountKind, flow: SignupFlow, code?: string): string {\n const value = code !== undefined ? shellValue(code) : flow.code_length !== undefined ? `<${flow.code_length} digits>` : '<code>'\n return `${invocation()} ${kind} --code ${value}`\n }\n\n /**\n * What to run next, from the action the SDK read from the server's answer\n * (`actionOf` with the step called). The server's sentence says what\n * happened; this is the one thing it cannot say: the command, under this\n * integration's name. `held` is the pending code this agent holds for the\n * same email, if any.\n */\n function nextSteps(\n kind: AccountKind,\n result: StepResult,\n called: 'start' | 'verify',\n input: SignupInput,\n code: string | undefined,\n held: PendingSignup | null,\n ): string[] {\n // A new code is sent only once the server's wait and the email's resend\n // window are over: the window as this answer states it, else what is\n // left of the one the held code's answer stated.\n const beforeNewCode = Math.max(result.flow.retry_after_s ?? 0, result.flow.resend_after_s ?? resendLeftS(held))\n // A start turned away (429) while the code already sent still works: go\n // back to that code (contract v1, \"Sign-up flows\").\n const heldCode =\n called === 'start' && result.httpStatus === 429 && held !== null && held.handle === input.handle && codeMayWork(held)\n ? [`Or enter the code already sent: \\`${codeCommand(kind, held.flow)}\\``]\n : []\n switch (result.action) {\n case 'done':\n return []\n case 'ask_code':\n return [runLine(codeCommand(kind, result.flow))]\n case 'ask_param': {\n const param = result.flow.param\n const field = param === 'email' ? 'email' : param === 'handle' ? 'handle' : null\n if (field === null) return []\n const handles = field === 'handle' ? (result.handles ?? []) : []\n const choices = handles.length > 0 ? `, with one of: ${handles.map((h) => `@${h}`).join(', ')}` : ''\n return [`${runLine(startCommand(kind, input, field), beforeNewCode)}${choices}`]\n }\n case 'offer_new_code':\n return [`For a new code: ${runLine(startCommand(kind, input), beforeNewCode)}`]\n case 'wait_then_retry': {\n const again = called === 'verify' ? codeCommand(kind, result.flow, code) : startCommand(kind, input)\n return [runLine(again, result.flow.retry_after_s ?? 0), ...heldCode]\n }\n case 'stop':\n return heldCode\n }\n }\n\n /**\n * The server's sentence (its code when it sent none), then the next\n * command: on stdout when the step did what it was asked, else on stderr.\n */\n function report(result: StepResult, lines: string[], ok: boolean): number {\n const said = result.message.length > 0 ? result.message : (result.code ?? `HTTP ${result.httpStatus}`)\n const text = [said, ...lines].join('\\n')\n if (ok) console.log(text)\n else console.error(text)\n return ok ? 0 : 1\n }\n\n /**\n * The key is the server's: save it with the handle the server returned\n * (never the one typed), place the integration for it, say where it is.\n * `message` is the server's sentence, or null when it has been shown.\n */\n async function finishSignup(kind: AccountKind, apiKey: string, handle: string, apiBase: string, message: string | null): Promise<number> {\n const home = profile.home()\n writeCredentials(home, {\n api_key: apiKey,\n handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n clearPending(home)\n // They have an identity now, so a previous \"not now\" is spent. If they\n // ever sign out, the setup offer should be free to appear again.\n clearOfferDeclined(home)\n const placed = await placeIdentity(handle, apiKey, apiBase)\n const lines =\n kind === 'register'\n ? [\n `API key for @${handle} stored at ${credentialsPath(home)} (never commit this file).`,\n ...placed,\n '',\n `This handle belongs to your ${LABEL} agent. Another coding agent on this machine is a separate peer with its own handle — you can DM each other.`,\n `Other agents can DM you at @${handle}. Check \\`${invocation()} status\\` any time.`,\n NEXT_HINT,\n ]\n : [`New API key for @${handle} stored at ${credentialsPath(home)} (never commit this file).`, ...placed, NEXT_HINT]\n console.log([...(message !== null && message.length > 0 ? [message] : []), ...lines].join('\\n'))\n return 0\n }\n\n /** Ask for a code: one start call. The flow is kept only when the server sent a code. */\n async function startSignup(kind: AccountKind, input: SignupInput, apiBase: string): Promise<number> {\n const home = profile.home()\n const before = readPending(home)\n const held = before !== null && before.kind === kind && before.email === input.email ? before : null\n let result: StepResult\n try {\n result =\n kind === 'register'\n ? await kit.account.start(\n 'register',\n {\n email: input.email,\n handle: input.handle ?? '',\n ...(input.display_name !== undefined ? { display_name: input.display_name } : {}),\n ...(input.description !== undefined ? { description: input.description } : {}),\n },\n accountOptions(apiBase),\n )\n : await kit.account.start(\n 'recover',\n { email: input.email, ...(input.handle !== undefined ? { handle: input.handle } : {}) },\n accountOptions(apiBase),\n )\n } catch (err) {\n console.error(`Could not reach AgentChat: ${errorText(err)}\\n${runLine(startCommand(kind, input))} again.`)\n return 1\n }\n if (result.action === 'ask_code') {\n writePending(home, {\n kind,\n flow: result.flow,\n received_at: new Date().toISOString(),\n ...input,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n })\n }\n return report(result, nextSteps(kind, result, 'start', input, undefined, held), result.action === 'ask_code')\n }\n\n /** Answer the pending code: one verify call, then keep, refresh or drop the flow as the answer says. */\n async function submitPendingCode(kind: AccountKind, rawCode: string, apiBase: string): Promise<number> {\n const home = profile.home()\n const code = rawCode.trim()\n const pending = readPending(home)\n const noun = kind === 'register' ? 'registration' : 'recovery'\n if (pending === null) {\n console.error(\n `No ${noun} in progress. Start with: ${kind === 'register' ? `${invocation()} register --email <email> --handle <handle>` : recoverUsage(invocation())}`,\n )\n return 1\n }\n if (pending.kind !== kind) {\n console.error(\n pending.kind === 'recover'\n ? `The pending code belongs to an account RECOVERY — complete it with: ${invocation()} recover --code ${shellValue(code)}`\n : `The pending code belongs to a REGISTRATION — complete it with: ${invocation()} register --code ${shellValue(code)}`,\n )\n return 1\n }\n if (pending.flow.next_step !== VERIFY_STEP[kind] || pending.flow.pending_id === undefined) {\n clearPending(home)\n console.error(`The saved ${noun} is not waiting for a code. Start again with: ${startCommand(kind, pending)}`)\n return 1\n }\n const base = pending.api_base ?? apiBase\n let result: StepResult\n try {\n result = await kit.account.submitCode(pending.flow, code, accountOptions(base))\n } catch (err) {\n console.error(`Could not reach AgentChat: ${errorText(err)}\\n${runLine(codeCommand(kind, pending.flow, code))} again.`)\n return 1\n }\n switch (result.action) {\n case 'done':\n return finishSignup(kind, result.apiKey!, result.handle!, base, result.message)\n case 'ask_code':\n // A wrong code, or one in the wrong form: the same pending id, asked again.\n writePending(home, { ...pending, flow: result.flow, received_at: new Date().toISOString() })\n break\n case 'offer_new_code':\n case 'ask_param':\n // The code is gone (expired, too many wrong tries, used up): only a new start can go on.\n clearPending(home)\n break\n default:\n // wait_then_retry: the code was not checked, and stays. stop: it stays\n // too, until an answer says it is gone (a 5xx after the code may have\n // created the account: never steer to a second start).\n break\n }\n return report(result, nextSteps(kind, result, 'verify', pending, code, pending), false)\n }\n\n /**\n * The whole sign-up on a terminal, for a person who left out what the\n * command needs: `integration.account.run` asks for each field the server\n * names, the code, and whether to send a new one; shows every server\n * sentence; and sits out the server's short waits. Nothing is kept between\n * runs: an interrupted conversation starts again.\n */\n async function converse(kind: AccountKind, input: Partial<SignupInput>, apiBase: string): Promise<number> {\n let outcome: kit.AccountRunResult\n try {\n outcome = await kit.account.run({\n kind,\n input,\n ...accountOptions(apiBase),\n show: (message) => console.log(message),\n ask: askOnTerminal,\n })\n } catch (err) {\n console.error(`Could not reach AgentChat: ${errorText(err)}`)\n return 1\n }\n if (outcome.outcome === 'done') return finishSignup(kind, outcome.apiKey, outcome.handle, apiBase, null)\n if (outcome.outcome === 'cancelled') console.error('Cancelled.')\n return 1\n }\n\n async function runRegister(opts: RegisterOpts): Promise<number> {\n const home = profile.home()\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n\n if (opts.code !== undefined) return submitPendingCode('register', opts.code, apiBase)\n\n // The gate is about THIS agent only — another coding agent having an\n // identity is irrelevant and must never block this one.\n if (resolveIdentity(home) !== null) {\n console.error(\n `${LABEL} already has an AgentChat identity (see \\`${invocation()} status\\`). Run \\`${invocation()} logout\\` first to replace it.`,\n )\n return 1\n }\n if (readPending(home)?.kind === 'recover') {\n console.error(\n `An account recovery is in progress — finish it with \\`${invocation()} recover --code <code>\\`, or discard it with \\`${invocation()} logout\\` before registering.`,\n )\n return 1\n }\n\n const email = emailInput(opts.email)\n const handle = handleInput(opts.handle)\n const extras = {\n ...(opts.displayName ? { display_name: opts.displayName } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n }\n if (email === undefined || handle === undefined) {\n if (interactive()) {\n return converse('register', { ...(email !== undefined ? { email } : {}), ...(handle !== undefined ? { handle } : {}), ...extras }, apiBase)\n }\n console.error(`Missing --${email === undefined ? 'email' : 'handle'}. Usage: ${invocation()} register --email <email> --handle <handle>`)\n return 1\n }\n return startSignup('register', { email, handle, ...extras }, apiBase)\n }\n\n async function runLogin(opts: { apiKey?: string; apiBase?: string }): Promise<number> {\n const home = profile.home()\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n let apiKey = opts.apiKey?.trim()\n\n // Where the key comes from, most explicit first. A key is never asked for\n // as an argument: argv is visible in `ps` to every user of the machine and\n // kept in shell history. It is piped in (`--api-key -`), typed at the\n // prompt, or taken from AGENTCHAT_API_KEY when this home holds no other\n // key. `--api-key <key>` keeps working for scripts that pass one, and the\n // output says where the key was seen.\n const onArgv = apiKey !== undefined && apiKey.length > 0 && apiKey !== '-'\n if (apiKey === '-') {\n apiKey = await readAllStdin()\n } else if (!apiKey) {\n const fromEnv = process.env['AGENTCHAT_API_KEY']?.trim()\n const refusal = fromEnv ? envKeyRefusal() : null\n if (refusal !== null) {\n console.error(`${refusal}\\nlogin does not adopt an exported key in place of the one this home holds; nothing was saved.`)\n return 1\n }\n if (fromEnv) {\n apiKey = fromEnv\n console.log('Using the key from AGENTCHAT_API_KEY.')\n } else if (process.stdin.isTTY !== true) {\n console.error(\n `Missing API key. Run \\`${invocation()} login\\` in a terminal and paste the key when it asks, or pipe it in from a file: \\`${invocation()} login --api-key - < key.txt\\`. Never put the key itself on a command line: \\`ps\\` and shell history can see it there.`,\n )\n return 1\n } else {\n apiKey = (await prompt('AgentChat API key (ac_…): ')) ?? ''\n }\n }\n if (!apiKey) {\n console.error('No API key given; nothing was saved.')\n return 1\n }\n\n // The server judges the key; a key it does not accept is never saved.\n let check: kit.CheckKeyResult\n try {\n check = await kit.account.checkKey(apiKey, accountOptions(apiBase))\n } catch (err) {\n console.error(`Login failed: ${errorText(err)}\\nThe key was not saved.`)\n return 1\n }\n if (!check.ok) {\n console.error(`Login failed. ${check.code}: ${check.message}\\nThe key was not saved.`)\n return 1\n }\n writeCredentials(home, {\n api_key: apiKey,\n handle: check.handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n clearOfferDeclined(home)\n console.log(\n [\n `Signed in as @${check.handle} for ${LABEL}.`,\n `API key stored at ${credentialsPath(home)} (never commit this file).`,\n ...(await placeIdentity(check.handle, apiKey, apiBase)),\n NEXT_HINT,\n ...(onArgv\n ? [\n `Note: the key was on this command line, where \\`ps\\` and shell history can see it. Next time run \\`${invocation()} login\\` and paste it, or pipe it in: \\`${invocation()} login --api-key - < key.txt\\`.`,\n ]\n : []),\n ].join('\\n'),\n )\n return 0\n }\n\n // Recovery re-keys ONE agent. One email can back several agents, so the\n // handle rides along whenever it is known (this agent's stored one by\n // default); asked by email alone, the server answers an email that backs\n // several agents after the code, with the handles to choose from.\n async function runRecover(opts: RecoverOpts): Promise<number> {\n const home = profile.home()\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n\n if (opts.code !== undefined) return submitPendingCode('recover', opts.code, apiBase)\n\n let handle = handleInput(opts.handle)\n if (handle === undefined) {\n const stored = readCredentials(home)?.handle\n if (stored !== undefined) {\n handle = stored\n console.log(`Recovering @${stored} — this agent's stored handle (pass --handle to recover a different agent).`)\n }\n }\n const email = emailInput(opts.email)\n if (email === undefined) {\n if (!interactive()) {\n console.error(`Missing --email. Usage: ${recoverUsage(invocation())}`)\n return 1\n }\n if (handle === undefined) handle = handleInput((await prompt('Handle of the agent to recover: ')) ?? undefined)\n return converse('recover', handle !== undefined ? { handle } : {}, apiBase)\n }\n return startSignup('recover', { email, ...(handle !== undefined ? { handle } : {}) }, apiBase)\n }\n\n /**\n * The instruction file's block as `status` reports it. A file that exists\n * but cannot be read (permissions, a symlink loop, not UTF-8) is said as\n * such — it is neither \"missing\" nor a reason for status to print nothing.\n */\n function anchorView(file: string | null, identityLine: string | null, handle: string | null): { present: boolean | null; current: boolean | null; error: string | null } {\n if (file === null) return { present: null, current: null, error: null }\n try {\n const present = hasAnchorAt(file)\n const current = identityLine === null || handle === null ? null : anchorIsCurrentAt(file, identityLine, handle)\n return { present, current, error: null }\n } catch (err) {\n return { present: null, current: null, error: errorText(err) }\n }\n }\n\n async function runStatus(opts: { json?: boolean }): Promise<number> {\n const home = profile.home()\n const anchorFile = profile.anchorFile?.() ?? null\n // A split identity is said before anything else, and nothing is asked of\n // the server with either key: status names one agent or none.\n const refusal = envKeyRefusal()\n if (refusal !== null) {\n if (opts.json) console.log(JSON.stringify({ configured: true, host: profile.id, error: { kind: 'env_key_conflict', detail: refusal }, home }))\n else console.error(refusal)\n return 1\n }\n const identity = resolveIdentity(home)\n const pending = readPending(home)\n const integration = readIntegrationStatus(home)\n\n if (identity === null) {\n if (opts.json) {\n console.log(\n JSON.stringify({\n configured: false,\n host: profile.id,\n pending: pending !== null,\n pending_kind: pending?.kind ?? null,\n integration,\n }),\n )\n } else if (pending !== null) {\n const what =\n pending.kind === 'recover'\n ? `an account recovery${pending.handle !== undefined ? ` for @${pending.handle}` : ''}`\n : `a registration for @${pending.handle ?? '?'}`\n console.log(\n codeMayWork(pending)\n ? `No identity yet, but ${what} is waiting on its emailed code — finish with: ${codeCommand(pending.kind, pending.flow)}`\n : `No identity yet; the code for ${what} has expired — for a new one, run: ${startCommand(pending.kind, pending)}`,\n )\n } else {\n console.log(`No AgentChat identity for this ${LABEL} agent. Set one up with: ${invocation()} register`)\n }\n return 0\n }\n\n let me: Awaited<ReturnType<AgentChatClient['getMe']>>\n const client = apiClient(identity.apiKey, identity.apiBase)\n try {\n me = await client.getMe()\n } catch (err) {\n // A refused key is not an unreachable server, and neither hides the\n // integration: its socket state and last error (`blocked`, `auth\n // rejected (close 1008 …)`) are exactly what explains the failure.\n const status = httpStatusOf(err)\n const refused = status === 401 || status === 403\n const detail = describeApiError(err)\n if (opts.json) {\n const offline = anchorView(anchorFile, null, null)\n console.log(\n JSON.stringify({\n configured: true,\n host: profile.id,\n handle: identity.handle,\n error: { kind: refused ? 'key_refused' : 'unreachable', status, detail },\n key_source: identity.source,\n api_base: identity.apiBase,\n home,\n anchor: offline.present,\n anchor_error: offline.error,\n integration,\n }),\n )\n } else {\n console.error(\n refused\n ? `AgentChat refused this agent's key (${detail}). Sign in with a current key: \\`${invocation()} login\\`; lost it? \\`${recoverUsage(invocation())}\\`.`\n : `Could not reach AgentChat: ${detail}`,\n )\n console.log(\n [\n `${identity.handle !== null ? `@${identity.handle}` : 'This agent'} — ${refused ? `key refused (HTTP ${status})` : 'AgentChat unreachable'} (${LABEL})`,\n `Key source: ${identity.source} (${identity.source === 'file' ? credentialsPath(home) : 'AGENTCHAT_API_KEY'})`,\n `API: ${identity.apiBase}`,\n ...formatIntegrationStatus(integration),\n ].join('\\n'),\n )\n // The server did not answer, so no texts fetch either: the host checks\n // what it can against the identity-home cache (what a fetch would\n // have fallen back to), or without texts when nothing is cached.\n const cached = readCachedTexts(home, profile.client.runtime)\n await printExtraStatus(cached === null ? NO_TEXTS : contextOf(cached.texts))\n }\n return 1\n }\n\n const tray = await traySummary(client).catch(() => null)\n const texts = await served(identity.apiKey, identity.apiBase)\n const identityLine = texts.identityLine\n const anchor = anchorView(anchorFile, identityLine, me.handle)\n\n if (opts.json) {\n console.log(\n JSON.stringify({\n configured: true,\n host: profile.id,\n handle: me.handle,\n status: me.status ?? 'unknown',\n tray,\n key_source: identity.source,\n api_base: identity.apiBase,\n home,\n anchor: anchor.present,\n /** null: the served texts were unavailable (or there is no instruction file, or it cannot be read), so currency could not be checked. */\n anchor_current: anchor.current,\n /** Why the instruction file could not be read, or null. */\n anchor_error: anchor.error,\n integration,\n }),\n )\n } else {\n const trayLine =\n tray === null\n ? 'Tray: could not be read'\n : `Tray: ${tray.waiting}${tray.truncated ? '+' : ''} conversation(s) waiting${tray.deferred > 0 ? `, ${tray.deferred} deferred` : ''}`\n console.log(\n [\n `@${me.handle} — ${me.status ?? 'active'} (${LABEL})`,\n trayLine,\n `Key source: ${identity.source} (${identity.source === 'file' ? credentialsPath(home) : 'AGENTCHAT_API_KEY'})`,\n `API: ${identity.apiBase}`,\n ...(anchorFile === null\n ? []\n : [\n `Identity line: ${anchor.error !== null ? `unreadable — ${anchor.error}` : anchor.present ? (anchor.current === null ? 'present (served texts unavailable — not checked)' : anchor.current ? 'current' : 'present (older text — `doctor --fix` refreshes it)') : 'missing'} (${anchorFile})`,\n ]),\n ...formatIntegrationStatus(integration),\n ].join('\\n'),\n )\n await printExtraStatus(texts)\n }\n return 0\n }\n\n /**\n * Sign out THIS agent. Authentication and integration installation are\n * separate lifecycles: logout must never silently remove the service or the\n * manual. It removes what authenticates as the old identity: the credential,\n * the identity line, and the key the hosted tool server was registered with.\n */\n function runLogout(): number {\n const home = profile.home()\n const anchorFile = profile.anchorFile?.() ?? null\n const reports: string[] = []\n let any = false\n\n // Read BEFORE clearing: `unplace` recognises the host's own registration\n // by the key and the API base that were placed, and both are gone from\n // disk once the credential is deleted.\n const identity = resolveIdentity(home)\n\n if (clearCredentials(home)) {\n any = true\n reports.push(' credentials deleted')\n }\n if (anchorFile !== null) {\n // A file that cannot be rewritten must not stop the sign-out half-way:\n // `unplace` below still has to take the old key out of the host.\n try {\n if (removeAnchorAt(anchorFile) === 'removed') {\n any = true\n reports.push(` ${anchorLabelOf(profile)} identity line removed`)\n }\n } catch (err) {\n any = true\n reports.push(` could not remove the identity line from ${anchorFile}: ${errorText(err)} — remove the agentchat block by hand`)\n }\n }\n if (profile.unplace !== undefined) {\n try {\n const lines = profile.unplace(identity)\n if (lines.length > 0) any = true\n reports.push(...lines)\n } catch (err) {\n reports.push(` could not undo placement: ${String(err)}`)\n }\n }\n\n console.log(\n [\n any ? `Signed out of ${LABEL}.` : 'Nothing to sign out of.',\n ...reports,\n ...(any\n ? [\n 'Any other coding agent on this machine is untouched — it is a separate AgentChat agent with its own handle.',\n ...(profile.logoutHints?.() ?? []),\n ]\n : []),\n ].join('\\n'),\n )\n return 0\n }\n\n /** What the instruction file claims, and whether it is the current block (null: no served line in hand). Throws when the file cannot be read. */\n function readIdentityLine(anchorFile: string, handle: string, texts: StatusContext): { claimed: string | null; current: boolean | null } {\n const claimed = readAnchorHandleAt(anchorFile, texts.identityLineTemplate)\n const current = texts.identityLine === null ? null : anchorIsCurrentAt(anchorFile, texts.identityLine, handle)\n return { claimed, current }\n }\n\n /** The doctor's identity-line check (and its `--fix`), for a host that has an instruction file. */\n async function identityLineCheck(\n anchorFile: string,\n creds: { handle: string; api_key: string },\n apiBase: string,\n texts: StatusContext,\n fix: boolean,\n ): Promise<DoctorCheck> {\n let claimed: string | null\n let current: boolean | null\n try {\n ;({ claimed, current } = readIdentityLine(anchorFile, creds.handle, texts))\n } catch (err) {\n return { name: 'identity-line', verdict: 'FAIL', detail: `cannot read ${anchorFile}: ${errorText(err)}` }\n }\n if (claimed === creds.handle && current === true) {\n return { name: 'identity-line', verdict: 'PASS', detail: `@${claimed} in ${anchorFile}` }\n }\n if (claimed === creds.handle && current === null) {\n return { name: 'identity-line', verdict: 'WARN', detail: `@${claimed} in ${anchorFile} (currency not checked: served texts unavailable)` }\n }\n const why =\n claimed === null\n ? `no identity line in ${anchorFile}`\n : claimed !== creds.handle\n ? `${anchorFile} says @${claimed} but this agent is @${creds.handle}`\n : `${anchorFile} carries an older identity text for @${claimed}`\n if (fix) {\n const report = await placeIdentity(creds.handle, creds.api_key, apiBase)\n const failed = report.some((l) => l.includes('FAILED') || l.includes('not written'))\n if (failed) return { name: 'identity-line', verdict: 'FAIL', detail: `could not repair: ${report.join('; ')}` }\n // Said repaired only when the file now reads as repaired.\n try {\n const after = readIdentityLine(anchorFile, creds.handle, texts)\n if (after.claimed === creds.handle && after.current !== false) {\n return { name: 'identity-line', verdict: 'PASS', detail: `repaired → @${creds.handle}` }\n }\n return { name: 'identity-line', verdict: 'FAIL', detail: `repair did not take: ${anchorFile} still ${after.claimed === null ? 'has no identity line' : after.claimed !== creds.handle ? `says @${after.claimed}` : 'differs from the served block'}${report.length > 0 ? ` (${report.join('; ').trim()})` : ''}` }\n } catch (err) {\n return { name: 'identity-line', verdict: 'FAIL', detail: `cannot read ${anchorFile} after the repair: ${errorText(err)}` }\n }\n }\n return { name: 'identity-line', verdict: 'WARN', detail: `${why} — repair with \\`${invocation()} doctor --fix\\`` }\n }\n\n async function runDoctor(opts: DoctorOpts = {}): Promise<number> {\n const home = profile.home()\n const anchorFile = profile.anchorFile?.() ?? null\n const checks: DoctorCheck[] = []\n let texts: StatusContext = NO_TEXTS\n\n checks.push({ name: 'node', verdict: 'PASS', detail: process.version })\n checks.push({ name: 'home', verdict: 'PASS', detail: home })\n // Every check below, and every repair `--fix` makes, uses the home's key.\n const refusal = envKeyRefusal()\n if (refusal !== null) checks.push({ name: 'env-key', verdict: 'FAIL', detail: refusal })\n\n const creds = readCredentials(home)\n if (creds === null) {\n checks.push({\n name: 'credentials',\n verdict: 'FAIL',\n detail: `no identity at ${credentialsPath(home)} — run \\`${invocation()} register\\``,\n })\n } else {\n checks.push({ name: 'credentials', verdict: 'PASS', detail: `@${creds.handle}` })\n const identity = resolveIdentity(home)\n if (identity !== null) {\n try {\n const client = apiClient(identity.apiKey, identity.apiBase)\n const started = Date.now()\n const me = await client.getMe()\n const verdict: Verdict = (me.status ?? 'active') === 'active' ? 'PASS' : 'WARN'\n checks.push({\n name: 'api-auth',\n verdict,\n detail: `@${me.handle} status=${me.status ?? 'active'} (${Date.now() - started}ms)`,\n })\n if (me.handle !== creds.handle) {\n checks.push({\n name: 'handle-drift',\n verdict: 'WARN',\n detail: `credentials say @${creds.handle} but the key authenticates as @${me.handle} — re-run \\`${invocation()} login\\``,\n })\n }\n } catch (err) {\n checks.push({ name: 'api-auth', verdict: 'FAIL', detail: `getMe failed: ${String(err)}` })\n }\n }\n\n // The identity line must name THIS agent, in the text the server serves\n // today. Releases of the old shared CLI wrote the anchor for every host\n // on the machine whenever any one registered, so a two-agent box could\n // end up with an instruction file announcing the OTHER agent's handle.\n const apiBase = identity?.apiBase ?? creds.api_base ?? DEFAULT_API_BASE\n texts = await served(creds.api_key, apiBase)\n checks.push(\n texts.identityLine === null\n ? { name: 'texts', verdict: 'WARN', detail: 'GET /v1/texts could not be reached and nothing is cached — the identity line cannot be checked or placed until it can' }\n : { name: 'texts', verdict: 'PASS', detail: 'served texts in hand' },\n )\n if (anchorFile !== null) checks.push(await identityLineCheck(anchorFile, creds, apiBase, texts, opts.fix === true))\n }\n\n // The receive loop's own record: repeated cycles that did not get done\n // (a runtime that fails, texts that never arrive, a cycle abandoned by\n // its watchdog) are a pattern to fix, even while the socket looks fine.\n const integration = readIntegrationStatus(home)\n // Runs failing for a runtime reason, as the daemon's own recheck found\n // (signed out, the binary gone, a flag an upgrade dropped).\n const runsFailing = integration?.runs_failing ?? null\n const gaveUp = integration?.unservable ?? null\n if (gaveUp !== null) {\n checks.push({\n name: 'runs',\n verdict: 'FAIL',\n detail:\n gaveUp.reason === 'key_refused'\n ? `this home gave the agent up: the server refuses its key (${gaveUp.detail}); it looks again at ${gaveUp.retry_at} (every 5 min) and takes the agent back whenever no other listener holds it, but only a key the server accepts can serve — sign in again here (login/recover; that clears this at once), or log out if another home serves the agent`\n : `this home gave the agent up: ${gaveUp.detail} (since ${gaveUp.since}); its runtime is checked again at ${gaveUp.retry_at} (every 60 s) and a check that passes clears this; it takes the agent back whenever no other listener holds it`,\n })\n } else if (runsFailing !== null) {\n checks.push({\n name: 'runs',\n verdict: 'FAIL',\n detail: `runs failing: ${runsFailing.reason} — since ${runsFailing.since}, ${runsFailing.runs_missed} run(s) missed (checked ${runsFailing.checked_at}); fix that, and the next run that succeeds clears this`,\n })\n }\n // Another daemon serves this agent from another identity home.\n const standby = integration?.standby ?? null\n if (standby !== null) {\n checks.push({\n name: 'single-listener',\n verdict: 'WARN',\n detail: `another listener serves this agent: ${standby.home ?? 'another identity home'}${standby.pid !== null ? ` (pid ${standby.pid})` : ''}; this one stands by (no socket, no run) so no message is answered twice`,\n })\n }\n const cycles = integration?.recent_cycles ?? []\n if (cycles.length > 0) {\n const failing = failedCyclesInARow(integration)\n const last = cycles[cycles.length - 1]!\n checks.push(\n failing !== null && failing.count >= REPEATED_FAILED_CYCLES\n ? {\n name: 'wake-cycles',\n verdict: 'WARN',\n detail: `the last ${failing.count} wake cycles did not get done (latest: ${failing.latest.outcome}${failing.latest.failure ? ` — ${failing.latest.failure}` : ''}); the cards stay on the tray`,\n }\n : { name: 'wake-cycles', verdict: 'PASS', detail: `last cycle ${last.outcome} at ${last.at} (${cycles.length} recent)` },\n )\n }\n // With conversation runs a cycle only starts runs: runs that keep failing\n // with no runtime reason found are said here.\n const failedRuns = repeatedFailedRuns(integration)\n if (failedRuns !== null) {\n const lastRun = integration?.last_run ?? null\n checks.push({\n name: 'runs',\n verdict: 'WARN',\n detail: `the last ${failedRuns} runs did not get done${lastRun !== null ? ` (latest: ${lastRun.state}${lastRun.detail ? ` — ${lastRun.detail}` : ''})` : ''}; the cards stay on the tray`,\n })\n }\n // Could not process: the conversations paused for this agent (a pause is\n // the server's, with its own end, whether or not the daemon runs), and a\n // runtime check that fails (then no failure is reported as a\n // conversation's: a broken runtime is not its fault) — said only while\n // the status file is fresh: a check from before the daemon went quiet\n // says nothing about now.\n const cnp = integration?.could_not_process ?? null\n if (cnp !== null) {\n const paused = describePausedConversations(cnp.paused_conversations)\n const lastCheck = cnp.last_runtime_check\n const counts = describeCouldNotProcessCounts(cnp)\n if (paused !== null) {\n checks.push({ name: 'could-not-process', verdict: 'WARN', detail: paused.replace(/^could not process: /, '') })\n } else if (lastCheck !== null && runtimeCheckFailingNow(integration)) {\n checks.push(\n integrationStatusFresh(integration)\n ? {\n name: 'could-not-process',\n verdict: 'WARN',\n detail: `the runtime check failed (${lastCheck.detail ?? 'no detail'}; ${lastCheck.at}): while it fails, a conversation whose run fails is not reported, its card stays on the tray and the server wakes the agent again`,\n }\n : {\n name: 'could-not-process',\n verdict: 'WARN',\n detail: `the daemon has not written its status for ${integrationStatusStaleFor(integration)} — it may be down (a running daemon rewrites it every 30 s); the runtime check that failed at ${lastCheck.at} says nothing about now`,\n },\n )\n } else if (counts !== null) {\n checks.push({ name: 'could-not-process', verdict: 'PASS', detail: counts.replace(/^could not process: /, '') })\n }\n }\n\n if (profile.extraDoctorChecks !== undefined) {\n try {\n checks.push(...(await profile.extraDoctorChecks({ ...opts, ...texts })))\n } catch (err) {\n checks.push({ name: 'host', verdict: 'FAIL', detail: `the ${LABEL} checks failed: ${errorText(err)}` })\n }\n }\n\n console.log(checks.map((c) => `${c.verdict.padEnd(4)} ${c.name}: ${c.detail}`).join('\\n'))\n return checks.some((c) => c.verdict === 'FAIL') ? 1 : 0\n }\n\n return {\n runRegister,\n runLogin,\n runRecover,\n runStatus,\n runLogout,\n runDoctor,\n }\n}\n","import type { IntegrationClient } from '../client-identity.js'\nimport type { ServedManual } from '../skill/served-manual.js'\nimport type { ResolvedIdentity } from './credentials.js'\n\nexport type Verdict = 'PASS' | 'WARN' | 'FAIL'\n\nexport interface DoctorCheck {\n name: string\n verdict: Verdict\n detail: string\n}\n\n/** What the shared `status` hands a host's extra lines: what it already fetched from the served texts (one fetch per command). */\nexport interface StatusContext {\n identityLine: string | null\n /**\n * The served `identity_line_template` from the same texts, or null when none\n * are in hand: what `readAnchorHandleAt` recognises an unmarked block by, in\n * whatever words the server serves today.\n */\n identityLineTemplate: string | null\n /** The manual the served texts announce (`texts.manual`), or null when none are in hand — what `checkManual` compares the skill file with. */\n manual: ServedManual | null\n}\n\n/** What the shared doctor hands a host's extra checks. */\nexport interface DoctorContext {\n fix?: boolean\n /** The served identity line for this agent, or null when the server could not be reached and nothing is cached. */\n identityLine: string | null\n /** The served `identity_line_template`, or null when none are in hand (see `StatusContext`). */\n identityLineTemplate: string | null\n /** The manual the served texts announce, or null when none are in hand (`--fix` syncs the skill file to it). */\n manual: ServedManual | null\n}\n\n/**\n * Everything the shared identity commands need to know about ONE coding agent.\n *\n * This is the seam. The register / login / recover / status / logout / doctor\n * flows are the same everywhere because they are a contract with the AgentChat\n * server; what differs per host is only what is described here. An integration\n * builds one of these and gets the commands back.\n *\n * Note what is NOT here: any way to name a *different* host. A profile\n * describes the caller and nothing else, so a command built from it cannot\n * reach another agent's files. That is the same property the per-repo split\n * gives, kept intact while the flow itself is shared once.\n *\n * The path-ish fields are functions, not strings: `CODEX_HOME` and friends are\n * read per call, and evaluating them at module load would freeze a value the\n * user can still change.\n */\nexport interface HostProfile {\n /** Human name for output, e.g. `Claude Code`. */\n label: string\n /** Stable machine identifier for `--json`, e.g. `claude-code`. */\n id: string\n /** How this integration names itself to the server: the texts runtime and its own version. */\n client: IntegrationClient\n /** THE identity home for this agent. */\n home(): string\n /**\n * This host's always-loaded instruction file. Absent for a front door whose\n * runtime has none it can place a line in (the `agentchat` listener runs an\n * owner's command): no identity line is placed, checked or removed.\n */\n anchorFile?(): string\n /** Exactly what a user types to reach this integration. */\n invocation(): string\n /**\n * The identity block this host places for `handle` from the served identity\n * line (normally `renderAnchorBlock`, the kit's shape with the handle line).\n * Throws when the line does not name the handle; nothing is written then.\n */\n renderAnchor(identityLine: string, handle: string): string\n /**\n * What to call the anchor in output. Defaults to the instruction file's own\n * basename (`CLAUDE.md`, `AGENTS.md`), which is what a user actually looks\n * for on disk.\n */\n anchorLabel?: string\n /**\n * Whether this host is wired up enough for an anchor to mean anything.\n * An integration uses this so it never writes an identity block announcing\n * a phone number before its own placement is actually in place.\n */\n isWired?(): boolean\n /**\n * Place the integration's texts for a freshly established identity: the\n * identity line, the manual, the hosted tool server with the key, and\n * whatever the key's home is on this runtime. Called after register, login\n * and recover (every time the key changes), and by `doctor --fix`.\n * `identityLine` is the served line for this agent (fetched just before,\n * or the cached one), or null when neither could be had — the host then\n * leaves the anchor for `doctor --fix` and says so. `manual` is what the\n * same texts announce (`syncManual` brings the skill file to it), or null.\n * Returns report lines. When absent, only the anchor is written.\n */\n place?(handle: string, apiKey: string, identityLine: string | null, manual: ServedManual | null): string[] | Promise<string[]>\n /**\n * Undo `place` for the identity being signed out: remove the key from the\n * tool server registration and anything else that would still authenticate\n * as the old identity. The anchor is removed by the shared flow. Returns\n * report lines.\n *\n * `identity` is the identity AS IT WAS BEFORE the credential was cleared\n * (its key and API base), or null when there was none: a host recognises\n * its own registration by that key and that server, and guessing either\n * after the fact left a non-default `api_base` entry classified as foreign\n * and the key still registered.\n */\n unplace?(identity: ResolvedIdentity | null): string[]\n /** Host-specific doctor checks, appended after the shared ones. */\n extraDoctorChecks?(context: DoctorContext): DoctorCheck[] | Promise<DoctorCheck[]>\n /**\n * Host-specific `status` lines (placement, probes), printed after the shared\n * ones in text mode. The served identity line and manual come along so the\n * host does not fetch `/v1/texts` a second time.\n */\n extraStatus?(context: StatusContext): string[] | Promise<string[]>\n /** Extra lines printed after a successful logout. */\n logoutHints?(): string[]\n}\n\n/** The label to use for this host's anchor in user-facing output. */\nexport function anchorLabelOf(profile: HostProfile): string {\n if (profile.anchorLabel !== undefined) return profile.anchorLabel\n if (profile.anchorFile === undefined) return 'identity line'\n const file = profile.anchorFile()\n const slash = Math.max(file.lastIndexOf('/'), file.lastIndexOf('\\\\'))\n return slash >= 0 ? file.slice(slash + 1) : file\n}\n","import * as crypto from 'node:crypto'\nimport * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { log } from '../util/log.js'\nimport { atomicWriteFile } from '../util/fsutil.js'\nimport { spawnCommand, spawnCommandSync } from '../util/spawn.js'\nimport { holderLive, parseLease } from '../util/lease.js'\nimport { DAEMON_LOCK_FILE } from './leader-lock.js'\n\n// ─── Service lifecycle (systemd / launchd / Windows Startup) ─────────────────\n//\n// `agentchatd start` only runs while the shell is open — no good for a 24/7\n// consumer product. `install` registers the daemon as a real background\n// service that starts on boot/login and restarts on crash:\n// * Linux (native) → a systemd USER unit + `loginctl enable-linger`.\n// * macOS → a launchd LaunchAgent with KeepAlive + RunAtLoad.\n// * Windows / WSL2 → a hidden, restart-on-exit VBScript in the user's Startup\n// folder (no admin). See the Windows section below.\n// One service per INTEGRATION (the leader lock already enforces one daemon per\n// identity on a box). The caller supplies the label and the env to capture —\n// this module has no idea which coding agents exist, which is what keeps two\n// integrations' services from ever colliding on a name or clobbering each\n// other's unit file. Convention is `agentchatd-<integration>`.\n//\n// ONE LABEL PER IDENTITY HOME, and never touch a job that serves another one.\n// `launchctl` and `systemctl --user` address the USER's domain, not the\n// current HOME or config dir, while the unit file follows HOME and the\n// identity home follows CLAUDE_CONFIG_DIR / CODEX_HOME. With one global label\n// per integration, a relocated config (a sandbox, a second profile) reported\n// the machine's real service as its own, and `uninstall` there would have\n// `launchctl remove`d it (live-fire E5). So:\n// * `serviceLabelFor` gives a relocated identity home its own label (a\n// short stable hash suffix); the default home keeps the plain label, so\n// existing installs keep working;\n// * before stopping, replacing or removing a job, its definition (the unit\n// file at this label's path, and the job the service manager has loaded\n// under this label) is read, and the operation is refused unless its\n// `--home` is this config's identity home;\n// * `AGENTCHAT_SERVICE_DRY_RUN` keeps the service manager out entirely —\n// not written, not stopped, not even queried for status.\n\n/**\n * Enough to ADDRESS an already-installed service. Removing one or reading its\n * status needs only its name — deliberately a narrower type than install, so\n * `uninstall` and `status` cannot be made to depend on a daemon entry they have\n * no use for.\n */\nexport interface ServiceRef {\n /** Unit/service name, e.g. `agentchatd-codex` — from `serviceLabelFor`, so unique per identity home. */\n label: string\n home: string\n /**\n * Labels this service replaces (e.g. the plain label a relocated home was\n * installed under before labels were per home). On install and uninstall,\n * a superseded service whose definition serves THIS home is removed; one\n * serving another home is left alone.\n */\n supersedes?: readonly string[]\n}\n\n/**\n * The service label for an identity home: `base` for the integration's\n * default home (so existing installs keep their label), `base-<8 hex>` — a\n * stable hash of the resolved path — for any other. Two configs of one\n * integration on one machine then never share a launchd/systemd job.\n */\nexport function serviceLabelFor(base: string, home: string, defaultHome: string): string {\n const key = (p: string): string => {\n const resolved = path.resolve(p)\n return process.platform === 'win32' ? resolved.toLowerCase() : resolved\n }\n if (key(home) === key(defaultHome)) return serviceLabel(base)\n const digest = crypto.createHash('sha256').update(key(home)).digest('hex').slice(0, 8)\n return serviceLabel(`${base}-${digest}`)\n}\n\nexport interface ServiceOpts extends ServiceRef {\n /**\n * Absolute path to the integration's DAEMON bundle — the script this service\n * runs. Required, and deliberately not defaulted.\n *\n * It used to default to `process.argv[1]`, i.e. whichever binary happened to\n * call `install`. That was the CLI, which has no daemon in it, so every\n * installed unit ran a command that exited 1 and then restart-looped forever\n * under `KeepAlive`/`Restart=on-failure` while the CLI cheerfully reported\n * \"Always-on is ON\". Making the caller name the entry is what stops a service\n * from being installed against a script that cannot serve it.\n *\n * Must also be a STABLE path. A plugin's own bundle lives in a\n * version-scoped cache directory that the next upgrade deletes, so an\n * integration distributed that way copies itself somewhere durable first and\n * passes that copy here.\n */\n entry: string\n /** Host-specific env the service must see because a systemd/launchd service\n * does NOT inherit the login shell (e.g. CODEX_HOME). PATH is captured\n * automatically. */\n env?: Record<string, string>\n}\n\nexport interface Plan {\n label: string // service/unit name\n node: string // absolute node path\n bin: string // absolute daemon entry, supplied by the integration\n home: string\n /** Host env captured from the current shell so the service sees the same\n * CODEX_HOME / CLAUDE_CONFIG_DIR the user installed under. */\n env: Record<string, string>\n}\n\nexport function planForTest(opts: ServiceOpts): Plan {\n return plan(opts)\n}\n\nfunction serviceValue(name: string, value: string): string {\n // Every supported service format is line-oriented; CR/LF/NUL would either\n // make an invalid definition or inject a new directive/script statement.\n if (/[\\0\\r\\n]/.test(value)) {\n throw new Error(`invalid control character in service ${name}`)\n }\n return value\n}\n\nfunction serviceLabel(value: string): string {\n if (!/^[A-Za-z0-9_.-]+$/.test(value)) {\n throw new Error(`invalid service label: ${value}`)\n }\n return value\n}\n\nfunction transientPathEntry(value: string): boolean {\n const normalized = value.replace(/\\\\/g, '/')\n return (\n /\\/node_modules\\/\\.bin\\/?$/i.test(normalized) ||\n /\\/node_modules\\/npm\\/node_modules\\/@npmcli\\/run-script\\/lib\\/node-gyp-bin\\/?$/i.test(normalized) ||\n /\\/\\.[^/]+\\/tmp\\//i.test(normalized)\n )\n}\n\n/** npm/NPX and agent shells prepend disposable directories to PATH. Capturing\n * those verbatim makes every later doctor run call a healthy service stale.\n * Keep real user paths, canonicalize version-manager symlinks, and anchor the\n * service to the Node installation that actually built its command plan. */\nexport function stableServicePath(\n value: string,\n nodePath: string = process.execPath,\n): string {\n const entries = [path.dirname(nodePath), ...value.split(path.delimiter)]\n const seen = new Set<string>()\n const stable: string[] = []\n for (const raw of entries) {\n const trimmed = raw.trim()\n if (!trimmed || transientPathEntry(trimmed)) continue\n let resolved = trimmed\n try {\n resolved = fs.realpathSync(trimmed)\n } catch {\n // A currently absent user path can become valid later; preserve it.\n }\n const key = process.platform === 'win32' ? resolved.toLowerCase() : resolved\n if (seen.has(key)) continue\n seen.add(key)\n stable.push(resolved)\n }\n return stable.join(path.delimiter)\n}\n\nfunction plan(opts: ServiceOpts): Plan {\n const env: Record<string, string> = {}\n // CRITICAL: a systemd/launchd service does NOT inherit the login shell's\n // PATH, so it can't find `claude` / `codex` / `npx` (often in ~/.local/bin\n // or a version-manager dir). Capture the installer's PATH so the service\n // resolves the same binaries the user does. (Without this the daemon exits\n // \"claude CLI not found on PATH\" and restart-loops.)\n if (process.env['PATH']) {\n env['PATH'] = serviceValue(\n 'environment value',\n stableServicePath(process.env['PATH']),\n )\n }\n // Whatever host env the integration says its adapter needs.\n for (const [k, v] of Object.entries(opts.env ?? {})) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) throw new Error(`invalid service environment key: ${k}`)\n if (typeof v === 'string' && v.length > 0) {\n env[k] = serviceValue(\n 'environment value',\n k === 'PATH' ? stableServicePath(v) : v,\n )\n }\n }\n return {\n label: serviceLabel(opts.label),\n node: serviceValue('Node path', process.execPath),\n bin: serviceValue('entry path', path.resolve(opts.entry)),\n home: serviceValue('home path', path.resolve(opts.home)),\n env,\n }\n}\n\nexport type ServiceCommandRunner = (cmd: string, args: string[]) => { ok: boolean; out: string }\n\nfunction runReal(cmd: string, args: string[]): { ok: boolean; out: string } {\n const r = spawnCommandSync(cmd, args, { encoding: 'utf-8' })\n const out = [\n typeof r.stdout === 'string' ? r.stdout : '',\n typeof r.stderr === 'string' ? r.stderr : '',\n r.error?.message ?? '',\n ]\n .filter((part) => part.length > 0)\n .join('\\n')\n .trim()\n return {\n ok: !r.error && r.status === 0,\n out,\n }\n}\n\nlet commandRunner: ServiceCommandRunner = runReal\n\n/**\n * Tests only: answer `launchctl` / `systemctl` / `loginctl` with a fake, so a\n * test can exercise the ownership guard without reaching the real service\n * manager. `null` restores the real one.\n */\nexport function setServiceCommandRunnerForTests(runner: ServiceCommandRunner | null): void {\n commandRunner = runner ?? runReal\n}\n\nfunction run(cmd: string, args: string[]): { ok: boolean; out: string } {\n return commandRunner(cmd, args)\n}\n\n/**\n * Write the unit file but do NOT hand it to the OS service manager.\n *\n * `HOME` sandboxes where the unit file lands, but it does not sandbox\n * `launchctl` or `systemctl` — those always address the real user's domain. So\n * a test that exercises `daemon install` registers a REAL service on the\n * developer's machine, pointed at a temp directory that is about to be deleted.\n * That happened, and it left two loaded launchd jobs behind.\n *\n * With this set, everything up to registration still runs and can be asserted\n * on; only the escaping side effect is skipped.\n */\nfunction registrationSkipped(): boolean {\n const v = process.env['AGENTCHAT_SERVICE_DRY_RUN']\n return v !== undefined && v !== '' && v !== '0'\n}\n\n// ─── which identity home a service serves ────────────────────────────────────\n\n/** The argument after `--home` in an argument list, or null. */\nfunction homeFromArgs(args: readonly string[]): string | null {\n const i = args.indexOf('--home')\n const next = i >= 0 ? args[i + 1] : undefined\n return next !== undefined && next.length > 0 ? next : null\n}\n\nfunction xmlUnescape(value: string): string {\n return value\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&quot;/g, '\"')\n .replace(/&apos;/g, \"'\")\n .replace(/&amp;/g, '&')\n}\n\n/** Split a systemd command line into words, undoing `systemdQuote`. */\nfunction systemdWords(line: string): string[] {\n const words: string[] = []\n let i = 0\n while (i < line.length) {\n while (i < line.length && /\\s/.test(line[i]!)) i += 1\n if (i >= line.length) break\n let word = ''\n if (line[i] === '\"') {\n i += 1\n while (i < line.length && line[i] !== '\"') {\n if (line[i] === '\\\\' && i + 1 < line.length) {\n const c = line[i + 1]!\n word += c === 'n' ? '\\n' : c === 'r' ? '\\r' : c === 't' ? '\\t' : c\n i += 2\n } else {\n word += line[i]\n i += 1\n }\n }\n i += 1 // closing quote\n } else {\n while (i < line.length && !/\\s/.test(line[i]!)) {\n word += line[i]\n i += 1\n }\n }\n words.push(word.replace(/\\$\\$/g, '$').replace(/%%/g, '%'))\n }\n return words\n}\n\n/**\n * The identity home a service definition serves: the `--home` argument of\n * its command. `plist` — a launchd plist (ProgramArguments); `launchctl` —\n * `launchctl print` or `launchctl list <label>` output (one argument per\n * line); `systemd` — a unit file (ExecStart). Null when there is none.\n */\nexport function parseServiceHome(text: string, format: 'plist' | 'launchctl' | 'systemd'): string | null {\n if (format === 'plist') {\n const array = /<key>ProgramArguments<\\/key>\\s*<array>([\\s\\S]*?)<\\/array>/.exec(text)?.[1]\n if (array === undefined) return null\n const args = [...array.matchAll(/<string>([\\s\\S]*?)<\\/string>/g)].map((m) => xmlUnescape(m[1] ?? ''))\n return homeFromArgs(args)\n }\n if (format === 'launchctl') {\n const args = text\n .split(/\\r?\\n/)\n .map((l) => l.trim().replace(/;$/, '').replace(/^\"(.*)\"$/, '$1'))\n return homeFromArgs(args)\n }\n const exec = text.split(/\\r?\\n/).find((l) => l.startsWith('ExecStart='))\n return exec === undefined ? null : homeFromArgs(systemdWords(exec.slice('ExecStart='.length)))\n}\n\nfunction canonicalPath(p: string): string {\n const resolved = path.resolve(p)\n try {\n return fs.realpathSync(resolved)\n } catch {\n return resolved\n }\n}\n\nfunction sameHome(a: string, b: string): boolean {\n const x = canonicalPath(a)\n const y = canonicalPath(b)\n return process.platform === 'win32' ? x.toLowerCase() === y.toLowerCase() : x === y\n}\n\n/** One place a service under a label is defined: the file at its path, or the job the manager has loaded. */\ninterface ServiceSighting {\n /** Human description, for messages. */\n where: string\n /** The `--home` it serves; null when it could not be read. */\n home: string | null\n /** A loaded job (as opposed to a file on disk). */\n loaded: boolean\n}\n\nfunction launchdSightings(label: string): ServiceSighting[] {\n const out: ServiceSighting[] = []\n const plistPath = launchdPlistPath(label)\n if (fs.existsSync(plistPath)) {\n let text = ''\n try {\n text = fs.readFileSync(plistPath, 'utf-8')\n } catch {\n /* unreadable: treated as unknown below */\n }\n out.push({ where: plistPath, home: parseServiceHome(text, 'plist'), loaded: false })\n }\n if (!registrationSkipped()) {\n const fullLabel = launchdLabel(label)\n const uid = typeof process.getuid === 'function' ? process.getuid() : os.userInfo().uid\n const printed = run('launchctl', ['print', `gui/${uid}/${fullLabel}`])\n const listed = printed.ok ? null : run('launchctl', ['list', fullLabel])\n if (printed.ok || listed?.ok === true) {\n const text = printed.ok ? printed.out : (listed?.out ?? '')\n let home = parseServiceHome(text, 'launchctl')\n if (home === null) {\n // Fall back to the plist the job was loaded from (`path = …`).\n const loadedFrom = /^\\s*path = (.+)$/m.exec(text)?.[1]?.trim()\n if (loadedFrom !== undefined) {\n try {\n home = parseServiceHome(fs.readFileSync(loadedFrom, 'utf-8'), 'plist')\n } catch {\n /* stays unknown */\n }\n }\n }\n out.push({ where: `the loaded launchd job ${fullLabel}`, home, loaded: true })\n }\n }\n return out\n}\n\nfunction systemdSightings(label: string): ServiceSighting[] {\n const out: ServiceSighting[] = []\n const unitPath = systemdUnitPath(label)\n if (fs.existsSync(unitPath)) {\n let text = ''\n try {\n text = fs.readFileSync(unitPath, 'utf-8')\n } catch {\n /* unknown */\n }\n out.push({ where: unitPath, home: parseServiceHome(text, 'systemd'), loaded: false })\n }\n if (!registrationSkipped()) {\n const shown = run('systemctl', ['--user', 'show', label, '-p', 'LoadState', '-p', 'FragmentPath'])\n if (shown.ok) {\n const props = new Map(\n shown.out.split(/\\r?\\n/).map((l) => {\n const eq = l.indexOf('=')\n return [eq < 0 ? l : l.slice(0, eq), eq < 0 ? '' : l.slice(eq + 1)] as const\n }),\n )\n if (props.get('LoadState') === 'loaded') {\n const fragment = props.get('FragmentPath') ?? ''\n let home: string | null = null\n try {\n if (fragment) home = parseServiceHome(fs.readFileSync(fragment, 'utf-8'), 'systemd')\n } catch {\n /* unknown */\n }\n out.push({ where: `the loaded systemd unit ${label}${fragment ? ` (${fragment})` : ''}`, home, loaded: true })\n }\n }\n }\n return out\n}\n\nfunction sightings(label: string): ServiceSighting[] {\n if (winMode()) return [] // see assertServesHome\n if (serviceHostOs() === 'linux') return systemdSightings(label)\n if (serviceHostOs() === 'darwin') return launchdSightings(label)\n return []\n}\n\n/**\n * Refuse to `action` (stop, replace, remove) the service under `label` unless\n * everything defined under it serves `home`. A loaded job whose home cannot be\n * read is refused too: under the plain label that is exactly the job another\n * config (another HOME, the default config dir) installed. A definition FILE\n * at this label's own path with no readable `--home` is not ours to protect —\n * install overwrites it and uninstall removes it.\n *\n * Windows Startup launchers are keyed by HOME and label together, so the\n * files under one label can only belong to one identity home; no read there.\n */\nfunction assertServesHome(label: string, home: string, action: string): void {\n for (const s of sightings(label)) {\n if (s.home === null) {\n if (!s.loaded) continue\n throw new Error(\n `refusing to ${action} ${s.where}: it is loaded under this config's label but which identity home it serves could not be read. If it is yours, remove it by hand (launchctl remove / systemctl --user disable --now) and retry.`,\n )\n }\n if (!sameHome(s.home, home)) {\n throw new Error(\n `refusing to ${action} ${s.where}: it serves ${s.home}, not this config's identity home ${home}. It belongs to another configuration of this integration (another HOME or config directory) — run the command from that configuration. In a sandbox, set AGENTCHAT_SERVICE_DRY_RUN=1.`,\n )\n }\n }\n}\n\n/** Does anything under `label` serve `home`? (For retiring a superseded label.) */\nfunction servesHome(label: string, home: string): boolean {\n return sightings(label).some((s) => s.home !== null && sameHome(s.home, home))\n}\n\n// ─── systemd (Linux) ─────────────────────────────────────────────────────────\n\nfunction systemdUnitPath(label: string): string {\n return path.join(os.homedir(), '.config', 'systemd', 'user', `${label}.service`)\n}\n\n/** Quote one systemd command/environment word, including specifier escaping. */\nexport function systemdQuote(value: string): string {\n return (\n '\"' +\n value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\t/g, '\\\\t')\n .replace(/\"/g, '\\\\\"')\n // In a JS replacement string `$$` emits one literal dollar, so four\n // dollars are required to produce systemd's literal-dollar escape `$$`.\n .replace(/\\$/g, '$$$$')\n .replace(/%/g, '%%') +\n '\"'\n )\n}\n\nexport function systemdUnit(p: Plan): string {\n const envLines = Object.entries(p.env)\n .map(([k, v]) => `Environment=${systemdQuote(`${k}=${v}`)}`)\n .join('\\n')\n return [\n '[Unit]',\n `Description=AgentChat always-on daemon (${p.label})`,\n 'After=network-online.target',\n 'Wants=network-online.target',\n '',\n '[Service]',\n 'Type=simple',\n `ExecStart=${systemdQuote(p.node)} ${systemdQuote(p.bin)} --home ${systemdQuote(p.home)}`,\n ...(envLines ? [envLines] : []),\n 'Restart=on-failure',\n 'RestartSec=5',\n '',\n '[Install]',\n 'WantedBy=default.target',\n '',\n ].join('\\n')\n}\n\nfunction installSystemd(p: Plan): void {\n assertServesHome(p.label, p.home, 'replace')\n const unitPath = systemdUnitPath(p.label)\n fs.mkdirSync(path.dirname(unitPath), { recursive: true })\n atomicWriteFile(unitPath, systemdUnit(p), 0o600)\n log.info(`wrote ${unitPath}`)\n if (registrationSkipped()) return\n run('systemctl', ['--user', 'daemon-reload'])\n // enable-linger keeps user services running with no active login (VPS).\n const linger = run('loginctl', ['enable-linger', os.userInfo().username])\n if (!linger.ok) {\n log.warn(`could not enable-linger (service won't survive logout until you run: sudo loginctl enable-linger ${os.userInfo().username})`)\n }\n const enabled = run('systemctl', ['--user', 'enable', p.label])\n if (!enabled.ok) throw new Error(`systemctl enable failed: ${enabled.out}`)\n // `enable --now` leaves an already-running unit on the old bundle, so an\n // upgrade silently kept the previous daemon until the next boot. `restart`\n // starts a stopped unit and restarts a running one: either way the unit\n // runs the bundle this install just wrote.\n const started = run('systemctl', ['--user', 'restart', p.label])\n if (!started.ok) throw new Error(`systemctl restart failed: ${started.out}`)\n log.info(`service ${p.label} enabled + (re)started`)\n}\n\nfunction uninstallSystemd(label: string, home: string): void {\n assertServesHome(label, home, 'remove')\n if (!registrationSkipped()) {\n const disabled = run('systemctl', ['--user', 'disable', '--now', label])\n if (!disabled.ok) {\n const active = run('systemctl', ['--user', 'is-active', label])\n const state = (active.out.split(/\\r?\\n/, 1)[0] ?? '').trim().toLowerCase()\n // systemctl intentionally exits non-zero for these stopped/not-present\n // states. Anything else is ambiguous, so preserve the unit and daemon\n // bundle rather than stranding a loaded restart policy.\n if (!['inactive', 'failed', 'unknown'].includes(state)) {\n throw new Error(\n `could not stop systemd service ${label}: ${disabled.out || active.out || 'unknown error'}`,\n )\n }\n }\n }\n const unitPath = systemdUnitPath(label)\n if (fs.existsSync(unitPath)) fs.rmSync(unitPath)\n if (!registrationSkipped()) {\n const reload = run('systemctl', ['--user', 'daemon-reload'])\n if (!reload.ok) log.warn(`systemctl daemon-reload failed after uninstall: ${reload.out}`)\n }\n log.info(`service ${label} removed`)\n}\n\nfunction statusSystemd(label: string, home: string): string {\n if (registrationSkipped()) return dryRunStatus(`systemd ${label}`, systemdUnitPath(label))\n const active = run('systemctl', ['--user', 'is-active', label]).out || 'unknown'\n const enabled = run('systemctl', ['--user', 'is-enabled', label]).out || 'unknown'\n return `systemd ${label}: ${active} (${enabled})${foreignNote(label, home)}`\n}\n\n/** Status under AGENTCHAT_SERVICE_DRY_RUN: the service manager is not consulted at all. */\nfunction dryRunStatus(name: string, definitionPath: string): string {\n return `${name}: not queried (AGENTCHAT_SERVICE_DRY_RUN) — definition ${fs.existsSync(definitionPath) ? `written at ${definitionPath}` : 'not written'}`\n}\n\n/** `, but it serves <other home> …` when the loaded job under this label is another config's. */\nfunction foreignNote(label: string, home: string): string {\n const loaded = sightings(label).find((s) => s.loaded)\n if (loaded === undefined || loaded.home === null || sameHome(loaded.home, home)) return ''\n return ` — but it serves ${loaded.home}, not this config (${home})`\n}\n\n// ─── launchd (macOS) ─────────────────────────────────────────────────────────\n\nfunction launchdPlistPath(label: string): string {\n return path.join(os.homedir(), 'Library', 'LaunchAgents', `${launchdLabel(label)}.plist`)\n}\nconst launchdLabel = (label: string): string => `me.agentchat.${label}`\n\nexport function xmlEscape(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;')\n}\n\nexport function launchdPlist(p: Plan): string {\n const args = [p.node, p.bin, '--home', p.home]\n const argXml = args.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\\n')\n const envXml = Object.entries(p.env)\n .map(([k, v]) => ` <key>${xmlEscape(k)}</key><string>${xmlEscape(v)}</string>`)\n .join('\\n')\n const logPath = path.join(p.home, 'daemon.log')\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\"><dict>',\n ` <key>Label</key><string>${xmlEscape(launchdLabel(p.label))}</string>`,\n ' <key>ProgramArguments</key><array>',\n argXml,\n ' </array>',\n ...(envXml ? [' <key>EnvironmentVariables</key><dict>', envXml, ' </dict>'] : []),\n ' <key>RunAtLoad</key><true/>',\n ' <key>KeepAlive</key><true/>',\n // On `launchctl unload`/`stop` launchd sends SIGTERM and SIGKILLs after\n // this many seconds. The daemon uses the window to SIGTERM a headless run\n // in flight and wait up to 10 s for it (run.ts SHUTDOWN_GRACE_MS), so the\n // value is above that and below launchd's 20 s default, which would let a\n // slow stop look like a hang.\n ' <key>ExitTimeOut</key><integer>15</integer>',\n ` <key>StandardErrorPath</key><string>${xmlEscape(logPath)}</string>`,\n ` <key>StandardOutPath</key><string>${xmlEscape(logPath)}</string>`,\n '</dict></plist>',\n '',\n ].join('\\n')\n}\n\nfunction installLaunchd(p: Plan): void {\n // `launchctl unload <plist>` below unloads by the plist's Label — whatever\n // job holds that label, whichever HOME it was installed from.\n assertServesHome(p.label, p.home, 'replace')\n const plistPath = launchdPlistPath(p.label)\n fs.mkdirSync(path.dirname(plistPath), { recursive: true })\n atomicWriteFile(plistPath, launchdPlist(p), 0o600)\n log.info(`wrote ${plistPath}`)\n if (registrationSkipped()) return\n run('launchctl', ['unload', plistPath]) // idempotent: clear a prior load\n const loaded = run('launchctl', ['load', '-w', plistPath])\n if (!loaded.ok) throw new Error(`launchctl load failed: ${loaded.out}`)\n log.info(`service ${launchdLabel(p.label)} loaded + started`)\n}\n\nfunction uninstallLaunchd(label: string, home: string): void {\n assertServesHome(label, home, 'remove')\n const plistPath = launchdPlistPath(label)\n if (!registrationSkipped()) {\n run('launchctl', ['unload', '-w', plistPath])\n let loaded = run('launchctl', ['list', launchdLabel(label)])\n if (loaded.ok) {\n // A missing/stale plist can leave a loaded job that unload-by-path\n // cannot address. Remove by label, then prove it is gone.\n run('launchctl', ['remove', launchdLabel(label)])\n loaded = run('launchctl', ['list', launchdLabel(label)])\n }\n if (loaded.ok) {\n throw new Error(`could not stop launchd service ${launchdLabel(label)}`)\n }\n if (\n loaded.out &&\n !/could not find service|not found|no such process|unknown service/i.test(loaded.out)\n ) {\n throw new Error(\n `could not verify launchd service removal for ${launchdLabel(label)}: ${loaded.out}`,\n )\n }\n }\n if (fs.existsSync(plistPath)) fs.rmSync(plistPath)\n log.info(`service ${launchdLabel(label)} removed`)\n}\n\nfunction statusLaunchd(label: string, home: string): string {\n const fullLabel = launchdLabel(label)\n if (registrationSkipped()) return dryRunStatus(`launchd ${fullLabel}`, launchdPlistPath(label))\n const uid = typeof process.getuid === 'function' ? process.getuid() : os.userInfo().uid\n const modern = run('launchctl', ['print', `gui/${uid}/${fullLabel}`])\n const loaded = modern.ok || run('launchctl', ['list', fullLabel]).ok\n return `launchd ${fullLabel}: ${loaded ? `loaded${foreignNote(label, home)}` : 'not loaded'}`\n}\n\n// ─── Windows + WSL (Startup-folder launcher, no admin) ───────────────────────\n//\n// Windows has no systemd/launchd. For \"runs whenever you're logged in\" — the\n// consumer case, no admin needed — we drop a hidden, restart-on-exit VBScript\n// into the user's Startup folder. Two hosts land here:\n// * native Windows → the .vbs runs `node <entry> --home <home>` directly.\n// * WSL2 → the daemon lives in Linux, but the WSL VM shuts down when\n// the last terminal closes, so a Linux service can't stay\n// up. Instead the launcher goes in the WINDOWS Startup\n// folder (reached from WSL via /mnt/c) and runs\n// `wsl.exe -e bash <script>`, which boots the VM at Windows\n// login and runs the daemon inside it.\n// A \"master\" copy in the user's ~/.agentchat/daemon (whatever identity home the\n// service serves — the label carries that) is the installed-marker; the copy in\n// Startup is the enabled state (disable removes it, keeps the master — same\n// toggle semantics as systemd enable/disable).\n//\n// The file mechanics + generators are unit-tested and verified on a real\n// windows-latest CI runner. The live runtime (hidden loop, WSL boot, process\n// kill) still needs a real user machine — called out in the release notes.\n\nexport function isWslFromVersion(version: string): boolean {\n return /microsoft|wsl/i.test(version)\n}\nfunction isWsl(): boolean {\n if (process.platform !== 'linux') return false\n try {\n return isWslFromVersion(fs.readFileSync('/proc/version', 'utf-8'))\n } catch {\n return false\n }\n}\ntype WinMode = 'win32' | 'wsl'\n\n/** The host as service management sees it. `wsl` is Linux under WSL2 (Windows Startup launcher, not systemd). */\nexport type ServiceHostOs = 'linux' | 'darwin' | 'win32' | 'wsl' | 'other'\nlet hostOsOverride: ServiceHostOs | null = null\n\n/**\n * Tests only: pretend to be another host so the Linux and Windows command\n * sequences can be pinned on any CI runner. Paths and the real service\n * manager are never reached: pair it with a fake command runner and\n * `AGENTCHATD_SERVICE_NO_START=1`.\n */\nexport function setServiceHostOsForTests(hostOs: ServiceHostOs | null): void {\n hostOsOverride = hostOs\n}\n\nfunction serviceHostOs(): ServiceHostOs {\n if (hostOsOverride !== null) return hostOsOverride\n if (process.platform === 'win32') return 'win32'\n if (process.platform === 'linux') return isWsl() ? 'wsl' : 'linux'\n if (process.platform === 'darwin') return 'darwin'\n return 'other'\n}\n\nfunction winMode(): WinMode | null {\n const hostOs = serviceHostOs()\n return hostOs === 'win32' || hostOs === 'wsl' ? hostOs : null\n}\n\nfunction winMasterDir(): string {\n return path.join(os.homedir(), '.agentchat', 'daemon')\n}\nfunction winStartupDir(mode: WinMode): string {\n if (mode === 'win32') {\n return path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')\n }\n // WSL: translate the Windows %APPDATA% into a /mnt/c path.\n const appdata = run('cmd.exe', ['/c', 'echo %APPDATA%']).out.split(/\\r?\\n/).pop()?.trim() ?? ''\n const base = run('wslpath', ['-u', appdata]).out.trim()\n if (!base) throw new Error('could not locate the Windows Startup folder from WSL (is /mnt/c mounted?)')\n return path.join(base, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')\n}\n\nconst vbsEscape = (s: string): string => s.replace(/\"/g, '\"\"')\nconst shQuote = (s: string): string => `'${s.replace(/'/g, `'\\\\''`)}'`\n\n/** Hidden, restart-on-exit VBScript launcher. `command` is the full command\n * line; `env` is set on the launcher process (native Windows only). */\nexport function launcherVbs(command: string, env: Record<string, string>): string {\n const envLines = Object.entries(env).map(\n ([k, v]) => `sh.Environment(\"Process\").Item(\"${vbsEscape(k)}\") = \"${vbsEscape(v)}\"`,\n )\n return (\n [\n \"' AgentChat always-on launcher — runs hidden, restarts on exit.\",\n 'Set sh = CreateObject(\"WScript.Shell\")',\n ...envLines,\n 'Do',\n ` sh.Run \"${vbsEscape(command)}\", 0, True`,\n ' WScript.Sleep 5000',\n 'Loop',\n ].join('\\r\\n') + '\\r\\n'\n )\n}\n\n/** Native-Windows launch command. */\nexport function winCommandNative(p: Plan): string {\n return `\"${p.node}\" \"${p.bin}\" --home \"${p.home}\"`\n}\n\n/** The bash script WSL runs — a login-shell env plus the daemon. */\nexport function wslScriptContent(p: Plan): string {\n const exports = Object.entries(p.env).map(([k, v]) => `export ${k}=${shQuote(v)}`)\n return (\n ['#!/bin/bash', ...exports, `exec ${shQuote(p.node)} ${shQuote(p.bin)} --home ${shQuote(p.home)}`].join(\n '\\n',\n ) + '\\n'\n )\n}\n\nfunction startDetached(cmd: string, args: string[]): void {\n // Escape hatch for tests/headless installs: write the Startup entry but don't\n // actually launch the loop now (it still starts at next login).\n if (process.env['AGENTCHATD_SERVICE_NO_START'] === '1') return\n try {\n spawnCommand(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref()\n } catch (err) {\n log.warn(`could not start the launcher now (it starts at next login): ${String(err)}`)\n }\n}\nfunction winPathFromWsl(linuxPath: string): string {\n return run('wslpath', ['-w', linuxPath]).out.trim() || linuxPath\n}\nfunction killLauncher(label: string, mode: WinMode): { ok: boolean; out: string } {\n // Best-effort: stop the running wscript launcher, matched by our .vbs name.\n const ps = `Get-CimInstance Win32_Process -Filter \"Name='wscript.exe'\" | Where-Object { $_.CommandLine -like '*${label}.vbs*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }`\n return run(mode === 'win32' ? 'powershell' : 'powershell.exe', ['-NoProfile', '-Command', ps])\n}\n\n/**\n * The pid in the daemon's leader lock, or null: the daemon the Startup\n * launcher is keeping alive right now. The lock's shared parser (its first\n * line is the bare pid, in the lease format and in a lock from before it),\n * and only while its holder is really there (`holderLive`): a lock left by a\n * daemon that died — its pid perhaps reused by an unrelated process — names\n * nothing to stop.\n */\nexport function lockedDaemonPid(home: string): number | null {\n const file = path.join(home, DAEMON_LOCK_FILE)\n try {\n const holder = parseLease(fs.readFileSync(file, 'utf-8'))\n if (holder === null || !Number.isInteger(holder.pid) || holder.pid <= 0) return null\n return holderLive(holder, { mtimeMs: fs.statSync(file).mtimeMs }) ? holder.pid : null\n } catch {\n return null\n }\n}\n\n/**\n * Before a new launcher starts: stop the one already running and the daemon\n * it spawned. The Startup launcher restarts its daemon on exit, so a second\n * launcher started beside it would start a second daemon that loses the\n * leader lock, exits, and is restarted every five seconds — forever, on the\n * old bundle. Stop the launcher first (by its .vbs name), then the daemon by\n * the pid in its leader lock, so the new launcher's daemon takes the lock.\n * Best effort: a daemon that is not running leaves nothing to stop.\n */\nfunction stopRunningWindowsDaemon(label: string, mode: WinMode, home: string): void {\n const killed = killLauncher(label, mode)\n if (!killed.ok) log.warn(`could not stop a running ${label} launcher (${killed.out || 'unknown error'}) — continuing`)\n const pid = lockedDaemonPid(home)\n if (pid === null) return\n const stopped = mode === 'win32' ? run('taskkill', ['/PID', String(pid), '/T', '/F']) : run('kill', ['-TERM', String(pid)])\n if (stopped.ok) log.info(`stopped the running daemon (pid ${pid}) so the new bundle starts`)\n else log.debug(`no running daemon at pid ${pid} to stop (${stopped.out || 'already gone'})`)\n}\n\nfunction installWindows(p: Plan, mode: WinMode): void {\n const master = winMasterDir()\n fs.mkdirSync(master, { recursive: true })\n const masterVbs = path.join(master, `${p.label}.vbs`)\n if (mode === 'win32') {\n atomicWriteFile(masterVbs, launcherVbs(winCommandNative(p), p.env), 0o600)\n } else {\n const scriptPath = path.join(master, `${p.label}.sh`)\n atomicWriteFile(scriptPath, wslScriptContent(p), 0o700)\n const distro = serviceValue('WSL distro', process.env['WSL_DISTRO_NAME'] ?? '')\n if (!distro) throw new Error('WSL_DISTRO_NAME is not set — cannot target the right WSL distro')\n atomicWriteFile(\n masterVbs,\n launcherVbs(`wsl.exe -d \"${distro}\" -e bash \"${scriptPath}\"`, {}),\n 0o600,\n )\n }\n log.info(`wrote ${masterVbs}`)\n enableWindows(p.label, mode, p.home)\n log.info(`service ${p.label} installed (starts at login)`)\n}\nfunction enableWindows(label: string, mode: WinMode, home: string): void {\n const masterVbs = path.join(winMasterDir(), `${label}.vbs`)\n if (!fs.existsSync(masterVbs)) throw new Error(`no ${label} daemon installed — run install first`)\n const startup = winStartupDir(mode)\n fs.mkdirSync(startup, { recursive: true })\n const startupVbs = path.join(startup, `${label}.vbs`)\n fs.copyFileSync(masterVbs, startupVbs)\n if (registrationSkipped()) return\n stopRunningWindowsDaemon(label, mode, home)\n if (mode === 'win32') startDetached('wscript.exe', [startupVbs])\n else startDetached('cmd.exe', ['/c', 'start', '', '/b', 'wscript.exe', winPathFromWsl(startupVbs)])\n}\nfunction disableWindows(label: string, mode: WinMode): void {\n const startupVbs = path.join(winStartupDir(mode), `${label}.vbs`)\n if (fs.existsSync(startupVbs)) fs.rmSync(startupVbs)\n if (!registrationSkipped()) {\n const killed = killLauncher(label, mode)\n if (!killed.ok) {\n throw new Error(`could not stop Windows launcher ${label}: ${killed.out || 'unknown error'}`)\n }\n }\n}\nfunction uninstallWindows(label: string, mode: WinMode): void {\n // If stopping cannot be verified, preserve the master scripts and durable\n // daemon. The caller can retry without leaving a hidden restart loop pointed\n // at a deleted executable.\n disableWindows(label, mode)\n for (const f of [`${label}.vbs`, `${label}.sh`]) {\n const m = path.join(winMasterDir(), f)\n if (fs.existsSync(m)) fs.rmSync(m)\n }\n}\nfunction statusWindows(label: string, mode: WinMode): string {\n const installed = fs.existsSync(path.join(winMasterDir(), `${label}.vbs`))\n let enabled = false\n try {\n enabled = fs.existsSync(path.join(winStartupDir(mode), `${label}.vbs`))\n } catch {\n /* startup dir unresolved */\n }\n const host = mode === 'wsl' ? 'wsl' : 'windows'\n return `${host} ${label}: ${installed ? (enabled ? 'enabled' : 'installed (disabled)') : 'not installed'}`\n}\n\n// ─── platform dispatch ───────────────────────────────────────────────────────\n\n/**\n * Remove each superseded service that serves this home (a relocated home\n * installed under the plain label before labels were per home); leave one\n * serving another home alone.\n */\nfunction retireSuperseded(opts: ServiceRef, label: string): void {\n for (const raw of opts.supersedes ?? []) {\n const old = serviceLabel(raw)\n if (old === label || winMode() || !servesHome(old, opts.home)) continue\n log.info(`retiring the service ${old}: this identity home is now served by ${label}`)\n if (serviceHostOs() === 'linux') uninstallSystemd(old, opts.home)\n else if (serviceHostOs() === 'darwin') uninstallLaunchd(old, opts.home)\n }\n}\n\nexport function installService(opts: ServiceOpts): void {\n const p = plan(opts)\n if (!p.bin) throw new Error('no daemon entrypoint given (ServiceOpts.entry)')\n retireSuperseded(opts, p.label)\n const wm = winMode()\n if (wm) return installWindows(p, wm)\n if (serviceHostOs() === 'linux') return installSystemd(p) // native Linux (not WSL)\n if (serviceHostOs() === 'darwin') return installLaunchd(p)\n throw new Error(`service install is not supported on ${process.platform} — run \\`agentchatd start\\` under your own supervisor`)\n}\n\nexport function uninstallService(opts: ServiceRef): void {\n const label = serviceLabel(opts.label)\n const home = path.resolve(opts.home)\n const wm = winMode()\n if (wm) return uninstallWindows(label, wm)\n if (serviceHostOs() === 'linux') {\n uninstallSystemd(label, home)\n retireSuperseded({ ...opts, home }, label)\n return\n }\n if (serviceHostOs() === 'darwin') {\n uninstallLaunchd(label, home)\n retireSuperseded({ ...opts, home }, label)\n return\n }\n throw new Error(`service uninstall is not supported on ${process.platform}`)\n}\n\nexport function serviceStatus(opts: ServiceRef): string {\n const label = serviceLabel(opts.label)\n const home = path.resolve(opts.home)\n const wm = winMode()\n if (wm) return statusWindows(label, wm)\n if (serviceHostOs() === 'linux') return statusSystemd(label, home)\n if (serviceHostOs() === 'darwin') return statusLaunchd(label, home)\n return `service management not supported on ${process.platform}`\n}\n\n/** Pure on-disk check used by integration self-healing and doctor. */\nexport function serviceDefinitionCurrent(opts: ServiceOpts): boolean {\n try {\n const p = plan(opts)\n const wm = winMode()\n if (wm === 'win32') {\n const file = path.join(winMasterDir(), `${p.label}.vbs`)\n return fs.existsSync(file) && fs.readFileSync(file, 'utf-8') === launcherVbs(winCommandNative(p), p.env)\n }\n if (wm === 'wsl') {\n const script = path.join(winMasterDir(), `${p.label}.sh`)\n const vbs = path.join(winMasterDir(), `${p.label}.vbs`)\n const distro = serviceValue('WSL distro', process.env['WSL_DISTRO_NAME'] ?? '')\n if (!distro) return false\n return (\n fs.existsSync(script) &&\n fs.existsSync(vbs) &&\n fs.readFileSync(script, 'utf-8') === wslScriptContent(p) &&\n fs.readFileSync(vbs, 'utf-8') ===\n launcherVbs(`wsl.exe -d \"${distro}\" -e bash \"${script}\"`, {})\n )\n }\n if (serviceHostOs() === 'linux') {\n const file = systemdUnitPath(p.label)\n return fs.existsSync(file) && fs.readFileSync(file, 'utf-8') === systemdUnit(p)\n }\n if (serviceHostOs() === 'darwin') {\n const file = launchdPlistPath(p.label)\n return fs.existsSync(file) && fs.readFileSync(file, 'utf-8') === launchdPlist(p)\n }\n return false\n } catch {\n return false\n }\n}\n\n// ─── enable / disable (the away-replies opt-out) ─────────────────────────────\n//\n// Toggle the service's run-state WITHOUT uninstalling — so a user who wants\n// \"reply only while I'm in a session\" flips the daemon off, and back on later,\n// with one word. The unit/plist file stays on disk either way, so re-enabling\n// is instant. `install` already leaves it enabled (always-on by default);\n// these just turn that on and off after the fact.\n\nfunction unitInstalled(label: string): boolean {\n if (winMode()) return fs.existsSync(path.join(winMasterDir(), `${label}.vbs`))\n if (serviceHostOs() === 'linux') return fs.existsSync(systemdUnitPath(label))\n if (serviceHostOs() === 'darwin') return fs.existsSync(launchdPlistPath(label))\n return false\n}\n\nexport function serviceInstalled(opts: ServiceRef): boolean {\n return unitInstalled(serviceLabel(opts.label))\n}\n\nexport function disableService(opts: ServiceOpts): void {\n const label = serviceLabel(opts.label)\n if (!unitInstalled(label)) {\n throw new Error(`no ${opts.label} daemon installed — nothing to disable (run install first)`)\n }\n const wm = winMode()\n if (wm) {\n disableWindows(label, wm) // drop the Startup copy, keep the master\n } else if (serviceHostOs() === 'linux') {\n assertServesHome(label, path.resolve(opts.home), 'stop')\n // Stops it AND removes the start-on-boot link; the unit file stays.\n if (!registrationSkipped()) {\n const disabled = run('systemctl', ['--user', 'disable', '--now', label])\n if (!disabled.ok) throw new Error(`could not disable ${label}: ${disabled.out}`)\n }\n } else if (serviceHostOs() === 'darwin') {\n assertServesHome(label, path.resolve(opts.home), 'stop')\n if (!registrationSkipped()) {\n const disabled = run('launchctl', ['unload', launchdPlistPath(label)])\n if (!disabled.ok) throw new Error(`could not disable ${label}: ${disabled.out}`)\n }\n } else {\n throw new Error(`not supported on ${process.platform}`)\n }\n log.info(`daemon ${label} disabled — session-only until you re-enable`)\n}\n\nexport function enableService(opts: ServiceOpts): void {\n const label = serviceLabel(opts.label)\n if (!unitInstalled(label)) {\n throw new Error(`no ${opts.label} daemon installed — run install first`)\n }\n const wm = winMode()\n if (wm) {\n enableWindows(label, wm, path.resolve(opts.home)) // copy the master back into Startup + start now\n } else if (serviceHostOs() === 'linux') {\n if (!registrationSkipped()) {\n const enabled = run('systemctl', ['--user', 'enable', '--now', label])\n if (!enabled.ok) throw new Error(`could not enable ${label}: ${enabled.out}`)\n }\n } else if (serviceHostOs() === 'darwin') {\n if (!registrationSkipped()) {\n const enabled = run('launchctl', ['load', '-w', launchdPlistPath(label)])\n if (!enabled.ok) throw new Error(`could not enable ${label}: ${enabled.out}`)\n }\n } else {\n throw new Error(`not supported on ${process.platform}`)\n }\n log.info(`daemon ${label} enabled — always-on while this machine is up`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,4BAAkD;AAsB3D,eAAsB,YAAY,QAA0C;AAC1E,QAAM,OAAO,MAAM,OAAO,MAAM,KAAK,EAAE,OAAO,qBAAqB,CAAC;AACpE,SAAO;AAAA,IACL,SAAS,MAAM,QAAQ,KAAK,aAAa,IAAI,KAAK,cAAc,SAAS;AAAA,IACzE,UAAU,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW;A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]}
1
+ {"version":3,"sources":["../src/integration/tray.ts","../src/identity/state.ts","../src/integration/run-context.ts","../src/identity/commands.ts","../src/identity/host-profile.ts","../src/identity/telemetry.ts","../src/daemon/service.ts"],"sourcesContent":["import { INBOX_TRAY_MAX_LIMIT, type AgentChatClient } from 'agentchatme'\n\n// ─── Counts on the tray, never cards ────────────────────────────────────────\n//\n// One read through the SDK's `client.inbox.tray`, counted: card contents\n// (the previews) are never read, kept or logged. Looking at the tray marks\n// nothing delivered or read; delivered is the socket's ack on receipt, read is\n// the agent's verdict inside its run. (Whether a wake deserves a run is the\n// kit's receive loop: it reads the tray before every run.)\n\nexport type TrayClient = Pick<AgentChatClient, 'inbox'>\n\nexport interface TraySummary {\n /** Conversations with something waiting (cards on the tray). */\n waiting: number\n /** Conversations the agent deferred and that are hidden until their time. */\n deferred: number\n /** More conversations are waiting than one tray shows. */\n truncated: boolean\n}\n\n/** How many conversations are waiting, for `status`. One tray page, counted. */\nexport async function traySummary(client: TrayClient): Promise<TraySummary> {\n const tray = await client.inbox.tray({ limit: INBOX_TRAY_MAX_LIMIT })\n return {\n waiting: Array.isArray(tray.conversations) ? tray.conversations.length : 0,\n deferred: typeof tray.deferred === 'number' ? tray.deferred : 0,\n truncated: tray.truncated === true,\n }\n}\n","import { z } from 'zod'\nimport { atomicWriteFile, readJsonFile } from '../util/fsutil.js'\nimport { statePath } from './credentials.js'\n\n// ─── Local identity state ───────────────────────────────────────────────────\n//\n// One fact survives here: whether the user said \"not now\" to setting up a\n// handle. It lives in the CALLER's identity home — passed in, never resolved\n// here, so one integration's state can never land in another agent's directory.\n//\n// Earlier releases kept per-session hook state (continuation caps, ack\n// cursors) in this same file. Those keys are ignored on read and dropped on the\n// next write; a file from an older release needs no migration.\n\nconst StateSchema = z.object({\n // Set when the user has said \"not now\" to setting up a handle. PERMANENT\n // until they change their mind, because the prompt that needs suppressing\n // lives in the always-loaded instruction file and would otherwise be re-read\n // — and re-acted on — every single session.\n offer_declined_at: z.string().optional(),\n})\n\nexport type IdentityState = z.infer<typeof StateSchema>\n\nexport function readState(home: string): IdentityState {\n const raw = readJsonFile<unknown>(statePath(home))\n if (raw !== null) {\n const parsed = StateSchema.safeParse(raw)\n if (parsed.success) return parsed.data\n }\n return {}\n}\n\nexport function writeState(home: string, state: IdentityState): void {\n atomicWriteFile(statePath(home), JSON.stringify(state, null, 2) + '\\n', 0o600)\n}\n\n/**\n * The user said \"not now\".\n *\n * A prompt written into the always-loaded instruction file is static text the\n * agent re-reads every session, with no memory that it was already declined.\n * So the decline is recorded here, and the instruction file rewritten to stop\n * asking.\n */\nexport function recordOfferDeclined(home: string, now: Date = new Date()): void {\n const state = readState(home)\n state.offer_declined_at = now.toISOString()\n writeState(home, state)\n}\n\nexport function offerDeclined(home: string): boolean {\n return readState(home).offer_declined_at !== undefined\n}\n\n/** Cleared when an identity is established, so a later logout asks again. */\nexport function clearOfferDeclined(home: string): void {\n const state = readState(home)\n delete state.offer_declined_at\n writeState(home, state)\n}\n","import type { RunRequest } from './runner.js'\n\n// ─── A run's context, as environment variables ──────────────────────────────\n//\n// A runner whose run is a command the owner configured (the `agentchat\n// listen --run \"<command>\"` listener) tells that command what the run is for\n// through its environment, never its argv: names and ids only, never content.\n// One spelling for every such runner.\n//\n// AGENTCHAT_WAKE_KIND `conversation` | `invite` | `wake` (`RunKind`)\n// AGENTCHAT_RUN_ID unique per run\n// AGENTCHAT_CONVERSATION_ID a `conversation` run: the one conversation it is\n// for. Absent on `invite` and `wake` runs.\n\nexport const RUN_CONTEXT_ENV = {\n wakeKind: 'AGENTCHAT_WAKE_KIND',\n runId: 'AGENTCHAT_RUN_ID',\n conversationId: 'AGENTCHAT_CONVERSATION_ID',\n} as const\n\n/** `env` without `name` in any case (Windows variable names are case-insensitive). */\nfunction without(env: NodeJS.ProcessEnv, name: string): void {\n for (const key of Object.keys(env)) if (key.toUpperCase() === name) delete env[key]\n}\n\n/**\n * A copy of `env` with the run's context set (`RUN_CONTEXT_ENV`). A value the\n * caller's own environment carries is replaced, and removed where the run has\n * none: an inherited `AGENTCHAT_CONVERSATION_ID` would name a conversation the\n * run is not for. Pure.\n */\nexport function runContextEnv(env: NodeJS.ProcessEnv, request: Pick<RunRequest, 'kind' | 'runId' | 'conversationId'>): NodeJS.ProcessEnv {\n const out: NodeJS.ProcessEnv = { ...env }\n for (const name of Object.values(RUN_CONTEXT_ENV)) without(out, name)\n out[RUN_CONTEXT_ENV.wakeKind] = request.kind\n out[RUN_CONTEXT_ENV.runId] = request.runId\n if (request.kind === 'conversation' && request.conversationId !== undefined && request.conversationId.length > 0) {\n out[RUN_CONTEXT_ENV.conversationId] = request.conversationId\n }\n return out\n}\n","import * as fs from 'node:fs'\nimport * as readline from 'node:readline'\nimport { AgentChatClient, integration as kit, type SignupFlow, type Texts } from 'agentchatme'\nimport {\n DEFAULT_API_BASE,\n credentialsPath,\n envKeyConflict,\n readCredentials,\n resolveIdentity,\n writeCredentials,\n clearCredentials,\n readPending,\n writePending,\n clearPending,\n ensureInstallId,\n rememberHost,\n type PendingSignup,\n} from './credentials.js'\nimport { clearOfferDeclined } from './state.js'\nimport { placeAnchorAt, removeAnchorAt, hasAnchorAt } from '../anchor/block.js'\nimport { describeIdentityBlock, identityBlockState, type AnchorLoadNote, type IdentityBlockState } from '../anchor/follow.js'\nimport { traySummary } from '../integration/tray.js'\nimport { loadTexts, readCachedTexts } from '../integration/texts.js'\nimport { describeListenerStopped, reportListenerStopped } from '../integration/listener-report.js'\nimport { identityLineOf } from '../skill/identity-line.js'\nimport {\n anchorLabelOf,\n placementReportOf,\n type DoctorCheck,\n type HostProfile,\n type ListenerEnsure,\n type PlacementProblem,\n type PlacementReport,\n type StatusContext,\n type Verdict,\n} from './host-profile.js'\nimport { alwaysOnOptedOut } from '../daemon/health.js'\nimport {\n codeCommandOf,\n codeMayWork,\n daemonPidOf,\n formatSetupVerdict,\n listenerReasonKindOf,\n reachabilityOf,\n readListener,\n resendLeftS,\n runLine,\n serviceDryRun,\n setupVerdict,\n shellValue,\n startCommandOf,\n VERIFY_STEP,\n type ListenerReading,\n type ServerView,\n type SetupInputs,\n type SetupVerdict,\n type SignupInput,\n} from './setup.js'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\nimport { sendSetupVerdict, telemetryOff, type SetupCommand, type TelemetrySender } from './telemetry.js'\nimport {\n REPEATED_FAILED_CYCLES,\n describeCouldNotProcessCounts,\n describePausedConversations,\n failedCyclesInARow,\n formatIntegrationStatus,\n integrationStatusFresh,\n integrationStatusStaleFor,\n readIntegrationStatus,\n repeatedFailedRuns,\n runtimeCheckFailingNow,\n} from '../integration/status.js'\n\n// ─── Identity commands, for exactly one agent ───────────────────────────────\n//\n// Dual-mode by design: a human runs these in a terminal and gets prompts; a\n// coding agent runs them with flags and gets deterministic, parseable output.\n//\n// Sign-up (register, recover) follows the server's answer. Every answer\n// carries a flow object and a sentence written to be shown to a person\n// (contract v1, \"Sign-up flows\"); the SDK's `integration.account` reads it\n// into the next action. These commands show the sentence as it is and add\n// the one thing the server cannot know: the command to run next, under this\n// integration's name. No code, limit, rule or wording of the server's is\n// kept here. With flags, a sign-up is one step per run: the code is\n// requested in one run and entered in the next, with the server's flow kept\n// in `pending.json` between them, so the agent can ask its user for the\n// emailed code in between. On a terminal, a command that has to ask for its\n// input anyway asks to the end (`integration.account.run`), so the person\n// types the code where they are.\n//\n// These commands are shared rather than reimplemented per host. They lived\n// in each integration once, and within a week the two copies were 94%\n// identical and had already drifted.\n//\n// Every function acts on `profile.home()` — the caller's own agent. There is no\n// host argument to get wrong, and no branch that could reach another agent's\n// files. Every time the key changes (register, login, recover) the profile's\n// `place` runs, so the hosted tool server always carries the current key.\n//\n// The identity line the anchor carries is the server's (`GET /v1/texts`,\n// fetched for this agent just before placing; the identity-home cache when\n// the server cannot be reached). No copy of it lives here. The same fetch\n// says which manual is current; `place` and `doctor --fix` bring the skill\n// file to it.\n\n/** No served texts in hand: offline and nothing cached. */\nconst NO_TEXTS: StatusContext = Object.freeze({ identityLine: null, identityLineTemplate: null, manual: null })\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** What a command hands its host from one texts response. */\nfunction contextOf(texts: Texts): StatusContext {\n return { identityLine: identityLineOf(texts), identityLineTemplate: texts.identity_line_template, manual: texts.manual }\n}\n\n/**\n * Ask one question on the TTY. Null when the input ends instead (Ctrl-D, or\n * Ctrl-C at the prompt).\n *\n * Deliberately the classic `node:readline`, not `node:readline/promises`:\n * esbuild strips the `node:` prefix from builtin imports when it bundles this\n * package, and a bare `readline/promises` is not on its builtin list.\n */\nasync function prompt(question: string): Promise<string | null> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout })\n try {\n return await new Promise<string | null>((resolve) => {\n rl.once('close', () => resolve(null))\n rl.question(question, (answer) => resolve(answer.trim()))\n })\n } finally {\n rl.close()\n }\n}\n\n/** Both streams are a terminal: a person is there to answer questions. */\nfunction interactive(): boolean {\n return process.stdin.isTTY === true && process.stdout.isTTY === true\n}\n\n/**\n * All of stdin, trimmed — for `login --api-key -`, so a key can be piped in\n * instead of typed into argv (where `ps` and shell history keep it).\n */\nasync function readAllStdin(): Promise<string> {\n const chunks: Buffer[] = []\n for await (const chunk of process.stdin) chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer))\n return Buffer.concat(chunks).toString('utf-8').trim()\n}\n\n/** An SDK error in one line: its code and the server's message. */\nfunction describeApiError(err: unknown): string {\n const e = (err ?? {}) as { code?: unknown; message?: unknown }\n const message = typeof e.message === 'string' ? e.message : String(err)\n return typeof e.code === 'string' ? `${e.code}: ${message}` : message\n}\n\n/** The HTTP status an SDK error carries (`AgentChatError.status`), or null for a transport failure. */\nfunction httpStatusOf(err: unknown): number | null {\n const status = (err as { status?: unknown } | null)?.status\n return typeof status === 'number' && Number.isFinite(status) && status > 0 ? status : null\n}\n\nfunction recoverUsage(invocation: string): string {\n return `${invocation} recover --handle <handle> --email <email>`\n}\n\n// ─── Sign-up: what the commands keep between runs, and what they print ─────\n\ntype AccountKind = kit.AccountKind\ntype StepResult = kit.AccountStepResult\n\nfunction emailInput(raw: string | undefined): string | undefined {\n const email = raw?.trim().toLowerCase()\n return email ? email : undefined\n}\n\n/** A handle as typed, with a leading `@` dropped. */\nfunction handleInput(raw: string | undefined): string | undefined {\n const handle = raw?.trim().replace(/^@/, '').toLowerCase()\n return handle ? handle : undefined\n}\n\n/**\n * One question of `integration.account.run`, asked on the terminal. Its\n * labels are the SDK's; the choices around them (\"new\", y/N) are ours.\n */\nasync function askOnTerminal(question: kit.AccountQuestion): Promise<kit.AccountAnswer> {\n if (question.field === 'new_code') {\n const answer = await prompt('Send a new code? [y/N] ')\n return answer !== null && /^y(es)?$/i.test(answer) ? { answer: 'new_code' } : { answer: 'cancel' }\n }\n const choices =\n question.handles !== undefined && question.handles.length > 0 ? ` (${question.handles.map((h) => `@${h}`).join(', ')})` : ''\n const hint = question.field === 'code' ? ' (or \"new\" for a new code)' : ''\n const answer = await prompt(`${question.label ?? question.field}${choices}${hint}: `)\n if (answer === null) return { answer: 'cancel' }\n if (question.field === 'code') return answer.toLowerCase() === 'new' ? { answer: 'new_code' } : { answer: 'value', value: answer }\n return { answer: 'value', value: (question.field === 'handle' ? handleInput(answer) : emailInput(answer)) ?? '' }\n}\n\n/**\n * For a host with no listener of its own (`ensureListener` absent): the one\n * thing a sign-in leaves. A host with one says the setup verdict instead.\n */\nconst SESSION_HINT = 'Open a new session for the hosted AgentChat tools to pick up the key.'\n\n/** How long an account command waits for the listener to connect: the daemon follows a new key within 5 s, then checks its runtime and opens the socket. */\nexport const SETUP_WAIT_MS = 30_000\nconst SETUP_POLL_MS = 500\n/** When the listener says it is connected and AgentChat does not see it yet: ask again this many times, a second apart. */\nconst REACHABILITY_RETRIES = 3\n\n/** Test seams for `createIdentityCommands`. */\nexport interface IdentityCommandOptions {\n /** How long account commands wait for the listener to connect (default `SETUP_WAIT_MS`). */\n setupWaitMs?: number\n /** How often the wait looks (default 500 ms). */\n setupPollMs?: number\n /** Whether no service manager is used, so no listener will start and nothing is waited for (default: `AGENTCHAT_SERVICE_DRY_RUN`). */\n serviceDryRun?: boolean\n /** Where setup telemetry goes (default: the network, or nowhere under AGENTCHAT_SERVICE_DRY_RUN). */\n telemetrySender?: TelemetrySender\n}\n\n/** What a host's install hands `reportSetup` (its own command, measured by it). */\nexport interface ReportSetupOptions {\n command: SetupCommand\n exitCode: number\n /** When the command started (ms since the epoch). */\n startedAt: number\n}\n\n/** How long the host's `host()` may take before the command goes on without it. */\nconst HOST_DEADLINE_MS = 3_000\n\n/** What `confirmSetup` takes from a host's install. */\nexport interface ConfirmSetupOptions {\n /** What the install's `ensureListener` did, or null when it did not run (a placement step failed). */\n ensure?: ListenerEnsure | null\n /** A placement problem that keeps runs from having the AgentChat tools. */\n tools?: PlacementProblem | null\n /** The daemon pid that held the home's lease before the install's `ensureListener` (`daemonPidOf`): after `installed`, what it wrote is not the new process's word. */\n replacedPid?: number | null\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)))\n\nexport interface RegisterOpts {\n email?: string\n handle?: string\n displayName?: string\n description?: string\n /** The code from the verification email — the completion leg. */\n code?: string\n apiBase?: string\n}\n\nexport interface RecoverOpts {\n /** The email the agent registered with. */\n email?: string\n /**\n * Which agent on that email to re-key. When omitted it defaults to this\n * agent's stored handle, then to a prompt on a TTY; without one the\n * server is asked by email alone, and names the handles to choose from\n * when the email backs several agents.\n */\n handle?: string\n /** The code from the recovery email — the completion leg. */\n code?: string\n apiBase?: string\n}\n\nexport interface DoctorOpts {\n fix?: boolean\n}\n\nexport interface IdentityCommands {\n runRegister(opts: RegisterOpts): Promise<number>\n runLogin(opts: { apiKey?: string; apiBase?: string }): Promise<number>\n runRecover(opts: RecoverOpts): Promise<number>\n runStatus(opts: { json?: boolean }): Promise<number>\n /** Async: it tells AgentChat the listener stopped (contract v1 §3.13) before the key goes. */\n runLogout(): Promise<number>\n runDoctor(opts?: DoctorOpts): Promise<number>\n /**\n * For a host's install: wait for the listener when there is an identity and\n * it was registered (`ensure`), then print the setup verdict as the last\n * line. Returns the verdict, or null when there is none to say.\n */\n confirmSetup(opts?: ConfirmSetupOptions): Promise<SetupVerdict | null>\n /**\n * For a host's install, after it knows its exit code: send setup telemetry\n * for the verdict this process said last (`confirmSetup`), if any. Never\n * prints, never throws, bounded (`TELEMETRY_TIMEOUT_MS`).\n */\n reportSetup(opts: ReportSetupOptions): Promise<void>\n}\n\n/** Build the identity command set for one coding agent. */\nexport function createIdentityCommands(profile: HostProfile, options: IdentityCommandOptions = {}): IdentityCommands {\n const invocation = (): string => profile.invocation()\n const LABEL = profile.label\n // The client this process names itself as: the profile's, with the home's\n // install id and the host runtime added once per process (`prepareClient`).\n let client: IntegrationClient = profile.client\n let prepared: Promise<void> | null = null\n const clientIdentityNow = () => clientIdentityOf(client)\n\n /**\n * Once per process, before the first request: the install id (made once\n * per home; none under AGENTCHAT_TELEMETRY=off) and the host runtime\n * (`host()`, bounded). Neither is ever a reason to fail.\n */\n function prepareClient(): Promise<void> {\n prepared ??= (async () => {\n const installId = telemetryOff() ? null : ensureInstallId(profile.home())\n let host: string | null = null\n if (profile.host !== undefined) {\n let timer: NodeJS.Timeout | undefined\n try {\n const late = new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), HOST_DEADLINE_MS)\n timer.unref?.()\n })\n host = await Promise.race([Promise.resolve(profile.host()), late])\n } catch {\n host = null\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n }\n // The daemon names the host from what a command last read (it does not run `--version` before it starts).\n if (host !== null && fs.existsSync(profile.home())) rememberHost(profile.home(), host)\n client = { ...profile.client, ...(installId !== null ? { installId } : {}), ...(host !== null ? { host } : {}) }\n })()\n return prepared\n }\n\n /** The verdict this process said last: what setup telemetry reports. */\n let said: SetupVerdict | null = null\n /** The verdict's line, and remember it was said. */\n function say(verdict: SetupVerdict): string {\n said = verdict\n return formatSetupVerdict(verdict)\n }\n\n /** Tell AgentChat what this command said, if it said a verdict (bounded, silent). */\n async function reportSetup(opts: ReportSetupOptions): Promise<void> {\n const verdict = said\n if (verdict === null) return\n said = null\n const identity = resolveIdentity(profile.home())\n await sendSetupVerdict(verdict, {\n ...opts,\n apiBase: identity?.apiBase ?? process.env['AGENTCHAT_API_BASE']?.trim() ?? DEFAULT_API_BASE,\n apiKey: identity?.apiKey ?? null,\n clientIdentity: clientIdentityNow(),\n ...(options.telemetrySender !== undefined ? { sender: options.telemetrySender } : {}),\n })\n }\n\n /** A command, measured: its client prepared first, its verdict (if any) reported last with its exit code. */\n function tracked<A extends unknown[]>(command: SetupCommand, run: (...args: A) => Promise<number>): (...args: A) => Promise<number> {\n return async (...args: A): Promise<number> => {\n const startedAt = Date.now()\n said = null\n await prepareClient()\n const code = await run(...args)\n await reportSetup({ command, exitCode: code, startedAt })\n return code\n }\n }\n\n /**\n * The refusal when an exported `AGENTCHAT_API_KEY` is not the key this\n * home holds, with what to do; null when there is no such split. Nothing\n * that acts as this agent adopts the exported key: it would quietly make\n * every command, and every placement `doctor --fix` writes, another agent\n * (found in testing). The listener of `@agentchatme/cli` refuses the\n * same split.\n */\n function envKeyRefusal(): string | null {\n const conflict = envKeyConflict(profile.home())\n if (conflict === null) return null\n return `${conflict}. Unset AGENTCHAT_API_KEY, or, to sign this home in with that key on purpose: printenv AGENTCHAT_API_KEY | ${invocation()} login --api-key -`\n }\n\n /**\n * One attempt, 5 s — for `status`, `doctor` and the texts fetch, which must\n * answer in seconds on a black-holed network (the SDK's default ramp is 4\n * attempts of up to 15 s).\n */\n const apiClient = (apiKey: string, apiBase: string): AgentChatClient =>\n new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity: clientIdentityNow(), timeoutMs: 5_000, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } })\n\n /** How the sign-up calls reach the server (never retried: a second call could send a second code). */\n const accountOptions = (apiBase: string): kit.AccountCallOptions => ({ clientIdentity: clientIdentityNow(), apiBase, timeoutMs: 15_000 })\n\n /**\n * The served texts for this agent: fetched now (one attempt, 5 s), else the\n * cached ones, else null (offline and never fetched). Fetched ONCE per\n * command: the identity line and the announced manual are handed to the\n * host's `place`, `extraStatus` and `extraDoctorChecks`, which must not\n * fetch again. The CLI never writes an identity line it did not get from\n * the server.\n */\n async function served(apiKey: string, apiBase: string): Promise<StatusContext> {\n const loaded = await loadTexts({ home: profile.home(), runtime: profile.client.runtime, client: apiClient(apiKey, apiBase), timeoutMs: 5_000 })\n return loaded === null ? NO_TEXTS : contextOf(loaded.texts)\n }\n\n /** The host's extra `status` lines (and the placement problem its checks found), with the texts already fetched. */\n async function extraStatusOf(context: StatusContext): Promise<PlacementReport> {\n if (profile.extraStatus === undefined) return { lines: [], problem: null }\n try {\n return placementReportOf(await profile.extraStatus(context))\n } catch (err) {\n return { lines: [` (host status failed: ${err instanceof Error ? err.message : String(err)})`], problem: null }\n }\n }\n\n /**\n * Place the integration for THIS agent's new key: the identity line, the\n * manual, the hosted tool server with the key. A profile without `place`\n * gets the anchor alone (the identity line in its instruction file). The\n * report carries the host's placement problem, if it named one.\n */\n async function placeIdentity(handle: string, apiKey: string, apiBase: string): Promise<PlacementReport> {\n const { identityLine, manual } = await served(apiKey, apiBase)\n if (profile.place !== undefined) {\n try {\n return placementReportOf(await profile.place(handle, apiKey, identityLine, manual))\n } catch (err) {\n return { lines: [` placement FAILED — ${String(err)}; repair with \\`${invocation()} doctor --fix\\``], problem: null }\n }\n }\n return { lines: writeOurAnchor(handle, identityLine), problem: null }\n }\n\n /** Write THIS agent's anchor. Only ever touches `profile.anchorFile()`. */\n function writeOurAnchor(handle: string, identityLine: string | null): string[] {\n if (profile.anchorFile === undefined) return []\n const file = profile.anchorFile()\n const label = anchorLabelOf(profile)\n // A host that wires itself separately must not be handed an identity block\n // before that wiring exists — it would announce a handle with nothing\n // listening. Once an anchor is already there, keep it current regardless.\n try {\n if (profile.isWired !== undefined && !profile.isWired() && !hasAnchorAt(file)) return []\n if (identityLine === null) {\n return [\n ` ${label}: identity line not written — GET /v1/texts could not be reached and nothing is cached; run \\`${invocation()} doctor --fix\\` once online`,\n ]\n }\n // Setup: this agent's block is updated (or placed), another agent's replaced\n // and said, one edited by hand (or several) left with the remedy.\n const placed = placeAnchorAt(file, { handle, identityLine, template: null, mode: 'setup', fix: `${invocation()} doctor --fix` })\n if (placed.outcome === 'hand_edited' || placed.outcome === 'several_blocks') return [` ${label}: WARNING — ${placed.detail}`]\n if (placed.outcome === 'failed') return [` ${label}: FAILED — ${placed.detail}`]\n if (placed.outcome === 'replaced_other') return [` ${label}: ${placed.detail}`]\n return [` ${label}: @${handle} → ${file}`]\n } catch (err) {\n return [` ${label}: FAILED — ${String(err)}`]\n }\n }\n\n // ─── Sign-up ──────────────────────────────────────────────────────────────\n\n /** The command that starts `kind` again, sending `input`; `blank` leaves that field for the person to fill in. */\n function startCommand(kind: AccountKind, input: SignupInput, blank?: 'email' | 'handle'): string {\n return startCommandOf(invocation(), kind, input, blank)\n }\n\n /** The command that answers a pending code: with `code`, or a placeholder of the server's `code_length`. */\n function codeCommand(kind: AccountKind, flow: SignupFlow, code?: string): string {\n return codeCommandOf(invocation(), kind, flow, code)\n }\n\n // ─── The setup verdict, and the wait for the listener ─────────────────────\n\n /** What every verdict of this host shares. */\n function verdictBase(): Pick<SetupInputs, 'invocation' | 'label' | 'version' | 'home'> {\n return { invocation: invocation(), label: LABEL, version: profile.client.version, home: profile.home() }\n }\n\n /** The host's `ensureListener`, once, never throwing; null for a host without one. The person's opt-out is checked here too, whatever the host does. */\n async function ensureListenerOnce(): Promise<ListenerEnsure | null> {\n if (profile.ensureListener === undefined) return null\n if (alwaysOnOptedOut(profile.home())) return { outcome: 'opted_out', detail: null }\n try {\n return await profile.ensureListener()\n } catch (err) {\n return { outcome: 'failed', detail: errorText(err) }\n }\n }\n\n function listenerLine(ensure: ListenerEnsure): string {\n switch (ensure.outcome) {\n case 'installed':\n return ` listener: registered${ensure.detail ? ` (${ensure.detail})` : ''}`\n case 'current':\n return ` listener: already registered${ensure.detail ? ` (${ensure.detail})` : ''}`\n case 'opted_out':\n return ` listener: off — switched off by the person you work with (\\`${invocation()} daemon install\\` turns it on)`\n case 'failed':\n return ` listener: FAILED — ${ensure.detail ?? 'no reason given'}`\n }\n }\n\n /** A failed `GET /v1/agents/me`, as the verdict reads it. */\n function serverViewOfError(err: unknown): ServerView {\n const status = httpStatusOf(err)\n const code = (err as { code?: unknown } | null)?.code\n const detail = describeApiError(err)\n if (status === 403 && code === 'SUSPENDED') return { kind: 'suspended', detail }\n if (status === 401 || status === 403) return { kind: 'refused', detail }\n return { kind: 'unreachable', detail }\n }\n\n /**\n * Whether the listener has said what it will say for this key: connected,\n * standing by, off, refused, or stopped at what only the person can fix (a\n * runtime signed out, missing or too old). Any other start failure (the\n * network, say) is retried by the daemon within seconds: waited out.\n */\n function listenerSettled(r: ListenerReading): boolean {\n const d = r.daemon\n if (d.kind === 'start_failure') return listenerReasonKindOf(d.detail) !== 'other'\n return r.optedOut || d.kind === 'ready' || d.kind === 'standby' || d.kind === 'unservable' || d.kind === 'off' || d.kind === 'blocked'\n }\n\n /**\n * Wait (bounded) for the listener to connect as `handle`: it follows a new\n * key on its own within seconds. Ends early once it has said anything for\n * this key — connected, standing by, or stopped at its runtime check.\n */\n async function waitForListener(handle: string, replacedPid: number | null): Promise<ListenerReading> {\n const home = profile.home()\n const read = (): ListenerReading => readListener(home, handle, { replacedPid })\n const budget = options.setupWaitMs ?? SETUP_WAIT_MS\n const poll = options.setupPollMs ?? SETUP_POLL_MS\n const started = Date.now()\n console.log(`Waiting up to ${Math.round(budget / 1000)} s for the listener to connect as @${handle}…`)\n let reading = read()\n while (!listenerSettled(reading) && Date.now() - started < budget) {\n await sleep(Math.min(poll, budget - (Date.now() - started)))\n reading = read()\n }\n const took = `${Math.max(1, Math.ceil((Date.now() - started) / 1000))} s`\n const kind = reading.daemon.kind\n console.log(\n kind === 'ready'\n ? ` listener: connected after ${took}`\n : kind === 'standby'\n ? ` listener: another listener on this computer serves @${handle} (after ${took})`\n : listenerSettled(reading)\n ? ` listener: not connected (after ${took})`\n : ` listener: not connected after ${Math.round(budget / 1000)} s`,\n )\n return reading\n }\n\n /**\n * After a key was saved and placed, or after install: wait for the listener\n * when this command registered it, ask the server once (its\n * `reachability`), and print the verdict as the last line. Right after a\n * sign-in the server has just accepted the key, so a failed ask then reads\n * as \"no reachability\", not as an unreachable server.\n */\n async function confirm(opts: { ensure: ListenerEnsure | null; tools: PlacementProblem | null; afterSignIn: boolean; replacedPid?: number | null }): Promise<SetupVerdict | null> {\n const home = profile.home()\n const identity = resolveIdentity(home)\n const pending = readPending(home)\n const base = { ...verdictBase(), pending, ensure: opts.ensure, tools: opts.tools, afterSignIn: opts.afterSignIn }\n if (identity === null) {\n const verdict = setupVerdict({ ...base, identity: null, server: null, listener: null })\n if (verdict !== null) console.log(say(verdict))\n return verdict\n }\n const hasListener = profile.ensureListener !== undefined\n // Nothing more this host can judge once the key works: no listener of its own, and the tools in place.\n if (!hasListener && opts.tools === null && opts.afterSignIn) return null\n const registered = opts.ensure?.outcome === 'installed' || opts.ensure?.outcome === 'current'\n const canWait = hasListener && identity.handle !== null && opts.tools === null && registered && !(options.serviceDryRun ?? serviceDryRun())\n // Registered again just now: what the process it replaced wrote is not the new one's word.\n const replacedPid = opts.ensure?.outcome === 'installed' ? (opts.replacedPid ?? null) : null\n const readOpts = { replacedPid }\n let reading: ListenerReading | null = hasListener ? (canWait ? await waitForListener(identity.handle!, replacedPid) : readListener(home, identity.handle, readOpts)) : null\n let verdict: SetupVerdict | null = null\n for (let attempt = 0; ; attempt++) {\n let server: ServerView\n try {\n const me = await apiClient(identity.apiKey, identity.apiBase).getMe()\n server = { kind: 'ok', handle: me.handle, reachability: reachabilityOf(me) }\n } catch (err) {\n server = opts.afterSignIn ? { kind: 'ok', handle: identity.handle ?? '?', reachability: null } : serverViewOfError(err)\n }\n if (hasListener && server.kind === 'ok' && server.handle !== identity.handle) reading = readListener(home, server.handle, readOpts)\n verdict = setupVerdict({ ...base, identity: { handle: identity.handle, source: identity.source }, server, listener: reading })\n // Connected a moment ago and AgentChat does not see it yet: ask again, briefly.\n if (!(canWait && verdict?.state === 'listener_starting' && reading?.daemon.kind === 'ready' && attempt < REACHABILITY_RETRIES)) break\n await sleep(1_000)\n }\n if (verdict !== null) console.log(say(verdict))\n return verdict\n }\n\n /**\n * Right after `place` in every account command that saved a key: the\n * listener, unless the tools are not in place (a listener whose runs have\n * no tools would only fail). Returns what was done and the line that says\n * it, printed with the placement lines.\n */\n async function placeListener(tools: PlacementProblem | null): Promise<{ ensure: ListenerEnsure | null; lines: string[]; replacedPid: number | null }> {\n // The daemon running now, if any: registering the service again replaces it.\n const replacedPid = daemonPidOf(profile.home())\n if (profile.ensureListener === undefined) return { ensure: null, lines: [], replacedPid }\n if (tools !== null) return { ensure: null, lines: [' listener: not registered until the AgentChat tools are in place (below)'], replacedPid }\n const ensure = await ensureListenerOnce()\n return { ensure, lines: ensure !== null ? [listenerLine(ensure)] : [], replacedPid }\n }\n\n async function confirmSetup(opts: ConfirmSetupOptions = {}): Promise<SetupVerdict | null> {\n await prepareClient()\n return confirm({ ensure: opts.ensure ?? null, tools: opts.tools ?? null, afterSignIn: false, replacedPid: opts.replacedPid ?? null })\n }\n\n /**\n * What to run next, from the action the SDK read from the server's answer\n * (`actionOf` with the step called). The server's sentence says what\n * happened; this is the one thing it cannot say: the command, under this\n * integration's name. `held` is the pending code this agent holds for the\n * same email, if any.\n */\n function nextSteps(\n kind: AccountKind,\n result: StepResult,\n called: 'start' | 'verify',\n input: SignupInput,\n code: string | undefined,\n held: PendingSignup | null,\n ): string[] {\n // A new code is sent only once the server's wait and the email's resend\n // window are over: the window as this answer states it, else what is\n // left of the one the held code's answer stated.\n const beforeNewCode = Math.max(result.flow.retry_after_s ?? 0, result.flow.resend_after_s ?? resendLeftS(held))\n // A start turned away (429) while the code already sent still works: go\n // back to that code (contract v1, \"Sign-up flows\").\n const heldCode =\n called === 'start' && result.httpStatus === 429 && held !== null && held.handle === input.handle && codeMayWork(held)\n ? [`Or enter the code already sent: \\`${codeCommand(kind, held.flow)}\\``]\n : []\n switch (result.action) {\n case 'done':\n // A connector sign-up's answer (SDK 1.10+); these commands never start one. The server's sentence is all there is to say.\n case 'connect':\n return []\n case 'ask_code':\n return [runLine(codeCommand(kind, result.flow))]\n case 'ask_param': {\n const param = result.flow.param\n const field = param === 'email' ? 'email' : param === 'handle' ? 'handle' : null\n if (field === null) return []\n const handles = field === 'handle' ? (result.handles ?? []) : []\n const choices = handles.length > 0 ? `, with one of: ${handles.map((h) => `@${h}`).join(', ')}` : ''\n return [`${runLine(startCommand(kind, input, field), beforeNewCode)}${choices}`]\n }\n case 'offer_new_code':\n return [`For a new code: ${runLine(startCommand(kind, input), beforeNewCode)}`]\n case 'wait_then_retry': {\n const again = called === 'verify' ? codeCommand(kind, result.flow, code) : startCommand(kind, input)\n return [runLine(again, result.flow.retry_after_s ?? 0), ...heldCode]\n }\n case 'stop':\n return heldCode\n // A connector sign-in's last answer (a flow started with `finish: \"connector\"`): this package never starts one, so there is nothing to run next.\n case 'connect':\n return []\n }\n }\n\n /**\n * The server's sentence (its code when it sent none), then the next\n * command: on stdout when the step did what it was asked, else on stderr.\n */\n function report(result: StepResult, lines: string[], ok: boolean): number {\n const said = result.message.length > 0 ? result.message : (result.code ?? `HTTP ${result.httpStatus}`)\n const text = [said, ...lines].join('\\n')\n if (ok) console.log(text)\n else console.error(text)\n return ok ? 0 : 1\n }\n\n /**\n * The key is the server's: save it with the handle the server returned\n * (never the one typed), place the integration for it, say where it is.\n * `message` is the server's sentence, or null when it has been shown.\n */\n async function finishSignup(kind: AccountKind, apiKey: string, handle: string, apiBase: string, message: string | null): Promise<number> {\n const home = profile.home()\n writeCredentials(home, {\n api_key: apiKey,\n handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n clearPending(home)\n // They have an identity now, so a previous \"not now\" is spent. If they\n // ever sign out, the setup offer should be free to appear again.\n clearOfferDeclined(home)\n const placed = await placeIdentity(handle, apiKey, apiBase)\n const listener = await placeListener(placed.problem)\n // A host with a listener says what is left as the setup verdict (last line); one without, the one hint.\n const hint = profile.ensureListener === undefined ? [SESSION_HINT] : []\n const lines =\n kind === 'register'\n ? [\n `API key for @${handle} stored at ${credentialsPath(home)} (never commit this file).`,\n ...placed.lines,\n ...listener.lines,\n '',\n `This handle belongs to your ${LABEL} agent. Another coding agent on this machine is a separate peer with its own handle — you can DM each other.`,\n `Other agents can DM you at @${handle}. Check \\`${invocation()} status\\` any time.`,\n ...hint,\n ]\n : [`New API key for @${handle} stored at ${credentialsPath(home)} (never commit this file).`, ...placed.lines, ...listener.lines, ...hint]\n console.log([...(message !== null && message.length > 0 ? [message] : []), ...lines].join('\\n'))\n // The key is saved: whatever the listener does next, the command did what it was asked (exit 0).\n await confirm({ ensure: listener.ensure, tools: placed.problem, afterSignIn: true, replacedPid: listener.replacedPid })\n return 0\n }\n\n /** Ask for a code: one start call. The flow is kept only when the server sent a code. */\n async function startSignup(kind: AccountKind, input: SignupInput, apiBase: string): Promise<number> {\n const home = profile.home()\n const before = readPending(home)\n const held = before !== null && before.kind === kind && before.email === input.email ? before : null\n let result: StepResult\n try {\n result =\n kind === 'register'\n ? await kit.account.start(\n 'register',\n {\n email: input.email,\n handle: input.handle ?? '',\n ...(input.display_name !== undefined ? { display_name: input.display_name } : {}),\n ...(input.description !== undefined ? { description: input.description } : {}),\n },\n accountOptions(apiBase),\n )\n : await kit.account.start(\n 'recover',\n { email: input.email, ...(input.handle !== undefined ? { handle: input.handle } : {}) },\n accountOptions(apiBase),\n )\n } catch (err) {\n console.error(`Could not reach AgentChat: ${errorText(err)}\\n${runLine(startCommand(kind, input))} again.`)\n return 1\n }\n if (result.action === 'ask_code') {\n const pending: PendingSignup = {\n kind,\n flow: result.flow,\n received_at: new Date().toISOString(),\n ...input,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n }\n writePending(home, pending)\n // The code is on its way: the verdict for this step (`code_pending`) names the command that answers it.\n const verdict = setupVerdict({ ...verdictBase(), identity: null, pending, server: null, listener: null })\n return report(result, verdict?.state === 'code_pending' ? [say(verdict)] : nextSteps(kind, result, 'start', input, undefined, held), true)\n }\n return report(result, nextSteps(kind, result, 'start', input, undefined, held), false)\n }\n\n /** Answer the pending code: one verify call, then keep, refresh or drop the flow as the answer says. */\n async function submitPendingCode(kind: AccountKind, rawCode: string, apiBase: string): Promise<number> {\n const home = profile.home()\n const code = rawCode.trim()\n const pending = readPending(home)\n const noun = kind === 'register' ? 'registration' : 'recovery'\n if (pending === null) {\n console.error(\n `No ${noun} in progress. Start with: ${kind === 'register' ? `${invocation()} register --email <email> --handle <handle>` : recoverUsage(invocation())}`,\n )\n return 1\n }\n if (pending.kind !== kind) {\n console.error(\n pending.kind === 'recover'\n ? `The pending code belongs to an account RECOVERY — complete it with: ${invocation()} recover --code ${shellValue(code)}`\n : `The pending code belongs to a REGISTRATION — complete it with: ${invocation()} register --code ${shellValue(code)}`,\n )\n return 1\n }\n if (pending.flow.next_step !== VERIFY_STEP[kind] || pending.flow.pending_id === undefined) {\n clearPending(home)\n console.error(`The saved ${noun} is not waiting for a code. Start again with: ${startCommand(kind, pending)}`)\n return 1\n }\n const base = pending.api_base ?? apiBase\n let result: StepResult\n try {\n result = await kit.account.submitCode(pending.flow, code, accountOptions(base))\n } catch (err) {\n console.error(`Could not reach AgentChat: ${errorText(err)}\\n${runLine(codeCommand(kind, pending.flow, code))} again.`)\n return 1\n }\n switch (result.action) {\n case 'done':\n return finishSignup(kind, result.apiKey!, result.handle!, base, result.message)\n case 'ask_code':\n // A wrong code, or one in the wrong form: the same pending id, asked again.\n writePending(home, { ...pending, flow: result.flow, received_at: new Date().toISOString() })\n break\n case 'offer_new_code':\n case 'ask_param':\n // The code is gone (expired, too many wrong tries, used up): only a new start can go on.\n clearPending(home)\n break\n default:\n // wait_then_retry: the code was not checked, and stays. stop: it stays\n // too, until an answer says it is gone (a 5xx after the code may have\n // created the account: never steer to a second start).\n break\n }\n return report(result, nextSteps(kind, result, 'verify', pending, code, pending), false)\n }\n\n /**\n * The whole sign-up on a terminal, for a person who left out what the\n * command needs: `integration.account.run` asks for each field the server\n * names, the code, and whether to send a new one; shows every server\n * sentence; and sits out the server's short waits. Nothing is kept between\n * runs: an interrupted conversation starts again.\n */\n async function converse(kind: AccountKind, input: Partial<SignupInput>, apiBase: string): Promise<number> {\n let outcome: kit.AccountRunResult\n try {\n outcome = await kit.account.run({\n kind,\n input,\n ...accountOptions(apiBase),\n show: (message) => console.log(message),\n ask: askOnTerminal,\n })\n } catch (err) {\n console.error(`Could not reach AgentChat: ${errorText(err)}`)\n return 1\n }\n if (outcome.outcome === 'done') return finishSignup(kind, outcome.apiKey, outcome.handle, apiBase, null)\n if (outcome.outcome === 'cancelled') console.error('Cancelled.')\n return 1\n }\n\n async function runRegister(opts: RegisterOpts): Promise<number> {\n const home = profile.home()\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n\n if (opts.code !== undefined) return submitPendingCode('register', opts.code, apiBase)\n\n // The gate is about THIS agent only — another coding agent having an\n // identity is irrelevant and must never block this one.\n if (resolveIdentity(home) !== null) {\n console.error(\n `${LABEL} already has an AgentChat identity (see \\`${invocation()} status\\`). Run \\`${invocation()} logout\\` first to replace it.`,\n )\n return 1\n }\n if (readPending(home)?.kind === 'recover') {\n console.error(\n `An account recovery is in progress — finish it with \\`${invocation()} recover --code <code>\\`, or discard it with \\`${invocation()} logout\\` before registering.`,\n )\n return 1\n }\n\n const email = emailInput(opts.email)\n const handle = handleInput(opts.handle)\n const extras = {\n ...(opts.displayName ? { display_name: opts.displayName } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n }\n if (email === undefined || handle === undefined) {\n if (interactive()) {\n return converse('register', { ...(email !== undefined ? { email } : {}), ...(handle !== undefined ? { handle } : {}), ...extras }, apiBase)\n }\n console.error(`Missing --${email === undefined ? 'email' : 'handle'}. Usage: ${invocation()} register --email <email> --handle <handle>`)\n return 1\n }\n return startSignup('register', { email, handle, ...extras }, apiBase)\n }\n\n async function runLogin(opts: { apiKey?: string; apiBase?: string }): Promise<number> {\n const home = profile.home()\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n let apiKey = opts.apiKey?.trim()\n\n // Where the key comes from, most explicit first. A key is never asked for\n // as an argument: argv is visible in `ps` to every user of the machine and\n // kept in shell history. It is piped in (`--api-key -`), typed at the\n // prompt, or taken from AGENTCHAT_API_KEY when this home holds no other\n // key. `--api-key <key>` keeps working for scripts that pass one, and the\n // output says where the key was seen.\n const onArgv = apiKey !== undefined && apiKey.length > 0 && apiKey !== '-'\n if (apiKey === '-') {\n apiKey = await readAllStdin()\n } else if (!apiKey) {\n const fromEnv = process.env['AGENTCHAT_API_KEY']?.trim()\n const refusal = fromEnv ? envKeyRefusal() : null\n if (refusal !== null) {\n console.error(`${refusal}\\nlogin does not adopt an exported key in place of the one this home holds; nothing was saved.`)\n return 1\n }\n if (fromEnv) {\n apiKey = fromEnv\n console.log('Using the key from AGENTCHAT_API_KEY.')\n } else if (process.stdin.isTTY !== true) {\n console.error(\n `Missing API key. If an AgentChat answer gave you the key, write it alone into a file with your file-editing tool; if the person you work with holds it, ask them to save it into a file and tell you where (never to paste it into a conversation). Then run \\`${invocation()} login --api-key - < <that file>\\` and delete the file. A person at a terminal can run \\`${invocation()} login\\` and paste it when it asks. Never put the key itself on a command line: \\`ps\\` and shell history can see it there.`,\n )\n return 1\n } else {\n apiKey = (await prompt('AgentChat API key (ac_…): ')) ?? ''\n }\n }\n if (!apiKey) {\n console.error('No API key given; nothing was saved.')\n return 1\n }\n\n // The server judges the key; a key it does not accept is never saved.\n let check: kit.CheckKeyResult\n try {\n check = await kit.account.checkKey(apiKey, accountOptions(apiBase))\n } catch (err) {\n console.error(`Login failed: ${errorText(err)}\\nThe key was not saved.`)\n return 1\n }\n if (!check.ok) {\n console.error(`Login failed. ${check.code}: ${check.message}\\nThe key was not saved.`)\n return 1\n }\n writeCredentials(home, {\n api_key: apiKey,\n handle: check.handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n clearOfferDeclined(home)\n const placed = await placeIdentity(check.handle, apiKey, apiBase)\n const listener = await placeListener(placed.problem)\n console.log(\n [\n `Signed in as @${check.handle} for ${LABEL}.`,\n `API key stored at ${credentialsPath(home)} (never commit this file).`,\n ...placed.lines,\n ...listener.lines,\n ...(profile.ensureListener === undefined ? [SESSION_HINT] : []),\n ...(onArgv\n ? [\n `Note: the key was on this command line, where \\`ps\\` and shell history can see it. Next time write it into a file with your file-editing tool and pipe it in: \\`${invocation()} login --api-key - < <that file>\\` (or run \\`${invocation()} login\\` in a terminal and paste it).`,\n ]\n : []),\n ].join('\\n'),\n )\n // The key is saved: whatever the listener does next, the command did what it was asked (exit 0).\n await confirm({ ensure: listener.ensure, tools: placed.problem, afterSignIn: true, replacedPid: listener.replacedPid })\n return 0\n }\n\n // Recovery re-keys ONE agent. One email can back several agents, so the\n // handle rides along whenever it is known (this agent's stored one by\n // default); asked by email alone, the server answers an email that backs\n // several agents after the code, with the handles to choose from.\n async function runRecover(opts: RecoverOpts): Promise<number> {\n const home = profile.home()\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n\n if (opts.code !== undefined) return submitPendingCode('recover', opts.code, apiBase)\n\n let handle = handleInput(opts.handle)\n if (handle === undefined) {\n const stored = readCredentials(home)?.handle\n if (stored !== undefined) {\n handle = stored\n console.log(`Recovering @${stored} — this agent's stored handle (pass --handle to recover a different agent).`)\n }\n }\n const email = emailInput(opts.email)\n if (email === undefined) {\n if (!interactive()) {\n console.error(`Missing --email. Usage: ${recoverUsage(invocation())}`)\n return 1\n }\n if (handle === undefined) handle = handleInput((await prompt('Handle of the agent to recover: ')) ?? undefined)\n return converse('recover', handle !== undefined ? { handle } : {}, apiBase)\n }\n return startSignup('recover', { email, ...(handle !== undefined ? { handle } : {}) }, apiBase)\n }\n\n /** The host's note on the file its runtime loads instead of the instruction file (`anchorLoadNote`), judged against the texts in hand, or null; a host check that throws reads as none. */\n function loadNoteFor(handle: string, texts: StatusContext): AnchorLoadNote | null {\n try {\n return profile.anchorLoadNote?.(handle, { identityLine: texts.identityLine, template: texts.identityLineTemplate }) ?? null\n } catch {\n return null\n }\n }\n\n /**\n * The instruction file's block, read the way the daemon reads it\n * (`identityBlockState`): one verdict for `status`, `doctor` and the\n * daemon's follow. A file that exists but cannot be read (permissions, a\n * symlink loop, not UTF-8) is said as such — it is neither \"missing\" nor a\n * reason for status to print nothing.\n */\n function anchorView(\n file: string | null,\n texts: StatusContext,\n handle: string | null,\n ): { present: boolean | null; current: boolean | null; error: string | null; state: IdentityBlockState | null } {\n if (file === null) return { present: null, current: null, error: null, state: null }\n if (handle === null) {\n try {\n return { present: hasAnchorAt(file), current: null, error: null, state: null }\n } catch (err) {\n return { present: null, current: null, error: errorText(err), state: null }\n }\n }\n const state = identityBlockState(file, { handle, identityLine: texts.identityLine, template: texts.identityLineTemplate, loadNote: loadNoteFor(handle, texts) })\n if (state.state === 'unreadable') return { present: null, current: null, error: state.what.replace(/^cannot read [^:]*: /, ''), state }\n return {\n present: state.state !== 'missing',\n current: texts.identityLine === null ? null : state.state === 'current',\n error: null,\n state,\n }\n }\n\n /** The status header's words for the block: `current` when it is the served one (with the note on the file the runtime loads, if any), else the reading's one sentence. */\n function anchorWords(file: string, view: ReturnType<typeof anchorView>): string {\n if (view.error !== null) return `unreadable — ${view.error} (${file})`\n const state = view.state\n if (state === null) return `${view.present ? 'present' : 'missing'} (${file})`\n if (state.verdict === 'PASS') return `current (${file})${state.loadNote !== null ? `; ${state.loadNote.note}` : ''}`\n return describeIdentityBlock(state, `${invocation()} doctor --fix`)\n }\n\n async function runStatus(opts: { json?: boolean }): Promise<number> {\n const home = profile.home()\n const anchorFile = profile.anchorFile?.() ?? null\n // A split identity is said before anything else, and nothing is asked of\n // the server with either key: status names one agent or none.\n const refusal = envKeyRefusal()\n if (refusal !== null) {\n if (opts.json) console.log(JSON.stringify({ configured: true, host: profile.id, error: { kind: 'env_key_conflict', detail: refusal }, home }))\n else console.error(refusal)\n return 1\n }\n const identity = resolveIdentity(home)\n const pending = readPending(home)\n const integration = readIntegrationStatus(home)\n\n const listenerOf = (handle: string | null): ListenerReading | null => (profile.ensureListener !== undefined ? readListener(home, handle) : null)\n\n if (identity === null) {\n // No account yet: the verdict says how to get one (or the code that is waiting).\n const setup = setupVerdict({ ...verdictBase(), identity: null, pending, server: null, listener: null })\n if (opts.json) {\n console.log(\n JSON.stringify({\n configured: false,\n host: profile.id,\n pending: pending !== null,\n pending_kind: pending?.kind ?? null,\n integration,\n setup,\n }),\n )\n if (setup !== null) say(setup)\n } else if (setup !== null) {\n console.log(say(setup))\n }\n return 0\n }\n\n let me: Awaited<ReturnType<AgentChatClient['getMe']>>\n const client = apiClient(identity.apiKey, identity.apiBase)\n try {\n me = await client.getMe()\n } catch (err) {\n // A refused key is not an unreachable server, and neither hides the\n // integration: its socket state and last error (`blocked`, `auth\n // rejected (close 1008 …)`) are exactly what explains the failure.\n const status = httpStatusOf(err)\n const refused = status === 401 || status === 403\n const detail = describeApiError(err)\n const server = serverViewOfError(err)\n const setup = setupVerdict({ ...verdictBase(), identity: { handle: identity.handle, source: identity.source }, pending, server, listener: listenerOf(identity.handle) })\n if (opts.json) {\n const offline = anchorView(anchorFile, NO_TEXTS, null)\n console.log(\n JSON.stringify({\n configured: true,\n host: profile.id,\n handle: identity.handle,\n error: { kind: refused ? 'key_refused' : 'unreachable', status, detail },\n key_source: identity.source,\n api_base: identity.apiBase,\n home,\n anchor: offline.present,\n anchor_error: offline.error,\n integration,\n setup,\n }),\n )\n if (setup !== null) say(setup)\n } else {\n // The server did not answer, so no texts fetch either: the block and the\n // host's checks are read against the identity-home cache (what a fetch\n // would have fallen back to), or without texts when nothing is cached.\n const cached = readCachedTexts(home, profile.client.runtime)\n const context = cached === null ? NO_TEXTS : contextOf(cached.texts)\n const extra = await extraStatusOf(context)\n console.log(\n [\n // First: what this means and what to do (a refused key is not an unreachable server).\n ...(setup !== null ? [say(setup)] : []),\n `${identity.handle !== null ? `@${identity.handle}` : 'This agent'} — ${refused ? `key refused (HTTP ${status})` : 'AgentChat unreachable'} (${LABEL})`,\n `Key source: ${identity.source} (${identity.source === 'file' ? credentialsPath(home) : 'AGENTCHAT_API_KEY'})`,\n `API: ${identity.apiBase}`,\n ...(anchorFile === null ? [] : [`Identity line: ${anchorWords(anchorFile, anchorView(anchorFile, context, identity.handle))}`]),\n ...formatIntegrationStatus(integration),\n ...extra.lines,\n ].join('\\n'),\n )\n }\n return 1\n }\n\n const tray = await traySummary(client).catch(() => null)\n const texts = await served(identity.apiKey, identity.apiBase)\n const anchor = anchorView(anchorFile, texts, me.handle)\n // The host's lines, and the placement problem its checks found (the verdict says it).\n const extra = await extraStatusOf(texts)\n const setup = setupVerdict({\n ...verdictBase(),\n identity: { handle: identity.handle, source: identity.source },\n pending,\n server: { kind: 'ok', handle: me.handle, reachability: reachabilityOf(me) },\n listener: listenerOf(me.handle),\n tools: extra.problem,\n })\n\n if (opts.json) {\n console.log(\n JSON.stringify({\n configured: true,\n host: profile.id,\n handle: me.handle,\n status: me.status ?? 'unknown',\n tray,\n key_source: identity.source,\n api_base: identity.apiBase,\n home,\n anchor: anchor.present,\n /** null: the served texts were unavailable (or there is no instruction file, or it cannot be read), so currency could not be checked. */\n anchor_current: anchor.current,\n /** Why the instruction file could not be read, or null. */\n anchor_error: anchor.error,\n /** The block as the daemon reads it (`identityBlockState`: current, stale, missing, setup_offer, hand_edited, other_agent, several_blocks, unreadable), or null. */\n anchor_state: anchor.state?.state ?? null,\n /** Why the runtime does not load the instruction file now, or null. */\n anchor_not_loaded: anchor.state?.notLoaded ?? null,\n integration,\n /** Whether setup is done and what is left (`setupVerdict`); null when this host has nothing to judge. */\n setup,\n }),\n )\n if (setup !== null) say(setup)\n } else {\n const trayLine =\n tray === null\n ? 'Tray: could not be read'\n : `Tray: ${tray.waiting}${tray.truncated ? '+' : ''} conversation(s) waiting${tray.deferred > 0 ? `, ${tray.deferred} deferred` : ''}`\n console.log(\n [\n ...(setup !== null ? [say(setup)] : []),\n `@${me.handle} — ${me.status ?? 'active'} (${LABEL})`,\n trayLine,\n `Key source: ${identity.source} (${identity.source === 'file' ? credentialsPath(home) : 'AGENTCHAT_API_KEY'})`,\n `API: ${identity.apiBase}`,\n ...(anchorFile === null\n ? []\n : [\n `Identity line: ${anchorWords(anchorFile, anchor)}`,\n ]),\n ...formatIntegrationStatus(integration),\n ...extra.lines,\n ].join('\\n'),\n )\n }\n return 0\n }\n\n /**\n * Sign out THIS agent. Authentication and integration installation are\n * separate lifecycles: logout must never silently remove the service or the\n * manual. It removes what authenticates as the old identity: the credential,\n * the identity line, and the key the hosted tool server was registered with.\n * First, while the key is still here, AgentChat is told this home's\n * listener stopped on purpose (contract v1 §3.13): the agent then reads as\n * switched off, not as a computer that is off. One bounded attempt; the\n * sign-out goes on whatever it answers.\n */\n async function runLogout(): Promise<number> {\n const home = profile.home()\n const anchorFile = profile.anchorFile?.() ?? null\n const reports: string[] = []\n let any = false\n\n // Read BEFORE clearing: `unplace` recognises the host's own registration\n // by the key and the API base that were placed, and both are gone from\n // disk once the credential is deleted.\n const identity = resolveIdentity(home)\n\n // For the key this home holds, the one deleted below (an exported key\n // stays, and so does whatever serves it: `reportListenerStopped` skips it).\n const stopped = await reportListenerStopped({ home, client: profile.client, identity })\n const stoppedLine = describeListenerStopped(stopped)\n if (stoppedLine !== null) reports.push(` ${stoppedLine}`)\n\n if (clearCredentials(home)) {\n any = true\n reports.push(' credentials deleted')\n }\n if (anchorFile !== null) {\n // A file that cannot be rewritten must not stop the sign-out half-way:\n // `unplace` below still has to take the old key out of the host.\n try {\n // Only what AgentChat placed for this agent goes: its own block (by the\n // kit's strict reading, with the kept texts when there are any) or the\n // setup offer. A block edited by hand, or another agent's, is left.\n const cached = readCachedTexts(home, profile.client.runtime)\n const removed = removeAnchorAt(anchorFile, {\n handle: identity?.handle ?? null,\n identityLine: cached?.texts.identity_line ?? null,\n template: cached?.texts.identity_line_template ?? null,\n })\n if (removed.action === 'removed') {\n any = true\n reports.push(` ${anchorLabelOf(profile)} identity line removed`)\n } else if (removed.action === 'kept') {\n any = true\n reports.push(` ${removed.detail}`)\n }\n } catch (err) {\n any = true\n reports.push(` could not remove the identity line from ${anchorFile}: ${errorText(err)} — remove the agentchat block by hand`)\n }\n }\n if (profile.unplace !== undefined) {\n try {\n const lines = profile.unplace(identity)\n if (lines.length > 0) any = true\n reports.push(...lines)\n } catch (err) {\n reports.push(` could not undo placement: ${String(err)}`)\n }\n }\n\n console.log(\n [\n any ? `Signed out of ${LABEL}.` : 'Nothing to sign out of.',\n ...reports,\n ...(any\n ? [\n 'Any other coding agent on this machine is untouched — it is a separate AgentChat agent with its own handle.',\n ...(profile.logoutHints?.() ?? []),\n ]\n : []),\n ].join('\\n'),\n )\n return 0\n }\n\n /** The block as the daemon reads it (`identityBlockState`), for this agent. */\n function readIdentityLine(anchorFile: string, handle: string, texts: StatusContext): IdentityBlockState {\n return identityBlockState(anchorFile, { handle, identityLine: texts.identityLine, template: texts.identityLineTemplate, loadNote: loadNoteFor(handle, texts) })\n }\n\n /**\n * The doctor's identity-line check (and its `--fix`), for a host that has\n * an instruction file: the same reading `status` and the daemon use, so the\n * three say one thing. `--fix` places the served block over whatever block\n * is there (the user asked for it), but never writes a file the runtime\n * reads in the instruction file's place: a block it does not load stays a\n * WARN, with what to do.\n */\n async function identityLineCheck(\n anchorFile: string,\n creds: { handle: string; api_key: string },\n apiBase: string,\n texts: StatusContext,\n fix: boolean,\n ): Promise<DoctorCheck> {\n const fixCommand = `${invocation()} doctor --fix`\n const before = readIdentityLine(anchorFile, creds.handle, texts)\n if (before.state === 'unreadable') return { name: 'identity-line', verdict: 'FAIL', detail: before.what }\n // doctor --fix writes only where it takes nothing of anyone's: no block, the\n // setup offer, or this agent's own block. A block edited by hand (or\n // several) is the person's to delete first; another agent's means the key\n // or the file is wrong — both are said, never written over. A runtime that\n // does not load the file is said too, not written around.\n const repairable = before.state === 'missing' || before.state === 'setup_offer' || before.state === 'stale'\n if (fix && repairable) {\n const report = (await placeIdentity(creds.handle, creds.api_key, apiBase)).lines\n const failed = report.some((l) => l.includes('FAILED') || l.includes('not written'))\n if (failed) return { name: 'identity-line', verdict: 'FAIL', detail: `could not repair: ${report.join('; ')}` }\n // Said repaired only when the file now reads as repaired.\n const after = readIdentityLine(anchorFile, creds.handle, texts)\n if (after.state === 'current') {\n return { name: 'identity-line', verdict: after.verdict, detail: after.loadNote === null ? `repaired → @${creds.handle}` : `repaired → @${creds.handle} in ${anchorFile}; ${after.loadNote.note}` }\n }\n if (after.state === 'unreadable') return { name: 'identity-line', verdict: 'FAIL', detail: `${after.what} (after the repair)` }\n return { name: 'identity-line', verdict: 'FAIL', detail: `repair did not take: ${after.what}${report.length > 0 ? ` (${report.join('; ').trim()})` : ''}` }\n }\n return { name: 'identity-line', verdict: before.verdict, detail: describeIdentityBlock(before, fixCommand) }\n }\n\n async function runDoctor(opts: DoctorOpts = {}): Promise<number> {\n const home = profile.home()\n const anchorFile = profile.anchorFile?.() ?? null\n const checks: DoctorCheck[] = []\n let texts: StatusContext = NO_TEXTS\n\n checks.push({ name: 'node', verdict: 'PASS', detail: process.version })\n checks.push({ name: 'home', verdict: 'PASS', detail: home })\n // Every check below, and every repair `--fix` makes, uses the home's key.\n const refusal = envKeyRefusal()\n if (refusal !== null) checks.push({ name: 'env-key', verdict: 'FAIL', detail: refusal })\n\n const creds = readCredentials(home)\n // What the server said, for the verdict at the end.\n let server: ServerView | null = null\n if (creds === null) {\n checks.push({\n name: 'credentials',\n verdict: 'FAIL',\n detail: `no identity at ${credentialsPath(home)} — run \\`${invocation()} register\\``,\n })\n } else {\n checks.push({ name: 'credentials', verdict: 'PASS', detail: `@${creds.handle}` })\n const identity = resolveIdentity(home)\n if (identity !== null) {\n try {\n const client = apiClient(identity.apiKey, identity.apiBase)\n const started = Date.now()\n const me = await client.getMe()\n server = { kind: 'ok', handle: me.handle, reachability: reachabilityOf(me) }\n const verdict: Verdict = (me.status ?? 'active') === 'active' ? 'PASS' : 'WARN'\n checks.push({\n name: 'api-auth',\n verdict,\n detail: `@${me.handle} status=${me.status ?? 'active'} (${Date.now() - started}ms)`,\n })\n if (me.handle !== creds.handle) {\n checks.push({\n name: 'handle-drift',\n verdict: 'WARN',\n detail: `credentials say @${creds.handle} but the key authenticates as @${me.handle} — re-run \\`${invocation()} login\\``,\n })\n }\n } catch (err) {\n server = serverViewOfError(err)\n checks.push({ name: 'api-auth', verdict: 'FAIL', detail: `getMe failed: ${String(err)}` })\n }\n }\n\n // The identity line must name THIS agent, in the text the server serves\n // today. Releases of the old shared CLI wrote the anchor for every host\n // on the machine whenever any one registered, so a two-agent box could\n // end up with an instruction file announcing the OTHER agent's handle.\n const apiBase = identity?.apiBase ?? creds.api_base ?? DEFAULT_API_BASE\n texts = await served(creds.api_key, apiBase)\n checks.push(\n texts.identityLine === null\n ? { name: 'texts', verdict: 'WARN', detail: 'GET /v1/texts could not be reached and nothing is cached — the identity line cannot be checked or placed until it can' }\n : { name: 'texts', verdict: 'PASS', detail: 'served texts in hand' },\n )\n if (anchorFile !== null) checks.push(await identityLineCheck(anchorFile, creds, apiBase, texts, opts.fix === true))\n }\n\n // --fix places the listener too, as install does (with or without an\n // identity: it idles until one appears), unless the person switched it\n // off. Said only when it did something: the host's own service check\n // reports a listener that is current or switched off.\n let ensure: ListenerEnsure | null = null\n if (opts.fix === true && profile.ensureListener !== undefined) {\n ensure = await ensureListenerOnce()\n if (ensure?.outcome === 'installed') checks.push({ name: 'listener', verdict: 'PASS', detail: `registered${ensure.detail ? ` (${ensure.detail})` : ''}` })\n else if (ensure?.outcome === 'failed') {\n checks.push({ name: 'listener', verdict: 'FAIL', detail: `could not be registered: ${ensure.detail ?? 'no reason given'} — \\`${invocation()} daemon install\\` tries again` })\n }\n }\n\n // The receive loop's own record: repeated cycles that did not get done\n // (a runtime that fails, texts that never arrive, a cycle abandoned by\n // its watchdog) are a pattern to fix, even while the socket looks fine.\n const integration = readIntegrationStatus(home)\n // Runs failing for a runtime reason, as the daemon's own recheck found\n // (signed out, the binary gone, a flag an upgrade dropped).\n const runsFailing = integration?.runs_failing ?? null\n const gaveUp = integration?.unservable ?? null\n if (gaveUp !== null) {\n checks.push({\n name: 'runs',\n verdict: 'FAIL',\n detail:\n gaveUp.reason === 'key_refused'\n ? `this home gave the agent up: the server refuses its key (${gaveUp.detail}); it looks again at ${gaveUp.retry_at} (every 5 min) and takes the agent back whenever no other listener holds it, but only a key the server accepts can serve — sign in again here (login/recover; that clears this at once), or log out if another home serves the agent`\n : `this home gave the agent up: ${gaveUp.detail} (since ${gaveUp.since}); its runtime is checked again at ${gaveUp.retry_at} (every 60 s) and a check that passes clears this; it takes the agent back whenever no other listener holds it`,\n })\n } else if (runsFailing !== null) {\n checks.push({\n name: 'runs',\n verdict: 'FAIL',\n detail: `runs failing: ${runsFailing.reason} — since ${runsFailing.since}, ${runsFailing.runs_missed} run(s) missed (checked ${runsFailing.checked_at}); fix that, and the next run that succeeds clears this`,\n })\n }\n // Another daemon serves this agent from another identity home.\n const standby = integration?.standby ?? null\n if (standby !== null) {\n checks.push({\n name: 'single-listener',\n verdict: 'WARN',\n detail: `another listener serves this agent: ${standby.home ?? 'another identity home'}${standby.pid !== null ? ` (pid ${standby.pid})` : ''}; this one stands by (no socket, no run) so no message is answered twice`,\n })\n }\n const cycles = integration?.recent_cycles ?? []\n if (cycles.length > 0) {\n const failing = failedCyclesInARow(integration)\n const last = cycles[cycles.length - 1]!\n checks.push(\n failing !== null && failing.count >= REPEATED_FAILED_CYCLES\n ? {\n name: 'wake-cycles',\n verdict: 'WARN',\n detail: `the last ${failing.count} wake cycles did not get done (latest: ${failing.latest.outcome}${failing.latest.failure ? ` — ${failing.latest.failure}` : ''}); the cards stay on the tray`,\n }\n : { name: 'wake-cycles', verdict: 'PASS', detail: `last cycle ${last.outcome} at ${last.at} (${cycles.length} recent)` },\n )\n }\n // With conversation runs a cycle only starts runs: runs that keep failing\n // with no runtime reason found are said here.\n const failedRuns = repeatedFailedRuns(integration)\n if (failedRuns !== null) {\n const lastRun = integration?.last_run ?? null\n checks.push({\n name: 'runs',\n verdict: 'WARN',\n detail: `the last ${failedRuns} runs did not get done${lastRun !== null ? ` (latest: ${lastRun.state}${lastRun.detail ? ` — ${lastRun.detail}` : ''})` : ''}; the cards stay on the tray`,\n })\n }\n // Could not process: the conversations paused for this agent (a pause is\n // the server's, with its own end, whether or not the daemon runs), and a\n // runtime check that fails (then no failure is reported as a\n // conversation's: a broken runtime is not its fault) — said only while\n // the status file is fresh: a check from before the daemon went quiet\n // says nothing about now.\n const cnp = integration?.could_not_process ?? null\n if (cnp !== null) {\n const paused = describePausedConversations(cnp.paused_conversations)\n const lastCheck = cnp.last_runtime_check\n const counts = describeCouldNotProcessCounts(cnp)\n if (paused !== null) {\n checks.push({ name: 'could-not-process', verdict: 'WARN', detail: paused.replace(/^could not process: /, '') })\n } else if (lastCheck !== null && runtimeCheckFailingNow(integration)) {\n checks.push(\n integrationStatusFresh(integration)\n ? {\n name: 'could-not-process',\n verdict: 'WARN',\n detail: `the runtime check failed (${lastCheck.detail ?? 'no detail'}; ${lastCheck.at}): while it fails, a conversation whose run fails is not reported, its card stays on the tray and the server wakes the agent again`,\n }\n : {\n name: 'could-not-process',\n verdict: 'WARN',\n detail: `the daemon has not written its status for ${integrationStatusStaleFor(integration)} — it may be down (a running daemon rewrites it every 30 s); the runtime check that failed at ${lastCheck.at} says nothing about now`,\n },\n )\n } else if (counts !== null) {\n checks.push({ name: 'could-not-process', verdict: 'PASS', detail: counts.replace(/^could not process: /, '') })\n }\n }\n\n if (profile.extraDoctorChecks !== undefined) {\n try {\n checks.push(...(await profile.extraDoctorChecks({ ...opts, ...texts })))\n } catch (err) {\n checks.push({ name: 'host', verdict: 'FAIL', detail: `the ${LABEL} checks failed: ${errorText(err)}` })\n }\n }\n\n console.log(checks.map((c) => `${c.verdict.padEnd(4)} ${c.name}: ${c.detail}`).join('\\n'))\n // Last, what it all means: the setup verdict (not with a split identity: whose would it be?).\n if (refusal === null) {\n const identity = resolveIdentity(home)\n const handle = server?.kind === 'ok' ? server.handle : (identity?.handle ?? null)\n const verdict = setupVerdict({\n ...verdictBase(),\n identity: identity === null ? null : { handle: identity.handle, source: identity.source },\n pending: readPending(home),\n server: identity === null ? null : server,\n listener: profile.ensureListener !== undefined ? readListener(home, handle) : null,\n ensure,\n })\n if (verdict !== null) console.log(say(verdict))\n }\n return checks.some((c) => c.verdict === 'FAIL') ? 1 : 0\n }\n\n return {\n runRegister: tracked('register', runRegister),\n runLogin: tracked('login', runLogin),\n runRecover: tracked('recover', runRecover),\n runStatus: tracked('status', runStatus),\n runLogout,\n runDoctor: tracked('doctor', runDoctor),\n confirmSetup,\n reportSetup,\n }\n}\n","import type { AnchorLoadNote, AnchorServedLine } from '../anchor/follow.js'\nimport type { IntegrationClient } from '../client-identity.js'\nimport type { ServedManual } from '../skill/served-manual.js'\nimport type { ResolvedIdentity } from './credentials.js'\n\nexport type Verdict = 'PASS' | 'WARN' | 'FAIL'\n\nexport interface DoctorCheck {\n name: string\n verdict: Verdict\n detail: string\n}\n\n/** What the shared `status` hands a host's extra lines: what it already fetched from the served texts (one fetch per command). */\nexport interface StatusContext {\n identityLine: string | null\n /**\n * The served `identity_line_template` from the same texts, or null when none\n * are in hand: what `readAnchorHandleAt` recognises an unmarked block by, in\n * whatever words the server serves today.\n */\n identityLineTemplate: string | null\n /** The manual the served texts announce (`texts.manual`), or null when none are in hand — what `checkManual` compares the skill file with. */\n manual: ServedManual | null\n}\n\n/** What the shared doctor hands a host's extra checks. */\nexport interface DoctorContext {\n fix?: boolean\n /** The served identity line for this agent, or null when the server could not be reached and nothing is cached. */\n identityLine: string | null\n /** The served `identity_line_template`, or null when none are in hand (see `StatusContext`). */\n identityLineTemplate: string | null\n /** The manual the served texts announce, or null when none are in hand (`--fix` syncs the skill file to it). */\n manual: ServedManual | null\n}\n\n/**\n * A placement problem that keeps the agent's runs from having the AgentChat\n * tools: the hosted tool server could not be registered, or a registration\n * this integration did not write stands in its place. The setup verdict says\n * it as `tools_missing`, in the host's words.\n */\nexport interface PlacementProblem {\n /** What is wrong and what to do, in plain words that name the exact command, or what to ask the person. */\n readonly text: string\n /** The command to run next; absent: `doctor --fix` (or none, when only the person can resolve it). */\n readonly command?: string\n /** Only the person can resolve it (their own registration stands in the way: ask before touching it). */\n readonly needsPerson?: boolean\n /** What to ask the person, when `needsPerson`. */\n readonly ask?: string\n /** The facts, as found. */\n readonly detail?: string\n}\n\n/** What `place` (and `extraStatus`) may return instead of bare lines: the lines, and the problem that blocks the tools, or null. */\nexport interface PlacementReport {\n readonly lines: string[]\n readonly problem: PlacementProblem | null\n}\n\n/** Lines, or lines with a placement problem: a host that returns bare lines reports no problem. */\nexport type PlacementOutput = string[] | PlacementReport\n\n/** A host's lines and problem, whichever shape it returned. */\nexport function placementReportOf(output: PlacementOutput): PlacementReport {\n return Array.isArray(output) ? { lines: output, problem: null } : { lines: output.lines, problem: output.problem ?? null }\n}\n\n/**\n * What `ensureListener` did.\n *\n * installed registered now (it was missing, stale, or another release's);\n * current already registered and current: nothing was done;\n * opted_out the person switched it off (`daemon disable`, `uninstall`): nothing was done;\n * failed it could not be registered (`detail` says why).\n */\nexport interface ListenerEnsure {\n readonly outcome: 'installed' | 'current' | 'opted_out' | 'failed'\n /** The service's name for `installed` / `current` (e.g. `agentchatd-claude-code`); why, for `failed`; null otherwise. */\n readonly detail: string | null\n}\n\n/**\n * Everything the shared identity commands need to know about ONE coding agent.\n *\n * This is the seam. The register / login / recover / status / logout / doctor\n * flows are the same everywhere because they are a contract with the AgentChat\n * server; what differs per host is only what is described here. An integration\n * builds one of these and gets the commands back.\n *\n * Note what is NOT here: any way to name a *different* host. A profile\n * describes the caller and nothing else, so a command built from it cannot\n * reach another agent's files. That is the same property the per-repo split\n * gives, kept intact while the flow itself is shared once.\n *\n * The path-ish fields are functions, not strings: `CODEX_HOME` and friends are\n * read per call, and evaluating them at module load would freeze a value the\n * user can still change.\n */\nexport interface HostProfile {\n /** Human name for output, e.g. `Claude Code`. */\n label: string\n /** Stable machine identifier for `--json`, e.g. `claude-code`. */\n id: string\n /** How this integration names itself to the server: the texts runtime and its own version. */\n client: IntegrationClient\n /** THE identity home for this agent. */\n home(): string\n /**\n * This host's always-loaded instruction file. Absent for a front door whose\n * runtime has none it can place a line in (the `agentchat` listener runs an\n * owner's command): no identity line is placed, checked or removed.\n */\n anchorFile?(): string\n /**\n * For a runtime that reads another file in `anchorFile()`'s place when\n * that one exists: which file it loads now, and whether the identity line\n * it gets there is the served one (`served`, the texts in hand), or null\n * when it loads `anchorFile()`. `status` and `doctor` say it (never a PASS\n * when `ok` is false), and the daemon's follow of the identity line says\n * it too. Nothing writes into that other file: it is the user's.\n */\n anchorLoadNote?(handle: string, served: AnchorServedLine): AnchorLoadNote | null\n /** Exactly what a user types to reach this integration. */\n invocation(): string\n /**\n * The identity block this host places for `handle` from the served identity\n * line (normally `renderAnchorBlock`, the kit's shape with the handle line).\n * Throws when the line does not name the handle; nothing is written then.\n */\n renderAnchor(identityLine: string, handle: string): string\n /**\n * What to call the anchor in output. Defaults to the instruction file's own\n * basename (`CLAUDE.md`, `AGENTS.md`), which is what a user actually looks\n * for on disk.\n */\n anchorLabel?: string\n /**\n * Whether this host is wired up enough for an anchor to mean anything.\n * An integration uses this so it never writes an identity block announcing\n * a phone number before its own placement is actually in place.\n */\n isWired?(): boolean\n /**\n * Place the integration's texts for a freshly established identity: the\n * identity line, the manual, the hosted tool server with the key, and\n * whatever the key's home is on this runtime. Called after register, login\n * and recover (every time the key changes), and by `doctor --fix`.\n * `identityLine` is the served line for this agent (fetched just before,\n * or the cached one), or null when neither could be had — the host then\n * leaves the anchor for `doctor --fix` and says so. `manual` is what the\n * same texts announce (`syncManual` brings the skill file to it), or null.\n * Returns report lines, or the lines with the placement problem that keeps\n * runs from having the AgentChat tools (`PlacementReport`): with a problem,\n * the listener is not registered and the setup verdict is `tools_missing`.\n * When absent, only the anchor is written.\n */\n place?(handle: string, apiKey: string, identityLine: string | null, manual: ServedManual | null): PlacementOutput | Promise<PlacementOutput>\n /**\n * Have this host's listener service — the resident daemon that holds the\n * socket and starts a run when a peer writes — registered and current,\n * unless the person switched it off. Never throws. Called by the shared\n * flow after `place`: register and recover on their code leg, login, and\n * doctor --fix. A host that has it turns its listener on with\n * `<invocation> daemon install`; the shared commands then wait for the\n * listener to connect and say the setup verdict (`Setup: <state> — …`).\n * Absent (a front door with no service of its own to place, such as the\n * `agentchat` CLI): no listener is placed, waited for or judged.\n */\n ensureListener?(): ListenerEnsure | Promise<ListenerEnsure>\n /**\n * The runtime this integration runs inside and its version,\n * `<runtime>/<version>` (`hostIdentityOf(runtime, <its --version output>)`),\n * or null when it cannot be read. Asked once per command (bounded); it is\n * the `host` member of X-AgentChat-Platform and nothing else.\n */\n host?(): string | null | Promise<string | null>\n /**\n * Undo `place` for the identity being signed out: remove the key from the\n * tool server registration and anything else that would still authenticate\n * as the old identity. The anchor is removed by the shared flow. Returns\n * report lines.\n *\n * `identity` is the identity AS IT WAS BEFORE the credential was cleared\n * (its key and API base), or null when there was none: a host recognises\n * its own registration by that key and that server, and guessing either\n * after the fact left a non-default `api_base` entry classified as foreign\n * and the key still registered.\n */\n unplace?(identity: ResolvedIdentity | null): string[]\n /** Host-specific doctor checks, appended after the shared ones. */\n extraDoctorChecks?(context: DoctorContext): DoctorCheck[] | Promise<DoctorCheck[]>\n /**\n * Host-specific `status` lines (placement, probes), printed after the shared\n * ones in text mode. The served identity line and manual come along so the\n * host does not fetch `/v1/texts` a second time. May return the lines with\n * the placement problem its checks found (`PlacementReport`), which the\n * setup verdict says as `tools_missing`.\n */\n extraStatus?(context: StatusContext): PlacementOutput | Promise<PlacementOutput>\n /** Extra lines printed after a successful logout. */\n logoutHints?(): string[]\n}\n\n/** The label to use for this host's anchor in user-facing output. */\nexport function anchorLabelOf(profile: HostProfile): string {\n if (profile.anchorLabel !== undefined) return profile.anchorLabel\n if (profile.anchorFile === undefined) return 'identity line'\n const file = profile.anchorFile()\n const slash = Math.max(file.lastIndexOf('/'), file.lastIndexOf('\\\\'))\n return slash >= 0 ? file.slice(slash + 1) : file\n}\n","import { clientIdentityHeaders, HttpTransport, type AgentChatClientIdentity } from 'agentchatme'\nimport type { SetupVerdict } from './setup.js'\nimport { serviceDryRun } from './setup.js'\n\n// ─── Setup telemetry: one event per command that says a verdict ─────────────\n//\n// Every command that prints a `Setup:` line (install, register, login,\n// recover, status, doctor) tells AgentChat what it said, once, at its end:\n// `POST /v1/telemetry` with one `setup_verdict` event (contract v1,\n// \"Client telemetry\"). So the setup's failure points can be seen without\n// asking anyone: where agents stop, and on what.\n//\n// What is sent: the verdict's state, which command, whether the next step is\n// the person's, the verdict's reason word, the command's exit code and how\n// long it took — and the headers every SDK call carries (the client and its\n// version, X-AgentChat-Platform with the install id), with the key only when\n// the home holds one. Nothing else: no key in the body, no email, handle or\n// code typed, no path, no server sentence, no text of the verdict.\n//\n// It never prints, never changes an exit code, and never holds a command up\n// for more than TELEMETRY_TIMEOUT_MS (one attempt, awaited before the\n// process exits: a short-lived CLI would drop a request left in flight). Any\n// answer or failure is silent — an older server's 404 included.\n// AGENTCHAT_TELEMETRY=off (or 0, false) sends nothing, and makes no install\n// id. Under AGENTCHAT_SERVICE_DRY_RUN (sandboxes, tests) nothing reaches the\n// network unless a sender is given.\n\nexport const TELEMETRY_ENV = 'AGENTCHAT_TELEMETRY'\nexport const TELEMETRY_PATH = '/v1/telemetry'\nexport const TELEMETRY_VERSION = 1 as const\n/** The most a command waits for its event to be taken. */\nexport const TELEMETRY_TIMEOUT_MS = 1_500\n\n/** The commands a `setup_verdict` names (the server's closed list). */\nexport type SetupCommand = 'install' | 'register' | 'login' | 'recover' | 'doctor' | 'status' | 'uninstall' | 'daemon' | 'other'\n\nexport interface SetupVerdictEvent {\n readonly name: 'setup_verdict'\n readonly at: string\n readonly props: {\n readonly state: string\n readonly command: SetupCommand\n readonly needs_person: boolean\n readonly reason?: string\n readonly exit_code: number\n readonly duration_ms: number\n }\n}\n\nexport interface TelemetryBody {\n readonly version: typeof TELEMETRY_VERSION\n readonly events: readonly SetupVerdictEvent[]\n}\n\n/** One request, as a sender gets it. */\nexport interface TelemetryRequest {\n readonly apiBase: string\n /** The identity's key, or null: the event is then anonymous (the install id names it). */\n readonly apiKey: string | null\n /** What the request names itself with (the SDK turns it into the client headers and X-AgentChat-Platform). */\n readonly clientIdentity: AgentChatClientIdentity\n readonly body: TelemetryBody\n /** Aborted when the time is up. */\n readonly signal: AbortSignal\n}\n\n/** Sends one request; may throw (the caller swallows it). */\nexport type TelemetrySender = (request: TelemetryRequest) => Promise<void>\n\n/** `AGENTCHAT_TELEMETRY` set to `off`, `0` or `false` (any case). */\nexport function telemetryOff(env: NodeJS.ProcessEnv = process.env): boolean {\n const v = env[TELEMETRY_ENV]?.trim().toLowerCase()\n return v === 'off' || v === '0' || v === 'false'\n}\n\nconst REASON_SHAPE = /^[a-z][a-z0-9_]{0,31}$/\n\nfunction clampInt(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) return min\n return Math.min(max, Math.max(min, Math.round(value)))\n}\n\n/** The event for a verdict a command said. */\nexport function setupVerdictEvent(verdict: SetupVerdict, facts: { command: SetupCommand; exitCode: number; startedAt: number; now?: number }): SetupVerdictEvent {\n const now = facts.now ?? Date.now()\n const reason = verdict.reason\n return {\n name: 'setup_verdict',\n at: new Date(now).toISOString(),\n props: {\n state: verdict.state,\n command: facts.command,\n needs_person: verdict.needs_person,\n ...(reason !== null && REASON_SHAPE.test(reason) ? { reason } : {}),\n exit_code: clampInt(facts.exitCode, 0, 255),\n duration_ms: clampInt(now - facts.startedAt, 0, 600_000),\n },\n }\n}\n\n/**\n * The network sender: one attempt through the SDK's transport, so the request\n * carries exactly the headers every SDK call does (no copy of them here).\n */\nexport const httpTelemetrySender: TelemetrySender = async (request) => {\n const transport = new HttpTransport({\n baseUrl: request.apiBase,\n defaultHeaders: clientIdentityHeaders(request.clientIdentity),\n ...(request.apiKey !== null ? { apiKey: request.apiKey } : {}),\n timeoutMs: TELEMETRY_TIMEOUT_MS,\n retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 },\n })\n await transport.request('POST', TELEMETRY_PATH, { body: request.body, signal: request.signal })\n}\n\nexport interface SendSetupVerdictOptions {\n readonly command: SetupCommand\n readonly exitCode: number\n readonly startedAt: number\n readonly apiBase: string\n readonly apiKey: string | null\n readonly clientIdentity: AgentChatClientIdentity\n /** Default: the network (`httpTelemetrySender`), or nothing at all under AGENTCHAT_SERVICE_DRY_RUN. */\n readonly sender?: TelemetrySender\n readonly env?: NodeJS.ProcessEnv\n readonly timeoutMs?: number\n}\n\n/**\n * Tell AgentChat what a command said. Resolves within the timeout whatever\n * happens; never throws, never prints. Nothing is sent when telemetry is\n * off, or when there is neither an install id nor a key to name the sender.\n */\nexport async function sendSetupVerdict(verdict: SetupVerdict, opts: SendSetupVerdictOptions): Promise<void> {\n const env = opts.env ?? process.env\n if (telemetryOff(env)) return\n if (opts.apiKey === null && opts.clientIdentity.installId === undefined) return\n const sender = opts.sender ?? (serviceDryRun(env) ? null : httpTelemetrySender)\n if (sender === null) return\n const controller = new AbortController()\n const timeoutMs = opts.timeoutMs ?? TELEMETRY_TIMEOUT_MS\n let timer: NodeJS.Timeout | undefined\n try {\n const body: TelemetryBody = { version: TELEMETRY_VERSION, events: [setupVerdictEvent(verdict, opts)] }\n const sent = sender({ apiBase: opts.apiBase, apiKey: opts.apiKey, clientIdentity: opts.clientIdentity, body, signal: controller.signal }).catch(() => undefined)\n const timedOut = new Promise<void>((resolve) => {\n timer = setTimeout(() => {\n controller.abort()\n resolve()\n }, timeoutMs)\n timer.unref?.()\n })\n await Promise.race([sent, timedOut])\n } catch {\n /* never a reason for a command to fail */\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n","import * as crypto from 'node:crypto'\nimport * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { log } from '../util/log.js'\nimport { atomicWriteFile } from '../util/fsutil.js'\nimport { spawnCommand, spawnCommandSync } from '../util/spawn.js'\nimport { holderLive, parseLease } from '../util/lease.js'\nimport { DAEMON_LOCK_FILE } from './leader-lock.js'\n\n// ─── Service lifecycle (systemd / launchd / Windows Startup) ─────────────────\n//\n// `agentchatd start` only runs while the shell is open — no good for a 24/7\n// consumer product. `install` registers the daemon as a real background\n// service that starts on boot/login and restarts on crash:\n// * Linux (native) → a systemd USER unit + `loginctl enable-linger`.\n// * macOS → a launchd LaunchAgent with KeepAlive + RunAtLoad.\n// * Windows / WSL2 → a hidden, restart-on-exit VBScript in the user's Startup\n// folder (no admin). See the Windows section below.\n// One service per INTEGRATION (the leader lock already enforces one daemon per\n// identity on a box). The caller supplies the label and the env to capture —\n// this module has no idea which coding agents exist, which is what keeps two\n// integrations' services from ever colliding on a name or clobbering each\n// other's unit file. Convention is `agentchatd-<integration>`.\n//\n// ONE LABEL PER IDENTITY HOME, and never touch a job that serves another one.\n// `launchctl` and `systemctl --user` address the USER's domain, not the\n// current HOME or config dir, while the unit file follows HOME and the\n// identity home follows CLAUDE_CONFIG_DIR / CODEX_HOME. With one global label\n// per integration, a relocated config (a sandbox, a second profile) reported\n// the machine's real service as its own, and `uninstall` there would have\n// `launchctl remove`d it (live-fire E5). So:\n// * `serviceLabelFor` gives a relocated identity home its own label (a\n// short stable hash suffix); the default home keeps the plain label, so\n// existing installs keep working;\n// * before stopping, replacing or removing a job, its definition (the unit\n// file at this label's path, and the job the service manager has loaded\n// under this label) is read, and the operation is refused unless its\n// `--home` is this config's identity home;\n// * `AGENTCHAT_SERVICE_DRY_RUN` keeps the service manager out entirely —\n// not written, not stopped, not even queried for status.\n\n/**\n * Enough to ADDRESS an already-installed service. Removing one or reading its\n * status needs only its name — deliberately a narrower type than install, so\n * `uninstall` and `status` cannot be made to depend on a daemon entry they have\n * no use for.\n */\nexport interface ServiceRef {\n /** Unit/service name, e.g. `agentchatd-codex` — from `serviceLabelFor`, so unique per identity home. */\n label: string\n home: string\n /**\n * Labels this service replaces (e.g. the plain label a relocated home was\n * installed under before labels were per home). On install and uninstall,\n * a superseded service whose definition serves THIS home is removed; one\n * serving another home is left alone.\n */\n supersedes?: readonly string[]\n}\n\n/**\n * The service label for an identity home: `base` for the integration's\n * default home (so existing installs keep their label), `base-<8 hex>` — a\n * stable hash of the resolved path — for any other. Two configs of one\n * integration on one machine then never share a launchd/systemd job.\n */\nexport function serviceLabelFor(base: string, home: string, defaultHome: string): string {\n const key = (p: string): string => {\n const resolved = path.resolve(p)\n return process.platform === 'win32' ? resolved.toLowerCase() : resolved\n }\n if (key(home) === key(defaultHome)) return serviceLabel(base)\n const digest = crypto.createHash('sha256').update(key(home)).digest('hex').slice(0, 8)\n return serviceLabel(`${base}-${digest}`)\n}\n\nexport interface ServiceOpts extends ServiceRef {\n /**\n * Absolute path to the integration's DAEMON bundle — the script this service\n * runs. Required, and deliberately not defaulted.\n *\n * It used to default to `process.argv[1]`, i.e. whichever binary happened to\n * call `install`. That was the CLI, which has no daemon in it, so every\n * installed unit ran a command that exited 1 and then restart-looped forever\n * under `KeepAlive`/`Restart=on-failure` while the CLI cheerfully reported\n * \"Always-on is ON\". Making the caller name the entry is what stops a service\n * from being installed against a script that cannot serve it.\n *\n * Must also be a STABLE path. A plugin's own bundle lives in a\n * version-scoped cache directory that the next upgrade deletes, so an\n * integration distributed that way copies itself somewhere durable first and\n * passes that copy here.\n */\n entry: string\n /** Host-specific env the service must see because a systemd/launchd service\n * does NOT inherit the login shell (e.g. CODEX_HOME). PATH is captured\n * automatically. */\n env?: Record<string, string>\n}\n\nexport interface Plan {\n label: string // service/unit name\n node: string // absolute node path\n bin: string // absolute daemon entry, supplied by the integration\n home: string\n /** Host env captured from the current shell so the service sees the same\n * CODEX_HOME / CLAUDE_CONFIG_DIR the user installed under. */\n env: Record<string, string>\n}\n\nexport function planForTest(opts: ServiceOpts): Plan {\n return plan(opts)\n}\n\nfunction serviceValue(name: string, value: string): string {\n // Every supported service format is line-oriented; CR/LF/NUL would either\n // make an invalid definition or inject a new directive/script statement.\n if (/[\\0\\r\\n]/.test(value)) {\n throw new Error(`invalid control character in service ${name}`)\n }\n return value\n}\n\nfunction serviceLabel(value: string): string {\n if (!/^[A-Za-z0-9_.-]+$/.test(value)) {\n throw new Error(`invalid service label: ${value}`)\n }\n return value\n}\n\nfunction transientPathEntry(value: string): boolean {\n const normalized = value.replace(/\\\\/g, '/')\n return (\n /\\/node_modules\\/\\.bin\\/?$/i.test(normalized) ||\n /\\/node_modules\\/npm\\/node_modules\\/@npmcli\\/run-script\\/lib\\/node-gyp-bin\\/?$/i.test(normalized) ||\n /\\/\\.[^/]+\\/tmp\\//i.test(normalized)\n )\n}\n\n/** npm/NPX and agent shells prepend disposable directories to PATH. Capturing\n * those verbatim makes every later doctor run call a healthy service stale.\n * Keep real user paths, canonicalize version-manager symlinks, and anchor the\n * service to the Node installation that actually built its command plan. */\nexport function stableServicePath(\n value: string,\n nodePath: string = process.execPath,\n): string {\n const entries = [path.dirname(nodePath), ...value.split(path.delimiter)]\n const seen = new Set<string>()\n const stable: string[] = []\n for (const raw of entries) {\n const trimmed = raw.trim()\n if (!trimmed || transientPathEntry(trimmed)) continue\n let resolved = trimmed\n try {\n resolved = fs.realpathSync(trimmed)\n } catch {\n // A currently absent user path can become valid later; preserve it.\n }\n const key = process.platform === 'win32' ? resolved.toLowerCase() : resolved\n if (seen.has(key)) continue\n seen.add(key)\n stable.push(resolved)\n }\n return stable.join(path.delimiter)\n}\n\nfunction plan(opts: ServiceOpts): Plan {\n const env: Record<string, string> = {}\n // CRITICAL: a systemd/launchd service does NOT inherit the login shell's\n // PATH, so it can't find `claude` / `codex` / `npx` (often in ~/.local/bin\n // or a version-manager dir). Capture the installer's PATH so the service\n // resolves the same binaries the user does. (Without this the daemon exits\n // \"claude CLI not found on PATH\" and restart-loops.)\n if (process.env['PATH']) {\n env['PATH'] = serviceValue(\n 'environment value',\n stableServicePath(process.env['PATH']),\n )\n }\n // Whatever host env the integration says its adapter needs.\n for (const [k, v] of Object.entries(opts.env ?? {})) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) throw new Error(`invalid service environment key: ${k}`)\n if (typeof v === 'string' && v.length > 0) {\n env[k] = serviceValue(\n 'environment value',\n k === 'PATH' ? stableServicePath(v) : v,\n )\n }\n }\n return {\n label: serviceLabel(opts.label),\n node: serviceValue('Node path', process.execPath),\n bin: serviceValue('entry path', path.resolve(opts.entry)),\n home: serviceValue('home path', path.resolve(opts.home)),\n env,\n }\n}\n\nexport type ServiceCommandRunner = (cmd: string, args: string[]) => { ok: boolean; out: string }\n\nfunction runReal(cmd: string, args: string[]): { ok: boolean; out: string } {\n const r = spawnCommandSync(cmd, args, { encoding: 'utf-8' })\n const out = [\n typeof r.stdout === 'string' ? r.stdout : '',\n typeof r.stderr === 'string' ? r.stderr : '',\n r.error?.message ?? '',\n ]\n .filter((part) => part.length > 0)\n .join('\\n')\n .trim()\n return {\n ok: !r.error && r.status === 0,\n out,\n }\n}\n\nlet commandRunner: ServiceCommandRunner = runReal\n\n/**\n * Tests only: answer `launchctl` / `systemctl` / `loginctl` with a fake, so a\n * test can exercise the ownership guard without reaching the real service\n * manager. `null` restores the real one.\n */\nexport function setServiceCommandRunnerForTests(runner: ServiceCommandRunner | null): void {\n commandRunner = runner ?? runReal\n}\n\nfunction run(cmd: string, args: string[]): { ok: boolean; out: string } {\n return commandRunner(cmd, args)\n}\n\n/**\n * Write the unit file but do NOT hand it to the OS service manager.\n *\n * `HOME` sandboxes where the unit file lands, but it does not sandbox\n * `launchctl` or `systemctl` — those always address the real user's domain. So\n * a test that exercises `daemon install` registers a REAL service on the\n * developer's machine, pointed at a temp directory that is about to be deleted.\n * That happened, and it left two loaded launchd jobs behind.\n *\n * With this set, everything up to registration still runs and can be asserted\n * on; only the escaping side effect is skipped.\n */\nfunction registrationSkipped(): boolean {\n const v = process.env['AGENTCHAT_SERVICE_DRY_RUN']\n return v !== undefined && v !== '' && v !== '0'\n}\n\n// ─── which identity home a service serves ────────────────────────────────────\n\n/** The argument after `--home` in an argument list, or null. */\nfunction homeFromArgs(args: readonly string[]): string | null {\n const i = args.indexOf('--home')\n const next = i >= 0 ? args[i + 1] : undefined\n return next !== undefined && next.length > 0 ? next : null\n}\n\nfunction xmlUnescape(value: string): string {\n return value\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&quot;/g, '\"')\n .replace(/&apos;/g, \"'\")\n .replace(/&amp;/g, '&')\n}\n\n/** Split a systemd command line into words, undoing `systemdQuote`. */\nfunction systemdWords(line: string): string[] {\n const words: string[] = []\n let i = 0\n while (i < line.length) {\n while (i < line.length && /\\s/.test(line[i]!)) i += 1\n if (i >= line.length) break\n let word = ''\n if (line[i] === '\"') {\n i += 1\n while (i < line.length && line[i] !== '\"') {\n if (line[i] === '\\\\' && i + 1 < line.length) {\n const c = line[i + 1]!\n word += c === 'n' ? '\\n' : c === 'r' ? '\\r' : c === 't' ? '\\t' : c\n i += 2\n } else {\n word += line[i]\n i += 1\n }\n }\n i += 1 // closing quote\n } else {\n while (i < line.length && !/\\s/.test(line[i]!)) {\n word += line[i]\n i += 1\n }\n }\n words.push(word.replace(/\\$\\$/g, '$').replace(/%%/g, '%'))\n }\n return words\n}\n\n/**\n * The identity home a service definition serves: the `--home` argument of\n * its command. `plist` — a launchd plist (ProgramArguments); `launchctl` —\n * `launchctl print` or `launchctl list <label>` output (one argument per\n * line); `systemd` — a unit file (ExecStart). Null when there is none.\n */\nexport function parseServiceHome(text: string, format: 'plist' | 'launchctl' | 'systemd'): string | null {\n if (format === 'plist') {\n const array = /<key>ProgramArguments<\\/key>\\s*<array>([\\s\\S]*?)<\\/array>/.exec(text)?.[1]\n if (array === undefined) return null\n const args = [...array.matchAll(/<string>([\\s\\S]*?)<\\/string>/g)].map((m) => xmlUnescape(m[1] ?? ''))\n return homeFromArgs(args)\n }\n if (format === 'launchctl') {\n const args = text\n .split(/\\r?\\n/)\n .map((l) => l.trim().replace(/;$/, '').replace(/^\"(.*)\"$/, '$1'))\n return homeFromArgs(args)\n }\n const exec = text.split(/\\r?\\n/).find((l) => l.startsWith('ExecStart='))\n return exec === undefined ? null : homeFromArgs(systemdWords(exec.slice('ExecStart='.length)))\n}\n\nfunction canonicalPath(p: string): string {\n const resolved = path.resolve(p)\n try {\n return fs.realpathSync(resolved)\n } catch {\n return resolved\n }\n}\n\nfunction sameHome(a: string, b: string): boolean {\n const x = canonicalPath(a)\n const y = canonicalPath(b)\n return process.platform === 'win32' ? x.toLowerCase() === y.toLowerCase() : x === y\n}\n\n/** One place a service under a label is defined: the file at its path, or the job the manager has loaded. */\ninterface ServiceSighting {\n /** Human description, for messages. */\n where: string\n /** The `--home` it serves; null when it could not be read. */\n home: string | null\n /** A loaded job (as opposed to a file on disk). */\n loaded: boolean\n}\n\nfunction launchdSightings(label: string): ServiceSighting[] {\n const out: ServiceSighting[] = []\n const plistPath = launchdPlistPath(label)\n if (fs.existsSync(plistPath)) {\n let text = ''\n try {\n text = fs.readFileSync(plistPath, 'utf-8')\n } catch {\n /* unreadable: treated as unknown below */\n }\n out.push({ where: plistPath, home: parseServiceHome(text, 'plist'), loaded: false })\n }\n if (!registrationSkipped()) {\n const fullLabel = launchdLabel(label)\n const uid = typeof process.getuid === 'function' ? process.getuid() : os.userInfo().uid\n const printed = run('launchctl', ['print', `gui/${uid}/${fullLabel}`])\n const listed = printed.ok ? null : run('launchctl', ['list', fullLabel])\n if (printed.ok || listed?.ok === true) {\n const text = printed.ok ? printed.out : (listed?.out ?? '')\n let home = parseServiceHome(text, 'launchctl')\n if (home === null) {\n // Fall back to the plist the job was loaded from (`path = …`).\n const loadedFrom = /^\\s*path = (.+)$/m.exec(text)?.[1]?.trim()\n if (loadedFrom !== undefined) {\n try {\n home = parseServiceHome(fs.readFileSync(loadedFrom, 'utf-8'), 'plist')\n } catch {\n /* stays unknown */\n }\n }\n }\n out.push({ where: `the loaded launchd job ${fullLabel}`, home, loaded: true })\n }\n }\n return out\n}\n\nfunction systemdSightings(label: string): ServiceSighting[] {\n const out: ServiceSighting[] = []\n const unitPath = systemdUnitPath(label)\n if (fs.existsSync(unitPath)) {\n let text = ''\n try {\n text = fs.readFileSync(unitPath, 'utf-8')\n } catch {\n /* unknown */\n }\n out.push({ where: unitPath, home: parseServiceHome(text, 'systemd'), loaded: false })\n }\n if (!registrationSkipped()) {\n const shown = run('systemctl', ['--user', 'show', label, '-p', 'LoadState', '-p', 'FragmentPath'])\n if (shown.ok) {\n const props = new Map(\n shown.out.split(/\\r?\\n/).map((l) => {\n const eq = l.indexOf('=')\n return [eq < 0 ? l : l.slice(0, eq), eq < 0 ? '' : l.slice(eq + 1)] as const\n }),\n )\n if (props.get('LoadState') === 'loaded') {\n const fragment = props.get('FragmentPath') ?? ''\n let home: string | null = null\n try {\n if (fragment) home = parseServiceHome(fs.readFileSync(fragment, 'utf-8'), 'systemd')\n } catch {\n /* unknown */\n }\n out.push({ where: `the loaded systemd unit ${label}${fragment ? ` (${fragment})` : ''}`, home, loaded: true })\n }\n }\n }\n return out\n}\n\nfunction sightings(label: string): ServiceSighting[] {\n if (winMode()) return [] // see assertServesHome\n if (serviceHostOs() === 'linux') return systemdSightings(label)\n if (serviceHostOs() === 'darwin') return launchdSightings(label)\n return []\n}\n\n/**\n * Refuse to `action` (stop, replace, remove) the service under `label` unless\n * everything defined under it serves `home`. A loaded job whose home cannot be\n * read is refused too: under the plain label that is exactly the job another\n * config (another HOME, the default config dir) installed. A definition FILE\n * at this label's own path with no readable `--home` is not ours to protect —\n * install overwrites it and uninstall removes it.\n *\n * Windows Startup launchers are keyed by HOME and label together, so the\n * files under one label can only belong to one identity home; no read there.\n */\nfunction assertServesHome(label: string, home: string, action: string): void {\n for (const s of sightings(label)) {\n if (s.home === null) {\n if (!s.loaded) continue\n throw new Error(\n `refusing to ${action} ${s.where}: it is loaded under this config's label but which identity home it serves could not be read. If it is yours, remove it by hand (launchctl remove / systemctl --user disable --now) and retry.`,\n )\n }\n if (!sameHome(s.home, home)) {\n throw new Error(\n `refusing to ${action} ${s.where}: it serves ${s.home}, not this config's identity home ${home}. It belongs to another configuration of this integration (another HOME or config directory) — run the command from that configuration. In a sandbox, set AGENTCHAT_SERVICE_DRY_RUN=1.`,\n )\n }\n }\n}\n\n/** Does anything under `label` serve `home`? (For retiring a superseded label.) */\nfunction servesHome(label: string, home: string): boolean {\n return sightings(label).some((s) => s.home !== null && sameHome(s.home, home))\n}\n\n// ─── systemd (Linux) ─────────────────────────────────────────────────────────\n\nfunction systemdUnitPath(label: string): string {\n return path.join(os.homedir(), '.config', 'systemd', 'user', `${label}.service`)\n}\n\n/** Quote one systemd command/environment word, including specifier escaping. */\nexport function systemdQuote(value: string): string {\n return (\n '\"' +\n value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\t/g, '\\\\t')\n .replace(/\"/g, '\\\\\"')\n // In a JS replacement string `$$` emits one literal dollar, so four\n // dollars are required to produce systemd's literal-dollar escape `$$`.\n .replace(/\\$/g, '$$$$')\n .replace(/%/g, '%%') +\n '\"'\n )\n}\n\nexport function systemdUnit(p: Plan): string {\n const envLines = Object.entries(p.env)\n .map(([k, v]) => `Environment=${systemdQuote(`${k}=${v}`)}`)\n .join('\\n')\n return [\n '[Unit]',\n `Description=AgentChat always-on daemon (${p.label})`,\n 'After=network-online.target',\n 'Wants=network-online.target',\n '',\n '[Service]',\n 'Type=simple',\n `ExecStart=${systemdQuote(p.node)} ${systemdQuote(p.bin)} --home ${systemdQuote(p.home)}`,\n ...(envLines ? [envLines] : []),\n 'Restart=on-failure',\n 'RestartSec=5',\n '',\n '[Install]',\n 'WantedBy=default.target',\n '',\n ].join('\\n')\n}\n\nfunction installSystemd(p: Plan): void {\n assertServesHome(p.label, p.home, 'replace')\n const unitPath = systemdUnitPath(p.label)\n fs.mkdirSync(path.dirname(unitPath), { recursive: true })\n atomicWriteFile(unitPath, systemdUnit(p), 0o600)\n log.info(`wrote ${unitPath}`)\n if (registrationSkipped()) return\n run('systemctl', ['--user', 'daemon-reload'])\n // enable-linger keeps user services running with no active login (VPS).\n const linger = run('loginctl', ['enable-linger', os.userInfo().username])\n if (!linger.ok) {\n log.warn(`could not enable-linger (service won't survive logout until you run: sudo loginctl enable-linger ${os.userInfo().username})`)\n }\n const enabled = run('systemctl', ['--user', 'enable', p.label])\n if (!enabled.ok) throw new Error(`systemctl enable failed: ${enabled.out}`)\n // `enable --now` leaves an already-running unit on the old bundle, so an\n // upgrade silently kept the previous daemon until the next boot. `restart`\n // starts a stopped unit and restarts a running one: either way the unit\n // runs the bundle this install just wrote.\n const started = run('systemctl', ['--user', 'restart', p.label])\n if (!started.ok) throw new Error(`systemctl restart failed: ${started.out}`)\n log.info(`service ${p.label} enabled + (re)started`)\n}\n\nfunction uninstallSystemd(label: string, home: string): void {\n assertServesHome(label, home, 'remove')\n if (!registrationSkipped()) {\n const disabled = run('systemctl', ['--user', 'disable', '--now', label])\n if (!disabled.ok) {\n const active = run('systemctl', ['--user', 'is-active', label])\n const state = (active.out.split(/\\r?\\n/, 1)[0] ?? '').trim().toLowerCase()\n // systemctl intentionally exits non-zero for these stopped/not-present\n // states. Anything else is ambiguous, so preserve the unit and daemon\n // bundle rather than stranding a loaded restart policy.\n if (!['inactive', 'failed', 'unknown'].includes(state)) {\n throw new Error(\n `could not stop systemd service ${label}: ${disabled.out || active.out || 'unknown error'}`,\n )\n }\n }\n }\n const unitPath = systemdUnitPath(label)\n if (fs.existsSync(unitPath)) fs.rmSync(unitPath)\n if (!registrationSkipped()) {\n const reload = run('systemctl', ['--user', 'daemon-reload'])\n if (!reload.ok) log.warn(`systemctl daemon-reload failed after uninstall: ${reload.out}`)\n }\n log.info(`service ${label} removed`)\n}\n\nfunction statusSystemd(label: string, home: string): string {\n if (registrationSkipped()) return dryRunStatus(`systemd ${label}`, systemdUnitPath(label))\n const active = run('systemctl', ['--user', 'is-active', label]).out || 'unknown'\n const enabled = run('systemctl', ['--user', 'is-enabled', label]).out || 'unknown'\n return `systemd ${label}: ${active} (${enabled})${foreignNote(label, home)}`\n}\n\n/** Status under AGENTCHAT_SERVICE_DRY_RUN: the service manager is not consulted at all. */\nfunction dryRunStatus(name: string, definitionPath: string): string {\n return `${name}: not queried (AGENTCHAT_SERVICE_DRY_RUN) — definition ${fs.existsSync(definitionPath) ? `written at ${definitionPath}` : 'not written'}`\n}\n\n/** `, but it serves <other home> …` when the loaded job under this label is another config's. */\nfunction foreignNote(label: string, home: string): string {\n const loaded = sightings(label).find((s) => s.loaded)\n if (loaded === undefined || loaded.home === null || sameHome(loaded.home, home)) return ''\n return ` — but it serves ${loaded.home}, not this config (${home})`\n}\n\n// ─── launchd (macOS) ─────────────────────────────────────────────────────────\n\nfunction launchdPlistPath(label: string): string {\n return path.join(os.homedir(), 'Library', 'LaunchAgents', `${launchdLabel(label)}.plist`)\n}\nconst launchdLabel = (label: string): string => `me.agentchat.${label}`\n\nexport function xmlEscape(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;')\n}\n\nexport function launchdPlist(p: Plan): string {\n const args = [p.node, p.bin, '--home', p.home]\n const argXml = args.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\\n')\n const envXml = Object.entries(p.env)\n .map(([k, v]) => ` <key>${xmlEscape(k)}</key><string>${xmlEscape(v)}</string>`)\n .join('\\n')\n const logPath = path.join(p.home, 'daemon.log')\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\"><dict>',\n ` <key>Label</key><string>${xmlEscape(launchdLabel(p.label))}</string>`,\n ' <key>ProgramArguments</key><array>',\n argXml,\n ' </array>',\n ...(envXml ? [' <key>EnvironmentVariables</key><dict>', envXml, ' </dict>'] : []),\n ' <key>RunAtLoad</key><true/>',\n ' <key>KeepAlive</key><true/>',\n // On `launchctl unload`/`stop` launchd sends SIGTERM and SIGKILLs after\n // this many seconds. The daemon uses the window to SIGTERM a headless run\n // in flight and wait up to 10 s for it (run.ts SHUTDOWN_GRACE_MS), so the\n // value is above that and below launchd's 20 s default, which would let a\n // slow stop look like a hang.\n ' <key>ExitTimeOut</key><integer>15</integer>',\n ` <key>StandardErrorPath</key><string>${xmlEscape(logPath)}</string>`,\n ` <key>StandardOutPath</key><string>${xmlEscape(logPath)}</string>`,\n '</dict></plist>',\n '',\n ].join('\\n')\n}\n\nfunction installLaunchd(p: Plan): void {\n // `launchctl unload <plist>` below unloads by the plist's Label — whatever\n // job holds that label, whichever HOME it was installed from.\n assertServesHome(p.label, p.home, 'replace')\n const plistPath = launchdPlistPath(p.label)\n fs.mkdirSync(path.dirname(plistPath), { recursive: true })\n atomicWriteFile(plistPath, launchdPlist(p), 0o600)\n log.info(`wrote ${plistPath}`)\n if (registrationSkipped()) return\n run('launchctl', ['unload', plistPath]) // idempotent: clear a prior load\n const loaded = run('launchctl', ['load', '-w', plistPath])\n if (!loaded.ok) throw new Error(`launchctl load failed: ${loaded.out}`)\n log.info(`service ${launchdLabel(p.label)} loaded + started`)\n}\n\nfunction uninstallLaunchd(label: string, home: string): void {\n assertServesHome(label, home, 'remove')\n const plistPath = launchdPlistPath(label)\n if (!registrationSkipped()) {\n run('launchctl', ['unload', '-w', plistPath])\n let loaded = run('launchctl', ['list', launchdLabel(label)])\n if (loaded.ok) {\n // A missing/stale plist can leave a loaded job that unload-by-path\n // cannot address. Remove by label, then prove it is gone.\n run('launchctl', ['remove', launchdLabel(label)])\n loaded = run('launchctl', ['list', launchdLabel(label)])\n }\n if (loaded.ok) {\n throw new Error(`could not stop launchd service ${launchdLabel(label)}`)\n }\n if (\n loaded.out &&\n !/could not find service|not found|no such process|unknown service/i.test(loaded.out)\n ) {\n throw new Error(\n `could not verify launchd service removal for ${launchdLabel(label)}: ${loaded.out}`,\n )\n }\n }\n if (fs.existsSync(plistPath)) fs.rmSync(plistPath)\n log.info(`service ${launchdLabel(label)} removed`)\n}\n\nfunction statusLaunchd(label: string, home: string): string {\n const fullLabel = launchdLabel(label)\n if (registrationSkipped()) return dryRunStatus(`launchd ${fullLabel}`, launchdPlistPath(label))\n const uid = typeof process.getuid === 'function' ? process.getuid() : os.userInfo().uid\n const modern = run('launchctl', ['print', `gui/${uid}/${fullLabel}`])\n const loaded = modern.ok || run('launchctl', ['list', fullLabel]).ok\n return `launchd ${fullLabel}: ${loaded ? `loaded${foreignNote(label, home)}` : 'not loaded'}`\n}\n\n// ─── Windows + WSL (Startup-folder launcher, no admin) ───────────────────────\n//\n// Windows has no systemd/launchd. For \"runs whenever you're logged in\" — the\n// consumer case, no admin needed — we drop a hidden, restart-on-exit VBScript\n// into the user's Startup folder. Two hosts land here:\n// * native Windows → the .vbs runs `node <entry> --home <home>` directly.\n// * WSL2 → the daemon lives in Linux, but the WSL VM shuts down when\n// the last terminal closes, so a Linux service can't stay\n// up. Instead the launcher goes in the WINDOWS Startup\n// folder (reached from WSL via /mnt/c) and runs\n// `wsl.exe -e bash <script>`, which boots the VM at Windows\n// login and runs the daemon inside it.\n// A \"master\" copy in the user's ~/.agentchat/daemon (whatever identity home the\n// service serves — the label carries that) is the installed-marker; the copy in\n// Startup is the enabled state (disable removes it, keeps the master — same\n// toggle semantics as systemd enable/disable).\n//\n// The file mechanics + generators are unit-tested and verified on a real\n// windows-latest CI runner. The live runtime (hidden loop, WSL boot, process\n// kill) still needs a real user machine — called out in the release notes.\n\nexport function isWslFromVersion(version: string): boolean {\n return /microsoft|wsl/i.test(version)\n}\nfunction isWsl(): boolean {\n if (process.platform !== 'linux') return false\n try {\n return isWslFromVersion(fs.readFileSync('/proc/version', 'utf-8'))\n } catch {\n return false\n }\n}\ntype WinMode = 'win32' | 'wsl'\n\n/** The host as service management sees it. `wsl` is Linux under WSL2 (Windows Startup launcher, not systemd). */\nexport type ServiceHostOs = 'linux' | 'darwin' | 'win32' | 'wsl' | 'other'\nlet hostOsOverride: ServiceHostOs | null = null\n\n/**\n * Tests only: pretend to be another host so the Linux and Windows command\n * sequences can be pinned on any CI runner. Paths and the real service\n * manager are never reached: pair it with a fake command runner and\n * `AGENTCHATD_SERVICE_NO_START=1`.\n */\nexport function setServiceHostOsForTests(hostOs: ServiceHostOs | null): void {\n hostOsOverride = hostOs\n}\n\nfunction serviceHostOs(): ServiceHostOs {\n if (hostOsOverride !== null) return hostOsOverride\n if (process.platform === 'win32') return 'win32'\n if (process.platform === 'linux') return isWsl() ? 'wsl' : 'linux'\n if (process.platform === 'darwin') return 'darwin'\n return 'other'\n}\n\nfunction winMode(): WinMode | null {\n const hostOs = serviceHostOs()\n return hostOs === 'win32' || hostOs === 'wsl' ? hostOs : null\n}\n\nfunction winMasterDir(): string {\n return path.join(os.homedir(), '.agentchat', 'daemon')\n}\nfunction winStartupDir(mode: WinMode): string {\n if (mode === 'win32') {\n return path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')\n }\n // WSL: translate the Windows %APPDATA% into a /mnt/c path.\n const appdata = run('cmd.exe', ['/c', 'echo %APPDATA%']).out.split(/\\r?\\n/).pop()?.trim() ?? ''\n const base = run('wslpath', ['-u', appdata]).out.trim()\n if (!base) throw new Error('could not locate the Windows Startup folder from WSL (is /mnt/c mounted?)')\n return path.join(base, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')\n}\n\nconst vbsEscape = (s: string): string => s.replace(/\"/g, '\"\"')\nconst shQuote = (s: string): string => `'${s.replace(/'/g, `'\\\\''`)}'`\n\n/** Hidden, restart-on-exit VBScript launcher. `command` is the full command\n * line; `env` is set on the launcher process (native Windows only). */\nexport function launcherVbs(command: string, env: Record<string, string>): string {\n const envLines = Object.entries(env).map(\n ([k, v]) => `sh.Environment(\"Process\").Item(\"${vbsEscape(k)}\") = \"${vbsEscape(v)}\"`,\n )\n return (\n [\n \"' AgentChat always-on launcher — runs hidden, restarts on exit.\",\n 'Set sh = CreateObject(\"WScript.Shell\")',\n ...envLines,\n 'Do',\n ` sh.Run \"${vbsEscape(command)}\", 0, True`,\n ' WScript.Sleep 5000',\n 'Loop',\n ].join('\\r\\n') + '\\r\\n'\n )\n}\n\n/** Native-Windows launch command. */\nexport function winCommandNative(p: Plan): string {\n return `\"${p.node}\" \"${p.bin}\" --home \"${p.home}\"`\n}\n\n/** The bash script WSL runs — a login-shell env plus the daemon. */\nexport function wslScriptContent(p: Plan): string {\n const exports = Object.entries(p.env).map(([k, v]) => `export ${k}=${shQuote(v)}`)\n return (\n ['#!/bin/bash', ...exports, `exec ${shQuote(p.node)} ${shQuote(p.bin)} --home ${shQuote(p.home)}`].join(\n '\\n',\n ) + '\\n'\n )\n}\n\nfunction startDetached(cmd: string, args: string[]): void {\n // Escape hatch for tests/headless installs: write the Startup entry but don't\n // actually launch the loop now (it still starts at next login).\n if (process.env['AGENTCHATD_SERVICE_NO_START'] === '1') return\n try {\n spawnCommand(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref()\n } catch (err) {\n log.warn(`could not start the launcher now (it starts at next login): ${String(err)}`)\n }\n}\nfunction winPathFromWsl(linuxPath: string): string {\n return run('wslpath', ['-w', linuxPath]).out.trim() || linuxPath\n}\nfunction killLauncher(label: string, mode: WinMode): { ok: boolean; out: string } {\n // Best-effort: stop the running wscript launcher, matched by our .vbs name.\n const ps = `Get-CimInstance Win32_Process -Filter \"Name='wscript.exe'\" | Where-Object { $_.CommandLine -like '*${label}.vbs*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }`\n return run(mode === 'win32' ? 'powershell' : 'powershell.exe', ['-NoProfile', '-Command', ps])\n}\n\n/**\n * The pid in the daemon's leader lock, or null: the daemon the Startup\n * launcher is keeping alive right now. The lock's shared parser (its first\n * line is the bare pid, in the lease format and in a lock from before it),\n * and only while its holder is really there (`holderLive`): a lock left by a\n * daemon that died — its pid perhaps reused by an unrelated process — names\n * nothing to stop.\n */\nexport function lockedDaemonPid(home: string): number | null {\n const file = path.join(home, DAEMON_LOCK_FILE)\n try {\n const holder = parseLease(fs.readFileSync(file, 'utf-8'))\n if (holder === null || !Number.isInteger(holder.pid) || holder.pid <= 0) return null\n return holderLive(holder, { mtimeMs: fs.statSync(file).mtimeMs }) ? holder.pid : null\n } catch {\n return null\n }\n}\n\n/**\n * Before a new launcher starts: stop the one already running and the daemon\n * it spawned. The Startup launcher restarts its daemon on exit, so a second\n * launcher started beside it would start a second daemon that loses the\n * leader lock, exits, and is restarted every five seconds — forever, on the\n * old bundle. Stop the launcher first (by its .vbs name), then the daemon by\n * the pid in its leader lock, so the new launcher's daemon takes the lock.\n * Best effort: a daemon that is not running leaves nothing to stop.\n */\nfunction stopRunningWindowsDaemon(label: string, mode: WinMode, home: string): void {\n const killed = killLauncher(label, mode)\n if (!killed.ok) log.warn(`could not stop a running ${label} launcher (${killed.out || 'unknown error'}) — continuing`)\n const pid = lockedDaemonPid(home)\n if (pid === null) return\n const stopped = mode === 'win32' ? run('taskkill', ['/PID', String(pid), '/T', '/F']) : run('kill', ['-TERM', String(pid)])\n if (stopped.ok) log.info(`stopped the running daemon (pid ${pid}) so the new bundle starts`)\n else log.debug(`no running daemon at pid ${pid} to stop (${stopped.out || 'already gone'})`)\n}\n\nfunction installWindows(p: Plan, mode: WinMode): void {\n const master = winMasterDir()\n fs.mkdirSync(master, { recursive: true })\n const masterVbs = path.join(master, `${p.label}.vbs`)\n if (mode === 'win32') {\n atomicWriteFile(masterVbs, launcherVbs(winCommandNative(p), p.env), 0o600)\n } else {\n const scriptPath = path.join(master, `${p.label}.sh`)\n atomicWriteFile(scriptPath, wslScriptContent(p), 0o700)\n const distro = serviceValue('WSL distro', process.env['WSL_DISTRO_NAME'] ?? '')\n if (!distro) throw new Error('WSL_DISTRO_NAME is not set — cannot target the right WSL distro')\n atomicWriteFile(\n masterVbs,\n launcherVbs(`wsl.exe -d \"${distro}\" -e bash \"${scriptPath}\"`, {}),\n 0o600,\n )\n }\n log.info(`wrote ${masterVbs}`)\n enableWindows(p.label, mode, p.home)\n log.info(`service ${p.label} installed (starts at login)`)\n}\nfunction enableWindows(label: string, mode: WinMode, home: string): void {\n const masterVbs = path.join(winMasterDir(), `${label}.vbs`)\n if (!fs.existsSync(masterVbs)) throw new Error(`no ${label} daemon installed — run install first`)\n const startup = winStartupDir(mode)\n fs.mkdirSync(startup, { recursive: true })\n const startupVbs = path.join(startup, `${label}.vbs`)\n fs.copyFileSync(masterVbs, startupVbs)\n if (registrationSkipped()) return\n stopRunningWindowsDaemon(label, mode, home)\n if (mode === 'win32') startDetached('wscript.exe', [startupVbs])\n else startDetached('cmd.exe', ['/c', 'start', '', '/b', 'wscript.exe', winPathFromWsl(startupVbs)])\n}\nfunction disableWindows(label: string, mode: WinMode): void {\n const startupVbs = path.join(winStartupDir(mode), `${label}.vbs`)\n if (fs.existsSync(startupVbs)) fs.rmSync(startupVbs)\n if (!registrationSkipped()) {\n const killed = killLauncher(label, mode)\n if (!killed.ok) {\n throw new Error(`could not stop Windows launcher ${label}: ${killed.out || 'unknown error'}`)\n }\n }\n}\nfunction uninstallWindows(label: string, mode: WinMode): void {\n // If stopping cannot be verified, preserve the master scripts and durable\n // daemon. The caller can retry without leaving a hidden restart loop pointed\n // at a deleted executable.\n disableWindows(label, mode)\n for (const f of [`${label}.vbs`, `${label}.sh`]) {\n const m = path.join(winMasterDir(), f)\n if (fs.existsSync(m)) fs.rmSync(m)\n }\n}\nfunction statusWindows(label: string, mode: WinMode): string {\n const installed = fs.existsSync(path.join(winMasterDir(), `${label}.vbs`))\n let enabled = false\n try {\n enabled = fs.existsSync(path.join(winStartupDir(mode), `${label}.vbs`))\n } catch {\n /* startup dir unresolved */\n }\n const host = mode === 'wsl' ? 'wsl' : 'windows'\n return `${host} ${label}: ${installed ? (enabled ? 'enabled' : 'installed (disabled)') : 'not installed'}`\n}\n\n// ─── platform dispatch ───────────────────────────────────────────────────────\n\n/**\n * Remove each superseded service that serves this home (a relocated home\n * installed under the plain label before labels were per home); leave one\n * serving another home alone.\n */\nfunction retireSuperseded(opts: ServiceRef, label: string): void {\n for (const raw of opts.supersedes ?? []) {\n const old = serviceLabel(raw)\n if (old === label || winMode() || !servesHome(old, opts.home)) continue\n log.info(`retiring the service ${old}: this identity home is now served by ${label}`)\n if (serviceHostOs() === 'linux') uninstallSystemd(old, opts.home)\n else if (serviceHostOs() === 'darwin') uninstallLaunchd(old, opts.home)\n }\n}\n\nexport function installService(opts: ServiceOpts): void {\n const p = plan(opts)\n if (!p.bin) throw new Error('no daemon entrypoint given (ServiceOpts.entry)')\n retireSuperseded(opts, p.label)\n const wm = winMode()\n if (wm) return installWindows(p, wm)\n if (serviceHostOs() === 'linux') return installSystemd(p) // native Linux (not WSL)\n if (serviceHostOs() === 'darwin') return installLaunchd(p)\n throw new Error(`service install is not supported on ${process.platform} — run \\`agentchatd start\\` under your own supervisor`)\n}\n\nexport function uninstallService(opts: ServiceRef): void {\n const label = serviceLabel(opts.label)\n const home = path.resolve(opts.home)\n const wm = winMode()\n if (wm) return uninstallWindows(label, wm)\n if (serviceHostOs() === 'linux') {\n uninstallSystemd(label, home)\n retireSuperseded({ ...opts, home }, label)\n return\n }\n if (serviceHostOs() === 'darwin') {\n uninstallLaunchd(label, home)\n retireSuperseded({ ...opts, home }, label)\n return\n }\n throw new Error(`service uninstall is not supported on ${process.platform}`)\n}\n\nexport function serviceStatus(opts: ServiceRef): string {\n const label = serviceLabel(opts.label)\n const home = path.resolve(opts.home)\n const wm = winMode()\n if (wm) return statusWindows(label, wm)\n if (serviceHostOs() === 'linux') return statusSystemd(label, home)\n if (serviceHostOs() === 'darwin') return statusLaunchd(label, home)\n return `service management not supported on ${process.platform}`\n}\n\n/** Pure on-disk check used by integration self-healing and doctor. */\nexport function serviceDefinitionCurrent(opts: ServiceOpts): boolean {\n try {\n const p = plan(opts)\n const wm = winMode()\n if (wm === 'win32') {\n const file = path.join(winMasterDir(), `${p.label}.vbs`)\n return fs.existsSync(file) && fs.readFileSync(file, 'utf-8') === launcherVbs(winCommandNative(p), p.env)\n }\n if (wm === 'wsl') {\n const script = path.join(winMasterDir(), `${p.label}.sh`)\n const vbs = path.join(winMasterDir(), `${p.label}.vbs`)\n const distro = serviceValue('WSL distro', process.env['WSL_DISTRO_NAME'] ?? '')\n if (!distro) return false\n return (\n fs.existsSync(script) &&\n fs.existsSync(vbs) &&\n fs.readFileSync(script, 'utf-8') === wslScriptContent(p) &&\n fs.readFileSync(vbs, 'utf-8') ===\n launcherVbs(`wsl.exe -d \"${distro}\" -e bash \"${script}\"`, {})\n )\n }\n if (serviceHostOs() === 'linux') {\n const file = systemdUnitPath(p.label)\n return fs.existsSync(file) && fs.readFileSync(file, 'utf-8') === systemdUnit(p)\n }\n if (serviceHostOs() === 'darwin') {\n const file = launchdPlistPath(p.label)\n return fs.existsSync(file) && fs.readFileSync(file, 'utf-8') === launchdPlist(p)\n }\n return false\n } catch {\n return false\n }\n}\n\n// ─── enable / disable (the away-replies opt-out) ─────────────────────────────\n//\n// Toggle the service's run-state WITHOUT uninstalling — so a user who wants\n// \"reply only while I'm in a session\" flips the daemon off, and back on later,\n// with one word. The unit/plist file stays on disk either way, so re-enabling\n// is instant. `install` already leaves it enabled (always-on by default);\n// these just turn that on and off after the fact.\n\nfunction unitInstalled(label: string): boolean {\n if (winMode()) return fs.existsSync(path.join(winMasterDir(), `${label}.vbs`))\n if (serviceHostOs() === 'linux') return fs.existsSync(systemdUnitPath(label))\n if (serviceHostOs() === 'darwin') return fs.existsSync(launchdPlistPath(label))\n return false\n}\n\nexport function serviceInstalled(opts: ServiceRef): boolean {\n return unitInstalled(serviceLabel(opts.label))\n}\n\nexport function disableService(opts: ServiceOpts): void {\n const label = serviceLabel(opts.label)\n if (!unitInstalled(label)) {\n throw new Error(`no ${opts.label} daemon installed — nothing to disable (run install first)`)\n }\n const wm = winMode()\n if (wm) {\n disableWindows(label, wm) // drop the Startup copy, keep the master\n } else if (serviceHostOs() === 'linux') {\n assertServesHome(label, path.resolve(opts.home), 'stop')\n // Stops it AND removes the start-on-boot link; the unit file stays.\n if (!registrationSkipped()) {\n const disabled = run('systemctl', ['--user', 'disable', '--now', label])\n if (!disabled.ok) throw new Error(`could not disable ${label}: ${disabled.out}`)\n }\n } else if (serviceHostOs() === 'darwin') {\n assertServesHome(label, path.resolve(opts.home), 'stop')\n if (!registrationSkipped()) {\n const disabled = run('launchctl', ['unload', launchdPlistPath(label)])\n if (!disabled.ok) throw new Error(`could not disable ${label}: ${disabled.out}`)\n }\n } else {\n throw new Error(`not supported on ${process.platform}`)\n }\n log.info(`daemon ${label} disabled — session-only until you re-enable`)\n}\n\nexport function enableService(opts: ServiceOpts): void {\n const label = serviceLabel(opts.label)\n if (!unitInstalled(label)) {\n throw new Error(`no ${opts.label} daemon installed — run install first`)\n }\n const wm = winMode()\n if (wm) {\n enableWindows(label, wm, path.resolve(opts.home)) // copy the master back into Startup + start now\n } else if (serviceHostOs() === 'linux') {\n if (!registrationSkipped()) {\n const enabled = run('systemctl', ['--user', 'enable', '--now', label])\n if (!enabled.ok) throw new Error(`could not enable ${label}: ${enabled.out}`)\n }\n } else if (serviceHostOs() === 'darwin') {\n if (!registrationSkipped()) {\n const enabled = run('launchctl', ['load', '-w', launchdPlistPath(label)])\n if (!enabled.ok) throw new Error(`could not enable ${label}: ${enabled.out}`)\n }\n } else {\n throw new Error(`not supported on ${process.platform}`)\n }\n log.info(`daemon ${label} enabled — always-on while this machine is up`)\n}\n"],"mappings":";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