@chroxy/server 0.10.0 → 0.11.10
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 +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- 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 +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- 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 +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- 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 +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- 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-stream-parser.js +109 -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 +223 -60
- 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 +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -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 +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- 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 +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- 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 +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- 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 +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- 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 +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- 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 +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -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 +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -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 +100 -10
- 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 +82 -12
- 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 +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- 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 +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- 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-title.js +168 -0
- package/src/session-token-store.js +70 -36
- 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 +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- 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/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -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 +301 -0
- package/src/utils/composite-key.js +45 -0
- 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/iso-datetime.js +51 -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/preflight.js +485 -29
- 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 +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- 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/summarize-session.js
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
import { query } from '@anthropic-ai/claude-agent-sdk'
|
|
24
24
|
import { extractSearchableText } from './conversation-search.js'
|
|
25
25
|
import { createLogger } from './logger.js'
|
|
26
|
+
import { buildSpawnEnv } from './utils/spawn-env.js'
|
|
26
27
|
|
|
27
28
|
const log = createLogger('summarize')
|
|
28
29
|
|
|
@@ -50,6 +51,9 @@ export function flattenHistory(history) {
|
|
|
50
51
|
const lines = []
|
|
51
52
|
for (const entry of history) {
|
|
52
53
|
if (!entry || typeof entry !== 'object') continue
|
|
54
|
+
// #8348: a permission prompt's outcome is a transcript marker, not
|
|
55
|
+
// conversation; its `tool` field would otherwise flatten to a bare "[Bash]".
|
|
56
|
+
if (entry.type === 'permission_outcome') continue
|
|
53
57
|
// extractSearchableText reads entry.message.content; chroxy history entries
|
|
54
58
|
// store their text on `content`. Normalize so the shared flattener sees a
|
|
55
59
|
// message-shaped object regardless of which source produced the entry.
|
|
@@ -178,14 +182,45 @@ export function buildSummaryPrompt({ transcript, truncated, sessionName }) {
|
|
|
178
182
|
* user prompt, and the result text collected from assistant content blocks.
|
|
179
183
|
* Used when the caller doesn't inject a `runOneShot` seam.
|
|
180
184
|
*
|
|
185
|
+
* `queryFn` is an injectable seam (defaults to the real SDK `query`) so a test
|
|
186
|
+
* can assert on the built options — including `pathToClaudeCodeExecutable`
|
|
187
|
+
* (#7986) — without module-mocking `@anthropic-ai/claude-agent-sdk`.
|
|
188
|
+
*
|
|
189
|
+
* `resolveExecutable` has NO default (#8030) — it is a REQUIRED, verified
|
|
190
|
+
* binary-gate call, not a plain path resolve. Before #8030 this defaulted to
|
|
191
|
+
* `resolveClaudeBinary()`, which resolves a path but verifies nothing: a
|
|
192
|
+
* `block`-mode hash-mismatched `claude` that `createSession` would refuse
|
|
193
|
+
* could still be spawned by this one-shot path (the summarizer, the
|
|
194
|
+
* semantic-title generator) with no gate at all. Every caller now supplies a
|
|
195
|
+
* verified resolver — production wires `SessionManager.verifyOneShotExecutable`
|
|
196
|
+
* (see summarize-handlers.js / session-manager.js's `_generateSemanticTitle`),
|
|
197
|
+
* which re-runs the SAME preflight gate `createSession` runs.
|
|
198
|
+
*
|
|
181
199
|
* @param {object} args
|
|
182
200
|
* @param {string} args.prompt
|
|
183
201
|
* @param {string} [args.model] - model id; omitted lets the SDK pick its default.
|
|
184
202
|
* @param {string} [args.cwd]
|
|
185
203
|
* @param {AbortSignal} [args.signal]
|
|
204
|
+
* @param {Function} [args.queryFn] - injected in tests; defaults to the SDK's `query`.
|
|
205
|
+
* @param {Function} args.resolveExecutable - REQUIRED (#8030): `() => string`,
|
|
206
|
+
* a verified binary-gate call. Throwing a `PROVIDER_BINARY_*`-coded error
|
|
207
|
+
* refuses the spawn before `queryFn` is ever invoked.
|
|
186
208
|
* @returns {Promise<string>} the model's text reply.
|
|
209
|
+
* @throws {Error} when `resolveExecutable` is not a function, or when it throws.
|
|
187
210
|
*/
|
|
188
|
-
export async function defaultRunOneShot({ prompt, model, cwd, signal }) {
|
|
211
|
+
export async function defaultRunOneShot({ prompt, model, cwd, signal, queryFn = query, resolveExecutable }) {
|
|
212
|
+
if (typeof resolveExecutable !== 'function') {
|
|
213
|
+
throw new Error('defaultRunOneShot (#8030): resolveExecutable is required — the caller must supply its verified spawn gate (e.g. SessionManager.verifyOneShotExecutable) instead of relying on an unverified default binary resolve.')
|
|
214
|
+
}
|
|
215
|
+
// Resolved BEFORE queryFn so a gate refusal never spawns anything. An empty
|
|
216
|
+
// result is refused too: with pathToClaudeCodeExecutable unset the SDK falls
|
|
217
|
+
// back to its own bundled binary, which nothing has verified.
|
|
218
|
+
const executable = resolveExecutable()
|
|
219
|
+
if (typeof executable !== 'string' || executable.length === 0) {
|
|
220
|
+
const err = new Error('defaultRunOneShot (#8030): the spawn gate returned no binary path — refusing rather than letting the SDK fall back to its bundled binary.')
|
|
221
|
+
err.code = 'PROVIDER_BINARY_UNVERIFIED'
|
|
222
|
+
throw err
|
|
223
|
+
}
|
|
189
224
|
const options = {
|
|
190
225
|
// No tools — a pure text summarization turn. The session must not be able
|
|
191
226
|
// to read/write files or run commands during summarization.
|
|
@@ -194,13 +229,22 @@ export async function defaultRunOneShot({ prompt, model, cwd, signal }) {
|
|
|
194
229
|
allowDangerouslySkipPermissions: true,
|
|
195
230
|
includePartialMessages: false,
|
|
196
231
|
maxTurns: 1,
|
|
232
|
+
// #7986 / #8030: the desktop bundle does not ship the Agent SDK's platform
|
|
233
|
+
// binary, and query() throws if pathToClaudeCodeExecutable is unset and
|
|
234
|
+
// that binary is absent — point it at the installed CLI, same as the
|
|
235
|
+
// chat-turn SDK provider, on every install.
|
|
236
|
+
pathToClaudeCodeExecutable: executable,
|
|
237
|
+
// #8262: without `env` the SDK copies process.env wholesale. Use the same
|
|
238
|
+
// builder the chat-turn SDK provider does, so a one-shot summary claude is a
|
|
239
|
+
// top-level session and no parent-session markers are inherited.
|
|
240
|
+
env: buildSpawnEnv('claude-sdk'),
|
|
197
241
|
}
|
|
198
242
|
if (typeof cwd === 'string' && cwd) options.cwd = cwd
|
|
199
243
|
if (typeof model === 'string' && model) options.model = model
|
|
200
244
|
if (signal) options.abortController = abortControllerFromSignal(signal)
|
|
201
245
|
|
|
202
246
|
const parts = []
|
|
203
|
-
const stream =
|
|
247
|
+
const stream = queryFn({ prompt, options })
|
|
204
248
|
for await (const msg of stream) {
|
|
205
249
|
if (msg?.type === 'assistant' && Array.isArray(msg.message?.content)) {
|
|
206
250
|
for (const block of msg.message.content) {
|
|
@@ -240,10 +284,13 @@ function abortControllerFromSignal(signal) {
|
|
|
240
284
|
* @param {string} [args.sessionName] - human label for the brief header.
|
|
241
285
|
* @param {Function} [args.runOneShot] - injected model runner.
|
|
242
286
|
* @param {AbortSignal} [args.signal]
|
|
287
|
+
* @param {Function} [args.resolveExecutable] - #8030: forwarded to the runner
|
|
288
|
+
* (`defaultRunOneShot` requires it; an injected `runOneShot` test double may
|
|
289
|
+
* ignore it). Production wires `SessionManager.verifyOneShotExecutable`.
|
|
243
290
|
* @returns {Promise<{ summary: string, truncated: boolean }>}
|
|
244
291
|
* @throws {Error} when there is no history to summarize or the model returns empty.
|
|
245
292
|
*/
|
|
246
|
-
export async function summarizeSession({ history, model, cwd, sessionName, runOneShot, signal } = {}) {
|
|
293
|
+
export async function summarizeSession({ history, model, cwd, sessionName, runOneShot, signal, resolveExecutable } = {}) {
|
|
247
294
|
const transcript = flattenHistory(history)
|
|
248
295
|
if (!transcript.trim()) {
|
|
249
296
|
const err = new Error('Session has no readable history to summarize')
|
|
@@ -255,7 +302,7 @@ export async function summarizeSession({ history, model, cwd, sessionName, runOn
|
|
|
255
302
|
const prompt = buildSummaryPrompt({ transcript: text, truncated, sessionName })
|
|
256
303
|
|
|
257
304
|
const runner = typeof runOneShot === 'function' ? runOneShot : defaultRunOneShot
|
|
258
|
-
const summary = await runner({ prompt, model, cwd, signal })
|
|
305
|
+
const summary = await runner({ prompt, model, cwd, signal, resolveExecutable })
|
|
259
306
|
|
|
260
307
|
if (typeof summary !== 'string' || !summary.trim()) {
|
|
261
308
|
const err = new Error('The summarizer returned no text')
|
package/src/supervisor.js
CHANGED
|
@@ -5,7 +5,6 @@ import { dirname, resolve, join } from 'path'
|
|
|
5
5
|
import { createInterface } from 'readline'
|
|
6
6
|
import { fileURLToPath } from 'url'
|
|
7
7
|
import { writeFileSync, readFileSync, unlinkSync, existsSync, mkdirSync } from 'fs'
|
|
8
|
-
import { homedir } from 'os'
|
|
9
8
|
import { EventEmitter } from 'events'
|
|
10
9
|
import { createTunnel, parseTunnelArg } from './tunnel/index.js'
|
|
11
10
|
import { QUICK_TUNNEL_DNS_SETTLE_MS, waitForTunnel } from './tunnel-check.js'
|
|
@@ -13,6 +12,8 @@ import { createLogger } from './logger.js'
|
|
|
13
12
|
import QRCode from 'qrcode'
|
|
14
13
|
import { writeConnectionInfo, removeConnectionInfo } from './connection-info.js'
|
|
15
14
|
import { PushManager } from './push.js'
|
|
15
|
+
import { configPath } from './config-dir.js'
|
|
16
|
+
import { isGitShaRef } from './utils/argv-safety.js'
|
|
16
17
|
|
|
17
18
|
function maskToken(token) {
|
|
18
19
|
if (!token) return ''
|
|
@@ -34,7 +35,9 @@ const __filename = fileURLToPath(import.meta.url)
|
|
|
34
35
|
const __dirname = dirname(__filename)
|
|
35
36
|
const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'))
|
|
36
37
|
const SUPERVISOR_VERSION = packageJson.version
|
|
37
|
-
|
|
38
|
+
function defaultPidFile() {
|
|
39
|
+
return configPath('supervisor.pid')
|
|
40
|
+
}
|
|
38
41
|
|
|
39
42
|
const DRAIN_TIMEOUT = 30000
|
|
40
43
|
const RESTART_BACKOFFS = [2000, 2000, 3000, 3000, 5000, 5000, 8000, 8000, 10000, 10000]
|
|
@@ -62,8 +65,8 @@ export class Supervisor extends EventEmitter {
|
|
|
62
65
|
this._port = config.port || parseInt(process.env.PORT || '8765', 10)
|
|
63
66
|
this._apiToken = config.apiToken || process.env.API_TOKEN
|
|
64
67
|
this._tunnelMode = config.tunnel || 'quick'
|
|
65
|
-
this._pidFilePath = config.pidFilePath ||
|
|
66
|
-
this._knownGoodFile = config.knownGoodFile ||
|
|
68
|
+
this._pidFilePath = config.pidFilePath || defaultPidFile()
|
|
69
|
+
this._knownGoodFile = config.knownGoodFile || configPath('known-good-ref')
|
|
67
70
|
this._maxRestarts = (typeof config.maxRestarts === 'number' && config.maxRestarts >= 0)
|
|
68
71
|
? config.maxRestarts
|
|
69
72
|
: 10
|
|
@@ -91,6 +94,10 @@ export class Supervisor extends EventEmitter {
|
|
|
91
94
|
this._tunnel = null
|
|
92
95
|
this._heartbeatInterval = null
|
|
93
96
|
this._currentWsUrl = null
|
|
97
|
+
// #6641: true while the tunnel is up but not routable — the server runs
|
|
98
|
+
// local/LAN-only and advertises no remote/QR access. Read by the degrade
|
|
99
|
+
// test; a natural gate for a future auto-reverify.
|
|
100
|
+
this._tunnelDegraded = false
|
|
94
101
|
this._signalsRegistered = false
|
|
95
102
|
this._restartScheduledAt = null
|
|
96
103
|
this._restartDelayMs = null
|
|
@@ -114,7 +121,7 @@ export class Supervisor extends EventEmitter {
|
|
|
114
121
|
lastBackoffMs: 0,
|
|
115
122
|
}
|
|
116
123
|
|
|
117
|
-
this._pushStoragePath = config.pushStoragePath ||
|
|
124
|
+
this._pushStoragePath = config.pushStoragePath || configPath('push-tokens.json')
|
|
118
125
|
}
|
|
119
126
|
|
|
120
127
|
/** Override point: fork a child process */
|
|
@@ -201,9 +208,9 @@ export class Supervisor extends EventEmitter {
|
|
|
201
208
|
// picks up prefs the child persisted after startup, same as the tokens.
|
|
202
209
|
const push = new PushManager({
|
|
203
210
|
storagePath: this._pushStoragePath,
|
|
204
|
-
prefsPath:
|
|
211
|
+
prefsPath: configPath('notification-prefs.json'),
|
|
205
212
|
discord: {
|
|
206
|
-
statePath:
|
|
213
|
+
statePath: configPath('discord-webhook-state.json'),
|
|
207
214
|
...(this.config.notifications?.discord || {}),
|
|
208
215
|
},
|
|
209
216
|
})
|
|
@@ -260,7 +267,7 @@ export class Supervisor extends EventEmitter {
|
|
|
260
267
|
|
|
261
268
|
async start() {
|
|
262
269
|
if (!this._apiToken) {
|
|
263
|
-
process.stderr.write('[!] No API token configured. Run \'
|
|
270
|
+
process.stderr.write('[!] No API token configured. Run \'chroxy init\' first.\n')
|
|
264
271
|
this._exit(1)
|
|
265
272
|
return
|
|
266
273
|
}
|
|
@@ -321,41 +328,87 @@ export class Supervisor extends EventEmitter {
|
|
|
321
328
|
this._log.error(message)
|
|
322
329
|
})
|
|
323
330
|
|
|
324
|
-
// 2
|
|
325
|
-
//
|
|
326
|
-
//
|
|
327
|
-
//
|
|
328
|
-
//
|
|
329
|
-
//
|
|
330
|
-
//
|
|
331
|
-
//
|
|
331
|
+
// 2. Wait for the tunnel to be routable. #6641 — a not-yet-routable tunnel
|
|
332
|
+
// must NOT abort the whole daemon. The default `chroxy start` used to
|
|
333
|
+
// exit(1) here whenever a warming quick-tunnel edge answered with a status
|
|
334
|
+
// outside {502,530} (e.g. a bare 404 during route propagation), taking down
|
|
335
|
+
// local + LAN access with it. Instead, degrade to local/LAN: start the
|
|
336
|
+
// child anyway so the server is usable right now.
|
|
337
|
+
//
|
|
338
|
+
// Degraded mode does NOT auto-recover to remote: `tunnel_recovered` only
|
|
339
|
+
// fires when the cloudflared PROCESS flaps (tunnel/base.js), not when an
|
|
340
|
+
// alive-but-unroutable tunnel finishes propagating, and there is no
|
|
341
|
+
// routability re-poll. So we advertise NO remote/QR access and tell the
|
|
342
|
+
// operator to restart (or use --tunnel named) once the tunnel is routable,
|
|
343
|
+
// rather than promising a QR that would never appear. (An auto re-verify in
|
|
344
|
+
// degraded mode is a possible follow-up — see #6641.)
|
|
345
|
+
//
|
|
346
|
+
// #5314 (WP-1.4) note: on the SIGINT/SIGTERM path the no-orphan guarantee
|
|
347
|
+
// still holds — shutdown() stops the tunnel and the supervised child
|
|
348
|
+
// together. (The crash-loop give-up path, _serveTerminalDown(), does not
|
|
349
|
+
// stop the tunnel — a pre-existing gap, not introduced here.) A
|
|
350
|
+
// NON-routability error (an unexpected throw) still takes the old
|
|
351
|
+
// stop-cloudflared-then-exit cleanup path via _failBoot().
|
|
352
|
+
let tunnelRoutable = true
|
|
332
353
|
try {
|
|
333
354
|
await this._waitForTunnel(httpUrl)
|
|
355
|
+
} catch (err) {
|
|
356
|
+
if (err?.code !== 'TUNNEL_NOT_ROUTABLE') {
|
|
357
|
+
await this._failBoot(err)
|
|
358
|
+
return
|
|
359
|
+
}
|
|
360
|
+
tunnelRoutable = false
|
|
361
|
+
this._tunnelDegraded = true
|
|
362
|
+
this._log.warn(
|
|
363
|
+
'Tunnel not routable — starting in local/LAN mode; remote access is ' +
|
|
364
|
+
'unavailable. Restart once your network/tunnel is ready, or use ' +
|
|
365
|
+
`--tunnel named for a stable URL. ${err.message}`
|
|
366
|
+
)
|
|
367
|
+
}
|
|
334
368
|
|
|
335
|
-
|
|
369
|
+
// 3. Display + persist connection info. The QR is shown ONLY for a routable
|
|
370
|
+
// tunnel — a QR to a not-yet-routable endpoint just hangs the app (the exact
|
|
371
|
+
// failure #6641 addresses), so in degraded mode we advertise local/LAN only.
|
|
372
|
+
// A throw in this block (QR encode / disk write) still routes to _failBoot().
|
|
373
|
+
try {
|
|
336
374
|
const connectionUrl = `chroxy://${wsUrl.replace('wss://', '')}?token=${this._apiToken}`
|
|
337
375
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
376
|
+
if (tunnelRoutable) {
|
|
377
|
+
// 3a. Display connection info
|
|
378
|
+
this._log.info(`${this._modeLabel} ready`)
|
|
379
|
+
process.stdout.write('📱 Scan this QR code with the Chroxy app:\n\n')
|
|
380
|
+
await this._displayQr(connectionUrl)
|
|
381
|
+
process.stdout.write('\nOr connect manually:\n')
|
|
382
|
+
process.stdout.write(` URL: ${wsUrl}\n`)
|
|
383
|
+
process.stdout.write(` Token: ${maskToken(this._apiToken)}\n`)
|
|
384
|
+
const dashboardBase = httpUrl || `http://localhost:${this._port}`
|
|
385
|
+
process.stdout.write(` Dashboard: ${dashboardBase.replace(/\/+$/, '')}/dashboard\n`)
|
|
386
|
+
process.stdout.write('\n')
|
|
387
|
+
} else {
|
|
388
|
+
// 3a. Degraded: local/LAN only, no QR to a dead endpoint, and no false
|
|
389
|
+
// promise of auto-recovery (#6641 review).
|
|
390
|
+
process.stdout.write('\n⚠️ Tunnel not routable — serving on local/LAN only (no remote/QR access).\n')
|
|
391
|
+
process.stdout.write(` Dashboard: http://localhost:${this._port}/dashboard\n`)
|
|
392
|
+
process.stdout.write(` LAN: http://<this-machine-ip>:${this._port}/dashboard\n`)
|
|
393
|
+
process.stdout.write(` Token: ${maskToken(this._apiToken)}\n`)
|
|
394
|
+
process.stdout.write(' For remote (phone) access, restart once the tunnel is routable, or use --tunnel named.\n\n')
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// 3b. Write connection info file for programmatic access. In degraded mode
|
|
398
|
+
// OMIT the public wsUrl/httpUrl/connectionUrl (they're not routable) so no
|
|
399
|
+
// consumer advertises a dead endpoint — notably the dashboard /qr route
|
|
400
|
+
// falls back to connectionUrl, which would otherwise resurface the exact
|
|
401
|
+
// dead QR #6641 kills, just in the dashboard modal (#6641 review). The
|
|
402
|
+
// local `port` is still written so loopback CLIs (chroxy publish / pages)
|
|
403
|
+
// hit the right port even in tunnel mode (#5683).
|
|
349
404
|
writeConnectionInfo({
|
|
350
|
-
wsUrl,
|
|
351
|
-
httpUrl,
|
|
352
|
-
// #5683: the LOCAL listen port, so loopback CLIs (chroxy publish / pages)
|
|
353
|
-
// hit the right port even in tunnel mode, where httpUrl is the public
|
|
354
|
-
// trycloudflare URL with no :port to parse.
|
|
405
|
+
wsUrl: tunnelRoutable ? wsUrl : null,
|
|
406
|
+
httpUrl: tunnelRoutable ? httpUrl : null,
|
|
355
407
|
port: this._port,
|
|
356
408
|
apiToken: this._apiToken,
|
|
357
|
-
connectionUrl,
|
|
409
|
+
connectionUrl: tunnelRoutable ? connectionUrl : null,
|
|
358
410
|
tunnelMode: this._modeLabel,
|
|
411
|
+
tunnelDegraded: !tunnelRoutable,
|
|
359
412
|
startedAt: new Date().toISOString(),
|
|
360
413
|
pid: process.pid,
|
|
361
414
|
})
|
|
@@ -778,9 +831,13 @@ export class Supervisor extends EventEmitter {
|
|
|
778
831
|
*
|
|
779
832
|
* Two layers of defense now close this:
|
|
780
833
|
*
|
|
781
|
-
* 1.
|
|
782
|
-
*
|
|
783
|
-
* `
|
|
834
|
+
* 1. `validateCwdAllowed` refuses a session cwd inside the config/state
|
|
835
|
+
* root, so the attacker can't reach `known-good-ref` via `write_file`.
|
|
836
|
+
* Two checks back that: `~/.chroxy` is in FORBIDDEN_HOME_SUBDIRS by
|
|
837
|
+
* name, AND the resolved `configDir()` is denied outright. The second
|
|
838
|
+
* is what keeps this true once CHROXY_CONFIG_DIR relocates the root
|
|
839
|
+
* (#7052) — the name-based set alone would then be guarding an empty
|
|
840
|
+
* directory while the real one sat open.
|
|
784
841
|
*
|
|
785
842
|
* 2. This function validates that the ref resolves to the SAME
|
|
786
843
|
* commit as an existing `known-good-*` git tag. The tag is
|
|
@@ -804,7 +861,11 @@ export class Supervisor extends EventEmitter {
|
|
|
804
861
|
// ≥ 7 chars to match historical behavior but require
|
|
805
862
|
// hex-only content. Rejects arbitrary branch names, refspecs,
|
|
806
863
|
// option flags (-rf, --help), etc.
|
|
807
|
-
|
|
864
|
+
//
|
|
865
|
+
// #7296: `chroxy deploy` reads the SAME file into a `git diff` argv, so
|
|
866
|
+
// the predicate moved to utils/argv-safety.js and both call sites share
|
|
867
|
+
// it. A second transcription of this regex is the drift this prevents.
|
|
868
|
+
if (!isGitShaRef(ref)) {
|
|
808
869
|
this._log.error(`Invalid known-good ref format: "${ref.slice(0, 64)}"`)
|
|
809
870
|
return false
|
|
810
871
|
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Boot-time sweep of stale per-session provider dirs (#7374).
|
|
3
|
+
*
|
|
4
|
+
* Extracted from `server-cli.js` so the sweep is pinned BEHAVIOURALLY. It used
|
|
5
|
+
* to be an inline block in the boot path, guarded only by a test that grepped
|
|
6
|
+
* `server-cli.js` for `sweepStaleSinkDirs(log)` inside an anchored `import(...)`
|
|
7
|
+
* slice. Mutation testing during #7371's review showed two bypasses that kept
|
|
8
|
+
* that guard green:
|
|
9
|
+
*
|
|
10
|
+
* - wrapping the whole block in `if (process.env.__NEVER_SET__) { … }`
|
|
11
|
+
* - replacing the call with `.then(({CliSession}) => void CliSession)` and
|
|
12
|
+
* putting the expected string in a comment INSIDE the anchored window
|
|
13
|
+
*
|
|
14
|
+
* That is catalogue entry 1 ("the gate that never ran"): a source grep cannot
|
|
15
|
+
* tell a call reached at boot from the same characters behind a false
|
|
16
|
+
* condition. Extracting the body means the WORK is now covered by tests that
|
|
17
|
+
* actually run it — see `tests/sweep-stale-provider-dirs.test.js`.
|
|
18
|
+
*
|
|
19
|
+
* What remains source-level is only that `server-cli.js` calls this function at
|
|
20
|
+
* boot. That residual is recorded in `docs/false-safety-guards.md` rather than
|
|
21
|
+
* papered over in a comment here.
|
|
22
|
+
*
|
|
23
|
+
* All four sweeps (claude-tui, claude-cli, codex app-server, docker-byok —
|
|
24
|
+
* #8047 added the latter two) are safe and unconditional: only dirs whose
|
|
25
|
+
* owner pid is DEAD are removed, so a live daemon's dirs — including ours —
|
|
26
|
+
* are kept. Lazily imported so a boot that uses none of the four providers
|
|
27
|
+
* pays nothing, and every failure is warned rather than thrown so a sweep can
|
|
28
|
+
* never affect startup.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The real module loaders. Injectable so a test can drive this function with
|
|
33
|
+
* stubs instead of `mock.module`, which leaks across the parallel test files
|
|
34
|
+
* `node --test` runs.
|
|
35
|
+
*/
|
|
36
|
+
export const DEFAULT_SWEEP_LOADERS = {
|
|
37
|
+
// #5323 (WP-5.1) — claude-tui hook-sink dirs left in /tmp by prior crashed
|
|
38
|
+
// processes (a leak on every crash).
|
|
39
|
+
'claude-tui sink-dir': async () => {
|
|
40
|
+
const { ClaudeTuiSession } = await import('./claude-tui-session.js')
|
|
41
|
+
return (log) => ClaudeTuiSession.sweepStaleSinkDirs(log)
|
|
42
|
+
},
|
|
43
|
+
// #7337 — same sweep for claude-cli's per-session permission-mode sidecar
|
|
44
|
+
// dirs, which leak on a crash for exactly the same reason.
|
|
45
|
+
'claude-cli sidecar-dir': async () => {
|
|
46
|
+
const { CliSession } = await import('./cli-session.js')
|
|
47
|
+
return (log) => CliSession.sweepStaleSidecarDirs(log)
|
|
48
|
+
},
|
|
49
|
+
// #7373 — codex app-server's per-session materialized-attachment dirs,
|
|
50
|
+
// same crash-leak shape as the two sweeps above.
|
|
51
|
+
'codex attach-dir': async () => {
|
|
52
|
+
const { CodexAppServerSession } = await import('./codex-app-server-session.js')
|
|
53
|
+
return (log) => CodexAppServerSession.sweepStaleAttachDirs(log)
|
|
54
|
+
},
|
|
55
|
+
// #7373 — docker-byok's per-session compose env-file dirs. This one is
|
|
56
|
+
// materially worse than a plain directory leak: the file holds
|
|
57
|
+
// ANTHROPIC_API_KEY, so an unswept orphan is a credential left in /tmp.
|
|
58
|
+
'docker-byok env-file-dir': async () => {
|
|
59
|
+
const { DockerByokSession } = await import('./docker-byok-session.js')
|
|
60
|
+
return (log) => DockerByokSession.sweepStaleEnvDirs(log)
|
|
61
|
+
},
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Run every provider's stale-dir sweep. Never rejects: a loader or sweep that
|
|
66
|
+
* throws is warned and the others still run.
|
|
67
|
+
*
|
|
68
|
+
* @param {{ info: Function, warn: Function }} log
|
|
69
|
+
* @param {Record<string, () => Promise<Function>>} [loaders]
|
|
70
|
+
* @returns {Promise<void>}
|
|
71
|
+
*/
|
|
72
|
+
export async function sweepStaleProviderDirs(log, loaders = DEFAULT_SWEEP_LOADERS) {
|
|
73
|
+
await Promise.all(
|
|
74
|
+
Object.entries(loaders).map(async ([label, load]) => {
|
|
75
|
+
try {
|
|
76
|
+
const sweep = await load()
|
|
77
|
+
await sweep(log)
|
|
78
|
+
} catch (err) {
|
|
79
|
+
// The logger is the one call left outside the try, and a throwing
|
|
80
|
+
// `log.warn` would reject `Promise.all` — which nothing awaits, so it
|
|
81
|
+
// surfaces as an unhandledRejection, and server-orchestrator treats
|
|
82
|
+
// that as fatal. The OLD inline form had the identical hole (a throw
|
|
83
|
+
// inside `.catch()` rejects the chain just the same), so this is not a
|
|
84
|
+
// regression being fixed — it is the "never rejects" claim being made
|
|
85
|
+
// true rather than nearly true.
|
|
86
|
+
try {
|
|
87
|
+
log.warn(`${label} sweep failed: ${(err && err.message) || err}`)
|
|
88
|
+
} catch {
|
|
89
|
+
// Nothing left to report it with. Swallowing is correct: a
|
|
90
|
+
// best-effort reaper must never be able to take down boot.
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}),
|
|
94
|
+
)
|
|
95
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ONE builder of the wire `thinking_level_changed` frame (#8700).
|
|
3
|
+
*
|
|
4
|
+
* Four senders put this frame on the wire: ws-history's `sendSessionInfo`
|
|
5
|
+
* replay (reconnect / tab switch), the event normalizer's `ready` burst, the
|
|
6
|
+
* `set_thinking_level` handler after an accepted change, and the normalizer's
|
|
7
|
+
* own `thinking_level_changed` entry for a level the SESSION changed or learned
|
|
8
|
+
* (a model switch that dropped an unoffered level, the effort Claude Code
|
|
9
|
+
* reported at the start of a turn). Each used to spell `{ level }` by hand, so a
|
|
10
|
+
* field added to one sender was missing from the rest — a replay would then
|
|
11
|
+
* erase what the live frame had said. They all build it here instead.
|
|
12
|
+
*
|
|
13
|
+
* `level` is what the operator asked for (`default` when nothing was asked).
|
|
14
|
+
* `effective` is what the provider REPORTS it applied, and it is sent only by a
|
|
15
|
+
* provider that declares `capabilities.thinkingLevelEffective`: there `null`
|
|
16
|
+
* means "not reported yet", while an absent key (every other provider) means
|
|
17
|
+
* "this provider makes no such report". Clients render the two differently, so
|
|
18
|
+
* the builder never collapses one into the other.
|
|
19
|
+
*
|
|
20
|
+
* Returns null for a session with no thinking-level concept (`thinkingLevel`
|
|
21
|
+
* getter `undefined`, BaseSession's default), so no sender invents a `default`
|
|
22
|
+
* that would stomp a client's state for a provider that never had one.
|
|
23
|
+
*/
|
|
24
|
+
import { LEGACY_DEFAULT_THINKING_LEVEL } from '@chroxy/protocol'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {object|null|undefined} session
|
|
28
|
+
* @returns {{ type: 'thinking_level_changed', level: string, effective?: string|null } | null}
|
|
29
|
+
*/
|
|
30
|
+
export function buildThinkingLevelChanged(session) {
|
|
31
|
+
const level = session?.thinkingLevel
|
|
32
|
+
if (level === undefined) return null
|
|
33
|
+
const msg = { type: 'thinking_level_changed', level: level || LEGACY_DEFAULT_THINKING_LEVEL }
|
|
34
|
+
if (session.constructor?.capabilities?.thinkingLevelEffective === true) {
|
|
35
|
+
const effective = session.effectiveThinkingLevel
|
|
36
|
+
msg.effective = typeof effective === 'string' && effective.length > 0 ? effective : null
|
|
37
|
+
}
|
|
38
|
+
return msg
|
|
39
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Producer for `thinking: true` stream frames (#7393).
|
|
3
|
+
*
|
|
4
|
+
* The wire contract is the one sdk-session and byok-session already emit
|
|
5
|
+
* (packages/protocol/src/schemas/server/stream.ts): a reasoning stream is a
|
|
6
|
+
* stream_start / stream_delta / stream_end triple tagged `thinking: true`, on a
|
|
7
|
+
* DISTINCT messageId `<turnId>-thinking-<n>` so it can never land in the
|
|
8
|
+
* response slot. The client renders it as a `type: 'thinking'` bubble, and the
|
|
9
|
+
* message history records it (`kind: 'thinking'`) from the very same frames, so
|
|
10
|
+
* a producer that emits these gets live display AND replay with nothing else.
|
|
11
|
+
*
|
|
12
|
+
* sdk-session and byok-session each carry an inline copy of this because they
|
|
13
|
+
* stream token by token off the API. The two providers that were never
|
|
14
|
+
* connected, claude-tui and claude-cli, get one shared implementation here
|
|
15
|
+
* instead of a third and fourth copy:
|
|
16
|
+
*
|
|
17
|
+
* - `emitBlock()` a block that is already complete (claude-tui reads it from
|
|
18
|
+
* the session transcript once claude has written it).
|
|
19
|
+
* - `open()` / `append()` / `close()` a block that arrives as stream events
|
|
20
|
+
* (claude-cli's `content_block_*`).
|
|
21
|
+
*
|
|
22
|
+
* Redaction. Thinking quotes what the model just read (an env file, a tool
|
|
23
|
+
* result) far more often than the reply does, so its text is pattern-redacted
|
|
24
|
+
* (redaction.js, the same value-shape patterns the logger and the tool-input
|
|
25
|
+
* broadcast use) before it leaves the process. A secret can straddle two
|
|
26
|
+
* chunks, which no per-chunk redactor can see (#8135 made the same point about
|
|
27
|
+
* tool input), so the streaming API holds a block's text and redacts the WHOLE
|
|
28
|
+
* of it at `close()`. `open()` still emits `stream_start` at once, which is the
|
|
29
|
+
* "it is thinking" signal; only the text waits for the block to finish.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { redactBounded } from './redaction.js'
|
|
33
|
+
import { boundedThinkingPrecedes } from './message-wire.js'
|
|
34
|
+
|
|
35
|
+
/** What stands in for an Anthropic `redacted_thinking` block, whose payload is encrypted and never readable. */
|
|
36
|
+
export const REDACTED_THINKING_PLACEHOLDER = '[redacted thinking]'
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Upper bound on the text kept for one block. The client bubble is capped at
|
|
40
|
+
* the same size (store-core MAX_THINKING_CONTENT_LEN), so anything past it
|
|
41
|
+
* would be dropped on arrival anyway.
|
|
42
|
+
*/
|
|
43
|
+
export const THINKING_TEXT_MAX = 1024 * 1024
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The messageId of the `n`th reasoning stream of a turn. The `-thinking-<n>`
|
|
47
|
+
* suffix is also how session-message-history classifies a legacy entry that
|
|
48
|
+
* predates the `kind` field, so it is part of the contract, not a style choice.
|
|
49
|
+
*/
|
|
50
|
+
export function thinkingMessageId(turnId, n) {
|
|
51
|
+
return `${turnId}-thinking-${n}`
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function cleanDuration(ms) {
|
|
55
|
+
return typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 ? Math.round(ms) : undefined
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function clip(text) {
|
|
59
|
+
const s = typeof text === 'string' ? text : ''
|
|
60
|
+
return s.length > THINKING_TEXT_MAX ? s.slice(0, THINKING_TEXT_MAX) : s
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export class ThinkingStreams {
|
|
64
|
+
/**
|
|
65
|
+
* @param {(event: string, data: object) => void} emit - the session's emit
|
|
66
|
+
* @param {string} turnId - the turn's response messageId; ids derive from it
|
|
67
|
+
* @param {object} [opts]
|
|
68
|
+
* @param {() => number} [opts.now] - monotonic ms clock (injectable for tests)
|
|
69
|
+
*/
|
|
70
|
+
constructor(emit, turnId, { now = () => performance.now() } = {}) {
|
|
71
|
+
this._emit = emit
|
|
72
|
+
this._turnId = turnId
|
|
73
|
+
this._now = now
|
|
74
|
+
this._seq = 0
|
|
75
|
+
/** @type {Map<unknown, {id: string, text: string, startMs: number}>} */
|
|
76
|
+
this._open = new Map()
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
get openCount() {
|
|
80
|
+
return this._open.size
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
_nextId() {
|
|
84
|
+
return thinkingMessageId(this._turnId, this._seq++)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
_body(text, redacted) {
|
|
88
|
+
if (redacted) return REDACTED_THINKING_PLACEHOLDER
|
|
89
|
+
return redactBounded(clip(text))
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Emit a reasoning block that is already complete as start, delta, end.
|
|
94
|
+
* Empty text (a block that carries only its signature, which is what the API
|
|
95
|
+
* returns when summaries are not requested) emits no delta: the client shows
|
|
96
|
+
* "Thought for Xs" with an empty body, and the history keeps that entry.
|
|
97
|
+
*
|
|
98
|
+
* `late: true` marks a block shown after its turn was already answered (the
|
|
99
|
+
* transcript is written late). It is an INTERNAL tag on the session event, not a
|
|
100
|
+
* wire field: the forwarder reads it to keep a finished session idle (a thinking
|
|
101
|
+
* `stream_start` otherwise pings the sidebar "busy", and nothing pings idle again
|
|
102
|
+
* until the next `result`), and it never reaches a client.
|
|
103
|
+
*
|
|
104
|
+
* `precedes` (#8518) is the transcript's own order, so a client can put a block that
|
|
105
|
+
* arrives late where it belongs: `{ kind: 'tool_use', toolUseId }` above that tool
|
|
106
|
+
* row, `{ kind: 'response' }` above the turn's answer. It rides the `stream_start`
|
|
107
|
+
* as `thinkingPrecedes` (the frame that creates the bubble). A response hint is
|
|
108
|
+
* sent only for a `late` block: before the answer exists its slot is empty and
|
|
109
|
+
* sits above the tool rows, so "above the response" would put the bubble in the
|
|
110
|
+
* wrong place; the block is simply appended, which is right for a block that
|
|
111
|
+
* arrives in order.
|
|
112
|
+
*
|
|
113
|
+
* @param {{ text?: string, redacted?: boolean, durationMs?: number, late?: boolean,
|
|
114
|
+
* precedes?: ({kind: 'tool_use', toolUseId: string}|{kind: 'response'}) }} block
|
|
115
|
+
* @returns {string} the messageId used
|
|
116
|
+
*/
|
|
117
|
+
emitBlock({ text = '', redacted = false, durationMs, late = false, precedes } = {}) {
|
|
118
|
+
const messageId = this._nextId()
|
|
119
|
+
const tag = late ? { late: true } : {}
|
|
120
|
+
const hint = this._hint(precedes, late)
|
|
121
|
+
this._emit('stream_start', { messageId, thinking: true, ...tag, ...(hint ? { thinkingPrecedes: hint } : {}) })
|
|
122
|
+
const body = this._body(text, redacted)
|
|
123
|
+
if (body) this._emit('stream_delta', { messageId, delta: body, thinking: true, ...tag })
|
|
124
|
+
this._emit('stream_end', { ...this._endFrame(messageId, cleanDuration(durationMs)), ...tag })
|
|
125
|
+
return messageId
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
_hint(precedes, late) {
|
|
129
|
+
if (precedes?.kind === 'response') {
|
|
130
|
+
return late ? boundedThinkingPrecedes({ kind: 'response', messageId: this._turnId }) : undefined
|
|
131
|
+
}
|
|
132
|
+
return boundedThinkingPrecedes(precedes)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Open a streaming block under `key` (idempotent per key). Emits `stream_start`. */
|
|
136
|
+
open(key) {
|
|
137
|
+
const existing = this._open.get(key)
|
|
138
|
+
if (existing) return existing.id
|
|
139
|
+
const id = this._nextId()
|
|
140
|
+
this._open.set(key, { id, text: '', startMs: this._now() })
|
|
141
|
+
this._emit('stream_start', { messageId: id, thinking: true })
|
|
142
|
+
return id
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Hold more text for the block under `key`. Nothing is emitted until `close()`. */
|
|
146
|
+
append(key, text) {
|
|
147
|
+
const block = this._open.get(key)
|
|
148
|
+
if (!block || typeof text !== 'string' || !text) return
|
|
149
|
+
if (block.text.length >= THINKING_TEXT_MAX) return
|
|
150
|
+
block.text += text
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Finish the block under `key`: one redacted delta (when there is text), then
|
|
155
|
+
* `stream_end` carrying the wall time since `open()`. No-op for an unknown key.
|
|
156
|
+
*
|
|
157
|
+
* @param {unknown} key
|
|
158
|
+
* @param {{ redacted?: boolean }} [opts]
|
|
159
|
+
*/
|
|
160
|
+
close(key, { redacted = false } = {}) {
|
|
161
|
+
const block = this._open.get(key)
|
|
162
|
+
if (!block) return
|
|
163
|
+
this._open.delete(key)
|
|
164
|
+
const body = this._body(block.text, redacted)
|
|
165
|
+
if (body) this._emit('stream_delta', { messageId: block.id, delta: body, thinking: true })
|
|
166
|
+
this._emit('stream_end', this._endFrame(block.id, cleanDuration(this._now() - block.startMs)))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Finalise every open block (a turn ending under them must not strand "Thinking…"). */
|
|
170
|
+
closeAll() {
|
|
171
|
+
for (const key of [...this._open.keys()]) this.close(key)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
_endFrame(messageId, durationMs) {
|
|
175
|
+
const frame = { messageId, thinking: true }
|
|
176
|
+
if (durationMs !== undefined) frame.thinkingDurationMs = durationMs
|
|
177
|
+
return frame
|
|
178
|
+
}
|
|
179
|
+
}
|