@tangle-network/agent-app 0.60.227 → 0.60.228

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.
@@ -100,7 +100,7 @@ import {
100
100
  warmBinOf,
101
101
  warmWeekdayOf,
102
102
  writeProfileFilesToBox
103
- } from "../chunk-YS2RYZQG.js";
103
+ } from "../chunk-JILHXHJE.js";
104
104
  import {
105
105
  EGRESS_PROXY_RECOVERY_PHASE,
106
106
  EGRESS_PROXY_RECOVERY_REQUIRED,
@@ -0,0 +1,51 @@
1
+ import type { SandboxInstance, EgressPolicy } from '@tangle-network/sandbox';
2
+ export type SandboxExistingBoxStage = 'reused' | 'resumed';
3
+ export type SandboxEgressPolicySource = Awaited<ReturnType<SandboxInstance['egress']['get']>>['source'];
4
+ /**
5
+ * Thrown when an existing sandbox cannot be proven to have the requested
6
+ * outbound network policy. The sandbox is preserved and its policy is not
7
+ * changed. The caller explicitly decides whether to preserve, migrate, or
8
+ * replace the sandbox.
9
+ */
10
+ export declare class SandboxEgressPolicyMismatchError extends Error {
11
+ readonly stage: SandboxExistingBoxStage;
12
+ readonly boxName: string;
13
+ readonly currentPolicy: EgressPolicy;
14
+ readonly currentSource: SandboxEgressPolicySource;
15
+ readonly desiredPolicy: EgressPolicy;
16
+ constructor(stage: SandboxExistingBoxStage, boxName: string, currentPolicy: EgressPolicy, currentSource: SandboxEgressPolicySource, desiredPolicy: EgressPolicy);
17
+ }
18
+ /** Represent an error thrown when sandbox runtime authentication refresh fails for a specific stage and name */
19
+ export declare class SandboxRuntimeAuthRefreshError extends Error {
20
+ constructor(stage: SandboxExistingBoxStage, name: string, detail: string, cause?: unknown);
21
+ }
22
+ /** Which step of the state-preserving stop→resume recovery failed. `stop` with a
23
+ * driver-unsupported cause means the platform cannot restart this box (the
24
+ * `tangle` driver exposes create/delete only); `probe` means the box restarted
25
+ * but is still unresponsive. */
26
+ export type SandboxRecoveryPhase = 'stop' | 'resume' | 'probe';
27
+ /**
28
+ * Thrown when an unresponsive box could not be recovered by a state-preserving
29
+ * restart. Contract: this error is only ever thrown with the workspace intact —
30
+ * recovery never deletes. The caller decides what to do next (retry, surface to
31
+ * the user, or explicitly replace via `forceNew`).
32
+ */
33
+ export declare class SandboxRecoveryFailedError extends Error {
34
+ readonly boxKey: string;
35
+ readonly stage: SandboxExistingBoxStage;
36
+ readonly phase: SandboxRecoveryPhase;
37
+ constructor(stage: SandboxExistingBoxStage, boxKey: string, phase: SandboxRecoveryPhase, detail: string, cause?: unknown);
38
+ }
39
+ /**
40
+ * Thrown instead of restarting a box that failed the reuse gate because it is
41
+ * not connectable (runtime URL missing or edge readiness failed) while its
42
+ * runtime reports running sessions. A restart would end those sessions, so the
43
+ * box is left running and only the request that asked for it fails. The box is
44
+ * not replaced either; retry once its sessions finish.
45
+ */
46
+ export declare class SandboxBoxBusyError extends Error {
47
+ readonly boxKey: string;
48
+ readonly stage: SandboxExistingBoxStage;
49
+ readonly runningSessions: number;
50
+ constructor(stage: SandboxExistingBoxStage, boxKey: string, runningSessions: number, detail: string);
51
+ }
@@ -0,0 +1,55 @@
1
+ /** Appended to a prompt-budget throw from any of this module's three choke
2
+ * points. A product that already raised the cap at compose time
3
+ * (`composeAgentProfile(base, channels, overlay, { maxSystemPromptBytes })` —
4
+ * gtm-agent uses 50_000) has to declare the SAME decision on the shell, or the
5
+ * shell's default reads as a contradiction instead of a missing declaration. */
6
+ export declare const SHELL_PROMPT_BUDGET_HINT: string;
7
+ /** Gate on the provision body: the platform orchestrator caps the create
8
+ * payload at 256 KiB; 240 KB leaves headroom for transport framing. An
9
+ * over-cap payload fails provisioning 100% of the time (a 282 KB payload
10
+ * shipped once and no sandbox could ever be created). */
11
+ export declare const PROVISION_PAYLOAD_MAX_BYTES = 240000;
12
+ /** Per-variable env gate: the kernel rejects any single `NAME=value` env entry
13
+ * over MAX_ARG_STRLEN (131072 bytes) with E2BIG, killing every exec inside
14
+ * the box. 120 KB leaves headroom for the name and framing. */
15
+ export declare const ENV_VALUE_MAX_BYTES = 120000;
16
+ /** Default wait for a box to reach `running`. Overridable per shell via
17
+ * {@link SandboxRuntimeConfig.provisionTimeoutMs}. */
18
+ export declare const DEFAULT_PROVISION_TIMEOUT_MS = 120000;
19
+ /** Total env gate: the whole environment block shares the payload budget with
20
+ * the profile; past 200 KB the provision body cannot stay under the cap. */
21
+ export declare const ENV_TOTAL_MAX_BYTES = 200000;
22
+ /** Structural slice of the profile the payload gate reads: it only measures
23
+ * the profile's serialized size and names `resources.files` in the breakdown,
24
+ * so callers composing a payload outside the SDK (products, tests) can pass a
25
+ * plain object without casting through `AgentProfile`. */
26
+ export interface ProvisionProfileSection {
27
+ resources?: {
28
+ files?: readonly unknown[];
29
+ };
30
+ }
31
+ /** The provision-payload sections the size gates need to see. Structural so
32
+ * the gate is testable without the SDK's (unexported) create-payload type. */
33
+ export interface ProvisionPayloadSections {
34
+ env?: Record<string, string>;
35
+ secrets?: readonly string[] | 'all';
36
+ /** `profile` may also be a named-profile string ref (the SDK's
37
+ * `BackendConfig` union) — a string ref is tiny and has no files channel. */
38
+ backend?: {
39
+ profile?: string | ProvisionProfileSection;
40
+ };
41
+ }
42
+ /**
43
+ * Throw when the serialized provision payload exceeds
44
+ * {@link PROVISION_PAYLOAD_MAX_BYTES}. The error carries a per-section byte
45
+ * breakdown (profile/files/env/secrets) so the offending channel is named, not
46
+ * guessed.
47
+ */
48
+ export declare function assertProvisionPayloadWithinCap(payload: ProvisionPayloadSections): void;
49
+ /**
50
+ * Throw when any single env value exceeds {@link ENV_VALUE_MAX_BYTES} or the
51
+ * whole env block exceeds {@link ENV_TOTAL_MAX_BYTES}, naming the offending
52
+ * variable. This is the E2BIG incident class: the box may even provision, but
53
+ * every exec inside it dies on the oversized entry.
54
+ */
55
+ export declare function assertEnvWithinLimits(env: Record<string, string>): void;
@@ -0,0 +1,4 @@
1
+ import type { EgressPolicy } from '@tangle-network/sandbox';
2
+ /** Hosts required when a product installs its pinned Python tooling at boot. */
3
+ export declare const PYPI_EGRESS_DOMAINS: readonly ['pypi.org', 'files.pythonhosted.org', 'pypi.python.org'];
4
+ export declare function buildProductEgressPolicy(publicOrigin: string | URL, extraDomains?: readonly string[]): EgressPolicy;
@@ -0,0 +1,16 @@
1
+ import type { AgentProfileFileMount } from '@tangle-network/agent-interface';
2
+ import type { SandboxRuntimeConfig } from './configuration';
3
+ import { Sandbox } from '@tangle-network/sandbox/core';
4
+ import type { SandboxInstance } from '@tangle-network/sandbox';
5
+ import type { SandboxExistingBoxStage } from './lifecycle-errors';
6
+ import type { Harness } from '../harness/index';
7
+ import { type Outcome } from './outcome';
8
+ export declare function deferredProfileWriteFailed(stage: 'new' | 'reused' | 'resumed', name: string, cause: Error): Error;
9
+ export declare const DEFERRED_CORPUS_HASH_KEY = "agentAppDeferredCorpusHash";
10
+ /** Stable content hash of the deferred file corpus (path + inline content).
11
+ * Unchanged corpus ⇒ same hash; a new/edited/removed skill ⇒ different hash.
12
+ * Exported for the reuse-skip test. */
13
+ export declare function deferredCorpusHash(files: AgentProfileFileMount[]): string;
14
+ export declare function materializeDeferredFilesForExistingBox(shell: SandboxRuntimeConfig, client: Sandbox, box: SandboxInstance, stage: SandboxExistingBoxStage, name: string, workspaceId: string, userId: string | undefined, harness: Harness, corpusMarker?: Promise<string | null>): Promise<Outcome<SandboxInstance>>;
15
+ /** The corpus hash a box last recorded, or null when it is absent or unreadable. */
16
+ export declare function readDeferredCorpusMarker(box: SandboxInstance): Promise<string | null>;
@@ -0,0 +1,16 @@
1
+ import type { AgentProfile, AgentProfileFileMount } from '@tangle-network/agent-interface';
2
+ import type { SandboxInstance } from '@tangle-network/sandbox';
3
+ import { type Outcome } from './outcome';
4
+ /** Split profile files into inline deferred files and a lean profile without them */
5
+ export declare function splitDeferredProfileFiles(profile: AgentProfile): {
6
+ leanProfile: AgentProfile;
7
+ deferredFiles: AgentProfileFileMount[];
8
+ };
9
+ /** Define options to control execution timeout, pacing, and retry behavior when writing profile files */
10
+ export interface WriteProfileFilesOptions {
11
+ execTimeoutMs?: number;
12
+ paceMs?: number;
13
+ maxRetries?: number;
14
+ }
15
+ /** Write profile files to a sandbox with pacing, retries, and optional execution timeout handling */
16
+ export declare function writeProfileFilesToBox(box: SandboxInstance, files: AgentProfileFileMount[], options?: WriteProfileFilesOptions): Promise<Outcome<void>>;
@@ -0,0 +1,14 @@
1
+ import type { SandboxSpendHooks, SandboxRuntimeConfig } from './configuration';
2
+ import type { SandboxInstance } from '@tangle-network/sandbox';
3
+ import { type PromptInputPart } from './prompt-profile';
4
+ import type { StreamSandboxPromptOptions } from './prompt-options';
5
+ /** Fire an activity tap without letting it affect the turn it reports on. */
6
+ export declare function emitSandboxActivity(spend: SandboxSpendHooks | undefined, box: SandboxInstance): void;
7
+ /**
8
+ * How long a refused dispatch is resent. Shorter than the completion
9
+ * Workflow's 10-minute wait for a dispatch to appear, so the request gives up
10
+ * before that Workflow reports the dispatch missing.
11
+ */
12
+ export declare const SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS: number;
13
+ /** Resolve and stream AI-generated responses from a sandboxed environment based on input messages and options */
14
+ export declare function streamSandboxPrompt(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options?: StreamSandboxPromptOptions): AsyncGenerator<unknown>;
@@ -0,0 +1,71 @@
1
+ import type { SandboxInstance } from '@tangle-network/sandbox';
2
+ import type { PromptInputPart } from './prompt-profile';
3
+ import type { StreamSandboxPromptOptions } from './prompt-options';
4
+ export type StreamPromptOptions = Parameters<SandboxInstance['streamPrompt']>[1];
5
+ /**
6
+ * Open the durable event lane for one detached prompt.
7
+ *
8
+ * `dispatchPrompt` is the admission boundary: it returns after the sandbox has
9
+ * accepted the run and keeps executing it after this Worker disappears. The
10
+ * SDK's execution replay stream is then the exact execution-scoped surface.
11
+ * Replaying through `streamPrompt` preserves the direct run-event vocabulary;
12
+ * the session bus wraps message parts under `data.properties`.
13
+ */
14
+ export declare function detachedSandboxPromptEvents(box: SandboxInstance, prompt: string | PromptInputPart[], options: StreamSandboxPromptOptions, backend: NonNullable<StreamPromptOptions>['backend']): AsyncGenerator<unknown>;
15
+ /**
16
+ * The small event shape consumed by agent-gateway's streaming adapters.
17
+ *
18
+ * Sandbox providers can add fields to their event payloads over time. This
19
+ * adapter deliberately copies only the fields the gateway understands so
20
+ * consumers do not each have to maintain a provider-to-gateway cast.
21
+ */
22
+ export interface SandboxStreamEvent {
23
+ type?: string;
24
+ data?: {
25
+ part?: {
26
+ type?: string;
27
+ text?: string;
28
+ };
29
+ delta?: string;
30
+ finalText?: string;
31
+ code?: string;
32
+ message?: string;
33
+ details?: Record<string, unknown>;
34
+ inputRequired?: {
35
+ prompt?: string;
36
+ };
37
+ usage?: {
38
+ inputTokens?: number;
39
+ outputTokens?: number;
40
+ reasoningTokens?: number;
41
+ toolTokens?: number;
42
+ toolCallCount?: number;
43
+ providerCostUsd?: number;
44
+ budgetEnforced?: boolean;
45
+ };
46
+ tool?: {
47
+ name?: string;
48
+ inputTokens?: number;
49
+ outputTokens?: number;
50
+ };
51
+ reasoning?: {
52
+ tokens?: number;
53
+ };
54
+ };
55
+ }
56
+ /** Normalize raw sandbox events for shared agent-gateway consumers. */
57
+ export declare function adaptSandboxStream(events: AsyncIterable<unknown>): AsyncGenerator<SandboxStreamEvent>;
58
+ /** Define transitions marking the start or finish of a sandbox step with associated details */
59
+ export type SandboxStepTransition = {
60
+ kind: 'step-start';
61
+ } | {
62
+ kind: 'step-finish';
63
+ reason: string;
64
+ severed: boolean;
65
+ };
66
+ /** Resolve the severed stream event to a corresponding sandbox step transition or null */
67
+ export declare function classifySeveredStream(event: unknown): SandboxStepTransition | null;
68
+ /** Determine if an event is a terminal prompt event with type 'result' or 'done */
69
+ export declare function isTerminalPromptEvent(event: unknown): boolean;
70
+ /** Resolve the interactive question text from a structured event or return null if none found */
71
+ export declare function detectInteractiveQuestion(event: unknown): string | null;
@@ -0,0 +1,79 @@
1
+ import type { AgentProfile, ReasoningEffort, AgentProfileMcpServer } from '@tangle-network/agent-interface';
2
+ import type { Harness } from '../harness/index';
3
+ import type { ProfileFingerprint } from '../profile/fingerprint';
4
+ import type { SandboxSpendHooks } from './configuration';
5
+ import type { TurnTrace, TurnSpan } from '../turn-trace/recorder';
6
+ /** Define options for configuring and controlling a streaming sandbox prompt session */
7
+ export interface StreamSandboxPromptOptions {
8
+ /** Complete server-owned profile for this turn. Skips the shell's default composer.
9
+ * Credentials, admission, session identity, and interactions remain execution options.
10
+ * Explicit turn selections override this profile; otherwise its model and harness win
11
+ * over shell defaults. Never populate this field from an untrusted request body. */
12
+ profile?: AgentProfile;
13
+ sessionId?: string;
14
+ executionId?: string;
15
+ /** Stable idempotency key for one logical dispatch. Reuse it with the same
16
+ * `sessionId` when a caller may retry the initial request. */
17
+ turnId?: string;
18
+ lastEventId?: string;
19
+ systemPrompt?: string;
20
+ model?: string;
21
+ modelApiKey?: string;
22
+ history?: Array<{
23
+ role: 'user' | 'assistant';
24
+ content: string;
25
+ }>;
26
+ harness?: Harness;
27
+ effort?: 'auto' | ReasoningEffort;
28
+ /** Provider-enforced visible answer ceiling for this turn. */
29
+ maxOutputTokens?: number;
30
+ /** Provider-enforced hidden reasoning ceiling for this turn. */
31
+ maxReasoningTokens?: number;
32
+ /** Provider-enforced combined answer and reasoning ceiling for this turn. */
33
+ maxTotalOutputTokens?: number;
34
+ appToolMcp?: Record<string, AgentProfileMcpServer>;
35
+ baseProfileMcp?: Record<string, AgentProfileMcpServer>;
36
+ extraMcp?: Record<string, AgentProfileMcpServer>;
37
+ /** Runtime-owned MCP tools for this turn, outside the authored profile. */
38
+ runtimeAttachments?: {
39
+ mcp: Record<string, AgentProfileMcpServer>;
40
+ };
41
+ /** Per-turn secret values used by runtime attachments; never stored in the profile or sandbox environment. */
42
+ runtimeSecrets?: Record<string, string>;
43
+ /** Mark a backend prepared for a secret-isolated native session. The caller creates
44
+ * that session and prepares its exact backend before dispatch. */
45
+ secretProfileIsolation?: true;
46
+ /** SDK-issued digest of the prepared public backend request. */
47
+ expectedPublicProfileRequestDigest?: `sha256:${string}`;
48
+ /** SDK-issued receipt for the prepared secret native profile revision. */
49
+ expectedSecretProfileReceipt?: `hmac-sha256:${string}`;
50
+ signal?: AbortSignal;
51
+ timeoutMs?: number;
52
+ /**
53
+ * Execution time limit for this run, in milliseconds. Unset, the runtime
54
+ * falls back to `timeoutMs`, then to its one-hour default, so a turn that
55
+ * must run longer than an hour names it here. The runtime refuses a value
56
+ * above its deployment maximum before the run starts. `timeoutMs` stays the
57
+ * shorter first-output budget.
58
+ */
59
+ ttlMs?: number;
60
+ requireVisibleAssistantOutput?: boolean;
61
+ disallowQuestions?: boolean;
62
+ interactions?: {
63
+ question?: boolean;
64
+ permission?: boolean;
65
+ plan?: boolean;
66
+ };
67
+ detach?: boolean;
68
+ onProfileResolved?: (fingerprint: ProfileFingerprint) => void;
69
+ spend?: SandboxSpendHooks;
70
+ /**
71
+ * The turn's trace (`@tangle-network/agent-app/turn-trace`). Its id is sent as `traceId`, the
72
+ * `x-tangle-trace-id` the Sandbox API, orchestrator, sidecar and the Router's dispatch rows all record, and
73
+ * the stream is recorded as a `sandbox.prompt` span: the sidecar's first-text phases, the generation and
74
+ * each tool the box agent ran. Omitted, the SDK mints a trace id the app does not keep.
75
+ */
76
+ trace?: TurnTrace;
77
+ /** The span the prompt hangs from. Default: the trace's root. */
78
+ traceParent?: TurnSpan;
79
+ }
@@ -0,0 +1,61 @@
1
+ import type { SandboxInstance } from '@tangle-network/sandbox';
2
+ import { type AgentProfileMcpServer, type AgentProfile, type ReasoningEffort } from '@tangle-network/agent-interface';
3
+ import { type Harness } from '../harness/index';
4
+ import type { SandboxRuntimeConfig } from './configuration';
5
+ import type { StreamSandboxPromptOptions } from './prompt-options';
6
+ /** Extract a single element type from the array parameter of SandboxInstance's streamPrompt method */
7
+ export type PromptInputPart = Extract<Parameters<SandboxInstance['streamPrompt']>[0], readonly unknown[]>[number];
8
+ /** Build a single string combining conversation history and the current user message */
9
+ export declare function flattenHistory(message: string, history?: Array<{
10
+ role: 'user' | 'assistant';
11
+ content: string;
12
+ }>): string;
13
+ /**
14
+ * History-aware equivalent of flattenHistory for multimodal prompt parts: the
15
+ * transcript is folded into the first text part (image/file parts carry no
16
+ * text to prepend to) rather than replacing the message wholesale.
17
+ */
18
+ export declare function mergeHistoryIntoParts(parts: PromptInputPart[], history?: Array<{
19
+ role: 'user' | 'assistant';
20
+ content: string;
21
+ }>): PromptInputPart[];
22
+ /** Resolve conflicts and merge extra MCP profiles into the app tool MCP without overwriting existing keys */
23
+ export declare function mergeExtraMcp(appToolMcp: Record<string, AgentProfileMcpServer>, baseProfileMcp: Record<string, AgentProfileMcpServer>, extra: Record<string, AgentProfileMcpServer> | undefined): Record<string, AgentProfileMcpServer>;
24
+ /** Attach explicit effort through the portable model contract consumed by providers. */
25
+ export declare function attachReasoningEffort(profile: AgentProfile, _harness: Harness, effort: 'auto' | ReasoningEffort | undefined): AgentProfile;
26
+ export interface SandboxPromptTokenLimits {
27
+ maxVisibleOutputTokens?: number;
28
+ maxReasoningTokens?: number;
29
+ maxTotalOutputTokens?: number;
30
+ }
31
+ /** Tighten the profile's provider-enforced token ceilings for one prompt. */
32
+ export declare function applyPromptTokenLimits(profile: AgentProfile, limits: SandboxPromptTokenLimits): AgentProfile;
33
+ /** Configuration needed to prepare a turn without provisioning a workspace. */
34
+ export type SandboxPromptConfig = Pick<SandboxRuntimeConfig, 'provider' | 'deferProfileFiles' | 'promptBudget'> & Partial<Pick<SandboxRuntimeConfig, 'profile'>>;
35
+ /** Prepare one effective backend for SDK dispatch or product-specific transport.
36
+ * Supply a server-owned profile, or a shell composer for the default profile.
37
+ * Reuse the returned backend for preflight and dispatch so they inspect identical configuration.
38
+ */
39
+ export declare function resolveSandboxPromptBackend(shell: SandboxPromptConfig, options: StreamSandboxPromptOptions, operation?: string): Promise<{
40
+ model?: {
41
+ model: string;
42
+ provider: string;
43
+ apiKey?: string;
44
+ apiKeyEnv?: string;
45
+ baseUrl?: string;
46
+ } | undefined;
47
+ type: Harness;
48
+ profile: AgentProfile;
49
+ runtimeAttachments?: {
50
+ mcp: Record<string, AgentProfileMcpServer>;
51
+ } | undefined;
52
+ runtimeSecrets?: Record<string, string> | undefined;
53
+ metadata?: {
54
+ profileSecretIsolation: true;
55
+ } | undefined;
56
+ interactions?: {
57
+ question?: boolean;
58
+ permission?: boolean;
59
+ plan?: boolean;
60
+ } | undefined;
61
+ }>;
@@ -0,0 +1,57 @@
1
+ import { type PromptInputPart } from './prompt-profile';
2
+ import type { StreamSandboxPromptOptions } from './prompt-options';
3
+ import type { SandboxRuntimeConfig } from './configuration';
4
+ import type { SandboxInstance, TurnDriveResult } from '@tangle-network/sandbox';
5
+ import { type Outcome } from './outcome';
6
+ /**
7
+ * Aggregate a sandbox prompt event stream down to the turn's one final answer.
8
+ *
9
+ * Exported SEPARATELY from `runSandboxPrompt` because the aggregation is pure —
10
+ * `AsyncIterable<event> -> string` — while the streaming half is not: a product
11
+ * that mounts per-turn MCP servers or resolves its harness per workspace wraps
12
+ * `streamSandboxPrompt` in its own generator. Binding this logic to one stream
13
+ * function is exactly what pushed three products into forking the whole thing,
14
+ * bug and all. Take this over a local copy no matter whose generator you drive.
15
+ *
16
+ * Two rules earn their keep, and both were learned from the naive version:
17
+ *
18
+ * - Text accumulates PER PART ID, never into one running buffer, so two
19
+ * concurrent text parts cannot overwrite each other.
20
+ * - A prompt echo is identified by CONTENT, never by arrival position. The
21
+ * "skip whichever text part arrives first" shortcut is wrong on both sandbox
22
+ * lanes: on the delta lane (`box.streamPrompt`, explicit deltas) the first
23
+ * part is the answer's opening token, so the answer silently loses it; and
24
+ * when the echo arrives AFTER the answer, the function returns the caller's
25
+ * own prompt as the agent's reply. Both failures produce a plausible-looking
26
+ * string, the worst shape for the unattended cron/judge turns this exists for.
27
+ *
28
+ * A blank-but-present `result.finalText` is ignored in favour of the streamed
29
+ * text rather than overwriting a real answer with whitespace.
30
+ *
31
+ * @param events raw sandbox turn events, in order
32
+ * @param message the prompt as handed to the stream, so an echo of it is dropped
33
+ * @param history folded into the dispatched prompt by `streamSandboxPrompt`;
34
+ * pass whatever was passed there, since the echo replays the FOLDED text
35
+ */
36
+ export declare function collectSandboxPromptText(events: AsyncIterable<unknown>, message: string | PromptInputPart[], history?: StreamSandboxPromptOptions['history']): Promise<string>;
37
+ /**
38
+ * Resolve a sandbox prompt by streaming it and aggregating the turn down to one
39
+ * final string. The shell's profile / model / MCP resolution and severed-stream
40
+ * fail-loud come from `streamSandboxPrompt`; the aggregation is
41
+ * `collectSandboxPromptText`, which products driving their own generator should
42
+ * import directly.
43
+ */
44
+ export declare function runSandboxPrompt(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options?: StreamSandboxPromptOptions): Promise<string>;
45
+ /** Define options to manage deterministic session resumption and turn idempotency in sandboxed drive turns */
46
+ export interface DriveSandboxTurnOptions extends StreamSandboxPromptOptions {
47
+ /** Deterministic resume key — required. Every tick for the same logical turn
48
+ * MUST reuse it so a crash + re-drive finds the in-flight session instead of
49
+ * starting a second agent run. */
50
+ sessionId: string;
51
+ /** Wall-clock cap in ms from the session's start. A still-running session past
52
+ * the cap is cancelled and reported `failed` — bounds an unattended run, such as
53
+ * a turn stalled on an interactive question with no consumer. Omit for no cap. */
54
+ wallCapMs?: number;
55
+ }
56
+ /** Resolve a sandbox turn by processing a message with given configuration and options */
57
+ export declare function driveSandboxTurn(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options: DriveSandboxTurnOptions): Promise<Outcome<TurnDriveResult>>;
@@ -0,0 +1,43 @@
1
+ import { Sandbox } from '@tangle-network/sandbox/core';
2
+ import { type ReuseChecks } from './reuse-state';
3
+ import type { SandboxInstance } from '@tangle-network/sandbox';
4
+ import type { SandboxClientCredentials } from './credentials';
5
+ import type { SandboxRuntimeConfig, EnsureWorkspaceSandboxOptions } from './configuration';
6
+ /**
7
+ * How long a reuse trusts what it last checked on a running box instead of
8
+ * repeating the round trip: the exec probe, the egress read, the runtime
9
+ * environment push, and the spend gate. Every check belongs to one identity of
10
+ * the box (its start time and filesystem incarnation, whichever the platform
11
+ * reports), a box that is not running when read keeps none, and a failed first
12
+ * call on the box drops them all ({@link dropTrustedBox}).
13
+ */
14
+ export declare const TRUSTED_REUSE_TTL_MS: number;
15
+ /** The running box last used under a box name, so a reuse reads it by id instead of listing every running box. A wrong id costs one read: the box read must carry the name. */
16
+ export declare const runningBoxIds: Map<string, string>;
17
+ /** Boxes an ensure handed out without an exec probe, because a recent probe of this start had passed. */
18
+ export declare const trustedBoxes: WeakSet<SandboxInstance>;
19
+ /** The checks recorded for this identity of the box. A box with another identity keeps none. */
20
+ export declare function checksFor(box: SandboxInstance): ReuseChecks | undefined;
21
+ export declare function recordCheck(box: SandboxInstance, patch: Omit<Partial<ReuseChecks>, 'identity'>): void;
22
+ export declare function forgetBox(boxId: string): void;
23
+ export declare function isRecent(at: number | undefined, ttlMs: number, now?: number): at is number;
24
+ /**
25
+ * Forget what this isolate trusts about a box after the first real call on it
26
+ * failed. Returns true when the ensure handed the box out without probing it, so
27
+ * the caller may ensure once more and get the full verification; false when the
28
+ * ensure had probed it and the failure is the box's own.
29
+ */
30
+ export declare function dropTrustedBox(box: SandboxInstance): boolean;
31
+ export declare function getClientFromCreds(creds: SandboxClientCredentials): Sandbox;
32
+ /** Resolve a synchronous sandbox client from provided runtime configuration credentials */
33
+ export declare function getClient(shell: SandboxRuntimeConfig): Sandbox;
34
+ /** Reset the process-local sandbox client and liveness-verification caches. */
35
+ export declare function resetClientCache(): void;
36
+ /** Remember the running box serving a box name, so the next reuse reads it by id. */
37
+ export declare function rememberRunningBox(name: string, box: SandboxInstance): SandboxInstance;
38
+ /** Whether this isolate probed the workspace's last-used box recently enough that a reuse would skip the probe. */
39
+ export declare function hasRecentProbe(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): boolean;
40
+ /** Load what another isolate recorded about this workspace's box, unless this isolate already knows it. */
41
+ export declare function hydrateReuseState(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): Promise<void>;
42
+ /** Share what this ensure learned about the box, unless the store already holds it. */
43
+ export declare function persistReuseState(shell: SandboxRuntimeConfig, box: SandboxInstance): Promise<void>;
@@ -0,0 +1,9 @@
1
+ import type { SandboxInstance } from '@tangle-network/sandbox';
2
+ import { Sandbox } from '@tangle-network/sandbox/core';
3
+ import { type SandboxExistingBoxStage } from './lifecycle-errors';
4
+ import { type Outcome } from './outcome';
5
+ import type { AgentProfileFileMount } from '@tangle-network/agent-interface';
6
+ export declare function sandboxRuntimeUrl(box: SandboxInstance): string | undefined;
7
+ export declare function sandboxEdgeFailed(box: SandboxInstance): boolean;
8
+ export declare function refreshRuntimeConnection(client: Sandbox, box: SandboxInstance): Promise<SandboxInstance>;
9
+ export declare function writeDeferredFilesWithRuntimeAuthRefresh(client: Sandbox, box: SandboxInstance, files: AgentProfileFileMount[], stage: SandboxExistingBoxStage, name: string): Promise<Outcome<SandboxInstance>>;
@@ -0,0 +1,2 @@
1
+ export declare function shellSingleQuote(value: string): string;
2
+ export declare function shellPath(path: string): string;
@@ -0,0 +1,76 @@
1
+ import { Sandbox } from '@tangle-network/sandbox/core';
2
+ import { type Outcome } from './outcome';
3
+ import type { SandboxInstance } from '@tangle-network/sandbox';
4
+ import type { SandboxRuntimeConfig, SandboxScope } from './configuration';
5
+ export declare function listRunning(client: Sandbox, name: string): Promise<Outcome<SandboxInstance | null>>;
6
+ /**
7
+ * The running box this isolate last used under `name`, read by id. Null when it
8
+ * is gone, stopped, renamed, or answers without the metadata a reuse decides on;
9
+ * the caller then lists, which is the authority.
10
+ */
11
+ export declare function getRunningBox(client: Sandbox, id: string, name: string): Promise<SandboxInstance | null>;
12
+ export declare function listStopped(client: Sandbox, name: string): Promise<Outcome<SandboxInstance | null>>;
13
+ export declare function deleteBox(box: SandboxInstance): Promise<Outcome<void>>;
14
+ /** Scope + the client and box key every workspace-scoped sandbox call needs.
15
+ * One place resolves credentials and derives the box name, so the ensure and
16
+ * peek paths cannot drift on which key a workspace's box lives under. */
17
+ export declare function resolveWorkspaceSandboxClient(shell: SandboxRuntimeConfig, workspaceId: string, userId: string | undefined): Promise<{
18
+ scope: SandboxScope;
19
+ client: Sandbox;
20
+ name: string;
21
+ }>;
22
+ /** What a peek can find. `warming` means the control plane is running while
23
+ * the filesystem incarnation is still transitioning. `not-running` carries
24
+ * the platform's own state string (`stopped`, `starting`, `failed`, …) —
25
+ * narrowing it to a union here would drop states the platform adds later,
26
+ * and every caller wants it for a log. */
27
+ export type PeekWorkspaceSandboxOutcome = {
28
+ status: 'running';
29
+ box: SandboxInstance;
30
+ } | {
31
+ status: 'warming';
32
+ readiness: 'transitioning';
33
+ box: SandboxInstance;
34
+ } | {
35
+ status: 'not-running';
36
+ state: string;
37
+ box: SandboxInstance;
38
+ } | {
39
+ status: 'absent';
40
+ };
41
+ /**
42
+ * Read-only twin of {@link ensureWorkspaceSandbox}: report whether a
43
+ * workspace's box exists and is fully ready, WITHOUT provisioning, resuming,
44
+ * or bootstrapping anything.
45
+ *
46
+ * This is what a read-mostly path needs — a file-index route's `authorize`
47
+ * seam, a stale-lock reconciliation, a status badge. Calling `ensure` from one
48
+ * of those spins a box up as a side effect of a read (legal-agent #509), and
49
+ * costs the caller a cold start it never asked for.
50
+ *
51
+ * Matching is on BOTH the box key and the display name, IN THAT ORDER.
52
+ * `client.get(id)` is a direct read by the platform's opaque sandbox id, not by
53
+ * the deterministic key a product derives from a workspace, so a lookup that
54
+ * has not seen the box before has to list and match (`ensureWorkspaceSandbox`
55
+ * reads a box it has seen by id).
56
+ * Provisioning here always stamps `name` with the box key, so the key is the
57
+ * authoritative match; the display-name pass exists only to adopt boxes on a
58
+ * host that predates that convention. The order matters: a single unordered
59
+ * `find` returns whichever the platform happens to list first, so a stopped
60
+ * display-name box could shadow a running box-key one and report
61
+ * `not-running` for a live workspace.
62
+ *
63
+ * Unlike `ensure`, this lists ALL statuses in one call: distinguishing "no box"
64
+ * from "box is stopped" is the whole point, and a status-filtered list cannot.
65
+ *
66
+ * A `client.list()` rejection propagates RAW, unlike the `Outcome`-wrapping
67
+ * helpers `ensure` uses internally. That is deliberate: there is no honest
68
+ * outcome to map a listing failure onto — it is not `absent` and not
69
+ * `not-running`, and inventing one would have callers act on a status the
70
+ * platform never reported. Callers that must tolerate it say so explicitly
71
+ * (the stale-turn-lock policy documents "a throw is treated as unreachable").
72
+ */
73
+ export declare function peekWorkspaceSandbox(shell: SandboxRuntimeConfig, options: {
74
+ workspaceId: string;
75
+ userId?: string;
76
+ }): Promise<PeekWorkspaceSandboxOutcome>;
@@ -0,0 +1,13 @@
1
+ import { type SandboxRuntimeConfig, type EnsureWorkspaceSandboxOptions } from './configuration';
2
+ import type { SandboxInstance } from '@tangle-network/sandbox';
3
+ /** Reuse a workspace sandbox, or remove its previous runtime before provisioning a replacement. */
4
+ export declare function ensureWorkspaceSandbox(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): Promise<SandboxInstance>;
5
+ /**
6
+ * Reuse the workspace's running box if this isolate used it recently, or return
7
+ * undefined. It never creates, resumes, restarts, replaces or deletes a box, so
8
+ * a caller can run it without the provisioning lease that serializes those
9
+ * steps (see `runForegroundSandboxSingleFlight`'s `reuse`); undefined means the
10
+ * box needs one of them (or this isolate has no recent probe of it), and the
11
+ * caller takes the lease and calls {@link ensureWorkspaceSandbox}.
12
+ */
13
+ export declare function reuseWorkspaceSandbox(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): Promise<SandboxInstance | undefined>;
@@ -0,0 +1,9 @@
1
+ import { type SandboxRuntimeConfig, type EnsureWorkspaceSandboxOptions } from './configuration';
2
+ import type { SandboxInstance } from '@tangle-network/sandbox';
3
+ /**
4
+ * `reuseOnly` stops before any step that creates, resumes, restarts, replaces or
5
+ * deletes a box and returns undefined there; every other step is a read or the
6
+ * idempotent renewal a reuse always made. `gate` is the spend gate: it runs
7
+ * before the first such step, and before a reuse whose probe was not trusted.
8
+ */
9
+ export declare function provisionWorkspaceSandbox(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions, gate: () => Promise<void>, reuseOnly: boolean): Promise<SandboxInstance | undefined>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.60.227",
3
+ "version": "0.60.228",
4
4
  "packageManager": "pnpm@11.24.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [