@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
@@ -64,6 +64,9 @@ const SECRET_FILE_EXACT = new Set([
64
64
  '.npmrc', '.pgpass', '.netrc', // credential dotfiles
65
65
  '.credentials.json', // claude's stored login, wherever its config dir is
66
66
  ])
67
+ // Files that configure what a session loads and runs. Floored for WRITES only
68
+ // (full floor); reading one is benign, like the other config files above.
69
+ const PROTECTED_WRITE_FILE_NAMES = new Set(['.mcp.json'])
67
70
  const SECRET_FILE_EXTENSIONS = ['.pem', '.key', '.p12', '.pfx']
68
71
  // The env-file family: exactly `.env`, or `.env.` followed by anything. Named so
69
72
  // the #7978 glob analysis below builds its templates from the same two spellings
@@ -885,6 +888,7 @@ function _matchesProtectedSegments(segments, start, secretsOnly) {
885
888
  // Config DIRS (any file within them) are floored only under the full (write)
886
889
  // floor; a read of a NON-credential config file stays un-prompted.
887
890
  if (PROTECTED_DIR_SEGMENTS.has(seg)) return true
891
+ if (PROTECTED_WRITE_FILE_NAMES.has(seg)) return true
888
892
  if (seg === '.config' && segments[i + 1] === 'git') return true
889
893
  }
890
894
  return false
