@namzu/sdk 73.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.
- package/CHANGELOG.md +56 -0
- package/README.md +34 -34
- package/dist/authorization/protected-paths.d.ts +7 -0
- package/dist/authorization/protected-paths.d.ts.map +1 -1
- package/dist/authorization/protected-paths.js +7 -0
- package/dist/authorization/protected-paths.js.map +1 -1
- package/dist/authorization/readonly-commands.d.ts +23 -0
- package/dist/authorization/readonly-commands.d.ts.map +1 -1
- package/dist/authorization/readonly-commands.js +89 -3
- package/dist/authorization/readonly-commands.js.map +1 -1
- package/dist/authorization/shell-paths.d.ts +8 -0
- package/dist/authorization/shell-paths.d.ts.map +1 -1
- package/dist/authorization/shell-paths.js +125 -2
- package/dist/authorization/shell-paths.js.map +1 -1
- package/dist/bridge/acp/permission.d.ts +6 -0
- package/dist/bridge/acp/permission.d.ts.map +1 -1
- package/dist/bridge/acp/permission.js.map +1 -1
- package/dist/bridge/acp/server.d.ts.map +1 -1
- package/dist/bridge/acp/server.js +21 -3
- package/dist/bridge/acp/server.js.map +1 -1
- package/dist/compaction/context-window.d.ts.map +1 -1
- package/dist/compaction/context-window.js +11 -0
- package/dist/compaction/context-window.js.map +1 -1
- package/dist/compaction/manual.d.ts.map +1 -1
- package/dist/compaction/manual.js +15 -8
- package/dist/compaction/manual.js.map +1 -1
- package/dist/compaction/plan.d.ts +2 -1
- package/dist/compaction/plan.d.ts.map +1 -1
- package/dist/compaction/plan.js +6 -5
- package/dist/compaction/plan.js.map +1 -1
- package/dist/compaction/retained-images.d.ts +16 -0
- package/dist/compaction/retained-images.d.ts.map +1 -0
- package/dist/compaction/retained-images.js +113 -0
- package/dist/compaction/retained-images.js.map +1 -0
- package/dist/compaction/token-estimate.d.ts +8 -3
- package/dist/compaction/token-estimate.d.ts.map +1 -1
- package/dist/compaction/token-estimate.js +76 -8
- package/dist/compaction/token-estimate.js.map +1 -1
- package/dist/compaction/tool-result-editing.d.ts.map +1 -1
- package/dist/compaction/tool-result-editing.js +15 -8
- package/dist/compaction/tool-result-editing.js.map +1 -1
- package/dist/config/runtime.d.ts +3 -3
- package/dist/constants/acp/index.d.ts +2 -0
- package/dist/constants/acp/index.d.ts.map +1 -1
- package/dist/constants/acp/index.js +2 -0
- package/dist/constants/acp/index.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 +353 -21
- package/dist/pricing/catalogue.generated.js.map +1 -1
- package/dist/provider/attribution.js +1 -1
- package/dist/provider/attribution.js.map +1 -1
- package/dist/public-runtime.d.ts +5 -2
- package/dist/public-runtime.d.ts.map +1 -1
- package/dist/public-runtime.js +8 -1
- package/dist/public-runtime.js.map +1 -1
- package/dist/rag/embedding.d.ts +5 -1
- package/dist/rag/embedding.d.ts.map +1 -1
- package/dist/rag/embedding.js +22 -7
- package/dist/rag/embedding.js.map +1 -1
- package/dist/runtime/query/abandon-turn.d.ts.map +1 -1
- package/dist/runtime/query/abandon-turn.js +9 -0
- package/dist/runtime/query/abandon-turn.js.map +1 -1
- package/dist/runtime/query/compact-session.d.ts +10 -3
- package/dist/runtime/query/compact-session.d.ts.map +1 -1
- package/dist/runtime/query/compact-session.js +24 -14
- package/dist/runtime/query/compact-session.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.map +1 -1
- package/dist/runtime/query/index.js +2 -0
- 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 +46 -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/iteration/phases/compaction.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/compaction.js +60 -5
- package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
- package/dist/runtime/query/iteration/phases/context.d.ts +2 -0
- package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/context.js +1 -0
- package/dist/runtime/query/iteration/phases/context.js.map +1 -1
- package/dist/runtime/query/iteration/request-prefix.d.ts +21 -0
- package/dist/runtime/query/iteration/request-prefix.d.ts.map +1 -0
- package/dist/runtime/query/iteration/request-prefix.js +111 -0
- package/dist/runtime/query/iteration/request-prefix.js.map +1 -0
- 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/review-policy.d.ts +11 -3
- package/dist/runtime/query/review-policy.d.ts.map +1 -1
- package/dist/runtime/query/review-policy.js +54 -3
- package/dist/runtime/query/review-policy.js.map +1 -1
- package/dist/sandbox/exec-stdin.d.ts +21 -0
- package/dist/sandbox/exec-stdin.d.ts.map +1 -0
- package/dist/sandbox/exec-stdin.js +40 -0
- package/dist/sandbox/exec-stdin.js.map +1 -0
- package/dist/sandbox/file-walk-program.js +1 -1
- package/dist/sandbox/file-walk.d.ts +12 -7
- package/dist/sandbox/file-walk.d.ts.map +1 -1
- package/dist/sandbox/file-walk.js +13 -4
- package/dist/sandbox/file-walk.js.map +1 -1
- package/dist/sandbox/ignore-matcher.d.ts +3 -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 +52 -8
- package/dist/sandbox/ignore-source.js.map +1 -1
- package/dist/sandbox/index.d.ts +3 -2
- package/dist/sandbox/index.d.ts.map +1 -1
- package/dist/sandbox/index.js +2 -1
- package/dist/sandbox/index.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 +52 -13
- package/dist/sandbox/provider/local.js.map +1 -1
- package/dist/session/paths.d.ts +6 -0
- package/dist/session/paths.d.ts.map +1 -1
- package/dist/session/paths.js +7 -0
- package/dist/session/paths.js.map +1 -1
- package/dist/session-query/index.d.ts +1 -0
- package/dist/session-query/index.d.ts.map +1 -1
- package/dist/session-query/index.js +26 -15
- package/dist/session-query/index.js.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/disk.js +3 -1
- package/dist/store/evidence/disk.js.map +1 -1
- package/dist/store/evidence/index-page.d.ts +1 -0
- package/dist/store/evidence/index-page.d.ts.map +1 -1
- package/dist/store/evidence/index-page.js +8 -0
- package/dist/store/evidence/index-page.js.map +1 -1
- package/dist/store/evidence/source-text.d.ts +1 -1
- package/dist/store/memory/operation-lock.d.ts.map +1 -1
- package/dist/store/memory/operation-lock.js +15 -1
- package/dist/store/memory/operation-lock.js.map +1 -1
- package/dist/store/session-log/core.d.ts.map +1 -1
- package/dist/store/session-log/core.js +23 -0
- package/dist/store/session-log/core.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/computer-use-image.d.ts +9 -0
- package/dist/tools/builtins/computer-use-image.d.ts.map +1 -1
- package/dist/tools/builtins/computer-use-image.js +21 -0
- package/dist/tools/builtins/computer-use-image.js.map +1 -1
- package/dist/tools/builtins/computer-use.d.ts +1 -9
- package/dist/tools/builtins/computer-use.d.ts.map +1 -1
- package/dist/tools/builtins/computer-use.js +2 -22
- package/dist/tools/builtins/computer-use.js.map +1 -1
- package/dist/tools/builtins/read-file.d.ts.map +1 -1
- package/dist/tools/builtins/read-file.js +20 -12
- package/dist/tools/builtins/read-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/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/toolsets/manager.d.ts +7 -3
- package/dist/toolsets/manager.d.ts.map +1 -1
- package/dist/toolsets/manager.js +7 -3
- package/dist/toolsets/manager.js.map +1 -1
- package/dist/types/common/index.d.ts +26 -0
- package/dist/types/common/index.d.ts.map +1 -1
- package/dist/types/common/index.js +17 -1
- package/dist/types/common/index.js.map +1 -1
- package/dist/types/hitl/index.d.ts +11 -0
- package/dist/types/hitl/index.d.ts.map +1 -1
- package/dist/types/hitl/index.js.map +1 -1
- package/dist/types/rag/embedding.d.ts +4 -0
- package/dist/types/rag/embedding.d.ts.map +1 -1
- package/dist/types/sandbox/index.d.ts +32 -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 +49 -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 +44 -6
- package/dist/types/session/records.d.ts.map +1 -1
- package/dist/types/session/records.js +10 -0
- package/dist/types/session/records.js.map +1 -1
- package/dist/utils/cost.d.ts +32 -0
- package/dist/utils/cost.d.ts.map +1 -1
- package/dist/utils/cost.js +101 -8
- package/dist/utils/cost.js.map +1 -1
- package/package.json +2 -2
- package/src/authorization/protected-paths.ts +7 -0
- package/src/authorization/readonly-commands.ts +85 -3
- package/src/authorization/shell-paths.ts +141 -3
- package/src/bridge/acp/permission.ts +6 -0
- package/src/bridge/acp/server.ts +20 -1
- package/src/compaction/context-window.ts +11 -0
- package/src/compaction/manual.ts +23 -8
- package/src/compaction/plan.ts +11 -5
- package/src/compaction/retained-images.ts +130 -0
- package/src/compaction/token-estimate.ts +86 -8
- package/src/compaction/tool-result-editing.ts +20 -8
- package/src/constants/acp/index.ts +2 -0
- package/src/index.ts +2 -0
- package/src/manager/session/turn-recorder.ts +31 -7
- package/src/pricing/catalogue.generated.ts +353 -21
- package/src/pricing/rates.source.json +254 -26
- package/src/provider/attribution.ts +1 -1
- package/src/public-runtime.ts +22 -0
- package/src/rag/embedding.ts +23 -7
- package/src/runtime/query/abandon-turn.ts +9 -0
- package/src/runtime/query/compact-session.ts +50 -15
- package/src/runtime/query/guard.ts +13 -2
- package/src/runtime/query/index.ts +2 -0
- package/src/runtime/query/iteration/index.ts +46 -11
- package/src/runtime/query/iteration/phases/advisory.ts +2 -2
- package/src/runtime/query/iteration/phases/compaction.ts +77 -5
- package/src/runtime/query/iteration/phases/context.ts +3 -0
- package/src/runtime/query/iteration/request-prefix.ts +161 -0
- package/src/runtime/query/prepare-turn.ts +2 -1
- package/src/runtime/query/review-policy.ts +79 -11
- package/src/sandbox/exec-stdin.ts +54 -0
- package/src/sandbox/file-walk-program.ts +1 -1
- package/src/sandbox/file-walk.ts +25 -18
- package/src/sandbox/ignore-matcher.ts +13 -3
- package/src/sandbox/ignore-source.ts +52 -8
- package/src/sandbox/index.ts +8 -2
- package/src/sandbox/limit-error.ts +10 -0
- package/src/sandbox/provider/local.ts +56 -23
- package/src/session/paths.ts +9 -0
- package/src/session-query/index.ts +23 -14
- package/src/store/budget/ledger.ts +93 -2
- package/src/store/evidence/disk.ts +3 -1
- package/src/store/evidence/index-page.ts +11 -0
- package/src/store/memory/operation-lock.ts +19 -1
- package/src/store/session-log/core.ts +26 -0
- package/src/tools/builtins/atomic-write-file.ts +49 -7
- package/src/tools/builtins/computer-use-image.ts +20 -0
- package/src/tools/builtins/computer-use.ts +1 -20
- package/src/tools/builtins/read-file.ts +34 -12
- package/src/tools/defineTool.ts +4 -3
- package/src/tools/tool-is-available.ts +11 -0
- package/src/toolsets/manager.ts +7 -3
- package/src/types/common/index.ts +50 -1
- package/src/types/hitl/index.ts +11 -0
- package/src/types/rag/embedding.ts +7 -0
- package/src/types/sandbox/index.ts +31 -1
- package/src/types/session/checkpoint.ts +2 -0
- package/src/types/session/events.ts +50 -0
- package/src/types/session/records.ts +15 -0
- package/src/utils/cost.ts +144 -8
|
@@ -854,9 +854,11 @@ export interface ToolReviewRequest {
|
|
|
854
854
|
readonly perCall?: true
|
|
855
855
|
/**
|
|
856
856
|
* Aborts when the question stops being open: the turn was cancelled, a
|
|
857
|
-
* rule or the mode now covers the call,
|
|
858
|
-
* turn
|
|
859
|
-
* ignored. Present
|
|
857
|
+
* rule or the mode now covers the call, an earlier refusal ended the
|
|
858
|
+
* turn, or the person wrote a message instead of answering. A host that
|
|
859
|
+
* shows the question closes it then; its answer is ignored. Present with
|
|
860
|
+
* `perCall`, and on any request when the host gave the turn a live message
|
|
861
|
+
* box (`ResumeContext.waitForOperator`).
|
|
860
862
|
*/
|
|
861
863
|
readonly signal?: AbortSignal
|
|
862
864
|
}
|
|
@@ -1037,6 +1039,69 @@ function isHookGranted(tc: ToolCallSummary): boolean {
|
|
|
1037
1039
|
)
|
|
1038
1040
|
}
|
|
1039
1041
|
|
|
1042
|
+
/**
|
|
1043
|
+
* What the model is told when a message from the person closed a question that
|
|
1044
|
+
* was open, or about to be shown. Nobody refused the call, and the text says so:
|
|
1045
|
+
* the refusal path would otherwise read as the person's decision.
|
|
1046
|
+
*/
|
|
1047
|
+
export const CLOSED_BY_MESSAGE_FEEDBACK =
|
|
1048
|
+
"[Tool call not completed: a message from the user arrived while the approval request for this call was open or about to be shown, so the request was closed and the call did not run. Nobody refused it, so this is not the user's decision. The message follows; ask again if the action is still needed.]"
|
|
1049
|
+
|
|
1050
|
+
/**
|
|
1051
|
+
* Put one question to the person, and take it back if they write instead.
|
|
1052
|
+
*
|
|
1053
|
+
* The host's prompt is handed a signal that closes it (the turn's own, joined
|
|
1054
|
+
* with this one), so a card is taken off the screen; the answer is then the
|
|
1055
|
+
* message's closing text rather than a refusal by the person. With no live
|
|
1056
|
+
* message box (`ResumeContext.waitForOperator`) the question waits as before.
|
|
1057
|
+
*/
|
|
1058
|
+
async function askUntilMessage(
|
|
1059
|
+
prompt: ToolReviewPrompt,
|
|
1060
|
+
request: Omit<ToolReviewRequest, 'signal'>,
|
|
1061
|
+
context: ResumeContext | undefined,
|
|
1062
|
+
): Promise<ToolReviewAnswer> {
|
|
1063
|
+
const wake = context?.waitForOperator
|
|
1064
|
+
if (!wake) {
|
|
1065
|
+
return prompt({
|
|
1066
|
+
...request,
|
|
1067
|
+
...(request.perCall && context?.signal ? { signal: context.signal } : {}),
|
|
1068
|
+
})
|
|
1069
|
+
}
|
|
1070
|
+
const closing = new AbortController()
|
|
1071
|
+
const turn = context?.signal
|
|
1072
|
+
const signal = turn ? AbortSignal.any([turn, closing.signal]) : closing.signal
|
|
1073
|
+
const watching = new AbortController()
|
|
1074
|
+
return new Promise<ToolReviewAnswer>((resolve, reject) => {
|
|
1075
|
+
let done = false
|
|
1076
|
+
const finish = (settle: () => void): void => {
|
|
1077
|
+
if (done) return
|
|
1078
|
+
done = true
|
|
1079
|
+
watching.abort()
|
|
1080
|
+
settle()
|
|
1081
|
+
}
|
|
1082
|
+
turn?.addEventListener('abort', () => watching.abort(), { once: true })
|
|
1083
|
+
Promise.resolve(wake(watching.signal)).then(
|
|
1084
|
+
() =>
|
|
1085
|
+
finish(() => {
|
|
1086
|
+
// Settled first, so the prompt's own rejection on the close below is ignored.
|
|
1087
|
+
resolve({ kind: 'reject', feedback: CLOSED_BY_MESSAGE_FEEDBACK })
|
|
1088
|
+
closing.abort(new Error('A message from the user closed the approval request.'))
|
|
1089
|
+
}),
|
|
1090
|
+
// An aborted or closed wait is the turn ending, which is not a message.
|
|
1091
|
+
() => {},
|
|
1092
|
+
)
|
|
1093
|
+
// One turn of the microtask queue later, so a message that was already waiting has
|
|
1094
|
+
// settled the question before the person is shown it, not after.
|
|
1095
|
+
queueMicrotask(() => {
|
|
1096
|
+
if (done) return
|
|
1097
|
+
Promise.resolve(prompt({ ...request, signal })).then(
|
|
1098
|
+
(answer) => finish(() => resolve(answer)),
|
|
1099
|
+
(error: unknown) => finish(() => reject(error)),
|
|
1100
|
+
)
|
|
1101
|
+
})
|
|
1102
|
+
})
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1040
1105
|
/** The handler behind `createReviewPolicy`, for a host that wants only the function. */
|
|
1041
1106
|
export function createReviewHandler(options: ReviewPolicyOptions = {}): ResumeHandler {
|
|
1042
1107
|
const { prompt, registry } = options
|
|
@@ -1254,14 +1319,17 @@ export function createReviewHandler(options: ReviewPolicyOptions = {}): ResumeHa
|
|
|
1254
1319
|
shown?: readonly ToolCallSummary[],
|
|
1255
1320
|
): Promise<ToolReviewAnswer> =>
|
|
1256
1321
|
answered ??
|
|
1257
|
-
(
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1322
|
+
askUntilMessage(
|
|
1323
|
+
prompt as ToolReviewPrompt,
|
|
1324
|
+
{
|
|
1325
|
+
sessionId: request.sessionId,
|
|
1326
|
+
turnId: request.turnId,
|
|
1327
|
+
toolCalls: shown ?? request.toolCalls,
|
|
1328
|
+
...(screenConsent ? { screenConsent } : {}),
|
|
1329
|
+
...(request.perCall ? { perCall: true as const } : {}),
|
|
1330
|
+
},
|
|
1331
|
+
context,
|
|
1332
|
+
)
|
|
1265
1333
|
// The first look at the screen in a session is the operator's to allow:
|
|
1266
1334
|
// what is on it goes to the model provider, and a screenshot reads as
|
|
1267
1335
|
// harmlessly as a file read to every rule below. Asked once, in the
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { SandboxExecOptions } from '../types/sandbox/index.js'
|
|
2
|
+
|
|
3
|
+
/** The most standard input, in UTF-8 bytes, one `exec` may carry. */
|
|
4
|
+
export const SANDBOX_EXEC_STDIN_MAX_BYTES = 1024 * 1024
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `SandboxExecOptions.stdin` was refused: it is not text, it is over
|
|
8
|
+
* {@link SANDBOX_EXEC_STDIN_MAX_BYTES}, or the backend has no guest agent to
|
|
9
|
+
* carry it. Thrown before anything is sent or started.
|
|
10
|
+
*/
|
|
11
|
+
export class SandboxExecStdinError extends Error {
|
|
12
|
+
constructor(
|
|
13
|
+
message: string,
|
|
14
|
+
readonly reason: 'not-text' | 'too-large' | 'unsupported',
|
|
15
|
+
) {
|
|
16
|
+
super(message)
|
|
17
|
+
this.name = 'SandboxExecStdinError'
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The stdin an agent-backed backend sends, validated: `undefined` when the
|
|
23
|
+
* caller gave none, the text when it is within the bound, a
|
|
24
|
+
* {@link SandboxExecStdinError} otherwise.
|
|
25
|
+
*/
|
|
26
|
+
export function execStdinOf(
|
|
27
|
+
opts: Pick<SandboxExecOptions, 'stdin'> | undefined,
|
|
28
|
+
): string | undefined {
|
|
29
|
+
const stdin = opts?.stdin
|
|
30
|
+
if (stdin === undefined) return undefined
|
|
31
|
+
if (typeof stdin !== 'string') {
|
|
32
|
+
throw new SandboxExecStdinError('exec stdin must be a string.', 'not-text')
|
|
33
|
+
}
|
|
34
|
+
const bytes = Buffer.byteLength(stdin, 'utf8')
|
|
35
|
+
if (bytes > SANDBOX_EXEC_STDIN_MAX_BYTES) {
|
|
36
|
+
throw new SandboxExecStdinError(
|
|
37
|
+
`exec stdin is ${bytes} bytes, over the ${SANDBOX_EXEC_STDIN_MAX_BYTES}-byte limit. Nothing was sent. Stage a larger document with writeFile and redirect it.`,
|
|
38
|
+
'too-large',
|
|
39
|
+
)
|
|
40
|
+
}
|
|
41
|
+
return stdin
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** For a backend without a guest agent: refuse a call that carries stdin. */
|
|
45
|
+
export function refuseExecStdin(
|
|
46
|
+
opts: Pick<SandboxExecOptions, 'stdin'> | undefined,
|
|
47
|
+
backend: string,
|
|
48
|
+
): void {
|
|
49
|
+
if (opts?.stdin === undefined) return
|
|
50
|
+
throw new SandboxExecStdinError(
|
|
51
|
+
`The ${backend} sandbox cannot give a command standard input, so nothing was run. Use an agent-backed sandbox (Firecracker or Kubernetes), or stage the text with writeFile and redirect it.`,
|
|
52
|
+
'unsupported',
|
|
53
|
+
)
|
|
54
|
+
}
|
|
@@ -50,7 +50,7 @@ async function run() {
|
|
|
50
50
|
let emitted = 0;
|
|
51
51
|
const matchers = plan.expressions.map(({source, flags}) => new RegExp(source, flags + 's'));
|
|
52
52
|
const maxDepth = plan.maxDepth === null ? Infinity : plan.maxDepth;
|
|
53
|
-
const ignore = plan.respectIgnore ? ignCreate({fs, path, extraFiles: []}) : null;
|
|
53
|
+
const ignore = plan.respectIgnore ? ignCreate({fs, syncFs: require('node:fs'), path, extraFiles: []}) : null;
|
|
54
54
|
const open = async (absolute, relative, depth, layered) => {
|
|
55
55
|
try {
|
|
56
56
|
const dir = await fs.opendir(absolute);
|
package/src/sandbox/file-walk.ts
CHANGED
|
@@ -183,13 +183,24 @@ function directoryMatcher(plan: WalkPlan): (relative: string) => boolean {
|
|
|
183
183
|
})
|
|
184
184
|
}
|
|
185
185
|
|
|
186
|
+
/** Host-only extensions for a walk inside an already authorized filesystem root. */
|
|
187
|
+
export interface LocalFileWalkOptions extends SandboxWalkFilesOptions {
|
|
188
|
+
/** Skip the per-file size read when the caller will open and check the file. */
|
|
189
|
+
readonly withoutSizes?: boolean
|
|
190
|
+
/** Read .gitignore even in a folder with no repository metadata. */
|
|
191
|
+
readonly gitignoreOutsideRepo?: boolean
|
|
192
|
+
/** Prune entries before descent, in addition to the ignore files. */
|
|
193
|
+
readonly skipEntry?: (absolutePath: string, isDirectory: boolean) => boolean
|
|
194
|
+
/** Called for each directory opened by the walk. */
|
|
195
|
+
readonly onDirectory?: (absolutePath: string) => void
|
|
196
|
+
}
|
|
197
|
+
|
|
186
198
|
/** Local traversal uses the same compiled matching/pruning plan as the guest. */
|
|
187
199
|
async function* executeWalk(
|
|
188
200
|
plan: WalkPlan,
|
|
189
|
-
|
|
190
|
-
onSummary?: (summary: SandboxWalkSummary) => void,
|
|
191
|
-
withoutSizes = false,
|
|
201
|
+
options: LocalFileWalkOptions,
|
|
192
202
|
): AsyncGenerator<SandboxFileEntry> {
|
|
203
|
+
const { signal, onSummary, withoutSizes = false } = options
|
|
193
204
|
const fs = await import('node:fs/promises')
|
|
194
205
|
const path = await import('node:path')
|
|
195
206
|
const { EventEmitter } = await import('node:events')
|
|
@@ -206,7 +217,12 @@ async function* executeWalk(
|
|
|
206
217
|
let ignoredDirectories = 0
|
|
207
218
|
let stopped: SandboxWalkSummary['stopped']
|
|
208
219
|
const ignore = plan.respectIgnore
|
|
209
|
-
? createIgnoreStack({
|
|
220
|
+
? createIgnoreStack({
|
|
221
|
+
fs,
|
|
222
|
+
path,
|
|
223
|
+
extraFiles: globalIgnoreFiles(),
|
|
224
|
+
gitignoreOutsideRepo: options.gitignoreOutsideRepo === true,
|
|
225
|
+
})
|
|
210
226
|
: undefined
|
|
211
227
|
const matchers = plan.expressions.map(({ source, flags }) => new RegExp(source, `${flags}s`))
|
|
212
228
|
const canDescend = directoryMatcher(plan)
|
|
@@ -324,6 +340,7 @@ async function* executeWalk(
|
|
|
324
340
|
})
|
|
325
341
|
if (layered) await ignore?.enter(absolute)
|
|
326
342
|
open.push({ dir, relative, depth, layered })
|
|
343
|
+
options.onDirectory?.(absolute)
|
|
327
344
|
} catch (error) {
|
|
328
345
|
if (!missing(error)) throw error
|
|
329
346
|
}
|
|
@@ -358,6 +375,7 @@ async function* executeWalk(
|
|
|
358
375
|
if (VCS_NAMES.has(entry.name)) continue
|
|
359
376
|
const relative = frame.relative ? `${frame.relative}/${entry.name}` : entry.name
|
|
360
377
|
const absolute = path.join(plan.root, relative)
|
|
378
|
+
if (options.skipEntry?.(absolute, entry.isDirectory())) continue
|
|
361
379
|
const depth = frame.depth + 1
|
|
362
380
|
if (entry.isDirectory()) {
|
|
363
381
|
if (depth >= maxDepth || !canDescend(relative)) continue
|
|
@@ -407,24 +425,13 @@ function globalIgnoreFiles(): string[] {
|
|
|
407
425
|
return base ? [join(base, 'git', 'ignore')] : []
|
|
408
426
|
}
|
|
409
427
|
|
|
410
|
-
/**
|
|
428
|
+
/** Enumerate files under an authorized, canonical host filesystem root. */
|
|
411
429
|
export async function* walkFilesLocally(
|
|
412
430
|
rootPath: string,
|
|
413
|
-
options:
|
|
414
|
-
/**
|
|
415
|
-
* Skip the per-file size read: entries carry `size: 0`. For a caller that
|
|
416
|
-
* opens every file itself and takes the size from the handle.
|
|
417
|
-
*/
|
|
418
|
-
readonly withoutSizes?: boolean
|
|
419
|
-
},
|
|
431
|
+
options: LocalFileWalkOptions,
|
|
420
432
|
): AsyncGenerator<SandboxFileEntry> {
|
|
421
433
|
options.signal?.throwIfAborted()
|
|
422
|
-
yield* executeWalk(
|
|
423
|
-
planWalk(rootPath, options),
|
|
424
|
-
options.signal,
|
|
425
|
-
options.onSummary,
|
|
426
|
-
options.withoutSizes === true,
|
|
427
|
-
)
|
|
434
|
+
yield* executeWalk(planWalk(rootPath, options), options)
|
|
428
435
|
}
|
|
429
436
|
|
|
430
437
|
/** The existing sandbox execution seam; no separate worker protocol is needed. */
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import * as fs from 'node:fs'
|
|
2
|
+
import * as path from 'node:path'
|
|
1
3
|
import { IGNORE_SOURCE } from './ignore-source.js'
|
|
2
4
|
|
|
3
5
|
/** One compiled ignore rule. */
|
|
@@ -23,24 +25,32 @@ export interface IgnoreDeps {
|
|
|
23
25
|
readonly path: unknown
|
|
24
26
|
/** Global exclude files, lowest precedence. The guest has none. */
|
|
25
27
|
readonly extraFiles?: readonly string[]
|
|
28
|
+
readonly gitignoreOutsideRepo?: boolean
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
interface IgnoreModule {
|
|
29
32
|
parse(text: string): IgnoreRule[]
|
|
30
33
|
decide(rules: readonly IgnoreRule[], relative: string, isDirectory: boolean): 0 | 1 | 2
|
|
31
|
-
create(deps: IgnoreDeps): IgnoreStack
|
|
34
|
+
create(deps: IgnoreDeps & { syncFs: typeof fs }): IgnoreStack
|
|
35
|
+
gitDirectory(directory: string, syncFs: typeof fs, paths: typeof path): string | null
|
|
32
36
|
vcs: readonly string[]
|
|
33
37
|
}
|
|
34
38
|
|
|
35
39
|
// The same text is embedded in the guest program, so both walks share it.
|
|
36
40
|
const module_ = new Function(
|
|
37
|
-
`${IGNORE_SOURCE}\nreturn { parse: ignParse, decide: ignDecide, create: ignCreate, vcs: IGN_VCS }`,
|
|
41
|
+
`${IGNORE_SOURCE}\nreturn { parse: ignParse, decide: ignDecide, create: ignCreate, gitDirectory, vcs: IGN_VCS }`,
|
|
38
42
|
)() as IgnoreModule
|
|
39
43
|
|
|
40
44
|
/** Parse the text of one ignore file into rules; a line it cannot read is dropped. */
|
|
41
45
|
export const parseIgnoreRules = module_.parse
|
|
42
46
|
/** 0: no rule matches, 1: ignored, 2: re-included. The last matching rule wins. */
|
|
43
47
|
export const decideIgnore = module_.decide
|
|
44
|
-
export const createIgnoreStack =
|
|
48
|
+
export const createIgnoreStack = (deps: IgnoreDeps): IgnoreStack =>
|
|
49
|
+
module_.create({ ...deps, syncFs: fs })
|
|
50
|
+
|
|
51
|
+
/** @internal Check whether this directory itself has a valid checkout marker. */
|
|
52
|
+
export function hasGitCheckoutMarker(directory: string): boolean {
|
|
53
|
+
return module_.gitDirectory(directory, fs, path) !== null
|
|
54
|
+
}
|
|
45
55
|
/** Version-control directories that no walk ever descends into. */
|
|
46
56
|
export const VCS_NAMES: ReadonlySet<string> = new Set(module_.vcs)
|
|
@@ -132,10 +132,50 @@ function ignDecide(rules, relative, isDirectory) {
|
|
|
132
132
|
}
|
|
133
133
|
return 0;
|
|
134
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* Resolve a checkout marker. A linked worktree uses its own HEAD and the
|
|
137
|
+
* objects and refs from its common directory.
|
|
138
|
+
*/
|
|
139
|
+
function gitDirectory(directory, fs, path) {
|
|
140
|
+
try {
|
|
141
|
+
const marker = path.join(directory, '.git');
|
|
142
|
+
const info = fs.statSync(marker);
|
|
143
|
+
let gitDir = marker;
|
|
144
|
+
if (info.isFile()) {
|
|
145
|
+
if (info.size > 4096) return null;
|
|
146
|
+
const pointer = /^gitdir: ([^\r\n\0]+)(?:\r?\n)?$/.exec(fs.readFileSync(marker, 'utf8'));
|
|
147
|
+
if (!pointer) return null;
|
|
148
|
+
gitDir = path.resolve(directory, pointer[1]);
|
|
149
|
+
if (!fs.statSync(gitDir).isDirectory()) return null;
|
|
150
|
+
} else if (!info.isDirectory()) {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
const head = path.join(gitDir, 'HEAD');
|
|
154
|
+
const headInfo = fs.statSync(head);
|
|
155
|
+
if (!headInfo.isFile() || headInfo.size > 4096) return null;
|
|
156
|
+
const headText = fs.readFileSync(head, 'utf8');
|
|
157
|
+
if (!/^(?:ref:[ \t]*refs\/[^\r\n]+|[0-9a-f]{40}(?:[0-9a-f]{24})?)(?:\r?\n)?$/.test(headText)) return null;
|
|
158
|
+
const common = path.join(gitDir, 'commondir');
|
|
159
|
+
const commonInfo = fs.statSync(common, { throwIfNoEntry: false });
|
|
160
|
+
let storage = gitDir;
|
|
161
|
+
if (commonInfo) {
|
|
162
|
+
if (!commonInfo.isFile() || commonInfo.size > 4096) return null;
|
|
163
|
+
const target = fs.readFileSync(common, 'utf8').replace(/[\r\n]+$/, '');
|
|
164
|
+
if (!target) return null;
|
|
165
|
+
storage = path.resolve(gitDir, target);
|
|
166
|
+
}
|
|
167
|
+
if (!fs.statSync(path.join(storage, 'objects')).isDirectory() ||
|
|
168
|
+
!fs.statSync(path.join(storage, 'refs')).isDirectory()) return null;
|
|
169
|
+
return gitDir;
|
|
170
|
+
} catch (error) {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
135
175
|
/**
|
|
136
176
|
* The layered rules for one walk. The caller enters a directory before it
|
|
137
177
|
* reads it and leaves it after, so the layers follow the depth-first stack.
|
|
138
|
-
* deps: fs (promises), path, extraFiles (
|
|
178
|
+
* deps: fs (promises), syncFs (marker validation), path, extraFiles (host excludes).
|
|
139
179
|
*/
|
|
140
180
|
function ignCreate(deps) {
|
|
141
181
|
const fs = deps.fs;
|
|
@@ -145,6 +185,10 @@ function ignCreate(deps) {
|
|
|
145
185
|
let ancestorsInRepo = false;
|
|
146
186
|
const posix = value => path.sep === '/' ? value : value.split(path.sep).join('/');
|
|
147
187
|
const lstat = async file => { try { return await fs.lstat(file); } catch (error) { return null; } };
|
|
188
|
+
const findGitDirectory = async directory => {
|
|
189
|
+
if (!await lstat(path.join(directory, '.git'))) return null;
|
|
190
|
+
return gitDirectory(directory, deps.syncFs, path);
|
|
191
|
+
};
|
|
148
192
|
const load = async file => {
|
|
149
193
|
const info = await lstat(file);
|
|
150
194
|
if (!info || !info.isFile() || info.size > IGN_MAX_BYTES * 4) return [];
|
|
@@ -152,7 +196,7 @@ function ignCreate(deps) {
|
|
|
152
196
|
};
|
|
153
197
|
const loadDirectory = async (directory, inRepo) => {
|
|
154
198
|
const rules = [];
|
|
155
|
-
if (inRepo) rules.push(...await load(path.join(directory, '.gitignore')));
|
|
199
|
+
if (inRepo || deps.gitignoreOutsideRepo) rules.push(...await load(path.join(directory, '.gitignore')));
|
|
156
200
|
rules.push(...await load(path.join(directory, '.ignore')));
|
|
157
201
|
return rules;
|
|
158
202
|
};
|
|
@@ -165,8 +209,8 @@ function ignCreate(deps) {
|
|
|
165
209
|
let directory = root;
|
|
166
210
|
let repo = null;
|
|
167
211
|
for (;;) {
|
|
168
|
-
const
|
|
169
|
-
if (
|
|
212
|
+
const gitDir = await findGitDirectory(directory);
|
|
213
|
+
if (gitDir) { repo = { directory, gitDir }; break; }
|
|
170
214
|
const parent = path.dirname(directory);
|
|
171
215
|
if (parent === directory) break;
|
|
172
216
|
directory = parent;
|
|
@@ -182,7 +226,7 @@ function ignCreate(deps) {
|
|
|
182
226
|
const rules = [];
|
|
183
227
|
if (index === 0) {
|
|
184
228
|
for (const file of deps.extraFiles || []) rules.push(...await load(file));
|
|
185
|
-
if (repo.
|
|
229
|
+
if (repo.gitDir === path.join(directory, '.git')) rules.push(...await load(path.join(repo.gitDir, 'info', 'exclude')));
|
|
186
230
|
}
|
|
187
231
|
rules.push(...await loadDirectory(directory, true));
|
|
188
232
|
push(directory, rules);
|
|
@@ -193,11 +237,11 @@ function ignCreate(deps) {
|
|
|
193
237
|
let inRepo = parentInRepo;
|
|
194
238
|
const rules = [];
|
|
195
239
|
if (!parentInRepo) {
|
|
196
|
-
const
|
|
197
|
-
if (
|
|
240
|
+
const gitDir = await findGitDirectory(directory);
|
|
241
|
+
if (gitDir) {
|
|
198
242
|
inRepo = true;
|
|
199
243
|
for (const file of deps.extraFiles || []) rules.push(...await load(file));
|
|
200
|
-
if (
|
|
244
|
+
if (gitDir === path.join(directory, '.git')) rules.push(...await load(path.join(gitDir, 'info', 'exclude')));
|
|
201
245
|
}
|
|
202
246
|
}
|
|
203
247
|
rules.push(...await loadDirectory(directory, inRepo));
|
package/src/sandbox/index.ts
CHANGED
|
@@ -2,5 +2,11 @@ export { LocalSandboxProvider } from './provider/local.js'
|
|
|
2
2
|
export type { LocalSandboxProviderOptions } from './provider/local.js'
|
|
3
3
|
export { SandboxProviderFactory } from './factory.js'
|
|
4
4
|
export { assertIsolation, describeIsolation, isolationOf, missingIsolation } from './isolation.js'
|
|
5
|
-
export { walkFilesViaExec } from './file-walk.js'
|
|
6
|
-
export type { SandboxFileWalkExec } from './file-walk.js'
|
|
5
|
+
export { walkFilesLocally, walkFilesViaExec } from './file-walk.js'
|
|
6
|
+
export type { LocalFileWalkOptions, SandboxFileWalkExec } from './file-walk.js'
|
|
7
|
+
export {
|
|
8
|
+
execStdinOf,
|
|
9
|
+
refuseExecStdin,
|
|
10
|
+
SANDBOX_EXEC_STDIN_MAX_BYTES,
|
|
11
|
+
SandboxExecStdinError,
|
|
12
|
+
} from './exec-stdin.js'
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export class SandboxLimitError extends Error {
|
|
2
|
+
constructor(
|
|
3
|
+
readonly kind: 'receive-frame' | 'receive-buffer' | 'exec-output' | 'read-file',
|
|
4
|
+
readonly limit: number,
|
|
5
|
+
readonly actual: number,
|
|
6
|
+
) {
|
|
7
|
+
super(`Sandbox ${kind} exceeded the ${limit} byte limit (got ${actual} bytes)`)
|
|
8
|
+
this.name = 'SandboxLimitError'
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -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'
|
|
@@ -58,6 +51,7 @@ import {
|
|
|
58
51
|
setEnvironmentEntry,
|
|
59
52
|
} from '../../utils/process-environment.js'
|
|
60
53
|
import { createTempDir, resolveTempBase } from '../../utils/temp.js'
|
|
54
|
+
import { refuseExecStdin } from '../exec-stdin.js'
|
|
61
55
|
import { walkFilesLocally } from '../file-walk.js'
|
|
62
56
|
import { assertIsolation, describeIsolation } from '../isolation.js'
|
|
63
57
|
import type { PtyLoader } from '../terminal.js'
|
|
@@ -480,7 +474,7 @@ function seatbeltString(value: string): string {
|
|
|
480
474
|
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
|
|
481
475
|
}
|
|
482
476
|
|
|
483
|
-
function buildSeatbeltProfile(additionalDirectories: readonly string[] = []): string {
|
|
477
|
+
export function buildSeatbeltProfile(additionalDirectories: readonly string[] = []): string {
|
|
484
478
|
return [
|
|
485
479
|
'(version 1)',
|
|
486
480
|
'(deny default)',
|
|
@@ -520,6 +514,16 @@ function buildSeatbeltProfile(additionalDirectories: readonly string[] = []): st
|
|
|
520
514
|
'(allow file-read* (subpath "/private/var/db/dyld"))',
|
|
521
515
|
'(allow file-read* (subpath "/private/var/select"))',
|
|
522
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
|
+
|
|
523
527
|
// --- Device files ---
|
|
524
528
|
'(allow file-read* (subpath "/dev"))',
|
|
525
529
|
'(allow file-write* (literal "/dev/null"))',
|
|
@@ -690,7 +694,15 @@ class LocalSandbox implements Sandbox {
|
|
|
690
694
|
if (this._status === 'destroyed') {
|
|
691
695
|
throw new Error(`Sandbox ${this.id} is destroyed`)
|
|
692
696
|
}
|
|
697
|
+
refuseExecStdin(opts, 'local')
|
|
693
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
|
+
}
|
|
694
706
|
this._status = 'busy'
|
|
695
707
|
const startTime = Date.now()
|
|
696
708
|
|
|
@@ -731,6 +743,7 @@ class LocalSandbox implements Sandbox {
|
|
|
731
743
|
opts?.signal,
|
|
732
744
|
bwrapInfoFd,
|
|
733
745
|
bwrapBlockFd,
|
|
746
|
+
maxOutputBytes,
|
|
734
747
|
)
|
|
735
748
|
return { ...result, durationMs: Date.now() - startTime }
|
|
736
749
|
} finally {
|
|
@@ -747,12 +760,7 @@ class LocalSandbox implements Sandbox {
|
|
|
747
760
|
}
|
|
748
761
|
|
|
749
762
|
const resolved = await resolveWithinAnyReal(this.roots, path)
|
|
750
|
-
await
|
|
751
|
-
|
|
752
|
-
// Convention 8: Atomic write (write-tmp-rename)
|
|
753
|
-
const tmpPath = `${resolved}.tmp.${Date.now()}`
|
|
754
|
-
await fsWriteFile(tmpPath, content)
|
|
755
|
-
await rename(tmpPath, resolved)
|
|
763
|
+
await atomicWriteResolvedFile(resolved, content)
|
|
756
764
|
|
|
757
765
|
this.log.debug('File written', { 'namzu.sandbox.path': resolved })
|
|
758
766
|
}
|
|
@@ -781,9 +789,12 @@ class LocalSandbox implements Sandbox {
|
|
|
781
789
|
}
|
|
782
790
|
|
|
783
791
|
const resolved = await resolveWithinAnyReal(this.roots, path)
|
|
784
|
-
const { offset, length, signal } = options ?? {}
|
|
792
|
+
const { offset, length, signal, maxBytes } = options ?? {}
|
|
785
793
|
signal?.throwIfAborted()
|
|
786
|
-
if (
|
|
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) {
|
|
787
798
|
return await fsReadFile(resolved, signal ? { signal } : undefined)
|
|
788
799
|
}
|
|
789
800
|
if (offset !== undefined && (!Number.isSafeInteger(offset) || offset < 0)) {
|
|
@@ -797,6 +808,9 @@ class LocalSandbox implements Sandbox {
|
|
|
797
808
|
const from = offset ?? 0
|
|
798
809
|
const remaining = Math.max(0, (await handle.stat()).size - from)
|
|
799
810
|
const want = Math.min(length ?? remaining, remaining)
|
|
811
|
+
if (maxBytes !== undefined && want > maxBytes) {
|
|
812
|
+
throw new SandboxLimitError('read-file', maxBytes, want)
|
|
813
|
+
}
|
|
800
814
|
if (want === 0) return Buffer.alloc(0)
|
|
801
815
|
const buf = Buffer.allocUnsafe(want)
|
|
802
816
|
const { bytesRead } = await handle.read(buf, 0, want, from)
|
|
@@ -986,6 +1000,7 @@ class LocalSandbox implements Sandbox {
|
|
|
986
1000
|
callerSignal?: AbortSignal,
|
|
987
1001
|
bwrapInfoFd?: number,
|
|
988
1002
|
bwrapBlockFd?: number,
|
|
1003
|
+
maxOutputBytes?: number,
|
|
989
1004
|
): Promise<Omit<SandboxExecResult, 'durationMs'>> {
|
|
990
1005
|
return new Promise((resolvePromise, rejectPromise) => {
|
|
991
1006
|
let child: ReturnType<typeof spawn>
|
|
@@ -1011,7 +1026,7 @@ class LocalSandbox implements Sandbox {
|
|
|
1011
1026
|
|
|
1012
1027
|
const stdout = new CappedStream(SANDBOX_MAX_OUTPUT_BYTES)
|
|
1013
1028
|
const stderr = new CappedStream(SANDBOX_MAX_OUTPUT_BYTES)
|
|
1014
|
-
let cancellation: 'caller' | 'deadline' | undefined
|
|
1029
|
+
let cancellation: 'caller' | 'deadline' | 'output' | undefined
|
|
1015
1030
|
let bwrapChildPid: number | undefined
|
|
1016
1031
|
let terminationSignal: NodeJS.Signals | undefined
|
|
1017
1032
|
let settled = false
|
|
@@ -1031,7 +1046,7 @@ class LocalSandbox implements Sandbox {
|
|
|
1031
1046
|
killTree(child, signal)
|
|
1032
1047
|
killBwrapChild(bwrapChildPid, signal)
|
|
1033
1048
|
}
|
|
1034
|
-
const cancel = (origin:
|
|
1049
|
+
const cancel = (origin: NonNullable<typeof cancellation>) => {
|
|
1035
1050
|
if (settled || cancellation !== undefined) return
|
|
1036
1051
|
cancellation = origin
|
|
1037
1052
|
// Own the group while its leader is still ours. Deferring this to
|
|
@@ -1047,8 +1062,22 @@ class LocalSandbox implements Sandbox {
|
|
|
1047
1062
|
escalation.unref?.()
|
|
1048
1063
|
}
|
|
1049
1064
|
|
|
1050
|
-
|
|
1051
|
-
|
|
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))
|
|
1052
1081
|
const bwrapInfo = bwrapInfoFd === undefined ? undefined : child.stdio[bwrapInfoFd]
|
|
1053
1082
|
const bwrapBlock = bwrapBlockFd === undefined ? undefined : child.stdio[bwrapBlockFd]
|
|
1054
1083
|
let bwrapInfoBuffer = ''
|
|
@@ -1096,6 +1125,10 @@ class LocalSandbox implements Sandbox {
|
|
|
1096
1125
|
// now: retaining its numeric pid for a later timer risks pid reuse.
|
|
1097
1126
|
terminate('SIGKILL')
|
|
1098
1127
|
}
|
|
1128
|
+
if (limitError) {
|
|
1129
|
+
rejectPromise(limitError)
|
|
1130
|
+
return
|
|
1131
|
+
}
|
|
1099
1132
|
const timedOut = cancellation === 'deadline'
|
|
1100
1133
|
const exitCode = code ?? (timedOut ? 124 : 1)
|
|
1101
1134
|
const attribution = attributeSandboxFailure({
|
package/src/session/paths.ts
CHANGED
|
@@ -34,6 +34,7 @@ import { uuidv7 } from '../utils/uuidv7.js'
|
|
|
34
34
|
* subagents/<child-id>.jsonl, <child-id>.meta.json, <child-id>/subagents/…
|
|
35
35
|
* tool-results/ checkpoints/ budgets/ tasks/ plans/ feedback/ goals/
|
|
36
36
|
* file-history/ lease.json
|
|
37
|
+
* memory/ scratch-<date>-<hex>/ (a conversation without a project only)
|
|
37
38
|
* $TMPDIR/namzu-<user>/<slug>/<session-id>/scratchpad/
|
|
38
39
|
* ```
|
|
39
40
|
*
|
|
@@ -326,6 +327,14 @@ export class SessionPaths {
|
|
|
326
327
|
return join(this.#logParent(locator), checkId(locator.sessionId, 'session'))
|
|
327
328
|
}
|
|
328
329
|
|
|
330
|
+
/**
|
|
331
|
+
* `<session-dir>/memory`: stored memory that belongs to one conversation alone, for a
|
|
332
|
+
* conversation that has no project. A project's own memory stays at {@link memoryDir}.
|
|
333
|
+
*/
|
|
334
|
+
sessionMemoryDir(locator: SessionLocator): string {
|
|
335
|
+
return join(this.sessionDir(locator), 'memory')
|
|
336
|
+
}
|
|
337
|
+
|
|
329
338
|
#child(parent: SessionLocator, childId: SessionId): SessionLocator {
|
|
330
339
|
return { sessionId: childId, ancestors: [...(parent.ancestors ?? []), parent.sessionId] }
|
|
331
340
|
}
|