@chroxy/server 0.11.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.
Files changed (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -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._pendingEvaluatorAwaits) ctx._pendingEvaluatorAwaits = new Map()
55
- return ctx._pendingEvaluatorAwaits
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
- return stripped
71
- ? `${stripped} [${attCount} file(s) attached]`
72
- : `[${attCount} file(s) attached]`
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 shouldSkipEvaluator.
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
- // shouldSkipEvaluator only reads `config.promptEvaluatorSkipPattern` (verified
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
- if ((!text || !text.trim()) && !attachments?.length) return
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
 
@@ -327,6 +637,7 @@ async function handleInput(ws, client, msg, ctx) {
327
637
  // turn that just ended) so restoring this pre-turn checkpoint can truncate
328
638
  // the conversation to here. Undefined on providers that don't track it.
329
639
  boundaryMessageId: entry.session.lastMessageUuid,
640
+ isAuthorized: authorizedFor(ctx, client),
330
641
  }).catch((err) => log.warn(`Auto-checkpoint failed: ${err.message}`))
331
642
  }
332
643
  // Adopt the sender's clientMessageId if present and well-formed; otherwise
@@ -360,7 +671,11 @@ async function handleInput(ws, client, msg, ctx) {
360
671
  function recordHistoryEntry(text) {
361
672
  if (_historyRecorded) return
362
673
  _historyRecorded = true
363
- ctx.sessions.sessionManager.recordUserInput(targetSessionId, buildHistoryText(text, attCount), messageId)
674
+ ctx.sessions.sessionManager.recordUserInput(
675
+ targetSessionId,
676
+ buildHistoryText(text, directAttachmentCount, contextCount),
677
+ messageId,
678
+ )
364
679
  ctx.sessions.sessionManager.touchActivity(targetSessionId)
365
680
  }
366
681
 
@@ -381,11 +696,47 @@ async function handleInput(ws, client, msg, ctx) {
381
696
  // (the toggle) is also per-session — the skip pattern shouldn't be the
382
697
  // odd one out forced through global config.
383
698
  let textToSend = trimmed
384
- if (
385
- entry.session.promptEvaluator === true
386
- && trimmed.length > 0
387
- && !shouldSkipEvaluator(trimmed, _resolveSkipConfig(entry, ctx))
388
- ) {
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) {
389
740
  const counters = _getEvaluatorIterations(ctx)
390
741
  const currentIteration = (counters.get(targetSessionId) || 0) + 1
391
742
 
@@ -394,12 +745,14 @@ async function handleInput(ws, client, msg, ctx) {
394
745
  // session isn't permanently locked out of evaluator gating.
395
746
  log.warn(`Evaluator iteration cap hit for session ${targetSessionId}; force-forwarding draft`)
396
747
  counters.delete(targetSessionId)
748
+ releaseSkipLock()
397
749
  } else {
398
750
  // #3636 — per-session serialization. Reject (don't queue) a second
399
751
  // concurrent draft for the same session while an evaluator round-trip
400
- // is in flight. The hoisted check at function entry (#3666) already
401
- // rejects messages arriving during an in-flight await, so by the time
402
- // we reach here the lock is guaranteed empty — we just take it.
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.
403
756
  const pending = _pendingAwaits
404
757
 
405
758
  const evaluator = typeof ctx.evaluateDraft === 'function' ? ctx.evaluateDraft : defaultEvaluateDraft
@@ -426,6 +779,18 @@ async function handleInput(ws, client, msg, ctx) {
426
779
  }
427
780
  }
428
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
+
429
794
  // #3636 — re-check input_conflict after the await. State may have
430
795
  // flipped during the round-trip (e.g. another path started the
431
796
  // session). Without this, the rewritten/forward draft would race
@@ -434,6 +799,15 @@ async function handleInput(ws, client, msg, ctx) {
434
799
  const primaryClientId = ctx.transport.getPrimary(targetSessionId)
435
800
  if (primaryClientId && primaryClientId !== client.id) {
436
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)
437
811
  return
438
812
  }
439
813
  }
@@ -484,6 +858,12 @@ async function handleInput(ws, client, msg, ctx) {
484
858
  { type: 'user_input', sessionId: targetSessionId, clientId: client.id, text: trimmed, messageId, timestamp: Date.now() },
485
859
  (c) => c.id !== client.id,
486
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
+ }
487
867
  return
488
868
  } else {
489
869
  // forward verdict (or unrecognised result) — drop the iteration
@@ -493,7 +873,7 @@ async function handleInput(ws, client, msg, ctx) {
493
873
  }
494
874
  }
495
875
 
496
- // #3636: record history at the forward boundary. All earlier
876
+ // #3636: prepare history for the forward boundary. All earlier
497
877
  // rejection paths (input_conflict pre-await, pending-evaluator guard,
498
878
  // post-await re-check) returned without recording. The clarify path
499
879
  // already recorded above before its own return.
@@ -501,8 +881,6 @@ async function handleInput(ws, client, msg, ctx) {
501
881
  // rewritten string on the rewrite verdict, the original `trimmed`
502
882
  // draft on every other path (forward, skip-heuristic, fail-open,
503
883
  // cap-bypass).
504
- recordHistoryEntry(textToSend)
505
-
506
884
  // #5313 (WP-1.3): sendMessage is fire-and-forget. If a provider's
507
885
  // sendMessage returns a rejecting promise, an unhandled rejection escapes
508
886
  // to process-level unhandledRejection → process.exit(1), crashing EVERY
@@ -515,7 +893,148 @@ async function handleInput(ws, client, msg, ctx) {
515
893
  // `message_queued` mirror carries the id the sender's optimistic copy uses —
516
894
  // letting that client reconcile its queued bubble. Providers that send
517
895
  // immediately ignore the extra option.
518
- const sendResult = entry.session.sendMessage(textToSend, attachments, { isVoice: !!msg.isVoice, clientMessageId: messageId })
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
+ }
519
1038
  if (sendResult && typeof sendResult.catch === 'function') {
520
1039
  sendResult.catch((err) => {
521
1040
  const message = err?.message || String(err)
@@ -523,16 +1042,33 @@ async function handleInput(ws, client, msg, ctx) {
523
1042
  })
524
1043
  }
525
1044
 
526
- ctx.transport.updatePrimary(targetSessionId, client.id)
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
+ }
527
1053
 
528
- // Echo user_input to other clients so they see what was sent (#1119).
529
- // The echo carries `trimmed` (the user's original text) so paired
530
- // clients can dedup their optimistic copy of what the user typed —
531
- // the rewritten text is signalled separately via evaluator_rewrite.
532
- ctx.transport.broadcast(
533
- { type: 'user_input', sessionId: targetSessionId, clientId: client.id, text: trimmed, messageId, timestamp: Date.now() },
534
- (c) => c.id !== client.id
535
- )
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
+ }
536
1072
  }
