@namzu/sdk 74.0.0 → 74.1.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 (116) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/config/runtime.d.ts +3 -3
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/manager/session/turn-recorder.d.ts +1 -0
  8. package/dist/manager/session/turn-recorder.d.ts.map +1 -1
  9. package/dist/manager/session/turn-recorder.js +31 -7
  10. package/dist/manager/session/turn-recorder.js.map +1 -1
  11. package/dist/pricing/catalogue.generated.d.ts.map +1 -1
  12. package/dist/pricing/catalogue.generated.js +176 -21
  13. package/dist/pricing/catalogue.generated.js.map +1 -1
  14. package/dist/public-runtime.d.ts +1 -0
  15. package/dist/public-runtime.d.ts.map +1 -1
  16. package/dist/public-runtime.js +1 -0
  17. package/dist/public-runtime.js.map +1 -1
  18. package/dist/runtime/query/guard.d.ts.map +1 -1
  19. package/dist/runtime/query/guard.js +12 -2
  20. package/dist/runtime/query/guard.js.map +1 -1
  21. package/dist/runtime/query/index.d.ts.map +1 -1
  22. package/dist/runtime/query/index.js +1 -0
  23. package/dist/runtime/query/index.js.map +1 -1
  24. package/dist/runtime/query/iteration/index.d.ts +3 -0
  25. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  26. package/dist/runtime/query/iteration/index.js +32 -11
  27. package/dist/runtime/query/iteration/index.js.map +1 -1
  28. package/dist/runtime/query/iteration/phases/advisory.js +2 -2
  29. package/dist/runtime/query/iteration/phases/advisory.js.map +1 -1
  30. package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
  31. package/dist/runtime/query/prepare-turn.js +1 -1
  32. package/dist/runtime/query/prepare-turn.js.map +1 -1
  33. package/dist/sandbox/file-walk-program.js +1 -1
  34. package/dist/sandbox/ignore-matcher.d.ts +2 -0
  35. package/dist/sandbox/ignore-matcher.d.ts.map +1 -1
  36. package/dist/sandbox/ignore-matcher.js +8 -2
  37. package/dist/sandbox/ignore-matcher.js.map +1 -1
  38. package/dist/sandbox/ignore-source.d.ts.map +1 -1
  39. package/dist/sandbox/ignore-source.js +51 -7
  40. package/dist/sandbox/ignore-source.js.map +1 -1
  41. package/dist/sandbox/limit-error.d.ts +7 -0
  42. package/dist/sandbox/limit-error.d.ts.map +1 -0
  43. package/dist/sandbox/limit-error.js +13 -0
  44. package/dist/sandbox/limit-error.js.map +1 -0
  45. package/dist/sandbox/provider/local.d.ts +1 -0
  46. package/dist/sandbox/provider/local.d.ts.map +1 -1
  47. package/dist/sandbox/provider/local.js +50 -13
  48. package/dist/sandbox/provider/local.js.map +1 -1
  49. package/dist/store/budget/ledger.d.ts +15 -1
  50. package/dist/store/budget/ledger.d.ts.map +1 -1
  51. package/dist/store/budget/ledger.js +80 -1
  52. package/dist/store/budget/ledger.js.map +1 -1
  53. package/dist/store/evidence/source-text.d.ts +1 -1
  54. package/dist/tools/builtins/atomic-write-file.d.ts +2 -0
  55. package/dist/tools/builtins/atomic-write-file.d.ts.map +1 -1
  56. package/dist/tools/builtins/atomic-write-file.js +37 -8
  57. package/dist/tools/builtins/atomic-write-file.js.map +1 -1
  58. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  59. package/dist/tools/builtins/read-file.js +20 -12
  60. package/dist/tools/builtins/read-file.js.map +1 -1
  61. package/dist/tools/defineTool.d.ts.map +1 -1
  62. package/dist/tools/defineTool.js +4 -3
  63. package/dist/tools/defineTool.js.map +1 -1
  64. package/dist/tools/tool-is-available.d.ts +4 -0
  65. package/dist/tools/tool-is-available.d.ts.map +1 -0
  66. package/dist/tools/tool-is-available.js +8 -0
  67. package/dist/tools/tool-is-available.js.map +1 -0
  68. package/dist/types/common/index.d.ts +6 -0
  69. package/dist/types/common/index.d.ts.map +1 -1
  70. package/dist/types/common/index.js +13 -0
  71. package/dist/types/common/index.js.map +1 -1
  72. package/dist/types/sandbox/index.d.ts +13 -2
  73. package/dist/types/sandbox/index.d.ts.map +1 -1
  74. package/dist/types/sandbox/index.js.map +1 -1
  75. package/dist/types/session/checkpoint.d.ts +4 -0
  76. package/dist/types/session/checkpoint.d.ts.map +1 -1
  77. package/dist/types/session/checkpoint.js +2 -0
  78. package/dist/types/session/checkpoint.js.map +1 -1
  79. package/dist/types/session/events.d.ts +1 -0
  80. package/dist/types/session/events.d.ts.map +1 -1
  81. package/dist/types/session/events.js.map +1 -1
  82. package/dist/types/session/records.d.ts +42 -6
  83. package/dist/types/session/records.d.ts.map +1 -1
  84. package/dist/types/session/records.js +1 -0
  85. package/dist/types/session/records.js.map +1 -1
  86. package/dist/utils/cost.d.ts +17 -0
  87. package/dist/utils/cost.d.ts.map +1 -1
  88. package/dist/utils/cost.js +78 -8
  89. package/dist/utils/cost.js.map +1 -1
  90. package/package.json +1 -1
  91. package/src/index.ts +2 -0
  92. package/src/manager/session/turn-recorder.ts +31 -7
  93. package/src/pricing/catalogue.generated.ts +176 -21
  94. package/src/pricing/rates.source.json +108 -33
  95. package/src/public-runtime.ts +1 -0
  96. package/src/runtime/query/guard.ts +13 -2
  97. package/src/runtime/query/index.ts +1 -0
  98. package/src/runtime/query/iteration/index.ts +32 -11
  99. package/src/runtime/query/iteration/phases/advisory.ts +2 -2
  100. package/src/runtime/query/prepare-turn.ts +2 -1
  101. package/src/sandbox/file-walk-program.ts +1 -1
  102. package/src/sandbox/ignore-matcher.ts +12 -3
  103. package/src/sandbox/ignore-source.ts +51 -7
  104. package/src/sandbox/limit-error.ts +10 -0
  105. package/src/sandbox/provider/local.ts +54 -23
  106. package/src/store/budget/ledger.ts +93 -2
  107. package/src/tools/builtins/atomic-write-file.ts +49 -7
  108. package/src/tools/builtins/read-file.ts +34 -12
  109. package/src/tools/defineTool.ts +4 -3
  110. package/src/tools/tool-is-available.ts +11 -0
  111. package/src/types/common/index.ts +24 -0
  112. package/src/types/sandbox/index.ts +12 -1
  113. package/src/types/session/checkpoint.ts +2 -0
  114. package/src/types/session/events.ts +1 -0
  115. package/src/types/session/records.ts +1 -0
  116. package/src/utils/cost.ts +101 -8
