@agentchatme/agent-core 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,91 @@
1
1
  import { TextsRuntime, AgentChatClientIdentity, integration } from 'agentchatme';
2
2
  import { z } from 'zod';
3
3
 
4
+ declare const LEASE_RENEW_MS = 10000;
5
+ declare const LEASE_STALE_MS = 45000;
6
+ /** Who holds a lease, as its file says. */
7
+ interface LeaseHolder {
8
+ readonly pid: number;
9
+ /** Null in a lock written before leases (a bare pid). */
10
+ readonly token: string | null;
11
+ readonly host: string | null;
12
+ readonly home?: string;
13
+ readonly label?: string;
14
+ readonly acquired_at?: string;
15
+ /** The holder's wall clock at its last renewal (informational: staleness is observed, not computed from it); null before leases. */
16
+ readonly renewed_at: number | null;
17
+ }
18
+ interface Lease {
19
+ readonly path: string;
20
+ /** True once the lease is no longer this process's (replaced, removed, unrenewable, or released). */
21
+ readonly lost: boolean;
22
+ /** Renewals that failed (an error writing or reading the file), and the last one's message. */
23
+ readonly renewErrors: number;
24
+ readonly lastRenewError: string | null;
25
+ /** Called once, when the lease is no longer this process's (not on `release`). */
26
+ onLost(listener: (why: string) => void): void;
27
+ /** Give the lease up (stop renewing; remove the file if it is still ours). Idempotent; never throws. */
28
+ release(): void;
29
+ }
30
+ type LeaseAttempt = {
31
+ readonly ok: true;
32
+ readonly lease: Lease;
33
+ } | {
34
+ readonly ok: false;
35
+ readonly path: string;
36
+ readonly holder: LeaseHolder | null;
37
+ };
38
+ interface LeaseOptions {
39
+ readonly renewMs?: number;
40
+ readonly staleMs?: number;
41
+ /** Test seam: the wall clock (for `renewed_at` and file ages). */
42
+ readonly now?: () => number;
43
+ /** Test seam: the monotonic clock (ms) staleness is observed on. Defaults to `performance.now()` (on macOS it runs on through sleep; hence the second look). */
44
+ readonly monotonic?: () => number;
45
+ /** Test seam: when this machine booted (epoch ms). */
46
+ readonly bootedAt?: () => number;
47
+ /**
48
+ * Keep observing a held lease for up to this long before refusing (default
49
+ * 0: one look). A holder seen renewing in that time is there: refused at once.
50
+ */
51
+ readonly observeMs?: number;
52
+ /** Stops the waits (observing, confirming): the attempt is refused. */
53
+ readonly signal?: AbortSignal;
54
+ }
55
+ /** When this machine booted (epoch ms): now minus its uptime. */
56
+ declare function bootedAt(now?: number): number;
57
+ /** Whether a pid names a live process (signal 0; EPERM means it exists under another user). */
58
+ declare function pidAlive(pid: number): boolean;
59
+ /** A lease file's holder: `<pid>\n{json}`, or a bare pid (a lock from before leases); null when it says neither. */
60
+ declare function parseLease(raw: string): LeaseHolder | null;
61
+ /**
62
+ * A one-look judgement (no history): for naming a holder and for the service
63
+ * reinstall, which stops the daemon a lock names only when it is really there.
64
+ * A dead pid on this host is gone; a lock from before leases is judged by its
65
+ * pid and the boot; a lease by a renewal within `staleMs` of this wall clock.
66
+ * Taking a lease over uses the observed rule (`acquireLease`), never this.
67
+ */
68
+ declare function holderLive(holder: LeaseHolder, at?: {
69
+ now?: number;
70
+ staleMs?: number;
71
+ mtimeMs?: number | null;
72
+ bootedAt?: number;
73
+ }): boolean;
74
+ /**
75
+ * Acquire the lease at `file`. Refused (naming the holder) while a holder is
76
+ * there; a stale one — by the observed rule, confirmed by a second look — is
77
+ * taken over under the guard. With `observeMs`, a held lease is watched that
78
+ * long before refusing. Async: it waits without blocking this process.
79
+ */
80
+ declare function acquireLease(file: string, info?: {
81
+ home?: string;
82
+ label?: string;
83
+ }, options?: LeaseOptions): Promise<LeaseAttempt>;
84
+ /** The holder of the lease at `file` by a one-look judgement (`holderLive`), or null. */
85
+ declare function leaseHolder(file: string, staleMs?: number): LeaseHolder | null;
86
+ /** Test seam: forget what this process has observed of leases. */
87
+ declare function resetLeaseObservations(): void;
88
+
4
89
  interface IntegrationClient {
5
90
  readonly runtime: TextsRuntime;
6
91
  readonly version: string;
@@ -58,6 +143,8 @@ interface IntegrationStatus {
58
143
  runtime: string | null;
59
144
  handle: string | null;
60
145
  profile: string;
146
+ /** The run workdir the daemon was given (absent in a file an older daemon wrote). */
147
+ workdir?: string;
61
148
  socket: SocketState;
62
149
  wakes: number;
63
150
  wakes_absorbed: number;
@@ -80,6 +167,57 @@ interface IntegrationStatus {
80
167
  recent_cycles?: IntegrationCycle[] | null;
81
168
  /** The socket's backpressure: true while it refuses new messages because handlers are behind (the kit's `intakePaused`); null from an older daemon. */
82
169
  intake_paused?: boolean | null;
170
+ /**
171
+ * Another daemon serves this agent (one agent, one listener): its identity
172
+ * home and pid. This one holds no socket and starts no run until it stops.
173
+ * Null or absent when this one serves it (or an older daemon wrote the file).
174
+ */
175
+ standby?: IntegrationStandby | null;
176
+ /**
177
+ * Runs keep failing and the runtime's own check says why (signed out, binary
178
+ * gone, a flag the installed version rejects): the check's words, since when,
179
+ * how many runs did not get done, when it was last checked. Cleared when a
180
+ * run succeeds. Null or absent when runs are fine (or an older daemon wrote the file).
181
+ */
182
+ runs_failing?: IntegrationRunsFailing | null;
183
+ /**
184
+ * This home gave its agent up because it cannot serve it — the server
185
+ * refuses its key, or its runs fail for a runtime reason while a healthy
186
+ * listener for the agent waits — and holds no socket until a recheck passes.
187
+ * Null or absent when it serves (or stands by for another).
188
+ */
189
+ unservable?: IntegrationUnservable | null;
190
+ /** Lock renewals that failed (the lock folder gone, a full disk, permissions), and the last message; null or absent when none did. */
191
+ lease_errors?: {
192
+ readonly count: number;
193
+ readonly last: string | null;
194
+ } | null;
195
+ }
196
+ interface IntegrationUnservable {
197
+ /** `key_refused`: the server refuses this home's key. `runs_failing`: the runtime's own check fails. */
198
+ readonly reason: 'key_refused' | 'runs_failing';
199
+ /** What was said: the refusal, or the runtime check's words. */
200
+ readonly detail: string;
201
+ /** When this home gave the agent up. */
202
+ readonly since: string;
203
+ /** When it checks again (the runtime first, for `runs_failing`). */
204
+ readonly retry_at: string;
205
+ }
206
+ interface IntegrationStandby {
207
+ /** The identity home of the daemon that serves the agent, as its lock says. */
208
+ readonly home: string | null;
209
+ readonly pid: number | null;
210
+ readonly since: string | null;
211
+ }
212
+ interface IntegrationRunsFailing {
213
+ /** The runtime's own check (preflight), in its words. */
214
+ readonly reason: string;
215
+ /** When the first of the failing runs ended. */
216
+ readonly since: string;
217
+ /** Runs that did not get done since then (each one a wake cycle that started a run). */
218
+ readonly runs_missed: number;
219
+ /** When the runtime was last checked. */
220
+ readonly checked_at: string;
83
221
  }
84
222
  /** One wake cycle as the status file keeps it: what it found and how it ended. Counts and outcomes only. */
85
223
  interface IntegrationCycle {
@@ -199,6 +337,12 @@ interface DoctorCheck {
199
337
  /** What the shared `status` hands a host's extra lines: what it already fetched from the served texts (one fetch per command). */
200
338
  interface StatusContext {
201
339
  identityLine: string | null;
340
+ /**
341
+ * The served `identity_line_template` from the same texts, or null when none
342
+ * are in hand: what `readAnchorHandleAt` recognises an unmarked block by, in
343
+ * whatever words the server serves today.
344
+ */
345
+ identityLineTemplate: string | null;
202
346
  /** The manual the served texts announce (`texts.manual`), or null when none are in hand — what `checkManual` compares the skill file with. */
203
347
  manual: ServedManual | null;
204
348
  }
@@ -207,6 +351,8 @@ interface DoctorContext {
207
351
  fix?: boolean;
208
352
  /** The served identity line for this agent, or null when the server could not be reached and nothing is cached. */
209
353
  identityLine: string | null;
354
+ /** The served `identity_line_template`, or null when none are in hand (see `StatusContext`). */
355
+ identityLineTemplate: string | null;
210
356
  /** The manual the served texts announce, or null when none are in hand (`--fix` syncs the skill file to it). */
211
357
  manual: ServedManual | null;
212
358
  }
@@ -244,8 +390,12 @@ interface HostProfile {
244
390
  anchorFile?(): string;
245
391
  /** Exactly what a user types to reach this integration. */
246
392
  invocation(): string;
247
- /** Render the anchor block body this host wants from the served identity line (normally `renderAnchorBlock`). */
248
- renderAnchor(identityLine: string): string;
393
+ /**
394
+ * The identity block this host places for `handle` from the served identity
395
+ * line (normally `renderAnchorBlock`, the kit's shape with the handle line).
396
+ * Throws when the line does not name the handle; nothing is written then.
397
+ */
398
+ renderAnchor(identityLine: string, handle: string): string;
249
399
  /**
250
400
  * What to call the anchor in output. Defaults to the instruction file's own
251
401
  * basename (`CLAUDE.md`, `AGENTS.md`), which is what a user actually looks
@@ -365,4 +515,4 @@ interface CheckManualOptions {
365
515
  /** Compare the skill file with the announced manual. Reads one file; no network. */
366
516
  declare function checkManual(options: CheckManualOptions): ManualCheck;
367
517
 
368
- export { resolveIdentity as $, clientIdentityOf as A, clientNameOf as B, type CheckManualOptions as C, DEFAULT_API_BASE as D, credentialsPath as E, FAILED_CYCLE_OUTCOMES as F, describeManualSync as G, type HostProfile as H, type IntegrationClient as I, envApiKey as J, failedCyclesInARow as K, LEGACY_STATUS_FILE as L, type ManualFetch as M, formatIntegrationStatus as N, fromKitResult as O, type PendingRegistration as P, integrationStatusAge as Q, REPEATED_FAILED_CYCLES as R, type SocketState as S, type TextsStatus as T, integrationStatusPath as U, type Verdict as V, pendingPath as W, readCredentials as X, readIntegrationStatus as Y, readManualVersion as Z, readPending as _, type IntegrationStatus as a, statePath as a0, syncManual as a1, writeCredentials as a2, writeIntegrationStatus as a3, writePending as a4, type Credentials as b, type DoctorCheck as c, type DoctorContext as d, INTEGRATION_STATUS_FILE as e, type IntegrationCycle as f, type IntegrationLastRun as g, MANUAL_FETCH_TIMEOUT_MS as h, MANUAL_MAX_BYTES as i, MANUAL_MAX_REDIRECTS as j, type ManualCheck as k, type ManualCheckState as l, type ManualSyncResult as m, type ManualSyncState as n, type ResolveIdentityOptions as o, type ResolvedIdentity as p, SOCKET_STATES as q, type ServedManual as r, type StatusContext as s, type SyncManualOptions as t, anchorLabelOf as u, checkManual as v, clearCredentials as w, clearIntegrationStatus as x, clearPending as y, clientHeadersOf as z };
518
+ export { envApiKey as $, type ServedManual as A, type StatusContext as B, type CheckManualOptions as C, DEFAULT_API_BASE as D, type SyncManualOptions as E, FAILED_CYCLE_OUTCOMES as F, acquireLease as G, type HostProfile as H, type IntegrationClient as I, anchorLabelOf as J, bootedAt as K, type LeaseOptions as L, type ManualFetch as M, checkManual as N, clearCredentials as O, type PendingRegistration as P, clearIntegrationStatus as Q, REPEATED_FAILED_CYCLES as R, type SocketState as S, type TextsStatus as T, clearPending as U, type Verdict as V, clientHeadersOf as W, clientIdentityOf as X, clientNameOf as Y, credentialsPath as Z, describeManualSync as _, type IntegrationStatus as a, failedCyclesInARow as a0, formatIntegrationStatus as a1, fromKitResult as a2, holderLive as a3, integrationStatusAge as a4, integrationStatusPath as a5, leaseHolder as a6, parseLease as a7, pendingPath as a8, pidAlive as a9, readCredentials as aa, readIntegrationStatus as ab, readManualVersion as ac, readPending as ad, resetLeaseObservations as ae, resolveIdentity as af, statePath as ag, syncManual as ah, writeCredentials as ai, writeIntegrationStatus as aj, writePending as ak, type IntegrationRunsFailing as b, type Lease as c, type LeaseAttempt as d, type LeaseHolder as e, type Credentials as f, type DoctorCheck as g, type DoctorContext as h, INTEGRATION_STATUS_FILE as i, type IntegrationCycle as j, type IntegrationLastRun as k, type IntegrationStandby as l, type IntegrationUnservable as m, LEASE_RENEW_MS as n, LEASE_STALE_MS as o, LEGACY_STATUS_FILE as p, MANUAL_FETCH_TIMEOUT_MS as q, MANUAL_MAX_BYTES as r, MANUAL_MAX_REDIRECTS as s, type ManualCheck as t, type ManualCheckState as u, type ManualSyncResult as v, type ManualSyncState as w, type ResolveIdentityOptions as x, type ResolvedIdentity as y, SOCKET_STATES as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentchatme/agent-core",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Shared host-agnostic engine for AgentChat integrations — the resident supervisor on the AgentChat SDK's integration kit (single-run mode: the socket acking on receipt, wakes, the tray before every run), the runner seam and spawnRun, the presets for known coding agents' headless runs, identity storage and flows, service plumbing. Runtime code only; every function takes an identity home, none resolves one.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,26 +0,0 @@
1
- import {
2
- clientIdentityOf
3
- } from "./chunk-NCSF3CCV.js";
4
-
5
- // src/integration/mcp-probe.ts
6
- import { integration as kit } from "agentchatme";
7
- var HOSTED_MCP_PATH = kit.HOSTED_MCP_PATH;
8
- function hostedMcpUrl(apiBase) {
9
- return kit.hostedMcpUrl(apiBase);
10
- }
11
- async function probeHostedMcp(params) {
12
- return kit.probeHostedTools({
13
- apiBase: params.apiBase,
14
- apiKey: params.apiKey,
15
- clientIdentity: clientIdentityOf(params.client),
16
- ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
17
- ...params.fetch !== void 0 ? { fetch: params.fetch } : {}
18
- });
19
- }
20
-
21
- export {
22
- HOSTED_MCP_PATH,
23
- hostedMcpUrl,
24
- probeHostedMcp
25
- };
26
- //# sourceMappingURL=chunk-HOY2FERJ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/integration/mcp-probe.ts"],"sourcesContent":["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":";;;;;AAAA,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,139 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/client-identity.ts
8
- function clientNameOf(client) {
9
- return client.name ?? client.runtime;
10
- }
11
- function clientIdentityOf(client) {
12
- return { name: clientNameOf(client), version: client.version };
13
- }
14
- function clientHeadersOf(client) {
15
- return {
16
- "X-AgentChat-Client": clientNameOf(client),
17
- "X-AgentChat-Client-Version": client.version
18
- };
19
- }
20
-
21
- // src/util/fsutil.ts
22
- import { randomBytes } from "crypto";
23
- import * as fs from "fs";
24
- import * as path from "path";
25
- function tmpPathFor(file) {
26
- return path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
27
- }
28
- var RENAME_RETRY_CODES = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
29
- var RENAME_ATTEMPTS = 6;
30
- var RENAME_DELAY_MS = 20;
31
- function sleepSync(ms) {
32
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
33
- }
34
- function renameWithRetry(from, to, options = {}) {
35
- const rename = options.rename ?? ((a, b) => fs.renameSync(a, b));
36
- const retry = options.retry ?? process.platform === "win32";
37
- const attempts = retry ? options.attempts ?? RENAME_ATTEMPTS : 1;
38
- for (let attempt = 1; ; attempt++) {
39
- try {
40
- rename(from, to);
41
- return;
42
- } catch (err) {
43
- const code = err.code;
44
- if (attempt >= attempts || code === void 0 || !RENAME_RETRY_CODES.has(code)) throw err;
45
- sleepSync(options.delayMs ?? RENAME_DELAY_MS);
46
- }
47
- }
48
- }
49
- function removeQuietly(file) {
50
- try {
51
- fs.rmSync(file, { force: true });
52
- } catch {
53
- }
54
- }
55
- function atomicWriteFile(filePath, data, mode) {
56
- const dir = path.dirname(filePath);
57
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
58
- const tmp = tmpPathFor(filePath);
59
- try {
60
- const fd = fs.openSync(tmp, "wx", mode ?? 438);
61
- try {
62
- if (mode !== void 0) fs.fchmodSync(fd, mode);
63
- fs.writeFileSync(fd, data);
64
- fs.fsyncSync(fd);
65
- } finally {
66
- fs.closeSync(fd);
67
- }
68
- renameWithRetry(tmp, filePath);
69
- } catch (err) {
70
- removeQuietly(tmp);
71
- throw err;
72
- }
73
- }
74
- function atomicCopyFile(source, destination, mode = 493) {
75
- const dir = path.dirname(destination);
76
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
77
- const tmp = tmpPathFor(destination);
78
- try {
79
- fs.copyFileSync(source, tmp, fs.constants.COPYFILE_EXCL);
80
- const fd = fs.openSync(tmp, fs.constants.O_RDWR | (fs.constants.O_NOFOLLOW ?? 0));
81
- try {
82
- fs.fchmodSync(fd, mode);
83
- fs.fsyncSync(fd);
84
- } finally {
85
- fs.closeSync(fd);
86
- }
87
- renameWithRetry(tmp, destination);
88
- } catch (err) {
89
- removeQuietly(tmp);
90
- throw err;
91
- }
92
- }
93
- function readJsonFile(filePath) {
94
- try {
95
- const raw = fs.readFileSync(filePath, "utf-8");
96
- return JSON.parse(raw);
97
- } catch {
98
- return null;
99
- }
100
- }
101
-
102
- // src/util/log.ts
103
- var LEVELS = ["silent", "error", "warn", "info", "debug"];
104
- function activeLevel() {
105
- const raw = (process.env["AGENTCHAT_LOG_LEVEL"] ?? "warn").toLowerCase();
106
- const idx = LEVELS.indexOf(raw);
107
- return idx === -1 ? LEVELS.indexOf("warn") : idx;
108
- }
109
- function emit(level, msg) {
110
- if (LEVELS.indexOf(level) <= activeLevel() && level !== "silent") {
111
- process.stderr.write(`[agentchat:${level}] ${msg}
112
- `);
113
- }
114
- }
115
- var log = {
116
- error: (msg) => emit("error", msg),
117
- warn: (msg) => emit("warn", msg),
118
- info: (msg) => emit("info", msg),
119
- debug: (msg) => emit("debug", msg)
120
- };
121
-
122
- // src/util/spawn.ts
123
- import crossSpawn from "cross-spawn";
124
- var spawnCommand = crossSpawn;
125
- var spawnCommandSync = crossSpawn.sync;
126
-
127
- export {
128
- __export,
129
- clientNameOf,
130
- clientIdentityOf,
131
- clientHeadersOf,
132
- atomicWriteFile,
133
- atomicCopyFile,
134
- readJsonFile,
135
- log,
136
- spawnCommand,
137
- spawnCommandSync
138
- };
139
- //# sourceMappingURL=chunk-NCSF3CCV.js.map
@@ -1 +0,0 @@
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// 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`. */\nfunction tmpPathFor(file: string): string {\n return path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${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;AAkBtB,SAAS,WAAW,MAAsB;AACxC,SAAY,UAAU,aAAQ,IAAI,GAAG,IAAS,cAAS,IAAI,CAAC,IAAI,QAAQ,GAAG,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,MAAM;AACrH;AAEA,IAAM,qBAAqB,oBAAI,IAAI,CAAC,SAAS,SAAS,QAAQ,CAAC;AAC/D,IAAM,kBAAkB;AACxB,IAAM,kBAAkB;AAExB,SAAS,UAAU,IAAkB;AACnC,UAAQ,KAAK,IAAI,WAAW,IAAI,kBAAkB,CAAC,CAAC,GAAG,GAAG,GAAG,EAAE;AACjE;AAYO,SAAS,gBAAgB,MAAc,IAAY,UAA8B,CAAC,GAAS;AAChG,QAAM,SAAS,QAAQ,WAAW,CAAC,GAAW,MAAiB,cAAW,GAAG,CAAC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a,aAAU,cAAc,EAAE;AAChF,QAAI;AACF,MAAG,cAAW,IAAI,IAAI;AACtB,MAAG,aAAU,EAAE;AAAA,IACjB,UAAE;AACA,MAAG,aAAU,EAAE;AAAA,IACjB;AACA,oBAAgB,KAAK,WAAW;AAAA,EAClC,SAAS,KAAK;AACZ,kBAAc,GAAG;AACjB,UAAM;AAAA,EACR;AACF;AAEO,SAAS,aAAgB,UAA4B;AAC1D,MAAI;AACF,UAAM,MAAS,gBAAa,UAAU,OAAO;AAC7C,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;AChHA,IAAM,SAAS,CAAC,UAAU,SAAS,QAAQ,QAAQ,OAAO;AAG1D,SAAS,cAAsB;AAC7B,QAAM,OAAO,QAAQ,IAAI,qBAAqB,KAAK,QAAQ,YAAY;AACvE,QAAM,MAAM,OAAO,QAAQ,GAAe;AAC1C,SAAO,QAAQ,KAAK,OAAO,QAAQ,MAAM,IAAI;AAC/C;AAEA,SAAS,KAAK,OAAiB,KAAmB;AAChD,MAAI,OAAO,QAAQ,KAAK,KAAK,YAAY,KAAK,UAAU,UAAU;AAChE,YAAQ,OAAO,MAAM,cAAc,KAAK,KAAK,GAAG;AAAA,CAAI;AAAA,EACtD;AACF;AAEO,IAAM,MAAM;AAAA,EACjB,OAAO,CAAC,QAAgB,KAAK,SAAS,GAAG;AAAA,EACzC,MAAM,CAAC,QAAgB,KAAK,QAAQ,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 +0,0 @@
1
- {"version":3,"sources":["../src/integration/spawn-run.ts"],"sourcesContent":["import type { ChildProcess } from 'node:child_process'\nimport { spawnCommand, spawnCommandSync } from '../util/spawn.js'\nimport type { RunOutcome } from './runner.js'\nimport { log } from '../util/log.js'\n\n// ─── Spawning one headless run ──────────────────────────────────────────────\n//\n// Shared by every runner: start the runtime's headless command, feed it the\n// prompt, bound it, classify the exit. The run's OUTPUT IS DISCARDED — stdout\n// is counted, never kept, never parsed, never logged. A run's text can quote\n// peer messages, and the integration reads no message content, ever. The only\n// thing retained is a short, credential-redacted tail of stderr for the\n// failure diagnostic, because \"exited 1\" alone has cost days of debugging.\n//\n// Classification: `ok` on exit 0; `timed_out` when the budget killed it;\n// `failed` when it was interrupted or exited non-zero after writing to stdout;\n// `not_started` when it exited non-zero with NOTHING ON STDOUT — a signed-out\n// CLI, a bad flag, a missing config all print their complaint on stderr and\n// quit, and they are \"the runtime did not get going\", stderr or not. The\n// stderr tail rides along in the detail either way.\n//\n// The run is spawned as its own process group (detached) so the whole tree\n// can be signalled at once: on the budget, and when the integration is stopping\n// (`signal`) — a daemon that exits with a run still going orphans a model call\n// that nobody will read and that the restarted daemon would run again.\n\n// A run must never hang the worker that started it. Two ways a child can\n// outlive its own classification, both seen with real runtimes:\n//\n// * the run's process exits, but something it started still holds its\n// stdout/stderr (a helper spawned with inherited pipes, an MCP server\n// that daemonised): Node's `close` waits for every holder of the pipes,\n// so it never comes. After `exit`, `close` gets DRAIN_MS; then the\n// run's process group is signalled (SIGKILL), the pipes are dropped, and\n// the run is classified by the exit it did make. A process that left the\n// group (`setsid`, a daemonising helper) is not reached by that signal\n// and can survive the run; the pipes are let go either way. Windows has\n// no process groups: there the run's orphaned children are swept\n// (`sweepWindowsDescendants`, best effort). Observed on Windows: a child\n// that inherited the run's stdio does not keep it open past the run's\n// exit, so `close` usually comes and this path is the fallback.\n// * a SIGKILL that does not end it (a process that escaped the group with\n// `setsid` and still holds the pipes; a process stuck in the kernel):\n// ABANDON_MS after the SIGKILL the pipes are dropped, the child is\n// unref'd, and the run is classified `timed_out` / `failed` as the\n// budget or the interrupt said — the worker moves on.\n\nconst DEFAULT_GRACE_MS = 5_000\n/** After the run's process exited: how long its pipes get to close before the run is detached from them. */\nconst DEFAULT_DRAIN_MS = 2_000\n/** After the SIGKILL: how long before a run that still has not ended is abandoned. */\nconst DEFAULT_ABANDON_MS = 5_000\nconst STDERR_TAIL_CHARS = 400\n\nexport interface SpawnRunSpec {\n readonly command: string\n readonly args: readonly string[]\n readonly cwd: string\n readonly env: NodeJS.ProcessEnv\n /**\n * Run `command` through the platform shell (`/bin/sh -c`, `cmd.exe /d /s /c`)\n * with no `args`: for a command line the OWNER configured. Nothing derived\n * from a wake or a message is ever part of it.\n */\n readonly shell?: boolean\n /** Written to the child's stdin and closed; `null` closes stdin at once. */\n readonly stdin: string | null\n /** Kill past this. */\n readonly budgetMs: number\n /** SIGTERM first; SIGKILL this long after. */\n readonly graceMs?: number\n /** After the process exited, how long its pipes may stay open before the run is detached from them. */\n readonly drainMs?: number\n /** After the SIGKILL, how long before a run that has still not ended is abandoned. */\n readonly abandonMs?: number\n /**\n * Aborting it SIGTERMs the run's process group (SIGKILL after `graceMs`);\n * the outcome is `failed` with an \"interrupted\" detail.\n */\n readonly signal?: AbortSignal\n /** Called once when the child process has been spawned (`RunRequest.onStarted`). */\n readonly onStarted?: () => void\n}\n\n/** Strip anything key-shaped or terminal-styled from a diagnostic, and bound it. */\nexport function redactDiagnostic(value: string, max = STDERR_TAIL_CHARS): string {\n return value\n .replace(/\\u001B\\[[0-?]*[ -/]*[@-~]/g, '')\n .replace(/\\b(api[_ -]?key\\s*[:=]\\s*)\\S+/gi, '$1[redacted]')\n .replace(/\\b(Bearer)\\s+[A-Za-z0-9._~-]{8,}\\b/gi, '$1 [redacted]')\n .replace(/\\bac_[A-Za-z0-9_-]{8,}\\b/g, '[redacted AgentChat key]')\n .replace(/\\bsk-[A-Za-z0-9_-]{8,}\\b/g, '[redacted key]')\n .replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(-max)\n}\n\n/** Bounds every synchronous kill: a stuck `taskkill` must not hold the worker it protects. */\nconst KILL_TIMEOUT_MS = 5_000\n\nfunction killProcessTree(child: ChildProcess, signal: NodeJS.Signals): void {\n if (child.pid === undefined) return\n try {\n if (process.platform === 'win32') {\n // The tree under a live root. A root that has exited is not found by\n // taskkill (Windows keeps no tree for it); `sweepWindowsDescendants`\n // covers that case.\n spawnCommandSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], {\n windowsHide: true,\n stdio: 'ignore',\n timeout: KILL_TIMEOUT_MS,\n })\n } else {\n // Negative pid = the process group the child leads (spawned detached).\n process.kill(-child.pid, signal)\n }\n } catch {\n try {\n child.kill(signal)\n } catch {\n /* already gone */\n }\n }\n}\n\n/** Epoch ms → a Windows FILETIME (100 ns ticks since 1601), for PowerShell's `[DateTime]::FromFileTime`. */\nfunction fileTime(ms: number): string {\n return String((BigInt(Math.round(ms)) + 11_644_473_600_000n) * 10_000n)\n}\n\n/** What one Windows sweep saw and did, for the log line and for tests. */\nexport interface WindowsSweep {\n /** PowerShell's exit code; null when it was killed past its deadline or could not start. */\n readonly exitCode: number | null\n readonly timedOut: boolean\n /** Every child of the root the sweep saw, as `<pid> <created ISO>`, in or out of the window. */\n readonly candidates: string[]\n /** Pids it ran `taskkill /T /F` on, with taskkill's exit code. */\n readonly killed: Array<{ pid: number; code: number }>\n /** The window it used, ISO. */\n readonly window: string | null\n /** stderr, bounded. */\n readonly stderr: string\n}\n\n/** A cold PowerShell on a busy runner takes seconds to start (seen: ~30 s on windows-latest the first time); past this the sweep is given up. */\nexport const WINDOWS_SWEEP_TIMEOUT_MS = 60_000\n\n/**\n * Windows: kill the processes an exited run left behind — its direct\n * children, which keep the dead run's pid as their `ParentProcessId` (Windows\n * does not reparent), created while the run was alive (so a reused pid cannot\n * pick up a stranger's children), each with its own tree. Best effort, and\n * never waited for by the run: `spawnRun` only logs the result. A\n * `powershell -EncodedCommand` (no quoting to get wrong), bounded by\n * `timeoutMs`. Resolves null off Windows.\n */\nexport function sweepWindowsDescendants(\n rootPid: number,\n aliveFromMs: number,\n aliveUntilMs: number,\n options: { timeoutMs?: number } = {},\n): Promise<WindowsSweep | null> {\n if (process.platform !== 'win32' || !Number.isInteger(rootPid) || rootPid <= 0) return Promise.resolve(null)\n const script = [\n \"$ErrorActionPreference = 'Continue'\",\n // Progress records ('Preparing modules for first use') would reach stderr as CLIXML.\n \"$ProgressPreference = 'SilentlyContinue'\",\n `$from = [DateTime]::FromFileTime(${fileTime(aliveFromMs - 1_000)})`,\n `$until = [DateTime]::FromFileTime(${fileTime(aliveUntilMs + 1_000)})`,\n \"Write-Output ('window ' + $from.ToUniversalTime().ToString('o') + ' ' + $until.ToUniversalTime().ToString('o'))\",\n `foreach ($p in @(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${rootPid}')) {`,\n \" Write-Output ('candidate ' + $p.ProcessId + ' ' + $p.CreationDate.ToUniversalTime().ToString('o'))\",\n ' if ($p.CreationDate -ge $from -and $p.CreationDate -le $until) {',\n ' & taskkill.exe /T /F /PID $p.ProcessId 2>&1 | Out-Null',\n \" Write-Output ('kill ' + $p.ProcessId + ' ' + $LASTEXITCODE)\",\n ' }',\n '}',\n ].join('\\n')\n return new Promise<WindowsSweep>((resolve) => {\n let stdout = ''\n let stderr = ''\n let timedOut = false\n let done = false\n const finish = (exitCode: number | null): void => {\n if (done) return\n done = true\n clearTimeout(timer)\n const lines = stdout.split(/\\r?\\n/).map((l) => l.trim()).filter((l) => l.length > 0)\n resolve({\n exitCode,\n timedOut,\n candidates: lines.filter((l) => l.startsWith('candidate ')).map((l) => l.slice('candidate '.length)),\n killed: lines\n .filter((l) => l.startsWith('kill '))\n .map((l) => l.split(' '))\n .map(([, pid, code]) => ({ pid: Number(pid), code: Number(code) })),\n window: lines.find((l) => l.startsWith('window '))?.slice('window '.length) ?? null,\n stderr: redactDiagnostic(stderr),\n })\n }\n let sweeper: ChildProcess\n try {\n sweeper = spawnCommand(\n 'powershell.exe',\n ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],\n { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true },\n )\n } catch (err) {\n stderr = String(err)\n finish(null)\n return\n }\n const timer = setTimeout(() => {\n timedOut = true\n try {\n sweeper.kill()\n } catch {\n /* gone */\n }\n finish(null)\n }, options.timeoutMs ?? WINDOWS_SWEEP_TIMEOUT_MS)\n timer.unref?.()\n sweeper.stdout?.on('data', (c: Buffer | string) => {\n stdout = (stdout + String(c)).slice(-16_000)\n })\n sweeper.stderr?.on('data', (c: Buffer | string) => {\n stderr = (stderr + String(c)).slice(-4_000)\n })\n sweeper.on('error', (err) => {\n stderr += String(err)\n finish(null)\n })\n sweeper.on('close', (code) => finish(code))\n })\n}\n\n/** One line for the log: what a sweep found and did. */\nexport function describeWindowsSweep(sweep: WindowsSweep): string {\n const killed = sweep.killed.map((k) => `${k.pid} (taskkill ${k.code})`).join(', ') || 'none'\n return `windows leftover sweep: exit ${sweep.exitCode ?? (sweep.timedOut ? 'timed out' : 'none')}; window ${sweep.window ?? '?'}; children seen ${sweep.candidates.length > 0 ? sweep.candidates.join(', ') : 'none'}; killed ${killed}${sweep.stderr ? `; stderr: ${sweep.stderr}` : ''}`\n}\n\n/** Start the command, wait for it, classify. Never throws, and always resolves. */\nexport function spawnRun(spec: SpawnRunSpec): Promise<RunOutcome> {\n const started = Date.now()\n const graceMs = spec.graceMs ?? DEFAULT_GRACE_MS\n const drainMs = spec.drainMs ?? DEFAULT_DRAIN_MS\n const abandonMs = spec.abandonMs ?? DEFAULT_ABANDON_MS\n return new Promise<RunOutcome>((resolve) => {\n let settled = false\n let stdoutBytes = 0\n let stderrTail = ''\n let timedOut = false\n let interrupted = false\n let terminating = false\n let exited: { code: number | null; signal: NodeJS.Signals | null; at: number } | null = null\n const timers = new Set<ReturnType<typeof setTimeout>>()\n let onAbort: (() => void) | null = null\n let child: ChildProcess | null = null\n\n const later = (ms: number, fn: () => void): void => {\n const timer = setTimeout(() => {\n timers.delete(timer)\n fn()\n }, ms)\n timers.add(timer)\n }\n\n const finish = (outcome: Omit<RunOutcome, 'durationMs'>): void => {\n if (settled) return\n settled = true\n for (const timer of timers) clearTimeout(timer)\n timers.clear()\n if (onAbort) spec.signal?.removeEventListener('abort', onAbort)\n resolve({ ...outcome, durationMs: Date.now() - started })\n }\n\n /** Stop waiting on the child's pipes and let the event loop forget it. */\n const detach = (): void => {\n if (child === null) return\n for (const stream of [child.stdin, child.stdout, child.stderr]) {\n try {\n stream?.destroy()\n } catch {\n /* already gone */\n }\n }\n try {\n child.unref()\n } catch {\n /* already gone */\n }\n }\n\n /** The outcome for an exit the run did make; `note` says why `close` was not waited for. */\n const classify = (code: number | null, signal: NodeJS.Signals | null, note: string | null): Omit<RunOutcome, 'durationMs'> => {\n const tail = redactDiagnostic(stderrTail)\n const extra = `${note ? ` (${note})` : ''}${tail ? `: ${tail}` : ''}`\n if (timedOut) {\n return { state: 'timed_out', exitCode: code, detail: `run exceeded its ${Math.round(spec.budgetMs / 1000)} s budget and was killed${extra}` }\n }\n if (interrupted) {\n return { state: 'failed', exitCode: code, detail: `interrupted — the integration was stopping; the tray stays unread for the next run${extra}` }\n }\n if (code === 0) return note ? { state: 'ok', exitCode: 0, detail: note } : { state: 'ok', exitCode: 0 }\n const exit = code === null ? `signal ${signal ?? 'unknown'}` : `exit ${code}`\n // Nothing on stdout: the runtime did not get going (missing, refused\n // to start, auth gate). Whatever it complained about is in the tail.\n if (stdoutBytes === 0) return { state: 'not_started', exitCode: code, detail: `${exit} with nothing on stdout${extra}` }\n return { state: 'failed', exitCode: code, detail: `${exit}${extra}` }\n }\n\n if (spec.signal?.aborted) {\n finish({ state: 'not_started', exitCode: null, detail: 'interrupted before the runtime was started' })\n return\n }\n\n try {\n child = spawnCommand(spec.command, [...spec.args], {\n cwd: spec.cwd,\n env: spec.env,\n stdio: [spec.stdin === null ? 'ignore' : 'pipe', 'pipe', 'pipe'],\n detached: process.platform !== 'win32',\n windowsHide: true,\n ...(spec.shell === true ? { shell: true } : {}),\n })\n } catch (err) {\n finish({ state: 'not_started', exitCode: null, detail: redactDiagnostic(String(err)) })\n return\n }\n const proc: ChildProcess = child\n\n if (spec.onStarted) {\n const onStarted = spec.onStarted\n proc.once('spawn', () => {\n try {\n onStarted()\n } catch {\n /* the callback belongs to the caller; a failure there is not the run's */\n }\n })\n }\n\n proc.stdout?.on('data', (chunk: Buffer | string) => {\n stdoutBytes += chunk.length // counted, never kept\n })\n proc.stderr?.on('data', (chunk: Buffer | string) => {\n stderrTail = (stderrTail + String(chunk)).slice(-4 * STDERR_TAIL_CHARS)\n })\n // A pipe torn down under us (detach, a dying child) must never surface as\n // an unhandled 'error' event.\n proc.stdout?.on('error', () => undefined)\n proc.stderr?.on('error', () => undefined)\n\n if (spec.stdin !== null && proc.stdin) {\n proc.stdin.on('error', () => {\n /* the child closed stdin early; the exit code tells the story */\n })\n try {\n proc.stdin.write(spec.stdin)\n proc.stdin.end()\n } catch {\n /* handled by the close path */\n }\n }\n\n const terminate = (): void => {\n if (terminating || settled) return\n terminating = true\n killProcessTree(proc, 'SIGTERM')\n later(graceMs, () => {\n if (settled) return\n killProcessTree(proc, 'SIGKILL')\n later(abandonMs, () => {\n if (settled) return\n // Exited but the pipes stayed open: the drain timer owns that case.\n if (exited !== null) return\n detach()\n const tail = redactDiagnostic(stderrTail)\n const why = `the run did not end ${Math.round((graceMs + abandonMs) / 1000)} s after it was signalled (SIGKILL included) — abandoned so the next wake can run${tail ? `: ${tail}` : ''}`\n finish(\n timedOut\n ? { state: 'timed_out', exitCode: null, detail: `run exceeded its ${Math.round(spec.budgetMs / 1000)} s budget; ${why}` }\n : { state: 'failed', exitCode: null, detail: `interrupted — ${why}` },\n )\n })\n })\n }\n\n later(spec.budgetMs, () => {\n // A run that already exited ended inside its budget; only its pipes\n // are late, and the drain timer owns that.\n if (exited !== null) return\n timedOut = true\n terminate()\n })\n\n if (spec.signal) {\n onAbort = (): void => {\n if (settled) return\n interrupted = true\n terminate()\n }\n spec.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n proc.on('error', (err) => {\n finish({ state: 'not_started', exitCode: null, detail: redactDiagnostic(String(err)) })\n })\n\n proc.on('exit', (code, signal) => {\n exited = { code, signal, at: Date.now() }\n // `close` follows once every holder of the pipes is gone. A process the\n // run started that still holds them must not hold the worker.\n later(drainMs, () => {\n if (settled || exited === null) return\n // The run is over; what is left of it is a leftover: its process\n // group on POSIX; on Windows its orphaned children (no groups there).\n killProcessTree(proc, 'SIGKILL')\n if (proc.pid !== undefined) {\n // Never awaited: the run's outcome does not wait for the sweep.\n void sweepWindowsDescendants(proc.pid, started, exited.at).then((sweep) => {\n if (sweep !== null) (sweep.exitCode === 0 ? log.info : log.warn)(describeWindowsSweep(sweep))\n })\n }\n detach()\n finish(\n classify(\n exited.code,\n exited.signal,\n process.platform === 'win32'\n ? 'a process the run started kept its output open after it exited; its children were swept (taskkill) and the run detached from it — a process the sweep cannot see can survive'\n : 'a process the run started kept its output open after it exited; the run\\'s process group was signalled (SIGKILL) and the run detached from it — a process that left the group can survive',\n ),\n )\n })\n })\n\n proc.on('close', (code, signal) => {\n finish(classify(code, signal, null))\n })\n })\n}\n"],"mappings":";;;;;;;AA+CA,IAAM,mBAAmB;AAEzB,IAAM,mBAAmB;AAEzB,IAAM,qBAAqB;AAC3B,IAAM,oBAAoB;AAiCnB,SAAS,iBAAiB,OAAe,MAAM,mBAA2B;AAC/E,SAAO,MACJ,QAAQ,8BAA8B,EAAE,EACxC,QAAQ,mCAAmC,cAAc,EACzD,QAAQ,wCAAwC,eAAe,EAC/D,QAAQ,6BAA6B,0BAA0B,EAC/D,QAAQ,6BAA6B,gBAAgB,EACrD,QAAQ,mDAAmD,EAAE,EAC7D,QAAQ,QAAQ,GAAG,EACnB,KAAK,EACL,MAAM,CAAC,GAAG;AACf;AAGA,IAAM,kBAAkB;AAExB,SAAS,gBAAgB,OAAqB,QAA8B;AAC1E,MAAI,MAAM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