@agentchatme/agent-core 0.3.1 → 0.4.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/version.ts","../src/identity/state.ts","../src/anchor/block.ts","../src/anchor/offer.ts","../src/integration/mcp-probe.ts","../src/identity/commands.ts","../src/identity/host-profile.ts","../src/daemon/service.ts"],"sourcesContent":["/** Published package version, kept in lockstep with package.json by tests. */\nexport const VERSION = '0.3.1'\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'\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. Same mechanism as the Hermes SOUL.md anchor and the OpenClaw\n// AGENTS.md anchor. The words are the server's; this module only fences them.\n//\n// This module knows how to edit a fenced block in a file. It does NOT know\n// WHICH file — that is the integration's business, because the file IS the\n// host. A shared function that picked the file itself is precisely what once\n// stamped one agent's handle into another agent's instruction file.\n//\n// Markers are shared verbatim across ALL AgentChat integrations — whichever\n// integration wrote last owns the block, and switching integrations overwrites\n// cleanly instead of duplicating. DO NOT change them without updating the\n// OpenClaw plugin (src/binding/agents-anchor.ts) and the Hermes plugin\n// (soul_anchor.py).\n\nexport const ANCHOR_START = '<!-- agentchat:start -->'\nexport const ANCHOR_END = '<!-- agentchat:end -->'\n\nconst LEGACY_ANCHOR_START = '<!-- agentchat-skill:start -->'\nconst LEGACY_ANCHOR_END = '<!-- agentchat-skill:end -->'\n\n/** The identity block: the served identity line, as fetched for this agent, between the markers. */\nexport function renderAnchorBlock(identityLine: string): string {\n const line = identityLine.trim()\n if (line.length === 0) throw new Error('renderAnchorBlock: the identity line is empty')\n return [ANCHOR_START, line, ANCHOR_END].join('\\n')\n}\n\nexport type AnchorAction = 'written' | 'removed' | 'noop'\n\n/**\n * Upsert `block` into the file at `filePath`, creating it if needed.\n *\n * Throws if `expectHandle` is given and does not appear in what was written —\n * a silently-wrong identity block is worse than a loud failure, because the\n * agent would spend every session announcing an address that isn't its own.\n */\nexport function writeAnchor(filePath: string, block: string, expectHandle?: string): AnchorAction {\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : ''\n fs.writeFileSync(filePath, upsertAnchorBlock(existing, block), 'utf-8')\n\n if (expectHandle !== undefined) {\n const verify = fs.readFileSync(filePath, 'utf-8')\n if (!verify.includes(`@${expectHandle}`)) {\n throw new Error(\n `writeAnchor: handle @${expectHandle} did not land in ${filePath} — remove the agentchat block manually and re-run.`,\n )\n }\n }\n return 'written'\n}\n\nexport function removeAnchorAt(filePath: string): AnchorAction {\n if (!fs.existsSync(filePath)) return 'noop'\n const existing = fs.readFileSync(filePath, 'utf-8')\n const next = stripAnchorBlock(existing)\n if (next === existing) return 'noop'\n fs.writeFileSync(filePath, next, 'utf-8')\n return 'removed'\n}\n\nexport function hasAnchorAt(filePath: string): boolean {\n if (!fs.existsSync(filePath)) return false\n return findBlock(fs.readFileSync(filePath, 'utf-8'), ANCHOR_START, ANCHOR_END) !== null\n}\n\n/** Whether the file's block is exactly the block for this served identity line. */\nexport function anchorIsCurrentAt(filePath: string, identityLine: string): boolean {\n if (!fs.existsSync(filePath)) return false\n const text = fs.readFileSync(filePath, 'utf-8')\n const block = findBlock(text, ANCHOR_START, ANCHOR_END)\n if (block === null) return false\n return text.slice(block.from, block.to) === renderAnchorBlock(identityLine)\n}\n\n// The served text (\"I am @handle on AgentChat\"), then the block releases\n// before the integration wrote (\"You are **@handle** on AgentChat\") so an\n// anchor from an older release is still recognised — and refreshed by\n// `doctor --fix`.\nconst IDENTITY_HANDLE_RE = /I am @([^\\s]+) on AgentChat/\nconst LEGACY_HANDLE_RE = /\\*\\*@([^*\\s]+)\\*\\*/\n\n/**\n * The handle a file's anchor block currently CLAIMS, or null if there is no\n * block. Lets an integration catch an anchor that disagrees with its own\n * credential — an agent told it is @a while authenticating as @b hands peers an\n * address that reaches someone else. Matched loosely precisely so a WRONG\n * value is still read back and reported rather than treated as \"no anchor\".\n */\nexport function readAnchorHandleAt(filePath: string): string | null {\n if (!fs.existsSync(filePath)) return null\n return readAnchorHandleFrom(fs.readFileSync(filePath, 'utf-8'))\n}\n\nexport function readAnchorHandleFrom(text: string): string | null {\n const block = findBlock(text, ANCHOR_START, ANCHOR_END)\n if (block === null) return null\n const inside = text.slice(block.from, block.to)\n const match = IDENTITY_HANDLE_RE.exec(inside) ?? LEGACY_HANDLE_RE.exec(inside)\n return match?.[1] ?? null\n}\n\n// Markers only count when they are a whole line — a marker quoted inside user\n// prose (\"the plugin uses <!-- agentchat:start --> fences\") must never be\n// treated as a fence, or the upsert would eat the user's content between the\n// quote and the real block.\nfunction lineAnchoredIndex(\n text: string,\n marker: string,\n fromIndex = 0,\n): { start: number; end: number } | null {\n let idx = text.indexOf(marker, fromIndex)\n while (idx >= 0) {\n const lineStart = text.lastIndexOf('\\n', idx - 1) + 1\n const lineEndRaw = text.indexOf('\\n', idx)\n const lineEnd = lineEndRaw === -1 ? text.length : lineEndRaw\n if (text.slice(lineStart, lineEnd).trim() === marker) {\n return { start: lineStart, end: lineEnd }\n }\n idx = text.indexOf(marker, idx + marker.length)\n }\n return null\n}\n\nfunction findBlock(\n text: string,\n startMarker: string,\n endMarker: string,\n): { from: number; to: number } | null {\n const start = lineAnchoredIndex(text, startMarker)\n if (start === null) return null\n const end = lineAnchoredIndex(text, endMarker, start.end)\n if (end === null) return null\n return { from: start.start, to: end.end }\n}\n\nexport function upsertAnchorBlock(existing: string, block: string): string {\n // Strip every existing block (unified AND legacy) first, then append the\n // fresh one — replacement and dedup in one motion, so a file that somehow\n // accumulated multiple blocks converges back to exactly one.\n const cleaned = stripAnchorBlock(existing)\n const trimmed = cleaned.replace(/\\n+$/, '')\n if (trimmed.length === 0) return block + '\\n'\n return trimmed + '\\n\\n' + block + '\\n'\n}\n\nexport function stripAnchorBlock(existing: string): string {\n const afterUnified = stripAllBlocks(existing, ANCHOR_START, ANCHOR_END)\n return stripAllBlocks(afterUnified, LEGACY_ANCHOR_START, LEGACY_ANCHOR_END)\n}\n\nfunction stripAllBlocks(existing: string, start: string, end: string): string {\n let text = existing\n // Bounded loop: each pass removes one block; a file can't hold more blocks\n // than lines.\n for (let i = 0; i < 10_000; i++) {\n const block = findBlock(text, start, end)\n if (block === null) return text\n const before = text.slice(0, block.from).replace(/\\n+$/, '')\n const after = text.slice(block.to).replace(/^\\n+/, '')\n if (before.length === 0 && after.length === 0) return ''\n if (before.length === 0) text = after.endsWith('\\n') ? after : after + '\\n'\n else if (after.length === 0) text = before + '\\n'\n else text = before + '\\n\\n' + after + (after.endsWith('\\n') ? '' : '\\n')\n }\n return text\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 `upsertAnchorBlock`, which strips every existing\n// block before writing, so registering REPLACES this with the identity block\n// and logout 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 */\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 'If they want a new account:',\n ' **Ask only one question per turn. Never ask for the email and handle in the same message.**',\n ' 1. Ask only: \"I need an email for verification and recovery. Which email should I use? After we choose my handle, AgentChat will send a 6-digit code there, and I’ll ask you to paste it here.\"',\n ' 2. After they answer, say: \"Now we need to choose an AgentChat username for me—my @handle, which other agents will use to reach me.\"',\n ' Explain the rules simply: \"Use 3–30 characters: lowercase letters, numbers, and hyphens. Start with a letter; no double or trailing hyphens.\"',\n ' If there is a concrete, relevant candidate, ask: \"How about @<candidate>?\" Otherwise ask: \"What username should I use? If you want, I can suggest one.\"',\n ` 3. Once there is an email and handle, run: ${invoke} register --email <email> --handle <handle>`,\n ' Registration is the authoritative availability check. Never promise availability before it succeeds.',\n ' If their handle is taken or invalid, ask only for another handle, keep the same email, and retry only after they choose or accept the replacement.',\n ' Never submit a handle the user has not chosen or accepted.',\n ' 4. Only after registration confirms the code was sent, say: \"AgentChat sent a 6-digit code to <email>. Paste it here and I’ll finish setup.\"',\n ` 5. Run: ${invoke} register --code <code>`,\n ' 6. On success, use the command’s exact handle and path: \"Done—I’m registered as @<handle>. The API key is stored at <credentials-path>.\"',\n '',\n `If they already have an account for this ${label} agent:`,\n ' **Ask one question per turn. Run the commands yourself.**',\n ' 1. Ask exactly: \"Give me the AgentChat API key for this account. If you no longer have it, I can help you recover the account.\"',\n ` 2. If they provide it, run: ${invoke} login --api-key <ac_…>`,\n ' On success, use the command’s exact handle and path: \"Done—I’m signed in as @<handle>. The API key is stored at <credentials-path>.\"',\n ' If login fails, say: \"That API key didn’t work. Please check it and send it again, or tell me if you need to recover the account.\"',\n ' 3. If they no longer have the key, ask exactly: \"I can recover the account. This will replace the old API key, so anything still using it will stop working. What email did you use for this AgentChat account?\"',\n ' 4. Then ask only: \"Which @handle is the account? One email can back several agents, so recovery needs both.\"',\n ` 5. Run: ${invoke} recover --handle <handle> --email <email>`,\n ' 6. Once recovery accepts the request, say: \"If @<handle> is registered with <email>, AgentChat sent a 6-digit recovery code to <email>. Paste it here and I’ll finish signing in.\"',\n ` 7. Run: ${invoke} recover --code <code>`,\n ' On success, use the command’s exact handle and path: \"Done—I recovered the account and signed in as @<handle>. The new API key is stored at <credentials-path>. The old key no longer works.\"',\n ' If the code fails, say: \"That code didn’t work. Check the 6 digits and paste it again.\"',\n ' 8. 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 { clientHeadersOf, type IntegrationClient } from '../client-identity.js'\n\n// ─── Is the hosted tool server reachable with this key? ─────────────────────\n//\n// `status` and `doctor` send ONE MCP `initialize` over Streamable HTTP with\n// the bearer key — the same first request a runtime makes on connect — and\n// read the answer. A `401` means the key does not authenticate; a transport\n// error means the endpoint is not reachable from here. Nothing else is called.\n// (The one request this package still makes outside the SDK: the SDK has no\n// MCP client, and this is a probe, not a tool call.)\n\nexport const HOSTED_MCP_PATH = '/mcp'\n\n/** The MCP protocol revision this probe speaks; the server answers with the one it serves. */\nconst MCP_PROTOCOL_VERSION = '2025-06-18'\n\nexport function hostedMcpUrl(apiBase: string): string {\n return `${apiBase.replace(/\\/+$/, '')}${HOSTED_MCP_PATH}`\n}\n\nexport interface McpProbeResult {\n readonly ok: boolean\n readonly status?: number\n readonly serverName?: string\n readonly serverVersion?: string\n readonly protocolVersion?: string\n readonly error?: string\n}\n\nexport async function probeHostedMcp(params: {\n apiKey: string\n apiBase: string\n /** How this integration identifies to the server (headers on the probe). */\n client: IntegrationClient\n /** MCP `clientInfo.name`; defaults to the runtime name. */\n clientName?: string\n /** MCP `clientInfo.version`; defaults to the integration's version. */\n clientVersion?: string\n timeoutMs?: number\n fetch?: typeof fetch\n}): Promise<McpProbeResult> {\n const fetchImpl = params.fetch ?? fetch\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), params.timeoutMs ?? 10_000)\n try {\n const res = await fetchImpl(hostedMcpUrl(params.apiBase), {\n method: 'POST',\n headers: {\n authorization: `Bearer ${params.apiKey}`,\n 'content-type': 'application/json',\n accept: 'application/json, text/event-stream',\n ...clientHeadersOf(params.client),\n },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'initialize',\n params: {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: {\n name: params.clientName ?? params.client.runtime,\n version: params.clientVersion ?? params.client.version,\n },\n },\n }),\n signal: controller.signal,\n })\n if (!res.ok) {\n return {\n ok: false,\n status: res.status,\n error:\n res.status === 401\n ? 'the key does not authenticate against the hosted MCP server'\n : `HTTP ${res.status}`,\n }\n }\n const result = readInitializeResult(await res.text())\n if (!result) return { ok: false, status: res.status, error: 'no initialize result in the answer' }\n const serverInfo = (result.serverInfo ?? {}) as Record<string, unknown>\n return {\n ok: true,\n status: res.status,\n ...(typeof serverInfo.name === 'string' ? { serverName: serverInfo.name } : {}),\n ...(typeof serverInfo.version === 'string' ? { serverVersion: serverInfo.version } : {}),\n ...(typeof result.protocolVersion === 'string' ? { protocolVersion: result.protocolVersion } : {}),\n }\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** The initialize result from a JSON body or an SSE body (`data: {...}` lines). */\nfunction readInitializeResult(text: string): Record<string, unknown> | null {\n const candidates: string[] = []\n const trimmed = text.trim()\n if (trimmed.startsWith('{')) candidates.push(trimmed)\n for (const line of text.split(/\\r?\\n/)) {\n if (line.startsWith('data:')) candidates.push(line.slice(5).trim())\n }\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate) as Record<string, unknown>\n const result = parsed.result\n if (result && typeof result === 'object' && !Array.isArray(result)) {\n return result as Record<string, unknown>\n }\n } catch {\n // not JSON — try the next candidate\n }\n }\n return null\n}\n","import * as readline from 'node:readline'\nimport { AgentChatClient } from 'agentchatme'\nimport {\n DEFAULT_API_BASE,\n credentialsPath,\n readCredentials,\n resolveIdentity,\n writeCredentials,\n clearCredentials,\n readPending,\n writePending,\n clearPending,\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 type { ServedManual } from '../skill/served-manual.js'\nimport { anchorLabelOf, type DoctorCheck, type HostProfile, type StatusContext, type Verdict } from './host-profile.js'\nimport { clientIdentityOf } from '../client-identity.js'\nimport { formatIntegrationStatus, readIntegrationStatus } 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// The OTP round-trip is split across two invocations with the pending state\n// persisted, so the agent can ask its user for the emailed code between them.\n//\n// These flows are a contract with the AgentChat server — the pending-state\n// machine, the error vocabulary, what a credential file holds — so they are\n// shared rather than reimplemented per host. They lived in each integration\n// once, and within a week the two copies were 94% identical and had already\n// 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// Canonical handle rule, mirrored from the server so obviously-bad input fails\n// locally with a helpful message instead of a round-trip.\nconst HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\n\nfunction validHandle(handle: string): boolean {\n return handle.length >= 3 && handle.length <= 30 && HANDLE_PATTERN.test(handle)\n}\n\n/**\n * Ask one question on the TTY.\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> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout })\n try {\n const answer = await new Promise<string>((resolve) => rl.question(question, resolve))\n return answer.trim()\n } finally {\n rl.close()\n }\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\ninterface ApiErrorLike {\n code?: string\n message?: string\n details?: Record<string, unknown>\n}\n\n/** The server's `details.limit` on an email-policy rejection, when it sent one. */\nfunction limitOf(e: ApiErrorLike): number | null {\n const limit = e.details?.['limit']\n return typeof limit === 'number' && Number.isFinite(limit) ? limit : null\n}\n\n/** The server's `details.handles` on HANDLE_REQUIRED, when it sent them. */\nfunction handlesOf(e: ApiErrorLike): string[] {\n const handles = e.details?.['handles']\n return Array.isArray(handles) ? handles.filter((h): h is string => typeof h === 'string') : []\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\nfunction describeApiError(err: unknown, invocation: string): string {\n const e = (err ?? {}) as ApiErrorLike\n const code = typeof e.code === 'string' ? e.code : undefined\n const message = typeof e.message === 'string' ? e.message : String(err)\n switch (code) {\n case 'HANDLE_TAKEN':\n return 'That handle is already taken — pick another and re-run.'\n // An email backs a bounded number of live agents, and the bound is a\n // server-side setting — so the number is always the one the server just\n // reported, never a constant here. `EMAIL_TAKEN` is what a not-yet-upgraded\n // server says in the same situation (its bound was one).\n case 'EMAIL_LIMIT_REACHED':\n case 'EMAIL_TAKEN': {\n const limit = limitOf(e)\n const lead =\n limit !== null\n ? `This email already backs ${limit} active agent${limit === 1 ? '' : 's'} — its maximum.`\n : message\n return `${lead} Delete one, sign in to one with \\`${invocation} login\\`, re-key one with \\`${recoverUsage(invocation)}\\`, or register with a different email (a + alias such as you+agent@example.com counts as a different email).`\n }\n case 'EMAIL_EXHAUSTED': {\n const limit = limitOf(e)\n const lead =\n limit !== null\n ? `This email has reached its lifetime maximum of ${limit} account registrations.`\n : message\n return `${lead} Register with a different email (a + alias such as you+agent@example.com counts as a different email).`\n }\n case 'HANDLE_REQUIRED': {\n const handles = handlesOf(e)\n const listed = handles.length > 0 ? ` Agents on this email: ${handles.map((h) => `@${h}`).join(', ')}.` : ''\n return `This email backs more than one agent, so the server needs to know which one to re-key.${listed} Run recovery again with the handle: ${recoverUsage(invocation)}`\n }\n case 'INVALID_HANDLE':\n return 'The server rejected the handle (invalid or reserved word).'\n case 'INVALID_CODE':\n return `Wrong or expired code. Re-check the 6 digits; after too many misses you must restart with \\`${invocation} register\\`.`\n case 'EXPIRED':\n return `This registration expired (codes last 10 minutes). Start over with \\`${invocation} register\\`.`\n default:\n return code ? `${code}: ${message}` : message\n }\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 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. An email can back several agents,\n * so this is required by the server; when omitted it defaults to this\n * agent's stored handle, then to a prompt on a TTY.\n */\n handle?: string\n /** The 6-digit 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 apiErr = (err: unknown): string => describeApiError(err, invocation())\n const LABEL = profile.label\n const clientIdentity = clientIdentityOf(profile.client)\n\n /**\n * `quick`: one attempt, 5 s — for `status`, `doctor` and the texts fetch,\n * which must answer in seconds on a black-holed network (the SDK's default\n * ramp is 4 attempts of up to 15 s). `patient`: the SDK's defaults, for a\n * sign-in the user is waiting on.\n */\n const apiClient = (apiKey: string, apiBase: string, budget: 'quick' | 'patient' = 'quick'): AgentChatClient =>\n budget === 'quick'\n ? new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5_000, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } })\n : new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, 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<{ identityLine: string | null; manual: ServedManual | null }> {\n const loaded = await loadTexts({ home: profile.home(), runtime: profile.client.runtime, client: apiClient(apiKey, apiBase), timeoutMs: 5_000 })\n return loaded === null ? { identityLine: null, manual: null } : { identityLine: identityLineOf(loaded.texts), manual: loaded.texts.manual }\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 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 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 try {\n writeAnchor(file, profile.renderAnchor(identityLine), handle)\n return [` ${label}: @${handle} → ${file}`]\n } catch (err) {\n return [` ${label}: FAILED — ${String(err)}`]\n }\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 // Completion leg\n if (opts.code !== undefined) {\n const code = opts.code.trim()\n if (!/^\\d{6}$/.test(code)) {\n console.error('The code is the 6-digit number from the verification email.')\n return 1\n }\n const pending = readPending(home)\n if (pending === null) {\n console.error(\n `No registration in progress. Start with: ${invocation()} register --email <email> --handle <handle>`,\n )\n return 1\n }\n if (pending.kind === 'recover') {\n console.error(\n `The pending code belongs to an account RECOVERY — complete it with: ${invocation()} recover --code ${code}`,\n )\n return 1\n }\n const pendingHandle = pending.handle\n if (pendingHandle === undefined) {\n clearPending(home)\n console.error(`Pending registration was corrupt — start again with: ${invocation()} register`)\n return 1\n }\n try {\n const result = await AgentChatClient.verify(pending.pending_id, code, {\n baseUrl: pending.api_base ?? apiBase,\n clientIdentity,\n })\n writeCredentials(home, {\n api_key: result.apiKey,\n handle: pendingHandle,\n ...(pending.api_base ? { api_base: pending.api_base } : {}),\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 console.log(\n [\n `Registered: @${pendingHandle} for ${LABEL}.`,\n `API key stored at ${credentialsPath(home)} (never commit this file).`,\n ...(await placeIdentity(pendingHandle, result.apiKey, pending.api_base ?? apiBase)),\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 @${pendingHandle}. Check \\`${invocation()} status\\` any time.`,\n NEXT_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Verification failed. ${apiErr(err)}`)\n return 1\n }\n }\n\n // Initiation leg. The gate is about THIS agent only — another coding agent\n // having an 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 const inFlight = readPending(home)\n if (inFlight?.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 let email = opts.email?.trim().toLowerCase()\n let handle = opts.handle?.trim().toLowerCase()\n const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true\n\n if (!email) {\n if (!interactive) {\n console.error(`Missing --email. Usage: ${invocation()} register --email <email> --handle <handle>`)\n return 1\n }\n email = (await prompt('Email for verification codes: ')).toLowerCase()\n }\n if (!handle) {\n if (!interactive) {\n console.error(`Missing --handle. Usage: ${invocation()} register --email <email> --handle <handle>`)\n return 1\n }\n handle = (await prompt('Desired handle (3–30 chars, e.g. sanim-dev): ')).toLowerCase()\n }\n\n if (!email.includes('@')) {\n console.error(`\"${email}\" does not look like an email address.`)\n return 1\n }\n if (!validHandle(handle)) {\n console.error(\n `Handle \"@${handle}\" is invalid. Rules: 3–30 characters, lowercase letters/digits/hyphens, must start with a letter, no trailing or doubled hyphens.`,\n )\n return 1\n }\n\n try {\n const result = await AgentChatClient.register({\n email,\n handle,\n ...(opts.displayName ? { display_name: opts.displayName } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n baseUrl: apiBase,\n clientIdentity,\n })\n writePending(home, {\n kind: 'register',\n pending_id: result.pending_id,\n email,\n handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n console.log(\n [\n `Verification code sent to ${email} (valid ~10 minutes).`,\n `Complete with: ${invocation()} register --code <6-digit-code>`,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Registration failed. ${apiErr(err)}`)\n return 1\n }\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. `--api-key <key>` keeps\n // working, but argv is visible in `ps` and kept in shell history, so a\n // key can also be piped in (`--api-key -`) or passed in the environment.\n if (apiKey === '-') {\n apiKey = await readAllStdin()\n } else if (!apiKey) {\n const fromEnv = process.env['AGENTCHAT_API_KEY']?.trim()\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. Pipe it in: printf %s \"$KEY\" | ${invocation()} login --api-key - (or set AGENTCHAT_API_KEY, or pass --api-key ac_live_…, which \\`ps\\` and shell history can see)`,\n )\n return 1\n } else {\n apiKey = await prompt('AgentChat API key (ac_…): ')\n }\n }\n if (apiKey.length < 20) {\n console.error('That does not look like an AgentChat API key (too short).')\n return 1\n }\n\n try {\n const client = apiClient(apiKey, apiBase, 'patient')\n const me = await client.getMe()\n writeCredentials(home, {\n api_key: apiKey,\n handle: me.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 @${me.handle} for ${LABEL}.`,\n `API key stored at ${credentialsPath(home)} (never commit this file).`,\n ...(await placeIdentity(me.handle, apiKey, apiBase)),\n NEXT_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Login failed. ${apiErr(err)}`)\n return 1\n }\n }\n\n // Recovery re-keys ONE agent, named by handle + email. One email can back\n // several agents, so the email alone no longer identifies an account; the\n // server treats an email-only request as \"the only agent on this email, if\n // there is exactly one\" and otherwise fails at verify time with\n // HANDLE_REQUIRED — after the code has been spent. Always sending the handle\n // keeps this a single round-trip.\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 const usage = recoverUsage(invocation())\n\n if (opts.code !== undefined) {\n const code = opts.code.trim()\n if (!/^\\d{6}$/.test(code)) {\n console.error('The code is the 6-digit number from the recovery email.')\n return 1\n }\n const pending = readPending(home)\n if (pending === null || pending.kind !== 'recover') {\n console.error(`No recovery in progress. Start with: ${usage}`)\n return 1\n }\n try {\n const result = await AgentChatClient.recoverVerify(pending.pending_id, code, {\n baseUrl: pending.api_base ?? apiBase,\n clientIdentity,\n })\n writeCredentials(home, {\n api_key: result.apiKey,\n handle: result.handle,\n ...(pending.api_base ? { api_base: pending.api_base } : {}),\n created_at: new Date().toISOString(),\n })\n clearPending(home)\n clearOfferDeclined(home)\n console.log(\n [\n `Recovered: @${result.handle} for ${LABEL}.`,\n `New API key stored at ${credentialsPath(home)} (the old key is now revoked; never commit this file).`,\n ...(await placeIdentity(result.handle, result.apiKey, pending.api_base ?? apiBase)),\n NEXT_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n // The code was accepted but the server could not pick an agent. That\n // code is spent and the server has dropped the pending record, so the\n // local one is dead too.\n if ((err as ApiErrorLike | null)?.code === 'HANDLE_REQUIRED') clearPending(home)\n console.error(`Recovery failed. ${apiErr(err)}`)\n return 1\n }\n }\n\n const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true\n\n let handle = opts.handle?.trim().replace(/^@/, '').toLowerCase()\n if (!handle) {\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 } else if (interactive) {\n handle = (await prompt('Handle of the agent to recover (e.g. sanim-dev): ')).replace(/^@/, '').toLowerCase()\n } else {\n console.error(\n `Missing --handle. An email can back more than one agent, so recovery needs the handle too. Usage: ${usage}`,\n )\n return 1\n }\n }\n if (!validHandle(handle)) {\n console.error(\n `Handle \"@${handle}\" is invalid. Rules: 3–30 characters, lowercase letters/digits/hyphens, must start with a letter, no trailing or doubled hyphens.`,\n )\n return 1\n }\n\n let email = opts.email?.trim().toLowerCase()\n if (!email) {\n if (!interactive) {\n console.error(`Missing --email. Usage: ${usage}`)\n return 1\n }\n email = (await prompt(`Email @${handle} was registered with: `)).toLowerCase()\n }\n if (!email.includes('@')) {\n console.error(`\"${email}\" does not look like an email address.`)\n return 1\n }\n\n try {\n // The handle rides along: one email can back several agents, and an\n // email-only request is only unambiguous while it backs exactly one.\n const result = await AgentChatClient.recover(email, { handle, baseUrl: apiBase, clientIdentity })\n if (!result.pending_id) {\n console.log(result.message || 'If an agent is registered with that email, a recovery code was sent to it.')\n return 0\n }\n writePending(home, {\n kind: 'recover',\n pending_id: result.pending_id,\n email,\n handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n console.log(\n [\n `If @${handle} is registered with ${email}, a recovery code was sent there (valid ~10 minutes).`,\n `Complete with: ${invocation()} recover --code <6-digit-code>`,\n 'Note: completing recovery rotates the API key — anything using the old key stops working.',\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Recovery failed. ${apiErr(err)}`)\n return 1\n }\n }\n\n async function runStatus(opts: { json?: boolean }): Promise<number> {\n const home = profile.home()\n const anchorFile = profile.anchorFile()\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 // The previous key, kept one release for scripts that read it.\n doorbell: integration,\n }),\n )\n } else if (pending?.kind === 'recover') {\n const who = pending.handle !== undefined ? ` for @${pending.handle}` : ''\n console.log(\n `No identity yet, but an account recovery${who} is waiting on its emailed code — finish with: ${invocation()} recover --code <code>`,\n )\n } else if (pending !== null) {\n console.log(\n `No identity yet, but a registration for @${pending.handle ?? '?'} is waiting on its emailed code — finish with: ${invocation()} register --code <code>`,\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 = apiErr(err)\n if (opts.json) {\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: hasAnchorAt(anchorFile),\n integration,\n doorbell: 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 ? { identityLine: null, manual: null } : { identityLine: identityLineOf(cached.texts), manual: cached.texts.manual })\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 anchorCurrent = identityLine === null ? null : anchorIsCurrentAt(anchorFile, identityLine)\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: hasAnchorAt(anchorFile),\n /** null: the served texts were unavailable, so currency could not be checked. */\n anchor_current: anchorCurrent,\n integration,\n doorbell: 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 `Identity line: ${hasAnchorAt(anchorFile) ? (anchorCurrent === null ? 'present (served texts unavailable — not checked)' : anchorCurrent ? 'current' : 'present (older text — `doctor --fix` refreshes it)') : 'missing'} (${anchorFile})`,\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()\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 (removeAnchorAt(anchorFile) === 'removed') {\n any = true\n reports.push(` ${anchorLabelOf(profile)} identity line removed`)\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 async function runDoctor(opts: DoctorOpts = {}): Promise<number> {\n const home = profile.home()\n const anchorFile = profile.anchorFile()\n const checks: DoctorCheck[] = []\n let identityLine: string | null = null\n let manual: ServedManual | null = null\n\n checks.push({ name: 'node', verdict: 'PASS', detail: process.version })\n checks.push({ name: 'home', verdict: 'PASS', detail: home })\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 ;({ identityLine, manual } = await served(creds.api_key, apiBase))\n const claimed = readAnchorHandleAt(anchorFile)\n const current = identityLine === null ? null : anchorIsCurrentAt(anchorFile, identityLine)\n checks.push(\n 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 (claimed === creds.handle && current === true) {\n checks.push({ name: 'identity-line', verdict: 'PASS', detail: `@${claimed} in ${anchorFile}` })\n } else if (claimed === creds.handle && current === null) {\n checks.push({ name: 'identity-line', verdict: 'WARN', detail: `@${claimed} in ${anchorFile} (currency not checked: served texts unavailable)` })\n } else {\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 (opts.fix === true) {\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 checks.push({\n name: 'identity-line',\n verdict: failed ? 'FAIL' : 'PASS',\n detail: failed ? `could not repair: ${report.join('; ')}` : `repaired → @${creds.handle}`,\n })\n } else {\n checks.push({\n name: 'identity-line',\n verdict: 'WARN',\n detail: `${why} — repair with \\`${invocation()} doctor --fix\\``,\n })\n }\n }\n }\n\n if (profile.extraDoctorChecks !== undefined) checks.push(...(await profile.extraDoctorChecks({ ...opts, identityLine, manual })))\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 /** 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 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 /** This host's always-loaded instruction file. */\n anchorFile(): string\n /** Exactly what a user types to reach this integration. */\n invocation(): string\n /** Render the anchor block body this host wants from the served identity line (normally `renderAnchorBlock`). */\n renderAnchor(identityLine: 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 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'\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 <daemon> start …` 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 under ~/.agentchat/daemon 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/** The pid in the daemon's leader lock, or null: the daemon the Startup launcher is keeping alive right now. */\nfunction lockedDaemonPid(home: string): number | null {\n try {\n const pid = Number.parseInt(fs.readFileSync(path.join(home, 'daemon.lock'), 'utf-8').trim(), 10)\n return Number.isInteger(pid) && pid > 0 ? 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACO,IAAM,UAAU;;;ACavB,IAAM,cAAc,iBAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,EAK3B,mBAAmB,iBAAE,OAAO,EAAE,SAAS;AACzC,CAAC;AAIM,SAAS,UAAU,MAA6B;AACrD,QAAM,MAAM,aAAsB,UAAU,IAAI,CAAC;AACjD,MAAI,QAAQ,MAAM;AAChB,UAAM,SAAS,YAAY,UAAU,GAAG;AACxC,QAAI,OAAO,QAAS,QAAO,OAAO;AAAA,EACpC;AACA,SAAO,CAAC;AACV;AAEO,SAAS,WAAW,MAAc,OAA4B;AACnE,kBAAgB,UAAU,IAAI,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,IAAI,MAAM,GAAK;AAC/E;AAUO,SAAS,oBAAoB,MAAc,MAAY,oBAAI,KAAK,GAAS;AAC9E,QAAM,QAAQ,UAAU,IAAI;AAC5B,QAAM,oBAAoB,IAAI,YAAY;AAC1C,aAAW,MAAM,KAAK;AACxB;AAEO,SAAS,cAAc,MAAuB;AACnD,SAAO,UAA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AAA,IACzG;AACA,QAAI,OAAO,OAAO;AAChB,YAAM,SAAc,WAAK,aAAa,GAAG,GAAG,EAAE,KAAK,KAAK;AACxD,YAAM,MAAW,WAAK,aAAa,GAAG,GAAG,EAAE,KAAK,MAAM;AACtD,YAAM,SAAS,aAAa,cAAc,QAAQ,IAAI,iBAAiB,KAAK,EAAE;AAC9E,UAAI,CAAC,OAAQ,QAAO;AACpB,aACK,eAAW,MAAM,KACjB,eAAW,GAAG,KACd,iBAAa,QAAQ,OAAO,MAAM,iBAAiB,CAAC,KACpD,iBAAa,KAAK,OAAO,MAC1B,YAAY,eAAe,MAAM,cAAc,MAAM,KAAK,CAAC,CAAC;AAAA,IAElE;AACA,QAAI,cAAc,MAAM,SAAS;AAC/B,YAAM,OAAO,gBAAgB,EAAE,KAAK;AACpC,aAAU,eAAW,IAAI,KAAQ,iBAAa,MAAM,OAAO,MAAM,YAAY,CAAC;AAAA,IAChF;AACA,QAAI,cAAc,MAAM,UAAU;AAChC,YAAM,OAAO,iBAAiB,EAAE,KAAK;AACrC,aAAU,eAAW,IAAI,KAAQ,iBAAa,MAAM,OAAO,MAAM,aAAa,CAAC;AAAA,IACjF;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAUA,SAAS,cAAc,OAAwB;AAC7C,MAAI,QAAQ,EAAG,QAAU,eAAgB,WAAK,aAAa,GAAG,GAAG,KAAK,MAAM,CAAC;AAC7E,MAAI,cAAc,MAAM,QAAS,QAAU,eAAW,gBAAgB,KAAK,CAAC;AAC5E,MAAI,cAAc,MAAM,SAAU,QAAU,eAAW,iBAAiB,KAAK,CAAC;AAC9E,SAAO;AACT;AAEO,SAAS,iBAAiB,MAA2B;AAC1D,SAAO,cAAc,aAAa,KAAK,KAAK,CAAC;AAC/C;","names":["resolve","fs","path"]}
1
+ {"version":3,"sources":["../src/version.ts","../src/integration/tray.ts","../src/identity/state.ts","../src/skill/identity-line.ts","../src/anchor/block.ts","../src/anchor/offer.ts","../src/identity/commands.ts","../src/identity/host-profile.ts","../src/daemon/service.ts"],"sourcesContent":["/** Published package version, kept in lockstep with package.json by tests. */\nexport const VERSION = '0.4.0'\n","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 { Texts } from 'agentchatme'\n\n// ─── The identity line: placed, not authored ────────────────────────────────\n//\n// The few lines written into whatever file the runtime loads on EVERY turn\n// (`CLAUDE.md`, `AGENTS.md`, `SOUL.md`, …) are the server's text: `GET\n// /v1/texts` serves them with the handle filled in and the hosted tool names\n// spelled for the runtime. This module no longer carries the words — it only\n// says which served field is the identity line and normalises the handle the\n// line is checked against. The fenced-block placement itself is\n// `anchor/block.ts`; the fetch and the cache are `integration/texts.ts`.\n\n/** The identity line, ready to place, from a served (or cached) texts response. */\nexport function identityLineOf(texts: Pick<Texts, 'identity_line'>): string {\n return texts.identity_line\n}\n\n/** Handles are canonical lowercase on the wire; a leading `@` is display only. */\nexport function normalizeHandle(handle: string): string {\n return handle.trim().replace(/^@/, '').toLowerCase()\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\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. Same mechanism as the Hermes SOUL.md anchor and the OpenClaw\n// AGENTS.md anchor. The words are the server's; this module only fences them.\n//\n// This module knows how to edit a fenced block in a file. It does NOT know\n// WHICH file — that is the integration's business, because the file IS the\n// host. A shared function that picked the file itself is precisely what once\n// stamped one agent's handle into another agent's instruction file.\n//\n// Markers are shared verbatim across ALL AgentChat integrations — whichever\n// integration wrote last owns the block, and switching integrations overwrites\n// cleanly instead of duplicating. DO NOT change them without updating the\n// OpenClaw plugin (src/binding/agents-anchor.ts) and the Hermes plugin\n// (soul_anchor.py).\n\nexport const ANCHOR_START = '<!-- agentchat:start -->'\nexport const ANCHOR_END = '<!-- agentchat:end -->'\n\nconst LEGACY_ANCHOR_START = '<!-- agentchat-skill:start -->'\nconst LEGACY_ANCHOR_END = '<!-- agentchat-skill:end -->'\n\n/** The identity block: the served identity line, as fetched for this agent, between the markers. */\nexport function renderAnchorBlock(identityLine: string): string {\n const line = identityLine.trim()\n if (line.length === 0) throw new Error('renderAnchorBlock: the identity line is empty')\n return [ANCHOR_START, line, ANCHOR_END].join('\\n')\n}\n\nexport type AnchorAction = 'written' | 'removed' | 'noop'\n\n/**\n * Upsert `block` into the file at `filePath`, creating it if needed.\n *\n * Throws if `expectHandle` is given and does not appear in what was written —\n * a silently-wrong identity block is worse than a loud failure, because the\n * agent would spend every session announcing an address that isn't its own.\n */\nexport function writeAnchor(filePath: string, block: string, expectHandle?: string): AnchorAction {\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : ''\n fs.writeFileSync(filePath, upsertAnchorBlock(existing, block), 'utf-8')\n\n if (expectHandle !== undefined) {\n const verify = fs.readFileSync(filePath, 'utf-8')\n if (!verify.includes(`@${expectHandle}`)) {\n throw new Error(\n `writeAnchor: handle @${expectHandle} did not land in ${filePath} — remove the agentchat block manually and re-run.`,\n )\n }\n }\n return 'written'\n}\n\nexport function removeAnchorAt(filePath: string): AnchorAction {\n if (!fs.existsSync(filePath)) return 'noop'\n const existing = fs.readFileSync(filePath, 'utf-8')\n const next = stripAnchorBlock(existing)\n if (next === existing) return 'noop'\n fs.writeFileSync(filePath, next, 'utf-8')\n return 'removed'\n}\n\nexport function hasAnchorAt(filePath: string): boolean {\n if (!fs.existsSync(filePath)) return false\n return findBlock(fs.readFileSync(filePath, 'utf-8'), ANCHOR_START, ANCHOR_END) !== null\n}\n\n/** Whether the file's block is exactly the block for this served identity line. */\nexport function anchorIsCurrentAt(filePath: string, identityLine: string): boolean {\n if (!fs.existsSync(filePath)) return false\n const text = fs.readFileSync(filePath, 'utf-8')\n const block = findBlock(text, ANCHOR_START, ANCHOR_END)\n if (block === null) return false\n return text.slice(block.from, block.to) === renderAnchorBlock(identityLine)\n}\n\n// The served text (\"I am @handle on AgentChat\"), then the block releases\n// before the integration wrote (\"You are **@handle** on AgentChat\") so an\n// anchor from an older release is still recognised — and refreshed by\n// `doctor --fix`.\nconst IDENTITY_HANDLE_RE = /I am @([^\\s]+) on AgentChat/\nconst LEGACY_HANDLE_RE = /\\*\\*@([^*\\s]+)\\*\\*/\n\n/**\n * The handle a file's anchor block currently CLAIMS, or null if there is no\n * block. Lets an integration catch an anchor that disagrees with its own\n * credential — an agent told it is @a while authenticating as @b hands peers an\n * address that reaches someone else. Matched loosely precisely so a WRONG\n * value is still read back and reported rather than treated as \"no anchor\".\n */\nexport function readAnchorHandleAt(filePath: string): string | null {\n if (!fs.existsSync(filePath)) return null\n return readAnchorHandleFrom(fs.readFileSync(filePath, 'utf-8'))\n}\n\nexport function readAnchorHandleFrom(text: string): string | null {\n const block = findBlock(text, ANCHOR_START, ANCHOR_END)\n if (block === null) return null\n const inside = text.slice(block.from, block.to)\n const match = IDENTITY_HANDLE_RE.exec(inside) ?? LEGACY_HANDLE_RE.exec(inside)\n return match?.[1] ?? null\n}\n\n// Markers only count when they are a whole line — a marker quoted inside user\n// prose (\"the plugin uses <!-- agentchat:start --> fences\") must never be\n// treated as a fence, or the upsert would eat the user's content between the\n// quote and the real block.\nfunction lineAnchoredIndex(\n text: string,\n marker: string,\n fromIndex = 0,\n): { start: number; end: number } | null {\n let idx = text.indexOf(marker, fromIndex)\n while (idx >= 0) {\n const lineStart = text.lastIndexOf('\\n', idx - 1) + 1\n const lineEndRaw = text.indexOf('\\n', idx)\n const lineEnd = lineEndRaw === -1 ? text.length : lineEndRaw\n if (text.slice(lineStart, lineEnd).trim() === marker) {\n return { start: lineStart, end: lineEnd }\n }\n idx = text.indexOf(marker, idx + marker.length)\n }\n return null\n}\n\nfunction findBlock(\n text: string,\n startMarker: string,\n endMarker: string,\n): { from: number; to: number } | null {\n const start = lineAnchoredIndex(text, startMarker)\n if (start === null) return null\n const end = lineAnchoredIndex(text, endMarker, start.end)\n if (end === null) return null\n return { from: start.start, to: end.end }\n}\n\nexport function upsertAnchorBlock(existing: string, block: string): string {\n // Strip every existing block (unified AND legacy) first, then append the\n // fresh one — replacement and dedup in one motion, so a file that somehow\n // accumulated multiple blocks converges back to exactly one.\n const cleaned = stripAnchorBlock(existing)\n const trimmed = cleaned.replace(/\\n+$/, '')\n if (trimmed.length === 0) return block + '\\n'\n return trimmed + '\\n\\n' + block + '\\n'\n}\n\nexport function stripAnchorBlock(existing: string): string {\n const afterUnified = stripAllBlocks(existing, ANCHOR_START, ANCHOR_END)\n return stripAllBlocks(afterUnified, LEGACY_ANCHOR_START, LEGACY_ANCHOR_END)\n}\n\nfunction stripAllBlocks(existing: string, start: string, end: string): string {\n let text = existing\n // Bounded loop: each pass removes one block; a file can't hold more blocks\n // than lines.\n for (let i = 0; i < 10_000; i++) {\n const block = findBlock(text, start, end)\n if (block === null) return text\n const before = text.slice(0, block.from).replace(/\\n+$/, '')\n const after = text.slice(block.to).replace(/^\\n+/, '')\n if (before.length === 0 && after.length === 0) return ''\n if (before.length === 0) text = after.endsWith('\\n') ? after : after + '\\n'\n else if (after.length === 0) text = before + '\\n'\n else text = before + '\\n\\n' + after + (after.endsWith('\\n') ? '' : '\\n')\n }\n return text\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 `upsertAnchorBlock`, which strips every existing\n// block before writing, so registering REPLACES this with the identity block\n// and logout 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 */\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 'If they want a new account:',\n ' **Ask only one question per turn. Never ask for the email and handle in the same message.**',\n ' 1. Ask only: \"I need an email for verification and recovery. Which email should I use? After we choose my handle, AgentChat will send a 6-digit code there, and I’ll ask you to paste it here.\"',\n ' 2. After they answer, say: \"Now we need to choose an AgentChat username for me—my @handle, which other agents will use to reach me.\"',\n ' Explain the rules simply: \"Use 3–30 characters: lowercase letters, numbers, and hyphens. Start with a letter; no double or trailing hyphens.\"',\n ' If there is a concrete, relevant candidate, ask: \"How about @<candidate>?\" Otherwise ask: \"What username should I use? If you want, I can suggest one.\"',\n ` 3. Once there is an email and handle, run: ${invoke} register --email <email> --handle <handle>`,\n ' Registration is the authoritative availability check. Never promise availability before it succeeds.',\n ' If their handle is taken or invalid, ask only for another handle, keep the same email, and retry only after they choose or accept the replacement.',\n ' Never submit a handle the user has not chosen or accepted.',\n ' 4. Only after registration confirms the code was sent, say: \"AgentChat sent a 6-digit code to <email>. Paste it here and I’ll finish setup.\"',\n ` 5. Run: ${invoke} register --code <code>`,\n ' 6. On success, use the command’s exact handle and path: \"Done—I’m registered as @<handle>. The API key is stored at <credentials-path>.\"',\n '',\n `If they already have an account for this ${label} agent:`,\n ' **Ask one question per turn. Run the commands yourself.**',\n ' 1. Ask exactly: \"Give me the AgentChat API key for this account. If you no longer have it, I can help you recover the account.\"',\n ` 2. If they provide it, run: ${invoke} login --api-key <ac_…>`,\n ' On success, use the command’s exact handle and path: \"Done—I’m signed in as @<handle>. The API key is stored at <credentials-path>.\"',\n ' If login fails, say: \"That API key didn’t work. Please check it and send it again, or tell me if you need to recover the account.\"',\n ' 3. If they no longer have the key, ask exactly: \"I can recover the account. This will replace the old API key, so anything still using it will stop working. What email did you use for this AgentChat account?\"',\n ' 4. Then ask only: \"Which @handle is the account? One email can back several agents, so recovery needs both.\"',\n ` 5. Run: ${invoke} recover --handle <handle> --email <email>`,\n ' 6. Once recovery accepts the request, say: \"If @<handle> is registered with <email>, AgentChat sent a 6-digit recovery code to <email>. Paste it here and I’ll finish signing in.\"',\n ` 7. Run: ${invoke} recover --code <code>`,\n ' On success, use the command’s exact handle and path: \"Done—I recovered the account and signed in as @<handle>. The new API key is stored at <credentials-path>. The old key no longer works.\"',\n ' If the code fails, say: \"That code didn’t work. Check the 6 digits and paste it again.\"',\n ' 8. 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 * as readline from 'node:readline'\nimport { AgentChatClient } from 'agentchatme'\nimport {\n DEFAULT_API_BASE,\n credentialsPath,\n readCredentials,\n resolveIdentity,\n writeCredentials,\n clearCredentials,\n readPending,\n writePending,\n clearPending,\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 type { ServedManual } from '../skill/served-manual.js'\nimport { anchorLabelOf, type DoctorCheck, type HostProfile, type StatusContext, type Verdict } from './host-profile.js'\nimport { clientIdentityOf } from '../client-identity.js'\nimport { REPEATED_FAILED_CYCLES, failedCyclesInARow, formatIntegrationStatus, readIntegrationStatus } 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// The OTP round-trip is split across two invocations with the pending state\n// persisted, so the agent can ask its user for the emailed code between them.\n//\n// These flows are a contract with the AgentChat server — the pending-state\n// machine, the error vocabulary, what a credential file holds — so they are\n// shared rather than reimplemented per host. They lived in each integration\n// once, and within a week the two copies were 94% identical and had already\n// 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// Canonical handle rule, mirrored from the server so obviously-bad input fails\n// locally with a helpful message instead of a round-trip.\nconst HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\n\nfunction validHandle(handle: string): boolean {\n return handle.length >= 3 && handle.length <= 30 && HANDLE_PATTERN.test(handle)\n}\n\n/**\n * Ask one question on the TTY.\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> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout })\n try {\n const answer = await new Promise<string>((resolve) => rl.question(question, resolve))\n return answer.trim()\n } finally {\n rl.close()\n }\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\ninterface ApiErrorLike {\n code?: string\n message?: string\n details?: Record<string, unknown>\n}\n\n/** The server's `details.limit` on an email-policy rejection, when it sent one. */\nfunction limitOf(e: ApiErrorLike): number | null {\n const limit = e.details?.['limit']\n return typeof limit === 'number' && Number.isFinite(limit) ? limit : null\n}\n\n/** The server's `details.handles` on HANDLE_REQUIRED, when it sent them. */\nfunction handlesOf(e: ApiErrorLike): string[] {\n const handles = e.details?.['handles']\n return Array.isArray(handles) ? handles.filter((h): h is string => typeof h === 'string') : []\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\nfunction describeApiError(err: unknown, invocation: string): string {\n const e = (err ?? {}) as ApiErrorLike\n const code = typeof e.code === 'string' ? e.code : undefined\n const message = typeof e.message === 'string' ? e.message : String(err)\n switch (code) {\n case 'HANDLE_TAKEN':\n return 'That handle is already taken — pick another and re-run.'\n // An email backs a bounded number of live agents, and the bound is a\n // server-side setting — so the number is always the one the server just\n // reported, never a constant here. `EMAIL_TAKEN` is what a not-yet-upgraded\n // server says in the same situation (its bound was one).\n case 'EMAIL_LIMIT_REACHED':\n case 'EMAIL_TAKEN': {\n const limit = limitOf(e)\n const lead =\n limit !== null\n ? `This email already backs ${limit} active agent${limit === 1 ? '' : 's'} — its maximum.`\n : message\n return `${lead} Delete one, sign in to one with \\`${invocation} login\\`, re-key one with \\`${recoverUsage(invocation)}\\`, or register with a different email (a + alias such as you+agent@example.com counts as a different email).`\n }\n case 'EMAIL_EXHAUSTED': {\n const limit = limitOf(e)\n const lead =\n limit !== null\n ? `This email has reached its lifetime maximum of ${limit} account registrations.`\n : message\n return `${lead} Register with a different email (a + alias such as you+agent@example.com counts as a different email).`\n }\n case 'HANDLE_REQUIRED': {\n const handles = handlesOf(e)\n const listed = handles.length > 0 ? ` Agents on this email: ${handles.map((h) => `@${h}`).join(', ')}.` : ''\n return `This email backs more than one agent, so the server needs to know which one to re-key.${listed} Run recovery again with the handle: ${recoverUsage(invocation)}`\n }\n case 'INVALID_HANDLE':\n return 'The server rejected the handle (invalid or reserved word).'\n case 'INVALID_CODE':\n return `Wrong or expired code. Re-check the 6 digits; after too many misses you must restart with \\`${invocation} register\\`.`\n case 'EXPIRED':\n return `This registration expired (codes last 10 minutes). Start over with \\`${invocation} register\\`.`\n default:\n return code ? `${code}: ${message}` : message\n }\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 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. An email can back several agents,\n * so this is required by the server; when omitted it defaults to this\n * agent's stored handle, then to a prompt on a TTY.\n */\n handle?: string\n /** The 6-digit 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 apiErr = (err: unknown): string => describeApiError(err, invocation())\n const LABEL = profile.label\n const clientIdentity = clientIdentityOf(profile.client)\n\n /**\n * `quick`: one attempt, 5 s — for `status`, `doctor` and the texts fetch,\n * which must answer in seconds on a black-holed network (the SDK's default\n * ramp is 4 attempts of up to 15 s). `patient`: the SDK's defaults, for a\n * sign-in the user is waiting on.\n */\n const apiClient = (apiKey: string, apiBase: string, budget: 'quick' | 'patient' = 'quick'): AgentChatClient =>\n budget === 'quick'\n ? new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5_000, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } })\n : new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, 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<{ identityLine: string | null; manual: ServedManual | null }> {\n const loaded = await loadTexts({ home: profile.home(), runtime: profile.client.runtime, client: apiClient(apiKey, apiBase), timeoutMs: 5_000 })\n return loaded === null ? { identityLine: null, manual: null } : { identityLine: identityLineOf(loaded.texts), manual: loaded.texts.manual }\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 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 try {\n writeAnchor(file, profile.renderAnchor(identityLine), handle)\n return [` ${label}: @${handle} → ${file}`]\n } catch (err) {\n return [` ${label}: FAILED — ${String(err)}`]\n }\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 // Completion leg\n if (opts.code !== undefined) {\n const code = opts.code.trim()\n if (!/^\\d{6}$/.test(code)) {\n console.error('The code is the 6-digit number from the verification email.')\n return 1\n }\n const pending = readPending(home)\n if (pending === null) {\n console.error(\n `No registration in progress. Start with: ${invocation()} register --email <email> --handle <handle>`,\n )\n return 1\n }\n if (pending.kind === 'recover') {\n console.error(\n `The pending code belongs to an account RECOVERY — complete it with: ${invocation()} recover --code ${code}`,\n )\n return 1\n }\n const pendingHandle = pending.handle\n if (pendingHandle === undefined) {\n clearPending(home)\n console.error(`Pending registration was corrupt — start again with: ${invocation()} register`)\n return 1\n }\n try {\n const result = await AgentChatClient.verify(pending.pending_id, code, {\n baseUrl: pending.api_base ?? apiBase,\n clientIdentity,\n })\n writeCredentials(home, {\n api_key: result.apiKey,\n handle: pendingHandle,\n ...(pending.api_base ? { api_base: pending.api_base } : {}),\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 console.log(\n [\n `Registered: @${pendingHandle} for ${LABEL}.`,\n `API key stored at ${credentialsPath(home)} (never commit this file).`,\n ...(await placeIdentity(pendingHandle, result.apiKey, pending.api_base ?? apiBase)),\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 @${pendingHandle}. Check \\`${invocation()} status\\` any time.`,\n NEXT_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Verification failed. ${apiErr(err)}`)\n return 1\n }\n }\n\n // Initiation leg. The gate is about THIS agent only — another coding agent\n // having an 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 const inFlight = readPending(home)\n if (inFlight?.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 let email = opts.email?.trim().toLowerCase()\n let handle = opts.handle?.trim().toLowerCase()\n const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true\n\n if (!email) {\n if (!interactive) {\n console.error(`Missing --email. Usage: ${invocation()} register --email <email> --handle <handle>`)\n return 1\n }\n email = (await prompt('Email for verification codes: ')).toLowerCase()\n }\n if (!handle) {\n if (!interactive) {\n console.error(`Missing --handle. Usage: ${invocation()} register --email <email> --handle <handle>`)\n return 1\n }\n handle = (await prompt('Desired handle (3–30 chars, e.g. sanim-dev): ')).toLowerCase()\n }\n\n if (!email.includes('@')) {\n console.error(`\"${email}\" does not look like an email address.`)\n return 1\n }\n if (!validHandle(handle)) {\n console.error(\n `Handle \"@${handle}\" is invalid. Rules: 3–30 characters, lowercase letters/digits/hyphens, must start with a letter, no trailing or doubled hyphens.`,\n )\n return 1\n }\n\n try {\n const result = await AgentChatClient.register({\n email,\n handle,\n ...(opts.displayName ? { display_name: opts.displayName } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n baseUrl: apiBase,\n clientIdentity,\n })\n writePending(home, {\n kind: 'register',\n pending_id: result.pending_id,\n email,\n handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n console.log(\n [\n `Verification code sent to ${email} (valid ~10 minutes).`,\n `Complete with: ${invocation()} register --code <6-digit-code>`,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Registration failed. ${apiErr(err)}`)\n return 1\n }\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. `--api-key <key>` keeps\n // working, but argv is visible in `ps` and kept in shell history, so a\n // key can also be piped in (`--api-key -`) or passed in the environment.\n if (apiKey === '-') {\n apiKey = await readAllStdin()\n } else if (!apiKey) {\n const fromEnv = process.env['AGENTCHAT_API_KEY']?.trim()\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. Pipe it in: printf %s \"$KEY\" | ${invocation()} login --api-key - (or set AGENTCHAT_API_KEY, or pass --api-key ac_live_…, which \\`ps\\` and shell history can see)`,\n )\n return 1\n } else {\n apiKey = await prompt('AgentChat API key (ac_…): ')\n }\n }\n if (apiKey.length < 20) {\n console.error('That does not look like an AgentChat API key (too short).')\n return 1\n }\n\n try {\n const client = apiClient(apiKey, apiBase, 'patient')\n const me = await client.getMe()\n writeCredentials(home, {\n api_key: apiKey,\n handle: me.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 @${me.handle} for ${LABEL}.`,\n `API key stored at ${credentialsPath(home)} (never commit this file).`,\n ...(await placeIdentity(me.handle, apiKey, apiBase)),\n NEXT_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Login failed. ${apiErr(err)}`)\n return 1\n }\n }\n\n // Recovery re-keys ONE agent, named by handle + email. One email can back\n // several agents, so the email alone no longer identifies an account; the\n // server treats an email-only request as \"the only agent on this email, if\n // there is exactly one\" and otherwise fails at verify time with\n // HANDLE_REQUIRED — after the code has been spent. Always sending the handle\n // keeps this a single round-trip.\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 const usage = recoverUsage(invocation())\n\n if (opts.code !== undefined) {\n const code = opts.code.trim()\n if (!/^\\d{6}$/.test(code)) {\n console.error('The code is the 6-digit number from the recovery email.')\n return 1\n }\n const pending = readPending(home)\n if (pending === null || pending.kind !== 'recover') {\n console.error(`No recovery in progress. Start with: ${usage}`)\n return 1\n }\n try {\n const result = await AgentChatClient.recoverVerify(pending.pending_id, code, {\n baseUrl: pending.api_base ?? apiBase,\n clientIdentity,\n })\n writeCredentials(home, {\n api_key: result.apiKey,\n handle: result.handle,\n ...(pending.api_base ? { api_base: pending.api_base } : {}),\n created_at: new Date().toISOString(),\n })\n clearPending(home)\n clearOfferDeclined(home)\n console.log(\n [\n `Recovered: @${result.handle} for ${LABEL}.`,\n `New API key stored at ${credentialsPath(home)} (the old key is now revoked; never commit this file).`,\n ...(await placeIdentity(result.handle, result.apiKey, pending.api_base ?? apiBase)),\n NEXT_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n // The code was accepted but the server could not pick an agent. That\n // code is spent and the server has dropped the pending record, so the\n // local one is dead too.\n if ((err as ApiErrorLike | null)?.code === 'HANDLE_REQUIRED') clearPending(home)\n console.error(`Recovery failed. ${apiErr(err)}`)\n return 1\n }\n }\n\n const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true\n\n let handle = opts.handle?.trim().replace(/^@/, '').toLowerCase()\n if (!handle) {\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 } else if (interactive) {\n handle = (await prompt('Handle of the agent to recover (e.g. sanim-dev): ')).replace(/^@/, '').toLowerCase()\n } else {\n console.error(\n `Missing --handle. An email can back more than one agent, so recovery needs the handle too. Usage: ${usage}`,\n )\n return 1\n }\n }\n if (!validHandle(handle)) {\n console.error(\n `Handle \"@${handle}\" is invalid. Rules: 3–30 characters, lowercase letters/digits/hyphens, must start with a letter, no trailing or doubled hyphens.`,\n )\n return 1\n }\n\n let email = opts.email?.trim().toLowerCase()\n if (!email) {\n if (!interactive) {\n console.error(`Missing --email. Usage: ${usage}`)\n return 1\n }\n email = (await prompt(`Email @${handle} was registered with: `)).toLowerCase()\n }\n if (!email.includes('@')) {\n console.error(`\"${email}\" does not look like an email address.`)\n return 1\n }\n\n try {\n // The handle rides along: one email can back several agents, and an\n // email-only request is only unambiguous while it backs exactly one.\n const result = await AgentChatClient.recover(email, { handle, baseUrl: apiBase, clientIdentity })\n if (!result.pending_id) {\n console.log(result.message || 'If an agent is registered with that email, a recovery code was sent to it.')\n return 0\n }\n writePending(home, {\n kind: 'recover',\n pending_id: result.pending_id,\n email,\n handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n console.log(\n [\n `If @${handle} is registered with ${email}, a recovery code was sent there (valid ~10 minutes).`,\n `Complete with: ${invocation()} recover --code <6-digit-code>`,\n 'Note: completing recovery rotates the API key — anything using the old key stops working.',\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Recovery failed. ${apiErr(err)}`)\n return 1\n }\n }\n\n async function runStatus(opts: { json?: boolean }): Promise<number> {\n const home = profile.home()\n const anchorFile = profile.anchorFile?.() ?? null\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 // The previous key, kept one release for scripts that read it.\n doorbell: integration,\n }),\n )\n } else if (pending?.kind === 'recover') {\n const who = pending.handle !== undefined ? ` for @${pending.handle}` : ''\n console.log(\n `No identity yet, but an account recovery${who} is waiting on its emailed code — finish with: ${invocation()} recover --code <code>`,\n )\n } else if (pending !== null) {\n console.log(\n `No identity yet, but a registration for @${pending.handle ?? '?'} is waiting on its emailed code — finish with: ${invocation()} register --code <code>`,\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 = apiErr(err)\n if (opts.json) {\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: anchorFile === null ? null : hasAnchorAt(anchorFile),\n integration,\n doorbell: 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 ? { identityLine: null, manual: null } : { identityLine: identityLineOf(cached.texts), manual: cached.texts.manual })\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 anchorCurrent = identityLine === null || anchorFile === null ? null : anchorIsCurrentAt(anchorFile, identityLine)\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: anchorFile === null ? null : hasAnchorAt(anchorFile),\n /** null: the served texts were unavailable (or there is no instruction file), so currency could not be checked. */\n anchor_current: anchorCurrent,\n integration,\n doorbell: 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: ${hasAnchorAt(anchorFile) ? (anchorCurrent === null ? 'present (served texts unavailable — not checked)' : anchorCurrent ? '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 && removeAnchorAt(anchorFile) === 'removed') {\n any = true\n reports.push(` ${anchorLabelOf(profile)} identity line removed`)\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 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 identityLine: string | null,\n fix: boolean,\n ): Promise<DoctorCheck> {\n const claimed = readAnchorHandleAt(anchorFile)\n const current = identityLine === null ? null : anchorIsCurrentAt(anchorFile, identityLine)\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 return {\n name: 'identity-line',\n verdict: failed ? 'FAIL' : 'PASS',\n detail: failed ? `could not repair: ${report.join('; ')}` : `repaired → @${creds.handle}`,\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 identityLine: string | null = null\n let manual: ServedManual | null = null\n\n checks.push({ name: 'node', verdict: 'PASS', detail: process.version })\n checks.push({ name: 'home', verdict: 'PASS', detail: home })\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 ;({ identityLine, manual } = await served(creds.api_key, apiBase))\n checks.push(\n 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, identityLine, 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 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\n if (profile.extraDoctorChecks !== undefined) checks.push(...(await profile.extraDoctorChecks({ ...opts, identityLine, manual })))\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 /** 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 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 /** Render the anchor block body this host wants from the served identity line (normally `renderAnchorBlock`). */\n renderAnchor(identityLine: 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'\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/** The pid in the daemon's leader lock, or null: the daemon the Startup launcher is keeping alive right now. */\nfunction lockedDaemonPid(home: string): number | null {\n try {\n const pid = Number.parseInt(fs.readFileSync(path.join(home, 'daemon.lock'), 'utf-8').trim(), 10)\n return Number.isInteger(pid) && pid > 0 ? 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACO,IAAM,UAAU;;;ACDvB,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;AAAA,IAC9D,WAAW,KAAK,cAAc;AAAA,EAChC;AACF;;;ACfA,IAAM,cAAc,iBAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,EAK3B,mBAAmB,iBAAE,OAAO,EAAE,SAAS;AACzC,CAAC;AAIM,SAAS,UAAU,MAA6B;AACrD,QAAM,MAAM,aAAsB,UAAU,IAAI,CAAC;AACjD,MAAI,QAAQ,MAAM;AAChB,UAAM,SAAS,YAAY,UAAU,GAAG;AACxC,QAAI,OAAO,QAAS,QAAO,OAAO;AAAA,EACpC;AACA,SAAO,CAAC;AACV;AAEO,SAAS,WAAW,MAAc,OAA4B;AACnE,kBAAgB,UAAU,IAAI,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,IAAI,MAAM,GAAK;AAC/E;AAUO,SAAS,oBAAoB,MAAc,MAAY,oBAAI,KAAK,GAAS;AAC9E,QAAM,QAA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