@namzu/sdk 74.0.0 → 75.0.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/CHANGELOG.md +65 -0
- package/dist/bridge/acp/server.d.ts +2 -0
- package/dist/bridge/acp/server.d.ts.map +1 -1
- package/dist/bridge/acp/server.js +9 -1
- package/dist/bridge/acp/server.js.map +1 -1
- package/dist/config/runtime.d.ts +3 -3
- package/dist/connector/mcp/adapter.d.ts +1 -1
- package/dist/connector/mcp/adapter.d.ts.map +1 -1
- package/dist/connector/mcp/adapter.js +3 -2
- package/dist/connector/mcp/adapter.js.map +1 -1
- package/dist/connector/mcp/client.d.ts +4 -25
- package/dist/connector/mcp/client.d.ts.map +1 -1
- package/dist/connector/mcp/client.js +32 -32
- package/dist/connector/mcp/client.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/manager/session/turn-recorder.d.ts +1 -0
- package/dist/manager/session/turn-recorder.d.ts.map +1 -1
- package/dist/manager/session/turn-recorder.js +31 -7
- package/dist/manager/session/turn-recorder.js.map +1 -1
- package/dist/pricing/catalogue.generated.d.ts.map +1 -1
- package/dist/pricing/catalogue.generated.js +176 -21
- package/dist/pricing/catalogue.generated.js.map +1 -1
- package/dist/provider/errors.d.ts.map +1 -1
- package/dist/provider/errors.js +13 -18
- package/dist/provider/errors.js.map +1 -1
- package/dist/provider/stream-request-timeout.d.ts +9 -0
- package/dist/provider/stream-request-timeout.d.ts.map +1 -0
- package/dist/provider/stream-request-timeout.js +34 -0
- package/dist/provider/stream-request-timeout.js.map +1 -0
- package/dist/public-runtime.d.ts +2 -0
- package/dist/public-runtime.d.ts.map +1 -1
- package/dist/public-runtime.js +2 -0
- package/dist/public-runtime.js.map +1 -1
- package/dist/public-tools.d.ts +1 -1
- package/dist/public-tools.d.ts.map +1 -1
- package/dist/public-tools.js +1 -1
- package/dist/public-tools.js.map +1 -1
- package/dist/runtime/query/executor.d.ts +3 -0
- package/dist/runtime/query/executor.d.ts.map +1 -1
- package/dist/runtime/query/executor.js +15 -3
- package/dist/runtime/query/executor.js.map +1 -1
- package/dist/runtime/query/file-evidence-replay.d.ts +1 -0
- package/dist/runtime/query/file-evidence-replay.d.ts.map +1 -1
- package/dist/runtime/query/file-evidence-replay.js +64 -21
- package/dist/runtime/query/file-evidence-replay.js.map +1 -1
- package/dist/runtime/query/file-evidence-seed.d.ts +7 -0
- package/dist/runtime/query/file-evidence-seed.d.ts.map +1 -1
- package/dist/runtime/query/file-evidence-seed.js +12 -1
- package/dist/runtime/query/file-evidence-seed.js.map +1 -1
- package/dist/runtime/query/guard.d.ts.map +1 -1
- package/dist/runtime/query/guard.js +12 -2
- package/dist/runtime/query/guard.js.map +1 -1
- package/dist/runtime/query/index.d.ts +2 -0
- package/dist/runtime/query/index.d.ts.map +1 -1
- package/dist/runtime/query/index.js +6 -2
- package/dist/runtime/query/index.js.map +1 -1
- package/dist/runtime/query/iteration/index.d.ts +3 -0
- package/dist/runtime/query/iteration/index.d.ts.map +1 -1
- package/dist/runtime/query/iteration/index.js +32 -11
- package/dist/runtime/query/iteration/index.js.map +1 -1
- package/dist/runtime/query/iteration/phases/advisory.js +2 -2
- package/dist/runtime/query/iteration/phases/advisory.js.map +1 -1
- package/dist/runtime/query/path-escalation.d.ts.map +1 -1
- package/dist/runtime/query/path-escalation.js +4 -3
- package/dist/runtime/query/path-escalation.js.map +1 -1
- package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
- package/dist/runtime/query/prepare-turn.js +1 -1
- package/dist/runtime/query/prepare-turn.js.map +1 -1
- package/dist/runtime/query/tooling.d.ts +2 -0
- package/dist/runtime/query/tooling.d.ts.map +1 -1
- package/dist/runtime/query/tooling.js +1 -0
- package/dist/runtime/query/tooling.js.map +1 -1
- package/dist/sandbox/file-walk-program.js +1 -1
- package/dist/sandbox/ignore-matcher.d.ts +2 -0
- package/dist/sandbox/ignore-matcher.d.ts.map +1 -1
- package/dist/sandbox/ignore-matcher.js +8 -2
- package/dist/sandbox/ignore-matcher.js.map +1 -1
- package/dist/sandbox/ignore-source.d.ts.map +1 -1
- package/dist/sandbox/ignore-source.js +51 -7
- package/dist/sandbox/ignore-source.js.map +1 -1
- package/dist/sandbox/limit-error.d.ts +7 -0
- package/dist/sandbox/limit-error.d.ts.map +1 -0
- package/dist/sandbox/limit-error.js +13 -0
- package/dist/sandbox/limit-error.js.map +1 -0
- package/dist/sandbox/provider/local.d.ts +1 -0
- package/dist/sandbox/provider/local.d.ts.map +1 -1
- package/dist/sandbox/provider/local.js +95 -31
- package/dist/sandbox/provider/local.js.map +1 -1
- package/dist/schedules/cron.js +1 -1
- package/dist/schedules/cron.js.map +1 -1
- package/dist/schedules/describe.js +1 -1
- package/dist/schedules/describe.js.map +1 -1
- package/dist/schedules/next-fire.d.ts +2 -2
- package/dist/schedules/next-fire.d.ts.map +1 -1
- package/dist/schedules/next-fire.js +7 -4
- package/dist/schedules/next-fire.js.map +1 -1
- package/dist/schedules/spec.d.ts.map +1 -1
- package/dist/schedules/spec.js +23 -7
- package/dist/schedules/spec.js.map +1 -1
- package/dist/schedules/types.d.ts +2 -0
- package/dist/schedules/types.d.ts.map +1 -1
- package/dist/store/budget/ledger.d.ts +15 -1
- package/dist/store/budget/ledger.d.ts.map +1 -1
- package/dist/store/budget/ledger.js +80 -1
- package/dist/store/budget/ledger.js.map +1 -1
- package/dist/store/evidence/source-text.d.ts +1 -1
- package/dist/store/session-index/sqlite.d.ts.map +1 -1
- package/dist/store/session-index/sqlite.js +7 -3
- package/dist/store/session-index/sqlite.js.map +1 -1
- package/dist/store/session-log/core.d.ts.map +1 -1
- package/dist/store/session-log/core.js +88 -24
- package/dist/store/session-log/core.js.map +1 -1
- package/dist/store/session-log/disk.js +1 -1
- package/dist/store/session-log/disk.js.map +1 -1
- package/dist/tools/builtins/atomic-write-file.d.ts +2 -0
- package/dist/tools/builtins/atomic-write-file.d.ts.map +1 -1
- package/dist/tools/builtins/atomic-write-file.js +37 -8
- package/dist/tools/builtins/atomic-write-file.js.map +1 -1
- package/dist/tools/builtins/code-analysis.d.ts.map +1 -1
- package/dist/tools/builtins/code-analysis.js +4 -1
- package/dist/tools/builtins/code-analysis.js.map +1 -1
- package/dist/tools/builtins/edit-apply.d.ts.map +1 -1
- package/dist/tools/builtins/edit-apply.js +24 -10
- package/dist/tools/builtins/edit-apply.js.map +1 -1
- package/dist/tools/builtins/edit.d.ts.map +1 -1
- package/dist/tools/builtins/edit.js +31 -15
- package/dist/tools/builtins/edit.js.map +1 -1
- package/dist/tools/builtins/file-text.d.ts +3 -0
- package/dist/tools/builtins/file-text.d.ts.map +1 -0
- package/dist/tools/builtins/file-text.js +14 -0
- package/dist/tools/builtins/file-text.js.map +1 -0
- package/dist/tools/builtins/glob.d.ts.map +1 -1
- package/dist/tools/builtins/glob.js +7 -2
- package/dist/tools/builtins/glob.js.map +1 -1
- package/dist/tools/builtins/grep.d.ts.map +1 -1
- package/dist/tools/builtins/grep.js +8 -5
- package/dist/tools/builtins/grep.js.map +1 -1
- package/dist/tools/builtins/ls.d.ts.map +1 -1
- package/dist/tools/builtins/ls.js +2 -1
- package/dist/tools/builtins/ls.js.map +1 -1
- package/dist/tools/builtins/notebook-edit.d.ts.map +1 -1
- package/dist/tools/builtins/notebook-edit.js +19 -10
- package/dist/tools/builtins/notebook-edit.js.map +1 -1
- package/dist/tools/builtins/read-file.d.ts.map +1 -1
- package/dist/tools/builtins/read-file.js +61 -29
- package/dist/tools/builtins/read-file.js.map +1 -1
- package/dist/tools/builtins/read-regular-file.d.ts +5 -0
- package/dist/tools/builtins/read-regular-file.d.ts.map +1 -0
- package/dist/tools/builtins/read-regular-file.js +23 -0
- package/dist/tools/builtins/read-regular-file.js.map +1 -0
- package/dist/tools/builtins/search-support.d.ts +2 -0
- package/dist/tools/builtins/search-support.d.ts.map +1 -1
- package/dist/tools/builtins/search-support.js +14 -0
- package/dist/tools/builtins/search-support.js.map +1 -1
- package/dist/tools/builtins/stale-before-review.d.ts.map +1 -1
- package/dist/tools/builtins/stale-before-review.js +8 -5
- package/dist/tools/builtins/stale-before-review.js.map +1 -1
- package/dist/tools/builtins/write-file.d.ts.map +1 -1
- package/dist/tools/builtins/write-file.js +17 -13
- package/dist/tools/builtins/write-file.js.map +1 -1
- package/dist/tools/defineTool.d.ts.map +1 -1
- package/dist/tools/defineTool.js +4 -3
- package/dist/tools/defineTool.js.map +1 -1
- package/dist/tools/paths.d.ts +9 -0
- package/dist/tools/paths.d.ts.map +1 -1
- package/dist/tools/paths.js +39 -9
- package/dist/tools/paths.js.map +1 -1
- package/dist/tools/posix-path.d.ts +2 -14
- package/dist/tools/posix-path.d.ts.map +1 -1
- package/dist/tools/posix-path.js +7 -0
- package/dist/tools/posix-path.js.map +1 -1
- package/dist/tools/tool-is-available.d.ts +4 -0
- package/dist/tools/tool-is-available.d.ts.map +1 -0
- package/dist/tools/tool-is-available.js +8 -0
- package/dist/tools/tool-is-available.js.map +1 -0
- package/dist/types/code-analysis/index.d.ts +1 -1
- package/dist/types/code-analysis/index.d.ts.map +1 -1
- package/dist/types/common/index.d.ts +6 -0
- package/dist/types/common/index.d.ts.map +1 -1
- package/dist/types/common/index.js +13 -0
- package/dist/types/common/index.js.map +1 -1
- package/dist/types/provider/errors.d.ts.map +1 -1
- package/dist/types/provider/errors.js +3 -5
- package/dist/types/provider/errors.js.map +1 -1
- package/dist/types/sandbox/index.d.ts +13 -2
- package/dist/types/sandbox/index.d.ts.map +1 -1
- package/dist/types/sandbox/index.js.map +1 -1
- package/dist/types/session/checkpoint.d.ts +4 -0
- package/dist/types/session/checkpoint.d.ts.map +1 -1
- package/dist/types/session/checkpoint.js +2 -0
- package/dist/types/session/checkpoint.js.map +1 -1
- package/dist/types/session/events.d.ts +1 -0
- package/dist/types/session/events.d.ts.map +1 -1
- package/dist/types/session/events.js.map +1 -1
- package/dist/types/session/records.d.ts +42 -6
- package/dist/types/session/records.d.ts.map +1 -1
- package/dist/types/session/records.js +1 -0
- package/dist/types/session/records.js.map +1 -1
- package/dist/types/tool/index.d.ts +2 -0
- package/dist/types/tool/index.d.ts.map +1 -1
- package/dist/types/tool/index.js.map +1 -1
- package/dist/utils/cost.d.ts +17 -0
- package/dist/utils/cost.d.ts.map +1 -1
- package/dist/utils/cost.js +78 -8
- package/dist/utils/cost.js.map +1 -1
- package/package.json +1 -1
- package/src/bridge/acp/server.ts +16 -7
- package/src/connector/mcp/adapter.ts +4 -3
- package/src/connector/mcp/client.ts +33 -32
- package/src/index.ts +2 -0
- package/src/manager/session/turn-recorder.ts +31 -7
- package/src/pricing/catalogue.generated.ts +176 -21
- package/src/pricing/rates.source.json +108 -33
- package/src/provider/errors.ts +12 -19
- package/src/provider/stream-request-timeout.ts +34 -0
- package/src/public-runtime.ts +2 -0
- package/src/public-tools.ts +1 -0
- package/src/runtime/query/executor.ts +29 -3
- package/src/runtime/query/file-evidence-replay.ts +73 -19
- package/src/runtime/query/file-evidence-seed.ts +16 -0
- package/src/runtime/query/guard.ts +13 -2
- package/src/runtime/query/index.ts +10 -1
- package/src/runtime/query/iteration/index.ts +32 -11
- package/src/runtime/query/iteration/phases/advisory.ts +2 -2
- package/src/runtime/query/path-escalation.ts +4 -3
- package/src/runtime/query/prepare-turn.ts +2 -1
- package/src/runtime/query/tooling.ts +3 -0
- package/src/sandbox/file-walk-program.ts +1 -1
- package/src/sandbox/ignore-matcher.ts +12 -3
- package/src/sandbox/ignore-source.ts +51 -7
- package/src/sandbox/limit-error.ts +10 -0
- package/src/sandbox/provider/local.ts +107 -48
- package/src/schedules/cron.ts +1 -1
- package/src/schedules/describe.ts +1 -1
- package/src/schedules/next-fire.ts +7 -4
- package/src/schedules/spec.ts +36 -7
- package/src/schedules/types.ts +2 -0
- package/src/store/budget/ledger.ts +93 -2
- package/src/store/session-index/sqlite.ts +8 -4
- package/src/store/session-log/core.ts +96 -25
- package/src/store/session-log/disk.ts +1 -1
- package/src/tools/builtins/atomic-write-file.ts +49 -7
- package/src/tools/builtins/code-analysis.ts +6 -1
- package/src/tools/builtins/edit-apply.ts +25 -10
- package/src/tools/builtins/edit.ts +31 -15
- package/src/tools/builtins/file-text.ts +14 -0
- package/src/tools/builtins/glob.ts +6 -1
- package/src/tools/builtins/grep.ts +7 -5
- package/src/tools/builtins/ls.ts +2 -1
- package/src/tools/builtins/notebook-edit.ts +18 -11
- package/src/tools/builtins/read-file.ts +71 -24
- package/src/tools/builtins/read-regular-file.ts +25 -0
- package/src/tools/builtins/search-support.ts +13 -0
- package/src/tools/builtins/stale-before-review.ts +8 -6
- package/src/tools/builtins/write-file.ts +18 -12
- package/src/tools/defineTool.ts +4 -3
- package/src/tools/paths.ts +49 -7
- package/src/tools/posix-path.ts +9 -0
- package/src/tools/tool-is-available.ts +11 -0
- package/src/types/code-analysis/index.ts +1 -1
- package/src/types/common/index.ts +24 -0
- package/src/types/provider/errors.ts +3 -5
- package/src/types/sandbox/index.ts +12 -1
- package/src/types/session/checkpoint.ts +2 -0
- package/src/types/session/events.ts +1 -0
- package/src/types/session/records.ts +1 -0
- package/src/types/tool/index.ts +2 -0
- 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"))',
|
|
@@ -661,6 +664,7 @@ class LocalSandbox implements Sandbox {
|
|
|
661
664
|
environment: SandboxEnvironment,
|
|
662
665
|
private readonly wrapperCommand: string | undefined,
|
|
663
666
|
private readonly removeRootOnDestroy: boolean,
|
|
667
|
+
private readonly seatbeltTempDir: string | undefined,
|
|
664
668
|
config: SandboxCreateConfig,
|
|
665
669
|
log: Logger,
|
|
666
670
|
) {
|
|
@@ -693,10 +697,17 @@ class LocalSandbox implements Sandbox {
|
|
|
693
697
|
}
|
|
694
698
|
refuseExecStdin(opts, 'local')
|
|
695
699
|
|
|
700
|
+
const maxOutputBytes = opts?.maxOutputBytes
|
|
701
|
+
if (
|
|
702
|
+
maxOutputBytes !== undefined &&
|
|
703
|
+
(!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0)
|
|
704
|
+
) {
|
|
705
|
+
throw new RangeError('maxOutputBytes must be a non-negative safe integer')
|
|
706
|
+
}
|
|
696
707
|
this._status = 'busy'
|
|
697
708
|
const startTime = Date.now()
|
|
698
709
|
|
|
699
|
-
const env =
|
|
710
|
+
const env = this.buildSpawnEnv(opts?.env)
|
|
700
711
|
const timeout = opts?.timeout ?? this.config.timeoutMs ?? SANDBOX_DEFAULT_TIMEOUT_MS
|
|
701
712
|
|
|
702
713
|
const cwd = opts?.cwd ? await resolveWithinAnyReal(this.roots, opts.cwd) : this.rootDir
|
|
@@ -733,6 +744,7 @@ class LocalSandbox implements Sandbox {
|
|
|
733
744
|
opts?.signal,
|
|
734
745
|
bwrapInfoFd,
|
|
735
746
|
bwrapBlockFd,
|
|
747
|
+
maxOutputBytes,
|
|
736
748
|
)
|
|
737
749
|
return { ...result, durationMs: Date.now() - startTime }
|
|
738
750
|
} finally {
|
|
@@ -749,12 +761,7 @@ class LocalSandbox implements Sandbox {
|
|
|
749
761
|
}
|
|
750
762
|
|
|
751
763
|
const resolved = await resolveWithinAnyReal(this.roots, path)
|
|
752
|
-
await
|
|
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)
|
|
764
|
+
await atomicWriteResolvedFile(resolved, content)
|
|
758
765
|
|
|
759
766
|
this.log.debug('File written', { 'namzu.sandbox.path': resolved })
|
|
760
767
|
}
|
|
@@ -783,9 +790,12 @@ class LocalSandbox implements Sandbox {
|
|
|
783
790
|
}
|
|
784
791
|
|
|
785
792
|
const resolved = await resolveWithinAnyReal(this.roots, path)
|
|
786
|
-
const { offset, length, signal } = options ?? {}
|
|
793
|
+
const { offset, length, signal, maxBytes } = options ?? {}
|
|
787
794
|
signal?.throwIfAborted()
|
|
788
|
-
if (
|
|
795
|
+
if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 0)) {
|
|
796
|
+
throw new RangeError('readFile: maxBytes must be a non-negative safe integer')
|
|
797
|
+
}
|
|
798
|
+
if (offset === undefined && length === undefined && maxBytes === undefined) {
|
|
789
799
|
return await fsReadFile(resolved, signal ? { signal } : undefined)
|
|
790
800
|
}
|
|
791
801
|
if (offset !== undefined && (!Number.isSafeInteger(offset) || offset < 0)) {
|
|
@@ -799,6 +809,9 @@ class LocalSandbox implements Sandbox {
|
|
|
799
809
|
const from = offset ?? 0
|
|
800
810
|
const remaining = Math.max(0, (await handle.stat()).size - from)
|
|
801
811
|
const want = Math.min(length ?? remaining, remaining)
|
|
812
|
+
if (maxBytes !== undefined && want > maxBytes) {
|
|
813
|
+
throw new SandboxLimitError('read-file', maxBytes, want)
|
|
814
|
+
}
|
|
802
815
|
if (want === 0) return Buffer.alloc(0)
|
|
803
816
|
const buf = Buffer.allocUnsafe(want)
|
|
804
817
|
const { bytesRead } = await handle.read(buf, 0, want, from)
|
|
@@ -859,9 +872,12 @@ class LocalSandbox implements Sandbox {
|
|
|
859
872
|
// A generated temp root belongs to this allocation. A working-directory
|
|
860
873
|
// root belongs to the caller. Conflating those lifetimes turns normal run
|
|
861
874
|
// teardown into recursive deletion of the project the turn just edited.
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
875
|
+
await Promise.all([
|
|
876
|
+
this.removeRootOnDestroy ? rm(this.rootDir, { recursive: true, force: true }) : undefined,
|
|
877
|
+
this.seatbeltTempDir === undefined
|
|
878
|
+
? undefined
|
|
879
|
+
: rm(this.seatbeltTempDir, { recursive: true, force: true }),
|
|
880
|
+
])
|
|
865
881
|
|
|
866
882
|
this.log.info('Sandbox destroyed', { 'namzu.sandbox.id': this.id })
|
|
867
883
|
}
|
|
@@ -884,7 +900,7 @@ class LocalSandbox implements Sandbox {
|
|
|
884
900
|
const { spawnCommand, spawnArgs, bwrapInfoFd, bwrapBlockFd } = this.buildSpawnArgs(command, [
|
|
885
901
|
...args,
|
|
886
902
|
])
|
|
887
|
-
const env =
|
|
903
|
+
const env = this.buildSpawnEnv(opts?.env)
|
|
888
904
|
const child = spawn(spawnCommand, spawnArgs, {
|
|
889
905
|
cwd,
|
|
890
906
|
env,
|
|
@@ -931,6 +947,13 @@ class LocalSandbox implements Sandbox {
|
|
|
931
947
|
}
|
|
932
948
|
}
|
|
933
949
|
|
|
950
|
+
private buildSpawnEnv(overrides?: Record<string, string>): Record<string, string> {
|
|
951
|
+
const env = buildSafeEnv(this.config.env, overrides)
|
|
952
|
+
const tempDir = this.environment === 'linux-bwrap' ? '/tmp' : this.seatbeltTempDir
|
|
953
|
+
if (tempDir !== undefined) env.TMPDIR ??= tempDir
|
|
954
|
+
return env
|
|
955
|
+
}
|
|
956
|
+
|
|
934
957
|
private buildSpawnArgs(
|
|
935
958
|
command: string,
|
|
936
959
|
args: string[],
|
|
@@ -940,15 +963,17 @@ class LocalSandbox implements Sandbox {
|
|
|
940
963
|
bwrapInfoFd?: number
|
|
941
964
|
bwrapBlockFd?: number
|
|
942
965
|
} {
|
|
966
|
+
const additionalDirectories =
|
|
967
|
+
this.seatbeltTempDir === undefined
|
|
968
|
+
? this.additionalDirectories
|
|
969
|
+
: [...this.additionalDirectories, this.seatbeltTempDir]
|
|
943
970
|
const built = buildLimitedSpawn({
|
|
944
971
|
environment: this.environment,
|
|
945
972
|
...(this.wrapperCommand !== undefined ? { wrapperCommand: this.wrapperCommand } : {}),
|
|
946
973
|
command,
|
|
947
974
|
args,
|
|
948
975
|
rootDir: this.rootDir,
|
|
949
|
-
|
|
950
|
-
? { additionalDirectories: this.additionalDirectories }
|
|
951
|
-
: {}),
|
|
976
|
+
additionalDirectories,
|
|
952
977
|
...(this.config.memoryLimitMb !== undefined
|
|
953
978
|
? { memoryLimitMb: this.config.memoryLimitMb }
|
|
954
979
|
: {}),
|
|
@@ -988,6 +1013,7 @@ class LocalSandbox implements Sandbox {
|
|
|
988
1013
|
callerSignal?: AbortSignal,
|
|
989
1014
|
bwrapInfoFd?: number,
|
|
990
1015
|
bwrapBlockFd?: number,
|
|
1016
|
+
maxOutputBytes?: number,
|
|
991
1017
|
): Promise<Omit<SandboxExecResult, 'durationMs'>> {
|
|
992
1018
|
return new Promise((resolvePromise, rejectPromise) => {
|
|
993
1019
|
let child: ReturnType<typeof spawn>
|
|
@@ -1013,7 +1039,7 @@ class LocalSandbox implements Sandbox {
|
|
|
1013
1039
|
|
|
1014
1040
|
const stdout = new CappedStream(SANDBOX_MAX_OUTPUT_BYTES)
|
|
1015
1041
|
const stderr = new CappedStream(SANDBOX_MAX_OUTPUT_BYTES)
|
|
1016
|
-
let cancellation: 'caller' | 'deadline' | undefined
|
|
1042
|
+
let cancellation: 'caller' | 'deadline' | 'output' | undefined
|
|
1017
1043
|
let bwrapChildPid: number | undefined
|
|
1018
1044
|
let terminationSignal: NodeJS.Signals | undefined
|
|
1019
1045
|
let settled = false
|
|
@@ -1033,7 +1059,7 @@ class LocalSandbox implements Sandbox {
|
|
|
1033
1059
|
killTree(child, signal)
|
|
1034
1060
|
killBwrapChild(bwrapChildPid, signal)
|
|
1035
1061
|
}
|
|
1036
|
-
const cancel = (origin:
|
|
1062
|
+
const cancel = (origin: NonNullable<typeof cancellation>) => {
|
|
1037
1063
|
if (settled || cancellation !== undefined) return
|
|
1038
1064
|
cancellation = origin
|
|
1039
1065
|
// Own the group while its leader is still ours. Deferring this to
|
|
@@ -1049,8 +1075,22 @@ class LocalSandbox implements Sandbox {
|
|
|
1049
1075
|
escalation.unref?.()
|
|
1050
1076
|
}
|
|
1051
1077
|
|
|
1052
|
-
|
|
1053
|
-
|
|
1078
|
+
let outputBytes = 0
|
|
1079
|
+
let limitError: SandboxLimitError | undefined
|
|
1080
|
+
const output = (stream: CappedStream, chunk: Buffer): void => {
|
|
1081
|
+
if (limitError) return
|
|
1082
|
+
if (maxOutputBytes !== undefined) {
|
|
1083
|
+
outputBytes += chunk.byteLength
|
|
1084
|
+
if (outputBytes > maxOutputBytes) {
|
|
1085
|
+
limitError = new SandboxLimitError('exec-output', maxOutputBytes, outputBytes)
|
|
1086
|
+
cancel('output')
|
|
1087
|
+
return
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
stream.push(chunk)
|
|
1091
|
+
}
|
|
1092
|
+
child.stdout?.on('data', (chunk: Buffer) => output(stdout, chunk))
|
|
1093
|
+
child.stderr?.on('data', (chunk: Buffer) => output(stderr, chunk))
|
|
1054
1094
|
const bwrapInfo = bwrapInfoFd === undefined ? undefined : child.stdio[bwrapInfoFd]
|
|
1055
1095
|
const bwrapBlock = bwrapBlockFd === undefined ? undefined : child.stdio[bwrapBlockFd]
|
|
1056
1096
|
let bwrapInfoBuffer = ''
|
|
@@ -1098,6 +1138,10 @@ class LocalSandbox implements Sandbox {
|
|
|
1098
1138
|
// now: retaining its numeric pid for a later timer risks pid reuse.
|
|
1099
1139
|
terminate('SIGKILL')
|
|
1100
1140
|
}
|
|
1141
|
+
if (limitError) {
|
|
1142
|
+
rejectPromise(limitError)
|
|
1143
|
+
return
|
|
1144
|
+
}
|
|
1101
1145
|
const timedOut = cancellation === 'deadline'
|
|
1102
1146
|
const exitCode = code ?? (timedOut ? 124 : 1)
|
|
1103
1147
|
const attribution = attributeSandboxFailure({
|
|
@@ -1247,24 +1291,39 @@ export class LocalSandboxProvider implements SandboxProvider {
|
|
|
1247
1291
|
rootDir = canonicalizePath(rawDir)
|
|
1248
1292
|
removeRootOnDestroy = true
|
|
1249
1293
|
}
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1294
|
+
let seatbeltTempDir: string | undefined
|
|
1295
|
+
try {
|
|
1296
|
+
config?.signal?.throwIfAborted()
|
|
1297
|
+
if (this.environment === 'macos-seatbelt') {
|
|
1298
|
+
// Keep scratch outside caller-owned workspaces, which may be read-only
|
|
1299
|
+
// on the host and outlive this sandbox.
|
|
1300
|
+
seatbeltTempDir = canonicalizePath(await createTempDir('namzu-seatbelt-'))
|
|
1301
|
+
}
|
|
1302
|
+
config?.signal?.throwIfAborted()
|
|
1254
1303
|
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1304
|
+
this.log.info('Creating sandbox', {
|
|
1305
|
+
'namzu.sandbox.id': id,
|
|
1306
|
+
'namzu.sandbox.root_dir': rootDir,
|
|
1307
|
+
})
|
|
1259
1308
|
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1309
|
+
return new LocalSandbox(
|
|
1310
|
+
id,
|
|
1311
|
+
rootDir,
|
|
1312
|
+
this.environment,
|
|
1313
|
+
this.wrapperCommand,
|
|
1314
|
+
removeRootOnDestroy,
|
|
1315
|
+
seatbeltTempDir,
|
|
1316
|
+
config ?? {},
|
|
1317
|
+
this.log,
|
|
1318
|
+
)
|
|
1319
|
+
} catch (error) {
|
|
1320
|
+
await Promise.all([
|
|
1321
|
+
removeRootOnDestroy ? rm(rootDir, { recursive: true, force: true }) : undefined,
|
|
1322
|
+
seatbeltTempDir === undefined
|
|
1323
|
+
? undefined
|
|
1324
|
+
: rm(seatbeltTempDir, { recursive: true, force: true }),
|
|
1325
|
+
])
|
|
1326
|
+
throw error
|
|
1327
|
+
}
|
|
1269
1328
|
}
|
|
1270
1329
|
}
|
package/src/schedules/cron.ts
CHANGED
|
@@ -129,7 +129,7 @@ function parseField(text: string, field: FieldSpec): number[] {
|
|
|
129
129
|
} else {
|
|
130
130
|
lo = parseValue(rangeText, field)
|
|
131
131
|
// `5/15` means "from 5, every 15", as in Vixie cron.
|
|
132
|
-
hi = stepText !== undefined ?
|
|
132
|
+
hi = stepText !== undefined ? field.max : lo
|
|
133
133
|
}
|
|
134
134
|
for (let v = lo; v <= hi; v += step) values.add(v)
|
|
135
135
|
}
|
|
@@ -119,7 +119,7 @@ export function describeSchedule(
|
|
|
119
119
|
spec: ScheduleSpec,
|
|
120
120
|
options: DescribeScheduleOptions = {},
|
|
121
121
|
): string {
|
|
122
|
-
const tz = options.tz ?? 'UTC'
|
|
122
|
+
const tz = options.tz ?? (spec.kind === 'at' ? spec.tz : undefined) ?? 'UTC'
|
|
123
123
|
switch (spec.kind) {
|
|
124
124
|
case 'at':
|
|
125
125
|
return `once at ${formatWall(Date.parse(spec.at), tz)} (${tz})`
|
|
@@ -107,8 +107,8 @@ function validEvery(spec: { everyMs: number; anchorAt: string }): number {
|
|
|
107
107
|
|
|
108
108
|
/**
|
|
109
109
|
* The first instant strictly after `afterExclusive` at which `spec` fires,
|
|
110
|
-
* or `null` when there is none
|
|
111
|
-
*
|
|
110
|
+
* or `null` when there is none within the supported date range (or, for cron,
|
|
111
|
+
* within the next five years).
|
|
112
112
|
*/
|
|
113
113
|
export function nextFireTime(spec: ScheduleSpec, afterExclusive: Date): Date | null {
|
|
114
114
|
const after = afterExclusive.getTime()
|
|
@@ -123,7 +123,8 @@ export function nextFireTime(spec: ScheduleSpec, afterExclusive: Date): Date | n
|
|
|
123
123
|
case 'every': {
|
|
124
124
|
const anchor = validEvery(spec)
|
|
125
125
|
const k = after < anchor ? 1 : Math.floor((after - anchor) / spec.everyMs) + 1
|
|
126
|
-
|
|
126
|
+
const next = new Date(anchor + Math.max(1, k) * spec.everyMs)
|
|
127
|
+
return Number.isFinite(next.getTime()) ? next : null
|
|
127
128
|
}
|
|
128
129
|
case 'cron': {
|
|
129
130
|
const expr = cronOf(spec.expr)
|
|
@@ -259,7 +260,9 @@ export function assertSpecFires(spec: ScheduleSpec, now: Date): void {
|
|
|
259
260
|
throw new ScheduleValidationError(
|
|
260
261
|
spec.kind === 'at'
|
|
261
262
|
? `${spec.at} is in the past`
|
|
262
|
-
:
|
|
263
|
+
: spec.kind === 'every'
|
|
264
|
+
? 'the next interval is outside the supported date range'
|
|
265
|
+
: `"${spec.expr}" never fires in the next five years`,
|
|
263
266
|
spec.kind === 'cron' ? spec.expr : spec.kind === 'at' ? spec.at : undefined,
|
|
264
267
|
)
|
|
265
268
|
}
|
package/src/schedules/spec.ts
CHANGED
|
@@ -71,6 +71,9 @@ function formatInterval(ms: number): string {
|
|
|
71
71
|
|
|
72
72
|
function everySpec(text: string, now: Date): ScheduleSpec {
|
|
73
73
|
const ms = parseDuration(text)
|
|
74
|
+
if (!Number.isSafeInteger(ms)) {
|
|
75
|
+
throw new ScheduleValidationError(`every ${text} is outside the supported date range`, text)
|
|
76
|
+
}
|
|
74
77
|
if (ms < MINUTE) {
|
|
75
78
|
throw new ScheduleValidationError(
|
|
76
79
|
`every ${text} is shorter than the minimum interval; the nearest allowed is every 1m`,
|
|
@@ -89,6 +92,22 @@ function everySpec(text: string, now: Date): ScheduleSpec {
|
|
|
89
92
|
return { kind: 'every', everyMs: ms, anchorAt: anchor.toISOString() }
|
|
90
93
|
}
|
|
91
94
|
|
|
95
|
+
function validateCivilTime(
|
|
96
|
+
wall: number,
|
|
97
|
+
y: number,
|
|
98
|
+
mo: number,
|
|
99
|
+
d: number,
|
|
100
|
+
h: number,
|
|
101
|
+
mi: number,
|
|
102
|
+
s: number,
|
|
103
|
+
token: string,
|
|
104
|
+
): void {
|
|
105
|
+
const c = civil(wall)
|
|
106
|
+
if (c.year !== y || c.month !== mo || c.day !== d || h > 23 || mi > 59 || s > 59) {
|
|
107
|
+
throw new ScheduleValidationError(`"${token}" is not a real date and time`, token)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
92
111
|
/** Resolve a local `YYYY-MM-DD HH:MM` in `tz` to one instant (the earlier of two). */
|
|
93
112
|
function localToInstant(
|
|
94
113
|
y: number,
|
|
@@ -100,10 +119,7 @@ function localToInstant(
|
|
|
100
119
|
token: string,
|
|
101
120
|
): number {
|
|
102
121
|
const wall = Date.UTC(y, mo - 1, d, h, mi)
|
|
103
|
-
|
|
104
|
-
if (c.year !== y || c.month !== mo || c.day !== d || h > 23 || mi > 59) {
|
|
105
|
-
throw new ScheduleValidationError(`"${token}" is not a real date and time`, token)
|
|
106
|
-
}
|
|
122
|
+
validateCivilTime(wall, y, mo, d, h, mi, 0, token)
|
|
107
123
|
const instants = instantsForWall(wall, tz)
|
|
108
124
|
if (instants.length === 0) {
|
|
109
125
|
throw new ScheduleValidationError(
|
|
@@ -116,8 +132,18 @@ function localToInstant(
|
|
|
116
132
|
|
|
117
133
|
function atSpec(text: string, now: Date, tz: string): ScheduleSpec {
|
|
118
134
|
const t = text.trim()
|
|
119
|
-
|
|
120
|
-
|
|
135
|
+
const offset =
|
|
136
|
+
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/i.exec(
|
|
137
|
+
t,
|
|
138
|
+
)
|
|
139
|
+
if (offset) {
|
|
140
|
+
const [, year, month, day, hour, minute, second = '0'] = offset
|
|
141
|
+
const y = Number(year)
|
|
142
|
+
const mo = Number(month)
|
|
143
|
+
const d = Number(day)
|
|
144
|
+
// setUTCFullYear keeps years 0000–0099 literal.
|
|
145
|
+
const wall = new Date(0).setUTCFullYear(y, mo - 1, d)
|
|
146
|
+
validateCivilTime(wall, y, mo, d, Number(hour), Number(minute), Number(second), t)
|
|
121
147
|
const at = Date.parse(t)
|
|
122
148
|
if (!Number.isFinite(at)) throw new ScheduleValidationError(`"${t}" is not a date`, t)
|
|
123
149
|
return { kind: 'at', at: new Date(at).toISOString() }
|
|
@@ -181,7 +207,10 @@ export function parseScheduleSpec(input: string, options: ParseScheduleOptions =
|
|
|
181
207
|
text.slice(3).trim(),
|
|
182
208
|
)
|
|
183
209
|
}
|
|
184
|
-
|
|
210
|
+
const at = new Date(now.getTime() + ms)
|
|
211
|
+
if (!Number.isFinite(at.getTime()))
|
|
212
|
+
throw new ScheduleValidationError(`${text} is outside the supported date range`, text)
|
|
213
|
+
spec = { kind: 'at', at: at.toISOString() }
|
|
185
214
|
} else if (lower.startsWith('at ')) {
|
|
186
215
|
spec = atSpec(text.slice(3), now, tz)
|
|
187
216
|
} else if (/^\d{4}-\d{2}-\d{2}T/i.test(text)) {
|
package/src/schedules/types.ts
CHANGED
|
@@ -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,
|
|
@@ -943,13 +943,17 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
943
943
|
|
|
944
944
|
async listChildren(sessionId: SessionId): Promise<ChildSessionSummary[]> {
|
|
945
945
|
await this.settledFor(sessionId)
|
|
946
|
-
|
|
946
|
+
const rows = this.#all(
|
|
947
947
|
'SELECT * FROM children WHERE session_id = ? ORDER BY spawned_at, child_id',
|
|
948
948
|
sessionId,
|
|
949
|
-
)
|
|
949
|
+
)
|
|
950
|
+
const children: ChildSessionSummary[] = []
|
|
951
|
+
for (const row of rows) {
|
|
950
952
|
const child = childRow(row)
|
|
951
|
-
|
|
952
|
-
|
|
953
|
+
await this.settledFor(child.childId)
|
|
954
|
+
children.push(childView(child, this.readSession(child.childId)))
|
|
955
|
+
}
|
|
956
|
+
return children
|
|
953
957
|
}
|
|
954
958
|
|
|
955
959
|
async listPendingDecisions(
|