@tangle-network/sandbox 0.49.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -353,6 +353,36 @@ An absent value means the cell published no estimate, not that the wait is short
353
353
  `TimeoutError.timeoutMs` is the budget you set, not how long the call ran.
354
354
  Read `TimeoutError.elapsedMs` for the duration: `create()` ends before its budget when a server-supplied `Retry-After` outlasts the remainder, because no attempt can follow that sleep.
355
355
 
356
+ ## One sandbox per customer
357
+
358
+ An app that gives each customer its own agent keeps one isolated sandbox per customer.
359
+ `client.instances.ensure()` returns the sandbox for your key, running.
360
+ It creates the first sandbox, resumes a stopped one, and replaces one that was deleted or keeps failing to start.
361
+ The platform records which sandbox serves each key, so your app stores no binding.
362
+ Concurrent calls and lost responses converge on one sandbox.
363
+
364
+ ```typescript
365
+ const instance = await client.instances.ensure({
366
+ key: `customer:${customerId}`,
367
+ profile: { version: release.id, backend: { type: "opencode", profile } },
368
+ create: {
369
+ resources: { cpuCores: 1, memoryMB: 2048, diskGB: 10 },
370
+ deleteAfterStoppedSeconds: 30 * 86_400,
371
+ },
372
+ });
373
+ const result = await instance.turn(text, { thread: "main", turnId: messageId });
374
+ ```
375
+
376
+ Sessions bind to the profile version.
377
+ A turn runs in the session `<thread>-<version>`, created from that version's backend.
378
+ When you pass a new version, the sandbox and its files stay, and the next turn opens a session on the new profile.
379
+
380
+ A sandbox that cannot start is replaced after `restartAfterMs` (default 60 s) of failed starts.
381
+ Until then `ensure()` throws `InstanceRestartingError` with `retryAfterMs`.
382
+ A replaced sandbox is not deleted; its own retention policy deletes it.
383
+ A refusal of your key, such as `SANDBOX_ATTRIBUTION_MISMATCH`, never replaces the sandbox.
384
+ Use `adopt` to move a sandbox you created earlier under a key.
385
+
356
386
  ## Commands and files
357
387
 
358
388
  `exec()` returns the exit code, standard output, standard error, and timing data.