@@ -1527,7 +1531,9 @@ function grepGlobFloored(input, rootRelative) {
1527
1531
  *
1528
1532
  * - {@link SECRET_READ_FLOOR_TOOLS} (Read / Glob / Grep — non-mutating) are
1529
1533
  * floored ONLY on secret + credential files ({@link isSecretReadTarget});
1530
- * reading a config dir stays benign and un-prompted.
1534
+ * reading a config dir stays benign and un-prompted. The one addition is a
1535
+ * Grep ROOTED at a directory holding those files, which floors unless an
1536
+ * include glob narrows it (see {@link CREDENTIAL_CONFIG_DIRS}).
1531
1537
  * - EVERY other tool (the mutating ones, and any future/unknown tool) gets the
1532
1538
  * full config-dir + secret floor ({@link isProtectedPathTarget}) — defaulting
1533
1539
  * the unknown case to the STRONGER floor is fail-safe.
@@ -1643,8 +1649,49 @@ function _searchTargets(input) {
1643
1649
  return targets
1644
1650
  }
1645
1651
 
1652
+ // The directories that hold the read-floored credential files, derived from
1653
+ // the same tables the read floor matches: the parent of each
1654
+ // CREDENTIAL_CONFIG_SEQUENCES entry (`.git`, `.config/git`) and the directory
1655
+ // of the `settings*.json` rule (`.claude`). A recursive search rooted at one of
1656
+ // them reads those files. Searches rooted ABOVE one are deliberately not judged
1657
+ // here: an ordinary project-root search is above `.claude`, and a search with
1658
+ // no `glob` already reads whatever the ignore rules let through (the documented
1659
+ // directory-search limit), so judging ancestors would prompt on every search.
1660
+ export const CREDENTIAL_CONFIG_DIRS = Object.freeze([
1661
+ ...CREDENTIAL_CONFIG_SEQUENCES.map((sequence) => sequence.slice(0, -1)),
1662
+ [CLAUDE_SETTINGS_DIR],
1663
+ ].filter((dir, i, all) => all.findIndex((d) => d.join('/') === dir.join('/')) === i))
1664
+
1665
+ /**
1666
+ * Is the absolute `resolved` itself one of the {@link CREDENTIAL_CONFIG_DIRS}
1667
+ * (its last path names, in the lowercased or canonical spelling)? A name that
1668
+ * cannot be canonicalised floors, and so does an 8.3 short name in the last
1669
+ * positions (a root that is the cwd itself has no relative segments for the
1670
+ * read floor's target scan to see).
1671
+ * @param {string} resolved
1672
+ * @param {object} call
1673
+ * @returns {boolean}
1674
+ */
1675
+ function _isCredentialConfigDir(resolved, call) {
1676
+ const pieces = resolved.split(/[/\\]+/).filter((s) => s.length > 0 && s !== '..').map(segmentName)
1677
+ const longest = Math.max(...CREDENTIAL_CONFIG_DIRS.map((d) => d.length))
1678
+ const tail = pieces.slice(-longest)
1679
+ if (tail.some((name) => SHORT_NAME_SEGMENT.test(name))) return true
1680
+ const canonical = []
1681
+ for (const name of tail) {
1682
+ const form = _canonicalNameIn(name, call)
1683
+ if (form === null) return true
1684
+ canonical.push(form)
1685
+ }
1686
+ const lowered = tail.map((name) => name.toLowerCase())
1687
+ return CREDENTIAL_CONFIG_DIRS.some((dir) =>
1688
+ [lowered, canonical].some((names) => names.length >= dir.length &&
1689
+ dir.every((name, k) => names[names.length - dir.length + k] === name)))
1690
+ }
1691
+
1646
1692
  /**
1647
- * Where a Grep / Glob searches, against the inbox socket and sessions rules.
1693
+ * Where a Grep / Glob searches, against the inbox socket, sessions and
1694
+ * credential-config-directory rules.
1648
1695
  * A call with no path field searches from the session cwd, so the cwd stands
1649
1696
  * in for the missing root; a supplied root is judged in its written and its
1650
1697
  * symlink-resolved form. A Grep also floors from the sessions directory's
@@ -1670,6 +1717,11 @@ function _searchRootFloored(toolName, input, cwd) {
1670
1717
  for (const form of forms) {
1671
1718
  if (_hitsInboxSocketDir(form, call) || _isSessionsDir(form, call)) return true
1672
1719
  if (toolName === 'Grep' && !globAvoidsKeyFiles(input.glob) && _searchReachesSessions(form, call)) return true
1720
+ // A Grep rooted at a directory holding read-floored files reads them
1721
+ // unless a `glob` narrows it (the glob analysis floors one that can
1722
+ // select a protected file). A Glob returns names only, so it is not
1723
+ // judged here, as for the sessions directory's parent.
1724
+ if (toolName === 'Grep' && _isCredentialConfigDir(form, call) && !globNarrowsSearch(input.glob)) return true
1673
1725
  }
1674
1726
  }
1675
1727
  return false
@@ -24,7 +24,7 @@ import {
24
24
  // #6038: the SDK/TUI permission path broadcasts to clients too, so it must apply
25
25
  // the same redaction as the hook path. Shared sanitizer + value redactor live in
26
26
  // redaction.js (a leaf module — no import cycle / HTTP-handler weight).
27
- import { sanitizeToolInput, redactValue, describeByNamedField, describeToolInput, describeComposedText } from './redaction.js'
27
+ import { sanitizeToolInput, redactBounded, describeByNamedField, describeToolInput, describeComposedText } from './redaction.js'
28
28
  import { redactMcpUrl, resolveTrustAddress, MCP_SERVER_SOURCE_VALUES } from './byok-mcp-config.js'
29
29
  import { DROPPED_HUNKS_KEY, KEPT_HUNKS_KEY, EditedInputRefusedError, isHunkReviewedTool, narrowByDroppedHunks, assertClientTextAllowed } from './edited-input.js'
30
30
  // #6842 review (Copilot) — audit entries must carry the store's NORMALIZED
@@ -36,6 +36,7 @@ import { DROPPED_HUNKS_KEY, KEPT_HUNKS_KEY, EditedInputRefusedError, isHunkRevie
36
36
  // normalizeProjectKey is a hoisted function declaration.
37
37
  import { normalizeProjectKey } from './permission-rule-store.js'
38
38
  import { permissionScope } from './permission-scope.js'
39
+ import { RESOLVED_BY, resolvedByForReason, normalizeResolvedBy } from './permission-resolved-by.js'
39
40
 
40
41
  const _fallbackLog = createLogger('permission-manager')
41
42
 
@@ -313,7 +314,9 @@ export function buildDenyMessage(reason) {
313
314
  if (typeof reason !== 'string') return 'User denied'
314
315
  const trimmed = reason.trim()
315
316
  if (trimmed.length === 0) return 'User denied'
316
- return redactValue(trimmed.slice(0, MAX_DENY_REASON_LEN))
317
+ // Redact the whole reason, then cut it: clipping first leaves a short fragment of a
318
+ // credential straddling the cap (#8416).
319
+ return redactBounded(trimmed, MAX_DENY_REASON_LEN)
317
320
  }
318
321
 
319
322
 
@@ -1005,6 +1008,7 @@ export class PermissionManager extends EventEmitter {
1005
1008
  requestId,
1006
1009
  decision: 'deny',
1007
1010
  reason,
1011
+ resolvedBy: RESOLVED_BY.abort,
1008
1012
  ...stoppedToolUseField(reason, pending.toolUseId),
1009
1013
  })
1010
1014
  }
@@ -1019,7 +1023,7 @@ export class PermissionManager extends EventEmitter {
1019
1023
  this._pendingPermissions.delete(requestId)
1020
1024
  this._lastPermissionData.delete(requestId)
1021
1025
  resolve({ behavior: 'deny', message: 'Permission timed out' })
1022
- this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'timeout' })
1026
+ this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'timeout', resolvedBy: RESOLVED_BY.timeout })
1023
1027
  }
1024
1028
  }, this._timeoutMs)
1025
1029
  this._permissionTimers.set(requestId, timer)
@@ -1054,6 +1058,15 @@ export class PermissionManager extends EventEmitter {
1054
1058
  return this._userStopInFlight
1055
1059
  }
1056
1060
 
1061
+ /**
1062
+ * #8281: request ids of the permission prompts waiting for a decision. A copy,
1063
+ * so a caller cannot reach the private map through it.
1064
+ * @returns {string[]}
1065
+ */
1066
+ getPendingPermissionIds() {
1067
+ return Array.from(this._pendingPermissions.keys())
1068
+ }
1069
+
1057
1070
  /** #8430: is any permission prompt or question waiting for a decision right now? */
1058
1071
  hasPendingPrompt() {
1059
1072
  return this._pendingPermissions.size > 0 || this._pendingUserAnswer != null
@@ -1141,7 +1154,7 @@ export class PermissionManager extends EventEmitter {
1141
1154
  this._pendingUserAnswer = null
1142
1155
  this._waitingForAnswer = false
1143
1156
  resolve({ behavior: 'deny', message: 'Cancelled' })
1144
- this.emit('permission_resolved', { toolUseId, reason, ...stoppedToolUseField(reason, sourceToolUseId) })
1157
+ this.emit('permission_resolved', { toolUseId, reason, resolvedBy: RESOLVED_BY.abort, ...stoppedToolUseField(reason, sourceToolUseId) })
1145
1158
  }
1146
1159
  }, { once: true })
