@agentchatme/agent-core 0.4.0 → 0.4.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.
@@ -2,7 +2,7 @@ import {
2
2
  log,
3
3
  spawnCommand,
4
4
  spawnCommandSync
5
- } from "./chunk-NCSF3CCV.js";
5
+ } from "./chunk-QDM4EFI7.js";
6
6
 
7
7
  // src/integration/spawn-run.ts
8
8
  var DEFAULT_GRACE_MS = 5e3;
@@ -280,4 +280,4 @@ export {
280
280
  describeWindowsSweep,
281
281
  spawnRun
282
282
  };
283
- //# sourceMappingURL=chunk-TH6XOVA3.js.map
283
+ //# sourceMappingURL=chunk-AE4XHKHQ.js.map
@@ -23,7 +23,7 @@ import { randomBytes } from "crypto";
23
23
  import * as fs from "fs";
24
24
  import * as path from "path";
25
25
  function tmpPathFor(file) {
26
- return path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
26
+ return path.join(path.dirname(file), `.${path.basename(file)}.${randomBytes(6).toString("hex")}.tmp`);
27
27
  }
28
28
  var RENAME_RETRY_CODES = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
29
29
  var RENAME_ATTEMPTS = 6;
@@ -136,4 +136,4 @@ export {
136
136
  spawnCommand,
137
137
  spawnCommandSync
138
138
  };
139
- //# sourceMappingURL=chunk-NCSF3CCV.js.map
139
+ //# sourceMappingURL=chunk-QDM4EFI7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client-identity.ts","../src/util/fsutil.ts","../src/util/log.ts","../src/util/spawn.ts"],"sourcesContent":["import type { AgentChatClientIdentity, AgentChatClientKind, TextsRuntime } from 'agentchatme'\n\n// ─── Who is calling ─────────────────────────────────────────────────────────\n//\n// An integration names itself to the server once: the runtime it serves, as\n// the server's texts endpoint spells it (`claude-code`, `codex`, …), and its\n// own package version. That one value drives two things — the served texts\n// (`GET /v1/texts?runtime=`) and the client identity on every request and on\n// the socket's hello — so the server's analytics tell the runtimes apart\n// instead of lumping them under one bucket. Nothing in this package branches\n// on it: it is a label the integration passes through, never a switch.\n\nexport interface IntegrationClient {\n readonly runtime: TextsRuntime\n readonly version: string\n /**\n * The client name sent to the server when it is not the runtime itself —\n * a front door that serves several runtimes (the `agentchat` listener)\n * names itself here, and `runtime` stays what the texts are rendered for.\n */\n readonly name?: string\n}\n\n/** The name this client identifies as: its own `name`, else its runtime. */\nexport function clientNameOf(client: IntegrationClient): string {\n return client.name ?? client.runtime\n}\n\n/**\n * The SDK's client identity for this integration. The SDK types client names\n * as a closed union and the server normalises whatever arrives, so the\n * runtime name is passed through as-is; the union widens on the SDK side.\n */\nexport function clientIdentityOf(client: IntegrationClient): AgentChatClientIdentity {\n return { name: clientNameOf(client) as unknown as AgentChatClientKind, version: client.version }\n}\n\n/** The same identity as headers, for the one raw request this package still makes (the MCP probe). */\nexport function clientHeadersOf(client: IntegrationClient): Record<string, string> {\n return {\n 'X-AgentChat-Client': clientNameOf(client),\n 'X-AgentChat-Client-Version': client.version,\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\n// ─── Atomic replacement ─────────────────────────────────────────────────────\n//\n// The synchronous twin of the SDK kit's `writeAtomic` / `renameWithRetry`\n// (`integration` in `agentchatme`, which was ported from this file). The kit\n// has only the async form, and every caller here is synchronous by design:\n// the service installers write their unit between `spawnSync` calls, the\n// credential and state writes sit in flows that must finish in order, the\n// status file is written from the receive loop's synchronous event handlers,\n// and a preset's `runner()` writes its MCP config before it returns. The two\n// copies behave the same — the same temp name shape, `wx`, mode on the\n// descriptor, fsync, rename, the same Windows retry — and\n// tests/fsutil-kit-parity.test.ts runs both through the same cases. The day\n// the kit exports a synchronous form, that test fails and says to delete this\n// copy and switch to the kit.\n//\n// Tmp file + rename in the same directory: a reader sees the old file or the\n// new one, never part of one, and a crash leaves the old file or a stray tmp —\n// never a truncated JSON that would make every later invocation throw. A\n// failed write removes its tmp file and leaves the old file exactly as it was.\n//\n// The tmp file is never a path someone else can prepare: its name carries a\n// random suffix, it is created exclusively (`wx`: O_CREAT|O_EXCL, which\n// refuses an existing name — a planted symlink included — instead of following\n// it), its mode is set on the open descriptor rather than on a path, and its\n// contents are flushed before the rename. On Windows a rename onto a file\n// another process has open fails transiently (EPERM / EBUSY / EACCES while a\n// scanner or an editor holds it), so the rename is retried for ~100 ms.\n\n/** A fresh, unguessable tmp name beside `file` (the kit's shape: `.<name>.<12 hex>.tmp`). */\nfunction tmpPathFor(file: string): string {\n return path.join(path.dirname(file), `.${path.basename(file)}.${randomBytes(6).toString('hex')}.tmp`)\n}\n\nconst RENAME_RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES'])\nconst RENAME_ATTEMPTS = 6\nconst RENAME_DELAY_MS = 20\n\nfunction sleepSync(ms: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)\n}\n\nexport interface RenameRetryOptions {\n /** Defaults to `fs.renameSync`; injectable for tests. */\n readonly rename?: (from: string, to: string) => void\n /** Defaults to Windows only, where the transient sharing errors happen. */\n readonly retry?: boolean\n readonly attempts?: number\n readonly delayMs?: number\n}\n\n/** `renameSync`, retried a few times over ~100 ms on a transient EPERM / EBUSY / EACCES (Windows). */\nexport function renameWithRetry(from: string, to: string, options: RenameRetryOptions = {}): void {\n const rename = options.rename ?? ((a: string, b: string) => fs.renameSync(a, b))\n const retry = options.retry ?? process.platform === 'win32'\n const attempts = retry ? (options.attempts ?? RENAME_ATTEMPTS) : 1\n for (let attempt = 1; ; attempt++) {\n try {\n rename(from, to)\n return\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (attempt >= attempts || code === undefined || !RENAME_RETRY_CODES.has(code)) throw err\n sleepSync(options.delayMs ?? RENAME_DELAY_MS)\n }\n }\n}\n\nfunction removeQuietly(file: string): void {\n try {\n fs.rmSync(file, { force: true })\n } catch {\n /* preserve the original error */\n }\n}\n\n/** `mode` is set exactly (whatever the umask); without one the file gets the umask's default, as `writeFileSync` would. */\nexport function atomicWriteFile(filePath: string, data: string | Uint8Array, mode?: number): void {\n const dir = path.dirname(filePath)\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 })\n const tmp = tmpPathFor(filePath)\n try {\n const fd = fs.openSync(tmp, 'wx', mode ?? 0o666)\n try {\n if (mode !== undefined) fs.fchmodSync(fd, mode)\n fs.writeFileSync(fd, data)\n fs.fsyncSync(fd)\n } finally {\n fs.closeSync(fd)\n }\n renameWithRetry(tmp, filePath)\n } catch (err) {\n removeQuietly(tmp)\n throw err\n }\n}\n\n/** Crash-safe file replacement for shipped executable bundles. */\nexport function atomicCopyFile(source: string, destination: string, mode = 0o755): void {\n const dir = path.dirname(destination)\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 })\n const tmp = tmpPathFor(destination)\n try {\n fs.copyFileSync(source, tmp, fs.constants.COPYFILE_EXCL)\n // Read-write, not read-only: Windows flushes a file to disk only through\n // a handle with write access (FlushFileBuffers), so fsync on a read-only\n // descriptor fails there with EPERM. 0.3.0 opened it read-only and every\n // Windows daemon install failed at this line.\n const fd = fs.openSync(tmp, fs.constants.O_RDWR | (fs.constants.O_NOFOLLOW ?? 0))\n try {\n fs.fchmodSync(fd, mode)\n fs.fsyncSync(fd)\n } finally {\n fs.closeSync(fd)\n }\n renameWithRetry(tmp, destination)\n } catch (err) {\n removeQuietly(tmp)\n throw err\n }\n}\n\nexport function readJsonFile<T>(filePath: string): T | null {\n try {\n const raw = fs.readFileSync(filePath, 'utf-8')\n return JSON.parse(raw) as T\n } catch {\n return null\n }\n}\n","// ─── stderr-only diagnostics ────────────────────────────────────────────────\n//\n// stdout belongs to the hook protocol (platforms parse it as JSON) and to\n// command output the agent reads. Every diagnostic goes to stderr, gated by\n// AGENTCHAT_LOG_LEVEL. There is deliberately no logging dependency here —\n// hooks run on every session start and must add zero startup weight.\n\nconst LEVELS = ['silent', 'error', 'warn', 'info', 'debug'] as const\nexport type LogLevel = (typeof LEVELS)[number]\n\nfunction activeLevel(): number {\n const raw = (process.env['AGENTCHAT_LOG_LEVEL'] ?? 'warn').toLowerCase()\n const idx = LEVELS.indexOf(raw as LogLevel)\n return idx === -1 ? LEVELS.indexOf('warn') : idx\n}\n\nfunction emit(level: LogLevel, msg: string): void {\n if (LEVELS.indexOf(level) <= activeLevel() && level !== 'silent') {\n process.stderr.write(`[agentchat:${level}] ${msg}\\n`)\n }\n}\n\nexport const log = {\n error: (msg: string) => emit('error', msg),\n warn: (msg: string) => emit('warn', msg),\n info: (msg: string) => emit('info', msg),\n debug: (msg: string) => emit('debug', msg),\n}\n","import crossSpawn from 'cross-spawn'\nimport type {\n spawn as nodeSpawn,\n spawnSync as nodeSpawnSync,\n} from 'node:child_process'\n\n// Node's child_process does not resolve npm's `.cmd` shims on Windows the way\n// a terminal does. Coding-agent and npx executables are commonly installed\n// through exactly those shims, so a direct spawn can report ENOENT even though\n// the user's command works. cross-spawn performs PATHEXT/shebang resolution\n// without putting paths or arguments through a shell.\nexport const spawnCommand = crossSpawn as typeof nodeSpawn\nexport const spawnCommandSync = crossSpawn.sync as typeof nodeSpawnSync\n"],"mappings":";;;;;;;AAwBO,SAAS,aAAa,QAAmC;AAC9D,SAAO,OAAO,QAAQ,OAAO;AAC/B;AAOO,SAAS,iBAAiB,QAAoD;AACnF,SAAO,EAAE,MAAM,aAAa,MAAM,GAAqC,SAAS,OAAO,QAAQ;AACjG;AAGO,SAAS,gBAAgB,QAAmD;AACjF,SAAO;AAAA,IACL,sBAAsB,aAAa,MAAM;AAAA,IACzC,8BAA8B,OAAO;AAAA,EACvC;AACF;;;AC3CA,SAAS,mBAAmB;AAC5B,YAAY,QAAQ;AACpB,YAAY,UAAU;AA+BtB,SAAS,WAAW,MAAsB;AACxC,SAAY,UAAU,aAAQ,IAAI,GAAG,IAAS,cAAS,IAAI,CAAC,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,MAAM;AACtG;AAEA,IAAM,qBA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GAAG;AAAA,EACvC,MAAM,CAAC,QAAgB,KAAK,QAAQ,GAAG;AAAA,EACvC,OAAO,CAAC,QAAgB,KAAK,SAAS,GAAG;AAC3C;;;AC3BA,OAAO,gBAAgB;AAWhB,IAAM,eAAe;AACrB,IAAM,mBAAmB,WAAW;","names":[]}
@@ -1,6 +1,9 @@
1
1
  import {
2
2
  clientIdentityOf
3
- } from "./chunk-NCSF3CCV.js";
3
+ } from "./chunk-QDM4EFI7.js";
4
+
5
+ // src/version.ts
6
+ var VERSION = "0.4.1";
4
7
 
5
8
  // src/integration/mcp-probe.ts
6
9
  import { integration as kit } from "agentchatme";
@@ -19,8 +22,9 @@ async function probeHostedMcp(params) {
19
22
  }
20
23
 
21
24
  export {
25
+ VERSION,
22
26
  HOSTED_MCP_PATH,
23
27
  hostedMcpUrl,
24
28
  probeHostedMcp
25
29
  };
