@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
@@ -1,5 +1,6 @@
1
1
  import { EventEmitter } from 'events'
2
2
  import { createLogger } from './logger.js'
3
+ import { truncateTitle } from './session-title.js'
3
4
 
4
5
  const log = createLogger('session-message-history')
5
6
  const MAX_PENDING_STREAM_SIZE = 100 * 1024 * 1024 // 100MB
@@ -11,7 +12,9 @@ const MAX_PENDING_STREAM_SIZE = 100 * 1024 * 1024 // 100MB
11
12
  * Extracted from SessionManager to isolate history concerns.
12
13
  *
13
14
  * Events emitted:
14
- * auto_label { sessionId, label } — when first user input triggers session rename
15
+ * auto_label { sessionId, label, text } — when first user input triggers a
16
+ * session rename. `label` is the truncation applied synchronously; `text` is
17
+ * the untruncated first message (source for the #6764 semantic-title upgrade).
15
18
  */
16
19
  export class SessionMessageHistory extends EventEmitter {
17
20
  /**
@@ -221,15 +224,16 @@ export class SessionMessageHistory extends EventEmitter {
221
224
  const baseTs = typeof entry.timestamp === 'number' && Number.isFinite(entry.timestamp)
222
225
  ? entry.timestamp
223
226
  : Date.now()
224
- // `synthetic` / `interrupted` / `isError` / `reason` are diagnostic
225
- // hints only — no client code branches on them today, and the wire
226
- // schema (`ServerToolResultSchema` in packages/protocol) strips
227
- // unknown fields on parse. The behaviour that clears the dashboard's
228
- // activeTools entry is driven purely by the `tool_result` type +
229
- // matching `toolUseId` going through `handleToolResult.applyToActiveTools`
230
- // (store-core/handlers/index.ts). Keep these fields anyway so the
231
- // synthetic stays grep-able on disk and a future renderer can show
232
- // a distinct "interrupted" badge without a protocol change.
227
+ // #6712: `isError` is now a first-class wire field
228
+ // (`ServerToolResultSchema`) that BOTH clients branch on to style a
229
+ // failed result (a red alert icon / ✕ marker) — so a replayed synthetic
230
+ // sweep entry surfaces the error affordance too (replay sends the entry
231
+ // raw). `synthetic` / `interrupted` / `reason` remain diagnostic hints
232
+ // that no client branches on and the schema strips on parse; kept so the
233
+ // synthetic stays grep-able on disk and a future renderer can show a
234
+ // distinct "interrupted" badge without a protocol change. The activeTools
235
+ // clear is driven purely by the `tool_result` type + matching `toolUseId`
236
+ // through `handleToolResult.applyToActiveTools`.
233
237
  out.push({
234
238
  type: 'tool_result',
235
239
  toolUseId: entry.toolUseId,
@@ -442,7 +446,15 @@ export class SessionMessageHistory extends EventEmitter {
442
446
 
443
447
  /**
444
448
  * Auto-label a session from the first user input if it still has a default name.
445
- * Truncates to ~40 chars at word boundary, appends "..." if truncated.
449
+ *
450
+ * Applies the word-boundary truncation label SYNCHRONOUSLY (via
451
+ * `truncateTitle`) so a session is never left unnamed — this is the always-
452
+ * available fallback. It also emits `auto_label` carrying the original first
453
+ * message `text`, so a listener (SessionManager, #6764) can optionally fire an
454
+ * asynchronous cheap-model call to UPGRADE the truncation to a short semantic
455
+ * title. Firing only from here means the semantic path inherits this method's
456
+ * once-per-session + default-name + manual-rename guards for free.
457
+ *
446
458
  * @param {string} sessionId
447
459
  * @param {string} text
448
460
  * @param {object} sessionEntry - Must have { name, _autoLabeled } properties
@@ -463,18 +475,12 @@ export class SessionMessageHistory extends EventEmitter {
463
475
 
464
476
  sessionEntry._autoLabeled = true
465
477
 
466
- const MAX_LEN = 40
467
- let label
468
- if (trimmed.length <= MAX_LEN) {
469
- label = trimmed
470
- } else {
471
- const cut = trimmed.lastIndexOf(' ', MAX_LEN)
472
- label = (cut > 10 ? trimmed.slice(0, cut) : trimmed.slice(0, MAX_LEN)) + '...'
473
- }
474
-
478
+ const label = truncateTitle(trimmed)
475
479
  sessionEntry.name = label
476
480
  log.info(`Auto-labeled session ${sessionId} to "${label}"`)
477
- this.emit('auto_label', { sessionId, label })
481
+ // `text` is the untruncated first message — the semantic-title upgrade path
482
+ // needs the full source, not the already-truncated label.
483
+ this.emit('auto_label', { sessionId, label, text: trimmed })
478
484
  }
479
485
 
480
486
  /**
@@ -0,0 +1,168 @@
1
+ /**
2
+ * #6764 — semantic session titles (pure logic).
3
+ *
4
+ * The sidebar's auto-generated session title has historically been the raw
5
+ * first user message truncated to ~40 chars at a word boundary. That is a
6
+ * copy of the prompt, not a summary — long or code-heavy first messages produce
7
+ * noisy, low-signal labels. This module produces a short, semantic title from a
8
+ * cheap one-shot model call instead, and ALWAYS falls back to the truncation
9
+ * behaviour when the feature is off, the call fails, or the model returns
10
+ * nothing usable.
11
+ *
12
+ * Everything here is PURE and dependency-free (no provider, no SDK import): the
13
+ * one-shot model runner is INJECTED (`runOneShot`) so the prompt/sanitise/gate
14
+ * logic is unit-testable without a live provider. Production wires
15
+ * `defaultRunOneShot` from summarize-session.js as the runner (reusing the same
16
+ * SDK one-shot + credential plumbing as the #5547 summarizer).
17
+ */
18
+
19
+ // Truncation-fallback cap — matches the historical `_autoLabelSession` length so
20
+ // the fallback label is byte-for-byte what the old behaviour produced.
21
+ export const TITLE_MAX_LEN = 40
22
+ // Cap for a model-generated title. A well-behaved Haiku reply is ~5-8 words; the
23
+ // cap only bites when the model ignores instructions and returns prose.
24
+ export const TITLE_MODEL_MAX_LEN = 60
25
+ // Default cheap model for the one-shot title call. The short alias resolves to
26
+ // the latest Haiku (see claude-model-catalog.js), so it survives model bumps.
27
+ export const DEFAULT_SEMANTIC_TITLE_MODEL = 'haiku'
28
+ // Default timeout (ms) for the one-shot title call. The call is fire-and-forget,
29
+ // so a stalled provider connection must never leave its promise pending forever:
30
+ // the closure retains the SessionManager, the first message, and the sessionId,
31
+ // so an un-timed-out call is an unbounded per-session leak for opted-in users, and
32
+ // the underlying one-shot subprocess is never torn down. The caller passes
33
+ // `AbortSignal.timeout(this)` as the `signal` so the call aborts (and the SDK
34
+ // tears the subprocess down) and `generateSessionTitle` fails open to the
35
+ // truncation label. Server-side only (Node's AbortSignal.timeout).
36
+ export const DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS = 15_000
37
+
38
+ /**
39
+ * Word-boundary truncation used as the ALWAYS-available fallback label. Byte-for
40
+ * -byte compatible with the pre-#6764 `_autoLabelSession` truncation.
41
+ *
42
+ * @param {string} text
43
+ * @param {number} [maxLen=TITLE_MAX_LEN]
44
+ * @returns {string} the label, or '' when the input has no usable text.
45
+ */
46
+ export function truncateTitle(text, maxLen = TITLE_MAX_LEN) {
47
+ const trimmed = typeof text === 'string' ? text.trim() : ''
48
+ if (!trimmed) return ''
49
+ if (trimmed.length <= maxLen) return trimmed
50
+ const cut = trimmed.lastIndexOf(' ', maxLen)
51
+ return (cut > 10 ? trimmed.slice(0, cut) : trimmed.slice(0, maxLen)) + '...'
52
+ }
53
+
54
+ /**
55
+ * Clean a raw model reply into a usable one-line title. Models occasionally wrap
56
+ * the title in quotes, add a trailing period, prepend prose, or emit multiple
57
+ * lines — this strips all of that and returns '' when nothing usable remains
58
+ * (which the caller treats as "fall back to truncation").
59
+ *
60
+ * @param {string} raw
61
+ * @param {number} [maxLen=TITLE_MODEL_MAX_LEN]
62
+ * @returns {string} a cleaned title, or '' when unusable.
63
+ */
64
+ export function sanitizeModelTitle(raw, maxLen = TITLE_MODEL_MAX_LEN) {
65
+ if (typeof raw !== 'string') return ''
66
+ // First non-empty line — models sometimes prepend a preamble or add newlines.
67
+ let line = ''
68
+ for (const l of raw.split('\n')) {
69
+ if (l.trim()) { line = l.trim(); break }
70
+ }
71
+ if (!line) return ''
72
+ // Strip surrounding quotes/backticks (straight or curly) the model wrapped it in.
73
+ line = line.replace(/^["'`“‘]+/, '').replace(/["'`”’]+$/, '').trim()
74
+ // Collapse internal whitespace runs to single spaces.
75
+ line = line.replace(/\s+/g, ' ')
76
+ // Drop a single trailing sentence period, but preserve a real ellipsis ('...').
77
+ line = line.replace(/(?<!\.)\.$/, '').trim()
78
+ if (!line) return ''
79
+ if (line.length <= maxLen) return line
80
+ const cut = line.lastIndexOf(' ', maxLen)
81
+ return (cut > 10 ? line.slice(0, cut) : line.slice(0, maxLen)) + '...'
82
+ }
83
+
84
+ /**
85
+ * Build the one-shot prompt asking for a short semantic title. The first user
86
+ * message is the primary signal; an optional first assistant response can be
87
+ * supplied for extra context. Both are length-capped so the call stays cheap
88
+ * even when the opening message is huge.
89
+ *
90
+ * @param {object} args
91
+ * @param {string} args.firstUserMessage
92
+ * @param {string} [args.firstAssistantResponse]
93
+ * @returns {string}
94
+ */
95
+ export function buildTitlePrompt({ firstUserMessage, firstAssistantResponse } = {}) {
96
+ const parts = [
97
+ 'Generate a short, specific title (5 to 8 words maximum) that summarizes what this coding session is about, based on the first message below.',
98
+ 'Rules:',
99
+ '- Output ONLY the title text: no surrounding quotes, no trailing punctuation, no preamble, no explanation.',
100
+ '- Be concrete — name the actual task, file, feature, or bug. Avoid generic titles like "Help request" or "Coding question".',
101
+ '- Never exceed 8 words.',
102
+ '',
103
+ 'First user message:',
104
+ String(firstUserMessage == null ? '' : firstUserMessage).slice(0, 4000),
105
+ ]
106
+ if (typeof firstAssistantResponse === 'string' && firstAssistantResponse.trim()) {
107
+ parts.push('', 'First assistant response (extra context):', firstAssistantResponse.slice(0, 2000))
108
+ }
109
+ parts.push('', 'Title:')
110
+ return parts.join('\n')
111
+ }
112
+
113
+ /**
114
+ * Produce a session title, gated + fail-open.
115
+ *
116
+ * Resolution order:
117
+ * 1. Feature off / no runner / no source text → truncation fallback.
118
+ * 2. Model call succeeds with usable text → the sanitised semantic title.
119
+ * 3. Model call errors, times out, or returns
120
+ * nothing usable → truncation fallback.
121
+ *
122
+ * The returned `source` lets the caller decide whether to broadcast an update
123
+ * (only a `'model'` title is worth replacing the already-applied truncation).
124
+ *
125
+ * @param {object} args
126
+ * @param {string} args.firstUserMessage
127
+ * @param {string} [args.firstAssistantResponse]
128
+ * @param {boolean} [args.enabled] - feature gate; false → truncation.
129
+ * @param {string} [args.model] - model id/alias for the one-shot.
130
+ * @param {string} [args.cwd] - working dir for the one-shot.
131
+ * @param {Function} [args.runOneShot] - injected model runner ({ prompt, model, cwd, signal }) => Promise<string>.
132
+ * @param {AbortSignal} [args.signal]
133
+ * @param {string} [args.fallback] - precomputed truncation label (else derived from firstUserMessage).
134
+ * @returns {Promise<{ title: string, source: 'model'|'truncation' }>}
135
+ */
136
+ export async function generateSessionTitle({
137
+ firstUserMessage,
138
+ firstAssistantResponse,
139
+ enabled,
140
+ model,
141
+ cwd,
142
+ runOneShot,
143
+ signal,
144
+ fallback,
145
+ } = {}) {
146
+ const fallbackTitle = typeof fallback === 'string' && fallback
147
+ ? fallback
148
+ : truncateTitle(firstUserMessage)
149
+ const truncated = { title: fallbackTitle, source: 'truncation' }
150
+
151
+ if (enabled !== true) return truncated
152
+ if (typeof runOneShot !== 'function') return truncated
153
+
154
+ const source = typeof firstUserMessage === 'string' ? firstUserMessage.trim() : ''
155
+ if (!source) return truncated
156
+
157
+ try {
158
+ const prompt = buildTitlePrompt({ firstUserMessage: source, firstAssistantResponse })
159
+ const raw = await runOneShot({ prompt, model, cwd, signal })
160
+ const clean = sanitizeModelTitle(raw)
161
+ if (clean) return { title: clean, source: 'model' }
162
+ return truncated
163
+ } catch {
164
+ // Fail open — a failed/timed-out title call must never leave a session
165
+ // unnamed; the truncation label is always good enough.
166
+ return truncated
167
+ }
168
+ }
@@ -26,57 +26,82 @@ const STORE_FILE = 'session-tokens.json'
26
26
  * @param {object} opts
27
27
  * @param {string} opts.dir - directory to hold the store (e.g. `~/.chroxy`).
28
28
  * @param {object} [opts.keychain] - keychain module (injectable for tests).
29
- * @returns {{ load: () => Array<[string, object]>, save: (entries: Array<[string, object]>) => void }}
29
+ * @returns {{
30
+ * load: () => Array<[string, object]>,
31
+ * loadResult: () => { status: 'absent'|'ok'|'unreadable', entries: Array<[string, object]> },
32
+ * exists: () => boolean,
33
+ * save: (entries: Array<[string, object]>, opts?: { durable?: boolean }) => boolean,
34
+ * }}
30
35
  * `entries` is the `[token, meta]` pair list from the PairingManager map.
31
36
  */
32
37
  export function createSessionTokenStore({ dir, keychain = realKeychain } = {}) {
33
38
  const file = join(dir, STORE_FILE)
34
39
 
35
- return {
36
- load() {
37
- try {
38
- if (!existsSync(file)) return []
39
- // Enforce owner-only 0600 (POSIX) — same boundary as the credential store.
40
- // A world/group-readable token file is refused rather than trusted.
41
- if (process.platform !== 'win32') {
42
- const perms = statSync(file).mode & 0o777
43
- if (perms !== 0o600) {
44
- log.warn(`${file} has mode ${perms.toString(8).padStart(3, '0')}; refusing to read (must be 0600) — devices will re-pair`)
45
- return []
46
- }
40
+ // Read the store, distinguishing the THREE outcomes an interactive caller must
41
+ // not conflate (#6599): 'absent' (no file), 'ok' (read + decoded), 'unreadable'
42
+ // (file present but wrong perms / no keychain key / corrupt / undecryptable).
43
+ // The daemon's `load()` fail-softs all of these to `[]` (a re-pair is harmless);
44
+ // the tokens CLI uses `loadResult()` so it never overwrites a store it couldn't
45
+ // read, nor reports "0 tokens" for one it simply failed to decrypt.
46
+ function read() {
47
+ try {
48
+ if (!existsSync(file)) return { status: 'absent', entries: [] }
49
+ // Enforce owner-only 0600 (POSIX) — same boundary as the credential store.
50
+ // A world/group-readable token file is refused rather than trusted.
51
+ if (process.platform !== 'win32') {
52
+ const perms = statSync(file).mode & 0o777
53
+ if (perms !== 0o600) {
54
+ log.warn(`${file} has mode ${perms.toString(8).padStart(3, '0')}; refusing to read (must be 0600) — devices will re-pair`)
55
+ return { status: 'unreadable', entries: [] }
47
56
  }
48
- const parsed = JSON.parse(readFileSync(file, 'utf8'))
49
- if (isEncryptedEnvelope(parsed)) {
50
- const key = getOrCreateMasterKey(keychain)
51
- if (!key) {
52
- log.warn('session-token store is encrypted but no keychain key is available — devices will re-pair')
53
- return []
54
- }
55
- const data = decryptEnvelope(parsed, key)
56
- return Array.isArray(data?.entries) ? data.entries : []
57
+ }
58
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
59
+ if (isEncryptedEnvelope(parsed)) {
60
+ const key = getOrCreateMasterKey(keychain)
61
+ if (!key) {
62
+ log.warn('session-token store is encrypted but no keychain key is available — devices will re-pair')
63
+ return { status: 'unreadable', entries: [] }
57
64
  }
58
- // Plaintext fallback (no-keychain host).
59
- return Array.isArray(parsed?.entries) ? parsed.entries : []
60
- } catch (err) {
61
- // A missing / corrupt / undecryptable store is not fatal: the worst case
62
- // is that devices re-pair (the pre-#6598 behaviour). Never throw into the
63
- // auth path.
64
- log.warn(`could not load persisted session tokens (${err.message}) — devices will re-pair`)
65
- return []
65
+ const data = decryptEnvelope(parsed, key)
66
+ return { status: 'ok', entries: Array.isArray(data?.entries) ? data.entries : [] }
66
67
  }
67
- },
68
+ // Plaintext fallback (no-keychain host).
69
+ return { status: 'ok', entries: Array.isArray(parsed?.entries) ? parsed.entries : [] }
70
+ } catch (err) {
71
+ // A missing / corrupt / undecryptable store is not fatal for the daemon: the
72
+ // worst case is that devices re-pair (the pre-#6598 behaviour). Never throw
73
+ // into the auth path. Report 'unreadable' so an interactive caller can tell
74
+ // this apart from a genuinely-empty store.
75
+ log.warn(`could not load persisted session tokens (${err.message}) — devices will re-pair`)
76
+ return { status: 'unreadable', entries: [] }
77
+ }
78
+ }
79
+
80
+ return {
81
+ load: () => read().entries,
82
+ loadResult: read,
83
+ exists: () => existsSync(file),
68
84
 
69
- save(entries) {
85
+ // `durable` (#6914): fsync the store to disk before returning success. The
86
+ // fail-CLOSED REVOKE path (`_persistSessionTokensSnapshot`) sets it so a
87
+ // power loss within the OS writeback window can't resurrect a revoked token
88
+ // after a reported-successful revoke. The fail-SAFE mint / slide / sweep
89
+ // path leaves it off (default) — a lost page-cache write there merely forces
90
+ // a harmless re-pair, and an fsync per token issuance is not worth the I/O.
91
+ save(entries, { durable = false } = {}) {
70
92
  try {
71
93
  mkdirSync(dir, { recursive: true })
72
94
  const payload = { v: 1, entries }
73
95
  const key = getOrCreateMasterKey(keychain)
74
96
  const body = key ? JSON.stringify(encryptJson(payload, key)) : JSON.stringify(payload)
75
- writeFileRestricted(file, body)
97
+ writeFileRestricted(file, body, { durable })
98
+ return true
76
99
  } catch (err) {
77
- // Persistence is best-effort: a failed write just means a restart may
78
- // require re-pairing. Don't let it break token issuance.
100
+ // Persistence is best-effort for the daemon (a failed write just means a
101
+ // restart may require re-pairing), so we don't throw; but RETURN false so
102
+ // an interactive caller can report the failure instead of a false success.
79
103
  log.warn(`could not persist session tokens (${err.message})`)
104
+ return false
80
105
  }
81
106
  },
82
107
  }
@@ -46,6 +46,7 @@ import { join } from 'node:path'
46
46
  import { createLogger } from './logger.js'
47
47
  import { loadJsonState, saveJsonState } from './json-state-file.js'
48
48
  import { getErrorMessage } from './utils/error-message.js'
49
+ import { MAX_WIRE_DATETIME_MS } from './utils/iso-datetime.js'
49
50
 
50
51
  const log = createLogger('skills-usage')
51
52
 
@@ -115,7 +116,17 @@ function normalizeAggregate(agg) {
115
116
  const count = typeof agg.count === 'number' && Number.isFinite(agg.count) && agg.count >= 0
116
117
  ? Math.trunc(agg.count)
117
118
  : 0
118
- const lastUsed = typeof agg.lastUsed === 'number' && Number.isFinite(agg.lastUsed) && agg.lastUsed > 0
119
+ // #7081: bound the RANGE, not just the type. `lastUsed` is rendered by
120
+ // skills-inventory.js via `new Date(ms).toISOString()` into a
121
+ // `z.string().datetime()` field, and there is a band above year 9999 where
122
+ // toISOString SUCCEEDS but emits the expanded-year form the wire rejects —
123
+ // which failed the whole snapshot's safeParse and left the Skills tab
124
+ // spinning with Refresh disabled. The adjacent `count` above already
125
+ // Math.truncs to match its int cap; this is the same rule, applied.
126
+ const lastUsed = typeof agg.lastUsed === 'number'
127
+ && Number.isFinite(agg.lastUsed)
128
+ && agg.lastUsed > 0
129
+ && agg.lastUsed <= MAX_WIRE_DATETIME_MS
119
130
  ? agg.lastUsed
120
131
  : null
121
132
  const repos = []
@@ -184,7 +195,14 @@ export function saveUsageStore(store, filePath = defaultSkillsUsagePath()) {
184
195
  export function applyUsage(store, record) {
185
196
  const skill = record && typeof record.skill === 'string' && record.skill.length > 0 ? record.skill : null
186
197
  if (!skill) return store
187
- const ts = typeof record.ts === 'number' && Number.isFinite(record.ts) && record.ts > 0 ? record.ts : Date.now()
198
+ // #7081: bound the RANGE here too. normalizeAggregate guards the LOAD path, but
199
+ // this is the WRITE path — it wrote `ts` verbatim into agg.lastUsed, persisting a
200
+ // number the next snapshot could not render. An out-of-range ts falls back to
201
+ // now(), which is what an unparseable one already did.
202
+ const tsRaw = record.ts
203
+ const ts = typeof tsRaw === 'number' && Number.isFinite(tsRaw) && tsRaw > 0 && tsRaw <= MAX_WIRE_DATETIME_MS
204
+ ? tsRaw
205
+ : Date.now()
188
206
  const sessionId = typeof record.sessionId === 'string' && record.sessionId.length > 0 ? record.sessionId : null
189
207
  const repo = typeof record.repo === 'string' && record.repo.length > 0 ? record.repo : null
190
208