@chroxy/server 0.10.0 → 0.11.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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -2,16 +2,24 @@
2
2
  * Conversation, history, and cost summary handlers.
3
3
  *
4
4
  * Handles: list_conversations, search_conversations, resume_conversation,
5
- * request_full_history, request_session_context, request_cost_summary
5
+ * request_conversation_transcript, request_full_history,
6
+ * request_session_context, request_cost_summary
6
7
  */
8
+ import { realpathSync } from 'fs'
7
9
  import { scanConversations as defaultScanConversations } from '../conversation-scanner.js'
8
10
  import { searchConversations as defaultSearchConversations } from '../conversation-search.js'
11
+ import { resolveJsonlPath, readConversationHistoryAsync as defaultReadConversationHistoryAsync } from '../jsonl-reader.js'
9
12
  import { validateCwdAllowed, broadcastFocusChanged, resolveSession, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError } from '../handler-utils.js'
10
13
  import { scopeConversationsToClient } from '../conversation-scope.js'
11
14
  import { createLogger, loggerForSession } from '../logger.js'
12
15
 
13
16
  const log = createLogger('ws')
14
17
 
18
+ // UUID v4-ish shape guard shared by resume_conversation and the read-only
19
+ // transcript handler — rejects anything that isn't a canonical conversation id
20
+ // before it reaches the filesystem, closing path-traversal via the id segment.
21
+ const CONVERSATION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
22
+
15
23
  async function handleListConversations(ws, client, msg, ctx) {
16
24
  // ctx.scanConversations override allows tests to inject a stub and skip real fs.
17
25
  const scan = ctx.scanConversations || defaultScanConversations
@@ -76,7 +84,7 @@ async function handleResumeConversation(ws, client, msg, ctx) {
76
84
  return
77
85
  }
78
86
  // Validate conversationId is a UUID to prevent path traversal
79
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(conversationId)) {
87
+ if (!CONVERSATION_ID_RE.test(conversationId)) {
80
88
  sendSessionError(ws, ctx, 'Invalid conversationId format')
81
89
  return
82
90
  }
@@ -109,6 +117,122 @@ async function handleResumeConversation(ws, client, msg, ctx) {
109
117
  }
110
118
  }
111
119
 
