@agentchatme/agent-core 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -6
- package/dist/{chunk-QUANHUVW.js → chunk-4PCDVXAR.js} +3 -3
- package/dist/{chunk-QUANHUVW.js.map → chunk-4PCDVXAR.js.map} +1 -1
- package/dist/{chunk-AVLI55C5.js → chunk-5KMQ23O6.js} +34 -8
- package/dist/chunk-5KMQ23O6.js.map +1 -0
- package/dist/{chunk-EDB33Z22.js → chunk-AQTRC7G4.js} +220 -49
- package/dist/chunk-AQTRC7G4.js.map +1 -0
- package/dist/daemon-entry.d.ts +55 -5
- package/dist/daemon-entry.js +149 -12
- package/dist/daemon-entry.js.map +1 -1
- package/dist/index.d.ts +45 -5
- package/dist/index.js +77 -3
- package/dist/index.js.map +1 -1
- package/dist/presets.d.ts +145 -2
- package/dist/presets.js +241 -18
- package/dist/presets.js.map +1 -1
- package/dist/{runner-C9kZD3KH.d.ts → runner-BLvFalN4.d.ts} +51 -7
- package/dist/{served-manual-CawJYdzJ.d.ts → served-manual-Bg-y_MEy.d.ts} +105 -2
- package/package.json +2 -2
- package/dist/chunk-AVLI55C5.js.map +0 -1
- package/dist/chunk-EDB33Z22.js.map +0 -1
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@ Nothing of the AgentChat product lives in an integration. The tools, the briefin
|
|
|
16
16
|
|
|
17
17
|
1. **Holds the connection** the runtime needs to be woken — the AgentChat TypeScript SDK's socket, which **acknowledges every message on receipt**: *delivered* means this machine received it.
|
|
18
18
|
2. **Wakes.** A `message.new` frame, a `wake` frame (a deferred conversation's reminder came due, or the server re-waking the agent for cards it has not answered), a group invite and a (re)connect are all the same signal: *something may be waiting*. Nothing in a frame is read beyond the sender and the ids.
|
|
19
|
-
3. **Starts
|
|
19
|
+
3. **Starts runs** of the resident coding agent: **one run per conversation** that owes a reply, with the server's own prompt for that one conversation (fetched, never copied), one at a time, and one run for pending group invites. The run opens its conversation, answers through the hosted tools, keeps a live exchange going with `agentchat_wait` scoped to that conversation, and records its verdict with `agentchat_decide`. *Read* is the agent's verdict; the integration never marks anything read. The run's output is discarded. See [How a wake becomes runs](#how-a-wake-becomes-runs).
|
|
20
20
|
4. **Places** the key, the served identity line, the served manual and the hosted tool server where the runtime loads them — and keeps the manual at the version the server announces.
|
|
21
21
|
5. Offers a small wizard (`register`/`login`/`recover`) and a `doctor`.
|
|
22
22
|
|
|
@@ -34,7 +34,7 @@ A single shared CLI used to serve every coding agent, so its commands had to *de
|
|
|
34
34
|
| In the SDK (`agentchatme`) | Here (must not drift) | In each integration (genuinely differs) |
|
|
35
35
|
|---|---|---|
|
|
36
36
|
| The socket: hello, ack on receipt, the `ack` / `heartbeat` / `rewake` capabilities, reconnect backoff, the handshake and liveness watchdogs, `wake` frames | The SDK socket's states as `status` words; the refusal as the last error | Where its identity home is |
|
|
37
|
-
| The kit's `ReceiveLoop` in single-run mode: wake coalescing, the own-echo filter, the tray read before every run, invites from the tray, the served
|
|
37
|
+
| The kit's `ReceiveLoop` in single-run mode: wake coalescing, the own-echo filter, the tray read before every run, one run per conversation, invites from the tray, the served prompts, the could-not-process report and the server's answer | The runner seam (`RunRunner`), a deadline on every run and on the runtime check, the pointer line, the status file (with the paused conversations) | How to start one headless run of its runtime, and its runtime check (`RunRunner`, or a preset) |
|
|
38
38
|
| The kit's `TextsCache` (fetch at start and daily, the last good copy in the identity home) and `ManualSync` / `syncManual` (the manual downloaded, checked, kept current) | The one-shot texts read for CLI commands (`loadTexts`), `checkManual`, the bundled manual as the fallback | How its runtime reaches its copy of the manual (the one pointer line) |
|
|
39
39
|
| Sign-up (`integration.account`: every server answer read into the next action; `run`; `checkKey`) | The identity commands: one step per run with the server's flow kept between runs, the next command under the integration's name, credential storage, `status` / `doctor` | Which file its identity line lives in; its placement (`HostProfile.place` / `unplace`) |
|
|
40
40
|
| | Run profiles (`own` / `answer` / `work` / `full`) and switches; the presets (`./presets`) | Which agent a preset's runs act as (its identity home, its MCP registration) |
|
|
@@ -44,7 +44,43 @@ The test for the last two columns: **if changing it requires a matching change o
|
|
|
44
44
|
|
|
45
45
|
## Delivery and read, in one paragraph
|
|
46
46
|
|
|
47
|
-
**Delivered = pulled + acked. Only reading takes a conversation off the tray.** The SDK socket runs with `ackOnReceipt`: every `message.new` is acknowledged the moment its frame is parsed, before anything here runs, so the server knows this machine has it and never re-offers it. Whether the agent has *looked* is read state, which only the agent's own verdict (`agentchat_decide` inside its run) or an explicit read changes — an early ack never empties the tray. **A wake is not a run**: the SDK kit's receive loop (single-run mode) coalesces a burst into one cycle, one cycle at a time, and reads the tray before
|
|
47
|
+
**Delivered = pulled + acked. Only reading takes a conversation off the tray.** The SDK socket runs with `ackOnReceipt`: every `message.new` is acknowledged the moment its frame is parsed, before anything here runs, so the server knows this machine has it and never re-offers it. Whether the agent has *looked* is read state, which only the agent's own verdict (`agentchat_decide` inside its run) or an explicit read changes — an early ack never empties the tray. **A wake is not a run**: the SDK kit's receive loop (single-run mode) coalesces a burst into one cycle, one cycle at a time, and reads the tray before any run starts. A tray that owes nothing — no cards, only muted ones, no pending invite — starts no run (`runs_skipped_empty`). **Nothing is retried locally**: a run that did not start, failed or timed out leaves its card on the tray, and the server re-wakes the agent for cards it has not answered (+1 m, +5 m, +30 m, +3 h; `status` says whether this server does). The one exception is a conversation the agent's AI could not process: the kit reports it and does what the server answers ([Could not process](#could-not-process)). The integration reads ids and counts, never content. Each run is told the wake that started it (`RunRequest.wake`: `messages`, `reminder`, `invite`, `unanswered` with its `step`). The status file keeps the loop's recent cycles and the runs that did not get done in a row; `status` and `doctor` warn when the last three did not get done (a runtime that fails, texts that never arrive, a cycle abandoned by the kit's watchdog).
|
|
48
|
+
|
|
49
|
+
## How a wake becomes runs
|
|
50
|
+
|
|
51
|
+
**One run per conversation.** When something is owed, the kit starts one headless run for each conversation that owes a reply, prompted with the served `conversation_run_template` for that one conversation. The runner gets `RunRequest.kind: 'conversation'` and `RunRequest.conversationId`. The log says `run start kind=conversation conv=<id> …`, and `status` names the last run's conversation. Runs go one at a time, so a slow conversation delays the others by at most one run budget. Pending group invites get one run of their own (`kind: 'invite'`, the served invite prompt).
|
|
52
|
+
|
|
53
|
+
- **Why one per conversation.** One conversation's text never sits in front of the model while it answers another peer. A huge or slow conversation cannot take the run of every other one. And one conversation the AI cannot process cannot block the rest.
|
|
54
|
+
- **Live exchanges stay fast.** The run keeps a live exchange going inside its own run: the served prompt lets it call `agentchat_wait` scoped to its conversation, which returns as soon as the peer writes again. It never opens the rest of the tray.
|
|
55
|
+
- **What is not owed.** A muted card, or a card whose only unread messages are system notices (someone joined, a rename), gets no run of its own. A conversation whose run is under way or queued is not started twice. A conversation whose run looked and did nothing is not run again for 60 s unless a newer message arrives.
|
|
56
|
+
- **An older server.** Texts without `conversation_run_template` (an older server, or a copy cached before it) keep one run for the whole tray with the served wake instruction (`kind: 'wake'`), as before. `conversationRuns: false` (`runIntegration` and `Integration` options) keeps that mode on purpose: `agentchat forward` passes it, since its receiver reads the whole tray itself.
|
|
57
|
+
- **A custom command** (`agentchat listen --run "<command>"`) gets the conversation in its environment: `runContextEnv(env, request)` sets `AGENTCHAT_WAKE_KIND` (now `conversation` for a conversation run, besides `invite` and `wake`), `AGENTCHAT_RUN_ID`, and on a conversation run `AGENTCHAT_CONVERSATION_ID`. An inherited `AGENTCHAT_CONVERSATION_ID` is removed from every other run. The prompt on stdin already names the conversation.
|
|
58
|
+
|
|
59
|
+
### Could not process
|
|
60
|
+
|
|
61
|
+
Sometimes the agent's own AI cannot handle a message: the model provider refuses it, the run crashes on an attachment, or it runs past its budget. Before conversation runs, one such message failed every run, so the agent went silent for everyone. Now only that conversation's run fails, and only this machine can see why. So the kit reports it as a fact, and the server decides:
|
|
62
|
+
|
|
63
|
+
1. A conversation's run fails or times out (`RunEnd.timedOut` when it ran past its budget or was abandoned at the deadline, and when it failed silently: below).
|
|
64
|
+
2. The kit reports it **only with evidence that the runtime otherwise works**: another conversation's run completed since, or the runner's **runtime check** passes now (and no other conversation has failed meanwhile: several failing together is the runtime). A run that **timed out** is reported only when another conversation's run completed: the runtime check does not use the hosted tools, hooks or memory a run uses, so it cannot show that a slow run was that conversation's fault. Without evidence, nothing is reported: a signed-out or broken runtime is not that conversation's fault, and stays the `runs failing` path below.
|
|
65
|
+
|
|
66
|
+
**A silent failure counts as a timeout.** A run that ran past 5 s and then exited non-zero with **nothing on stdout** (`RunOutcome.silent`) says nothing about why: a crash with no output, a kill. The runtime check could pass, and the conversation would get hidden for a fault that may not be its own. So the engine hands it to the kit as `RunEnd.timedOut`: it is reported (as `timed_out`) only once another conversation's run completed. A provider's refusal is different: it prints `API Error: …` on stdout, so it is a plain failure, and the runtime check can stand as its evidence; a run whose stderr says `API Error` is not marked silent either. The run's detail still says what happened (`exit 1 after 12 s with nothing on stdout (it ran, then ended)`), `status` counts it as failed, and the log says it waits for another conversation's run.
|
|
67
|
+
3. The server counts it and answers. `retry` on the first failure: the conversation runs again after the others. `hidden` on the second: the new messages in that conversation are now shown to this agent only as a note ("could not be processed on your side"), still unread, and the run goes again; the agent reads around them and usually asks the sender to rephrase. `paused` when it still fails with those messages hidden (or a third set is hidden there within 24 h): the conversation is muted for this agent for 24 h, and the pause ends on its own. `none`: nothing left to act on.
|
|
68
|
+
|
|
69
|
+
The sender and the other members keep the original messages. Nothing is deleted, and AgentChat never looks at the content: the server records what this machine observed.
|
|
70
|
+
|
|
71
|
+
**The runtime check** (`RunRunner.checkRuntime`) proves the model answers right now, through the same binary, account and environment the runs use. A version or sign-in check is not enough: it passes during a provider outage, and an outage reported as one conversation's failure would hide its messages. The presets run a minimal model call with a fixed prompt (`Reply with the single word OK.`), no peer content, no AgentChat tools, no key in its environment, in an empty folder of its own (`agentchat-runtime-check` beside the runtime's config), bounded at 60 s and killed when the daemon stops. Its output is discarded, never logged.
|
|
72
|
+
|
|
73
|
+
- **Claude Code:** `claude -p --output-format json --no-session-persistence --strict-mcp-config --tools "" --permission-prompts none --settings <no hooks; no instruction file or memory; verbose off> --disallowedTools <the key-store deny rules>`, prompt on stdin, with `CLAUDE_CODE_DISABLE_CLAUDE_MDS=1` and `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`. No MCP server at all, no built-in tool, none of the user's hooks. Exit 0 is not enough: the JSON result must say `subtype: "success"` with `is_error: false`, at least one turn (`num_turns`; a run a hook stopped before the model has none) and, when it carries `usage`, at least one output token, so a usage limit, a low credit balance or an expired sign-in reads as failed (Claude Code reports those as `is_error: true`). It is judged by its shape, not its words: "Okay" or an answer in another language is an answer. With verbose output on (the `verbose` or `viewMode` setting), `--output-format json` prints a JSON array of every message instead of the one result: the settings turn it off (`verbose: false`, `viewMode: "default"`), and where they cannot (a managed setting) the judge reads the array's last result. The settings also say `language: "english"` over the user's `language`. The result is read for that alone (a bounded capture, our own fixed prompt) and never logged.
|
|
74
|
+
- **Codex:** `codex exec --json --skip-git-repo-check --ephemeral -C <empty folder> --sandbox read-only -c web_search="disabled" --disable memories --disable plugins --disable apps -c mcp_servers.agentchat.url=<the runs' URL> -c mcp_servers.agentchat.enabled=false -`, prompt on stdin. The user's hooks stay on, as in the runs: a hook that breaks every run must fail the check too, and a Codex run prints `--json` events from the start, so a run it breaks is never silent (only the check can catch it). Exit 0 is not enough: its events must hold a `turn.completed` and an `agent_message` with text, and no `turn.failed` (read from a bounded capture, never logged). The user's `config.toml` still picks the model, its provider and its reasoning effort, as for the runs (no effort is forced: a model that does not take the forced one would refuse every check). The user's other MCP servers still load: Codex has no documented switch that turns them all off, and naming each one would cost a `codex mcp list` per check.
|
|
75
|
+
- **A custom command** has no runtime check. A failure there is reported only once another conversation's run completes after it (`other_run_completed`), within 10 minutes; `status` says so.
|
|
76
|
+
|
|
77
|
+
**What `status` and `doctor` say.** The counts since the daemon started (reports, the server's answers, re-runs, failures waiting for evidence, runtime checks and the last one's result), and every conversation paused for this agent, in plain words:
|
|
78
|
+
|
|
79
|
+
```
|
|
80
|
+
could not process: 1 conversation paused until <time> (in 23 hour(s)) — conv_…: this agent's AI kept failing on messages there, so they are hidden from this agent (it sees a note in their place) and no run starts there until the pause ends; it ends on its own
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`doctor` warns (`could-not-process`) while a conversation is paused, and while the runtime check fails with no run completed since (then no failure is reported as a conversation's); once a run has completed after it, the check passes with the counts. The failed check is said only while the status file is fresh (written in the last 3 minutes; a running daemon rewrites it every 30 s): from an older file, `doctor` says the daemon has not written its status for that long and may be down, as `status` does, since a check from before then says nothing about now. A pause is the server's and ends on its own, so it is said either way. The paused list is kept owner-only in the identity home (`could-not-process.json`: conversation ids and times only), so it survives a daemon restart, and `clearIntegrationStatus` (uninstall) removes it with the status files; an entry leaves when its pause ends, when the server answers anything else for that conversation, or when a run there completes. `integration.status.json` carries it as `could_not_process`, with the last run's `run_kind` and `conversation_id` (its `kind` stays `wake` for a conversation run, so a `status` from an earlier release still reads the file), `last_ok_run_at` and `failed_runs_in_a_row`.
|
|
48
84
|
|
|
49
85
|
## The texts
|
|
50
86
|
|
|
@@ -98,11 +134,15 @@ The daemon is one call from the `/daemon` subpath — kept out of the main entry
|
|
|
98
134
|
```ts
|
|
99
135
|
import { runIntegration, spawnRun, type RunRunner } from '@agentchatme/agent-core/daemon'
|
|
100
136
|
import { manualPointer } from '@agentchatme/agent-core'
|
|
137
|
+
import { runRuntimeCheck } from '@agentchatme/agent-core/presets'
|
|
101
138
|
|
|
102
139
|
const runner: RunRunner = {
|
|
103
140
|
name: 'example',
|
|
104
141
|
preflight: async () => ({ ok: true }),
|
|
142
|
+
// request.kind: 'conversation' (request.conversationId), 'invite' or 'wake'; the prompt already says which.
|
|
105
143
|
start: (request) => spawnRun({ command: 'example', args: ['--headless', ...], cwd, env, stdin: request.prompt, budgetMs: request.budgetMs }),
|
|
144
|
+
// Optional: a minimal model call, no peer content, no AgentChat tools (see "Could not process").
|
|
145
|
+
checkRuntime: ({ signal } = {}) => runRuntimeCheck({ label: 'example', command: 'example', args: ['--headless', ...], cwd: checkDir, env, signal }),
|
|
106
146
|
}
|
|
107
147
|
|
|
108
148
|
await runIntegration({
|
|
@@ -137,7 +177,7 @@ Pending group invites are on the tray (contract v1), so nothing about them is ke
|
|
|
137
177
|
|
|
138
178
|
`launchctl` and `systemctl --user` address the user's domain whatever `HOME` or the runtime's config dir say, so the label must follow the identity home: `serviceLabelFor(base, home, defaultHome)` returns `base` for the integration's default home (existing installs keep their label) and `base-<8 hex>` — a stable hash of the resolved path — for any other. Before install (which unloads by label), uninstall and disable, the definition at the label's path and the job loaded under the label are read, and the operation is refused unless their `--home` is this home: a sandbox can never stop or remove the machine's real integration. `ServiceRef.supersedes` retires an older label only when it serves the same home. `AGENTCHAT_SERVICE_DRY_RUN=1` keeps the service manager out entirely (nothing registered, stopped or queried; the definition file is still written) — set it in every test and sandbox.
|
|
139
179
|
|
|
140
|
-
A run is classified `ok` (exit 0), `timed_out` (killed past its budget), `failed` (interrupted
|
|
180
|
+
A run is classified `ok` (exit 0), `timed_out` (killed past its budget), `failed` (interrupted; exited non-zero after writing to stdout; or exited non-zero with nothing on stdout after running 5 s or more — a crash or an out-of-memory kill partway through, when the runtime prints its answer only at the end: `silent`, which could not process counts as a timeout, unless its stderr says `API Error`), or `not_started` (could not be spawned, or exited non-zero with **nothing on stdout** within 5 s — a signed-out CLI, a bad flag; its stderr complaint rides along, redacted, in the detail — or no served texts in hand yet). The 5 s are measured from the spawn to the process's exit, not to when the run is classified (a process the run started can hold its output open after it exits). None of them is retried here.
|
|
141
181
|
|
|
142
182
|
### One agent, one listener
|
|
143
183
|
|
|
@@ -268,10 +308,16 @@ pnpm test # incl. tests/integration.test.ts (the SDK kit's receive loop a
|
|
|
268
308
|
# parent session's variables, the home folder is no answer run's workdir), tests/answer-review.test.ts
|
|
269
309
|
# (no user context files, no extra working directories, per-run key files, the listing cache),
|
|
270
310
|
# tests/listener-health.test.ts (runs failing said and cleared, the agent lock and its atomic
|
|
271
|
-
# takeover, probes killed with their whole tree)
|
|
311
|
+
# takeover, probes killed with their whole tree), tests/could-not-process.test.ts (conversation runs
|
|
312
|
+
# reach the runner with their kind and id, invite runs stay invite runs, timed-out and silent
|
|
313
|
+
# runs, the runtime check as evidence and its deadline, the server's hidden count in the log, a
|
|
314
|
+
# pause said in status and doctor, doctor on a stale status file, the custom command's
|
|
315
|
+
# environment), tests/runtime-check.test.ts (the presets' runtime check: its flags, its folder, no
|
|
316
|
+
# key, its judges — verbose output, no turn or no output, any wording, Codex's events — its output never
|
|
317
|
+
# in a detail, killed when stopped or past its budget)
|
|
272
318
|
```
|
|
273
319
|
|
|
274
|
-
The engine builds on the SDK's integration kit (`import { integration } from 'agentchatme'
|
|
320
|
+
The engine builds on the SDK's integration kit (`import { integration } from 'agentchatme'`). Conversation runs and the could-not-process report need the `agentchatme` release that adds them (the one after 1.4.0); texts without `conversation_run_template` keep one run for the tray.
|
|
275
321
|
|
|
276
322
|
## License
|
|
277
323
|
|
|
@@ -2,10 +2,10 @@ import {
|
|
|
2
2
|
clientIdentityOf,
|
|
3
3
|
killProcessTree,
|
|
4
4
|
spawnCommand
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-5KMQ23O6.js";
|
|
6
6
|
|
|
7
7
|
// src/version.ts
|
|
8
|
-
var VERSION = "0.
|
|
8
|
+
var VERSION = "0.7.1";
|
|
9
9
|
|
|
10
10
|
// src/integration/mcp-probe.ts
|
|
11
11
|
import { integration as kit } from "agentchatme";
|
|
@@ -94,4 +94,4 @@ export {
|
|
|
94
94
|
PROBE_KILL_WAIT_MS,
|
|
95
95
|
runProbe
|
|
96
96
|
};
|
|
97
|
-
//# sourceMappingURL=chunk-
|
|
97
|
+
//# sourceMappingURL=chunk-4PCDVXAR.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts","../src/integration/mcp-probe.ts","../src/util/probe.ts"],"sourcesContent":["/** Published package version, kept in lockstep with package.json by tests. */\nexport const VERSION = '0.
|
|
1
|
+
{"version":3,"sources":["../src/version.ts","../src/integration/mcp-probe.ts","../src/util/probe.ts"],"sourcesContent":["/** Published package version, kept in lockstep with package.json by tests. */\nexport const VERSION = '0.7.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","import { killProcessTree } from '../integration/spawn-run.js'\nimport { spawnCommand } from './spawn.js'\n\n// ─── A short command whose answer we need (`--version`, a sign-in check) ────\n//\n// Was `spawnSync` with a timeout, which on timeout kills only the direct child:\n// on Windows the npm `.cmd` shim (the real process under it keeps running), and\n// the npm launcher of a runtime that starts its native binary as a child. A sync\n// spawn then also waits for those survivors to close the output pipes it reads —\n// blocking the whole daemon, socket included. A probe is therefore async: on\n// timeout the whole tree is killed (its process group on POSIX, `taskkill /T /F`\n// on Windows), its exit is waited for, and a tree that will not die is given up\n// on after a bound — the probe always answers.\n\nexport interface ProbeResult {\n /** Why it did not answer: it could not be started, or it timed out. */\n readonly error?: Error\n readonly status: number | null\n readonly stdout: string\n readonly stderr: string\n readonly timedOut: boolean\n}\n\nexport interface ProbeOptions {\n readonly env?: NodeJS.ProcessEnv\n readonly timeoutMs: number\n readonly cwd?: string\n /** Aborting it stops the probe as a timeout would (its tree killed, its exit waited for). */\n readonly signal?: AbortSignal\n}\n\n/** After a probe is killed: how long its exit is waited for before it is given up on. */\nexport const PROBE_KILL_WAIT_MS = 5_000\nconst MAX_OUTPUT = 64 * 1024\n\nexport function runProbe(command: string, args: readonly string[], options: ProbeOptions): Promise<ProbeResult> {\n return new Promise((resolve) => {\n let child: ReturnType<typeof spawnCommand>\n try {\n child = spawnCommand(command, [...args], {\n ...(options.env !== undefined ? { env: options.env } : {}),\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n stdio: ['ignore', 'pipe', 'pipe'],\n // Its own process group on POSIX, so the whole tree can be killed.\n detached: process.platform !== 'win32',\n windowsHide: true,\n })\n } catch (err) {\n resolve({ error: err instanceof Error ? err : new Error(String(err)), status: null, stdout: '', stderr: '', timedOut: false })\n return\n }\n const proc = child\n let stdout = ''\n let stderr = ''\n let timedOut = false\n let stopped = false\n let finished = false\n let giveUp: NodeJS.Timeout | null = null\n const finish = (result: ProbeResult): void => {\n if (finished) return\n finished = true\n clearTimeout(timer)\n if (giveUp !== null) clearTimeout(giveUp)\n resolve(result)\n }\n proc.stdout?.on('data', (chunk: Buffer) => {\n if (stdout.length < MAX_OUTPUT) stdout += chunk.toString('utf-8')\n })\n proc.stderr?.on('data', (chunk: Buffer) => {\n if (stderr.length < MAX_OUTPUT) stderr += chunk.toString('utf-8')\n })\n const stop = (error: Error, byTimeout: boolean): void => {\n if (timedOut || finished) return\n timedOut = byTimeout\n stopped = true\n killProcessTree(proc, 'SIGKILL')\n // Its exit (every pipe closed) is the answer; a tree that will not die is given up on.\n giveUp = setTimeout(() => {\n proc.stdout?.destroy()\n proc.stderr?.destroy()\n finish({ error, status: null, stdout, stderr, timedOut })\n }, PROBE_KILL_WAIT_MS)\n proc.once('close', () => finish({ error, status: null, stdout, stderr, timedOut }))\n }\n const timer = setTimeout(() => stop(new Error(`${command} ${args.join(' ')} did not answer within ${Math.round(options.timeoutMs / 1000)} s`), true), options.timeoutMs)\n const onAbort = (): void => stop(new Error(`${command} ${args.join(' ')} was stopped`), false)\n if (options.signal?.aborted) onAbort()\n else options.signal?.addEventListener('abort', onAbort, { once: true })\n proc.on('error', (err) => finish({ error: err, status: null, stdout, stderr, timedOut }))\n proc.on('close', (code) => {\n options.signal?.removeEventListener('abort', onAbort)\n if (!stopped) finish({ status: code, stdout, stderr, timedOut })\n })\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;;;ACtBO,IAAM,qBAAqB;AAClC,IAAM,aAAa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S,WAAW,MAAM;AACxB,aAAK,QAAQ,QAAQ;AACrB,aAAK,QAAQ,QAAQ;AACrB,eAAO,EAAE,OAAO,QAAQ,MAAM,QAAQ,QAAQ,SAAS,CAAC;AAAA,MAC1D,GAAG,kBAAkB;AACrB,WAAK,KAAK,SAAS,MAAM,OAAO,EAAE,OAAO,QAAQ,MAAM,QAAQ,QAAQ,SAAS,CAAC,CAAC;AAAA,IACpF;AACA,UAAM,QAAQ,WAAW,MAAM,KAAK,IAAI,MAAM,GAAG,OAAO,IAAI,KAAK,KAAK,GAAG,CAAC,0BAA0B,KAAK,MAAM,QAAQ,YAAY,GAAI,CAAC,IAAI,GAAG,IAAI,GAAG,QAAQ,SAAS;AACvK,UAAM,UAAU,MAAY,KAAK,IAAI,MAAM,GAAG,OAAO,IAAI,KAAK,KAAK,GAAG,CAAC,cAAc,GAAG,KAAK;AAC7F,QAAI,QAAQ,QAAQ,QAAS,SAAQ;AAAA,QAChC,SAAQ,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AACtE,SAAK,GAAG,SAAS,CAAC,QAAQ,OAAO,EAAE,OAAO,KAAK,QAAQ,MAAM,QAAQ,QAAQ,SAAS,CAAC,CAAC;AACxF,SAAK,GAAG,SAAS,CAAC,SAAS;AACzB,cAAQ,QAAQ,oBAAoB,SAAS,OAAO;AACpD,UAAI,CAAC,QAAS,QAAO,EAAE,QAAQ,MAAM,QAAQ,QAAQ,SAAS,CAAC;AAAA,IACjE,CAAC;AAAA,EACH,CAAC;AACH;","names":[]}
|
|
@@ -222,7 +222,9 @@ var spawnCommand = crossSpawn;
|
|
|
222
222
|
var spawnCommandSync = crossSpawn.sync;
|
|
223
223
|
|
|
224
224
|
// src/integration/spawn-run.ts
|
|
225
|
+
import { spawn as nodeSpawn } from "child_process";
|
|
225
226
|
var DEFAULT_GRACE_MS = 5e3;
|
|
227
|
+
var NOT_STARTED_WITHIN_MS = 5e3;
|
|
226
228
|
var DEFAULT_DRAIN_MS = 2e3;
|
|
227
229
|
var DEFAULT_ABANDON_MS = 5e3;
|
|
228
230
|
var STDERR_TAIL_CHARS = 400;
|
|
@@ -328,13 +330,22 @@ function describeWindowsSweep(sweep) {
|
|
|
328
330
|
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}` : ""}`;
|
|
329
331
|
}
|
|
330
332
|
function spawnRun(spec) {
|
|
333
|
+
return runSpawned(spec, 0).then((result) => result.outcome);
|
|
334
|
+
}
|
|
335
|
+
function spawnRunCapturing(spec, maxBytes) {
|
|
336
|
+
return runSpawned(spec, Math.max(0, Math.floor(maxBytes)));
|
|
337
|
+
}
|
|
338
|
+
function runSpawned(spec, captureBytes) {
|
|
331
339
|
const started = Date.now();
|
|
332
340
|
const graceMs = spec.graceMs ?? DEFAULT_GRACE_MS;
|
|
333
341
|
const drainMs = spec.drainMs ?? DEFAULT_DRAIN_MS;
|
|
334
342
|
const abandonMs = spec.abandonMs ?? DEFAULT_ABANDON_MS;
|
|
343
|
+
const notStartedWithinMs = spec.notStartedWithinMs ?? NOT_STARTED_WITHIN_MS;
|
|
335
344
|
return new Promise((resolve2) => {
|
|
336
345
|
let settled = false;
|
|
337
346
|
let stdoutBytes = 0;
|
|
347
|
+
let captured = "";
|
|
348
|
+
let spawnedAt = null;
|
|
338
349
|
let stderrTail = "";
|
|
339
350
|
let timedOut = false;
|
|
340
351
|
let interrupted = false;
|
|
@@ -356,7 +367,7 @@ function spawnRun(spec) {
|
|
|
356
367
|
for (const timer of timers) clearTimeout(timer);
|
|
357
368
|
timers.clear();
|
|
358
369
|
if (onAbort) spec.signal?.removeEventListener("abort", onAbort);
|
|
359
|
-
resolve2({ ...outcome, durationMs: Date.now() - started });
|
|
370
|
+
resolve2({ outcome: { ...outcome, durationMs: Date.now() - started }, stdout: captured });
|
|
360
371
|
};
|
|
361
372
|
const detach = () => {
|
|
362
373
|
if (child === null) return;
|
|
@@ -371,7 +382,7 @@ function spawnRun(spec) {
|
|
|
371
382
|
} catch {
|
|
372
383
|
}
|
|
373
384
|
};
|
|
374
|
-
const classify = (code, signal, note) => {
|
|
385
|
+
const classify = (code, signal, note, exitedAt) => {
|
|
375
386
|
const tail = redactDiagnostic(stderrTail);
|
|
376
387
|
const extra = `${note ? ` (${note})` : ""}${tail ? `: ${tail}` : ""}`;
|
|
377
388
|
if (timedOut) {
|
|
@@ -380,9 +391,17 @@ function spawnRun(spec) {
|
|
|
380
391
|
if (interrupted) {
|
|
381
392
|
return { state: "failed", exitCode: code, detail: `interrupted \u2014 the integration was stopping; the tray stays unread for the next run${extra}` };
|
|
382
393
|
}
|
|
394
|
+
if (code === 0 && spec.requireStdout === true && stdoutBytes === 0) return { state: "failed", exitCode: 0, detail: `exit 0 with nothing on stdout${extra}` };
|
|
383
395
|
if (code === 0) return note ? { state: "ok", exitCode: 0, detail: note } : { state: "ok", exitCode: 0 };
|
|
384
396
|
const exit = code === null ? `signal ${signal ?? "unknown"}` : `exit ${code}`;
|
|
385
|
-
if (stdoutBytes === 0)
|
|
397
|
+
if (stdoutBytes === 0) {
|
|
398
|
+
const ranMs = spawnedAt === null ? 0 : Math.max(0, exitedAt - spawnedAt);
|
|
399
|
+
if (spawnedAt !== null && ranMs >= notStartedWithinMs) {
|
|
400
|
+
const refused = tail.includes("API Error");
|
|
401
|
+
return { state: "failed", ...refused ? {} : { silent: true }, exitCode: code, detail: `${exit} after ${Math.round(ranMs / 1e3)} s with nothing on stdout (it ran, then ended)${extra}` };
|
|
402
|
+
}
|
|
403
|
+
return { state: "not_started", exitCode: code, detail: `${exit} with nothing on stdout${extra}` };
|
|
404
|
+
}
|
|
386
405
|
return { state: "failed", exitCode: code, detail: `${exit}${extra}` };
|
|
387
406
|
};
|
|
388
407
|
if (spec.signal?.aborted) {
|
|
@@ -390,7 +409,8 @@ function spawnRun(spec) {
|
|
|
390
409
|
return;
|
|
391
410
|
}
|
|
392
411
|
try {
|
|
393
|
-
|
|
412
|
+
const spawner = spec.shell === true ? nodeSpawn : spawnCommand;
|
|
413
|
+
child = spawner(spec.command, [...spec.args], {
|
|
394
414
|
cwd: spec.cwd,
|
|
395
415
|
env: spec.env,
|
|
396
416
|
stdio: [spec.stdin === null ? "ignore" : "pipe", "pipe", "pipe"],
|
|
@@ -403,6 +423,9 @@ function spawnRun(spec) {
|
|
|
403
423
|
return;
|
|
404
424
|
}
|
|
405
425
|
const proc = child;
|
|
426
|
+
proc.once("spawn", () => {
|
|
427
|
+
spawnedAt = Date.now();
|
|
428
|
+
});
|
|
406
429
|
if (spec.onStarted) {
|
|
407
430
|
const onStarted = spec.onStarted;
|
|
408
431
|
proc.once("spawn", () => {
|
|
@@ -414,6 +437,7 @@ function spawnRun(spec) {
|
|
|
414
437
|
}
|
|
415
438
|
proc.stdout?.on("data", (chunk) => {
|
|
416
439
|
stdoutBytes += chunk.length;
|
|
440
|
+
if (captured.length < captureBytes) captured = (captured + String(chunk)).slice(0, captureBytes);
|
|
417
441
|
});
|
|
418
442
|
proc.stderr?.on("data", (chunk) => {
|
|
419
443
|
stderrTail = (stderrTail + String(chunk)).slice(-4 * STDERR_TAIL_CHARS);
|
|
@@ -479,13 +503,14 @@ function spawnRun(spec) {
|
|
|
479
503
|
classify(
|
|
480
504
|
exited.code,
|
|
481
505
|
exited.signal,
|
|
482
|
-
process.platform === "win32" ? "a process the run started kept its output open after it exited; its children were swept (taskkill) and the run detached from it \u2014 a process the sweep cannot see can survive" : "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 \u2014 a process that left the group can survive"
|
|
506
|
+
process.platform === "win32" ? "a process the run started kept its output open after it exited; its children were swept (taskkill) and the run detached from it \u2014 a process the sweep cannot see can survive" : "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 \u2014 a process that left the group can survive",
|
|
507
|
+
exited.at
|
|
483
508
|
)
|
|
484
509
|
);
|
|
485
510
|
});
|
|
486
511
|
});
|
|
487
512
|
proc.on("close", (code, signal) => {
|
|
488
|
-
finish(classify(code, signal, null));
|
|
513
|
+
finish(classify(code, signal, null, exited?.at ?? Date.now()));
|
|
489
514
|
});
|
|
490
515
|
});
|
|
491
516
|
}
|
|
@@ -526,6 +551,7 @@ export {
|
|
|
526
551
|
WINDOWS_SWEEP_TIMEOUT_MS,
|
|
527
552
|
sweepWindowsDescendants,
|
|
528
553
|
describeWindowsSweep,
|
|
529
|
-
spawnRun
|
|
554
|
+
spawnRun,
|
|
555
|
+
spawnRunCapturing
|
|
530
556
|
};
|
|
531
|
-
//# sourceMappingURL=chunk-
|
|
557
|
+
//# sourceMappingURL=chunk-5KMQ23O6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client-identity.ts","../src/util/fsutil.ts","../src/integration/profile.ts","../src/util/log.ts","../src/util/spawn.ts","../src/integration/spawn-run.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","// ─── Run profile and switches ───────────────────────────────────────────────\n//\n// What a headless run may do is the operator's decision, not the peer's and\n// not ours. A run is started by ANY peer's unread message — a stranger's cold\n// DM included. Four profiles, mapped by each integration to its runtime's\n// real flags (documented per runtime in that integration's README):\n//\n// own — the agent itself: the runtime's own permission settings (the\n// user's permission mode, allow and deny rules, sandbox, MCP\n// servers, instruction files, memory, hooks) decide what the run\n// may do, exactly as in the user's own headless runs. AgentChat\n// adds only what a run cannot do without — its own tools,\n// pre-approved — and what keeps the key out of reach (the key\n// store's deny rules where the runtime has them; no key in the\n// run's environment). The default.\n// answer — every AgentChat hosted tool and no other MCP server, and file\n// reads inside the run's own working folder only (never the home\n// folder or above it): no web search or fetch, no shell, no edits,\n// nothing outside the workdir readable. The lock: an explicit\n// opt-in, and what a value that names no profile means.\n// work — plus the web, edits and shell (in the run's workspace).\n// full — the runtime's own bypass-everything mode.\n//\n// `own`, `work` and `full` let runs started by peers' messages act beyond\n// AgentChat: `own` with the user's own permissions (`OWN_RUN_WARNING`), `work`\n// and `full` reading and changing this machine (`PEER_RUN_WARNING`). Wherever\n// a profile is offered or described, its sentence says so\n// (`runProfileWarning`, `describeRunProfile`).\n//\n// Whatever the profile, a headless run NEVER waits on a permission prompt:\n// anything that would prompt is denied, not waited on.\n\nimport * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\n\nexport const RUN_PROFILES = ['own', 'answer', 'work', 'full'] as const\nexport type RunProfile = (typeof RUN_PROFILES)[number]\n\n/** What `work` and `full` mean, said plainly wherever either is offered or described. */\nexport const PEER_RUN_WARNING = \"runs started by peers' messages can read and change this machine\"\n\n/** What `own` means for a run a peer's message started, said after `ownProfileLine` wherever `own` is offered or described. */\nexport const OWN_RUN_WARNING = \"runs started by peers' messages act with those permissions\"\n\n/**\n * The one line that says what `own` does: `reply runs use your own Claude\n * Code permission settings, with anything that would ask refused`. The\n * runtime is the caller's to name (this engine names none); without it, the\n * line names none either.\n */\nexport function ownProfileLine(runtimeLabel?: string | null): string {\n const settings = runtimeLabel !== undefined && runtimeLabel !== null && runtimeLabel.trim().length > 0 ? `your own ${runtimeLabel.trim()} permission settings` : 'your own permission settings'\n return `reply runs use ${settings}, with anything that would ask refused`\n}\n\n/** `OWN_RUN_WARNING` for `own`, `PEER_RUN_WARNING` for `work` and `full`; null for `answer` (and anything that is not a profile). */\nexport function runProfileWarning(profile: string): string | null {\n if (profile === 'work' || profile === 'full') return PEER_RUN_WARNING\n return profile === 'own' ? OWN_RUN_WARNING : null\n}\n\n/**\n * What a run of `profile` may do, in one plain line for `status`, `doctor`\n * and install output, with the profile's warning in it. A value that is not a\n * profile is described as `answer`, which is what it means (`resolveRunProfile`).\n */\nexport function describeRunProfile(profile: string, runtimeLabel?: string | null): string {\n switch (profile) {\n case 'own':\n return `${ownProfileLine(runtimeLabel)}; ${OWN_RUN_WARNING}`\n case 'work':\n return `reply runs also get the shell and edits in their work folder; ${PEER_RUN_WARNING}`\n case 'full':\n return `reply runs use ${runtimeLabel !== undefined && runtimeLabel !== null && runtimeLabel.trim().length > 0 ? `${runtimeLabel.trim()}'s` : \"the runtime's\"} bypass mode; ${PEER_RUN_WARNING}`\n default:\n return 'reply runs get the AgentChat tools and reads inside their own work folder, nothing else'\n }\n}\n\n/**\n * The kernel's identity of a directory (device and inode), or null when it\n * cannot be read or the filesystem reports no inode (0: FAT, some network\n * filesystems — then only spellings are compared).\n */\nfunction identityOf(dir: string): string | null {\n try {\n const st = fs.statSync(dir, { bigint: true })\n return st.ino === 0n ? null : `${st.dev}:${st.ino}`\n } catch {\n return null\n }\n}\n\n/** `p` as the kernel resolves it (symlinks, and on macOS the on-disk case), or resolved only when it cannot be. */\nfunction realOrResolved(p: string): string {\n const resolved = path.resolve(p)\n try {\n return fs.realpathSync.native(resolved)\n } catch {\n return resolved\n }\n}\n\n/** Case-folded where the platform's default filesystems are case-insensitive. */\nfunction spelling(p: string): string {\n return process.platform === 'win32' || process.platform === 'darwin' ? p.toLowerCase() : p\n}\n\n/**\n * Whether a run workdir is the user's home folder, a folder that contains it\n * (`/Users`, `/home`, a drive root), or the filesystem root. A run started\n * there sees everything under it: a peer-started run whose readable folder is\n * the home folder can read `~/.ssh`.\n *\n * Decided by what the kernel says the directories ARE (device and inode), not\n * by their spelling: the workdir exposes the home folder when, for some\n * trailing part of the home folder's path (`Users/<name>`, `<name>`, or\n * nothing), `<workdir>/<that part>` is the home folder itself. That holds for\n * an ancestor and for the home folder, however they are reached — a\n * case-insensitive volume's `/users/<name>` or `/USERS/<NAME>`, macOS's\n * `/System/Volumes/Data` (a firmlink root that is not `/`), a symlink, a bind\n * mount that keeps the names. A filesystem without inodes falls back to\n * comparing spellings (case-folded on macOS and Windows).\n */\nexport function workdirExposesHome(workdir: string, home: string = os.homedir()): boolean {\n const dir = realOrResolved(workdir)\n if (dir === path.parse(dir).root) return true\n const homes = [...new Set([path.resolve(home), realOrResolved(home)])]\n const homeIds = new Set(homes.map(identityOf).filter((id): id is string => id !== null))\n for (const h of homes) {\n const parts = h.slice(path.parse(h).root.length).split(path.sep).filter((part) => part.length > 0)\n for (let i = 0; i <= parts.length; i++) {\n const candidate = path.join(dir, ...parts.slice(i))\n const id = identityOf(candidate)\n if (id !== null ? homeIds.has(id) : spelling(realOrResolved(candidate)) === spelling(realOrResolved(h)) && fs.existsSync(candidate)) return true\n }\n }\n return false\n}\n\nexport const RUN_PROFILE_ENV = 'AGENTCHAT_RUN_PROFILE'\n/** The profile when `AGENTCHAT_RUN_PROFILE` is unset or blank: the agent itself. */\nexport const DEFAULT_RUN_PROFILE: RunProfile = 'own'\n/**\n * The profile when `AGENTCHAT_RUN_PROFILE` names no profile (a typo, a value\n * from a newer release): `answer`, the lock. Fail-safe: a value someone set\n * on purpose and got wrong never gives a run more than they meant.\n */\nexport const FALLBACK_RUN_PROFILE: RunProfile = 'answer'\n\nexport function isRunProfile(value: unknown): value is RunProfile {\n return typeof value === 'string' && (RUN_PROFILES as readonly string[]).includes(value)\n}\n\n/** `AGENTCHAT_RUN_PROFILE`: unset or blank is `own` (the default); a value that names no profile is `answer` (fail-safe). */\nexport function resolveRunProfile(env: NodeJS.ProcessEnv = process.env): RunProfile {\n const raw = env[RUN_PROFILE_ENV]?.trim().toLowerCase()\n if (raw === undefined || raw.length === 0) return DEFAULT_RUN_PROFILE\n return isRunProfile(raw) ? raw : FALLBACK_RUN_PROFILE\n}\n\n/** The one switch: `AGENTCHAT_INTEGRATION=off` holds no socket and starts no run. Tools and manual stay. */\nexport const INTEGRATION_ENV = 'AGENTCHAT_INTEGRATION'\n/**\n * The previous spelling of the switch (a legacy name: compatibility reader\n * only). Still read, because a service installed before the rename captured\n * it into its unit file, and that unit must keep meaning what the operator\n * set; `AGENTCHAT_INTEGRATION` wins when both are set. Contract v1 (section 7,\n * old integration settings) removes it on `INTEGRATION_ENV_LEGACY_REMOVAL`;\n * tests/legacy-env-removal.test.ts fails from that day, so the reader is\n * deleted in a release rather than remembered. Until then an `off` here is\n * honoured — never silently dropped, which would turn on an integration its\n * operator switched off.\n */\nexport const INTEGRATION_ENV_LEGACY = 'AGENTCHAT_DOORBELL'\n/** The day contract v1 drops `AGENTCHAT_DOORBELL` (UTC). */\nexport const INTEGRATION_ENV_LEGACY_REMOVAL = '2027-02-01'\n\nfunction isOff(raw: string | undefined): boolean {\n const value = raw?.trim().toLowerCase()\n return value === 'off' || value === '0' || value === 'false'\n}\n\n/** Which switch turned the integration off, or null when it is on. The new spelling wins when both are set. */\nexport function integrationDisabledBy(env: NodeJS.ProcessEnv = process.env): string | null {\n if (env[INTEGRATION_ENV] !== undefined && env[INTEGRATION_ENV].trim().length > 0) {\n return isOff(env[INTEGRATION_ENV]) ? INTEGRATION_ENV : null\n }\n return isOff(env[INTEGRATION_ENV_LEGACY]) ? INTEGRATION_ENV_LEGACY : null\n}\n\nexport function integrationDisabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return integrationDisabledBy(env) !== null\n}\n\n/** A run's time budget. Killed past it; that counts as a failed run. */\nexport const RUN_BUDGET_ENV = 'AGENTCHAT_RUN_BUDGET_MS'\nexport const DEFAULT_RUN_BUDGET_MS = 10 * 60_000\nconst MAX_RUN_BUDGET_MS = 2 * 60 * 60_000\n\nexport function resolveRunBudgetMs(env: NodeJS.ProcessEnv = process.env): number {\n const parsed = Number(env[RUN_BUDGET_ENV])\n if (!Number.isFinite(parsed) || parsed < 1_000) return DEFAULT_RUN_BUDGET_MS\n return Math.min(parsed, MAX_RUN_BUDGET_MS)\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","import { spawn as nodeSpawn, 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, exited non-zero after writing to stdout,\n// or exited non-zero with nothing on stdout after it had run a while\n// (`NOT_STARTED_WITHIN_MS`, measured from the spawn to the process's exit: a\n// crash, an out-of-memory kill, a SIGKILL partway through — a runtime that\n// prints its answer only at the end has said nothing yet); `not_started` when\n// it could not be spawned, or exited non-zero with NOTHING ON STDOUT within\n// that window — a signed-out CLI, a bad flag, a missing config all print\n// their complaint on stderr and quit at once, and they are \"the runtime did\n// not get going\", stderr or not. The stderr tail rides along in the detail\n// either way.\n//\n// The silent failure past the window is `failed` with `silent: true`\n// (`RunOutcome.silent`): a crash with no output says nothing about why, and\n// the runtime check (which loads no hook, MCP server or instruction file of\n// the user's) could pass. So the engine counts a silent failure like a\n// timeout (`RunEnd.timedOut`): it is reported as a conversation's only once\n// another conversation's run completed. A provider's refusal is not silent:\n// Claude Code prints its `API Error: …` on stdout, and a run whose stderr\n// tail says `API Error` is not marked silent either (should a runtime move\n// the refusal to stderr, it stays a plain `failed`, for which the runtime\n// check is evidence).\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/**\n * A run that exits non-zero with nothing on stdout counts as `not_started`\n * only when it exited within this long of its spawn (a refused flag, a\n * signed-out CLI: they quit at once). Exited later, it ran and then died:\n * `failed`, `silent`.\n */\nexport const NOT_STARTED_WITHIN_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 * An exit 0 with nothing on stdout is `failed`, not `ok`: for a probe whose\n * answer must be there (a model call that printed nothing did not answer).\n * Still counted, never kept.\n */\n readonly requireStdout?: boolean\n /** Test seam: `NOT_STARTED_WITHIN_MS`. */\n readonly notStartedWithinMs?: number\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\n/**\n * Signal a child and everything it started: on POSIX its process group (the\n * child must have been spawned `detached`, so it leads one), on Windows its\n * tree (`taskkill /T /F` — there a command found through an npm `.cmd` shim\n * runs under `cmd.exe`, and killing the shim alone leaves the real process\n * running). Falls back to the child alone. Never throws.\n */\nexport function 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. The output is counted, never kept. */\nexport function spawnRun(spec: SpawnRunSpec): Promise<RunOutcome> {\n return runSpawned(spec, 0).then((result) => result.outcome)\n}\n\n/**\n * `spawnRun`, keeping the first `maxBytes` of stdout. ONLY for a probe whose\n * input is a fixed text of ours (a runtime check: no peer content) and whose\n * answer must be read to be judged; a run started for a peer's message never\n * goes through here. The caller reads it and drops it; it is never logged.\n */\nexport function spawnRunCapturing(spec: SpawnRunSpec, maxBytes: number): Promise<{ outcome: RunOutcome; stdout: string }> {\n return runSpawned(spec, Math.max(0, Math.floor(maxBytes)))\n}\n\nfunction runSpawned(spec: SpawnRunSpec, captureBytes: number): Promise<{ outcome: RunOutcome; stdout: string }> {\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 const notStartedWithinMs = spec.notStartedWithinMs ?? NOT_STARTED_WITHIN_MS\n return new Promise<{ outcome: RunOutcome; stdout: string }>((resolve) => {\n let settled = false\n let stdoutBytes = 0\n let captured = ''\n /** When the process was spawned; null until it was (a spawn error never sets it). */\n let spawnedAt: number | null = null\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: { ...outcome, durationMs: Date.now() - started }, stdout: captured })\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 /**\n * The outcome for an exit the run did make; `note` says why `close` was\n * not waited for. `exitedAt`: when the process exited (its `exit` event),\n * not when it is classified — `close` can follow much later (a process\n * the run started holding its pipes, the drain).\n */\n const classify = (code: number | null, signal: NodeJS.Signals | null, note: string | null, exitedAt: number): 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 && spec.requireStdout === true && stdoutBytes === 0) return { state: 'failed', exitCode: 0, detail: `exit 0 with nothing on stdout${extra}` }\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 if (stdoutBytes === 0) {\n // It ran a while and then died (a crash, an OOM kill, a SIGKILL\n // partway through) before printing anything: a failed run, and a\n // silent one — as ambiguous as a timeout (`RunOutcome.silent`).\n // Measured to the exit, not to now.\n const ranMs = spawnedAt === null ? 0 : Math.max(0, exitedAt - spawnedAt)\n if (spawnedAt !== null && ranMs >= notStartedWithinMs) {\n // A refusal said on stderr (`API Error: …`) is the provider's answer,\n // not silence: a plain failure.\n const refused = tail.includes('API Error')\n return { state: 'failed', ...(refused ? {} : { silent: true }), exitCode: code, detail: `${exit} after ${Math.round(ranMs / 1000)} s with nothing on stdout (it ran, then ended)${extra}` }\n }\n // It quit at once: the runtime did not get going (refused to start,\n // a bad flag, an auth gate). Whatever it complained about is in the tail.\n return { state: 'not_started', exitCode: code, detail: `${exit} with nothing on stdout${extra}` }\n }\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 // A shell run goes to Node's own spawn: with `shell: true` cross-spawn\n // resolves nothing (the shell does), yet on Windows its hook re-emits\n // every exit 1 of an unresolved command as `spawn … ENOENT`. `cmd.exe\n // /c` exits 1 both for a command it cannot find and for a command that\n // ran and failed with 1, so the hook turned a failed run into \"not\n // found\". The exit code is kept, and the rule below tells the two apart\n // as on every platform: nothing on stdout is not started. Direct runs\n // keep cross-spawn for its PATHEXT and `.cmd` shim resolution.\n const spawner = spec.shell === true ? nodeSpawn : spawnCommand\n child = spawner(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 proc.once('spawn', () => {\n spawnedAt = Date.now()\n })\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; kept only for a probe that asked (`spawnRunCapturing`), bounded\n if (captured.length < captureBytes) captured = (captured + String(chunk)).slice(0, captureBytes)\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 exited.at,\n ),\n )\n })\n })\n\n proc.on('close', (code, signal) => {\n // `exit` comes before `close` (Node emits `close` only once the process\n // has exited and its pipes are closed); `now` only if it somehow did not.\n finish(classify(code, signal, null, exited?.at ?? Date.now()))\n })\n })\n}\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,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;AAC9E,QAAM,QAAQ,QAAQ,SAAS,QAAQ,aAAa;A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