@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,311 @@
1
+ /**
2
+ * PathHashTrustLedger (#5580) — the shared core of chroxy's path-keyed,
3
+ * SHA-256-pinned trust ledgers.
4
+ *
5
+ * Two security surfaces grew the same ledger independently:
6
+ *
7
+ * - SkillsTrustStore (skills-trust.js, #3204): pins the hash of every skill
8
+ * body the loader has seen; a changed hash re-gates (warn / block).
9
+ * - SessionPresetTrustStore (session-preset-trust.js, #5553/#5576): pins the
10
+ * hash of a repo-local `.chroxy/session.json`; a changed hash re-gates the
11
+ * preset to INERT until an operator re-approves.
12
+ *
13
+ * Both store a path → `{ sha256, firstSeen, <approvalTs> }` map under a single
14
+ * top-level wrapper key, both key paths through a case-folding normaliser, both
15
+ * fail OPEN to an empty ledger on a corrupt/missing file (a single bad write
16
+ * must never lock every skill / preset out), and both persist atomically at
17
+ * mode 0600. This base owns exactly that shared mechanism. Everything that
18
+ * genuinely differs is a subclass override:
19
+ *
20
+ * - the third timestamp FIELD NAME (`lastVerified` vs `approvedAt`)
21
+ * - the on-disk WRAPPER key (`skills` vs `presets`) and any sibling indexes
22
+ * (skills' `communityTrust`)
23
+ * - whether `flush()` RE-THROWS a persistence failure (skills — so a handler
24
+ * can surface TRUST_FLUSH_FAILED) or SWALLOWS it (preset — best-effort)
25
+ * - any EXTRAS layered on top (skills' modes, v1→v2 migration, verify-throttle)
26
+ *
27
+ * SAFEST-default policy (per #5580): where the two stores diverged on a SAFETY
28
+ * mechanic, the base defaults to the more defensive variant and lets a subclass
29
+ * opt out explicitly. Concretely:
30
+ *
31
+ * - PERSIST: writes go through a `openSync(tmp, 'wx', 0o600)` + `fsyncSync` +
32
+ * `renameSync` dance with a per-pid + per-call RANDOM temp suffix. The
33
+ * random suffix is the skills variant (#3238) — it survives two writers in
34
+ * the SAME process flushing to the same default ledger path, which the
35
+ * preset store's `pid + Date.now()` suffix could (in principle) collide on
36
+ * within a millisecond. fsync-before-rename is also the skills variant; the
37
+ * preset store had it too, so this is a no-op for preset and a strict
38
+ * safety win as the shared default.
39
+ * - KEY NORMALISATION: each subclass supplies its own `normalizeKey` (skills
40
+ * and preset already share identical case-folding logic but import it from
41
+ * different modules — kept as a hook so neither module's exported
42
+ * `_normalizePathKey` identity changes).
43
+ *
44
+ * On-disk formats are BYTE-COMPATIBLE with the pre-extraction files — existing
45
+ * ledgers load unchanged and re-serialise to the same shape. No migration.
46
+ */
47
+ import { readFileSync } from 'fs'
48
+ import { randomBytes } from 'crypto'
49
+ import { saveJsonState } from './json-state-file.js'
50
+ import { getErrorMessage } from './utils/error-message.js'
51
+ import { HEX64 } from './utils/validation-patterns.js'
52
+
53
+ /**
54
+ * @typedef {Object} TrustRecord
55
+ * @property {string} sha256 64-char lower-case hex digest
56
+ * @property {string} firstSeen ISO timestamp of first sight
57
+ * @property {string} [approvalTs] The third timestamp (named per subclass)
58
+ */
59
+
60
+ export class PathHashTrustLedger {
61
+ /**
62
+ * @param {{
63
+ * filePath: string,
64
+ * log: { warn: Function, info?: Function },
65
+ * normalizeKey: (p: string) => string,
66
+ * approvalField?: string, // name of the third timestamp field (default 'approvedAt')
67
+ * wrapperKey?: string, // on-disk top-level key holding the records map (default 'records')
68
+ * throwOnFlushError?: boolean, // re-throw persistence failures (default false — best-effort)
69
+ * }} opts
70
+ */
71
+ constructor(opts = {}) {
72
+ if (!opts.filePath) throw new Error('PathHashTrustLedger: filePath is required')
73
+ if (!opts.log) throw new Error('PathHashTrustLedger: log is required')
74
+ if (typeof opts.normalizeKey !== 'function') throw new Error('PathHashTrustLedger: normalizeKey is required')
75
+ this._filePath = opts.filePath
76
+ this._log = opts.log
77
+ this._normalizeKey = opts.normalizeKey
78
+ this._approvalField = opts.approvalField || 'approvedAt'
79
+ this._wrapperKey = opts.wrapperKey || 'records'
80
+ this._throwOnFlushError = opts.throwOnFlushError === true
81
+ // Subclasses run their own _load() (which may parse extra sibling indexes
82
+ // and set extra dirty state) — the base does not auto-load so a subclass
83
+ // can wire its constructor in whatever order it needs.
84
+ this._records = Object.create(null)
85
+ this._dirty = false
86
+ }
87
+
88
+ /**
89
+ * Read + parse the ledger's records map, failing open to empty on any error.
90
+ * Returns `{ records, parsed, migratedLegacy }` where:
91
+ * - `records` is the validated, key-normalised path → record map
92
+ * - `parsed` is the raw parsed JSON object (so a subclass can pull sibling
93
+ * indexes like communityTrust out of it) or null on a read/parse failure
94
+ * - `migratedLegacy` is whether a subclass legacy-shape hook claimed the file
95
+ *
96
+ * The records map is sourced from `parsed[wrapperKey]` (v2-style nesting). A
97
+ * subclass that supports a legacy flat-root format overrides `_extractLegacy`
98
+ * to detect + return it (skills v1).
99
+ *
100
+ * @returns {{ records: object, parsed: object|null, migratedLegacy: boolean }}
101
+ * @protected
102
+ */
103
+ _loadRecords() {
104
+ const empty = { records: Object.create(null), parsed: null, migratedLegacy: false }
105
+
106
+ let raw
107
+ try {
108
+ raw = readFileSync(this._filePath, 'utf8')
109
+ } catch (err) {
110
+ if (err && err.code !== 'ENOENT') {
111
+ this._log.warn(`Could not read trust file (${err.code || err.message}); starting fresh`)
112
+ }
113
+ return empty
114
+ }
115
+
116
+ let parsed
117
+ try {
118
+ parsed = JSON.parse(raw)
119
+ } catch (err) {
120
+ this._log.warn(`Trust file is malformed JSON (${getErrorMessage(err, err)}); starting fresh`)
121
+ return empty
122
+ }
123
+
124
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
125
+ this._log.warn('Trust file root is not an object; starting fresh')
126
+ return empty
127
+ }
128
+
129
+ // Locate the records map. v2 nesting under the wrapper key wins; otherwise
130
+ // a subclass legacy hook gets a chance to claim a flat-root format.
131
+ let rawMap = null
132
+ let migratedLegacy = false
133
+ const nested = parsed[this._wrapperKey]
134
+ if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
135
+ rawMap = nested
136
+ } else {
137
+ const legacy = this._extractLegacy(parsed)
138
+ if (legacy && legacy.rawMap) {
139
+ rawMap = legacy.rawMap
140
+ migratedLegacy = legacy.migratedLegacy === true
141
+ } else if (Object.keys(parsed).length === 0) {
142
+ // Empty object — treat as an empty ledger (fresh).
143
+ rawMap = {}
144
+ } else {
145
+ this._log.warn('Trust file has unrecognised shape; starting fresh')
146
+ return empty
147
+ }
148
+ }
149
+
150
+ const records = Object.create(null)
151
+ for (const [key, value] of Object.entries(rawMap)) {
152
+ const rec = this._validateRecord(value)
153
+ if (rec) {
154
+ // Last-writer-wins on key collisions (only possible on a case-folding
155
+ // FS with mixed historical casings); Object.entries is insertion-order.
156
+ records[this._normalizeKey(key)] = rec
157
+ }
158
+ }
159
+ return { records, parsed, migratedLegacy }
160
+ }
161
+
162
+ /**
163
+ * Validate + coerce a single on-disk record. Drops any record that lacks a
164
+ * valid sha256 + firstSeen. The third timestamp falls back to firstSeen when
165
+ * missing/malformed (matches both stores' self-heal behaviour).
166
+ *
167
+ * @param {unknown} value
168
+ * @returns {TrustRecord|null}
169
+ * @protected
170
+ */
171
+ _validateRecord(value) {
172
+ if (
173
+ value && typeof value === 'object'
174
+ && typeof value.sha256 === 'string' && HEX64.test(value.sha256)
175
+ && typeof value.firstSeen === 'string'
176
+ ) {
177
+ const approval = typeof value[this._approvalField] === 'string'
178
+ ? value[this._approvalField]
179
+ : value.firstSeen
180
+ return {
181
+ sha256: value.sha256,
182
+ firstSeen: value.firstSeen,
183
+ [this._approvalField]: approval,
184
+ }
185
+ }
186
+ return null
187
+ }
188
+
189
+ /**
190
+ * Legacy-shape hook. Base returns null (no legacy format). A subclass that
191
+ * supports a flat-root legacy file (skills v1) overrides this to detect it and
192
+ * return `{ rawMap, migratedLegacy: true }`.
193
+ *
194
+ * @param {object} _parsed
195
+ * @returns {{ rawMap: object, migratedLegacy: boolean }|null}
196
+ * @protected
197
+ */
198
+ _extractLegacy(_parsed) {
199
+ return null
200
+ }
201
+
202
+ /**
203
+ * Is the path at `absPath` currently trusted for content hash `hash`?
204
+ * True only when a record exists AND its sha256 equals `hash`.
205
+ *
206
+ * @param {string} absPath
207
+ * @param {string} hash
208
+ * @returns {boolean}
209
+ */
210
+ isTrusted(absPath, hash) {
211
+ if (typeof absPath !== 'string' || typeof hash !== 'string') return false
212
+ const rec = this._records[this._normalizeKey(absPath)]
213
+ return !!rec && rec.sha256 === hash
214
+ }
215
+
216
+ /**
217
+ * Read-only clone of the stored record (or null). Lets a dashboard render
218
+ * firstSeen / the approval timestamp without mutating ledger state.
219
+ *
220
+ * @param {string} absPath
221
+ * @returns {TrustRecord|null}
222
+ */
223
+ getRecord(absPath) {
224
+ const rec = this._records[this._normalizeKey(absPath)]
225
+ if (!rec) return null
226
+ return {
227
+ sha256: rec.sha256,
228
+ firstSeen: rec.firstSeen,
229
+ [this._approvalField]: rec[this._approvalField],
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Approve `hash` for `absPath`: records (or refreshes) the entry, preserving
235
+ * the original firstSeen, and stamps the approval timestamp to now. Persists
236
+ * synchronously so the grant survives a crash. Rejects a non-hex hash.
237
+ *
238
+ * @param {string} absPath
239
+ * @param {string} hash
240
+ * @returns {boolean} true when the grant was recorded
241
+ */
242
+ approve(absPath, hash) {
243
+ if (typeof absPath !== 'string' || !absPath) return false
244
+ if (typeof hash !== 'string' || !HEX64.test(hash)) return false
245
+ const key = this._normalizeKey(absPath)
246
+ const now = new Date().toISOString()
247
+ const existing = this._records[key]
248
+ this._records[key] = {
249
+ sha256: hash,
250
+ firstSeen: existing && typeof existing.firstSeen === 'string' ? existing.firstSeen : now,
251
+ [this._approvalField]: now,
252
+ }
253
+ this._dirty = true
254
+ this.flush()
255
+ return true
256
+ }
257
+
258
+ /**
259
+ * Revoke `absPath` — drops the record so the path goes inert again. Persists
260
+ * synchronously.
261
+ *
262
+ * @param {string} absPath
263
+ * @returns {boolean} true when a record was removed
264
+ */
265
+ revoke(absPath) {
266
+ if (typeof absPath !== 'string' || !absPath) return false
267
+ const key = this._normalizeKey(absPath)
268
+ if (!this._records[key]) return false
269
+ delete this._records[key]
270
+ this._dirty = true
271
+ this.flush()
272
+ return true
273
+ }
274
+
275
+ /**
276
+ * Serialise the in-memory ledger to the on-disk shape. A subclass overrides
277
+ * this to wrap the records map in its top-level key and emit any sibling
278
+ * indexes. The base wraps the records map under `wrapperKey`.
279
+ *
280
+ * @returns {object} the object to JSON.stringify
281
+ * @protected
282
+ */
283
+ _serialize() {
284
+ const map = {}
285
+ for (const [k, v] of Object.entries(this._records)) map[k] = v
286
+ return { [this._wrapperKey]: map }
287
+ }
288
+
289
+ /**
290
+ * Persist the ledger to disk. No-op when clean. Delegates to the shared
291
+ * durable-write seam (`saveJsonState({ fsync: true })`, #5620) — atomic
292
+ * via-rename + 0600, fsync before rename, with a per-pid + random temp suffix
293
+ * (the safest variant — tolerates concurrent writers in the same process,
294
+ * #3238). The seam owns the fd/temp cleanup; this layer only adds the dirty
295
+ * gate + the warn / conditional re-throw policy.
296
+ *
297
+ * On failure: either re-throw (subclass set `throwOnFlushError`) or swallow
298
+ * with a warn. `_dirty` stays set on failure so a later flush retries.
299
+ */
300
+ flush() {
301
+ if (!this._dirty) return
302
+ const tmpSuffix = `.${process.pid}.${randomBytes(6).toString('hex')}.tmp`
303
+ try {
304
+ saveJsonState(this._filePath, this._serialize(), { fsync: true, tmpSuffix })
305
+ this._dirty = false
306
+ } catch (err) {
307
+ this._log.warn(`Could not persist trust file (${err && err.code ? err.code : err.message || err})`)
308
+ if (this._throwOnFlushError) throw err
309
+ }
310
+ }
311
+ }
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Per-session settings registry (#4664).
3
+ *
4
+ * Collapses the boilerplate around the per-session toggle pattern that
5
+ * promptEvaluator (#3185), chroxyContextHint (#3805), and sessionPreamble
6
+ * (#4660) each hand-wrote across SessionManager (createSession forwarding +
7
+ * serializeState + restoreState) and settings-handlers.js (WS handler +
8
+ * broadcast + immediate persist).
9
+ *
10
+ * Three iterations in, the next addition (snippet library, sticky visible
11
+ * prefix in the issue body) would be the 4th time someone hand-writes the
12
+ * same 5 sites and risks dropping the jsonl-subprocess middle layer (see
13
+ * memory `[[feedback_jsonl_subprocess_middle_layer]]`).
14
+ *
15
+ * Scope of this module:
16
+ *
17
+ * - `definePerSessionSetting()` — declarative shape per knob.
18
+ * - `PER_SESSION_SETTINGS` — registry of the three existing knobs.
19
+ * - `forwardPerSessionSettingsToProviderOpts()` — used by
20
+ * SessionManager.createSession to feed providerOpts.
21
+ * - `serializePerSessionSettings()` / `restorePerSessionSettings()` —
22
+ * used by SessionManager.serializeState / restoreState so adding a
23
+ * new knob takes ONE registry entry instead of a 3-site edit.
24
+ * - `buildPerSessionSettingHandler()` — generates the WS handler
25
+ * function for a setting (replaces the three near-identical 50-LOC
26
+ * handlers in settings-handlers.js).
27
+ *
28
+ * Out of scope (intentionally — keeps the refactor narrow):
29
+ *
30
+ * - BaseSession field declarations + `_coerceXxxOpt()` validators +
31
+ * `setX()` setters: each knob still hand-writes these on BaseSession
32
+ * so the existing tests + `_buildSystemPrompt()` ordering stay
33
+ * byte-identical. The registry references the setter by NAME so the
34
+ * handler factory calls `session[setterName](value)` — see
35
+ * `buildPerSessionSettingHandler`.
36
+ * - Provider middle layers (cli-session, sdk-session, claude-tui-session,
37
+ * codex-session, gemini-session, jsonl-subprocess-session) still
38
+ * destructure each opt and forward to `super({...})`. The list of opt
39
+ * keys per provider is small and stable; the issue note about
40
+ * "...opts everywhere" matches the byok/deepseek pattern but
41
+ * reworking every provider's signature is a bigger refactor than the
42
+ * issue warrants. Adding `[id]` to that list per provider is a
43
+ * mechanical lift if/when a new knob lands.
44
+ * - Dashboard side: still requires the Zustand action +
45
+ * `message-handler.ts` entry + `store/types.ts` field. The capability
46
+ * gate / per-knob UI shape (text area vs checkbox) means a single
47
+ * dashboard helper would over-fit; the README in #4664 calls this
48
+ * out as "document the checklist" instead of "abstract."
49
+ */
50
+
51
+ import { createLogger } from './logger.js'
52
+ import { resolveSessionOrError, requireSessionMethod, sendSessionError } from './handler-utils.js'
53
+
54
+ const log = createLogger('per-session-settings')
55
+
56
+ const REQUIRED_DEFINITION_KEYS = [
57
+ 'id',
58
+ 'defaultValue',
59
+ 'coerce',
60
+ 'acceptFromWire',
61
+ 'acceptFromConstructor',
62
+ 'requestType',
63
+ 'broadcastType',
64
+ 'setterName',
65
+ 'handlerInvalidValueMessage',
66
+ 'handlerUnsupportedMessage',
67
+ ]
68
+
69
+ /**
70
+ * Define a per-session setting. Returns a frozen object that the helpers
71
+ * below iterate.
72
+ *
73
+ * @param {object} opts
74
+ * @param {string} opts.id — field name on the session AND key on the
75
+ * serialized state file. Must match the BaseSession field declaration
76
+ * (e.g. `'promptEvaluator'`).
77
+ * @param {boolean|string} opts.defaultValue — value when the field is
78
+ * unset on a session (used by serializePerSessionSettings's read-back
79
+ * guard so a custom provider that skips BaseSession's initialiser still
80
+ * round-trips a valid wire shape).
81
+ * @param {(v: any) => any} opts.coerce — applied to the session field
82
+ * when serialising. For booleans: `(v) => !!v`. For strings: a coerce
83
+ * that returns `''` for non-string values.
84
+ * @param {(v: any) => boolean} opts.acceptFromWire — predicate gating
85
+ * forwarding into `providerOpts` in `createSession`. Reject is silent —
86
+ * BaseSession's constructor coerce will apply its own default. Mirrors
87
+ * the existing `typeof x === 'boolean'` / `typeof x === 'string'`
88
+ * guards at the createSession call site.
89
+ * @param {(v: any) => boolean} opts.acceptFromConstructor — predicate
90
+ * gating restoration from the state file. Same shape as
91
+ * `acceptFromWire` but kept separate so a future setting could relax
92
+ * either side independently (e.g. accept wider shapes during
93
+ * restore for forward-compat).
94
+ * @param {string} opts.requestType — wire message `type` field (e.g.
95
+ * `'set_prompt_evaluator'`).
96
+ * @param {string} opts.broadcastType — wire broadcast `type` field (e.g.
97
+ * `'prompt_evaluator_changed'`).
98
+ * @param {string} opts.setterName — method name to call on the session
99
+ * when applying the update. The setter MUST return `true` when state
100
+ * changed, `false` for redundant / rejected updates. This is the
101
+ * existing BaseSession setter contract — handlers branch on it to
102
+ * decide whether to broadcast.
103
+ * @param {string} opts.handlerInvalidValueMessage — user-facing error
104
+ * for malformed payloads.
105
+ * @param {string} opts.handlerUnsupportedMessage — user-facing error
106
+ * when the session lacks the setter (defensive — every shipping
107
+ * provider extends BaseSession, so this only fires for custom
108
+ * providers).
109
+ * @returns {Readonly<object>}
110
+ */
111
+ export function definePerSessionSetting(opts) {
112
+ for (const k of REQUIRED_DEFINITION_KEYS) {
113
+ // `defaultValue: false` is legal — the check is "key present" not "truthy".
114
+ if (!(k in opts)) {
115
+ throw new Error(`definePerSessionSetting: missing required field '${k}'`)
116
+ }
117
+ }
118
+ return Object.freeze({
119
+ id: opts.id,
120
+ defaultValue: opts.defaultValue,
121
+ coerce: opts.coerce,
122
+ acceptFromWire: opts.acceptFromWire,
123
+ acceptFromConstructor: opts.acceptFromConstructor,
124
+ requestType: opts.requestType,
125
+ broadcastType: opts.broadcastType,
126
+ setterName: opts.setterName,
127
+ handlerInvalidValueMessage: opts.handlerInvalidValueMessage,
128
+ handlerUnsupportedMessage: opts.handlerUnsupportedMessage,
129
+ })
130
+ }
131
+
132
+ // --- Concrete settings -------------------------------------------------------
133
+
134
+ /**
135
+ * `promptEvaluator` (#3185): boolean toggle for the auto-evaluator chain.
136
+ * Default `false` so the manual `evaluate_draft` flow (PR #3089) is the
137
+ * only behaviour until the operator opts in.
138
+ */
139
+ const promptEvaluatorDef = definePerSessionSetting({
140
+ id: 'promptEvaluator',
141
+ defaultValue: false,
142
+ coerce: (v) => !!v,
143
+ acceptFromWire: (v) => typeof v === 'boolean',
144
+ acceptFromConstructor: (v) => typeof v === 'boolean',
145
+ requestType: 'set_prompt_evaluator',
146
+ broadcastType: 'prompt_evaluator_changed',
147
+ setterName: 'setPromptEvaluator',
148
+ handlerInvalidValueMessage: 'set_prompt_evaluator requires a boolean `value`',
149
+ handlerUnsupportedMessage: 'This provider does not support promptEvaluator toggling',
150
+ })
151
+
152
+ /**
153
+ * `chroxyContextHint` (#3805): boolean toggle for the canned Chroxy
154
+ * context paragraph prepended to the system prompt so the model can
155
+ * adjust output for mobile clients. Default `false` — existing users
156
+ * see no observable change.
157
+ */
158
+ const chroxyContextHintDef = definePerSessionSetting({
159
+ id: 'chroxyContextHint',
160
+ defaultValue: false,
161
+ coerce: (v) => !!v,
162
+ acceptFromWire: (v) => typeof v === 'boolean',
163
+ acceptFromConstructor: (v) => typeof v === 'boolean',
164
+ requestType: 'set_chroxy_context_hint',
165
+ broadcastType: 'chroxy_context_hint_changed',
166
+ setterName: 'setChroxyContextHint',
167
+ handlerInvalidValueMessage: 'set_chroxy_context_hint requires a boolean `value`',
168
+ handlerUnsupportedMessage: 'This provider does not support chroxyContextHint toggling',
169
+ })
170
+
171
+ /**
172
+ * `sessionPreamble` (#4660): user-authored free text prepended to the
173
+ * system prompt every turn. Empty string is the OFF default — non-string
174
+ * inputs coerce to '' so a hand-edited state file with a number / object
175
+ * round-trips safely.
176
+ */
177
+ const sessionPreambleDef = definePerSessionSetting({
178
+ id: 'sessionPreamble',
179
+ defaultValue: '',
180
+ // The actual trim + length cap lives in BaseSession's
181
+ // `_coerceSessionPreambleOpt` so the wire-level cap stays the single
182
+ // source of truth. The coerce here is only used by
183
+ // serializePerSessionSettings — at that point the field has already
184
+ // been through BaseSession's coerce, so we only defend against the
185
+ // custom-provider case (no field initialiser).
186
+ coerce: (v) => (typeof v === 'string' ? v : ''),
187
+ acceptFromWire: (v) => typeof v === 'string',
188
+ acceptFromConstructor: (v) => typeof v === 'string',
189
+ requestType: 'set_session_preamble',
190
+ broadcastType: 'session_preamble_changed',
191
+ setterName: 'setSessionPreamble',
192
+ handlerInvalidValueMessage: 'set_session_preamble requires a string `value`',
193
+ handlerUnsupportedMessage: 'This provider does not support sessionPreamble',
194
+ })
195
+
196
+ /**
197
+ * Registry of every per-session setting. Order is the order in which
198
+ * fields appear on the wire payload (alphabetical here so a future
199
+ * `git diff` is predictable). New knobs MUST be added in alphabetical
200
+ * order so review diffs stay tight.
201
+ */
202
+ export const PER_SESSION_SETTINGS = Object.freeze([
203
+ chroxyContextHintDef,
204
+ promptEvaluatorDef,
205
+ sessionPreambleDef,
206
+ ])
207
+
208
+ // --- SessionManager helpers --------------------------------------------------
209
+
210
+ /**
211
+ * Forward each registered setting from `source` (a destructured opts
212
+ * object — typically `createSession` arguments) into `providerOpts` when
213
+ * the setting's `acceptFromWire` predicate accepts. Mirrors the per-knob
214
+ * `if (typeof x === 'boolean') providerOpts.x = x` shape at the
215
+ * createSession call site.
216
+ *
217
+ * Mutates `providerOpts` and returns it for chaining.
218
+ *
219
+ * @param {object} providerOpts — target object passed to the provider constructor
220
+ * @param {object} source — object containing per-session-setting values keyed by id
221
+ * @returns {object} the same `providerOpts`
222
+ */
223
+ export function forwardPerSessionSettingsToProviderOpts(providerOpts, source) {
224
+ for (const def of PER_SESSION_SETTINGS) {
225
+ if (!Object.prototype.hasOwnProperty.call(source, def.id)) continue
226
+ const value = source[def.id]
227
+ if (def.acceptFromWire(value)) {
228
+ providerOpts[def.id] = value
229
+ }
230
+ // Reject is silent — BaseSession's coerce applies the default. This
231
+ // matches the existing per-knob behaviour exactly: passing
232
+ // `{ chroxyContextHint: 'not-bool' }` to createSession drops the key,
233
+ // and BaseSession initialises the field to `false`.
234
+ }
235
+ return providerOpts
236
+ }
237
+
238
+ /**
239
+ * Build the serialized per-session-settings dict for `serializeState`.
240
+ * Each value falls back to the setting's `defaultValue` when the session
241
+ * field is `undefined` (custom provider that skipped BaseSession's field
242
+ * initialiser, or a hand-edited state file), then runs through `coerce`
243
+ * to guarantee a wire-shape match (`boolean` for toggles, `string` for
244
+ * preamble). This mirrors the defensive guards the pre-refactor per-knob
245
+ * sites used (`!!entry.session.chroxyContextHint`,
246
+ * `typeof entry.session.sessionPreamble === 'string' ? ... : ''`) while
247
+ * giving `defaultValue` a single observable purpose (Copilot review on
248
+ * PR #4751).
249
+ *
250
+ * @param {object} session — a session instance (BaseSession subclass)
251
+ * @returns {Record<string, any>} — dict ready to spread into the state-file entry
252
+ */
253
+ export function serializePerSessionSettings(session) {
254
+ const out = {}
255
+ for (const def of PER_SESSION_SETTINGS) {
256
+ const raw = session[def.id]
257
+ const seed = raw === undefined ? def.defaultValue : raw
258
+ out[def.id] = def.coerce(seed)
259
+ }
260
+ return out
261
+ }
262
+
263
+ /**
264
+ * Build the createSession-arguments dict for `restoreState`. Each value
265
+ * is either forwarded as-is when `acceptFromConstructor` accepts, or
266
+ * `undefined` (so `forwardPerSessionSettingsToProviderOpts` skips it and
267
+ * BaseSession's constructor coerce applies the default).
268
+ *
269
+ * `undefined` (not `null`) is deliberate — `null` would survive the
270
+ * acceptFromConstructor predicate's `typeof` check on some shapes and
271
+ * land in providerOpts as a real value; `undefined` is the universal
272
+ * "key absent" signal that mirrors the pre-refactor per-knob code.
273
+ *
274
+ * @param {object} saved — entry from `state.sessions[i]` in the state file
275
+ * @returns {Record<string, any|undefined>}
276
+ */
277
+ export function restorePerSessionSettings(saved) {
278
+ const out = {}
279
+ for (const def of PER_SESSION_SETTINGS) {
280
+ const value = saved?.[def.id]
281
+ if (def.acceptFromConstructor(value)) {
282
+ // sessionPreamble special case: empty string is the OFF default —
283
+ // forward it so a session that the user explicitly cleared
284
+ // round-trips as cleared rather than as the BaseSession default
285
+ // (which happens to be the same value, but the explicit-forward is
286
+ // clearer and matches the pre-refactor behaviour). For string
287
+ // settings with a non-empty default this also matters.
288
+ out[def.id] = value
289
+ } else {
290
+ out[def.id] = undefined
291
+ }
292
+ }
293
+ return out
294
+ }
295
+
296
+ // --- WS handler factory ------------------------------------------------------
297
+
298
+ /**
299
+ * Build the WS handler function for a per-session setting. Replaces the
300
+ * three near-identical 50-line handlers in settings-handlers.js with one
301
+ * factory call per knob.
302
+ *
303
+ * The handler:
304
+ * 1. Validates the inbound payload with `def.acceptFromWire`.
305
+ * 2. Resolves the bound session (via the standard handler-utils path).
306
+ * 3. Calls `session[def.setterName](value)`.
307
+ * 4. On a real change (setter returns true): broadcasts
308
+ * `{ type: def.broadcastType, sessionId, value }` to all session
309
+ * clients AND triggers an immediate `serializeState()` flush.
310
+ *
311
+ * Persistence is an immediate flush rather than the debounced
312
+ * `schedulePersist` so a crash within the debounce window doesn't
313
+ * silently lose the change — matches the existing per-knob behaviour.
314
+ *
315
+ * @param {object} settingDef — definition from definePerSessionSetting
316
+ * @returns {(ws: any, client: any, msg: any, ctx: any) => void}
317
+ */
318
+ export function buildPerSessionSettingHandler(settingDef) {
319
+ return function perSessionSettingHandler(ws, client, msg, ctx) {
320
+ if (!settingDef.acceptFromWire(msg?.value)) {
321
+ sendSessionError(ws, ctx, settingDef.handlerInvalidValueMessage)
322
+ return
323
+ }
324
+
325
+ const sessionId = msg?.sessionId || client?.activeSessionId
326
+ // Use the same resolveSessionOrError path every other settings handler
327
+ // uses — it enforces session-token binding for bound clients and falls
328
+ // back to `client.activeSessionId` otherwise. Calling
329
+ // `ctx.sessions.sessionManager.getSession(sessionId)` directly here would
330
+ // bypass that gate.
331
+ const entry = resolveSessionOrError(ws, ctx, msg, client)
332
+ if (!entry) return
333
+
334
+ // Defensive — every shipping provider extends BaseSession which adds
335
+ // the setter. A custom provider that bypasses BaseSession would land
336
+ // here; refuse rather than silently dropping the update.
337
+ if (!requireSessionMethod(ws, ctx, entry, settingDef.setterName, settingDef.handlerUnsupportedMessage)) {
338
+ return
339
+ }
340
+ const setter = entry.session[settingDef.setterName]
341
+
342
+ const changed = setter.call(entry.session, msg.value)
343
+ if (!changed) {
344
+ // Setter no-op (redundant set, type-rejected at setter, or a
345
+ // string that trims to the same stored value). No broadcast, no
346
+ // persist — the dashboard already shows the current value.
347
+ return
348
+ }
349
+
350
+ // Surface the STORED value (BaseSession coerces trim + cap), not the
351
+ // raw payload, so subscribed clients see a stable shape.
352
+ const storedValue = entry.session[settingDef.id]
353
+ ctx.transport.broadcastToSession(sessionId, {
354
+ type: settingDef.broadcastType,
355
+ sessionId,
356
+ value: storedValue,
357
+ })
358
+
359
+ try {
360
+ ctx.sessions.sessionManager?.serializeState?.()
361
+ } catch (err) {
362
+ log.warn(`Failed to persist ${settingDef.id} for ${sessionId}: ${err?.message || err}`)
363
+ }
364
+ }
365
+ }
366
+