26
- //# sourceMappingURL=chunk-HOY2FERJ.js.map
30
+ //# sourceMappingURL=chunk-XDWBTX5J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/version.ts","../src/integration/mcp-probe.ts"],"sourcesContent":["/** Published package version, kept in lockstep with package.json by tests. */\nexport const VERSION = '0.4.1'\n","import { integration as kit } from 'agentchatme'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\n\n// ─── Can this key reach the hosted tools? ───────────────────────────────────\n//\n// `status` and `doctor` ask the SDK kit's `probeHostedTools`: one MCP\n// `initialize` over Streamable HTTP with the bearer key — the same first\n// request a runtime makes on connect — then `tools/list`, which must show the\n// tools a run needs (`agentchat_inbox`, `agentchat_decide`). A 401 means the\n// key does not authenticate; a transport error means the endpoint is not\n// reachable from here. No tool is called.\n\nexport const HOSTED_MCP_PATH = kit.HOSTED_MCP_PATH\n\nexport function hostedMcpUrl(apiBase: string): string {\n return kit.hostedMcpUrl(apiBase)\n}\n\nexport interface McpProbeResult {\n readonly ok: boolean\n readonly status?: number\n readonly serverName?: string\n readonly serverVersion?: string\n readonly protocolVersion?: string\n /** Every tool the server listed for this key. */\n readonly tools?: readonly string[]\n /** Tools a run needs that were not listed. */\n readonly missing?: readonly string[]\n readonly error?: string\n}\n\nexport async function probeHostedMcp(params: {\n apiKey: string\n apiBase: string\n /** How this integration identifies to the server. */\n client: IntegrationClient\n /**\n * Accepted for compatibility and ignored: the probe identifies as `client`\n * (headers and `clientInfo` alike), so the server's analytics see the\n * integration, never a free-text name it would file as unknown.\n */\n clientName?: string\n /** Accepted for compatibility and ignored (see `clientName`). */\n clientVersion?: string\n timeoutMs?: number\n fetch?: typeof fetch\n}): Promise<McpProbeResult> {\n return kit.probeHostedTools({\n apiBase: params.apiBase,\n apiKey: params.apiKey,\n clientIdentity: clientIdentityOf(params.client),\n ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),\n ...(params.fetch !== undefined ? { fetch: params.fetch } : {}),\n })\n}\n"],"mappings":";;;;;AACO,IAAM,UAAU;;;ACDvB,SAAS,eAAe,WAAW;AAY5B,IAAM,kBAAkB,IAAI;AAE5B,SAAS,aAAa,SAAyB;AACpD,SAAO,IAAI,aAAa,OAAO;AACjC;AAeA,eAAsB,eAAe,QAeT;AAC1B,SAAO,IAAI,iBAAiB;AAAA,IAC1B,SAAS,OAAO;AAAA,IAChB,QAAQ,OAAO;AAAA,IACf,gBAAgB,iBAAiB,OAAO,MAAM;AAAA,IAC9C,GAAI,OAAO,cAAc,SAAY,EAAE,WAAW,OAAO,UAAU,IAAI,CAAC;AAAA,IACxE,GAAI,OAAO,UAAU,SAAY,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;AAAA,EAC9D,CAAC;AACH;","names":[]}
@@ -1,6 +1,6 @@
1
- import { I as IntegrationClient, M as ManualFetch, a as IntegrationStatus, S as SocketState } from './served-manual-DZmEak4_.js';
2
- import { R as RunnerSource, a as RunProfile, b as RunRunner, c as RunOutcome } from './runner-BzgsiS3V.js';
3
- export { d as RunKind, e as RunOutcomeState, f as RunPreflight, g as RunRequest, h as RunWake, i as RunnerFactory, j as RunnerIdentity } from './runner-BzgsiS3V.js';
1
+ import { I as IntegrationClient, M as ManualFetch, a as IntegrationStatus, S as SocketState } from './served-manual-99vEOjJS.js';
2
+ import { R as RunnerSource, a as RunProfile, b as RunRunner, c as RunOutcome } from './runner-B-ZZDAAm.js';
3
+ export { d as RunKind, e as RunOutcomeState, f as RunPreflight, g as RunRequest, h as RunWake, i as RunnerFactory, j as RunnerIdentity } from './runner-B-ZZDAAm.js';
4
4
  import { AgentChatClient, RealtimeClient, BlockedInfo, RealtimeState } from 'agentchatme';
5
5
  import 'zod';
6
6
 
@@ -1,4 +1,7 @@
1
1
  import {
2
+ INTEGRATION_ENV,
3
+ INTEGRATION_ENV_LEGACY,
4
+ INTEGRATION_ENV_LEGACY_REMOVAL,
2
5
  MANUAL,
3
6
  acquireLeaderLock,
4
7
  beat,
@@ -12,18 +15,18 @@ import {
12
15
  resolveRunProfile,
13
16
  textsCachePath,
14
17
  writeIntegrationStatus
15
- } from "./chunk-W3LYBKIV.js";
18
+ } from "./chunk-7LAAAXUO.js";
16
19
  import {
17
20
  WINDOWS_SWEEP_TIMEOUT_MS,
18
21
  describeWindowsSweep,
19
22
  redactDiagnostic,
20
23
  spawnRun,
21
24
  sweepWindowsDescendants
22
- } from "./chunk-TH6XOVA3.js";
25
+ } from "./chunk-AE4XHKHQ.js";
23
26
  import {
24
27
  clientIdentityOf,
25
28
  log
26
- } from "./chunk-NCSF3CCV.js";
29
+ } from "./chunk-QDM4EFI7.js";
27
30
 
28
31
  // src/integration/run.ts
29
32
  import * as path2 from "path";