@@ -611,6 +641,53 @@ try {
611
641
  Always detach the lease in `finally`.
612
642
  Deleting the base sandbox remains a separate cleanup step.
613
643
 
644
+ ## Phone lines
645
+
646
+ A line gives a sandbox a messaging address that Tangle Hub receives on, today an Inkbox iMessage identity connected in Hub.
647
+ Hub routes each message to the attached sandbox, runs one agent session per member, handles STOP and START, and answers on the same line.
648
+
649
+ ```typescript
650
+ const line = await client.lines.fromConnection({
651
+ connectionId: "hubconn_...",
652
+ transport: "imessage",
653
+ });
654
+ await box.lines.attach({
655
+ number: line.id,
656
+ mode: "personal",
657
+ members: [{ address: "+15550100001", role: "owner" }],
658
+ });
659
+ // On the member's phone: text line.connect to line.routerAddress, then write.
660
+ ```
661
+
662
+ Use `mode: "shared"` with `roles` and several `members` for one agent that many people text.
663
+ Each member gets their own thread; a `shared`-context role sees other shared members' recent exchanges, and an `own`-context role sees none.
664
+ Unknown senders are rejected unless `unknownSenders: "guest"` admits them with the `guest` role.
665
+ Attach with an API key that can run the sandbox: each turn runs as a short-lived child of that key.
666
+
667
+ To check each answer before it is sent, name a reply gate.
668
+ Hub posts `{ ...context, candidate }` to the gate with its secret as a bearer token.
669
+ It sends the exact `answer` the gate returns, or nothing.
670
+ Hub never sends the agent's own text on a gated line, and refuses an answer over 4,000 characters instead of cutting it.
671
+
672
+ ```typescript
673
+ await box.lines.attach({
674
+ number: line.id,
675
+ mode: "personal",
676
+ members: [{ address: "+15550100001", role: "owner" }],
677
+ respond: {
678
+ kind: "agent",
679
+ gate: {
680
+ url: "https://gtm.example.com/api/gtm/cited-draft",
681
+ secret: process.env.GATE_KEY!,
682
+ context: { workspaceId: "ws_..." },
683
+ audience: "owner",
684
+ },
685
+ },
686
+ });
687
+ ```
688
+
689
+ A gated attachment must reject unknown senders.
690
+
614
691
  ## Public API map
615
692
 
616
693
  The root entrypoint exports the primary client, instance, session, fleet, image, error, trace, and resource types.
@@ -621,8 +698,10 @@ The root entrypoint exports the primary client, instance, session, fleet, image,
621
698
  | One environment | `SandboxInstance` |
622
699
  | One or more managed Agents in a Sandbox | `box.agents` from the `/agent` entrypoint |
623
700
  | Continued conversation | `SandboxSession` |
701
+ | One sandbox per customer | `client.instances`, `HostedInstance` |
624
702
  | Coordinated environments | `SandboxFleetClient`, `SandboxFleet` |
625
703
  | Reusable images | `Image`, `ImageBuilder` |
704
+ | Phone and messaging lines | `client.lines`, `box.lines` |
626
705
  | Failures | `SandboxError` and its specific subclasses |
627
706
 
628
707
  The main client provides `create`, `list`, `get`, `usage`, `subscription`, and `health`.
@@ -1,6 +1,6 @@
1
- import { g as SandboxSession, h as SandboxTaskSession, r as SandboxInstance } from "../sandbox-CUCPmTH3.js";
1
+ import { g as SandboxSession, h as SandboxTaskSession, r as SandboxInstance } from "../sandbox-DxBZCyMo.js";
2
2
  import { D as CodeExecutionResult, E as CodeExecutionOptions, Mi as SessionInfo, O as CodeLanguage, Pi as SessionListOptions, d as BackendConfig, k as CodeResultPart } from "../types-BoW_VFjX.js";
3
- import { i as Sandbox } from "../client-V2L7F4jq.js";
3
+ import { i as Sandbox } from "../client-0HxOqMTg.js";
4
4
  import * as _$_modelcontextprotocol_sdk_server_index_js0 from "@modelcontextprotocol/sdk/server/index.js";
5
5
  import { JSONSchema } from "zod/v4/core";
6
6
 
@@ -1,7 +1,7 @@
1
1
  import { y as assertCurrentBackendType } from "../runtime-api-DHHveKas.js";
2
2
  import { c as NotFoundError, g as ValidationError, m as StateError } from "../errors-CmYPVl-k.js";
3
- import { n as Sandbox } from "../client-ssVzKUfj.js";
4
- import { t as SandboxInstance } from "../sandbox-BotrtJlw.js";
3
+ import { n as Sandbox } from "../client-ypkUXWEV.js";
4
+ import { t as SandboxInstance } from "../sandbox-D9m16QdB.js";
5
5
  import { createRequire } from "node:module";
6
6
  import { z } from "zod";
7
7
  //#region src/agent/instances.ts
@@ -1,2 +1,2 @@
1
- import { _ as ReadTokenPayload, a as issueCollaborationToken, b as materializeCliAuthBundle, c as issueSessionScopedToken, d as AnyTokenPayload, f as BatchScopedTokenPayload, g as ProjectScopedTokenPayload, h as IssueCollaborationTokenOptions, i as issueBatchScopedToken, l as unsafeDecodeToken, m as CollaborationTokenPayload, n as getTokenTTL, o as issueProjectScopedToken, p as CollaborationAccess, r as isTokenExpiringSoon, s as issueReadToken, t as ProductTokenIssuer, u as verifyToken, v as SessionScopedTokenPayload, y as TokenScope } from "../index-CS-t6tPU.js";
1
+ import { _ as ReadTokenPayload, a as issueCollaborationToken, b as materializeCliAuthBundle, c as issueSessionScopedToken, d as AnyTokenPayload, f as BatchScopedTokenPayload, g as ProjectScopedTokenPayload, h as IssueCollaborationTokenOptions, i as issueBatchScopedToken, l as unsafeDecodeToken, m as CollaborationTokenPayload, n as getTokenTTL, o as issueProjectScopedToken, p as CollaborationAccess, r as isTokenExpiringSoon, s as issueReadToken, t as ProductTokenIssuer, u as verifyToken, v as SessionScopedTokenPayload, y as TokenScope } from "../index-BfVsF6yU.js";
2
2
  export { AnyTokenPayload, BatchScopedTokenPayload, CollaborationAccess, CollaborationTokenPayload, IssueCollaborationTokenOptions, ProductTokenIssuer, ProjectScopedTokenPayload, ReadTokenPayload, SessionScopedTokenPayload, TokenScope, getTokenTTL, isTokenExpiringSoon, issueBatchScopedToken, issueCollaborationToken, issueProjectScopedToken, issueReadToken, issueSessionScopedToken, materializeCliAuthBundle, unsafeDecodeToken, verifyToken };
@@ -1,6 +1,7 @@
1
- import { l as TraceExportResult, n as HttpClient, r as SandboxInstance, u as TraceExportSink } from "./sandbox-CUCPmTH3.js";
1
+ import { M as LinesClient, l as TraceExportResult, n as HttpClient, r as SandboxInstance, u as TraceExportSink } from "./sandbox-DxBZCyMo.js";
2
2
  import { l as ScopedToken, s as MintInteractiveSessionTokenOptions } from "./terminal-stream-CcaBTVg3.js";
3
- import { $n as ReconcileSandboxFleetsResult, B as CreateSandboxOptions, Bn as PromptOptions, Bt as FleetMachineId, Cr as SandboxFleetCostEstimate, Er as SandboxFleetDriverCapability, F as CreateIntelligenceReportOptions, Ft as FleetDispatchStreamOptions, G as DeleteMatchingSandboxesFilter, Gr as SandboxFleetWorkspaceReconcileResult, Hr as SandboxFleetTraceOptions, Ht as FleetPromptDispatchResult, I as CreateRequestOptions, Ir as SandboxFleetOperationsSummary, It as FleetDriveTurnOutcome, Jn as PublishPublicTemplateOptions, Jr as SandboxIdentity, K as DeleteMatchingSandboxesOptions, Ki as SshKeysManager, Kn as PublicTemplateInfo, Kr as SandboxFleetWorkspaceRestoreResult, L as CreateSandboxFleetOptions, Lt as FleetDriveTurnRequest, Mr as SandboxFleetMachineRecord, Mt as FleetDispatchCancelResult, Nt as FleetDispatchResultBuffer, Or as SandboxFleetInfo, Pr as SandboxFleetManifest, Pt as FleetDispatchResultBufferOptions, Qn as ReconcileSandboxFleetsOptions, R as CreateSandboxFleetTokenOptions, Rr as SandboxFleetToken, Rt as FleetExecDispatchOptions, Si as SecretsManager, Sr as SandboxFleetArtifactSpec, Tr as SandboxFleetDispatchResponse, Ur as SandboxFleetUsage, Vn as PromptResult, Vt as FleetPromptDispatchOptions, Xi as SubscriptionInfo, Xn as ReapExpiredSandboxFleetsOptions, Yn as PublishPublicTemplateVersionOptions, Yr as SandboxInfo, Zn as ReapExpiredSandboxFleetsResult, _t as ExecOptions, b as BatchRunRequest, dn as IntelligenceReportBudget, fn as IntelligenceReportCompareTo, fr as SandboxConfig, l as AttachSandboxFleetMachineOptions, mn as IntelligenceReportWindow, oi as SandboxShapesInfo, pa as UsageInfo, q as DeleteMatchingSandboxesResult, qn as PublicTemplateVersionInfo, qr as SandboxFleetWorkspaceSnapshotResult, sa as TokenRefreshHandler, un as IntelligenceReport, v as BatchResult, vn as ListSandboxFleetOptions, vt as ExecResult, xa as BatchEvent, xr as SandboxFleetArtifact, y as BatchRunOptions, yn as ListSandboxOptions, yr as SandboxEnvironment, z as CreateSandboxFleetWithCoordinatorOptions, zn as PromptInputPart, zr as SandboxFleetTraceBundle, zt as FleetExecDispatchResult } from "./types-BoW_VFjX.js";
3
+ import { $n as ReconcileSandboxFleetsResult, B as CreateSandboxOptions, Bn as PromptOptions, Bt as FleetMachineId, Cr as SandboxFleetCostEstimate, Er as SandboxFleetDriverCapability, F as CreateIntelligenceReportOptions, Ft as FleetDispatchStreamOptions, G as DeleteMatchingSandboxesFilter, Gr as SandboxFleetWorkspaceReconcileResult, Hr as SandboxFleetTraceOptions, Ht as FleetPromptDispatchResult, I as CreateRequestOptions, Ir as SandboxFleetOperationsSummary, It as FleetDriveTurnOutcome, Jn as PublishPublicTemplateOptions, Jr as SandboxIdentity, K as DeleteMatchingSandboxesOptions, Ki as SshKeysManager, Kn as PublicTemplateInfo, Kr as SandboxFleetWorkspaceRestoreResult, L as CreateSandboxFleetOptions, Lt as FleetDriveTurnRequest, M as ConversationTurnOptions, Mr as SandboxFleetMachineRecord, Mt as FleetDispatchCancelResult, N as ConversationTurnResult, Nt as FleetDispatchResultBuffer, Or as SandboxFleetInfo, Pr as SandboxFleetManifest, Pt as FleetDispatchResultBufferOptions, Qn as ReconcileSandboxFleetsOptions, R as CreateSandboxFleetTokenOptions, Rr as SandboxFleetToken, Rt as FleetExecDispatchOptions, Si as SecretsManager, Sr as SandboxFleetArtifactSpec, Tr as SandboxFleetDispatchResponse, Ur as SandboxFleetUsage, Vn as PromptResult, Vt as FleetPromptDispatchOptions, Xi as SubscriptionInfo, Xn as ReapExpiredSandboxFleetsOptions, Yn as PublishPublicTemplateVersionOptions, Yr as SandboxInfo, Zn as ReapExpiredSandboxFleetsResult, _t as ExecOptions, b as BatchRunRequest, d as BackendConfig, dn as IntelligenceReportBudget, fn as IntelligenceReportCompareTo, fr as SandboxConfig, l as AttachSandboxFleetMachineOptions, mn as IntelligenceReportWindow, oi as SandboxShapesInfo, pa as UsageInfo, q as DeleteMatchingSandboxesResult, qn as PublicTemplateVersionInfo, qr as SandboxFleetWorkspaceSnapshotResult, sa as TokenRefreshHandler, un as IntelligenceReport, v as BatchResult, vn as ListSandboxFleetOptions, vt as ExecResult, xa as BatchEvent, xr as SandboxFleetArtifact, y as BatchRunOptions, yn as ListSandboxOptions, yr as SandboxEnvironment, z as CreateSandboxFleetWithCoordinatorOptions, zn as PromptInputPart, zr as SandboxFleetTraceBundle, zt as FleetExecDispatchResult } from "./types-BoW_VFjX.js";
4
+ import { f as SandboxError } from "./errors-Cz23YNu2.js";
4
5
  import { AgentInteractiveSessionRef } from "@tangle-network/agent-interface";
5
6
  import { z } from "zod";
6
7
 
@@ -291,6 +292,119 @@ declare class SandboxFleetClient {
291
292
  private listBySandboxMetadata;
292
293
  }
293
294
  //#endregion
295
+ //#region src/instances.d.ts
296
+ /** The profile version that new sessions of an instance bind to. */
297
+ interface InstanceProfile {
298
+ /** Your identifier for this profile version, such as a release id. */
299
+ version: string;
300
+ /** The backend a new session is created from. */
301
+ backend: BackendConfig;
302
+ }
303
+ /** The platform's record of one named instance. */
304
+ interface InstanceRecord {
305
+ key: string;
306
+ /** Counts the key's sandboxes; a replacement moves to the next one. */
307
+ generation: number;
308
+ sandboxId: string | null;
309
+ profileVersion: string | null;
310
+ /** Epoch ms of the current sandbox's first failed start, or null. */
311
+ unstartableSince: number | null;
312
+ createdAt: number;
313
+ updatedAt: number;
314
+ }
315
+ interface EnsureInstanceOptions {
316
+ /** Your tenant key: 1-200 letters, digits and `. _ : @ -`. */
317
+ key: string;
318
+ /** The profile version new sessions bind to. */
319
+ profile?: InstanceProfile;
320
+ /**
321
+ * How a new sandbox is created. The sandbox is always isolated from your
322
+ * own account's context; the SDK sets its idempotency key and adds
323
+ * `instanceKey` and `instanceGeneration` to its metadata.
324
+ */
325
+ create: Omit<CreateSandboxOptions, "ownerContext" | "idempotencyKey" | "backend">;
326
+ /**
327
+ * How long a sandbox may keep failing to start before a fresh sandbox
328
+ * replaces it. The replaced sandbox is not deleted; its own retention
329
+ * deletes it. Default 60 s.
330
+ */
331
+ restartAfterMs?: number;
332
+ /**
333
+ * A sandbox you created before using instances, to adopt for a key that
334
+ * has no instance yet. Ignored once the key has one.
335
+ */
336
+ adopt?: string;
337
+ }
338
+ /**
339
+ * The sandbox cannot start yet. `ensure()` replaces it once it has kept
340
+ * failing for `restartAfterMs`; retry after `retryAfterMs`.
341
+ */
342
+ declare class InstanceRestartingError extends SandboxError {
343
+ readonly instance: InstanceRecord;
344
+ /** The start failure that was recorded. */
345
+ readonly failure: Error;
346
+ constructor(message: string, instance: InstanceRecord, /** The start failure that was recorded. */
347
+
348
+ failure: Error, retryAfterMs: number);
349
+ }
350
+ /** The part of the SDK client that instances use. */
351
+ interface InstancesHttpClient {
352
+ fetch(path: string, options?: RequestInit): Promise<Response>;
353
+ get(id: string): Promise<SandboxInstance | null>;
354
+ createIsolated(options: Omit<CreateSandboxOptions, "ownerContext">): Promise<SandboxInstance>;
355
+ }
356
+ /** One running instance: its sandbox and the profile version it binds. */
357
+ declare class HostedInstance {
358
+ readonly record: InstanceRecord;
359
+ readonly box: SandboxInstance;
360
+ readonly profile?: InstanceProfile | undefined;
361
+ constructor(record: InstanceRecord, box: SandboxInstance, profile?: InstanceProfile | undefined);
362
+ get key(): string;
363
+ get generation(): number;
364
+ get sandboxId(): string;
365
+ get profileVersion(): string | null;
366
+ /**
367
+ * The session a thread's turns run in on the current profile version:
368
+ * `<thread>-<version>`. Without a profile version it is the thread itself.
369
+ */
370
+ sessionId(thread: string): string;
371
+ /**
372
+ * Run one turn in the thread's session. The session is created from the
373
+ * profile version's backend the first time; retrying with the same
374
+ * `turnId` settles the same turn.
375
+ */
376
+ turn(message: string | PromptInputPart[], options: Omit<ConversationTurnOptions, "sessionId" | "backend"> & {
377
+ thread: string;
378
+ }): Promise<ConversationTurnResult>;
379
+ }
380
+ /** `client.instances`: one isolated sandbox per tenant key. */
381
+ declare class InstancesClient {
382
+ private readonly client;
383
+ private readonly now;
384
+ constructor(client: InstancesHttpClient, now?: () => number);
385
+ /** The platform's record for `key`, or null when it has none. */
386
+ get(key: string): Promise<InstanceRecord | null>;
387
+ /** Forget `key`. Its sandbox is left as it is. */
388
+ release(key: string): Promise<boolean>;
389
+ /**
390
+ * The key's sandbox, running. Creates the first sandbox, resumes a stopped
391
+ * one, replaces one that was deleted or has kept failing to start, and
392
+ * moves the key to `profile.version` without replacing the sandbox.
393
+ */
394
+ ensure(options: EnsureInstanceOptions): Promise<HostedInstance>;
395
+ private create;
396
+ private start;
397
+ /**
398
+ * Record a failed start. The sandbox is replaced once starts have failed
399
+ * for `restartAfterMs`; until then the caller is told to retry.
400
+ */
401
+ private failedStart;
402
+ private replace;
403
+ private update;
404
+ /** A write the platform refused as stale answers `ok: false`. */
405
+ private write;
406
+ }
407
+ //#endregion
294
408
  //#region src/scoped-token.d.ts
295
409
  interface ScopedTokenHttpClient {
296
410
  fetch(path: string, options?: RequestInit, fetchOptions?: {
@@ -350,7 +464,9 @@ declare class Sandbox implements HttpClient, ScopedTokenHttpClient {
350
464
  private _secrets;
351
465
  private _sshKeys;
352
466
  private _fleets;
467
+ private _instances;
353
468
  private _intelligence;
469
+ private _lines;
354
470
  constructor(config: SandboxConfig);
355
471
  /**
356
472
  * Fleet operations for agent-managed groups of sandboxes.
@@ -359,7 +475,19 @@ declare class Sandbox implements HttpClient, ScopedTokenHttpClient {
359
475
  * API. Each worker is a normal sandbox tagged with stable fleet metadata,
360
476
  * so older clients and dashboards can still inspect and delete them.
361
477
  */
478
+ /**
479
+ * Named instances: one isolated sandbox per tenant key, kept by the
480
+ * platform. `ensure()` creates, resumes or replaces the key's sandbox and
481
+ * binds new sessions to a profile version.
482
+ */
483
+ get instances(): InstancesClient;
362
484
  get fleets(): SandboxFleetClient;
485
+ /**
486
+ * Lines: phone numbers and messaging addresses that Tangle Hub receives on.
487
+ * Create a line from a connected Inkbox identity, then attach it to a
488
+ * sandbox with `sandbox.lines.attach()`.
489
+ */
490
+ get lines(): LinesClient;
363
491
  get intelligence(): IntelligenceClient;
364
492
  getApiKey(): string;
365
493
  /**
@@ -888,4 +1016,4 @@ declare class TeamsClient {
888
1016
  deleteTemplate(teamId: string, templateId: string): Promise<void>;
889
1017
  }
890
1018
  //#endregion
891
- export { isBackendRegistryInteractionKind as C, backendRegistryResponseSchema as S, parseBackendRegistryResponseBody as T, BackendRegistryInteractionKind as _, Team as a, backendRegistryEntrySchema as b, SessionBroadcastEvent as c, SandboxFleetClient as d, ParseSSEStreamOptions as f, BackendRegistryEntry as g, BackendRegistryCapabilities as h, Sandbox as i, SessionBroadcastResult as l, parseSSEStream as m, IntelligenceClient as n, TeamInvitation as o, ParsedSSEEvent as p, InviteTeamMemberOptions as r, TeamMember as s, CreateTeamOptions as t, SandboxFleet as u, BackendRegistryResponse as v, parseBackendRegistryResponse as w, backendRegistryInteractionKindSchema as x, backendRegistryCapabilitiesSchema as y };
1019
+ export { parseBackendRegistryResponse as A, BackendRegistryInteractionKind as C, backendRegistryInteractionKindSchema as D, backendRegistryEntrySchema as E, backendRegistryResponseSchema as O, BackendRegistryEntry as S, backendRegistryCapabilitiesSchema as T, SandboxFleetClient as _, Team as a, parseSSEStream as b, SessionBroadcastEvent as c, HostedInstance as d, InstanceProfile as f, SandboxFleet as g, InstancesClient as h, Sandbox as i, parseBackendRegistryResponseBody as j, isBackendRegistryInteractionKind as k, SessionBroadcastResult as l, InstanceRestartingError as m, IntelligenceClient as n, TeamInvitation as o, InstanceRecord as p, InviteTeamMemberOptions as r, TeamMember as s, CreateTeamOptions as t, EnsureInstanceOptions as u, ParseSSEStreamOptions as v, BackendRegistryResponse as w, BackendRegistryCapabilities as x, ParsedSSEEvent as y };
@@ -1,7 +1,7 @@
1
1
  import { E as backendTypeSchema, _ as parseSSEStream, g as encodeTextForWire, h as encodePromptForWire, p as SANDBOX_PROXY_REQUEST_MAX_BYTES, v as applyRequestedModel, x as normalizeRuntimeBackendConfig, y as assertCurrentBackendType } from "./runtime-api-DHHveKas.js";
2
2
  import { _ as parseErrorResponse, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, l as PartialFailureError, p as ServerError, s as NetworkError, t as AuthError } from "./errors-CmYPVl-k.js";
3
3
  import { n as combineAbortSignals } from "./abort-signal-si1WMfJb.js";
4
- import { D as normalizeSandboxShape, E as normalizeConnection, b as requestInteractiveSessionToken, i as normalizeStartupDiagnostics, k as exportTraceBundle, n as createSandboxInstanceFromResponse, r as normalizeSandboxCreateReceipt } from "./sandbox-BotrtJlw.js";
4
+ import { D as normalizeSandboxShape, E as normalizeConnection, O as LinesClient, b as requestInteractiveSessionToken, i as normalizeStartupDiagnostics, j as exportTraceBundle, n as createSandboxInstanceFromResponse, r as normalizeSandboxCreateReceipt } from "./sandbox-D9m16QdB.js";
5
5
  import { agentProfileSchema } from "@tangle-network/agent-interface";
6
6
  import { z } from "zod";
7
7
  //#region src/backend-registry.ts
@@ -2081,6 +2081,277 @@ function getMachineRole(info) {
2081
2081
  return value === "coordinator" || value === "worker" ? value : void 0;
2082
2082
  }
2083
2083
  //#endregion
2084
+ //#region src/instances.ts
2085
+ /**
2086
+ * Named instances: one isolated sandbox per tenant of your app, kept by the
2087
+ * platform.
2088
+ *
2089
+ * An app that gives each customer (or each shared space) its own agent keeps
2090
+ * one sandbox per customer under a key it chooses. `client.instances.ensure()`
2091
+ * returns that sandbox running: it creates the first one, resumes a stopped
2092
+ * one, and replaces one that was deleted or keeps failing to start. The
2093
+ * platform records which sandbox serves each key, so concurrent callers and
2094
+ * lost responses converge on one sandbox, and the app stores nothing.
2095
+ *
2096
+ * Sessions bind to a profile version. A turn runs in the session named by its
2097
+ * thread and the instance's profile version, created from that version's
2098
+ * backend. A new version therefore keeps the sandbox and its files, and the
2099
+ * next turn opens a session on the new profile.
2100
+ *
2101
+ * @example
2102
+ * ```ts
2103
+ * const instance = await client.instances.ensure({
2104
+ * key: `customer:${customerId}`,
2105
+ * profile: { version: release.id, backend: { type: "opencode", profile } },
2106
+ * create: { resources: { cpuCores: 1, memoryMB: 2048, diskGB: 10 } },
2107
+ * });
2108
+ * const result = await instance.turn(text, { thread: "main", turnId: messageId });
2109
+ * ```
2110
+ */
2111
+ /**
2112
+ * The sandbox cannot start yet. `ensure()` replaces it once it has kept
2113
+ * failing for `restartAfterMs`; retry after `retryAfterMs`.
2114
+ */
2115
+ var InstanceRestartingError = class extends SandboxError {
2116
+ constructor(message, instance, failure, retryAfterMs) {
2117
+ super(message, "INSTANCE_RESTARTING", 503, { retryAfterMs });
2118
+ this.instance = instance;
2119
+ this.failure = failure;
2120
+ this.name = "InstanceRestartingError";
2121
+ }
2122
+ };
2123
+ /** Resume refusals that say this sandbox cannot start, as opposed to the
2124
+ * account, key or platform being unavailable. An attribution refusal is not
2125
+ * one: it means the caller's key cannot run the sandbox, and replacing the
2126
+ * sandbox would only hide that. */
2127
+ const UNSTARTABLE = new Set(["CONTAINER_START_FAILED", "SANDBOX_LIFECYCLE_IN_PROGRESS"]);
2128
+ const DEFAULT_RESTART_AFTER_MS = 6e4;
2129
+ /** A failed start this much older than the wait means failures stopped in
2130
+ * between; the wait starts again rather than replacing at once. */
2131
+ const STALE_FAILURE_FACTOR = 5;
2132
+ const MAX_PASSES = 4;
2133
+ const KEY = /^[A-Za-z0-9][A-Za-z0-9._:@-]{0,199}$/;
2134
+ const THREAD = /^[A-Za-z0-9_-]{1,120}$/;
2135
+ /** The runtime's session id alphabet and length. */
2136
+ const SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/;
2137
+ /** One running instance: its sandbox and the profile version it binds. */
2138
+ var HostedInstance = class {
2139
+ constructor(record, box, profile) {
2140
+ this.record = record;
2141
+ this.box = box;
2142
+ this.profile = profile;
2143
+ }
2144
+ get key() {
2145
+ return this.record.key;
2146
+ }
2147
+ get generation() {
2148
+ return this.record.generation;
2149
+ }
2150
+ get sandboxId() {
2151
+ return this.box.id;
2152
+ }
2153
+ get profileVersion() {
2154
+ return this.profile?.version ?? this.record.profileVersion;
2155
+ }
2156
+ /**
2157
+ * The session a thread's turns run in on the current profile version:
2158
+ * `<thread>-<version>`. Without a profile version it is the thread itself.
2159
+ */
2160
+ sessionId(thread) {
2161
+ if (!THREAD.test(thread)) throw new ValidationError("A thread is 1-120 letters, digits, '_' or '-'");
2162
+ const version = this.profileVersion?.replace(/[^A-Za-z0-9_-]/g, "_");
2163
+ const id = version ? `${thread}-${version}` : thread;
2164
+ if (!SESSION_ID.test(id)) throw new ValidationError(`Session id for thread ${thread} is longer than 128 characters`);
2165
+ return id;
2166
+ }
2167
+ /**
2168
+ * Run one turn in the thread's session. The session is created from the
2169
+ * profile version's backend the first time; retrying with the same
2170
+ * `turnId` settles the same turn.
2171
+ */
2172
+ turn(message, options) {
2173
+ const { thread, ...turn } = options;
2174
+ return this.box.driveConversationTurn(message, {
2175
+ ...turn,
2176
+ sessionId: this.sessionId(thread),
2177
+ ...this.profile ? { backend: this.profile.backend } : {}
2178
+ });
2179
+ }
2180
+ };
2181
+ /** `client.instances`: one isolated sandbox per tenant key. */
2182
+ var InstancesClient = class {
2183
+ constructor(client, now = Date.now) {
2184
+ this.client = client;
2185
+ this.now = now;
2186
+ }
2187
+ /** The platform's record for `key`, or null when it has none. */
2188
+ async get(key) {
2189
+ const response = await this.client.fetch(path(key));
2190
+ if (response.status === 404) {
2191
+ const body = await response.text();
2192
+ if (errorCode(body) === "INSTANCE_NOT_FOUND") return null;
2193
+ throw parseErrorResponse(404, body, void 0, response.headers);
2194
+ }
2195
+ return (await read(response)).instance;
2196
+ }
2197
+ /** Forget `key`. Its sandbox is left as it is. */
2198
+ async release(key) {
2199
+ const response = await this.client.fetch(path(key), { method: "DELETE" });
2200
+ if (response.status === 204) return true;
2201
+ const body = await response.text();
2202
+ if (response.status === 404 && errorCode(body) === "INSTANCE_NOT_FOUND") return false;
2203
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
2204
+ }
2205
+ /**
2206
+ * The key's sandbox, running. Creates the first sandbox, resumes a stopped
2207
+ * one, replaces one that was deleted or has kept failing to start, and
2208
+ * moves the key to `profile.version` without replacing the sandbox.
2209
+ */
2210
+ async ensure(options) {
2211
+ if (!KEY.test(options.key)) throw new ValidationError("An instance key is 1-200 letters, digits and . _ : @ -");
2212
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
2213
+ const record = await this.get(options.key);
2214
+ if (!record?.sandboxId) {
2215
+ if (!record && options.adopt) {
2216
+ await this.write(bindingPath(options.key), "PUT", {
2217
+ generation: 1,
2218
+ sandboxId: options.adopt,
2219
+ ...options.profile ? { profileVersion: options.profile.version } : {}
2220
+ });
2221
+ continue;
2222
+ }
2223
+ const created = await this.create(options, record?.generation ?? 1);
2224
+ if (created) return created;
2225
+ continue;
2226
+ }
2227
+ const running = await this.start(options, record, record.sandboxId);
2228
+ if (running) return running;
2229
+ }
2230
+ throw new SandboxError(`Instance ${options.key} changed on every attempt; retry`, "INSTANCE_CONTENDED", 409);
2231
+ }
2232
+ async create(options, generation) {
2233
+ const box = await this.client.createIsolated({
2234
+ ...options.create,
2235
+ ...options.profile ? { backend: options.profile.backend } : {},
2236
+ idempotencyKey: `instance:${options.key}:${generation}`,
2237
+ metadata: {
2238
+ ...options.create.metadata,
2239
+ instanceKey: options.key,
2240
+ instanceGeneration: String(generation)
2241
+ }
2242
+ });
2243
+ const bound = await this.write(bindingPath(options.key), "PUT", {
2244
+ generation,
2245
+ sandboxId: box.id,
2246
+ ...options.profile ? { profileVersion: options.profile.version } : {}
2247
+ });
2248
+ const record = bound.ok ? bound.instance : bound.instance?.generation === generation && bound.instance.sandboxId === box.id ? bound.instance : null;
2249
+ return record ? new HostedInstance(record, box, options.profile) : null;
2250
+ }
2251
+ async start(options, record, sandboxId) {
2252
+ let box = await this.client.get(sandboxId);
2253
+ if (!box || box.status === "deleted") {
2254
+ await this.replace(options.key, record.generation);
2255
+ return null;
2256
+ }
2257
+ if (box.status === "failed") {
2258
+ await this.failedStart(options, record, /* @__PURE__ */ new Error("sandbox failed"));
2259
+ return null;
2260
+ }
2261
+ if (box.status === "stopped" || box.status === "expired") {
2262
+ try {
2263
+ await box.resume();
2264
+ } catch (error) {
2265
+ const code = error?.code;
2266
+ if (typeof code !== "string" || !UNSTARTABLE.has(code)) throw error;
2267
+ await this.failedStart(options, record, error instanceof Error ? error : new Error(String(error)));
2268
+ return null;
2269
+ }
2270
+ box = await this.client.get(sandboxId) ?? box;
2271
+ }
2272
+ let current = record;
2273
+ if (record.unstartableSince !== null && box.status === "running") {
2274
+ const cleared = await this.update(options.key, record.generation, { unstartable: "clear" });
2275
+ if (!cleared.ok) return null;
2276
+ current = cleared.instance;
2277
+ }
2278
+ if (options.profile && options.profile.version !== current.profileVersion) {
2279
+ const moved = await this.update(options.key, record.generation, { profileVersion: options.profile.version });
2280
+ if (!moved.ok) return null;
2281
+ current = moved.instance;
2282
+ }
2283
+ return new HostedInstance(current, box, options.profile);
2284
+ }
2285
+ /**
2286
+ * Record a failed start. The sandbox is replaced once starts have failed
2287
+ * for `restartAfterMs`; until then the caller is told to retry.
2288
+ */
2289
+ async failedStart(options, record, cause) {
2290
+ const wait = options.restartAfterMs ?? DEFAULT_RESTART_AFTER_MS;
2291
+ const now = this.now();
2292
+ if (record.unstartableSince !== null && now - record.unstartableSince > STALE_FAILURE_FACTOR * wait) {
2293
+ if (!(await this.update(options.key, record.generation, { unstartable: "clear" })).ok) return;
2294
+ }
2295
+ const marked = await this.update(options.key, record.generation, { unstartable: "mark" });
2296
+ if (!marked.ok) return;
2297
+ const since = marked.instance.unstartableSince ?? now;
2298
+ if (now - since >= wait) {
2299
+ await this.replace(options.key, record.generation);
2300
+ return;
2301
+ }
2302
+ throw new InstanceRestartingError(`Instance ${options.key} could not start; a fresh sandbox replaces it if this persists`, marked.instance, cause, Math.max(1e3, since + wait - now));
2303
+ }
2304
+ replace(key, generation) {
2305
+ return this.write(`/v1/instances/${encodeURIComponent(key)}/replace`, "POST", { generation });
2306
+ }
2307
+ update(key, generation, change) {
2308
+ return this.write(path(key), "PATCH", {
2309
+ generation,
2310
+ ...change
2311
+ });
2312
+ }
2313
+ /** A write the platform refused as stale answers `ok: false`. */
2314
+ async write(route, method, body) {
2315
+ const response = await this.client.fetch(route, {
2316
+ method,
2317
+ body: JSON.stringify(body)
2318
+ });
2319
+ if (response.status === 409) {
2320
+ const text = await response.text();
2321
+ if (errorCode(text) !== "INSTANCE_CONFLICT") throw parseErrorResponse(409, text, void 0, response.headers);
2322
+ return {
2323
+ ok: false,
2324
+ instance: JSON.parse(text).instance ?? null
2325
+ };
2326
+ }
2327
+ return {
2328
+ ok: true,
2329
+ instance: (await read(response)).instance
2330
+ };
2331
+ }
2332
+ };
2333
+ function path(key) {
2334
+ return `/v1/instances/${encodeURIComponent(key)}`;
2335
+ }
2336
+ function bindingPath(key) {
2337
+ return `/v1/instances/${encodeURIComponent(key)}/binding`;
2338
+ }
2339
+ function errorCode(body) {
2340
+ try {
2341
+ const parsed = JSON.parse(body);
2342
+ return typeof parsed.error?.code === "string" ? parsed.error.code : void 0;
2343
+ } catch {
2344
+ return;
2345
+ }
2346
+ }
2347
+ async function read(response) {
2348
+ const body = await response.text();
2349
+ if (!response.ok) throw parseErrorResponse(response.status, body, void 0, response.headers);
2350
+ const parsed = JSON.parse(body);
2351
+ if (!parsed.instance) throw parseErrorResponse(502, body, void 0, response.headers);
2352
+ return { instance: parsed.instance };
2353
+ }
2354
+ //#endregion
2084
2355
  //#region src/profile-file-mounts.ts
2085
2356
  const PROFILE_FILE_MOUNT_B64_CHUNK_CHARS = 3e3;
2086
2357
  const PROFILE_FILE_MOUNT_MAX_RETRIES = 4;
@@ -2605,7 +2876,9 @@ const RETRYABLE_CREATE_STATUS_CODES = new Set([
2605
2876
  * turned a ~10 s failure into a 120 s TimeoutError. It keeps the
2606
2877
  * five-attempt budget, paced on its Retry-After, like every other 503. The
2607
2878
  * same code also answers a failed read of that recovery state, a transient
2608
- * the short budget already covers.
2879
+ * the short budget already covers. When the hold follows this call's own
2880
+ * failed attempt, create() throws that earlier failure instead: it names
2881
+ * the cause, and the hold only names the journal it left.
2609
2882
  */
2610
2883
  const DEPLOY_WINDOW_RETRY_CODES = new Set([
2611
2884
  "IDEMPOTENT_CREATE_PROBE_FAILED",
@@ -2743,7 +3016,9 @@ var Sandbox = class {
2743
3016
  _secrets = null;
2744
3017
  _sshKeys = null;
2745
3018
  _fleets = null;
3019
+ _instances = null;
2746
3020
  _intelligence = null;
3021
+ _lines = null;
2747
3022
  constructor(config) {
2748
3023
  if (!config.apiKey) throw new AuthError("API key is required");
2749
3024
  if (!config.baseUrl) throw new ValidationError("Base URL is required");
@@ -2759,10 +3034,28 @@ var Sandbox = class {
2759
3034
  * API. Each worker is a normal sandbox tagged with stable fleet metadata,
2760
3035
  * so older clients and dashboards can still inspect and delete them.
2761
3036
  */
3037
+ /**
3038
+ * Named instances: one isolated sandbox per tenant key, kept by the
3039
+ * platform. `ensure()` creates, resumes or replaces the key's sandbox and
3040
+ * binds new sessions to a profile version.
3041
+ */
3042
+ get instances() {
3043
+ if (!this._instances) this._instances = new InstancesClient(this);
3044
+ return this._instances;
3045
+ }
2762
3046
  get fleets() {
2763
3047
  if (!this._fleets) this._fleets = new SandboxFleetClient(this);
2764
3048
  return this._fleets;
2765
3049
  }
3050
+ /**
3051
+ * Lines: phone numbers and messaging addresses that Tangle Hub receives on.
3052
+ * Create a line from a connected Inkbox identity, then attach it to a
3053
+ * sandbox with `sandbox.lines.attach()`.
3054
+ */
3055
+ get lines() {
3056
+ if (!this._lines) this._lines = new LinesClient(this);
3057
+ return this._lines;
3058
+ }
2766
3059
  get intelligence() {
2767
3060
  if (!this._intelligence) this._intelligence = new IntelligenceClient(this);
2768
3061
  return this._intelligence;
@@ -3036,6 +3329,7 @@ var Sandbox = class {
3036
3329
  const body = await response.text();
3037
3330
  const error = parseErrorResponse(response.status, body, { allPreviousCreateAttemptsRefused }, response.headers);
3038
3331
  allPreviousCreateAttemptsRefused = error.createFailureDisposition === "not-admitted";
3332
+ if (error.code === "SANDBOX_CREATE_RECONCILING" && lastServerError && lastServerError.code !== "SANDBOX_CREATE_RECONCILING") throw lastServerError;
3039
3333
  lastServerError = error;
3040
3334
  if (exhaustsRetryBudget(error)) throw error;
3041
3335
  await waitBeforeRetry(error, attempt);
@@ -4059,4 +4353,4 @@ var TeamsClient = class {
4059
4353
  }
4060
4354
  };
4061
4355
  //#endregion
4062
- export { parseBackendRegistryResponse as _, splitInlineProfileSkills as a, SandboxFleetClient as c, validateBatchRunRequest as d, backendRegistryCapabilitiesSchema as f, isBackendRegistryInteractionKind as g, backendRegistryResponseSchema as h, splitInlineProfileFileMounts as i, runtimeWorkspaceCwdSchema as l, backendRegistryInteractionKindSchema as m, Sandbox as n, validateDeferredProfileFileMounts as o, backendRegistryEntrySchema as p, materializeProfileFileMounts as r, SandboxFleet as s, IntelligenceClient as t, createBatchResultAccumulator as u, parseBackendRegistryResponseBody as v };
4356
+ export { backendRegistryInteractionKindSchema as _, splitInlineProfileSkills as a, parseBackendRegistryResponse as b, InstanceRestartingError as c, SandboxFleetClient as d, runtimeWorkspaceCwdSchema as f, backendRegistryEntrySchema as g, backendRegistryCapabilitiesSchema as h, splitInlineProfileFileMounts as i, InstancesClient as l, validateBatchRunRequest as m, Sandbox as n, validateDeferredProfileFileMounts as o, createBatchResultAccumulator as p, materializeProfileFileMounts as r, HostedInstance as s, IntelligenceClient as t, SandboxFleet as u, backendRegistryResponseSchema as v, parseBackendRegistryResponseBody as x, isBackendRegistryInteractionKind as y };
@@ -1,2 +1,2 @@
1
- import { _ as CollaborationTransportConfig, a as CollaborationClient, c as CollaborationClientConfig, d as CollaborationDocumentRef, f as CollaborationFileBridgeOptions, g as CollaborationTokenRefreshResponse, h as CollaborationTokenRefreshRequest, i as parseCollaborationDocumentId, l as CollaborationDocumentAdapter, m as CollaborationPermissions, n as buildCollaborationDocumentId, o as CollaborationBootstrapRequest, p as CollaborationFileEvent, r as normalizeCollaborationPath, s as CollaborationBootstrapResponse, t as CollaborationFileBridge, u as CollaborationDocumentChange, v as SaveCollaborationSnapshotRequest, y as SaveCollaborationSnapshotResponse } from "../index-BzAxTiqF.js";
1
+ import { _ as CollaborationTransportConfig, a as CollaborationClient, c as CollaborationClientConfig, d as CollaborationDocumentRef, f as CollaborationFileBridgeOptions, g as CollaborationTokenRefreshResponse, h as CollaborationTokenRefreshRequest, i as parseCollaborationDocumentId, l as CollaborationDocumentAdapter, m as CollaborationPermissions, n as buildCollaborationDocumentId, o as CollaborationBootstrapRequest, p as CollaborationFileEvent, r as normalizeCollaborationPath, s as CollaborationBootstrapResponse, t as CollaborationFileBridge, u as CollaborationDocumentChange, v as SaveCollaborationSnapshotRequest, y as SaveCollaborationSnapshotResponse } from "../index-BWiG3Vcw.js";
2
2
  export { CollaborationBootstrapRequest, CollaborationBootstrapResponse, CollaborationClient, CollaborationClientConfig, CollaborationDocumentAdapter, CollaborationDocumentChange, CollaborationDocumentRef, CollaborationFileBridge, CollaborationFileBridgeOptions, CollaborationFileEvent, CollaborationPermissions, CollaborationTokenRefreshRequest, CollaborationTokenRefreshResponse, CollaborationTransportConfig, SaveCollaborationSnapshotRequest, SaveCollaborationSnapshotResponse, buildCollaborationDocumentId, normalizeCollaborationPath, parseCollaborationDocumentId };