@chroxy/server 0.11.10 → 0.11.11

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 (153) hide show
  1. package/CONFIG.md +4 -2
  2. package/package.json +3 -3
  3. package/src/acp-session.js +5 -1
  4. package/src/agent-connections.js +12 -1
  5. package/src/agent-control/client.js +29 -0
  6. package/src/agent-control/events.js +8 -4
  7. package/src/agent-control/local-connection.js +34 -16
  8. package/src/agent-control/mcp-server.js +2 -0
  9. package/src/anthropic-compatible-config.js +1 -0
  10. package/src/anthropic-gemini-shim.js +444 -0
  11. package/src/anthropic-gemini-translate.js +1030 -0
  12. package/src/base-session.js +319 -2
  13. package/src/bound-client-policy.js +12 -0
  14. package/src/byok-mcp-config.js +9 -5
  15. package/src/byok-mcp-trust.js +34 -20
  16. package/src/byok-session.js +62 -9
  17. package/src/byok-tool-executor.js +81 -1
  18. package/src/claude-setting-sources.js +74 -0
  19. package/src/claude-tui/pty-driver.js +5 -1
  20. package/src/claude-tui/usage-limit.js +2 -2
  21. package/src/claude-tui-session.js +57 -4
  22. package/src/cli/agent-cmd.js +236 -0
  23. package/src/cli/connection-state.js +54 -0
  24. package/src/cli/freshness-cmd.js +53 -0
  25. package/src/cli/pages-cmd.js +6 -4
  26. package/src/cli/pair-code-cmd.js +7 -6
  27. package/src/cli/pair-discord-cmd.js +7 -6
  28. package/src/cli/schedule-cmd.js +25 -3
  29. package/src/cli/server-cmd.js +6 -0
  30. package/src/cli/shell-cmd.js +7 -4
  31. package/src/cli/status-cmd.js +19 -5
  32. package/src/cli-session.js +190 -11
  33. package/src/cli.js +4 -0
  34. package/src/codex-app-server-session.js +78 -17
  35. package/src/codex-error-text.js +114 -0
  36. package/src/config-dir-migration.js +11 -6
  37. package/src/config.js +23 -3
  38. package/src/connection-info.js +73 -14
  39. package/src/continuations.js +153 -40
  40. package/src/conversation-scanner.js +2 -21
  41. package/src/conversation-search.js +4 -17
  42. package/src/dev-preview.js +2 -1
  43. package/src/docker-session.js +10 -1
  44. package/src/doctor.js +14 -3
  45. package/src/durable-write.js +35 -0
  46. package/src/environments/authority.js +7 -1
  47. package/src/event-normalizer.js +35 -2
  48. package/src/folder-trust-wire.js +137 -0
  49. package/src/folder-trust-worker.js +17 -0
  50. package/src/folder-trust.js +1572 -0
  51. package/src/freshness/activity-meter.js +101 -0
  52. package/src/freshness/adapter.js +199 -0
  53. package/src/freshness/checks.js +239 -0
  54. package/src/freshness/config.js +98 -0
  55. package/src/freshness/core.js +185 -0
  56. package/src/freshness/derive.js +680 -0
  57. package/src/freshness/exchange.js +305 -0
  58. package/src/freshness/file-ledger.js +400 -0
  59. package/src/freshness/grade.js +81 -0
  60. package/src/freshness/hash.js +45 -0
  61. package/src/freshness/inbox.js +163 -0
  62. package/src/freshness/index.js +20 -0
  63. package/src/freshness/investigation.js +474 -0
  64. package/src/freshness/keys.js +177 -0
  65. package/src/freshness/ledger.js +122 -0
  66. package/src/freshness/outbox.js +131 -0
  67. package/src/freshness/policy.js +599 -0
  68. package/src/freshness/queue.js +843 -0
  69. package/src/freshness/read-errors.js +23 -0
  70. package/src/freshness/render.js +153 -0
  71. package/src/freshness/runtime.js +113 -0
  72. package/src/freshness/session-registry-adapter.js +161 -0
  73. package/src/freshness/state-file-adapter.js +167 -0
  74. package/src/freshness-runner/build-info.js +139 -0
  75. package/src/freshness-runner/cli.js +105 -0
  76. package/src/freshness-runner/run-tick.js +109 -0
  77. package/src/freshness-runner/stamp.js +57 -0
  78. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  79. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  80. package/src/freshness-sources/index.js +8 -0
  81. package/src/gemini-byok-session.js +292 -0
  82. package/src/gemini-credentials.js +67 -0
  83. package/src/gemini-key-safety.js +246 -0
  84. package/src/gemini-models.js +386 -0
  85. package/src/handler-utils.js +6 -13
  86. package/src/handlers/checkpoint-handlers.js +8 -0
  87. package/src/handlers/folder-trust-handlers.js +90 -0
  88. package/src/handlers/input-handlers.js +40 -11
  89. package/src/handlers/principal-admin-handlers.js +229 -0
  90. package/src/handlers/principal-handlers.js +262 -0
  91. package/src/handlers/scheduler-handlers.js +4 -4
  92. package/src/handlers/session-handlers.js +10 -1
  93. package/src/handlers/settings-handlers.js +42 -8
  94. package/src/handlers/skills-handlers.js +7 -0
  95. package/src/history-page.js +8 -0
  96. package/src/jsonl-reader.js +90 -10
  97. package/src/jsonl-subprocess-session.js +4 -1
  98. package/src/logger.js +105 -15
  99. package/src/mailbox-route.js +102 -0
  100. package/src/notification-prefs.js +15 -0
  101. package/src/orchestration/orchestration-manager.js +38 -9
  102. package/src/orchestration/permission-gate.js +4 -1
  103. package/src/orchestration/run-record.js +11 -0
  104. package/src/orchestration/turn-driver.js +151 -33
  105. package/src/orphan-reaper.js +77 -20
  106. package/src/outgoing-policy.js +10 -4
  107. package/src/permission-floor.js +54 -2
  108. package/src/permission-manager.js +32 -13
  109. package/src/permission-resolved-by.js +89 -0
  110. package/src/permission-resolver.js +7 -3
  111. package/src/platform.js +156 -4
  112. package/src/principal-audit.js +189 -0
  113. package/src/principal-binding.js +25 -0
  114. package/src/principal-brakes.js +21 -0
  115. package/src/principal-effect.js +101 -0
  116. package/src/principal-journal.js +905 -0
  117. package/src/principal-kill-switch.js +183 -0
  118. package/src/principal-label.js +5 -0
  119. package/src/principal-pending-permissions.js +177 -0
  120. package/src/principal-policy.js +1094 -0
  121. package/src/principal-sessions-snapshot.js +208 -0
  122. package/src/principal-store.js +488 -0
  123. package/src/principal-subscriptions.js +283 -0
  124. package/src/providers.js +2 -0
  125. package/src/redaction.js +181 -22
  126. package/src/scheduled-task-store.js +12 -0
  127. package/src/scheduler.js +304 -17
  128. package/src/sdk-session.js +60 -7
  129. package/src/server-cli/push-notification-handler.js +6 -1
  130. package/src/server-cli.js +30 -1
  131. package/src/session-ci-watcher.js +210 -37
  132. package/src/session-manager.js +590 -19
  133. package/src/session-message-history.js +121 -2
  134. package/src/session-name-allocator.js +685 -0
  135. package/src/statusline.js +78 -19
  136. package/src/summarize-session.js +2 -0
  137. package/src/turn-outcome.js +5 -2
  138. package/src/utils/argv-safety.js +29 -0
  139. package/src/utils/binary-package-manifest.js +57 -15
  140. package/src/utils/bounded-regex-worker.js +4 -0
  141. package/src/utils/bounded-regex.js +16 -7
  142. package/src/utils/pid-liveness.js +47 -0
  143. package/src/web-task-manager.js +45 -4
  144. package/src/worktree-gc.js +195 -4
  145. package/src/ws-auth.js +103 -19
  146. package/src/ws-broadcaster.js +39 -7
  147. package/src/ws-client-manager.js +8 -0
  148. package/src/ws-file-ops/browser.js +35 -3
  149. package/src/ws-forwarding.js +23 -3
  150. package/src/ws-handler-context.js +18 -0
  151. package/src/ws-history.js +79 -12
  152. package/src/ws-message-handlers.js +10 -2
  153. package/src/ws-server.js +253 -13
