@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
|
@@ -5,11 +5,17 @@
|
|
|
5
5
|
* user_question_response, notification_prefs_get,
|
|
6
6
|
* notification_prefs_set (#4541)
|
|
7
7
|
*/
|
|
8
|
-
import { randomUUID } from 'node:crypto'
|
|
8
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
9
|
+
import { authorizedFor, stillAuthorized } from '../connection-authority.js'
|
|
10
|
+
import { InputContextEnvelopeSchema } from '@chroxy/protocol/schemas'
|
|
9
11
|
import { validateAttachments, resolveFileRefAttachments, resolveSession, sendError, sendSessionError, buildSessionTokenMismatchPayload, isSessionViewer, isUserShellSession } from '../handler-utils.js'
|
|
10
|
-
import { evaluateDraft as defaultEvaluateDraft, shouldSkipEvaluator } from '../prompt-evaluator.js'
|
|
12
|
+
import { evaluateDraft as defaultEvaluateDraft, shouldSkipEvaluator, shouldSkipEvaluatorAsync } from '../prompt-evaluator.js'
|
|
11
13
|
import { PushManager } from '../push.js'
|
|
14
|
+
import { isBoundClient } from '../environments/authority.js'
|
|
15
|
+
import { isPrincipalClient, refusePrincipalHandler, sendPrincipalRefusal } from '../principal-policy.js'
|
|
12
16
|
import { createLogger, sessionLogger } from '../logger.js'
|
|
17
|
+
import { answerDigest } from '../question-route-map.js'
|
|
18
|
+
import { INPUT_CONTEXT_CAPABILITIES, InputContextError, prepareInputContext } from '../input-context.js'
|
|
13
19
|
|
|
14
20
|
const log = createLogger('ws')
|
|
15
21
|
|
|
@@ -50,9 +56,13 @@ function _getEvaluatorIterations(ctx) {
|
|
|
50
56
|
// We reject the second concurrent draft with the same input_conflict
|
|
51
57
|
// category the user already understands — not queue it — so callers retry
|
|
52
58
|
// rather than silently waiting on an unbounded queue.
|
|
59
|
+
//
|
|
60
|
+
// The map lives on `ctx.runtime` (like the iteration counter above), NOT on the
|
|
61
|
+
// ctx itself: the ctx is spread per message, so a property set directly on it
|
|
62
|
+
// would be a fresh, empty map for every message and the lock would never be seen.
|
|
53
63
|
function _getEvaluatorAwaits(ctx) {
|
|
54
|
-
if (!ctx.
|
|
55
|
-
return ctx.
|
|
64
|
+
if (!ctx.runtime.pendingEvaluatorAwaits) ctx.runtime.pendingEvaluatorAwaits = new Map()
|
|
65
|
+
return ctx.runtime.pendingEvaluatorAwaits
|
|
56
66
|
}
|
|
57
67
|
|
|
58
68
|
// #3665 — build the history text appended for a recorded user input.
|
|
@@ -64,19 +74,20 @@ function _getEvaluatorAwaits(ctx) {
|
|
|
64
74
|
// without normalization the recorded text reads `'foo \n[1 file(s) attached]'`
|
|
65
75
|
// (double whitespace before the marker). Empty/whitespace-only text drops
|
|
66
76
|
// to a marker-only entry.
|
|
67
|
-
export function buildHistoryText(text, attCount) {
|
|
68
|
-
if (!attCount) return text
|
|
77
|
+
export function buildHistoryText(text, attCount, contextCount = 0) {
|
|
78
|
+
if (!attCount && !contextCount) return text
|
|
69
79
|
const stripped = typeof text === 'string' ? text.replace(/\s+$/, '') : ''
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
80
|
+
const markers = []
|
|
81
|
+
if (attCount) markers.push(`[${attCount} file(s) attached]`)
|
|
82
|
+
if (contextCount) markers.push(`[${contextCount} context item(s) selected]`)
|
|
83
|
+
return stripped ? `${stripped} ${markers.join(' ')}` : markers.join(' ')
|
|
73
84
|
}
|
|
74
85
|
|
|
75
|
-
// #3639 — build the minimal config object passed into
|
|
86
|
+
// #3639 — build the minimal config object passed into shouldSkipEvaluatorAsync.
|
|
76
87
|
// The per-session promptEvaluatorSkipPattern (string source) takes precedence;
|
|
77
88
|
// the server-wide ctx.services.config.promptEvaluatorSkipPattern (#3187) is the
|
|
78
89
|
// fallback so existing global-config deployments keep working unchanged.
|
|
79
|
-
//
|
|
90
|
+
// shouldSkipEvaluatorAsync only reads `config.promptEvaluatorSkipPattern` (verified
|
|
80
91
|
// in prompt-evaluator.js), so we return a single-key object rather than
|
|
81
92
|
// spreading the whole ctx.services.config — this runs on the user_input hot path and
|
|
82
93
|
// the spread was unnecessary allocation/copy work.
|
|
@@ -99,6 +110,10 @@ function _resolveSkipConfig(entry, ctx) {
|
|
|
99
110
|
// but collisions inside one session's ring buffer are the client's problem.
|
|
100
111
|
const USER_INPUT_ID_RE = /^[A-Za-z0-9_-]+$/
|
|
101
112
|
const MAX_CLIENT_MESSAGE_ID_LEN = 128
|
|
113
|
+
export const INPUT_DEDUP_TTL_MS = 10 * 60 * 1000
|
|
114
|
+
export const INPUT_DEDUP_TOMBSTONE_TTL_MS = 60 * 60 * 1000
|
|
115
|
+
export const INPUT_DEDUP_MAX_PER_SESSION = 4096
|
|
116
|
+
const INPUT_HASH_STRING_CHUNK_CODE_UNITS = 64 * 1024
|
|
102
117
|
// IDs the clients treat specially in their stores (e.g. the "thinking"
|
|
103
118
|
// placeholder shown while waiting for the first stream_delta). Never let a
|
|
104
119
|
// client-supplied id collide with these — it would clobber the placeholder
|
|
@@ -117,6 +132,161 @@ function resolveUserInputId(candidate) {
|
|
|
117
132
|
return candidate
|
|
118
133
|
}
|
|
119
134
|
|
|
135
|
+
function isWellFormedClientMessageId(candidate) {
|
|
136
|
+
return typeof candidate === 'string' &&
|
|
137
|
+
candidate.length > 0 &&
|
|
138
|
+
candidate.length <= MAX_CLIENT_MESSAGE_ID_LEN &&
|
|
139
|
+
USER_INPUT_ID_RE.test(candidate) &&
|
|
140
|
+
!RESERVED_USER_INPUT_IDS.has(candidate)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function updateCanonicalHash(hash, value) {
|
|
144
|
+
if (Array.isArray(value)) {
|
|
145
|
+
hash.update(`a${value.length}:`)
|
|
146
|
+
value.forEach((item) => updateCanonicalHash(hash, item))
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
if (value && typeof value === 'object') {
|
|
150
|
+
const keys = Object.keys(value).sort()
|
|
151
|
+
hash.update(`o${keys.length}:`)
|
|
152
|
+
keys.forEach((key) => {
|
|
153
|
+
updateCanonicalHash(hash, key)
|
|
154
|
+
updateCanonicalHash(hash, value[key])
|
|
155
|
+
})
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
if (typeof value === 'string') {
|
|
159
|
+
// Length-prefix and feed the original string straight into Hash.update.
|
|
160
|
+
// UTF-16LE preserves JavaScript code units, including lone surrogates that
|
|
161
|
+
// UTF-8 would collapse to the same replacement bytes. Bounded slices avoid
|
|
162
|
+
// building a second multi-megabyte representation for image data.
|
|
163
|
+
hash.update(`s${value.length}:`)
|
|
164
|
+
for (let offset = 0; offset < value.length; offset += INPUT_HASH_STRING_CHUNK_CODE_UNITS) {
|
|
165
|
+
hash.update(value.slice(offset, offset + INPUT_HASH_STRING_CHUNK_CODE_UNITS), 'utf16le')
|
|
166
|
+
}
|
|
167
|
+
return
|
|
168
|
+
}
|
|
169
|
+
if (value === null) {
|
|
170
|
+
hash.update('z')
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
if (value === undefined) {
|
|
174
|
+
hash.update('u')
|
|
175
|
+
return
|
|
176
|
+
}
|
|
177
|
+
if (typeof value === 'boolean') {
|
|
178
|
+
hash.update(value ? 'b1' : 'b0')
|
|
179
|
+
return
|
|
180
|
+
}
|
|
181
|
+
hash.update(`n${String(value)}:`)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function inputPayloadHash(msg) {
|
|
185
|
+
const hash = createHash('sha256')
|
|
186
|
+
updateCanonicalHash(hash, {
|
|
187
|
+
data: msg.data,
|
|
188
|
+
attachments: msg.attachments,
|
|
189
|
+
context: msg.context,
|
|
190
|
+
isVoice: !!msg.isVoice,
|
|
191
|
+
})
|
|
192
|
+
return hash.digest('hex')
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function getInputDedupRecords(ctx) {
|
|
196
|
+
if (!ctx.runtime.inputDedupRecords) ctx.runtime.inputDedupRecords = new Map()
|
|
197
|
+
return ctx.runtime.inputDedupRecords
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function sendInputAck(ws, ctx, record, overrides = {}) {
|
|
201
|
+
if (!record) return
|
|
202
|
+
const status = overrides.status ?? record.status
|
|
203
|
+
const delivery = overrides.delivery ?? record.delivery
|
|
204
|
+
const provesContextAdmission = delivery === 'dispatch_started' || delivery === 'queued'
|
|
205
|
+
const context = record.contextItemIds?.length && provesContextAdmission &&
|
|
206
|
+
(status === 'accepted' || status === 'queued' || status === 'duplicate')
|
|
207
|
+
? {
|
|
208
|
+
version: 1,
|
|
209
|
+
acceptedItemIds: [...record.contextItemIds],
|
|
210
|
+
supportedKinds: [...INPUT_CONTEXT_CAPABILITIES.kinds],
|
|
211
|
+
supportedLifetimes: [...INPUT_CONTEXT_CAPABILITIES.lifetimes],
|
|
212
|
+
}
|
|
213
|
+
: undefined
|
|
214
|
+
ctx.transport.send(ws, {
|
|
215
|
+
type: 'input_ack',
|
|
216
|
+
sessionId: record.sessionId,
|
|
217
|
+
clientMessageId: record.clientMessageId,
|
|
218
|
+
status,
|
|
219
|
+
delivery,
|
|
220
|
+
retrySafe: false,
|
|
221
|
+
acceptedAt: record.acceptedAt,
|
|
222
|
+
retentionExpiresAt: record.expiresAt,
|
|
223
|
+
dedupScope: 'process',
|
|
224
|
+
...(context ? { context } : {}),
|
|
225
|
+
...overrides,
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function sendInputRejectionAck(ws, ctx, sessionId, msg, reason, message) {
|
|
230
|
+
if (!isWellFormedClientMessageId(msg.clientMessageId)) return
|
|
231
|
+
const parsedContext = msg.context ? InputContextEnvelopeSchema.safeParse(msg.context) : null
|
|
232
|
+
sendInputAck(ws, ctx, {
|
|
233
|
+
sessionId,
|
|
234
|
+
clientMessageId: msg.clientMessageId,
|
|
235
|
+
contextItemIds: parsedContext?.success ? parsedContext.data.items.map((item) => item.id) : null,
|
|
236
|
+
status: 'rejected',
|
|
237
|
+
delivery: 'not_dispatched',
|
|
238
|
+
}, { reason, message })
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function reserveInputRequest(ctx, sessionId, msg) {
|
|
242
|
+
if (!isWellFormedClientMessageId(msg.clientMessageId)) return { record: null, duplicate: false }
|
|
243
|
+
const now = typeof ctx.now === 'function' ? ctx.now() : Date.now()
|
|
244
|
+
const ttlMs = Number.isFinite(ctx.inputDedupTtlMs) ? ctx.inputDedupTtlMs : INPUT_DEDUP_TTL_MS
|
|
245
|
+
const tombstoneTtlMs = Number.isFinite(ctx.inputDedupTombstoneTtlMs)
|
|
246
|
+
? ctx.inputDedupTombstoneTtlMs
|
|
247
|
+
: INPUT_DEDUP_TOMBSTONE_TTL_MS
|
|
248
|
+
const bySession = getInputDedupRecords(ctx)
|
|
249
|
+
let records = bySession.get(sessionId)
|
|
250
|
+
if (!records) {
|
|
251
|
+
records = new Map()
|
|
252
|
+
bySession.set(sessionId, records)
|
|
253
|
+
}
|
|
254
|
+
for (const [id, record] of records) {
|
|
255
|
+
if (now > record.tombstoneExpiresAt) records.delete(id)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const hash = inputPayloadHash(msg)
|
|
259
|
+
const existing = records.get(msg.clientMessageId)
|
|
260
|
+
if (existing) {
|
|
261
|
+
if (existing.hash !== hash) return { record: existing, mismatch: true }
|
|
262
|
+
if (now > existing.expiresAt) return { record: existing, expired: true }
|
|
263
|
+
return { record: existing, duplicate: true }
|
|
264
|
+
}
|
|
265
|
+
if (records.size >= INPUT_DEDUP_MAX_PER_SESSION) return { record: null, capacity: true }
|
|
266
|
+
|
|
267
|
+
const record = {
|
|
268
|
+
sessionId,
|
|
269
|
+
clientMessageId: msg.clientMessageId,
|
|
270
|
+
hash,
|
|
271
|
+
// Retain only bounded identifiers, never image/text payload bytes. The
|
|
272
|
+
// payload hash is sufficient for duplicate/mismatch decisions.
|
|
273
|
+
contextItemIds: msg.context?.items?.map((item) => item.id) ?? null,
|
|
274
|
+
status: 'uncertain',
|
|
275
|
+
delivery: 'unknown',
|
|
276
|
+
expiresAt: now + ttlMs,
|
|
277
|
+
tombstoneExpiresAt: now + ttlMs + tombstoneTtlMs,
|
|
278
|
+
}
|
|
279
|
+
records.set(msg.clientMessageId, record)
|
|
280
|
+
return { record, duplicate: false }
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function releaseInputRequest(ctx, record) {
|
|
284
|
+
if (!record) return
|
|
285
|
+
const records = getInputDedupRecords(ctx).get(record.sessionId)
|
|
286
|
+
if (records?.get(record.clientMessageId) === record) records.delete(record.clientMessageId)
|
|
287
|
+
if (records?.size === 0) getInputDedupRecords(ctx).delete(record.sessionId)
|
|
288
|
+
}
|
|
289
|
+
|
|
120
290
|
// #5281 ①.3 — an input_conflict rejection: the session can't accept this send
|
|
121
291
|
// right now (busy with another device's request, or still evaluating a previous
|
|
122
292
|
// draft on the same session). Echo the session and the rejected clientMessageId
|
|
@@ -150,6 +320,10 @@ function buildInputConflictError(sessionId, clientMessageId, message = INPUT_CON
|
|
|
150
320
|
}
|
|
151
321
|
|
|
152
322
|
async function handleInput(ws, client, msg, ctx) {
|
|
323
|
+
// An agent principal never falls into the host path below: its target is
|
|
324
|
+
// resolved from an EXPLICIT sessionId through principalMaySee (no activeSessionId
|
|
325
|
+
// fallback) and the branch always returns (contract §3.1 item 6).
|
|
326
|
+
if (isPrincipalClient(client)) return refusePrincipalHandler(ws, client, msg, ctx, 'steer')
|
|
153
327
|
const text = msg.data
|
|
154
328
|
let attachments = Array.isArray(msg.attachments) ? msg.attachments : undefined
|
|
155
329
|
const targetSessionId = msg.sessionId || client.activeSessionId
|
|
@@ -209,10 +383,19 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
209
383
|
return
|
|
210
384
|
}
|
|
211
385
|
|
|
386
|
+
// Only negotiated clients receive the new acknowledgement/dedup behavior.
|
|
387
|
+
// An explicit context envelope also opts in by construction. This keeps the
|
|
388
|
+
// observable plain-input behavior unchanged for deployed older clients.
|
|
389
|
+
const supportsInputAck = !!msg.context
|
|
390
|
+
|| client.clientCapabilities?.has?.('input_context_v1') === true
|
|
391
|
+
|
|
212
392
|
if (attachments?.length) {
|
|
213
393
|
const err = validateAttachments(attachments)
|
|
214
394
|
if (err) {
|
|
215
395
|
sendSessionError(ws, ctx, `Invalid attachment: ${err}`)
|
|
396
|
+
if (supportsInputAck) {
|
|
397
|
+
sendInputRejectionAck(ws, ctx, targetSessionId, msg, 'invalid_attachment', `Invalid attachment: ${err}`)
|
|
398
|
+
}
|
|
216
399
|
return
|
|
217
400
|
}
|
|
218
401
|
}
|
|
@@ -222,9 +405,59 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
222
405
|
attachments = resolveFileRefAttachments(attachments, entry.cwd)
|
|
223
406
|
}
|
|
224
407
|
|
|
225
|
-
|
|
408
|
+
let preparedContext
|
|
409
|
+
const attachmentsWithoutContext = attachments
|
|
410
|
+
if (msg.context) {
|
|
411
|
+
const parsedContext = InputContextEnvelopeSchema.safeParse(msg.context)
|
|
412
|
+
if (!parsedContext.success) {
|
|
413
|
+
const record = isWellFormedClientMessageId(msg.clientMessageId)
|
|
414
|
+
? {
|
|
415
|
+
sessionId: targetSessionId,
|
|
416
|
+
clientMessageId: msg.clientMessageId,
|
|
417
|
+
contextItemIds: null,
|
|
418
|
+
status: 'rejected',
|
|
419
|
+
delivery: 'not_dispatched',
|
|
420
|
+
}
|
|
421
|
+
: null
|
|
422
|
+
sendInputAck(ws, ctx, record, { reason: 'invalid_context', message: 'The selected context envelope is invalid.' })
|
|
423
|
+
return
|
|
424
|
+
}
|
|
425
|
+
try {
|
|
426
|
+
preparedContext = prepareInputContext(text?.trim() || '', attachments, parsedContext.data)
|
|
427
|
+
attachments = preparedContext.attachments
|
|
428
|
+
} catch (err) {
|
|
429
|
+
if (!(err instanceof InputContextError)) throw err
|
|
430
|
+
if (isWellFormedClientMessageId(msg.clientMessageId)) {
|
|
431
|
+
sendInputAck(ws, ctx, {
|
|
432
|
+
sessionId: targetSessionId,
|
|
433
|
+
clientMessageId: msg.clientMessageId,
|
|
434
|
+
contextItemIds: null,
|
|
435
|
+
status: 'rejected',
|
|
436
|
+
delivery: 'not_dispatched',
|
|
437
|
+
}, { reason: err.reason, message: err.message })
|
|
438
|
+
}
|
|
439
|
+
return
|
|
440
|
+
}
|
|
441
|
+
const attachmentError = validateAttachments(attachments)
|
|
442
|
+
if (attachmentError) {
|
|
443
|
+
if (isWellFormedClientMessageId(msg.clientMessageId)) {
|
|
444
|
+
sendInputAck(ws, ctx, {
|
|
445
|
+
sessionId: targetSessionId,
|
|
446
|
+
clientMessageId: msg.clientMessageId,
|
|
447
|
+
contextItemIds: null,
|
|
448
|
+
status: 'rejected',
|
|
449
|
+
delivery: 'not_dispatched',
|
|
450
|
+
}, { reason: 'invalid_context_attachment', message: `Invalid context attachment: ${attachmentError}` })
|
|
451
|
+
}
|
|
452
|
+
return
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
if ((!text || !text.trim()) && !attachments?.length && !msg.context?.items?.length) return
|
|
226
457
|
const trimmed = text?.trim() || ''
|
|
227
458
|
const attCount = attachments?.length || 0
|
|
459
|
+
const directAttachmentCount = attachmentsWithoutContext?.length || 0
|
|
460
|
+
const contextCount = preparedContext?.context.items.length || 0
|
|
228
461
|
log.debug(`Message from ${client.id} to session ${targetSessionId}: "${trimmed.slice(0, 80)}"${attCount ? ` (+${attCount} attachment(s))` : ''}`)
|
|
229
462
|
|
|
230
463
|
// #4733 — wire-arrival fingerprint. Logs the byte/codepoint/whitespace
|
|
@@ -284,7 +517,13 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
284
517
|
}
|
|
285
518
|
|
|
286
519
|
if (ctx.sessions.sessionManager.isBudgetPaused(targetSessionId)) {
|
|
520
|
+
// A budget-paused rejection is still a person typing (#8301): the reservation
|
|
521
|
+
// site below is never reached, so record the intent here.
|
|
522
|
+
ctx.sessions.sessionManager?.recordUserIntent?.(targetSessionId)
|
|
287
523
|
sendSessionError(ws, ctx, 'Session is paused — cost budget exceeded. Use "Resume Budget" to continue.')
|
|
524
|
+
if (supportsInputAck) {
|
|
525
|
+
sendInputRejectionAck(ws, ctx, targetSessionId, msg, 'budget_paused', 'The input was not dispatched because the session budget is paused.')
|
|
526
|
+
}
|
|
288
527
|
return
|
|
289
528
|
}
|
|
290
529
|
|
|
@@ -293,10 +532,79 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
293
532
|
const primaryClientId = ctx.transport.getPrimary(targetSessionId)
|
|
294
533
|
if (primaryClientId && primaryClientId !== client.id) {
|
|
295
534
|
ctx.transport.send(ws, buildInputConflictError(targetSessionId, msg.clientMessageId))
|
|
535
|
+
if (supportsInputAck) {
|
|
536
|
+
sendInputRejectionAck(ws, ctx, targetSessionId, msg, 'input_conflict', INPUT_CONFLICT_CROSS_DEVICE_MESSAGE)
|
|
537
|
+
}
|
|
296
538
|
return
|
|
297
539
|
}
|
|
298
540
|
}
|
|
299
541
|
|
|
542
|
+
const reservation = supportsInputAck
|
|
543
|
+
? reserveInputRequest(ctx, targetSessionId, msg)
|
|
544
|
+
: { record: null, duplicate: false }
|
|
545
|
+
if (reservation.mismatch) {
|
|
546
|
+
sendInputAck(ws, ctx, {
|
|
547
|
+
...reservation.record,
|
|
548
|
+
status: 'rejected',
|
|
549
|
+
delivery: 'not_dispatched',
|
|
550
|
+
}, {
|
|
551
|
+
reason: 'payload_mismatch',
|
|
552
|
+
message: 'This clientMessageId was already used for a different input payload. Generate a new id.',
|
|
553
|
+
})
|
|
554
|
+
return
|
|
555
|
+
}
|
|
556
|
+
if (reservation.expired) {
|
|
557
|
+
sendInputAck(ws, ctx, {
|
|
558
|
+
...reservation.record,
|
|
559
|
+
status: 'expired',
|
|
560
|
+
delivery: 'not_dispatched',
|
|
561
|
+
}, {
|
|
562
|
+
reason: 'dedup_expired',
|
|
563
|
+
message: 'The server retention window expired for this input id; delivery is uncertain and it was not submitted again.',
|
|
564
|
+
})
|
|
565
|
+
return
|
|
566
|
+
}
|
|
567
|
+
if (reservation.duplicate) {
|
|
568
|
+
const accepted = reservation.record.delivery === 'dispatch_started' ||
|
|
569
|
+
reservation.record.delivery === 'queued' ||
|
|
570
|
+
reservation.record.delivery === 'evaluation_held'
|
|
571
|
+
if (accepted) {
|
|
572
|
+
sendInputAck(ws, ctx, { ...reservation.record, status: 'duplicate' })
|
|
573
|
+
} else {
|
|
574
|
+
sendInputAck(ws, ctx, reservation.record, {
|
|
575
|
+
status: 'uncertain',
|
|
576
|
+
delivery: 'unknown',
|
|
577
|
+
reason: 'delivery_uncertain',
|
|
578
|
+
message: 'This input id is still retained, but provider admission has not been confirmed. It was not submitted again.',
|
|
579
|
+
})
|
|
580
|
+
}
|
|
581
|
+
return
|
|
582
|
+
}
|
|
583
|
+
if (reservation.capacity) {
|
|
584
|
+
sendInputAck(ws, ctx, {
|
|
585
|
+
sessionId: targetSessionId,
|
|
586
|
+
clientMessageId: msg.clientMessageId,
|
|
587
|
+
contextItemIds: null,
|
|
588
|
+
status: 'rejected',
|
|
589
|
+
delivery: 'not_dispatched',
|
|
590
|
+
}, {
|
|
591
|
+
reason: 'dedup_capacity',
|
|
592
|
+
message: 'The input deduplication window is full; wait for retained entries to expire before submitting.',
|
|
593
|
+
})
|
|
594
|
+
return
|
|
595
|
+
}
|
|
596
|
+
const inputRecord = reservation.record
|
|
597
|
+
|
|
598
|
+
// #8301 / #8329: a person just typed into this session. Record the INTENT here,
|
|
599
|
+
// once the input is a NEW one (the empty-input return and the duplicate /
|
|
600
|
+
// payload_mismatch / expired / capacity rejections above have already run), so a
|
|
601
|
+
// client's retransmit of input sent before a Stop cannot undo that Stop. Nothing
|
|
602
|
+
// between receipt and this line awaits, so it still lands before any dispatch or
|
|
603
|
+
// admission wait: input sent BEFORE a Stop cannot be admitted after it and
|
|
604
|
+
// silently undo it. A context-only send counts. A budget-paused rejection
|
|
605
|
+
// records at its own return above.
|
|
606
|
+
ctx.sessions.sessionManager?.recordUserIntent?.(targetSessionId)
|
|
607
|
+
|
|
300
608
|
// #3666 — hoist the per-session evaluator-await lock check above the
|
|
301
609
|
// routing logic so trivial-skip-path messages also reject during an
|
|
302
610
|
// in-flight evaluator round-trip. Without this, a fast trivial draft
|
|
@@ -313,6 +621,15 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
313
621
|
msg.clientMessageId,
|
|
314
622
|
'Session is already evaluating a previous draft. Wait for it to finish or interrupt first.',
|
|
315
623
|
))
|
|
624
|
+
if (inputRecord) {
|
|
625
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
626
|
+
status: 'rejected',
|
|
627
|
+
delivery: 'not_dispatched',
|
|
628
|
+
reason: 'input_conflict',
|
|
629
|
+
message: 'Session is already evaluating a previous draft. The input was not dispatched.',
|
|
630
|
+
})
|
|
631
|
+
}
|
|
632
|
+
releaseInputRequest(ctx, inputRecord)
|
|
316
633
|
return
|
|
317
634
|
}
|
|
318
635
|
|
|
@@ -327,6 +644,7 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
327
644
|
// turn that just ended) so restoring this pre-turn checkpoint can truncate
|
|
328
645
|
// the conversation to here. Undefined on providers that don't track it.
|
|
329
646
|
boundaryMessageId: entry.session.lastMessageUuid,
|
|
647
|
+
isAuthorized: authorizedFor(ctx, client),
|
|
330
648
|
}).catch((err) => log.warn(`Auto-checkpoint failed: ${err.message}`))
|
|
331
649
|
}
|
|
332
650
|
// Adopt the sender's clientMessageId if present and well-formed; otherwise
|
|
@@ -360,7 +678,11 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
360
678
|
function recordHistoryEntry(text) {
|
|
361
679
|
if (_historyRecorded) return
|
|
362
680
|
_historyRecorded = true
|
|
363
|
-
ctx.sessions.sessionManager.recordUserInput(
|
|
681
|
+
ctx.sessions.sessionManager.recordUserInput(
|
|
682
|
+
targetSessionId,
|
|
683
|
+
buildHistoryText(text, directAttachmentCount, contextCount),
|
|
684
|
+
messageId,
|
|
685
|
+
)
|
|
364
686
|
ctx.sessions.sessionManager.touchActivity(targetSessionId)
|
|
365
687
|
}
|
|
366
688
|
|
|
@@ -381,11 +703,47 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
381
703
|
// (the toggle) is also per-session — the skip pattern shouldn't be the
|
|
382
704
|
// odd one out forced through global config.
|
|
383
705
|
let textToSend = trimmed
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
706
|
+
// The skip decision is awaited (a configured pattern is matched off the event
|
|
707
|
+
// loop), so the per-session lock is taken BEFORE that await: otherwise a second
|
|
708
|
+
// input arriving in the gap passes the entry check above and either overtakes
|
|
709
|
+
// this one or reaches the evaluator concurrently. The placeholder is replaced by
|
|
710
|
+
// the evaluator promise below, or released on the skip / cap / error paths.
|
|
711
|
+
let skipLock = null
|
|
712
|
+
let skipDecision = true
|
|
713
|
+
// The default (synchronous) rules decide first: a trivial ack never waits and
|
|
714
|
+
// never takes the lock. Only a draft that a configured pattern must still judge,
|
|
715
|
+
// or that the evaluator will run on, holds it.
|
|
716
|
+
if (entry.session.promptEvaluator === true && trimmed.length > 0 && !shouldSkipEvaluator(trimmed)) {
|
|
717
|
+
skipLock = Promise.resolve()
|
|
718
|
+
_pendingAwaits.set(targetSessionId, skipLock)
|
|
719
|
+
try {
|
|
720
|
+
skipDecision = await shouldSkipEvaluatorAsync(trimmed, _resolveSkipConfig(entry, ctx), undefined, String(client.id))
|
|
721
|
+
} catch (err) {
|
|
722
|
+
log.warn(`Skip-pattern check failed: ${err?.message || err}; evaluating the draft`)
|
|
723
|
+
skipDecision = false
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
const releaseSkipLock = () => {
|
|
727
|
+
if (skipLock && _pendingAwaits.get(targetSessionId) === skipLock) _pendingAwaits.delete(targetSessionId)
|
|
728
|
+
}
|
|
729
|
+
// The skip decision was a wait: the connection may have lost its credential
|
|
730
|
+
// meanwhile. Nothing below (skip dispatch, cap force-forward, evaluator) runs
|
|
731
|
+
// for it.
|
|
732
|
+
if (skipLock) {
|
|
733
|
+
let authorized = false
|
|
734
|
+
try {
|
|
735
|
+
authorized = stillAuthorized(authorizedFor(ctx, client))
|
|
736
|
+
} finally {
|
|
737
|
+
// Released on a refusal AND if the check itself throws.
|
|
738
|
+
if (!authorized) {
|
|
739
|
+
releaseSkipLock()
|
|
740
|
+
releaseInputRequest(ctx, inputRecord)
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
if (!authorized) return
|
|
744
|
+
}
|
|
745
|
+
if (skipLock && skipDecision) releaseSkipLock()
|
|
746
|
+
if (skipLock && !skipDecision) {
|
|
389
747
|
const counters = _getEvaluatorIterations(ctx)
|
|
390
748
|
const currentIteration = (counters.get(targetSessionId) || 0) + 1
|
|
391
749
|
|
|
@@ -394,12 +752,14 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
394
752
|
// session isn't permanently locked out of evaluator gating.
|
|
395
753
|
log.warn(`Evaluator iteration cap hit for session ${targetSessionId}; force-forwarding draft`)
|
|
396
754
|
counters.delete(targetSessionId)
|
|
755
|
+
releaseSkipLock()
|
|
397
756
|
} else {
|
|
398
757
|
// #3636 — per-session serialization. Reject (don't queue) a second
|
|
399
758
|
// concurrent draft for the same session while an evaluator round-trip
|
|
400
|
-
// is in flight. The
|
|
401
|
-
//
|
|
402
|
-
//
|
|
759
|
+
// is in flight. The check at function entry (#3666) rejects messages
|
|
760
|
+
// arriving while the lock is held, and the lock is held from before the
|
|
761
|
+
// skip decision is awaited, so it is ours here: we replace the
|
|
762
|
+
// placeholder with the evaluator promise.
|
|
403
763
|
const pending = _pendingAwaits
|
|
404
764
|
|
|
405
765
|
const evaluator = typeof ctx.evaluateDraft === 'function' ? ctx.evaluateDraft : defaultEvaluateDraft
|
|
@@ -426,6 +786,18 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
426
786
|
}
|
|
427
787
|
}
|
|
428
788
|
|
|
789
|
+
// The connection may have ended (credential revoked / expired) while the
|
|
790
|
+
// evaluator was running. Nothing below may dispatch, record or broadcast
|
|
791
|
+
// on its behalf.
|
|
792
|
+
let authorizedAfterEvaluator = false
|
|
793
|
+
try {
|
|
794
|
+
authorizedAfterEvaluator = stillAuthorized(authorizedFor(ctx, client))
|
|
795
|
+
} finally {
|
|
796
|
+
// Released on a refusal AND if the check itself throws.
|
|
797
|
+
if (!authorizedAfterEvaluator) releaseInputRequest(ctx, inputRecord)
|
|
798
|
+
}
|
|
799
|
+
if (!authorizedAfterEvaluator) return
|
|
800
|
+
|
|
429
801
|
// #3636 — re-check input_conflict after the await. State may have
|
|
430
802
|
// flipped during the round-trip (e.g. another path started the
|
|
431
803
|
// session). Without this, the rewritten/forward draft would race
|
|
@@ -434,6 +806,15 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
434
806
|
const primaryClientId = ctx.transport.getPrimary(targetSessionId)
|
|
435
807
|
if (primaryClientId && primaryClientId !== client.id) {
|
|
436
808
|
ctx.transport.send(ws, buildInputConflictError(targetSessionId, msg.clientMessageId))
|
|
809
|
+
if (inputRecord) {
|
|
810
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
811
|
+
status: 'rejected',
|
|
812
|
+
delivery: 'not_dispatched',
|
|
813
|
+
reason: 'input_conflict',
|
|
814
|
+
message: 'Another client took control while the draft was being evaluated. The input was not dispatched.',
|
|
815
|
+
})
|
|
816
|
+
}
|
|
817
|
+
releaseInputRequest(ctx, inputRecord)
|
|
437
818
|
return
|
|
438
819
|
}
|
|
439
820
|
}
|
|
@@ -484,6 +865,12 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
484
865
|
{ type: 'user_input', sessionId: targetSessionId, clientId: client.id, text: trimmed, messageId, timestamp: Date.now() },
|
|
485
866
|
(c) => c.id !== client.id,
|
|
486
867
|
)
|
|
868
|
+
if (inputRecord) {
|
|
869
|
+
inputRecord.status = 'accepted'
|
|
870
|
+
inputRecord.delivery = 'evaluation_held'
|
|
871
|
+
inputRecord.acceptedAt = typeof ctx.now === 'function' ? ctx.now() : Date.now()
|
|
872
|
+
sendInputAck(ws, ctx, inputRecord)
|
|
873
|
+
}
|
|
487
874
|
return
|
|
488
875
|
} else {
|
|
489
876
|
// forward verdict (or unrecognised result) — drop the iteration
|
|
@@ -493,7 +880,7 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
493
880
|
}
|
|
494
881
|
}
|
|
495
882
|
|
|
496
|
-
// #3636:
|
|
883
|
+
// #3636: prepare history for the forward boundary. All earlier
|
|
497
884
|
// rejection paths (input_conflict pre-await, pending-evaluator guard,
|
|
498
885
|
// post-await re-check) returned without recording. The clarify path
|
|
499
886
|
// already recorded above before its own return.
|
|
@@ -501,8 +888,6 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
501
888
|
// rewritten string on the rewrite verdict, the original `trimmed`
|
|
502
889
|
// draft on every other path (forward, skip-heuristic, fail-open,
|
|
503
890
|
// cap-bypass).
|
|
504
|
-
recordHistoryEntry(textToSend)
|
|
505
|
-
|
|
506
891
|
// #5313 (WP-1.3): sendMessage is fire-and-forget. If a provider's
|
|
507
892
|
// sendMessage returns a rejecting promise, an unhandled rejection escapes
|
|
508
893
|
// to process-level unhandledRejection → process.exit(1), crashing EVERY
|
|
@@ -515,7 +900,148 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
515
900
|
// `message_queued` mirror carries the id the sender's optimistic copy uses —
|
|
516
901
|
// letting that client reconcile its queued bubble. Providers that send
|
|
517
902
|
// immediately ignore the extra option.
|
|
518
|
-
|
|
903
|
+
//
|
|
904
|
+
// #8866: a session continued from the archive as a NEW thread owes the model
|
|
905
|
+
// the archived transcript with its first message. It is claimed here, after
|
|
906
|
+
// every rejection path above, merged into the text through the same
|
|
907
|
+
// `prepareInputContext` envelope a client-selected context takes, and kept OUT
|
|
908
|
+
// of `contextCount` (history shows what the user typed) and of the
|
|
909
|
+
// `sendOptions.context` below (that stays "what the user selected"; an adapter
|
|
910
|
+
// that refuses selected context, like BYOK with attachments, is unaffected).
|
|
911
|
+
// It is consumed when the provider ADMITS the input, and also when admission
|
|
912
|
+
// is UNCERTAIN (re-sending the transcript twice is worse than losing it once);
|
|
913
|
+
// a definite rejection or a throw returns it to pending. While a claim is
|
|
914
|
+
// unresolved a second input is REFUSED, so nothing can become the first
|
|
915
|
+
// delivered input without the transcript. The claim is observed through an
|
|
916
|
+
// admission callback passed whenever a seed is claimed, separately from the
|
|
917
|
+
// client-ack bookkeeping, so a client without input acks is covered too.
|
|
918
|
+
const sm = ctx.sessions.sessionManager
|
|
919
|
+
const seedClaim = sm.claimContinuationSeed?.(targetSessionId) ?? null
|
|
920
|
+
if (seedClaim?.busy || seedClaim?.unpersisted) {
|
|
921
|
+
const [reason, message] = seedClaim.busy
|
|
922
|
+
? ['continuation_seed_pending', 'The first message of this continued session is still being delivered. Wait for it to be accepted, then send again.']
|
|
923
|
+
: ['continuation_seed_unpersisted', 'Could not safely record the start of this continued session (the state file was not written), so nothing was sent. Check disk space and try again.']
|
|
924
|
+
// The dashboard restores the draft from a retry-safe rejection but does not
|
|
925
|
+
// render the ack's message, so the refusal is ALSO a session error (the same
|
|
926
|
+
// pairing the budget-paused rejection uses) for the user to read.
|
|
927
|
+
sendSessionError(ws, ctx, message)
|
|
928
|
+
if (inputRecord) {
|
|
929
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
930
|
+
status: 'rejected',
|
|
931
|
+
delivery: 'not_dispatched',
|
|
932
|
+
retrySafe: true,
|
|
933
|
+
reason,
|
|
934
|
+
message,
|
|
935
|
+
})
|
|
936
|
+
releaseInputRequest(ctx, inputRecord)
|
|
937
|
+
}
|
|
938
|
+
return
|
|
939
|
+
}
|
|
940
|
+
let seedSettled = !seedClaim
|
|
941
|
+
const settleSeed = (consumed) => {
|
|
942
|
+
if (seedSettled) return
|
|
943
|
+
seedSettled = true
|
|
944
|
+
sm.settleContinuationSeed?.(targetSessionId, seedClaim.token, consumed)
|
|
945
|
+
}
|
|
946
|
+
const observeSeedAdmission = (admission) => {
|
|
947
|
+
if (seedSettled || !admission || typeof admission !== 'object') return
|
|
948
|
+
if (admission.status === 'rejected' && admission.delivery === 'not_dispatched') settleSeed(false)
|
|
949
|
+
else if (
|
|
950
|
+
(admission.status === 'accepted' && admission.delivery === 'dispatch_started') ||
|
|
951
|
+
(admission.status === 'queued' && admission.delivery === 'queued') ||
|
|
952
|
+
(admission.status === 'uncertain' && admission.delivery === 'unknown')
|
|
953
|
+
) settleSeed(true)
|
|
954
|
+
}
|
|
955
|
+
let dispatchText
|
|
956
|
+
try {
|
|
957
|
+
const dispatchContext = seedClaim
|
|
958
|
+
? { version: 1, items: [seedClaim.item, ...(preparedContext?.context.items || [])] }
|
|
959
|
+
: preparedContext?.context
|
|
960
|
+
dispatchText = dispatchContext
|
|
961
|
+
? prepareInputContext(textToSend, attachmentsWithoutContext, dispatchContext).text
|
|
962
|
+
: textToSend
|
|
963
|
+
} catch (err) {
|
|
964
|
+
settleSeed(false)
|
|
965
|
+
throw err
|
|
966
|
+
}
|
|
967
|
+
let sendResult
|
|
968
|
+
let admissionFinal = false
|
|
969
|
+
let forwardedEffectsCommitted = false
|
|
970
|
+
const commitForwardedEffects = () => {
|
|
971
|
+
if (forwardedEffectsCommitted) return
|
|
972
|
+
forwardedEffectsCommitted = true
|
|
973
|
+
recordHistoryEntry(textToSend)
|
|
974
|
+
ctx.transport.updatePrimary(targetSessionId, client.id)
|
|
975
|
+
ctx.transport.broadcast(
|
|
976
|
+
{ type: 'user_input', sessionId: targetSessionId, clientId: client.id, text: trimmed, messageId, timestamp: Date.now() },
|
|
977
|
+
(c) => c.id !== client.id
|
|
978
|
+
)
|
|
979
|
+
}
|
|
980
|
+
const onInputAdmission = (admission) => {
|
|
981
|
+
observeSeedAdmission(admission)
|
|
982
|
+
if (!inputRecord || admissionFinal || !admission || typeof admission !== 'object') return
|
|
983
|
+
const status = admission.status
|
|
984
|
+
const delivery = admission.delivery
|
|
985
|
+
const accepted = (status === 'accepted' && delivery === 'dispatch_started') ||
|
|
986
|
+
(status === 'queued' && delivery === 'queued')
|
|
987
|
+
const rejected = status === 'rejected' && delivery === 'not_dispatched'
|
|
988
|
+
const uncertain = status === 'uncertain' && delivery === 'unknown'
|
|
989
|
+
if (!accepted && !rejected && !uncertain) return
|
|
990
|
+
|
|
991
|
+
admissionFinal = true
|
|
992
|
+
inputRecord.status = status
|
|
993
|
+
inputRecord.delivery = delivery
|
|
994
|
+
if (accepted) {
|
|
995
|
+
inputRecord.acceptedAt = typeof ctx.now === 'function' ? ctx.now() : Date.now()
|
|
996
|
+
sendInputAck(ws, ctx, inputRecord)
|
|
997
|
+
commitForwardedEffects()
|
|
998
|
+
return
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
if (uncertain) {
|
|
1002
|
+
// A lost native acknowledgement is terminal uncertainty, not definite
|
|
1003
|
+
// dispatch. Retain the reservation so the same id cannot be retried.
|
|
1004
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
1005
|
+
retrySafe: false,
|
|
1006
|
+
reason: typeof admission.reason === 'string' ? admission.reason : 'provider_admission_uncertain',
|
|
1007
|
+
message: typeof admission.message === 'string'
|
|
1008
|
+
? admission.message
|
|
1009
|
+
: 'Provider admission is uncertain; inspect the original session before explicitly resending.',
|
|
1010
|
+
})
|
|
1011
|
+
return
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
1015
|
+
status: 'rejected',
|
|
1016
|
+
delivery: 'not_dispatched',
|
|
1017
|
+
retrySafe: admission.retrySafe === true,
|
|
1018
|
+
reason: typeof admission.reason === 'string' ? admission.reason : 'provider_rejected',
|
|
1019
|
+
message: typeof admission.message === 'string'
|
|
1020
|
+
? admission.message
|
|
1021
|
+
: 'The provider rejected the input before admission.',
|
|
1022
|
+
})
|
|
1023
|
+
releaseInputRequest(ctx, inputRecord)
|
|
1024
|
+
}
|
|
1025
|
+
try {
|
|
1026
|
+
sendResult = entry.session.sendMessage(dispatchText, attachments, {
|
|
1027
|
+
isVoice: !!msg.isVoice,
|
|
1028
|
+
clientMessageId: messageId,
|
|
1029
|
+
...(inputRecord || seedClaim ? { onInputAdmission } : {}),
|
|
1030
|
+
...(preparedContext?.context ? { context: preparedContext.context } : {}),
|
|
1031
|
+
isAuthorized: authorizedFor(ctx, client),
|
|
1032
|
+
})
|
|
1033
|
+
} catch (err) {
|
|
1034
|
+
settleSeed(false)
|
|
1035
|
+
if (inputRecord && !admissionFinal) {
|
|
1036
|
+
inputRecord.status = 'uncertain'
|
|
1037
|
+
inputRecord.delivery = 'unknown'
|
|
1038
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
1039
|
+
reason: 'dispatch_threw',
|
|
1040
|
+
message: 'Provider dispatch failed synchronously; acceptance is uncertain and the server will not retry automatically.',
|
|
1041
|
+
})
|
|
1042
|
+
}
|
|
1043
|
+
throw err
|
|
1044
|
+
}
|
|
519
1045
|
if (sendResult && typeof sendResult.catch === 'function') {
|
|
520
1046
|
sendResult.catch((err) => {
|
|
521
1047
|
const message = err?.message || String(err)
|
|
@@ -523,23 +1049,49 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
523
1049
|
})
|
|
524
1050
|
}
|
|
525
1051
|
|
|
526
|
-
|
|
1052
|
+
if (inputRecord && !admissionFinal) {
|
|
1053
|
+
inputRecord.status = 'uncertain'
|
|
1054
|
+
inputRecord.delivery = 'unknown'
|
|
1055
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
1056
|
+
reason: 'admission_pending',
|
|
1057
|
+
message: 'The provider has not confirmed admission yet. The server will not retry automatically.',
|
|
1058
|
+
})
|
|
1059
|
+
}
|
|
527
1060
|
|
|
528
|
-
//
|
|
529
|
-
//
|
|
530
|
-
//
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
1061
|
+
// Older clients have no correlated admission contract. Preserve their
|
|
1062
|
+
// established fire-and-forget history, primary, and peer-echo behavior.
|
|
1063
|
+
//
|
|
1064
|
+
if (!inputRecord) commitForwardedEffects()
|
|
1065
|
+
|
|
1066
|
+
// #8866: a claimed seed whose provider reported no admission by the time
|
|
1067
|
+
// sendMessage returned. Every in-tree provider reports it (base/sdk/cli/
|
|
1068
|
+
// claude-tui/jsonl-subprocess incl. codex-exec and gemini, byok, acp, codex
|
|
1069
|
+
// app-server); one that does not is treated as having taken the input once its
|
|
1070
|
+
// call settles (a rejected call included: no signal means uncertain, and
|
|
1071
|
+
// uncertain counts as consumed). A synchronous return settles it now.
|
|
1072
|
+
if (!seedSettled) {
|
|
1073
|
+
if (sendResult && typeof sendResult.then === 'function') {
|
|
1074
|
+
sendResult.then(() => settleSeed(true), () => settleSeed(true))
|
|
1075
|
+
} else {
|
|
1076
|
+
settleSeed(true)
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
536
1079
|
}
|
|
537
1080
|
|
|
538
1081
|
function handleInterrupt(ws, client, msg, ctx) {
|
|
1082
|
+
// Principal branch: explicit sessionId through principalMaySee, never the host path.
|
|
1083
|
+
if (isPrincipalClient(client)) return refusePrincipalHandler(ws, client, msg, ctx, 'drive')
|
|
539
1084
|
const interruptSessionId = msg.sessionId || client.activeSessionId
|
|
540
1085
|
const entry = resolveSession(ctx, msg, client)
|
|
541
1086
|
if (entry) {
|
|
542
1087
|
log.info(`Interrupt from ${client.id} to session ${interruptSessionId}`)
|
|
1088
|
+
// #8301: a user Stop ends daemon wakes for this session until they next type.
|
|
1089
|
+
ctx.sessions.sessionManager?.recordUserInterrupt?.(interruptSessionId)
|
|
1090
|
+
// #8374/#8430: record that the USER stopped this turn, before the abort
|
|
1091
|
+
// resolves any open prompt (a failed turn aborts the same controller).
|
|
1092
|
+
entry.session.markUserStopInFlight?.()
|
|
1093
|
+
// #9241: and for the stop-before-reply marker, which is separate on purpose.
|
|
1094
|
+
entry.session.markStopRequested?.()
|
|
543
1095
|
entry.session.interrupt()
|
|
544
1096
|
return
|
|
545
1097
|
}
|
|
@@ -757,7 +1309,13 @@ function handleRegisterPushToken(ws, client, msg, ctx) {
|
|
|
757
1309
|
// is actually pruned from the registry. Without ref-counting, the
|
|
758
1310
|
// first disconnect would strip the token from the second client's
|
|
759
1311
|
// active session.
|
|
760
|
-
|
|
1312
|
+
// A session-scoped connection registers a destination for ITS session's
|
|
1313
|
+
// notifications only; the sink delivers nothing else to it.
|
|
1314
|
+
const ok = ctx.services.pushManager.registerToken(
|
|
1315
|
+
msg.token,
|
|
1316
|
+
client.id,
|
|
1317
|
+
isBoundClient(client) ? { sessionId: client.boundSessionId } : undefined,
|
|
1318
|
+
)
|
|
761
1319
|
if (!ok) {
|
|
762
1320
|
ctx.transport.send(ws, {
|
|
763
1321
|
type: 'push_token_error',
|
|
@@ -816,6 +1374,12 @@ function handleNotificationPrefsGet(ws, client, msg, ctx) {
|
|
|
816
1374
|
}
|
|
817
1375
|
|
|
818
1376
|
function handleNotificationPrefsSet(ws, client, msg, ctx) {
|
|
1377
|
+
// Host-wide notification routing is never delegated to an agent principal. This
|
|
1378
|
+
// handler carries no other client-authority check (S2 adds the principal one).
|
|
1379
|
+
if (isPrincipalClient(client)) {
|
|
1380
|
+
sendPrincipalRefusal(ws, client, msg, ctx, 'handler')
|
|
1381
|
+
return
|
|
1382
|
+
}
|
|
819
1383
|
if (!ctx.services.pushManager) {
|
|
820
1384
|
sendError(ws, msg?.requestId, 'NOT_AVAILABLE', 'notification prefs unavailable (no push manager)', undefined, ctx)
|
|
821
1385
|
return
|
|
@@ -875,6 +1439,33 @@ function handleNotificationPrefsSet(ws, client, msg, ctx) {
|
|
|
875
1439
|
}
|
|
876
1440
|
}
|
|
877
1441
|
|
|
1442
|
+
/**
|
|
1443
|
+
* #8470: the wire code of the error frame that tells the ANSWERING client its
|
|
1444
|
+
* `user_question_response` reached nothing. Without it the answer is dropped
|
|
1445
|
+
* silently, and both clients have already marked the card answered on send.
|
|
1446
|
+
*/
|
|
1447
|
+
const QUESTION_NOT_DELIVERED_CODE = 'QUESTION_NOT_DELIVERED'
|
|
1448
|
+
|
|
1449
|
+
/**
|
|
1450
|
+
* Tell the answering client (only) that its answer to `msg.toolUseId` was not
|
|
1451
|
+
* delivered. Reuses the `error` envelope (a coded frame, `toolUseId` and
|
|
1452
|
+
* `sessionId` ride along as the envelope's passthrough fields) rather than a new
|
|
1453
|
+
* wire type: the clients already surface an error frame, and key the card off the
|
|
1454
|
+
* `toolUseId`. The wording covers every cause without claiming one: the question
|
|
1455
|
+
* was already answered, timed out, or replaced by a newer one.
|
|
1456
|
+
*/
|
|
1457
|
+
function sendQuestionNotDelivered(ws, msg, sessionId, ctx) {
|
|
1458
|
+
sendError(
|
|
1459
|
+
ws,
|
|
1460
|
+
null,
|
|
1461
|
+
QUESTION_NOT_DELIVERED_CODE,
|
|
1462
|
+
'Your answer was not delivered: that question is no longer waiting (it was already answered, timed out, or replaced by a newer question).',
|
|
1463
|
+
// `fatal: false`: the session is fine, one answer was lost (a warning, not an error toast).
|
|
1464
|
+
{ toolUseId: msg.toolUseId, fatal: false, ...(sessionId ? { sessionId } : {}) },
|
|
1465
|
+
ctx,
|
|
1466
|
+
)
|
|
1467
|
+
}
|
|
1468
|
+
|
|
878
1469
|
function handleUserQuestionResponse(ws, client, msg, ctx) {
|
|
879
1470
|
// #5753 — route by toolUseId when one is supplied. `_registerQuestionRoute`
|
|
880
1471
|
// maps every question that has a toolUseId at DISPATCH time (before the
|
|
@@ -898,14 +1489,28 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
|
|
|
898
1489
|
// (legacy single-session mode / clients that don't send one), where there is
|
|
899
1490
|
// a single question in flight and no cross-question mis-route risk.
|
|
900
1491
|
let questionSessionId
|
|
1492
|
+
// #8470: false when the route is gone and the owner comes from the map's memory
|
|
1493
|
+
// of recently removed routes. Such an answer reaches nothing, but the sender is
|
|
1494
|
+
// still told, and only after the SAME entitlement checks as a live route.
|
|
1495
|
+
let routeLive = true
|
|
1496
|
+
let recentAnswerDigest
|
|
901
1497
|
if (typeof msg.toolUseId === 'string') {
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
1498
|
+
const routes = ctx.permissions.questionSessionMap
|
|
1499
|
+
if (routes.has(msg.toolUseId)) {
|
|
1500
|
+
questionSessionId = routes.get(msg.toolUseId)
|
|
1501
|
+
} else {
|
|
1502
|
+
// An id nobody routed (never existed, or older than the memory) is silent:
|
|
1503
|
+
// answering it would tell a client which ids exist. And NOT logged either: a
|
|
1504
|
+
// log line goes out as a `log_entry` to the sender's own session's viewers
|
|
1505
|
+
// (ws-server fans logs out), and a line that appears only for a resolved or
|
|
1506
|
+
// unknown id is the oracle by another route. The log is written below, after
|
|
1507
|
+
// the entitlement checks, to the OWNING session.
|
|
1508
|
+
const recent = routes.recentOwner?.(msg.toolUseId)
|
|
1509
|
+
if (!recent) return
|
|
1510
|
+
questionSessionId = recent.sessionId
|
|
1511
|
+
recentAnswerDigest = recent.answerDigest
|
|
1512
|
+
routeLive = false
|
|
907
1513
|
}
|
|
908
|
-
questionSessionId = ctx.permissions.questionSessionMap.get(msg.toolUseId)
|
|
909
1514
|
} else {
|
|
910
1515
|
questionSessionId = client.activeSessionId
|
|
911
1516
|
}
|
|
@@ -929,10 +1534,27 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
|
|
|
929
1534
|
if (!isSessionViewer(client, questionSessionId)) return
|
|
930
1535
|
}
|
|
931
1536
|
|
|
1537
|
+
if (!routeLive) {
|
|
1538
|
+
sessionLogger(questionSessionId || undefined).info(
|
|
1539
|
+
`user_question_response dropped: stale toolUseId=${msg.toolUseId} (question already resolved or its session is gone)`,
|
|
1540
|
+
)
|
|
1541
|
+
// #8470: the sender marked its card answered when it sent; say it was not,
|
|
1542
|
+
// unless the answer that landed IS this one (a duplicate or a second tab that
|
|
1543
|
+
// chose the same thing): then the card is right and retracting it would be
|
|
1544
|
+
// the lie.
|
|
1545
|
+
if (recentAnswerDigest !== undefined && recentAnswerDigest === answerDigest(msg)) return
|
|
1546
|
+
sendQuestionNotDelivered(ws, msg, questionSessionId || undefined, ctx)
|
|
1547
|
+
return
|
|
1548
|
+
}
|
|
1549
|
+
|
|
932
1550
|
if (msg.toolUseId) ctx.permissions.questionSessionMap.delete(msg.toolUseId)
|
|
933
1551
|
|
|
934
1552
|
const entry = ctx.sessions.sessionManager.getSession(questionSessionId)
|
|
935
1553
|
if (entry && typeof entry.session.respondToQuestion === 'function' && typeof msg.answer === 'string') {
|
|
1554
|
+
// #9242: a person answering a session's question is taking part in its
|
|
1555
|
+
// conversation: a scheduled task stops owning the session, exactly as when they
|
|
1556
|
+
// type. Before delivery, so the turn their answer resumes is already theirs.
|
|
1557
|
+
ctx.sessions.sessionManager?.recordUserIntent?.(questionSessionId)
|
|
936
1558
|
// #4604: log the incoming response shape so a multi-question form
|
|
937
1559
|
// wedge is correlatable from chroxy.log alone (toolUseId + map-key
|
|
938
1560
|
// count distinguishes the SDK's per-question form from the TUI's
|
|
@@ -959,18 +1581,44 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
|
|
|
959
1581
|
const qlog = sessionLogger(questionSessionId)
|
|
960
1582
|
qlog.info(`user_question_response received: toolUseId=${msg.toolUseId || '?'} answer.length=${(msg.answer || '').length} answers.keys=${msg.answers ? Object.keys(msg.answers).length : 0} freeform=${hasFreeform ? msg.freeformText.length : 0}`)
|
|
961
1583
|
// #4668: forward msg.toolUseId so claude-tui-session can route the
|
|
962
|
-
// answer to the right pending entry in its Map.
|
|
963
|
-
//
|
|
964
|
-
//
|
|
965
|
-
// a safe addition. ByokSession's respondToQuestion forwards to
|
|
966
|
-
// _permissions.respondToQuestion which similarly ignores trailing
|
|
967
|
-
// args it doesn't read.
|
|
1584
|
+
// answer to the right pending entry in its Map. #8460: SDK, BYOK and
|
|
1585
|
+
// codex forward it to the permission manager, which refuses an answer
|
|
1586
|
+
// whose id is not the pending question's. cli-session ignores it.
|
|
968
1587
|
// #4651: forward msg.freeformText as a final opts object — claude-tui-
|
|
969
1588
|
// session uses it to drive the two-stage Other-path write (digit →
|
|
970
1589
|
// text-input prompt → freeform text + Enter). Other providers ignore
|
|
971
1590
|
// the trailing arg.
|
|
972
1591
|
const opts = hasFreeform ? { freeformText: msg.freeformText } : undefined
|
|
973
|
-
entry.session.respondToQuestion(msg.answer, msg.answers, msg.toolUseId, opts)
|
|
1592
|
+
const delivered = entry.session.respondToQuestion(msg.answer, msg.answers, msg.toolUseId, opts)
|
|
1593
|
+
// #8362: the one place every provider's answer passes through. cli and tui
|
|
1594
|
+
// deliver the answer before the tool's result event arrives, so without this
|
|
1595
|
+
// record a restart in that window labels an answered question interrupted.
|
|
1596
|
+
// Only an actionable answer counts (the TUI driver drops an empty one without
|
|
1597
|
+
// an answers map); anything else stays unanswered and is swept as before.
|
|
1598
|
+
// "Accepted" means this handler accepted the answer, NOT that the provider
|
|
1599
|
+
// delivered it: apart from the #8460 refusal below, which returns `false`,
|
|
1600
|
+
// respondToQuestion reports nothing, and a provider can still silently
|
|
1601
|
+
// drop the answer -- the claude-tui form driver with no pending entry or no
|
|
1602
|
+
// terminal, its multi-select refuse branch, the CLI with `_waitingForAnswer`
|
|
1603
|
+
// false, a permission manager with nothing pending (SDK / BYOK). That is
|
|
1604
|
+
// acceptable because such a drop is either a repeat of an answer already
|
|
1605
|
+
// delivered, or follows (or, for the multi-select refuse branch, is) a turn
|
|
1606
|
+
// teardown that has already recorded a `tool_result` for the question's
|
|
1607
|
+
// tool, synthetic or the provider's own error result, so marking it
|
|
1608
|
+
// answered hides no real interrupted state.
|
|
1609
|
+
const hasAnswers = msg.answers && typeof msg.answers === 'object' && Object.keys(msg.answers).length > 0
|
|
1610
|
+
// #8460: the one drop the provider REPORTS -- an answer the permission manager
|
|
1611
|
+
// (SDK / BYOK / codex) refused because its toolUseId is not the pending
|
|
1612
|
+
// question's -- returns `false`. That answer was for a question that is no
|
|
1613
|
+
// longer the one being asked, so it must not mark anything answered.
|
|
1614
|
+
if (delivered === false) {
|
|
1615
|
+
// #8470: and the sender must be told, or its card keeps reading answered.
|
|
1616
|
+
sendQuestionNotDelivered(ws, msg, questionSessionId || undefined, ctx)
|
|
1617
|
+
} else if (msg.answer.length > 0 || hasAnswers) {
|
|
1618
|
+
ctx.sessions.sessionManager.recordQuestionAnswered?.(questionSessionId, msg.toolUseId)
|
|
1619
|
+
// #8470: remember WHAT landed, so a duplicate of it is not called lost.
|
|
1620
|
+
if (typeof msg.toolUseId === 'string') ctx.permissions.questionSessionMap.noteAnswered?.(msg.toolUseId, answerDigest(msg))
|
|
1621
|
+
}
|
|
974
1622
|
}
|
|
975
1623
|
}
|
|
976
1624
|
|
|
@@ -989,6 +1637,14 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
|
|
|
989
1637
|
// Only claude-tui sessions expose writeTerminalInput; other providers have no PTY,
|
|
990
1638
|
// so the keystroke is silently dropped for them.
|
|
991
1639
|
function handleTerminalInput(ws, client, msg, ctx) {
|
|
1640
|
+
// Raw keystrokes into a PTY are never delegated to an agent principal. The
|
|
1641
|
+
// user-shell check below applies to user-shell sessions only, so this refusal is
|
|
1642
|
+
// unconditional and first (a principal reaches a PTY only through the fenced
|
|
1643
|
+
// sendMessage path of the input contract).
|
|
1644
|
+
if (isPrincipalClient(client)) {
|
|
1645
|
+
sendPrincipalRefusal(ws, client, msg, ctx, 'handler')
|
|
1646
|
+
return
|
|
1647
|
+
}
|
|
992
1648
|
const sid = msg.sessionId || client.activeSessionId
|
|
993
1649
|
const entry = resolveSession(ctx, msg, client)
|
|
994
1650
|
if (!entry) {
|
|
@@ -1035,6 +1691,16 @@ function handleTerminalInput(ws, client, msg, ctx) {
|
|
|
1035
1691
|
))
|
|
1036
1692
|
return
|
|
1037
1693
|
}
|
|
1694
|
+
// #8301: a human submitting a line in the terminal pane is the same intent as a
|
|
1695
|
+
// typed chat input (a TUI user who Stops and keeps working in the pane would
|
|
1696
|
+
// otherwise have wakes refused forever). Only a submission counts — a bare
|
|
1697
|
+
// keystroke stream without a newline is not "I want the agent to work" — and
|
|
1698
|
+
// only after the primary/viewer/claim checks above, so a refused observer's
|
|
1699
|
+
// keystroke does not. The daemon's own PTY wake never comes through this
|
|
1700
|
+
// handler (it calls `writeTerminalInput` directly).
|
|
1701
|
+
if (msg.data.includes('\r') || msg.data.includes('\n')) {
|
|
1702
|
+
ctx.sessions.sessionManager?.recordUserIntent?.(sid)
|
|
1703
|
+
}
|
|
1038
1704
|
entry.session.writeTerminalInput(msg.data)
|
|
1039
1705
|
}
|
|
1040
1706
|
|