@chroxy/server 0.11.0 → 0.11.11
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/CONFIG.md +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +215 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +170 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +27 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -0,0 +1,958 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config-driven ACP (Agent Client Protocol) provider (#7319, part of the
|
|
3
|
+
* #7304/#7306 ACP-interop tranche).
|
|
4
|
+
*
|
|
5
|
+
* `AcpSession` spawns an arbitrary ACP-speaking agent over stdio and holds
|
|
6
|
+
* the connection open for the LIFETIME of the chroxy session — one child
|
|
7
|
+
* process, many turns, with `initialize` and `session/new` happening once at
|
|
8
|
+
* start(). This mirrors `codex-app-server-session.js` (`CodexAppServerSession
|
|
9
|
+
* extends BaseSession`), NOT `jsonl-subprocess-session.js`, whose `spawn()`
|
|
10
|
+
* call sits inside `sendMessage()` and therefore starts a NEW child per
|
|
11
|
+
* message — the wrong shape for a persistent JSON-RPC agent connection. The
|
|
12
|
+
* `@agentclientprotocol/sdk` package (added by #7318) supplies the JSON-RPC
|
|
13
|
+
* framing itself (`ndJsonStream` + `client()`), so unlike
|
|
14
|
+
* `codex-app-server-client.js` there is no need for a hand-rolled transport
|
|
15
|
+
* layer here — this file IS the driving layer.
|
|
16
|
+
*
|
|
17
|
+
* Permissions ship HARDWIRED TO DENY ALL: `capabilities.inProcessPermissions`
|
|
18
|
+
* is false (so `validateProviderClass` does not require
|
|
19
|
+
* `respondToPermission`/`respondToQuestion` — see providers.js), and every
|
|
20
|
+
* `session/request_permission` the agent sends is answered with a rejection
|
|
21
|
+
* option by `_denyAllPermission`. That is a legal, safe, fully-testable
|
|
22
|
+
* intermediate state; #7320 wires the real permission bridge.
|
|
23
|
+
*
|
|
24
|
+
* Translation onto Chroxy's EXISTING outbound session events only (no new
|
|
25
|
+
* `@chroxy/protocol` wire types in this PR — see docs on `_onSessionUpdate`):
|
|
26
|
+
* - `agent_message_chunk` → stream_start / stream_delta / stream_end
|
|
27
|
+
* - `agent_thought_chunk` → stream_start / stream_delta / stream_end (thinking:true)
|
|
28
|
+
* - `tool_call` / `tool_call_update` (terminal status only) → tool_start / tool_result
|
|
29
|
+
* - `StopReason` → result (carrying `turnOutcome`, #7326) or stopped
|
|
30
|
+
* - `plan` / `available_commands_update` / `current_mode_update` — DROPPED.
|
|
31
|
+
* None of these map onto an existing outbound event; a new one would drag
|
|
32
|
+
* in ~3 separate protocol coverage guards (#7319 issue body), so they are
|
|
33
|
+
* explicitly deferred to a follow-up rather than absorbed here.
|
|
34
|
+
*
|
|
35
|
+
* Protocol version is pinned to v1 (`acp.PROTOCOL_VERSION`, the stable
|
|
36
|
+
* `@agentclientprotocol/sdk` root export) — `./experimental/v2` and the other
|
|
37
|
+
* `experimental/*` subpaths are never imported.
|
|
38
|
+
*/
|
|
39
|
+
import { spawn } from 'child_process'
|
|
40
|
+
import { Readable, Writable } from 'stream'
|
|
41
|
+
import { isAbsolute } from 'node:path'
|
|
42
|
+
import * as acp from '@agentclientprotocol/sdk'
|
|
43
|
+
import { BaseSession, buildBaseSessionOpts, CHROXY_CONTEXT_HINT_TEXT, reportInputAdmission } from './base-session.js'
|
|
44
|
+
import { prepareSpawn } from './utils/win-spawn.js'
|
|
45
|
+
import { labelBinarySpawnFailure, verifyBinary, BINARY_STATUS } from './utils/verify-binary.js'
|
|
46
|
+
import { guardChildStreams } from './child-stream-guard.js'
|
|
47
|
+
import { killProcessTree } from './platform.js'
|
|
48
|
+
import { getChroxyHostEnv } from './chroxy-host-metadata.js'
|
|
49
|
+
import { CHROXY_SECRET_DENYLIST, STANDARD_ALLOWLIST } from './utils/spawn-env.js'
|
|
50
|
+
import { validateAcpProviders } from './acp-config.js'
|
|
51
|
+
import { registerProvider, getRegisteredProviderNames } from './providers.js'
|
|
52
|
+
import { BILLING_CLASSES } from './billing-class.js'
|
|
53
|
+
import { turnOutcomeField, outcomeFromAcpStopReason } from './turn-outcome.js'
|
|
54
|
+
import { createLogger, loggerForSession } from './logger.js'
|
|
55
|
+
import { ACP_CUSTOMIZATION } from './provider-customization.js'
|
|
56
|
+
|
|
57
|
+
const log = createLogger('acp-session')
|
|
58
|
+
|
|
59
|
+
// Cap on the rendered tool_result text (mirrors codex-app-server-session.js's
|
|
60
|
+
// MAX_MCP_RESULT_CHARS) — a tool_call_update's content array can carry an
|
|
61
|
+
// arbitrarily large diff/output blob; bound it so a single tool_result can't
|
|
62
|
+
// balloon the transcript or the persisted history ring.
|
|
63
|
+
const MAX_TOOL_RESULT_CHARS = 10_000
|
|
64
|
+
|
|
65
|
+
// Cap on captured stderr (diagnostics only — surfaced in a spawn/exit error).
|
|
66
|
+
const STDERR_CAP = 2000
|
|
67
|
+
|
|
68
|
+
// #7319 review — grace window between SIGTERM and SIGKILL on teardown. The
|
|
69
|
+
// configured `command` is entirely operator-chosen and unvetted (unlike the
|
|
70
|
+
// four binaries chroxy itself resolves), so nothing guarantees it honors
|
|
71
|
+
// SIGTERM; a no-op handler would otherwise leave it running indefinitely,
|
|
72
|
+
// inheriting the daemon's own environment. Matches byok-mcp-client.js's
|
|
73
|
+
// destroy()-teardown grace exactly (KILL_GRACE_MS).
|
|
74
|
+
const ACP_KILL_GRACE_MS = 1000
|
|
75
|
+
|
|
76
|
+
// #7319 review — grace window given to `child.on('exit')` to win the race
|
|
77
|
+
// against `connection.closed` and report the informative code/signal message
|
|
78
|
+
// (see `_onConnectionClosed`) before falling back to the generic "connection
|
|
79
|
+
// closed" message. Both fire off the same underlying process teardown in the
|
|
80
|
+
// common case (near-simultaneously); this is generous enough for that ORDER
|
|
81
|
+
// to settle while still being a rounding error against the wedge it exists to
|
|
82
|
+
// unstick (previously: forever).
|
|
83
|
+
const CONNECTION_CLOSED_GRACE_MS = 250
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Build the child's environment for a configured ACP agent.
|
|
87
|
+
*
|
|
88
|
+
* ALLOWLIST posture (#7319 review), not denylist: `spawn-env.js`'s own header
|
|
89
|
+
* comment states the rule this file previously got backwards — allowlist mode
|
|
90
|
+
* is for THIRD-PARTY providers so operator secrets never reach them; denylist
|
|
91
|
+
* is for the first-party Claude CLI only. An ACP agent's `command` is entirely
|
|
92
|
+
* operator-chosen and unvetted — the least-trusted binary in the registry, not
|
|
93
|
+
* the most — so it starts from `STANDARD_ALLOWLIST` (PATH/HOME/locale/etc,
|
|
94
|
+
* the same baseline codex/gemini use) plus Chroxy's host-identity metadata,
|
|
95
|
+
* plus the entry's configured `env` overrides (highest precedence — the whole
|
|
96
|
+
* point of the config knob, e.g. to hand the agent its OWN provider API key).
|
|
97
|
+
*
|
|
98
|
+
* Chroxy's own daemon secrets (`CHROXY_SECRET_DENYLIST`, #6311's floor) are
|
|
99
|
+
* stripped LAST, after `configuredEnv` is merged — not just from the ambient
|
|
100
|
+
* allowlisted env — so a `providers.acp[].env` entry can never smuggle one
|
|
101
|
+
* back in either. This is the one place that floor is enforced against an
|
|
102
|
+
* OPERATOR-supplied input, not just an ambient one, and it must actually hold
|
|
103
|
+
* for the claim below to be true rather than aspirational.
|
|
104
|
+
*
|
|
105
|
+
* @param {Record<string,string>} configuredEnv
|
|
106
|
+
* @returns {Record<string,string>}
|
|
107
|
+
*/
|
|
108
|
+
function buildAcpChildEnv(configuredEnv) {
|
|
109
|
+
const env = {}
|
|
110
|
+
for (const key of STANDARD_ALLOWLIST) {
|
|
111
|
+
if (process.env[key] !== undefined) env[key] = process.env[key]
|
|
112
|
+
}
|
|
113
|
+
const merged = { ...env, ...getChroxyHostEnv(), ...configuredEnv }
|
|
114
|
+
for (const key of CHROXY_SECRET_DENYLIST) delete merged[key]
|
|
115
|
+
return merged
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Reduce a `tool_call`/`tool_call_update`'s `content` array (ToolCallContent[])
|
|
120
|
+
* to a `{ result, truncated }` tool_result pair. `content` items are one of
|
|
121
|
+
* `{type:'content', content: ContentBlock}`, `{type:'diff', path, ...}`, or
|
|
122
|
+
* `{type:'terminal', terminalId}` — text content blocks render verbatim,
|
|
123
|
+
* everything else renders a short marker (fs/terminal bridging — reading a
|
|
124
|
+
* diff's full text or a terminal's live output — is deferred to #7306).
|
|
125
|
+
*
|
|
126
|
+
* @param {Array<object>|null|undefined} content
|
|
127
|
+
* @returns {{ result: string, truncated: boolean }}
|
|
128
|
+
*/
|
|
129
|
+
function summarizeToolCallContent(content) {
|
|
130
|
+
if (!Array.isArray(content) || content.length === 0) return { result: '', truncated: false }
|
|
131
|
+
const parts = []
|
|
132
|
+
for (const entry of content) {
|
|
133
|
+
if (!entry || typeof entry !== 'object') continue
|
|
134
|
+
if (entry.type === 'content') {
|
|
135
|
+
const block = entry.content
|
|
136
|
+
if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
137
|
+
else if (block?.type) parts.push(`[${block.type}]`)
|
|
138
|
+
} else if (entry.type === 'diff') {
|
|
139
|
+
parts.push(`diff: ${typeof entry.path === 'string' ? entry.path : '(unknown path)'}`)
|
|
140
|
+
} else if (entry.type === 'terminal') {
|
|
141
|
+
parts.push('[terminal output]')
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const text = parts.join('\n')
|
|
145
|
+
if (text.length > MAX_TOOL_RESULT_CHARS) return { result: text.slice(0, MAX_TOOL_RESULT_CHARS), truncated: true }
|
|
146
|
+
return { result: text, truncated: false }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* #8035 — the spawn-failure backstop for an ACP agent, narrower than the one
|
|
151
|
+
* the resolved-binary providers get (#6708), because the `command` is
|
|
152
|
+
* operator-configured rather than resolved by Chroxy:
|
|
153
|
+
* - a BARE command (PATH lookup) is never labeled: `verifyBinary` reports
|
|
154
|
+
* any non-absolute path as not_found whatever the real cause (Node's own
|
|
155
|
+
* ENOENT for a missing `cwd`, say), so a label would misdiagnose it;
|
|
156
|
+
* - an ABSOLUTE command is labeled only when it is quarantined or not
|
|
157
|
+
* executable. A missing one keeps Node's raw `spawn <path> ENOENT`, which
|
|
158
|
+
* names the configured path; the generic "not found — install it" label
|
|
159
|
+
* would not, and there is nothing for the operator to install.
|
|
160
|
+
*
|
|
161
|
+
* @param {{ command: string, label: string }} entry - the validated ACP entry
|
|
162
|
+
* @param {string} prefix - message prefix naming the failed operation
|
|
163
|
+
* @param {Function} [verify=verifyBinary] - integrity checker (test seam)
|
|
164
|
+
* @returns {string|null} the labeled message, or null to keep the raw error
|
|
165
|
+
*/
|
|
166
|
+
export function labelAcpSpawnFailure(entry, prefix, verify = verifyBinary) {
|
|
167
|
+
if (typeof entry?.command !== 'string' || !isAbsolute(entry.command)) return null
|
|
168
|
+
let health
|
|
169
|
+
try {
|
|
170
|
+
health = verify(entry.command)
|
|
171
|
+
} catch {
|
|
172
|
+
return null
|
|
173
|
+
}
|
|
174
|
+
if (health?.status !== BINARY_STATUS.QUARANTINED && health?.status !== BINARY_STATUS.NOT_EXECUTABLE) return null
|
|
175
|
+
return labelBinarySpawnFailure({ attemptedPath: entry.command, binary: entry.label, prefix, verify: () => health })
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Create an AcpSession subclass for one validated config entry (the
|
|
180
|
+
* `createAnthropicCompatibleSessionClass` shape — a class-factory closing
|
|
181
|
+
* over the entry, stamped out once per configured agent by
|
|
182
|
+
* `registerAcpProviders`).
|
|
183
|
+
*
|
|
184
|
+
* @param {object} rawEntry - `{ id, label?, command, args?, env? }`
|
|
185
|
+
* @returns {typeof AcpSession}
|
|
186
|
+
*/
|
|
187
|
+
export function createAcpSessionClass(rawEntry) {
|
|
188
|
+
if (typeof rawEntry !== 'object' || rawEntry === null || typeof rawEntry.id !== 'string' || rawEntry.id.length === 0) {
|
|
189
|
+
throw new Error('createAcpSessionClass requires an entry with a non-empty id')
|
|
190
|
+
}
|
|
191
|
+
if (typeof rawEntry.command !== 'string' || rawEntry.command.length === 0) {
|
|
192
|
+
throw new Error(`acp entry '${rawEntry.id}' requires a command`)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Defensive normalization (no-op for validateAcpProviders output).
|
|
196
|
+
const entry = Object.freeze({
|
|
197
|
+
id: rawEntry.id,
|
|
198
|
+
label: typeof rawEntry.label === 'string' && rawEntry.label.length > 0 ? rawEntry.label : rawEntry.id,
|
|
199
|
+
command: rawEntry.command,
|
|
200
|
+
args: Object.freeze(Array.isArray(rawEntry.args) ? rawEntry.args.filter((a) => typeof a === 'string') : []),
|
|
201
|
+
env: Object.freeze(
|
|
202
|
+
rawEntry.env && typeof rawEntry.env === 'object' && !Array.isArray(rawEntry.env) ? { ...rawEntry.env } : {},
|
|
203
|
+
),
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
class AcpSession extends BaseSession {
|
|
207
|
+
static get customizationDescriptor() { return ACP_CUSTOMIZATION }
|
|
208
|
+
|
|
209
|
+
static get providerName() { return entry.id }
|
|
210
|
+
static get displayLabel() { return entry.label }
|
|
211
|
+
// No `~/.claude`-style local data-dir dependency — pure stdio to the
|
|
212
|
+
// configured agent. getProviderDataDirs() skips providers returning null.
|
|
213
|
+
static get dataDir() { return null }
|
|
214
|
+
static get messageIdPrefix() { return 'acp' }
|
|
215
|
+
static get apiKeyEnv() { return null }
|
|
216
|
+
|
|
217
|
+
/** The validated config entry this class was built from (introspection/tests). */
|
|
218
|
+
static get acpEntry() { return entry }
|
|
219
|
+
|
|
220
|
+
static get capabilities() {
|
|
221
|
+
return {
|
|
222
|
+
// #7319 ships permissions hardwired to deny-all — no operator-facing
|
|
223
|
+
// permission flow exists yet, so `permissions` is false (mirrors
|
|
224
|
+
// gemini-session.js's "no permission surface at all" convention
|
|
225
|
+
// rather than codex/CLI's "surfaced, in-process or hook-routed"
|
|
226
|
+
// true). #7320 flips both this and inProcessPermissions on.
|
|
227
|
+
permissions: false,
|
|
228
|
+
inProcessPermissions: false,
|
|
229
|
+
// The spawned agent picks its own model; Chroxy has no visibility or
|
|
230
|
+
// control over it in this PR.
|
|
231
|
+
modelSwitch: false,
|
|
232
|
+
permissionModeSwitch: false,
|
|
233
|
+
planMode: false,
|
|
234
|
+
resume: false,
|
|
235
|
+
// fs/* and terminal/* client methods are not implemented yet — #7306.
|
|
236
|
+
terminal: false,
|
|
237
|
+
thinkingLevel: false,
|
|
238
|
+
// #7725: the spawned ACP agent chooses its own reasoning behaviour and
|
|
239
|
+
// Chroxy never scans the prompt for the Claude magic keywords.
|
|
240
|
+
thinkingKeywords: false,
|
|
241
|
+
thinkingLevelEffective: false, // #8700: no report of the applied level
|
|
242
|
+
streaming: true,
|
|
243
|
+
// #8301: the provider-neutral turn-input seam. `sendMessage` dispatches when
|
|
244
|
+
// idle, queues via `enqueueOutgoingMessage` when busy (flushed at turn end,
|
|
245
|
+
// cleared by `interrupt()`), and reports admission through
|
|
246
|
+
// `onInputAdmission` — so a daemon-authored line (the CI-completion wake)
|
|
247
|
+
// can travel it as an ordinary user turn. session-wake.js gates on this with
|
|
248
|
+
// strict `=== true`; absent means NOT supported. Never duck-typed.
|
|
249
|
+
daemonTurnInput: true,
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// The spawned agent manages its OWN authentication (OAuth, its own API
|
|
254
|
+
// key, whatever it needs) — chroxy has no credential to check, so start()
|
|
255
|
+
// never has a "missing env var" reason to refuse.
|
|
256
|
+
static hasAlternativeCredentials() { return true }
|
|
257
|
+
|
|
258
|
+
static get preflight() {
|
|
259
|
+
return {
|
|
260
|
+
label: entry.label,
|
|
261
|
+
credentials: { envVars: [], hint: '', optional: true },
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
static resolveAuth() {
|
|
266
|
+
return {
|
|
267
|
+
ready: true,
|
|
268
|
+
source: 'none',
|
|
269
|
+
envVar: null,
|
|
270
|
+
envVars: [],
|
|
271
|
+
hint: '',
|
|
272
|
+
detail: `${entry.label} — spawns "${entry.command}" (ACP agent manages its own authentication)`,
|
|
273
|
+
// External agent, billed against whatever credential IT holds —
|
|
274
|
+
// never chroxy's own subscription/credit pool (#5630 convention).
|
|
275
|
+
billingClass: BILLING_CLASSES.API_KEY,
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// No model concept Chroxy can see or control (the agent picks its own).
|
|
280
|
+
// null/[] read as "not applicable" (mirrors dataDir's null convention),
|
|
281
|
+
// not "zero models allowed".
|
|
282
|
+
static getFallbackModels() { return [] }
|
|
283
|
+
static getAllowedModels() { return null }
|
|
284
|
+
static getModelMetadata() { return null }
|
|
285
|
+
|
|
286
|
+
constructor(opts = {}) {
|
|
287
|
+
// #5367 canonical picker — forward every BaseSession opt.
|
|
288
|
+
super(buildBaseSessionOpts(opts, { provider: opts.provider || entry.id }))
|
|
289
|
+
this._acpEntry = entry
|
|
290
|
+
this._child = null
|
|
291
|
+
this._connection = null
|
|
292
|
+
this._sessionId = null
|
|
293
|
+
// { messageId, thinkingMessageId, didStreamStart, openToolCalls,
|
|
294
|
+
// toolCallContent } — null between turns.
|
|
295
|
+
this._activeTurn = null
|
|
296
|
+
// #7319 review — inject the combined skills/preamble prefix once, on
|
|
297
|
+
// turn 1 (mirrors codex-app-server-session.js's #6606 fix).
|
|
298
|
+
this._skillsPrepended = false
|
|
299
|
+
// #7319 review — dedup so a dying child's `connection.closed` and
|
|
300
|
+
// `child.on('exit')` (which both fire off the same underlying process
|
|
301
|
+
// teardown) don't each independently report the same failure.
|
|
302
|
+
this._teardownReported = false
|
|
303
|
+
this._connectionClosedGraceTimer = null
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
_buildChildEnv() { return buildAcpChildEnv(this._acpEntry.env) }
|
|
307
|
+
|
|
308
|
+
// ------------------------------------------------------------------
|
|
309
|
+
// Lifecycle
|
|
310
|
+
// ------------------------------------------------------------------
|
|
311
|
+
|
|
312
|
+
async start() {
|
|
313
|
+
const entryRef = this._acpEntry
|
|
314
|
+
let child
|
|
315
|
+
try {
|
|
316
|
+
const spawnSpec = prepareSpawn(entryRef.command, entryRef.args)
|
|
317
|
+
child = spawn(spawnSpec.command, spawnSpec.args, {
|
|
318
|
+
cwd: this.cwd,
|
|
319
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
320
|
+
env: this._buildChildEnv(),
|
|
321
|
+
...spawnSpec.options,
|
|
322
|
+
})
|
|
323
|
+
} catch (err) {
|
|
324
|
+
// #8035 — see labelAcpSpawnFailure for which failures get a label. The
|
|
325
|
+
// label keeps the spawn error's own code, which may be the real cause.
|
|
326
|
+
const labeled = labelAcpSpawnFailure(entryRef, `Failed to spawn ACP agent "${entryRef.label}"`)
|
|
327
|
+
throw new Error(labeled
|
|
328
|
+
? `${labeled} (${err?.code || err?.message})`
|
|
329
|
+
: `Failed to spawn ACP agent "${entryRef.label}" (${entryRef.command}): ${err.message}`)
|
|
330
|
+
}
|
|
331
|
+
this._child = child
|
|
332
|
+
|
|
333
|
+
let stderrTail = ''
|
|
334
|
+
child.stderr?.on('data', (chunk) => {
|
|
335
|
+
if (stderrTail.length < STDERR_CAP) stderrTail += chunk.toString().slice(0, STDERR_CAP - stderrTail.length)
|
|
336
|
+
})
|
|
337
|
+
// #5324/#5361 pattern — an EPIPE/read-fault on stdout/stderr with no
|
|
338
|
+
// listener would otherwise crash the whole daemon.
|
|
339
|
+
guardChildStreams(child, { destroying: () => this._destroying, log, label: entryRef.id })
|
|
340
|
+
child.on('exit', (code, signal) => this._onChildExit(code, signal, stderrTail))
|
|
341
|
+
child.on('error', (err) => this._onChildError(err))
|
|
342
|
+
|
|
343
|
+
const output = Writable.toWeb(child.stdin)
|
|
344
|
+
const input = Readable.toWeb(child.stdout)
|
|
345
|
+
const stream = acp.ndJsonStream(output, input)
|
|
346
|
+
|
|
347
|
+
// Registered BEFORE connecting — a request/notification can arrive the
|
|
348
|
+
// instant the child starts talking.
|
|
349
|
+
const app = acp.client({ name: 'chroxy' })
|
|
350
|
+
.onNotification(acp.CLIENT_METHODS.session_update, (ctx) => this._onSessionUpdate(ctx.params))
|
|
351
|
+
// Trampoline (not a direct bound reference) so a test double can
|
|
352
|
+
// override `session._denyAllPermission` on the INSTANCE and have it
|
|
353
|
+
// take effect — the lookup happens at call time, not registration
|
|
354
|
+
// time. See acp-session.test.js's guard-proof test.
|
|
355
|
+
.onRequest(acp.CLIENT_METHODS.session_request_permission, (ctx) => this._denyAllPermission(ctx))
|
|
356
|
+
|
|
357
|
+
let connection
|
|
358
|
+
try {
|
|
359
|
+
connection = app.connect(stream)
|
|
360
|
+
// #7319 review — child.on('exit'/'error') is NOT actually the sole
|
|
361
|
+
// authoritative teardown signal: an agent can close stdout (ending
|
|
362
|
+
// the stream, which settles `connection.closed`) while staying alive
|
|
363
|
+
// — no exit, no error, ever. Left unconsumed, that wedges the session
|
|
364
|
+
// "ready" forever with no path back to a working turn. Route it
|
|
365
|
+
// through the SAME dedup'd teardown path as child.on('exit') so
|
|
366
|
+
// EITHER signal — whichever actually fires — reports exactly once.
|
|
367
|
+
connection.closed
|
|
368
|
+
.then(() => this._onConnectionClosed())
|
|
369
|
+
.catch((err) => this._onConnectionClosed(err))
|
|
370
|
+
this._connection = connection
|
|
371
|
+
|
|
372
|
+
const init = await connection.agent.request(acp.AGENT_METHODS.initialize, {
|
|
373
|
+
protocolVersion: acp.PROTOCOL_VERSION,
|
|
374
|
+
clientCapabilities: {},
|
|
375
|
+
clientInfo: { name: 'chroxy', version: '1' },
|
|
376
|
+
})
|
|
377
|
+
// #7319 review — the schema says the client SHOULD disconnect if the
|
|
378
|
+
// negotiated version isn't one it supports. We only ever OFFER v1;
|
|
379
|
+
// enforce that we also GOT v1 back rather than silently proceeding
|
|
380
|
+
// against an agent that negotiated something else.
|
|
381
|
+
if (init?.protocolVersion !== acp.PROTOCOL_VERSION) {
|
|
382
|
+
throw new Error(
|
|
383
|
+
`negotiated protocol version ${init?.protocolVersion} — chroxy only supports v${acp.PROTOCOL_VERSION}`,
|
|
384
|
+
)
|
|
385
|
+
}
|
|
386
|
+
const newSession = await connection.agent.request(acp.AGENT_METHODS.session_new, {
|
|
387
|
+
cwd: this.cwd,
|
|
388
|
+
mcpServers: [],
|
|
389
|
+
})
|
|
390
|
+
this._sessionId = newSession?.sessionId || null
|
|
391
|
+
} catch (err) {
|
|
392
|
+
this._connection = null
|
|
393
|
+
this._child = null
|
|
394
|
+
try { killProcessTree(child) } catch { /* already gone */ }
|
|
395
|
+
throw new Error(`Failed to initialize ACP agent "${entryRef.label}": ${err.message}`)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
this._processReady = true
|
|
399
|
+
this._log = loggerForSession('acp', this._sessionId || entryRef.id)
|
|
400
|
+
;(this._log || log).info(`ACP agent ready (id=${entryRef.id} pid=${child.pid} session=${this._sessionId})`)
|
|
401
|
+
this.emit('ready', { model: this.model })
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* #8301: `sendMessage` on a session whose agent connection is not up emits a
|
|
406
|
+
* user-visible "not started" error. A daemon wake must not cause one.
|
|
407
|
+
* @returns {string|null}
|
|
408
|
+
*/
|
|
409
|
+
daemonTurnRefusal() {
|
|
410
|
+
return (!this._processReady || !this._connection) ? 'not-started' : null
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
async sendMessage(prompt, attachments, sendOptions = {}) {
|
|
414
|
+
if (this._isBusy) {
|
|
415
|
+
const queued = this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
|
|
416
|
+
reportInputAdmission(sendOptions, queued
|
|
417
|
+
? { status: 'queued', delivery: 'queued' }
|
|
418
|
+
: {
|
|
419
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
420
|
+
reason: 'queue_full', message: 'The provider input queue is full; retry after queued work advances.',
|
|
421
|
+
})
|
|
422
|
+
return
|
|
423
|
+
}
|
|
424
|
+
if (!this._processReady || !this._connection) {
|
|
425
|
+
this.emit('error', { message: 'ACP session is not started' })
|
|
426
|
+
reportInputAdmission(sendOptions, {
|
|
427
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
428
|
+
reason: 'not_runnable', message: 'The provider session is not started.',
|
|
429
|
+
})
|
|
430
|
+
return
|
|
431
|
+
}
|
|
432
|
+
if (Array.isArray(attachments) && attachments.length > 0) {
|
|
433
|
+
// #7319 scope: attachment → ACP ContentBlock mapping (image/resource)
|
|
434
|
+
// is not implemented yet. Refuse loudly rather than silently drop the
|
|
435
|
+
// user's files, mirroring JsonlSubprocessSession's attachment refusal.
|
|
436
|
+
this.emit('error', {
|
|
437
|
+
message: `${this.constructor.displayLabel} does not support attachments yet`,
|
|
438
|
+
})
|
|
439
|
+
reportInputAdmission(sendOptions, {
|
|
440
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
441
|
+
reason: 'unsupported_attachments', message: 'This provider does not support attachments.',
|
|
442
|
+
})
|
|
443
|
+
return
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
this._isBusy = true
|
|
447
|
+
this._messageCounter += 1
|
|
448
|
+
const messageId = `msg-${this._messageIdPrefix}-${this._messageCounter}`
|
|
449
|
+
this._currentMessageId = messageId
|
|
450
|
+
// Captured locally so a stale response (a promise that resolves AFTER a
|
|
451
|
+
// timeout/interrupt/destroy already ended this turn) can be detected
|
|
452
|
+
// and ignored below, instead of re-processing a turn that already ended.
|
|
453
|
+
const turn = { messageId, thinkingMessageId: null, didStreamStart: false }
|
|
454
|
+
this._activeTurn = turn
|
|
455
|
+
this._armResultTimeout()
|
|
456
|
+
|
|
457
|
+
// #7319 review — ACP has no system-prompt channel, so the first-turn
|
|
458
|
+
// message is the ONLY vehicle for the session preamble, the chroxy
|
|
459
|
+
// context hint, and any loaded skill (mirrors codex-app-server-
|
|
460
|
+
// session.js's #6606 fix for the identical "no system channel" shape).
|
|
461
|
+
// Flipped to true only AFTER the request succeeds so a failed first
|
|
462
|
+
// turn still retries with the prefix (jsonl-subprocess-session.js's
|
|
463
|
+
// discipline for the same flag).
|
|
464
|
+
let text = prompt || ''
|
|
465
|
+
const willPrependFirstTurn = !this._skillsPrepended
|
|
466
|
+
if (willPrependFirstTurn) {
|
|
467
|
+
const prefix = this._buildFirstTurnPrefix()
|
|
468
|
+
if (prefix) text = `${prefix}\n\n---\n\n${text}`
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
let res
|
|
472
|
+
try {
|
|
473
|
+
const request = this._connection.agent.request(acp.AGENT_METHODS.session_prompt, {
|
|
474
|
+
sessionId: this._sessionId,
|
|
475
|
+
prompt: [{ type: 'text', text }],
|
|
476
|
+
})
|
|
477
|
+
// request() has synchronously admitted the prompt to the persistent
|
|
478
|
+
// transport. The promise represents the whole turn, so do not delay
|
|
479
|
+
// admission until the model response completes.
|
|
480
|
+
reportInputAdmission(sendOptions, { status: 'accepted', delivery: 'dispatch_started' })
|
|
481
|
+
res = await request
|
|
482
|
+
if (willPrependFirstTurn) this._skillsPrepended = true
|
|
483
|
+
} catch (err) {
|
|
484
|
+
if (this._activeTurn !== turn) return
|
|
485
|
+
this._failTurn(`ACP agent error: ${err.message}`)
|
|
486
|
+
return
|
|
487
|
+
}
|
|
488
|
+
if (this._activeTurn !== turn) return
|
|
489
|
+
this._finishTurn(res)
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* The combined first-turn prefix: session preamble, then the chroxy
|
|
494
|
+
* context hint, then every loaded skill (prepend + append/system buckets
|
|
495
|
+
* combined — `_buildCombinedSkillsPrefix()` already de-duplicates those
|
|
496
|
+
* two buckets for a provider with no separate system-prompt channel; do
|
|
497
|
+
* NOT also call `_buildSystemPrompt()`, whose OWN skillsText source is
|
|
498
|
+
* the same append bucket and would double-inject it). Same ordering as
|
|
499
|
+
* `_buildSystemPrompt()` for consistency. Empty string when nothing is
|
|
500
|
+
* configured, so the `sendMessage` caller can branch on truthiness.
|
|
501
|
+
*
|
|
502
|
+
* @returns {string}
|
|
503
|
+
*/
|
|
504
|
+
_buildFirstTurnPrefix() {
|
|
505
|
+
const parts = []
|
|
506
|
+
if (this.sessionPreamble) parts.push(this.sessionPreamble)
|
|
507
|
+
if (this.chroxyContextHint) parts.push(CHROXY_CONTEXT_HINT_TEXT)
|
|
508
|
+
const skills = typeof this._buildCombinedSkillsPrefix === 'function' ? this._buildCombinedSkillsPrefix() : ''
|
|
509
|
+
if (skills) parts.push(skills)
|
|
510
|
+
return parts.join('\n\n')
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// ------------------------------------------------------------------
|
|
514
|
+
// session/update → Chroxy event mapping
|
|
515
|
+
// ------------------------------------------------------------------
|
|
516
|
+
|
|
517
|
+
_onSessionUpdate(params) {
|
|
518
|
+
if (!this._activeTurn) return // between turns: ignore stray updates
|
|
519
|
+
if (params?.sessionId && this._sessionId && params.sessionId !== this._sessionId) return
|
|
520
|
+
this._resetResultTimeout()
|
|
521
|
+
const update = params?.update
|
|
522
|
+
if (!update) return
|
|
523
|
+
switch (update.sessionUpdate) {
|
|
524
|
+
case 'agent_message_chunk':
|
|
525
|
+
this._onAgentMessageChunk(update)
|
|
526
|
+
break
|
|
527
|
+
case 'agent_thought_chunk':
|
|
528
|
+
this._onAgentThoughtChunk(update)
|
|
529
|
+
break
|
|
530
|
+
case 'tool_call':
|
|
531
|
+
this._onToolCall(update)
|
|
532
|
+
break
|
|
533
|
+
case 'tool_call_update':
|
|
534
|
+
this._onToolCallUpdate(update)
|
|
535
|
+
break
|
|
536
|
+
default:
|
|
537
|
+
// user_message_chunk / plan / plan_update / plan_removed /
|
|
538
|
+
// available_commands_update / current_mode_update / config_option_update /
|
|
539
|
+
// session_info_update / usage_update / compaction_* — no matching
|
|
540
|
+
// existing outbound event (see the file-header doc). Dropped in #7319.
|
|
541
|
+
break
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
_onAgentMessageChunk(update) {
|
|
546
|
+
const text = update?.content?.type === 'text' ? update.content.text : ''
|
|
547
|
+
if (!text) return
|
|
548
|
+
const t = this._activeTurn
|
|
549
|
+
if (!t.didStreamStart) {
|
|
550
|
+
t.didStreamStart = true
|
|
551
|
+
this.emit('stream_start', { messageId: t.messageId })
|
|
552
|
+
}
|
|
553
|
+
this.emit('stream_delta', { messageId: t.messageId, delta: text })
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
_onAgentThoughtChunk(update) {
|
|
557
|
+
const text = update?.content?.type === 'text' ? update.content.text : ''
|
|
558
|
+
if (!text) return
|
|
559
|
+
const t = this._activeTurn
|
|
560
|
+
if (!t.thinkingMessageId) {
|
|
561
|
+
t.thinkingMessageId = `${t.messageId}-thinking`
|
|
562
|
+
this.emit('stream_start', { messageId: t.thinkingMessageId, thinking: true })
|
|
563
|
+
}
|
|
564
|
+
this.emit('stream_delta', { messageId: t.thinkingMessageId, delta: text, thinking: true })
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// #7319 review — `ToolCall.status` is OPTIONAL and schema-legal to
|
|
568
|
+
// already be terminal on the VERY FIRST message about a call (only
|
|
569
|
+
// `toolCallId` + `title` are required); the SDK's own example agent
|
|
570
|
+
// always splits open/close into two messages, which is what the original
|
|
571
|
+
// implementation silently assumed. Ignoring `update.status` here left a
|
|
572
|
+
// tool_call that arrives pre-completed open for the rest of the turn, so
|
|
573
|
+
// the turn-end orphan sweep (BaseSession._sweepUnresolvedToolStarts)
|
|
574
|
+
// synthesized a FALSE "did not emit a result" failure for a tool that
|
|
575
|
+
// actually succeeded. Close immediately when the initial message is
|
|
576
|
+
// already terminal, exactly as if a separate tool_call_update had
|
|
577
|
+
// followed it.
|
|
578
|
+
_onToolCall(update) {
|
|
579
|
+
const toolUseId = update?.toolCallId
|
|
580
|
+
if (typeof toolUseId !== 'string' || toolUseId.length === 0) return
|
|
581
|
+
const t = this._activeTurn
|
|
582
|
+
if (!t.openToolCalls) t.openToolCalls = new Set()
|
|
583
|
+
t.openToolCalls.add(toolUseId)
|
|
584
|
+
this._rememberToolCallContent(t, toolUseId, update.content)
|
|
585
|
+
const tool = update.kind || update.name || 'tool'
|
|
586
|
+
this.emit('tool_start', {
|
|
587
|
+
messageId: t.messageId,
|
|
588
|
+
toolUseId,
|
|
589
|
+
tool,
|
|
590
|
+
input: { title: update.title, kind: update.kind, rawInput: update.rawInput, locations: update.locations },
|
|
591
|
+
})
|
|
592
|
+
this._trackToolStart(toolUseId, tool)
|
|
593
|
+
if (update.status === 'completed' || update.status === 'failed') {
|
|
594
|
+
this._closeToolCall(toolUseId, update.status)
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
_onToolCallUpdate(update) {
|
|
599
|
+
const toolUseId = update?.toolCallId
|
|
600
|
+
if (typeof toolUseId !== 'string' || toolUseId.length === 0) return
|
|
601
|
+
const t = this._activeTurn
|
|
602
|
+
this._rememberToolCallContent(t, toolUseId, update.content)
|
|
603
|
+
const status = update.status
|
|
604
|
+
// Non-terminal progress updates (pending/in_progress) have no matching
|
|
605
|
+
// existing outbound event beyond remembering their content above —
|
|
606
|
+
// only a completed/failed update closes the tool_start opened earlier
|
|
607
|
+
// (or synthesizes one, for a nonconformant agent that updates before
|
|
608
|
+
// it ever opened the call).
|
|
609
|
+
if (status !== 'completed' && status !== 'failed') return
|
|
610
|
+
if (!t.openToolCalls || !t.openToolCalls.has(toolUseId)) {
|
|
611
|
+
this._onToolCall({ toolCallId: toolUseId, title: update.title, kind: update.kind, name: update.name, rawInput: update.rawInput, locations: update.locations })
|
|
612
|
+
// The synthetic open above carries no `status`, so it never
|
|
613
|
+
// self-closes — fall through and close with the status we actually
|
|
614
|
+
// received.
|
|
615
|
+
}
|
|
616
|
+
this._closeToolCall(toolUseId, status)
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// #7319 review — `ToolCallUpdate`'s fields are ALL optional except
|
|
620
|
+
// `toolCallId` ("only changed fields need to be included" — the schema's
|
|
621
|
+
// own words), so a terminal update legitimately omits `content` when it
|
|
622
|
+
// didn't change since an earlier tick (e.g. content arrives on an
|
|
623
|
+
// in-progress update, then a bare `status:'completed'` follows with no
|
|
624
|
+
// content of its own). Remembering the latest non-empty content per
|
|
625
|
+
// toolCallId and reading it back here means a contentless terminal
|
|
626
|
+
// update can never blank out real output that already arrived.
|
|
627
|
+
_rememberToolCallContent(t, toolUseId, content) {
|
|
628
|
+
if (!t.toolCallContent) t.toolCallContent = new Map()
|
|
629
|
+
if (Array.isArray(content) && content.length > 0) t.toolCallContent.set(toolUseId, content)
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
_closeToolCall(toolUseId, status) {
|
|
633
|
+
const t = this._activeTurn
|
|
634
|
+
if (!t.openToolCalls || !t.openToolCalls.has(toolUseId)) return // already closed
|
|
635
|
+
t.openToolCalls.delete(toolUseId)
|
|
636
|
+
const content = t.toolCallContent?.get(toolUseId) ?? null
|
|
637
|
+
t.toolCallContent?.delete(toolUseId)
|
|
638
|
+
const { result, truncated } = summarizeToolCallContent(content)
|
|
639
|
+
this.emit('tool_result', { toolUseId, result, truncated, isError: status === 'failed' })
|
|
640
|
+
this._trackToolResult(toolUseId)
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// ------------------------------------------------------------------
|
|
644
|
+
// Turn completion
|
|
645
|
+
// ------------------------------------------------------------------
|
|
646
|
+
|
|
647
|
+
_closeOpenStreams(t) {
|
|
648
|
+
if (!t) return
|
|
649
|
+
if (t.didStreamStart) this.emit('stream_end', { messageId: t.messageId })
|
|
650
|
+
if (t.thinkingMessageId) this.emit('stream_end', { messageId: t.thinkingMessageId })
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* `session/prompt` resolved. `StopReason` (`end_turn` / `max_tokens` /
|
|
655
|
+
* `max_turn_requests` / `refusal` / `cancelled`) maps onto Chroxy's
|
|
656
|
+
* existing turn-boundary events: any turn that resolved while
|
|
657
|
+
* `interrupt()`'s intentional-stop flag was armed, regardless of what the
|
|
658
|
+
* agent reported, is a `stopped` exactly like every other provider's
|
|
659
|
+
* interrupt path; everything else is a `result`.
|
|
660
|
+
*
|
|
661
|
+
* #7326: that `result` now says HOW the turn ended, through the
|
|
662
|
+
* provider-neutral `turnOutcome` (turn-outcome.js): `end_turn` completed,
|
|
663
|
+
* `max_tokens` / `max_turn_requests` truncated, `refusal` refused,
|
|
664
|
+
* `cancelled` stopped. A `cancelled` the agent reports on its own (we did
|
|
665
|
+
* not ask for it) used to surface as a loud error with no turn boundary; it
|
|
666
|
+
* is now a `result` carrying `stopped`, so the turn ends cleanly and the
|
|
667
|
+
* clients mark it, rather than showing a failure nobody caused.
|
|
668
|
+
*/
|
|
669
|
+
_finishTurn(res) {
|
|
670
|
+
const t = this._activeTurn
|
|
671
|
+
this._clearResultTimeout()
|
|
672
|
+
this._closeOpenStreams(t)
|
|
673
|
+
this._activeTurn = null
|
|
674
|
+
const wasIntentional = this._consumeIntentionalStop()
|
|
675
|
+
if (wasIntentional) {
|
|
676
|
+
// #9241: the prompt RESOLVED while the Stop was armed: the requested stop. (The
|
|
677
|
+
// failure path below also reports `stopped`, without this word.)
|
|
678
|
+
// Only a `cancelled` stop reason is the cancel being honoured; a limit or a
|
|
679
|
+
// refusal that won the race with `session/cancel` is not a Stop.
|
|
680
|
+
this.emit('stopped', res?.stopReason === 'cancelled' ? { stopRequested: true } : {})
|
|
681
|
+
this._clearMessageState()
|
|
682
|
+
this._maybeDequeue()
|
|
683
|
+
return
|
|
684
|
+
}
|
|
685
|
+
this._emitResult(
|
|
686
|
+
{
|
|
687
|
+
cost: null,
|
|
688
|
+
duration: null,
|
|
689
|
+
usage: null,
|
|
690
|
+
sessionId: this._sessionId,
|
|
691
|
+
...turnOutcomeField(outcomeFromAcpStopReason(res?.stopReason)),
|
|
692
|
+
},
|
|
693
|
+
'turn_ended_with_orphan_tool_start',
|
|
694
|
+
)
|
|
695
|
+
this._clearIntentionalStop()
|
|
696
|
+
this._clearMessageState()
|
|
697
|
+
this._maybeDequeue()
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
_failTurn(message, { code } = {}) {
|
|
701
|
+
const t = this._activeTurn
|
|
702
|
+
this._clearResultTimeout()
|
|
703
|
+
this._closeOpenStreams(t)
|
|
704
|
+
this._activeTurn = null
|
|
705
|
+
const wasIntentional = this._consumeIntentionalStop()
|
|
706
|
+
if (wasIntentional) this.emit('stopped', {})
|
|
707
|
+
else this.emit('error', code ? { message, code } : { message })
|
|
708
|
+
this._clearMessageState()
|
|
709
|
+
this._maybeDequeue()
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
_maybeDequeue() {
|
|
713
|
+
if (this._outgoingQueue.length && !this._destroying) this.dequeueNextOutgoing()
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// ------------------------------------------------------------------
|
|
717
|
+
// Result timeout (soft warning only — mirrors codex-app-server-session.js;
|
|
718
|
+
// no hard-timeout / stream-stall machinery, which even that reference
|
|
719
|
+
// doesn't implement).
|
|
720
|
+
// ------------------------------------------------------------------
|
|
721
|
+
|
|
722
|
+
_armResultTimeout() {
|
|
723
|
+
this._clearResultTimeout()
|
|
724
|
+
this._resultTimeout = setTimeout(() => {
|
|
725
|
+
;(this._log || log).warn(`ACP agent turn result timeout (msg=${this._currentMessageId})`)
|
|
726
|
+
this._failTurn('ACP agent turn timed out with no result')
|
|
727
|
+
}, this._resultTimeoutMs)
|
|
728
|
+
if (typeof this._resultTimeout.unref === 'function') this._resultTimeout.unref()
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
_resetResultTimeout() {
|
|
732
|
+
if (this._activeTurn) this._armResultTimeout()
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
_clearResultTimeout() {
|
|
736
|
+
if (this._resultTimeout) { clearTimeout(this._resultTimeout); this._resultTimeout = null }
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// ------------------------------------------------------------------
|
|
740
|
+
// Permissions — hardwired to deny-all (#7319). #7320 replaces this with
|
|
741
|
+
// the real PermissionManager bridge.
|
|
742
|
+
// ------------------------------------------------------------------
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* Answer a `session/request_permission` request with a rejection. Picks a
|
|
746
|
+
* `reject_once` (preferred — the most locally-scoped decline) or
|
|
747
|
+
* `reject_always` option from whatever the agent offered; falls back to
|
|
748
|
+
* the protocol-legal `{outcome:'cancelled'}` if the agent offered no
|
|
749
|
+
* reject option at all (defensive — every real ACP agent offers one).
|
|
750
|
+
*
|
|
751
|
+
* @param {{params: import('@agentclientprotocol/sdk').RequestPermissionRequest}} ctx
|
|
752
|
+
*/
|
|
753
|
+
async _denyAllPermission(ctx) {
|
|
754
|
+
const options = Array.isArray(ctx?.params?.options) ? ctx.params.options : []
|
|
755
|
+
const reject = options.find((o) => o?.kind === 'reject_once') || options.find((o) => o?.kind === 'reject_always')
|
|
756
|
+
const toolCallId = ctx?.params?.toolCall?.toolCallId ?? 'unknown'
|
|
757
|
+
;(this._log || log).info(
|
|
758
|
+
`ACP permission request denied by default (toolCallId=${toolCallId}) — the permission bridge lands in #7320`,
|
|
759
|
+
)
|
|
760
|
+
if (reject) return { outcome: { outcome: 'selected', optionId: reject.optionId } }
|
|
761
|
+
return { outcome: { outcome: 'cancelled' } }
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// ------------------------------------------------------------------
|
|
765
|
+
// Child / connection teardown
|
|
766
|
+
// ------------------------------------------------------------------
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* Single choke point for reporting an UNEXPECTED teardown, from whichever
|
|
770
|
+
* signal actually fires first (#7319 review — `child.on('exit')` and
|
|
771
|
+
* `connection.closed` both stem from the same underlying process death in
|
|
772
|
+
* the common case, with no ordering guarantee between them; an agent that
|
|
773
|
+
* closes stdout while staying alive fires ONLY `connection.closed`, never
|
|
774
|
+
* `exit`). `_teardownReported` makes this report exactly once regardless
|
|
775
|
+
* of which signal(s) fire, or in which order.
|
|
776
|
+
*/
|
|
777
|
+
_reportTeardown(message, { recoverable = true } = {}) {
|
|
778
|
+
if (this._destroying || this._teardownReported) return
|
|
779
|
+
this._teardownReported = true
|
|
780
|
+
this._processReady = false
|
|
781
|
+
if (this._activeTurn) this._failTurn(message)
|
|
782
|
+
else this.emit('error', { message, recoverable })
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
_onChildExit(code, signal, stderrTail) {
|
|
786
|
+
if (this._destroying) return
|
|
787
|
+
const detail = `code=${code}${signal ? ` signal=${signal}` : ''}`
|
|
788
|
+
;(this._log || log).warn(`ACP agent "${this._acpEntry.id}" exited unexpectedly (${detail})`)
|
|
789
|
+
const tail = stderrTail ? `: ${stderrTail.slice(0, 500)}` : ''
|
|
790
|
+
this._reportTeardown(`ACP agent "${this._acpEntry.label}" exited unexpectedly (${detail})${tail}`)
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
_onChildError(err) {
|
|
794
|
+
if (this._destroying) return
|
|
795
|
+
// #8035 — same backstop as start()'s sync spawn catch.
|
|
796
|
+
const labeled = labelAcpSpawnFailure(this._acpEntry, `Failed to run ACP agent "${this._acpEntry.label}"`)
|
|
797
|
+
this._reportTeardown(labeled
|
|
798
|
+
? `${labeled} (${err?.code || err?.message})`
|
|
799
|
+
: `Failed to run ACP agent "${this._acpEntry.label}": ${err.message}`)
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* `connection.closed` settled — either because WE closed it (destroy(),
|
|
804
|
+
* guarded by `_destroying` above), the child exited (child.on('exit')
|
|
805
|
+
* fires too; whichever of the two gets here first wins via
|
|
806
|
+
* `_teardownReported`), or — the case this handler exists to catch — the
|
|
807
|
+
* agent closed stdout while remaining alive, which `child.on('exit')`
|
|
808
|
+
* never sees at all.
|
|
809
|
+
*
|
|
810
|
+
* Deferred by a short grace window rather than reported immediately: if
|
|
811
|
+
* `child.on('exit')` is ALSO about to fire (the common case), it carries
|
|
812
|
+
* the useful exit code/signal and should win the race and report that
|
|
813
|
+
* instead of this generic message. Reporting synchronously here would
|
|
814
|
+
* make the generic message win essentially every time (stdout 'end'
|
|
815
|
+
* tends to observably precede the 'exit' event), producing a double
|
|
816
|
+
* report — the exact defect a prior version of this file had (#7319
|
|
817
|
+
* review finding #10).
|
|
818
|
+
*/
|
|
819
|
+
_onConnectionClosed(err) {
|
|
820
|
+
if (this._destroying || this._teardownReported) return
|
|
821
|
+
const detail = err ? `: ${err.message}` : ''
|
|
822
|
+
this._connectionClosedGraceTimer = setTimeout(() => {
|
|
823
|
+
this._connectionClosedGraceTimer = null
|
|
824
|
+
this._reportTeardown(`ACP agent "${this._acpEntry.label}" connection closed unexpectedly${detail}`)
|
|
825
|
+
}, CONNECTION_CLOSED_GRACE_MS)
|
|
826
|
+
if (typeof this._connectionClosedGraceTimer.unref === 'function') this._connectionClosedGraceTimer.unref()
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// ------------------------------------------------------------------
|
|
830
|
+
// Interrupt / teardown
|
|
831
|
+
// ------------------------------------------------------------------
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* #7319 review — `markIntentionalStop()` and the `session/cancel` notify
|
|
835
|
+
* are gated behind an ACTIVE turn (mirrors SdkSession.interrupt(),
|
|
836
|
+
* sdk-session.js:1844: "return early when no query is active").
|
|
837
|
+
* `clearOutgoingQueue()` stays unconditional either way, matching that
|
|
838
|
+
* same method — a deliberate Stop should always cancel queued follow-ups,
|
|
839
|
+
* even with nothing currently running.
|
|
840
|
+
*
|
|
841
|
+
* Without the guard, tapping Stop between turns (input-handlers.js calls
|
|
842
|
+
* interrupt() with no busy check) armed the flag with no active turn to
|
|
843
|
+
* consume it — `_finishTurn` is the ONLY consumer, so the flag sat armed
|
|
844
|
+
* until the NEXT turn's clean `end_turn` completion, which then read it
|
|
845
|
+
* as an intentional stop and emitted `stopped` with no `result` event at
|
|
846
|
+
* all for a turn nobody interrupted.
|
|
847
|
+
*/
|
|
848
|
+
async interrupt() {
|
|
849
|
+
this.clearOutgoingQueue()
|
|
850
|
+
if (!this._activeTurn) return
|
|
851
|
+
this.markIntentionalStop()
|
|
852
|
+
if (this._connection && this._sessionId) {
|
|
853
|
+
try { await this._connection.agent.notify(acp.AGENT_METHODS.session_cancel, { sessionId: this._sessionId }) }
|
|
854
|
+
catch (err) { (this._log || log).debug(`session/cancel notify failed: ${err.message}`) }
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
async destroy() {
|
|
859
|
+
this._destroying = true
|
|
860
|
+
this.clearOutgoingQueue({ emit: false })
|
|
861
|
+
this._clearIntentionalStop()
|
|
862
|
+
this._clearResultTimeout()
|
|
863
|
+
if (this._connectionClosedGraceTimer) { clearTimeout(this._connectionClosedGraceTimer); this._connectionClosedGraceTimer = null }
|
|
864
|
+
this._activeTurn = null
|
|
865
|
+
if (this._connection) {
|
|
866
|
+
try { this._connection.close() } catch { /* already gone */ }
|
|
867
|
+
this._connection = null
|
|
868
|
+
}
|
|
869
|
+
if (this._child) {
|
|
870
|
+
await this._killChildWithGrace(this._child)
|
|
871
|
+
this._child = null
|
|
872
|
+
}
|
|
873
|
+
this._clearMessageState()
|
|
874
|
+
this._destroyPendingBackgroundShells()
|
|
875
|
+
this._processReady = false
|
|
876
|
+
this.removeAllListeners()
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/**
|
|
880
|
+
* #7319 review — a bare `killProcessTree()` is a SIGTERM-only request on
|
|
881
|
+
* POSIX (platform.js): it relies on the child actually honoring the
|
|
882
|
+
* signal. This provider's binary is entirely operator-chosen and
|
|
883
|
+
* unvetted (verified: an agent with a no-op SIGTERM handler was still
|
|
884
|
+
* alive 4.2s later) — an orphan here inherits the daemon's own
|
|
885
|
+
* environment, the expensive kind of leak. Escalate to SIGKILL after a
|
|
886
|
+
* short grace window, mirroring byok-mcp-client.js's destroy() teardown.
|
|
887
|
+
* Resolves once the child actually exits, or once the grace window
|
|
888
|
+
* elapses and SIGKILL is sent — whichever comes first.
|
|
889
|
+
*
|
|
890
|
+
* @param {import('child_process').ChildProcess} child
|
|
891
|
+
* @returns {Promise<void>}
|
|
892
|
+
*/
|
|
893
|
+
_killChildWithGrace(child) {
|
|
894
|
+
// Already exited (e.g. the child died on its own — _onChildExit
|
|
895
|
+
// already ran — and destroy() is only now cleaning up) — nothing to
|
|
896
|
+
// signal or wait out. Node never replays a past 'exit' to a listener
|
|
897
|
+
// attached after the fact, so without this check we'd needlessly burn
|
|
898
|
+
// the full grace window waiting on an event that will never fire.
|
|
899
|
+
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()
|
|
900
|
+
return new Promise((resolve) => {
|
|
901
|
+
let settled = false
|
|
902
|
+
const finish = () => {
|
|
903
|
+
if (settled) return
|
|
904
|
+
settled = true
|
|
905
|
+
clearTimeout(graceTimer)
|
|
906
|
+
resolve()
|
|
907
|
+
}
|
|
908
|
+
child.once('exit', finish)
|
|
909
|
+
try { killProcessTree(child) } catch { /* already gone */ }
|
|
910
|
+
const graceTimer = setTimeout(() => {
|
|
911
|
+
try { killProcessTree(child, { force: true }) } catch { /* already gone */ }
|
|
912
|
+
finish()
|
|
913
|
+
}, ACP_KILL_GRACE_MS)
|
|
914
|
+
if (typeof graceTimer.unref === 'function') graceTimer.unref()
|
|
915
|
+
})
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
return AcpSession
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
/**
|
|
923
|
+
* Register every valid `providers.acp` entry from the merged config as a
|
|
924
|
+
* first-class provider (#7319) — one registered provider per configured
|
|
925
|
+
* agent, mirroring `registerAnthropicCompatibleProviders`. Called once at
|
|
926
|
+
* server startup (server-cli.js).
|
|
927
|
+
*
|
|
928
|
+
* Invalid entries are logged and skipped; valid siblings still register.
|
|
929
|
+
* Collisions are checked against both the static RESERVED_PROVIDER_IDS and
|
|
930
|
+
* the LIVE registry at call time.
|
|
931
|
+
*
|
|
932
|
+
* @param {object | null | undefined} config - Merged server config
|
|
933
|
+
* @returns {string[]} The provider ids that were registered
|
|
934
|
+
*/
|
|
935
|
+
export function registerAcpProviders(config) {
|
|
936
|
+
const block = config?.providers
|
|
937
|
+
// Legacy form: `providers` as an array of provider-id strings
|
|
938
|
+
// (informational, written by `chroxy init`) — nothing to register.
|
|
939
|
+
if (typeof block !== 'object' || block === null || Array.isArray(block)) return []
|
|
940
|
+
if (!Object.prototype.hasOwnProperty.call(block, 'acp')) return []
|
|
941
|
+
|
|
942
|
+
const { entries, warnings } = validateAcpProviders(block.acp, {
|
|
943
|
+
reservedIds: getRegisteredProviderNames(),
|
|
944
|
+
})
|
|
945
|
+
for (const warning of warnings) {
|
|
946
|
+
log.warn(warning)
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
const registered = []
|
|
950
|
+
for (const entry of entries) {
|
|
951
|
+
registerProvider(entry.id, createAcpSessionClass(entry))
|
|
952
|
+
registered.push(entry.id)
|
|
953
|
+
log.info(
|
|
954
|
+
`ACP provider registered: ${entry.id} → ${entry.command}${entry.args.length ? ` ${entry.args.join(' ')}` : ''} (permissions: deny-all)`,
|
|
955
|
+
)
|
|
956
|
+
}
|
|
957
|
+
return registered
|
|
958
|
+
}
|