1147
1160
  }
@@ -1154,7 +1167,7 @@ export class PermissionManager extends EventEmitter {
1154
1167
  this._pendingUserAnswer = null
1155
1168
  this._waitingForAnswer = false
1156
1169
  resolve({ behavior: 'deny', message: 'Question timed out' })
1157
- this.emit('permission_resolved', { toolUseId, reason: 'timeout' })
1170
+ this.emit('permission_resolved', { toolUseId, reason: 'timeout', resolvedBy: RESOLVED_BY.timeout })
1158
1171
  }
1159
1172
  }, this._timeoutMs)
1160
1173
  })
@@ -1175,7 +1188,7 @@ export class PermissionManager extends EventEmitter {
1175
1188
  this._waitingForAnswer = false
1176
1189
  this._logInfo(`Question ${superseded.toolUseId} superseded by a newer question`)
1177
1190
  superseded.resolve({ behavior: 'deny', message: 'Superseded by a newer question' })
1178
- this.emit('permission_resolved', { toolUseId: superseded.toolUseId, decision: 'deny', reason: 'superseded' })
1191
+ this.emit('permission_resolved', { toolUseId: superseded.toolUseId, decision: 'deny', reason: 'superseded', resolvedBy: RESOLVED_BY.cleared })
1179
1192
  }
1180
1193
 
1181
1194
  /**
@@ -1191,10 +1204,14 @@ export class PermissionManager extends EventEmitter {
1191
1204
  * Session" (the decision is then `allow`). A LABEL for the permission_resolved
1192
1205
  * event and the journal: it changes nothing about how the request is resolved,
1193
1206
  * and is dropped unless it rides beside `allow` (permission-scope.js).
1207
+ * @param {{ kind: string }} [resolvedBy] #9119 WHO resolved it (`RESOLVED_BY.*`). Absent means
1208
+ * `cleared`: an unattributed caller must never read as a person, so a client's answer
1209
+ * passes `RESOLVED_BY.user` explicitly (permission-resolver.js) and a daemon-made one passes
1210
+ * `rule` (policy) or `cleared` (nobody to ask).
1194
1211
  * @returns {boolean} true if a pending permission was found and resolved,
1195
1212
  * false if the requestId was unknown (already resolved or expired).
1196
1213
  */