@@ -2,7 +2,7 @@ import { readdir, stat, realpath } from 'fs/promises'
2
2
  import { readContainedBytes } from './utils/regular-file.js'
3
3
  import { join, basename } from 'path'
4
4
  import { claudeProjectsDir } from './utils/claude-config-dir.js'
5
- import { decodeProjectPath } from './jsonl-reader.js'
5
+ import { decodeProjectPath, isTypedPromptString, promptPreview } from './jsonl-reader.js'
6
6
  import { runWithConcurrency } from './utils/concurrency.js'
7
7
 
8
8
  const MIN_FILE_SIZE = 100
@@ -26,7 +26,8 @@ export function extractSearchableText(entry) {
26
26
  if (entry.message?.content) {
27
27
  const content = entry.message.content
28
28
  if (typeof content === 'string') {
29
- parts.push(content)
29
+ // A user string no person typed (wrapper, meta, sidechain) is not searchable (#9363)
30
+ if (entry.type !== 'user' || isTypedPromptString(entry, content)) parts.push(content)
30
31
  } else if (Array.isArray(content)) {
31
32
  for (const block of content) {
32
33
  if (block.type === 'text' && block.text) {
@@ -79,21 +80,7 @@ async function searchFile(filePath, queryLower, conversationId, projectName, dec
79
80
  }
80
81
 
81
82
  // Extract preview from first user message
82
- if (!preview && entry.type === 'user') {
83
- const content = entry.message?.content
84
- if (typeof content === 'string') {
85
- preview = content.slice(0, 200)
86
- } else if (Array.isArray(content)) {
87
- const hasToolResult = content.some((b) => b.type === 'tool_result')
88
- if (!hasToolResult) {
89
- const textParts = content
90
- .filter((b) => b.type === 'text')
91
- .map((b) => b.text)
92
- .join('\n')
93
- if (textParts) preview = textParts.slice(0, 200)
94
- }
95
- }
96
- }
83
+ if (!preview) preview = promptPreview(entry)
97
84
 
98
85
  const searchable = extractSearchableText(entry)
99
86
  if (!searchable) continue
@@ -1,6 +1,7 @@
1
1
  import { EventEmitter } from 'node:events'
2
2
  import { buildPermissionRequestMessage } from '@chroxy/protocol'
3
3
  import { PermissionManager } from './permission-manager.js'
4
+ import { normalizeResolvedBy } from './permission-resolved-by.js'
4
5
  import { PreviewTunnelAdapter } from './tunnel/preview.js'
5
6
  import { assertPreviewPort, pinPreviewTarget, createPinnedPreviewProxy } from './preview-target.js'
6
7
  import { createLogger } from './logger.js'
@@ -60,7 +61,7 @@ export class DevPreviewManager extends EventEmitter {
60
61
  request.permissions = permissions
61
62
  permissions.on('permission_request', data => send(buildPermissionRequestMessage({ ...data, sessionId })))
62
63
  permissions.on('permission_resolved', data => {
63
- send({ type: 'permission_resolved', sessionId, ...data })
64
+ send({ type: 'permission_resolved', sessionId, ...data, resolvedBy: normalizeResolvedBy(data.resolvedBy) })
64
65
  if (data.decision !== 'allow') this._status(request, data.reason === 'user' ? 'denied' : 'cancelled', data.reason === 'timeout' ? 'Consent expired; request a new preview' : data.reason === 'user' ? 'Preview consent denied' : request.endReason || 'Preview request cancelled')
65
66
  })
66
67
  request.pin = await this._pinTarget({ port, cwd: session.cwd, signal: request.controller.signal })
@@ -528,6 +528,8 @@ export class DockerSession extends CliSession {
528
528
  this._rl = rl
529
529
 
530
530
  rl.on('line', (line) => {
531
+ // #9267: a retired client's late output must not reach the session.
532
+ if (this._child !== child) return
531
533
  if (!line.trim()) return
532
534
  let data
533
535
  try {
@@ -548,6 +550,7 @@ export class DockerSession extends CliSession {
548
550
  })
549
551
 
550
552
  child.on('error', (err) => {
553
+ if (this._child !== child) return // #9267: a retired client's error is not the fresh one's
551
554
  this._cleanupReadlines()
552
555
  this._processReady = false
553
556
  this._child = null
@@ -557,7 +560,13 @@ export class DockerSession extends CliSession {
557
560
  this._scheduleRespawn()
558
561
  })
559
562
 
560
- child.on('close', (code) => this._handleChildClose(code))
563
+ child.on('close', (code) => {
564
+ // #9267: the same identity guard the host provider has. A client the Stop timer
565
+ // retired closes AFTER a fresh one may be running; its close must not clear the
566
+ // fresh child's readlines, null `_child` or schedule a respawn.
567
+ if (this._child !== child) return
568
+ this._handleChildClose(code)
569
+ })
561
570
 
562
571
  this._processReady = true
563
572
  log.info('Container exec started, ready for messages')
package/src/doctor.js CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  billingClassForProvider,
25
25
  billingDetailForClass,
26
26
  isProgrammaticCreditEra,
27
+ programmaticCreditEraEnabled,
27
28
  PROGRAMMATIC_CREDIT_ERA_START,
28
29
  } from './billing-class.js'
29
30
  import { checkDependencies } from './utils/check-dependencies.js'
@@ -955,15 +956,25 @@ export async function runDoctorChecks({
955
956
  status: 'pass',
956
957
  message: `Default provider '${effectiveDefault}' — ${detail}`,
957
958
  })
958
- } else {
959
- // Pre-cutover: nothing meters yet, but surface the upcoming boundary and
960
- // what the default will bill once it lands.
959
+ } else if (programmaticCreditEraEnabled()) {
960
+ // Operator declared the era but the announced instant is still ahead:
961
+ // surface the upcoming boundary and what the default will bill once it
962
+ // lands.
961
963
  const cutover = new Date(PROGRAMMATIC_CREDIT_ERA_START).toISOString().slice(0, 10)
962
964
  checks.push({
963
965
  name: 'Billing',
964
966
  status: 'pass',
965
967
  message: `Default provider '${effectiveDefault}' — ${detail}. Programmatic-credit cutover: ${cutover}.`,
966
968
  })
969
+ } else {
970
+ // Era flag off (the default): the announced 2026-06-15 cutover was paused
971
+ // and never took effect (#7333), so naming that date would announce a
972
+ // change that is not scheduled. Say nothing about it (#8278).
973
+ checks.push({
974
+ name: 'Billing',
975
+ status: 'pass',
976
+ message: `Default provider '${effectiveDefault}' — ${detail}`,
977
+ })
967
978
  }
968
979
  }
969
980
 
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The one durable-write helper (agent-principals contract §5.4, §6.6, §10.2).
3
+ *
4
+ * "Durable" here is the standard `_flushPersistConfirmedDurable`
5
+ * (session-manager.js) uses: write a temp file, fsync the file, rename it over the
6
+ * destination, fsync the DIRECTORY. `writeFileRestricted` (platform.js) already is
7
+ * exactly that recipe when asked for `durable: true` (it also keeps the 0600 mode and
8
+ * the Windows write-through rename), so this module is a thin, named wrapper rather
9
+ * than a second implementation. What it adds is the VERDICT the principal-store
10
+ * callers act on:
11
+ *
12
+ * - `{ durable: true }` the file is live and its directory entry is fsynced.
13
+ * - `{ durable: false }` the file is live but the directory fsync failed
14
+ * (`unconfirmed` carries the reason). A caller must not tell
15
+ * the operator the write is durable.
16
+ * - a throw nothing was published (the temp write, the file fsync or the
17
+ * rename failed); the temp file is removed.
18
+ *
19
+ * The temp name carries the pid and random bytes, so a stale or planted sidecar at a
20
+ * fixed name is never reused, and two writes in one process never share one.
21
+ */
22
+ import { randomBytes } from 'node:crypto'
23
+ import { writeFileRestricted } from './platform.js'
24
+
25
+ /**
26
+ * @param {string} filePath
27
+ * @param {string} data
28
+ * @param {object} [seams] test seams passed to `writeFileRestricted` (`_fsync`, `_rename`)
29
+ * @returns {{ durable: boolean, unconfirmed: string|null }}
30
+ */
31
+ export function writeDurableFile(filePath, data, seams = {}) {
32
+ const tmpSuffix = `.${process.pid}.${randomBytes(6).toString('hex')}.tmp`
33
+ const { durabilityUnconfirmed } = writeFileRestricted(filePath, data, { ...seams, tmpSuffix, durable: true, strict: true })
34
+ return { durable: durabilityUnconfirmed == null, unconfirmed: durabilityUnconfirmed ?? null }
35
+ }
@@ -34,7 +34,10 @@
34
34
  * so `''` and any real id are bound; a nullish client is bound too.
35
35
  */
36
36
  export function isBoundClient(client) {
37
- return !client || client.boundSessionId != null
37
+ // #9116: an agent principal is never a host client. It also carries a sentinel
38
+ // `boundSessionId`, but this clause does not depend on that binding: a principal is
39
+ // bound whatever its binding field says (fail-safe, the same shape as `== null`).
40
+ return !client || client.boundSessionId != null || client.principal != null
38
41
  }
39
42
 
40
43
  /**
@@ -57,6 +60,9 @@ export function isBoundToOtherSession(client, sessionId) {
57
60
  * binding on the recipient is a binding, and matches no unscoped peer.
58
61
  */
59
62
  export function canSeePeer(recipient, peer) {
63
+ // #9116: a principal is told of no peer at all (not even another principal that shares
64
+ // its sentinel binding).
65
+ if (recipient?.principal != null) return false
60
66
  if (!isBoundClient(recipient)) return true
61
67
  const own = recipient?.boundSessionId
62
68
  return typeof own === 'string' && own.length > 0 && peer?.boundSessionId === own
@@ -6,7 +6,9 @@ import { buildPermissionRequestMessage, MAX_SANE_DURATION_MS } from '@chroxy/pro
6
6
  import { boundedNonNegInt, boundedThinkingPrecedes, buildMessageWire, buildErrorWire } from './message-wire.js'
7
7
  import { turnOutcomeField } from './turn-outcome.js'
8
8
  import { permissionScope } from './permission-scope.js'
9
+ import { resolvedByField } from './permission-resolved-by.js'
9
10
  import { buildThinkingLevelChanged } from './thinking-level-wire.js'
11
+ import { buildFolderTrustStateMessageIfCached, folderTrustFrameApplies } from './folder-trust-wire.js'
10
12
 
11
13
  const log = createLogger('event-normalizer')
12
14
 
@@ -86,6 +88,18 @@ function backgroundTaskFields(ctx) {
86
88
  }
87
89
  }
88
90
 
91
+ /**
92
+ * The payload of a relayed subagent event. A nested `permission_resolved` has its `resolvedBy`
93
+ * rebuilt (#9119) on a copy, so nothing but the class (and an agent's label) can ride the
94
+ * relay; every other payload stays verbatim.
95
+ */
96
+ function nestedPayload(data) {
97
+ const payload = data.payload ?? {}
98
+ if (data.type !== 'permission_resolved' || payload === null || typeof payload !== 'object' || !('resolvedBy' in payload)) return payload
99
+ const { resolvedBy, ...rest } = payload
100
+ return { ...rest, ...resolvedByField(resolvedBy) }
101
+ }
102
+
89
103
  const EVENT_MAP = Object.create(null)
90
104
  Object.assign(EVENT_MAP, {
91
105
  ready: (data, ctx) => {
@@ -93,6 +107,7 @@ Object.assign(EVENT_MAP, {
93
107
  // reconnect mid-orchestration doesn't present the session as fully idle.
94
108
  const bgFields = backgroundTaskFields(ctx)
95
109
  const messages = [{ msg: { type: 'claude_ready', ...(bgFields || {}) } }]
110
+ const sideEffects = []
96
111
  const entry = ctx.getSessionEntry?.()
97
112
  if (entry) {
98
113
  // #3687: prefer the actual model the underlying CLI/SDK reports at
@@ -129,8 +144,22 @@ Object.assign(EVENT_MAP, {
129
144
  // client that already has the right value.
130
145
  const thinkingLevelMsg = buildThinkingLevelChanged(entry.session)
131
146
  if (thinkingLevelMsg) messages.push({ msg: thinkingLevelMsg })
147
+ // Whether this session's folder settings are loaded: re-sent on every ready
148
+ // so a client that missed the last change (or a file edit that revoked
149
+ // trust) converges. Answered only from a fresh cached scan, never by walking
150
+ // the folder here. A cold cache starts an off-thread scan, and the frame is sent
151
+ // when that scan resolves (`folder_trust_refresh`). Display only; a failure never
152
+ // costs the ready frame.
153
+ try {
154
+ const hasSession = typeof ctx.sessionId === 'string' && ctx.sessionId
155
+ const trustMsg = hasSession ? buildFolderTrustStateMessageIfCached(ctx.sessionId, entry) : null
156
+ if (trustMsg) messages.push({ msg: trustMsg })
157
+ else if (hasSession && folderTrustFrameApplies(entry)) sideEffects.push({ type: 'folder_trust_refresh', sessionId: ctx.sessionId })
158
+ } catch (err) {
159
+ log.debug?.(`folder trust state failed: ${err?.message} — omitted from ready`)
160
+ }
132
161
  }
133
- return { messages }
162
+ return sideEffects.length > 0 ? { messages, sideEffects } : { messages }
134
163
  },
135
164
 
136
165
  // #8700: the SESSION changed or learned its level — a model switch dropped a
@@ -351,7 +380,7 @@ Object.assign(EVENT_MAP, {
351
380
  type: 'agent_event',
352
381
  parentToolUseId: data.parentToolUseId,
353
382
  eventType: data.type,
354
- payload: data.payload ?? {},
383
+ payload: nestedPayload(data),
355
384
  },
356
385
  }],
357
386
  }
@@ -780,6 +809,9 @@ Object.assign(EVENT_MAP, {
780
809
  ...(typeof data.reason === 'string' && data.reason ? { reason: data.reason } : {}),
781
810
  // #8517: "Allow for Session" -- the decision above stays a plain `allow`.
782
811
  ...(permissionScope(data.decision, data.scope) ? { scope: 'session' } : {}),
812
+ // #9119: WHO or WHAT resolved it, as a class (user / agent / rule / timeout / auto_mode /
813
+ // abort / cleared), rebuilt here so nothing but `kind` (and an agent's label) can ride.
814
+ ...resolvedByField(data.resolvedBy),
783
815
  sessionId: ctx.sessionId,
784
816
  },
785
817
  })
@@ -806,6 +838,7 @@ Object.assign(EVENT_MAP, {
806
838
  toolUseId: data.toolUseId,
807
839
  decision: 'deny',
808
840
  reason: 'superseded',
841
+ ...resolvedByField(data.resolvedBy),
809
842
  sessionId: ctx.sessionId,
810
843
  },
811
844
  })
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Wire shape of a session folder's trust state (`folder_trust_state`).
3
+ *
4
+ * One builder for every emission: when a session becomes ready, when a client
5
+ * subscribes to or switches to it, and after a trust change. The folder always
6
+ * comes from the server's record of the session, never from a client message.
7
+ */
8
+
9
+ import { getFolderTrustState, getFolderTrustStateForDisplay, getFolderTrustStateIfCached, resolveRealPath } from './folder-trust.js'
10
+
11
+ /**
12
+ * When a change reaches a running session of this provider. claude-sdk reads its
13
+ * setting sources on every turn; claude-cli and claude-tui (and the docker
14
+ * variants that run claude) read them at launch. Anything else never runs claude.
15
+ */
16
+ const APPLIES_FROM = Object.freeze({
17
+ 'claude-sdk': 'next_turn',
18
+ 'docker-sdk': 'next_turn',
19
+ 'claude-cli': 'restart',
20
+ 'claude-tui': 'restart',
21
+ 'docker-cli': 'restart',
22
+ docker: 'restart',
23
+ })
24
+
25
+ export function folderTrustAppliesFrom(provider) {
26
+ return APPLIES_FROM[provider] ?? 'n/a'
27
+ }
28
+
29
+ /** Frames built from a display scan that timed out: not a finding about the folder. */
30
+ const timedOutFrames = new WeakSet()
31
+
32
+ function frameFor(sessionId, entry, appliesFrom, state) {
33
+ const { status, summary, digest } = state
34
+ // What the RUNNING process was launched with: claude-cli and claude-tui keep it until restart.
35
+ const launched = appliesFrom === 'restart' ? entry.session?.launchedWithProject : undefined
36
+ const frame = {
37
+ type: 'folder_trust_state',
38
+ sessionId,
39
+ status,
40
+ summary,
41
+ digest,
42
+ appliesFrom,
43
+ ...(typeof launched === 'boolean' ? { launchedWithProject: launched } : {}),
44
+ }
45
+ if (state.timedOut) timedOutFrames.add(frame)
46
+ return frame
47
+ }
48
+
49
+ const folderOf = (entry) => {
50
+ const cwd = entry?.cwd ?? entry?.session?.cwd
51
+ return typeof cwd === 'string' && cwd !== '' ? cwd : null
52
+ }
53
+
54
+ /**
55
+ * The `folder_trust_state` frame, built from a scan done in this thread (a caller that
56
+ * has just decided something, or that passes a `state` it already computed). A provider
57
+ * that does not run claude gets no frame and no scan.
58
+ * @param {string} sessionId
59
+ * @param {{ cwd?: string, provider?: string, session?: object }} entry - the session manager's record
60
+ * @param {{ cached?: boolean, state?: object }} [opts]
61
+ * @returns {object|null}
62
+ */
63
+ export function buildFolderTrustStateMessage(sessionId, entry, opts = {}) {
64
+ const cwd = folderOf(entry)
65
+ if (!cwd) return null
66
+ const appliesFrom = folderTrustAppliesFrom(entry.provider)
67
+ if (appliesFrom === 'n/a') return null
68
+ return frameFor(sessionId, entry, appliesFrom, opts.state ?? getFolderTrustState(cwd, opts))
69
+ }
70
+
71
+ /** Whether a session of this record gets a `folder_trust_state` frame at all (it has a folder and runs claude). */
72
+ export function folderTrustFrameApplies(entry) {
73
+ return folderOf(entry) !== null && folderTrustAppliesFrom(entry.provider) !== 'n/a'
74
+ }
75
+
76
+ /**
77
+ * The same frame for a synchronous emitter that must not scan: answers only from a
78
+ * fresh cached scan (and starts an off-thread scan to warm the cache), else null.
79
+ */
80
+ export function buildFolderTrustStateMessageIfCached(sessionId, entry) {
81
+ const cwd = folderOf(entry)
82
+ if (!cwd) return null
83
+ const appliesFrom = folderTrustAppliesFrom(entry.provider)
84
+ if (appliesFrom === 'n/a') return null
85
+ const state = getFolderTrustStateIfCached(cwd)
86
+ return state ? frameFor(sessionId, entry, appliesFrom, state) : null
87
+ }
88
+
89
+ /**
90
+ * The same frame with the scan done on a worker thread, so building it never blocks
91
+ * the frames clients are waiting for. Used for subscribe / switch.
92
+ */
93
+ export async function buildFolderTrustStateMessageForDisplay(sessionId, entry) {
94
+ const cwd = folderOf(entry)
95
+ if (!cwd) return null
96
+ const appliesFrom = folderTrustAppliesFrom(entry.provider)
97
+ if (appliesFrom === 'n/a') return null
98
+ return frameFor(sessionId, entry, appliesFrom, await getFolderTrustStateForDisplay(cwd))
99
+ }
100
+
101
+ /**
102
+ * Tell the rest of the daemon that a session's folder is not trusted (as of a frame
103
+ * about to be sent), so anything that was running from the folder's own settings can
104
+ * stop showing its output (`folder_trust_lost` on the session manager). Idempotent
105
+ * for its listeners; a failure is never allowed to cost the frame.
106
+ * @param {{ emit?: Function }|null|undefined} sessionManager
107
+ * @param {{ sessionId?: string, status?: string }|null} frame
108
+ */
109
+ export function noteFolderTrustFrame(sessionManager, frame) {
110
+ // A frame from a scan that timed out says the folder was not reviewed, not that it lost trust.
111
+ if (!frame || frame.status === 'trusted' || timedOutFrames.has(frame) || typeof frame.sessionId !== 'string') return
112
+ try { sessionManager?.emit?.('folder_trust_lost', { sessionId: frame.sessionId }) } catch { /* display only */ }
113
+ }
114
+
115
+ /**
116
+ * Send the fresh state to every session whose folder has the same real path. The
117
+ * folder is scanned once (off-thread), not once per session.
118
+ * @param {{ sessions: { sessionManager: object }, transport: { broadcastToSession: Function } }} ctx
119
+ * @param {string} realPath
120
+ */
121
+ export async function broadcastFolderTrustState(ctx, realPath) {
122
+ const manager = ctx.sessions?.sessionManager
123
+ let state = null
124
+ for (const listed of manager?.listSessions?.() ?? []) {
125
+ if (typeof listed.cwd !== 'string') continue
126
+ const r = resolveRealPath(listed.cwd)
127
+ if (r.error || r.path !== realPath) continue
128
+ const entry = manager.getSession(listed.sessionId)
129
+ if (!entry) continue
130
+ const appliesFrom = folderTrustAppliesFrom(entry.provider)
131
+ if (appliesFrom === 'n/a') continue
132
+ state ??= await getFolderTrustStateForDisplay(realPath)
133
+ const frame = frameFor(listed.sessionId, entry, appliesFrom, state)
134
+ noteFolderTrustFrame(manager, frame)
135
+ ctx.transport.broadcastToSession(listed.sessionId, frame)
136
+ }
137
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Worker thread that runs `scanFolderSettings` off the daemon's main thread, so a
3
+ * scan of a large folder never delays the frames clients are waiting for. Used for
4
+ * display scans and for launch decisions (each in its own worker; folder-trust.js).
5
+ */
6
+ import { parentPort } from 'node:worker_threads'
7
+ import { scanFolderSettings } from './folder-trust.js'
8
+
9
+ parentPort.on('message', ({ id, cwd, limits }) => {
10
+ let scan = null
11
+ try {
12
+ scan = scanFolderSettings(cwd, limits)
13
+ } catch {
14
+ scan = null
15
+ }
16
+ parentPort.postMessage({ id, scan })
17
+ })