@agentchatme/agent-core 0.4.1 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -3
- package/dist/chunk-3ERPUP4M.js +97 -0
- package/dist/chunk-3ERPUP4M.js.map +1 -0
- package/dist/{chunk-AE4XHKHQ.js → chunk-AFDD53DD.js} +234 -10
- package/dist/chunk-AFDD53DD.js.map +1 -0
- package/dist/{chunk-7LAAAXUO.js → chunk-CDJASQ3X.js} +509 -104
- package/dist/chunk-CDJASQ3X.js.map +1 -0
- package/dist/daemon-entry.d.ts +58 -3
- package/dist/daemon-entry.js +287 -33
- package/dist/daemon-entry.js.map +1 -1
- package/dist/index.d.ts +94 -13
- package/dist/index.js +402 -354
- package/dist/index.js.map +1 -1
- package/dist/presets.d.ts +352 -21
- package/dist/presets.js +700 -105
- package/dist/presets.js.map +1 -1
- package/dist/{runner-B-ZZDAAm.d.ts → runner-DYVqz_9P.d.ts} +38 -2
- package/dist/{served-manual-99vEOjJS.d.ts → served-manual-Be_eUo0m.d.ts} +157 -26
- package/package.json +2 -2
- package/dist/chunk-7LAAAXUO.js.map +0 -1
- package/dist/chunk-AE4XHKHQ.js.map +0 -1
- package/dist/chunk-QDM4EFI7.js +0 -139
- package/dist/chunk-QDM4EFI7.js.map +0 -1
- package/dist/chunk-XDWBTX5J.js +0 -30
- package/dist/chunk-XDWBTX5J.js.map +0 -1
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@ A single shared CLI used to serve every coding agent, so its commands had to *de
|
|
|
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
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 prompt | The runner seam (`RunRunner`), a deadline on every run, the pointer line, the status file | How to start one headless run of its runtime (`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 (`answer` / `work` / `full`) and switches; the presets (`./presets`) | Which agent a preset's runs act as (its identity home, its MCP registration) |
|
|
41
41
|
| | Service install (launchd / systemd / Windows Startup), leader lock, heartbeat, the resident supervisor | Where its runtime keeps skills, how it registers a remote MCP server; its packaging and front door |
|
|
42
42
|
|
|
@@ -89,6 +89,8 @@ const profile: HostProfile = {
|
|
|
89
89
|
const { runRegister, runLogin, runRecover, runStatus, runLogout, runDoctor } = createIdentityCommands(profile)
|
|
90
90
|
```
|
|
91
91
|
|
|
92
|
+
Sign-up follows the server (contract v1, "Sign-up flows", through the SDK's `integration.account`). `register --email --handle` and `recover --handle --email` ask for a code; `register --code` and `recover --code`, in a later run, answer it; the server's flow object (`pending_id`, `expires_in_s`, `resend_after_s`, …) and when it arrived are kept in `<home>/pending.json` between the two. Each run prints the server's sentence as it is, then the command to run next, chosen by the SDK's `actionOf` from the answer and the step called: the code command (`ask_code`), the same command with the field the server names left to fill in (`ask_param`; for `HANDLE_REQUIRED` with the handles to choose from), the command for a new code after any wait the server set (`offer_new_code`), the same command after the server's wait (`wait_then_retry`), or nothing more (`stop`; after a 429 on a new-code request, the code already sent while it still works). No code, limit or wording of the server's is kept here. On a terminal, a command that has to ask for its input anyway runs the whole conversation in one process (`integration.account.run`). `login` saves a key only when `checkKey` says the server accepts it; every flow saves the handle the server returned, never the one typed. The setup offer an unregistered agent reads (`renderUnregisteredBlock`) names the three commands and has the agent relay each command's answer and run the command it prints next; it carries no handle rule, code length or scripted failure line of its own.
|
|
93
|
+
|
|
92
94
|
The daemon is one call from the `/daemon` subpath — kept out of the main entry because it bundles `ws` (CommonJS), which must never reach an integration's CLI:
|
|
93
95
|
|
|
94
96
|
```ts
|
|
@@ -135,9 +137,81 @@ Pending group invites are on the tray (contract v1), so nothing about them is ke
|
|
|
135
137
|
|
|
136
138
|
A run is classified `ok` (exit 0), `timed_out` (killed past its budget), `failed` (interrupted, or exited non-zero after writing to stdout), or `not_started` (exited non-zero with **nothing on stdout** — a signed-out CLI, a bad flag; its stderr complaint rides along, redacted, in the detail — or no served texts in hand yet). None of them is retried here.
|
|
137
139
|
|
|
140
|
+
### One agent, one listener
|
|
141
|
+
|
|
142
|
+
Two identity homes can hold the same agent's key: a CLI listener's home and an integration's, say. If both held a socket, every message would be answered twice. So the first daemon to start for an agent holds its **agent lock**, and any other daemon for that agent holds no socket and starts no run. `status` names the home that serves the agent (`standby`, rewritten every poll), `doctor` warns, and the standby takes over when that one stops.
|
|
143
|
+
|
|
144
|
+
**A holder that cannot serve gives the agent up.** If the server refuses its key (socket `blocked`, say a key rotated by `recover` in another home), it gives the agent up at once. If its runs fail for a runtime reason (`runs_failing`), it gives the agent up only when a healthy listener for the agent is actually waiting: a standby keeps a fresh marker beside the lease, and only while its own runtime checks out (its preflight, rechecked every 5 min), so a signed-out standby never leaves the agent with no socket. A lone install keeps its socket: wakes keep arriving, are counted, and start runs, and the next run that succeeds clears it. A home that gave the agent up says so in status (`unservable`: `key_refused` or `runs_failing`, the detail, since, `retry_at`). It holds no socket and starts no run while another listener can serve the agent, and looks again every 60 s after failing runs (the runtime checked first, within a deadline: a check that passes clears it) or every 5 min after a refused key (signing in again clears it at once). Whenever no other listener holds the agent, it takes the agent back: a failing install is still better than none.
|
|
145
|
+
|
|
146
|
+
- **Where the lock lives:** one file per agent, `agent-<32 hex>.lock`, named by a hash of the API origin and the agent's handle (never the key). The folder is per user and owner-only, derived from the home folder alone so that a service and a shell agree on it:
|
|
147
|
+
- macOS: `~/Library/Application Support/AgentChat/locks`
|
|
148
|
+
- Windows: `%USERPROFILE%\AppData\Local\AgentChat\locks`
|
|
149
|
+
- elsewhere: `~/.local/state/agentchat/locks`
|
|
150
|
+
- `AGENTCHAT_LOCK_DIR` in the process environment overrides it, for tests and sandboxes.
|
|
151
|
+
- **A lease.** The agent lock and each home's `daemon.lock` are leases (`util/lease.ts`).
|
|
152
|
+
- **Format:** the first line is the holder's bare pid, so readers from before (the Windows service reinstall, a 0.4.x daemon) see the pid and refuse a live lock instead of stealing it. A line of JSON follows: token, host, home, `acquired_at`, `renewed_at`.
|
|
153
|
+
- **Created** with O_EXCL. The holder rewrites the lease every 10 s.
|
|
154
|
+
- **When a holder is gone, by what a contender observes.** A contender never compares the holder's wall clock with its own. A lease is stale only when its content (token and `renewed_at`) has not changed for 45 s on the contender's own monotonic clock since it first saw that content (the Kubernetes leader-election rule).
|
|
155
|
+
- **A second look before a takeover.** Node's monotonic clock does not behave the same in sleep everywhere: it stops while a Linux machine is suspended, and keeps running through a macOS sleep. So on a Mac, a standby that wakes can find an unchanged lease that already looks 45 s old, before the holder (woken at the same moment) has fired its overdue renewal. A stale verdict by observation is therefore confirmed 15 s later (1.5 renewals); a holder that is there has renewed by then. Wall-clock steps and another host's skew play no part.
|
|
156
|
+
- **Dead pid:** a holder whose pid is dead on this host is gone at once.
|
|
157
|
+
- **Before this boot:** a lease on this host whose file and `renewed_at` both predate the current boot is gone at once (its pid belongs to someone else now). Windows Fast Startup keeps the uptime counting, so this cannot be the only rule there.
|
|
158
|
+
- **A daemon starting up watches before refusing.** It observes a held `daemon.lock` for the stale window plus a renewal (55 s), so a lease whose pid was reused (a reboot, or a logoff that killed the daemon) is taken over by that same process rather than refused into a service restart that would look at it afresh, for ever. A holder seen renewing is refused at once (within one renewal).
|
|
159
|
+
- **Old locks:** a lock from before leases (a bare pid) is judged by its pid, unless the file predates this boot (its pid may belong to someone else now).
|
|
160
|
+
- **No probes:** there are no start-time probes (`ps`, PowerShell).
|
|
161
|
+
- **Takeover, renewal, release:** all happen under a short O_EXCL guard. On every renewal the holder re-reads the file and stands down at once if it is no longer its own: the integration stops right there, so no wake can start a run in the meantime. A renewal that fails (the lock folder removed, a full disk) is counted in status (`lease_errors`) and never crashes the daemon. A lease that cannot be renewed for 45 s is given up cleanly.
|
|
162
|
+
- **The Windows/WSL reinstall** stops the pid in `daemon.lock` (`DAEMON_LOCK_FILE`) only while that holder is really there.
|
|
163
|
+
- **Limit:** two different OS users holding one agent's key do not see each other.
|
|
164
|
+
|
|
165
|
+
### When runs keep failing
|
|
166
|
+
|
|
167
|
+
The socket can be fine while every run fails: the runtime was signed out, its binary removed, or an upgrade dropped a flag. After a run that did not get done, the daemon checks the runtime again with the runner's own preflight. It does this at most once every 5 minutes while runs keep failing, never on every wake. If the check fails, `status` says so plainly, under a headline that reads "socket ready — but runs are failing":
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
runs failing: claude: claude is not signed in (run `claude` once and sign in) — since <time>, N run(s) missed
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`doctor` reports a FAIL check `runs`, and `integration.status.json` carries `runs_failing` (`reason`, `since`, `runs_missed`, `checked_at`). Wakes still start runs and are counted: each one is the quickest way back. The next run that succeeds clears it. The one exception is a healthy listener for the same agent waiting in another home: then this home hands the agent over (`unservable`, above), and its runtime recheck clears it.
|
|
174
|
+
|
|
175
|
+
A runtime check in flight is stopped, its probes killed, when the daemon or the integration stops. A `claude auth status` that hangs is reported as not answering ("did not answer within 10 s"), not as signed out.
|
|
176
|
+
|
|
177
|
+
The runtime probes (`inspectClaudeRuntime`, `claudeIsLoggedIn`, `inspectCodexRuntime`, `codexIsLoggedIn`, `Preset.inspect`) are async (`runProbe`). A probe that hangs is killed with everything it started: its process group on POSIX, `taskkill /T /F` on Windows, where the npm `.cmd` shim and the real process differ. Its exit is waited for, within a bound. A synchronous probe could only kill the shim, and then sat blocking the daemon.
|
|
178
|
+
|
|
138
179
|
### Run profiles
|
|
139
180
|
|
|
140
|
-
`AGENTCHAT_RUN_PROFILE=answer|work|full` (default `answer`) says what a headless run may do; each integration maps the profile to its runtime's real flags and documents them.
|
|
181
|
+
`AGENTCHAT_RUN_PROFILE=answer|work|full` (default `answer`) says what a headless run may do; each integration maps the profile to its runtime's real flags and documents them. A run is started by **any** peer's unread message, a stranger's cold DM included, so the default gives it nothing to leak and no way to leak it:
|
|
182
|
+
|
|
183
|
+
- **`answer`** (default): every AgentChat hosted tool and no other MCP server, and file reads inside the run's own working folder only (never the home folder or above it). No web search or fetch, no shell, no edits, nothing outside the workdir readable, and none of the user's own context files (CLAUDE.md, memory, project docs) in the run's context, except where a runtime gives no way to leave them out (known limits below).
|
|
184
|
+
- **`work`**: plus the web, edits and shell. **Runs started by peers' messages can then read and change this machine.**
|
|
185
|
+
- **`full`**: the runtime's own bypass-everything mode. **Runs started by peers' messages can then read and change this machine.**
|
|
186
|
+
|
|
187
|
+
`work` and `full` are explicit opt-ins, for an agent whose peers you trust with your machine. `status` prints the same warning next to either (`PEER_RUN_WARNING`, `runProfileWarning`). Whatever the profile, a headless run never waits on a permission prompt: anything that would prompt is denied. `AGENTCHAT_RUN_BUDGET_MS` bounds a run (default 10 minutes); a run past its budget is killed and counts as failed.
|
|
188
|
+
|
|
189
|
+
How the presets map `answer`:
|
|
190
|
+
|
|
191
|
+
- **Claude Code:** `--mcp-config <AgentChat-only file> --strict-mcp-config --permission-mode default --permission-prompts none --tools Read,Glob,Grep --allowedTools mcp__agentchat__*,Read(//<workdir>),Read(//<workdir>/**) --settings {"permissions":{"blockReadsOutsideWorkingDirectories":true},"env":{"CLAUDE_CODE_DISABLE_CLAUDE_MDS":"1","CLAUDE_CODE_DISABLE_AUTO_MEMORY":"1"},"disableAllHooks":true} --disallowedTools WebFetch,WebSearch,Bash,<the key-store deny rules>`.
|
|
192
|
+
- **One MCP server.** The `--mcp-config` file holds the AgentChat hosted server alone, and `--strict-mcp-config` makes it the only one: no user, project or plugin server, no claude.ai connector. A listener passes its own file (`mcpConfigPath`, every profile). An integration passes `ClaudeRunnerOptions.answerMcp` (`{ file, apiBase, apiKey, clientVersion? }`): the file is written owner-only for each answer run, beside `file` under a name of that run's own (`<stem>.<run id>.json`, so a late cleanup cannot remove another run's), from the key `apiKey()` returns then, and removed when the run ends. It must sit inside a `denyReadPaths` entry, because it holds the key. Without either, an answer run does not start (preflight says why): it would load every MCP server the user registered.
|
|
193
|
+
- **No user context.** `CLAUDE_CODE_DISABLE_CLAUDE_MDS=1` and `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` are in the `--settings` `env` block as well as the run's environment (`ANSWER_ENV`), so no `CLAUDE.md` of any scope (user, project, ancestors, `.claude/rules`, `@` imports) and no auto memory reach its context. Why both: a settings file's `env` overrides the process environment, and a workdir repository's own `.claude/settings.json` is applied in print mode. `--settings` outranks the user's, project and local settings. Its identity line, the served `identity_line` the integration hands each run (`RunRequest.identityLine`), comes in by `--append-system-prompt-file`. That file is written for the run beside its tool config and removed after it: a file, because an argument cannot carry a line break through a Windows `.cmd` shim. `<config dir>/projects` (every project's transcripts and auto memory) is denied as well: Claude Code otherwise lets a run read its project's memory folder even with auto memory off. Verified on 2.1.322 and on 2.1.274, the floor, against a fake model API, with the user's and the workdir's settings both setting the two switches to `"0"`: no context file reached the request, and the identity line did.
|
|
194
|
+
- **No hooks.** `disableAllHooks` (1.0.68+): **your own hooks, status line and file-suggestion command do not run in peer-started answer runs**, and neither do a workdir repository's. A hook runs a shell command and can inject text, on every peer's message. Hooks set by managed settings still run: only managed settings can turn those off.
|
|
195
|
+
- **No extra working directories.** `permissions.additionalDirectories` count as working directories even under the read block. So an answer run does not start while one of these files lists them: the user's settings, the managed file or a `managed-settings.d/` drop-in, or `.claude/settings.local.json` at the workdir's repository root or in the workdir itself (Claude Code reads the latter without git, and on Windows). Preflight and every run say so, naming the file (`status`: last error). `--restricted` would ignore them, but it also ignores the user's own settings files, and with them their `env` (provider), `apiKeyHelper` and `model` (`claude --help`, 2.1.274 and 2.1.322), so it is not used.
|
|
196
|
+
- **Files.** Allow rules are written for the workdir as given and for its real path when that differs (`/tmp` is `/private/tmp` on macOS; a symlinked workdir). An allow rule matches only when the path and the file it resolves to both match, so a link out of the workdir is not allowed by it. Glob and Grep are governed by `Read(…)` rules. `blockReadsOutsideWorkingDirectories` (Claude Code 2.1.257+) makes Read, Glob and Grep refuse every path outside the working directories in every mode, whatever allow rules the user's own settings hold. A workdir no allow rule can carry (whitespace, a comma, a gitignore pattern character; every path on Windows) gets no allow rule: the run still reads it as its working directory, and nothing else.
|
|
197
|
+
- **Codex:** `-c approval_policy="never" -c default_permissions="agentchat_answer" -c permissions.agentchat_answer.filesystem={ ":workspace_roots" = "read" } -c web_search="disabled" -c project_doc_max_bytes=0 --disable shell_tool --disable view_image --disable image_generation --disable plugins --disable apps --disable memories --disable browser_use --disable browser_use_external --disable computer_use --disable in_app_browser`, then `-c mcp_servers.<name>.enabled=false` for every other server (no `--sandbox`).
|
|
198
|
+
- **No shell, no local-file tool.** Codex can restrict a sandbox's reads with a permission profile. But a shell needs the `:minimal` platform set to run at all, and that set also opens `/etc`, `/usr` and, for the shell, read-write `/tmp` (macOS seatbelt; `/etc`, `/usr`, `/bin` on Linux). So the shell tool, the image tools, plugins (their MCP servers and skills, a computer-use server among them), the ChatGPT connectors, local memories and the hosted web search are off. `apply_patch` has no off switch; it reads and writes through the sandbox, and the `agentchat_answer` profile lets it read the workdir only and write nothing (no network either).
|
|
199
|
+
- **One MCP server.** Codex has no "only this server" switch, and a tool that a user's own server marks read-only runs without approval. So before each answer run the preset asks Codex itself, `codex mcp list --json`, with the run's own flags, from the run's workdir. It then adds `-c mcp_servers.<name>.enabled=false` for every enabled server but `agentchat`: the user's config, a project's, a managed one. If that listing fails, times out (20 s), prints something that is not the list, or names a server whose name a `-c` key cannot address (a `.` in it), the run does not start. Preflight runs the same listing, so `status` names the reason (Codex's own first line, redacted: an unknown `--disable` feature, for instance) before any message arrives. `codex mcp list` probes each HTTP server's sign-in (OAuth discovery requests to the user's MCP hosts), so a good listing is reused: until one of the config files Codex reads changes (size or mtime: system, managed, requirements, `$CODEX_HOME/config.toml`, macOS managed preferences, `config.toml` / `.codex/config.toml` from the workdir up), and for at most an hour (`CODEX_MCP_LIST_MAX_AGE_MS`). A failure is never reused.
|
|
200
|
+
- **No project docs.** `-c project_doc_max_bytes=0`: no `AGENTS.md` from the project or its ancestors (`core/src/agents_md.rs`: a zero budget reads none).
|
|
201
|
+
- Verified against `codex-cli` 0.154.0 and the openai/codex sources at `rust-v0.154.0`.
|
|
202
|
+
|
|
203
|
+
**Every preset run, every profile, starts without the parent session's variables.** A listener or daemon started from inside a Claude Code or Codex session would otherwise hand its runs that session's id, its messaging socket and token, or a sandbox marker. Dropped: every `CLAUDE_CODE_*` variable except the documented settings for sign-in, provider, TLS, privacy and platform (`CLAUDE_CODE_ENV_KEPT`, e.g. `CLAUDE_CODE_OAUTH_TOKEN`, `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`); `CLAUDECODE`, `CLAUDE_PID`, `CLAUDE_EFFORT`, `AI_AGENT`; `CLAUDE_JOB_DIR`, `CLAUDE_PROJECT_DIR`, `TRACEPARENT`; and what a Codex session sets in its children (`CODEX_SESSION_ENV`: `CODEX_SANDBOX`, `CODEX_THREAD_ID`, `CODEX_ESCALATE_SOCKET`, …). A parent Codex proxy's settings go too (modelled on Codex's `strip_managed_proxy_env`): its proxy URLs and its generated CA bundle (Codex's own `<CODEX_HOME>/proxy/ca-bundle-<64 hex>.pem`), only while its `CODEX_NETWORK_PROXY_ACTIVE` marker is set, so a user's own proxy and corporate CA bundle stay; its marked `GIT_SSH_COMMAND`; and the dummy credentials its broker substituted. `CODEX_HOME`, `CODEX_API_KEY` and the other user settings stay, as do the user's `CLAUDE_ENV_FILE`, `CLAUDE_CODE_DISABLE_CLAUDE_MDS`, `_DISABLE_AUTO_MEMORY`, `_DISABLE_EXPERIMENTAL_BETAS`, `_EXTRA_BODY` and `_MAX_OUTPUT_TOKENS`. See `withoutParentSession`.
|
|
204
|
+
|
|
205
|
+
**The home folder is no answer run's workdir.** A workdir that is the user's home folder, a folder above it, or `/` would make the whole home the run's readable folder (`workdirExposesHome`). That is decided by what the kernel says the folders are (device and inode), not by their spelling, so `/users/<name>`, `/USERS/<NAME>`, `/System/Volumes/Data` and a symlink are all caught. An answer run then works in an empty folder of its own instead: `<Claude Code config dir>/agentchat-answer-workdir` (`claudeAnswerFallbackWorkdir`) or `$CODEX_HOME/agentchat-answer-workdir` (`codexAnswerFallbackWorkdir`). It keeps answering; it only cannot read the user's files. The daemon logs it once, and `status` warns whenever the workdir is the home folder or above it, in every profile. `work` and `full` keep the workdir the operator chose.
|
|
206
|
+
|
|
207
|
+
**Known limits of `answer`.**
|
|
208
|
+
|
|
209
|
+
- Codex: `$CODEX_HOME/AGENTS.md` (and `AGENTS.override.md`) is always in the run's context. Codex 0.154.0 reads it with no switch to turn it off (`codex-home/src/instructions/mod.rs`, wired unconditionally in `app-server/src/message_processor.rs` and `cli/src/main.rs`). The integration's identity line lives there, and so does whatever else the user wrote in that file.
|
|
210
|
+
- Codex: the listing that switches off the user's other MCP servers is itself `codex mcp list`, which contacts each HTTP server's sign-in discovery endpoints. That happens once per config change, at most hourly, never per message.
|
|
211
|
+
- Claude Code: `permissions.additionalDirectories` set by an MDM profile or by server-managed settings (claude.ai) is not a file and is not detected.
|
|
212
|
+
- Codex: the helper process Codex starts for `apply_patch` always gets read access to the `:minimal` system folders (`/etc`, `/usr`, …). That is system files, not the user's.
|
|
213
|
+
- An answer run cannot reach the AgentChat manual: the file is outside its folder (Codex has no file tool at all) and it has no web. It has the served wake or invite instruction only.
|
|
214
|
+
- Claude Code key-store deny rules are still written in the comma-separated `--disallowedTools` list. A key-store path with whitespace or a comma cannot be carried there: the listener refuses such a home, an integration warns. On Windows no deny rule is written, although Claude Code now documents a Windows path form (`//c/...`), and a `--settings` JSON list could carry any path.
|
|
141
215
|
|
|
142
216
|
## Refreshing the bundled manual
|
|
143
217
|
|
|
@@ -160,7 +234,13 @@ pnpm test # incl. tests/integration.test.ts (the SDK kit's receive loop a
|
|
|
160
234
|
# hash checks, keep on failure, the bundled fallback, atomic write),
|
|
161
235
|
# tests/status.test.ts (the renamed status file reads the old one), tests/service.test.ts,
|
|
162
236
|
# tests/home-scoping.test.ts, tests/core-is-host-agnostic.test.ts, tests/presets.test.ts (the flags per
|
|
163
|
-
# profile, and preset runs acting as the given agent, with fake runtimes)
|
|
237
|
+
# profile, and preset runs acting as the given agent, with fake runtimes), tests/answer-profile.test.ts
|
|
238
|
+
# (the regression guard: an answer argv never gains the web, the shell or a read outside its workdir),
|
|
239
|
+
# tests/answer-isolation.test.ts (answer runs load only the AgentChat MCP server, no run carries a
|
|
240
|
+
# parent session's variables, the home folder is no answer run's workdir), tests/answer-review.test.ts
|
|
241
|
+
# (no user context files, no extra working directories, per-run key files, the listing cache),
|
|
242
|
+
# tests/listener-health.test.ts (runs failing said and cleared, the agent lock and its atomic
|
|
243
|
+
# takeover, probes killed with their whole tree)
|
|
164
244
|
```
|
|
165
245
|
|
|
166
246
|
The engine builds on the SDK's integration kit (`import { integration } from 'agentchatme'`, `agentchatme` 1.3.0 and later).
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import {
|
|
2
|
+
clientIdentityOf,
|
|
3
|
+
killProcessTree,
|
|
4
|
+
spawnCommand
|
|
5
|
+
} from "./chunk-AFDD53DD.js";
|
|
6
|
+
|
|
7
|
+
// src/version.ts
|
|
8
|
+
var VERSION = "0.5.1";
|
|
9
|
+
|
|
10
|
+
// src/integration/mcp-probe.ts
|
|
11
|
+
import { integration as kit } from "agentchatme";
|
|
12
|
+
var HOSTED_MCP_PATH = kit.HOSTED_MCP_PATH;
|
|
13
|
+
function hostedMcpUrl(apiBase) {
|
|
14
|
+
return kit.hostedMcpUrl(apiBase);
|
|
15
|
+
}
|
|
16
|
+
async function probeHostedMcp(params) {
|
|
17
|
+
return kit.probeHostedTools({
|
|
18
|
+
apiBase: params.apiBase,
|
|
19
|
+
apiKey: params.apiKey,
|
|
20
|
+
clientIdentity: clientIdentityOf(params.client),
|
|
21
|
+
...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
|
|
22
|
+
...params.fetch !== void 0 ? { fetch: params.fetch } : {}
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/util/probe.ts
|
|
27
|
+
var PROBE_KILL_WAIT_MS = 5e3;
|
|
28
|
+
var MAX_OUTPUT = 64 * 1024;
|
|
29
|
+
function runProbe(command, args, options) {
|
|
30
|
+
return new Promise((resolve) => {
|
|
31
|
+
let child;
|
|
32
|
+
try {
|
|
33
|
+
child = spawnCommand(command, [...args], {
|
|
34
|
+
...options.env !== void 0 ? { env: options.env } : {},
|
|
35
|
+
...options.cwd !== void 0 ? { cwd: options.cwd } : {},
|
|
36
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
37
|
+
// Its own process group on POSIX, so the whole tree can be killed.
|
|
38
|
+
detached: process.platform !== "win32",
|
|
39
|
+
windowsHide: true
|
|
40
|
+
});
|
|
41
|
+
} catch (err) {
|
|
42
|
+
resolve({ error: err instanceof Error ? err : new Error(String(err)), status: null, stdout: "", stderr: "", timedOut: false });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const proc = child;
|
|
46
|
+
let stdout = "";
|
|
47
|
+
let stderr = "";
|
|
48
|
+
let timedOut = false;
|
|
49
|
+
let stopped = false;
|
|
50
|
+
let finished = false;
|
|
51
|
+
let giveUp = null;
|
|
52
|
+
const finish = (result) => {
|
|
53
|
+
if (finished) return;
|
|
54
|
+
finished = true;
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
if (giveUp !== null) clearTimeout(giveUp);
|
|
57
|
+
resolve(result);
|
|
58
|
+
};
|
|
59
|
+
proc.stdout?.on("data", (chunk) => {
|
|
60
|
+
if (stdout.length < MAX_OUTPUT) stdout += chunk.toString("utf-8");
|
|
61
|
+
});
|
|
62
|
+
proc.stderr?.on("data", (chunk) => {
|
|
63
|
+
if (stderr.length < MAX_OUTPUT) stderr += chunk.toString("utf-8");
|
|
64
|
+
});
|
|
65
|
+
const stop = (error, byTimeout) => {
|
|
66
|
+
if (timedOut || finished) return;
|
|
67
|
+
timedOut = byTimeout;
|
|
68
|
+
stopped = true;
|
|
69
|
+
killProcessTree(proc, "SIGKILL");
|
|
70
|
+
giveUp = setTimeout(() => {
|
|
71
|
+
proc.stdout?.destroy();
|
|
72
|
+
proc.stderr?.destroy();
|
|
73
|
+
finish({ error, status: null, stdout, stderr, timedOut });
|
|
74
|
+
}, PROBE_KILL_WAIT_MS);
|
|
75
|
+
proc.once("close", () => finish({ error, status: null, stdout, stderr, timedOut }));
|
|
76
|
+
};
|
|
77
|
+
const timer = setTimeout(() => stop(new Error(`${command} ${args.join(" ")} did not answer within ${Math.round(options.timeoutMs / 1e3)} s`), true), options.timeoutMs);
|
|
78
|
+
const onAbort = () => stop(new Error(`${command} ${args.join(" ")} was stopped`), false);
|
|
79
|
+
if (options.signal?.aborted) onAbort();
|
|
80
|
+
else options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
81
|
+
proc.on("error", (err) => finish({ error: err, status: null, stdout, stderr, timedOut }));
|
|
82
|
+
proc.on("close", (code) => {
|
|
83
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
84
|
+
if (!stopped) finish({ status: code, stdout, stderr, timedOut });
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export {
|
|
90
|
+
VERSION,
|
|
91
|
+
HOSTED_MCP_PATH,
|
|
92
|
+
hostedMcpUrl,
|
|
93
|
+
probeHostedMcp,
|
|
94
|
+
PROBE_KILL_WAIT_MS,
|
|
95
|
+
runProbe
|
|
96
|
+
};
|
|
97
|
+
//# sourceMappingURL=chunk-3ERPUP4M.js.map
|
|
@@ -0,0 +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.5.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":"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","names":[]}
|
|
@@ -1,8 +1,205 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
}
|
|
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)}.${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/integration/profile.ts
|
|
123
|
+
import * as fs2 from "fs";
|
|
124
|
+
import * as os from "os";
|
|
125
|
+
import * as path2 from "path";
|
|
126
|
+
var RUN_PROFILES = ["answer", "work", "full"];
|
|
127
|
+
var PEER_RUN_WARNING = "runs started by peers' messages can read and change this machine";
|
|
128
|
+
function runProfileWarning(profile) {
|
|
129
|
+
return profile === "work" || profile === "full" ? PEER_RUN_WARNING : null;
|
|
130
|
+
}
|
|
131
|
+
function identityOf(dir) {
|
|
132
|
+
try {
|
|
133
|
+
const st = fs2.statSync(dir, { bigint: true });
|
|
134
|
+
return st.ino === 0n ? null : `${st.dev}:${st.ino}`;
|
|
135
|
+
} catch {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function realOrResolved(p) {
|
|
140
|
+
const resolved = path2.resolve(p);
|
|
141
|
+
try {
|
|
142
|
+
return fs2.realpathSync.native(resolved);
|
|
143
|
+
} catch {
|
|
144
|
+
return resolved;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function spelling(p) {
|
|
148
|
+
return process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p;
|
|
149
|
+
}
|
|
150
|
+
function workdirExposesHome(workdir, home = os.homedir()) {
|
|
151
|
+
const dir = realOrResolved(workdir);
|
|
152
|
+
if (dir === path2.parse(dir).root) return true;
|
|
153
|
+
const homes = [.../* @__PURE__ */ new Set([path2.resolve(home), realOrResolved(home)])];
|
|
154
|
+
const homeIds = new Set(homes.map(identityOf).filter((id) => id !== null));
|
|
155
|
+
for (const h of homes) {
|
|
156
|
+
const parts = h.slice(path2.parse(h).root.length).split(path2.sep).filter((part) => part.length > 0);
|
|
157
|
+
for (let i = 0; i <= parts.length; i++) {
|
|
158
|
+
const candidate = path2.join(dir, ...parts.slice(i));
|
|
159
|
+
const id = identityOf(candidate);
|
|
160
|
+
if (id !== null ? homeIds.has(id) : spelling(realOrResolved(candidate)) === spelling(realOrResolved(h)) && fs2.existsSync(candidate)) return true;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
var RUN_PROFILE_ENV = "AGENTCHAT_RUN_PROFILE";
|
|
166
|
+
var DEFAULT_RUN_PROFILE = "answer";
|
|
167
|
+
function isRunProfile(value) {
|
|
168
|
+
return typeof value === "string" && RUN_PROFILES.includes(value);
|
|
169
|
+
}
|
|
170
|
+
function resolveRunProfile(env = process.env) {
|
|
171
|
+
const raw = env[RUN_PROFILE_ENV]?.trim().toLowerCase();
|
|
172
|
+
return isRunProfile(raw) ? raw : DEFAULT_RUN_PROFILE;
|
|
173
|
+
}
|
|
174
|
+
var INTEGRATION_ENV = "AGENTCHAT_INTEGRATION";
|
|
175
|
+
var INTEGRATION_ENV_LEGACY = "AGENTCHAT_DOORBELL";
|
|
176
|
+
var INTEGRATION_ENV_LEGACY_REMOVAL = "2027-02-01";
|
|
177
|
+
function isOff(raw) {
|
|
178
|
+
const value = raw?.trim().toLowerCase();
|
|
179
|
+
return value === "off" || value === "0" || value === "false";
|
|
180
|
+
}
|
|
181
|
+
function integrationDisabledBy(env = process.env) {
|
|
182
|
+
if (env[INTEGRATION_ENV] !== void 0 && env[INTEGRATION_ENV].trim().length > 0) {
|
|
183
|
+
return isOff(env[INTEGRATION_ENV]) ? INTEGRATION_ENV : null;
|
|
184
|
+
}
|
|
185
|
+
return isOff(env[INTEGRATION_ENV_LEGACY]) ? INTEGRATION_ENV_LEGACY : null;
|
|
186
|
+
}
|
|
187
|
+
function integrationDisabled(env = process.env) {
|
|
188
|
+
return integrationDisabledBy(env) !== null;
|
|
189
|
+
}
|
|
190
|
+
var RUN_BUDGET_ENV = "AGENTCHAT_RUN_BUDGET_MS";
|
|
191
|
+
var DEFAULT_RUN_BUDGET_MS = 10 * 6e4;
|
|
192
|
+
var MAX_RUN_BUDGET_MS = 2 * 60 * 6e4;
|
|
193
|
+
function resolveRunBudgetMs(env = process.env) {
|
|
194
|
+
const parsed = Number(env[RUN_BUDGET_ENV]);
|
|
195
|
+
if (!Number.isFinite(parsed) || parsed < 1e3) return DEFAULT_RUN_BUDGET_MS;
|
|
196
|
+
return Math.min(parsed, MAX_RUN_BUDGET_MS);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// src/util/spawn.ts
|
|
200
|
+
import crossSpawn from "cross-spawn";
|
|
201
|
+
var spawnCommand = crossSpawn;
|
|
202
|
+
var spawnCommandSync = crossSpawn.sync;
|
|
6
203
|
|
|
7
204
|
// src/integration/spawn-run.ts
|
|
8
205
|
var DEFAULT_GRACE_MS = 5e3;
|
|
@@ -53,7 +250,7 @@ function sweepWindowsDescendants(rootPid, aliveFromMs, aliveUntilMs, options = {
|
|
|
53
250
|
" }",
|
|
54
251
|
"}"
|
|
55
252
|
].join("\n");
|
|
56
|
-
return new Promise((
|
|
253
|
+
return new Promise((resolve2) => {
|
|
57
254
|
let stdout = "";
|
|
58
255
|
let stderr = "";
|
|
59
256
|
let timedOut = false;
|
|
@@ -63,7 +260,7 @@ function sweepWindowsDescendants(rootPid, aliveFromMs, aliveUntilMs, options = {
|
|
|
63
260
|
done = true;
|
|
64
261
|
clearTimeout(timer);
|
|
65
262
|
const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
|
|
66
|
-
|
|
263
|
+
resolve2({
|
|
67
264
|
exitCode,
|
|
68
265
|
timedOut,
|
|
69
266
|
candidates: lines.filter((l) => l.startsWith("candidate ")).map((l) => l.slice("candidate ".length)),
|
|
@@ -115,7 +312,7 @@ function spawnRun(spec) {
|
|
|
115
312
|
const graceMs = spec.graceMs ?? DEFAULT_GRACE_MS;
|
|
116
313
|
const drainMs = spec.drainMs ?? DEFAULT_DRAIN_MS;
|
|
117
314
|
const abandonMs = spec.abandonMs ?? DEFAULT_ABANDON_MS;
|
|
118
|
-
return new Promise((
|
|
315
|
+
return new Promise((resolve2) => {
|
|
119
316
|
let settled = false;
|
|
120
317
|
let stdoutBytes = 0;
|
|
121
318
|
let stderrTail = "";
|
|
@@ -139,7 +336,7 @@ function spawnRun(spec) {
|
|
|
139
336
|
for (const timer of timers) clearTimeout(timer);
|
|
140
337
|
timers.clear();
|
|
141
338
|
if (onAbort) spec.signal?.removeEventListener("abort", onAbort);
|
|
142
|
-
|
|
339
|
+
resolve2({ ...outcome, durationMs: Date.now() - started });
|
|
143
340
|
};
|
|
144
341
|
const detach = () => {
|
|
145
342
|
if (child === null) return;
|
|
@@ -274,10 +471,37 @@ function spawnRun(spec) {
|
|
|
274
471
|
}
|
|
275
472
|
|
|
276
473
|
export {
|
|
474
|
+
__export,
|
|
475
|
+
clientNameOf,
|
|
476
|
+
clientIdentityOf,
|
|
477
|
+
clientHeadersOf,
|
|
478
|
+
atomicWriteFile,
|
|
479
|
+
atomicCopyFile,
|
|
480
|
+
readJsonFile,
|
|
481
|
+
log,
|
|
482
|
+
RUN_PROFILES,
|
|
483
|
+
PEER_RUN_WARNING,
|
|
484
|
+
runProfileWarning,
|
|
485
|
+
workdirExposesHome,
|
|
486
|
+
RUN_PROFILE_ENV,
|
|
487
|
+
DEFAULT_RUN_PROFILE,
|
|
488
|
+
isRunProfile,
|
|
489
|
+
resolveRunProfile,
|
|
490
|
+
INTEGRATION_ENV,
|
|
491
|
+
INTEGRATION_ENV_LEGACY,
|
|
492
|
+
INTEGRATION_ENV_LEGACY_REMOVAL,
|
|
493
|
+
integrationDisabledBy,
|
|
494
|
+
integrationDisabled,
|
|
495
|
+
RUN_BUDGET_ENV,
|
|
496
|
+
DEFAULT_RUN_BUDGET_MS,
|
|
497
|
+
resolveRunBudgetMs,
|
|
498
|
+
spawnCommand,
|
|
499
|
+
spawnCommandSync,
|
|
277
500
|
redactDiagnostic,
|
|
501
|
+
killProcessTree,
|
|
278
502
|
WINDOWS_SWEEP_TIMEOUT_MS,
|
|
279
503
|
sweepWindowsDescendants,
|
|
280
504
|
describeWindowsSweep,
|
|
281
505
|
spawnRun
|
|
282
506
|
};
|
|
283
|
-
//# sourceMappingURL=chunk-
|
|
507
|
+
//# sourceMappingURL=chunk-AFDD53DD.js.map
|