@agentchatme/agent-core 0.6.0 → 0.7.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 +52 -6
- package/dist/{chunk-QUANHUVW.js → chunk-4PCDVXAR.js} +3 -3
- package/dist/{chunk-QUANHUVW.js.map → chunk-4PCDVXAR.js.map} +1 -1
- package/dist/{chunk-AVLI55C5.js → chunk-5KMQ23O6.js} +34 -8
- package/dist/chunk-5KMQ23O6.js.map +1 -0
- package/dist/{chunk-EDB33Z22.js → chunk-AQTRC7G4.js} +220 -49
- package/dist/chunk-AQTRC7G4.js.map +1 -0
- package/dist/daemon-entry.d.ts +55 -5
- package/dist/daemon-entry.js +149 -12
- package/dist/daemon-entry.js.map +1 -1
- package/dist/index.d.ts +45 -5
- package/dist/index.js +77 -3
- package/dist/index.js.map +1 -1
- package/dist/presets.d.ts +145 -2
- package/dist/presets.js +241 -18
- package/dist/presets.js.map +1 -1
- package/dist/{runner-C9kZD3KH.d.ts → runner-BLvFalN4.d.ts} +51 -7
- package/dist/{served-manual-CawJYdzJ.d.ts → served-manual-Bg-y_MEy.d.ts} +105 -2
- package/package.json +2 -2
- package/dist/chunk-AVLI55C5.js.map +0 -1
- package/dist/chunk-EDB33Z22.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 { 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, envKeyConflict } 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` (`resolveRunProfile`: unset is `own`, a value that names no profile is `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, never one of\n * `AGENTCHAT_API_KEY` (default false: an exported key stands in for a home\n * that holds none; it never replaces a key the home holds). The `agentchat`\n * 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 // Said once: the daemon serves the agent its home names, never the exported key's.\n const split = envKeyConflict(home, process.env)\n if (split !== null) log.warn(`${split}; this daemon serves the agent of ${credentialsPath(home)} — unset AGENTCHAT_API_KEY where it runs`)\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 runtime_label: opts.runner.label ?? null,\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 stand in for a home that holds no key (default true; it never replaces one: 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 stands in only for a home with no credentials file,\n // so it has no handle on disk: ask 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 runtime_label: this.options.runner.label ?? null,\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;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cAAc,OAAO,IAAI,YAAY,QAAQ,eAAe,OAAQ,KAAK,iBAAiB,kBAAmB,aAAa,IAAI,SAAS,KAAK,IAAI,SAAS,KAAK,KAAK,IAAI,UAAU,CAAC,GAAG,cAAc;AACvO,aAAS;AACT,UAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,WAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC,KAAK,QAAQ,WAAW,KAAK,IAAI,IAAI,UAAU;AACjF,YAAM,YAAY,KAAK,UAAU,SAAS,KAAK,MAAM;AAAA,IACvD;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"]}
|
|
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, envKeyConflict } 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` (`resolveRunProfile`: unset is `own`, a value that names no profile is `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, never one of\n * `AGENTCHAT_API_KEY` (default false: an exported key stands in for a home\n * that holds none; it never replaces a key the home holds). The `agentchat`\n * listener sets it.\n */\n credentialsFromHomeOnly?: boolean\n /** See `IntegrationOptions.dismissIgnoredInvites` (default true). */\n dismissIgnoredInvites?: boolean\n /** See `IntegrationOptions.conversationRuns` (default true: one run per conversation whenever the served texts allow it). */\n conversationRuns?: 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 // Said once: the daemon serves the agent its home names, never the exported key's.\n const split = envKeyConflict(home, process.env)\n if (split !== null) log.warn(`${split}; this daemon serves the agent of ${credentialsPath(home)} — unset AGENTCHAT_API_KEY where it runs`)\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 runtime_label: opts.runner.label ?? null,\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.conversationRuns !== undefined ? { conversationRuns: opts.conversationRuns } : {}),\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 stand in for a home that holds no key (default true; it never replaces one: 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 stands in only for a home with no credentials file,\n // so it has no handle on disk: ask 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, RunPreflight, RunRunner, RunWake } from './runner.js'\nimport {\n writeIntegrationStatus,\n type IntegrationCouldNotProcess,\n type IntegrationLastRun,\n type IntegrationRunsFailing,\n type IntegrationStatus,\n type SocketState,\n} from './status.js'\nimport { PausedConversations } from './could-not-process.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.\n// With served texts that carry `conversation_run_template` (every\n// current server): CONVERSATION RUNS — one run per conversation that owes\n// a reply, prompted for that one conversation, one at a time, and one\n// run for the pending invites; a live exchange stays in its run (the\n// scoped `agentchat_wait` for that conversation). One conversation's\n// content never sits in front of the model while it answers another, and\n// one the AI cannot process never blocks the rest. From an older server\n// (no template): ONE run for the whole tray with the served wake\n// instruction, as before; a tray that cannot be read starts it anyway.\n// A run records its own verdicts; nothing is recorded on its behalf;\n// * could not process — a conversation's run that failed or timed out\n// while the runtime otherwise works (another conversation's run completed\n// since, or — for a run that failed, not one that timed out — the\n// runner's `checkRuntime`, a minimal model call, passes) is reported; the\n// server answers retry, hidden (the span is shown to this agent as a\n// note), paused (a 24 h mute) or none, and the kit follows it once;\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\n/**\n * A runner's `checkRuntime()` (a minimal model call) past this counts as not\n * ok, and its probe is stopped (killed with its tree). The kit's own bound is\n * the same 60 s.\n */\nexport const RUNTIME_CHECK_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 * Conversation runs (default true): whenever the served texts carry\n * `conversation_run_template`, one run per conversation that owes a reply\n * instead of one run for the whole tray. False keeps one run for the tray:\n * right when a \"run\" does not start the agent on that one conversation (the\n * `agentchat forward` mode hands each run to a receiver that reads the\n * whole tray itself).\n */\n readonly conversationRuns?: boolean\n /** Injectable for tests; `RUNTIME_CHECK_DEADLINE_MS`. */\n readonly runtimeCheckDeadlineMs?: number\n}\n\ntype ProcessingFailureCounts = ReturnType<kit.ReceiveLoop['status']>['processingFailures']\n\n/** The kit's could-not-process counts when it keeps none (a kit from before could not process). */\nconst NO_PROCESSING_FAILURES: ProcessingFailureCounts = {\n reported: 0,\n retry: 0,\n hidden: 0,\n paused: 0,\n none: 0,\n reportErrors: 0,\n reruns: 0,\n rerunsCapped: 0,\n awaitingEvidence: 0,\n runtimeChecksOk: 0,\n runtimeChecksFailed: 0,\n lastRuntimeCheck: null,\n} as ProcessingFailureCounts\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 /** When the last run that got done ended (`last_ok_run_at`). */\n private lastOkRunAt: string | 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 /** The conversations the server paused for this agent, as it answered (kept in the identity home). */\n private readonly paused: PausedConversations\n /** The runner's runtime check in flight: concurrent asks share it. */\n private runtimeCheckInFlight: Promise<RunPreflight> | null = null\n\n constructor(private readonly options: IntegrationOptions) {\n const { cfg, client } = options\n const identity = clientIdentityOf(client)\n this.paused = new PausedConversations(cfg.home, cfg.handle)\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 // One run per conversation whenever the served texts carry the template.\n ...(options.conversationRuns === false ? { conversationRuns: false } : {}),\n // The evidence a could-not-process report needs when no other run has\n // completed since: the runtime's own minimal model call. Without one, a\n // failure waits for another run to complete.\n ...(options.runner.checkRuntime !== undefined ? { checkRuntime: () => this.checkRuntime() } : {}),\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 runtime_label: this.options.runner.label ?? null,\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 failed_runs_in_a_row: this.failingRuns,\n last_ok_run_at: this.lastOkRunAt,\n could_not_process: this.couldNotProcess(status),\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 // ─── a run ──────────────────────────────────────────────────────────────\n\n private async startRun(request: kit.RunRequest): Promise<kit.RunEnd> {\n // What the run is for, as the kit says: one conversation (conversation\n // runs), the pending invites, or the whole tray (texts from an older\n // server). A conversation run without its id is not one the kit makes;\n // it would run as a tray run.\n const conversationId = request.kind === 'conversation' && typeof request.conversationId === 'string' && request.conversationId.length > 0 ? request.conversationId : undefined\n const kind: RunKind = conversationId !== undefined ? 'conversation' : request.kind === 'invite' ? '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 // Ids only, never content: the conversation a run is for, and the run's own.\n const subject = `kind=${kind}${conversationId !== undefined ? ` conv=${conversationId}` : ''} id=${runId}`\n this.runsStarted += 1\n this.writeStatus()\n log.info(\n `run start ${subject} budget=${Math.round(budgetMs / 1000)}s${\n kind === 'conversation' ? '' : ` (tray: ${request.cards ?? '?'} card(s), ${request.invites ?? '?'} invite(s))`\n }`,\n )\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 ...(conversationId !== undefined ? { conversationId } : {}),\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 // Readers from before conversation runs know only `wake` and `invite`.\n kind: kind === 'invite' ? 'invite' : 'wake',\n run_kind: kind,\n conversation_id: conversationId ?? null,\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 this.lastOkRunAt = this.lastRun.ended_at\n log.info(`run ok ${subject} ${Math.round(outcome.durationMs / 1000)}s (output discarded; any send was the agent's own hosted-tool call)`)\n // A conversation that ran is not paused (any more).\n if (conversationId !== undefined) this.paused.clear(conversationId)\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(\n `run ${outcome.state} ${subject}${outcome.detail ? `: ${outcome.detail}` : ''} — ${\n kind !== 'conversation'\n ? 'the cards stay on the tray; the next wake (or the server\\'s re-wake) finds them'\n : outcome.state === 'failed' && outcome.silent === true\n ? 'its card stays on the tray; a silent failure counts as a timeout: it is reported (could not process) only once another conversation\\'s run completes, and the server decides what follows'\n : 'its card stays on the tray; if the runtime otherwise works, the failure is reported (could not process) and the server decides what follows'\n }`,\n )\n }\n this.noteRunHealth(outcome, this.lastRun.ended_at)\n this.writeStatus()\n if (outcome.state === 'ok') return { status: 'completed' }\n if (outcome.state === 'not_started') return { status: 'not_started', ...(outcome.detail !== undefined ? { detail: outcome.detail } : {}) }\n // A run past its budget (killed, or abandoned by the deadline above) is a\n // timed-out failure: a could-not-process report then says `timed_out`.\n // So is a silent failure (`RunOutcome.silent`: it ran, then exited\n // non-zero with nothing on stdout): as ambiguous as a timeout — a crash\n // with no output says nothing about why, and the runtime check could\n // pass. The kit reports either only once another conversation's run\n // completed.\n const timedOut = outcome.state === 'timed_out' || (outcome.state === 'failed' && outcome.silent === true)\n return { status: 'failed', ...(timedOut ? { timedOut: true } : {}), ...(outcome.detail !== undefined ? { detail: outcome.detail } : {}) }\n }\n\n /**\n * The runner's runtime check (a minimal model call, no peer content, no\n * AgentChat tools), bounded by `RUNTIME_CHECK_DEADLINE_MS` and stopped with\n * the integration; concurrent asks share one check. Its output is the\n * runner's to discard: only whether it answered, and a bounded diagnostic,\n * come back.\n */\n private checkRuntime(): Promise<RunPreflight> {\n this.runtimeCheckInFlight ??= this.runRuntimeCheck().finally(() => {\n this.runtimeCheckInFlight = null\n // The kit counts the answer once it has it: the status file follows\n // right after (a check that fails reports nothing, so no event would).\n setTimeout(() => this.writeStatus(), 0).unref?.()\n })\n return this.runtimeCheckInFlight\n }\n\n private async runRuntimeCheck(): Promise<RunPreflight> {\n const check = this.options.runner.checkRuntime\n if (check === undefined) return { ok: false, detail: 'this runtime has no runtime check' }\n if (this.stopping) return { ok: false, detail: 'the integration is stopping' }\n const deadlineMs = this.options.runtimeCheckDeadlineMs ?? RUNTIME_CHECK_DEADLINE_MS\n const controller = new AbortController()\n const onStop = (): void => controller.abort()\n this.recheckAbort.signal.addEventListener('abort', onStop, { once: true })\n const startedAt = Date.now()\n try {\n const answer = await withDeadline(check.call(this.options.runner, { signal: controller.signal }), deadlineMs, () => {\n controller.abort()\n return { ok: false, detail: `the runtime check did not answer within ${Math.round(deadlineMs / 1000)} s (stopped)` }\n }).catch((err: unknown) => ({ ok: false, detail: `the runtime check threw: ${err instanceof Error ? err.message : String(err)}` }))\n const took = `${Math.round((Date.now() - startedAt) / 1000)} s`\n if (answer.ok) log.info(`runtime check ok (${this.options.runner.name}: the model answered, ${took}; output discarded)`)\n else if (!this.stopping) log.warn(`runtime check failed (${this.options.runner.name}, ${took}): ${answer.detail ?? 'no detail'} — a failed run is not reported as this conversation's`)\n return answer.ok ? { ok: true } : { ok: false, ...(answer.detail !== undefined ? { detail: answer.detail } : {}) }\n } finally {\n this.recheckAbort.signal.removeEventListener('abort', onStop)\n }\n }\n\n /** The kit's could-not-process counts and the paused conversations, as the status file keeps them. */\n private couldNotProcess(status: ReturnType<kit.ReceiveLoop['status']>): IntegrationCouldNotProcess {\n // A kit from before could not process has no such block: zero, never a throw (the status write runs at start).\n const f = (status as { processingFailures?: ProcessingFailureCounts }).processingFailures ?? NO_PROCESSING_FAILURES\n return {\n runtime_check: this.options.runner.checkRuntime !== undefined,\n reported: f.reported,\n retry: f.retry,\n hidden: f.hidden,\n paused: f.paused,\n none: f.none,\n report_errors: f.reportErrors,\n reruns: f.reruns,\n reruns_capped: f.rerunsCapped,\n awaiting_evidence: f.awaitingEvidence,\n runtime_checks_ok: f.runtimeChecksOk,\n runtime_checks_failed: f.runtimeChecksFailed,\n last_runtime_check: f.lastRuntimeCheck === null ? null : { at: f.lastRuntimeCheck.at, ok: f.lastRuntimeCheck.ok, detail: f.lastRuntimeCheck.detail?.slice(0, CYCLE_FAILURE_CHARS) ?? null },\n paused_conversations: this.paused.list(),\n }\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, heldByTurns, paced } = event.summary\n if (outcome === 'nothing_owed' && (heldByTurns > 0 || paced > 0)) {\n // Conversation runs: everything owed is running, waiting for its\n // turn, or paced after a run that just looked. Not an empty tray.\n log.info(\n `wake: nothing new to start — ${heldByTurns} conversation(s) already running or waiting${paced > 0 ? `, ${paced} paced after a recent run` : ''} (${cards} card(s), ${invites} invite(s))`,\n )\n } else if (outcome === 'empty' || outcome === 'nothing_owed') {\n this.runsSkippedEmpty += 1\n log.info(`wake: ${outcome === 'empty' ? 'the tray is empty' : 'nothing owed (muted or notices-only cards)'} — 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 } else if (outcome === 'runs_started') {\n const { turnsStarted, turnsQueued } = event.summary\n log.info(\n `wake: ${turnsStarted + turnsQueued} run(s) for ${cards} card(s), ${invites} invite(s) — ${turnsStarted} started, ${turnsQueued} queued (one at a time)${\n heldByTurns > 0 ? `; ${heldByTurns} conversation(s) already running or waiting` : ''\n }${paced > 0 ? `; ${paced} paced` : ''}`,\n )\n }\n this.writeStatus()\n break\n }\n case 'processing_failure':\n this.onProcessingFailure(event)\n break\n case 'error':\n if (!this.stopping) log.warn(`receive loop: ${event.error.message}`)\n break\n default:\n break\n }\n }\n\n /**\n * One could-not-process report and the server's answer: said in the log\n * (ids and counts only), and a `paused` answer kept for `status` until the\n * pause ends; any other answer for that conversation ends what was kept.\n */\n private onProcessingFailure(event: Extract<kit.ReceiveLoopEvent, { type: 'processing_failure' }>): void {\n const what = `conv=${event.conversationId} (${event.source} ${event.outcome}, evidence ${event.evidence === 'runtime_check' ? 'runtime check passed' : 'another run completed'})`\n const result = event.result\n if (result === null) {\n log.warn(`could not process: ${what} — the report failed (${event.error ?? 'no detail'}); nothing more is done for it now: its card stays on the tray and the server re-wakes it`)\n } else {\n // `hidden_message_ids` names at most the newest 200; `hidden_count` counts\n // them all (absent from a server that predates it: the list then is all).\n const hidden = result.hidden_count ?? result.hidden_message_ids.length\n const answered =\n result.action === 'retry'\n ? 'retry (the first failure for these messages)'\n : result.action === 'hidden'\n ? `hidden (${hidden} message(s) are now a note for this agent, still unread)`\n : result.action === 'paused'\n ? `paused until ${result.paused_until ?? '?'}${hidden > 0 ? ` (${hidden} more message(s) hidden)` : ''} — no run starts there until then`\n : 'none (nothing left to act on)'\n const next =\n event.next === 'rerun'\n ? 'it runs again after the others'\n : event.next === 'running'\n ? 'its next run is under way already'\n : event.next === 'rerun_capped'\n ? 'not run again in this cycle (3 re-runs already); the server re-wakes it'\n : 'nothing more for it'\n ;(result.action === 'paused' ? log.warn : log.info)(`could not process: ${what} → server: ${answered}; ${next}`)\n if (result.action === 'paused' && result.paused_until !== null) this.paused.record(event.conversationId, result.paused_until)\n else this.paused.clear(event.conversationId)\n }\n this.writeStatus()\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,KAAK,gBAAgB,MAAM,EAAE,QAAQ,KAAK,WAAW,MAAM,CAAC;AAClE,MAAI,OAAO,MAAM;AACf,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AC9B,WAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC,KAAK,QAAQ,WAAW,KAAK,IAAI,IAAI,UAAU;AACjF,YAAM,YAAY,KAAK,UAAU,SAAS,KAAK,MAAM;AAAA,IACvD;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,13 @@
|
|
|
1
|
-
import { I as IntegrationClient, H as HostProfile, c as Lease, L as LeaseOptions, d as LeaseAttempt, e as LeaseHolder } from './served-manual-
|
|
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
|
|
1
|
+
import { I as IntegrationClient, H as HostProfile, c as Lease, L as LeaseOptions, d as LeaseAttempt, e as LeaseHolder } from './served-manual-Bg-y_MEy.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 INTEGRATION_STATUS_STALE_MS, k as IntegrationCouldNotProcess, l as IntegrationCycle, m as IntegrationLastRun, n as IntegrationPausedConversation, b as IntegrationRunsFailing, o as IntegrationStandby, a as IntegrationStatus, p as IntegrationUnservable, q as LEASE_RENEW_MS, r as LEASE_STALE_MS, s as LEGACY_STATUS_FILE, t as MANUAL_FETCH_TIMEOUT_MS, u as MANUAL_MAX_BYTES, v as MANUAL_MAX_REDIRECTS, w as ManualCheck, x as ManualCheckState, M as ManualFetch, y as ManualSyncResult, z as ManualSyncState, P as PendingRegistration, A as PendingSignup, R as REPEATED_FAILED_CYCLES, B as ResolveIdentityOptions, E as ResolvedIdentity, G as SOCKET_STATES, J as ServedManual, S as SocketState, K as StatusContext, N as SyncManualOptions, T as TextsStatus, V as Verdict, O as acquireLease, Q as anchorLabelOf, U as bootedAt, W as checkManual, X as clearCredentials, Y as clearIntegrationStatus, Z as clearPending, _ as clientHeadersOf, $ as clientIdentityOf, a0 as clientNameOf, a1 as credentialsPath, a2 as describeCouldNotProcessCounts, a3 as describeManualSync, a4 as describePausedConversations, a5 as envApiKey, a6 as envKeyConflict, a7 as failedCyclesInARow, a8 as formatIntegrationStatus, a9 as fromKitResult, aa as holderLive, ab as integrationStatusAge, ac as integrationStatusFresh, ad as integrationStatusPath, ae as integrationStatusStaleFor, af as leaseHolder, ag as parseLease, ah as pendingPath, ai as pidAlive, aj as readCredentials, ak as readIntegrationStatus, al as readManualVersion, am as readPending, an as repeatedFailedRuns, ao as resetLeaseObservations, ap as resolveIdentity, aq as runtimeCheckFailingNow, ar as statePath, as as syncManual, at as writeCredentials, au as writeIntegrationStatus, av as writePending } from './served-manual-Bg-y_MEy.js';
|
|
3
3
|
import { AgentChatClient, Texts, TextsRuntime, integration } from 'agentchatme';
|
|
4
4
|
import { z } from 'zod';
|
|
5
|
-
|
|
5
|
+
import { g as RunRequest } from './runner-BLvFalN4.js';
|
|
6
|
+
export { D as DEFAULT_RUN_BUDGET_MS, k as DEFAULT_RUN_PROFILE, F as FALLBACK_RUN_PROFILE, I as INTEGRATION_ENV, l as INTEGRATION_ENV_LEGACY, m as INTEGRATION_ENV_LEGACY_REMOVAL, O as OWN_RUN_WARNING, 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, b as RunRunner, h as RunWake, i as RunnerFactory, j as RunnerIdentity, R as RunnerSource, r as describeRunProfile, s as integrationDisabled, t as integrationDisabledBy, u as isRunProfile, v as isRunnerFactory, w as ownProfileLine, x as resolveRunBudgetMs, y as resolveRunProfile, z as runProfileWarning, A as workdirExposesHome } from './runner-BLvFalN4.js';
|
|
6
7
|
import { spawn, spawnSync } from 'node:child_process';
|
|
7
8
|
|
|
8
9
|
/** Published package version, kept in lockstep with package.json by tests. */
|
|
9
|
-
declare const VERSION = "0.
|
|
10
|
+
declare const VERSION = "0.7.1";
|
|
10
11
|
|
|
11
12
|
type TrayClient = Pick<AgentChatClient, 'inbox'>;
|
|
12
13
|
interface TraySummary {
|
|
@@ -248,6 +249,45 @@ declare function probeHostedMcp(params: {
|
|
|
248
249
|
fetch?: typeof fetch;
|
|
249
250
|
}): Promise<McpProbeResult>;
|
|
250
251
|
|
|
252
|
+
declare const RUN_CONTEXT_ENV: {
|
|
253
|
+
readonly wakeKind: "AGENTCHAT_WAKE_KIND";
|
|
254
|
+
readonly runId: "AGENTCHAT_RUN_ID";
|
|
255
|
+
readonly conversationId: "AGENTCHAT_CONVERSATION_ID";
|
|
256
|
+
};
|
|
257
|
+
/**
|
|
258
|
+
* A copy of `env` with the run's context set (`RUN_CONTEXT_ENV`). A value the
|
|
259
|
+
* caller's own environment carries is replaced, and removed where the run has
|
|
260
|
+
* none: an inherited `AGENTCHAT_CONVERSATION_ID` would name a conversation the
|
|
261
|
+
* run is not for. Pure.
|
|
262
|
+
*/
|
|
263
|
+
declare function runContextEnv(env: NodeJS.ProcessEnv, request: Pick<RunRequest, 'kind' | 'runId' | 'conversationId'>): NodeJS.ProcessEnv;
|
|
264
|
+
|
|
265
|
+
declare const COULD_NOT_PROCESS_FILE = "could-not-process.json";
|
|
266
|
+
interface PausedConversation {
|
|
267
|
+
readonly conversation_id: string;
|
|
268
|
+
/** When the pause (the server's 24 h mute) ends, as the server answered. */
|
|
269
|
+
readonly paused_until: string;
|
|
270
|
+
/** When the server answered `paused`. */
|
|
271
|
+
readonly at: string;
|
|
272
|
+
}
|
|
273
|
+
declare function couldNotProcessPath(home: string): string;
|
|
274
|
+
/** The paused conversations this machine was told about, for one agent. */
|
|
275
|
+
declare class PausedConversations {
|
|
276
|
+
private readonly home;
|
|
277
|
+
private readonly handle;
|
|
278
|
+
private readonly now;
|
|
279
|
+
private entries;
|
|
280
|
+
constructor(home: string, handle: string, now?: () => number);
|
|
281
|
+
/** The conversations paused now, newest answer first. */
|
|
282
|
+
list(): PausedConversation[];
|
|
283
|
+
/** The server answered `paused` for this conversation, until `pausedUntil`. */
|
|
284
|
+
record(conversationId: string, pausedUntil: string): void;
|
|
285
|
+
/** The conversation is not paused (any other answer for it, or a run for it completed). */
|
|
286
|
+
clear(conversationId: string): void;
|
|
287
|
+
/** Best effort: the ledger is diagnostics, never a dependency of waking. */
|
|
288
|
+
private persist;
|
|
289
|
+
}
|
|
290
|
+
|
|
251
291
|
interface RegisterOpts {
|
|
252
292
|
email?: string;
|
|
253
293
|
handle?: string;
|
|
@@ -532,4 +572,4 @@ interface ProbeOptions {
|
|
|
532
572
|
declare const PROBE_KILL_WAIT_MS = 5000;
|
|
533
573
|
declare function runProbe(command: string, args: readonly string[], options: ProbeOptions): Promise<ProbeResult>;
|
|
534
574
|
|
|
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 };
|
|
575
|
+
export { AGENT_LOCK_DIR_ENV, ANCHOR_END, ANCHOR_START, type AlwaysOnState, type AnchorAction, COULD_NOT_PROCESS_FILE, 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 PausedConversation, PausedConversations, type Plan, type ProbeOptions, type ProbeResult, RUN_CONTEXT_ENV, type RecoverOpts, type RegisterOpts, RunRequest, 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, couldNotProcessPath, 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, runContextEnv, runProbe, serviceDefinitionCurrent, serviceInstalled, serviceLabelFor, serviceStatus, setServiceCommandRunnerForTests, setServiceHostOsForTests, spawnCommand, spawnCommandSync, standbyMarkerPath, standbyWaiting, stripAnchorBlock, systemdQuote, systemdUnit, textsCachePath, traySummary, uninstallService, upsertAnchorBlock, writeAnchor, writeState, xmlEscape };
|