1197
- respondToPermission(requestId, decision, editedInput, reason, scope) {
1214
+ respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy) {
1198
1215
  const pending = this._pendingPermissions.get(requestId)
1199
1216
  if (!pending) {
1200
1217
  this._logWarn(`No pending permission for ${requestId}`)
@@ -1221,7 +1238,7 @@ export class PermissionManager extends EventEmitter {
1221
1238
  // Emit before resolve() so listeners see the pending-count drop
1222
1239
  // before any follow-on work runs synchronously.
1223
1240
  const resolvedScope = permissionScope(decision, scope)
1224
- this.emit('permission_resolved', { requestId, decision, reason: 'user', ...(resolvedScope ? { scope: resolvedScope } : {}) })
1241
+ this.emit('permission_resolved', { requestId, decision, reason: 'user', resolvedBy: normalizeResolvedBy(resolvedBy) ?? RESOLVED_BY.cleared, ...(resolvedScope ? { scope: resolvedScope } : {}) })
1225
1242
 
1226
1243
  // #6543 (feature B): on an approve, an operator who reviewed the proposed
1227
1244
  // Write/Edit per-hunk may narrow the CONTENT (never the path — see
@@ -1328,7 +1345,7 @@ export class PermissionManager extends EventEmitter {
1328
1345
  // Emit before resolve() so listeners (e.g. the SdkSession
1329
1346
  // inactivity-timer resumer, #2831) see the state flip before any
1330
1347
  // downstream synchronous work runs.
1331
- this.emit('permission_resolved', { toolUseId: pendingToolUseId, reason: 'answered' })
1348
+ this.emit('permission_resolved', { toolUseId: pendingToolUseId, reason: 'answered', resolvedBy: RESOLVED_BY.user })
1332
1349
 
1333
1350
  // Build structured answers map: SDK expects { [questionText]: selectedLabel }.
1334
1351
  // Per @anthropic-ai/claude-agent-sdk sdk-tools.d.ts (AskUserQuestionOutput.answers,
@@ -1479,7 +1496,7 @@ export class PermissionManager extends EventEmitter {
1479
1496
  behavior: 'deny',
1480
1497
  message: 'MCP trust not persisted via auto-mode bypass; approve explicitly to trust this server',
1481
1498
  })
1482
- this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'auto_mode_mcp_trust_bypass' })
1499
+ this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'auto_mode_mcp_trust_bypass', resolvedBy: RESOLVED_BY.auto_mode })
1483
1500
  deniedMcpTrust += 1
1484
1501
  continue
1485
1502
  }
@@ -1508,7 +1525,7 @@ export class PermissionManager extends EventEmitter {
1508
1525
  this._lastPermissionData.delete(requestId)
1509
1526
  this._clearPermissionTimer(requestId)
1510
1527
  pending.resolve({ behavior: 'allow', updatedInput: pending.input })
1511
- this.emit('permission_resolved', { requestId, decision: 'allow', reason: 'auto_mode' })
1528
+ this.emit('permission_resolved', { requestId, decision: 'allow', reason: 'auto_mode', resolvedBy: RESOLVED_BY.auto_mode })
1512
1529
  allowed += 1
1513
1530
  }
1514
1531
  if (deniedMcpTrust > 0 || preservedProtected > 0 || preservedNotDelegable > 0) {
@@ -1574,6 +1591,7 @@ export class PermissionManager extends EventEmitter {
1574
1591
  requestId,
1575
1592
  decision: 'deny',
1576
1593
  reason: requestReason,
1594
+ resolvedBy: resolvedByForReason(requestReason),
1577
1595
  ...stoppedToolUseField(requestReason, pendingToolUseIds.get(requestId)),
1578
1596
  })
1579
1597
  }
@@ -1585,6 +1603,7 @@ export class PermissionManager extends EventEmitter {
1585
1603
  this.emit('permission_resolved', {
1586
1604
  toolUseId: clearedUserAnswer.toolUseId,
1587
1605
  reason: requestReason,
1606
+ resolvedBy: resolvedByForReason(requestReason),
1588
1607
  ...stoppedToolUseField(requestReason, clearedUserAnswer.sourceToolUseId),
1589
1608
  })
1590
1609
  }
@@ -1601,7 +1620,7 @@ export class PermissionManager extends EventEmitter {
1601
1620
  this._lastPermissionData.delete(requestId)
1602
1621
  this._clearPermissionTimer(requestId)
1603
1622
  signal?.removeEventListener('abort', abort)
1604
- this.emit('permission_resolved', { requestId, decision: allowed ? 'allow' : 'deny', reason })
1623
+ this.emit('permission_resolved', { requestId, decision: allowed ? 'allow' : 'deny', reason, resolvedBy: resolvedByForReason(reason) })
1605
1624
  resolve(allowed)
1606
1625
  }
1607
1626
  const abort = () => finish(false, 'cancelled')
@@ -1773,7 +1792,7 @@ export class PermissionManager extends EventEmitter {
1773
1792
  this._pendingPermissions.delete(requestId)
1774
1793
  this._lastPermissionData.delete(requestId)
1775
1794
  resolve(false)
1776
- this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'timeout' })
1795
+ this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'timeout', resolvedBy: RESOLVED_BY.timeout })
1777
1796
  }
1778
1797
  }, this._timeoutMs)
1779
1798
  this._permissionTimers.set(requestId, timer)
