@agentchatme/agent-core 0.4.1 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -3
- package/dist/chunk-3ERPUP4M.js +97 -0
- package/dist/chunk-3ERPUP4M.js.map +1 -0
- package/dist/{chunk-AE4XHKHQ.js → chunk-AFDD53DD.js} +234 -10
- package/dist/chunk-AFDD53DD.js.map +1 -0
- package/dist/{chunk-7LAAAXUO.js → chunk-CDJASQ3X.js} +509 -104
- package/dist/chunk-CDJASQ3X.js.map +1 -0
- package/dist/daemon-entry.d.ts +58 -3
- package/dist/daemon-entry.js +287 -33
- package/dist/daemon-entry.js.map +1 -1
- package/dist/index.d.ts +94 -13
- package/dist/index.js +402 -354
- package/dist/index.js.map +1 -1
- package/dist/presets.d.ts +352 -21
- package/dist/presets.js +700 -105
- package/dist/presets.js.map +1 -1
- package/dist/{runner-B-ZZDAAm.d.ts → runner-DYVqz_9P.d.ts} +38 -2
- package/dist/{served-manual-99vEOjJS.d.ts → served-manual-Be_eUo0m.d.ts} +157 -26
- package/package.json +2 -2
- package/dist/chunk-7LAAAXUO.js.map +0 -1
- package/dist/chunk-AE4XHKHQ.js.map +0 -1
- package/dist/chunk-QDM4EFI7.js +0 -139
- package/dist/chunk-QDM4EFI7.js.map +0 -1
- package/dist/chunk-XDWBTX5J.js +0 -30
- package/dist/chunk-XDWBTX5J.js.map +0 -1
package/dist/daemon-entry.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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 { INTEGRATION_ENV, INTEGRATION_ENV_LEGACY, INTEGRATION_ENV_LEGACY_REMOVAL, 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 if (disabledBy === INTEGRATION_ENV_LEGACY) {\n log.warn(`${INTEGRATION_ENV_LEGACY} is the old name of ${INTEGRATION_ENV} (agent contract v1 schedules its removal for ${INTEGRATION_ENV_LEGACY_REMOVAL}); set ${INTEGRATION_ENV}=off instead`)\n }\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,YAAYA,WAAU;AACtB,YAAY,QAAQ;;;ACDpB,YAAY,UAAU;AACtB,SAAS,uBAAuB;AA6BzB,SAAS,UAAU,SAAyB;AACjD,SAAO,QAAQ,QAAQ,SAAS,IAAI,EAAE,QAAQ,QAAQ,EAAE;AAC1D;AAGO,SAAS,SAAS,SAAyB;AAChD,SAAO,GAAG,UAAU,OAAO,CAAC;AAC9B;AAqBA,eAAsB,oBAAoB,MAAgD;AACxF,QAAM,OAAY,aAAQ,KAAK,IAAI;AACnC,QAAM,KAA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OAAO,eAAe,QAAQ,IAAI,UAAU,GAAG;AAC3D,YAAI,QAAQ,aAAa;AACvB,cAAI,KAAK,uBAAuB,GAAG,EAAE;AACrC,wBAAc;AACd,oBAAU,WAAW,GAAG,UAAU,IAAI;AAAA,QACxC;AACA,oBAAY;AACZ,eAAO;AACP,0BAAkB;AAClB,aAAK,IAAI;AAAA,MACX;AAAA,IACF;AAMA,UAAM,SAAS,aAAa,IAAI,UAAU,KAAK,IAAI,UAAU,KAAK,KAAK,IAAI,UAAU,CAAC,GAAG,cAAc;AACvG,aAAS;AACT,UAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,WAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC,KAAK,QAAQ,WAAW,KAAK,IAAI,IAAI,UAAU;AACjF,YAAM,MAAM,OAAO;AAAA,IACrB;AAAA,EACF;AAEA,UAAQ,IAAI,UAAU,QAAQ;AAC9B,UAAQ,IAAI,WAAW,SAAS;AAChC,MAAI,SAAS,MAAM;AACjB,UAAM,QAAQ,MAAM,KAAK,YAAY,iBAAiB;AACtD,QAAI,CAAC,MAAO,KAAI,KAAK,sCAAsC,KAAK,MAAM,oBAAoB,GAAI,CAAC,8CAAyC;AACxI,WAAO;AAAA,EACT;AACA,OAAK,IAAI;AACT,OAAK,QAAQ;AACb,MAAI,cAAc;AAChB,QAAI,KAAK,mBAAmB;AAC3B,KAAC,KAAK,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAChC;AACA,SAAO;AACT;","names":["path","AgentChatClient","resolve","AgentChatClient"]}
|
|
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 { acquireAgentLock, agentLockPath, agentLockRefusal, clearStandby, markStandby, standbyWaiting } from '../daemon/agent-lock.js'\nimport type { Lease, LeaseOptions } from '../util/lease.js'\nimport type { DaemonConfig } from '../daemon/config.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, PREFLIGHT_DEADLINE_MS, RUNTIME_RECHECK_MS, withDeadline } from './integration.js'\nimport { INTEGRATION_ENV, INTEGRATION_ENV_LEGACY, INTEGRATION_ENV_LEGACY_REMOVAL, integrationDisabledBy, resolveRunBudgetMs, resolveRunProfile, type RunProfile } from './profile.js'\nimport { isRunnerFactory, type RunRunner, type RunnerSource } from './runner.js'\nimport { writeIntegrationStatus, type IntegrationRunsFailing, type IntegrationStandby, type IntegrationStatus, type IntegrationUnservable } 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/** While another daemon serves this agent: how often to look whether it still does (and rewrite the status file, so it never reads as a daemon that is down). */\nconst STANDBY_POLL_MS = 30_000\n/** After giving the agent up because this home could not serve it: when to check again (the runtime; then the lease). */\nconst UNSERVABLE_RECHECK_MS = 60_000\n/** A home whose key the server refused tries again this much later (a new hello with the same key). */\nconst BLOCKED_RETRY_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 /** Test seam: while serving, how often to look again (5 s; the backoff after failed starts grows from it). */\n pollMs?: number\n /** Test seam: the loop's own tick, how soon it notices a nudge (250 ms). */\n tickMs?: number\n /** Test seams: `IntegrationOptions.quietMs`, `maxMs` and `paceMs` (when a wake's run starts). */\n quietMs?: number\n maxMs?: number\n paceMs?: number\n /** Test seam: while another daemon serves this agent, how often to look again (30 s). */\n standbyPollMs?: number\n /** Test seam: `IntegrationOptions.runtimeRecheckMs`. */\n runtimeRecheckMs?: number\n /** Test seam: after giving the agent up, when to look again (60 s; 5 min after a refused key). */\n unservableRecheckMs?: number\n /** Test seam: the agent and home leases' timing (`LeaseOptions`). */\n lease?: LeaseOptions\n /** Test seam: how long a give-up recheck waits for the runtime's preflight (`PREFLIGHT_DEADLINE_MS`). */\n preflightDeadlineMs?: number\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))\n\n/** Sleep `ms`, or less if `signal` fires (a stop is never held for a tick). */\nfunction sleepUnless(ms: number, signal: AbortSignal | undefined): Promise<void> {\n if (signal?.aborted === true) return Promise.resolve()\n return new Promise((resolve) => {\n const done = (): void => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', done)\n resolve()\n }\n const timer = setTimeout(done, ms)\n signal?.addEventListener('abort', done, { once: true })\n })\n}\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/** The agent is served by another daemon (or this home waits to serve again): not a failure, no backoff. */\nclass StandbyError extends Error {}\n\n/** A home that gave its agent up because it could not serve it, and when it looks again. */\ninterface Unservable {\n readonly kind: IntegrationUnservable['reason']\n readonly detail: string\n readonly since: string\n readonly retryAt: number\n readonly runsFailing: IntegrationRunsFailing | null\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 // Wakes the loop's wait early (a credential change, a lost lock).\n let nudged = false\n // Stops checks in flight (a give-up recheck's probes) when the daemon stops.\n const stopChecks = new AbortController()\n // A signal aborted already fires no event: stopped from the start.\n if (opts.signal?.aborted === true) stopChecks.abort()\n else opts.signal?.addEventListener('abort', () => stopChecks.abort(), { once: true })\n\n // Taken for the PROCESS, not for a connection: one resident daemon per\n // identity home, signed in or not. A lease: should another daemon ever take\n // it (this one stalled past the lease), this one stands down and exits now.\n // Taking it, a held lease is watched for the stale window plus a renewal\n // (`acquireLeaderLock`): a lease whose pid was reused is taken over here,\n // not refused into a service restart that would look at it afresh, for ever.\n const lock = await acquireLeaderLock(home, { ...(opts.lease ?? {}), signal: stopChecks.signal })\n if (lock === null) return 1\n let homeLost: string | null = null\n /** The integration being started, before it is `live`: a lost lock stops it too. */\n let starting: Integration | null = null\n lock.onLost((why) => {\n homeLost = why\n nudged = true\n // At once, not at the loop's next tick: no wake may start a run meanwhile.\n starting?.stop()\n live?.stop()\n log.error(`lost this home's daemon lock (${why}) — another daemon serves ${home} now; this one exits`)\n })\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 /** The agent lock (one agent, one listener), held for as long as an integration is live. */\n let agentLock: Lease | null = null\n /** Set by the lease when a renewal finds it no longer this process's: stand down at once. */\n let agentLost: string | null = null\n /** Another daemon serves this agent: who, for status. */\n let standby: IntegrationStandby | null = null\n /** This home gave the agent up because it could not serve it; when to look again. */\n let unservable: Unservable | null = null\n /** The runner the last integration used: what checks the runtime while this home waits to serve again. */\n let lastRunner: RunRunner | null = null\n /** The resolved identity for the current credential: an env-key standby does not ask /v1/agents/me on every poll. */\n let cachedCfg: { fp: string; cfg: DaemonConfig } | null = null\n /** The agent lock's file (for the standby marker beside it), once the identity is known. */\n let agentLockFile: string | null = null\n /** The runner for the current identity, built once: what a standby checks, and what serves when it takes over. */\n let prepared: { fp: string; runner: RunRunner } | null = null\n /** A standby's last check of its own runtime (it offers to take over failing runs only while that passes). */\n let standbyCheck: { fp: string; ok: boolean; detail: string | null; at: number } | null = null\n const runnerFor = (cfg: DaemonConfig, fp: string): RunRunner => {\n if (prepared === null || prepared.fp !== fp) prepared = { fp, runner: isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner }\n return prepared.runner\n }\n /** The runtime's own preflight: bounded, and stopped with the daemon. */\n const preflightOf = async (runner: RunRunner): Promise<{ ok: boolean; detail?: string }> => {\n const deadlineMs = opts.preflightDeadlineMs ?? PREFLIGHT_DEADLINE_MS\n return withDeadline(runner.preflight({ signal: stopChecks.signal }), deadlineMs, () => ({ ok: false, detail: `preflight did not answer within ${Math.round(deadlineMs / 1000)} s` })).catch(\n (err: unknown) => ({ ok: false, detail: `preflight threw: ${err instanceof Error ? err.message : String(err)}` }),\n )\n }\n const releaseAgent = (): void => {\n agentLock?.release()\n agentLock = null\n agentLost = null\n }\n const stopWaiting = (): void => {\n if (agentLockFile !== null) clearStandby(agentLockFile, home)\n }\n /** Lock renewals that failed, for status: the home lock's and the agent lock's. */\n const leaseErrors = (): NonNullable<IntegrationStatus['lease_errors']> | null => {\n const count = lock.renewErrors + (agentLock?.renewErrors ?? 0)\n return count === 0 ? null : { count, last: agentLock?.lastRenewError ?? lock.lastRenewError }\n }\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 workdir,\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 standby,\n runs_failing: unservable?.runsFailing ?? null,\n unservable: unservable === null ? null : { reason: unservable.kind, detail: unservable.detail, since: unservable.since, retry_at: new Date(unservable.retryAt).toISOString() },\n lease_errors: leaseErrors(),\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 releaseAgent()\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 stopChecks.abort()\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 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 if (disabledBy === INTEGRATION_ENV_LEGACY) {\n log.warn(`${INTEGRATION_ENV_LEGACY} is the old name of ${INTEGRATION_ENV} (agent contract v1 schedules its removal for ${INTEGRATION_ENV_LEGACY_REMOVAL}); set ${INTEGRATION_ENV}=off instead`)\n }\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 (homeLost !== null) break\n if (identityChanged) {\n disconnect(fp === null ? 'signed out' : 'identity changed')\n observedFingerprint = fp\n failures = 0\n lastFailure = null\n stopWaiting()\n standby = null\n unservable = null\n cachedCfg = null\n agentLockFile = 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 (live !== null && fp === liveFingerprint) {\n // Serving. Stand down at once if the agent lock is no longer ours, and\n // give the agent up while this home cannot serve it — so a healthy\n // listener for the same agent (a standby) can take over.\n const health = live.health()\n if (agentLost !== null) {\n const why = agentLost\n disconnect(`the agent lock is no longer this home's (${why})`)\n lastFailure = `@${cachedCfg?.cfg.handle ?? '?'}: ${why}; another listener serves this agent now`\n } else if (!health.ok) {\n const handle = cachedCfg?.cfg.handle ?? '?'\n const kind: Unservable['kind'] = health.runsFailing === null ? 'key_refused' : 'runs_failing'\n // A refused key cannot serve at all: given up whatever waits. Failing\n // runs are given up only to a healthy listener that is actually\n // waiting; a lone install keeps its socket — wakes keep arriving, are\n // counted and start runs (each the quickest way back).\n if (kind === 'key_refused' || (agentLockFile !== null && standbyWaiting(agentLockFile, home))) {\n const retryMs = opts.unservableRecheckMs ?? (kind === 'key_refused' ? BLOCKED_RETRY_MS : UNSERVABLE_RECHECK_MS)\n unservable = { kind, detail: health.reason, since: new Date().toISOString(), retryAt: Date.now() + retryMs, runsFailing: health.runsFailing }\n disconnect(`this home cannot serve @${handle} (${health.reason}): giving it up to ${kind === 'key_refused' ? 'any healthy listener' : 'the healthy listener waiting for it'}`)\n lastFailure = `this home cannot serve @${handle}: ${health.reason}. It holds no socket and starts no run while another listener can serve @${handle}; it looks again every ${Math.round(retryMs / 1000)} s${kind === 'runs_failing' ? ' (the runtime checked first: a check that passes clears this)' : ' (signing in again here clears this at once)'}, and takes @${handle} back whenever no other listener holds it.`\n log.warn(lastFailure)\n offStatus(handle)\n }\n }\n } else if (live === null) {\n try {\n // Not before its time: a home that gave the agent up retries on its own clock.\n if (unservable !== null && Date.now() < unservable.retryAt) throw new StandbyError(unservable.detail)\n const waiting: Unservable | null = unservable\n if (waiting !== null && waiting.kind === 'runs_failing' && lastRunner !== null) {\n // Runs were failing: the runtime is checked first (bounded, stopped with the daemon).\n const before: Unservable = waiting\n const checker = lastRunner\n const pre = await preflightOf(checker)\n standbyCheck = { fp, ok: pre.ok, detail: pre.ok ? null : `${checker.name}: ${pre.detail ?? 'its check failed'}`, at: Date.now() }\n if (shuttingDown || opts.signal?.aborted) throw new StandbyError('stopping')\n if (pre.ok) unservable = null\n else unservable = { ...before, detail: `runs failing: ${checker.name}: ${pre.detail ?? 'its check failed'}`, retryAt: Date.now() + (opts.unservableRecheckMs ?? UNSERVABLE_RECHECK_MS) }\n }\n if (cachedCfg === null || cachedCfg.fp !== fp) cachedCfg = { fp, cfg: await resolveDaemonConfig({ home, workdir, client: opts.client, envKey }) }\n const cfg = cachedCfg.cfg\n agentLockFile = agentLockPath({ apiBase: cfg.apiBase, handle: cfg.handle })\n // One agent, one listener: a daemon in another home that already\n // serves this agent keeps it; this one stands by (no socket, no run)\n // and takes over when that one stops or gives it up. The lock folder\n // comes from the process environment only: a service and a shell for\n // the same user agree on it, whatever switches `env` carries.\n const attempt = await acquireAgentLock({ apiBase: cfg.apiBase, handle: cfg.handle, home }, process.env, { ...(opts.lease ?? {}), signal: stopChecks.signal })\n if (shuttingDown || opts.signal?.aborted) {\n if (attempt.ok) attempt.lease.release()\n throw new StandbyError('stopping')\n }\n if (!attempt.ok) {\n const current: Unservable | null = unservable\n if (current !== null) {\n // Still unable to serve, and another listener holds the agent: wait, without saying it is healthy.\n unservable = { ...current, retryAt: Date.now() + (opts.unservableRecheckMs ?? (current.kind === 'key_refused' ? BLOCKED_RETRY_MS : UNSERVABLE_RECHECK_MS)) }\n throw new StandbyError(current.detail)\n }\n standby = { home: attempt.holder?.home ?? null, pid: attempt.holder?.pid ?? null, since: attempt.holder?.acquired_at ?? null }\n // A standby says it is waiting — so a holder whose runs fail hands the\n // agent over — only while its own runtime checks out: one that could\n // not serve either must not leave the agent with no socket at all.\n const recheckMs = opts.runtimeRecheckMs ?? RUNTIME_RECHECK_MS\n if (standbyCheck === null || standbyCheck.fp !== fp || Date.now() - standbyCheck.at >= recheckMs) {\n const runner = runnerFor(cfg, fp)\n const pre = await preflightOf(runner)\n if (shuttingDown || opts.signal?.aborted) throw new StandbyError('stopping')\n standbyCheck = { fp, ok: pre.ok, detail: pre.ok ? null : `${runner.name}: ${pre.detail ?? 'its check failed'}`, at: Date.now() }\n }\n if (standbyCheck.ok) markStandby(attempt.path, home)\n else clearStandby(attempt.path, home)\n const refusal = agentLockRefusal({ handle: cfg.handle, home }, attempt.holder, attempt.path)\n const msg = standbyCheck.ok\n ? refusal\n : `${refusal} Its own runtime does not check out (${standbyCheck.detail ?? 'its check failed'}), so it does not offer to take over from a holder whose runs fail.`\n if (msg !== lastFailure) log.warn(msg)\n lastFailure = msg\n throw new StandbyError(msg)\n }\n stopWaiting()\n if (standby !== null) log.info(`@${cfg.handle}: the other listener stopped; this one serves the agent now`)\n if (unservable !== null) log.info(`@${cfg.handle}: no other listener holds the agent; this home serves it again (${unservable.detail})`)\n standby = null\n unservable = null\n const lease = attempt.lease\n agentLock = lease\n lease.onLost((why) => {\n if (agentLock !== lease) return\n agentLost = why\n nudged = true\n // At once, not at the loop's next tick: no wake may start a run meanwhile.\n starting?.stop()\n live?.stop()\n })\n const runner = runnerFor(cfg, fp)\n lastRunner = 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 ...(opts.runtimeRecheckMs !== undefined ? { runtimeRecheckMs: opts.runtimeRecheckMs } : {}),\n ...(opts.quietMs !== undefined ? { quietMs: opts.quietMs } : {}),\n ...(opts.maxMs !== undefined ? { maxMs: opts.maxMs } : {}),\n ...(opts.paceMs !== undefined ? { paceMs: opts.paceMs } : {}),\n statusExtra: () => ({ lease_errors: leaseErrors() }),\n })\n starting = candidate\n try {\n await candidate.start()\n } finally {\n starting = null\n }\n // The lock lost while it started: it was stopped; never serve on a lock that is not ours.\n if (agentLost !== null || homeLost !== null) {\n candidate.stop()\n throw new StandbyError(`the agent lock is no longer this home's (${agentLost ?? homeLost})`)\n }\n live = candidate\n liveFingerprint = fp\n failures = 0\n lastFailure = null\n } catch (err) {\n releaseAgent()\n live = null\n liveFingerprint = null\n if (err instanceof StandbyError) {\n // Standing by, or waiting to serve again: the status file is rewritten\n // every poll, so `status` never reads it as a daemon that is down.\n offStatus(cachedCfg?.cfg.handle ?? identityOf()?.handle ?? null)\n } else {\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 }\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 pollMs = opts.pollMs ?? POLL_MS\n const waitMs = homeLost !== null || agentLost !== null ? 0 : standby !== null || unservable !== null ? (opts.standbyPollMs ?? STANDBY_POLL_MS) : failures === 0 ? pollMs : Math.min(pollMs * 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 sleepUnless(opts.tickMs ?? TICK_MS, opts.signal)\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 releaseAgent()\n stopWaiting()\n idle(home)\n lock.release()\n if (homeLost !== null) return 1\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 IntegrationRunsFailing, 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/**\n * After a run that did not get done, the runtime is checked again (its\n * preflight) — at most once per this while runs keep failing, never on every\n * wake. A failing check is what `status` and `doctor` then say.\n */\nexport const RUNTIME_RECHECK_MS = 5 * 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; `RUNTIME_RECHECK_MS`. */\n readonly runtimeRecheckMs?: number\n /** What the supervisor adds to every status this integration writes (its locks' renewal errors). */\n readonly statusExtra?: () => Partial<IntegrationStatus>\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. */\nexport function 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 /** When the first run that did not get done since the last good one ended; null while runs succeed. */\n private failingSince: string | null = null\n /** Runs that did not get done since then. */\n private failingRuns = 0\n /** What the runtime's own check says while runs fail (status `runs_failing`); null when it has not failed one. */\n private runsFailing: IntegrationRunsFailing | null = null\n private lastRecheckAt = 0\n private recheckInFlight: Promise<void> | null = null\n /** Aborts a runtime check in flight when the integration stops (its probes are killed, not left running). */\n private readonly recheckAbort = new AbortController()\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.recheckAbort.abort()\n this.stopped = Promise.all([this.loop.stop(), this.recheckInFlight ?? Promise.resolve()]).then(() => undefined)\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 workdir: this.options.cfg.workdir,\n standby: null,\n runs_failing: this.runsFailing,\n unservable: null,\n ...(this.options.statusExtra?.() ?? {}),\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 const identityLine = this.texts.current()?.identity_line\n let outcome: RunOutcome\n try {\n outcome = await withDeadline(\n this.options.runner.start({\n kind,\n wake,\n // No pointer, no trailing blank lines.\n prompt: this.options.manualPointer.trim().length > 0 ? `${request.prompt}\\n\\n${this.options.manualPointer}` : request.prompt,\n runId,\n ...(identityLine !== undefined && identityLine.trim().length > 0 ? { identityLine } : {}),\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.noteRunHealth(outcome, this.lastRun.ended_at)\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 /**\n * A run that did not get done may be the runtime itself (signed out, the\n * binary gone, a flag an upgrade dropped): checked again, at most once per\n * `RUNTIME_RECHECK_MS`, and said in status until a run succeeds. Wakes keep\n * starting runs meanwhile — each is the quickest way back — and are counted.\n */\n private noteRunHealth(outcome: RunOutcome, endedAt: string): void {\n if (outcome.state === 'ok') {\n if (this.runsFailing !== null) log.info(`runs work again (${this.failingRuns} run(s) missed since ${this.failingSince})`)\n this.failingSince = null\n this.failingRuns = 0\n this.runsFailing = null\n // A new failure after a good run is a new problem: checked at once, not after the old window.\n this.lastRecheckAt = 0\n return\n }\n this.failingSince ??= endedAt\n this.failingRuns += 1\n if (this.runsFailing !== null) this.runsFailing = { ...this.runsFailing, runs_missed: this.failingRuns }\n const recheckMs = this.options.runtimeRecheckMs ?? RUNTIME_RECHECK_MS\n if (this.recheckInFlight === null && !this.stopping && (this.lastRecheckAt === 0 || Date.now() - this.lastRecheckAt >= recheckMs)) {\n this.recheckInFlight = this.recheckRuntime().finally(() => {\n this.recheckInFlight = null\n })\n }\n }\n\n private async recheckRuntime(): Promise<void> {\n this.lastRecheckAt = Date.now()\n const pre = await withDeadline(this.options.runner.preflight({ signal: this.recheckAbort.signal }), PREFLIGHT_DEADLINE_MS, () => ({\n ok: false,\n detail: `preflight did not answer within ${Math.round(PREFLIGHT_DEADLINE_MS / 1000)} s`,\n })).catch((err: unknown) => ({ ok: false, detail: `preflight threw: ${err instanceof Error ? err.message : String(err)}` }))\n // A run succeeded while it was being checked: nothing to say.\n if (this.failingSince === null || this.stopping) return\n const checkedAt = new Date().toISOString()\n if (!pre.ok) {\n const reason = `${this.options.runner.name}: ${pre.detail ?? 'its check failed'}`\n if (this.runsFailing?.reason !== reason) log.warn(`runs failing — ${reason} (since ${this.failingSince}, ${this.failingRuns} run(s) missed); status says so until a run succeeds`)\n this.runsFailing = { reason, since: this.failingSince, runs_missed: this.failingRuns, checked_at: checkedAt }\n } else if (this.runsFailing !== null) {\n // The runtime checks out again, but no run has succeeded yet.\n this.runsFailing = {\n ...this.runsFailing,\n reason: `${this.options.runner.name} checks out now, but runs still fail${this.lastRun?.detail ? ` (last: ${this.lastRun.detail})` : ''}`,\n checked_at: checkedAt,\n }\n }\n this.writeStatus()\n }\n\n /**\n * Whether this integration can serve its agent: not while the server refuses\n * its key (socket `blocked`: rotated by `recover` elsewhere, revoked), nor\n * while runs fail for a runtime reason (`runs_failing`). The supervisor then\n * gives the agent up so a healthy listener for it can serve.\n */\n health(): { ok: true } | { ok: false; reason: string; runsFailing: IntegrationRunsFailing | null } {\n if (this.socket === 'blocked') return { ok: false, reason: `the server refuses this home's key${this.lastError ? ` (${this.lastError})` : ''}`, runsFailing: null }\n if (this.runsFailing !== null) return { ok: false, reason: `runs failing: ${this.runsFailing.reason}`, runsFailing: this.runsFailing }\n return { ok: true }\n }\n\n /** Test seam: resolves when a runtime check started by a failed run has finished. */\n async runtimeCheckDone(): Promise<void> {\n await this.recheckInFlight\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,YAAYA,WAAU;AACtB,YAAY,QAAQ;;;ACDpB,YAAY,UAAU;AACtB,SAAS,uBAAuB;AA6BzB,SAAS,UAAU,SAAyB;AACjD,SAAO,QAAQ,QAAQ,SAAS,IAAI,EAAE,QAAQ,QAAQ,EAAE;AAC1D;AAGO,SAAS,SAAS,SAAyB;AAChD,SAAO,GAAG,UAAU,OAAO,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;AAAA,EACF;AAEA,UAAQ,IAAI,UAAU,QAAQ;AAC9B,UAAQ,IAAI,WAAW,SAAS;AAChC,MAAI,SAAS,MAAM;AACjB,UAAM,QAAQ,MAAM,KAAK,YAAY,iBAAiB;AACtD,QAAI,CAAC,MAAO,KAAI,KAAK,sCAAsC,KAAK,MAAM,oBAAoB,GAAI,CAAC,8CAAyC;AACxI,WAAO;AAAA,EACT;AACA,eAAa;AACb,cAAY;AACZ,OAAK,IAAI;AACT,OAAK,QAAQ;AACb,MAAI,aAAa,KAAM,QAAO;AAC9B,MAAI,cAAc;AAChB,QAAI,KAAK,mBAAmB;AAC3B,KAAC,KAAK,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAChC;AACA,SAAO;AACT;","names":["path","AgentChatClient","resolve","AgentChatClient","resolve","runner"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { I as IntegrationClient, H as HostProfile } from './served-manual-
|
|
2
|
-
export { C as CheckManualOptions,
|
|
1
|
+
import { I as IntegrationClient, H as HostProfile, c as Lease, L as LeaseOptions, d as LeaseAttempt, e as LeaseHolder } from './served-manual-Be_eUo0m.js';
|
|
2
|
+
export { C as CheckManualOptions, f as Credentials, D as DEFAULT_API_BASE, g as DoctorCheck, h as DoctorContext, F as FAILED_CYCLE_OUTCOMES, i as INTEGRATION_STATUS_FILE, j as IntegrationCycle, k as IntegrationLastRun, b as IntegrationRunsFailing, l as IntegrationStandby, a as IntegrationStatus, m as IntegrationUnservable, n as LEASE_RENEW_MS, o as LEASE_STALE_MS, p as LEGACY_STATUS_FILE, q as MANUAL_FETCH_TIMEOUT_MS, r as MANUAL_MAX_BYTES, s as MANUAL_MAX_REDIRECTS, t as ManualCheck, u as ManualCheckState, M as ManualFetch, v as ManualSyncResult, w as ManualSyncState, P as PendingRegistration, x as PendingSignup, R as REPEATED_FAILED_CYCLES, y as ResolveIdentityOptions, z as ResolvedIdentity, A as SOCKET_STATES, B as ServedManual, S as SocketState, E as StatusContext, G as SyncManualOptions, T as TextsStatus, V as Verdict, J as acquireLease, K as anchorLabelOf, N as bootedAt, O as checkManual, Q as clearCredentials, U as clearIntegrationStatus, W as clearPending, X as clientHeadersOf, Y as clientIdentityOf, Z as clientNameOf, _ as credentialsPath, $ as describeManualSync, a0 as envApiKey, a1 as failedCyclesInARow, a2 as formatIntegrationStatus, a3 as fromKitResult, a4 as holderLive, a5 as integrationStatusAge, a6 as integrationStatusPath, a7 as leaseHolder, a8 as parseLease, a9 as pendingPath, aa as pidAlive, ab as readCredentials, ac as readIntegrationStatus, ad as readManualVersion, ae as readPending, af as resetLeaseObservations, ag as resolveIdentity, ah as statePath, ai as syncManual, aj as writeCredentials, ak as writeIntegrationStatus, al as writePending } from './served-manual-Be_eUo0m.js';
|
|
3
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 INTEGRATION_ENV_LEGACY_REMOVAL, n as RUN_BUDGET_ENV, o as RUN_PROFILES, p 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,
|
|
5
|
+
export { D as DEFAULT_RUN_BUDGET_MS, k as DEFAULT_RUN_PROFILE, I as INTEGRATION_ENV, l as INTEGRATION_ENV_LEGACY, m as INTEGRATION_ENV_LEGACY_REMOVAL, P as PEER_RUN_WARNING, n as RUN_BUDGET_ENV, o as RUN_PROFILES, p as RUN_PROFILE_ENV, d as RunKind, c as RunOutcome, e as RunOutcomeState, f as RunPreflight, q as RunPreflightOptions, a as RunProfile, g as RunRequest, b as RunRunner, h as RunWake, i as RunnerFactory, j as RunnerIdentity, R as RunnerSource, r as integrationDisabled, s as integrationDisabledBy, t as isRunProfile, u as isRunnerFactory, v as resolveRunBudgetMs, w as resolveRunProfile, x as runProfileWarning, y as workdirExposesHome } from './runner-DYVqz_9P.js';
|
|
6
6
|
import { spawn, spawnSync } from 'node:child_process';
|
|
7
7
|
|
|
8
8
|
/** Published package version, kept in lockstep with package.json by tests. */
|
|
9
|
-
declare const VERSION = "0.
|
|
9
|
+
declare const VERSION = "0.5.1";
|
|
10
10
|
|
|
11
11
|
type TrayClient = Pick<AgentChatClient, 'inbox'>;
|
|
12
12
|
interface TraySummary {
|
|
@@ -137,6 +137,12 @@ interface HostCopy {
|
|
|
137
137
|
* Deliberately bounded: static text is re-read every session, so without an
|
|
138
138
|
* explicit stop condition an agent would raise it forever. `--not-now` records
|
|
139
139
|
* the decline and rewrites this block to the silent variant below.
|
|
140
|
+
*
|
|
141
|
+
* It names the commands and nothing of the server's: no handle rules, no
|
|
142
|
+
* code length, no scripted answer for a failure. Each command prints the
|
|
143
|
+
* server's sentence and the command to run next, and the agent relays the one
|
|
144
|
+
* and runs the other, so a rule that moves on the server never leaves a stale
|
|
145
|
+
* copy in every instruction file.
|
|
140
146
|
*/
|
|
141
147
|
declare function renderUnregisteredBlock(copy: HostCopy): string;
|
|
142
148
|
/**
|
|
@@ -247,6 +253,7 @@ interface RegisterOpts {
|
|
|
247
253
|
handle?: string;
|
|
248
254
|
displayName?: string;
|
|
249
255
|
description?: string;
|
|
256
|
+
/** The code from the verification email — the completion leg. */
|
|
250
257
|
code?: string;
|
|
251
258
|
apiBase?: string;
|
|
252
259
|
}
|
|
@@ -254,12 +261,13 @@ interface RecoverOpts {
|
|
|
254
261
|
/** The email the agent registered with. */
|
|
255
262
|
email?: string;
|
|
256
263
|
/**
|
|
257
|
-
* Which agent on that email to re-key.
|
|
258
|
-
*
|
|
259
|
-
*
|
|
264
|
+
* Which agent on that email to re-key. When omitted it defaults to this
|
|
265
|
+
* agent's stored handle, then to a prompt on a TTY; without one the
|
|
266
|
+
* server is asked by email alone, and names the handles to choose from
|
|
267
|
+
* when the email backs several agents.
|
|
260
268
|
*/
|
|
261
269
|
handle?: string;
|
|
262
|
-
/** The
|
|
270
|
+
/** The code from the recovery email — the completion leg. */
|
|
263
271
|
code?: string;
|
|
264
272
|
apiBase?: string;
|
|
265
273
|
}
|
|
@@ -334,10 +342,64 @@ declare function alwaysOnHealth(home: string): {
|
|
|
334
342
|
healthy: boolean;
|
|
335
343
|
};
|
|
336
344
|
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
345
|
+
type LockHandle = Lease;
|
|
346
|
+
/** The leader lock's file name in an identity home (consumers that stop or inspect a daemon read it). */
|
|
347
|
+
declare const DAEMON_LOCK_FILE = "daemon.lock";
|
|
348
|
+
/**
|
|
349
|
+
* Take the home's leader lock, once, as a daemon starts. A held lease is
|
|
350
|
+
* watched for the stale window plus a renewal before refusing (unless
|
|
351
|
+
* `options.observeMs` says otherwise): a holder that is there renews within it
|
|
352
|
+
* (refused, within one renewal), and one whose pid was reused — a reboot, a
|
|
353
|
+
* logoff that killed the daemon — is taken over by this process instead of
|
|
354
|
+
* leaving a service to restart into the same first look for ever.
|
|
355
|
+
*/
|
|
356
|
+
declare function acquireLeaderLock(home: string, options?: LeaseOptions): Promise<LockHandle | null>;
|
|
357
|
+
|
|
358
|
+
/** Overrides the folder (tests and sandboxes). Two listeners given different folders do not see each other. */
|
|
359
|
+
declare const AGENT_LOCK_DIR_ENV = "AGENTCHAT_LOCK_DIR";
|
|
360
|
+
/**
|
|
361
|
+
* The per-user folder the agent locks live in. Derived from the home folder
|
|
362
|
+
* only — not XDG_STATE_HOME or LOCALAPPDATA, which a service's environment
|
|
363
|
+
* and a shell's can disagree on:
|
|
364
|
+
*
|
|
365
|
+
* macOS ~/Library/Application Support/AgentChat/locks
|
|
366
|
+
* Windows %USERPROFILE%\AppData\Local\AgentChat\locks
|
|
367
|
+
* other ~/.local/state/agentchat/locks
|
|
368
|
+
*
|
|
369
|
+
* Created owner-only (0700).
|
|
370
|
+
*/
|
|
371
|
+
declare function agentLockDir(env?: NodeJS.ProcessEnv, system?: NodeJS.Platform, home?: string): string;
|
|
372
|
+
/** The agent lock's file for an agent: `agent-<32 hex>.lock`, the hash of its API origin and handle. */
|
|
373
|
+
declare function agentLockPath(agent: {
|
|
374
|
+
apiBase: string;
|
|
375
|
+
handle: string;
|
|
376
|
+
}, env?: NodeJS.ProcessEnv): string;
|
|
377
|
+
/**
|
|
378
|
+
* Hold this agent for this process (an identity home's daemon), or learn which
|
|
379
|
+
* live process does. The lock is a lease (`util/lease.ts`): renewed while held,
|
|
380
|
+
* stale 45 s after its holder stops renewing (at once when its pid is dead on
|
|
381
|
+
* this host); a holder that finds it replaced stands down (`Lease.onLost`).
|
|
382
|
+
*/
|
|
383
|
+
declare function acquireAgentLock(agent: {
|
|
384
|
+
apiBase: string;
|
|
385
|
+
handle: string;
|
|
386
|
+
home: string;
|
|
387
|
+
}, env?: NodeJS.ProcessEnv, options?: LeaseOptions): Promise<LeaseAttempt>;
|
|
388
|
+
/** The status sentence for a daemon that does not serve its agent because another does (or the lock is contended right now). */
|
|
389
|
+
declare function agentLockRefusal(agent: {
|
|
390
|
+
handle: string;
|
|
391
|
+
home: string;
|
|
392
|
+
}, holder: LeaseHolder | null, file: string): string;
|
|
393
|
+
/** How fresh a standby marker must be to count (three standby polls). */
|
|
394
|
+
declare const STANDBY_MARKER_FRESH_MS = 90000;
|
|
395
|
+
/** The marker a standby in `home` keeps beside the agent lock at `lockFile`. */
|
|
396
|
+
declare function standbyMarkerPath(lockFile: string, home: string): string;
|
|
397
|
+
/** Say (again) that the standby in `home` is waiting to serve the agent. Best effort; never throws. */
|
|
398
|
+
declare function markStandby(lockFile: string, home: string): void;
|
|
399
|
+
/** The standby in `home` no longer waits (it serves now, or stops). Never throws. */
|
|
400
|
+
declare function clearStandby(lockFile: string, home: string): void;
|
|
401
|
+
/** Whether a healthy standby other than `home` is waiting for the agent at `lockFile`. */
|
|
402
|
+
declare function standbyWaiting(lockFile: string, home: string, now?: number): boolean;
|
|
341
403
|
|
|
342
404
|
/**
|
|
343
405
|
* Enough to ADDRESS an already-installed service. Removing one or reading its
|
|
@@ -451,4 +513,23 @@ declare function readJsonFile<T>(filePath: string): T | null;
|
|
|
451
513
|
declare const spawnCommand: typeof spawn;
|
|
452
514
|
declare const spawnCommandSync: typeof spawnSync;
|
|
453
515
|
|
|
454
|
-
|
|
516
|
+
interface ProbeResult {
|
|
517
|
+
/** Why it did not answer: it could not be started, or it timed out. */
|
|
518
|
+
readonly error?: Error;
|
|
519
|
+
readonly status: number | null;
|
|
520
|
+
readonly stdout: string;
|
|
521
|
+
readonly stderr: string;
|
|
522
|
+
readonly timedOut: boolean;
|
|
523
|
+
}
|
|
524
|
+
interface ProbeOptions {
|
|
525
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
526
|
+
readonly timeoutMs: number;
|
|
527
|
+
readonly cwd?: string;
|
|
528
|
+
/** Aborting it stops the probe as a timeout would (its tree killed, its exit waited for). */
|
|
529
|
+
readonly signal?: AbortSignal;
|
|
530
|
+
}
|
|
531
|
+
/** After a probe is killed: how long its exit is waited for before it is given up on. */
|
|
532
|
+
declare const PROBE_KILL_WAIT_MS = 5000;
|
|
533
|
+
declare function runProbe(command: string, args: readonly string[], options: ProbeOptions): Promise<ProbeResult>;
|
|
534
|
+
|
|
535
|
+
export { AGENT_LOCK_DIR_ENV, ANCHOR_END, ANCHOR_START, type AlwaysOnState, type AnchorAction, type CachedTexts, DAEMON_LOCK_FILE, type DoctorOpts, type FetchIdentityLineOptions, type FetchServedTextsOptions, HEARTBEAT_FILE, HOSTED_MCP_PATH, type HostCopy, HostProfile, type IdentityCommands, type IdentityState, IntegrationClient, Lease, LeaseAttempt, LeaseHolder, LeaseOptions, type LoadTextsOptions, type LoadedTexts, type LockHandle, MANUAL, MANUAL_FILENAME, MANUAL_SKILL_NAME, MANUAL_URL, type McpProbeResult, PROBE_KILL_WAIT_MS, type Plan, type ProbeOptions, type ProbeResult, type RecoverOpts, type RegisterOpts, STANDBY_MARKER_FRESH_MS, type ServiceCommandRunner, type ServiceHostOs, type ServiceOpts, type ServiceRef, TEXTS_CACHE_FILE, type TextsClient, type TextsSource, type TrayClient, type TraySummary, VERSION, acquireAgentLock, acquireLeaderLock, agentLockDir, agentLockPath, agentLockRefusal, alwaysOnHealth, alwaysOnOptedOut, alwaysOnState, alwaysOnWanted, anchorIsCurrentAt, atomicCopyFile, atomicWriteFile, beat, clearAlwaysOnInstalledVersion, clearAlwaysOnOptOut, clearAlwaysOnWanted, clearOfferDeclined, clearStandby, createIdentityCommands, fetchIdentityLine, fetchServedTexts, hasAnchorAt, hostedMcpUrl, identityLineOf, idle, installService, launchdPlist, loadTexts, log, manualFrontMatter, manualPointer, manualVersion, markAlwaysOnInstalledVersion, markAlwaysOnOptOut, markAlwaysOnWanted, markStandby, normalizeHandle, offerDeclined, parseServiceHome, planForTest, probeHostedMcp, readAlwaysOnInstalledVersion, readAnchorHandleAt, readAnchorHandleFrom, readCachedTexts, readJsonFile, readState, recordOfferDeclined, removeAnchorAt, renderAnchorBlock, renderDeclinedBlock, renderUnregisteredBlock, runProbe, serviceDefinitionCurrent, serviceInstalled, serviceLabelFor, serviceStatus, setServiceCommandRunnerForTests, setServiceHostOsForTests, spawnCommand, spawnCommandSync, standbyMarkerPath, standbyWaiting, stripAnchorBlock, systemdQuote, systemdUnit, textsCachePath, traySummary, uninstallService, upsertAnchorBlock, writeAnchor, writeState, xmlEscape };
|