@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.
- package/CONFIG.md +411 -14
- package/hooks/permission-hook.sh +253 -3
- package/package.json +8 -15
- package/sidecar/node_modules/.package-lock.json +29 -0
- package/sidecar/node_modules/ws/LICENSE +20 -0
- package/sidecar/node_modules/ws/README.md +548 -0
- package/sidecar/node_modules/ws/browser.js +8 -0
- package/sidecar/node_modules/ws/index.js +22 -0
- package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
- package/sidecar/node_modules/ws/lib/constants.js +19 -0
- package/sidecar/node_modules/ws/lib/event-target.js +292 -0
- package/sidecar/node_modules/ws/lib/extension.js +203 -0
- package/sidecar/node_modules/ws/lib/limiter.js +55 -0
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
- package/sidecar/node_modules/ws/lib/receiver.js +706 -0
- package/sidecar/node_modules/ws/lib/sender.js +602 -0
- package/sidecar/node_modules/ws/lib/stream.js +161 -0
- package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
- package/sidecar/node_modules/ws/lib/validation.js +152 -0
- package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
- package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
- package/sidecar/node_modules/ws/package.json +70 -0
- package/sidecar/node_modules/ws/wrapper.mjs +21 -0
- package/src/base-session.js +151 -6
- package/src/billing-budget.js +5 -1
- package/src/binary-provenance-trust.js +95 -0
- package/src/built-in-tools/file-ops.js +5 -4
- package/src/byok-mcp-client.js +1061 -13
- package/src/byok-mcp-config.js +1201 -4
- package/src/byok-mcp-fleet.js +374 -29
- package/src/byok-mcp-oauth-store.js +327 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +254 -37
- package/src/byok-session.js +789 -13
- package/src/byok-tool-executor.js +20 -13
- package/src/checkpoint-manager.js +33 -6
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-stream-parser.js +56 -0
- package/src/claude-tui/pty-driver.js +54 -14
- package/src/claude-tui-session.js +106 -7
- package/src/cli/config-cmd.js +2 -2
- package/src/cli/deploy-cmd.js +1 -1
- package/src/cli/init-cmd.js +1 -1
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +775 -0
- package/src/cli/server-cmd.js +16 -1
- package/src/cli/service-cmd.js +39 -19
- package/src/cli/shared.js +7 -4
- package/src/cli/tokens-cmd.js +213 -0
- package/src/cli/tunnel-cmd.js +1 -1
- package/src/cli-session.js +66 -10
- package/src/cli.js +4 -0
- package/src/codex-app-server-session.js +671 -39
- package/src/codex-session.js +121 -18
- package/src/config.js +453 -27
- package/src/control-room/integrations.js +16 -10
- package/src/control-room/skills-inventory.js +6 -1
- package/src/control-room/survey.js +32 -0
- package/src/credential-store.js +256 -10
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
- package/src/diagnostics.js +3 -0
- package/src/docker-sdk-session.js +16 -1
- package/src/docker-session.js +9 -0
- package/src/doctor.js +19 -8
- package/src/environments/backends/docker.js +8 -0
- package/src/environments/backends/k8s.js +9 -0
- package/src/event-ingest.js +19 -1
- package/src/event-normalizer.js +354 -19
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +19 -2
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +42 -8
- package/src/handlers/checkpoint-handlers.js +126 -19
- package/src/handlers/control-room-handlers.js +48 -18
- package/src/handlers/conversation-handlers.js +127 -2
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/file-handlers.js +47 -3
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +4 -0
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +510 -0
- package/src/handlers/session-handlers.js +10 -2
- package/src/handlers/settings-handlers.js +510 -11
- package/src/handlers/token-handlers.js +11 -2
- package/src/http-routes.js +159 -0
- package/src/jsonl-reader.js +60 -6
- package/src/jsonl-subprocess-session.js +35 -6
- package/src/keychain.js +159 -12
- package/src/logger.js +182 -19
- package/src/notification-prefs.js +88 -6
- package/src/notifications/discord-webhook-sink.js +30 -1
- package/src/orchestration/build-manager.js +56 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +347 -0
- package/src/orchestration/orchestration-manager.js +1295 -0
- package/src/orchestration/permission-gate.js +109 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +205 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +398 -0
- package/src/pairing.js +146 -1
- package/src/permission-audit.js +79 -3
- package/src/permission-floor.js +455 -0
- package/src/permission-manager.js +492 -40
- package/src/permission-resolver.js +55 -7
- package/src/permission-rule-store.js +411 -0
- package/src/platform.js +367 -23
- package/src/providers.js +21 -2
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +653 -0
- package/src/scheduler.js +1029 -0
- package/src/sdk-session.js +338 -5
- package/src/server-cli/server-orchestrator.js +23 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli.js +238 -26
- package/src/server-identity.js +28 -4
- package/src/service.js +291 -33
- package/src/session-manager.js +417 -25
- package/src/session-message-history.js +27 -21
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +60 -35
- package/src/skills-usage.js +20 -2
- package/src/statusline.js +584 -0
- package/src/subagent-counter.js +9 -1
- package/src/supervisor.js +77 -27
- package/src/token-manager.js +39 -9
- package/src/transcript-tasks.js +41 -6
- package/src/tunnel/cloudflare.js +115 -8
- package/src/tunnel/index.js +4 -1
- package/src/tunnel-check.js +1 -1
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +118 -0
- package/src/user-shell-session.js +98 -32
- package/src/utils/componentwise-resolver.js +205 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/preflight.js +140 -28
- package/src/utils/spawn-env.js +8 -2
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +241 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/worktree-gc.js +4 -1
- package/src/ws-file-ops/browser.js +42 -11
- package/src/ws-file-ops/common.js +68 -1
- package/src/ws-file-ops/git.js +221 -3
- package/src/ws-file-ops/index.js +5 -0
- package/src/ws-file-ops/memory.js +358 -0
- package/src/ws-file-ops/reader.js +124 -0
- package/src/ws-forwarding.js +44 -16
- package/src/ws-handler-context.js +19 -0
- package/src/ws-history.js +84 -11
- package/src/ws-message-handlers.js +6 -0
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +285 -4
- package/src/ws-schemas.js +1 -0
- package/src/ws-server.js +301 -17
package/src/supervisor.js
CHANGED
|
@@ -91,6 +91,10 @@ export class Supervisor extends EventEmitter {
|
|
|
91
91
|
this._tunnel = null
|
|
92
92
|
this._heartbeatInterval = null
|
|
93
93
|
this._currentWsUrl = null
|
|
94
|
+
// #6641: true while the tunnel is up but not routable — the server runs
|
|
95
|
+
// local/LAN-only and advertises no remote/QR access. Read by the degrade
|
|
96
|
+
// test; a natural gate for a future auto-reverify.
|
|
97
|
+
this._tunnelDegraded = false
|
|
94
98
|
this._signalsRegistered = false
|
|
95
99
|
this._restartScheduledAt = null
|
|
96
100
|
this._restartDelayMs = null
|
|
@@ -260,7 +264,7 @@ export class Supervisor extends EventEmitter {
|
|
|
260
264
|
|
|
261
265
|
async start() {
|
|
262
266
|
if (!this._apiToken) {
|
|
263
|
-
process.stderr.write('[!] No API token configured. Run \'
|
|
267
|
+
process.stderr.write('[!] No API token configured. Run \'chroxy init\' first.\n')
|
|
264
268
|
this._exit(1)
|
|
265
269
|
return
|
|
266
270
|
}
|
|
@@ -321,41 +325,87 @@ export class Supervisor extends EventEmitter {
|
|
|
321
325
|
this._log.error(message)
|
|
322
326
|
})
|
|
323
327
|
|
|
324
|
-
// 2
|
|
325
|
-
//
|
|
326
|
-
//
|
|
327
|
-
//
|
|
328
|
-
//
|
|
329
|
-
//
|
|
330
|
-
//
|
|
331
|
-
//
|
|
328
|
+
// 2. Wait for the tunnel to be routable. #6641 — a not-yet-routable tunnel
|
|
329
|
+
// must NOT abort the whole daemon. The default `chroxy start` used to
|
|
330
|
+
// exit(1) here whenever a warming quick-tunnel edge answered with a status
|
|
331
|
+
// outside {502,530} (e.g. a bare 404 during route propagation), taking down
|
|
332
|
+
// local + LAN access with it. Instead, degrade to local/LAN: start the
|
|
333
|
+
// child anyway so the server is usable right now.
|
|
334
|
+
//
|
|
335
|
+
// Degraded mode does NOT auto-recover to remote: `tunnel_recovered` only
|
|
336
|
+
// fires when the cloudflared PROCESS flaps (tunnel/base.js), not when an
|
|
337
|
+
// alive-but-unroutable tunnel finishes propagating, and there is no
|
|
338
|
+
// routability re-poll. So we advertise NO remote/QR access and tell the
|
|
339
|
+
// operator to restart (or use --tunnel named) once the tunnel is routable,
|
|
340
|
+
// rather than promising a QR that would never appear. (An auto re-verify in
|
|
341
|
+
// degraded mode is a possible follow-up — see #6641.)
|
|
342
|
+
//
|
|
343
|
+
// #5314 (WP-1.4) note: on the SIGINT/SIGTERM path the no-orphan guarantee
|
|
344
|
+
// still holds — shutdown() stops the tunnel and the supervised child
|
|
345
|
+
// together. (The crash-loop give-up path, _serveTerminalDown(), does not
|
|
346
|
+
// stop the tunnel — a pre-existing gap, not introduced here.) A
|
|
347
|
+
// NON-routability error (an unexpected throw) still takes the old
|
|
348
|
+
// stop-cloudflared-then-exit cleanup path via _failBoot().
|
|
349
|
+
let tunnelRoutable = true
|
|
332
350
|
try {
|
|
333
351
|
await this._waitForTunnel(httpUrl)
|
|
352
|
+
} catch (err) {
|
|
353
|
+
if (err?.code !== 'TUNNEL_NOT_ROUTABLE') {
|
|
354
|
+
await this._failBoot(err)
|
|
355
|
+
return
|
|
356
|
+
}
|
|
357
|
+
tunnelRoutable = false
|
|
358
|
+
this._tunnelDegraded = true
|
|
359
|
+
this._log.warn(
|
|
360
|
+
'Tunnel not routable — starting in local/LAN mode; remote access is ' +
|
|
361
|
+
'unavailable. Restart once your network/tunnel is ready, or use ' +
|
|
362
|
+
`--tunnel named for a stable URL. ${err.message}`
|
|
363
|
+
)
|
|
364
|
+
}
|
|
334
365
|
|
|
335
|
-
|
|
366
|
+
// 3. Display + persist connection info. The QR is shown ONLY for a routable
|
|
367
|
+
// tunnel — a QR to a not-yet-routable endpoint just hangs the app (the exact
|
|
368
|
+
// failure #6641 addresses), so in degraded mode we advertise local/LAN only.
|
|
369
|
+
// A throw in this block (QR encode / disk write) still routes to _failBoot().
|
|
370
|
+
try {
|
|
336
371
|
const connectionUrl = `chroxy://${wsUrl.replace('wss://', '')}?token=${this._apiToken}`
|
|
337
372
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
373
|
+
if (tunnelRoutable) {
|
|
374
|
+
// 3a. Display connection info
|
|
375
|
+
this._log.info(`${this._modeLabel} ready`)
|
|
376
|
+
process.stdout.write('📱 Scan this QR code with the Chroxy app:\n\n')
|
|
377
|
+
await this._displayQr(connectionUrl)
|
|
378
|
+
process.stdout.write('\nOr connect manually:\n')
|
|
379
|
+
process.stdout.write(` URL: ${wsUrl}\n`)
|
|
380
|
+
process.stdout.write(` Token: ${maskToken(this._apiToken)}\n`)
|
|
381
|
+
const dashboardBase = httpUrl || `http://localhost:${this._port}`
|
|
382
|
+
process.stdout.write(` Dashboard: ${dashboardBase.replace(/\/+$/, '')}/dashboard\n`)
|
|
383
|
+
process.stdout.write('\n')
|
|
384
|
+
} else {
|
|
385
|
+
// 3a. Degraded: local/LAN only, no QR to a dead endpoint, and no false
|
|
386
|
+
// promise of auto-recovery (#6641 review).
|
|
387
|
+
process.stdout.write('\n⚠️ Tunnel not routable — serving on local/LAN only (no remote/QR access).\n')
|
|
388
|
+
process.stdout.write(` Dashboard: http://localhost:${this._port}/dashboard\n`)
|
|
389
|
+
process.stdout.write(` LAN: http://<this-machine-ip>:${this._port}/dashboard\n`)
|
|
390
|
+
process.stdout.write(` Token: ${maskToken(this._apiToken)}\n`)
|
|
391
|
+
process.stdout.write(' For remote (phone) access, restart once the tunnel is routable, or use --tunnel named.\n\n')
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// 3b. Write connection info file for programmatic access. In degraded mode
|
|
395
|
+
// OMIT the public wsUrl/httpUrl/connectionUrl (they're not routable) so no
|
|
396
|
+
// consumer advertises a dead endpoint — notably the dashboard /qr route
|
|
397
|
+
// falls back to connectionUrl, which would otherwise resurface the exact
|
|
398
|
+
// dead QR #6641 kills, just in the dashboard modal (#6641 review). The
|
|
399
|
+
// local `port` is still written so loopback CLIs (chroxy publish / pages)
|
|
400
|
+
// hit the right port even in tunnel mode (#5683).
|
|
349
401
|
writeConnectionInfo({
|
|
350
|
-
wsUrl,
|
|
351
|
-
httpUrl,
|
|
352
|
-
// #5683: the LOCAL listen port, so loopback CLIs (chroxy publish / pages)
|
|
353
|
-
// hit the right port even in tunnel mode, where httpUrl is the public
|
|
354
|
-
// trycloudflare URL with no :port to parse.
|
|
402
|
+
wsUrl: tunnelRoutable ? wsUrl : null,
|
|
403
|
+
httpUrl: tunnelRoutable ? httpUrl : null,
|
|
355
404
|
port: this._port,
|
|
356
405
|
apiToken: this._apiToken,
|
|
357
|
-
connectionUrl,
|
|
406
|
+
connectionUrl: tunnelRoutable ? connectionUrl : null,
|
|
358
407
|
tunnelMode: this._modeLabel,
|
|
408
|
+
tunnelDegraded: !tunnelRoutable,
|
|
359
409
|
startedAt: new Date().toISOString(),
|
|
360
410
|
pid: process.pid,
|
|
361
411
|
})
|
package/src/token-manager.js
CHANGED
|
@@ -16,7 +16,14 @@ const log = createLogger('token-manager')
|
|
|
16
16
|
* 4. Calls the persist callback to save the new token
|
|
17
17
|
*
|
|
18
18
|
* Events:
|
|
19
|
-
* token_rotated { oldToken, newToken, expiresAt, reason }
|
|
19
|
+
* token_rotated { oldToken, newToken, expiresAt, reason, persisted }
|
|
20
|
+
*
|
|
21
|
+
* `persisted` (#6965) is a Promise for the `onPersist` write (null when no persist
|
|
22
|
+
* callback is configured). It settles when whichever storage path ran has completed —
|
|
23
|
+
* including its fsync where the persist site performs one (the `config.json` fallback
|
|
24
|
+
* on a durable revoke; the OS keychain owns its own durability) — and REJECTS if the
|
|
25
|
+
* write failed. It exists so the revoke's client-facing ack can be gated on the write
|
|
26
|
+
* instead of racing it.
|
|
20
27
|
*
|
|
21
28
|
* `reason` distinguishes a scheduled/periodic rotation ('scheduled') from an
|
|
22
29
|
* operator revoke ('revoke', via `revoke()`). A revoke is the panic button:
|
|
@@ -44,7 +51,12 @@ export class TokenManager extends EventEmitter {
|
|
|
44
51
|
* @param {string} opts.token - Current API token
|
|
45
52
|
* @param {string|null} opts.tokenExpiry - Expiry duration (e.g. '24h', '7d') or null
|
|
46
53
|
* @param {number} opts.graceMs - Grace period in ms (default: 5 min)
|
|
47
|
-
* @param {Function} opts.onPersist - Callback to save new token:
|
|
54
|
+
* @param {Function} opts.onPersist - Callback to save new token:
|
|
55
|
+
* `async (newToken, { reason }) => {}`. `reason` is 'scheduled' | 'revoke'
|
|
56
|
+
* (#6927) so the persist site can make the panic-button revoke DURABLE while
|
|
57
|
+
* leaving the routine scheduled rotation non-durable. #6965: it MUST reject (or
|
|
58
|
+
* throw) when the write fails — the revoke ack is gated on it resolving, so a
|
|
59
|
+
* swallowed error there is reported to the operator as a successful revoke.
|
|
48
60
|
*/
|
|
49
61
|
constructor({ token, tokenExpiry, graceMs, onPersist } = {}) {
|
|
50
62
|
super()
|
|
@@ -154,21 +166,39 @@ export class TokenManager extends EventEmitter {
|
|
|
154
166
|
log.info(`Token rotated`)
|
|
155
167
|
}
|
|
156
168
|
|
|
169
|
+
// Persist the new token. #6927 — forward `reason` so the persist site can
|
|
170
|
+
// fsync a 'revoke' (the operator panic button killing a compromised token)
|
|
171
|
+
// while leaving a routine 'scheduled' rotation non-durable.
|
|
172
|
+
//
|
|
173
|
+
// #6965 — the persist is STARTED before the event is emitted and the resulting
|
|
174
|
+
// promise rides the event as `persisted`, so the revoke's client-facing ACK can
|
|
175
|
+
// be gated on the durable write actually landing (see WsServer's `token_rotated`
|
|
176
|
+
// handler). Previously this was fire-and-forget emitted AFTER the ack: the
|
|
177
|
+
// operator could be told the highest-authority token was dead while a power loss
|
|
178
|
+
// in the writeback window brought the daemon back still honouring it.
|
|
179
|
+
// The async wrapper turns a SYNCHRONOUS throw from `onPersist` into a rejection,
|
|
180
|
+
// so a failing persist can never escape as an exception out of rotate() and can
|
|
181
|
+
// never masquerade as success.
|
|
182
|
+
let persisted = null
|
|
183
|
+
if (this._onPersist) {
|
|
184
|
+
persisted = (async () => this._onPersist(newToken, { reason }))()
|
|
185
|
+
// Attach a handler unconditionally: the log line is the SCHEDULED path's only
|
|
186
|
+
// report, and it also guarantees no unhandled rejection when nothing consumes
|
|
187
|
+
// `persisted` (no WsServer wired, or a listener that ignores it).
|
|
188
|
+
persisted.catch((err) => {
|
|
189
|
+
log.error(`Failed to persist new token: ${err?.message || err}`)
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
|
|
157
193
|
// Emit event for WsServer to broadcast to clients
|
|
158
194
|
this.emit('token_rotated', {
|
|
159
195
|
oldToken,
|
|
160
196
|
newToken,
|
|
161
197
|
expiresAt: this._expiresAt,
|
|
162
198
|
reason,
|
|
199
|
+
persisted,
|
|
163
200
|
})
|
|
164
201
|
|
|
165
|
-
// Persist the new token
|
|
166
|
-
if (this._onPersist) {
|
|
167
|
-
Promise.resolve(this._onPersist(newToken)).catch(err => {
|
|
168
|
-
log.error(`Failed to persist new token: ${err.message}`)
|
|
169
|
-
})
|
|
170
|
-
}
|
|
171
|
-
|
|
172
202
|
// Start grace period for the old token — scheduled rotations only. A revoke
|
|
173
203
|
// killed the old token above and must not resurrect it via a grace window.
|
|
174
204
|
if (!isRevoke) {
|
package/src/transcript-tasks.js
CHANGED
|
@@ -285,12 +285,39 @@ export class TranscriptTaskScanner {
|
|
|
285
285
|
if (name === 'ScheduleWakeup') {
|
|
286
286
|
const delaySeconds = Number(input.delaySeconds)
|
|
287
287
|
if (Number.isFinite(delaySeconds) && delaySeconds >= 0) {
|
|
288
|
-
|
|
289
|
-
//
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
288
|
+
const at = startedAt + delaySeconds * 1000
|
|
289
|
+
// #7084: the computed instant must be a SAFE integer, not merely finite.
|
|
290
|
+
// `delaySeconds` is model-authored tool input, so it is arbitrary JSON, and the
|
|
291
|
+
// wire schema is `z.number().int().nonnegative().finite()` — where Zod's
|
|
292
|
+
// `.int()` enforces the SAFE-integer range, not just integrality. Two reachable
|
|
293
|
+
// shapes fail it:
|
|
294
|
+
// delaySeconds: 0.0001 -> a fractional `at` (invalid_type)
|
|
295
|
+
// delaySeconds: 1e15 -> an `at` past 2^53 (too_big)
|
|
296
|
+
// Measured against the built schema; 9e12 still fits, so the ceiling is real
|
|
297
|
+
// rather than theoretical.
|
|
298
|
+
//
|
|
299
|
+
// DROP the wakeup rather than clamp it. The field is optional, and any clamp
|
|
300
|
+
// renders a precise-looking lie about when the agent will wake — clamping to
|
|
301
|
+
// MAX_SAFE_INTEGER actually yields an Invalid Date, and to Date's own ceiling
|
|
302
|
+
// (8.64e15) yields "13 Sep 275760". Neither is a time. A nonsense delay means
|
|
303
|
+
// the tool call is garbage, so having no scheduled wakeup is the honest state.
|
|
304
|
+
//
|
|
305
|
+
// Ignoring (rather than clearing an existing wakeup) matches what this guard
|
|
306
|
+
// already did for a NaN `delaySeconds`: invalid input leaves any previously
|
|
307
|
+
// armed wakeup alone instead of destroying it.
|
|
308
|
+
// `at >= 0` is DEFENCE-IN-DEPTH, not load-bearing: measured, no input reaches
|
|
309
|
+
// the snapshot with a negative `at`, because the consumption path already treats
|
|
310
|
+
// a wakeup whose instant has passed as spent and every negative instant is past.
|
|
311
|
+
// Kept because it is free and states the wire contract at the point of
|
|
312
|
+
// construction — but do not read it as a guard with test coverage.
|
|
313
|
+
if (Number.isSafeInteger(at) && at >= 0) {
|
|
314
|
+
// A newer ScheduleWakeup supersedes any earlier pending one — the
|
|
315
|
+
// harness keeps at most one timer armed.
|
|
316
|
+
this._wakeup = {
|
|
317
|
+
at,
|
|
318
|
+
reason: typeof input.reason === 'string' ? input.reason : '',
|
|
319
|
+
prompt: typeof input.prompt === 'string' ? input.prompt : '',
|
|
320
|
+
}
|
|
294
321
|
}
|
|
295
322
|
}
|
|
296
323
|
return
|
|
@@ -310,6 +337,14 @@ export class TranscriptTaskScanner {
|
|
|
310
337
|
: typeof input.prompt === 'string'
|
|
311
338
|
? input.prompt.slice(0, PROMPT_DESCRIPTION_MAX)
|
|
312
339
|
: ''
|
|
340
|
+
// #7084: `startedAt` carries the byte-identical wire constraint to
|
|
341
|
+
// scheduledWakeup.at — BackgroundTaskSchema.startedAt is
|
|
342
|
+
// `z.number().int().nonnegative().finite()` — and had no guard at all. It comes
|
|
343
|
+
// from Date.parse of a transcript timestamp, so a pre-epoch entry yields a negative
|
|
344
|
+
// instant (verified: 1960-01-01 -> -315619200000, which the schema refuses as
|
|
345
|
+
// too_small). Drop the task rather than emit an unrepresentable one; the snapshot
|
|
346
|
+
// is a list, so one bad entry would otherwise fail the whole claude_ready frame.
|
|
347
|
+
if (!Number.isSafeInteger(startedAt) || startedAt < 0) return
|
|
313
348
|
this._tasks.set(block.id, { toolUseId: block.id, kind, description, startedAt })
|
|
314
349
|
}
|
|
315
350
|
|
package/src/tunnel/cloudflare.js
CHANGED
|
@@ -1,9 +1,36 @@
|
|
|
1
1
|
import { spawn, execFileSync } from 'child_process'
|
|
2
|
+
import { homedir } from 'os'
|
|
3
|
+
import { join } from 'path'
|
|
2
4
|
import { BaseTunnelAdapter } from './base.js'
|
|
3
5
|
import { createLogger, redactSensitive } from '../logger.js'
|
|
6
|
+
import { cloudflaredInstallHint } from '../platform.js'
|
|
7
|
+
import { resolveBinary as defaultResolveBinary } from '../utils/resolve-binary.js'
|
|
8
|
+
import { verifyBinary as defaultVerifyBinary } from '../utils/verify-binary.js'
|
|
9
|
+
import { verifyProvenance as defaultVerifyProvenance, PROVENANCE_STATUS } from '../utils/verify-provenance.js'
|
|
4
10
|
|
|
5
11
|
const log = createLogger('tunnel')
|
|
6
12
|
|
|
13
|
+
// Well-known cloudflared install locations (mirrors doctor.js) so provenance can
|
|
14
|
+
// resolve the SAME absolute path the spawn will use even under a minimal PATH.
|
|
15
|
+
const CLOUDFLARED_CANDIDATES = [
|
|
16
|
+
'/opt/homebrew/bin/cloudflared',
|
|
17
|
+
'/usr/local/bin/cloudflared',
|
|
18
|
+
join(homedir(), '.local/bin/cloudflared'),
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Thrown when the opt-in provenance gate (#6858) refuses to spawn `cloudflared`
|
|
23
|
+
* because its pinned SHA-256 changed in place (block mode) or it failed the
|
|
24
|
+
* macOS signature gate. Never thrown when the gate is off (the default).
|
|
25
|
+
*/
|
|
26
|
+
export class TunnelBinaryProvenanceError extends Error {
|
|
27
|
+
constructor(message) {
|
|
28
|
+
super(message)
|
|
29
|
+
this.name = 'TunnelBinaryProvenanceError'
|
|
30
|
+
this.code = 'TUNNEL_BINARY_PROVENANCE'
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
7
34
|
// #5328 (WP-5.6): how much of cloudflared's recent output to retain so a
|
|
8
35
|
// startup failure can quote the REAL reason in its error, not just an exit code.
|
|
9
36
|
const CLOUDFLARED_OUTPUT_TAIL_CAP = 2000
|
|
@@ -26,11 +53,27 @@ function redactedTail(rawTail) {
|
|
|
26
53
|
* Named mode: spawns `cloudflared tunnel run <name>` — stable URL via DNS CNAME.
|
|
27
54
|
*/
|
|
28
55
|
export class CloudflareTunnelAdapter extends BaseTunnelAdapter {
|
|
29
|
-
constructor({
|
|
56
|
+
constructor({
|
|
57
|
+
port, mode = 'quick', config = {}, tunnelName, tunnelHostname,
|
|
58
|
+
// #6858 test seams — injected so the provenance gate is exercisable without a
|
|
59
|
+
// real cloudflared / ledger file. Production falls through to the real ones.
|
|
60
|
+
resolveBinary = defaultResolveBinary,
|
|
61
|
+
verifyBinary = defaultVerifyBinary,
|
|
62
|
+
verifyProvenance = defaultVerifyProvenance,
|
|
63
|
+
} = {}) {
|
|
30
64
|
super({ port, mode, config })
|
|
31
65
|
// Support both config object keys and legacy top-level constructor args
|
|
32
66
|
this.tunnelName = config.tunnelName ?? tunnelName ?? null
|
|
33
67
|
this.tunnelHostname = config.tunnelHostname ?? tunnelHostname ?? null
|
|
68
|
+
this._resolveBinary = resolveBinary
|
|
69
|
+
this._verifyBinary = verifyBinary
|
|
70
|
+
this._verifyProvenance = verifyProvenance
|
|
71
|
+
// #6937: the EXACT absolute cloudflared path the provenance gate resolved +
|
|
72
|
+
// verified, pinned so the spawn execs the same bytes we checked even if PATH
|
|
73
|
+
// changes between verify and spawn. null when the gate is off or the binary
|
|
74
|
+
// didn't resolve/verify — the spawn then falls back to the bare name and the
|
|
75
|
+
// normal ENOENT/doctor path, so default (feature-off) behaviour is unchanged.
|
|
76
|
+
this._resolvedCloudflaredPath = null
|
|
34
77
|
}
|
|
35
78
|
|
|
36
79
|
static get name() {
|
|
@@ -43,7 +86,7 @@ export class CloudflareTunnelAdapter extends BaseTunnelAdapter {
|
|
|
43
86
|
stableUrl: false,
|
|
44
87
|
binaryName: 'cloudflared',
|
|
45
88
|
setupRequired: false,
|
|
46
|
-
installHint:
|
|
89
|
+
installHint: cloudflaredInstallHint(),
|
|
47
90
|
}
|
|
48
91
|
}
|
|
49
92
|
|
|
@@ -60,7 +103,7 @@ export class CloudflareTunnelAdapter extends BaseTunnelAdapter {
|
|
|
60
103
|
return {
|
|
61
104
|
available: false,
|
|
62
105
|
version: null,
|
|
63
|
-
hint:
|
|
106
|
+
hint: `Install with: ${cloudflaredInstallHint()}`,
|
|
64
107
|
}
|
|
65
108
|
}
|
|
66
109
|
}
|
|
@@ -71,10 +114,74 @@ export class CloudflareTunnelAdapter extends BaseTunnelAdapter {
|
|
|
71
114
|
|
|
72
115
|
/** Override point for test injection */
|
|
73
116
|
_spawnCloudflared(argv, spawnOpts) {
|
|
74
|
-
|
|
117
|
+
// Spawn the EXACT verified absolute path when the provenance gate pinned one
|
|
118
|
+
// (#6937), so a PATH change between verify and spawn can't swap in a different
|
|
119
|
+
// binary than the one we checked. Falls back to the bare name when the gate is
|
|
120
|
+
// off / the binary didn't resolve — preserving default (feature-off) behaviour.
|
|
121
|
+
const bin = this._resolvedCloudflaredPath || 'cloudflared'
|
|
122
|
+
return spawn(bin, argv, spawnOpts)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* #6858: opt-in pre-spawn provenance gate for `cloudflared`. `cloudflared` is
|
|
127
|
+
* spawned by bare name (resolved off PATH) with the operator's network, so it
|
|
128
|
+
* shares the provider binaries' supply-chain surface — this folds it into the
|
|
129
|
+
* SAME pin ledger + signature gate.
|
|
130
|
+
*
|
|
131
|
+
* No-op unless `config.binaryProvenance` opted in (mode warn/block or the
|
|
132
|
+
* signature gate). A binary that can't be resolved is left to the normal spawn
|
|
133
|
+
* ENOENT path (provenance must not mask "cloudflared not installed"). Fail-safe:
|
|
134
|
+
* a block-mode hash mismatch or a failed signature gate THROWS
|
|
135
|
+
* TunnelBinaryProvenanceError before any spawn; a warn-mode issue logs and
|
|
136
|
+
* proceeds.
|
|
137
|
+
*/
|
|
138
|
+
_verifyCloudflaredProvenance() {
|
|
139
|
+
// Clear any path pinned by a previous start attempt up front, so if the gate
|
|
140
|
+
// is now off — or the binary has since become unresolvable/unhealthy — the
|
|
141
|
+
// spawn falls back to the bare name instead of exec'ing a stale absolute path.
|
|
142
|
+
this._resolvedCloudflaredPath = null
|
|
143
|
+
|
|
144
|
+
const prov = this.config && this.config.binaryProvenance
|
|
145
|
+
const enabled = prov
|
|
146
|
+
&& (prov.mode === 'warn' || prov.mode === 'block' || prov.signatureGate === true)
|
|
147
|
+
if (!enabled) return
|
|
148
|
+
|
|
149
|
+
const resolved = this._resolveBinary('cloudflared', CLOUDFLARED_CANDIDATES)
|
|
150
|
+
// Only gate a binary that actually resolves to a real, healthy file — a
|
|
151
|
+
// missing/quarantined cloudflared is surfaced by the spawn / doctor path, not
|
|
152
|
+
// here (provenance is about "is this the binary I pinned", not "does it exist").
|
|
153
|
+
const health = this._verifyBinary(resolved)
|
|
154
|
+
if (!health.ok) return
|
|
155
|
+
|
|
156
|
+
const verdict = this._verifyProvenance({
|
|
157
|
+
resolvedPath: health.path,
|
|
158
|
+
mode: prov.mode || 'off',
|
|
159
|
+
signatureGate: prov.signatureGate === true,
|
|
160
|
+
ledger: prov.ledger || null,
|
|
161
|
+
})
|
|
162
|
+
if (verdict.blocked) {
|
|
163
|
+
throw new TunnelBinaryProvenanceError(
|
|
164
|
+
`Refusing to spawn cloudflared: "${verdict.path}" ${verdict.message || 'failed provenance verification'}`
|
|
165
|
+
+ `${verdict.remediation ? ` — ${verdict.remediation}` : ''}`,
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
if (
|
|
169
|
+
verdict.status === PROVENANCE_STATUS.HASH_MISMATCH
|
|
170
|
+
|| verdict.status === PROVENANCE_STATUS.SIGNATURE_INVALID
|
|
171
|
+
|| verdict.status === PROVENANCE_STATUS.UNREADABLE
|
|
172
|
+
) {
|
|
173
|
+
log.warn(`cloudflared provenance ${verdict.status}: ${verdict.message || ''} (allowed — mode=${prov.mode})`)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Provenance passed (or a warn-mode issue was surfaced + allowed): pin the
|
|
177
|
+
// EXACT absolute path we just verified so _spawnCloudflared execs those bytes,
|
|
178
|
+
// not whatever `cloudflared` resolves to off PATH at spawn time (#6937).
|
|
179
|
+
this._resolvedCloudflaredPath = health.path
|
|
75
180
|
}
|
|
76
181
|
|
|
77
182
|
async _startTunnel() {
|
|
183
|
+
// #6858: gate the binary before either start path spawns it.
|
|
184
|
+
this._verifyCloudflaredProvenance()
|
|
78
185
|
if (this.mode === 'named') {
|
|
79
186
|
return this._startNamedTunnel()
|
|
80
187
|
}
|
|
@@ -147,7 +254,7 @@ export class CloudflareTunnelAdapter extends BaseTunnelAdapter {
|
|
|
147
254
|
|
|
148
255
|
proc.on('error', (err) => {
|
|
149
256
|
if (!resolved) {
|
|
150
|
-
reject(new Error(`Failed to start cloudflared: ${err.message}. Install with:
|
|
257
|
+
reject(new Error(`Failed to start cloudflared: ${err.message}. Install with: ${cloudflaredInstallHint()}`))
|
|
151
258
|
}
|
|
152
259
|
})
|
|
153
260
|
|
|
@@ -176,7 +283,7 @@ export class CloudflareTunnelAdapter extends BaseTunnelAdapter {
|
|
|
176
283
|
timedOut = true
|
|
177
284
|
proc.kill()
|
|
178
285
|
const tail = redactedTail(outputTailRaw)
|
|
179
|
-
reject(new Error(`Tunnel timed out after 30s. Is cloudflared installed and logged in? (
|
|
286
|
+
reject(new Error(`Tunnel timed out after 30s. Is cloudflared installed and logged in? (${cloudflaredInstallHint()})${tail ? `. Last output: ${tail}` : ''}`))
|
|
180
287
|
}
|
|
181
288
|
}, 30_000)
|
|
182
289
|
// Don't let the 30s start-timeout timer pin the event loop on success —
|
|
@@ -241,7 +348,7 @@ export class CloudflareTunnelAdapter extends BaseTunnelAdapter {
|
|
|
241
348
|
|
|
242
349
|
proc.on('error', (err) => {
|
|
243
350
|
if (!resolved) {
|
|
244
|
-
reject(new Error(`Failed to start cloudflared: ${err.message}. Install with:
|
|
351
|
+
reject(new Error(`Failed to start cloudflared: ${err.message}. Install with: ${cloudflaredInstallHint()}`))
|
|
245
352
|
}
|
|
246
353
|
})
|
|
247
354
|
|
|
@@ -267,7 +374,7 @@ export class CloudflareTunnelAdapter extends BaseTunnelAdapter {
|
|
|
267
374
|
timedOut = true
|
|
268
375
|
proc.kill()
|
|
269
376
|
const tail = redactedTail(outputTailRaw)
|
|
270
|
-
reject(new Error(`Tunnel timed out after 30s. Is cloudflared installed? (
|
|
377
|
+
reject(new Error(`Tunnel timed out after 30s. Is cloudflared installed? (${cloudflaredInstallHint()})${tail ? `. Last output: ${tail}` : ''}`))
|
|
271
378
|
}
|
|
272
379
|
}, 30_000)
|
|
273
380
|
// Don't let the 30s start-timeout timer pin the event loop on success.
|
package/src/tunnel/index.js
CHANGED
|
@@ -38,7 +38,7 @@ export function parseTunnelArg(value) {
|
|
|
38
38
|
/**
|
|
39
39
|
* Create a CloudflareTunnelAdapter instance from a config object.
|
|
40
40
|
*
|
|
41
|
-
* @param {{ port: number, mode: string, tunnelConfig?: object, tunnelName?: string, tunnelHostname?: string }} config
|
|
41
|
+
* @param {{ port: number, mode: string, tunnelConfig?: object, tunnelName?: string, tunnelHostname?: string, binaryProvenance?: object }} config
|
|
42
42
|
* @returns {CloudflareTunnelAdapter}
|
|
43
43
|
*/
|
|
44
44
|
export function createTunnel(config) {
|
|
@@ -49,6 +49,9 @@ export function createTunnel(config) {
|
|
|
49
49
|
...config.tunnelConfig,
|
|
50
50
|
tunnelName: config.tunnelName || null,
|
|
51
51
|
tunnelHostname: config.tunnelHostname || null,
|
|
52
|
+
// #6858: opt-in provenance gate for the cloudflared spawn. A plain-ish bag
|
|
53
|
+
// ({ mode, signatureGate, ledger }); undefined ⇒ the gate is skipped.
|
|
54
|
+
binaryProvenance: config.binaryProvenance || null,
|
|
52
55
|
},
|
|
53
56
|
})
|
|
54
57
|
}
|
package/src/tunnel-check.js
CHANGED
|
@@ -77,7 +77,7 @@ export async function waitForTunnel(httpUrl, { maxAttempts = 20, initialInterval
|
|
|
77
77
|
`Tunnel failed to become routable after ${maxAttempts} attempts (${elapsed}s). ` +
|
|
78
78
|
`${lastFailure ? `Last failure: ${lastFailure}. ` : ''}` +
|
|
79
79
|
'This usually means your network is blocking Cloudflare, or DNS has not propagated yet. ' +
|
|
80
|
-
'Try a named tunnel (--tunnel named) or run `
|
|
80
|
+
'Try a named tunnel (--tunnel named) or run `chroxy doctor` for diagnostics.'
|
|
81
81
|
)
|
|
82
82
|
err.code = 'TUNNEL_NOT_ROUTABLE'
|
|
83
83
|
throw err
|
package/src/turn-tracker.js
CHANGED
|
Binary file
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-provider per-model usage normalization (#6692).
|
|
3
|
+
*
|
|
4
|
+
* Every provider session emits a terminal `result` event whose flat `usage`
|
|
5
|
+
* object feeds the per-session accumulator (session-manager `_trackUsage`).
|
|
6
|
+
* What that flat shape cannot carry is a per-model split — the Agent SDK
|
|
7
|
+
* reports one (`msg.modelUsage`, camelCase keys) and single-model providers
|
|
8
|
+
* can synthesize one — so the result payload gains an ADDITIVE `modelUsage`
|
|
9
|
+
* field in the shape below. Token keys stay snake_case so any cell can be
|
|
10
|
+
* passed straight to `computePromptCostUsd` (models.js) unchanged.
|
|
11
|
+
*
|
|
12
|
+
* modelUsage: {
|
|
13
|
+
* [modelId]: {
|
|
14
|
+
* input_tokens, output_tokens,
|
|
15
|
+
* cache_read_input_tokens, cache_creation_input_tokens,
|
|
16
|
+
* web_search_requests,
|
|
17
|
+
* cost_usd, // provider-reported; null when unknown
|
|
18
|
+
* }
|
|
19
|
+
* } | null // null = provider produced nothing this turn
|
|
20
|
+
*
|
|
21
|
+
* Consumers must treat `modelUsage` as optional — `_trackUsage` and every
|
|
22
|
+
* existing subscriber ignore unknown result fields by design.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Clamp to a non-negative finite integer — mirrors `_trackUsage`'s
|
|
27
|
+
* tokenDelta coercion so a poisoned provider value can never drive an
|
|
28
|
+
* accumulator negative or NaN.
|
|
29
|
+
*/
|
|
30
|
+
export function nonNegInt(x) {
|
|
31
|
+
const n = Number(x)
|
|
32
|
+
if (!Number.isFinite(n) || n <= 0) return 0
|
|
33
|
+
return Math.floor(n)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Normalize the Agent SDK's per-model usage map (camelCase ModelUsage
|
|
38
|
+
* entries) into the wire contract above. Returns null when the input is
|
|
39
|
+
* absent, not an object, or normalizes to zero entries.
|
|
40
|
+
*/
|
|
41
|
+
// model ids come from provider output (untrusted). Reject the keys that could
|
|
42
|
+
// pollute a plain object so a hostile/buggy id can't reach `out[id] = …`.
|
|
43
|
+
const UNSAFE_KEY = new Set(['__proto__', 'constructor', 'prototype'])
|
|
44
|
+
const isSafeModelId = (id) => typeof id === 'string' && id.length > 0 && !UNSAFE_KEY.has(id)
|
|
45
|
+
|
|
46
|
+
export function normalizeSdkModelUsage(raw) {
|
|
47
|
+
if (!raw || typeof raw !== 'object') return null
|
|
48
|
+
const out = {}
|
|
49
|
+
for (const [modelId, u] of Object.entries(raw)) {
|
|
50
|
+
if (!isSafeModelId(modelId) || !u || typeof u !== 'object') continue
|
|
51
|
+
out[modelId] = {
|
|
52
|
+
input_tokens: nonNegInt(u.inputTokens ?? u.input_tokens),
|
|
53
|
+
output_tokens: nonNegInt(u.outputTokens ?? u.output_tokens),
|
|
54
|
+
cache_read_input_tokens: nonNegInt(u.cacheReadInputTokens ?? u.cache_read_input_tokens),
|
|
55
|
+
cache_creation_input_tokens: nonNegInt(u.cacheCreationInputTokens ?? u.cache_creation_input_tokens),
|
|
56
|
+
web_search_requests: nonNegInt(u.webSearchRequests ?? u.web_search_requests),
|
|
57
|
+
cost_usd: Number.isFinite(u.costUSD) ? u.costUSD : (Number.isFinite(u.cost_usd) ? u.cost_usd : null),
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return Object.keys(out).length > 0 ? out : null
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Build a single-entry modelUsage map for providers that run exactly one
|
|
65
|
+
* model per session (byok family, codex, gemini). `usage` is the provider's
|
|
66
|
+
* flat snake_case turn usage; absent fields clamp to 0. Returns null when
|
|
67
|
+
* the model id is unknown or the usage object carries no token signal at
|
|
68
|
+
* all, so a both-null synthetic result (stream-stall recovery) never
|
|
69
|
+
* fabricates an all-zero per-model row.
|
|
70
|
+
*
|
|
71
|
+
* Note the gate is BROADER than `_trackUsage`'s (session-manager.js), which
|
|
72
|
+
* keys only on a finite `input_tokens`: this returns a row when ANY of the 5
|
|
73
|
+
* token fields is finite. They coincide today because every provider call
|
|
74
|
+
* site emits a finite `input_tokens` (0 or positive) whenever `usage` is an
|
|
75
|
+
* object, so the sole divergence (an output-or-cache-only turn) can't arise.
|
|
76
|
+
* A future consumer that sums these rows against `cumulativeUsage` should not
|
|
77
|
+
* assume literal parity — if an output-only provider ever appears, this would
|
|
78
|
+
* synthesize a row `_trackUsage` skips.
|
|
79
|
+
*/
|
|
80
|
+
export function synthesizeModelUsage(model, usage, costUsd = null) {
|
|
81
|
+
if (!isSafeModelId(model)) return null
|
|
82
|
+
if (!usage || typeof usage !== 'object') return null
|
|
83
|
+
// A real numeric token field is the signal. Test `typeof === 'number'` (not
|
|
84
|
+
// Number(v)) so a provider's explicit null for a missing field is NOT read
|
|
85
|
+
// as 0 — `Number(null) === 0` is finite and would fabricate an all-zero row
|
|
86
|
+
// for a genuinely-empty turn. An explicit numeric 0 still counts as signal.
|
|
87
|
+
const anyTokenSignal = [
|
|
88
|
+
usage.input_tokens, usage.output_tokens,
|
|
89
|
+
usage.cache_read_input_tokens, usage.cached_input_tokens,
|
|
90
|
+
usage.cache_creation_input_tokens,
|
|
91
|
+
].some((v) => typeof v === 'number' && Number.isFinite(v))
|
|
92
|
+
if (!anyTokenSignal) return null
|
|
93
|
+
return {
|
|
94
|
+
[model]: {
|
|
95
|
+
input_tokens: nonNegInt(usage.input_tokens),
|
|
96
|
+
output_tokens: nonNegInt(usage.output_tokens),
|
|
97
|
+
// codex historically emitted `cached_input_tokens`; accept both so a
|
|
98
|
+
// caller can hand this the raw pre-#6692 shape without dropping cache.
|
|
99
|
+
cache_read_input_tokens: nonNegInt(usage.cache_read_input_tokens ?? usage.cached_input_tokens),
|
|
100
|
+
cache_creation_input_tokens: nonNegInt(usage.cache_creation_input_tokens),
|
|
101
|
+
web_search_requests: nonNegInt(usage.web_search_requests),
|
|
102
|
+
cost_usd: Number.isFinite(costUsd) ? costUsd : null,
|
|
103
|
+
},
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Whether a provider's sessions produce token telemetry at all. claude-tui
|
|
109
|
+
* and claude-channel emit `usage:null, cost:null` on every turn (Stop-hook
|
|
110
|
+
* limitation), so anything that needs metering — orchestration runs (#6691),
|
|
111
|
+
* cost comparisons — must refuse or caveat them. user-shell runs no model.
|
|
112
|
+
*/
|
|
113
|
+
const UNMETERABLE_PROVIDERS = new Set(['claude-tui', 'claude-channel', 'user-shell'])
|
|
114
|
+
|
|
115
|
+
export function isMeterableProvider(provider) {
|
|
116
|
+
if (!provider || typeof provider !== 'string') return false
|
|
117
|
+
return !UNMETERABLE_PROVIDERS.has(provider)
|
|
118
|
+
}
|