@theokit/sdk 2.15.2 → 2.18.1
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 +90 -0
- package/dist/a2a/index.cjs +875 -198
- package/dist/a2a/index.cjs.map +1 -1
- package/dist/a2a/index.js +876 -199
- package/dist/a2a/index.js.map +1 -1
- package/dist/{cron-BxLSz1UH.d.cts → cron-Bbg0mBOv.d.ts} +33 -3
- package/dist/{cron-DcaoP7aW.d.ts → cron-ZLSKbDbB.d.cts} +33 -3
- package/dist/cron.cjs +840 -187
- package/dist/cron.cjs.map +1 -1
- package/dist/cron.d.cts +2 -2
- package/dist/cron.d.ts +2 -2
- package/dist/cron.js +840 -187
- package/dist/cron.js.map +1 -1
- package/dist/define-tool.d.ts +9 -2
- package/dist/{errors-Bart0ptP.d.cts → errors-1tVcX3Fq.d.cts} +1 -1
- package/dist/{errors-DJuuubJK.d.ts → errors-qyVYfk9H.d.ts} +1 -1
- package/dist/errors.d.cts +2 -2
- package/dist/eval.cjs +846 -189
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +846 -189
- package/dist/eval.js.map +1 -1
- package/dist/event-bus.d.ts +3 -0
- package/dist/index.cjs +977 -215
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +122 -27
- package/dist/index.d.ts +122 -27
- package/dist/index.js +977 -217
- package/dist/index.js.map +1 -1
- package/dist/internal/agent-loop/tool-dispatch.d.ts +3 -1
- package/dist/internal/agent-loop/tool-result-guard.d.ts +24 -0
- package/dist/internal/agent-loop/tool-timeout.d.ts +23 -0
- package/dist/internal/llm/openai.d.ts +4 -0
- package/dist/internal/llm/sse.d.ts +13 -1
- package/dist/internal/mcp/client.d.ts +1 -1
- package/dist/internal/memory/active-memory.d.ts +1 -1
- package/dist/internal/persistence/conversation-storage-fs.d.cts +7 -1
- package/dist/internal/persistence/conversation-storage-fs.d.ts +7 -1
- package/dist/internal/persistence/conversation-storage-memory.d.cts +7 -1
- package/dist/internal/persistence/conversation-storage-memory.d.ts +7 -1
- package/dist/internal/persistence/pagination.d.cts +8 -0
- package/dist/internal/persistence/pagination.d.ts +8 -0
- package/dist/internal/plugins/index.cjs +135 -0
- package/dist/internal/plugins/index.cjs.map +1 -1
- package/dist/internal/plugins/index.js +135 -0
- package/dist/internal/plugins/index.js.map +1 -1
- package/dist/internal/plugins/manager.d.cts +21 -1
- package/dist/internal/plugins/manager.d.ts +21 -1
- package/dist/internal/plugins/types.d.cts +40 -0
- package/dist/internal/plugins/types.d.ts +40 -0
- package/dist/internal/{memory → resilience}/circuit-breaker.d.ts +5 -1
- package/dist/internal/runtime/hooks/hooks-frontmatter.d.ts +1 -1
- package/dist/internal/runtime/lifecycle/env-policy.d.ts +30 -0
- package/dist/internal/runtime/session/agent-session-store.d.ts +1 -0
- package/dist/internal/telemetry/span-names.d.ts +7 -1
- package/dist/job-queue.d.ts +29 -7
- package/dist/permission-engine.d.ts +32 -7
- package/dist/{run-DXy_MVwz.d.cts → run-pE-34AAo.d.cts} +64 -3
- package/dist/{run-DXy_MVwz.d.ts → run-pE-34AAo.d.ts} +64 -3
- package/dist/sandbox/index.cjs +53 -2
- package/dist/sandbox/index.cjs.map +1 -1
- package/dist/sandbox/index.js +53 -2
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/local-sandbox.d.cts +11 -3
- package/dist/sandbox/local-sandbox.d.ts +11 -3
- package/dist/sandbox/types.d.cts +7 -0
- package/dist/sandbox/types.d.ts +7 -0
- package/dist/types/agent-prims.d.ts +6 -2
- package/dist/types/conversation-storage.d.ts +32 -2
- package/dist/types/mcp.d.ts +20 -0
- package/dist/types/run.d.ts +17 -0
- package/dist/workflow.cjs +6 -3
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.js +6 -3
- package/dist/workflow.js.map +1 -1
- package/package.json +14 -14
package/dist/job-queue.d.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `JobQueue` — background job queue with status tracking
|
|
2
|
+
* `JobQueue` — background job queue with status tracking, cancellation, and an
|
|
3
|
+
* optional concurrency bound.
|
|
3
4
|
*
|
|
4
|
-
* EC-1: all enqueued functions are wrapped in Promise.resolve().then()
|
|
5
|
-
*
|
|
5
|
+
* EC-1: all enqueued functions are wrapped in Promise.resolve().then() so
|
|
6
|
+
* synchronous throws become rejections.
|
|
7
|
+
*
|
|
8
|
+
* #58: each job runs under an `AbortController` whose signal is passed to the
|
|
9
|
+
* job fn, so `cancel()` actually interrupts a running job (not just a status
|
|
10
|
+
* flip); an optional `maxConcurrency` bounds how many jobs run at once.
|
|
6
11
|
*/
|
|
7
12
|
type JobStatus = "pending" | "running" | "completed" | "failed" | "cancelled";
|
|
8
13
|
interface Job<T> {
|
|
@@ -11,17 +16,34 @@ interface Job<T> {
|
|
|
11
16
|
result?: T;
|
|
12
17
|
error?: string;
|
|
13
18
|
}
|
|
19
|
+
/** #58 — construction options. */
|
|
20
|
+
export interface JobQueueOptions {
|
|
21
|
+
/**
|
|
22
|
+
* Max jobs running concurrently. Omit for unbounded (previous behavior).
|
|
23
|
+
* Values < 1 are clamped to 1 (an invalid bound must not deadlock).
|
|
24
|
+
*/
|
|
25
|
+
maxConcurrency?: number;
|
|
26
|
+
}
|
|
14
27
|
export declare class JobQueue {
|
|
28
|
+
#private;
|
|
15
29
|
private jobs;
|
|
30
|
+
private controllers;
|
|
31
|
+
private readonly maxConcurrency;
|
|
32
|
+
private running;
|
|
33
|
+
private readonly waiting;
|
|
34
|
+
constructor(options?: JobQueueOptions);
|
|
16
35
|
/**
|
|
17
|
-
* Enqueue a background function. Returns the job ID immediately.
|
|
18
|
-
*
|
|
36
|
+
* Enqueue a background function. Returns the job ID immediately. The function
|
|
37
|
+
* receives an `AbortSignal` that fires when the job is cancelled (#58) — a
|
|
38
|
+
* cooperative job should observe it to stop early. Existing `() => Promise<T>`
|
|
39
|
+
* callers are unaffected (the signal argument is simply ignored).
|
|
19
40
|
*/
|
|
20
|
-
enqueue<T>(fn: () => Promise<T>): string;
|
|
41
|
+
enqueue<T>(fn: (signal: AbortSignal) => Promise<T>): string;
|
|
21
42
|
getJob(id: string): Job<unknown> | undefined;
|
|
22
43
|
list(): Job<unknown>[];
|
|
23
44
|
/**
|
|
24
|
-
* Cancel a pending or running job. Returns true if cancelled.
|
|
45
|
+
* Cancel a pending or running job. Returns true if cancelled. #58 — aborts the
|
|
46
|
+
* job's `AbortSignal` so a cooperative running job is actually interrupted.
|
|
25
47
|
*/
|
|
26
48
|
cancel(id: string): boolean;
|
|
27
49
|
}
|
|
@@ -1,29 +1,54 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `PermissionEngine` — first-match permission rules for tool invocations.
|
|
3
3
|
*
|
|
4
|
-
* Evaluates a tool name against an ordered list
|
|
5
|
-
* wins; when no rule matches the `defaultAction`
|
|
6
|
-
*
|
|
4
|
+
* Evaluates a tool name (and optional arguments, #55) against an ordered list
|
|
5
|
+
* of rules. First matching rule wins; when no rule matches the `defaultAction`
|
|
6
|
+
* is returned. #55 — the default is now `"ask"` (FAIL-CLOSED): a permission
|
|
7
|
+
* engine that cannot positively allow must not silently allow. Opt back into
|
|
8
|
+
* the previous fail-open behavior with `{ defaultAction: "allow" }`.
|
|
7
9
|
*/
|
|
8
10
|
export type PermissionAction = "allow" | "deny" | "ask";
|
|
11
|
+
/**
|
|
12
|
+
* #55 — an argument matcher. A rule with `args` gates on the tool's argument
|
|
13
|
+
* VALUES, not just its name: an exact string, a RegExp (tested against the
|
|
14
|
+
* stringified value), or a predicate. Every declared arg must match for the
|
|
15
|
+
* rule to apply — so `{ tool: "shell", args: { command: /rm\s+-rf/ } }` denies
|
|
16
|
+
* a destructive shell call while leaving `ls` to fall through.
|
|
17
|
+
*/
|
|
18
|
+
export type ArgMatcher = string | RegExp | ((value: unknown) => boolean);
|
|
9
19
|
export interface PermissionRule {
|
|
10
20
|
/** Tool name (exact string) or pattern (RegExp). */
|
|
11
21
|
tool: string | RegExp;
|
|
22
|
+
/**
|
|
23
|
+
* #55 — optional per-argument matchers. When present, the rule matches only
|
|
24
|
+
* if the tool name matches AND every declared arg predicate matches the
|
|
25
|
+
* corresponding call argument. A missing/undefined arg fails its predicate
|
|
26
|
+
* (the rule does not match) — never throws.
|
|
27
|
+
*/
|
|
28
|
+
args?: Record<string, ArgMatcher>;
|
|
12
29
|
/** Action to take when rule matches. */
|
|
13
30
|
action: PermissionAction;
|
|
14
31
|
}
|
|
15
32
|
/** Options for {@link PermissionEngine}. */
|
|
16
33
|
export interface PermissionEngineOptions {
|
|
17
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Action when no rule matches. #55 — default is now `"ask"` (fail-closed): a
|
|
36
|
+
* permission engine that cannot positively allow must not silently allow.
|
|
37
|
+
* Pass `"allow"` to restore the previous fail-open behavior.
|
|
38
|
+
*/
|
|
18
39
|
readonly defaultAction?: PermissionAction;
|
|
19
40
|
}
|
|
20
41
|
export declare class PermissionEngine {
|
|
42
|
+
#private;
|
|
21
43
|
private readonly rules;
|
|
22
44
|
private readonly defaultAction;
|
|
23
45
|
constructor(rules: PermissionRule[], options?: PermissionEngineOptions);
|
|
24
46
|
/**
|
|
25
|
-
* Evaluate a tool name against the rules. First
|
|
26
|
-
* configured `defaultAction` (default `"
|
|
47
|
+
* Evaluate a tool name (and optional arguments) against the rules. First
|
|
48
|
+
* match wins; falls back to the configured `defaultAction` (default `"ask"`,
|
|
49
|
+
* fail-closed) when no rule matches. #55 — a rule with `args` gates on the
|
|
50
|
+
* argument values, so the same tool name can resolve to different actions
|
|
51
|
+
* depending on what it is asked to do.
|
|
27
52
|
*/
|
|
28
|
-
evaluate(toolName: string): PermissionAction;
|
|
53
|
+
evaluate(toolName: string, args?: Record<string, unknown>): PermissionAction;
|
|
29
54
|
}
|
|
@@ -1,3 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #57 — content-level defense for tool results before they reach the LLM.
|
|
3
|
+
*
|
|
4
|
+
* Two opt-in behaviors, applied at the `transform_tool_result` seam (#65):
|
|
5
|
+
* - `delimit`: wrap untrusted tool output in explicit data boundaries
|
|
6
|
+
* ("spotlighting") so the model treats it as DATA, not instructions — the
|
|
7
|
+
* primary mitigation against tool-result prompt injection. Non-destructive:
|
|
8
|
+
* the content is preserved, only framed. A boundary marker appearing inside
|
|
9
|
+
* the content is neutralized so it cannot break out of the frame.
|
|
10
|
+
* - `redactPii`: replace common PII patterns (email, phone) with `[REDACTED]`.
|
|
11
|
+
*
|
|
12
|
+
* @internal
|
|
13
|
+
*/
|
|
14
|
+
interface ToolResultGuardOptions {
|
|
15
|
+
/** Wrap tool-result content in explicit data boundaries (spotlighting). */
|
|
16
|
+
delimit?: boolean;
|
|
17
|
+
/** Redact common PII patterns (email, phone) in tool-result content. */
|
|
18
|
+
redactPii?: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
1
21
|
/**
|
|
2
22
|
* Type-leaf — primitives shared between `agent.ts`, `run.ts`, and
|
|
3
23
|
* `messages.ts`. Extracted to break LOW type-only cycles #5 and #7
|
|
@@ -55,9 +75,13 @@ interface CustomTool {
|
|
|
55
75
|
* Local handler invoked when the model emits `tool_use` for this tool.
|
|
56
76
|
* Returns a string (becomes the `tool_result.content` surfaced back to the
|
|
57
77
|
* model). Throws → SDK converts to `tool_result` with `isError: true` and
|
|
58
|
-
* the error `message` as content.
|
|
78
|
+
* the error `message` as content. #65 — an optional 2nd `ToolContext`
|
|
79
|
+
* argument carries the run's `AbortSignal`; single-argument handlers are
|
|
80
|
+
* unaffected.
|
|
59
81
|
*/
|
|
60
|
-
handler: (input: Record<string, unknown
|
|
82
|
+
handler: (input: Record<string, unknown>, ctx?: {
|
|
83
|
+
signal?: AbortSignal;
|
|
84
|
+
}) => string | Promise<string>;
|
|
61
85
|
}
|
|
62
86
|
|
|
63
87
|
/**
|
|
@@ -341,6 +365,20 @@ type McpStdioServerConfig = {
|
|
|
341
365
|
env?: Record<string, string>;
|
|
342
366
|
/** Local agents only. Cloud rejects this field. */
|
|
343
367
|
cwd?: string;
|
|
368
|
+
/**
|
|
369
|
+
* #59 — per-request timeout in ms. A request that gets no reply within this
|
|
370
|
+
* window rejects with a typed `NetworkError` (`code: "mcp_timeout"`) instead
|
|
371
|
+
* of hanging the agent loop forever. Default 30_000.
|
|
372
|
+
*/
|
|
373
|
+
requestTimeoutMs?: number;
|
|
374
|
+
/**
|
|
375
|
+
* #54 — env inherit/scrub policy for the spawned MCP server process. Defaults
|
|
376
|
+
* to `"inherit-scrubbed"` (drop secret-like host vars: `*KEY*`/`*SECRET*`/
|
|
377
|
+
* `*TOKEN*`/`*PASSWORD*`/`*_AUTH*`/…) so a third-party MCP server binary cannot
|
|
378
|
+
* exfiltrate host secrets via the environment. `env` above is merged AFTER the
|
|
379
|
+
* policy and always wins. Pass `"all"` to restore full inheritance.
|
|
380
|
+
*/
|
|
381
|
+
envPolicy?: undefined;
|
|
344
382
|
};
|
|
345
383
|
/**
|
|
346
384
|
* OAuth-style auth bundle for HTTP/SSE MCP servers.
|
|
@@ -386,6 +424,12 @@ type McpHttpServerConfig = {
|
|
|
386
424
|
/** Passed through. `Authorization` works here. */
|
|
387
425
|
headers?: Record<string, string>;
|
|
388
426
|
auth?: McpAuthConfig;
|
|
427
|
+
/**
|
|
428
|
+
* #59 — per-request timeout in ms, enforced via `AbortSignal.timeout`. A
|
|
429
|
+
* fetch that does not respond within this window rejects with a typed
|
|
430
|
+
* `NetworkError` (`code: "mcp_timeout"`). Default 30_000.
|
|
431
|
+
*/
|
|
432
|
+
requestTimeoutMs?: number;
|
|
389
433
|
};
|
|
390
434
|
/**
|
|
391
435
|
* Union of MCP server configs. See `docs.md` for the full reference.
|
|
@@ -874,6 +918,23 @@ interface SendOptions {
|
|
|
874
918
|
* @public
|
|
875
919
|
*/
|
|
876
920
|
signal?: AbortSignal;
|
|
921
|
+
/**
|
|
922
|
+
* #58 — per-tool execution timeout in ms. Each tool call is bounded by this
|
|
923
|
+
* deadline (merged with `signal`); a hung tool yields a typed timeout result
|
|
924
|
+
* (exit 124) instead of wedging the run. Undefined = no per-tool timeout.
|
|
925
|
+
*
|
|
926
|
+
* @public
|
|
927
|
+
*/
|
|
928
|
+
perToolTimeoutMs?: number;
|
|
929
|
+
/**
|
|
930
|
+
* #57 — opt-in tool-result content guard applied before tool output reaches
|
|
931
|
+
* the LLM. `{ delimit: true }` frames untrusted tool output as data
|
|
932
|
+
* (prompt-injection mitigation); `{ redactPii: true }` redacts email/phone.
|
|
933
|
+
* Undefined = no guard.
|
|
934
|
+
*
|
|
935
|
+
* @public
|
|
936
|
+
*/
|
|
937
|
+
toolResultGuard?: ToolResultGuardOptions;
|
|
877
938
|
/**
|
|
878
939
|
* Opt-in task wrapping (ADRs D363, D374). When truthy, the entire
|
|
879
940
|
* run is registered as a `Task` in the SDK's observable registry —
|
|
@@ -937,4 +998,4 @@ interface Run {
|
|
|
937
998
|
onDidChangeStatus(listener: (status: RunStatus) => void): () => void;
|
|
938
999
|
}
|
|
939
1000
|
|
|
940
|
-
export type { ThinkingDeltaUpdate as $, AgentConversationTurn as A, SDKTaskMessage as B, CustomTool as C, DoomLoopThresholds as D, SDKThinkingMessage as E, SDKToolUseMessage as F, SDKUserMessage as G, SDKUserMessageEvent as H, InteractionUpdate as I, SendOptions as J, ShellCommand as K, ShellConversationTurn as L, ModelSelection as M, ShellOutput as N, ShellOutputDeltaUpdate as O, PartialToolCallUpdate as P, StepCompletedUpdate as Q, RunResult as R, SDKMessage as S, StepStartedUpdate as T, StreamToCompletionResult as U, SummaryCompletedUpdate as V, SummaryStartedUpdate as W, SummaryUpdate as X, TextBlock as Y, TextDeltaUpdate as Z, ThinkingCompletedUpdate as _, McpServerConfig as a, ThinkingMessage as a0, TokenDeltaUpdate as a1, TokenUsage as a2, ToolCall as a3, ToolCallCompletedUpdate as a4, ToolCallStartedUpdate as a5, ToolResult as a6,
|
|
1001
|
+
export type { ThinkingDeltaUpdate as $, AgentConversationTurn as A, SDKTaskMessage as B, CustomTool as C, DoomLoopThresholds as D, SDKThinkingMessage as E, SDKToolUseMessage as F, SDKUserMessage as G, SDKUserMessageEvent as H, InteractionUpdate as I, SendOptions as J, ShellCommand as K, ShellConversationTurn as L, ModelSelection as M, ShellOutput as N, ShellOutputDeltaUpdate as O, PartialToolCallUpdate as P, StepCompletedUpdate as Q, RunResult as R, SDKMessage as S, StepStartedUpdate as T, StreamToCompletionResult as U, SummaryCompletedUpdate as V, SummaryStartedUpdate as W, SummaryUpdate as X, TextBlock as Y, TextDeltaUpdate as Z, ThinkingCompletedUpdate as _, McpServerConfig as a, ThinkingMessage as a0, TokenDeltaUpdate as a1, TokenUsage as a2, ToolCall as a3, ToolCallCompletedUpdate as a4, ToolCallStartedUpdate as a5, ToolResult as a6, ToolResultGuardOptions as a7, ToolUseBlock as a8, TurnEndedUpdate as a9, UserMessage as aa, UserMessageAppendedUpdate as ab, Run as b, AssistantMessage as c, ConversationStep as d, ConversationTurn as e, CostBreakdown as f, CostSource as g, CostStatus as h, McpAuthConfig as i, McpHttpServerConfig as j, McpOAuthConfig as k, McpStdioServerConfig as l, ModelParameterValue as m, RunErrorDetail as n, RunGitInfo as o, RunOperation as p, RunStatus as q, RunToCompletionOptions as r, RunToCompletionResult as s, SDKAssistantMessage as t, SDKImage as u, SDKImageDimension as v, SDKObjectDelta as w, SDKRequestMessage as x, SDKStatusMessage as y, SDKSystemMessage as z };
|
|
@@ -1,3 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #57 — content-level defense for tool results before they reach the LLM.
|
|
3
|
+
*
|
|
4
|
+
* Two opt-in behaviors, applied at the `transform_tool_result` seam (#65):
|
|
5
|
+
* - `delimit`: wrap untrusted tool output in explicit data boundaries
|
|
6
|
+
* ("spotlighting") so the model treats it as DATA, not instructions — the
|
|
7
|
+
* primary mitigation against tool-result prompt injection. Non-destructive:
|
|
8
|
+
* the content is preserved, only framed. A boundary marker appearing inside
|
|
9
|
+
* the content is neutralized so it cannot break out of the frame.
|
|
10
|
+
* - `redactPii`: replace common PII patterns (email, phone) with `[REDACTED]`.
|
|
11
|
+
*
|
|
12
|
+
* @internal
|
|
13
|
+
*/
|
|
14
|
+
interface ToolResultGuardOptions {
|
|
15
|
+
/** Wrap tool-result content in explicit data boundaries (spotlighting). */
|
|
16
|
+
delimit?: boolean;
|
|
17
|
+
/** Redact common PII patterns (email, phone) in tool-result content. */
|
|
18
|
+
redactPii?: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
1
21
|
/**
|
|
2
22
|
* Type-leaf — primitives shared between `agent.ts`, `run.ts`, and
|
|
3
23
|
* `messages.ts`. Extracted to break LOW type-only cycles #5 and #7
|
|
@@ -55,9 +75,13 @@ interface CustomTool {
|
|
|
55
75
|
* Local handler invoked when the model emits `tool_use` for this tool.
|
|
56
76
|
* Returns a string (becomes the `tool_result.content` surfaced back to the
|
|
57
77
|
* model). Throws → SDK converts to `tool_result` with `isError: true` and
|
|
58
|
-
* the error `message` as content.
|
|
78
|
+
* the error `message` as content. #65 — an optional 2nd `ToolContext`
|
|
79
|
+
* argument carries the run's `AbortSignal`; single-argument handlers are
|
|
80
|
+
* unaffected.
|
|
59
81
|
*/
|
|
60
|
-
handler: (input: Record<string, unknown
|
|
82
|
+
handler: (input: Record<string, unknown>, ctx?: {
|
|
83
|
+
signal?: AbortSignal;
|
|
84
|
+
}) => string | Promise<string>;
|
|
61
85
|
}
|
|
62
86
|
|
|
63
87
|
/**
|
|
@@ -341,6 +365,20 @@ type McpStdioServerConfig = {
|
|
|
341
365
|
env?: Record<string, string>;
|
|
342
366
|
/** Local agents only. Cloud rejects this field. */
|
|
343
367
|
cwd?: string;
|
|
368
|
+
/**
|
|
369
|
+
* #59 — per-request timeout in ms. A request that gets no reply within this
|
|
370
|
+
* window rejects with a typed `NetworkError` (`code: "mcp_timeout"`) instead
|
|
371
|
+
* of hanging the agent loop forever. Default 30_000.
|
|
372
|
+
*/
|
|
373
|
+
requestTimeoutMs?: number;
|
|
374
|
+
/**
|
|
375
|
+
* #54 — env inherit/scrub policy for the spawned MCP server process. Defaults
|
|
376
|
+
* to `"inherit-scrubbed"` (drop secret-like host vars: `*KEY*`/`*SECRET*`/
|
|
377
|
+
* `*TOKEN*`/`*PASSWORD*`/`*_AUTH*`/…) so a third-party MCP server binary cannot
|
|
378
|
+
* exfiltrate host secrets via the environment. `env` above is merged AFTER the
|
|
379
|
+
* policy and always wins. Pass `"all"` to restore full inheritance.
|
|
380
|
+
*/
|
|
381
|
+
envPolicy?: undefined;
|
|
344
382
|
};
|
|
345
383
|
/**
|
|
346
384
|
* OAuth-style auth bundle for HTTP/SSE MCP servers.
|
|
@@ -386,6 +424,12 @@ type McpHttpServerConfig = {
|
|
|
386
424
|
/** Passed through. `Authorization` works here. */
|
|
387
425
|
headers?: Record<string, string>;
|
|
388
426
|
auth?: McpAuthConfig;
|
|
427
|
+
/**
|
|
428
|
+
* #59 — per-request timeout in ms, enforced via `AbortSignal.timeout`. A
|
|
429
|
+
* fetch that does not respond within this window rejects with a typed
|
|
430
|
+
* `NetworkError` (`code: "mcp_timeout"`). Default 30_000.
|
|
431
|
+
*/
|
|
432
|
+
requestTimeoutMs?: number;
|
|
389
433
|
};
|
|
390
434
|
/**
|
|
391
435
|
* Union of MCP server configs. See `docs.md` for the full reference.
|
|
@@ -874,6 +918,23 @@ interface SendOptions {
|
|
|
874
918
|
* @public
|
|
875
919
|
*/
|
|
876
920
|
signal?: AbortSignal;
|
|
921
|
+
/**
|
|
922
|
+
* #58 — per-tool execution timeout in ms. Each tool call is bounded by this
|
|
923
|
+
* deadline (merged with `signal`); a hung tool yields a typed timeout result
|
|
924
|
+
* (exit 124) instead of wedging the run. Undefined = no per-tool timeout.
|
|
925
|
+
*
|
|
926
|
+
* @public
|
|
927
|
+
*/
|
|
928
|
+
perToolTimeoutMs?: number;
|
|
929
|
+
/**
|
|
930
|
+
* #57 — opt-in tool-result content guard applied before tool output reaches
|
|
931
|
+
* the LLM. `{ delimit: true }` frames untrusted tool output as data
|
|
932
|
+
* (prompt-injection mitigation); `{ redactPii: true }` redacts email/phone.
|
|
933
|
+
* Undefined = no guard.
|
|
934
|
+
*
|
|
935
|
+
* @public
|
|
936
|
+
*/
|
|
937
|
+
toolResultGuard?: ToolResultGuardOptions;
|
|
877
938
|
/**
|
|
878
939
|
* Opt-in task wrapping (ADRs D363, D374). When truthy, the entire
|
|
879
940
|
* run is registered as a `Task` in the SDK's observable registry —
|
|
@@ -937,4 +998,4 @@ interface Run {
|
|
|
937
998
|
onDidChangeStatus(listener: (status: RunStatus) => void): () => void;
|
|
938
999
|
}
|
|
939
1000
|
|
|
940
|
-
export type { ThinkingDeltaUpdate as $, AgentConversationTurn as A, SDKTaskMessage as B, CustomTool as C, DoomLoopThresholds as D, SDKThinkingMessage as E, SDKToolUseMessage as F, SDKUserMessage as G, SDKUserMessageEvent as H, InteractionUpdate as I, SendOptions as J, ShellCommand as K, ShellConversationTurn as L, ModelSelection as M, ShellOutput as N, ShellOutputDeltaUpdate as O, PartialToolCallUpdate as P, StepCompletedUpdate as Q, RunResult as R, SDKMessage as S, StepStartedUpdate as T, StreamToCompletionResult as U, SummaryCompletedUpdate as V, SummaryStartedUpdate as W, SummaryUpdate as X, TextBlock as Y, TextDeltaUpdate as Z, ThinkingCompletedUpdate as _, McpServerConfig as a, ThinkingMessage as a0, TokenDeltaUpdate as a1, TokenUsage as a2, ToolCall as a3, ToolCallCompletedUpdate as a4, ToolCallStartedUpdate as a5, ToolResult as a6,
|
|
1001
|
+
export type { ThinkingDeltaUpdate as $, AgentConversationTurn as A, SDKTaskMessage as B, CustomTool as C, DoomLoopThresholds as D, SDKThinkingMessage as E, SDKToolUseMessage as F, SDKUserMessage as G, SDKUserMessageEvent as H, InteractionUpdate as I, SendOptions as J, ShellCommand as K, ShellConversationTurn as L, ModelSelection as M, ShellOutput as N, ShellOutputDeltaUpdate as O, PartialToolCallUpdate as P, StepCompletedUpdate as Q, RunResult as R, SDKMessage as S, StepStartedUpdate as T, StreamToCompletionResult as U, SummaryCompletedUpdate as V, SummaryStartedUpdate as W, SummaryUpdate as X, TextBlock as Y, TextDeltaUpdate as Z, ThinkingCompletedUpdate as _, McpServerConfig as a, ThinkingMessage as a0, TokenDeltaUpdate as a1, TokenUsage as a2, ToolCall as a3, ToolCallCompletedUpdate as a4, ToolCallStartedUpdate as a5, ToolResult as a6, ToolResultGuardOptions as a7, ToolUseBlock as a8, TurnEndedUpdate as a9, UserMessage as aa, UserMessageAppendedUpdate as ab, Run as b, AssistantMessage as c, ConversationStep as d, ConversationTurn as e, CostBreakdown as f, CostSource as g, CostStatus as h, McpAuthConfig as i, McpHttpServerConfig as j, McpOAuthConfig as k, McpStdioServerConfig as l, ModelParameterValue as m, RunErrorDetail as n, RunGitInfo as o, RunOperation as p, RunStatus as q, RunToCompletionOptions as r, RunToCompletionResult as s, SDKAssistantMessage as t, SDKImage as u, SDKImageDimension as v, SDKObjectDelta as w, SDKRequestMessage as x, SDKStatusMessage as y, SDKSystemMessage as z };
|
package/dist/sandbox/index.cjs
CHANGED
|
@@ -6,6 +6,53 @@ var path = require('path');
|
|
|
6
6
|
|
|
7
7
|
// src/sandbox/local-sandbox.ts
|
|
8
8
|
|
|
9
|
+
// src/internal/runtime/lifecycle/env-policy.ts
|
|
10
|
+
var SECRET_PATTERNS = [
|
|
11
|
+
/KEY/i,
|
|
12
|
+
/SECRET/i,
|
|
13
|
+
/TOKEN/i,
|
|
14
|
+
/PASSWORD/i,
|
|
15
|
+
/PASSWD/i,
|
|
16
|
+
/PASSPHRASE/i,
|
|
17
|
+
/[_-]PWD/i,
|
|
18
|
+
/CREDENTIAL/i,
|
|
19
|
+
/PRIVATE/i,
|
|
20
|
+
/_AUTH/i
|
|
21
|
+
];
|
|
22
|
+
var CORE_VARS = [
|
|
23
|
+
"PATH",
|
|
24
|
+
"HOME",
|
|
25
|
+
"SHELL",
|
|
26
|
+
"LANG",
|
|
27
|
+
"LC_ALL",
|
|
28
|
+
"LC_CTYPE",
|
|
29
|
+
"TMPDIR",
|
|
30
|
+
"TMP",
|
|
31
|
+
"TEMP",
|
|
32
|
+
"USER",
|
|
33
|
+
"LOGNAME"
|
|
34
|
+
];
|
|
35
|
+
function isSecretName(name) {
|
|
36
|
+
return SECRET_PATTERNS.some((re) => re.test(name));
|
|
37
|
+
}
|
|
38
|
+
function inheritsUnderPolicy(name, policy) {
|
|
39
|
+
if (policy === "all") return true;
|
|
40
|
+
if (policy === "core") return CORE_VARS.includes(name);
|
|
41
|
+
return !isSecretName(name);
|
|
42
|
+
}
|
|
43
|
+
function resolveChildEnv(options = {}) {
|
|
44
|
+
const parent = options.parent ?? process.env;
|
|
45
|
+
const policy = options.policy ?? "inherit-scrubbed";
|
|
46
|
+
const base = {};
|
|
47
|
+
for (const [name, value] of Object.entries(parent)) {
|
|
48
|
+
if (value !== void 0 && inheritsUnderPolicy(name, policy)) base[name] = value;
|
|
49
|
+
}
|
|
50
|
+
for (const [name, value] of Object.entries(options.overrides ?? {})) {
|
|
51
|
+
base[name] = value;
|
|
52
|
+
}
|
|
53
|
+
return base;
|
|
54
|
+
}
|
|
55
|
+
|
|
9
56
|
// src/sandbox/shell-escape.ts
|
|
10
57
|
function shellEscapePosix(arg) {
|
|
11
58
|
return `'${arg.replace(/'/g, "'\\''")}'`;
|
|
@@ -33,7 +80,9 @@ var SandboxBackend = class {
|
|
|
33
80
|
this.config = {
|
|
34
81
|
workDir: config.workDir ?? "/tmp",
|
|
35
82
|
timeoutMs: config.timeoutMs ?? 3e4,
|
|
36
|
-
maxOutputBytes: config.maxOutputBytes ?? 5 * 1024 * 1024
|
|
83
|
+
maxOutputBytes: config.maxOutputBytes ?? 5 * 1024 * 1024,
|
|
84
|
+
// #54 — preserve the env policy so backends can scrub secrets.
|
|
85
|
+
env: config.env ?? "inherit-scrubbed"
|
|
37
86
|
};
|
|
38
87
|
}
|
|
39
88
|
async readFile(path) {
|
|
@@ -103,7 +152,9 @@ var LocalSandbox = class extends SandboxBackend {
|
|
|
103
152
|
cwd: this.config.workDir,
|
|
104
153
|
timeout,
|
|
105
154
|
maxBuffer: max,
|
|
106
|
-
encoding: "utf-8"
|
|
155
|
+
encoding: "utf-8",
|
|
156
|
+
// #54 — scrub secret-like host env vars from the child by default.
|
|
157
|
+
env: resolveChildEnv({ policy: this.config.env })
|
|
107
158
|
},
|
|
108
159
|
(error, stdout, stderr) => {
|
|
109
160
|
resolve(this.buildResult(error, stdout ?? "", stderr ?? ""));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sandbox/shell-escape.ts","../../src/sandbox/types.ts","../../src/sandbox/local-sandbox.ts","../../src/errors.ts","../../src/sandbox/provision.ts"],"names":["execFile","path","mkdir","dirname","fsWriteFile"],"mappings":";;;;;;;;;AASO,SAAS,iBAAiB,GAAA,EAAqB;AACpD,EAAA,OAAO,CAAA,CAAA,EAAI,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAC,CAAA,CAAA,CAAA;AACvC;;;ACcO,IAAM,oBAAA,GAAN,cAAmC,KAAA,CAAM;AAAA,EACrC,IAAA,GAAO,kBAAA;AAAA,EAChB,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,sBAAA;AAAA,EACd;AACF;AAEO,IAAM,wBAAA,GAAN,cAAuC,KAAA,CAAM;AAAA,EACzC,IAAA,GAAO,uBAAA;AAAA,EAChB,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,0BAAA;AAAA,EACd;AACF;AAEA,IAAM,oBAAA,GAAuB,aAAA;AAEtB,IAAe,iBAAf,MAA8B;AAAA,EACzB,MAAA;AAAA,EAEV,WAAA,CAAY,MAAA,GAAwB,EAAC,EAAG;AACtC,IAAA,IAAA,CAAK,MAAA,GAAS;AAAA,MACZ,OAAA,EAAS,OAAO,OAAA,IAAW,MAAA;AAAA,MAC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AEA,EAAA,OAAO,EAAE,OAAA,EAAQ;AACnB","file":"index.cjs","sourcesContent":["/**\n * POSIX shell escaping for values interpolated into a `SandboxBackend.execute`\n * command string. `execute` runs via `/bin/sh -c`, so any untrusted value\n * (repo URL, ref, path) MUST be quoted to prevent command injection.\n *\n * @internal\n */\n\n/** Wrap `arg` in single quotes, escaping embedded single quotes (`'\\''`). */\nexport function shellEscapePosix(arg: string): string {\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * Sandbox backend protocol — pluggable execution environment for agent tools.\n *\n * Per ADR D1: only 2 abstract methods (`execute` + `uploadFile`). All\n * higher-level operations are derived on the base class. New backends\n * (Docker, Firecracker, E2B) only implement those 2 methods.\n *\n * @public\n */\n\nimport { shellEscapePosix } from \"./shell-escape.js\";\n\nexport interface ExecuteResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n timedOut: boolean;\n}\n\nexport interface SandboxConfig {\n workDir?: string;\n timeoutMs?: number;\n maxOutputBytes?: number;\n}\n\nexport class SandboxSecurityError extends Error {\n readonly code = \"sandbox_security\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"SandboxSecurityError\";\n }\n}\n\nexport class SandboxNotAvailableError extends Error {\n readonly code = \"sandbox_not_available\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"SandboxNotAvailableError\";\n }\n}\n\nconst SHELL_METACHARACTERS = /[;&|`$(){}]/;\n\nexport abstract class SandboxBackend {\n protected config: SandboxConfig;\n\n constructor(config: SandboxConfig = {}) {\n this.config = {\n workDir: config.workDir ?? \"/tmp\",\n timeoutMs: config.timeoutMs ?? 30_000,\n maxOutputBytes: config.maxOutputBytes ?? 5 * 1024 * 1024,\n };\n }\n\n abstract execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult>;\n\n abstract uploadFile(path: string, content: string | Buffer): Promise<void>;\n\n async readFile(path: string): Promise<string> {\n const result = await this.execute(`cat ${this.shellEscape(path)}`);\n if (result.exitCode !== 0) {\n throw new Error(`readFile failed: ${result.stderr}`);\n }\n return result.stdout;\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await this.uploadFile(path, content);\n }\n\n async glob(pattern: string, cwd?: string): Promise<string[]> {\n const dir = cwd ?? this.config.workDir ?? \".\";\n const result = await this.execute(\n `find ${this.shellEscape(dir)} -name ${this.shellEscape(pattern)} -type f 2>/dev/null`,\n );\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async grep(pattern: string, path?: string): Promise<string[]> {\n const target = path ?? \".\";\n const result = await this.execute(\n `grep -rn ${this.shellEscape(pattern)} ${this.shellEscape(target)} 2>/dev/null`,\n );\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async listDir(path: string): Promise<string[]> {\n const result = await this.execute(`ls -1 ${this.shellEscape(path)}`);\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n protected validateCommand(command: string): void {\n if (SHELL_METACHARACTERS.test(command)) {\n throw new SandboxSecurityError(\n `Command contains shell metacharacters: ${command.slice(0, 80)}`,\n );\n }\n }\n\n protected truncateOutput(output: string): string {\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n if (Buffer.byteLength(output) > max) {\n return `${output.slice(0, max)}\\n...(truncated)`;\n }\n return output;\n }\n\n private shellEscape(arg: string): string {\n return shellEscapePosix(arg);\n }\n}\n","/**\n * LocalSandbox — subprocess-based execution with NO isolation.\n *\n * Uses `execFile` with split args (NOT `exec` with string) per EC-1.\n * This is NOT a security boundary — only DockerSandbox provides isolation.\n *\n * @public\n */\n\nimport { execFile } from \"node:child_process\";\nimport { writeFile as fsWriteFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport { type ExecuteResult, SandboxBackend, type SandboxConfig } from \"./types.js\";\n\nexport class LocalSandbox extends SandboxBackend {\n constructor(config: SandboxConfig = {}) {\n super(config);\n }\n\n async execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult> {\n const timeout = opts?.timeoutMs ?? this.config.timeoutMs ?? 30_000;\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n\n return new Promise<ExecuteResult>((resolve) => {\n const child = execFile(\n \"/bin/sh\",\n [\"-c\", command],\n {\n cwd: this.config.workDir,\n timeout,\n maxBuffer: max,\n encoding: \"utf-8\",\n },\n (error, stdout, stderr) => {\n resolve(this.buildResult(error, stdout ?? \"\", stderr ?? \"\"));\n },\n );\n\n // Safety: if child somehow doesn't callback\n child.on(\"error\", () => {\n resolve({ stdout: \"\", stderr: \"spawn error\", exitCode: 1, timedOut: false });\n });\n });\n }\n\n private buildResult(error: Error | null, stdout: string, stderr: string): ExecuteResult {\n const timedOut = error !== null && \"killed\" in error && (error as { killed: boolean }).killed;\n return {\n stdout: this.truncateOutput(stdout),\n stderr: this.truncateOutput(stderr),\n exitCode: timedOut ? 124 : error ? 1 : 0,\n timedOut,\n };\n }\n\n async uploadFile(path: string, content: string | Buffer): Promise<void> {\n const fullPath = path.startsWith(\"/\") ? path : `${this.config.workDir}/${path}`;\n await mkdir(dirname(fullPath), { recursive: true });\n await fsWriteFile(fullPath, content, \"utf-8\");\n }\n}\n","import { defaultRetriableForCode } from \"./internal/default-retriable.js\";\nimport { redactSecrets } from \"./internal/security/redact.js\";\nimport type { RunOperation } from \"./types/run.js\";\n\n/**\n * Finite, machine-readable error codes for provider-originated errors\n * (ADR D66). Consumers can `switch (err.metadata?.code)` exhaustively\n * — adding a new variant is an explicit decision + test coverage.\n *\n * @public\n */\nexport type ErrorCode =\n | \"rate_limit\"\n | \"auth_failed\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"context_too_long\"\n | \"content_filtered\"\n | \"model_unavailable\"\n | \"network\"\n | \"quota_exceeded\"\n | \"unknown\";\n\n/**\n * Codes used by {@link AgentRunError} (Production-Readiness #3, ADR D311).\n *\n * Superset of {@link ErrorCode} extended with codes that do NOT originate\n * from a provider HTTP response:\n *\n * - `quota_exceeded` — billing limit hit (provider 402 or signalled error)\n * - `tool_runtime_error` — custom tool handler threw inside dispatch\n * - `aborted` — caller's `AbortSignal` fired (Phase 4)\n * - `invalid_model` — model id rejected by provider (400 \"model not found\")\n * - `safety_blocked` — provider safety filter blocked req or resp\n * - `provider_unreachable` — DNS/TCP/timeout/5xx at transport boundary\n *\n * The `& {}` tail keeps the literal-union ergonomics (autocomplete) while\n * accepting any string for forward compatibility with constructor calls\n * that pass arbitrary code values (legacy callers).\n *\n * @public\n */\n/**\n * T1.1 — closed literal union for `AgentRunError.code`. The previous\n * `(string & {})` escape hatch let arbitrary strings slip into the type\n * surface and defeated exhaustive `switch (code)` discrimination. This is\n * the canonical closed form. `AgentRunErrorCode` is re-aliased below for\n * source-level back-compat.\n *\n * Adding a new code: append the literal here AND audit every `switch (err.code)`\n * in callers. Type-checker enforces the audit via the `default: assertNever(code)`\n * convention.\n *\n * @public\n */\nexport type KnownAgentRunErrorCode =\n | ErrorCode\n | \"quota_exceeded\"\n | \"tool_runtime_error\"\n | \"aborted\"\n | \"invalid_model\"\n | \"safety_blocked\"\n | \"provider_unreachable\";\n\n/**\n * Back-compat alias of {@link KnownAgentRunErrorCode}. Pre-T1.1 callers that\n * imported `AgentRunErrorCode` keep working; new code SHOULD prefer\n * `KnownAgentRunErrorCode` to make the closed-union intent explicit.\n *\n * @public\n */\nexport type AgentRunErrorCode = KnownAgentRunErrorCode;\n\n/** Snapshot of every known code at runtime — used by the boundary coercer. */\nconst KNOWN_AGENT_RUN_ERROR_CODES = new Set<string>([\n \"rate_limit\",\n \"auth_failed\",\n \"invalid_request\",\n \"timeout\",\n \"server_error\",\n \"context_too_long\",\n \"content_filtered\",\n \"model_unavailable\",\n \"network\",\n \"unknown\",\n \"quota_exceeded\",\n \"tool_runtime_error\",\n \"aborted\",\n \"invalid_model\",\n \"safety_blocked\",\n \"provider_unreachable\",\n]);\n\n/**\n * T1.1 boundary helper — coerce an arbitrary string (typically arriving from\n * a downstream `RunErrorDetail.code` or a deserialized cloud response) into a\n * `KnownAgentRunErrorCode`. Unknown strings collapse to `\"unknown\"` so the\n * closed type contract holds without forcing every caller to switch.\n *\n * @internal\n */\nexport function coerceToKnownAgentRunErrorCode(code: string | undefined): KnownAgentRunErrorCode {\n if (code !== undefined && KNOWN_AGENT_RUN_ERROR_CODES.has(code)) {\n return code as KnownAgentRunErrorCode;\n }\n return \"unknown\";\n}\n\n/**\n * Structured context for errors that originated from a provider HTTP\n * call (ADR D65). Lets callers retry with the right backoff (`retryAfter`),\n * surface actionable diagnostics (`provider`, `endpoint`), and inspect the\n * raw response body when needed (`raw`, capped at ~2KB by the mapper).\n *\n * @public\n */\nexport interface ErrorMetadata {\n /** Provider canonical name (e.g., `\"anthropic\"`, `\"openai\"`, `\"openrouter\"`, `\"gemini\"`). */\n provider: string;\n /** HTTP endpoint that failed (e.g., `\"/v1/messages\"`, `\"/v1/chat/completions\"`). */\n endpoint: string;\n /** Machine-readable error code (finite enum). */\n code: ErrorCode;\n /** HTTP status code if applicable. */\n statusCode?: number;\n /** Seconds to wait before retry, per provider's `retry-after` header (numeric form only). */\n retryAfter?: number;\n /** Raw response body for debugging (truncated to ~2KB by the mapper). */\n raw?: unknown;\n}\n\n/**\n * Base class for all errors thrown by `@theokit/sdk`.\n *\n * Use `isRetryable` to drive retry/backoff logic. `code` and `protoErrorCode`\n * are populated for server-originated errors when available. `metadata`\n * (ADR D65) carries structured `{ provider, endpoint, code, ... }` when\n * the error originated from a provider HTTP call.\n *\n * @public\n */\nexport class TheokitAgentError extends Error {\n override readonly name: string = \"TheokitAgentError\";\n readonly isRetryable: boolean;\n readonly code?: string;\n readonly protoErrorCode?: string;\n readonly metadata?: ErrorMetadata;\n\n constructor(\n message: string,\n options: {\n isRetryable?: boolean;\n code?: string;\n protoErrorCode?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n } = {},\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.isRetryable = options.isRetryable ?? false;\n if (options.code !== undefined) this.code = options.code;\n if (options.protoErrorCode !== undefined) this.protoErrorCode = options.protoErrorCode;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n}\n\n/**\n * Invalid API key, not logged in, insufficient permissions.\n *\n * @public\n */\nexport class AuthenticationError extends TheokitAgentError {\n override readonly name: string = \"AuthenticationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Too many requests or usage limits exceeded.\n *\n * @public\n */\nexport class RateLimitError extends TheokitAgentError {\n override readonly name: string = \"RateLimitError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Invalid model, bad request parameters, malformed options.\n *\n * @public\n */\nexport class ConfigurationError extends TheokitAgentError {\n override readonly name: string = \"ConfigurationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when creating a cloud agent for a repo whose SCM provider is not\n * connected. Use `helpUrl` to point the user at the right reconnect flow.\n *\n * @public\n */\nexport class IntegrationNotConnectedError extends ConfigurationError {\n override readonly name: string = \"IntegrationNotConnectedError\";\n readonly provider: string;\n readonly helpUrl: string;\n\n constructor(\n message: string,\n options: {\n provider: string;\n helpUrl: string;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, options);\n this.provider = options.provider;\n this.helpUrl = options.helpUrl;\n }\n}\n\n/**\n * Service unavailable, timeout, transport-level failure.\n *\n * @public\n */\nexport class NetworkError extends TheokitAgentError {\n override readonly name: string = \"NetworkError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Catch-all for unclassified server or runtime errors.\n *\n * @public\n */\nexport class UnknownAgentError extends TheokitAgentError {\n override readonly name: string = \"UnknownAgentError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown by `Agent.prompt` (and helpers that go through `run.wait()`) when\n * the option `{ throwOnError: true }` is set and the run terminates with\n * `status: 'error'`. Carries the structured `RunResult.error` fields so\n * callers can `catch` once and branch on `code` / `provider` instead of\n * unwrapping the run.\n *\n * Extends {@link TheokitAgentError} per ADR D65 — no new hierarchy.\n *\n * @example\n * try {\n * await Agent.prompt(msg, { apiKey, model, throwOnError: true });\n * } catch (err) {\n * if (err instanceof AgentRunError && err.code === 'auth_failed') {\n * // bad key\n * }\n * }\n *\n * @public\n */\nexport class AgentRunError extends TheokitAgentError {\n override readonly name: string = \"AgentRunError\";\n readonly provider?: string;\n readonly raw?: string;\n /** Provider's request id (`x-request-id` / `request-id` header). Useful for support tickets. */\n readonly requestId?: string;\n /** SDK conversation id this error was raised inside. */\n readonly conversationId?: string;\n\n constructor(\n message: string,\n options: {\n code: AgentRunErrorCode;\n provider?: string;\n raw?: string;\n requestId?: string;\n conversationId?: string;\n retriable?: boolean;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n code: options.code,\n cause: options.cause,\n metadata: options.metadata,\n // D311: most AgentRunErrors are not retriable (auth, validation, abort).\n // Provider mappers (D314) override per-status — explicit `retriable` wins\n // over the implicit default when supplied.\n isRetryable: options.retriable ?? defaultRetriableForCode(options.code),\n });\n if (options.provider !== undefined) this.provider = options.provider;\n if (options.raw !== undefined) this.raw = options.raw;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.conversationId !== undefined) this.conversationId = options.conversationId;\n }\n\n /**\n * Production-Readiness #3 (ADR D311): alias for `isRetryable` exposed as\n * `retriable` to match the handoff contract. Future v2 will deprecate\n * `isRetryable` in favor of this.\n */\n get retriable(): boolean {\n return this.isRetryable;\n }\n\n /**\n * D312: provider's `Retry-After` header in **milliseconds**. Mappers store\n * the header value (seconds) in `metadata.retryAfter`; this getter\n * multiplies by 1000 so the result composes with `Date.now()`/`setTimeout`.\n *\n * Returns `undefined` when no hint was provided. `0` is a legitimate value\n * — use `=== undefined` check rather than truthy check.\n */\n get retryAfterMs(): number | undefined {\n if (this.metadata?.retryAfter === undefined) return undefined;\n return this.metadata.retryAfter * 1000;\n }\n\n /**\n * D313 + T1.5: alias for `metadata.raw`. Provider response body for\n * debugging. T1.5 wraps the value in `redactSecrets` at the getter\n * boundary so secret-shaped substrings (`sk-...`, Bearer JWTs, etc.) are\n * stripped before reaching the caller. Available but NEVER serialized\n * into `.message` (anti-leak invariant).\n */\n get providerError(): unknown {\n const raw = this.metadata?.raw;\n if (raw === undefined) return undefined;\n if (typeof raw === \"string\") return redactSecrets(raw);\n // Non-string raw (object/buffer) — stringify then redact.\n try {\n return redactSecrets(JSON.stringify(raw));\n } catch {\n return redactSecrets(String(raw));\n }\n }\n\n /**\n * T1.5 — sanitized JSON form. `metadata.raw` is OMITTED by default; opt\n * in via `THEOKIT_DEBUG_RAW_ERRORS=1` to surface the (redacted) raw\n * payload for diagnostics. Every other field stays accessible.\n *\n * The single env-var gate is read each call so operators can toggle at\n * runtime without restarting the process.\n */\n toJSON(): Record<string, unknown> {\n const json: Record<string, unknown> = {\n name: this.name,\n message: this.message,\n isRetryable: this.isRetryable,\n };\n addOptionalFields(json, this);\n const safeMeta = sanitizeMetadata(this.metadata);\n if (safeMeta !== undefined) json.metadata = safeMeta;\n return json;\n }\n}\n\nfunction addOptionalFields(json: Record<string, unknown>, err: AgentRunError): void {\n if (err.code !== undefined) json.code = err.code;\n if (err.provider !== undefined) json.provider = err.provider;\n if (err.requestId !== undefined) json.requestId = err.requestId;\n if (err.conversationId !== undefined) json.conversationId = err.conversationId;\n if (err.raw !== undefined) json.raw = redactSecrets(err.raw);\n}\n\nfunction sanitizeMetadata(meta: ErrorMetadata | undefined): ErrorMetadata | undefined {\n if (meta === undefined) return undefined;\n const { raw, ...rest } = meta;\n const debugRaw = process.env.THEOKIT_DEBUG_RAW_ERRORS === \"1\";\n if (debugRaw && raw !== undefined) {\n const redactedRaw =\n typeof raw === \"string\" ? redactSecrets(raw) : redactSecrets(safeStringify(raw));\n return { ...rest, raw: redactedRaw } as ErrorMetadata;\n }\n return rest as ErrorMetadata;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Is this error transient (worth retrying)?\n *\n * Returns the SDK's own retryability verdict: every {@link TheokitAgentError}\n * subclass computes `isRetryable` at construction (rate-limit / network /\n * credential-pool-exhausted are retryable; auth / configuration / unsupported\n * are not), so this predicate is a single source of truth rather than a\n * re-derivation. Non-SDK errors return `false` conservatively — wrap a foreign\n * error in the appropriate SDK error first if you want it considered transient.\n * It never inspects `err.message`.\n *\n * @example\n * try {\n * await agent.send(message, { throwOnError: true });\n * } catch (err) {\n * if (isTransientError(err)) return retryWithBackoff();\n * throw err;\n * }\n *\n * @public\n */\nexport function isTransientError(err: unknown): boolean {\n return err instanceof TheokitAgentError && err.isRetryable === true;\n}\n\n/**\n * Thrown when a {@link Run} or agent operation is not available on the current\n * runtime. Check first with `run.supports(operation)`.\n *\n * Extends {@link TheokitAgentError} (so error-catching code that branches on\n * `instanceof TheokitAgentError` continues to work) but is never retryable —\n * an unsupported operation will not become supported on retry.\n *\n * @public\n */\nexport class UnsupportedRunOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedRunOperationError\";\n readonly operation: RunOperation;\n\n constructor(\n message: string,\n operation: RunOperation,\n options: { code?: string; cause?: unknown } = {},\n ) {\n super(message, {\n ...options,\n isRetryable: false,\n code: options.code ?? \"unsupported_run_operation\",\n });\n this.operation = operation;\n }\n}\n\n/**\n * Thrown when every credential in a per-provider pool is in cooldown\n * and no healthy key is available (ADR D133). The caller's\n * {@link import(\"./internal/llm/fallback-client.js\").FallbackLlmClient}\n * catches this and tries the next provider in the fallback chain.\n *\n * `metadata.nextRetryAt` (epoch ms) tells callers when the soonest\n * pool entry resumes — useful for manual retry scheduling.\n *\n * @public\n */\nexport class CredentialPoolExhaustedError extends TheokitAgentError {\n override readonly name: string = \"CredentialPoolExhaustedError\";\n readonly provider: string;\n readonly nextRetryAt: number | undefined;\n\n constructor(\n message: string,\n options: {\n provider: string;\n nextRetryAt?: number;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n ...options,\n isRetryable: true,\n code: options.code ?? \"credential_pool_exhausted\",\n });\n this.provider = options.provider;\n this.nextRetryAt = options.nextRetryAt;\n }\n}\n\n/**\n * Finite error codes specific to memory adapter operations (ADR D141).\n *\n * @public\n */\nexport type MemoryAdapterErrorCode =\n | \"auth_failed\"\n | \"rate_limited\"\n | \"not_found\"\n | \"network\"\n | \"invalid_input\"\n | \"unknown\";\n\n/**\n * Error raised by `@theokit-memory-*` adapters. Carries `adapterId`\n * so callers can branch on which provider failed (ADR D141).\n *\n * @public\n */\nexport class MemoryAdapterError extends TheokitAgentError {\n override readonly name: string = \"MemoryAdapterError\";\n readonly adapterId: string;\n\n constructor(\n message: string,\n options: {\n adapterId: string;\n code: MemoryAdapterErrorCode;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n isRetryable: options.code === \"rate_limited\" || options.code === \"network\",\n code: options.code,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n });\n this.adapterId = options.adapterId;\n }\n}\n\n/**\n * Thrown when a user-supplied task ID violates the grammar\n * `^[a-z0-9][a-z0-9_-]*$` (D368) OR starts with a reserved adapter\n * prefix (`wf-` / `b-` / `cron-`, EC-5).\n *\n * @public\n */\nexport class InvalidTaskIdError extends TheokitAgentError {\n override readonly name: string = \"InvalidTaskIdError\";\n readonly taskId: string;\n\n constructor(message: string, taskId: string, options: { cause?: unknown } = {}) {\n super(message, {\n ...options,\n isRetryable: false,\n code: \"invalid_task_id\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `Task.subscribe(id)` is called for a task that has been\n * evicted, never submitted, or evicted after retention (D373).\n *\n * @public\n */\nexport class TaskNotFoundError extends TheokitAgentError {\n override readonly name: string = \"TaskNotFoundError\";\n readonly taskId: string;\n\n constructor(taskId: string, options: { cause?: unknown } = {}) {\n super(`Task not found: ${taskId}`, {\n ...options,\n isRetryable: false,\n code: \"task_not_found\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `CloudAgent` is asked to wrap a task (D370). Cloud\n * task observability is deferred until Theo PaaS GA.\n *\n * @public\n */\nexport class UnsupportedTaskOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedTaskOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Task operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D370)`,\n {\n ...options,\n isRetryable: false,\n code: \"task_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n\n/**\n * Thrown by `Budget` enforcement (ADR D386) when a `mode: \"block\"`\n * budget would be exceeded by the upcoming LLM call. Caller pega\n * tipado para retry-after-window-reset or surface to the user.\n *\n * @public\n */\nexport class BudgetExceededError extends TheokitAgentError {\n override readonly name: string = \"BudgetExceededError\";\n readonly budgetName: string;\n readonly window: import(\"./types/budget.js\").BudgetWindow;\n readonly spentUsd: number;\n readonly limitUsd: number;\n readonly mode: import(\"./types/budget.js\").BudgetMode;\n\n constructor(args: {\n budgetName: string;\n window: import(\"./types/budget.js\").BudgetWindow;\n spentUsd: number;\n limitUsd: number;\n mode: import(\"./types/budget.js\").BudgetMode;\n cause?: unknown;\n }) {\n super(\n `Budget \"${args.budgetName}\" exceeded for window ${args.window}: spent $${args.spentUsd.toFixed(4)} > limit $${args.limitUsd.toFixed(4)}`,\n {\n ...(args.cause !== undefined ? { cause: args.cause } : {}),\n isRetryable: false,\n code: \"budget_exceeded\",\n },\n );\n this.budgetName = args.budgetName;\n this.window = args.window;\n this.spentUsd = args.spentUsd;\n this.limitUsd = args.limitUsd;\n this.mode = args.mode;\n }\n}\n\n/**\n * Thrown when `CloudAgent.send({ budget })` is invoked (D388). Cloud\n * budget surface waits for Theo PaaS GA.\n *\n * @public\n */\n/**\n * T1.6 — Thrown when a consumer calls `agent.send()` or any method\n * on an agent that has already been `dispose()`d. Pre-T1.6 this was\n * a generic `new Error(\"Agent has been disposed\")` — consumers\n * couldn't catch it without string-matching the message.\n *\n * @public\n */\nexport class AgentDisposedError extends TheokitAgentError {\n override readonly name: string = \"AgentDisposedError\";\n readonly agentId: string;\n\n constructor(agentId: string) {\n super(`Agent \"${agentId}\" has been disposed. Create a new agent or use Agent.resume().`, {\n isRetryable: false,\n code: \"agent_disposed\",\n });\n this.agentId = agentId;\n }\n}\n\nexport class UnsupportedBudgetOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedBudgetOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Budget operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D388)`,\n {\n ...options,\n isRetryable: false,\n code: \"budget_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n","/**\n * M6-3 — portable repo provisioner for the eval harness.\n *\n * Clones a repository and checks out a ref into an isolated working dir, issuing\n * every git command through {@link SandboxBackend.execute} (ADR D2 — same code\n * runs on Local/Docker/E2B; never a direct `child_process` import). Promotes\n * theocode's `prepareRepo` (`swebench-provision.ts:37`) onto the SDK's sandbox\n * abstraction.\n *\n * referencia: knowledge-base/references/theocode-eval/lib/swebench-provision.ts:37\n * (clone+checkout), :13 (ProvisionError with instanceId).\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"../errors.js\";\nimport { LocalSandbox } from \"./local-sandbox.js\";\nimport { shellEscapePosix } from \"./shell-escape.js\";\nimport type { SandboxBackend } from \"./types.js\";\n\n/**\n * Raised when cloning or checking out a repo fails. Carries the `instanceId`\n * so a batch run can attribute the failure to the offending dataset row.\n */\nexport class RepoProvisionError extends TheokitAgentError {\n override readonly name = \"RepoProvisionError\";\n\n constructor(\n readonly instanceId: string,\n message: string,\n options: { cause?: unknown } = {},\n ) {\n super(`[${instanceId}] ${message}`, {\n code: \"repo_provision_failed\",\n isRetryable: false,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n });\n }\n}\n\n/** Options for {@link provisionRepo}. */\nexport interface ProvisionRepoOptions {\n /**\n * Clonable repo URL or local path. SECURITY: when this comes from an\n * untrusted dataset, the value is passed to `git clone` after a `--`\n * end-of-options terminator (no flag injection) and with the `ext::`\n * transport disabled (no arbitrary-command transport).\n */\n readonly repoUrl: string;\n /** Branch, tag, or commit SHA to check out. Rejected if it begins with `-`. */\n readonly ref: string;\n /**\n * Unique id for this row — names the target dir and any error. Validated to\n * `[A-Za-z0-9._-]` (no path traversal) since it becomes a directory name.\n */\n readonly instanceId: string;\n}\n\n/**\n * Reject ids that would escape the workdir or be parsed as a git flag. Must\n * start with an alphanumeric (blocks `.`, `..`, `-foo`, leading-dot names) and\n * thereafter allow only `[A-Za-z0-9._-]`.\n */\nconst SAFE_INSTANCE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/**\n * Clone `repoUrl` into `<sandbox workdir>/<instanceId>` and check out `ref`.\n * Returns the absolute `repoDir` (resolved via `git rev-parse --show-toplevel`,\n * which is portable across backends). Throws {@link RepoProvisionError} naming\n * the `instanceId` when clone or checkout exits non-zero.\n *\n * The `sandbox` is optional (V3-5): when omitted, a default {@link LocalSandbox}\n * is used (clones into the process cwd's `<instanceId>`) — pass an explicit\n * sandbox (e.g. `LocalSandbox({ workDir })` / Docker / E2B) to control the workdir.\n */\nexport function provisionRepo(opts: ProvisionRepoOptions): Promise<{ repoDir: string }>;\nexport function provisionRepo(\n sandbox: SandboxBackend,\n opts: ProvisionRepoOptions,\n): Promise<{ repoDir: string }>;\nexport async function provisionRepo(\n sandboxOrOpts: SandboxBackend | ProvisionRepoOptions,\n maybeOpts?: ProvisionRepoOptions,\n): Promise<{ repoDir: string }> {\n const sandbox = maybeOpts !== undefined ? (sandboxOrOpts as SandboxBackend) : new LocalSandbox();\n const opts = maybeOpts ?? (sandboxOrOpts as ProvisionRepoOptions);\n const { repoUrl, ref, instanceId } = opts;\n\n // Validate untrusted-derivable inputs before they reach git/the shell.\n if (!SAFE_INSTANCE_ID.test(instanceId)) {\n throw new RepoProvisionError(\n instanceId,\n \"invalid instanceId: must match [A-Za-z0-9._-] (no path traversal)\",\n );\n }\n if (ref.startsWith(\"-\")) {\n throw new RepoProvisionError(instanceId, `invalid ref: must not begin with '-' (got ${ref})`);\n }\n\n // `--` terminates options (no `--upload-pack=` flag injection); `protocol.ext.allow=never`\n // blocks the `ext::` arbitrary-command transport. `file`/`https` stay allowed.\n const clone = await sandbox.execute(\n `git -c protocol.ext.allow=never clone --quiet -- ${shellEscapePosix(repoUrl)} ${shellEscapePosix(instanceId)}`,\n );\n if (clone.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `clone failed: ${clone.stderr.trim()}`);\n }\n\n const top = await sandbox.execute(\n `git -C ${shellEscapePosix(instanceId)} rev-parse --show-toplevel`,\n );\n if (top.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `resolve repoDir failed: ${top.stderr.trim()}`);\n }\n const repoDir = top.stdout.trim();\n\n // `ref` is validated above not to begin with `-`, so it cannot be parsed as a flag.\n const checkout = await sandbox.execute(\n `git -C ${shellEscapePosix(repoDir)} checkout --quiet ${shellEscapePosix(ref)}`,\n );\n if (checkout.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `checkout ${ref} failed: ${checkout.stderr.trim()}`);\n }\n\n return { repoDir };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/internal/runtime/lifecycle/env-policy.ts","../../src/sandbox/shell-escape.ts","../../src/sandbox/types.ts","../../src/sandb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AAA,EAAQ;AACnB","file":"index.cjs","sourcesContent":["/**\n * Child-process environment policy (#54).\n *\n * Every subprocess the SDK spawns previously inherited the FULL `process.env`,\n * so API keys, tokens and passwords leaked into hook scripts and shell tools.\n * `resolveChildEnv` computes the env a child receives under an explicit policy,\n * modeled on codex's `ShellEnvironmentPolicy`\n * (referencia: codex/codex-rs/protocol/src/shell_environment.rs).\n *\n * Modes:\n * - `inherit-scrubbed` (DEFAULT) — inherit all parent vars EXCEPT secret-like\n * names (`*KEY*`, `*SECRET*`, `*TOKEN*`, `*PASSWORD*`, `*_AUTH*`). Non-breaking:\n * existing spawns keep every non-secret var; only secrets stop leaking.\n * - `core` — inherit ONLY a safe base allowlist (PATH/HOME/…); strongest scrub.\n * - `all` — explicit opt-out: inherit everything, secrets included.\n *\n * Explicit `overrides` ALWAYS win (merged last), so a tool can re-inject a var\n * it genuinely needs even under a scrubbing policy.\n *\n * @internal\n */\n\nexport type EnvPolicy = \"inherit-scrubbed\" | \"core\" | \"all\";\n\nexport interface ResolveChildEnvOptions {\n /** Source env to derive from. Defaults to `process.env`. */\n parent?: Record<string, string | undefined>;\n /** Inherit/scrub policy. Defaults to `inherit-scrubbed`. */\n policy?: EnvPolicy;\n /** Explicit vars merged AFTER the policy — always win. */\n overrides?: Record<string, string>;\n}\n\n/**\n * Secret-like variable-name patterns (case-insensitive). A parent var whose\n * name matches any of these is dropped under `inherit-scrubbed`. Conservative\n * by design — see the EC-4 false-positive test. `[_-]PWD` (not bare `PWD`)\n * catches `DB_PWD` without dropping the shell's working-directory `PWD`.\n * `CREDENTIAL` catches `GOOGLE_APPLICATION_CREDENTIALS`. NOTE: a denylist cannot\n * catch creds embedded in a value (e.g. `DATABASE_URL=postgres://u:pw@…`) — for\n * untrusted children use policy `\"core\"` (allowlist), the only fail-closed mode.\n */\nconst SECRET_PATTERNS: readonly RegExp[] = [\n /KEY/i,\n /SECRET/i,\n /TOKEN/i,\n /PASSWORD/i,\n /PASSWD/i,\n /PASSPHRASE/i,\n /[_-]PWD/i,\n /CREDENTIAL/i,\n /PRIVATE/i,\n /_AUTH/i,\n];\n\n/**\n * Safe base variables kept under the `core` policy. Process-hygiene vars a\n * child almost always needs; none are secret-bearing.\n */\nconst CORE_VARS: readonly string[] = [\n \"PATH\",\n \"HOME\",\n \"SHELL\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TMPDIR\",\n \"TMP\",\n \"TEMP\",\n \"USER\",\n \"LOGNAME\",\n];\n\nfunction isSecretName(name: string): boolean {\n return SECRET_PATTERNS.some((re) => re.test(name));\n}\n\n/** Whether a parent var of the given name is inherited under `policy`. */\nfunction inheritsUnderPolicy(name: string, policy: EnvPolicy): boolean {\n if (policy === \"all\") return true;\n if (policy === \"core\") return CORE_VARS.includes(name);\n return !isSecretName(name); // inherit-scrubbed\n}\n\nexport function resolveChildEnv(options: ResolveChildEnvOptions = {}): Record<string, string> {\n const parent = options.parent ?? process.env;\n const policy = options.policy ?? \"inherit-scrubbed\";\n\n const base: Record<string, string> = {};\n for (const [name, value] of Object.entries(parent)) {\n if (value !== undefined && inheritsUnderPolicy(name, policy)) base[name] = value;\n }\n\n // Explicit overrides always win — even over a scrub.\n for (const [name, value] of Object.entries(options.overrides ?? {})) {\n base[name] = value;\n }\n return base;\n}\n","/**\n * POSIX shell escaping for values interpolated into a `SandboxBackend.execute`\n * command string. `execute` runs via `/bin/sh -c`, so any untrusted value\n * (repo URL, ref, path) MUST be quoted to prevent command injection.\n *\n * @internal\n */\n\n/** Wrap `arg` in single quotes, escaping embedded single quotes (`'\\''`). */\nexport function shellEscapePosix(arg: string): string {\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * Sandbox backend protocol — pluggable execution environment for agent tools.\n *\n * Per ADR D1: only 2 abstract methods (`execute` + `uploadFile`). All\n * higher-level operations are derived on the base class. New backends\n * (Docker, Firecracker, E2B) only implement those 2 methods.\n *\n * @public\n */\n\nimport { shellEscapePosix } from \"./shell-escape.js\";\n\nexport interface ExecuteResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n timedOut: boolean;\n}\n\nexport interface SandboxConfig {\n workDir?: string;\n timeoutMs?: number;\n maxOutputBytes?: number;\n /**\n * #54 — env inherit/scrub policy for the executed command's child process.\n * Defaults to `\"inherit-scrubbed\"` (drop secret-like vars: `*KEY*`, `*SECRET*`,\n * `*TOKEN*`, `*PASSWORD*`, `*_AUTH*`). Pass `\"all\"` to restore full inheritance\n * or `\"core\"` for a minimal safe allowlist.\n */\n env?: import(\"../internal/runtime/lifecycle/env-policy.js\").EnvPolicy;\n}\n\nexport class SandboxSecurityError extends Error {\n readonly code = \"sandbox_security\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"SandboxSecurityError\";\n }\n}\n\nexport class SandboxNotAvailableError extends Error {\n readonly code = \"sandbox_not_available\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"SandboxNotAvailableError\";\n }\n}\n\nconst SHELL_METACHARACTERS = /[;&|`$(){}]/;\n\nexport abstract class SandboxBackend {\n protected config: SandboxConfig;\n\n constructor(config: SandboxConfig = {}) {\n this.config = {\n workDir: config.workDir ?? \"/tmp\",\n timeoutMs: config.timeoutMs ?? 30_000,\n maxOutputBytes: config.maxOutputBytes ?? 5 * 1024 * 1024,\n // #54 — preserve the env policy so backends can scrub secrets.\n env: config.env ?? \"inherit-scrubbed\",\n };\n }\n\n abstract execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult>;\n\n abstract uploadFile(path: string, content: string | Buffer): Promise<void>;\n\n async readFile(path: string): Promise<string> {\n const result = await this.execute(`cat ${this.shellEscape(path)}`);\n if (result.exitCode !== 0) {\n throw new Error(`readFile failed: ${result.stderr}`);\n }\n return result.stdout;\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await this.uploadFile(path, content);\n }\n\n async glob(pattern: string, cwd?: string): Promise<string[]> {\n const dir = cwd ?? this.config.workDir ?? \".\";\n const result = await this.execute(\n `find ${this.shellEscape(dir)} -name ${this.shellEscape(pattern)} -type f 2>/dev/null`,\n );\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async grep(pattern: string, path?: string): Promise<string[]> {\n const target = path ?? \".\";\n const result = await this.execute(\n `grep -rn ${this.shellEscape(pattern)} ${this.shellEscape(target)} 2>/dev/null`,\n );\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n async listDir(path: string): Promise<string[]> {\n const result = await this.execute(`ls -1 ${this.shellEscape(path)}`);\n if (result.exitCode !== 0) return [];\n return result.stdout.trim().split(\"\\n\").filter(Boolean);\n }\n\n protected validateCommand(command: string): void {\n if (SHELL_METACHARACTERS.test(command)) {\n throw new SandboxSecurityError(\n `Command contains shell metacharacters: ${command.slice(0, 80)}`,\n );\n }\n }\n\n protected truncateOutput(output: string): string {\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n if (Buffer.byteLength(output) > max) {\n return `${output.slice(0, max)}\\n...(truncated)`;\n }\n return output;\n }\n\n private shellEscape(arg: string): string {\n return shellEscapePosix(arg);\n }\n}\n","/**\n * LocalSandbox — subprocess-based execution. **This is NOT an isolation\n * boundary.** It runs the command via `/bin/sh -c` in the SAME OS as the host\n * with the host's filesystem and network fully reachable — it provides NO\n * process, filesystem, or network isolation. Its only safety affordances are:\n * - a wall-clock timeout (kills a runaway command),\n * - an output-size cap (bounds memory), and\n * - env scrubbing (#54): secret-like parent env vars (`*KEY*`/`*SECRET*`/\n * `*TOKEN*`/`*PASSWORD*`/`*_AUTH*`) are dropped from the child by default\n * (`SandboxConfig.env`), so a shell tool cannot exfiltrate host secrets via\n * the environment.\n *\n * For real isolation (untrusted code), use a container/VM backend — NOT this.\n *\n * @public\n */\n\nimport { execFile } from \"node:child_process\";\nimport { writeFile as fsWriteFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport { resolveChildEnv } from \"../internal/runtime/lifecycle/env-policy.js\";\nimport { type ExecuteResult, SandboxBackend, type SandboxConfig } from \"./types.js\";\n\nexport class LocalSandbox extends SandboxBackend {\n constructor(config: SandboxConfig = {}) {\n super(config);\n }\n\n async execute(command: string, opts?: { timeoutMs?: number }): Promise<ExecuteResult> {\n const timeout = opts?.timeoutMs ?? this.config.timeoutMs ?? 30_000;\n const max = this.config.maxOutputBytes ?? 5 * 1024 * 1024;\n\n return new Promise<ExecuteResult>((resolve) => {\n const child = execFile(\n \"/bin/sh\",\n [\"-c\", command],\n {\n cwd: this.config.workDir,\n timeout,\n maxBuffer: max,\n encoding: \"utf-8\",\n // #54 — scrub secret-like host env vars from the child by default.\n env: resolveChildEnv({ policy: this.config.env }),\n },\n (error, stdout, stderr) => {\n resolve(this.buildResult(error, stdout ?? \"\", stderr ?? \"\"));\n },\n );\n\n // Safety: if child somehow doesn't callback\n child.on(\"error\", () => {\n resolve({ stdout: \"\", stderr: \"spawn error\", exitCode: 1, timedOut: false });\n });\n });\n }\n\n private buildResult(error: Error | null, stdout: string, stderr: string): ExecuteResult {\n const timedOut = error !== null && \"killed\" in error && (error as { killed: boolean }).killed;\n return {\n stdout: this.truncateOutput(stdout),\n stderr: this.truncateOutput(stderr),\n exitCode: timedOut ? 124 : error ? 1 : 0,\n timedOut,\n };\n }\n\n async uploadFile(path: string, content: string | Buffer): Promise<void> {\n const fullPath = path.startsWith(\"/\") ? path : `${this.config.workDir}/${path}`;\n await mkdir(dirname(fullPath), { recursive: true });\n await fsWriteFile(fullPath, content, \"utf-8\");\n }\n}\n","import { defaultRetriableForCode } from \"./internal/default-retriable.js\";\nimport { redactSecrets } from \"./internal/security/redact.js\";\nimport type { RunOperation } from \"./types/run.js\";\n\n/**\n * Finite, machine-readable error codes for provider-originated errors\n * (ADR D66). Consumers can `switch (err.metadata?.code)` exhaustively\n * — adding a new variant is an explicit decision + test coverage.\n *\n * @public\n */\nexport type ErrorCode =\n | \"rate_limit\"\n | \"auth_failed\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"context_too_long\"\n | \"content_filtered\"\n | \"model_unavailable\"\n | \"network\"\n | \"quota_exceeded\"\n | \"unknown\";\n\n/**\n * Codes used by {@link AgentRunError} (Production-Readiness #3, ADR D311).\n *\n * Superset of {@link ErrorCode} extended with codes that do NOT originate\n * from a provider HTTP response:\n *\n * - `quota_exceeded` — billing limit hit (provider 402 or signalled error)\n * - `tool_runtime_error` — custom tool handler threw inside dispatch\n * - `aborted` — caller's `AbortSignal` fired (Phase 4)\n * - `invalid_model` — model id rejected by provider (400 \"model not found\")\n * - `safety_blocked` — provider safety filter blocked req or resp\n * - `provider_unreachable` — DNS/TCP/timeout/5xx at transport boundary\n *\n * The `& {}` tail keeps the literal-union ergonomics (autocomplete) while\n * accepting any string for forward compatibility with constructor calls\n * that pass arbitrary code values (legacy callers).\n *\n * @public\n */\n/**\n * T1.1 — closed literal union for `AgentRunError.code`. The previous\n * `(string & {})` escape hatch let arbitrary strings slip into the type\n * surface and defeated exhaustive `switch (code)` discrimination. This is\n * the canonical closed form. `AgentRunErrorCode` is re-aliased below for\n * source-level back-compat.\n *\n * Adding a new code: append the literal here AND audit every `switch (err.code)`\n * in callers. Type-checker enforces the audit via the `default: assertNever(code)`\n * convention.\n *\n * @public\n */\nexport type KnownAgentRunErrorCode =\n | ErrorCode\n | \"quota_exceeded\"\n | \"tool_runtime_error\"\n | \"aborted\"\n | \"invalid_model\"\n | \"safety_blocked\"\n | \"provider_unreachable\";\n\n/**\n * Back-compat alias of {@link KnownAgentRunErrorCode}. Pre-T1.1 callers that\n * imported `AgentRunErrorCode` keep working; new code SHOULD prefer\n * `KnownAgentRunErrorCode` to make the closed-union intent explicit.\n *\n * @public\n */\nexport type AgentRunErrorCode = KnownAgentRunErrorCode;\n\n/** Snapshot of every known code at runtime — used by the boundary coercer. */\nconst KNOWN_AGENT_RUN_ERROR_CODES = new Set<string>([\n \"rate_limit\",\n \"auth_failed\",\n \"invalid_request\",\n \"timeout\",\n \"server_error\",\n \"context_too_long\",\n \"content_filtered\",\n \"model_unavailable\",\n \"network\",\n \"unknown\",\n \"quota_exceeded\",\n \"tool_runtime_error\",\n \"aborted\",\n \"invalid_model\",\n \"safety_blocked\",\n \"provider_unreachable\",\n]);\n\n/**\n * T1.1 boundary helper — coerce an arbitrary string (typically arriving from\n * a downstream `RunErrorDetail.code` or a deserialized cloud response) into a\n * `KnownAgentRunErrorCode`. Unknown strings collapse to `\"unknown\"` so the\n * closed type contract holds without forcing every caller to switch.\n *\n * @internal\n */\nexport function coerceToKnownAgentRunErrorCode(code: string | undefined): KnownAgentRunErrorCode {\n if (code !== undefined && KNOWN_AGENT_RUN_ERROR_CODES.has(code)) {\n return code as KnownAgentRunErrorCode;\n }\n return \"unknown\";\n}\n\n/**\n * Structured context for errors that originated from a provider HTTP\n * call (ADR D65). Lets callers retry with the right backoff (`retryAfter`),\n * surface actionable diagnostics (`provider`, `endpoint`), and inspect the\n * raw response body when needed (`raw`, capped at ~2KB by the mapper).\n *\n * @public\n */\nexport interface ErrorMetadata {\n /** Provider canonical name (e.g., `\"anthropic\"`, `\"openai\"`, `\"openrouter\"`, `\"gemini\"`). */\n provider: string;\n /** HTTP endpoint that failed (e.g., `\"/v1/messages\"`, `\"/v1/chat/completions\"`). */\n endpoint: string;\n /** Machine-readable error code (finite enum). */\n code: ErrorCode;\n /** HTTP status code if applicable. */\n statusCode?: number;\n /** Seconds to wait before retry, per provider's `retry-after` header (numeric form only). */\n retryAfter?: number;\n /** Raw response body for debugging (truncated to ~2KB by the mapper). */\n raw?: unknown;\n}\n\n/**\n * Base class for all errors thrown by `@theokit/sdk`.\n *\n * Use `isRetryable` to drive retry/backoff logic. `code` and `protoErrorCode`\n * are populated for server-originated errors when available. `metadata`\n * (ADR D65) carries structured `{ provider, endpoint, code, ... }` when\n * the error originated from a provider HTTP call.\n *\n * @public\n */\nexport class TheokitAgentError extends Error {\n override readonly name: string = \"TheokitAgentError\";\n readonly isRetryable: boolean;\n readonly code?: string;\n readonly protoErrorCode?: string;\n readonly metadata?: ErrorMetadata;\n\n constructor(\n message: string,\n options: {\n isRetryable?: boolean;\n code?: string;\n protoErrorCode?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n } = {},\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.isRetryable = options.isRetryable ?? false;\n if (options.code !== undefined) this.code = options.code;\n if (options.protoErrorCode !== undefined) this.protoErrorCode = options.protoErrorCode;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n}\n\n/**\n * Invalid API key, not logged in, insufficient permissions.\n *\n * @public\n */\nexport class AuthenticationError extends TheokitAgentError {\n override readonly name: string = \"AuthenticationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Too many requests or usage limits exceeded.\n *\n * @public\n */\nexport class RateLimitError extends TheokitAgentError {\n override readonly name: string = \"RateLimitError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Invalid model, bad request parameters, malformed options.\n *\n * @public\n */\nexport class ConfigurationError extends TheokitAgentError {\n override readonly name: string = \"ConfigurationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when creating a cloud agent for a repo whose SCM provider is not\n * connected. Use `helpUrl` to point the user at the right reconnect flow.\n *\n * @public\n */\nexport class IntegrationNotConnectedError extends ConfigurationError {\n override readonly name: string = \"IntegrationNotConnectedError\";\n readonly provider: string;\n readonly helpUrl: string;\n\n constructor(\n message: string,\n options: {\n provider: string;\n helpUrl: string;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, options);\n this.provider = options.provider;\n this.helpUrl = options.helpUrl;\n }\n}\n\n/**\n * Service unavailable, timeout, transport-level failure.\n *\n * @public\n */\nexport class NetworkError extends TheokitAgentError {\n override readonly name: string = \"NetworkError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Catch-all for unclassified server or runtime errors.\n *\n * @public\n */\nexport class UnknownAgentError extends TheokitAgentError {\n override readonly name: string = \"UnknownAgentError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown by `Agent.prompt` (and helpers that go through `run.wait()`) when\n * the option `{ throwOnError: true }` is set and the run terminates with\n * `status: 'error'`. Carries the structured `RunResult.error` fields so\n * callers can `catch` once and branch on `code` / `provider` instead of\n * unwrapping the run.\n *\n * Extends {@link TheokitAgentError} per ADR D65 — no new hierarchy.\n *\n * @example\n * try {\n * await Agent.prompt(msg, { apiKey, model, throwOnError: true });\n * } catch (err) {\n * if (err instanceof AgentRunError && err.code === 'auth_failed') {\n * // bad key\n * }\n * }\n *\n * @public\n */\nexport class AgentRunError extends TheokitAgentError {\n override readonly name: string = \"AgentRunError\";\n readonly provider?: string;\n readonly raw?: string;\n /** Provider's request id (`x-request-id` / `request-id` header). Useful for support tickets. */\n readonly requestId?: string;\n /** SDK conversation id this error was raised inside. */\n readonly conversationId?: string;\n\n constructor(\n message: string,\n options: {\n code: AgentRunErrorCode;\n provider?: string;\n raw?: string;\n requestId?: string;\n conversationId?: string;\n retriable?: boolean;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n code: options.code,\n cause: options.cause,\n metadata: options.metadata,\n // D311: most AgentRunErrors are not retriable (auth, validation, abort).\n // Provider mappers (D314) override per-status — explicit `retriable` wins\n // over the implicit default when supplied.\n isRetryable: options.retriable ?? defaultRetriableForCode(options.code),\n });\n if (options.provider !== undefined) this.provider = options.provider;\n if (options.raw !== undefined) this.raw = options.raw;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.conversationId !== undefined) this.conversationId = options.conversationId;\n }\n\n /**\n * Production-Readiness #3 (ADR D311): alias for `isRetryable` exposed as\n * `retriable` to match the handoff contract. Future v2 will deprecate\n * `isRetryable` in favor of this.\n */\n get retriable(): boolean {\n return this.isRetryable;\n }\n\n /**\n * D312: provider's `Retry-After` header in **milliseconds**. Mappers store\n * the header value (seconds) in `metadata.retryAfter`; this getter\n * multiplies by 1000 so the result composes with `Date.now()`/`setTimeout`.\n *\n * Returns `undefined` when no hint was provided. `0` is a legitimate value\n * — use `=== undefined` check rather than truthy check.\n */\n get retryAfterMs(): number | undefined {\n if (this.metadata?.retryAfter === undefined) return undefined;\n return this.metadata.retryAfter * 1000;\n }\n\n /**\n * D313 + T1.5: alias for `metadata.raw`. Provider response body for\n * debugging. T1.5 wraps the value in `redactSecrets` at the getter\n * boundary so secret-shaped substrings (`sk-...`, Bearer JWTs, etc.) are\n * stripped before reaching the caller. Available but NEVER serialized\n * into `.message` (anti-leak invariant).\n */\n get providerError(): unknown {\n const raw = this.metadata?.raw;\n if (raw === undefined) return undefined;\n if (typeof raw === \"string\") return redactSecrets(raw);\n // Non-string raw (object/buffer) — stringify then redact.\n try {\n return redactSecrets(JSON.stringify(raw));\n } catch {\n return redactSecrets(String(raw));\n }\n }\n\n /**\n * T1.5 — sanitized JSON form. `metadata.raw` is OMITTED by default; opt\n * in via `THEOKIT_DEBUG_RAW_ERRORS=1` to surface the (redacted) raw\n * payload for diagnostics. Every other field stays accessible.\n *\n * The single env-var gate is read each call so operators can toggle at\n * runtime without restarting the process.\n */\n toJSON(): Record<string, unknown> {\n const json: Record<string, unknown> = {\n name: this.name,\n message: this.message,\n isRetryable: this.isRetryable,\n };\n addOptionalFields(json, this);\n const safeMeta = sanitizeMetadata(this.metadata);\n if (safeMeta !== undefined) json.metadata = safeMeta;\n return json;\n }\n}\n\nfunction addOptionalFields(json: Record<string, unknown>, err: AgentRunError): void {\n if (err.code !== undefined) json.code = err.code;\n if (err.provider !== undefined) json.provider = err.provider;\n if (err.requestId !== undefined) json.requestId = err.requestId;\n if (err.conversationId !== undefined) json.conversationId = err.conversationId;\n if (err.raw !== undefined) json.raw = redactSecrets(err.raw);\n}\n\nfunction sanitizeMetadata(meta: ErrorMetadata | undefined): ErrorMetadata | undefined {\n if (meta === undefined) return undefined;\n const { raw, ...rest } = meta;\n const debugRaw = process.env.THEOKIT_DEBUG_RAW_ERRORS === \"1\";\n if (debugRaw && raw !== undefined) {\n const redactedRaw =\n typeof raw === \"string\" ? redactSecrets(raw) : redactSecrets(safeStringify(raw));\n return { ...rest, raw: redactedRaw } as ErrorMetadata;\n }\n return rest as ErrorMetadata;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Is this error transient (worth retrying)?\n *\n * Returns the SDK's own retryability verdict: every {@link TheokitAgentError}\n * subclass computes `isRetryable` at construction (rate-limit / network /\n * credential-pool-exhausted are retryable; auth / configuration / unsupported\n * are not), so this predicate is a single source of truth rather than a\n * re-derivation. Non-SDK errors return `false` conservatively — wrap a foreign\n * error in the appropriate SDK error first if you want it considered transient.\n * It never inspects `err.message`.\n *\n * @example\n * try {\n * await agent.send(message, { throwOnError: true });\n * } catch (err) {\n * if (isTransientError(err)) return retryWithBackoff();\n * throw err;\n * }\n *\n * @public\n */\nexport function isTransientError(err: unknown): boolean {\n return err instanceof TheokitAgentError && err.isRetryable === true;\n}\n\n/**\n * Thrown when a {@link Run} or agent operation is not available on the current\n * runtime. Check first with `run.supports(operation)`.\n *\n * Extends {@link TheokitAgentError} (so error-catching code that branches on\n * `instanceof TheokitAgentError` continues to work) but is never retryable —\n * an unsupported operation will not become supported on retry.\n *\n * @public\n */\nexport class UnsupportedRunOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedRunOperationError\";\n readonly operation: RunOperation;\n\n constructor(\n message: string,\n operation: RunOperation,\n options: { code?: string; cause?: unknown } = {},\n ) {\n super(message, {\n ...options,\n isRetryable: false,\n code: options.code ?? \"unsupported_run_operation\",\n });\n this.operation = operation;\n }\n}\n\n/**\n * Thrown when every credential in a per-provider pool is in cooldown\n * and no healthy key is available (ADR D133). The caller's\n * {@link import(\"./internal/llm/fallback-client.js\").FallbackLlmClient}\n * catches this and tries the next provider in the fallback chain.\n *\n * `metadata.nextRetryAt` (epoch ms) tells callers when the soonest\n * pool entry resumes — useful for manual retry scheduling.\n *\n * @public\n */\nexport class CredentialPoolExhaustedError extends TheokitAgentError {\n override readonly name: string = \"CredentialPoolExhaustedError\";\n readonly provider: string;\n readonly nextRetryAt: number | undefined;\n\n constructor(\n message: string,\n options: {\n provider: string;\n nextRetryAt?: number;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n ...options,\n isRetryable: true,\n code: options.code ?? \"credential_pool_exhausted\",\n });\n this.provider = options.provider;\n this.nextRetryAt = options.nextRetryAt;\n }\n}\n\n/**\n * Finite error codes specific to memory adapter operations (ADR D141).\n *\n * @public\n */\nexport type MemoryAdapterErrorCode =\n | \"auth_failed\"\n | \"rate_limited\"\n | \"not_found\"\n | \"network\"\n | \"invalid_input\"\n | \"unknown\";\n\n/**\n * Error raised by `@theokit-memory-*` adapters. Carries `adapterId`\n * so callers can branch on which provider failed (ADR D141).\n *\n * @public\n */\nexport class MemoryAdapterError extends TheokitAgentError {\n override readonly name: string = \"MemoryAdapterError\";\n readonly adapterId: string;\n\n constructor(\n message: string,\n options: {\n adapterId: string;\n code: MemoryAdapterErrorCode;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n isRetryable: options.code === \"rate_limited\" || options.code === \"network\",\n code: options.code,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n });\n this.adapterId = options.adapterId;\n }\n}\n\n/**\n * Thrown when a user-supplied task ID violates the grammar\n * `^[a-z0-9][a-z0-9_-]*$` (D368) OR starts with a reserved adapter\n * prefix (`wf-` / `b-` / `cron-`, EC-5).\n *\n * @public\n */\nexport class InvalidTaskIdError extends TheokitAgentError {\n override readonly name: string = \"InvalidTaskIdError\";\n readonly taskId: string;\n\n constructor(message: string, taskId: string, options: { cause?: unknown } = {}) {\n super(message, {\n ...options,\n isRetryable: false,\n code: \"invalid_task_id\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `Task.subscribe(id)` is called for a task that has been\n * evicted, never submitted, or evicted after retention (D373).\n *\n * @public\n */\nexport class TaskNotFoundError extends TheokitAgentError {\n override readonly name: string = \"TaskNotFoundError\";\n readonly taskId: string;\n\n constructor(taskId: string, options: { cause?: unknown } = {}) {\n super(`Task not found: ${taskId}`, {\n ...options,\n isRetryable: false,\n code: \"task_not_found\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `CloudAgent` is asked to wrap a task (D370). Cloud\n * task observability is deferred until Theo PaaS GA.\n *\n * @public\n */\nexport class UnsupportedTaskOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedTaskOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Task operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D370)`,\n {\n ...options,\n isRetryable: false,\n code: \"task_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n\n/**\n * Thrown by `Budget` enforcement (ADR D386) when a `mode: \"block\"`\n * budget would be exceeded by the upcoming LLM call. Caller pega\n * tipado para retry-after-window-reset or surface to the user.\n *\n * @public\n */\nexport class BudgetExceededError extends TheokitAgentError {\n override readonly name: string = \"BudgetExceededError\";\n readonly budgetName: string;\n readonly window: import(\"./types/budget.js\").BudgetWindow;\n readonly spentUsd: number;\n readonly limitUsd: number;\n readonly mode: import(\"./types/budget.js\").BudgetMode;\n\n constructor(args: {\n budgetName: string;\n window: import(\"./types/budget.js\").BudgetWindow;\n spentUsd: number;\n limitUsd: number;\n mode: import(\"./types/budget.js\").BudgetMode;\n cause?: unknown;\n }) {\n super(\n `Budget \"${args.budgetName}\" exceeded for window ${args.window}: spent $${args.spentUsd.toFixed(4)} > limit $${args.limitUsd.toFixed(4)}`,\n {\n ...(args.cause !== undefined ? { cause: args.cause } : {}),\n isRetryable: false,\n code: \"budget_exceeded\",\n },\n );\n this.budgetName = args.budgetName;\n this.window = args.window;\n this.spentUsd = args.spentUsd;\n this.limitUsd = args.limitUsd;\n this.mode = args.mode;\n }\n}\n\n/**\n * Thrown when `CloudAgent.send({ budget })` is invoked (D388). Cloud\n * budget surface waits for Theo PaaS GA.\n *\n * @public\n */\n/**\n * T1.6 — Thrown when a consumer calls `agent.send()` or any method\n * on an agent that has already been `dispose()`d. Pre-T1.6 this was\n * a generic `new Error(\"Agent has been disposed\")` — consumers\n * couldn't catch it without string-matching the message.\n *\n * @public\n */\nexport class AgentDisposedError extends TheokitAgentError {\n override readonly name: string = \"AgentDisposedError\";\n readonly agentId: string;\n\n constructor(agentId: string) {\n super(`Agent \"${agentId}\" has been disposed. Create a new agent or use Agent.resume().`, {\n isRetryable: false,\n code: \"agent_disposed\",\n });\n this.agentId = agentId;\n }\n}\n\nexport class UnsupportedBudgetOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedBudgetOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Budget operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D388)`,\n {\n ...options,\n isRetryable: false,\n code: \"budget_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n","/**\n * M6-3 — portable repo provisioner for the eval harness.\n *\n * Clones a repository and checks out a ref into an isolated working dir, issuing\n * every git command through {@link SandboxBackend.execute} (ADR D2 — same code\n * runs on Local/Docker/E2B; never a direct `child_process` import). Promotes\n * theocode's `prepareRepo` (`swebench-provision.ts:37`) onto the SDK's sandbox\n * abstraction.\n *\n * referencia: knowledge-base/references/theocode-eval/lib/swebench-provision.ts:37\n * (clone+checkout), :13 (ProvisionError with instanceId).\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"../errors.js\";\nimport { LocalSandbox } from \"./local-sandbox.js\";\nimport { shellEscapePosix } from \"./shell-escape.js\";\nimport type { SandboxBackend } from \"./types.js\";\n\n/**\n * Raised when cloning or checking out a repo fails. Carries the `instanceId`\n * so a batch run can attribute the failure to the offending dataset row.\n */\nexport class RepoProvisionError extends TheokitAgentError {\n override readonly name = \"RepoProvisionError\";\n\n constructor(\n readonly instanceId: string,\n message: string,\n options: { cause?: unknown } = {},\n ) {\n super(`[${instanceId}] ${message}`, {\n code: \"repo_provision_failed\",\n isRetryable: false,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n });\n }\n}\n\n/** Options for {@link provisionRepo}. */\nexport interface ProvisionRepoOptions {\n /**\n * Clonable repo URL or local path. SECURITY: when this comes from an\n * untrusted dataset, the value is passed to `git clone` after a `--`\n * end-of-options terminator (no flag injection) and with the `ext::`\n * transport disabled (no arbitrary-command transport).\n */\n readonly repoUrl: string;\n /** Branch, tag, or commit SHA to check out. Rejected if it begins with `-`. */\n readonly ref: string;\n /**\n * Unique id for this row — names the target dir and any error. Validated to\n * `[A-Za-z0-9._-]` (no path traversal) since it becomes a directory name.\n */\n readonly instanceId: string;\n}\n\n/**\n * Reject ids that would escape the workdir or be parsed as a git flag. Must\n * start with an alphanumeric (blocks `.`, `..`, `-foo`, leading-dot names) and\n * thereafter allow only `[A-Za-z0-9._-]`.\n */\nconst SAFE_INSTANCE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/**\n * Clone `repoUrl` into `<sandbox workdir>/<instanceId>` and check out `ref`.\n * Returns the absolute `repoDir` (resolved via `git rev-parse --show-toplevel`,\n * which is portable across backends). Throws {@link RepoProvisionError} naming\n * the `instanceId` when clone or checkout exits non-zero.\n *\n * The `sandbox` is optional (V3-5): when omitted, a default {@link LocalSandbox}\n * is used (clones into the process cwd's `<instanceId>`) — pass an explicit\n * sandbox (e.g. `LocalSandbox({ workDir })` / Docker / E2B) to control the workdir.\n */\nexport function provisionRepo(opts: ProvisionRepoOptions): Promise<{ repoDir: string }>;\nexport function provisionRepo(\n sandbox: SandboxBackend,\n opts: ProvisionRepoOptions,\n): Promise<{ repoDir: string }>;\nexport async function provisionRepo(\n sandboxOrOpts: SandboxBackend | ProvisionRepoOptions,\n maybeOpts?: ProvisionRepoOptions,\n): Promise<{ repoDir: string }> {\n const sandbox = maybeOpts !== undefined ? (sandboxOrOpts as SandboxBackend) : new LocalSandbox();\n const opts = maybeOpts ?? (sandboxOrOpts as ProvisionRepoOptions);\n const { repoUrl, ref, instanceId } = opts;\n\n // Validate untrusted-derivable inputs before they reach git/the shell.\n if (!SAFE_INSTANCE_ID.test(instanceId)) {\n throw new RepoProvisionError(\n instanceId,\n \"invalid instanceId: must match [A-Za-z0-9._-] (no path traversal)\",\n );\n }\n if (ref.startsWith(\"-\")) {\n throw new RepoProvisionError(instanceId, `invalid ref: must not begin with '-' (got ${ref})`);\n }\n\n // `--` terminates options (no `--upload-pack=` flag injection); `protocol.ext.allow=never`\n // blocks the `ext::` arbitrary-command transport. `file`/`https` stay allowed.\n const clone = await sandbox.execute(\n `git -c protocol.ext.allow=never clone --quiet -- ${shellEscapePosix(repoUrl)} ${shellEscapePosix(instanceId)}`,\n );\n if (clone.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `clone failed: ${clone.stderr.trim()}`);\n }\n\n const top = await sandbox.execute(\n `git -C ${shellEscapePosix(instanceId)} rev-parse --show-toplevel`,\n );\n if (top.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `resolve repoDir failed: ${top.stderr.trim()}`);\n }\n const repoDir = top.stdout.trim();\n\n // `ref` is validated above not to begin with `-`, so it cannot be parsed as a flag.\n const checkout = await sandbox.execute(\n `git -C ${shellEscapePosix(repoDir)} checkout --quiet ${shellEscapePosix(ref)}`,\n );\n if (checkout.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `checkout ${ref} failed: ${checkout.stderr.trim()}`);\n }\n\n return { repoDir };\n}\n"]}
|