@@ -0,0 +1,89 @@
1
+ // permission-resolved-by.js (#9119, S4 of #9112) -- the one definition of WHO or WHAT
2
+ // resolved a permission prompt, carried on `permission_resolved` as `resolvedBy`
3
+ // (docs/security/agent-principals.md section 9).
4
+ //
5
+ // `resolvedBy` is a CLASS, never an identity: { kind, label? }.
6
+ // user a person answered (any client: the dashboard, the app, the HTTP fallback)
7
+ // agent an agent principal answered; `label` is the operator-authored principal
8
+ // label. RESERVED: principals cannot answer until S15, so nothing produces it
9
+ // rule the daemon's own POLICY decided it: the orchestration allowlist's allow and
10
+ // deny, and the deny after a refused edit. (A session rule decides before a
11
+ // prompt exists and emits no `permission_resolved`, #6842, so it never shows here.)
12
+ // timeout nobody answered in time
13
+ // auto_mode the session's auto mode resolved a pending prompt
14
+ // abort the turn was stopped or aborted, or the request was cancelled
15
+ // cleared the daemon drained it (message completion, session teardown, a newer
16
+ // question superseding an older one)
17
+ //
18
+ // It never carries a token, a client id, a device name or a principal id. The emit sites
19
+ // use the frozen constants below, and the event normalizer rebuilds the wire value through
20
+ // `normalizeResolvedBy`, so a producer that added a field would still not put it on the wire.
21
+
22
+ /** The closed set of kinds (the protocol's `PermissionResolvedByKindValues`). */
23
+ export const RESOLVED_BY_KINDS = Object.freeze(['user', 'agent', 'rule', 'timeout', 'auto_mode', 'abort', 'cleared'])
24
+
25
+ /** The longest label that crosses the wire (the principal label cap, principal-store.js). */
26
+ export const RESOLVED_BY_LABEL_MAX = 64
27
+
28
+ /** The label-free kinds, frozen, ready to put on an emit. `agent` has no constant: it needs a label. */
29
+ export const RESOLVED_BY = Object.freeze({
30
+ user: Object.freeze({ kind: 'user' }),
31
+ rule: Object.freeze({ kind: 'rule' }),
32
+ timeout: Object.freeze({ kind: 'timeout' }),
33
+ auto_mode: Object.freeze({ kind: 'auto_mode' }),
34
+ abort: Object.freeze({ kind: 'abort' }),
35
+ cleared: Object.freeze({ kind: 'cleared' }),
36
+ })
37
+
38
+ /**
39
+ * The `resolvedBy` for a PermissionManager resolution `reason`. The reasons are the ones the
40
+ * manager already puts on `permission_resolved`; anything it does not know is `cleared`, the
41
+ * kind that claims nothing about a person.
42
+ *
43
+ * @param {unknown} reason
44
+ * @returns {Readonly<{ kind: string }>}
45
+ */
46
+ export function resolvedByForReason(reason) {
47
+ switch (reason) {
48
+ case 'user': return RESOLVED_BY.user
49
+ case 'timeout': return RESOLVED_BY.timeout
50
+ case 'stopped':
51
+ case 'aborted':
52
+ case 'cancelled': return RESOLVED_BY.abort
53
+ case 'auto_mode':
54
+ case 'auto_mode_mcp_trust_bypass': return RESOLVED_BY.auto_mode
55
+ default: return RESOLVED_BY.cleared
56
+ }
57
+ }
58
+
59
+ /**
60
+ * The wire `resolvedBy` for a value an emitter supplied, rebuilt from scratch: `kind` must be
61
+ * a known one, `label` survives only on `agent` and only as a bounded string with no control
62
+ * characters, and every other key is dropped. Returns undefined for anything else, so the
63
+ * field is simply absent rather than carrying something unvetted.
64
+ *
65
+ * @param {unknown} value
66
+ * @returns {{ kind: string, label?: string } | undefined}
67
+ */
68
+ export function normalizeResolvedBy(value) {
69
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
70
+ const kind = value.kind
71
+ if (typeof kind !== 'string' || !RESOLVED_BY_KINDS.includes(kind)) return undefined
72
+ if (kind !== 'agent') return { kind }
73
+ const label = value.label
74
+ if (typeof label === 'string' && label.length > 0 && label.length <= RESOLVED_BY_LABEL_MAX && !/[\u0000-\u001f\u007f]/.test(label)) {
75
+ return { kind, label }
76
+ }
77
+ return { kind }
78
+ }
79
+
80
+ /**
81
+ * `{ resolvedBy }` for a spread into a wire frame, or `{}` when the emitter supplied nothing
82
+ * usable (an older producer, a relayed event): the field is additive and optional.
83
+ * @param {unknown} value
84
+ * @returns {{ resolvedBy: { kind: string, label?: string } } | {}}
85
+ */
86
+ export function resolvedByField(value) {
87
+ const normalized = normalizeResolvedBy(value)
88
+ return normalized ? { resolvedBy: normalized } : {}
89
+ }
@@ -38,6 +38,7 @@ import { normalizeProjectKey } from './permission-rule-store.js'
38
38
  import { EditedInputRefusedError } from './edited-input.js'