120
+ /**
121
+ * Read-only transcript endpoint (#6860, epic #6765).
122
+ *
123
+ * Streams a CLOSED conversation's full history back to the requesting client
124
+ * straight off the persisted store (the Claude Code CLI JSONL layer under
125
+ * `~/.claude/projects/`) — WITHOUT calling `createSession` or spawning any
126
+ * provider process. Because it reads persisted bytes rather than driving a live
127
+ * process, it works uniformly for every provider, including those whose
128
+ * `capabilities.resume === false` (BYOK, Codex, Gemini, user-shell) for which
129
+ * `resume_conversation` is refused outright.
130
+ *
131
+ * Access follows the same cwd-scoping as `list_conversations`/`search_conversations`
132
+ * (`scopeConversationsToClient`): an UNBOUND client (primary token / dashboard)
133
+ * may read any conversation; a BOUND pairing-issued client may only read
134
+ * conversations recorded under its bound session's cwd — anything else is
135
+ * rejected. This mirrors bearer-token-authority.md: read-only history is the
136
+ * same authority class as other session-state reads.
137
+ *
138
+ * The response reuses the existing `history_replay_start` / `message` /
139
+ * `history_replay_end` server→client frames (identical to `handleRequestFullHistory`,
140
+ * only sourced from disk) so clients render it with their existing renderers.
141
+ * The replay frames carry the `conversationId` in the `sessionId` field — there
142
+ * is no live session, and a resumed session always gets a fresh id distinct from
143
+ * the conversationId, so this cannot collide with or clobber a live session's
144
+ * transcript.
145
+ */
146
+ async function handleRequestConversationTranscript(ws, client, msg, ctx) {
147
+ const { conversationId } = msg
148
+ if (!conversationId || typeof conversationId !== 'string') {
149
+ sendSessionError(ws, ctx, 'Missing conversationId')
150
+ return
151
+ }
152
+ // UUID guard — path-traversal protection (same gate as resume_conversation).
153
+ if (!CONVERSATION_ID_RE.test(conversationId)) {
154
+ sendSessionError(ws, ctx, 'Invalid conversationId format')
155
+ return
156
+ }
157
+
158
+ // Resolve the conversation's recorded cwd authoritatively from the persisted
159
+ // store (the scanner reads the same JSONL layer list_conversations does). Only
160
+ // fall back to a client-provided cwd hint when the scan can't find it (e.g. a
161
+ // tiny conversation below the scanner's MIN_FILE_SIZE floor).
162
+ const scan = ctx.scanConversations || defaultScanConversations
163
+ let conv = null
164
+ try {
165
+ const scanOpts = ctx.runtime.projectsDirs ? { projectsDirs: ctx.runtime.projectsDirs } : {}
166
+ const all = await scan(scanOpts)
167
+ conv = Array.isArray(all) ? all.find((c) => c?.conversationId === conversationId) || null : null
168
+ } catch (err) {
169
+ // Scan failure is non-fatal — fall through to the client-provided cwd hint.
170
+ log.warn(`Transcript scan failed for ${conversationId}: ${err.message}`)
171
+ }
172
+
173
+ let cwd = conv?.cwd || null
174
+ if (!cwd && typeof msg.cwd === 'string' && msg.cwd) {
175
+ // Client-supplied fallback: validate it against the same path hygiene the
176
+ // create/resume paths enforce before trusting it to resolve a filesystem path.
177
+ const cwdError = validateCwdAllowed(msg.cwd, ctx.services.config)
178
+ if (cwdError) {
179
+ sendSessionError(ws, ctx, cwdError)
180
+ return
181
+ }
182
+ // Defense-in-depth: validateCwdAllowed already resolved + vetted the realpath
183
+ // but discarded it. Canonicalize ONCE here and reuse the resolved path for
184
+ // BOTH the scope check and the on-disk read, so a symlinked hint can't point
185
+ // the scope check at one directory and the file read at another.
186
+ try {
187
+ cwd = realpathSync(msg.cwd)
188
+ } catch {
189
+ sendSessionError(ws, ctx, `Cannot resolve path: ${msg.cwd}`)
190
+ return
191
+ }
192
+ }
193
+
194
+ if (!cwd) {
195
+ sendSessionError(ws, ctx, `Conversation not found: ${conversationId}`)
196
+ return
197
+ }
198
+
199
+ // Scope enforcement — reuse the guard list_conversations/search_conversations
200
+ // use. A bound client that can't see this cwd gets an empty set → reject.
201
+ const scoped = scopeConversationsToClient([{ conversationId, cwd }], client, ctx)
202
+ if (scoped.length === 0) {
203
+ sendSessionError(ws, ctx, 'Not authorized to view this conversation')
204
+ return
205
+ }
206
+
207
+ // Read the transcript from disk. NO createSession, NO provider spawn. Reader is
208
+ // injectable for tests so the suite never touches the real ~/.claude/projects.
209
+ const readTranscript = ctx.readConversationTranscript || defaultReadConversationHistoryAsync
210
+ let messages = []
211
+ try {
212
+ messages = await readTranscript(resolveJsonlPath(cwd, conversationId))
213
+ } catch (err) {
214
+ // A read error is graceful — surface an empty transcript rather than a crash.
215
+ log.warn(`Failed to read transcript for ${conversationId}: ${err.message}`)
216
+ messages = []
217
+ }
218
+
219
+ // Stream back using the SAME wire shape as request_full_history so existing
220
+ // renderers light up. `sessionId` carries the conversationId (read-only; no
221
+ // live session exists for a closed conversation).
222
+ ctx.transport.send(ws, { type: 'history_replay_start', sessionId: conversationId, fullHistory: true, conversationId })
223
+ for (const entry of messages) {
224
+ ctx.transport.send(ws, {
225
+ type: 'message',
226
+ messageType: entry.type,
227
+ content: entry.content,
228
+ tool: entry.tool,
229
+ timestamp: entry.timestamp,
230
+ sessionId: conversationId,
231
+ })
232
+ }
233
+ ctx.transport.send(ws, { type: 'history_replay_end', sessionId: conversationId })
234
+ }
235
+
112
236
  async function handleRequestFullHistory(ws, client, msg, ctx) {
113
237
  const targetId = (typeof msg.sessionId === 'string' && msg.sessionId) || client.activeSessionId
114
238
  if (!targetId || !resolveSession(ctx, msg, client)) {
@@ -195,6 +319,7 @@ export const conversationHandlers = {
195
319
  list_conversations: handleListConversations,
196
320
  search_conversations: handleSearchConversations,
197
321
  resume_conversation: handleResumeConversation,
322
+ request_conversation_transcript: handleRequestConversationTranscript,
198
323
  request_full_history: handleRequestFullHistory,
199
324
  request_session_context: handleRequestSessionContext,
200
325
  request_cost_summary: handleRequestCostSummary,
@@ -116,19 +116,42 @@ function handleByokSetCredentials(ws, client, msg, ctx) {
116
116
 
117
117
  function handleByokClearCredentials(ws, client, msg, ctx) {
118
118
  if (rejectCredentialWriteIfBound(ws, client, msg, ctx)) return
119
+ let outcome
119
120
  try {
120
121
  // Remove only the Anthropic key from the canonical store — siblings (and
121
122
  // the encrypted envelope) survive; the file is unlinked only when empty.
122
- deleteStoredCredential('ANTHROPIC_API_KEY')
123
+ //
124
+ // #7062: durable. An operator clears a BYOK key precisely because they
125
+ // believe it leaked — a clear that is acked but still in the OS writeback
126
+ // window can restore the leaked key on the next start after a power loss.
127
+ outcome = deleteStoredCredential('ANTHROPIC_API_KEY', { durable: true })
123
128
  } catch (err) {
124
129
  sendError(ws, msg?.requestId, 'CREDENTIALS_CLEAR_FAILED', err?.message || 'clear failed', undefined, ctx)
125
130
  return
126
131
  }
132
+ // The reply is the success status: the key IS cleared. Reporting a failure for
133
+ // a clear that landed would send the operator to re-clear an already-cleared key.
127
134
  const status = getAnthropicApiKeyStatus()
128
135
  ctx.transport.send(ws, { type: 'byok_credentials_status', requestId: msg?.requestId, ...status })
129
136
  if (typeof ctx.transport.broadcast === 'function') {
130
137
  ctx.transport.broadcast({ type: 'byok_credentials_status', ...status })
131
138
  }
139
+ if (outcome?.durabilityUnconfirmed) {
140
+ // ...but the operator still learns the fsync failed. Deliberately requestId-LESS,
141
+ // mirroring the webhook clear: the status above is this request's reply, and a
142
+ // client correlating an error to its in-flight requestId must not read this as
143
+ // the clear's verdict.
144
+ sendError(
145
+ ws,
146
+ null,
147
+ 'CREDENTIAL_DELETE_DURABILITY_UNCONFIRMED',
148
+ 'The API key is cleared, but the filesystem could not confirm the removal is durable ' +
149
+ `(${outcome.durabilityUnconfirmed}) — a power loss could restore the cleared key. ` +
150
+ 'Resolve the storage error, then re-check the stored credentials after the next restart.',
151
+ undefined,
152
+ ctx,
153
+ )
154
+ }
132
155
  }
133
156
 
134
157
  /**
@@ -201,13 +224,31 @@ function handleDeleteCredential(ws, client, msg, ctx) {
201
224
  sendError(ws, msg?.requestId, 'INVALID_REQUEST', `Unknown credential key: ${key}`, undefined, ctx)
202
225
  return
203
226
  }
227
+ let outcome
204
228
  try {
205
- deleteStoredCredential(key)
229
+ // #7062: durable — see handleByokClearCredentials for the reasoning. A
230
+ // deleted provider key that comes back after a power loss is exactly the
231
+ // failure the operator was trying to prevent.
232
+ outcome = deleteStoredCredential(key, { durable: true })
206
233
  } catch (err) {
207
234
  sendError(ws, msg?.requestId, 'CREDENTIAL_CLEAR_FAILED', err?.message || 'clear failed', undefined, ctx)
208
235
  return
209
236
  }
237
+ // The reply is the success status: the key IS deleted.
210
238
  _sendCredentialsStatus(ctx, ws, msg?.requestId)
239
+ if (outcome?.durabilityUnconfirmed) {
240
+ // requestId-LESS, for the same reason as the clear path above.
241
+ sendError(
242
+ ws,
243
+ null,
244
+ 'CREDENTIAL_DELETE_DURABILITY_UNCONFIRMED',
245
+ `The ${key} credential is deleted, but the filesystem could not confirm the removal is durable ` +
246
+ `(${outcome.durabilityUnconfirmed}) — a power loss could restore the deleted key. ` +
247
+ 'Resolve the storage error, then re-check the stored credentials after the next restart.',
248
+ undefined,
249
+ ctx,
250
+ )
251
+ }
211
252
  }
212
253
 
213
254
  async function handleTestCredential(ws, client, msg, ctx) {
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Handles: list_directory, browse_files, list_files, read_file, write_file,
5
5
  * get_diff, git_status, git_branches, git_stage, git_unstage,
6
- * git_commit, list_slash_commands, list_agents
6
+ * git_commit, git_create_pr, list_slash_commands, list_agents
7
7
  */
8
8
  import { resolveSession, sendError } from '../handler-utils.js'
9
9
  import { loggerForSession } from '../logger.js'
@@ -58,7 +58,12 @@ function handleBrowseFiles(ws, client, msg, ctx) {
58
58
  function handleListFiles(ws, client, msg, ctx) {
59
59
  const sid = msg.sessionId || client.activeSessionId
60
60
  const entry = resolveSession(ctx, msg, client)
61
- ctx.services.fileOps.listFiles(ws, entry?.cwd || null, msg.query || null, sid)
61
+ // #6823: BYOK sessions surface their connected MCP servers' resources in the
62
+ // same `@`-picker data source. Other providers return no resources here.
63
+ const mcpResources = typeof entry?.session?.getMcpResources === 'function'
64
+ ? entry.session.getMcpResources()
65
+ : []
66
+ ctx.services.fileOps.listFiles(ws, entry?.cwd || null, msg.query || null, sid, mcpResources)
62
67
  }
63
68
 
64
69
  function handleReadFile(ws, client, msg, ctx) {
@@ -74,6 +79,23 @@ function handleWriteFile(ws, client, msg, ctx) {
74
79
  ctx.services.fileOps.writeFile(ws, msg.path, msg.content, entry?.cwd || null)
75
80
  }
76
81
 
82
+ function handleAppendMemory(ws, client, msg, ctx) {
83
+ // #6861 — `#`-prefix composer quick-append. Same mutation gate as write_file:
84
+ // a bound (share-a-session) token cannot append to the host's CLAUDE.md.
85
+ if (rejectMutationIfBound(ws, client, msg, ctx, 'append_memory')) return
86
+ const entry = resolveSession(ctx, msg, client)
87
+ ctx.services.fileOps.appendMemory(ws, msg.text, entry?.cwd || null)
88
+ }
89
+
90
+ function handleMemoryRead(ws, client, msg, ctx) {
91
+ // #6864 (epic #6760) — server read of the effective merged CLAUDE.md memory
92
+ // stack (global/project/local + @imports) plus the auto-generated
93
+ // MEMORY.md descriptor. Read-only: no mutation gate needed (a bound/
94
+ // share-a-session client may read memory, matching read_file/get_diff).
95
+ const entry = resolveSession(ctx, msg, client)
96
+ ctx.services.fileOps.readMemory(ws, entry?.cwd || null, msg.requestId)
97
+ }
98
+
77
99
  function handleGetDiff(ws, client, msg, ctx) {
78
100
  const entry = resolveSession(ctx, msg, client)
79
101
  ctx.services.fileOps.getDiff(ws, msg.base, entry?.cwd || null)
@@ -107,6 +129,19 @@ function handleGitCommit(ws, client, msg, ctx) {
107
129
  ctx.services.fileOps.gitCommit(ws, msg.message, entry?.cwd || null)
108
130
  }
109
131
 
132
+ function handleGitCreatePr(ws, client, msg, ctx) {
133
+ // #6876 — same pairing-bound mutation gate as stage/commit: opening a PR
134
+ // pushes a branch + creates a remote PR, a host-level side effect a bound
135
+ // (share-a-session) token must not reach.
136
+ if (rejectMutationIfBound(ws, client, msg, ctx, 'git_create_pr')) return
137
+ const entry = resolveSession(ctx, msg, client)
138
+ ctx.services.fileOps.gitCreatePR(
139
+ ws,
140
+ { title: msg.title, body: msg.body, base: msg.base, draft: msg.draft },
141
+ entry?.cwd || null,
142
+ )
143
+ }
144
+
110
145
  function handleListSlashCommands(ws, client, msg, ctx) {
111
146
  const sid = msg.sessionId || client.activeSessionId
112
147
  const entry = resolveSession(ctx, msg, client)
@@ -115,7 +150,13 @@ function handleListSlashCommands(ws, client, msg, ctx) {
115
150
  // Falls back to null in legacy single-cliSession mode — built-ins simply
116
151
  // don't surface there (safe default; project/user .md skills still work).
117
152
  const provider = entry?.provider || null
118
- ctx.services.fileOps.listSlashCommands(ws, entry?.cwd || null, sid, provider)
153
+ // #6823: merge the session's MCP-server prompts (`/mcp__<server>__<prompt>`)
154
+ // into the slash-command surface. Only BYOK sessions expose the accessor;
155
+ // other providers fall back to an empty list.
156
+ const mcpPrompts = typeof entry?.session?.getMcpPromptCommands === 'function'
157
+ ? entry.session.getMcpPromptCommands()
158
+ : []
159
+ ctx.services.fileOps.listSlashCommands(ws, entry?.cwd || null, sid, provider, mcpPrompts)
119
160
  }
120
161
 
121
162
  function handleListAgents(ws, client, msg, ctx) {
@@ -131,12 +172,15 @@ export const fileHandlers = {
131
172
  list_files: handleListFiles,
132
173
  read_file: handleReadFile,
133
174
  write_file: handleWriteFile,
175
+ append_memory: handleAppendMemory,
176
+ memory_read: handleMemoryRead,
134
177
  get_diff: handleGetDiff,
135
178
  git_status: handleGitStatus,
136
179
  git_branches: handleGitBranches,
137
180
  git_stage: handleGitStage,
138
181
  git_unstage: handleGitUnstage,
139
182
  git_commit: handleGitCommit,
183
+ git_create_pr: handleGitCreatePr,
140
184
  list_slash_commands: handleListSlashCommands,
141
185
  list_agents: handleListAgents,
142
186
  }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * GitHub webhook-secret config handlers (#6540, item 3 of #6536).
3
+ *
4
+ * The Control Room repo-events feed's ingest (github-webhook.js) is inert until
5
+ * an operator sets a webhook secret and points a GitHub webhook at
6
+ * `POST /api/github/webhook`. These handlers let that be configured from the
7
+ * dashboard instead of an env var / CLI:
8
+ *
9
+ * - github_webhook_config_request — read the current config (is a secret set +
10
+ * source, the payload URL to paste into GitHub, recent delivery status). Open
11
+ * to any authenticated client (the reply is value-free), like
12
+ * get_credentials_status.
13
+ * - github_webhook_set_secret — set / rotate the secret (host-authority
14
+ * gated).
15
+ * - github_webhook_clear_secret — clear the stored secret (host-authority
16
+ * gated).
17
+ *
18
+ * SECURITY: the secret is HMAC key material. It is stored ENCRYPTED AT REST in
19
+ * the OS-keychain-backed credentials store (never plaintext config.json), and is
20
+ * NEVER echoed back — the reply carries only whether a secret is configured. The
21
+ * WRITE handlers are host-authority gated exactly like the provider-credential
22
+ * writes (`rejectCredentialWriteIfBound`, #5155): a pairing-bound
23
+ * (share-a-session) token can read the value-free config but cannot set/rotate or
24
+ * clear the host webhook secret. See docs/security/bearer-token-authority.md §4.
25
+ */
26
+ import { sendError } from '../handler-utils.js'
27
+ import { setStoredField, deleteStoredField } from '../credential-store.js'
28
+ import {
29
+ WEBHOOK_SECRET_FIELD,
30
+ RECOMMENDED_WEBHOOK_EVENTS,
31
+ webhookSecretSource,
32
+ } from '../github-webhook.js'
33
+ import { loggerForSession } from '../logger.js'
34
+
35
+ const EMPTY_DELIVERIES = Object.freeze({
36
+ total: 0,
37
+ verified: 0,
38
+ rejected: 0,
39
+ lastAt: null,
40
+ lastResult: null,
41
+ lastKind: null,
42
+ })
43
+
44
+ /** Minimum accepted secret length (after trim) — a weak/typo'd secret weakens the HMAC. */
45
+ const MIN_SECRET_LENGTH = 8
46
+
47
+ /**
48
+ * #6540: gate webhook-secret WRITES behind host-level authority, mirroring the
49
+ * provider-credential `rejectCredentialWriteIfBound` (#5155). The webhook secret
50
+ * is host-wide HMAC key material — a pairing-bound (share-a-session) token can
51
+ * read the value-free config but must not be able to swap in a secret it controls
52
+ * or clear it (integrity / DoS). Only an unbound client (the primary token or an
53
+ * unbound linking-mode pairing token, both with `boundSessionId` unset) may write.
54
+ *
55
+ * Returns true and sends the rejection if the client is bound (caller early-returns);
56
+ * false to proceed. See docs/security/bearer-token-authority.md.
57
+ */
58
+ function rejectWebhookSecretWriteIfBound(ws, client, msg, ctx) {
59
+ if (!client?.boundSessionId) return false
60
+ loggerForSession('ws', client.boundSessionId).warn(
61
+ `Client ${client.id} (bound to ${client.boundSessionId}) attempted to modify the GitHub webhook secret — rejected`,
62
+ )
63
+ sendError(ws, msg?.requestId, 'WEBHOOK_SECRET_WRITE_FORBIDDEN_BOUND_CLIENT',
64
+ 'Pairing-issued session tokens cannot modify the GitHub webhook secret. Use the primary API token from a device with physical access to this machine.', undefined, ctx)
65
+ return true
66
+ }
67
+
68
+ /**
69
+ * Build the value-free `github_webhook_config` reply. Assembles the secret
70
+ * source (store / env / none — via `webhookSecretSource`, which reads the store
71
+ * but never the value), the derived payload URL (`ctx.services.webhookPayloadUrl`),
72
+ * and the recent-delivery readout (`ctx.services.repoWebhookDeliveries`). The
73
+ * secret value is never part of this object.
74
+ */
75
+ function buildWebhookConfig(ctx, requestId) {
76
+ const source = webhookSecretSource()
77
+ const payload = ctx?.services?.webhookPayloadUrl || { url: null, lanOnly: false, note: null }
78
+ const ring = ctx?.services?.repoWebhookDeliveries
79
+ const deliveries = ring && typeof ring.summary === 'function' ? ring.summary() : { ...EMPTY_DELIVERIES }
80
+ return {
81
+ type: 'github_webhook_config',
82
+ requestId: requestId ?? null,
83
+ generatedAt: new Date().toISOString(),
84
+ configured: source !== 'none',
85
+ source,
86
+ payloadUrl: typeof payload.url === 'string' ? payload.url : null,
87
+ lanOnly: Boolean(payload.lanOnly),
88
+ note: payload.note ?? null,
89
+ recommendedEvents: [...RECOMMENDED_WEBHOOK_EVENTS],
90
+ deliveries,
91
+ }
92
+ }
93
+
94
+ function sendWebhookConfig(ws, ctx, requestId) {
95
+ ctx.transport.send(ws, buildWebhookConfig(ctx, requestId))
96
+ }
97
+
98
+ function handleGithubWebhookConfigRequest(ws, client, msg, ctx) {
99
+ sendWebhookConfig(ws, ctx, msg?.requestId)
100
+ }
101
+
102
+ function handleGithubWebhookSetSecret(ws, client, msg, ctx) {
103
+ if (rejectWebhookSecretWriteIfBound(ws, client, msg, ctx)) return
104
+ const secret = typeof msg?.secret === 'string' ? msg.secret.trim() : ''
105
+ if (secret.length === 0) {
106
+ sendError(ws, msg?.requestId, 'INVALID_REQUEST', 'secret is required', undefined, ctx)
107
+ return
108
+ }
109
+ if (secret.length < MIN_SECRET_LENGTH) {
110
+ sendError(ws, msg?.requestId, 'INVALID_REQUEST', `secret must be at least ${MIN_SECRET_LENGTH} characters`, undefined, ctx)
111
+ return
112
+ }
113
+ let outcome
114
+ try {
115
+ // Encrypt-at-rest aware, atomic 0600 write into the credentials store — never
116
+ // plaintext config.json. err.message is validation/file-mode text, never the value.
117
+ //
118
+ // #6964: `durable: true` — this is credential ROTATION of a secret SHARED with
119
+ // GitHub. The operator gets a success ack and then re-points the GitHub webhook
120
+ // at the new secret, so losing the write to a power loss inside the OS writeback
121
+ // window would leave the daemon verifying deliveries with the old secret and
122
+ // rejecting every real one. A THROW here means nothing was published (the write
123
+ // itself failed, or its PRE-rename fsync did) — the old secret still stands, so
124
+ // report WEBHOOK_SECRET_WRITE_FAILED and do not touch the cache.
125
+ outcome = setStoredField(WEBHOOK_SECRET_FIELD, secret, { durable: true })
126
+ } catch (err) {
127
+ sendError(ws, msg?.requestId, 'WEBHOOK_SECRET_WRITE_FAILED', err?.message || 'write failed', undefined, ctx)
128
+ return
129
+ }
130
+ // Update the in-process hot cache so live webhook deliveries pick up the new
131
+ // secret without a keychain re-read (and so a rotate never serves the stale
132
+ // lazily-cached value). Guarded — a minimal test ctx may omit it.
133
+ //
134
+ // This runs for `outcome.durabilityUnconfirmed` too, and must: that outcome means
135
+ // the new secret IS live on disk and only the durability of the rename is unproven.
136
+ // Skipping it would leave the running daemon verifying deliveries with the OLD
137
+ // secret while the NEW one is what a restart loads — a silent, delayed outage.
138
+ if (typeof ctx?.services?.setWebhookSecretCache === 'function') {
139
+ ctx.services.setWebhookSecretCache(secret)
140
+ }
141
+ // The reply is the success config: the rotation took effect. Reporting a failure
142
+ // for a write that landed would send the operator to re-point GitHub back at the
143
+ // old secret that the daemon no longer accepts.
144
+ sendWebhookConfig(ws, ctx, msg?.requestId)
145
+ if (outcome?.durabilityUnconfirmed) {
146
+ // ...but the operator still learns the fsync failed. Deliberately requestId-LESS:
147
+ // the config above is this request's reply, and a client correlating an error to
148
+ // its in-flight requestId must not read this as the rotation's verdict.
149
+ sendError(
150
+ ws,
151
+ null,
152
+ 'WEBHOOK_SECRET_DURABILITY_UNCONFIRMED',
153
+ 'The new webhook secret is saved and live, but the filesystem could not confirm the write is durable ' +
154
+ `(${outcome.durabilityUnconfirmed}) — a power loss could roll the rotation back. ` +
155
+ 'Resolve the storage error, then re-check the configured secret after the next restart.',
156
+ undefined,
157
+ ctx,
158
+ )
159
+ }
160
+ }
161
+
162
+ function handleGithubWebhookClearSecret(ws, client, msg, ctx) {
163
+ if (rejectWebhookSecretWriteIfBound(ws, client, msg, ctx)) return
164
+ let outcome
165
+ try {
166
+ // #7056: durable, for the same reason the rotation is. An operator clears a
167
+ // shared secret precisely because they believe it leaked — a clear that is
168
+ // acked but still sitting in the OS writeback window can restore the leaked
169
+ // value on the next start after a power loss.
170
+ outcome = deleteStoredField(WEBHOOK_SECRET_FIELD, { durable: true })
171
+ } catch (err) {
172
+ sendError(ws, msg?.requestId, 'WEBHOOK_SECRET_CLEAR_FAILED', err?.message || 'clear failed', undefined, ctx)
173
+ return
174
+ }
175
+ // Drop the hot cache so the next delivery re-resolves (store now empty → env or none).
176
+ if (typeof ctx?.services?.setWebhookSecretCache === 'function') {
177
+ ctx.services.setWebhookSecretCache(null)
178
+ }
179
+ // The reply is the success config: the secret IS cleared. Reporting a failure for
180
+ // a clear that landed would send the operator to re-clear an already-cleared value.
181
+ sendWebhookConfig(ws, ctx, msg?.requestId)
182
+ if (outcome?.durabilityUnconfirmed) {
183
+ // ...but the operator still learns the fsync failed. Deliberately requestId-LESS,
184
+ // mirroring the rotation path: the config above is this request's reply, and a
185
+ // client correlating an error to its in-flight requestId must not read this as
186
+ // the clear's verdict.
187
+ sendError(
188
+ ws,
189
+ null,
190
+ 'WEBHOOK_SECRET_DURABILITY_UNCONFIRMED',
191
+ 'The webhook secret is cleared, but the filesystem could not confirm the removal is durable ' +
192
+ `(${outcome.durabilityUnconfirmed}) — a power loss could restore the cleared secret. ` +
193
+ 'Resolve the storage error, then re-check the configured secret after the next restart.',
194
+ undefined,
195
+ ctx,
196
+ )
197
+ }
198
+ }
199
+
200
+ export const githubWebhookHandlers = {
201
+ github_webhook_config_request: handleGithubWebhookConfigRequest,
202
+ github_webhook_set_secret: handleGithubWebhookSetSecret,
203
+ github_webhook_clear_secret: handleGithubWebhookClearSecret,
204
+ }
@@ -323,6 +323,10 @@ async function handleInput(ws, client, msg, ctx) {
323
323
  cwd: entry.cwd,
324
324
  description: trimmed.slice(0, 100),
325
325
  messageCount: ctx.sessions.sessionManager.getHistoryCount(targetSessionId),
326
+ // #6766: capture the fork boundary (last assistant transcript UUID of the
327
+ // turn that just ended) so restoring this pre-turn checkpoint can truncate
328
+ // the conversation to here. Undefined on providers that don't track it.
329
+ boundaryMessageId: entry.session.lastMessageUuid,
326
330
  }).catch((err) => log.warn(`Auto-checkpoint failed: ${err.message}`))
327
331
  }
328
332
  // Adopt the sender's clientMessageId if present and well-formed; otherwise