@chroxy/server 0.10.0

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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,511 @@
1
+ import { EventEmitter } from 'events'
2
+ import { createLogger } from './logger.js'
3
+
4
+ const log = createLogger('session-message-history')
5
+ const MAX_PENDING_STREAM_SIZE = 100 * 1024 * 1024 // 100MB
6
+
7
+ /**
8
+ * Manages per-session message history ring buffers, stream delta accumulation,
9
+ * truncation tracking, and auto-labeling from first user input.
10
+ *
11
+ * Extracted from SessionManager to isolate history concerns.
12
+ *
13
+ * Events emitted:
14
+ * auto_label { sessionId, label } — when first user input triggers session rename
15
+ */
16
+ export class SessionMessageHistory extends EventEmitter {
17
+ /**
18
+ * @param {object} [opts]
19
+ * @param {number} [opts.maxMessages=1000] - Max messages per session (FIFO eviction when exceeded)
20
+ * @param {number} [opts.maxHistory] - Alias for maxMessages (legacy option name)
21
+ * @param {number} [opts.maxToolInput] - Max characters for tool input (unused here, reserved)
22
+ * @param {number} [opts.maxPendingStreamSize] - Max accumulated chars for one pending stream before further deltas are dropped (default 100MB). Injectable for tests.
23
+ */
24
+ constructor({ maxMessages, maxHistory, maxToolInput, maxPendingStreamSize } = {}) {
25
+ super()
26
+ this._maxHistory = maxMessages ?? maxHistory ?? 1000
27
+ this._maxToolInput = maxToolInput || null
28
+ this._maxPendingStreamSize = maxPendingStreamSize || MAX_PENDING_STREAM_SIZE
29
+ this._messageHistory = new Map() // sessionId -> Array<{ type, _seq, ...data }>
30
+ this._pendingStreams = new Map() // sessionId:messageId -> accumulated delta text
31
+ // #6431 — messageIds whose pending stream has already been truncated, so the
32
+ // truncation is signalled to the client ONCE per stream (every subsequent
33
+ // over-size delta for the same message also exceeds the cap and would
34
+ // otherwise re-fire the error). Cleared on stream_end / session clear.
35
+ this._truncatedStreams = new Set() // sessionId:messageId
36
+ this._historyTruncated = new Map() // sessionId -> boolean
37
+ // #5555.3 (lastSeq delta replay) — per-session monotonic history sequence.
38
+ // Every entry pushed into the ring buffer is stamped with a strictly
39
+ // increasing `_seq` (1-based). The counter NEVER resets while a session
40
+ // lives, even as the ring buffer trims old entries off the front — so a
41
+ // client cursor (`lastSeq`) can be compared against the oldest RETAINED
42
+ // entry's seq to detect a trim gap and fall back to a full replay. The
43
+ // seq is server-internal bookkeeping; the wire only exposes it as
44
+ // `historySeq` on replayed entries (see ws-history.js).
45
+ this._seqCounters = new Map() // sessionId -> next seq to assign (>= 1)
46
+ }
47
+
48
+ /**
49
+ * #5555.3 — allocate the next monotonic seq for a session.
50
+ * @param {string} sessionId
51
+ * @returns {number}
52
+ */
53
+ _nextSeq(sessionId) {
54
+ const next = this._seqCounters.get(sessionId) || 1
55
+ this._seqCounters.set(sessionId, next + 1)
56
+ return next
57
+ }
58
+
59
+ /**
60
+ * #5555.3 — seq of the oldest entry still retained in the ring buffer, or
61
+ * null when the session has no history. Used by the cursor-replay path to
62
+ * detect whether a client's cursor points at an entry that has since been
63
+ * trimmed off the front (gap → full-replay fallback).
64
+ * @param {string} sessionId
65
+ * @returns {number|null}
66
+ */
67
+ getOldestSeq(sessionId) {
68
+ const history = this._messageHistory.get(sessionId)
69
+ if (!history || history.length === 0) return null
70
+ const seq = history[0]._seq
71
+ return typeof seq === 'number' ? seq : null
72
+ }
73
+
74
+ /**
75
+ * #5555.3 — seq of the newest entry, or 0 when the session has no history
76
+ * (so `lastSeq >= getLatestSeq` cleanly means "nothing newer to replay").
77
+ * @param {string} sessionId
78
+ * @returns {number}
79
+ */
80
+ getLatestSeq(sessionId) {
81
+ const history = this._messageHistory.get(sessionId)
82
+ if (!history || history.length === 0) return 0
83
+ const seq = history[history.length - 1]._seq
84
+ return typeof seq === 'number' ? seq : 0
85
+ }
86
+
87
+ /**
88
+ * Get the max message count (FIFO cap).
89
+ * @returns {number}
90
+ */
91
+ get maxMessages() {
92
+ return this._maxHistory
93
+ }
94
+
95
+ /**
96
+ * Get the max history size (alias for maxMessages).
97
+ * @returns {number}
98
+ */
99
+ get maxHistory() {
100
+ return this._maxHistory
101
+ }
102
+
103
+ /**
104
+ * Get the pending streams map (used by tests and cleanupSession internals).
105
+ * @returns {Map}
106
+ */
107
+ get pendingStreams() {
108
+ return this._pendingStreams
109
+ }
110
+
111
+ /**
112
+ * Close all in-flight pending streams for a session, emitting synthetic
113
+ * stream_end data so callers can notify clients of stream termination.
114
+ *
115
+ * @param {string} sessionId
116
+ * @returns {string[]} Array of messageIds that were closed
117
+ */
118
+ closePendingStreams(sessionId) {
119
+ const prefix = sessionId + ':'
120
+ const closedMessageIds = []
121
+ for (const key of this._pendingStreams.keys()) {
122
+ if (key.startsWith(prefix)) {
123
+ const messageId = key.slice(prefix.length)
124
+ closedMessageIds.push(messageId)
125
+ this._pendingStreams.delete(key)
126
+ this._truncatedStreams.delete(key) // #6431 — release the truncation guard
127
+ }
128
+ }
129
+ return closedMessageIds
130
+ }
131
+
132
+ /**
133
+ * Get message history for a session.
134
+ * @param {string} sessionId
135
+ * @returns {Array<{ type, ...data }>}
136
+ */
137
+ getHistory(sessionId) {
138
+ return this._messageHistory.get(sessionId) || []
139
+ }
140
+
141
+ /**
142
+ * Get the count of messages in the ring buffer for a session.
143
+ * @param {string} sessionId
144
+ * @returns {number}
145
+ */
146
+ getHistoryCount(sessionId) {
147
+ return (this._messageHistory.get(sessionId) || []).length
148
+ }
149
+
150
+ /**
151
+ * Check whether a session's history has been truncated (ring buffer overflow).
152
+ * @param {string} sessionId
153
+ * @returns {boolean}
154
+ */
155
+ isHistoryTruncated(sessionId) {
156
+ return this._historyTruncated.get(sessionId) || false
157
+ }
158
+
159
+ /**
160
+ * Set pre-existing history for a session (used during state restore).
161
+ * @param {string} sessionId
162
+ * @param {Array} history
163
+ */
164
+ setHistory(sessionId, history) {
165
+ // #5555.3 — restored entries predate the seq scheme (it is server-internal
166
+ // and not persisted), so stamp them with a fresh 1..N sequence and advance
167
+ // the counter past the end. A reconnecting client's cursor from a PRIOR
168
+ // server process can't be honoured across a restart (seqs reset to 1), so
169
+ // it will simply fall through to a full replay — the safe default.
170
+ if (Array.isArray(history)) {
171
+ let seq = 1
172
+ for (const entry of history) {
173
+ if (entry && typeof entry === 'object') entry._seq = seq
174
+ seq++
175
+ }
176
+ this._seqCounters.set(sessionId, seq)
177
+ }
178
+ this._messageHistory.set(sessionId, history)
179
+ }
180
+
181
+ /**
182
+ * Sweep an in-memory history array for `tool_start` entries that lack a
183
+ * matching `tool_result` and splice in a synthetic `tool_result` right
184
+ * after each one. Used during session restore (#4617) so that a session
185
+ * which was wedged on a tool when chroxy shut down does not zombify the
186
+ * dashboard's `activeTools` pill on the next history replay — the
187
+ * synthetic result rides the same handler path that normally clears
188
+ * activeTools (`handleToolResult.applyToActiveTools`).
189
+ *
190
+ * Returns a NEW array; the input is not mutated. The original ordering
191
+ * is preserved and the synthetic result is inserted immediately after
192
+ * its matching `tool_start`, with a timestamp one millisecond later so
193
+ * downstream consumers that sort by timestamp stay monotonic without
194
+ * pretending the tool completed "now".
195
+ *
196
+ * Safe to call on:
197
+ * - empty / non-array input (returns the input unchanged)
198
+ * - history with no tool_start entries (returns a shallow copy)
199
+ * - history with all tool_starts already matched (returns a shallow copy)
200
+ *
201
+ * @param {Array} history
202
+ * @returns {Array}
203
+ */
204
+ static sweepUnresolvedToolStarts(history) {
205
+ if (!Array.isArray(history) || history.length === 0) return history
206
+ const resolved = new Set()
207
+ for (const entry of history) {
208
+ if (entry && entry.type === 'tool_result' && typeof entry.toolUseId === 'string') {
209
+ resolved.add(entry.toolUseId)
210
+ }
211
+ }
212
+ const out = []
213
+ for (const entry of history) {
214
+ out.push(entry)
215
+ if (
216
+ entry
217
+ && entry.type === 'tool_start'
218
+ && typeof entry.toolUseId === 'string'
219
+ && !resolved.has(entry.toolUseId)
220
+ ) {
221
+ const baseTs = typeof entry.timestamp === 'number' && Number.isFinite(entry.timestamp)
222
+ ? entry.timestamp
223
+ : Date.now()
224
+ // `synthetic` / `interrupted` / `isError` / `reason` are diagnostic
225
+ // hints only — no client code branches on them today, and the wire
226
+ // schema (`ServerToolResultSchema` in packages/protocol) strips
227
+ // unknown fields on parse. The behaviour that clears the dashboard's
228
+ // activeTools entry is driven purely by the `tool_result` type +
229
+ // matching `toolUseId` going through `handleToolResult.applyToActiveTools`
230
+ // (store-core/handlers/index.ts). Keep these fields anyway so the
231
+ // synthetic stays grep-able on disk and a future renderer can show
232
+ // a distinct "interrupted" badge without a protocol change.
233
+ out.push({
234
+ type: 'tool_result',
235
+ toolUseId: entry.toolUseId,
236
+ result: 'Tool was in flight when chroxy was last shut down. Tool may have continued or been cancelled — no record of outcome.',
237
+ interrupted: true,
238
+ isError: true,
239
+ synthetic: true,
240
+ reason: 'session_restored',
241
+ timestamp: baseTs + 1,
242
+ })
243
+ // Mark this toolUseId resolved so a malformed history with two
244
+ // tool_starts for the same id does not get two synthetic results.
245
+ resolved.add(entry.toolUseId)
246
+ }
247
+ }
248
+ return out
249
+ }
250
+
251
+ /**
252
+ * Record a user input message in the session's history ring buffer.
253
+ * On the first non-empty input, emits auto_label if the session qualifies.
254
+ *
255
+ * @param {string} sessionId
256
+ * @param {string} text
257
+ * @param {object} [sessionEntry] - Session entry from SessionManager (for auto-label check)
258
+ * @param {string} [messageId] - Optional stable ID so clients can dedup
259
+ * rehydrated entries against optimistic/live-echo copies on the sender.
260
+ * Only attached when a non-empty string is provided; the ws-layer (see
261
+ * `handlers/input-handlers.js::resolveUserInputId`) always resolves one
262
+ * before calling in, so replayed entries always carry an id in practice.
263
+ * See issue #2902.
264
+ */
265
+ recordUserInput(sessionId, text, sessionEntry, messageId) {
266
+ if (sessionEntry) {
267
+ this._autoLabelSession(sessionId, text, sessionEntry)
268
+ }
269
+ const entry = {
270
+ type: 'user_input',
271
+ content: text,
272
+ timestamp: Date.now(),
273
+ }
274
+ if (typeof messageId === 'string' && messageId.length > 0) {
275
+ entry.messageId = messageId
276
+ }
277
+ this.recordHistory(sessionId, 'message', entry)
278
+ }
279
+
280
+ /**
281
+ * Record an event into the session's message history ring buffer.
282
+ * @param {string} sessionId
283
+ * @param {string} event
284
+ * @param {object} data
285
+ * @returns {{ persistNeeded: boolean }} - Whether the caller should schedule a persist
286
+ */
287
+ recordHistory(sessionId, event, data) {
288
+ if (!this._messageHistory.has(sessionId)) {
289
+ this._messageHistory.set(sessionId, [])
290
+ }
291
+ const history = this._messageHistory.get(sessionId)
292
+ let persistNeeded = false
293
+
294
+ switch (event) {
295
+ case 'stream_start': {
296
+ const key = `${sessionId}:${data.messageId}`
297
+ this._pendingStreams.set(key, '')
298
+ break
299
+ }
300
+
301
+ case 'stream_delta': {
302
+ const key = `${sessionId}:${data.messageId}`
303
+ const existing = this._pendingStreams.get(key)
304
+ if (existing !== undefined) {
305
+ if (existing.length + data.delta.length > this._maxPendingStreamSize) {
306
+ // #6431 — drop the over-size delta from history. The client still
307
+ // received it (forwarded independently), so its local copy now
308
+ // diverges from the persisted message. Signal truncation ONCE per
309
+ // stream so the caller can emit a client-visible error instead of a
310
+ // silent desync.
311
+ const firstDrop = !this._truncatedStreams.has(key)
312
+ if (firstDrop) {
313
+ this._truncatedStreams.add(key)
314
+ log.warn(`Stream delta exceeded size limit for ${key} — truncating; client will be notified`)
315
+ }
316
+ return { persistNeeded: false, truncated: firstDrop }
317
+ }
318
+ this._pendingStreams.set(key, existing + data.delta)
319
+ }
320
+ break
321
+ }
322
+
323
+ case 'stream_end': {
324
+ const key = `${sessionId}:${data.messageId}`
325
+ const content = this._pendingStreams.get(key) || ''
326
+ this._pendingStreams.delete(key)
327
+ this._truncatedStreams.delete(key) // #6431 — release the once-per-stream guard
328
+ if (content) {
329
+ this._pushHistory(history, {
330
+ type: 'message',
331
+ messageType: 'response',
332
+ content,
333
+ messageId: data.messageId,
334
+ timestamp: Date.now(),
335
+ }, sessionId)
336
+ }
337
+ persistNeeded = true
338
+ break
339
+ }
340
+
341
+ case 'message':
342
+ this._pushHistory(history, {
343
+ type: 'message',
344
+ messageType: data.type,
345
+ content: data.content,
346
+ tool: data.tool,
347
+ options: data.options,
348
+ // Carry through the stable messageId for user_input entries so
349
+ // clients can dedup rehydrated prompts against their own
350
+ // optimistic/live-echo copies (issue #2902).
351
+ ...(data.messageId ? { messageId: data.messageId } : {}),
352
+ timestamp: data.timestamp,
353
+ }, sessionId)
354
+ persistNeeded = true
355
+ break
356
+
357
+ case 'tool_start':
358
+ this._pushHistory(history, {
359
+ type: 'tool_start',
360
+ messageId: data.messageId,
361
+ toolUseId: data.toolUseId,
362
+ tool: data.tool,
363
+ input: data.input,
364
+ timestamp: Date.now(),
365
+ }, sessionId)
366
+ break
367
+
368
+ case 'tool_result':
369
+ this._pushHistory(history, {
370
+ type: 'tool_result',
371
+ toolUseId: data.toolUseId,
372
+ result: data.result,
373
+ truncated: data.truncated,
374
+ timestamp: Date.now(),
375
+ }, sessionId)
376
+ break
377
+
378
+ case 'result':
379
+ this._pushHistory(history, {
380
+ type: 'result',
381
+ cost: data.cost,
382
+ duration: data.duration,
383
+ usage: data.usage,
384
+ timestamp: Date.now(),
385
+ }, sessionId)
386
+ persistNeeded = true
387
+ break
388
+
389
+ case 'user_question':
390
+ this._pushHistory(history, {
391
+ type: 'user_question',
392
+ toolUseId: data.toolUseId,
393
+ questions: data.questions,
394
+ timestamp: Date.now(),
395
+ }, sessionId)
396
+ break
397
+ }
398
+
399
+ return { persistNeeded }
400
+ }
401
+
402
+ /**
403
+ * Push an entry to the history array, trimming to max size.
404
+ * @param {Array} history
405
+ * @param {object} entry
406
+ * @param {string} sessionId
407
+ */
408
+ _pushHistory(history, entry, sessionId) {
409
+ // #5555.3 — stamp the monotonic per-session seq before pushing. The counter
410
+ // keeps climbing past any front-trim below, so a cursor can always be
411
+ // compared against the oldest retained entry's seq to detect a trim gap.
412
+ if (entry && typeof entry === 'object' && entry._seq === undefined) {
413
+ entry._seq = this._nextSeq(sessionId)
414
+ }
415
+ history.push(entry)
416
+ if (history.length > this._maxHistory) {
417
+ history.shift()
418
+ this._historyTruncated.set(sessionId, true)
419
+ }
420
+ }
421
+
422
+ /**
423
+ * Shallow-clone and truncate a history entry for serialization.
424
+ * Content/input fields >50KB are truncated to avoid bloated state files.
425
+ * @param {object} entry
426
+ * @returns {object}
427
+ */
428
+ truncateEntry(entry) {
429
+ const MAX = 50 * 1024
430
+ const clone = { ...entry }
431
+ // #5555.3 — `_seq` is per-process server bookkeeping (reassigned 1..N on
432
+ // restore via setHistory), so keep it out of the persisted state file.
433
+ delete clone._seq
434
+ if (typeof clone.content === 'string' && clone.content.length > MAX) {
435
+ clone.content = clone.content.slice(0, MAX) + '[truncated]'
436
+ }
437
+ if (typeof clone.input === 'string' && clone.input.length > MAX) {
438
+ clone.input = clone.input.slice(0, MAX) + '[truncated]'
439
+ }
440
+ return clone
441
+ }
442
+
443
+ /**
444
+ * Auto-label a session from the first user input if it still has a default name.
445
+ * Truncates to ~40 chars at word boundary, appends "..." if truncated.
446
+ * @param {string} sessionId
447
+ * @param {string} text
448
+ * @param {object} sessionEntry - Must have { name, _autoLabeled } properties
449
+ */
450
+ _autoLabelSession(sessionId, text, sessionEntry) {
451
+ if (!sessionEntry) return
452
+ if (sessionEntry._autoLabeled) return
453
+
454
+ // Only rename sessions with default names
455
+ const isDefault = /^(Session \d+|New Session)$/i.test(sessionEntry.name)
456
+ if (!isDefault) return
457
+
458
+ const trimmed = text.trim()
459
+ if (!trimmed) return
460
+
461
+ // Skip attachment-only markers (e.g. "[2 file(s) attached]") — not meaningful labels
462
+ if (/^\[\d+ file\(s\) attached\]$/.test(trimmed)) return
463
+
464
+ sessionEntry._autoLabeled = true
465
+
466
+ const MAX_LEN = 40
467
+ let label
468
+ if (trimmed.length <= MAX_LEN) {
469
+ label = trimmed
470
+ } else {
471
+ const cut = trimmed.lastIndexOf(' ', MAX_LEN)
472
+ label = (cut > 10 ? trimmed.slice(0, cut) : trimmed.slice(0, MAX_LEN)) + '...'
473
+ }
474
+
475
+ sessionEntry.name = label
476
+ log.info(`Auto-labeled session ${sessionId} to "${label}"`)
477
+ this.emit('auto_label', { sessionId, label })
478
+ }
479
+
480
+ /**
481
+ * Remove all history state for a session.
482
+ * @param {string} sessionId
483
+ */
484
+ cleanupSession(sessionId) {
485
+ this._messageHistory.delete(sessionId)
486
+ this._historyTruncated.delete(sessionId)
487
+ this._seqCounters.delete(sessionId)
488
+
489
+ // Clean up pending stream state (composite keys: `${sessionId}:messageId`)
490
+ const prefix = sessionId + ':'
491
+ for (const key of this._pendingStreams.keys()) {
492
+ if (key.startsWith(prefix)) {
493
+ this._pendingStreams.delete(key)
494
+ }
495
+ }
496
+ // #6431 — and any lingering truncation guards for this session
497
+ for (const key of this._truncatedStreams) {
498
+ if (key.startsWith(prefix)) this._truncatedStreams.delete(key)
499
+ }
500
+ }
501
+
502
+ /**
503
+ * Clear all state (used during destroyAll).
504
+ */
505
+ clear() {
506
+ this._messageHistory.clear()
507
+ this._historyTruncated.clear()
508
+ this._pendingStreams.clear()
509
+ this._seqCounters.clear()
510
+ }
511
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Session-preset trust store (#5553).
3
+ *
4
+ * Mirrors the skills trust model (skills-trust.js): a repo-local preset that
5
+ * silently feeds the system prompt is a prompt-injection vector for cloned /
6
+ * collaborative repos. So the first time a repo-local `.chroxy/session.json` is
7
+ * seen — or whenever its content hash CHANGES — the preset is INERT (pending)
8
+ * until an operator approves it. Daemon-side config overrides are pre-trusted
9
+ * (the operator wrote them) and never consult this store.
10
+ *
11
+ * Storage shape (sidecar JSON file next to skills-trust.json):
12
+ *
13
+ * {
14
+ * "presets": {
15
+ * "/abs/path/to/.chroxy/session.json": {
16
+ * "sha256": "<64 hex chars>", // the preset CONTENT hash
17
+ * "firstSeen": "2026-06-11T12:34:56.000Z",
18
+ * "approvedAt": "2026-06-11T12:34:56.000Z"
19
+ * }
20
+ * }
21
+ * }
22
+ *
23
+ * A path is TRUSTED only when its stored `sha256` equals the hash of the
24
+ * currently-resolved preset content. First sight (no record) → pending. A
25
+ * changed hash (record present but differs) → pending again (re-gated). The
26
+ * operator approves the CURRENT hash via `approve(path, hash)`; `revoke(path)`
27
+ * drops the record so the preset goes inert again.
28
+ *
29
+ * Since #5580 the ledger mechanics (load/isTrusted/approve/revoke/getRecord +
30
+ * atomic 0600 persist + fail-open) live in `PathHashTrustLedger`; this class is
31
+ * a thin subclass that pins the `presets` wrapper key and the `approvedAt`
32
+ * timestamp field. The on-disk format is byte-identical to the pre-#5580 file.
33
+ *
34
+ * Persistence safety mirrors SkillsTrustStore: atomic write-via-rename, mode
35
+ * 0600, fail-open on a corrupt/missing file. Failures are non-fatal (best-effort
36
+ * flush) so a read-only $HOME never breaks session creation.
37
+ */
38
+ import { existsSync } from 'fs'
39
+ import { createLogger } from './logger.js'
40
+ import { PathHashTrustLedger } from './path-hash-trust-ledger.js'
41
+ import { DEFAULT_PRESET_TRUST_FILE, _normalizePathKey } from './session-preset.js'
42
+
43
+ const log = createLogger('session-preset-trust')
44
+
45
+ export { DEFAULT_PRESET_TRUST_FILE }
46
+
47
+ /**
48
+ * In-memory + on-disk trust ledger for repo-local session presets. One
49
+ * instance per daemon (constructed by SessionManager); tests pass an explicit
50
+ * `filePath` so they never touch the real ledger.
51
+ */
52
+ export class SessionPresetTrustStore extends PathHashTrustLedger {
53
+ /**
54
+ * @param {{ filePath?: string }} [opts]
55
+ */
56
+ constructor({ filePath } = {}) {
57
+ super({
58
+ filePath: filePath || DEFAULT_PRESET_TRUST_FILE,
59
+ log,
60
+ normalizeKey: _normalizePathKey,
61
+ approvalField: 'approvedAt',
62
+ wrapperKey: 'presets',
63
+ throwOnFlushError: false, // best-effort: a read-only $HOME never breaks session creation
64
+ })
65
+ const loaded = this._loadRecords()
66
+ this._records = loaded.records
67
+ this._dirty = false
68
+ }
69
+ }
70
+
71
+ // Helper so tests can confirm the file existed at one point.
72
+ export function presetTrustFileExists(filePath) {
73
+ try {
74
+ return existsSync(filePath)
75
+ } catch {
76
+ return false
77
+ }
78
+ }