@@ -571,6 +574,9 @@ async function runIntegration(opts) {
571
574
  log.info(`integration resident for ${home} (${credentialsPath(home)}) \u2014 ${opts.client.runtime} ${opts.client.version}`);
572
575
  if (disabled) {
573
576
  log.info(`${disabledBy}=off \u2014 holding no socket and starting no run; the hosted tools and the manual still work in every session`);
577
+ if (disabledBy === INTEGRATION_ENV_LEGACY) {
578
+ 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`);
579
+ }
574
580
  }
575
581
  idle(home);
576
582
  offStatus(null);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/integration/run.ts","../src/daemon/config.ts","../src/integration/integration.ts","../src/integration/socket-state.ts"],"sourcesContent":["import * as path from 'node:path'\nimport * as fs from 'node:fs'\nimport { log } from '../util/log.js'\nimport { acquireLeaderLock } from '../daemon/leader-lock.js'\nimport { resolveIdentity, credentialsPath } from '../identity/credentials.js'\nimport { resolveDaemonConfig } from '../daemon/config.js'\nimport { idle } from '../daemon/health.js'\nimport type { IntegrationClient } from '../client-identity.js'\nimport { Integration } from './integration.js'\nimport { integrationDisabledBy, resolveRunBudgetMs, resolveRunProfile, type RunProfile } from './profile.js'\nimport { isRunnerFactory, type RunnerSource } from './runner.js'\nimport { writeIntegrationStatus } from './status.js'\n\n// ─── The resident supervisor ────────────────────────────────────────────────\n//\n// This process is RESIDENT. It is registered as a service when the integration\n// is installed, and from then on it simply exists — whether or not anyone has\n// signed in. Installation and authentication are different lifecycles (the\n// shape every comparable daemon uses: tailscaled runs before `tailscale up`,\n// and logging out idles it rather than uninstalling it).\n//\n// no credentials → idle. No socket, no retries, no CPU. Just watch.\n// credentials → connect and wake.\n// credentials change → follow them.\n// AGENTCHAT_INTEGRATION=off → stay resident, hold nothing, wake nothing.\n//\n// A refused key is not this loop's case: the SDK's client stays up in\n// `blocked` and tries a fresh hello every 10–15 minutes (`status` reads\n// `socket blocked` meanwhile), so a rotated-back key or a reinstated account\n// reconnects on its own, and a different key is simply a credential change.\n//\n// The only thing that removes this process is an explicit `daemon disable`.\n//\n// SIGTERM/SIGINT (launchd/systemd stop, Ctrl-C) interrupts a run in flight:\n// the integration SIGTERMs the run's process group and this process waits up\n// to SHUTDOWN_GRACE_MS for it before exiting. A daemon that exited at once\n// left the detached run orphaned, and the restarted daemon's connect found\n// the same tray and started a second run beside it.\n\n/** How often to re-read the identity. A `stat`; the watcher usually beats it. */\nconst POLL_MS = 5_000\n/** How often the watcher flag is consulted while waiting out a poll. */\nconst TICK_MS = 250\n/** Ceiling for retry backoff when the runtime simply is not usable yet. */\nconst MAX_BACKOFF_MS = 5 * 60_000\n/**\n * How long a shutdown waits for an interrupted run to end before the process\n * exits. The runner SIGTERMs the run's process group at once and SIGKILLs 5 s\n * later, so this is normally over in well under a second. Below launchd's\n * `ExitTimeOut` (15 s in the plist this package writes).\n */\nconst SHUTDOWN_GRACE_MS = 10_000\nconst MAX_LOG_BYTES = 5 * 1024 * 1024\nconst KEEP_LOG_BYTES = 1024 * 1024\n\nexport interface RunIntegrationOpts {\n /** THE identity home for the agent this daemon serves. */\n home: string\n /** How to start one headless run: a runner, or a factory that builds one per identity (`RunnerFactory`). */\n runner: RunnerSource\n /** How this integration names itself to the server: the texts runtime and its own version. */\n client: IntegrationClient\n /** The one pointer line a run prompt ends with: how THIS runtime reaches its copy of the manual (`manualPointer(...)`). */\n manualPointer: string\n /**\n * The skill file that follows the served manual (`<skills dir>/agentchat/SKILL.md`):\n * whenever the texts in hand announce a version the file does not carry, the\n * announced manual is downloaded, checked and written over it. Absent, the\n * daemon leaves the manual to the CLI's install and `doctor --fix`.\n */\n manualPath?: string\n /** Scratch dir for runs. The integration decides where; this package never derives one. */\n workdir: string\n /** Defaults to `AGENTCHAT_RUN_PROFILE`, then `answer`. */\n profile?: RunProfile\n /** Defaults to `AGENTCHAT_RUN_BUDGET_MS`, then 10 minutes. */\n budgetMs?: number\n /** Ends the loop (tests). Production runs until SIGTERM/SIGINT. */\n signal?: AbortSignal\n env?: NodeJS.ProcessEnv\n /** Test seam: what a signal-initiated shutdown calls last. Defaults to `process.exit`. */\n exit?: (code: number) => void\n /**\n * Serve only the agent the home's `credentials` hold: `AGENTCHAT_API_KEY`\n * in the environment is ignored (default false: it overrides, as for every\n * integration). The `agentchat` listener sets it.\n */\n credentialsFromHomeOnly?: boolean\n /** See `IntegrationOptions.dismissIgnoredInvites` (default true). */\n dismissIgnoredInvites?: boolean\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))\n\n/**\n * Identity fingerprint: changes when the user signs out, signs in, or swaps to\n * a different agent. Comparing it is how the supervisor notices without caring\n * why.\n */\nfunction fingerprint(home: string, envKey: boolean): string | null {\n const id = resolveIdentity(home, { envKey })\n return id === null ? null : `${id.apiKey}:${id.handle ?? ''}`\n}\n\n/** Bound launchd's append-only file without losing the most recent diagnosis. */\nfunction boundDaemonLog(home: string): void {\n const file = path.join(home, 'daemon.log')\n try {\n const size = fs.statSync(file).size\n if (size <= MAX_LOG_BYTES) return\n const fd = fs.openSync(file, 'r')\n try {\n const keep = Buffer.alloc(Math.min(KEEP_LOG_BYTES, size))\n fs.readSync(fd, keep, 0, keep.length, size - keep.length)\n fs.writeFileSync(\n file,\n `[agentchat:info] older daemon log output truncated at ${new Date().toISOString()}\\n${keep.toString('utf-8')}`,\n )\n } finally {\n fs.closeSync(fd)\n }\n } catch {\n /* absent/unreadable log is not a runtime failure */\n }\n}\n\n/**\n * Run the integration daemon. Returns only on a condition that makes running\n * pointless — another daemon already holding this home's lock — or when\n * `signal` aborts (tests).\n */\nexport async function runIntegration(opts: RunIntegrationOpts): Promise<number> {\n const home = path.resolve(opts.home)\n const workdir = path.resolve(opts.workdir)\n const env = opts.env ?? process.env\n const profile = opts.profile ?? resolveRunProfile(env)\n const budgetMs = opts.budgetMs ?? resolveRunBudgetMs(env)\n boundDaemonLog(home)\n\n // A resident service's output goes to a log file nobody sees until something\n // is wrong, and an empty log is useless for \"is the integration working?\".\n if (process.env['AGENTCHAT_LOG_LEVEL'] === undefined) process.env['AGENTCHAT_LOG_LEVEL'] = 'info'\n\n // Taken for the PROCESS, not for a connection: one resident daemon per\n // identity home, signed in or not.\n const lock = acquireLeaderLock(home)\n if (lock === null) return 1\n\n const envKey = opts.credentialsFromHomeOnly !== true\n const identityOf = () => resolveIdentity(home, { envKey })\n const disabledBy = integrationDisabledBy(env)\n const disabled = disabledBy !== null\n let live: Integration | null = null\n let liveFingerprint: string | null = null\n let observedFingerprint: string | null = null\n /** Consecutive start failures, for backoff. Reset on success or on a new credential. */\n let failures = 0\n let lastFailure: string | null = null\n let shuttingDown = false\n\n const offStatus = (handle: string | null): void =>\n writeIntegrationStatus(home, {\n version: 2,\n updated_at: new Date().toISOString(),\n pid: process.pid,\n runtime: opts.runner.name,\n handle,\n profile,\n socket: disabled ? 'off' : 'idle',\n wakes: 0,\n wakes_absorbed: 0,\n invites: 0,\n runs_started: 0,\n runs_ok: 0,\n runs_failed: 0,\n runs_timed_out: 0,\n runs_not_started: 0,\n runs_skipped_empty: 0,\n last_run: null,\n retry_rung: 0,\n retry_due_at: null,\n last_error: lastFailure,\n texts: null,\n })\n\n const disconnect = (why: string): void => {\n if (live === null) return\n log.info(`${why} — disconnecting (a run in flight is interrupted), staying resident`)\n live.stop()\n live = null\n liveFingerprint = null\n idle(home)\n }\n\n // The loop notices `shuttingDown` within a tick and takes the one exit path\n // below: stop the integration, give an interrupted run its grace, release, exit.\n const shutdown = (sig: string): void => {\n if (shuttingDown) return\n shuttingDown = true\n log.info(`${sig} — shutting down`)\n }\n const onSigint = (): void => shutdown('SIGINT')\n const onSigterm = (): void => shutdown('SIGTERM')\n process.on('SIGINT', onSigint)\n process.on('SIGTERM', onSigterm)\n\n // Best-effort accelerator so signing in connects in about a second instead of\n // waiting out a poll. fs.watch is unreliable on some filesystems, so the poll\n // below is the real guarantee and this is pure upside.\n let nudged = false\n try {\n fs.mkdirSync(home, { recursive: true })\n const watcher = fs.watch(home, (_event, filename) => {\n if (filename === null || String(filename).startsWith('credentials')) nudged = true\n })\n watcher.on('error', (err) => {\n log.warn(`credential watcher unavailable; polling instead: ${String(err)}`)\n try {\n watcher.close()\n } catch {\n /* already closed */\n }\n })\n watcher.unref()\n } catch {\n /* polling covers it */\n }\n\n log.info(`integration resident for ${home} (${credentialsPath(home)}) — ${opts.client.runtime} ${opts.client.version}`)\n if (disabled) {\n log.info(`${disabledBy}=off — holding no socket and starting no run; the hosted tools and the manual still work in every session`)\n }\n idle(home)\n offStatus(null)\n\n for (;;) {\n if (shuttingDown || opts.signal?.aborted) break\n const fp = fingerprint(home, envKey)\n const identityChanged = fp !== observedFingerprint\n if (identityChanged) {\n disconnect(fp === null ? 'signed out' : 'identity changed')\n observedFingerprint = fp\n failures = 0\n lastFailure = null\n if (fp === null || disabled) offStatus(fp === null ? null : identityOf()?.handle ?? null)\n }\n\n if (fp === null) {\n // Signed out, or never signed in. Idle.\n } else if (disabled) {\n // Signed in, switched off. Resident, silent.\n } else if (fp !== liveFingerprint) {\n try {\n const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client, envKey })\n const runner = isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner\n const candidate = new Integration({\n cfg,\n runner,\n client: opts.client,\n manualPointer: opts.manualPointer,\n ...(opts.manualPath !== undefined ? { manualPath: opts.manualPath } : {}),\n profile,\n budgetMs,\n ...(opts.dismissIgnoredInvites !== undefined ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {}),\n })\n await candidate.start()\n live = candidate\n liveFingerprint = fp\n failures = 0\n lastFailure = null\n } catch (err) {\n // Runtime not ready (host CLI missing or not signed in), network\n // down, whatever. Stay resident and try again later — exiting would\n // just make the service manager restart us in a loop. Backed off and\n // de-duplicated so a condition that lasts days does not fill the log.\n const msg = String(err instanceof Error ? err.message : err)\n if (msg !== lastFailure) {\n log.warn(`not connecting yet: ${msg}`)\n lastFailure = msg\n offStatus(identityOf()?.handle ?? null)\n }\n failures += 1\n live = null\n liveFingerprint = null\n idle(home)\n }\n }\n\n // Wait out the poll interval, but wake as soon as the watcher fires so a\n // sign-in connects in well under a second. Exponential backoff while a\n // start keeps failing, capped — the watcher still wakes us instantly when\n // credentials change, so backing off never delays a real sign-in.\n const waitMs = failures === 0 ? POLL_MS : Math.min(POLL_MS * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS)\n nudged = false\n const deadline = Date.now() + waitMs\n while (!nudged && !shuttingDown && !opts.signal?.aborted && Date.now() < deadline) {\n await sleep(TICK_MS)\n }\n }\n\n process.off('SIGINT', onSigint)\n process.off('SIGTERM', onSigterm)\n if (live !== null) {\n const ended = await live.stopAndWait(SHUTDOWN_GRACE_MS)\n if (!ended) log.warn(`a run in flight did not end within ${Math.round(SHUTDOWN_GRACE_MS / 1000)}s of being interrupted — exiting anyway`)\n live = null\n }\n idle(home)\n lock.release()\n if (shuttingDown) {\n log.info('shutdown complete')\n ;(opts.exit ?? process.exit)(0)\n }\n return 0\n}\n","import * as path from 'node:path'\nimport { AgentChatClient } from 'agentchatme'\nimport { resolveIdentity } from '../identity/credentials.js'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\n\n// ─── Daemon identity resolution ─────────────────────────────────────────────\n//\n// The daemon runs AS one host agent — the same identity that agent's sessions\n// use through the hosted tools, never a separate account. It reads that\n// credential from the home it is GIVEN.\n//\n// The predecessor of this file mapped a `runtime` enum to a home\n// (`codex → ~/.codex/agentchat`, `claude-code → ~/.claude/agentchat`). That\n// mapping is exactly the \"a function that decides can decide wrong\" defect this\n// package exists to make unrepresentable, so it is gone: the caller passes its\n// own home and there is no enum to mis-set.\n\nexport interface DaemonConfig {\n apiKey: string\n handle: string\n apiBase: string\n /** `wss://api.agentchat.me` — the SDK's socket base; it appends `/v1/ws`. */\n wsBase: string\n /** The identity home. Credentials, leader lock, and heartbeat all live here. */\n home: string\n /** Scratch dir for runs (the headless run's cwd). */\n workdir: string\n}\n\n/** `https://api.agentchat.me` → `wss://api.agentchat.me`. */\nexport function wsBaseFor(apiBase: string): string {\n return apiBase.replace(/^http/, 'ws').replace(/\\/+$/, '')\n}\n\n/** `https://api.agentchat.me` → `wss://api.agentchat.me/v1/ws`, for logs and checks. */\nexport function wsUrlFor(apiBase: string): string {\n return `${wsBaseFor(apiBase)}/v1/ws`\n}\n\nexport interface ResolveDaemonOpts {\n /** THE identity home. Required — this module never derives one. */\n home: string\n /** The run workdir. Required — this module never derives one either. */\n workdir: string\n /** How to identify to the server when the handle has to be asked for. */\n client: IntegrationClient\n /** Whether `AGENTCHAT_API_KEY` may override the home's credentials (default true; see `resolveIdentity`). */\n envKey?: boolean\n}\n\n/**\n * Resolve the identity the daemon runs as.\n *\n * Async because the handle is load-bearing at runtime — it filters this agent's\n * own outbound echoed back by server fan-out. An env-only identity\n * (`AGENTCHAT_API_KEY`, no credentials file) has no handle on disk, so we ask\n * the server rather than starting up blind and waking on ourselves.\n */\nexport async function resolveDaemonConfig(opts: ResolveDaemonOpts): Promise<DaemonConfig> {\n const home = path.resolve(opts.home)\n const id = resolveIdentity(home, { envKey: opts.envKey !== false })\n if (id === null) {\n throw new Error(`no AgentChat identity in ${home} — register this agent first`)\n }\n\n // An environment key is the authenticated identity even when this home also\n // contains an older credentials file. That file's handle is not evidence\n // about the env key, so resolve it from the server.\n let handle = id.source === 'file' ? id.handle : null\n if (handle === null) {\n const client = new AgentChatClient({\n apiKey: id.apiKey,\n baseUrl: id.apiBase,\n clientIdentity: clientIdentityOf(opts.client),\n timeoutMs: 10_000,\n })\n const me = await client.getMe().catch(() => null)\n if (me === null || typeof me.handle !== 'string' || me.handle.length === 0) {\n throw new Error(\n 'could not determine this agent’s handle (no credentials file, and /v1/agents/me did not answer)',\n )\n }\n handle = me.handle\n }\n\n return {\n apiKey: id.apiKey,\n handle,\n apiBase: id.apiBase,\n wsBase: wsBaseFor(id.apiBase),\n home,\n workdir: path.resolve(opts.workdir),\n }\n}\n","import * as crypto from 'node:crypto'\nimport { AgentChatClient, RealtimeClient, integration as kit } from 'agentchatme'\nimport { log } from '../util/log.js'\nimport type { DaemonConfig } from '../daemon/config.js'\nimport { beat, idle } from '../daemon/health.js'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\nimport type { RunProfile } from './profile.js'\nimport type { RunKind, RunOutcome, RunRunner, RunWake } from './runner.js'\nimport { writeIntegrationStatus, type IntegrationLastRun, type IntegrationStatus, type SocketState } from './status.js'\nimport { blockedDetail, socketStateOf } from './socket-state.js'\nimport { textsCachePath } from './texts.js'\nimport { MANUAL } from '../skill/manual.js'\nimport { describeManualSync, type ManualFetch } from '../skill/served-manual.js'\n\n// ─── The integration: the SDK kit's receive loop, and one runtime's runner ──\n//\n// Everything that talks to AgentChat is the SDK's integration kit (`import {\n// integration } from 'agentchatme'`), written once for every runtime:\n//\n// * the socket — `ackOnReceipt` (delivered = this machine received it) with\n// the `ack`, `heartbeat` and `rewake` capabilities, never reading a body;\n// * the wakes — a `message.new` that is not this agent's own echo, a `wake`\n// frame (a reminder, or the server re-waking unanswered cards), a group\n// invite, every accepted hello — coalesced into one cycle per burst, one\n// cycle at a time (`WakeCoalescer`);\n// * the cycle in SINGLE-RUN mode (`ReceiveLoop`): read the tray; nothing\n// owed (no cards, only muted ones, no pending invite) starts nothing; a\n// tray that cannot be read is not an empty tray, and the run starts\n// anyway; otherwise ONE run with the served wake instruction (and the\n// invite prompt when invites wait). The run reads the tray and records its\n// own verdicts; nothing is recorded on its behalf;\n// * the served texts (`TextsCache`, the last good copy kept in the identity\n// home) and the manual they announce (`ManualSync`).\n//\n// There is no retry ladder here, and no invite ledger: the server re-wakes\n// unanswered cards on its own durable ladder and shows pending invites on the\n// tray (contract v1, D3/D4), so a run that could not finish leaves the cards\n// where they are and the next wake finds them.\n//\n// What stays here is this package's own: the runner seam (how a runtime's run\n// is started is the integration's — `RunRunner`), the one pointer line a run\n// prompt ends with, a deadline on every run (a runner that never returns must\n// not hold the loop), and the status file `status` and `doctor` read.\n\nconst HEARTBEAT_MS = 30_000\nconst STATUS_MS = 30_000\n/** HTTP calls the loop makes are the tray and the texts; none deserves a long wait or a retry ramp. */\nconst HTTP_TIMEOUT_MS = 10_000\n\n/**\n * How long past its budget a runner may take to return before the loop stops\n * waiting for it. `spawnRun` always returns well inside this (grace, drain and\n * abandon are seconds); the deadline is for a runner that does not keep the\n * \"never hangs\" promise — the loop must outlive every runner.\n */\nexport const RUNNER_DEADLINE_SLACK_MS = 60_000\n\n/** A runner's `preflight()` (a `--version`, an auth probe) past this counts as not ok. */\nexport const PREFLIGHT_DEADLINE_MS = 60_000\n\nexport interface IntegrationOptions {\n readonly cfg: DaemonConfig\n readonly runner: RunRunner\n /** How this integration names itself to the server (texts runtime + its version). */\n readonly client: IntegrationClient\n /** The one pointer line a run prompt ends with (`manualPointer(...)`). */\n readonly manualPointer: string\n /** The skill file that follows the served manual (`<skills dir>/agentchat/SKILL.md`); absent, the manual is left to the CLI. */\n readonly manualPath?: string\n /** Injectable for tests; the manual download's `fetch`. */\n readonly manualFetch?: ManualFetch\n readonly profile: RunProfile\n readonly budgetMs: number\n /** Injectable for tests; past `budgetMs` plus this a runner that has not returned is abandoned. */\n readonly runnerDeadlineSlackMs?: number\n /** Injectable for tests; defaults to an SDK client for `cfg`. */\n readonly api?: AgentChatClient\n /** Injectable for tests: the socket (built with `ackOnReceipt` and the v1 capabilities otherwise). */\n readonly realtime?: RealtimeClient\n /** Injectable for tests: the coalescing window. */\n readonly quietMs?: number\n readonly maxMs?: number\n /** Injectable for tests: the kit's cycle watchdog (default 10 min, not counting runs). */\n readonly cycleTimeoutMs?: number\n /**\n * Injectable for tests: the kit's pacing window (default 60 s) — a second\n * completed run that leaves an invite pending counts toward dismissing it\n * only this long after the first.\n */\n readonly paceMs?: number\n /**\n * The kit's single-run rule dismisses an invite two completed runs left\n * pending, so an ignored invite does not cost a run on every wake. Right\n * when a run is the agent itself; wrong when \"completed\" only means a\n * receiver accepted a POST (the `agentchat forward` mode): there it is\n * false, and no invite is ever dismissed on the agent's behalf.\n */\n readonly dismissIgnoredInvites?: boolean\n}\n\n/** Most of a failure line: enough to diagnose, bounded for the status file. */\nconst CYCLE_FAILURE_CHARS = 240\n\n/** The webhook wake's reason for a kit wake source (contract v1); null when the source names none. */\nfunction reasonOf(source: kit.WakeSource, frameReason: string | undefined): string | null {\n switch (source) {\n case 'message':\n return 'messages'\n case 'invite':\n return 'invite'\n case 'wake_frame':\n return frameReason ?? 'reminder'\n default:\n return null\n }\n}\n\n/** `work`, or `onTimeout()` once `ms` have passed — whichever first. A late result is dropped. */\nfunction withDeadline<T>(work: Promise<T>, ms: number, onTimeout: () => T): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let done = false\n const timer = setTimeout(() => {\n if (done) return\n done = true\n try {\n resolve(onTimeout())\n } catch (err) {\n reject(err)\n }\n }, ms)\n timer.unref?.()\n work.then(\n (value) => {\n if (done) return\n done = true\n clearTimeout(timer)\n resolve(value)\n },\n (err: unknown) => {\n if (done) return\n done = true\n clearTimeout(timer)\n reject(err)\n },\n )\n })\n}\n\nexport class Integration {\n private readonly api: AgentChatClient\n private readonly realtime: RealtimeClient\n private readonly texts: kit.TextsCache\n private readonly manual: kit.ManualSync | null\n private readonly loop: kit.ReceiveLoop\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null\n private statusTimer: ReturnType<typeof setInterval> | null = null\n private socket: SocketState = 'idle'\n private lastError: string | null = null\n private stopping = false\n private stopped: Promise<void> | null = null\n\n private invites = 0\n private runsStarted = 0\n private runsOk = 0\n private runsFailed = 0\n private runsTimedOut = 0\n private runsNotStarted = 0\n private runsSkippedEmpty = 0\n private lastRun: IntegrationLastRun | null = null\n /** The newest wake since the last run started (for `RunRequest.wake`). */\n private pendingWake: RunWake | null = null\n /** The rung of the newest `unanswered` wake frame (the kit's wake event does not carry it). */\n private lastUnansweredStep: number | null = null\n\n constructor(private readonly options: IntegrationOptions) {\n const { cfg, client } = options\n const identity = clientIdentityOf(client)\n this.api =\n options.api ??\n new AgentChatClient({ apiKey: cfg.apiKey, baseUrl: cfg.apiBase, clientIdentity: identity, timeoutMs: HTTP_TIMEOUT_MS, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } })\n this.texts = new kit.TextsCache({\n client: this.api,\n runtime: client.runtime,\n filePath: textsCachePath(cfg.home),\n onError: (err) => log.warn(err.message),\n })\n this.texts.onChange((texts, source) => {\n log.info(`texts ${source === 'server' ? 'fetched' : 'read from the cache'} for ${client.runtime} (texts v${texts.version}, manual ${texts.manual.version})`)\n this.writeStatus()\n })\n this.manual =\n options.manualPath === undefined\n ? null\n : new kit.ManualSync({\n texts: this.texts,\n targetPath: options.manualPath,\n fallback: MANUAL,\n ...(options.manualFetch !== undefined ? { fetch: options.manualFetch } : {}),\n onResult: (result) => {\n const line = `manual: ${describeManualSync({ ...result, source: result.source === 'fallback' ? 'bundled' : result.source })}`\n if (result.upToDate === false || result.state === 'failed') log.warn(line)\n else if (result.written) log.info(line)\n },\n })\n // Built here rather than by the loop, so the status file can follow the\n // socket's own words and a refused key reads `blocked` with its reason.\n // No REST drain client: the server re-offers unacked envelopes over the\n // socket right after the hello, and nothing here ever needs a body.\n this.realtime =\n options.realtime ??\n new RealtimeClient({\n apiKey: cfg.apiKey,\n baseUrl: cfg.wsBase,\n clientIdentity: identity,\n ackOnReceipt: true,\n reconnect: true,\n capabilities: { heartbeat: true, rewake: true },\n })\n this.realtime.on('state', (next) => {\n const word = socketStateOf(next, this.socket)\n if (word === this.socket) return\n this.socket = word\n if (word === 'ready') {\n beat(cfg.home)\n // An accepted hello lifts a refusal: the key works again.\n this.lastError = null\n log.info(`socket ready (hello.ok) — acks ${this.realtime.ackNegotiated ? 'on receipt' : 'not negotiated by this server'}; ${this.realtime.capabilities.has('rewake') ? 'the server re-wakes unanswered cards' : 'this server does not re-wake unanswered cards'}`)\n } else {\n idle(cfg.home)\n if (word === 'reconnecting') log.info('socket reconnecting — the SDK backs off and retries; it never gives up')\n }\n this.writeStatus()\n })\n this.realtime.on('blocked', (info) => {\n // A refused key is a state to show, not to die from: the SDK stays\n // `blocked` and tries a fresh hello every 10–15 min.\n this.lastError = blockedDetail(info)\n log.error(`socket blocked (auth): ${this.lastError}`)\n this.writeStatus()\n })\n this.realtime.on('wake', (frame) => {\n const payload = (frame.payload ?? {}) as { reason?: unknown; step?: unknown }\n if (payload.reason === 'unanswered' && typeof payload.step === 'number') this.lastUnansweredStep = payload.step\n })\n this.loop = new kit.ReceiveLoop({\n client: this.api,\n // The kit's own switch: off, no invite is dismissed on the agent's behalf.\n ...(options.dismissIgnoredInvites === false ? { dismissIgnoredInvites: false } : {}),\n texts: this.texts,\n mode: 'singleRun',\n socket: this.realtime,\n handle: cfg.handle,\n startRun: (request) => this.startRun(request),\n onEvent: (event) => this.onEvent(event),\n ...(options.quietMs !== undefined ? { quietMs: options.quietMs } : {}),\n ...(options.maxMs !== undefined ? { maxMs: options.maxMs } : {}),\n ...(options.cycleTimeoutMs !== undefined ? { cycleTimeoutMs: options.cycleTimeoutMs } : {}),\n ...(options.paceMs !== undefined ? { paceMs: options.paceMs } : {}),\n })\n }\n\n async start(): Promise<void> {\n // Bounded: a preflight that never answers must not hold the supervisor\n // (and with it the shutdown path) forever.\n const pre = await withDeadline(this.options.runner.preflight(), PREFLIGHT_DEADLINE_MS, () => ({\n ok: false,\n detail: `preflight did not answer within ${Math.round(PREFLIGHT_DEADLINE_MS / 1000)} s`,\n }))\n if (!pre.ok) throw new Error(`runtime (${this.options.runner.name}) not ready: ${pre.detail ?? 'unknown'}`)\n log.info(\n `integration up as @${this.options.cfg.handle} via ${this.options.runner.name} (${this.options.client.runtime} ${this.options.client.version}), profile ${this.options.profile}; fetching the served texts, then holding the socket`,\n )\n // The texts are in before the socket opens, so the first wake has the\n // freshest text; a failure is logged and the cached copy (if any) serves.\n await this.texts.start()\n if (this.stopping) return\n // The skill file follows the announced manual from now on; a download\n // never holds up the socket.\n void this.manual?.start()\n await this.loop.start()\n this.heartbeatTimer = setInterval(() => {\n if (this.socket === 'ready') beat(this.options.cfg.home)\n }, HEARTBEAT_MS)\n this.heartbeatTimer.unref()\n this.statusTimer = setInterval(() => this.writeStatus(), STATUS_MS)\n this.statusTimer.unref()\n this.writeStatus()\n }\n\n /**\n * Stop holding the socket and interrupt a run in flight (its signal aborts;\n * the runner SIGTERMs its process group). `idle()` / `stopAndWait()`\n * tell when the run has actually ended.\n */\n stop(): void {\n if (this.stopping) return\n this.stopping = true\n if (this.heartbeatTimer) clearInterval(this.heartbeatTimer)\n if (this.statusTimer) clearInterval(this.statusTimer)\n this.stopped = this.loop.stop()\n this.texts.stop()\n this.manual?.stop()\n this.socket = 'closed'\n idle(this.options.cfg.home)\n this.writeStatus()\n }\n\n /** `stop()`, then wait up to `graceMs` for the interrupted run to end. Resolves true when nothing runs any more. */\n async stopAndWait(graceMs: number): Promise<boolean> {\n this.stop()\n let timer: ReturnType<typeof setTimeout> | null = null\n try {\n return await Promise.race([\n (this.stopped ?? Promise.resolve()).then(() => true),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), graceMs)\n }),\n ])\n } finally {\n if (timer !== null) clearTimeout(timer)\n }\n }\n\n /** Resolves when no cycle (and so no run) is running: the kit's `ReceiveLoop.idle()`. */\n idle(): Promise<void> {\n return this.loop.idle()\n }\n\n /** A wake heard outside the socket (a test, a webhook the integration received). */\n wake(): void {\n this.loop.wake()\n }\n\n snapshot(): IntegrationStatus {\n const status = this.loop.status()\n const texts = this.texts.current()\n return {\n version: 2,\n updated_at: new Date().toISOString(),\n pid: process.pid,\n runtime: this.options.runner.name,\n handle: this.options.cfg.handle,\n profile: this.options.profile,\n socket: this.stopping ? 'closed' : this.socket,\n wakes: status.coalescer.wakes,\n wakes_absorbed: status.coalescer.absorbed,\n invites: this.invites,\n runs_started: this.runsStarted,\n runs_ok: this.runsOk,\n runs_failed: this.runsFailed,\n runs_timed_out: this.runsTimedOut,\n runs_not_started: this.runsNotStarted,\n runs_skipped_empty: this.runsSkippedEmpty,\n last_run: this.lastRun,\n // No local retry ladder (the server re-wakes, D3); kept for older readers.\n retry_rung: 0,\n retry_due_at: null,\n last_error: this.lastError,\n texts: {\n source: this.texts.source,\n fetched_at: this.texts.fetchedAt,\n version: texts?.version ?? null,\n manual_version: texts?.manual.version ?? null,\n },\n capabilities: status.socket === null ? null : status.socket.capabilities,\n intake_paused: status.socket === null ? null : status.socket.intakePaused,\n recent_cycles: status.recentCycles.map((cycle) => ({\n at: cycle.at,\n outcome: cycle.outcome,\n cards: cycle.cards,\n invites: cycle.invites,\n failure: cycle.failure === null ? null : cycle.failure.slice(0, CYCLE_FAILURE_CHARS),\n })),\n }\n }\n\n // ─── the one run ────────────────────────────────────────────────────────\n\n private async startRun(request: kit.RunRequest): Promise<kit.RunEnd> {\n // Invites alone: the served invite prompt. Anything else: a wake run.\n const kind: RunKind = request.cards === 0 && (request.invites ?? 0) > 0 ? 'invite' : 'wake'\n // What woke it: the newest named wake since the previous run; a connect\n // (or a follow-on) names none, and the tray says what it found.\n const wake: RunWake = this.pendingWake ?? { reason: kind === 'invite' ? 'invite' : 'messages' }\n this.pendingWake = null\n const runId = crypto.randomUUID()\n const startedAt = Date.now()\n const budgetMs = this.options.budgetMs\n const slackMs = this.options.runnerDeadlineSlackMs ?? RUNNER_DEADLINE_SLACK_MS\n this.runsStarted += 1\n this.writeStatus()\n log.info(`run start kind=${kind} id=${runId} budget=${Math.round(budgetMs / 1000)}s (tray: ${request.cards ?? '?'} card(s), ${request.invites ?? '?'} invite(s))`)\n\n // The run's own stop signal: the loop stopping, or the deadline below.\n const controller = new AbortController()\n const onAbort = (): void => controller.abort()\n if (request.signal.aborted) controller.abort()\n else request.signal.addEventListener('abort', onAbort, { once: true })\n let outcome: RunOutcome\n try {\n outcome = await withDeadline(\n this.options.runner.start({\n kind,\n wake,\n prompt: `${request.prompt}\\n\\n${this.options.manualPointer}`,\n runId,\n budgetMs,\n signal: controller.signal,\n }),\n budgetMs + slackMs,\n () => {\n controller.abort()\n return {\n state: 'timed_out',\n exitCode: null,\n durationMs: Date.now() - startedAt,\n detail: `the runner did not return within ${Math.round((budgetMs + slackMs) / 1000)} s (budget plus ${Math.round(slackMs / 1000)} s) — abandoned so the next wake can run`,\n }\n },\n )\n } catch (err) {\n // The runner contract is \"never throws\"; a throw is a bug in the runner.\n outcome = { state: 'not_started', exitCode: null, durationMs: Date.now() - startedAt, detail: `runner threw: ${err instanceof Error ? err.message : String(err)}` }\n } finally {\n request.signal.removeEventListener('abort', onAbort)\n }\n\n this.lastRun = {\n kind,\n started_at: new Date(startedAt).toISOString(),\n ended_at: new Date().toISOString(),\n state: outcome.state,\n exit_code: outcome.exitCode,\n duration_ms: outcome.durationMs,\n detail: outcome.detail ?? null,\n }\n switch (outcome.state) {\n case 'ok':\n this.runsOk += 1\n log.info(`run ok kind=${kind} id=${runId} ${Math.round(outcome.durationMs / 1000)}s (output discarded; any send was the agent's own hosted-tool call)`)\n break\n case 'failed':\n this.runsFailed += 1\n break\n case 'timed_out':\n this.runsTimedOut += 1\n break\n case 'not_started':\n this.runsNotStarted += 1\n break\n }\n if (outcome.state !== 'ok') {\n log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ''} — the cards stay on the tray; the next wake (or the server's re-wake) finds them`)\n }\n this.writeStatus()\n return outcome.state === 'ok'\n ? { status: 'completed' }\n : { status: outcome.state === 'not_started' ? 'not_started' : 'failed', ...(outcome.detail !== undefined ? { detail: outcome.detail } : {}) }\n }\n\n private onEvent(event: kit.ReceiveLoopEvent): void {\n switch (event.type) {\n case 'wake': {\n if (event.source === 'invite') this.invites += 1\n const reason = reasonOf(event.source, event.reason)\n if (reason !== null) {\n this.pendingWake = reason === 'unanswered' && this.lastUnansweredStep !== null ? { reason, step: this.lastUnansweredStep } : { reason }\n }\n log.info(`wake — ${event.source}${event.reason ? ` (${event.reason})` : ''}${event.conversationId ? ` conv=${event.conversationId}` : ''}`)\n break\n }\n case 'echo':\n log.debug(`own echo${event.conversationId ? ` in ${event.conversationId}` : ''} — not a wake`)\n break\n case 'cycle': {\n const { outcome, cards, invites } = event.summary\n if (outcome === 'empty' || outcome === 'nothing_owed') {\n this.runsSkippedEmpty += 1\n log.info(`wake: ${outcome === 'empty' ? 'the tray is empty' : 'nothing owed (muted cards only)'} — no run (${cards} card(s), ${invites} invite(s))`)\n } else if (outcome === 'abandoned') {\n log.warn(`wake cycle abandoned by the watchdog: ${event.summary.failure ?? 'it ran past its deadline'} — the next wake starts a new one`)\n } else if (outcome === 'texts_missing') {\n this.runsNotStarted += 1\n log.warn('no served texts in hand: GET /v1/texts has not answered yet and nothing is cached in the identity home — no run this time')\n }\n this.writeStatus()\n break\n }\n case 'error':\n if (!this.stopping) log.warn(`receive loop: ${event.error.message}`)\n break\n default:\n break\n }\n }\n\n private writeStatus(): void {\n writeIntegrationStatus(this.options.cfg.home, this.snapshot())\n }\n}\n","import type { BlockedInfo, RealtimeState } from 'agentchatme'\nimport type { SocketState } from './status.js'\n\n// ─── The SDK socket's states, in the status file's words ───────────────────\n\n/**\n * The SDK's connection state in the status file's vocabulary. Pure. `previous`\n * is the status word in effect, which decides two things the SDK's state alone\n * does not say: a `connecting` after a close is `reconnecting`, and the slow\n * retry out of `blocked` (`connecting` again) stays `blocked` — only an\n * accepted hello (`ready`) lifts it. `stopped` is `closed` from any state; a\n * refusal stays visible as the last error, not as the socket word.\n */\nexport function socketStateOf(next: RealtimeState, previous: SocketState): SocketState {\n switch (next) {\n case 'idle':\n return 'idle'\n case 'connecting':\n if (previous === 'blocked') return 'blocked'\n return previous === 'idle' || previous === 'connecting' ? 'connecting' : 'reconnecting'\n case 'ready':\n return 'ready'\n case 'backoff':\n return 'reconnecting'\n case 'blocked':\n return 'blocked'\n case 'stopped':\n return 'closed'\n }\n}\n\n/** The `last error` line for a refused credential: the server's close, what to do, and that the SDK keeps trying. */\nexport function blockedDetail(info: BlockedInfo): string {\n return `auth rejected (close ${info.code}${info.reason ? ` ${info.reason}` : ''}) — check the agent's API key; a fresh hello is tried every 10–15 min until one is accepted`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,YAAYA,WAAU;AACtB,YAAY,QAAQ;;;ACDpB,YAAY,UAAU;AACtB,SAAS,uBAAuB;AA6BzB,SAAS,UAAU,SAAyB;AACjD,SAAO,QAAQ,QAAQ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ACP,0BAAkB;AAClB,mBAAW;AACX,sBAAc;AAAA,MAChB,SAAS,KAAK;AAKZ,cAAM,MAAM,OAAO,eAAe,QAAQ,IAAI,UAAU,GAAG;AAC3D,YAAI,QAAQ,aAAa;AACvB,cAAI,KAAK,uBAAuB,GAAG,EAAE;AACrC,wBAAc;AACd,oBAAU,WAAW,GAAG,UAAU,IAAI;AAAA,QACxC;AACA,oBAAY;AACZ,eAAO;AACP,0BAAkB;AAClB,aAAK,IAAI;AAAA,MACX;AAAA,IACF;AAMA,UAAM,SAAS,aAAa,IAAI,UAAU,KAAK,IAAI,UAAU,KAAK,KAAK,IAAI,UAAU,CAAC,GAAG,cAAc;AACvG,aAAS;AACT,UAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,WAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC,KAAK,QAAQ,WAAW,KAAK,IAAI,IAAI,UAAU;AACjF,YAAM,MAAM,OAAO;AAAA,IACrB;AAAA,EACF;AAEA,UAAQ,IAAI,UAAU,QAAQ;AAC9B,UAAQ,IAAI,WAAW,SAAS;AAChC,MAAI,SAAS,MAAM;AACjB,UAAM,QAAQ,MAAM,KAAK,YAAY,iBAAiB;AACtD,QAAI,CAAC,MAAO,KAAI,KAAK,sCAAsC,KAAK,MAAM,oBAAoB,GAAI,CAAC,8CAAyC;AACxI,WAAO;AAAA,EACT;AACA,OAAK,IAAI;AACT,OAAK,QAAQ;AACb,MAAI,cAAc;AAChB,QAAI,KAAK,mBAAmB;AAC3B,KAAC,KAAK,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAChC;AACA,SAAO;AACT;","names":["path","AgentChatClient","resolve","AgentChatClient"]}
1
+ {"version":3,"sources":["../src/integration/run.ts","../src/daemon/config.ts","../src/integration/integration.ts","../src/integration/socket-state.ts"],"sourcesContent":["import * as path from 'node:path'\nimport * as fs from 'node:fs'\nimport { log } from '../util/log.js'\nimport { acquireLeaderLock } from '../daemon/leader-lock.js'\nimport { resolveIdentity, credentialsPath } from '../identity/credentials.js'\nimport { resolveDaemonConfig } from '../daemon/config.js'\nimport { idle } from '../daemon/health.js'\nimport type { IntegrationClient } from '../client-identity.js'\nimport { Integration } from './integration.js'\nimport { INTEGRATION_ENV, INTEGRATION_ENV_LEGACY, INTEGRATION_ENV_LEGACY_REMOVAL, integrationDisabledBy, resolveRunBudgetMs, resolveRunProfile, type RunProfile } from './profile.js'\nimport { isRunnerFactory, type RunnerSource } from './runner.js'\nimport { writeIntegrationStatus } from './status.js'\n\n// ─── The resident supervisor ────────────────────────────────────────────────\n//\n// This process is RESIDENT. It is registered as a service when the integration\n// is installed, and from then on it simply exists — whether or not anyone has\n// signed in. Installation and authentication are different lifecycles (the\n// shape every comparable daemon uses: tailscaled runs before `tailscale up`,\n// and logging out idles it rather than uninstalling it).\n//\n// no credentials → idle. No socket, no retries, no CPU. Just watch.\n// credentials → connect and wake.\n// credentials change → follow them.\n// AGENTCHAT_INTEGRATION=off → stay resident, hold nothing, wake nothing.\n//\n// A refused key is not this loop's case: the SDK's client stays up in\n// `blocked` and tries a fresh hello every 10–15 minutes (`status` reads\n// `socket blocked` meanwhile), so a rotated-back key or a reinstated account\n// reconnects on its own, and a different key is simply a credential change.\n//\n// The only thing that removes this process is an explicit `daemon disable`.\n//\n// SIGTERM/SIGINT (launchd/systemd stop, Ctrl-C) interrupts a run in flight:\n// the integration SIGTERMs the run's process group and this process waits up\n// to SHUTDOWN_GRACE_MS for it before exiting. A daemon that exited at once\n// left the detached run orphaned, and the restarted daemon's connect found\n// the same tray and started a second run beside it.\n\n/** How often to re-read the identity. A `stat`; the watcher usually beats it. */\nconst POLL_MS = 5_000\n/** How often the watcher flag is consulted while waiting out a poll. */\nconst TICK_MS = 250\n/** Ceiling for retry backoff when the runtime simply is not usable yet. */\nconst MAX_BACKOFF_MS = 5 * 60_000\n/**\n * How long a shutdown waits for an interrupted run to end before the process\n * exits. The runner SIGTERMs the run's process group at once and SIGKILLs 5 s\n * later, so this is normally over in well under a second. Below launchd's\n * `ExitTimeOut` (15 s in the plist this package writes).\n */\nconst SHUTDOWN_GRACE_MS = 10_000\nconst MAX_LOG_BYTES = 5 * 1024 * 1024\nconst KEEP_LOG_BYTES = 1024 * 1024\n\nexport interface RunIntegrationOpts {\n /** THE identity home for the agent this daemon serves. */\n home: string\n /** How to start one headless run: a runner, or a factory that builds one per identity (`RunnerFactory`). */\n runner: RunnerSource\n /** How this integration names itself to the server: the texts runtime and its own version. */\n client: IntegrationClient\n /** The one pointer line a run prompt ends with: how THIS runtime reaches its copy of the manual (`manualPointer(...)`). */\n manualPointer: string\n /**\n * The skill file that follows the served manual (`<skills dir>/agentchat/SKILL.md`):\n * whenever the texts in hand announce a version the file does not carry, the\n * announced manual is downloaded, checked and written over it. Absent, the\n * daemon leaves the manual to the CLI's install and `doctor --fix`.\n */\n manualPath?: string\n /** Scratch dir for runs. The integration decides where; this package never derives one. */\n workdir: string\n /** Defaults to `AGENTCHAT_RUN_PROFILE`, then `answer`. */\n profile?: RunProfile\n /** Defaults to `AGENTCHAT_RUN_BUDGET_MS`, then 10 minutes. */\n budgetMs?: number\n /** Ends the loop (tests). Production runs until SIGTERM/SIGINT. */\n signal?: AbortSignal\n env?: NodeJS.ProcessEnv\n /** Test seam: what a signal-initiated shutdown calls last. Defaults to `process.exit`. */\n exit?: (code: number) => void\n /**\n * Serve only the agent the home's `credentials` hold: `AGENTCHAT_API_KEY`\n * in the environment is ignored (default false: it overrides, as for every\n * integration). The `agentchat` listener sets it.\n */\n credentialsFromHomeOnly?: boolean\n /** See `IntegrationOptions.dismissIgnoredInvites` (default true). */\n dismissIgnoredInvites?: boolean\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))\n\n/**\n * Identity fingerprint: changes when the user signs out, signs in, or swaps to\n * a different agent. Comparing it is how the supervisor notices without caring\n * why.\n */\nfunction fingerprint(home: string, envKey: boolean): string | null {\n const id = resolveIdentity(home, { envKey })\n return id === null ? null : `${id.apiKey}:${id.handle ?? ''}`\n}\n\n/** Bound launchd's append-only file without losing the most recent diagnosis. */\nfunction boundDaemonLog(home: string): void {\n const file = path.join(home, 'daemon.log')\n try {\n const size = fs.statSync(file).size\n if (size <= MAX_LOG_BYTES) return\n const fd = fs.openSync(file, 'r')\n try {\n const keep = Buffer.alloc(Math.min(KEEP_LOG_BYTES, size))\n fs.readSync(fd, keep, 0, keep.length, size - keep.length)\n fs.writeFileSync(\n file,\n `[agentchat:info] older daemon log output truncated at ${new Date().toISOString()}\\n${keep.toString('utf-8')}`,\n )\n } finally {\n fs.closeSync(fd)\n }\n } catch {\n /* absent/unreadable log is not a runtime failure */\n }\n}\n\n/**\n * Run the integration daemon. Returns only on a condition that makes running\n * pointless — another daemon already holding this home's lock — or when\n * `signal` aborts (tests).\n */\nexport async function runIntegration(opts: RunIntegrationOpts): Promise<number> {\n const home = path.resolve(opts.home)\n const workdir = path.resolve(opts.workdir)\n const env = opts.env ?? process.env\n const profile = opts.profile ?? resolveRunProfile(env)\n const budgetMs = opts.budgetMs ?? resolveRunBudgetMs(env)\n boundDaemonLog(home)\n\n // A resident service's output goes to a log file nobody sees until something\n // is wrong, and an empty log is useless for \"is the integration working?\".\n if (process.env['AGENTCHAT_LOG_LEVEL'] === undefined) process.env['AGENTCHAT_LOG_LEVEL'] = 'info'\n\n // Taken for the PROCESS, not for a connection: one resident daemon per\n // identity home, signed in or not.\n const lock = acquireLeaderLock(home)\n if (lock === null) return 1\n\n const envKey = opts.credentialsFromHomeOnly !== true\n const identityOf = () => resolveIdentity(home, { envKey })\n const disabledBy = integrationDisabledBy(env)\n const disabled = disabledBy !== null\n let live: Integration | null = null\n let liveFingerprint: string | null = null\n let observedFingerprint: string | null = null\n /** Consecutive start failures, for backoff. Reset on success or on a new credential. */\n let failures = 0\n let lastFailure: string | null = null\n let shuttingDown = false\n\n const offStatus = (handle: string | null): void =>\n writeIntegrationStatus(home, {\n version: 2,\n updated_at: new Date().toISOString(),\n pid: process.pid,\n runtime: opts.runner.name,\n handle,\n profile,\n socket: disabled ? 'off' : 'idle',\n wakes: 0,\n wakes_absorbed: 0,\n invites: 0,\n runs_started: 0,\n runs_ok: 0,\n runs_failed: 0,\n runs_timed_out: 0,\n runs_not_started: 0,\n runs_skipped_empty: 0,\n last_run: null,\n retry_rung: 0,\n retry_due_at: null,\n last_error: lastFailure,\n texts: null,\n })\n\n const disconnect = (why: string): void => {\n if (live === null) return\n log.info(`${why} — disconnecting (a run in flight is interrupted), staying resident`)\n live.stop()\n live = null\n liveFingerprint = null\n idle(home)\n }\n\n // The loop notices `shuttingDown` within a tick and takes the one exit path\n // below: stop the integration, give an interrupted run its grace, release, exit.\n const shutdown = (sig: string): void => {\n if (shuttingDown) return\n shuttingDown = true\n log.info(`${sig} — shutting down`)\n }\n const onSigint = (): void => shutdown('SIGINT')\n const onSigterm = (): void => shutdown('SIGTERM')\n process.on('SIGINT', onSigint)\n process.on('SIGTERM', onSigterm)\n\n // Best-effort accelerator so signing in connects in about a second instead of\n // waiting out a poll. fs.watch is unreliable on some filesystems, so the poll\n // below is the real guarantee and this is pure upside.\n let nudged = false\n try {\n fs.mkdirSync(home, { recursive: true })\n const watcher = fs.watch(home, (_event, filename) => {\n if (filename === null || String(filename).startsWith('credentials')) nudged = true\n })\n watcher.on('error', (err) => {\n log.warn(`credential watcher unavailable; polling instead: ${String(err)}`)\n try {\n watcher.close()\n } catch {\n /* already closed */\n }\n })\n watcher.unref()\n } catch {\n /* polling covers it */\n }\n\n log.info(`integration resident for ${home} (${credentialsPath(home)}) — ${opts.client.runtime} ${opts.client.version}`)\n if (disabled) {\n log.info(`${disabledBy}=off — holding no socket and starting no run; the hosted tools and the manual still work in every session`)\n if (disabledBy === INTEGRATION_ENV_LEGACY) {\n log.warn(`${INTEGRATION_ENV_LEGACY} is the old name of ${INTEGRATION_ENV} (agent contract v1 schedules its removal for ${INTEGRATION_ENV_LEGACY_REMOVAL}); set ${INTEGRATION_ENV}=off instead`)\n }\n }\n idle(home)\n offStatus(null)\n\n for (;;) {\n if (shuttingDown || opts.signal?.aborted) break\n const fp = fingerprint(home, envKey)\n const identityChanged = fp !== observedFingerprint\n if (identityChanged) {\n disconnect(fp === null ? 'signed out' : 'identity changed')\n observedFingerprint = fp\n failures = 0\n lastFailure = null\n if (fp === null || disabled) offStatus(fp === null ? null : identityOf()?.handle ?? null)\n }\n\n if (fp === null) {\n // Signed out, or never signed in. Idle.\n } else if (disabled) {\n // Signed in, switched off. Resident, silent.\n } else if (fp !== liveFingerprint) {\n try {\n const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client, envKey })\n const runner = isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner\n const candidate = new Integration({\n cfg,\n runner,\n client: opts.client,\n manualPointer: opts.manualPointer,\n ...(opts.manualPath !== undefined ? { manualPath: opts.manualPath } : {}),\n profile,\n budgetMs,\n ...(opts.dismissIgnoredInvites !== undefined ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {}),\n })\n await candidate.start()\n live = candidate\n liveFingerprint = fp\n failures = 0\n lastFailure = null\n } catch (err) {\n // Runtime not ready (host CLI missing or not signed in), network\n // down, whatever. Stay resident and try again later — exiting would\n // just make the service manager restart us in a loop. Backed off and\n // de-duplicated so a condition that lasts days does not fill the log.\n const msg = String(err instanceof Error ? err.message : err)\n if (msg !== lastFailure) {\n log.warn(`not connecting yet: ${msg}`)\n lastFailure = msg\n offStatus(identityOf()?.handle ?? null)\n }\n failures += 1\n live = null\n liveFingerprint = null\n idle(home)\n }\n }\n\n // Wait out the poll interval, but wake as soon as the watcher fires so a\n // sign-in connects in well under a second. Exponential backoff while a\n // start keeps failing, capped — the watcher still wakes us instantly when\n // credentials change, so backing off never delays a real sign-in.\n const waitMs = failures === 0 ? POLL_MS : Math.min(POLL_MS * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS)\n nudged = false\n const deadline = Date.now() + waitMs\n while (!nudged && !shuttingDown && !opts.signal?.aborted && Date.now() < deadline) {\n await sleep(TICK_MS)\n }\n }\n\n process.off('SIGINT', onSigint)\n process.off('SIGTERM', onSigterm)\n if (live !== null) {\n const ended = await live.stopAndWait(SHUTDOWN_GRACE_MS)\n if (!ended) log.warn(`a run in flight did not end within ${Math.round(SHUTDOWN_GRACE_MS / 1000)}s of being interrupted — exiting anyway`)\n live = null\n }\n idle(home)\n lock.release()\n if (shuttingDown) {\n log.info('shutdown complete')\n ;(opts.exit ?? process.exit)(0)\n }\n return 0\n}\n","import * as path from 'node:path'\nimport { AgentChatClient } from 'agentchatme'\nimport { resolveIdentity } from '../identity/credentials.js'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\n\n// ─── Daemon identity resolution ─────────────────────────────────────────────\n//\n// The daemon runs AS one host agent — the same identity that agent's sessions\n// use through the hosted tools, never a separate account. It reads that\n// credential from the home it is GIVEN.\n//\n// The predecessor of this file mapped a `runtime` enum to a home\n// (`codex → ~/.codex/agentchat`, `claude-code → ~/.claude/agentchat`). That\n// mapping is exactly the \"a function that decides can decide wrong\" defect this\n// package exists to make unrepresentable, so it is gone: the caller passes its\n// own home and there is no enum to mis-set.\n\nexport interface DaemonConfig {\n apiKey: string\n handle: string\n apiBase: string\n /** `wss://api.agentchat.me` — the SDK's socket base; it appends `/v1/ws`. */\n wsBase: string\n /** The identity home. Credentials, leader lock, and heartbeat all live here. */\n home: string\n /** Scratch dir for runs (the headless run's cwd). */\n workdir: string\n}\n\n/** `https://api.agentchat.me` → `wss://api.agentchat.me`. */\nexport function wsBaseFor(apiBase: string): string {\n return apiBase.replace(/^http/, 'ws').replace(/\\/+$/, '')\n}\n\n/** `https://api.agentchat.me` → `wss://api.agentchat.me/v1/ws`, for logs and checks. */\nexport function wsUrlFor(apiBase: string): string {\n return `${wsBaseFor(apiBase)}/v1/ws`\n}\n\nexport interface ResolveDaemonOpts {\n /** THE identity home. Required — this module never derives one. */\n home: string\n /** The run workdir. Required — this module never derives one either. */\n workdir: string\n /** How to identify to the server when the handle has to be asked for. */\n client: IntegrationClient\n /** Whether `AGENTCHAT_API_KEY` may override the home's credentials (default true; see `resolveIdentity`). */\n envKey?: boolean\n}\n\n/**\n * Resolve the identity the daemon runs as.\n *\n * Async because the handle is load-bearing at runtime — it filters this agent's\n * own outbound echoed back by server fan-out. An env-only identity\n * (`AGENTCHAT_API_KEY`, no credentials file) has no handle on disk, so we ask\n * the server rather than starting up blind and waking on ourselves.\n */\nexport async function resolveDaemonConfig(opts: ResolveDaemonOpts): Promise<DaemonConfig> {\n const home = path.resolve(opts.home)\n const id = resolveIdentity(home, { envKey: opts.envKey !== false })\n if (id === null) {\n throw new Error(`no AgentChat identity in ${home} — register this agent first`)\n }\n\n // An environment key is the authenticated identity even when this home also\n // contains an older credentials file. That file's handle is not evidence\n // about the env key, so resolve it from the server.\n let handle = id.source === 'file' ? id.handle : null\n if (handle === null) {\n const client = new AgentChatClient({\n apiKey: id.apiKey,\n baseUrl: id.apiBase,\n clientIdentity: clientIdentityOf(opts.client),\n timeoutMs: 10_000,\n })\n const me = await client.getMe().catch(() => null)\n if (me === null || typeof me.handle !== 'string' || me.handle.length === 0) {\n throw new Error(\n 'could not determine this agent’s handle (no credentials file, and /v1/agents/me did not answer)',\n )\n }\n handle = me.handle\n }\n\n return {\n apiKey: id.apiKey,\n handle,\n apiBase: id.apiBase,\n wsBase: wsBaseFor(id.apiBase),\n home,\n workdir: path.resolve(opts.workdir),\n }\n}\n","import * as crypto from 'node:crypto'\nimport { AgentChatClient, RealtimeClient, integration as kit } from 'agentchatme'\nimport { log } from '../util/log.js'\nimport type { DaemonConfig } from '../daemon/config.js'\nimport { beat, idle } from '../daemon/health.js'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\nimport type { RunProfile } from './profile.js'\nimport type { RunKind, RunOutcome, RunRunner, RunWake } from './runner.js'\nimport { writeIntegrationStatus, type IntegrationLastRun, type IntegrationStatus, type SocketState } from './status.js'\nimport { blockedDetail, socketStateOf } from './socket-state.js'\nimport { textsCachePath } from './texts.js'\nimport { MANUAL } from '../skill/manual.js'\nimport { describeManualSync, type ManualFetch } from '../skill/served-manual.js'\n\n// ─── The integration: the SDK kit's receive loop, and one runtime's runner ──\n//\n// Everything that talks to AgentChat is the SDK's integration kit (`import {\n// integration } from 'agentchatme'`), written once for every runtime:\n//\n// * the socket — `ackOnReceipt` (delivered = this machine received it) with\n// the `ack`, `heartbeat` and `rewake` capabilities, never reading a body;\n// * the wakes — a `message.new` that is not this agent's own echo, a `wake`\n// frame (a reminder, or the server re-waking unanswered cards), a group\n// invite, every accepted hello — coalesced into one cycle per burst, one\n// cycle at a time (`WakeCoalescer`);\n// * the cycle in SINGLE-RUN mode (`ReceiveLoop`): read the tray; nothing\n// owed (no cards, only muted ones, no pending invite) starts nothing; a\n// tray that cannot be read is not an empty tray, and the run starts\n// anyway; otherwise ONE run with the served wake instruction (and the\n// invite prompt when invites wait). The run reads the tray and records its\n// own verdicts; nothing is recorded on its behalf;\n// * the served texts (`TextsCache`, the last good copy kept in the identity\n// home) and the manual they announce (`ManualSync`).\n//\n// There is no retry ladder here, and no invite ledger: the server re-wakes\n// unanswered cards on its own durable ladder and shows pending invites on the\n// tray (contract v1, D3/D4), so a run that could not finish leaves the cards\n// where they are and the next wake finds them.\n//\n// What stays here is this package's own: the runner seam (how a runtime's run\n// is started is the integration's — `RunRunner`), the one pointer line a run\n// prompt ends with, a deadline on every run (a runner that never returns must\n// not hold the loop), and the status file `status` and `doctor` read.\n\nconst HEARTBEAT_MS = 30_000\nconst STATUS_MS = 30_000\n/** HTTP calls the loop makes are the tray and the texts; none deserves a long wait or a retry ramp. */\nconst HTTP_TIMEOUT_MS = 10_000\n\n/**\n * How long past its budget a runner may take to return before the loop stops\n * waiting for it. `spawnRun` always returns well inside this (grace, drain and\n * abandon are seconds); the deadline is for a runner that does not keep the\n * \"never hangs\" promise — the loop must outlive every runner.\n */\nexport const RUNNER_DEADLINE_SLACK_MS = 60_000\n\n/** A runner's `preflight()` (a `--version`, an auth probe) past this counts as not ok. */\nexport const PREFLIGHT_DEADLINE_MS = 60_000\n\nexport interface IntegrationOptions {\n readonly cfg: DaemonConfig\n readonly runner: RunRunner\n /** How this integration names itself to the server (texts runtime + its version). */\n readonly client: IntegrationClient\n /** The one pointer line a run prompt ends with (`manualPointer(...)`). */\n readonly manualPointer: string\n /** The skill file that follows the served manual (`<skills dir>/agentchat/SKILL.md`); absent, the manual is left to the CLI. */\n readonly manualPath?: string\n /** Injectable for tests; the manual download's `fetch`. */\n readonly manualFetch?: ManualFetch\n readonly profile: RunProfile\n readonly budgetMs: number\n /** Injectable for tests; past `budgetMs` plus this a runner that has not returned is abandoned. */\n readonly runnerDeadlineSlackMs?: number\n /** Injectable for tests; defaults to an SDK client for `cfg`. */\n readonly api?: AgentChatClient\n /** Injectable for tests: the socket (built with `ackOnReceipt` and the v1 capabilities otherwise). */\n readonly realtime?: RealtimeClient\n /** Injectable for tests: the coalescing window. */\n readonly quietMs?: number\n readonly maxMs?: number\n /** Injectable for tests: the kit's cycle watchdog (default 10 min, not counting runs). */\n readonly cycleTimeoutMs?: number\n /**\n * Injectable for tests: the kit's pacing window (default 60 s) — a second\n * completed run that leaves an invite pending counts toward dismissing it\n * only this long after the first.\n */\n readonly paceMs?: number\n /**\n * The kit's single-run rule dismisses an invite two completed runs left\n * pending, so an ignored invite does not cost a run on every wake. Right\n * when a run is the agent itself; wrong when \"completed\" only means a\n * receiver accepted a POST (the `agentchat forward` mode): there it is\n * false, and no invite is ever dismissed on the agent's behalf.\n */\n readonly dismissIgnoredInvites?: boolean\n}\n\n/** Most of a failure line: enough to diagnose, bounded for the status file. */\nconst CYCLE_FAILURE_CHARS = 240\n\n/** The webhook wake's reason for a kit wake source (contract v1); null when the source names none. */\nfunction reasonOf(source: kit.WakeSource, frameReason: string | undefined): string | null {\n switch (source) {\n case 'message':\n return 'messages'\n case 'invite':\n return 'invite'\n case 'wake_frame':\n return frameReason ?? 'reminder'\n default:\n return null\n }\n}\n\n/** `work`, or `onTimeout()` once `ms` have passed — whichever first. A late result is dropped. */\nfunction withDeadline<T>(work: Promise<T>, ms: number, onTimeout: () => T): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let done = false\n const timer = setTimeout(() => {\n if (done) return\n done = true\n try {\n resolve(onTimeout())\n } catch (err) {\n reject(err)\n }\n }, ms)\n timer.unref?.()\n work.then(\n (value) => {\n if (done) return\n done = true\n clearTimeout(timer)\n resolve(value)\n },\n (err: unknown) => {\n if (done) return\n done = true\n clearTimeout(timer)\n reject(err)\n },\n )\n })\n}\n\nexport class Integration {\n private readonly api: AgentChatClient\n private readonly realtime: RealtimeClient\n private readonly texts: kit.TextsCache\n private readonly manual: kit.ManualSync | null\n private readonly loop: kit.ReceiveLoop\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null\n private statusTimer: ReturnType<typeof setInterval> | null = null\n private socket: SocketState = 'idle'\n private lastError: string | null = null\n private stopping = false\n private stopped: Promise<void> | null = null\n\n private invites = 0\n private runsStarted = 0\n private runsOk = 0\n private runsFailed = 0\n private runsTimedOut = 0\n private runsNotStarted = 0\n private runsSkippedEmpty = 0\n private lastRun: IntegrationLastRun | null = null\n /** The newest wake since the last run started (for `RunRequest.wake`). */\n private pendingWake: RunWake | null = null\n /** The rung of the newest `unanswered` wake frame (the kit's wake event does not carry it). */\n private lastUnansweredStep: number | null = null\n\n constructor(private readonly options: IntegrationOptions) {\n const { cfg, client } = options\n const identity = clientIdentityOf(client)\n this.api =\n options.api ??\n new AgentChatClient({ apiKey: cfg.apiKey, baseUrl: cfg.apiBase, clientIdentity: identity, timeoutMs: HTTP_TIMEOUT_MS, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } })\n this.texts = new kit.TextsCache({\n client: this.api,\n runtime: client.runtime,\n filePath: textsCachePath(cfg.home),\n onError: (err) => log.warn(err.message),\n })\n this.texts.onChange((texts, source) => {\n log.info(`texts ${source === 'server' ? 'fetched' : 'read from the cache'} for ${client.runtime} (texts v${texts.version}, manual ${texts.manual.version})`)\n this.writeStatus()\n })\n this.manual =\n options.manualPath === undefined\n ? null\n : new kit.ManualSync({\n texts: this.texts,\n targetPath: options.manualPath,\n fallback: MANUAL,\n ...(options.manualFetch !== undefined ? { fetch: options.manualFetch } : {}),\n onResult: (result) => {\n const line = `manual: ${describeManualSync({ ...result, source: result.source === 'fallback' ? 'bundled' : result.source })}`\n if (result.upToDate === false || result.state === 'failed') log.warn(line)\n else if (result.written) log.info(line)\n },\n })\n // Built here rather than by the loop, so the status file can follow the\n // socket's own words and a refused key reads `blocked` with its reason.\n // No REST drain client: the server re-offers unacked envelopes over the\n // socket right after the hello, and nothing here ever needs a body.\n this.realtime =\n options.realtime ??\n new RealtimeClient({\n apiKey: cfg.apiKey,\n baseUrl: cfg.wsBase,\n clientIdentity: identity,\n ackOnReceipt: true,\n reconnect: true,\n capabilities: { heartbeat: true, rewake: true },\n })\n this.realtime.on('state', (next) => {\n const word = socketStateOf(next, this.socket)\n if (word === this.socket) return\n this.socket = word\n if (word === 'ready') {\n beat(cfg.home)\n // An accepted hello lifts a refusal: the key works again.\n this.lastError = null\n log.info(`socket ready (hello.ok) — acks ${this.realtime.ackNegotiated ? 'on receipt' : 'not negotiated by this server'}; ${this.realtime.capabilities.has('rewake') ? 'the server re-wakes unanswered cards' : 'this server does not re-wake unanswered cards'}`)\n } else {\n idle(cfg.home)\n if (word === 'reconnecting') log.info('socket reconnecting — the SDK backs off and retries; it never gives up')\n }\n this.writeStatus()\n })\n this.realtime.on('blocked', (info) => {\n // A refused key is a state to show, not to die from: the SDK stays\n // `blocked` and tries a fresh hello every 10–15 min.\n this.lastError = blockedDetail(info)\n log.error(`socket blocked (auth): ${this.lastError}`)\n this.writeStatus()\n })\n this.realtime.on('wake', (frame) => {\n const payload = (frame.payload ?? {}) as { reason?: unknown; step?: unknown }\n if (payload.reason === 'unanswered' && typeof payload.step === 'number') this.lastUnansweredStep = payload.step\n })\n this.loop = new kit.ReceiveLoop({\n client: this.api,\n // The kit's own switch: off, no invite is dismissed on the agent's behalf.\n ...(options.dismissIgnoredInvites === false ? { dismissIgnoredInvites: false } : {}),\n texts: this.texts,\n mode: 'singleRun',\n socket: this.realtime,\n handle: cfg.handle,\n startRun: (request) => this.startRun(request),\n onEvent: (event) => this.onEvent(event),\n ...(options.quietMs !== undefined ? { quietMs: options.quietMs } : {}),\n ...(options.maxMs !== undefined ? { maxMs: options.maxMs } : {}),\n ...(options.cycleTimeoutMs !== undefined ? { cycleTimeoutMs: options.cycleTimeoutMs } : {}),\n ...(options.paceMs !== undefined ? { paceMs: options.paceMs } : {}),\n })\n }\n\n async start(): Promise<void> {\n // Bounded: a preflight that never answers must not hold the supervisor\n // (and with it the shutdown path) forever.\n const pre = await withDeadline(this.options.runner.preflight(), PREFLIGHT_DEADLINE_MS, () => ({\n ok: false,\n detail: `preflight did not answer within ${Math.round(PREFLIGHT_DEADLINE_MS / 1000)} s`,\n }))\n if (!pre.ok) throw new Error(`runtime (${this.options.runner.name}) not ready: ${pre.detail ?? 'unknown'}`)\n log.info(\n `integration up as @${this.options.cfg.handle} via ${this.options.runner.name} (${this.options.client.runtime} ${this.options.client.version}), profile ${this.options.profile}; fetching the served texts, then holding the socket`,\n )\n // The texts are in before the socket opens, so the first wake has the\n // freshest text; a failure is logged and the cached copy (if any) serves.\n await this.texts.start()\n if (this.stopping) return\n // The skill file follows the announced manual from now on; a download\n // never holds up the socket.\n void this.manual?.start()\n await this.loop.start()\n this.heartbeatTimer = setInterval(() => {\n if (this.socket === 'ready') beat(this.options.cfg.home)\n }, HEARTBEAT_MS)\n this.heartbeatTimer.unref()\n this.statusTimer = setInterval(() => this.writeStatus(), STATUS_MS)\n this.statusTimer.unref()\n this.writeStatus()\n }\n\n /**\n * Stop holding the socket and interrupt a run in flight (its signal aborts;\n * the runner SIGTERMs its process group). `idle()` / `stopAndWait()`\n * tell when the run has actually ended.\n */\n stop(): void {\n if (this.stopping) return\n this.stopping = true\n if (this.heartbeatTimer) clearInterval(this.heartbeatTimer)\n if (this.statusTimer) clearInterval(this.statusTimer)\n this.stopped = this.loop.stop()\n this.texts.stop()\n this.manual?.stop()\n this.socket = 'closed'\n idle(this.options.cfg.home)\n this.writeStatus()\n }\n\n /** `stop()`, then wait up to `graceMs` for the interrupted run to end. Resolves true when nothing runs any more. */\n async stopAndWait(graceMs: number): Promise<boolean> {\n this.stop()\n let timer: ReturnType<typeof setTimeout> | null = null\n try {\n return await Promise.race([\n (this.stopped ?? Promise.resolve()).then(() => true),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), graceMs)\n }),\n ])\n } finally {\n if (timer !== null) clearTimeout(timer)\n }\n }\n\n /** Resolves when no cycle (and so no run) is running: the kit's `ReceiveLoop.idle()`. */\n idle(): Promise<void> {\n return this.loop.idle()\n }\n\n /** A wake heard outside the socket (a test, a webhook the integration received). */\n wake(): void {\n this.loop.wake()\n }\n\n snapshot(): IntegrationStatus {\n const status = this.loop.status()\n const texts = this.texts.current()\n return {\n version: 2,\n updated_at: new Date().toISOString(),\n pid: process.pid,\n runtime: this.options.runner.name,\n handle: this.options.cfg.handle,\n profile: this.options.profile,\n socket: this.stopping ? 'closed' : this.socket,\n wakes: status.coalescer.wakes,\n wakes_absorbed: status.coalescer.absorbed,\n invites: this.invites,\n runs_started: this.runsStarted,\n runs_ok: this.runsOk,\n runs_failed: this.runsFailed,\n runs_timed_out: this.runsTimedOut,\n runs_not_started: this.runsNotStarted,\n runs_skipped_empty: this.runsSkippedEmpty,\n last_run: this.lastRun,\n // No local retry ladder (the server re-wakes, D3); kept for older readers.\n retry_rung: 0,\n retry_due_at: null,\n last_error: this.lastError,\n texts: {\n source: this.texts.source,\n fetched_at: this.texts.fetchedAt,\n version: texts?.version ?? null,\n manual_version: texts?.manual.version ?? null,\n },\n capabilities: status.socket === null ? null : status.socket.capabilities,\n intake_paused: status.socket === null ? null : status.socket.intakePaused,\n recent_cycles: status.recentCycles.map((cycle) => ({\n at: cycle.at,\n outcome: cycle.outcome,\n cards: cycle.cards,\n invites: cycle.invites,\n failure: cycle.failure === null ? null : cycle.failure.slice(0, CYCLE_FAILURE_CHARS),\n })),\n }\n }\n\n // ─── the one run ────────────────────────────────────────────────────────\n\n private async startRun(request: kit.RunRequest): Promise<kit.RunEnd> {\n // Invites alone: the served invite prompt. Anything else: a wake run.\n const kind: RunKind = request.cards === 0 && (request.invites ?? 0) > 0 ? 'invite' : 'wake'\n // What woke it: the newest named wake since the previous run; a connect\n // (or a follow-on) names none, and the tray says what it found.\n const wake: RunWake = this.pendingWake ?? { reason: kind === 'invite' ? 'invite' : 'messages' }\n this.pendingWake = null\n const runId = crypto.randomUUID()\n const startedAt = Date.now()\n const budgetMs = this.options.budgetMs\n const slackMs = this.options.runnerDeadlineSlackMs ?? RUNNER_DEADLINE_SLACK_MS\n this.runsStarted += 1\n this.writeStatus()\n log.info(`run start kind=${kind} id=${runId} budget=${Math.round(budgetMs / 1000)}s (tray: ${request.cards ?? '?'} card(s), ${request.invites ?? '?'} invite(s))`)\n\n // The run's own stop signal: the loop stopping, or the deadline below.\n const controller = new AbortController()\n const onAbort = (): void => controller.abort()\n if (request.signal.aborted) controller.abort()\n else request.signal.addEventListener('abort', onAbort, { once: true })\n let outcome: RunOutcome\n try {\n outcome = await withDeadline(\n this.options.runner.start({\n kind,\n wake,\n prompt: `${request.prompt}\\n\\n${this.options.manualPointer}`,\n runId,\n budgetMs,\n signal: controller.signal,\n }),\n budgetMs + slackMs,\n () => {\n controller.abort()\n return {\n state: 'timed_out',\n exitCode: null,\n durationMs: Date.now() - startedAt,\n detail: `the runner did not return within ${Math.round((budgetMs + slackMs) / 1000)} s (budget plus ${Math.round(slackMs / 1000)} s) — abandoned so the next wake can run`,\n }\n },\n )\n } catch (err) {\n // The runner contract is \"never throws\"; a throw is a bug in the runner.\n outcome = { state: 'not_started', exitCode: null, durationMs: Date.now() - startedAt, detail: `runner threw: ${err instanceof Error ? err.message : String(err)}` }\n } finally {\n request.signal.removeEventListener('abort', onAbort)\n }\n\n this.lastRun = {\n kind,\n started_at: new Date(startedAt).toISOString(),\n ended_at: new Date().toISOString(),\n state: outcome.state,\n exit_code: outcome.exitCode,\n duration_ms: outcome.durationMs,\n detail: outcome.detail ?? null,\n }\n switch (outcome.state) {\n case 'ok':\n this.runsOk += 1\n log.info(`run ok kind=${kind} id=${runId} ${Math.round(outcome.durationMs / 1000)}s (output discarded; any send was the agent's own hosted-tool call)`)\n break\n case 'failed':\n this.runsFailed += 1\n break\n case 'timed_out':\n this.runsTimedOut += 1\n break\n case 'not_started':\n this.runsNotStarted += 1\n break\n }\n if (outcome.state !== 'ok') {\n log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ''} — the cards stay on the tray; the next wake (or the server's re-wake) finds them`)\n }\n this.writeStatus()\n return outcome.state === 'ok'\n ? { status: 'completed' }\n : { status: outcome.state === 'not_started' ? 'not_started' : 'failed', ...(outcome.detail !== undefined ? { detail: outcome.detail } : {}) }\n }\n\n private onEvent(event: kit.ReceiveLoopEvent): void {\n switch (event.type) {\n case 'wake': {\n if (event.source === 'invite') this.invites += 1\n const reason = reasonOf(event.source, event.reason)\n if (reason !== null) {\n this.pendingWake = reason === 'unanswered' && this.lastUnansweredStep !== null ? { reason, step: this.lastUnansweredStep } : { reason }\n }\n log.info(`wake — ${event.source}${event.reason ? ` (${event.reason})` : ''}${event.conversationId ? ` conv=${event.conversationId}` : ''}`)\n break\n }\n case 'echo':\n log.debug(`own echo${event.conversationId ? ` in ${event.conversationId}` : ''} — not a wake`)\n break\n case 'cycle': {\n const { outcome, cards, invites } = event.summary\n if (outcome === 'empty' || outcome === 'nothing_owed') {\n this.runsSkippedEmpty += 1\n log.info(`wake: ${outcome === 'empty' ? 'the tray is empty' : 'nothing owed (muted cards only)'} — no run (${cards} card(s), ${invites} invite(s))`)\n } else if (outcome === 'abandoned') {\n log.warn(`wake cycle abandoned by the watchdog: ${event.summary.failure ?? 'it ran past its deadline'} — the next wake starts a new one`)\n } else if (outcome === 'texts_missing') {\n this.runsNotStarted += 1\n log.warn('no served texts in hand: GET /v1/texts has not answered yet and nothing is cached in the identity home — no run this time')\n }\n this.writeStatus()\n break\n }\n case 'error':\n if (!this.stopping) log.warn(`receive loop: ${event.error.message}`)\n break\n default:\n break\n }\n }\n\n private writeStatus(): void {\n writeIntegrationStatus(this.options.cfg.home, this.snapshot())\n }\n}\n","import type { BlockedInfo, RealtimeState } from 'agentchatme'\nimport type { SocketState } from './status.js'\n\n// ─── The SDK socket's states, in the status file's words ───────────────────\n\n/**\n * The SDK's connection state in the status file's vocabulary. Pure. `previous`\n * is the status word in effect, which decides two things the SDK's state alone\n * does not say: a `connecting` after a close is `reconnecting`, and the slow\n * retry out of `blocked` (`connecting` again) stays `blocked` — only an\n * accepted hello (`ready`) lifts it. `stopped` is `closed` from any state; a\n * refusal stays visible as the last error, not as the socket word.\n */\nexport function socketStateOf(next: RealtimeState, previous: SocketState): SocketState {\n switch (next) {\n case 'idle':\n return 'idle'\n case 'connecting':\n if (previous === 'blocked') return 'blocked'\n return previous === 'idle' || previous === 'connecting' ? 'connecting' : 'reconnecting'\n case 'ready':\n return 'ready'\n case 'backoff':\n return 'reconnecting'\n case 'blocked':\n return 'blocked'\n case 'stopped':\n return 'closed'\n }\n}\n\n/** The `last error` line for a refused credential: the server's close, what to do, and that the SDK keeps trying. */\nexport function blockedDetail(info: BlockedInfo): string {\n return `auth rejected (close ${info.code}${info.reason ? ` ${info.reason}` : ''}) — check the agent's API key; a fresh hello is tried every 10–15 min until one is accepted`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,YAAYA,WAAU;AACtB,YAAY,QAAQ;;;ACDpB,YAAY,UAAU;AACtB,SAAS,uBAAuB;AA6BzB,SAAS,UAAU,SAAyB;AACjD,SAAO,QAAQ,QAAQ,SAAS,IAAI,EAAE,QAAQ,QAAQ,EAAE;AAC1D;AAGO,SAAS,SAAS,SAAyB;AAChD,SAAO,GAAG,UAAU,OAAO,CAAC;AAC9B;AA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ACP,0BAAkB;AAClB,mBAAW;AACX,sBAAc;AAAA,MAChB,SAAS,KAAK;AAKZ,cAAM,MAAM,OAAO,eAAe,QAAQ,IAAI,UAAU,GAAG;AAC3D,YAAI,QAAQ,aAAa;AACvB,cAAI,KAAK,uBAAuB,GAAG,EAAE;AACrC,wBAAc;AACd,oBAAU,WAAW,GAAG,UAAU,IAAI;AAAA,QACxC;AACA,oBAAY;AACZ,eAAO;AACP,0BAAkB;AAClB,aAAK,IAAI;AAAA,MACX;AAAA,IACF;AAMA,UAAM,SAAS,aAAa,IAAI,UAAU,KAAK,IAAI,UAAU,KAAK,KAAK,IAAI,UAAU,CAAC,GAAG,cAAc;AACvG,aAAS;AACT,UAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,WAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC,KAAK,QAAQ,WAAW,KAAK,IAAI,IAAI,UAAU;AACjF,YAAM,MAAM,OAAO;AAAA,IACrB;AAAA,EACF;AAEA,UAAQ,IAAI,UAAU,QAAQ;AAC9B,UAAQ,IAAI,WAAW,SAAS;AAChC,MAAI,SAAS,MAAM;AACjB,UAAM,QAAQ,MAAM,KAAK,YAAY,iBAAiB;AACtD,QAAI,CAAC,MAAO,KAAI,KAAK,sCAAsC,KAAK,MAAM,oBAAoB,GAAI,CAAC,8CAAyC;AACxI,WAAO;AAAA,EACT;AACA,OAAK,IAAI;AACT,OAAK,QAAQ;AACb,MAAI,cAAc;AAChB,QAAI,KAAK,mBAAmB;AAC3B,KAAC,KAAK,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAChC;AACA,SAAO;AACT;","names":["path","AgentChatClient","resolve","AgentChatClient"]}
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
- import { I as IntegrationClient, H as HostProfile } from './served-manual-DZmEak4_.js';
2
- export { C as CheckManualOptions, b as Credentials, D as DEFAULT_API_BASE, c as DoctorCheck, d as DoctorContext, F as FAILED_CYCLE_OUTCOMES, e as INTEGRATION_STATUS_FILE, f as IntegrationCycle, g as IntegrationLastRun, a as IntegrationStatus, L as LEGACY_STATUS_FILE, h as MANUAL_FETCH_TIMEOUT_MS, i as MANUAL_MAX_BYTES, j as MANUAL_MAX_REDIRECTS, k as ManualCheck, l as ManualCheckState, M as ManualFetch, m as ManualSyncResult, n as ManualSyncState, P as PendingRegistration, R as REPEATED_FAILED_CYCLES, o as ResolveIdentityOptions, p as ResolvedIdentity, q as SOCKET_STATES, r as ServedManual, S as SocketState, s as StatusContext, t as SyncManualOptions, T as TextsStatus, V as Verdict, u as anchorLabelOf, v as checkManual, w as clearCredentials, x as clearIntegrationStatus, y as clearPending, z as clientHeadersOf, A as clientIdentityOf, B as clientNameOf, E as credentialsPath, G as describeManualSync, J as envApiKey, K as failedCyclesInARow, N as formatIntegrationStatus, O as fromKitResult, Q as integrationStatusAge, U as integrationStatusPath, W as pendingPath, X as readCredentials, Y as readIntegrationStatus, Z as readManualVersion, _ as readPending, $ as resolveIdentity, a0 as statePath, a1 as syncManual, a2 as writeCredentials, a3 as writeIntegrationStatus, a4 as writePending } from './served-manual-DZmEak4_.js';
1
+ import { I as IntegrationClient, H as HostProfile } from './served-manual-99vEOjJS.js';
2
+ export { C as CheckManualOptions, b as Credentials, D as DEFAULT_API_BASE, c as DoctorCheck, d as DoctorContext, F as FAILED_CYCLE_OUTCOMES, e as INTEGRATION_STATUS_FILE, f as IntegrationCycle, g as IntegrationLastRun, a as IntegrationStatus, L as LEGACY_STATUS_FILE, h as MANUAL_FETCH_TIMEOUT_MS, i as MANUAL_MAX_BYTES, j as MANUAL_MAX_REDIRECTS, k as ManualCheck, l as ManualCheckState, M as ManualFetch, m as ManualSyncResult, n as ManualSyncState, P as PendingRegistration, R as REPEATED_FAILED_CYCLES, o as ResolveIdentityOptions, p as ResolvedIdentity, q as SOCKET_STATES, r as ServedManual, S as SocketState, s as StatusContext, t as SyncManualOptions, T as TextsStatus, V as Verdict, u as anchorLabelOf, v as checkManual, w as clearCredentials, x as clearIntegrationStatus, y as clearPending, z as clientHeadersOf, A as clientIdentityOf, B as clientNameOf, E as credentialsPath, G as describeManualSync, J as envApiKey, K as failedCyclesInARow, N as formatIntegrationStatus, O as fromKitResult, Q as integrationStatusAge, U as integrationStatusPath, W as pendingPath, X as readCredentials, Y as readIntegrationStatus, Z as readManualVersion, _ as readPending, $ as resolveIdentity, a0 as statePath, a1 as syncManual, a2 as writeCredentials, a3 as writeIntegrationStatus, a4 as writePending } from './served-manual-99vEOjJS.js';
3
3
  import { AgentChatClient, Texts, TextsRuntime, integration } from 'agentchatme';
4
4
  import { z } from 'zod';
5
- export { D as DEFAULT_RUN_BUDGET_MS, k as DEFAULT_RUN_PROFILE, I as INTEGRATION_ENV, l as INTEGRATION_ENV_LEGACY, m as RUN_BUDGET_ENV, n as RUN_PROFILES, o as RUN_PROFILE_ENV, d as RunKind, c as RunOutcome, e as RunOutcomeState, f as RunPreflight, a as RunProfile, g as RunRequest, b as RunRunner, h as RunWake, i as RunnerFactory, j as RunnerIdentity, R as RunnerSource, p as integrationDisabled, q as integrationDisabledBy, r as isRunProfile, s as isRunnerFactory, t as resolveRunBudgetMs, u as resolveRunProfile } from './runner-BzgsiS3V.js';
5
+ export { D as DEFAULT_RUN_BUDGET_MS, k as DEFAULT_RUN_PROFILE, I as INTEGRATION_ENV, l as INTEGRATION_ENV_LEGACY, m as INTEGRATION_ENV_LEGACY_REMOVAL, n as RUN_BUDGET_ENV, o as RUN_PROFILES, p as RUN_PROFILE_ENV, d as RunKind, c as RunOutcome, e as RunOutcomeState, f as RunPreflight, a as RunProfile, g as RunRequest, b as RunRunner, h as RunWake, i as RunnerFactory, j as RunnerIdentity, R as RunnerSource, q as integrationDisabled, r as integrationDisabledBy, s as isRunProfile, t as isRunnerFactory, u as resolveRunBudgetMs, v as resolveRunProfile } from './runner-B-ZZDAAm.js';
6
6
  import { spawn, spawnSync } from 'node:child_process';
7
7
 
8
8
  /** Published package version, kept in lockstep with package.json by tests. */
9
- declare const VERSION = "0.4.0";
9
+ declare const VERSION = "0.4.1";
10
10
 
11
11
  type TrayClient = Pick<AgentChatClient, 'inbox'>;
12
12
  interface TraySummary {
@@ -115,7 +115,7 @@ declare function manualPointer(location: string): string;
115
115
 
116
116
  /** The identity line, ready to place, from a served (or cached) texts response. */
117
117
  declare function identityLineOf(texts: Pick<Texts, 'identity_line'>): string;
118
- /** Handles are canonical lowercase on the wire; a leading `@` is display only. */
118
+ /** Handles are canonical lowercase on the wire; a leading `@` is display only. The kit's (`integration.anchor.normalizeHandle`). */
119
119
  declare function normalizeHandle(handle: string): string;
120
120
 
121
121
  /**
@@ -148,33 +148,67 @@ declare function renderUnregisteredBlock(copy: HostCopy): string;
148
148
  */
149
149
  declare function renderDeclinedBlock(copy: HostCopy): string;
150
150
 
151
- declare const ANCHOR_START = "<!-- agentchat:start -->";
152
- declare const ANCHOR_END = "<!-- agentchat:end -->";
153
- /** The identity block: the served identity line, as fetched for this agent, between the markers. */
154
- declare function renderAnchorBlock(identityLine: string): string;
151
+ declare const ANCHOR_START: string;
152
+ declare const ANCHOR_END: string;
153
+ /**
154
+ * The identity block for `handle`: the fences, the handle line and the served
155
+ * identity line. Throws when the handle is empty, when the line does not name
156
+ * `@handle` — a silently wrong identity is worse than a loud failure: the
157
+ * agent would hand peers an address that reaches someone else — or when a
158
+ * line of it is a marker. Nothing is written then.
159
+ */
160
+ declare function renderAnchorBlock(identityLine: string, handle: string): string;
155
161
  type AnchorAction = 'written' | 'removed' | 'noop';
156
162
  /**
157
- * Upsert `block` into the file at `filePath`, creating it if needed.
163
+ * Put `block` in the file at `filePath`, in place of the first AgentChat block
164
+ * of any known shape (every other one is removed), or after the file's own
165
+ * text when there is none. Creates the file if needed. The rest of the file is
166
+ * kept as it was, except that the blank lines next to the block become
167
+ * exactly one; the write is atomic (see `writeInstructionFile`).
158
168
  *
159
- * Throws if `expectHandle` is given and does not appear in what was written —
160
- * a silently-wrong identity block is worse than a loud failure, because the
161
- * agent would spend every session announcing an address that isn't its own.
169
+ * With `expectHandle`, throws — writing nothing — unless the block names that
170
+ * handle, and throws if the file does not read back as written.
162
171
  */
163
172
  declare function writeAnchor(filePath: string, block: string, expectHandle?: string): AnchorAction;
173
+ /** Remove every AgentChat block (current or legacy) from the file; the rest stays as it was. */
164
174
  declare function removeAnchorAt(filePath: string): AnchorAction;
175
+ /**
176
+ * Whether the file holds an AgentChat block of any known shape (the identity
177
+ * block, a legacy one, or the wizard's offer). Throws when the file exists but
178
+ * cannot be read (or is not UTF-8): that is not "no block".
179
+ */
165
180
  declare function hasAnchorAt(filePath: string): boolean;
166
- /** Whether the file's block is exactly the block for this served identity line. */
167
- declare function anchorIsCurrentAt(filePath: string, identityLine: string): boolean;
168
181
  /**
169
- * The handle a file's anchor block currently CLAIMS, or null if there is no
170
- * block. Lets an integration catch an anchor that disagrees with its own
171
- * credential — an agent told it is @a while authenticating as @b hands peers an
172
- * address that reaches someone else. Matched loosely precisely so a WRONG
173
- * value is still read back and reported rather than treated as "no anchor".
182
+ * Whether writing the block for this served identity line and handle would
183
+ * change nothing: the file holds exactly that block, in the kit's place, and
184
+ * no other AgentChat block. An older shape (no handle line, older words), a
185
+ * stale second block, or a block the kit would re-space is not current, so
186
+ * placement and `doctor --fix` rewrite it — after which it is current
187
+ * (`replace` is idempotent), so status and the doctor converge. Throws as
188
+ * `hasAnchorAt` does.
189
+ */
190
+ declare function anchorIsCurrentAt(filePath: string, identityLine: string, handle: string): boolean;
191
+ /**
192
+ * The handle a file's block currently CLAIMS, or null when there is no block
193
+ * or it names no handle that can be read (the wizard's offer, most
194
+ * hand-edited blocks). Lets an integration catch a block that disagrees with
195
+ * its own credential — an agent told it is @a while authenticating as @b
196
+ * hands peers an address that reaches someone else — so a WRONG handle is
197
+ * read back, not treated as "no anchor".
198
+ *
199
+ * `template` is the served `identity_line_template` (null when no texts are
200
+ * in hand): it recognises an unmarked block in whatever words the server
201
+ * serves today; without it, the handle line and the two wordings earlier
202
+ * releases wrote are still read. A hand-edited block whose words happen to
203
+ * follow one of those (`I am happy … on AgentChat`) reads as claiming that
204
+ * word: the kit's wording match does not require the `@`. Throws as
205
+ * `hasAnchorAt` does.
174
206
  */
175
- declare function readAnchorHandleAt(filePath: string): string | null;
176
- declare function readAnchorHandleFrom(text: string): string | null;
207
+ declare function readAnchorHandleAt(filePath: string, template: string | null): string | null;
208
+ declare function readAnchorHandleFrom(text: string, template: string | null): string | null;
209
+ /** `existing` with `block` in place of the first block (current or legacy) and every other block removed; `kit.anchor.replace`. */
177
210
  declare function upsertAnchorBlock(existing: string, block: string): string;
211
+ /** `existing` without any block (current or legacy); `kit.anchor.remove`. */
178
212
  declare function stripAnchorBlock(existing: string): string;
179
213
 
180
214
  declare const HOSTED_MCP_PATH: "/mcp";