39
39
  import { permissionScope, permissionDecisionToken } from './permission-scope.js'
40
40
  import { isBoundClient } from './environments/authority.js'
41
+ import { RESOLVED_BY } from './permission-resolved-by.js'
41
42
 
42
43
  const unboundOnly = (client) => !isBoundClient(client)
43
44
 
@@ -68,6 +69,9 @@ export function buildLegacyResolvedBroadcast(result, requestId, decision) {
68
69
  type: 'permission_resolved',
69
70
  requestId,
70
71
  decision,
72
+ // #9119: a legacy answer is always a client's: the WS and HTTP handlers resolve it only on a
73
+ // `permission_response`. A class, never the answering client's id or token.
74
+ resolvedBy: RESOLVED_BY.user,
71
75
  // #8517: the "Allow for Session" label, when the caller sent it beside an allow.
72
76
  ...(result.scope ? { scope: result.scope } : {}),
73
77
  ...(result.mapped ? { sessionId: result.sessionId } : {}),
@@ -167,7 +171,6 @@ export function createPermissionResolver({
167
171
  // scope label above, which was already dropped beside `allowAlways`.)
168
172
  if (callerIsScoped && decision === 'allowAlways') decision = 'allow'
169
173
  const scopeResult = scope ? { scope } : {}
170
- const scopeArg = scope ? [scope] : []
171
174
 
172
175
  // Invariant B (#2806 residual): the binding check reads the RAW map entry —
173
176
  // never an activeSessionId fallback. For a bound caller the request MUST be
@@ -222,7 +225,8 @@ export function createPermissionResolver({
222
225
  // agent-facing denial message (permission-manager.js buildDenyMessage).
223
226
  let resolved
224
227
  try {
225
- resolved = entry.session.respondToPermission(requestId, decision, editedInput, reason, ...scopeArg)
228
+ // #9119: this path is a client's answer, the one place that is a person.
229
+ resolved = entry.session.respondToPermission(requestId, decision, editedInput, reason, scope, RESOLVED_BY.user)
226
230
  } catch (err) {
227
231
  if (!(err instanceof EditedInputRefusedError)) throw err
228
232
  // #8446 — the operator's edit cannot be applied without writing a
@@ -236,7 +240,7 @@ export function createPermissionResolver({
236
240
  // subagent's prompt lives in its child's manager; the parent routes to it)
237
241
  // and its return value says whether it did: a deny that found nothing to
238
242
  // resolve is not audited as one.
239
- const denied = entry.session.respondToPermission(requestId, 'deny', undefined, err.message)
243
+ const denied = entry.session.respondToPermission(requestId, 'deny', undefined, err.message, undefined, RESOLVED_BY.rule)
240
244
  consumeRoute(requestId)
241
245
  if (!denied) return { kind: 'expired', sessionId: originSessionId }
242
246
  audit(clientId, originSessionId, requestId, 'deny', { ...(toolName ? { tool: toolName } : {}), reason: 'edit_refused' })
package/src/platform.js CHANGED
@@ -169,7 +169,7 @@ export function defaultShell({ platform = process.platform, env = process.env }
169
169
  * `_fsync` is a test seam (default `fsyncSync`) so the durable + benign-error
170
170
  * paths are exercisable without a real disk fault.
171
171
  */
172
- export function fsyncForDurability(target, { isDir = false, _fsync = fsyncSync } = {}) {
172
+ export function fsyncForDurability(target, { isDir = false, _fsync = fsyncSync, strict = false } = {}) {
173
173
  let fd
174
174
  try {
175
175
  // Directories open read-only; regular files open `r+` so the handle is
@@ -179,7 +179,9 @@ export function fsyncForDurability(target, { isDir = false, _fsync = fsyncSync }
179
179
  fd = openSync(target, isDir ? 'r' : 'r+')
180
180
  _fsync(fd)
181
181
  } catch (err) {
182
- if (err && BENIGN_FSYNC_CODES.has(err.code)) {
182
+ // `strict` (agent-principal store, #9116): a filesystem that cannot sync is NOT
183
+ // durable. Nothing is swallowed, so the caller reports it instead of claiming it.
184
+ if (!strict && err && BENIGN_FSYNC_CODES.has(err.code)) {
183
185
  log.warn(`durable-write: fsync of ${isDir ? 'directory' : 'file'} ${target} unsupported (${err.code}); continuing best-effort`)
184
186
  return
185
187
  }
@@ -358,6 +360,9 @@ export function writeFileRestricted(
358
360
  // Test seam (#6914): inject the fsync used by the `durable` path so the
359
361
  // durable + benign-fsync-error branches are exercisable without a disk fault.
360
362
  _fsync = fsyncSync,
363
+ // #9116: no benign-errno swallowing; a failed file sync prevents publication and a
364
+ // failed directory sync is reported as unconfirmed.
365
+ strict = false,
361
366
  } = {},
362
367
  ) {
363
368
  const onWindows = _isWindowsOverride ?? isWindows
@@ -407,7 +412,7 @@ export function writeFileRestricted(
407
412
  // has already swallowed the benign, filesystem-cannot-sync codes.)
408
413
  if (durable) {
409
414
  try {
410
- fsyncForDurability(tmpPath, { _fsync })
415
+ fsyncForDurability(tmpPath, { _fsync, strict })
411
416
  } catch (err) {
412
417
  try {
413
418
  unlinkSync(tmpPath)
@@ -464,7 +469,7 @@ export function writeFileRestricted(
464
469
  durable,
465
470
  onWindows,
466
471
  // Bind this call's `_fsync` seam into the shared helper's higher-level one.
467
- fsync: (target, opts) => fsyncForDurability(target, { ...opts, _fsync }),
472
+ fsync: (target, opts) => fsyncForDurability(target, { ...opts, _fsync, strict }),
468
473
  })
469
474
  }
470
475
 
@@ -589,6 +594,153 @@ export function killProcessTree(child, { force = false, ...deps } = {}) {
589
594
  try { child.kill(signal) } catch { /* already gone */ }
590
595
  }
591
596
 
597
+ /**
598
+ * #9267: the start wall-clock of `pid` (`ps -o lstart=`), or null when the
599
+ * process is gone or unreadable. Fixed for a process's lifetime and different
600
+ * for a recycled pid's new occupant, so equality is the "same incarnation"
601
+ * check (the same one the user-shell orphan reaper uses). `deps.startTimeOf` is
602
+ * the test seam.
603
+ */
604
+ export function processStartTime(pid, deps = {}) {
605
+ if (deps.startTimeOf) return deps.startTimeOf(pid) || null
606
+ if (!Number.isInteger(pid) || pid <= 0) return null
607
+ try {
608
+ return execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
609
+ encoding: 'utf8',
610
+ stdio: ['ignore', 'pipe', 'ignore'],
611
+ timeout: 5000,
612
+ }).trim() || null
613
+ } catch {
614
+ return null
615
+ }
616
+ }
617
+
618
+ /**
619
+ * #9267: one bounded snapshot of the process table, `pid ppid lstart`, parsed
620
+ * once. Returns a Map pid -> { ppid, started } or null when `ps` is unavailable.
621
+ * `lstart` is kept verbatim (never parsed as a date: it is locale-dependent) and
622
+ * only ever compared for equality with the same `ps` formatting. `deps.ps` is the
623
+ * test seam (returns the raw table).
624
+ */
625
+ function processTableSnapshot(deps = {}) {
626
+ let raw
627
+ try {
628
+ raw = deps.ps
629
+ ? deps.ps()
630
+ : execFileSync('ps', ['-axo', 'pid=,ppid=,lstart='], {
631
+ encoding: 'utf8',
632
+ stdio: ['ignore', 'pipe', 'ignore'],
633
+ timeout: 5000,
634
+ maxBuffer: 16 * 1024 * 1024,
635
+ })
636
+ } catch {
637
+ return null
638
+ }
639
+ const table = new Map()
640
+ for (const line of String(raw || '').split('\n')) {
641
+ const m = /^\s*(\d+)\s+(\d+)\s+(\S.*?)\s*$/.exec(line)
642
+ if (m) table.set(Number(m[1]), { ppid: Number(m[2]), started: m[3] })
643
+ }
644
+ return table
645
+ }
646
+
647
+ /** Node has not reaped `child`: its pid is still ours and cannot have been recycled. */
648
+ function isLiveOwnedChild(child) {
649
+ return !!child && child.exitCode == null && !child.signalCode
650
+ }
651
+
652
+ /**
653
+ * #9267: snapshot `child`'s live descendants as `{ pid, started }` BEFORE
654
+ * anything is signalled, so a later escalation can still reach a descendant
655
+ * after its parent has exited and reparented it (a parent's exit erases the
656
+ * ppid links the enumeration depends on).
657
+ *
658
+ * Ownership argument: the root is `child`, which Node has not reaped
659
+ * (`exitCode`/`signalCode` unset), so its pid is still ours -- an unreaped child
660
+ * holds its pid, it cannot have been recycled. A child already reaped records
661
+ * NOTHING (its pid may belong to someone else now; the caller signals through
662
+ * the handle only). The descendant set AND each descendant's start time come
663
+ * from the SAME single process-table snapshot, so a pid reused between an
664
+ * enumeration and a separate start-time lookup cannot be stored with the
665
+ * replacement's identity. The root's own start time is not compared: a
666
+ * handle-liveness check is stronger than comparing a locale-formatted string
667
+ * against a spawn time we never recorded in that format. POSIX only (Windows
668
+ * reaps the tree with `taskkill /T`). `deps.ps` is the test seam.
669
+ */
670
+ export function recordProcessTree(child, deps = {}) {
671
+ const win = deps.isWindows ?? isWindows
672
+ if (win || !isLiveOwnedChild(child) || !Number.isInteger(child.pid) || child.pid <= 0) return []
673
+ const table = processTableSnapshot(deps)
674
+ if (!table || !table.has(child.pid)) return [] // the root is not demonstrably alive: record nothing
675
+ const childrenOf = new Map()
676
+ for (const [pid, { ppid }] of table) {
677
+ if (!childrenOf.has(ppid)) childrenOf.set(ppid, [])
678
+ childrenOf.get(ppid).push(pid)
679
+ }
680
+ const out = []
681
+ const seen = new Set([child.pid])
682
+ const stack = [child.pid]
683
+ while (stack.length) {
684
+ for (const pid of childrenOf.get(stack.pop()) || []) {
685
+ if (seen.has(pid)) continue
686
+ seen.add(pid)
687
+ out.push({ pid, started: table.get(pid).started })
688
+ stack.push(pid)
689
+ }
690
+ }
691
+ return out
692
+ }
693
+
694
+ /**
695
+ * #9267: signal `child` and the descendants recorded by {@link recordProcessTree}.
696
+ * PID-reuse safe by construction: a recorded descendant is signalled only while
697
+ * a process with that pid is alive AND still reports the start time recorded
698
+ * for it, so a recycled pid is never touched. The direct child is signalled
699
+ * through its handle (a no-op once Node has reaped it), never by pid. Deepest
700
+ * descendant first, the parent last, as {@link killProcessTree} does. Does NOT
701
+ * re-enumerate, which is the point: it works after the parent has exited.
702
+ * `force` selects SIGKILL over SIGTERM; `deps.kill` is the `process.kill` seam.
703
+ *
704
+ * Windows: records no descendants, and a numeric-pid `taskkill` of a child that
705
+ * may have exited (and whose pid may be recycled) is never acceptable. The tree
706
+ * `taskkill` runs only for a child Node has not reaped and only when the caller
707
+ * is not on a delayed path (`handleOnly` -- the escalation and destroy()); every
708
+ * other case goes through the Node handle, a no-op once the child is reaped.
709
+ * `deps.isWindows` forces the branch and `deps.taskkill(pid)` is the seam, so no
710
+ * test reaches the real binary.
711
+ */
712
+ export function killRecordedTree(child, recorded = [], { force = false, handleOnly = false, ...deps } = {}) {
713
+ if (!child) return
714
+ const win = deps.isWindows ?? isWindows
715
+ if (win) {
716
+ if (!handleOnly && isLiveOwnedChild(child) && Number.isInteger(child.pid) && child.pid > 0) {
717
+ try {
718
+ const taskkill = deps.taskkill || ((pid) => execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], {
719
+ stdio: 'ignore',
720
+ windowsHide: true,
721
+ timeout: 5000,
722
+ }))
723
+ taskkill(child.pid)
724
+ return
725
+ } catch { /* fall through to the handle */ }
726
+ }
727
+ try { child.kill('SIGKILL') } catch { /* already gone */ }
728
+ return
729
+ }
730
+ const signal = force ? 'SIGKILL' : 'SIGTERM'
731
+ const kill = deps.kill || process.kill
732
+ // ONE bounded snapshot decides every descendant (not one `ps -p` per pid), which also
733
+ // narrows the check-to-kill window. No snapshot: signal no descendant, the handle still runs.
734
+ const table = recorded.length > 0 ? processTableSnapshot(deps) : null
735
+ for (let i = recorded.length - 1; table && i >= 0; i--) {
736
+ const { pid, started } = recorded[i]
737
+ if (!started) continue // no identity, never signalled
738
+ if (table.get(pid)?.started !== started) continue // gone, or a recycled pid
739
+ try { kill(pid, signal) } catch { /* already gone */ }
740
+ }
741
+ try { child.kill(signal) } catch { /* already gone */ }
742
+ }
743
+
592
744
  /**
593
745
  * Force-kill `child` and its whole descendant tree (#6643, #7606). POSIX
594
746
  * SIGKILLs the enumerated tree; Windows reaps it via taskkill. See