@@ -1,20 +1,12 @@
1
1
  import { spawn, spawnSync } from 'node:child_process'
2
2
  import { constants, accessSync, existsSync, realpathSync } from 'node:fs'
3
- import {
4
- readFile as fsReadFile,
5
- writeFile as fsWriteFile,
6
- mkdir,
7
- open,
8
- readdir,
9
- rename,
10
- rm,
11
- stat,
12
- } from 'node:fs/promises'
3
+ import { readFile as fsReadFile, open, readdir, rm, stat } from 'node:fs/promises'
13
4
  import { tmpdir } from 'node:os'
14
5
  import { dirname, isAbsolute, join, parse, resolve } from 'node:path'
15
6
  import { NAMZU } from '../../constants/telemetry/index.js'
16
7
  import { SCOPE_ATTRIBUTE } from '../../utils/log/types.js'
17
8
  import { attributeSandboxFailure } from '../denial.js'
9
+ import { SandboxLimitError } from '../limit-error.js'
18
10
 
19
11
  import {
20
12
  SANDBOX_DEFAULT_TIMEOUT_MS,
@@ -28,6 +20,7 @@ import {
28
20
  // every bug the original's comment was written to record.
29
21
  import { killTree } from '../../process/kill-tree.js'
30
22
  import { SESSION_CHILD_ENV } from '../../process/session-child.js'
23
+ import { atomicWriteResolvedFile } from '../../tools/builtins/atomic-write-file.js'
31
24
  import { withSafeGitConfig } from '../../tools/git-config-env.js'
32
25
  import { resolveWithinAny, resolveWithinAnyReal } from '../../tools/paths.js'
33
26
  import type { SandboxId } from '../../types/ids/index.js'
@@ -481,7 +474,7 @@ function seatbeltString(value: string): string {
481
474
  return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
482
475
  }
483
476
 
484
- function buildSeatbeltProfile(additionalDirectories: readonly string[] = []): string {
477
+ export function buildSeatbeltProfile(additionalDirectories: readonly string[] = []): string {
485
478
  return [
486
479
  '(version 1)',
487
480
  '(deny default)',
@@ -521,6 +514,16 @@ function buildSeatbeltProfile(additionalDirectories: readonly string[] = []): st
521
514
  '(allow file-read* (subpath "/private/var/db/dyld"))',
522
515
  '(allow file-read* (subpath "/private/var/select"))',
523
516
 
517
+ // --- Apple developer-tool shims (read-only) ---
518
+ // /usr/bin/python3, git, clang and the other shims in /usr/bin are
519
+ // xcrun stubs: they load libxcrun from the active developer
520
+ // directory and run the real tool from there. Read only, and only the
521
+ // two places xcode-select can point at; xcrun's own lookup cache is
522
+ // read, never written (it works without it).
523
+ '(allow file-read* (subpath "/Library/Developer/CommandLineTools"))',
524
+ '(allow file-read* (subpath "/Applications/Xcode.app/Contents/Developer"))',
525
+ '(allow file-read* (regex #"^/private/var/folders/[^/]+/[^/]+/C/xcrun_db(-[^/]*)?$"))',
526
+
524
527
  // --- Device files ---
525
528
  '(allow file-read* (subpath "/dev"))',
526
529
  '(allow file-write* (literal "/dev/null"))',
@@ -693,6 +696,13 @@ class LocalSandbox implements Sandbox {
693
696
  }
694
697
  refuseExecStdin(opts, 'local')
695
698
 
699
+ const maxOutputBytes = opts?.maxOutputBytes
700
+ if (
701
+ maxOutputBytes !== undefined &&
702
+ (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0)
703
+ ) {
704
+ throw new RangeError('maxOutputBytes must be a non-negative safe integer')
705
+ }
696
706
  this._status = 'busy'
697
707
  const startTime = Date.now()
698
708
 
@@ -733,6 +743,7 @@ class LocalSandbox implements Sandbox {
733
743
  opts?.signal,
734
744
  bwrapInfoFd,
735
745
  bwrapBlockFd,
746
+ maxOutputBytes,
736
747
  )
737
748
  return { ...result, durationMs: Date.now() - startTime }
738
749
  } finally {
@@ -749,12 +760,7 @@ class LocalSandbox implements Sandbox {
749
760
  }
750
761
 
751
762
  const resolved = await resolveWithinAnyReal(this.roots, path)
752
- await mkdir(dirname(resolved), { recursive: true })
753
-
754
- // Convention 8: Atomic write (write-tmp-rename)
755
- const tmpPath = `${resolved}.tmp.${Date.now()}`
756
- await fsWriteFile(tmpPath, content)
757
- await rename(tmpPath, resolved)
763
+ await atomicWriteResolvedFile(resolved, content)
758
764
 
759
765
  this.log.debug('File written', { 'namzu.sandbox.path': resolved })
760
766
  }
@@ -783,9 +789,12 @@ class LocalSandbox implements Sandbox {
783
789
  }
784
790
 
785
791
  const resolved = await resolveWithinAnyReal(this.roots, path)
786
- const { offset, length, signal } = options ?? {}
792
+ const { offset, length, signal, maxBytes } = options ?? {}
787
793
  signal?.throwIfAborted()
788
- if (offset === undefined && length === undefined) {
794
+ if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 0)) {
795
+ throw new RangeError('readFile: maxBytes must be a non-negative safe integer')
796
+ }
797
+ if (offset === undefined && length === undefined && maxBytes === undefined) {
789
798
  return await fsReadFile(resolved, signal ? { signal } : undefined)
790
799
  }
791
800
  if (offset !== undefined && (!Number.isSafeInteger(offset) || offset < 0)) {
@@ -799,6 +808,9 @@ class LocalSandbox implements Sandbox {
799
808
  const from = offset ?? 0
800
809
  const remaining = Math.max(0, (await handle.stat()).size - from)
801
810
  const want = Math.min(length ?? remaining, remaining)
811
+ if (maxBytes !== undefined && want > maxBytes) {
812
+ throw new SandboxLimitError('read-file', maxBytes, want)
813
+ }
802
814
  if (want === 0) return Buffer.alloc(0)
803
815
  const buf = Buffer.allocUnsafe(want)
804
816
  const { bytesRead } = await handle.read(buf, 0, want, from)
@@ -988,6 +1000,7 @@ class LocalSandbox implements Sandbox {
988
1000
  callerSignal?: AbortSignal,
989
1001
  bwrapInfoFd?: number,
990
1002
  bwrapBlockFd?: number,
1003
+ maxOutputBytes?: number,
991
1004
  ): Promise<Omit<SandboxExecResult, 'durationMs'>> {
992
1005
  return new Promise((resolvePromise, rejectPromise) => {
993
1006
  let child: ReturnType<typeof spawn>
@@ -1013,7 +1026,7 @@ class LocalSandbox implements Sandbox {
1013
1026
 
1014
1027
  const stdout = new CappedStream(SANDBOX_MAX_OUTPUT_BYTES)
1015
1028
  const stderr = new CappedStream(SANDBOX_MAX_OUTPUT_BYTES)
1016
- let cancellation: 'caller' | 'deadline' | undefined
1029
+ let cancellation: 'caller' | 'deadline' | 'output' | undefined
1017
1030
  let bwrapChildPid: number | undefined
1018
1031
  let terminationSignal: NodeJS.Signals | undefined
1019
1032
  let settled = false
@@ -1033,7 +1046,7 @@ class LocalSandbox implements Sandbox {
1033
1046
  killTree(child, signal)
1034
1047
  killBwrapChild(bwrapChildPid, signal)
1035
1048
  }
1036
- const cancel = (origin: 'caller' | 'deadline') => {
1049
+ const cancel = (origin: NonNullable<typeof cancellation>) => {
1037
1050
  if (settled || cancellation !== undefined) return
1038
1051
  cancellation = origin
1039
1052
  // Own the group while its leader is still ours. Deferring this to
@@ -1049,8 +1062,22 @@ class LocalSandbox implements Sandbox {
1049
1062
  escalation.unref?.()
1050
1063
  }
1051
1064
 
1052
- child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk))
1053
- child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk))
1065
+ let outputBytes = 0
1066
+ let limitError: SandboxLimitError | undefined
1067
+ const output = (stream: CappedStream, chunk: Buffer): void => {
1068
+ if (limitError) return
1069
+ if (maxOutputBytes !== undefined) {
1070
+ outputBytes += chunk.byteLength
1071
+ if (outputBytes > maxOutputBytes) {
1072
+ limitError = new SandboxLimitError('exec-output', maxOutputBytes, outputBytes)
1073
+ cancel('output')
1074
+ return
1075
+ }
1076
+ }
1077
+ stream.push(chunk)
1078
+ }
1079
+ child.stdout?.on('data', (chunk: Buffer) => output(stdout, chunk))
1080
+ child.stderr?.on('data', (chunk: Buffer) => output(stderr, chunk))
1054
1081
  const bwrapInfo = bwrapInfoFd === undefined ? undefined : child.stdio[bwrapInfoFd]
1055
1082
  const bwrapBlock = bwrapBlockFd === undefined ? undefined : child.stdio[bwrapBlockFd]
1056
1083
  let bwrapInfoBuffer = ''
@@ -1098,6 +1125,10 @@ class LocalSandbox implements Sandbox {
1098
1125
  // now: retaining its numeric pid for a later timer risks pid reuse.
1099
1126
  terminate('SIGKILL')
1100
1127
  }
1128
+ if (limitError) {
1129
+ rejectPromise(limitError)
1130
+ return
1131
+ }
1101
1132
  const timedOut = cancellation === 'deadline'
1102
1133
  const exitCode = code ?? (timedOut ? 124 : 1)
1103
1134
  const attribution = attributeSandboxFailure({
@@ -1,6 +1,7 @@
1
- import { EMPTY_TOKEN_USAGE } from '../../constants/limits.js'
2
- import { type TokenUsage, accumulateTokenUsage } from '../../types/common/index.js'
1
+ import { EMPTY_TOKEN_USAGE, ZERO_COST } from '../../constants/limits.js'
2
+ import { type CostInfo, type TokenUsage, accumulateTokenUsage } from '../../types/common/index.js'
3
3
  import type { SessionId, TurnId } from '../../types/ids/index.js'
4
+ import { CostInfoSchema } from '../../types/session/checkpoint.js'
4
5
  import type { TurnBudgetBinding } from '../../types/session/turn.js'
5
6
  import { entityIdPattern } from '../../utils/id-format.js'
6
7
  import { isEntityId } from '../../utils/id.js'
@@ -36,6 +37,9 @@ export interface SessionTokenBudgetAccountSnapshot {
36
37
  turn?: SessionTokenBudgetTurn
37
38
  /** Cumulative own usage, keyed by the bound turn's id; descendants never appear here. */
38
39
  usage: Record<string, TokenUsage>
40
+ cost?: CostInfo
41
+ pricedThroughTokens?: number
42
+ costLimitUsd?: number
39
43
  }
40
44
 
41
45
  export interface SessionTokenBudgetRequestSnapshot {
@@ -76,6 +80,7 @@ export interface SessionTokenBudgetSummary {
76
80
  limit: number
77
81
  ownTokens: number
78
82
  treeTokens: number
83
+ treeCost?: CostInfo
79
84
  reservedTokens: number
80
85
  /** null means unlimited; unlike Infinity this survives JSON serialization. */
81
86
  remainingTokens: number | null
@@ -154,6 +159,11 @@ function usageValue(value: unknown): TokenUsage {
154
159
  totalTokens: count(source.totalTokens, 'totalTokens'),
155
160
  cachedTokens: count(source.cachedTokens, 'cachedTokens'),
156
161
  cacheWriteTokens: count(source.cacheWriteTokens, 'cacheWriteTokens'),
162
+ ...(source.cacheTokensInPrompt === undefined
163
+ ? {}
164
+ : {
165
+ cacheTokensInPrompt: count(source.cacheTokensInPrompt, 'cacheTokensInPrompt'),
166
+ }),
157
167
  ...(source.reasoningTokens === undefined
158
168
  ? {}
159
169
  : { reasoningTokens: count(source.reasoningTokens, 'reasoningTokens') }),
@@ -177,6 +187,14 @@ function maxUsage(left: TokenUsage, right: TokenUsage): TokenUsage {
177
187
  totalTokens: Math.max(left.totalTokens, right.totalTokens),
178
188
  cachedTokens: Math.max(left.cachedTokens, right.cachedTokens),
179
189
  cacheWriteTokens: Math.max(left.cacheWriteTokens, right.cacheWriteTokens),
190
+ ...(left.cacheTokensInPrompt === undefined && right.cacheTokensInPrompt === undefined
191
+ ? {}
192
+ : {
193
+ cacheTokensInPrompt: Math.max(
194
+ left.cacheTokensInPrompt ?? 0,
195
+ right.cacheTokensInPrompt ?? 0,
196
+ ),
197
+ }),
180
198
  ...(left.reasoningTokens === undefined && right.reasoningTokens === undefined
181
199
  ? {}
182
200
  : { reasoningTokens: Math.max(left.reasoningTokens ?? 0, right.reasoningTokens ?? 0) }),
@@ -252,6 +270,15 @@ export function validateSessionTokenBudgetSnapshot(value: unknown): SessionToken
252
270
  settled: account.settled,
253
271
  ...(turn === undefined ? {} : { turn }),
254
272
  usage,
273
+ ...(account.costLimitUsd === undefined
274
+ ? {}
275
+ : { costLimitUsd: CostInfoSchema.shape.totalCost.parse(account.costLimitUsd) }),
276
+ ...(account.cost === undefined
277
+ ? {}
278
+ : {
279
+ cost: CostInfoSchema.parse(account.cost),
280
+ pricedThroughTokens: count(account.pricedThroughTokens, 'pricedThroughTokens'),
281
+ }),
255
282
  }
256
283
  })
257
284
  const byId = new Map(accounts.map((account) => [account.id, account]))
@@ -504,6 +531,68 @@ export class SessionTokenBudget {
504
531
  get treeTokens(): number {
505
532
  return this.totals(this.node).tree
506
533
  }
534
+ /** Dollar ceiling of this turn, inherited by requests in its descendants. */
535
+ setCostLimit(limit: number | undefined): void {
536
+ if (limit === undefined || limit <= 0 || this.node.costLimitUsd === limit) return
537
+ this.node.costLimitUsd = limit
538
+ this.persist()
539
+ }
540
+
541
+ ancestorCostStop(): 'cost_limit' | 'cost_unmeasurable' | undefined {
542
+ let parentId = this.node.parentId
543
+ while (parentId !== undefined) {
544
+ const parent = this.requireAccount(parentId)
545
+ if (parent.costLimitUsd !== undefined) {
546
+ const spend = this.costOfAccounts(this.descendants(parent))
547
+ if (spend.totalCost >= parent.costLimitUsd) return 'cost_limit'
548
+ if (spend.unpricedTokens > 0) return 'cost_unmeasurable'
549
+ }
550
+ parentId = parent.parentId
551
+ }
552
+ return undefined
553
+ }
554
+
555
+ get treeCost(): CostInfo | undefined {
556
+ const ids = this.descendants(this.node)
557
+ return ids.size > 1 ? this.costOfAccounts(ids) : undefined
558
+ }
559
+
560
+ private costOfAccounts(ids: ReadonlySet<string>): CostInfo {
561
+ const total = { ...ZERO_COST }
562
+ for (const id of ids) {
563
+ const account = this.requireAccount(id)
564
+ const cost = account.cost ?? ZERO_COST
565
+ total.totalCost += cost.totalCost
566
+ total.cacheDiscount += cost.cacheDiscount
567
+ total.unpricedTokens += cost.unpricedTokens
568
+ if (cost.includedTokens !== undefined) {
569
+ total.includedTokens = (total.includedTokens ?? 0) + cost.includedTokens
570
+ }
571
+ if (!this.hasRequest(account)) {
572
+ const ownTokens = Object.values(account.usage).reduce(
573
+ (sum, usage) => sum + usage.totalTokens,
574
+ 0,
575
+ )
576
+ total.unpricedTokens += Math.max(0, ownTokens - (account.pricedThroughTokens ?? 0))
577
+ }
578
+ }
579
+ return total
580
+ }
581
+
582
+ get recordedCost(): { cost: CostInfo; tokens: number } | undefined {
583
+ const { cost, pricedThroughTokens } = this.node
584
+ return cost && pricedThroughTokens !== undefined
585
+ ? { cost, tokens: pricedThroughTokens }
586
+ : undefined
587
+ }
588
+
589
+ recordCost(cost: CostInfo, accountedTokens: number): void {
590
+ if (accountedTokens < (this.node.pricedThroughTokens ?? 0)) return
591
+ this.node.cost = { ...cost }
592
+ this.node.pricedThroughTokens = accountedTokens
593
+ this.persist()
594
+ }
595
+
507
596
  /** This account's request is still awaiting its final receipt; descendants are independent. */
508
597
  get hasInFlightRequest(): boolean {
509
598
  return this.hasRequest(this.node)
@@ -724,7 +813,9 @@ export class SessionTokenBudget {
724
813
  summary(): SessionTokenBudgetSummary {
725
814
  const totals = this.totals(this.node)
726
815
  const descendants = this.descendants(this.node)
816
+ const treeCost = descendants.size > 1 ? this.costOfAccounts(descendants) : undefined
727
817
  return {
818
+ ...(treeCost ? { treeCost } : {}),
728
819
  limit: this.limit,
729
820
  ownTokens: totals.own,
730
821
  treeTokens: totals.tree,
@@ -1,6 +1,15 @@
1
1
  import { randomUUID } from 'node:crypto'
2
- import { lstatSync, realpathSync } from 'node:fs'
3
- import { type FileHandle, mkdir, open, realpath, rename, stat, unlink } from 'node:fs/promises'
2
+ import { constants, lstatSync, realpathSync } from 'node:fs'
3
+ import {
4
+ type FileHandle,
5
+ access,
6
+ mkdir,
7
+ open,
8
+ realpath,
9
+ rename,
10
+ stat,
11
+ unlink,
12
+ } from 'node:fs/promises'
4
13
  import nodePath, { basename, dirname, join, sep } from 'node:path'
5
14
 
6
15
  /** A write refused because its path runs through a symbolic link or out of its root. */
@@ -71,6 +80,25 @@ function assertNoLinkBelow(anchor: string, file: string): void {
71
80
  }
72
81
  }
73
82
 
83
+ async function writableMode(filePath: string): Promise<number | undefined> {
84
+ const existing = await stat(filePath).catch((error: NodeJS.ErrnoException) => {
85
+ if (error.code !== 'ENOENT') throw error
86
+ return undefined
87
+ })
88
+ if (existing === undefined) return undefined
89
+
90
+ const mode = existing.mode & 0o7777
91
+ // A privileged process can pass W_OK even when every write bit is clear.
92
+ if ((mode & 0o222) === 0) {
93
+ throw Object.assign(new Error(`EACCES: permission denied, file is read-only: ${filePath}`), {
94
+ code: 'EACCES',
95
+ path: filePath,
96
+ })
97
+ }
98
+ await access(filePath, constants.W_OK)
99
+ return mode
100
+ }
101
+
74
102
  /**
75
103
  * Commit a complete file body without exposing a truncated destination.
76
104
  *
@@ -92,12 +120,20 @@ export async function atomicWriteFile(
92
120
  if (anchor !== undefined) assertNoLinkBelow(anchor, requestedPath)
93
121
  const filePath =
94
122
  anchor === undefined ? await realpath(requestedPath).catch(() => requestedPath) : requestedPath
123
+ return atomicWriteResolvedFile(filePath, content, hooks)
124
+ }
125
+
126
+ /** Commit at a path already resolved by the caller's containment policy. */
127
+ export async function atomicWriteResolvedFile(
128
+ filePath: string,
129
+ content: string | Buffer,
130
+ hooks: AtomicWriteOptions = {},
131
+ ): Promise<void> {
95
132
  const directory = dirname(filePath)
133
+ const existingMode = await writableMode(filePath)
96
134
  await mkdir(directory, { recursive: true })
97
135
 
98
- const existingMode = await stat(filePath)
99
- .then((value) => value.mode)
100
- .catch(() => undefined)
136
+ const preservedMode = hooks.mode === undefined ? existingMode : undefined
101
137
  const tempPath = join(
102
138
  directory,
103
139
  `.${basename(filePath)}.namzu-${process.pid}-${randomUUID()}.tmp`,
@@ -106,13 +142,19 @@ export async function atomicWriteFile(
106
142
  let committed = false
107
143
 
108
144
  try {
109
- handle = await open(tempPath, 'wx', hooks.mode ?? existingMode ?? 0o666)
145
+ handle = await open(tempPath, 'wx', preservedMode === undefined ? (hooks.mode ?? 0o666) : 0o600)
110
146
  await handle.writeFile(content, 'utf-8')
147
+ // Creation applies the umask. Set the retained bits after writing, which
148
+ // can clear special mode bits on some filesystems.
149
+ if (preservedMode !== undefined) await handle.chmod(preservedMode)
111
150
  await handle.sync()
112
151
  await handle.close()
113
152
  handle = undefined
114
153
  await hooks.beforeCommit?.()
115
- if (anchor !== undefined) assertNoLinkBelow(anchor, filePath)
154
+ if (hooks.refuseLinksBelow !== undefined) assertNoLinkBelow(hooks.refuseLinksBelow, filePath)
155
+ if ((await writableMode(filePath)) !== existingMode) {
156
+ throw new Error(`File permissions changed before the write could commit: ${filePath}`)
157
+ }
116
158
  await rename(tempPath, filePath)
117
159
  committed = true
118
160
  await syncDirectory(directory)
@@ -7,6 +7,7 @@ import { defineTool } from '../defineTool.js'
7
7
  import { resolveWithinAnyReal, toolRoots } from '../paths.js'
8
8
  import { resolveRetainedOutput } from '../retained-output.js'
9
9
  import { looksBinary } from '../text-window.js'
10
+ import { toolIsAvailable } from '../tool-is-available.js'
10
11
  import { TEXT_MAX_INPUT_BYTES, readBoundedChunks, readBoundedFile } from './bounded-file-read.js'
11
12
  import { fingerprintContent } from './content-fingerprint.js'
12
13
  import {
@@ -89,6 +90,7 @@ export const ReadFileTool = defineTool({
89
90
  },
90
91
 
91
92
  async execute(input, context) {
93
+ const shellAvailable = toolIsAvailable(context, 'bash')
92
94
  // This session's own retained tool output lives on the host, outside the
93
95
  // roots and outside any sandbox. It is read here, as a plain window of text,
94
96
  // because the result that named it told the model to.
@@ -105,7 +107,7 @@ export const ReadFileTool = defineTool({
105
107
  )
106
108
  const media = await readMediaFile(buffer, input.path, input, context, true)
107
109
  if (media) return media
108
- const binaryGuidance = describeStructuredBinaryRead(input.path)
110
+ const binaryGuidance = describeStructuredBinaryRead(input.path, shellAvailable)
109
111
  if (binaryGuidance) {
110
112
  return {
111
113
  success: false,
@@ -124,7 +126,8 @@ export const ReadFileTool = defineTool({
124
126
  }
125
127
  }
126
128
  const content = buffer.toString('utf-8')
127
- if (looksBinary(content)) return unreadableAsText(input.path, buffer.length, true)
129
+ if (looksBinary(content))
130
+ return unreadableAsText(input.path, buffer.length, true, shellAvailable)
128
131
  const capped = renderCappedRead(content, buffer.length, input, capOptions(input, context))
129
132
  if (!capped.ok) return refusedRead(input.path, buffer.length, capped.message, true)
130
133
  const rendered = capped.rendered
@@ -162,7 +165,7 @@ export const ReadFileTool = defineTool({
162
165
  )
163
166
  const media = await readMediaFile(buffer, filePath, input, context, false)
164
167
  if (media) return media
165
- const binaryGuidance = describeStructuredBinaryRead(filePath)
168
+ const binaryGuidance = describeStructuredBinaryRead(filePath, shellAvailable)
166
169
  if (binaryGuidance) {
167
170
  return {
168
171
  success: false,
@@ -180,7 +183,8 @@ export const ReadFileTool = defineTool({
180
183
  }
181
184
  }
182
185
  const content = buffer.toString('utf-8')
183
- if (looksBinary(content)) return unreadableAsText(filePath, buffer.length, false)
186
+ if (looksBinary(content))
187
+ return unreadableAsText(filePath, buffer.length, false, shellAvailable)
184
188
  const capped = renderCappedRead(content, buffer.length, input, capOptions(input, context))
185
189
  if (!capped.ok) return refusedRead(filePath, buffer.length, capped.message, false)
186
190
  const rendered = capped.rendered
@@ -337,10 +341,18 @@ function capOptions(
337
341
  * A file whose bytes are not text. The model gets a short note with the size
338
342
  * and the next step, never the numbered garbage a decode would produce.
339
343
  */
340
- function unreadableAsText(path: string, bytes: number, sandboxed: boolean) {
344
+ function unreadableAsText(
345
+ path: string,
346
+ bytes: number,
347
+ sandboxed: boolean,
348
+ shellAvailable: boolean,
349
+ ) {
350
+ const hint = shellAvailable
351
+ ? ' Inspect it with a shell command such as file or xxd, or use a tool made for its format.'
352
+ : ''
341
353
  return {
342
354
  success: false as const,
343
- output: `This file is not readable as text (${humanBytes(bytes)} of binary or non-UTF-8 data). Inspect it with a shell command such as file or xxd, or use a tool made for its format.`,
355
+ output: `This file is not readable as text (${humanBytes(bytes)} of binary or non-UTF-8 data).${hint}`,
344
356
  data: { path, binary: true, ...(sandboxed ? { sandboxed: true } : {}) },
345
357
  facts: { kind: 'read' as const, path, binary: true, bytes },
346
358
  }
@@ -463,17 +475,27 @@ function unchangedRead(
463
475
  }
464
476
  }
465
477
 
466
- function describeStructuredBinaryRead(path: string): string | null {
478
+ function describeStructuredBinaryRead(path: string, shellAvailable: boolean): string | null {
467
479
  const ext = extname(path).toLowerCase()
468
- if (ext === '.docx') return buildStructuredBinaryGuidance(path, 'DOCX', 'python-docx')
469
- if (ext === '.pptx') return buildStructuredBinaryGuidance(path, 'PPTX', 'python-pptx')
470
- if (ext === '.xlsx') return buildStructuredBinaryGuidance(path, 'XLSX', 'openpyxl')
480
+ if (ext === '.docx')
481
+ return buildStructuredBinaryGuidance(path, 'DOCX', 'python-docx', shellAvailable)
482
+ if (ext === '.pptx')
483
+ return buildStructuredBinaryGuidance(path, 'PPTX', 'python-pptx', shellAvailable)
484
+ if (ext === '.xlsx')
485
+ return buildStructuredBinaryGuidance(path, 'XLSX', 'openpyxl', shellAvailable)
471
486
  return null
472
487
  }
473
488
 
474
- function buildStructuredBinaryGuidance(path: string, format: string, extractor: string): string {
489
+ function buildStructuredBinaryGuidance(
490
+ path: string,
491
+ format: string,
492
+ extractor: string,
493
+ shellAvailable: boolean,
494
+ ): string {
495
+ const description = `The file "${path}" is a ${format} document package, not UTF-8 text.`
496
+ if (!shellAvailable) return description
475
497
  return [
476
- `The file "${path}" is a ${format} document package, not UTF-8 text.`,
498
+ description,
477
499
  'Do not use the read/cat tools as evidence for this raw file.',
478
500
  `Extract its text with shell/Python tooling already available in the sandbox (${extractor}), write the extracted text or summary under scratch, then read that text file.`,
479
501
  'If extraction fails, report the exact filename and extraction error instead of claiming the attachment is unavailable.',
@@ -8,6 +8,7 @@ import type {
8
8
  import type { ToolPresentation } from '../types/tool/presentation.js'
9
9
  import { toErrorMessage } from '../utils/error.js'
10
10
  import { failureFactsFromError } from './failure-facts.js'
11
+ import { toolIsAvailable } from './tool-is-available.js'
11
12
 
12
13
  export interface DefineToolOptions<S extends z.ZodType> {
13
14
  name: string
@@ -211,7 +212,7 @@ export function defineTool<S extends z.ZodType>(
211
212
  try {
212
213
  return await options.execute(input, context)
213
214
  } catch (err) {
214
- const message = `${toErrorMessage(err)}${missingPathNote(options.name, err)}`
215
+ const message = `${toErrorMessage(err)}${missingPathNote(options.name, err, context)}`
215
216
  const facts = failureFactsFromError(err)
216
217
  return {
217
218
  success: false,
@@ -232,8 +233,8 @@ const PATH_GUESSING_TOOLS: ReadonlySet<string> = new Set(['read', 'edit'])
232
233
  * What to do when a path does not exist. A model that is told only "no such
233
234
  * file" tries another guess; listing the folder finds the real name in one call.
234
235
  */
235
- function missingPathNote(toolName: string, err: unknown): string {
236
- if (!PATH_GUESSING_TOOLS.has(toolName)) return ''
236
+ function missingPathNote(toolName: string, err: unknown, context: ToolContext): string {
237
+ if (!PATH_GUESSING_TOOLS.has(toolName) || !toolIsAvailable(context, 'glob')) return ''
237
238
  return (err as { code?: unknown } | null)?.code === 'ENOENT'
238
239
  ? ' Nothing exists at that path. Find the file with `glob` instead of trying another guess.'
239
240
  : ''
@@ -0,0 +1,11 @@
1
+ import type { ToolContext } from '../types/tool/index.js'
2
+
3
+ /** Whether the model can call a follow-up tool in the current step. */
4
+ export function toolIsAvailable(context: ToolContext, name: string): boolean {
5
+ const registry = context.toolRegistry
6
+ return (
7
+ registry?.has(name) === true &&
8
+ registry.availability(name) === 'active' &&
9
+ (context.allowedTools === undefined || context.allowedTools.includes(name))
10
+ )
11
+ }
@@ -12,6 +12,11 @@ export interface TokenUsage {
12
12
  cachedTokens: number
13
13
  cacheWriteTokens: number
14
14
 
15
+ /** Cache reads and writes already included in the prompt count, when explicitly measured. */
16
+ cacheTokensInPrompt?: number
17
+ /** Billing route selected for this model request. */
18
+ billingRoute?: 'subscription' | 'api'
19
+
15
20
  /**
16
21
  * The whole prompt this call processed, cache reads and cache writes
17
22
  * included: the size of the context the model was given.
@@ -155,6 +160,12 @@ export function accumulateTokenUsage(current: TokenUsage, addition: TokenUsage):
155
160
  totalTokens: current.totalTokens + addition.totalTokens,
156
161
  cachedTokens: current.cachedTokens + addition.cachedTokens,
157
162
  cacheWriteTokens: current.cacheWriteTokens + addition.cacheWriteTokens,
163
+ ...(current.cacheTokensInPrompt !== undefined || addition.cacheTokensInPrompt !== undefined
164
+ ? {
165
+ cacheTokensInPrompt:
166
+ (current.cacheTokensInPrompt ?? 0) + (addition.cacheTokensInPrompt ?? 0),
167
+ }
168
+ : {}),
158
169
  // Summed only when at least one side reported it. Coercing absent to
159
170
  // zero would turn 'this driver does not tell us' into 'it spent none',
160
171
  // and a turn mixing a reporting driver with a silent one would read as
@@ -202,6 +213,17 @@ export function mergeTokenUsage(current: TokenUsage, next: TokenUsage): TokenUsa
202
213
  totalTokens: Math.max(current.totalTokens, next.totalTokens, promptTokens + completionTokens),
203
214
  cachedTokens: Math.max(current.cachedTokens, next.cachedTokens),
204
215
  cacheWriteTokens: Math.max(current.cacheWriteTokens, next.cacheWriteTokens),
216
+ ...((next.billingRoute ?? current.billingRoute)
217
+ ? { billingRoute: next.billingRoute ?? current.billingRoute }
218
+ : {}),
219
+ ...(current.cacheTokensInPrompt !== undefined || next.cacheTokensInPrompt !== undefined
220
+ ? {
221
+ cacheTokensInPrompt: Math.max(
222
+ current.cacheTokensInPrompt ?? 0,
223
+ next.cacheTokensInPrompt ?? 0,
224
+ ),
225
+ }
226
+ : {}),
205
227
  ...(current.fullPromptTokens !== undefined || next.fullPromptTokens !== undefined
206
228
  ? { fullPromptTokens: Math.max(current.fullPromptTokens ?? 0, next.fullPromptTokens ?? 0) }
207
229
  : {}),
@@ -241,6 +263,8 @@ export function mergeTokenUsage(current: TokenUsage, next: TokenUsage): TokenUsa
241
263
  }
242
264
 
243
265
  export interface CostInfo {
266
+ /** Tokens covered by a subscription plan. */
267
+ includedTokens?: number
244
268
  /**
245
269
  * The input rate this total was accumulated at — present only when ONE rate
246
270
  * card describes the whole total.
@@ -128,6 +128,11 @@ export interface SandboxExecResult {
128
128
  // ---------------------------------------------------------------------------
129
129
 
130
130
  export interface SandboxExecOptions {
131
+ /**
132
+ * Maximum combined stdout and stderr bytes accepted by the host.
133
+ * The host rejects with `SandboxLimitError` when output exceeds it.
134
+ */
135
+ maxOutputBytes?: number
131
136
  readonly timeout?: number
132
137
  readonly env?: Record<string, string>
133
138
  readonly cwd?: string
@@ -364,6 +369,12 @@ export interface SandboxTcpConnectOptions {
364
369
  * file.
365
370
  */
366
371
  export interface SandboxReadFileOptions {
372
+ /**
373
+ * Maximum bytes in the requested file slice. A larger slice is refused
374
+ * with `SandboxLimitError`. A backend that cannot enforce this limit
375
+ * must refuse the operation.
376
+ */
377
+ readonly maxBytes?: number
367
378
  /** First byte to read. Defaults to 0. */
368
379
  readonly offset?: number
369
380
  /**
@@ -377,7 +388,7 @@ export interface SandboxReadFileOptions {
377
388
  * asked for 4 MiB, got 1 MiB and was told nothing would read the short
378
389
  * answer as the end of its range. The agent-backed backends cap it at
379
390
  * `NAMZU_AGENT_READ_FILE_RANGE_BYTES` (1 MiB by default), because one
380
- * range is one wire frame there; a provider reading from local disk has
391
+ * range without `maxBytes` is one wire frame there; a provider reading from local disk has
381
392
  * no such ceiling. A caller that wants more than a frame's worth in one
382
393
  * call iterates {@link Sandbox.readFileStream} instead, which is not
383
394
  * capped.
@@ -78,6 +78,7 @@ export const TokenUsageSchema = z
78
78
  totalTokens: count,
79
79
  cachedTokens: count,
80
80
  cacheWriteTokens: count,
81
+ cacheTokensInPrompt: count.optional(),
81
82
  reasoningTokens: count.optional(),
82
83
  cacheTtlMs: count.optional(),
83
84
  cacheWriteTtlTokens: z
@@ -94,6 +95,7 @@ export const CostInfoSchema = z
94
95
  totalCost: z.number().nonnegative(),
95
96
  cacheDiscount: z.number(),
96
97
  unpricedTokens: count,
98
+ includedTokens: count.optional(),
97
99
  })
98
100
  .strict()
99
101
 
@@ -987,6 +987,7 @@ type CoreSessionEvent =
987
987
  }
988
988
  | {
989
989
  type: 'token_usage_updated'
990
+ billingRoute?: TokenUsage['billingRoute']
990
991
  /** Aggregate tree spend, distinct from this turn's own usage. */
991
992
  budget?: SessionTokenBudgetSummary
992
993
  sessionId: SessionId