@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
|
@@ -5,11 +5,16 @@
|
|
|
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'
|
|
12
15
|
import { createLogger, sessionLogger } from '../logger.js'
|
|
16
|
+
import { answerDigest } from '../question-route-map.js'
|
|
17
|
+
import { INPUT_CONTEXT_CAPABILITIES, InputContextError, prepareInputContext } from '../input-context.js'
|
|
13
18
|
|
|
14
19
|
const log = createLogger('ws')
|
|
15
20
|
|
|
@@ -50,9 +55,13 @@ function _getEvaluatorIterations(ctx) {
|
|
|
50
55
|
// We reject the second concurrent draft with the same input_conflict
|
|
51
56
|
// category the user already understands — not queue it — so callers retry
|
|
52
57
|
// rather than silently waiting on an unbounded queue.
|
|
58
|
+
//
|
|
59
|
+
// The map lives on `ctx.runtime` (like the iteration counter above), NOT on the
|
|
60
|
+
// ctx itself: the ctx is spread per message, so a property set directly on it
|
|
61
|
+
// would be a fresh, empty map for every message and the lock would never be seen.
|
|
53
62
|
function _getEvaluatorAwaits(ctx) {
|
|
54
|
-
if (!ctx.
|
|
55
|
-
return ctx.
|
|
63
|
+
if (!ctx.runtime.pendingEvaluatorAwaits) ctx.runtime.pendingEvaluatorAwaits = new Map()
|
|
64
|
+
return ctx.runtime.pendingEvaluatorAwaits
|
|
56
65
|
}
|
|
57
66
|
|
|
58
67
|
// #3665 — build the history text appended for a recorded user input.
|
|
@@ -64,19 +73,20 @@ function _getEvaluatorAwaits(ctx) {
|
|
|
64
73
|
// without normalization the recorded text reads `'foo \n[1 file(s) attached]'`
|
|
65
74
|
// (double whitespace before the marker). Empty/whitespace-only text drops
|
|
66
75
|
// to a marker-only entry.
|
|
67
|
-
export function buildHistoryText(text, attCount) {
|
|
68
|
-
if (!attCount) return text
|
|
76
|
+
export function buildHistoryText(text, attCount, contextCount = 0) {
|
|
77
|
+
if (!attCount && !contextCount) return text
|
|
69
78
|
const stripped = typeof text === 'string' ? text.replace(/\s+$/, '') : ''
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
79
|
+
const markers = []
|
|
80
|
+
if (attCount) markers.push(`[${attCount} file(s) attached]`)
|
|
81
|
+
if (contextCount) markers.push(`[${contextCount} context item(s) selected]`)
|
|
82
|
+
return stripped ? `${stripped} ${markers.join(' ')}` : markers.join(' ')
|
|
73
83
|
}
|
|
74
84
|
|
|
75
|
-
// #3639 — build the minimal config object passed into
|
|
85
|
+
// #3639 — build the minimal config object passed into shouldSkipEvaluatorAsync.
|
|
76
86
|
// The per-session promptEvaluatorSkipPattern (string source) takes precedence;
|
|
77
87
|
// the server-wide ctx.services.config.promptEvaluatorSkipPattern (#3187) is the
|
|
78
88
|
// fallback so existing global-config deployments keep working unchanged.
|
|
79
|
-
//
|
|
89
|
+
// shouldSkipEvaluatorAsync only reads `config.promptEvaluatorSkipPattern` (verified
|
|
80
90
|
// in prompt-evaluator.js), so we return a single-key object rather than
|
|
81
91
|
// spreading the whole ctx.services.config — this runs on the user_input hot path and
|
|
82
92
|
// the spread was unnecessary allocation/copy work.
|
|
@@ -99,6 +109,10 @@ function _resolveSkipConfig(entry, ctx) {
|
|
|
99
109
|
// but collisions inside one session's ring buffer are the client's problem.
|
|
100
110
|
const USER_INPUT_ID_RE = /^[A-Za-z0-9_-]+$/
|
|
101
111
|
const MAX_CLIENT_MESSAGE_ID_LEN = 128
|
|
112
|
+
export const INPUT_DEDUP_TTL_MS = 10 * 60 * 1000
|
|
113
|
+
export const INPUT_DEDUP_TOMBSTONE_TTL_MS = 60 * 60 * 1000
|
|
114
|
+
export const INPUT_DEDUP_MAX_PER_SESSION = 4096
|
|
115
|
+
const INPUT_HASH_STRING_CHUNK_CODE_UNITS = 64 * 1024
|
|
102
116
|
// IDs the clients treat specially in their stores (e.g. the "thinking"
|
|
103
117
|
// placeholder shown while waiting for the first stream_delta). Never let a
|
|
104
118
|
// client-supplied id collide with these — it would clobber the placeholder
|
|
@@ -117,6 +131,161 @@ function resolveUserInputId(candidate) {
|
|
|
117
131
|
return candidate
|
|
118
132
|
}
|
|
119
133
|
|
|
134
|
+
function isWellFormedClientMessageId(candidate) {
|
|
135
|
+
return typeof candidate === 'string' &&
|
|
136
|
+
candidate.length > 0 &&
|
|
137
|
+
candidate.length <= MAX_CLIENT_MESSAGE_ID_LEN &&
|
|
138
|
+
USER_INPUT_ID_RE.test(candidate) &&
|
|
139
|
+
!RESERVED_USER_INPUT_IDS.has(candidate)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function updateCanonicalHash(hash, value) {
|
|
143
|
+
if (Array.isArray(value)) {
|
|
144
|
+
hash.update(`a${value.length}:`)
|
|
145
|
+
value.forEach((item) => updateCanonicalHash(hash, item))
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
if (value && typeof value === 'object') {
|
|
149
|
+
const keys = Object.keys(value).sort()
|
|
150
|
+
hash.update(`o${keys.length}:`)
|
|
151
|
+
keys.forEach((key) => {
|
|
152
|
+
updateCanonicalHash(hash, key)
|
|
153
|
+
updateCanonicalHash(hash, value[key])
|
|
154
|
+
})
|
|
155
|
+
return
|
|
156
|
+
}
|
|
157
|
+
if (typeof value === 'string') {
|
|
158
|
+
// Length-prefix and feed the original string straight into Hash.update.
|
|
159
|
+
// UTF-16LE preserves JavaScript code units, including lone surrogates that
|
|
160
|
+
// UTF-8 would collapse to the same replacement bytes. Bounded slices avoid
|
|
161
|
+
// building a second multi-megabyte representation for image data.
|
|
162
|
+
hash.update(`s${value.length}:`)
|
|
163
|
+
for (let offset = 0; offset < value.length; offset += INPUT_HASH_STRING_CHUNK_CODE_UNITS) {
|
|
164
|
+
hash.update(value.slice(offset, offset + INPUT_HASH_STRING_CHUNK_CODE_UNITS), 'utf16le')
|
|
165
|
+
}
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
if (value === null) {
|
|
169
|
+
hash.update('z')
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
if (value === undefined) {
|
|
173
|
+
hash.update('u')
|
|
174
|
+
return
|
|
175
|
+
}
|
|
176
|
+
if (typeof value === 'boolean') {
|
|
177
|
+
hash.update(value ? 'b1' : 'b0')
|
|
178
|
+
return
|
|
179
|
+
}
|
|
180
|
+
hash.update(`n${String(value)}:`)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function inputPayloadHash(msg) {
|
|
184
|
+
const hash = createHash('sha256')
|
|
185
|
+
updateCanonicalHash(hash, {
|
|
186
|
+
data: msg.data,
|
|
187
|
+
attachments: msg.attachments,
|
|
188
|
+
context: msg.context,
|
|
189
|
+
isVoice: !!msg.isVoice,
|
|
190
|
+
})
|
|
191
|
+
return hash.digest('hex')
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function getInputDedupRecords(ctx) {
|
|
195
|
+
if (!ctx.runtime.inputDedupRecords) ctx.runtime.inputDedupRecords = new Map()
|
|
196
|
+
return ctx.runtime.inputDedupRecords
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function sendInputAck(ws, ctx, record, overrides = {}) {
|
|
200
|
+
if (!record) return
|
|
201
|
+
const status = overrides.status ?? record.status
|
|
202
|
+
const delivery = overrides.delivery ?? record.delivery
|
|
203
|
+
const provesContextAdmission = delivery === 'dispatch_started' || delivery === 'queued'
|
|
204
|
+
const context = record.contextItemIds?.length && provesContextAdmission &&
|
|
205
|
+
(status === 'accepted' || status === 'queued' || status === 'duplicate')
|
|
206
|
+
? {
|
|
207
|
+
version: 1,
|
|
208
|
+
acceptedItemIds: [...record.contextItemIds],
|
|
209
|
+
supportedKinds: [...INPUT_CONTEXT_CAPABILITIES.kinds],
|
|
210
|
+
supportedLifetimes: [...INPUT_CONTEXT_CAPABILITIES.lifetimes],
|
|
211
|
+
}
|
|
212
|
+
: undefined
|
|
213
|
+
ctx.transport.send(ws, {
|
|
214
|
+
type: 'input_ack',
|
|
215
|
+
sessionId: record.sessionId,
|
|
216
|
+
clientMessageId: record.clientMessageId,
|
|
217
|
+
status,
|
|
218
|
+
delivery,
|
|
219
|
+
retrySafe: false,
|
|
220
|
+
acceptedAt: record.acceptedAt,
|
|
221
|
+
retentionExpiresAt: record.expiresAt,
|
|
222
|
+
dedupScope: 'process',
|
|
223
|
+
...(context ? { context } : {}),
|
|
224
|
+
...overrides,
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function sendInputRejectionAck(ws, ctx, sessionId, msg, reason, message) {
|
|
229
|
+
if (!isWellFormedClientMessageId(msg.clientMessageId)) return
|
|
230
|
+
const parsedContext = msg.context ? InputContextEnvelopeSchema.safeParse(msg.context) : null
|
|
231
|
+
sendInputAck(ws, ctx, {
|
|
232
|
+
sessionId,
|
|
233
|
+
clientMessageId: msg.clientMessageId,
|
|
234
|
+
contextItemIds: parsedContext?.success ? parsedContext.data.items.map((item) => item.id) : null,
|
|
235
|
+
status: 'rejected',
|
|
236
|
+
delivery: 'not_dispatched',
|
|
237
|
+
}, { reason, message })
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function reserveInputRequest(ctx, sessionId, msg) {
|
|
241
|
+
if (!isWellFormedClientMessageId(msg.clientMessageId)) return { record: null, duplicate: false }
|
|
242
|
+
const now = typeof ctx.now === 'function' ? ctx.now() : Date.now()
|
|
243
|
+
const ttlMs = Number.isFinite(ctx.inputDedupTtlMs) ? ctx.inputDedupTtlMs : INPUT_DEDUP_TTL_MS
|
|
244
|
+
const tombstoneTtlMs = Number.isFinite(ctx.inputDedupTombstoneTtlMs)
|
|
245
|
+
? ctx.inputDedupTombstoneTtlMs
|
|
246
|
+
: INPUT_DEDUP_TOMBSTONE_TTL_MS
|
|
247
|
+
const bySession = getInputDedupRecords(ctx)
|
|
248
|
+
let records = bySession.get(sessionId)
|
|
249
|
+
if (!records) {
|
|
250
|
+
records = new Map()
|
|
251
|
+
bySession.set(sessionId, records)
|
|
252
|
+
}
|
|
253
|
+
for (const [id, record] of records) {
|
|
254
|
+
if (now > record.tombstoneExpiresAt) records.delete(id)
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const hash = inputPayloadHash(msg)
|
|
258
|
+
const existing = records.get(msg.clientMessageId)
|
|
259
|
+
if (existing) {
|
|
260
|
+
if (existing.hash !== hash) return { record: existing, mismatch: true }
|
|
261
|
+
if (now > existing.expiresAt) return { record: existing, expired: true }
|
|
262
|
+
return { record: existing, duplicate: true }
|
|
263
|
+
}
|
|
264
|
+
if (records.size >= INPUT_DEDUP_MAX_PER_SESSION) return { record: null, capacity: true }
|
|
265
|
+
|
|
266
|
+
const record = {
|
|
267
|
+
sessionId,
|
|
268
|
+
clientMessageId: msg.clientMessageId,
|
|
269
|
+
hash,
|
|
270
|
+
// Retain only bounded identifiers, never image/text payload bytes. The
|
|
271
|
+
// payload hash is sufficient for duplicate/mismatch decisions.
|
|
272
|
+
contextItemIds: msg.context?.items?.map((item) => item.id) ?? null,
|
|
273
|
+
status: 'uncertain',
|
|
274
|
+
delivery: 'unknown',
|
|
275
|
+
expiresAt: now + ttlMs,
|
|
276
|
+
tombstoneExpiresAt: now + ttlMs + tombstoneTtlMs,
|
|
277
|
+
}
|
|
278
|
+
records.set(msg.clientMessageId, record)
|
|
279
|
+
return { record, duplicate: false }
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function releaseInputRequest(ctx, record) {
|
|
283
|
+
if (!record) return
|
|
284
|
+
const records = getInputDedupRecords(ctx).get(record.sessionId)
|
|
285
|
+
if (records?.get(record.clientMessageId) === record) records.delete(record.clientMessageId)
|
|
286
|
+
if (records?.size === 0) getInputDedupRecords(ctx).delete(record.sessionId)
|
|
287
|
+
}
|
|
288
|
+
|
|
120
289
|
// #5281 ①.3 — an input_conflict rejection: the session can't accept this send
|
|
121
290
|
// right now (busy with another device's request, or still evaluating a previous
|
|
122
291
|
// draft on the same session). Echo the session and the rejected clientMessageId
|
|
@@ -209,10 +378,30 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
209
378
|
return
|
|
210
379
|
}
|
|
211
380
|
|
|
381
|
+
// #8301: a person just typed into this session. Record the INTENT here, at
|
|
382
|
+
// receipt: synchronously, before any await or dispatch, and whether or not the
|
|
383
|
+
// input is later rejected, queued or deduped. It must not wait for admission
|
|
384
|
+
// (`recordUserInput` runs at admission for correlated input, which a provider
|
|
385
|
+
// may reach only after awaiting its transport): input sent BEFORE a Stop could
|
|
386
|
+
// otherwise be admitted after it and silently undo it. An empty send is not
|
|
387
|
+
// intent.
|
|
388
|
+
if ((typeof text === 'string' && text.trim().length > 0) || attachments?.length) {
|
|
389
|
+
ctx.sessions.sessionManager?.recordUserIntent?.(targetSessionId)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Only negotiated clients receive the new acknowledgement/dedup behavior.
|
|
393
|
+
// An explicit context envelope also opts in by construction. This keeps the
|
|
394
|
+
// observable plain-input behavior unchanged for deployed older clients.
|
|
395
|
+
const supportsInputAck = !!msg.context
|
|
396
|
+
|| client.clientCapabilities?.has?.('input_context_v1') === true
|
|
397
|
+
|
|
212
398
|
if (attachments?.length) {
|
|
213
399
|
const err = validateAttachments(attachments)
|
|
214
400
|
if (err) {
|
|
215
401
|
sendSessionError(ws, ctx, `Invalid attachment: ${err}`)
|
|
402
|
+
if (supportsInputAck) {
|
|
403
|
+
sendInputRejectionAck(ws, ctx, targetSessionId, msg, 'invalid_attachment', `Invalid attachment: ${err}`)
|
|
404
|
+
}
|
|
216
405
|
return
|
|
217
406
|
}
|
|
218
407
|
}
|
|
@@ -222,9 +411,59 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
222
411
|
attachments = resolveFileRefAttachments(attachments, entry.cwd)
|
|
223
412
|
}
|
|
224
413
|
|
|
225
|
-
|
|
414
|
+
let preparedContext
|
|
415
|
+
const attachmentsWithoutContext = attachments
|
|
416
|
+
if (msg.context) {
|
|
417
|
+
const parsedContext = InputContextEnvelopeSchema.safeParse(msg.context)
|
|
418
|
+
if (!parsedContext.success) {
|
|
419
|
+
const record = isWellFormedClientMessageId(msg.clientMessageId)
|
|
420
|
+
? {
|
|
421
|
+
sessionId: targetSessionId,
|
|
422
|
+
clientMessageId: msg.clientMessageId,
|
|
423
|
+
contextItemIds: null,
|
|
424
|
+
status: 'rejected',
|
|
425
|
+
delivery: 'not_dispatched',
|
|
426
|
+
}
|
|
427
|
+
: null
|
|
428
|
+
sendInputAck(ws, ctx, record, { reason: 'invalid_context', message: 'The selected context envelope is invalid.' })
|
|
429
|
+
return
|
|
430
|
+
}
|
|
431
|
+
try {
|
|
432
|
+
preparedContext = prepareInputContext(text?.trim() || '', attachments, parsedContext.data)
|
|
433
|
+
attachments = preparedContext.attachments
|
|
434
|
+
} catch (err) {
|
|
435
|
+
if (!(err instanceof InputContextError)) throw err
|
|
436
|
+
if (isWellFormedClientMessageId(msg.clientMessageId)) {
|
|
437
|
+
sendInputAck(ws, ctx, {
|
|
438
|
+
sessionId: targetSessionId,
|
|
439
|
+
clientMessageId: msg.clientMessageId,
|
|
440
|
+
contextItemIds: null,
|
|
441
|
+
status: 'rejected',
|
|
442
|
+
delivery: 'not_dispatched',
|
|
443
|
+
}, { reason: err.reason, message: err.message })
|
|
444
|
+
}
|
|
445
|
+
return
|
|
446
|
+
}
|
|
447
|
+
const attachmentError = validateAttachments(attachments)
|
|
448
|
+
if (attachmentError) {
|
|
449
|
+
if (isWellFormedClientMessageId(msg.clientMessageId)) {
|
|
450
|
+
sendInputAck(ws, ctx, {
|
|
451
|
+
sessionId: targetSessionId,
|
|
452
|
+
clientMessageId: msg.clientMessageId,
|
|
453
|
+
contextItemIds: null,
|
|
454
|
+
status: 'rejected',
|
|
455
|
+
delivery: 'not_dispatched',
|
|
456
|
+
}, { reason: 'invalid_context_attachment', message: `Invalid context attachment: ${attachmentError}` })
|
|
457
|
+
}
|
|
458
|
+
return
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
if ((!text || !text.trim()) && !attachments?.length && !msg.context?.items?.length) return
|
|
226
463
|
const trimmed = text?.trim() || ''
|
|
227
464
|
const attCount = attachments?.length || 0
|
|
465
|
+
const directAttachmentCount = attachmentsWithoutContext?.length || 0
|
|
466
|
+
const contextCount = preparedContext?.context.items.length || 0
|
|
228
467
|
log.debug(`Message from ${client.id} to session ${targetSessionId}: "${trimmed.slice(0, 80)}"${attCount ? ` (+${attCount} attachment(s))` : ''}`)
|
|
229
468
|
|
|
230
469
|
// #4733 — wire-arrival fingerprint. Logs the byte/codepoint/whitespace
|
|
@@ -285,6 +524,9 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
285
524
|
|
|
286
525
|
if (ctx.sessions.sessionManager.isBudgetPaused(targetSessionId)) {
|
|
287
526
|
sendSessionError(ws, ctx, 'Session is paused — cost budget exceeded. Use "Resume Budget" to continue.')
|
|
527
|
+
if (supportsInputAck) {
|
|
528
|
+
sendInputRejectionAck(ws, ctx, targetSessionId, msg, 'budget_paused', 'The input was not dispatched because the session budget is paused.')
|
|
529
|
+
}
|
|
288
530
|
return
|
|
289
531
|
}
|
|
290
532
|
|
|
@@ -293,10 +535,69 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
293
535
|
const primaryClientId = ctx.transport.getPrimary(targetSessionId)
|
|
294
536
|
if (primaryClientId && primaryClientId !== client.id) {
|
|
295
537
|
ctx.transport.send(ws, buildInputConflictError(targetSessionId, msg.clientMessageId))
|
|
538
|
+
if (supportsInputAck) {
|
|
539
|
+
sendInputRejectionAck(ws, ctx, targetSessionId, msg, 'input_conflict', INPUT_CONFLICT_CROSS_DEVICE_MESSAGE)
|
|
540
|
+
}
|
|
296
541
|
return
|
|
297
542
|
}
|
|
298
543
|
}
|
|
299
544
|
|
|
545
|
+
const reservation = supportsInputAck
|
|
546
|
+
? reserveInputRequest(ctx, targetSessionId, msg)
|
|
547
|
+
: { record: null, duplicate: false }
|
|
548
|
+
if (reservation.mismatch) {
|
|
549
|
+
sendInputAck(ws, ctx, {
|
|
550
|
+
...reservation.record,
|
|
551
|
+
status: 'rejected',
|
|
552
|
+
delivery: 'not_dispatched',
|
|
553
|
+
}, {
|
|
554
|
+
reason: 'payload_mismatch',
|
|
555
|
+
message: 'This clientMessageId was already used for a different input payload. Generate a new id.',
|
|
556
|
+
})
|
|
557
|
+
return
|
|
558
|
+
}
|
|
559
|
+
if (reservation.expired) {
|
|
560
|
+
sendInputAck(ws, ctx, {
|
|
561
|
+
...reservation.record,
|
|
562
|
+
status: 'expired',
|
|
563
|
+
delivery: 'not_dispatched',
|
|
564
|
+
}, {
|
|
565
|
+
reason: 'dedup_expired',
|
|
566
|
+
message: 'The server retention window expired for this input id; delivery is uncertain and it was not submitted again.',
|
|
567
|
+
})
|
|
568
|
+
return
|
|
569
|
+
}
|
|
570
|
+
if (reservation.duplicate) {
|
|
571
|
+
const accepted = reservation.record.delivery === 'dispatch_started' ||
|
|
572
|
+
reservation.record.delivery === 'queued' ||
|
|
573
|
+
reservation.record.delivery === 'evaluation_held'
|
|
574
|
+
if (accepted) {
|
|
575
|
+
sendInputAck(ws, ctx, { ...reservation.record, status: 'duplicate' })
|
|
576
|
+
} else {
|
|
577
|
+
sendInputAck(ws, ctx, reservation.record, {
|
|
578
|
+
status: 'uncertain',
|
|
579
|
+
delivery: 'unknown',
|
|
580
|
+
reason: 'delivery_uncertain',
|
|
581
|
+
message: 'This input id is still retained, but provider admission has not been confirmed. It was not submitted again.',
|
|
582
|
+
})
|
|
583
|
+
}
|
|
584
|
+
return
|
|
585
|
+
}
|
|
586
|
+
if (reservation.capacity) {
|
|
587
|
+
sendInputAck(ws, ctx, {
|
|
588
|
+
sessionId: targetSessionId,
|
|
589
|
+
clientMessageId: msg.clientMessageId,
|
|
590
|
+
contextItemIds: null,
|
|
591
|
+
status: 'rejected',
|
|
592
|
+
delivery: 'not_dispatched',
|
|
593
|
+
}, {
|
|
594
|
+
reason: 'dedup_capacity',
|
|
595
|
+
message: 'The input deduplication window is full; wait for retained entries to expire before submitting.',
|
|
596
|
+
})
|
|
597
|
+
return
|
|
598
|
+
}
|
|
599
|
+
const inputRecord = reservation.record
|
|
600
|
+
|
|
300
601
|
// #3666 — hoist the per-session evaluator-await lock check above the
|
|
301
602
|
// routing logic so trivial-skip-path messages also reject during an
|
|
302
603
|
// in-flight evaluator round-trip. Without this, a fast trivial draft
|
|
@@ -313,6 +614,15 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
313
614
|
msg.clientMessageId,
|
|
314
615
|
'Session is already evaluating a previous draft. Wait for it to finish or interrupt first.',
|
|
315
616
|
))
|
|
617
|
+
if (inputRecord) {
|
|
618
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
619
|
+
status: 'rejected',
|
|
620
|
+
delivery: 'not_dispatched',
|
|
621
|
+
reason: 'input_conflict',
|
|
622
|
+
message: 'Session is already evaluating a previous draft. The input was not dispatched.',
|
|
623
|
+
})
|
|
624
|
+
}
|
|
625
|
+
releaseInputRequest(ctx, inputRecord)
|
|
316
626
|
return
|
|
317
627
|
}
|
|
318
628
|
|
|
@@ -323,6 +633,11 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
323
633
|
cwd: entry.cwd,
|
|
324
634
|
description: trimmed.slice(0, 100),
|
|
325
635
|
messageCount: ctx.sessions.sessionManager.getHistoryCount(targetSessionId),
|
|
636
|
+
// #6766: capture the fork boundary (last assistant transcript UUID of the
|
|
637
|
+
// turn that just ended) so restoring this pre-turn checkpoint can truncate
|
|
638
|
+
// the conversation to here. Undefined on providers that don't track it.
|
|
639
|
+
boundaryMessageId: entry.session.lastMessageUuid,
|
|
640
|
+
isAuthorized: authorizedFor(ctx, client),
|
|
326
641
|
}).catch((err) => log.warn(`Auto-checkpoint failed: ${err.message}`))
|
|
327
642
|
}
|
|
328
643
|
// Adopt the sender's clientMessageId if present and well-formed; otherwise
|
|
@@ -356,7 +671,11 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
356
671
|
function recordHistoryEntry(text) {
|
|
357
672
|
if (_historyRecorded) return
|
|
358
673
|
_historyRecorded = true
|
|
359
|
-
ctx.sessions.sessionManager.recordUserInput(
|
|
674
|
+
ctx.sessions.sessionManager.recordUserInput(
|
|
675
|
+
targetSessionId,
|
|
676
|
+
buildHistoryText(text, directAttachmentCount, contextCount),
|
|
677
|
+
messageId,
|
|
678
|
+
)
|
|
360
679
|
ctx.sessions.sessionManager.touchActivity(targetSessionId)
|
|
361
680
|
}
|
|
362
681
|
|
|
@@ -377,11 +696,47 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
377
696
|
// (the toggle) is also per-session — the skip pattern shouldn't be the
|
|
378
697
|
// odd one out forced through global config.
|
|
379
698
|
let textToSend = trimmed
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
699
|
+
// The skip decision is awaited (a configured pattern is matched off the event
|
|
700
|
+
// loop), so the per-session lock is taken BEFORE that await: otherwise a second
|
|
701
|
+
// input arriving in the gap passes the entry check above and either overtakes
|
|
702
|
+
// this one or reaches the evaluator concurrently. The placeholder is replaced by
|
|
703
|
+
// the evaluator promise below, or released on the skip / cap / error paths.
|
|
704
|
+
let skipLock = null
|
|
705
|
+
let skipDecision = true
|
|
706
|
+
// The default (synchronous) rules decide first: a trivial ack never waits and
|
|
707
|
+
// never takes the lock. Only a draft that a configured pattern must still judge,
|
|
708
|
+
// or that the evaluator will run on, holds it.
|
|
709
|
+
if (entry.session.promptEvaluator === true && trimmed.length > 0 && !shouldSkipEvaluator(trimmed)) {
|
|
710
|
+
skipLock = Promise.resolve()
|
|
711
|
+
_pendingAwaits.set(targetSessionId, skipLock)
|
|
712
|
+
try {
|
|
713
|
+
skipDecision = await shouldSkipEvaluatorAsync(trimmed, _resolveSkipConfig(entry, ctx), undefined, String(client.id))
|
|
714
|
+
} catch (err) {
|
|
715
|
+
log.warn(`Skip-pattern check failed: ${err?.message || err}; evaluating the draft`)
|
|
716
|
+
skipDecision = false
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
const releaseSkipLock = () => {
|
|
720
|
+
if (skipLock && _pendingAwaits.get(targetSessionId) === skipLock) _pendingAwaits.delete(targetSessionId)
|
|
721
|
+
}
|
|
722
|
+
// The skip decision was a wait: the connection may have lost its credential
|
|
723
|
+
// meanwhile. Nothing below (skip dispatch, cap force-forward, evaluator) runs
|
|
724
|
+
// for it.
|
|
725
|
+
if (skipLock) {
|
|
726
|
+
let authorized = false
|
|
727
|
+
try {
|
|
728
|
+
authorized = stillAuthorized(authorizedFor(ctx, client))
|
|
729
|
+
} finally {
|
|
730
|
+
// Released on a refusal AND if the check itself throws.
|
|
731
|
+
if (!authorized) {
|
|
732
|
+
releaseSkipLock()
|
|
733
|
+
releaseInputRequest(ctx, inputRecord)
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
if (!authorized) return
|
|
737
|
+
}
|
|
738
|
+
if (skipLock && skipDecision) releaseSkipLock()
|
|
739
|
+
if (skipLock && !skipDecision) {
|
|
385
740
|
const counters = _getEvaluatorIterations(ctx)
|
|
386
741
|
const currentIteration = (counters.get(targetSessionId) || 0) + 1
|
|
387
742
|
|
|
@@ -390,12 +745,14 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
390
745
|
// session isn't permanently locked out of evaluator gating.
|
|
391
746
|
log.warn(`Evaluator iteration cap hit for session ${targetSessionId}; force-forwarding draft`)
|
|
392
747
|
counters.delete(targetSessionId)
|
|
748
|
+
releaseSkipLock()
|
|
393
749
|
} else {
|
|
394
750
|
// #3636 — per-session serialization. Reject (don't queue) a second
|
|
395
751
|
// concurrent draft for the same session while an evaluator round-trip
|
|
396
|
-
// is in flight. The
|
|
397
|
-
//
|
|
398
|
-
//
|
|
752
|
+
// is in flight. The check at function entry (#3666) rejects messages
|
|
753
|
+
// arriving while the lock is held, and the lock is held from before the
|
|
754
|
+
// skip decision is awaited, so it is ours here: we replace the
|
|
755
|
+
// placeholder with the evaluator promise.
|
|
399
756
|
const pending = _pendingAwaits
|
|
400
757
|
|
|
401
758
|
const evaluator = typeof ctx.evaluateDraft === 'function' ? ctx.evaluateDraft : defaultEvaluateDraft
|
|
@@ -422,6 +779,18 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
422
779
|
}
|
|
423
780
|
}
|
|
424
781
|
|
|
782
|
+
// The connection may have ended (credential revoked / expired) while the
|
|
783
|
+
// evaluator was running. Nothing below may dispatch, record or broadcast
|
|
784
|
+
// on its behalf.
|
|
785
|
+
let authorizedAfterEvaluator = false
|
|
786
|
+
try {
|
|
787
|
+
authorizedAfterEvaluator = stillAuthorized(authorizedFor(ctx, client))
|
|
788
|
+
} finally {
|
|
789
|
+
// Released on a refusal AND if the check itself throws.
|
|
790
|
+
if (!authorizedAfterEvaluator) releaseInputRequest(ctx, inputRecord)
|
|
791
|
+
}
|
|
792
|
+
if (!authorizedAfterEvaluator) return
|
|
793
|
+
|
|
425
794
|
// #3636 — re-check input_conflict after the await. State may have
|
|
426
795
|
// flipped during the round-trip (e.g. another path started the
|
|
427
796
|
// session). Without this, the rewritten/forward draft would race
|
|
@@ -430,6 +799,15 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
430
799
|
const primaryClientId = ctx.transport.getPrimary(targetSessionId)
|
|
431
800
|
if (primaryClientId && primaryClientId !== client.id) {
|
|
432
801
|
ctx.transport.send(ws, buildInputConflictError(targetSessionId, msg.clientMessageId))
|
|
802
|
+
if (inputRecord) {
|
|
803
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
804
|
+
status: 'rejected',
|
|
805
|
+
delivery: 'not_dispatched',
|
|
806
|
+
reason: 'input_conflict',
|
|
807
|
+
message: 'Another client took control while the draft was being evaluated. The input was not dispatched.',
|
|
808
|
+
})
|
|
809
|
+
}
|
|
810
|
+
releaseInputRequest(ctx, inputRecord)
|
|
433
811
|
return
|
|
434
812
|
}
|
|
435
813
|
}
|
|
@@ -480,6 +858,12 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
480
858
|
{ type: 'user_input', sessionId: targetSessionId, clientId: client.id, text: trimmed, messageId, timestamp: Date.now() },
|
|
481
859
|
(c) => c.id !== client.id,
|
|
482
860
|
)
|
|
861
|
+
if (inputRecord) {
|
|
862
|
+
inputRecord.status = 'accepted'
|
|
863
|
+
inputRecord.delivery = 'evaluation_held'
|
|
864
|
+
inputRecord.acceptedAt = typeof ctx.now === 'function' ? ctx.now() : Date.now()
|
|
865
|
+
sendInputAck(ws, ctx, inputRecord)
|
|
866
|
+
}
|
|
483
867
|
return
|
|
484
868
|
} else {
|
|
485
869
|
// forward verdict (or unrecognised result) — drop the iteration
|
|
@@ -489,7 +873,7 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
489
873
|
}
|
|
490
874
|
}
|
|
491
875
|
|
|
492
|
-
// #3636:
|
|
876
|
+
// #3636: prepare history for the forward boundary. All earlier
|
|
493
877
|
// rejection paths (input_conflict pre-await, pending-evaluator guard,
|
|
494
878
|
// post-await re-check) returned without recording. The clarify path
|
|
495
879
|
// already recorded above before its own return.
|
|
@@ -497,8 +881,6 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
497
881
|
// rewritten string on the rewrite verdict, the original `trimmed`
|
|
498
882
|
// draft on every other path (forward, skip-heuristic, fail-open,
|
|
499
883
|
// cap-bypass).
|
|
500
|
-
recordHistoryEntry(textToSend)
|
|
501
|
-
|
|
502
884
|
// #5313 (WP-1.3): sendMessage is fire-and-forget. If a provider's
|
|
503
885
|
// sendMessage returns a rejecting promise, an unhandled rejection escapes
|
|
504
886
|
// to process-level unhandledRejection → process.exit(1), crashing EVERY
|
|
@@ -511,7 +893,148 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
511
893
|
// `message_queued` mirror carries the id the sender's optimistic copy uses —
|
|
512
894
|
// letting that client reconcile its queued bubble. Providers that send
|
|
513
895
|
// immediately ignore the extra option.
|
|
514
|
-
|
|
896
|
+
//
|
|
897
|
+
// #8866: a session continued from the archive as a NEW thread owes the model
|
|
898
|
+
// the archived transcript with its first message. It is claimed here, after
|
|
899
|
+
// every rejection path above, merged into the text through the same
|
|
900
|
+
// `prepareInputContext` envelope a client-selected context takes, and kept OUT
|
|
901
|
+
// of `contextCount` (history shows what the user typed) and of the
|
|
902
|
+
// `sendOptions.context` below (that stays "what the user selected"; an adapter
|
|
903
|
+
// that refuses selected context, like BYOK with attachments, is unaffected).
|
|
904
|
+
// It is consumed when the provider ADMITS the input, and also when admission
|
|
905
|
+
// is UNCERTAIN (re-sending the transcript twice is worse than losing it once);
|
|
906
|
+
// a definite rejection or a throw returns it to pending. While a claim is
|
|
907
|
+
// unresolved a second input is REFUSED, so nothing can become the first
|
|
908
|
+
// delivered input without the transcript. The claim is observed through an
|
|
909
|
+
// admission callback passed whenever a seed is claimed, separately from the
|
|
910
|
+
// client-ack bookkeeping, so a client without input acks is covered too.
|
|
911
|
+
const sm = ctx.sessions.sessionManager
|
|
912
|
+
const seedClaim = sm.claimContinuationSeed?.(targetSessionId) ?? null
|
|
913
|
+
if (seedClaim?.busy || seedClaim?.unpersisted) {
|
|
914
|
+
const [reason, message] = seedClaim.busy
|
|
915
|
+
? ['continuation_seed_pending', 'The first message of this continued session is still being delivered. Wait for it to be accepted, then send again.']
|
|
916
|
+
: ['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.']
|
|
917
|
+
// The dashboard restores the draft from a retry-safe rejection but does not
|
|
918
|
+
// render the ack's message, so the refusal is ALSO a session error (the same
|
|
919
|
+
// pairing the budget-paused rejection uses) for the user to read.
|
|
920
|
+
sendSessionError(ws, ctx, message)
|
|
921
|
+
if (inputRecord) {
|
|
922
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
923
|
+
status: 'rejected',
|
|
924
|
+
delivery: 'not_dispatched',
|
|
925
|
+
retrySafe: true,
|
|
926
|
+
reason,
|
|
927
|
+
message,
|
|
928
|
+
})
|
|
929
|
+
releaseInputRequest(ctx, inputRecord)
|
|
930
|
+
}
|
|
931
|
+
return
|
|
932
|
+
}
|
|
933
|
+
let seedSettled = !seedClaim
|
|
934
|
+
const settleSeed = (consumed) => {
|
|
935
|
+
if (seedSettled) return
|
|
936
|
+
seedSettled = true
|
|
937
|
+
sm.settleContinuationSeed?.(targetSessionId, seedClaim.token, consumed)
|
|
938
|
+
}
|
|
939
|
+
const observeSeedAdmission = (admission) => {
|
|
940
|
+
if (seedSettled || !admission || typeof admission !== 'object') return
|
|
941
|
+
if (admission.status === 'rejected' && admission.delivery === 'not_dispatched') settleSeed(false)
|
|
942
|
+
else if (
|
|
943
|
+
(admission.status === 'accepted' && admission.delivery === 'dispatch_started') ||
|
|
944
|
+
(admission.status === 'queued' && admission.delivery === 'queued') ||
|
|
945
|
+
(admission.status === 'uncertain' && admission.delivery === 'unknown')
|
|
946
|
+
) settleSeed(true)
|
|
947
|
+
}
|
|
948
|
+
let dispatchText
|
|
949
|
+
try {
|
|
950
|
+
const dispatchContext = seedClaim
|
|
951
|
+
? { version: 1, items: [seedClaim.item, ...(preparedContext?.context.items || [])] }
|
|
952
|
+
: preparedContext?.context
|
|
953
|
+
dispatchText = dispatchContext
|
|
954
|
+
? prepareInputContext(textToSend, attachmentsWithoutContext, dispatchContext).text
|
|
955
|
+
: textToSend
|
|
956
|
+
} catch (err) {
|
|
957
|
+
settleSeed(false)
|
|
958
|
+
throw err
|
|
959
|
+
}
|
|
960
|
+
let sendResult
|
|
961
|
+
let admissionFinal = false
|
|
962
|
+
let forwardedEffectsCommitted = false
|
|
963
|
+
const commitForwardedEffects = () => {
|
|
964
|
+
if (forwardedEffectsCommitted) return
|
|
965
|
+
forwardedEffectsCommitted = true
|
|
966
|
+
recordHistoryEntry(textToSend)
|
|
967
|
+
ctx.transport.updatePrimary(targetSessionId, client.id)
|
|
968
|
+
ctx.transport.broadcast(
|
|
969
|
+
{ type: 'user_input', sessionId: targetSessionId, clientId: client.id, text: trimmed, messageId, timestamp: Date.now() },
|
|
970
|
+
(c) => c.id !== client.id
|
|
971
|
+
)
|
|
972
|
+
}
|
|
973
|
+
const onInputAdmission = (admission) => {
|
|
974
|
+
observeSeedAdmission(admission)
|
|
975
|
+
if (!inputRecord || admissionFinal || !admission || typeof admission !== 'object') return
|
|
976
|
+
const status = admission.status
|
|
977
|
+
const delivery = admission.delivery
|
|
978
|
+
const accepted = (status === 'accepted' && delivery === 'dispatch_started') ||
|
|
979
|
+
(status === 'queued' && delivery === 'queued')
|
|
980
|
+
const rejected = status === 'rejected' && delivery === 'not_dispatched'
|
|
981
|
+
const uncertain = status === 'uncertain' && delivery === 'unknown'
|
|
982
|
+
if (!accepted && !rejected && !uncertain) return
|
|
983
|
+
|
|
984
|
+
admissionFinal = true
|
|
985
|
+
inputRecord.status = status
|
|
986
|
+
inputRecord.delivery = delivery
|
|
987
|
+
if (accepted) {
|
|
988
|
+
inputRecord.acceptedAt = typeof ctx.now === 'function' ? ctx.now() : Date.now()
|
|
989
|
+
sendInputAck(ws, ctx, inputRecord)
|
|
990
|
+
commitForwardedEffects()
|
|
991
|
+
return
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
if (uncertain) {
|
|
995
|
+
// A lost native acknowledgement is terminal uncertainty, not definite
|
|
996
|
+
// dispatch. Retain the reservation so the same id cannot be retried.
|
|
997
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
998
|
+
retrySafe: false,
|
|
999
|
+
reason: typeof admission.reason === 'string' ? admission.reason : 'provider_admission_uncertain',
|
|
1000
|
+
message: typeof admission.message === 'string'
|
|
1001
|
+
? admission.message
|
|
1002
|
+
: 'Provider admission is uncertain; inspect the original session before explicitly resending.',
|
|
1003
|
+
})
|
|
1004
|
+
return
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
1008
|
+
status: 'rejected',
|
|
1009
|
+
delivery: 'not_dispatched',
|
|
1010
|
+
retrySafe: admission.retrySafe === true,
|
|
1011
|
+
reason: typeof admission.reason === 'string' ? admission.reason : 'provider_rejected',
|
|
1012
|
+
message: typeof admission.message === 'string'
|
|
1013
|
+
? admission.message
|
|
1014
|
+
: 'The provider rejected the input before admission.',
|
|
1015
|
+
})
|
|
1016
|
+
releaseInputRequest(ctx, inputRecord)
|
|
1017
|
+
}
|
|
1018
|
+
try {
|
|
1019
|
+
sendResult = entry.session.sendMessage(dispatchText, attachments, {
|
|
1020
|
+
isVoice: !!msg.isVoice,
|
|
1021
|
+
clientMessageId: messageId,
|
|
1022
|
+
...(inputRecord || seedClaim ? { onInputAdmission } : {}),
|
|
1023
|
+
...(preparedContext?.context ? { context: preparedContext.context } : {}),
|
|
1024
|
+
isAuthorized: authorizedFor(ctx, client),
|
|
1025
|
+
})
|
|
1026
|
+
} catch (err) {
|
|
1027
|
+
settleSeed(false)
|
|
1028
|
+
if (inputRecord && !admissionFinal) {
|
|
1029
|
+
inputRecord.status = 'uncertain'
|
|
1030
|
+
inputRecord.delivery = 'unknown'
|
|
1031
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
1032
|
+
reason: 'dispatch_threw',
|
|
1033
|
+
message: 'Provider dispatch failed synchronously; acceptance is uncertain and the server will not retry automatically.',
|
|
1034
|
+
})
|
|
1035
|
+
}
|
|
1036
|
+
throw err
|
|
1037
|
+
}
|
|
515
1038
|
if (sendResult && typeof sendResult.catch === 'function') {
|
|
516
1039
|
sendResult.catch((err) => {
|
|
517
1040
|
const message = err?.message || String(err)
|
|
@@ -519,16 +1042,33 @@ async function handleInput(ws, client, msg, ctx) {
|
|
|
519
1042
|
})
|
|
520
1043
|
}
|
|
521
1044
|
|
|
522
|
-
|
|
1045
|
+
if (inputRecord && !admissionFinal) {
|
|
1046
|
+
inputRecord.status = 'uncertain'
|
|
1047
|
+
inputRecord.delivery = 'unknown'
|
|
1048
|
+
sendInputAck(ws, ctx, inputRecord, {
|
|
1049
|
+
reason: 'admission_pending',
|
|
1050
|
+
message: 'The provider has not confirmed admission yet. The server will not retry automatically.',
|
|
1051
|
+
})
|
|
1052
|
+
}
|
|
523
1053
|
|
|
524
|
-
//
|
|
525
|
-
//
|
|
526
|
-
//
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
1054
|
+
// Older clients have no correlated admission contract. Preserve their
|
|
1055
|
+
// established fire-and-forget history, primary, and peer-echo behavior.
|
|
1056
|
+
//
|
|
1057
|
+
if (!inputRecord) commitForwardedEffects()
|
|
1058
|
+
|
|
1059
|
+
// #8866: a claimed seed whose provider reported no admission by the time
|
|
1060
|
+
// sendMessage returned. Every in-tree provider reports it (base/sdk/cli/
|
|
1061
|
+
// claude-tui/jsonl-subprocess incl. codex-exec and gemini, byok, acp, codex
|
|
1062
|
+
// app-server); one that does not is treated as having taken the input once its
|
|
1063
|
+
// call settles (a rejected call included: no signal means uncertain, and
|
|
1064
|
+
// uncertain counts as consumed). A synchronous return settles it now.
|
|
1065
|
+
if (!seedSettled) {
|
|
1066
|
+
if (sendResult && typeof sendResult.then === 'function') {
|
|
1067
|
+
sendResult.then(() => settleSeed(true), () => settleSeed(true))
|
|
1068
|
+
} else {
|
|
1069
|
+
settleSeed(true)
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
532
1072
|
}
|
|
533
1073
|
|
|
534
1074
|
function handleInterrupt(ws, client, msg, ctx) {
|
|
@@ -536,6 +1076,11 @@ function handleInterrupt(ws, client, msg, ctx) {
|
|
|
536
1076
|
const entry = resolveSession(ctx, msg, client)
|
|
537
1077
|
if (entry) {
|
|
538
1078
|
log.info(`Interrupt from ${client.id} to session ${interruptSessionId}`)
|
|
1079
|
+
// #8301: a user Stop ends daemon wakes for this session until they next type.
|
|
1080
|
+
ctx.sessions.sessionManager?.recordUserInterrupt?.(interruptSessionId)
|
|
1081
|
+
// #8374/#8430: record that the USER stopped this turn, before the abort
|
|
1082
|
+
// resolves any open prompt (a failed turn aborts the same controller).
|
|
1083
|
+
entry.session.markUserStopInFlight?.()
|
|
539
1084
|
entry.session.interrupt()
|
|
540
1085
|
return
|
|
541
1086
|
}
|
|
@@ -753,7 +1298,13 @@ function handleRegisterPushToken(ws, client, msg, ctx) {
|
|
|
753
1298
|
// is actually pruned from the registry. Without ref-counting, the
|
|
754
1299
|
// first disconnect would strip the token from the second client's
|
|
755
1300
|
// active session.
|
|
756
|
-
|
|
1301
|
+
// A session-scoped connection registers a destination for ITS session's
|
|
1302
|
+
// notifications only; the sink delivers nothing else to it.
|
|
1303
|
+
const ok = ctx.services.pushManager.registerToken(
|
|
1304
|
+
msg.token,
|
|
1305
|
+
client.id,
|
|
1306
|
+
isBoundClient(client) ? { sessionId: client.boundSessionId } : undefined,
|
|
1307
|
+
)
|
|
757
1308
|
if (!ok) {
|
|
758
1309
|
ctx.transport.send(ws, {
|
|
759
1310
|
type: 'push_token_error',
|
|
@@ -871,6 +1422,33 @@ function handleNotificationPrefsSet(ws, client, msg, ctx) {
|
|
|
871
1422
|
}
|
|
872
1423
|
}
|
|
873
1424
|
|
|
1425
|
+
/**
|
|
1426
|
+
* #8470: the wire code of the error frame that tells the ANSWERING client its
|
|
1427
|
+
* `user_question_response` reached nothing. Without it the answer is dropped
|
|
1428
|
+
* silently, and both clients have already marked the card answered on send.
|
|
1429
|
+
*/
|
|
1430
|
+
const QUESTION_NOT_DELIVERED_CODE = 'QUESTION_NOT_DELIVERED'
|
|
1431
|
+
|
|
1432
|
+
/**
|
|
1433
|
+
* Tell the answering client (only) that its answer to `msg.toolUseId` was not
|
|
1434
|
+
* delivered. Reuses the `error` envelope (a coded frame, `toolUseId` and
|
|
1435
|
+
* `sessionId` ride along as the envelope's passthrough fields) rather than a new
|
|
1436
|
+
* wire type: the clients already surface an error frame, and key the card off the
|
|
1437
|
+
* `toolUseId`. The wording covers every cause without claiming one: the question
|
|
1438
|
+
* was already answered, timed out, or replaced by a newer one.
|
|
1439
|
+
*/
|
|
1440
|
+
function sendQuestionNotDelivered(ws, msg, sessionId, ctx) {
|
|
1441
|
+
sendError(
|
|
1442
|
+
ws,
|
|
1443
|
+
null,
|
|
1444
|
+
QUESTION_NOT_DELIVERED_CODE,
|
|
1445
|
+
'Your answer was not delivered: that question is no longer waiting (it was already answered, timed out, or replaced by a newer question).',
|
|
1446
|
+
// `fatal: false`: the session is fine, one answer was lost (a warning, not an error toast).
|
|
1447
|
+
{ toolUseId: msg.toolUseId, fatal: false, ...(sessionId ? { sessionId } : {}) },
|
|
1448
|
+
ctx,
|
|
1449
|
+
)
|
|
1450
|
+
}
|
|
1451
|
+
|
|
874
1452
|
function handleUserQuestionResponse(ws, client, msg, ctx) {
|
|
875
1453
|
// #5753 — route by toolUseId when one is supplied. `_registerQuestionRoute`
|
|
876
1454
|
// maps every question that has a toolUseId at DISPATCH time (before the
|
|
@@ -894,14 +1472,28 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
|
|
|
894
1472
|
// (legacy single-session mode / clients that don't send one), where there is
|
|
895
1473
|
// a single question in flight and no cross-question mis-route risk.
|
|
896
1474
|
let questionSessionId
|
|
1475
|
+
// #8470: false when the route is gone and the owner comes from the map's memory
|
|
1476
|
+
// of recently removed routes. Such an answer reaches nothing, but the sender is
|
|
1477
|
+
// still told, and only after the SAME entitlement checks as a live route.
|
|
1478
|
+
let routeLive = true
|
|
1479
|
+
let recentAnswerDigest
|
|
897
1480
|
if (typeof msg.toolUseId === 'string') {
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
1481
|
+
const routes = ctx.permissions.questionSessionMap
|
|
1482
|
+
if (routes.has(msg.toolUseId)) {
|
|
1483
|
+
questionSessionId = routes.get(msg.toolUseId)
|
|
1484
|
+
} else {
|
|
1485
|
+
// An id nobody routed (never existed, or older than the memory) is silent:
|
|
1486
|
+
// answering it would tell a client which ids exist. And NOT logged either: a
|
|
1487
|
+
// log line goes out as a `log_entry` to the sender's own session's viewers
|
|
1488
|
+
// (ws-server fans logs out), and a line that appears only for a resolved or
|
|
1489
|
+
// unknown id is the oracle by another route. The log is written below, after
|
|
1490
|
+
// the entitlement checks, to the OWNING session.
|
|
1491
|
+
const recent = routes.recentOwner?.(msg.toolUseId)
|
|
1492
|
+
if (!recent) return
|
|
1493
|
+
questionSessionId = recent.sessionId
|
|
1494
|
+
recentAnswerDigest = recent.answerDigest
|
|
1495
|
+
routeLive = false
|
|
903
1496
|
}
|
|
904
|
-
questionSessionId = ctx.permissions.questionSessionMap.get(msg.toolUseId)
|
|
905
1497
|
} else {
|
|
906
1498
|
questionSessionId = client.activeSessionId
|
|
907
1499
|
}
|
|
@@ -925,6 +1517,19 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
|
|
|
925
1517
|
if (!isSessionViewer(client, questionSessionId)) return
|
|
926
1518
|
}
|
|
927
1519
|
|
|
1520
|
+
if (!routeLive) {
|
|
1521
|
+
sessionLogger(questionSessionId || undefined).info(
|
|
1522
|
+
`user_question_response dropped: stale toolUseId=${msg.toolUseId} (question already resolved or its session is gone)`,
|
|
1523
|
+
)
|
|
1524
|
+
// #8470: the sender marked its card answered when it sent; say it was not,
|
|
1525
|
+
// unless the answer that landed IS this one (a duplicate or a second tab that
|
|
1526
|
+
// chose the same thing): then the card is right and retracting it would be
|
|
1527
|
+
// the lie.
|
|
1528
|
+
if (recentAnswerDigest !== undefined && recentAnswerDigest === answerDigest(msg)) return
|
|
1529
|
+
sendQuestionNotDelivered(ws, msg, questionSessionId || undefined, ctx)
|
|
1530
|
+
return
|
|
1531
|
+
}
|
|
1532
|
+
|
|
928
1533
|
if (msg.toolUseId) ctx.permissions.questionSessionMap.delete(msg.toolUseId)
|
|
929
1534
|
|
|
930
1535
|
const entry = ctx.sessions.sessionManager.getSession(questionSessionId)
|
|
@@ -955,18 +1560,44 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
|
|
|
955
1560
|
const qlog = sessionLogger(questionSessionId)
|
|
956
1561
|
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}`)
|
|
957
1562
|
// #4668: forward msg.toolUseId so claude-tui-session can route the
|
|
958
|
-
// answer to the right pending entry in its Map.
|
|
959
|
-
//
|
|
960
|
-
//
|
|
961
|
-
// a safe addition. ByokSession's respondToQuestion forwards to
|
|
962
|
-
// _permissions.respondToQuestion which similarly ignores trailing
|
|
963
|
-
// args it doesn't read.
|
|
1563
|
+
// answer to the right pending entry in its Map. #8460: SDK, BYOK and
|
|
1564
|
+
// codex forward it to the permission manager, which refuses an answer
|
|
1565
|
+
// whose id is not the pending question's. cli-session ignores it.
|
|
964
1566
|
// #4651: forward msg.freeformText as a final opts object — claude-tui-
|
|
965
1567
|
// session uses it to drive the two-stage Other-path write (digit →
|
|
966
1568
|
// text-input prompt → freeform text + Enter). Other providers ignore
|
|
967
1569
|
// the trailing arg.
|
|
968
1570
|
const opts = hasFreeform ? { freeformText: msg.freeformText } : undefined
|
|
969
|
-
entry.session.respondToQuestion(msg.answer, msg.answers, msg.toolUseId, opts)
|
|
1571
|
+
const delivered = entry.session.respondToQuestion(msg.answer, msg.answers, msg.toolUseId, opts)
|
|
1572
|
+
// #8362: the one place every provider's answer passes through. cli and tui
|
|
1573
|
+
// deliver the answer before the tool's result event arrives, so without this
|
|
1574
|
+
// record a restart in that window labels an answered question interrupted.
|
|
1575
|
+
// Only an actionable answer counts (the TUI driver drops an empty one without
|
|
1576
|
+
// an answers map); anything else stays unanswered and is swept as before.
|
|
1577
|
+
// "Accepted" means this handler accepted the answer, NOT that the provider
|
|
1578
|
+
// delivered it: apart from the #8460 refusal below, which returns `false`,
|
|
1579
|
+
// respondToQuestion reports nothing, and a provider can still silently
|
|
1580
|
+
// drop the answer -- the claude-tui form driver with no pending entry or no
|
|
1581
|
+
// terminal, its multi-select refuse branch, the CLI with `_waitingForAnswer`
|
|
1582
|
+
// false, a permission manager with nothing pending (SDK / BYOK). That is
|
|
1583
|
+
// acceptable because such a drop is either a repeat of an answer already
|
|
1584
|
+
// delivered, or follows (or, for the multi-select refuse branch, is) a turn
|
|
1585
|
+
// teardown that has already recorded a `tool_result` for the question's
|
|
1586
|
+
// tool, synthetic or the provider's own error result, so marking it
|
|
1587
|
+
// answered hides no real interrupted state.
|
|
1588
|
+
const hasAnswers = msg.answers && typeof msg.answers === 'object' && Object.keys(msg.answers).length > 0
|
|
1589
|
+
// #8460: the one drop the provider REPORTS -- an answer the permission manager
|
|
1590
|
+
// (SDK / BYOK / codex) refused because its toolUseId is not the pending
|
|
1591
|
+
// question's -- returns `false`. That answer was for a question that is no
|
|
1592
|
+
// longer the one being asked, so it must not mark anything answered.
|
|
1593
|
+
if (delivered === false) {
|
|
1594
|
+
// #8470: and the sender must be told, or its card keeps reading answered.
|
|
1595
|
+
sendQuestionNotDelivered(ws, msg, questionSessionId || undefined, ctx)
|
|
1596
|
+
} else if (msg.answer.length > 0 || hasAnswers) {
|
|
1597
|
+
ctx.sessions.sessionManager.recordQuestionAnswered?.(questionSessionId, msg.toolUseId)
|
|
1598
|
+
// #8470: remember WHAT landed, so a duplicate of it is not called lost.
|
|
1599
|
+
if (typeof msg.toolUseId === 'string') ctx.permissions.questionSessionMap.noteAnswered?.(msg.toolUseId, answerDigest(msg))
|
|
1600
|
+
}
|
|
970
1601
|
}
|
|
971
1602
|
}
|
|
972
1603
|
|
|
@@ -1031,6 +1662,16 @@ function handleTerminalInput(ws, client, msg, ctx) {
|
|
|
1031
1662
|
))
|
|
1032
1663
|
return
|
|
1033
1664
|
}
|
|
1665
|
+
// #8301: a human submitting a line in the terminal pane is the same intent as a
|
|
1666
|
+
// typed chat input (a TUI user who Stops and keeps working in the pane would
|
|
1667
|
+
// otherwise have wakes refused forever). Only a submission counts — a bare
|
|
1668
|
+
// keystroke stream without a newline is not "I want the agent to work" — and
|
|
1669
|
+
// only after the primary/viewer/claim checks above, so a refused observer's
|
|
1670
|
+
// keystroke does not. The daemon's own PTY wake never comes through this
|
|
1671
|
+
// handler (it calls `writeTerminalInput` directly).
|
|
1672
|
+
if (msg.data.includes('\r') || msg.data.includes('\n')) {
|
|
1673
|
+
ctx.sessions.sessionManager?.recordUserIntent?.(sid)
|
|
1674
|
+
}
|
|
1034
1675
|
entry.session.writeTerminalInput(msg.data)
|
|
1035
1676
|
}
|
|
1036
1677
|
|