@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.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  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 +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  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 +74 -9
  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 +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -0,0 +1,64 @@
1
+ import { CloudflareTunnelAdapter } from './cloudflare.js'
2
+ import { assertPreviewIngress } from '../preview-ingress.js'
3
+
4
+ function waitForExit(proc, milliseconds) {
5
+ if (proc.exitCode != null || proc.signalCode != null) return Promise.resolve(true)
6
+ return new Promise(resolve => {
7
+ const finish = result => { clearTimeout(timer)
8
+ proc.off('close', closed)
9
+ resolve(result) }
10
+ const closed = () => finish(true)
11
+ const timer = setTimeout(() => finish(false), milliseconds)
12
+ proc.once('close', closed)
13
+ })
14
+ }
15
+
16
+ /** A preview has one lifetime: no retries, recovery or URL replacement. */
17
+ export class PreviewTunnelAdapter extends CloudflareTunnelAdapter {
18
+ constructor(opts) {
19
+ super({ ...opts, mode: 'quick' })
20
+ this.maxStartAttempts = 1
21
+ this._children = new Set()
22
+ }
23
+
24
+ _spawnCloudflared(argv, opts) {
25
+ assertPreviewIngress(this.config.previewIngress)
26
+ if (JSON.stringify(argv) !== JSON.stringify(this._quickTunnelArguments())) throw new Error('Preview ingress arguments changed')
27
+ const proc = super._spawnCloudflared(argv, opts)
28
+ this._children.add(proc)
29
+ proc.once('close', () => this._children.delete(proc))
30
+ return proc
31
+ }
32
+
33
+ async _handleUnexpectedExit() {
34
+ if (!this.intentionalShutdown) this.emit('tunnel_lost')
35
+ this.intentionalShutdown = true
36
+ }
37
+
38
+ _quickTunnelExposureMessage(url) {
39
+ return `HTTP preview publicly reachable at ${url}; Chroxy adds no authentication. HTTP only: no WebSockets or reconnect.`
40
+ }
41
+
42
+ _quickTunnelArguments() {
43
+ if (!this.config.previewIngress?.path) throw new Error('Preview requires a private Unix ingress configuration')
44
+ // Quick dispatch needs this flag; the private ingress selects the origin.
45
+ return ['tunnel', '--config', this.config.previewIngress.path, '--hello-world', '--no-autoupdate']
46
+ }
47
+
48
+ async stop() {
49
+ this.intentionalShutdown = true
50
+ this._startAbort?.abort()
51
+ this._recoveryAbort?.abort()
52
+ for (const proc of this._children) {
53
+ const terminated = waitForExit(proc, 3000)
54
+ proc.kill('SIGTERM')
55
+ if (!await terminated) {
56
+ const killed = waitForExit(proc, 2000)
57
+ proc.kill('SIGKILL')
58
+ if (!await killed) throw new Error('Preview tunnel process exit could not be confirmed after TERM and KILL')
59
+ }
60
+ }
61
+ this.process = null
62
+ this.url = null
63
+ }
64
+ }
@@ -77,7 +77,7 @@ export async function waitForTunnel(httpUrl, { maxAttempts = 20, initialInterval
77
77
  `Tunnel failed to become routable after ${maxAttempts} attempts (${elapsed}s). ` +
78
78
  `${lastFailure ? `Last failure: ${lastFailure}. ` : ''}` +
79
79
  'This usually means your network is blocking Cloudflare, or DNS has not propagated yet. ' +
80
- 'Try a named tunnel (--tunnel named) or run `npx chroxy doctor` for diagnostics.'
80
+ 'Try a named tunnel (--tunnel named) or run `chroxy doctor` for diagnostics.'
81
81
  )
82
82
  err.code = 'TUNNEL_NOT_ROUTABLE'
83
83
  throw err
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Provider-neutral turn outcome (#7326).
3
+ *
4
+ * Every provider ends a turn with some provider-specific signal (an ACP
5
+ * `StopReason`, an Anthropic `stop_reason`, an Agent SDK result subtype). Before
6
+ * #7326 all of them were discarded: a turn that hit the token ceiling, ran out
7
+ * of its request budget or was refused by the model reached the clients as a
8
+ * plain successful `result`, indistinguishable from a finished one.
9
+ *
10
+ * Not to be confused with `terminatedReason` (#7376, @chroxy/protocol's
11
+ * turn-termination.ts): that stamps a TOOL call whose turn was ended underneath
12
+ * it. This describes how the TURN ended. The name also stays clear of the raw
13
+ * provider `stopReason` / `stop_reason` strings this module maps FROM (ACP,
14
+ * Anthropic, and BYOK's own `result.stopReason`).
15
+ *
16
+ * This module is the ONE place those signals are mapped onto the four-value
17
+ * vocabulary that rides the `result` wire frame (`turnOutcome`):
18
+ *
19
+ * completed — the model finished on its own.
20
+ * truncated — the turn was cut short by a limit (tokens, turns, budget, context).
21
+ * refused — the model declined to answer.
22
+ * stopped — the turn was cancelled.
23
+ *
24
+ * Every mapper returns `undefined` for a signal it does not recognise. The
25
+ * field is then OMITTED from the wire, which clients read as "unknown" and
26
+ * render as nothing, rather than a fabricated `completed`.
27
+ */
28
+
29
+ import { TURN_OUTCOMES, isTurnOutcome } from '@chroxy/protocol'
30
+
31
+ // The vocabulary and its wording are single-sourced in @chroxy/protocol (the
32
+ // clients word the same values); this module only maps provider signals onto it.
33
+ export { TURN_OUTCOMES, isTurnOutcome }
34
+
35
+ /**
36
+ * ACP `StopReason` (the closed set in the SDK's schema.json `$defs.StopReason`).
37
+ * @param {unknown} stopReason
38
+ * @returns {'completed'|'truncated'|'refused'|'stopped'|undefined}
39
+ */
40
+ export function outcomeFromAcpStopReason(stopReason) {
41
+ switch (stopReason) {
42
+ case 'end_turn': return 'completed'
43
+ case 'max_tokens':
44
+ case 'max_turn_requests': return 'truncated'
45
+ case 'refusal': return 'refused'
46
+ case 'cancelled': return 'stopped'
47
+ default: return undefined
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Anthropic Messages API `stop_reason` — also what the Agent SDK's result
53
+ * message and the BYOK loop carry. `tool_use` is deliberately unmapped: a turn
54
+ * is not over while the model is waiting on a tool.
55
+ *
56
+ * Two values are not what their names suggest (checked against
57
+ * `StopReason` / `Message.stop_reason` in @anthropic-ai/sdk 0.91.1's
58
+ * resources/messages/messages.d.ts, #8461):
59
+ *
60
+ * pause_turn — "we paused a long-running turn. You may provide the response
61
+ * back as-is in a subsequent request to let the model continue."
62
+ * The model has NOT finished; a client has to resume it. Neither
63
+ * BYOK's loop nor the SDK result path does, so the user is left
64
+ * holding a half reply: `truncated`, never `completed`.
65
+ * stop_sequence — one of the request's own `stop_sequences` was generated, so
66
+ * the model stopped where it was told to: `completed`. We send
67
+ * no `stop_sequences`, so a genuine one does not occur today.
68
+ * The one place it does appear is the OpenAI-compatible shim,
69
+ * which folds `content_filter` into it (anthropic-openai-
70
+ * translate.js `mapFinishReason`); that path reads as
71
+ * `completed` here, a known gap listed in #8461 and left
72
+ * unmapped on purpose because a filter is not a clear refusal.
73
+ * @param {unknown} stopReason
74
+ * @returns {'completed'|'truncated'|'refused'|'stopped'|undefined}
75
+ */
76
+ export function outcomeFromAnthropicStopReason(stopReason) {
77
+ switch (stopReason) {
78
+ case 'end_turn':
79
+ case 'stop_sequence': return 'completed'
80
+ case 'max_tokens':
81
+ case 'pause_turn':
82
+ case 'model_context_window_exceeded': return 'truncated'
83
+ case 'refusal': return 'refused'
84
+ default: return undefined
85
+ }
86
+ }
87
+
88
+ /**
89
+ * BYOK turn. Same mapping as {@link outcomeFromAnthropicStopReason}, except a
90
+ * turn that spent MAX_TOOL_ROUNDS is `truncated` whatever the summary round
91
+ * said: the forced no-tools summary ends with an ordinary `end_turn`, which
92
+ * overwrites the loop's own stop reason and read as a clean finish (#8461). The
93
+ * work was cut off by the round cap; the summary only reports how far it got.
94
+ *
95
+ * An `interrupted` turn (an abort that landed in the tool phase, #7072) is
96
+ * `stopped` whatever stop reason the last round carried: that reason is
97
+ * `tool_use`, which says nothing about how the turn ended.
98
+ * @param {{ stopReason?: unknown, toolRoundCapReached?: boolean, interrupted?: boolean }} turn
99
+ * @returns {'completed'|'truncated'|'refused'|'stopped'|undefined}
100
+ */
101
+ export function outcomeFromByokTurn({ stopReason, toolRoundCapReached = false, interrupted = false } = {}) {
102
+ if (interrupted) return 'stopped'
103
+ // A refusal in the summary round still outranks the cap: it is the more specific fact.
104
+ const mapped = outcomeFromAnthropicStopReason(stopReason)
105
+ if (toolRoundCapReached && (mapped === undefined || mapped === 'completed')) return 'truncated'
106
+ return mapped
107
+ }
108
+
109
+ /**
110
+ * Agent SDK `result` message (SDKResultSuccess / SDKResultError). The loop-level
111
+ * signals outrank the API `stop_reason`: `error_max_turns` ends a turn whose last
112
+ * API stop_reason was an ordinary `tool_use`.
113
+ * @param {{ subtype?: unknown, stop_reason?: unknown, terminal_reason?: unknown }|null|undefined} msg
114
+ * @returns {'completed'|'truncated'|'refused'|'stopped'|undefined}
115
+ */
116
+ export function outcomeFromSdkResult(msg) {
117
+ if (!msg || typeof msg !== 'object') return undefined
118
+ if (msg.subtype === 'error_max_turns' || msg.terminal_reason === 'max_turns') return 'truncated'
119
+ if (msg.subtype === 'error_max_budget_usd') return 'truncated'
120
+ if (msg.terminal_reason === 'aborted_streaming' || msg.terminal_reason === 'aborted_tools') return 'stopped'
121
+ const mapped = outcomeFromAnthropicStopReason(msg.stop_reason)
122
+ // A failed run (`error_during_execution`, an `is_error` result) can still carry
123
+ // an ordinary `end_turn` from the last API call that DID complete. That is not
124
+ // a clean finish, so `completed` is withheld there; a limit or refusal stands.
125
+ const failed = msg.is_error === true || (typeof msg.subtype === 'string' && msg.subtype !== 'success')
126
+ return failed && mapped === 'completed' ? undefined : mapped
127
+ }
128
+
129
+ /**
130
+ * Spread-ready field for a `result` payload: `{ turnOutcome }` for a known
131
+ * reason, `{}` otherwise, so an unmapped signal leaves the key off entirely.
132
+ * @param {unknown} reason
133
+ * @returns {{ turnOutcome?: 'completed'|'truncated'|'refused'|'stopped' }}
134
+ */
135
+ export function turnOutcomeField(reason) {
136
+ return isTurnOutcome(reason) ? { turnOutcome: reason } : {}
137
+ }
Binary file
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Cross-provider per-model usage normalization (#6692).
3
+ *
4
+ * Every provider session emits a terminal `result` event whose flat `usage`
5
+ * object feeds the per-session accumulator (session-manager `_trackUsage`).
6
+ * What that flat shape cannot carry is a per-model split — the Agent SDK
7
+ * reports one (`msg.modelUsage`, camelCase keys) and single-model providers
8
+ * can synthesize one — so the result payload gains an ADDITIVE `modelUsage`
9
+ * field in the shape below. Token keys stay snake_case so any cell can be
10
+ * passed straight to `computePromptCostUsd` (models.js) unchanged.
11
+ *
12
+ * modelUsage: {
13
+ * [modelId]: {
14
+ * input_tokens, output_tokens,
15
+ * cache_read_input_tokens, cache_creation_input_tokens,
16
+ * web_search_requests,
17
+ * cost_usd, // provider-reported; null when unknown
18
+ * }
19
+ * } | null // null = provider produced nothing this turn
20
+ *
21
+ * Consumers must treat `modelUsage` as optional — `_trackUsage` and every
22
+ * existing subscriber ignore unknown result fields by design.
23
+ */
24
+
25
+ // The generic prototype-pollution key set (`__proto__` / `constructor` /
26
+ // `prototype`), single-sourced in @chroxy/protocol since #7030. Imported from
27
+ // the Zod-free subpath so this module stays dependency-light.
28
+ import { UNSAFE_MCP_KEYS } from '@chroxy/protocol/mcp-validation'
29
+
30
+ /**
31
+ * Clamp to a non-negative finite integer — mirrors `_trackUsage`'s
32
+ * tokenDelta coercion so a poisoned provider value can never drive an
33
+ * accumulator negative or NaN.
34
+ */
35
+ export function nonNegInt(x) {
36
+ const n = Number(x)
37
+ if (!Number.isFinite(n) || n <= 0) return 0
38
+ return Math.floor(n)
39
+ }
40
+
41
+ // model ids come from provider output (untrusted). Reject the keys that could
42
+ // pollute a plain object so a hostile/buggy id can't reach `out[id] = …`.
43
+ const isSafeModelId = (id) => typeof id === 'string' && id.length > 0 && !UNSAFE_MCP_KEYS.has(id)
44
+
45
+ /**
46
+ * Normalize the Agent SDK's per-model usage map (camelCase ModelUsage
47
+ * entries) into the wire contract above. Returns null when the input is
48
+ * absent, not an object, or normalizes to zero entries.
49
+ */
50
+ export function normalizeSdkModelUsage(raw) {
51
+ if (!raw || typeof raw !== 'object') return null
52
+ const out = {}
53
+ for (const [modelId, u] of Object.entries(raw)) {
54
+ if (!isSafeModelId(modelId) || !u || typeof u !== 'object') continue
55
+ out[modelId] = {
56
+ input_tokens: nonNegInt(u.inputTokens ?? u.input_tokens),
57
+ output_tokens: nonNegInt(u.outputTokens ?? u.output_tokens),
58
+ cache_read_input_tokens: nonNegInt(u.cacheReadInputTokens ?? u.cache_read_input_tokens),
59
+ cache_creation_input_tokens: nonNegInt(u.cacheCreationInputTokens ?? u.cache_creation_input_tokens),
60
+ web_search_requests: nonNegInt(u.webSearchRequests ?? u.web_search_requests),
61
+ cost_usd: Number.isFinite(u.costUSD) ? u.costUSD : (Number.isFinite(u.cost_usd) ? u.cost_usd : null),
62
+ }
63
+ }
64
+ return Object.keys(out).length > 0 ? out : null
65
+ }
66
+
67
+ /**
68
+ * Build a single-entry modelUsage map for providers that run exactly one
69
+ * model per session (byok family, codex, gemini). `usage` is the provider's
70
+ * flat snake_case turn usage; absent fields clamp to 0. Returns null when
71
+ * the model id is unknown or the usage object carries no token signal at
72
+ * all, so a both-null synthetic result (stream-stall recovery) never
73
+ * fabricates an all-zero per-model row.
74
+ *
75
+ * Note the gate is BROADER than `_trackUsage`'s (session-manager.js), which
76
+ * keys only on a finite `input_tokens`: this returns a row when ANY of the 5
77
+ * token fields is finite. They coincide today because every provider call
78
+ * site emits a finite `input_tokens` (0 or positive) whenever `usage` is an
79
+ * object, so the sole divergence (an output-or-cache-only turn) can't arise.
80
+ * A future consumer that sums these rows against `cumulativeUsage` should not
81
+ * assume literal parity — if an output-only provider ever appears, this would
82
+ * synthesize a row `_trackUsage` skips.
83
+ */
84
+ export function synthesizeModelUsage(model, usage, costUsd = null) {
85
+ if (!isSafeModelId(model)) return null
86
+ if (!usage || typeof usage !== 'object') return null
87
+ // A real numeric token field is the signal. Test `typeof === 'number'` (not
88
+ // Number(v)) so a provider's explicit null for a missing field is NOT read
89
+ // as 0 — `Number(null) === 0` is finite and would fabricate an all-zero row
90
+ // for a genuinely-empty turn. An explicit numeric 0 still counts as signal.
91
+ const anyTokenSignal = [
92
+ usage.input_tokens, usage.output_tokens,
93
+ usage.cache_read_input_tokens, usage.cached_input_tokens,
94
+ usage.cache_creation_input_tokens,
95
+ ].some((v) => typeof v === 'number' && Number.isFinite(v))
96
+ if (!anyTokenSignal) return null
97
+ return {
98
+ [model]: {
99
+ input_tokens: nonNegInt(usage.input_tokens),
100
+ output_tokens: nonNegInt(usage.output_tokens),
101
+ // codex historically emitted `cached_input_tokens`; accept both so a
102
+ // caller can hand this the raw pre-#6692 shape without dropping cache.
103
+ cache_read_input_tokens: nonNegInt(usage.cache_read_input_tokens ?? usage.cached_input_tokens),
104
+ cache_creation_input_tokens: nonNegInt(usage.cache_creation_input_tokens),
105
+ web_search_requests: nonNegInt(usage.web_search_requests),
106
+ cost_usd: Number.isFinite(costUsd) ? costUsd : null,
107
+ },
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Whether a provider's sessions produce token telemetry at all. claude-tui
113
+ * and claude-channel emit `usage:null, cost:null` on every turn (Stop-hook
114
+ * limitation), so anything that needs metering — orchestration runs (#6691),
115
+ * cost comparisons — must refuse or caveat them. user-shell runs no model.
116
+ */
117
+ const UNMETERABLE_PROVIDERS = new Set(['claude-tui', 'claude-channel', 'user-shell'])
118
+
119
+ export function isMeterableProvider(provider) {
120
+ if (!provider || typeof provider !== 'string') return false
121
+ return !UNMETERABLE_PROVIDERS.has(provider)
122
+ }
@@ -17,8 +17,11 @@
17
17
  import { realpathSync, existsSync } from 'fs'
18
18
  import { USER_SHELL_PROVIDER } from '@chroxy/protocol'
19
19
  import { BaseSession, buildBaseSessionOpts } from './base-session.js'
20
+ import { USER_SHELL_CUSTOMIZATION } from './provider-customization.js'
20
21
  import { createLogger } from './logger.js'
21
- import { CHROXY_SECRET_DENYLIST } from './utils/spawn-env.js'
22
+ import { isWindows, defaultShell, killProcessTree } from './platform.js'
23
+ import { CHROXY_SECRET_DENYLIST, stripInheritedChroxySecrets, stripParentClaudeSessionEnv } from './utils/spawn-env.js'
24
+ import { nodePtyImportFailureError } from './utils/node-pty-support.js'
22
25
 
23
26
  const log = createLogger('user-shell-session')
24
27
 
@@ -28,25 +31,57 @@ const DEFAULT_COLS = 120
28
31
  const DEFAULT_ROWS = 30
29
32
  // Coalesce PTY bytes into one terminal_output per tick (bounds broadcast churn).
30
33
  const MIRROR_FLUSH_MS = 50
31
- // SIGTERM → grace → SIGKILL the process group on destroy.
34
+ // POSIX destroy() escalation window: SIGTERM → grace → SIGKILL the process
35
+ // group. Windows has no grace — destroy() reaps the whole tree at once via
36
+ // taskkill (#6646), so this constant is POSIX-only.
32
37
  const DESTROY_GRACE_MS = 3000
33
38
 
39
+ // Windows PowerShell 5.1 ships in-box at this fixed System32 path on every
40
+ // Windows install (the `v1.0` dir name is a historical constant, not the PS
41
+ // version). Preferred over cmd.exe for a real interactive terminal.
42
+ const WIN_POWERSHELL_RELATIVE = 'System32\\WindowsPowerShell\\v1.0\\powershell.exe'
43
+
34
44
  /**
35
- * Resolve the shell to spawn: `$SHELL` if it exists, then common fallbacks.
36
- * Returns the first path that exists; if none do (a truly unusual host), falls
37
- * back to `/bin/sh` as a last resort — start() then surfaces a clean spawn error
38
- * if that path is also missing.
45
+ * Resolve the interactive shell to spawn.
46
+ *
47
+ * POSIX: `$SHELL` if it exists, then `/bin/zsh|bash|sh`, then `/bin/sh` as a
48
+ * last resort (start() surfaces a clean spawn error if even that is missing).
49
+ *
50
+ * Windows (#6646): the POSIX candidates never exist, so the old code returned
51
+ * `/bin/sh` and node-pty's spawn always failed — the embedded shell never
52
+ * launched. Prefer a real interactive shell instead: an explicit `$SHELL` that
53
+ * exists wins (lets a user pin e.g. `pwsh.exe`), then Windows PowerShell 5.1 at
54
+ * its fixed System32 path, then `defaultShell()` (COMSPEC/cmd.exe).
55
+ *
56
+ * `platform`/`env`/`exists` are injectable so both platform branches are
57
+ * unit-testable on any CI host — the Windows path can't rely on a Windows
58
+ * runner being present. Production callers pass no args.
39
59
  */
40
- function resolveShell() {
41
- const shell = process.env.SHELL
42
- if (typeof shell === 'string' && shell && existsSync(shell)) return shell
60
+ export function resolveShell({
61
+ platform = process.platform,
62
+ env = process.env,
63
+ exists = existsSync,
64
+ } = {}) {
65
+ const shell = env.SHELL
66
+ if (platform === 'win32') {
67
+ if (typeof shell === 'string' && shell && exists(shell)) return shell
68
+ const systemRoot = env.SystemRoot || env.windir || 'C:\\Windows'
69
+ const winPowerShell = `${systemRoot}\\${WIN_POWERSHELL_RELATIVE}`
70
+ if (exists(winPowerShell)) return winPowerShell
71
+ return defaultShell({ platform, env })
72
+ }
73
+ if (typeof shell === 'string' && shell && exists(shell)) return shell
43
74
  for (const cand of ['/bin/zsh', '/bin/bash', '/bin/sh']) {
44
- if (existsSync(cand)) return cand
75
+ if (exists(cand)) return cand
45
76
  }
46
77
  return '/bin/sh'
47
78
  }
48
79
 
49
80
  export class UserShellSession extends BaseSession {
81
+ static get customizationDescriptor() {
82
+ return USER_SHELL_CUSTOMIZATION
83
+ }
84
+
50
85
  static get displayLabel() {
51
86
  return 'Shell'
52
87
  }
@@ -72,6 +107,10 @@ export class UserShellSession extends BaseSession {
72
107
  resume: false,
73
108
  terminal: true,
74
109
  thinkingLevel: false,
110
+ // #7725: a raw $SHELL PTY. There is no model, so there is nothing to
111
+ // escalate — the magic keywords would just be shell words.
112
+ thinkingKeywords: false,
113
+ thinkingLevelEffective: false, // #8700: no report of the applied level
75
114
  streaming: false,
76
115
  tools: false,
77
116
  }
@@ -99,6 +138,9 @@ export class UserShellSession extends BaseSession {
99
138
  this._mirrorTimer = null
100
139
  this._terminalMirrorActive = false
101
140
  this._killTimer = null
141
+ // Windows tree-reaper for destroy() (taskkill /T /F). Injectable so a test
142
+ // can assert the Windows branch without spawning a real taskkill (#6646).
143
+ this._killProcessTree = killProcessTree
102
144
  }
103
145
 
104
146
  /**
@@ -119,6 +161,14 @@ export class UserShellSession extends BaseSession {
119
161
  * primary bearer token from the environment. Extracted so the strip is
120
162
  * unit-testable without a real PTY spawn.
121
163
  *
164
+ * Also strips CHROXY_PORT/CHROXY_HOOK_SECRET (#7360): this session never
165
+ * sets its own (a user shell has no permission hook — see the class doc —
166
+ * so there is no "this session's own value" to preserve here, unlike
167
+ * cli-session.js/claude-tui-session.js), so any value present is
168
+ * necessarily AMBIENTLY inherited — e.g. this daemon was itself launched
169
+ * from inside another chroxy session — and is a foreign session's hook
170
+ * secret with no legitimate use in a plain interactive shell.
171
+ *
122
172
  * @returns {Record<string, string>}
123
173
  */
124
174
  _buildShellEnv() {
@@ -126,6 +176,8 @@ export class UserShellSession extends BaseSession {
126
176
  for (const key of CHROXY_SECRET_DENYLIST) {
127
177
  delete env[key]
128
178
  }
179
+ stripInheritedChroxySecrets(env)
180
+ stripParentClaudeSessionEnv(env) // #8262
129
181
  return env
130
182
  }
131
183
 
@@ -136,10 +188,44 @@ export class UserShellSession extends BaseSession {
136
188
  */
137
189
  async start() {
138
190
  let ptyMod
139
- try {
140
- ptyMod = await import('node-pty')
141
- } catch (err) {
142
- throw new Error(`node-pty unavailable: ${err.message}`)
191
+ // Test seam (#8151 C4): a test may set `_ptyModOverride` to a FUNCTION to
192
+ // simulate the import ITSELF rejecting, exercising this real catch/throw
193
+ // rather than reimplementing its logic in the test. Undefined in
194
+ // production → the genuine dynamic import runs unchanged. Kept as a
195
+ // SEPARATE branch rather than routing the real import through a shared
196
+ // wrapper function: lint-argv-sinks.mjs recognises `ptyMod = await
197
+ // import('node-pty')` as a literal AST shape (an import expression bound
198
+ // DIRECTLY to `ptyMod`) to find this node-pty spawn sink and argv-guard
199
+ // it — a wrapper would make the lint blind to this call site (see
200
+ // claude-tui-session.js's `_spawnPty` for the same reasoning, applied
201
+ // there first).
202
+ //
203
+ // #8151 round-2 review (Critical 1): the two catch BODIES below used to
204
+ // duplicate the `describeNodePtyUnavailable` + `Object.assign(..., {
205
+ // code })` construction verbatim — only the `try`/`await import(...)`
206
+ // shape stays duplicated (for lint-argv-sinks, above); the failure
207
+ // object itself is now built by the one shared `nodePtyImportFailureError`
208
+ // helper, so there is a single place to change what this failure looks
209
+ // like.
210
+ if (typeof this._ptyModOverride === 'function') {
211
+ try {
212
+ ptyMod = await this._ptyModOverride()
213
+ } catch (err) {
214
+ throw nodePtyImportFailureError(err)
215
+ }
216
+ } else {
217
+ try {
218
+ ptyMod = await import('node-pty')
219
+ } catch (err) {
220
+ // start() already rejects directly with the actionable message (no
221
+ // intermediate generic-message overwrite the way
222
+ // claude-tui-session.js's _spawnPty/start() split needed fixing
223
+ // for) — this is the PRODUCTION branch: node-pty-production-import
224
+ // .test.js exercises it in a real child process via a
225
+ // `node:module` resolve hook, not just the `_ptyModOverride` test
226
+ // seam above.
227
+ throw nodePtyImportFailureError(err)
228
+ }
143
229
  }
144
230
 
145
231
  // Resolved in the constructor (see _shellPath) so the create-audit can read
@@ -168,9 +254,11 @@ export class UserShellSession extends BaseSession {
168
254
  }
169
255
 
170
256
  // destroy() can race the spawn (it set _destroying while we awaited the
171
- // import): kill the fresh PTY so it isn't orphaned, then bail.
257
+ // import): reap the fresh PTY so it isn't orphaned, then bail. Uses the same
258
+ // Windows tree-kill as destroy() (#6646) — a shell rc/profile can spawn a
259
+ // child immediately, so a direct kill on Windows would orphan it here too.
172
260
  if (this._destroying) {
173
- try { this._term.kill('SIGTERM') } catch { /* already gone */ }
261
+ this._reapTerm(this._term)
174
262
  this._term = null
175
263
  return
176
264
  }
@@ -351,10 +439,19 @@ export class UserShellSession extends BaseSession {
351
439
  }
352
440
 
353
441
  /**
354
- * Kill the PTY (no respawn) and clear all timers. SIGTERM, then after a grace
355
- * window SIGKILL the whole process group so backgrounded jobs die too. The
356
- * liveness probe + _ptyExited latch narrow escalation to a genuinely-hung
357
- * shell (never a recycled pid).
442
+ * Kill the PTY (no respawn) and clear all timers.
443
+ *
444
+ * POSIX: SIGTERM, then after a grace window SIGKILL the whole process GROUP so
445
+ * backgrounded jobs die too. The liveness probe + `_ptyExited` latch narrow
446
+ * escalation to a genuinely-hung shell (never a recycled pid).
447
+ *
448
+ * Windows (#6646): there is no graceful SIGTERM (node-pty maps `kill()` to
449
+ * `TerminateProcess` on the direct pid) and no process groups, so a direct
450
+ * kill would orphan the shell's children — acute here because a shell often
451
+ * launches `.cmd`/`.bat` wrappers whose real process is a grandchild. Reap the
452
+ * whole descendant tree at once with `taskkill /PID <pid> /T /F` (via
453
+ * killProcessTree); no grace window, since the shell can't run a SIGTERM
454
+ * handler on Windows anyway.
358
455
  */
359
456
  destroy() {
360
457
  // Idempotent: a second destroy() (or a destroy racing the exit path) is a
@@ -370,27 +467,32 @@ export class UserShellSession extends BaseSession {
370
467
  }
371
468
  this._mirrorBuffer = ''
372
469
 
470
+ const onWindows = this._isWindowsOverride ?? isWindows
373
471
  const term = this._term
374
472
  const pid = term?.pid
375
473
  if (term && !this._ptyExited) {
376
- try { term.kill('SIGTERM') } catch { /* already gone */ }
377
- if (Number.isInteger(pid) && pid > 0) {
378
- this._killTimer = setTimeout(() => {
379
- this._killTimer = null
380
- if (this._ptyExited) return
381
- try { process.kill(pid, 0) } catch { return /* already exited */ }
382
- log.warn(`user-shell PTY (pid=${pid}) did not exit ${DESTROY_GRACE_MS}ms after SIGTERM — escalating to SIGKILL`)
383
- let killed = false
384
- if (process.platform !== 'win32') {
385
- try { process.kill(-pid, 'SIGKILL'); killed = true } catch { /* group gone */ }
386
- }
387
- if (!killed) {
388
- try { term.kill('SIGKILL') } catch {
389
- try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }
474
+ if (onWindows) {
475
+ this._killProcessTree(term, { force: true })
476
+ } else {
477
+ try { term.kill('SIGTERM') } catch { /* already gone */ }
478
+ if (Number.isInteger(pid) && pid > 0) {
479
+ this._killTimer = setTimeout(() => {
480
+ this._killTimer = null
481
+ if (this._ptyExited) return
482
+ try { process.kill(pid, 0) } catch { return /* already exited */ }
483
+ log.warn(`user-shell PTY (pid=${pid}) did not exit ${DESTROY_GRACE_MS}ms after SIGTERM — escalating to SIGKILL`)
484
+ // SIGKILL the whole process group so backgrounded jobs die too; fall
485
+ // back to the direct pid if the group is already gone.
486
+ try {
487
+ process.kill(-pid, 'SIGKILL')
488
+ } catch {
489
+ try { term.kill('SIGKILL') } catch {
490
+ try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }
491
+ }
390
492
  }
391
- }
392
- }, DESTROY_GRACE_MS)
393
- if (typeof this._killTimer.unref === 'function') this._killTimer.unref()
493
+ }, DESTROY_GRACE_MS)
494
+ if (typeof this._killTimer.unref === 'function') this._killTimer.unref()
495
+ }
394
496
  }
395
497
  }
396
498
  this._term = null
@@ -408,4 +510,22 @@ export class UserShellSession extends BaseSession {
408
510
  this._killTimer = null
409
511
  }
410
512
  }
513
+
514
+ /**
515
+ * One-shot teardown of a term with no grace window — used by the start()
516
+ * destroy-race path where the shell was just spawned. POSIX: a direct SIGTERM
517
+ * (nothing is running in the fresh shell to gracefully save). Windows (#6646):
518
+ * the whole descendant tree via taskkill /T /F (a shell rc/profile may already
519
+ * have spawned a child, and node-pty's kill() would orphan it). destroy()'s
520
+ * own kill path stays separate because it adds the POSIX grace-escalation.
521
+ */
522
+ _reapTerm(term) {
523
+ if (!term) return
524
+ const onWindows = this._isWindowsOverride ?? isWindows
525
+ if (onWindows) {
526
+ this._killProcessTree(term, { force: true })
527
+ } else {
528
+ try { term.kill('SIGTERM') } catch { /* already gone */ }
529
+ }
530
+ }
411
531
  }