537
1073
 
538
1074
  function handleInterrupt(ws, client, msg, ctx) {
@@ -540,6 +1076,11 @@ function handleInterrupt(ws, client, msg, ctx) {
540
1076
  const entry = resolveSession(ctx, msg, client)
541
1077
  if (entry) {
542
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?.()
543
1084
  entry.session.interrupt()
544
1085
  return
545
1086
  }
@@ -757,7 +1298,13 @@ function handleRegisterPushToken(ws, client, msg, ctx) {
757
1298
  // is actually pruned from the registry. Without ref-counting, the
758
1299
  // first disconnect would strip the token from the second client's
759
1300
  // active session.
760
- const ok = ctx.services.pushManager.registerToken(msg.token, client.id)
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
+ )
761
1308
  if (!ok) {
762
1309
  ctx.transport.send(ws, {
763
1310
  type: 'push_token_error',
@@ -875,6 +1422,33 @@ function handleNotificationPrefsSet(ws, client, msg, ctx) {
875
1422
  }
876
1423
  }
877
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
+
878
1452
  function handleUserQuestionResponse(ws, client, msg, ctx) {
879
1453
  // #5753 — route by toolUseId when one is supplied. `_registerQuestionRoute`
880
1454
  // maps every question that has a toolUseId at DISPATCH time (before the
@@ -898,14 +1472,28 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
898
1472
  // (legacy single-session mode / clients that don't send one), where there is
899
1473
  // a single question in flight and no cross-question mis-route risk.
900
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
901
1480
  if (typeof msg.toolUseId === 'string') {
902
- if (!ctx.permissions.questionSessionMap.has(msg.toolUseId)) {
903
- sessionLogger(client.activeSessionId || undefined).info(
904
- `user_question_response dropped: stale/unknown toolUseId=${msg.toolUseId} (question already resolved or its session is gone)`,
905
- )
906
- return
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
907
1496
  }
908
- questionSessionId = ctx.permissions.questionSessionMap.get(msg.toolUseId)
909
1497
  } else {
910
1498
  questionSessionId = client.activeSessionId
911
1499
  }
@@ -929,6 +1517,19 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
929
1517
  if (!isSessionViewer(client, questionSessionId)) return
930
1518
  }
931
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
+
932
1533
  if (msg.toolUseId) ctx.permissions.questionSessionMap.delete(msg.toolUseId)
933
1534
 
934
1535
  const entry = ctx.sessions.sessionManager.getSession(questionSessionId)
@@ -959,18 +1560,44 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
959
1560
  const qlog = sessionLogger(questionSessionId)
960
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}`)
961
1562
  // #4668: forward msg.toolUseId so claude-tui-session can route the
962
- // answer to the right pending entry in its Map. Sessions that don't
963
- // care about toolUseId (cli-session, sdk-session via permission-
964
- // manager) ignore the extra argument — JS positional args make this
965
- // a safe addition. ByokSession's respondToQuestion forwards to
966
- // _permissions.respondToQuestion which similarly ignores trailing
967
- // 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.
968
1566
  // #4651: forward msg.freeformText as a final opts object — claude-tui-
969
1567
  // session uses it to drive the two-stage Other-path write (digit →
970
1568
  // text-input prompt → freeform text + Enter). Other providers ignore
971
1569
  // the trailing arg.
972
1570
  const opts = hasFreeform ? { freeformText: msg.freeformText } : undefined
973
- 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
+ }
974
1601
  }
975
1602
  }
976
1603
 
@@ -1035,6 +1662,16 @@ function handleTerminalInput(ws, client, msg, ctx) {
1035
1662
  ))
1036
1663
  return
1037
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
+ }
1038
1675
  entry.session.writeTerminalInput(msg.data)
1039
1676
  }
1040
1677