@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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/integration/run.ts","../src/daemon/config.ts","../src/integration/integration.ts","../src/integration/connection.ts","../src/integration/invoker.ts","../src/integration/wake.ts","../src/integration/invites.ts","../src/integration/spawn-run.ts"],"sourcesContent":["import * as path from 'node:path'\nimport * as fs from 'node:fs'\nimport { log } from '../util/log.js'\nimport { acquireLeaderLock } from '../daemon/leader-lock.js'\nimport { resolveIdentity, credentialsPath } from '../identity/credentials.js'\nimport { resolveDaemonConfig } from '../daemon/config.js'\nimport { idle } from '../daemon/health.js'\nimport type { IntegrationClient } from '../client-identity.js'\nimport { Integration } from './integration.js'\nimport { integrationDisabledBy, resolveRunBudgetMs, resolveRunProfile, type RunProfile } from './profile.js'\nimport type { RunRunner } from './runner.js'\nimport { writeIntegrationStatus } from './status.js'\n\n// ─── The resident supervisor ────────────────────────────────────────────────\n//\n// This process is RESIDENT. It is registered as a service when the integration\n// is installed, and from then on it simply exists — whether or not anyone has\n// signed in. Installation and authentication are different lifecycles (the\n// shape every comparable daemon uses: tailscaled runs before `tailscale up`,\n// and logging out idles it rather than uninstalling it).\n//\n// no credentials → idle. No socket, no retries, no CPU. Just watch.\n// credentials → connect and wake.\n// credentials change → follow them.\n// AGENTCHAT_INTEGRATION=off → stay resident, hold nothing, wake nothing.\n//\n// A refused key is not this loop's case: the SDK's client stays up in\n// `blocked` and tries a fresh hello every 10–15 minutes (`status` reads\n// `socket blocked` meanwhile), so a rotated-back key or a reinstated account\n// reconnects on its own, and a different key is simply a credential change.\n//\n// The only thing that removes this process is an explicit `daemon disable`.\n//\n// SIGTERM/SIGINT (launchd/systemd stop, Ctrl-C) interrupts a run in flight:\n// the integration SIGTERMs the run's process group and this process waits up\n// to SHUTDOWN_GRACE_MS for it before exiting. A daemon that exited at once\n// left the detached run orphaned, and the restarted daemon's connect found\n// the same tray and started a second run beside it.\n\n/** How often to re-read the identity. A `stat`; the watcher usually beats it. */\nconst POLL_MS = 5_000\n/** How often the watcher flag is consulted while waiting out a poll. */\nconst TICK_MS = 250\n/** Ceiling for retry backoff when the runtime simply is not usable yet. */\nconst MAX_BACKOFF_MS = 5 * 60_000\n/**\n * How long a shutdown waits for an interrupted run to end before the process\n * exits. The runner SIGTERMs the run's process group at once and SIGKILLs 5 s\n * later, so this is normally over in well under a second. Below launchd's\n * `ExitTimeOut` (15 s in the plist this package writes).\n */\nconst SHUTDOWN_GRACE_MS = 10_000\nconst MAX_LOG_BYTES = 5 * 1024 * 1024\nconst KEEP_LOG_BYTES = 1024 * 1024\n\nexport interface RunIntegrationOpts {\n /** THE identity home for the agent this daemon serves. */\n home: string\n /** How to start one headless run of this integration's coding agent. */\n runner: RunRunner\n /** How this integration names itself to the server: the texts runtime and its own version. */\n client: IntegrationClient\n /** The one pointer line a run prompt ends with: how THIS runtime reaches its copy of the manual (`manualPointer(...)`). */\n manualPointer: string\n /**\n * The skill file that follows the served manual (`<skills dir>/agentchat/SKILL.md`):\n * whenever the texts in hand announce a version the file does not carry, the\n * announced manual is downloaded, checked and written over it. Absent, the\n * daemon leaves the manual to the CLI's install and `doctor --fix`.\n */\n manualPath?: string\n /** Scratch dir for runs. The integration decides where; this package never derives one. */\n workdir: string\n /** Defaults to `AGENTCHAT_RUN_PROFILE`, then `answer`. */\n profile?: RunProfile\n /** Defaults to `AGENTCHAT_RUN_BUDGET_MS`, then 10 minutes. */\n budgetMs?: number\n /** Ends the loop (tests). Production runs until SIGTERM/SIGINT. */\n signal?: AbortSignal\n env?: NodeJS.ProcessEnv\n /** Test seam: what a signal-initiated shutdown calls last. Defaults to `process.exit`. */\n exit?: (code: number) => void\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))\n\n/**\n * Identity fingerprint: changes when the user signs out, signs in, or swaps to\n * a different agent. Comparing it is how the supervisor notices without caring\n * why.\n */\nfunction fingerprint(home: string): string | null {\n const id = resolveIdentity(home)\n return id === null ? null : `${id.apiKey}:${id.handle ?? ''}`\n}\n\n/** Bound launchd's append-only file without losing the most recent diagnosis. */\nfunction boundDaemonLog(home: string): void {\n const file = path.join(home, 'daemon.log')\n try {\n const size = fs.statSync(file).size\n if (size <= MAX_LOG_BYTES) return\n const fd = fs.openSync(file, 'r')\n try {\n const keep = Buffer.alloc(Math.min(KEEP_LOG_BYTES, size))\n fs.readSync(fd, keep, 0, keep.length, size - keep.length)\n fs.writeFileSync(\n file,\n `[agentchat:info] older daemon log output truncated at ${new Date().toISOString()}\\n${keep.toString('utf-8')}`,\n )\n } finally {\n fs.closeSync(fd)\n }\n } catch {\n /* absent/unreadable log is not a runtime failure */\n }\n}\n\n/**\n * Run the integration daemon. Returns only on a condition that makes running\n * pointless — another daemon already holding this home's lock — or when\n * `signal` aborts (tests).\n */\nexport async function runIntegration(opts: RunIntegrationOpts): Promise<number> {\n const home = path.resolve(opts.home)\n const workdir = path.resolve(opts.workdir)\n const env = opts.env ?? process.env\n const profile = opts.profile ?? resolveRunProfile(env)\n const budgetMs = opts.budgetMs ?? resolveRunBudgetMs(env)\n boundDaemonLog(home)\n\n // A resident service's output goes to a log file nobody sees until something\n // is wrong, and an empty log is useless for \"is the integration working?\".\n if (process.env['AGENTCHAT_LOG_LEVEL'] === undefined) process.env['AGENTCHAT_LOG_LEVEL'] = 'info'\n\n // Taken for the PROCESS, not for a connection: one resident daemon per\n // identity home, signed in or not.\n const lock = acquireLeaderLock(home)\n if (lock === null) return 1\n\n const disabledBy = integrationDisabledBy(env)\n const disabled = disabledBy !== null\n let live: Integration | null = null\n let liveFingerprint: string | null = null\n let observedFingerprint: string | null = null\n /** Consecutive start failures, for backoff. Reset on success or on a new credential. */\n let failures = 0\n let lastFailure: string | null = null\n let shuttingDown = false\n\n const offStatus = (handle: string | null): void =>\n writeIntegrationStatus(home, {\n version: 2,\n updated_at: new Date().toISOString(),\n pid: process.pid,\n runtime: opts.runner.name,\n handle,\n profile,\n socket: disabled ? 'off' : 'idle',\n wakes: 0,\n wakes_absorbed: 0,\n invites: 0,\n runs_started: 0,\n runs_ok: 0,\n runs_failed: 0,\n runs_timed_out: 0,\n runs_not_started: 0,\n runs_skipped_empty: 0,\n last_run: null,\n retry_rung: 0,\n retry_due_at: null,\n last_error: lastFailure,\n texts: null,\n })\n\n const disconnect = (why: string): void => {\n if (live === null) return\n log.info(`${why} — disconnecting (a run in flight is interrupted), staying resident`)\n live.stop()\n live = null\n liveFingerprint = null\n idle(home)\n }\n\n // The loop notices `shuttingDown` within a tick and takes the one exit path\n // below: stop the integration, give an interrupted run its grace, release, exit.\n const shutdown = (sig: string): void => {\n if (shuttingDown) return\n shuttingDown = true\n log.info(`${sig} — shutting down`)\n }\n const onSigint = (): void => shutdown('SIGINT')\n const onSigterm = (): void => shutdown('SIGTERM')\n process.on('SIGINT', onSigint)\n process.on('SIGTERM', onSigterm)\n\n // Best-effort accelerator so signing in connects in about a second instead of\n // waiting out a poll. fs.watch is unreliable on some filesystems, so the poll\n // below is the real guarantee and this is pure upside.\n let nudged = false\n try {\n fs.mkdirSync(home, { recursive: true })\n const watcher = fs.watch(home, (_event, filename) => {\n if (filename === null || String(filename).startsWith('credentials')) nudged = true\n })\n watcher.on('error', (err) => {\n log.warn(`credential watcher unavailable; polling instead: ${String(err)}`)\n try {\n watcher.close()\n } catch {\n /* already closed */\n }\n })\n watcher.unref()\n } catch {\n /* polling covers it */\n }\n\n log.info(`integration resident for ${home} (${credentialsPath(home)}) — ${opts.client.runtime} ${opts.client.version}`)\n if (disabled) {\n log.info(`${disabledBy}=off — holding no socket and starting no run; the hosted tools and the manual still work in every session`)\n }\n idle(home)\n offStatus(null)\n\n for (;;) {\n if (shuttingDown || opts.signal?.aborted) break\n const fp = fingerprint(home)\n const identityChanged = fp !== observedFingerprint\n if (identityChanged) {\n disconnect(fp === null ? 'signed out' : 'identity changed')\n observedFingerprint = fp\n failures = 0\n lastFailure = null\n if (fp === null || disabled) offStatus(fp === null ? null : resolveIdentity(home)?.handle ?? null)\n }\n\n if (fp === null) {\n // Signed out, or never signed in. Idle.\n } else if (disabled) {\n // Signed in, switched off. Resident, silent.\n } else if (fp !== liveFingerprint) {\n try {\n const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client })\n const candidate = new Integration({\n cfg,\n runner: opts.runner,\n client: opts.client,\n manualPointer: opts.manualPointer,\n ...(opts.manualPath !== undefined ? { manualPath: opts.manualPath } : {}),\n profile,\n budgetMs,\n })\n await candidate.start()\n live = candidate\n liveFingerprint = fp\n failures = 0\n lastFailure = null\n } catch (err) {\n // Runtime not ready (host CLI missing or not signed in), network\n // down, whatever. Stay resident and try again later — exiting would\n // just make the service manager restart us in a loop. Backed off and\n // de-duplicated so a condition that lasts days does not fill the log.\n const msg = String(err instanceof Error ? err.message : err)\n if (msg !== lastFailure) {\n log.warn(`not connecting yet: ${msg}`)\n lastFailure = msg\n offStatus(resolveIdentity(home)?.handle ?? null)\n }\n failures += 1\n live = null\n liveFingerprint = null\n idle(home)\n }\n }\n\n // Wait out the poll interval, but wake as soon as the watcher fires so a\n // sign-in connects in well under a second. Exponential backoff while a\n // start keeps failing, capped — the watcher still wakes us instantly when\n // credentials change, so backing off never delays a real sign-in.\n const waitMs = failures === 0 ? POLL_MS : Math.min(POLL_MS * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS)\n nudged = false\n const deadline = Date.now() + waitMs\n while (!nudged && !shuttingDown && !opts.signal?.aborted && Date.now() < deadline) {\n await sleep(TICK_MS)\n }\n }\n\n process.off('SIGINT', onSigint)\n process.off('SIGTERM', onSigterm)\n if (live !== null) {\n const ended = await live.stopAndWait(SHUTDOWN_GRACE_MS)\n if (!ended) log.warn(`a run in flight did not end within ${Math.round(SHUTDOWN_GRACE_MS / 1000)}s of being interrupted — exiting anyway`)\n live = null\n }\n idle(home)\n lock.release()\n if (shuttingDown) {\n log.info('shutdown complete')\n ;(opts.exit ?? process.exit)(0)\n }\n return 0\n}\n","import * as path from 'node:path'\nimport { AgentChatClient } from 'agentchatme'\nimport { resolveIdentity } from '../identity/credentials.js'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\n\n// ─── Daemon identity resolution ─────────────────────────────────────────────\n//\n// The daemon runs AS one host agent — the same identity that agent's sessions\n// use through the hosted tools, never a separate account. It reads that\n// credential from the home it is GIVEN.\n//\n// The predecessor of this file mapped a `runtime` enum to a home\n// (`codex → ~/.codex/agentchat`, `claude-code → ~/.claude/agentchat`). That\n// mapping is exactly the \"a function that decides can decide wrong\" defect this\n// package exists to make unrepresentable, so it is gone: the caller passes its\n// own home and there is no enum to mis-set.\n\nexport interface DaemonConfig {\n apiKey: string\n handle: string\n apiBase: string\n /** `wss://api.agentchat.me` — the SDK's socket base; it appends `/v1/ws`. */\n wsBase: string\n /** The identity home. Credentials, leader lock, and heartbeat all live here. */\n home: string\n /** Scratch dir for runs (the headless run's cwd). */\n workdir: string\n}\n\n/** `https://api.agentchat.me` → `wss://api.agentchat.me`. */\nexport function wsBaseFor(apiBase: string): string {\n return apiBase.replace(/^http/, 'ws').replace(/\\/+$/, '')\n}\n\n/** `https://api.agentchat.me` → `wss://api.agentchat.me/v1/ws`, for logs and checks. */\nexport function wsUrlFor(apiBase: string): string {\n return `${wsBaseFor(apiBase)}/v1/ws`\n}\n\nexport interface ResolveDaemonOpts {\n /** THE identity home. Required — this module never derives one. */\n home: string\n /** The run workdir. Required — this module never derives one either. */\n workdir: string\n /** How to identify to the server when the handle has to be asked for. */\n client: IntegrationClient\n}\n\n/**\n * Resolve the identity the daemon runs as.\n *\n * Async because the handle is load-bearing at runtime — it filters this agent's\n * own outbound echoed back by server fan-out. An env-only identity\n * (`AGENTCHAT_API_KEY`, no credentials file) has no handle on disk, so we ask\n * the server rather than starting up blind and waking on ourselves.\n */\nexport async function resolveDaemonConfig(opts: ResolveDaemonOpts): Promise<DaemonConfig> {\n const home = path.resolve(opts.home)\n const id = resolveIdentity(home)\n if (id === null) {\n throw new Error(`no AgentChat identity in ${home} — register this agent first`)\n }\n\n // An environment key is the authenticated identity even when this home also\n // contains an older credentials file. That file's handle is not evidence\n // about the env key, so resolve it from the server.\n let handle = id.source === 'file' ? id.handle : null\n if (handle === null) {\n const client = new AgentChatClient({\n apiKey: id.apiKey,\n baseUrl: id.apiBase,\n clientIdentity: clientIdentityOf(opts.client),\n timeoutMs: 10_000,\n })\n const me = await client.getMe().catch(() => null)\n if (me === null || typeof me.handle !== 'string' || me.handle.length === 0) {\n throw new Error(\n 'could not determine this agent’s handle (no credentials file, and /v1/agents/me did not answer)',\n )\n }\n handle = me.handle\n }\n\n return {\n apiKey: id.apiKey,\n handle,\n apiBase: id.apiBase,\n wsBase: wsBaseFor(id.apiBase),\n home,\n workdir: path.resolve(opts.workdir),\n }\n}\n","import { AgentChatClient } from 'agentchatme'\nimport { log } from '../util/log.js'\nimport type { DaemonConfig } from '../daemon/config.js'\nimport { beat, idle } from '../daemon/health.js'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\nimport { IntegrationConnection, type InviteWake } from './connection.js'\nimport { IntegrationInvoker } from './invoker.js'\nimport { OfferedInvites } from './invites.js'\nimport { buildRunPrompts, type RunPrompts } from './prompts.js'\nimport type { RunProfile } from './profile.js'\nimport type { RunRunner } from './runner.js'\nimport { writeIntegrationStatus, type IntegrationStatus, type SocketState } from './status.js'\nimport { TextsStore } from './texts.js'\nimport { ManualFollower, type ManualFetch } from '../skill/served-manual.js'\nimport { trayHasWaiting } from './tray.js'\n\n// ─── The integration: a connection, an invoker, a runner ────────────────────\n//\n// Everything it knows about the agent arrives in `DaemonConfig`; everything it\n// knows about the coding agent arrives as a `RunRunner`. It cannot name a\n// host, so it cannot act on the wrong one.\n//\n// A WAKE IS NOT A RUN. Every wake — a `message.new` frame, a `wake` frame, the\n// connect-time catch-up, a ladder re-wake — goes through the invoker, which\n// reads one COUNT before it starts a run (`trayHasWaiting`: `GET /v1/inbox?\n// limit=1` through the SDK, never a card, never a body, marks nothing read)\n// and starts none when the tray is empty. That single guard is what makes\n// reconnects cheap: sleep/wake, Wi-Fi roaming and every server deploy\n// reconnect the whole fleet, and a reconnect with nothing unread costs a\n// count, not a run.\n//\n// On `hello.ok` the integration therefore simply wakes once (catching a\n// backlog no frame announced; it coalesces with whatever the server re-offers\n// after the hello) and reads the pending group invites (`GET\n// /v1/groups/invites` through the SDK): the server pushes an invite live only\n// and never re-offers it, so an invite that arrived while the laptop was\n// closed is surfaced here. Deduplicated downstream against the invites\n// already offered from this machine. A failed invite read is logged, never\n// fatal.\n//\n// The texts a run starts with are the server's (`GET /v1/texts`), fetched at\n// start, refreshed daily, cached in the identity home for an offline start.\n// The same texts announce the current manual; with a `manualPath` the skill\n// file follows it on that cadence (`ManualFollower`: a download only when the\n// announced version is not the one on disk, the old file kept on any failure).\n\nconst HEARTBEAT_MS = 30_000\nconst STATUS_MS = 30_000\n/** HTTP calls the daemon makes are counts and texts; none deserves a long wait or the SDK's retry ramp. */\nconst HTTP_TIMEOUT_MS = 10_000\n\nexport interface IntegrationOptions {\n readonly cfg: DaemonConfig\n readonly runner: RunRunner\n /** How this integration names itself to the server (texts runtime + its version). */\n readonly client: IntegrationClient\n /** The one pointer line a run prompt ends with (`manualPointer(...)`). */\n readonly manualPointer: string\n /** The skill file that follows the served manual (`<skills dir>/agentchat/SKILL.md`); absent, the daemon leaves the manual to the CLI. */\n readonly manualPath?: string\n /** Injectable for tests; the manual download's `fetch`. */\n readonly manualFetch?: ManualFetch\n readonly profile: RunProfile\n readonly budgetMs: number\n /** Injectable for tests; defaults to a real connection on the SDK socket. */\n readonly connection?: IntegrationConnection\n /** Injectable for tests; defaults to an SDK client for `cfg`. */\n readonly api?: AgentChatClient\n /** Injectable for tests; defaults to a store on `api` and the identity home. */\n readonly texts?: TextsStore\n}\n\nexport class Integration {\n private readonly api: AgentChatClient\n private readonly connection: IntegrationConnection\n private readonly texts: TextsStore\n private readonly manual: ManualFollower | null\n private readonly invoker: IntegrationInvoker\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null\n private statusTimer: ReturnType<typeof setInterval> | null = null\n private lastError: string | null = null\n private stopping = false\n\n constructor(private readonly options: IntegrationOptions) {\n const { cfg, client } = options\n this.api =\n options.api ??\n new AgentChatClient({\n apiKey: cfg.apiKey,\n baseUrl: cfg.apiBase,\n clientIdentity: clientIdentityOf(client),\n timeoutMs: HTTP_TIMEOUT_MS,\n retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 },\n })\n this.manual =\n options.manualPath === undefined\n ? null\n : new ManualFollower({ path: options.manualPath, apiBase: cfg.apiBase, ...(options.manualFetch !== undefined ? { fetch: options.manualFetch } : {}) })\n this.texts =\n options.texts ??\n new TextsStore({ home: cfg.home, runtime: client.runtime, client: this.api, onChange: () => this.textsChanged() })\n this.invoker = new IntegrationInvoker({\n runner: options.runner,\n prompts: () => this.runPrompts(),\n budgetMs: options.budgetMs,\n onChange: () => this.writeStatus(),\n trayHasWaiting: () => trayHasWaiting(this.api),\n offeredInvites: OfferedInvites.load(cfg.home),\n })\n this.connection =\n options.connection ??\n new IntegrationConnection({ apiKey: cfg.apiKey, wsBase: cfg.wsBase, selfHandle: cfg.handle, client })\n this.connection.on('wake', (wake) => this.invoker.wake(wake.source))\n this.connection.on('invite', (invite) => {\n this.invoker.invite(invite)\n })\n this.connection.on('ready', () => {\n void this.catchUp()\n })\n this.connection.on('state', (state) => {\n if (state === 'ready') {\n beat(cfg.home)\n // An accepted hello lifts a refusal: the key works again.\n this.lastError = null\n } else {\n idle(cfg.home)\n }\n this.writeStatus()\n })\n this.connection.on('blocked', (detail) => {\n // A refused key is a state to show, not to die from: the SDK's client\n // stays up in `blocked` and tries a fresh hello every 10–15 min; `status`\n // reads `socket blocked` with this line as the last error until one is\n // accepted, or the user signs in with another key (a new connection).\n this.lastError = detail\n this.writeStatus()\n })\n }\n\n async start(): Promise<void> {\n const pre = await this.options.runner.preflight()\n if (!pre.ok) {\n throw new Error(`runtime (${this.options.runner.name}) not ready: ${pre.detail ?? 'unknown'}`)\n }\n log.info(\n `integration up as @${this.options.cfg.handle} via ${this.options.runner.name} (${this.options.client.runtime} ${this.options.client.version}), profile ${this.options.profile}; fetching the served texts, then holding the socket`,\n )\n // The start-time fetch settles before the socket opens, so the first wake\n // has the freshest text; a failure logs once and the cache (if any) serves.\n await this.texts.start()\n if (this.stopping) return\n this.connection.start()\n this.heartbeatTimer = setInterval(() => {\n if (this.connection.connected) beat(this.options.cfg.home)\n }, HEARTBEAT_MS)\n this.heartbeatTimer.unref()\n this.statusTimer = setInterval(() => this.writeStatus(), STATUS_MS)\n this.statusTimer.unref()\n this.writeStatus()\n }\n\n /**\n * Stop holding the socket and interrupt a run in flight (its process group\n * is SIGTERMed by the runner). Synchronous; `settled()` or `stopAndWait()`\n * tell when the run has actually ended.\n */\n stop(): void {\n if (this.stopping) return\n this.stopping = true\n if (this.heartbeatTimer) clearInterval(this.heartbeatTimer)\n if (this.statusTimer) clearInterval(this.statusTimer)\n this.invoker.stop()\n this.texts.stop()\n this.manual?.stop()\n this.connection.stop()\n idle(this.options.cfg.home)\n this.writeStatus()\n }\n\n /**\n * `stop()`, then wait up to `graceMs` for the interrupted run to end. What a\n * shutdown awaits before the process exits, so a launchd/systemd stop\n * reaches the child and the restarted daemon does not find a run still\n * going. Resolves true when nothing is running any more.\n */\n async stopAndWait(graceMs: number): Promise<boolean> {\n this.stop()\n let timer: ReturnType<typeof setTimeout> | null = null\n try {\n return await Promise.race([\n this.invoker.settled().then(() => true),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), graceMs)\n }),\n ])\n } finally {\n if (timer !== null) clearTimeout(timer)\n }\n }\n\n /** A run in flight finishes on its own; this resolves when it has. */\n settled(): Promise<void> {\n return this.invoker.settled()\n }\n\n snapshot(): IntegrationStatus {\n const c = this.invoker.counters()\n // Stopping reads `closed` whatever the socket was doing; a refusal stays\n // visible to `status` and `doctor` as the last error.\n const socket: SocketState = this.stopping ? 'closed' : this.connection.state\n const texts = this.texts.current()\n return {\n version: 2,\n updated_at: new Date().toISOString(),\n pid: process.pid,\n runtime: this.options.runner.name,\n handle: this.options.cfg.handle,\n profile: this.options.profile,\n socket,\n wakes: c.wakes,\n wakes_absorbed: c.absorbed,\n invites: c.invites,\n runs_started: c.runsStarted,\n runs_ok: c.runsOk,\n runs_failed: c.runsFailed,\n runs_timed_out: c.runsTimedOut,\n runs_not_started: c.runsNotStarted,\n runs_skipped_empty: c.runsSkippedEmpty,\n last_run: c.lastRun,\n retry_rung: c.retryRung,\n retry_due_at: c.retryDueAt === null ? null : new Date(c.retryDueAt).toISOString(),\n last_error: this.lastError,\n texts: {\n source: this.texts.source,\n fetched_at: this.texts.fetchedAt,\n version: texts?.version ?? null,\n manual_version: texts?.manual.version ?? null,\n },\n }\n }\n\n /**\n * After every change in the texts in hand: the status file, and the skill\n * file brought to the manual they announce. Exposed for an injected store's\n * `onChange` (tests); the store this class builds calls it itself.\n */\n textsChanged(): void {\n this.writeStatus()\n if (this.manual !== null && !this.stopping) void this.manual.follow(this.texts.current()?.manual ?? null)\n }\n\n /** The served texts plus the pointer line, or null while no text is in hand. */\n private async runPrompts(): Promise<RunPrompts | null> {\n const texts = await this.texts.ensure()\n return texts === null ? null : buildRunPrompts(texts, this.options.manualPointer)\n }\n\n /**\n * The connect-time catch-up: one wake (the invoker counts the tray before\n * any run, so an empty tray costs a count, not a run) and the pending invites.\n */\n private async catchUp(): Promise<void> {\n if (this.stopping) return\n log.info('wake — connect (a run starts only if the tray has something unread)')\n this.invoker.wake('connect')\n try {\n const invites = await this.api.listGroupInvites()\n if (this.stopping) return\n let surfaced = 0\n for (const row of invites) {\n const invite: InviteWake = {\n inviteId: row.id,\n groupId: row.group_id ?? null,\n groupName: row.group_name ?? null,\n inviterHandle: row.inviter_handle ?? null,\n }\n if (this.invoker.invite(invite)) surfaced += 1\n }\n if (surfaced > 0) log.info(`wake — ${surfaced} pending group invite(s) surfaced on connect`)\n } catch (err) {\n log.warn(`connect-time invite list failed (${err instanceof Error ? err.message : String(err)}) — live invite frames are unaffected`)\n }\n this.writeStatus()\n }\n\n private writeStatus(): void {\n writeIntegrationStatus(this.options.cfg.home, this.snapshot())\n }\n}\n","import { EventEmitter } from 'node:events'\nimport { RealtimeClient, type BlockedInfo, type RealtimeState, type WakeFrame, type WsMessage } from 'agentchatme'\nimport { log } from '../util/log.js'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\nimport { normalizeHandle } from '../skill/identity-line.js'\nimport type { SocketState } from './status.js'\n\n// ─── The connection: the SDK's socket, read as wakes ────────────────────────\n//\n// The socket is the SDK's `RealtimeClient` — hello, capabilities, acks,\n// reconnect backoff, the handshake and liveness watchdogs, frame validation\n// all live there, once, for every AgentChat integration. With `ackOnReceipt`\n// it acknowledges every `message.new` the moment the frame is parsed:\n// DELIVERED means this machine received the message. Whether the agent has\n// looked is read state, which only the agent's own verdict inside its run\n// changes; an early ack never empties the tray (docs/architecture.md, rule 5).\n//\n// One client, for as long as this connection lives. The SDK's client never\n// dies on its own: every close leads to a backoff and a fresh attempt (capped\n// at 30 s, five minutes once an outage is 60 attempts long), a refused\n// credential leads to `blocked` — a fresh hello every 10–15 minutes until one\n// is accepted — and only `disconnect()` (our `stop()`) ends it. Nothing here\n// classifies a close or replaces the client; the credential's fate is the\n// supervisor's only through the identity file (a new key is a new\n// connection).\n//\n// What this class adds is the integration's reading of the SDK's events:\n//\n// * `message.new` → a WAKE. Two facts are read: the sender (to skip the\n// echo of this agent's own sends) and the ids (for the\n// log line). The body is never read; the agent reads it\n// through the hosted tools inside its run.\n// * `wake` → a WAKE of the second kind: a deferred conversation's\n// reminder came due. No message, nothing to ack. Handled\n// exactly like a `message.new`: one coalesced wake.\n// * `group.invite.received` → an invite wake.\n// * `onConnect` → `ready`. NOT a wake by itself: the holder wakes once on\n// it, and the server re-offers unacked envelopes right\n// after it. Whether any of that deserves a run is the\n// invoker's tray count, never this class's call.\n// * `state` → the status file's `socket` word (`socketStateOf`): the\n// SDK's `backoff` is `reconnecting`, its `blocked` is\n// `blocked` — one word for one state across the layers;\n// the refusal itself travels as the `blocked` event's\n// detail, for `last error`.\n//\n// `ws` stays a dependency of this package although nothing here imports it:\n// the SDK prefers it on Node, and only on `ws` are the server's 45 s pings\n// visible to the SDK's idle deadline (100 s) — a quiet but healthy socket\n// stays up, a dead one is reopened.\n\nexport interface MessageWake {\n readonly source: 'message'\n readonly sender: string | null\n readonly conversationId: string | null\n readonly messageId: string | null\n}\n\n/** A `wake` frame: a deferred conversation's reminder came due. */\nexport interface ReminderWake {\n readonly source: 'reminder'\n readonly conversationId: string\n readonly anchorMessageId: string\n readonly step: number\n}\n\nexport type Wake = MessageWake | ReminderWake\n\nexport interface InviteWake {\n readonly inviteId: string\n readonly groupId: string | null\n readonly groupName: string | null\n readonly inviterHandle: string | null\n}\n\nexport interface IntegrationConnectionEvents {\n wake: (wake: Wake) => void\n invite: (invite: InviteWake) => void\n /** This agent's own outbound, echoed back by server fan-out. Not a wake. */\n echo: () => void\n state: (state: SocketState, previous: SocketState) => void\n /** `hello.ok` arrived: the connection is live. Once per (re)connection, after `state` → `ready`. */\n ready: () => void\n /**\n * The server refused the credential on the hello (the SDK is `blocked`,\n * and so is `state`). Once per rejected attempt — the first one in a\n * run and every 10–15 minutes after it, until a hello is accepted and\n * `state` → `ready` lifts it. `detail` is the line `status` shows as the\n * last error.\n */\n blocked: (detail: string, info: BlockedInfo) => void\n}\n\nexport interface IntegrationConnectionOptions {\n readonly apiKey: string\n /** `wss://api.agentchat.me` — the SDK appends `/v1/ws`. */\n readonly wsBase: string\n /** This agent's handle, to recognise its own echo. Bare, any case. */\n readonly selfHandle: string\n readonly client: IntegrationClient\n /** Test seams for the SDK's backoff; its defaults (500 ms → 30 s) otherwise. */\n readonly reconnectIntervalMs?: number\n readonly maxReconnectIntervalMs?: number\n}\n\n/**\n * The SDK's connection state in the status file's vocabulary. Pure. `previous`\n * is the status word in effect, which decides two things the SDK's state alone\n * does not say: a `connecting` after a close is `reconnecting`, and the slow\n * retry out of `blocked` (`connecting` again) stays `blocked` — only an\n * accepted hello (`ready`) lifts it. `stopped` is `closed` from any state; a\n * refusal stays visible as the last error, not as the socket word.\n */\nexport function socketStateOf(next: RealtimeState, previous: SocketState): SocketState {\n switch (next) {\n case 'idle':\n return 'idle'\n case 'connecting':\n if (previous === 'blocked') return 'blocked'\n return previous === 'idle' || previous === 'connecting' ? 'connecting' : 'reconnecting'\n case 'ready':\n return 'ready'\n case 'backoff':\n return 'reconnecting'\n case 'blocked':\n return 'blocked'\n case 'stopped':\n return 'closed'\n }\n}\n\n/** The `last error` line for a refused credential: the server's close, what to do, and that the SDK keeps trying. */\nexport function blockedDetail(info: BlockedInfo): string {\n return `auth rejected (close ${info.code}${info.reason ? ` ${info.reason}` : ''}) — check the agent's API key; a fresh hello is tried every 10–15 min until one is accepted`\n}\n\nfunction stringField(record: Record<string, unknown>, keys: readonly string[]): string | null {\n for (const key of keys) {\n const value = record[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return null\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n}\n\nexport class IntegrationConnection extends EventEmitter {\n private rt: RealtimeClient | null = null\n private _state: SocketState = 'idle'\n private stopped = false\n /** Rejected hellos since the last accepted one: the first is an error line, the rest are info. */\n private refusals = 0\n private readonly selfHandle: string\n\n constructor(private readonly options: IntegrationConnectionOptions) {\n super()\n this.selfHandle = normalizeHandle(options.selfHandle)\n }\n\n get state(): SocketState {\n return this._state\n }\n\n /** True only while the socket is live — `hello.ok` received, not merely open. */\n get connected(): boolean {\n return this._state === 'ready'\n }\n\n override on<E extends keyof IntegrationConnectionEvents>(event: E, listener: IntegrationConnectionEvents[E]): this {\n return super.on(event, listener as (...args: unknown[]) => void)\n }\n\n /** Open the SDK's client. Once: it lives until `stop()`, reconnecting on its own. */\n start(): void {\n if (this.rt !== null || this.stopped) return\n const rt = new RealtimeClient({\n apiKey: this.options.apiKey,\n baseUrl: this.options.wsBase,\n clientIdentity: clientIdentityOf(this.options.client),\n // Delivered = this machine received it. Acked at parse time, before\n // anything here runs; read state is the agent's verdict, separately.\n ackOnReceipt: true,\n reconnect: true,\n ...(this.options.reconnectIntervalMs !== undefined ? { reconnectInterval: this.options.reconnectIntervalMs } : {}),\n ...(this.options.maxReconnectIntervalMs !== undefined ? { maxReconnectInterval: this.options.maxReconnectIntervalMs } : {}),\n })\n this.rt = rt\n this.setState('connecting')\n\n rt.on('state', (next) => this.setState(socketStateOf(next, this._state)))\n rt.on('blocked', (info) => this.onBlocked(info))\n rt.onConnect(() => {\n this.refusals = 0\n log.info(`socket ready (hello.ok) — acks ${rt.ackNegotiated ? 'on receipt' : 'not negotiated by this server'}`)\n this.emit('ready')\n })\n rt.onDisconnect(({ code, reason, initiator }) => {\n if (this.stopped) return\n log.warn(`socket closed (${code}${reason ? ` ${reason}` : ''}${initiator === 'client' ? ', by this client' : ''})`)\n })\n rt.onError((err) => {\n if (this.stopped) return\n log.warn(`socket: ${err.message}`)\n })\n rt.on('message.new', (message) => {\n if (!this.stopped) this.onMessageFrame(message)\n })\n rt.on('wake', (frame) => {\n if (!this.stopped) this.onWakeFrame(frame)\n })\n rt.on('group.invite.received', (message) => {\n if (!this.stopped) this.onInviteFrame(message)\n })\n\n rt.connect().catch((err: unknown) => {\n // A failed attempt the SDK retries was already announced through\n // onError. The one it does not retry — no WebSocket implementation at\n // all — leaves the client idle, and is said once.\n if (this.stopped || rt.state !== 'idle') return\n log.error(`socket cannot be opened (${err instanceof Error ? err.message : String(err)}) — no WebSocket implementation; holding no socket`)\n })\n }\n\n /** End the SDK's client. Final: a stopped connection is not restarted. */\n stop(): void {\n if (this.stopped) return\n this.stopped = true\n const rt = this.rt\n this.rt = null\n try {\n rt?.disconnect() // fires `state` → `stopped`, mapped to `closed`; a late frame flushed here is ignored\n } catch {\n /* already closed */\n }\n this.setState('closed') // also for a connection that was never started\n }\n\n private setState(next: SocketState): void {\n const prev = this._state\n if (prev === next) return\n this._state = next\n // `ready` is logged with the ack note on hello.ok, `blocked` with the\n // refusal on the blocked event.\n if (next === 'connecting') log.info('socket connecting')\n else if (next === 'reconnecting') log.info('socket reconnecting — the SDK backs off and retries; it never gives up')\n else if (next === 'closed') log.info('socket closed')\n this.emit('state', next, prev)\n }\n\n /** The SDK is `blocked`: the server refused the credential on the hello. Fires per rejected attempt. */\n private onBlocked(info: BlockedInfo): void {\n if (this.stopped) return\n const detail = blockedDetail(info)\n this.refusals += 1\n if (this.refusals === 1) {\n log.error(`socket blocked (auth): ${detail}`)\n } else {\n const next = info.retryInMs === null ? 'no retry' : `next hello in about ${Math.max(1, Math.round(info.retryInMs / 60_000))} min`\n log.info(`socket still blocked (auth): close ${info.code}${info.reason ? ` ${info.reason}` : ''} — ${next}`)\n }\n this.emit('blocked', detail, info)\n }\n\n /**\n * A `message.new` frame. Only the sender (echo filter) and the ids (log\n * line) are read. `content`, `metadata`, previews — never touched. The SDK\n * acked it before this ran.\n */\n private onMessageFrame(message: WsMessage): void {\n const payload = asRecord(message.payload)\n if (payload === null) {\n log.warn('socket: message.new without an object payload — dropped')\n return\n }\n const senderRaw = stringField(payload, ['sender', 'sender_handle', 'from'])\n const sender = senderRaw === null ? null : normalizeHandle(senderRaw)\n const messageId = stringField(payload, ['id'])\n const conversationId = stringField(payload, ['conversation_id'])\n if (sender !== null && sender === this.selfHandle) {\n log.debug(`socket: own echo in ${conversationId ?? '?'} — not a wake`)\n this.emit('echo')\n return\n }\n log.info(`wake — message.new conv=${conversationId ?? '?'} msg=${messageId ?? '?'} from=@${sender ?? '?'}`)\n this.emit('wake', { source: 'message', sender, conversationId, messageId } satisfies MessageWake)\n }\n\n /** A `wake` frame, validated by the SDK. No message, nothing to ack. */\n private onWakeFrame(frame: WakeFrame): void {\n const { conversation_id, anchor_message_id, step, reason } = frame.payload\n log.info(`wake — ${reason} conv=${conversation_id} anchor=${anchor_message_id} step=${step}`)\n this.emit('wake', {\n source: 'reminder',\n conversationId: conversation_id,\n anchorMessageId: anchor_message_id,\n step,\n } satisfies ReminderWake)\n }\n\n private onInviteFrame(message: WsMessage): void {\n const payload = asRecord(message.payload)\n if (payload === null) {\n log.warn('socket: group.invite.received without an object payload — dropped')\n return\n }\n const inviteId = stringField(payload, ['invite_id', 'id'])\n if (inviteId === null) {\n log.warn('socket: group invite without an invite id — dropped')\n return\n }\n const invite: InviteWake = {\n inviteId,\n groupId: stringField(payload, ['group_id', 'conversation_id']),\n groupName: stringField(payload, ['group_name', 'name']),\n inviterHandle: stringField(payload, ['inviter_handle', 'inviter', 'from']),\n }\n log.info(`wake — group invite ${invite.inviteId} to ${invite.groupId ?? '?'} from=@${invite.inviterHandle ?? '?'}`)\n this.emit('invite', invite)\n }\n}\n","import * as crypto from 'node:crypto'\nimport { log } from '../util/log.js'\nimport { WakeCoalescer, DEFAULT_WAKE_DEBOUNCE_MS, type TimerHandle } from './wake.js'\nimport type { RunPrompts } from './prompts.js'\nimport type { RunKind, RunOutcome, RunRunner } from './runner.js'\nimport type { InviteWake } from './connection.js'\nimport { OfferedInvites, type OfferedInviteStore } from './invites.js'\nimport type { IntegrationLastRun } from './status.js'\n\n// ─── Wake → one run. The only path from the socket to the agent ─────────────\n//\n// 1. Coalesce. Wakes inside a short window become one (`WakeCoalescer`).\n// 2. Count. Ask the tray whether anything is waiting (`trayHasWaiting`: one\n// `GET /v1/inbox?limit=1` through the SDK — a count, never a card; marks\n// nothing read). Empty → no run: nothing is owed, so the retry ladder\n// resets too. A count that cannot be read (network, 5xx) is not evidence\n// of an empty tray and the wake was real: the run starts anyway.\n// 3. Run. Start ONE headless run of the resident coding agent with the served\n// wake text. The agent reads the tray with the hosted inbox tool, judges\n// every card with the tray's own question, decides or sends through the\n// hosted tools. The run's output is discarded.\n//\n// The count guards EVERY wake run — a frame, a reminder, the connect-time\n// catch-up, a ladder re-wake, the preflight re-wake, the follow-on after a\n// busy run — so no source needs its own \"is this worth a run?\" logic.\n// Sleep/wake, Wi-Fi roaming and every server deploy reconnect the whole\n// fleet; a reconnect with nothing waiting costs a count, not a run.\n//\n// One run at a time per agent, ever. A wake that lands while a run is in\n// flight earns exactly one more cycle after it (counted first, so a burst the\n// first run already answered costs a count, not a run); ten wakes during a\n// run still earn one.\n//\n// A run that fails to start (runtime missing, auth expired, non-zero exit with\n// nothing on stdout), fails, or exceeds its budget schedules a re-wake on a\n// local ladder (60 s, 5 min, 30 min), because a connected socket gets no\n// re-ring from the server. One outage climbs one rung: a retry already on its\n// way is never replaced by a later one. A successful wake run, or a count that\n// finds the tray empty, resets the ladder and cancels a pending re-wake:\n// nothing is owed any more.\n//\n// When the ladder is exhausted the invoker does not go deaf. It asks the\n// runner's `preflight()` every PREFLIGHT_WATCH_MS; if the runtime was found\n// unusable (signed out, binary gone) and later answers ok, that flip earns ONE\n// re-wake — a day's backlog behind a signed-out CLI is read when the user\n// signs back in, not when the next new peer happens to write. If the first\n// probe already says ok, the failures are not the runtime's readiness and the\n// watch stops: the backlog waits for the next wake, as it always did. A wake\n// from any source while watching is served as usual and, if it succeeds, ends\n// the watch.\n//\n// `stop()` interrupts a run in flight: the run's `AbortSignal` fires, the\n// runner SIGTERMs the run's process group, and `settled()` resolves when it\n// has ended. An integration that stops without doing this leaves a model call\n// running that nobody will read and that the next connect would run again.\n//\n// Group invites are the second wake kind: not on the tray, one run each with\n// the served invite prompt, serialized on the same worker. An invite is\n// OFFERED once per machine — the id is written to the identity home the\n// moment its run has started (the runner's `onStarted`, `OfferedInvites`), so\n// a daemon restart does not start one paid run per still-pending invite, and\n// neither does a run cut short by a shutdown or a crash: the model call was\n// made. An invite whose run never got going (`not_started`: runtime missing,\n// signed out, nothing on stdout) is taken back out and offered again on the\n// next wake; the next connect's listing finds it still pending.\n//\n// The prompts arrive lazily: the served texts may not have been fetched yet\n// when the first wake lands. A run with no texts in hand does not start — it\n// counts as `not_started`, and the wake retries on the ladder.\n//\n// The integration reads NO tray and makes NO verdicts. That is the run's job.\n\nexport const RETRY_LADDER_MS: readonly number[] = [60_000, 300_000, 1_800_000]\n\n/** After the ladder is exhausted: how often the runtime is asked whether it is usable again. */\nexport const PREFLIGHT_WATCH_MS = 5 * 60_000\n\nconst MAX_TAKEN = 1_000\n\nexport interface IntegrationInvokerOptions {\n readonly runner: RunRunner\n /** The run prompts, resolved per run; null when the served texts are not available yet. */\n readonly prompts: () => Promise<RunPrompts | null>\n /** A run is killed past this and counts as failed. */\n readonly budgetMs: number\n readonly debounceMs?: number\n readonly retryLadderMs?: readonly number[]\n readonly preflightWatchMs?: number\n /**\n * Is anything waiting on the tray? Asked before every wake run (never\n * before an invite run). Resolves the answer; rejects when the count could\n * not be read, and then the run starts anyway. Absent: every wake runs.\n */\n readonly trayHasWaiting?: () => Promise<boolean>\n /** Invites already offered to a run from this machine. Defaults to an in-memory set. */\n readonly offeredInvites?: OfferedInviteStore\n /** Called after every state change (a status writer hangs off this). */\n readonly onChange?: () => void\n readonly now?: () => number\n readonly setTimeout?: (fn: () => void, ms: number) => TimerHandle\n readonly clearTimeout?: (handle: TimerHandle) => void\n readonly runId?: () => string\n}\n\nexport interface InvokerCounters {\n readonly wakes: number\n readonly absorbed: number\n readonly invites: number\n readonly runsStarted: number\n readonly runsOk: number\n readonly runsFailed: number\n readonly runsTimedOut: number\n readonly runsNotStarted: number\n /** Wake cycles that found the tray empty and started no run. */\n readonly runsSkippedEmpty: number\n readonly retryRung: number\n readonly retryDueAt: number | null\n readonly lastRun: IntegrationLastRun | null\n readonly running: boolean\n}\n\nexport class IntegrationInvoker {\n private readonly runner: RunRunner\n private readonly prompts: () => Promise<RunPrompts | null>\n private readonly budgetMs: number\n private readonly ladder: readonly number[]\n private readonly preflightWatchMs: number\n private readonly now: () => number\n private readonly _setTimeout: (fn: () => void, ms: number) => TimerHandle\n private readonly _clearTimeout: (handle: TimerHandle) => void\n private readonly onChange: () => void\n private readonly newRunId: () => string\n private readonly trayHasWaiting: (() => Promise<boolean>) | null\n private readonly offered: OfferedInviteStore\n private readonly coalescer: WakeCoalescer\n\n private cycleDue = false\n private running: Promise<void> | null = null\n private inFlight: AbortController | null = null\n private stopped = false\n /** Invites queued for a run, in arrival order. */\n private readonly invites: InviteWake[] = []\n /** Invites whose run did not start; offered again on the next wake. */\n private readonly invitesAwaitingRetry: InviteWake[] = []\n /**\n * Invite ids this process has taken, offered or not. The on-disk store says\n * what was OFFERED; this says what is already in hand here — queued, in\n * flight, or awaiting its retry — so the connect-time listing and a live\n * frame for the same invite cannot queue it twice.\n */\n private readonly taken = new Set<string>()\n private retryRung = 0\n private preflightWatch: TimerHandle | null = null\n private preflightWasDown = false\n\n private invitesSeen = 0\n private runsStarted = 0\n private runsOk = 0\n private runsFailed = 0\n private runsTimedOut = 0\n private runsNotStarted = 0\n private runsSkippedEmpty = 0\n private lastRun: IntegrationLastRun | null = null\n\n constructor(options: IntegrationInvokerOptions) {\n this.runner = options.runner\n this.prompts = options.prompts\n this.budgetMs = options.budgetMs\n this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS\n this.preflightWatchMs = options.preflightWatchMs ?? PREFLIGHT_WATCH_MS\n this.now = options.now ?? Date.now\n this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms))\n this._clearTimeout = options.clearTimeout ?? ((handle) => clearTimeout(handle))\n this.onChange = options.onChange ?? (() => undefined)\n this.newRunId = options.runId ?? (() => crypto.randomUUID())\n this.trayHasWaiting = options.trayHasWaiting ?? null\n this.offered = options.offeredInvites ?? new OfferedInvites(null)\n this.coalescer = new WakeCoalescer({\n onFire: () => this.onWakeFired(),\n debounceMs: options.debounceMs ?? DEFAULT_WAKE_DEBOUNCE_MS,\n now: this.now,\n ...(options.setTimeout ? { setTimeout: options.setTimeout } : {}),\n ...(options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}),\n })\n }\n\n // ─── wakes ──────────────────────────────────────────────────────────────\n\n /** A wake from the socket (a frame), the connect-time catch-up, or any other source. Coalesced, then run. */\n wake(source: string): void {\n if (this.stopped) return\n log.debug(`wake (${source})`)\n this.coalescer.wake()\n this.onChange()\n }\n\n /**\n * The second wake kind. Offered once per machine: an invite already offered\n * to a run, already queued, or awaiting its retry is not queued again.\n * Returns true when newly queued.\n */\n invite(invite: InviteWake): boolean {\n if (this.stopped) return false\n if (this.offered.has(invite.inviteId) || this.taken.has(invite.inviteId)) return false\n this.taken.add(invite.inviteId)\n if (this.taken.size > MAX_TAKEN) {\n const oldest = this.taken.values().next().value\n if (oldest !== undefined) this.taken.delete(oldest)\n }\n this.invitesSeen += 1\n this.invites.push(invite)\n this.onChange()\n this.schedule()\n return true\n }\n\n /**\n * Cancel timers and interrupt a run in flight (its signal aborts; the\n * runner SIGTERMs the run's process group). `settled()` resolves when the\n * interrupted run has ended.\n */\n stop(): void {\n this.stopped = true\n this.coalescer.stop()\n this.clearPreflightWatch()\n this.inFlight?.abort()\n }\n\n /** The promise of the work currently running, for tests and graceful stops. */\n settled(): Promise<void> {\n return this.running ?? Promise.resolve()\n }\n\n counters(): InvokerCounters {\n return {\n wakes: this.coalescer.wakes,\n absorbed: this.coalescer.absorbed,\n invites: this.invitesSeen,\n runsStarted: this.runsStarted,\n runsOk: this.runsOk,\n runsFailed: this.runsFailed,\n runsTimedOut: this.runsTimedOut,\n runsNotStarted: this.runsNotStarted,\n runsSkippedEmpty: this.runsSkippedEmpty,\n retryRung: this.retryRung,\n retryDueAt: this.coalescer.delayedDue,\n lastRun: this.lastRun,\n running: this.running !== null,\n }\n }\n\n // ─── worker ─────────────────────────────────────────────────────────────\n\n private onWakeFired(): void {\n this.cycleDue = true\n // An invite whose run did not start gets its next chance on the next\n // wake, whatever woke us.\n if (this.invitesAwaitingRetry.length > 0) {\n const retry = this.invitesAwaitingRetry.splice(0)\n log.info(`${retry.length} group invite(s) whose run did not start are offered again`)\n this.invites.push(...retry)\n }\n this.schedule()\n }\n\n /** Run the worker if idle. One run at a time; work that lands mid-run runs afterwards. */\n private schedule(): void {\n if (this.running) return\n this.running = this.drain().finally(() => {\n this.running = null\n this.onChange()\n if (!this.stopped && (this.cycleDue || this.invites.length > 0)) this.schedule()\n })\n }\n\n private async drain(): Promise<void> {\n while (!this.stopped) {\n const invite = this.invites.shift()\n if (invite) {\n await this.run('invite', invite)\n continue\n }\n if (this.cycleDue) {\n // Clear BEFORE the count and the run: a wake landing during either\n // sets it again and earns exactly one more cycle afterwards.\n this.cycleDue = false\n if (!(await this.trayOwesRun())) continue\n await this.run('wake')\n continue\n }\n return\n }\n }\n\n /**\n * The count before a wake run. True: start the run (something waits, or\n * the count could not be read). False: the tray is empty — no run, nothing\n * owed — or the invoker stopped while counting.\n */\n private async trayOwesRun(): Promise<boolean> {\n if (this.trayHasWaiting === null) return true\n let waiting: boolean\n try {\n waiting = await this.trayHasWaiting()\n } catch (err) {\n if (this.stopped) return false\n log.warn(\n `tray count failed (${err instanceof Error ? err.message : String(err)}) — starting the run anyway: a failed count is not an empty tray`,\n )\n return true\n }\n if (this.stopped) return false\n if (waiting) return true\n this.runsSkippedEmpty += 1\n log.info(`wake: the tray is empty — no run (nothing is owed; ${this.runsSkippedEmpty} skipped so far)`)\n this.settleLadder()\n this.onChange()\n return false\n }\n\n /**\n * Nothing is owed any more — a wake run read the whole tray, or a count\n * found it empty: back to the first rung, drop a pending re-wake (it would\n * only ring for a backlog that is already handled), end the preflight watch.\n */\n private settleLadder(): void {\n this.retryRung = 0\n if (this.coalescer.cancelDelayed()) log.info('pending re-wake cancelled — nothing is owed any more')\n this.clearPreflightWatch()\n }\n\n private async run(kind: RunKind, invite?: InviteWake): Promise<void> {\n const runId = this.newRunId()\n const startedAt = this.now()\n this.runsStarted += 1\n this.onChange()\n log.info(`run start kind=${kind} id=${runId} budget=${Math.round(this.budgetMs / 1000)}s`)\n\n const controller = new AbortController()\n this.inFlight = controller\n // An invite is recorded as offered the moment the runtime has started —\n // the paid call is made from then on, whatever ends the run.\n let offerRecorded = false\n const onStarted = (): void => {\n if (invite === undefined || offerRecorded) return\n offerRecorded = true\n this.offered.add(invite.inviteId)\n }\n let outcome: RunOutcome\n try {\n const prompts = await this.prompts()\n if (prompts === null) {\n outcome = {\n state: 'not_started',\n exitCode: null,\n durationMs: this.now() - startedAt,\n detail: 'no served texts in hand: GET /v1/texts has not answered yet and nothing is cached in the identity home',\n }\n } else if (this.stopped) {\n outcome = { state: 'not_started', exitCode: null, durationMs: this.now() - startedAt, detail: 'interrupted before the runtime was started' }\n } else {\n const prompt = kind === 'invite' ? prompts.invite : prompts.wake\n outcome = await this.runner.start({\n kind,\n prompt,\n runId,\n budgetMs: this.budgetMs,\n signal: controller.signal,\n ...(invite !== undefined ? { onStarted } : {}),\n })\n }\n } catch (err) {\n // The runner contract is \"never throws\"; a throw is a bug in the runner,\n // not a reason to drop the wake.\n outcome = {\n state: 'not_started',\n exitCode: null,\n durationMs: this.now() - startedAt,\n detail: `runner threw: ${err instanceof Error ? err.message : String(err)}`,\n }\n } finally {\n if (this.inFlight === controller) this.inFlight = null\n }\n\n this.lastRun = {\n kind,\n started_at: new Date(startedAt).toISOString(),\n ended_at: new Date(this.now()).toISOString(),\n state: outcome.state,\n exit_code: outcome.exitCode,\n duration_ms: outcome.durationMs,\n detail: outcome.detail ?? null,\n }\n\n switch (outcome.state) {\n case 'ok':\n this.runsOk += 1\n // A wake run read the whole tray. An invite run did not, so it leaves\n // a pending wake retry alone.\n if (kind === 'wake') this.settleLadder()\n log.info(`run ok kind=${kind} id=${runId} ${Math.round(outcome.durationMs / 1000)}s (output discarded; any send was the agent's own hosted-tool call)`)\n break\n case 'failed':\n this.runsFailed += 1\n break\n case 'timed_out':\n this.runsTimedOut += 1\n break\n case 'not_started':\n this.runsNotStarted += 1\n break\n }\n\n if (invite !== undefined) this.settleInvite(invite, outcome, offerRecorded)\n\n if (outcome.state !== 'ok') {\n log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ''}`)\n if (this.stopped) {\n // Interrupted by stop(): nothing to schedule, the tray stays unread\n // and the next connect's catch-up finds it.\n } else if (kind === 'wake') {\n // The agent never saw the tray, or did not finish: the cards are still\n // unread. Look again on the ladder instead of waiting for the next peer.\n this.scheduleRetry(`run ${outcome.state}`)\n }\n }\n this.onChange()\n }\n\n /**\n * An invite counts as offered once its run has started (recorded at\n * `onStarted`; a runner that never signals it is recorded here, when the\n * run ends): the agent had its chance, and the invite stays reachable\n * through the hosted invite tools in any later run — including a run this\n * integration interrupted. A run that never got going is no offer: the\n * record is taken back and the invite is held for the next wake.\n */\n private settleInvite(invite: InviteWake, outcome: RunOutcome, offerRecorded: boolean): void {\n if (outcome.state === 'not_started') {\n if (offerRecorded) this.offered.remove(invite.inviteId)\n if (!this.invitesAwaitingRetry.some((i) => i.inviteId === invite.inviteId)) this.invitesAwaitingRetry.push(invite)\n log.info(`group-invite run did not start — invite ${invite.inviteId} is offered again on the next wake`)\n return\n }\n if (!offerRecorded) this.offered.add(invite.inviteId)\n if (outcome.state !== 'ok') log.info(`group-invite run ${outcome.state} — the invite stays pending server-side, reachable through the hosted tools`)\n }\n\n private scheduleRetry(reason: string): void {\n if (this.coalescer.delayedPending) {\n // A retry is already on its way (a wake landed mid-outage and failed\n // again). One outage climbs the ladder once; climbing per failed run\n // would replace the sooner retry with a later one.\n log.info(`${reason} — a re-wake is already scheduled; not climbing the ladder`)\n return\n }\n if (this.retryRung >= this.ladder.length) {\n log.warn(\n `${reason} — retry ladder exhausted; the backlog stays unread. Watching the runtime's preflight every ${Math.round(this.preflightWatchMs / 1000)}s: if it comes back, one re-wake; any wake also re-runs`,\n )\n this.armPreflightWatch()\n return\n }\n const delay = this.ladder[this.retryRung] ?? this.ladder[this.ladder.length - 1] ?? 60_000\n this.retryRung += 1\n log.warn(`${reason} — re-waking in ${Math.round(delay / 1000)}s (rung ${this.retryRung}/${this.ladder.length})`)\n this.coalescer.wakeAfter(delay)\n }\n\n // ─── preflight watch, after an exhausted ladder ─────────────────────────\n\n private armPreflightWatch(): void {\n if (this.stopped || this.preflightWatch !== null) return\n this.preflightWatch = this._setTimeout(() => {\n this.preflightWatch = null\n void this.probePreflight()\n }, this.preflightWatchMs)\n this.onChange()\n }\n\n private clearPreflightWatch(): void {\n if (this.preflightWatch !== null) {\n this._clearTimeout(this.preflightWatch)\n this.preflightWatch = null\n }\n this.preflightWasDown = false\n }\n\n private async probePreflight(): Promise<void> {\n if (this.stopped) return\n let ok: boolean\n try {\n ok = (await this.runner.preflight()).ok\n } catch {\n ok = false\n }\n if (this.stopped) return\n if (!ok) {\n if (!this.preflightWasDown) log.info('runtime preflight is not ok — watching for it to come back')\n this.preflightWasDown = true\n this.armPreflightWatch()\n return\n }\n if (this.preflightWasDown) {\n this.preflightWasDown = false\n log.info('runtime preflight is ok again after an exhausted ladder — waking once')\n this.wake('preflight')\n return\n }\n log.info('runtime preflight was already ok — the failures are not its readiness; the backlog waits for the next wake')\n }\n}\n","// ─── Wake coalescing — one run per burst, not per frame ─────────────────────\n//\n// A `message.new` frame, a `wake` frame, a (re)connect: each is a WAKE — a\n// hint that something may be waiting, never the carrier of what is waiting.\n// A group burst arrives as many frames within a second; the first wake arms a\n// short timer, every wake inside the window is absorbed, and the timer fires\n// exactly once. Whoever fires then starts ONE run, and the run reads the whole\n// tray through the hosted tools — so nothing a later frame announced is\n// missed. The tray is the truth, the wake is not.\n//\n// `wakeAfter` serves the local retry ladder: when a run could not start or did\n// not complete, the integration schedules another wake later instead of\n// dropping the backlog. The server's own ladder only rings webhooks; a\n// connected socket gets no re-ring, so the integration carries that duty\n// itself. When a delayed wake is already pending the SOONER deadline wins — a\n// later retry never pushes an earlier one back. (Learned on the Hermes\n// integration: two failed cycles inside one outage once climbed the ladder to\n// 300 s and replaced the pending 60 s retry.) `cancelDelayed` drops a pending\n// retry once nothing is owed: a stale re-wake once fired 4.5 min after a\n// successful run and started a run on an empty tray (Codex live-fire, leg 10).\n\nexport const DEFAULT_WAKE_DEBOUNCE_MS = 2_000\n\nexport type TimerHandle = ReturnType<typeof setTimeout>\n\nexport interface WakeCoalescerOptions {\n readonly onFire: () => void\n readonly debounceMs?: number\n /** Clock and timers are injectable so tests never wait on real time. */\n readonly now?: () => number\n readonly setTimeout?: (fn: () => void, ms: number) => TimerHandle\n readonly clearTimeout?: (handle: TimerHandle) => void\n}\n\nexport class WakeCoalescer {\n private readonly onFire: () => void\n private readonly debounceMs: number\n private readonly now: () => number\n private readonly _setTimeout: (fn: () => void, ms: number) => TimerHandle\n private readonly _clearTimeout: (handle: TimerHandle) => void\n\n private timer: TimerHandle | null = null\n private delayed: TimerHandle | null = null\n private delayedDeadline: number | null = null\n private stopped = false\n\n wakes = 0\n absorbed = 0\n fires = 0\n\n constructor(options: WakeCoalescerOptions) {\n const debounce = options.debounceMs ?? DEFAULT_WAKE_DEBOUNCE_MS\n if (!(debounce >= 0)) throw new RangeError('debounceMs must be >= 0')\n this.onFire = options.onFire\n this.debounceMs = debounce\n this.now = options.now ?? Date.now\n this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms))\n this._clearTimeout = options.clearTimeout ?? ((handle) => clearTimeout(handle))\n }\n\n /** True while a debounce timer is armed. */\n get armed(): boolean {\n return this.timer !== null\n }\n\n /** True while a retry wake is scheduled and has not fired. */\n get delayedPending(): boolean {\n return this.delayed !== null\n }\n\n /** Epoch ms of the pending retry wake, or null. */\n get delayedDue(): number | null {\n return this.delayedDeadline\n }\n\n /** A wake: arm the timer if none is armed; otherwise absorb. */\n wake(): void {\n if (this.stopped) return\n this.wakes += 1\n if (this.timer !== null) {\n this.absorbed += 1\n return\n }\n this.timer = this._setTimeout(() => this.fire(), this.debounceMs)\n }\n\n /** A delayed wake (retry ladder). The sooner pending deadline is kept. */\n wakeAfter(delayMs: number): void {\n if (this.stopped) return\n const delay = Math.max(0, delayMs)\n const deadline = this.now() + delay\n if (this.delayed !== null) {\n if (this.delayedDeadline !== null && this.delayedDeadline <= deadline) {\n return // an earlier retry is already on its way; keep it\n }\n this._clearTimeout(this.delayed)\n }\n this.delayedDeadline = deadline\n this.delayed = this._setTimeout(() => {\n this.delayed = null\n this.delayedDeadline = null\n this.wake()\n }, delay)\n }\n\n /**\n * Drop a pending retry wake, if there is one; returns whether there was.\n * The debounce timer and later wakes are unaffected. For when nothing is\n * owed any more — a run read the whole tray, or the tray was found empty —\n * so the retry would only ring for a backlog that is already handled.\n */\n cancelDelayed(): boolean {\n if (this.delayed === null) return false\n this._clearTimeout(this.delayed)\n this.delayed = null\n this.delayedDeadline = null\n return true\n }\n\n /** Cancel everything; later wakes are ignored. */\n stop(): void {\n this.stopped = true\n if (this.timer !== null) {\n this._clearTimeout(this.timer)\n this.timer = null\n }\n this.cancelDelayed()\n }\n\n private fire(): void {\n this.timer = null\n if (this.stopped) return\n this.fires += 1\n try {\n this.onFire()\n } catch {\n // The callback belongs to the invoker; a failure there must not kill\n // the timer machinery. The next wake re-arms as usual.\n }\n }\n}\n","import * as path from 'node:path'\nimport { z } from 'zod'\nimport { atomicWriteFile, readJsonFile } from '../util/fsutil.js'\nimport { log } from '../util/log.js'\n\n// ─── Which invites were already offered to a run ────────────────────────────\n//\n// The server pushes a group invite live once and never re-offers it, so on\n// every connect the integration lists the pending invites and offers each to\n// a run. \"Offered\" used to live in process memory, which meant a daemon\n// restart offered every still-pending invite again — one paid run per invite,\n// per restart, for as long as the agent left them pending. The set now lives\n// in the identity home: an invite id is recorded the moment its run has\n// started (the runner's `onStarted`, i.e. the process spawned), so a run cut\n// short by a shutdown or a crash still counts as the one offer — the paid\n// model call was made. An invite whose run never got going (`not_started`:\n// binary missing, signed out, exited with nothing on stdout) is taken back\n// out, so the next wake (and the next connect's listing) offers it again.\n//\n// Bounded and private to the user: ids and timestamps only.\n\nexport const OFFERED_INVITES_FILE = 'invites.offered.json'\nconst MAX_REMEMBERED = 1_000\n\nconst Schema = z.object({\n version: z.literal(1),\n offered: z.array(z.object({ id: z.string(), at: z.string() })),\n})\n\n/** The seam the invoker uses; `OfferedInvites` is the on-disk implementation. */\nexport interface OfferedInviteStore {\n has(inviteId: string): boolean\n add(inviteId: string): void\n /** Forget an offer: the run recorded at start turned out never to have got going. */\n remove(inviteId: string): void\n}\n\nexport function offeredInvitesPath(home: string): string {\n return path.join(home, OFFERED_INVITES_FILE)\n}\n\nexport class OfferedInvites implements OfferedInviteStore {\n private readonly entries: Array<{ id: string; at: string }>\n\n /** `home === null` keeps the set in memory only (tests). */\n constructor(\n private readonly home: string | null,\n entries: Array<{ id: string; at: string }> = [],\n private readonly now: () => Date = () => new Date(),\n ) {\n this.entries = entries.slice(-MAX_REMEMBERED)\n }\n\n /** Read the set from the identity home; a missing or malformed file is an empty set. */\n static load(home: string, now?: () => Date): OfferedInvites {\n const parsed = Schema.safeParse(readJsonFile<unknown>(offeredInvitesPath(home)))\n return new OfferedInvites(home, parsed.success ? parsed.data.offered : [], now)\n }\n\n get size(): number {\n return this.entries.length\n }\n\n has(inviteId: string): boolean {\n return this.entries.some((entry) => entry.id === inviteId)\n }\n\n add(inviteId: string): void {\n if (this.has(inviteId)) return\n this.entries.push({ id: inviteId, at: this.now().toISOString() })\n while (this.entries.length > MAX_REMEMBERED) this.entries.shift()\n this.persist()\n }\n\n remove(inviteId: string): void {\n const index = this.entries.findIndex((entry) => entry.id === inviteId)\n if (index === -1) return\n this.entries.splice(index, 1)\n this.persist()\n }\n\n private persist(): void {\n if (this.home === null) return\n try {\n atomicWriteFile(\n offeredInvitesPath(this.home),\n `${JSON.stringify({ version: 1, offered: this.entries } satisfies z.infer<typeof Schema>, null, 2)}\\n`,\n 0o600,\n )\n } catch (err) {\n // Best effort: the worst case is one repeated invite run after a restart.\n log.debug(`offered-invites write failed: ${String(err)}`)\n }\n }\n}\n","import type { ChildProcess } from 'node:child_process'\nimport { spawnCommand, spawnCommandSync } from '../util/spawn.js'\nimport type { RunOutcome } from './runner.js'\n\n// ─── Spawning one headless run ──────────────────────────────────────────────\n//\n// Shared by every runner: start the runtime's headless command, feed it the\n// prompt, bound it, classify the exit. The run's OUTPUT IS DISCARDED — stdout\n// is counted, never kept, never parsed, never logged. A run's text can quote\n// peer messages, and the integration reads no message content, ever. The only\n// thing retained is a short, credential-redacted tail of stderr for the\n// failure diagnostic, because \"exited 1\" alone has cost days of debugging.\n//\n// Classification: `ok` on exit 0; `timed_out` when the budget killed it;\n// `failed` when it was interrupted or exited non-zero after writing to stdout;\n// `not_started` when it exited non-zero with NOTHING ON STDOUT — a signed-out\n// CLI, a bad flag, a missing config all print their complaint on stderr and\n// quit, and they are \"the runtime did not get going\", stderr or not. The\n// stderr tail rides along in the detail either way.\n//\n// The run is spawned as its own process group (detached) so the whole tree\n// can be signalled at once: on the budget, and when the integration is stopping\n// (`signal`) — a daemon that exits with a run still going orphans a model call\n// that nobody will read and that the restarted daemon would run again.\n\nconst DEFAULT_GRACE_MS = 5_000\nconst STDERR_TAIL_CHARS = 400\n\nexport interface SpawnRunSpec {\n readonly command: string\n readonly args: readonly string[]\n readonly cwd: string\n readonly env: NodeJS.ProcessEnv\n /** Written to the child's stdin and closed; `null` closes stdin at once. */\n readonly stdin: string | null\n /** Kill past this. */\n readonly budgetMs: number\n /** SIGTERM first; SIGKILL this long after. */\n readonly graceMs?: number\n /**\n * Aborting it SIGTERMs the run's process group (SIGKILL after `graceMs`);\n * the outcome is `failed` with an \"interrupted\" detail.\n */\n readonly signal?: AbortSignal\n /** Called once when the child process has been spawned (`RunRequest.onStarted`). */\n readonly onStarted?: () => void\n}\n\n/** Strip anything key-shaped or terminal-styled from a diagnostic, and bound it. */\nexport function redactDiagnostic(value: string, max = STDERR_TAIL_CHARS): string {\n return value\n .replace(/\\u001B\\[[0-?]*[ -/]*[@-~]/g, '')\n .replace(/\\b(api[_ -]?key\\s*[:=]\\s*)\\S+/gi, '$1[redacted]')\n .replace(/\\b(Bearer)\\s+[A-Za-z0-9._~-]{8,}\\b/gi, '$1 [redacted]')\n .replace(/\\bac_[A-Za-z0-9_-]{8,}\\b/g, '[redacted AgentChat key]')\n .replace(/\\bsk-[A-Za-z0-9_-]{8,}\\b/g, '[redacted key]')\n .replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(-max)\n}\n\nfunction killProcessTree(child: ChildProcess, signal: NodeJS.Signals): void {\n if (child.pid === undefined) return\n try {\n if (process.platform === 'win32') {\n spawnCommandSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], {\n windowsHide: true,\n stdio: 'ignore',\n })\n } else {\n // Negative pid = the process group the child leads (spawned detached).\n process.kill(-child.pid, signal)\n }\n } catch {\n try {\n child.kill(signal)\n } catch {\n /* already gone */\n }\n }\n}\n\n/** Start the command, wait for it, classify. Never throws. */\nexport function spawnRun(spec: SpawnRunSpec): Promise<RunOutcome> {\n const started = Date.now()\n return new Promise<RunOutcome>((resolve) => {\n let settled = false\n let stdoutBytes = 0\n let stderrTail = ''\n let timedOut = false\n let interrupted = false\n let killTimer: ReturnType<typeof setTimeout> | null = null\n let graceTimer: ReturnType<typeof setTimeout> | null = null\n let onAbort: (() => void) | null = null\n\n const finish = (outcome: Omit<RunOutcome, 'durationMs'>): void => {\n if (settled) return\n settled = true\n if (killTimer) clearTimeout(killTimer)\n if (graceTimer) clearTimeout(graceTimer)\n if (onAbort) spec.signal?.removeEventListener('abort', onAbort)\n resolve({ ...outcome, durationMs: Date.now() - started })\n }\n\n if (spec.signal?.aborted) {\n finish({ state: 'not_started', exitCode: null, detail: 'interrupted before the runtime was started' })\n return\n }\n\n let child: ChildProcess\n try {\n child = spawnCommand(spec.command, [...spec.args], {\n cwd: spec.cwd,\n env: spec.env,\n stdio: [spec.stdin === null ? 'ignore' : 'pipe', 'pipe', 'pipe'],\n detached: process.platform !== 'win32',\n windowsHide: true,\n })\n } catch (err) {\n finish({ state: 'not_started', exitCode: null, detail: redactDiagnostic(String(err)) })\n return\n }\n\n if (spec.onStarted) {\n const onStarted = spec.onStarted\n child.once('spawn', () => {\n try {\n onStarted()\n } catch {\n /* the callback belongs to the invoker; a failure there is not the run's */\n }\n })\n }\n\n child.stdout?.on('data', (chunk: Buffer | string) => {\n stdoutBytes += chunk.length // counted, never kept\n })\n child.stderr?.on('data', (chunk: Buffer | string) => {\n stderrTail = (stderrTail + String(chunk)).slice(-4 * STDERR_TAIL_CHARS)\n })\n\n if (spec.stdin !== null && child.stdin) {\n child.stdin.on('error', () => {\n /* the child closed stdin early; the exit code tells the story */\n })\n try {\n child.stdin.write(spec.stdin)\n child.stdin.end()\n } catch {\n /* handled by the close path */\n }\n }\n\n const terminate = (): void => {\n killProcessTree(child, 'SIGTERM')\n if (graceTimer) clearTimeout(graceTimer)\n graceTimer = setTimeout(() => killProcessTree(child, 'SIGKILL'), spec.graceMs ?? DEFAULT_GRACE_MS)\n }\n\n killTimer = setTimeout(() => {\n timedOut = true\n terminate()\n }, spec.budgetMs)\n\n if (spec.signal) {\n onAbort = (): void => {\n if (settled) return\n interrupted = true\n terminate()\n }\n spec.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n child.on('error', (err) => {\n finish({ state: 'not_started', exitCode: null, detail: redactDiagnostic(String(err)) })\n })\n\n child.on('close', (code, signal) => {\n const tail = redactDiagnostic(stderrTail)\n if (timedOut) {\n finish({\n state: 'timed_out',\n exitCode: code,\n detail: `run exceeded its ${Math.round(spec.budgetMs / 1000)} s budget and was killed${tail ? `: ${tail}` : ''}`,\n })\n return\n }\n if (interrupted) {\n finish({\n state: 'failed',\n exitCode: code,\n detail: `interrupted — the integration was stopping; the tray stays unread for the next run${tail ? `: ${tail}` : ''}`,\n })\n return\n }\n if (code === 0) {\n finish({ state: 'ok', exitCode: 0 })\n return\n }\n const exit = code === null ? `signal ${signal ?? 'unknown'}` : `exit ${code}`\n if (stdoutBytes === 0) {\n // Nothing on stdout: the runtime did not get going (missing, refused\n // to start, auth gate). Whatever it complained about is in the tail.\n finish({ state: 'not_started', exitCode: code, detail: `${exit} with nothing on stdout${tail ? `: ${tail}` : ''}` })\n return\n }\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E,OAAO,eAAe,UAAU,MAAM,QAAQ,GAAG,IAAI,0BAA0B,OAAO,KAAK,IAAI,KAAK,EAAE,GAAG,CAAC;AACnH;AAAA,MACF;AACA,aAAO,EAAE,OAAO,UAAU,UAAU,MAAM,QAAQ,GAAG,IAAI,GAAG,OAAO,KAAK,IAAI,KAAK,EAAE,GAAG,CAAC;AAAA,IACzF,CAAC;AAAA,EACH,CAAC;AACH;","names":["path","AgentChatClient","path","AgentChatClient","resolve","resolve"]}
1
+ {"version":3,"sources":["../src/integration/run.ts","../src/daemon/config.ts","../src/integration/integration.ts","../src/integration/socket-state.ts"],"sourcesContent":["import * as path from 'node:path'\nimport * as fs from 'node:fs'\nimport { log } from '../util/log.js'\nimport { acquireLeaderLock } from '../daemon/leader-lock.js'\nimport { resolveIdentity, credentialsPath } from '../identity/credentials.js'\nimport { resolveDaemonConfig } from '../daemon/config.js'\nimport { idle } from '../daemon/health.js'\nimport type { IntegrationClient } from '../client-identity.js'\nimport { Integration } from './integration.js'\nimport { integrationDisabledBy, resolveRunBudgetMs, resolveRunProfile, type RunProfile } from './profile.js'\nimport { isRunnerFactory, type RunnerSource } from './runner.js'\nimport { writeIntegrationStatus } from './status.js'\n\n// ─── The resident supervisor ────────────────────────────────────────────────\n//\n// This process is RESIDENT. It is registered as a service when the integration\n// is installed, and from then on it simply exists — whether or not anyone has\n// signed in. Installation and authentication are different lifecycles (the\n// shape every comparable daemon uses: tailscaled runs before `tailscale up`,\n// and logging out idles it rather than uninstalling it).\n//\n// no credentials → idle. No socket, no retries, no CPU. Just watch.\n// credentials → connect and wake.\n// credentials change → follow them.\n// AGENTCHAT_INTEGRATION=off → stay resident, hold nothing, wake nothing.\n//\n// A refused key is not this loop's case: the SDK's client stays up in\n// `blocked` and tries a fresh hello every 10–15 minutes (`status` reads\n// `socket blocked` meanwhile), so a rotated-back key or a reinstated account\n// reconnects on its own, and a different key is simply a credential change.\n//\n// The only thing that removes this process is an explicit `daemon disable`.\n//\n// SIGTERM/SIGINT (launchd/systemd stop, Ctrl-C) interrupts a run in flight:\n// the integration SIGTERMs the run's process group and this process waits up\n// to SHUTDOWN_GRACE_MS for it before exiting. A daemon that exited at once\n// left the detached run orphaned, and the restarted daemon's connect found\n// the same tray and started a second run beside it.\n\n/** How often to re-read the identity. A `stat`; the watcher usually beats it. */\nconst POLL_MS = 5_000\n/** How often the watcher flag is consulted while waiting out a poll. */\nconst TICK_MS = 250\n/** Ceiling for retry backoff when the runtime simply is not usable yet. */\nconst MAX_BACKOFF_MS = 5 * 60_000\n/**\n * How long a shutdown waits for an interrupted run to end before the process\n * exits. The runner SIGTERMs the run's process group at once and SIGKILLs 5 s\n * later, so this is normally over in well under a second. Below launchd's\n * `ExitTimeOut` (15 s in the plist this package writes).\n */\nconst SHUTDOWN_GRACE_MS = 10_000\nconst MAX_LOG_BYTES = 5 * 1024 * 1024\nconst KEEP_LOG_BYTES = 1024 * 1024\n\nexport interface RunIntegrationOpts {\n /** THE identity home for the agent this daemon serves. */\n home: string\n /** How to start one headless run: a runner, or a factory that builds one per identity (`RunnerFactory`). */\n runner: RunnerSource\n /** How this integration names itself to the server: the texts runtime and its own version. */\n client: IntegrationClient\n /** The one pointer line a run prompt ends with: how THIS runtime reaches its copy of the manual (`manualPointer(...)`). */\n manualPointer: string\n /**\n * The skill file that follows the served manual (`<skills dir>/agentchat/SKILL.md`):\n * whenever the texts in hand announce a version the file does not carry, the\n * announced manual is downloaded, checked and written over it. Absent, the\n * daemon leaves the manual to the CLI's install and `doctor --fix`.\n */\n manualPath?: string\n /** Scratch dir for runs. The integration decides where; this package never derives one. */\n workdir: string\n /** Defaults to `AGENTCHAT_RUN_PROFILE`, then `answer`. */\n profile?: RunProfile\n /** Defaults to `AGENTCHAT_RUN_BUDGET_MS`, then 10 minutes. */\n budgetMs?: number\n /** Ends the loop (tests). Production runs until SIGTERM/SIGINT. */\n signal?: AbortSignal\n env?: NodeJS.ProcessEnv\n /** Test seam: what a signal-initiated shutdown calls last. Defaults to `process.exit`. */\n exit?: (code: number) => void\n /**\n * Serve only the agent the home's `credentials` hold: `AGENTCHAT_API_KEY`\n * in the environment is ignored (default false: it overrides, as for every\n * integration). The `agentchat` listener sets it.\n */\n credentialsFromHomeOnly?: boolean\n /** See `IntegrationOptions.dismissIgnoredInvites` (default true). */\n dismissIgnoredInvites?: boolean\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))\n\n/**\n * Identity fingerprint: changes when the user signs out, signs in, or swaps to\n * a different agent. Comparing it is how the supervisor notices without caring\n * why.\n */\nfunction fingerprint(home: string, envKey: boolean): string | null {\n const id = resolveIdentity(home, { envKey })\n return id === null ? null : `${id.apiKey}:${id.handle ?? ''}`\n}\n\n/** Bound launchd's append-only file without losing the most recent diagnosis. */\nfunction boundDaemonLog(home: string): void {\n const file = path.join(home, 'daemon.log')\n try {\n const size = fs.statSync(file).size\n if (size <= MAX_LOG_BYTES) return\n const fd = fs.openSync(file, 'r')\n try {\n const keep = Buffer.alloc(Math.min(KEEP_LOG_BYTES, size))\n fs.readSync(fd, keep, 0, keep.length, size - keep.length)\n fs.writeFileSync(\n file,\n `[agentchat:info] older daemon log output truncated at ${new Date().toISOString()}\\n${keep.toString('utf-8')}`,\n )\n } finally {\n fs.closeSync(fd)\n }\n } catch {\n /* absent/unreadable log is not a runtime failure */\n }\n}\n\n/**\n * Run the integration daemon. Returns only on a condition that makes running\n * pointless — another daemon already holding this home's lock — or when\n * `signal` aborts (tests).\n */\nexport async function runIntegration(opts: RunIntegrationOpts): Promise<number> {\n const home = path.resolve(opts.home)\n const workdir = path.resolve(opts.workdir)\n const env = opts.env ?? process.env\n const profile = opts.profile ?? resolveRunProfile(env)\n const budgetMs = opts.budgetMs ?? resolveRunBudgetMs(env)\n boundDaemonLog(home)\n\n // A resident service's output goes to a log file nobody sees until something\n // is wrong, and an empty log is useless for \"is the integration working?\".\n if (process.env['AGENTCHAT_LOG_LEVEL'] === undefined) process.env['AGENTCHAT_LOG_LEVEL'] = 'info'\n\n // Taken for the PROCESS, not for a connection: one resident daemon per\n // identity home, signed in or not.\n const lock = acquireLeaderLock(home)\n if (lock === null) return 1\n\n const envKey = opts.credentialsFromHomeOnly !== true\n const identityOf = () => resolveIdentity(home, { envKey })\n const disabledBy = integrationDisabledBy(env)\n const disabled = disabledBy !== null\n let live: Integration | null = null\n let liveFingerprint: string | null = null\n let observedFingerprint: string | null = null\n /** Consecutive start failures, for backoff. Reset on success or on a new credential. */\n let failures = 0\n let lastFailure: string | null = null\n let shuttingDown = false\n\n const offStatus = (handle: string | null): void =>\n writeIntegrationStatus(home, {\n version: 2,\n updated_at: new Date().toISOString(),\n pid: process.pid,\n runtime: opts.runner.name,\n handle,\n profile,\n socket: disabled ? 'off' : 'idle',\n wakes: 0,\n wakes_absorbed: 0,\n invites: 0,\n runs_started: 0,\n runs_ok: 0,\n runs_failed: 0,\n runs_timed_out: 0,\n runs_not_started: 0,\n runs_skipped_empty: 0,\n last_run: null,\n retry_rung: 0,\n retry_due_at: null,\n last_error: lastFailure,\n texts: null,\n })\n\n const disconnect = (why: string): void => {\n if (live === null) return\n log.info(`${why} — disconnecting (a run in flight is interrupted), staying resident`)\n live.stop()\n live = null\n liveFingerprint = null\n idle(home)\n }\n\n // The loop notices `shuttingDown` within a tick and takes the one exit path\n // below: stop the integration, give an interrupted run its grace, release, exit.\n const shutdown = (sig: string): void => {\n if (shuttingDown) return\n shuttingDown = true\n log.info(`${sig} — shutting down`)\n }\n const onSigint = (): void => shutdown('SIGINT')\n const onSigterm = (): void => shutdown('SIGTERM')\n process.on('SIGINT', onSigint)\n process.on('SIGTERM', onSigterm)\n\n // Best-effort accelerator so signing in connects in about a second instead of\n // waiting out a poll. fs.watch is unreliable on some filesystems, so the poll\n // below is the real guarantee and this is pure upside.\n let nudged = false\n try {\n fs.mkdirSync(home, { recursive: true })\n const watcher = fs.watch(home, (_event, filename) => {\n if (filename === null || String(filename).startsWith('credentials')) nudged = true\n })\n watcher.on('error', (err) => {\n log.warn(`credential watcher unavailable; polling instead: ${String(err)}`)\n try {\n watcher.close()\n } catch {\n /* already closed */\n }\n })\n watcher.unref()\n } catch {\n /* polling covers it */\n }\n\n log.info(`integration resident for ${home} (${credentialsPath(home)}) — ${opts.client.runtime} ${opts.client.version}`)\n if (disabled) {\n log.info(`${disabledBy}=off — holding no socket and starting no run; the hosted tools and the manual still work in every session`)\n }\n idle(home)\n offStatus(null)\n\n for (;;) {\n if (shuttingDown || opts.signal?.aborted) break\n const fp = fingerprint(home, envKey)\n const identityChanged = fp !== observedFingerprint\n if (identityChanged) {\n disconnect(fp === null ? 'signed out' : 'identity changed')\n observedFingerprint = fp\n failures = 0\n lastFailure = null\n if (fp === null || disabled) offStatus(fp === null ? null : identityOf()?.handle ?? null)\n }\n\n if (fp === null) {\n // Signed out, or never signed in. Idle.\n } else if (disabled) {\n // Signed in, switched off. Resident, silent.\n } else if (fp !== liveFingerprint) {\n try {\n const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client, envKey })\n const runner = isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner\n const candidate = new Integration({\n cfg,\n runner,\n client: opts.client,\n manualPointer: opts.manualPointer,\n ...(opts.manualPath !== undefined ? { manualPath: opts.manualPath } : {}),\n profile,\n budgetMs,\n ...(opts.dismissIgnoredInvites !== undefined ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {}),\n })\n await candidate.start()\n live = candidate\n liveFingerprint = fp\n failures = 0\n lastFailure = null\n } catch (err) {\n // Runtime not ready (host CLI missing or not signed in), network\n // down, whatever. Stay resident and try again later — exiting would\n // just make the service manager restart us in a loop. Backed off and\n // de-duplicated so a condition that lasts days does not fill the log.\n const msg = String(err instanceof Error ? err.message : err)\n if (msg !== lastFailure) {\n log.warn(`not connecting yet: ${msg}`)\n lastFailure = msg\n offStatus(identityOf()?.handle ?? null)\n }\n failures += 1\n live = null\n liveFingerprint = null\n idle(home)\n }\n }\n\n // Wait out the poll interval, but wake as soon as the watcher fires so a\n // sign-in connects in well under a second. Exponential backoff while a\n // start keeps failing, capped — the watcher still wakes us instantly when\n // credentials change, so backing off never delays a real sign-in.\n const waitMs = failures === 0 ? POLL_MS : Math.min(POLL_MS * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS)\n nudged = false\n const deadline = Date.now() + waitMs\n while (!nudged && !shuttingDown && !opts.signal?.aborted && Date.now() < deadline) {\n await sleep(TICK_MS)\n }\n }\n\n process.off('SIGINT', onSigint)\n process.off('SIGTERM', onSigterm)\n if (live !== null) {\n const ended = await live.stopAndWait(SHUTDOWN_GRACE_MS)\n if (!ended) log.warn(`a run in flight did not end within ${Math.round(SHUTDOWN_GRACE_MS / 1000)}s of being interrupted — exiting anyway`)\n live = null\n }\n idle(home)\n lock.release()\n if (shuttingDown) {\n log.info('shutdown complete')\n ;(opts.exit ?? process.exit)(0)\n }\n return 0\n}\n","import * as path from 'node:path'\nimport { AgentChatClient } from 'agentchatme'\nimport { resolveIdentity } from '../identity/credentials.js'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\n\n// ─── Daemon identity resolution ─────────────────────────────────────────────\n//\n// The daemon runs AS one host agent — the same identity that agent's sessions\n// use through the hosted tools, never a separate account. It reads that\n// credential from the home it is GIVEN.\n//\n// The predecessor of this file mapped a `runtime` enum to a home\n// (`codex → ~/.codex/agentchat`, `claude-code → ~/.claude/agentchat`). That\n// mapping is exactly the \"a function that decides can decide wrong\" defect this\n// package exists to make unrepresentable, so it is gone: the caller passes its\n// own home and there is no enum to mis-set.\n\nexport interface DaemonConfig {\n apiKey: string\n handle: string\n apiBase: string\n /** `wss://api.agentchat.me` — the SDK's socket base; it appends `/v1/ws`. */\n wsBase: string\n /** The identity home. Credentials, leader lock, and heartbeat all live here. */\n home: string\n /** Scratch dir for runs (the headless run's cwd). */\n workdir: string\n}\n\n/** `https://api.agentchat.me` → `wss://api.agentchat.me`. */\nexport function wsBaseFor(apiBase: string): string {\n return apiBase.replace(/^http/, 'ws').replace(/\\/+$/, '')\n}\n\n/** `https://api.agentchat.me` → `wss://api.agentchat.me/v1/ws`, for logs and checks. */\nexport function wsUrlFor(apiBase: string): string {\n return `${wsBaseFor(apiBase)}/v1/ws`\n}\n\nexport interface ResolveDaemonOpts {\n /** THE identity home. Required — this module never derives one. */\n home: string\n /** The run workdir. Required — this module never derives one either. */\n workdir: string\n /** How to identify to the server when the handle has to be asked for. */\n client: IntegrationClient\n /** Whether `AGENTCHAT_API_KEY` may override the home's credentials (default true; see `resolveIdentity`). */\n envKey?: boolean\n}\n\n/**\n * Resolve the identity the daemon runs as.\n *\n * Async because the handle is load-bearing at runtime — it filters this agent's\n * own outbound echoed back by server fan-out. An env-only identity\n * (`AGENTCHAT_API_KEY`, no credentials file) has no handle on disk, so we ask\n * the server rather than starting up blind and waking on ourselves.\n */\nexport async function resolveDaemonConfig(opts: ResolveDaemonOpts): Promise<DaemonConfig> {\n const home = path.resolve(opts.home)\n const id = resolveIdentity(home, { envKey: opts.envKey !== false })\n if (id === null) {\n throw new Error(`no AgentChat identity in ${home} — register this agent first`)\n }\n\n // An environment key is the authenticated identity even when this home also\n // contains an older credentials file. That file's handle is not evidence\n // about the env key, so resolve it from the server.\n let handle = id.source === 'file' ? id.handle : null\n if (handle === null) {\n const client = new AgentChatClient({\n apiKey: id.apiKey,\n baseUrl: id.apiBase,\n clientIdentity: clientIdentityOf(opts.client),\n timeoutMs: 10_000,\n })\n const me = await client.getMe().catch(() => null)\n if (me === null || typeof me.handle !== 'string' || me.handle.length === 0) {\n throw new Error(\n 'could not determine this agent’s handle (no credentials file, and /v1/agents/me did not answer)',\n )\n }\n handle = me.handle\n }\n\n return {\n apiKey: id.apiKey,\n handle,\n apiBase: id.apiBase,\n wsBase: wsBaseFor(id.apiBase),\n home,\n workdir: path.resolve(opts.workdir),\n }\n}\n","import * as crypto from 'node:crypto'\nimport { AgentChatClient, RealtimeClient, integration as kit } from 'agentchatme'\nimport { log } from '../util/log.js'\nimport type { DaemonConfig } from '../daemon/config.js'\nimport { beat, idle } from '../daemon/health.js'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\nimport type { RunProfile } from './profile.js'\nimport type { RunKind, RunOutcome, RunRunner, RunWake } from './runner.js'\nimport { writeIntegrationStatus, type IntegrationLastRun, type IntegrationStatus, type SocketState } from './status.js'\nimport { blockedDetail, socketStateOf } from './socket-state.js'\nimport { textsCachePath } from './texts.js'\nimport { MANUAL } from '../skill/manual.js'\nimport { describeManualSync, type ManualFetch } from '../skill/served-manual.js'\n\n// ─── The integration: the SDK kit's receive loop, and one runtime's runner ──\n//\n// Everything that talks to AgentChat is the SDK's integration kit (`import {\n// integration } from 'agentchatme'`), written once for every runtime:\n//\n// * the socket — `ackOnReceipt` (delivered = this machine received it) with\n// the `ack`, `heartbeat` and `rewake` capabilities, never reading a body;\n// * the wakes — a `message.new` that is not this agent's own echo, a `wake`\n// frame (a reminder, or the server re-waking unanswered cards), a group\n// invite, every accepted hello — coalesced into one cycle per burst, one\n// cycle at a time (`WakeCoalescer`);\n// * the cycle in SINGLE-RUN mode (`ReceiveLoop`): read the tray; nothing\n// owed (no cards, only muted ones, no pending invite) starts nothing; a\n// tray that cannot be read is not an empty tray, and the run starts\n// anyway; otherwise ONE run with the served wake instruction (and the\n// invite prompt when invites wait). The run reads the tray and records its\n// own verdicts; nothing is recorded on its behalf;\n// * the served texts (`TextsCache`, the last good copy kept in the identity\n// home) and the manual they announce (`ManualSync`).\n//\n// There is no retry ladder here, and no invite ledger: the server re-wakes\n// unanswered cards on its own durable ladder and shows pending invites on the\n// tray (contract v1, D3/D4), so a run that could not finish leaves the cards\n// where they are and the next wake finds them.\n//\n// What stays here is this package's own: the runner seam (how a runtime's run\n// is started is the integration's — `RunRunner`), the one pointer line a run\n// prompt ends with, a deadline on every run (a runner that never returns must\n// not hold the loop), and the status file `status` and `doctor` read.\n\nconst HEARTBEAT_MS = 30_000\nconst STATUS_MS = 30_000\n/** HTTP calls the loop makes are the tray and the texts; none deserves a long wait or a retry ramp. */\nconst HTTP_TIMEOUT_MS = 10_000\n\n/**\n * How long past its budget a runner may take to return before the loop stops\n * waiting for it. `spawnRun` always returns well inside this (grace, drain and\n * abandon are seconds); the deadline is for a runner that does not keep the\n * \"never hangs\" promise — the loop must outlive every runner.\n */\nexport const RUNNER_DEADLINE_SLACK_MS = 60_000\n\n/** A runner's `preflight()` (a `--version`, an auth probe) past this counts as not ok. */\nexport const PREFLIGHT_DEADLINE_MS = 60_000\n\nexport interface IntegrationOptions {\n readonly cfg: DaemonConfig\n readonly runner: RunRunner\n /** How this integration names itself to the server (texts runtime + its version). */\n readonly client: IntegrationClient\n /** The one pointer line a run prompt ends with (`manualPointer(...)`). */\n readonly manualPointer: string\n /** The skill file that follows the served manual (`<skills dir>/agentchat/SKILL.md`); absent, the manual is left to the CLI. */\n readonly manualPath?: string\n /** Injectable for tests; the manual download's `fetch`. */\n readonly manualFetch?: ManualFetch\n readonly profile: RunProfile\n readonly budgetMs: number\n /** Injectable for tests; past `budgetMs` plus this a runner that has not returned is abandoned. */\n readonly runnerDeadlineSlackMs?: number\n /** Injectable for tests; defaults to an SDK client for `cfg`. */\n readonly api?: AgentChatClient\n /** Injectable for tests: the socket (built with `ackOnReceipt` and the v1 capabilities otherwise). */\n readonly realtime?: RealtimeClient\n /** Injectable for tests: the coalescing window. */\n readonly quietMs?: number\n readonly maxMs?: number\n /** Injectable for tests: the kit's cycle watchdog (default 10 min, not counting runs). */\n readonly cycleTimeoutMs?: number\n /**\n * Injectable for tests: the kit's pacing window (default 60 s) — a second\n * completed run that leaves an invite pending counts toward dismissing it\n * only this long after the first.\n */\n readonly paceMs?: number\n /**\n * The kit's single-run rule dismisses an invite two completed runs left\n * pending, so an ignored invite does not cost a run on every wake. Right\n * when a run is the agent itself; wrong when \"completed\" only means a\n * receiver accepted a POST (the `agentchat forward` mode): there it is\n * false, and no invite is ever dismissed on the agent's behalf.\n */\n readonly dismissIgnoredInvites?: boolean\n}\n\n/** Most of a failure line: enough to diagnose, bounded for the status file. */\nconst CYCLE_FAILURE_CHARS = 240\n\n/** The webhook wake's reason for a kit wake source (contract v1); null when the source names none. */\nfunction reasonOf(source: kit.WakeSource, frameReason: string | undefined): string | null {\n switch (source) {\n case 'message':\n return 'messages'\n case 'invite':\n return 'invite'\n case 'wake_frame':\n return frameReason ?? 'reminder'\n default:\n return null\n }\n}\n\n/** `work`, or `onTimeout()` once `ms` have passed — whichever first. A late result is dropped. */\nfunction withDeadline<T>(work: Promise<T>, ms: number, onTimeout: () => T): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let done = false\n const timer = setTimeout(() => {\n if (done) return\n done = true\n try {\n resolve(onTimeout())\n } catch (err) {\n reject(err)\n }\n }, ms)\n timer.unref?.()\n work.then(\n (value) => {\n if (done) return\n done = true\n clearTimeout(timer)\n resolve(value)\n },\n (err: unknown) => {\n if (done) return\n done = true\n clearTimeout(timer)\n reject(err)\n },\n )\n })\n}\n\nexport class Integration {\n private readonly api: AgentChatClient\n private readonly realtime: RealtimeClient\n private readonly texts: kit.TextsCache\n private readonly manual: kit.ManualSync | null\n private readonly loop: kit.ReceiveLoop\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null\n private statusTimer: ReturnType<typeof setInterval> | null = null\n private socket: SocketState = 'idle'\n private lastError: string | null = null\n private stopping = false\n private stopped: Promise<void> | null = null\n\n private invites = 0\n private runsStarted = 0\n private runsOk = 0\n private runsFailed = 0\n private runsTimedOut = 0\n private runsNotStarted = 0\n private runsSkippedEmpty = 0\n private lastRun: IntegrationLastRun | null = null\n /** The newest wake since the last run started (for `RunRequest.wake`). */\n private pendingWake: RunWake | null = null\n /** The rung of the newest `unanswered` wake frame (the kit's wake event does not carry it). */\n private lastUnansweredStep: number | null = null\n\n constructor(private readonly options: IntegrationOptions) {\n const { cfg, client } = options\n const identity = clientIdentityOf(client)\n this.api =\n options.api ??\n new AgentChatClient({ apiKey: cfg.apiKey, baseUrl: cfg.apiBase, clientIdentity: identity, timeoutMs: HTTP_TIMEOUT_MS, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } })\n this.texts = new kit.TextsCache({\n client: this.api,\n runtime: client.runtime,\n filePath: textsCachePath(cfg.home),\n onError: (err) => log.warn(err.message),\n })\n this.texts.onChange((texts, source) => {\n log.info(`texts ${source === 'server' ? 'fetched' : 'read from the cache'} for ${client.runtime} (texts v${texts.version}, manual ${texts.manual.version})`)\n this.writeStatus()\n })\n this.manual =\n options.manualPath === undefined\n ? null\n : new kit.ManualSync({\n texts: this.texts,\n targetPath: options.manualPath,\n fallback: MANUAL,\n ...(options.manualFetch !== undefined ? { fetch: options.manualFetch } : {}),\n onResult: (result) => {\n const line = `manual: ${describeManualSync({ ...result, source: result.source === 'fallback' ? 'bundled' : result.source })}`\n if (result.upToDate === false || result.state === 'failed') log.warn(line)\n else if (result.written) log.info(line)\n },\n })\n // Built here rather than by the loop, so the status file can follow the\n // socket's own words and a refused key reads `blocked` with its reason.\n // No REST drain client: the server re-offers unacked envelopes over the\n // socket right after the hello, and nothing here ever needs a body.\n this.realtime =\n options.realtime ??\n new RealtimeClient({\n apiKey: cfg.apiKey,\n baseUrl: cfg.wsBase,\n clientIdentity: identity,\n ackOnReceipt: true,\n reconnect: true,\n capabilities: { heartbeat: true, rewake: true },\n })\n this.realtime.on('state', (next) => {\n const word = socketStateOf(next, this.socket)\n if (word === this.socket) return\n this.socket = word\n if (word === 'ready') {\n beat(cfg.home)\n // An accepted hello lifts a refusal: the key works again.\n this.lastError = null\n log.info(`socket ready (hello.ok) — acks ${this.realtime.ackNegotiated ? 'on receipt' : 'not negotiated by this server'}; ${this.realtime.capabilities.has('rewake') ? 'the server re-wakes unanswered cards' : 'this server does not re-wake unanswered cards'}`)\n } else {\n idle(cfg.home)\n if (word === 'reconnecting') log.info('socket reconnecting — the SDK backs off and retries; it never gives up')\n }\n this.writeStatus()\n })\n this.realtime.on('blocked', (info) => {\n // A refused key is a state to show, not to die from: the SDK stays\n // `blocked` and tries a fresh hello every 10–15 min.\n this.lastError = blockedDetail(info)\n log.error(`socket blocked (auth): ${this.lastError}`)\n this.writeStatus()\n })\n this.realtime.on('wake', (frame) => {\n const payload = (frame.payload ?? {}) as { reason?: unknown; step?: unknown }\n if (payload.reason === 'unanswered' && typeof payload.step === 'number') this.lastUnansweredStep = payload.step\n })\n this.loop = new kit.ReceiveLoop({\n client: this.api,\n // The kit's own switch: off, no invite is dismissed on the agent's behalf.\n ...(options.dismissIgnoredInvites === false ? { dismissIgnoredInvites: false } : {}),\n texts: this.texts,\n mode: 'singleRun',\n socket: this.realtime,\n handle: cfg.handle,\n startRun: (request) => this.startRun(request),\n onEvent: (event) => this.onEvent(event),\n ...(options.quietMs !== undefined ? { quietMs: options.quietMs } : {}),\n ...(options.maxMs !== undefined ? { maxMs: options.maxMs } : {}),\n ...(options.cycleTimeoutMs !== undefined ? { cycleTimeoutMs: options.cycleTimeoutMs } : {}),\n ...(options.paceMs !== undefined ? { paceMs: options.paceMs } : {}),\n })\n }\n\n async start(): Promise<void> {\n // Bounded: a preflight that never answers must not hold the supervisor\n // (and with it the shutdown path) forever.\n const pre = await withDeadline(this.options.runner.preflight(), PREFLIGHT_DEADLINE_MS, () => ({\n ok: false,\n detail: `preflight did not answer within ${Math.round(PREFLIGHT_DEADLINE_MS / 1000)} s`,\n }))\n if (!pre.ok) throw new Error(`runtime (${this.options.runner.name}) not ready: ${pre.detail ?? 'unknown'}`)\n log.info(\n `integration up as @${this.options.cfg.handle} via ${this.options.runner.name} (${this.options.client.runtime} ${this.options.client.version}), profile ${this.options.profile}; fetching the served texts, then holding the socket`,\n )\n // The texts are in before the socket opens, so the first wake has the\n // freshest text; a failure is logged and the cached copy (if any) serves.\n await this.texts.start()\n if (this.stopping) return\n // The skill file follows the announced manual from now on; a download\n // never holds up the socket.\n void this.manual?.start()\n await this.loop.start()\n this.heartbeatTimer = setInterval(() => {\n if (this.socket === 'ready') beat(this.options.cfg.home)\n }, HEARTBEAT_MS)\n this.heartbeatTimer.unref()\n this.statusTimer = setInterval(() => this.writeStatus(), STATUS_MS)\n this.statusTimer.unref()\n this.writeStatus()\n }\n\n /**\n * Stop holding the socket and interrupt a run in flight (its signal aborts;\n * the runner SIGTERMs its process group). `idle()` / `stopAndWait()`\n * tell when the run has actually ended.\n */\n stop(): void {\n if (this.stopping) return\n this.stopping = true\n if (this.heartbeatTimer) clearInterval(this.heartbeatTimer)\n if (this.statusTimer) clearInterval(this.statusTimer)\n this.stopped = this.loop.stop()\n this.texts.stop()\n this.manual?.stop()\n this.socket = 'closed'\n idle(this.options.cfg.home)\n this.writeStatus()\n }\n\n /** `stop()`, then wait up to `graceMs` for the interrupted run to end. Resolves true when nothing runs any more. */\n async stopAndWait(graceMs: number): Promise<boolean> {\n this.stop()\n let timer: ReturnType<typeof setTimeout> | null = null\n try {\n return await Promise.race([\n (this.stopped ?? Promise.resolve()).then(() => true),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), graceMs)\n }),\n ])\n } finally {\n if (timer !== null) clearTimeout(timer)\n }\n }\n\n /** Resolves when no cycle (and so no run) is running: the kit's `ReceiveLoop.idle()`. */\n idle(): Promise<void> {\n return this.loop.idle()\n }\n\n /** A wake heard outside the socket (a test, a webhook the integration received). */\n wake(): void {\n this.loop.wake()\n }\n\n snapshot(): IntegrationStatus {\n const status = this.loop.status()\n const texts = this.texts.current()\n return {\n version: 2,\n updated_at: new Date().toISOString(),\n pid: process.pid,\n runtime: this.options.runner.name,\n handle: this.options.cfg.handle,\n profile: this.options.profile,\n socket: this.stopping ? 'closed' : this.socket,\n wakes: status.coalescer.wakes,\n wakes_absorbed: status.coalescer.absorbed,\n invites: this.invites,\n runs_started: this.runsStarted,\n runs_ok: this.runsOk,\n runs_failed: this.runsFailed,\n runs_timed_out: this.runsTimedOut,\n runs_not_started: this.runsNotStarted,\n runs_skipped_empty: this.runsSkippedEmpty,\n last_run: this.lastRun,\n // No local retry ladder (the server re-wakes, D3); kept for older readers.\n retry_rung: 0,\n retry_due_at: null,\n last_error: this.lastError,\n texts: {\n source: this.texts.source,\n fetched_at: this.texts.fetchedAt,\n version: texts?.version ?? null,\n manual_version: texts?.manual.version ?? null,\n },\n capabilities: status.socket === null ? null : status.socket.capabilities,\n intake_paused: status.socket === null ? null : status.socket.intakePaused,\n recent_cycles: status.recentCycles.map((cycle) => ({\n at: cycle.at,\n outcome: cycle.outcome,\n cards: cycle.cards,\n invites: cycle.invites,\n failure: cycle.failure === null ? null : cycle.failure.slice(0, CYCLE_FAILURE_CHARS),\n })),\n }\n }\n\n // ─── the one run ────────────────────────────────────────────────────────\n\n private async startRun(request: kit.RunRequest): Promise<kit.RunEnd> {\n // Invites alone: the served invite prompt. Anything else: a wake run.\n const kind: RunKind = request.cards === 0 && (request.invites ?? 0) > 0 ? 'invite' : 'wake'\n // What woke it: the newest named wake since the previous run; a connect\n // (or a follow-on) names none, and the tray says what it found.\n const wake: RunWake = this.pendingWake ?? { reason: kind === 'invite' ? 'invite' : 'messages' }\n this.pendingWake = null\n const runId = crypto.randomUUID()\n const startedAt = Date.now()\n const budgetMs = this.options.budgetMs\n const slackMs = this.options.runnerDeadlineSlackMs ?? RUNNER_DEADLINE_SLACK_MS\n this.runsStarted += 1\n this.writeStatus()\n log.info(`run start kind=${kind} id=${runId} budget=${Math.round(budgetMs / 1000)}s (tray: ${request.cards ?? '?'} card(s), ${request.invites ?? '?'} invite(s))`)\n\n // The run's own stop signal: the loop stopping, or the deadline below.\n const controller = new AbortController()\n const onAbort = (): void => controller.abort()\n if (request.signal.aborted) controller.abort()\n else request.signal.addEventListener('abort', onAbort, { once: true })\n let outcome: RunOutcome\n try {\n outcome = await withDeadline(\n this.options.runner.start({\n kind,\n wake,\n prompt: `${request.prompt}\\n\\n${this.options.manualPointer}`,\n runId,\n budgetMs,\n signal: controller.signal,\n }),\n budgetMs + slackMs,\n () => {\n controller.abort()\n return {\n state: 'timed_out',\n exitCode: null,\n durationMs: Date.now() - startedAt,\n detail: `the runner did not return within ${Math.round((budgetMs + slackMs) / 1000)} s (budget plus ${Math.round(slackMs / 1000)} s) — abandoned so the next wake can run`,\n }\n },\n )\n } catch (err) {\n // The runner contract is \"never throws\"; a throw is a bug in the runner.\n outcome = { state: 'not_started', exitCode: null, durationMs: Date.now() - startedAt, detail: `runner threw: ${err instanceof Error ? err.message : String(err)}` }\n } finally {\n request.signal.removeEventListener('abort', onAbort)\n }\n\n this.lastRun = {\n kind,\n started_at: new Date(startedAt).toISOString(),\n ended_at: new Date().toISOString(),\n state: outcome.state,\n exit_code: outcome.exitCode,\n duration_ms: outcome.durationMs,\n detail: outcome.detail ?? null,\n }\n switch (outcome.state) {\n case 'ok':\n this.runsOk += 1\n log.info(`run ok kind=${kind} id=${runId} ${Math.round(outcome.durationMs / 1000)}s (output discarded; any send was the agent's own hosted-tool call)`)\n break\n case 'failed':\n this.runsFailed += 1\n break\n case 'timed_out':\n this.runsTimedOut += 1\n break\n case 'not_started':\n this.runsNotStarted += 1\n break\n }\n if (outcome.state !== 'ok') {\n log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ''} — the cards stay on the tray; the next wake (or the server's re-wake) finds them`)\n }\n this.writeStatus()\n return outcome.state === 'ok'\n ? { status: 'completed' }\n : { status: outcome.state === 'not_started' ? 'not_started' : 'failed', ...(outcome.detail !== undefined ? { detail: outcome.detail } : {}) }\n }\n\n private onEvent(event: kit.ReceiveLoopEvent): void {\n switch (event.type) {\n case 'wake': {\n if (event.source === 'invite') this.invites += 1\n const reason = reasonOf(event.source, event.reason)\n if (reason !== null) {\n this.pendingWake = reason === 'unanswered' && this.lastUnansweredStep !== null ? { reason, step: this.lastUnansweredStep } : { reason }\n }\n log.info(`wake — ${event.source}${event.reason ? ` (${event.reason})` : ''}${event.conversationId ? ` conv=${event.conversationId}` : ''}`)\n break\n }\n case 'echo':\n log.debug(`own echo${event.conversationId ? ` in ${event.conversationId}` : ''} — not a wake`)\n break\n case 'cycle': {\n const { outcome, cards, invites } = event.summary\n if (outcome === 'empty' || outcome === 'nothing_owed') {\n this.runsSkippedEmpty += 1\n log.info(`wake: ${outcome === 'empty' ? 'the tray is empty' : 'nothing owed (muted cards only)'} — no run (${cards} card(s), ${invites} invite(s))`)\n } else if (outcome === 'abandoned') {\n log.warn(`wake cycle abandoned by the watchdog: ${event.summary.failure ?? 'it ran past its deadline'} — the next wake starts a new one`)\n } else if (outcome === 'texts_missing') {\n this.runsNotStarted += 1\n log.warn('no served texts in hand: GET /v1/texts has not answered yet and nothing is cached in the identity home — no run this time')\n }\n this.writeStatus()\n break\n }\n case 'error':\n if (!this.stopping) log.warn(`receive loop: ${event.error.message}`)\n break\n default:\n break\n }\n }\n\n private writeStatus(): void {\n writeIntegrationStatus(this.options.cfg.home, this.snapshot())\n }\n}\n","import type { BlockedInfo, RealtimeState } from 'agentchatme'\nimport type { SocketState } from './status.js'\n\n// ─── The SDK socket's states, in the status file's words ───────────────────\n\n/**\n * The SDK's connection state in the status file's vocabulary. Pure. `previous`\n * is the status word in effect, which decides two things the SDK's state alone\n * does not say: a `connecting` after a close is `reconnecting`, and the slow\n * retry out of `blocked` (`connecting` again) stays `blocked` — only an\n * accepted hello (`ready`) lifts it. `stopped` is `closed` from any state; a\n * refusal stays visible as the last error, not as the socket word.\n */\nexport function socketStateOf(next: RealtimeState, previous: SocketState): SocketState {\n switch (next) {\n case 'idle':\n return 'idle'\n case 'connecting':\n if (previous === 'blocked') return 'blocked'\n return previous === 'idle' || previous === 'connecting' ? 'connecting' : 'reconnecting'\n case 'ready':\n return 'ready'\n case 'backoff':\n return 'reconnecting'\n case 'blocked':\n return 'blocked'\n case 'stopped':\n return 'closed'\n }\n}\n\n/** The `last error` line for a refused credential: the server's close, what to do, and that the SDK keeps trying. */\nexport function blockedDetail(info: BlockedInfo): string {\n return `auth rejected (close ${info.code}${info.reason ? ` ${info.reason}` : ''}) — check the agent's API key; a fresh hello is tried every 10–15 min until one is accepted`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;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, H as HostProfile } from './prompts-BUfpwUT7.js';
2
- export { C as CachedTexts, l as CheckManualOptions, m as Credentials, n as DEFAULT_API_BASE, o as DEFAULT_RUN_BUDGET_MS, p as DEFAULT_RUN_PROFILE, q as DoctorCheck, r as DoctorContext, F as FetchIdentityLineOptions, s as FetchServedTextsOptions, t as INTEGRATION_ENV, u as INTEGRATION_ENV_LEGACY, v as INTEGRATION_STATUS_FILE, e as IntegrationLastRun, b as IntegrationStatus, L as LEGACY_STATUS_FILE, w as LoadTextsOptions, x as LoadedTexts, y as MANUAL_FETCH_TIMEOUT_MS, z as MANUAL_MAX_BYTES, A as MANUAL_MAX_REDIRECTS, B as ManualCheck, E as ManualCheckState, M as ManualFetch, G as ManualFollower, J as ManualFollowerOptions, K as ManualSyncResult, N as ManualSyncState, P as PendingRegistration, O as RUN_BUDGET_ENV, Q as RUN_PROFILES, U as RUN_PROFILE_ENV, V as ResolvedIdentity, g as RunKind, f as RunOutcome, h as RunOutcomeState, i as RunPreflight, a as RunProfile, c as RunPrompts, j as RunRequest, R as RunRunner, X as SOCKET_STATES, Y as ServedManual, S as SocketState, Z as StatusContext, _ as SyncManualOptions, $ as TEXTS_CACHE_FILE, a0 as TEXTS_REFRESH_MS, a1 as TEXTS_RETRY_MS, a2 as TextsClient, a3 as TextsSource, a4 as TextsStatus, T as TextsStore, a5 as TextsStoreOptions, a6 as Verdict, a7 as anchorLabelOf, a8 as buildRunPrompts, a9 as checkManual, aa as clearCredentials, ab as clearIntegrationStatus, ac as clearPending, ad as clientHeadersOf, ae as clientIdentityOf, af as credentialsPath, ag as describeManualSync, ah as fetchIdentityLine, ai as fetchServedTexts, aj as formatIntegrationStatus, ak as integrationDisabled, al as integrationDisabledBy, am as integrationStatusAge, an as integrationStatusPath, ao as isRunProfile, ap as loadTexts, aq as pendingPath, ar as readCachedTexts, as as readCredentials, at as readIntegrationStatus, au as readManualVersion, av as readPending, aw as resolveIdentity, ax as resolveRunBudgetMs, ay as resolveRunProfile, az as statePath, aA as syncManual, aB as textsCachePath, aC as writeCachedTexts, aD as writeCredentials, aE as writeIntegrationStatus, aF as writePending } from './prompts-BUfpwUT7.js';
3
- import { AgentChatClient, Texts } from 'agentchatme';
1
+ import { I as IntegrationClient, H as HostProfile } from './served-manual-DZmEak4_.js';
2
+ export { C as CheckManualOptions, b as Credentials, D as DEFAULT_API_BASE, c as DoctorCheck, d as DoctorContext, F as FAILED_CYCLE_OUTCOMES, e as INTEGRATION_STATUS_FILE, f as IntegrationCycle, g as IntegrationLastRun, a as IntegrationStatus, L as LEGACY_STATUS_FILE, h as MANUAL_FETCH_TIMEOUT_MS, i as MANUAL_MAX_BYTES, j as MANUAL_MAX_REDIRECTS, k as ManualCheck, l as ManualCheckState, M as ManualFetch, m as ManualSyncResult, n as ManualSyncState, P as PendingRegistration, R as REPEATED_FAILED_CYCLES, o as ResolveIdentityOptions, p as ResolvedIdentity, q as SOCKET_STATES, r as ServedManual, S as SocketState, s as StatusContext, t as SyncManualOptions, T as TextsStatus, V as Verdict, u as anchorLabelOf, v as checkManual, w as clearCredentials, x as clearIntegrationStatus, y as clearPending, z as clientHeadersOf, A as clientIdentityOf, B as clientNameOf, E as credentialsPath, G as describeManualSync, J as envApiKey, K as failedCyclesInARow, N as formatIntegrationStatus, O as fromKitResult, Q as integrationStatusAge, U as integrationStatusPath, W as pendingPath, X as readCredentials, Y as readIntegrationStatus, Z as readManualVersion, _ as readPending, $ as resolveIdentity, a0 as statePath, a1 as syncManual, a2 as writeCredentials, a3 as writeIntegrationStatus, a4 as writePending } from './served-manual-DZmEak4_.js';
3
+ import { AgentChatClient, Texts, TextsRuntime, integration } from 'agentchatme';
4
4
  import { z } from 'zod';
5
+ export { D as DEFAULT_RUN_BUDGET_MS, k as DEFAULT_RUN_PROFILE, I as INTEGRATION_ENV, l as INTEGRATION_ENV_LEGACY, m as RUN_BUDGET_ENV, n as RUN_PROFILES, o as RUN_PROFILE_ENV, d as RunKind, c as RunOutcome, e as RunOutcomeState, f as RunPreflight, a as RunProfile, g as RunRequest, b as RunRunner, h as RunWake, i as RunnerFactory, j as RunnerIdentity, R as RunnerSource, p as integrationDisabled, q as integrationDisabledBy, r as isRunProfile, s as isRunnerFactory, t as resolveRunBudgetMs, u as resolveRunProfile } from './runner-BzgsiS3V.js';
5
6
  import { spawn, spawnSync } from 'node:child_process';
6
7
 
7
8
  /** Published package version, kept in lockstep with package.json by tests. */
8
- declare const VERSION = "0.3.1";
9
+ declare const VERSION = "0.4.0";
9
10
 
10
11
  type TrayClient = Pick<AgentChatClient, 'inbox'>;
11
12
  interface TraySummary {
@@ -18,13 +19,53 @@ interface TraySummary {
18
19
  }
19
20
  /** How many conversations are waiting, for `status`. One tray page, counted. */
20
21
  declare function traySummary(client: TrayClient): Promise<TraySummary>;
22
+
23
+ declare const TEXTS_CACHE_FILE = "texts.json";
24
+ type TextsSource = 'server' | 'cache' | 'none';
25
+ interface CachedTexts {
26
+ readonly fetched_at: string;
27
+ readonly runtime: string;
28
+ readonly texts: Texts;
29
+ }
30
+ declare function textsCachePath(home: string): string;
31
+ /** The last copy kept for this runtime, or null. A copy for another runtime is not this one's. No network. */
32
+ declare function readCachedTexts(home: string, runtime: TextsRuntime): CachedTexts | null;
33
+ type TextsClient = integration.TextsClient;
34
+ interface LoadedTexts {
35
+ readonly texts: Texts;
36
+ readonly source: 'server' | 'cache';
37
+ readonly fetched_at: string;
38
+ }
39
+ interface LoadTextsOptions {
40
+ readonly home: string;
41
+ readonly runtime: TextsRuntime;
42
+ readonly client: TextsClient;
43
+ readonly timeoutMs?: number;
44
+ readonly now?: () => Date;
45
+ }
21
46
  /**
22
- * Is anything waiting on the tray? `GET /v1/inbox?limit=1` — a count, never a
23
- * card: the one card the server may return is not read. This is the question
24
- * asked before every wake run: "does this wake deserve a run at all?" — the
25
- * reason a reconnect with an empty tray starts no run.
47
+ * One fetch with the cached copy as fallback (the kit's `TextsCache`, started
48
+ * and stopped) — what a CLI command does before it places the identity line
49
+ * or checks it. Null only when the server could not be reached and nothing was
50
+ * ever kept for this runtime.
26
51
  */
27
- declare function trayHasWaiting(client: TrayClient): Promise<boolean>;
52
+ declare function loadTexts(options: LoadTextsOptions): Promise<LoadedTexts | null>;
53
+ interface FetchIdentityLineOptions {
54
+ readonly home: string;
55
+ readonly apiKey: string;
56
+ readonly apiBase: string;
57
+ readonly client: IntegrationClient;
58
+ readonly timeoutMs?: number;
59
+ }
60
+ type FetchServedTextsOptions = FetchIdentityLineOptions;
61
+ /**
62
+ * The served texts for this agent, for an integration's own install and
63
+ * placement paths: one fetch through an SDK client built here, the cached
64
+ * copy as fallback, null when neither answers.
65
+ */
66
+ declare function fetchServedTexts(options: FetchServedTextsOptions): Promise<LoadedTexts | null>;
67
+ /** `fetchServedTexts`, reduced to the identity line. */
68
+ declare function fetchIdentityLine(options: FetchIdentityLineOptions): Promise<string | null>;
28
69
 
29
70
  declare const StateSchema: z.ZodObject<{
30
71
  offer_declined_at: z.ZodOptional<z.ZodString>;
@@ -136,7 +177,7 @@ declare function readAnchorHandleFrom(text: string): string | null;
136
177
  declare function upsertAnchorBlock(existing: string, block: string): string;
137
178
  declare function stripAnchorBlock(existing: string): string;
138
179
 
139
- declare const HOSTED_MCP_PATH = "/mcp";
180
+ declare const HOSTED_MCP_PATH: "/mcp";
140
181
  declare function hostedMcpUrl(apiBase: string): string;
141
182
  interface McpProbeResult {
142
183
  readonly ok: boolean;
@@ -144,16 +185,24 @@ interface McpProbeResult {
144
185
  readonly serverName?: string;
145
186
  readonly serverVersion?: string;
146
187
  readonly protocolVersion?: string;
188
+ /** Every tool the server listed for this key. */
189
+ readonly tools?: readonly string[];
190
+ /** Tools a run needs that were not listed. */
191
+ readonly missing?: readonly string[];
147
192
  readonly error?: string;
148
193
  }
149
194
  declare function probeHostedMcp(params: {
150
195
  apiKey: string;
151
196
  apiBase: string;
152
- /** How this integration identifies to the server (headers on the probe). */
197
+ /** How this integration identifies to the server. */
153
198
  client: IntegrationClient;
154
- /** MCP `clientInfo.name`; defaults to the runtime name. */
199
+ /**
200
+ * Accepted for compatibility and ignored: the probe identifies as `client`
201
+ * (headers and `clientInfo` alike), so the server's analytics see the
202
+ * integration, never a free-text name it would file as unknown.
203
+ */
155
204
  clientName?: string;
156
- /** MCP `clientInfo.version`; defaults to the integration's version. */
205
+ /** Accepted for compatibility and ignored (see `clientName`). */
157
206
  clientVersion?: string;
158
207
  timeoutMs?: number;
159
208
  fetch?: typeof fetch;
@@ -368,4 +417,4 @@ declare function readJsonFile<T>(filePath: string): T | null;
368
417
  declare const spawnCommand: typeof spawn;
369
418
  declare const spawnCommandSync: typeof spawnSync;
370
419
 
371
- export { ANCHOR_END, ANCHOR_START, type AlwaysOnState, type AnchorAction, type DoctorOpts, HEARTBEAT_FILE, HOSTED_MCP_PATH, type HostCopy, HostProfile, type IdentityCommands, type IdentityState, IntegrationClient, type LockHandle, MANUAL, MANUAL_FILENAME, MANUAL_SKILL_NAME, MANUAL_URL, type McpProbeResult, type Plan, type RecoverOpts, type RegisterOpts, type ServiceCommandRunner, type ServiceHostOs, type ServiceOpts, type ServiceRef, type TrayClient, type TraySummary, VERSION, acquireLeaderLock, alwaysOnHealth, alwaysOnOptedOut, alwaysOnState, alwaysOnWanted, anchorIsCurrentAt, atomicCopyFile, atomicWriteFile, beat, clearAlwaysOnInstalledVersion, clearAlwaysOnOptOut, clearAlwaysOnWanted, clearOfferDeclined, createIdentityCommands, hasAnchorAt, hostedMcpUrl, identityLineOf, idle, installService, launchdPlist, log, manualFrontMatter, manualPointer, manualVersion, markAlwaysOnInstalledVersion, markAlwaysOnOptOut, markAlwaysOnWanted, normalizeHandle, offerDeclined, parseServiceHome, planForTest, probeHostedMcp, readAlwaysOnInstalledVersion, readAnchorHandleAt, readAnchorHandleFrom, readJsonFile, readState, recordOfferDeclined, removeAnchorAt, renderAnchorBlock, renderDeclinedBlock, renderUnregisteredBlock, serviceDefinitionCurrent, serviceInstalled, serviceLabelFor, serviceStatus, setServiceCommandRunnerForTests, setServiceHostOsForTests, spawnCommand, spawnCommandSync, stripAnchorBlock, systemdQuote, systemdUnit, trayHasWaiting, traySummary, uninstallService, upsertAnchorBlock, writeAnchor, writeState, xmlEscape };
420
+ export { ANCHOR_END, ANCHOR_START, type AlwaysOnState, type AnchorAction, type CachedTexts, type DoctorOpts, type FetchIdentityLineOptions, type FetchServedTextsOptions, HEARTBEAT_FILE, HOSTED_MCP_PATH, type HostCopy, HostProfile, type IdentityCommands, type IdentityState, IntegrationClient, type LoadTextsOptions, type LoadedTexts, type LockHandle, MANUAL, MANUAL_FILENAME, MANUAL_SKILL_NAME, MANUAL_URL, type McpProbeResult, type Plan, type RecoverOpts, type RegisterOpts, type ServiceCommandRunner, type ServiceHostOs, type ServiceOpts, type ServiceRef, TEXTS_CACHE_FILE, type TextsClient, type TextsSource, type TrayClient, type TraySummary, VERSION, acquireLeaderLock, alwaysOnHealth, alwaysOnOptedOut, alwaysOnState, alwaysOnWanted, anchorIsCurrentAt, atomicCopyFile, atomicWriteFile, beat, clearAlwaysOnInstalledVersion, clearAlwaysOnOptOut, clearAlwaysOnWanted, clearOfferDeclined, createIdentityCommands, fetchIdentityLine, fetchServedTexts, hasAnchorAt, hostedMcpUrl, identityLineOf, idle, installService, launchdPlist, loadTexts, log, manualFrontMatter, manualPointer, manualVersion, markAlwaysOnInstalledVersion, markAlwaysOnOptOut, markAlwaysOnWanted, normalizeHandle, offerDeclined, parseServiceHome, planForTest, probeHostedMcp, readAlwaysOnInstalledVersion, readAnchorHandleAt, readAnchorHandleFrom, readCachedTexts, readJsonFile, readState, recordOfferDeclined, removeAnchorAt, renderAnchorBlock, renderDeclinedBlock, renderUnregisteredBlock, serviceDefinitionCurrent, serviceInstalled, serviceLabelFor, serviceStatus, setServiceCommandRunnerForTests, setServiceHostOsForTests, spawnCommand, spawnCommandSync, stripAnchorBlock, systemdQuote, systemdUnit, textsCachePath, traySummary, uninstallService, upsertAnchorBlock, writeAnchor, writeState, xmlEscape };