@tangle-network/sandbox 0.60.78-develop.20261022130634.e0beb70 → 0.60.78-develop.20261022135157.7c7d4e9

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.
Files changed (29) hide show
  1. package/dist/agent/index.d.ts +4 -4
  2. package/dist/agent/index.js +2 -2
  3. package/dist/agent/preview.d.ts +1 -1
  4. package/dist/{agent-run-outcome-BSQJEeQO.d.ts → agent-run-outcome-UqVoiafo.d.ts} +1 -1
  5. package/dist/auth/index.js +1 -1
  6. package/dist/{cli-auth-bundle-hoD3-9Xr.js → cli-auth-bundle-DiO80j-k.js} +22 -6
  7. package/dist/{client-ZUAg3t1p.d.ts → client-Bzklblzg.d.ts} +10 -24
  8. package/dist/{client-BwffEbHl.js → client-CAa6I_92.js} +3 -3
  9. package/dist/core.d.ts +5 -5
  10. package/dist/core.js +2 -2
  11. package/dist/{index-D7VkrwXt.d.ts → index-iYdJi4O8.d.ts} +7 -3
  12. package/dist/index.d.ts +8 -8
  13. package/dist/index.js +42 -25
  14. package/dist/intelligence/index.d.ts +12 -12
  15. package/dist/{interactive-controller-BcMoYAot.d.ts → interactive-controller-CG-ikeYf.d.ts} +1 -1
  16. package/dist/{lines-CNyn-3BG.d.ts → lines-CEX65fBF.d.ts} +1 -1
  17. package/dist/lines.d.ts +1 -1
  18. package/dist/{local-cli-auth-BphtVcki.js → local-cli-auth-DAukxS-v.js} +1 -1
  19. package/dist/openai/index.d.ts +3 -3
  20. package/dist/{preview-CjgZkVue.d.ts → preview-Cjg3Lsls.d.ts} +3 -3
  21. package/dist/{public-templates-C2ZWpukc.d.ts → public-templates-CXn4aQsN.d.ts} +1 -1
  22. package/dist/public-templates.d.ts +1 -1
  23. package/dist/runtime.d.ts +3 -3
  24. package/dist/{sandbox-dxjJMlUt.js → sandbox-CICD7KcJ.js} +219 -222
  25. package/dist/tangle/index.d.ts +1 -1
  26. package/dist/tangle/index.js +1 -1
  27. package/dist/{tangle-DXYPV6rH.js → tangle-DA1aBXXG.js} +1 -1
  28. package/dist/{types-rqzp5pEX.d.ts → types-CxfH95D5.d.ts} +49 -31
  29. package/package.json +4 -4
@@ -4,7 +4,7 @@ import { C as StreamInterruptedError, F as profileFileMountOutsideRootsMessage,
4
4
  import { _ as interactiveSessionStatusResponseSchema, d as awaitWithAbort, f as combineAbortSignals, g as interactiveSessionControlValidationResponseSchema, h as interactiveSessionControlReleaseResponseSchema, l as createInteractiveControlHolderId, m as interactiveSessionControlClaimResponseSchema, p as delayUntilAborted } from "./browser-interactive-control-controller-DHx53yre.js";
5
5
  import { n as fetchWithKeepAlive, t as emitTiming } from "./keep-alive-fetch-BBzJDWyt.js";
6
6
  import { s as uploadChunked } from "./chunked-upload-DN2twsUu.js";
7
- import { r as cliAuthReferenceSchema } from "./cli-auth-bundle-hoD3-9Xr.js";
7
+ import { r as cliAuthReferenceSchema } from "./cli-auth-bundle-DiO80j-k.js";
8
8
  import { n as SandboxLines } from "./lines-C5ER4aN_.js";
9
9
  import { z } from "zod";
10
10
  import { AgentExactRunControlRefSchema, AgentInteractiveSessionAttachSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimRequestSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionPromptCommandSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStartSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentInteractiveSessionStopCommandSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, InteractionAcknowledgementSchema, InteractionBindingSchema, InteractionRequestSchema, InteractionResponseCommandSchema, InteractionResponseSchema, PlanContinuationSchema, TerminalInputSchema, TerminalOutputEventSchema, TerminalReplayWindowSchema, TerminalResizeSchema, TerminalSessionRefSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimIsNewer, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionPromptRequestDigest, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentProfileSchema, agentRunCancellationAcknowledgementMatchesRequest, canonicalCandidateDigest, canonicalCandidateJson, exactAgentInteractiveSessionStart, sha256DigestSchema, terminalSessionUsable } from "@tangle-network/agent-interface";
@@ -6238,6 +6238,18 @@ var SandboxSessionAdmissionCapabilities = class extends SandboxProfileCapabiliti
6238
6238
  };
6239
6239
  //#endregion
6240
6240
  //#region src/sandbox-prompt-transport.ts
6241
+ function validatePromptDispatchOptions(sandboxId, options) {
6242
+ if (options?.nativeResume !== void 0) {
6243
+ const resume = options.nativeResume;
6244
+ const validId = (id) => typeof id === "string" && /^[A-Za-z0-9._:-]{1,256}$/u.test(id);
6245
+ if (!options.sessionId || options.lastEventId !== void 0 || resume === null || typeof resume !== "object" || Object.keys(resume).sort().join(",") !== "harness,nativeSessionId,sourceCheckpointId" || !["claude-code", "codex"].includes(resume.harness) || !validId(resume.nativeSessionId) || !validId(resume.sourceCheckpointId)) throw new ValidationError("Native resume requires an exact harness, native session, source checkpoint, and new session dispatch");
6246
+ }
6247
+ if (options?.lastEventId && !options.executionId) throw new ValidationError("lastEventId requires executionId so the SDK can replay the correct execution", { executionId: "Required when lastEventId is set" });
6248
+ const runControlRef = options?.runControlRef ? AgentExactRunControlRefSchema.safeParse(options.runControlRef) : void 0;
6249
+ if (runControlRef && !runControlRef.success) throw new ValidationError("Invalid runControlRef", { runControlRef: runControlRef.error.message });
6250
+ if (runControlRef?.success && (runControlRef.data.environmentId !== sandboxId || runControlRef.data.sessionId !== options?.sessionId || runControlRef.data.executionId !== options?.executionId)) throw new ValidationError("runControlRef does not belong to this sandbox dispatch", { runControlRef: "environmentId, sessionId, and executionId must match the dispatch" });
6251
+ return runControlRef?.success ? runControlRef.data : void 0;
6252
+ }
6241
6253
  var SandboxPromptTransportCapabilities = class extends SandboxSessionAdmissionCapabilities {
6242
6254
  logStreamCheckpoint(checkpoint, data = {}) {
6243
6255
  if (globalThis.process?.env?.TANGLE_SANDBOX_SDK_STREAM_DEBUG !== "1") return;
@@ -6254,15 +6266,7 @@ var SandboxPromptTransportCapabilities = class extends SandboxSessionAdmissionCa
6254
6266
  * callers never see a thrown generator.
6255
6267
  */
6256
6268
  async *streamPromptInner(message, options, internal) {
6257
- if (options?.nativeResume !== void 0) {
6258
- const resume = options.nativeResume;
6259
- const validId = (id) => typeof id === "string" && /^[A-Za-z0-9._:-]{1,256}$/u.test(id);
6260
- if (!options.sessionId || options.lastEventId !== void 0 || resume === null || typeof resume !== "object" || Object.keys(resume).sort().join(",") !== "harness,nativeSessionId,sourceCheckpointId" || !["claude-code", "codex"].includes(resume.harness) || !validId(resume.nativeSessionId) || !validId(resume.sourceCheckpointId)) throw new ValidationError("Native resume requires an exact harness, native session, source checkpoint, and new session dispatch");
6261
- }
6262
- if (options?.lastEventId && !options.executionId) throw new ValidationError("lastEventId requires executionId so the SDK can replay the correct execution", { executionId: "Required when lastEventId is set" });
6263
- const runControlRef = options?.runControlRef ? AgentExactRunControlRefSchema.safeParse(options.runControlRef) : void 0;
6264
- if (runControlRef && !runControlRef.success) throw new ValidationError("Invalid runControlRef", { runControlRef: runControlRef.error.message });
6265
- if (runControlRef?.success && (runControlRef.data.environmentId !== this.id || runControlRef.data.sessionId !== options?.sessionId || runControlRef.data.executionId !== options?.executionId)) throw new ValidationError("runControlRef does not belong to this sandbox dispatch", { runControlRef: "environmentId, sessionId, and executionId must match the dispatch" });
6269
+ const runControlRef = validatePromptDispatchOptions(this.id, options);
6266
6270
  const ttlMs = usableExecutionTtlMs(options?.ttlMs);
6267
6271
  await this.ensureRunning();
6268
6272
  const timeoutMs = typeof options?.timeoutMs === "number" && options.timeoutMs > 0 ? options.timeoutMs : void 0;
@@ -6301,186 +6305,210 @@ var SandboxPromptTransportCapabilities = class extends SandboxSessionAdmissionCa
6301
6305
  format: "sse"
6302
6306
  });
6303
6307
  appendSessionIdQuery(replaySearch, internal?.replaySessionId);
6304
- const requestEndpoint = explicitReplay ? `/agents/run/${encodeURIComponent(options?.executionId ?? "")}/events?${replaySearch}` : "/agents/run/stream";
6305
- let lastEventId = options?.lastEventId;
6306
- let executionId = options?.executionId;
6307
- let sessionId = options?.sessionId;
6308
- let receivedTerminal = false;
6309
- const reconnectWindowMs = resolveReconnectWindowMs(options?.reconnectWindowMs);
6310
- const delivered = new DeliveredEvents(lastEventId);
6311
- let recordedEnd;
6312
- const endFromRecord = (end) => {
6313
- receivedTerminal = true;
6314
- logStreamCheckpoint("terminal_event", {
6315
- eventType: "done",
6316
- synthetic: true,
6317
- reason: "execution_ended_without_terminal_event",
6318
- status: end.status,
6319
- sessionId,
6320
- executionId
6321
- });
6322
- return {
6323
- type: "done",
6324
- data: {
6325
- ...sessionId ? { sessionId } : {},
6326
- ...executionId ? { executionId } : {},
6327
- status: end.status,
6328
- ...end.status === "completed" ? { outcome: { type: "completed" } } : {},
6329
- ...end.code ? { code: end.code } : {},
6330
- ...end.message ? { message: end.message } : {},
6331
- endedWithoutTerminalEvent: true
6332
- }
6333
- };
6308
+ const state = {
6309
+ options,
6310
+ internal,
6311
+ runControlRef,
6312
+ ttlMs,
6313
+ timeoutMs,
6314
+ streamSignal,
6315
+ throwIfTimedOut,
6316
+ reconcileRuntimeRefusal,
6317
+ logStreamCheckpoint,
6318
+ explicitReplay,
6319
+ requestEndpoint: explicitReplay ? `/agents/run/${encodeURIComponent(options?.executionId ?? "")}/events?${replaySearch}` : "/agents/run/stream",
6320
+ traceHeaders: options?.traceId ? { [TRACE_ID_HEADER]: options.traceId } : {},
6321
+ lastEventId: options?.lastEventId,
6322
+ executionId: options?.executionId,
6323
+ sessionId: options?.sessionId,
6324
+ receivedTerminal: false,
6325
+ reconnectWindowMs: resolveReconnectWindowMs(options?.reconnectWindowMs),
6326
+ delivered: new DeliveredEvents(options?.lastEventId),
6327
+ firstSseEventSeen: false,
6328
+ deliveredThisConnection: 0
6334
6329
  };
6335
- let lastReplayStatus;
6336
- let lastExecutionStatus;
6337
- let firstSseEventSeen = false;
6338
- const traceHeaders = options?.traceId ? { [TRACE_ID_HEADER]: options.traceId } : {};
6330
+ const response = await this.openPromptStream(message, state);
6331
+ if (!response.ok) {
6332
+ const body = await response.text();
6333
+ const responseError = parseErrorResponse(response.status, body, {
6334
+ method: state.explicitReplay ? "GET" : "POST",
6335
+ path: `/v1/sandboxes/${encodeURIComponent(this.id)}/runtime${state.requestEndpoint}`
6336
+ }, response.headers);
6337
+ if (!isProfileNotCachedError(responseError)) await state.reconcileRuntimeRefusal(response.status);
6338
+ if (!state.explicitReplay) throw responseError;
6339
+ state.lastReplayStatus = response.status;
6340
+ state.logStreamCheckpoint("replay_response_status", {
6341
+ attempt: 0,
6342
+ status: response.status,
6343
+ ok: false
6344
+ });
6345
+ } else try {
6346
+ yield* this.readPromptStream(response, state, false);
6347
+ } catch (readError) {
6348
+ state.throwIfTimedOut();
6349
+ if (state.receivedTerminal || state.options?.signal?.aborted || state.streamSignal?.aborted) return;
6350
+ state.logStreamCheckpoint("stream_read_failed", { error: readError instanceof Error ? readError.message : String(readError) });
6351
+ console.warn(`[sandbox-sdk] Stream connection broke: ${readError instanceof Error ? readError.message : String(readError)}`);
6352
+ }
6353
+ if (state.receivedTerminal) return;
6354
+ if (state.recordedEnd) {
6355
+ yield this.endPromptStreamFromRecord(state, state.recordedEnd);
6356
+ return;
6357
+ }
6358
+ state.throwIfTimedOut();
6359
+ if (state.options?.signal?.aborted || state.streamSignal?.aborted) return;
6360
+ state.logStreamCheckpoint("stream_drop", {
6361
+ executionId: state.executionId,
6362
+ sessionId: state.sessionId,
6363
+ lastEventId: state.lastEventId,
6364
+ receivedTerminal: state.receivedTerminal
6365
+ });
6366
+ yield* this.rejoinPromptStream(state);
6367
+ }
6368
+ async openPromptStream(message, state) {
6339
6369
  let response;
6340
6370
  try {
6341
- logStreamCheckpoint("runtime_post_start", {
6342
- endpoint: requestEndpoint,
6343
- sessionId: options?.sessionId,
6344
- executionId: options?.executionId,
6345
- hasLastEventId: Boolean(options?.lastEventId),
6346
- detach: options?.detach === true,
6347
- replayOnly: explicitReplay
6371
+ state.logStreamCheckpoint("runtime_post_start", {
6372
+ endpoint: state.requestEndpoint,
6373
+ sessionId: state.options?.sessionId,
6374
+ executionId: state.options?.executionId,
6375
+ hasLastEventId: Boolean(state.options?.lastEventId),
6376
+ detach: state.options?.detach === true,
6377
+ replayOnly: state.explicitReplay
6348
6378
  });
6349
- const request = explicitReplay ? {
6379
+ const request = state.explicitReplay ? {
6350
6380
  method: "GET",
6351
- signal: streamSignal,
6352
- headers: traceHeaders
6381
+ signal: state.streamSignal,
6382
+ headers: state.traceHeaders
6353
6383
  } : {
6354
6384
  method: "POST",
6355
- signal: streamSignal,
6385
+ signal: state.streamSignal,
6356
6386
  headers: {
6357
- ...traceHeaders,
6358
- ...options?.executionId ? { "X-Execution-ID": options.executionId } : {},
6359
- ...options?.detach ? { "x-agent-detach": "true" } : {}
6387
+ ...state.traceHeaders,
6388
+ ...state.options?.executionId ? { "X-Execution-ID": state.options.executionId } : {},
6389
+ ...state.options?.detach ? { "x-agent-detach": "true" } : {}
6360
6390
  },
6361
6391
  body: JSON.stringify({
6362
6392
  id: "default",
6363
- ...options?.sessionId ? { sessionId: options.sessionId } : {},
6364
- ...options?.nativeResume ? { nativeResume: options.nativeResume } : {},
6365
- ...runControlRef?.success ? { runControlRef: runControlRef.data } : {},
6393
+ ...state.options?.sessionId ? { sessionId: state.options.sessionId } : {},
6394
+ ...state.options?.nativeResume ? { nativeResume: state.options.nativeResume } : {},
6395
+ ...state.runControlRef ? { runControlRef: state.runControlRef } : {},
6366
6396
  parts: encodePromptForWire(message),
6367
- turnId: options?.turnId,
6368
- metadata: options?.context,
6369
- requireVisibleAssistantOutput: options?.requireVisibleAssistantOutput,
6370
- ...timeoutMs ? { timeoutMs } : {},
6371
- ...ttlMs !== void 0 ? { ttlMs } : {},
6372
- ...options?.detach ? { detach: true } : {},
6373
- ...options?.expectedPublicProfileRequestDigest ? { expectedPublicProfileRequestDigest: options.expectedPublicProfileRequestDigest } : {},
6374
- ...options?.expectedSecretProfileReceipt ? { expectedSecretProfileReceipt: options.expectedSecretProfileReceipt } : {},
6375
- backend: await this.buildRunBackendBody(options?.backend, (internal?.forceFullProfile ?? false) || options?.expectedSecretProfileReceipt !== void 0, options?.model, streamSignal, options?.expectedSecretProfileReceipt !== void 0)
6397
+ turnId: state.options?.turnId,
6398
+ metadata: state.options?.context,
6399
+ requireVisibleAssistantOutput: state.options?.requireVisibleAssistantOutput,
6400
+ ...state.timeoutMs ? { timeoutMs: state.timeoutMs } : {},
6401
+ ...state.ttlMs !== void 0 ? { ttlMs: state.ttlMs } : {},
6402
+ ...state.options?.detach ? { detach: true } : {},
6403
+ ...state.options?.expectedPublicProfileRequestDigest ? { expectedPublicProfileRequestDigest: state.options.expectedPublicProfileRequestDigest } : {},
6404
+ ...state.options?.expectedSecretProfileReceipt ? { expectedSecretProfileReceipt: state.options.expectedSecretProfileReceipt } : {},
6405
+ backend: await this.buildRunBackendBody(state.options?.backend, (state.internal?.forceFullProfile ?? false) || state.options?.expectedSecretProfileReceipt !== void 0, state.options?.model, state.streamSignal, state.options?.expectedSecretProfileReceipt !== void 0)
6376
6406
  })
6377
6407
  };
6378
6408
  if (typeof request.body === "string" && new TextEncoder().encode(request.body).byteLength > 1048576) throw new ValidationError("Agent run request exceeds the gateway request bound; place large content in resources.files");
6379
- response = await this.runtimeFetch(requestEndpoint, request);
6380
- for (let attempt = 1; !explicitReplay && response.status === 503 && attempt <= MAX_CREDENTIAL_REFUSAL_RETRIES; attempt += 1) {
6409
+ response = await this.runtimeFetch(state.requestEndpoint, request);
6410
+ for (let attempt = 1; !state.explicitReplay && response.status === 503 && attempt <= MAX_CREDENTIAL_REFUSAL_RETRIES; attempt += 1) {
6381
6411
  const body = await response.clone().text();
6382
6412
  const refusal = parseErrorResponse(response.status, body, {
6383
6413
  method: request.method,
6384
- path: `/v1/sandboxes/${encodeURIComponent(this.id)}/runtime${requestEndpoint}`
6414
+ path: `/v1/sandboxes/${encodeURIComponent(this.id)}/runtime${state.requestEndpoint}`
6385
6415
  }, response.headers);
6386
6416
  if (!isRetryableCredentialRefusal(refusal)) break;
6387
- await waitForRetryAfter(refusal.retryAfterMs ?? 1e3, streamSignal);
6388
- response = await this.runtimeFetch(requestEndpoint, request);
6417
+ await waitForRetryAfter(refusal.retryAfterMs ?? 1e3, state.streamSignal);
6418
+ response = await this.runtimeFetch(state.requestEndpoint, request);
6389
6419
  }
6390
- logStreamCheckpoint("runtime_response_headers", {
6420
+ state.logStreamCheckpoint("runtime_response_headers", {
6391
6421
  status: response.status,
6392
6422
  ok: response.ok
6393
6423
  });
6394
6424
  } catch (err) {
6395
- logStreamCheckpoint("runtime_post_failed", { error: err instanceof Error ? err.message : String(err) });
6396
- throwIfTimedOut();
6425
+ state.logStreamCheckpoint("runtime_post_failed", { error: err instanceof Error ? err.message : String(err) });
6426
+ state.throwIfTimedOut();
6397
6427
  throw err;
6398
6428
  }
6399
- if (!response.ok) {
6400
- const body = await response.text();
6401
- const responseError = parseErrorResponse(response.status, body, {
6402
- method: explicitReplay ? "GET" : "POST",
6403
- path: `/v1/sandboxes/${encodeURIComponent(this.id)}/runtime${requestEndpoint}`
6404
- }, response.headers);
6405
- if (!isProfileNotCachedError(responseError)) await reconcileRuntimeRefusal(response.status);
6406
- if (!explicitReplay) throw responseError;
6407
- lastReplayStatus = response.status;
6408
- logStreamCheckpoint("replay_response_status", {
6409
- attempt: 0,
6410
- status: response.status,
6411
- ok: false
6429
+ return response;
6430
+ }
6431
+ endPromptStreamFromRecord(state, end) {
6432
+ state.receivedTerminal = true;
6433
+ state.logStreamCheckpoint("terminal_event", {
6434
+ eventType: "done",
6435
+ synthetic: true,
6436
+ reason: "execution_ended_without_terminal_event",
6437
+ status: end.status,
6438
+ sessionId: state.sessionId,
6439
+ executionId: state.executionId
6440
+ });
6441
+ return {
6442
+ type: "done",
6443
+ data: {
6444
+ ...state.sessionId ? { sessionId: state.sessionId } : {},
6445
+ ...state.executionId ? { executionId: state.executionId } : {},
6446
+ status: end.status,
6447
+ ...end.status === "completed" ? { outcome: { type: "completed" } } : {},
6448
+ ...end.code ? { code: end.code } : {},
6449
+ ...end.message ? { message: end.message } : {},
6450
+ endedWithoutTerminalEvent: true
6451
+ }
6452
+ };
6453
+ }
6454
+ async *readPromptStream(response, state, replay) {
6455
+ let previousId;
6456
+ const firstEvent = (event) => {
6457
+ if (state.firstSseEventSeen) return;
6458
+ state.firstSseEventSeen = true;
6459
+ state.logStreamCheckpoint("first_sse_event", {
6460
+ eventType: event.type,
6461
+ eventId: event.id,
6462
+ ...replay ? { replay: true } : {}
6412
6463
  });
6413
- } else {
6414
- let previousId;
6415
- try {
6416
- for await (const event of this.parseSSEStream(response, streamSignal)) {
6417
- if (event.type === "history.replay.start" || event.type === "history.replay.end") continue;
6418
- if (!firstSseEventSeen) {
6419
- firstSseEventSeen = true;
6420
- logStreamCheckpoint("first_sse_event", {
6421
- eventType: event.type,
6422
- eventId: event.id
6423
- });
6424
- }
6425
- const repeated = isDuplicateDelivery(delivered, event, previousId);
6426
- if (event.id) previousId = event.id;
6427
- if (repeated) continue;
6428
- delivered.record(event.id);
6429
- if (event.id) lastEventId = event.id;
6430
- if (event.type === "execution.started" && event.data?.executionId) {
6431
- executionId = event.data.executionId;
6432
- const eventSessionId = event.data?.sessionId;
6433
- if (sessionId === void 0 && typeof eventSessionId === "string" && eventSessionId.length > 0) sessionId = eventSessionId;
6434
- }
6435
- if (event.type === "done" || event.type === "error") {
6436
- receivedTerminal = true;
6437
- logStreamCheckpoint("terminal_event", {
6438
- eventType: event.type,
6439
- eventId: event.id,
6440
- sessionId,
6441
- executionId
6442
- });
6443
- }
6444
- recordedEnd ??= receivedTerminal ? void 0 : recordedExecutionEnd(event);
6445
- yield event;
6446
- }
6447
- } catch (readError) {
6448
- throwIfTimedOut();
6449
- if (receivedTerminal || options?.signal?.aborted || streamSignal?.aborted) return;
6450
- logStreamCheckpoint("stream_read_failed", { error: readError instanceof Error ? readError.message : String(readError) });
6451
- console.warn(`[sandbox-sdk] Stream connection broke: ${readError instanceof Error ? readError.message : String(readError)}`);
6464
+ };
6465
+ for await (const event of this.parseSSEStream(response, state.streamSignal)) {
6466
+ if (replay) firstEvent(event);
6467
+ if (event.type === "history.replay.start" || event.type === "history.replay.end") continue;
6468
+ if (!replay) firstEvent(event);
6469
+ const repeated = isDuplicateDelivery(state.delivered, event, previousId);
6470
+ if (event.id) previousId = event.id;
6471
+ if (repeated) continue;
6472
+ state.delivered.record(event.id);
6473
+ if (replay) state.deliveredThisConnection += 1;
6474
+ if (event.id) state.lastEventId = event.id;
6475
+ if (event.type === "execution.started") {
6476
+ if (!replay && event.data?.executionId) state.executionId = event.data.executionId;
6477
+ const eventSessionId = event.data?.sessionId;
6478
+ if (state.sessionId === void 0 && (replay || event.data?.executionId) && typeof eventSessionId === "string" && eventSessionId.length > 0) state.sessionId = eventSessionId;
6452
6479
  }
6480
+ if (event.type === "done" || event.type === "error") {
6481
+ state.receivedTerminal = true;
6482
+ state.logStreamCheckpoint("terminal_event", {
6483
+ eventType: event.type,
6484
+ eventId: event.id,
6485
+ ...replay ? { replay: true } : {},
6486
+ sessionId: state.sessionId,
6487
+ executionId: state.executionId
6488
+ });
6489
+ }
6490
+ state.recordedEnd ??= state.receivedTerminal ? void 0 : recordedExecutionEnd(event);
6491
+ yield event;
6453
6492
  }
6454
- if (receivedTerminal) return;
6455
- if (recordedEnd) {
6456
- yield endFromRecord(recordedEnd);
6457
- return;
6458
- }
6459
- throwIfTimedOut();
6460
- if (options?.signal?.aborted || streamSignal?.aborted) return;
6461
- logStreamCheckpoint("stream_drop", {
6462
- executionId,
6463
- sessionId,
6464
- lastEventId,
6465
- receivedTerminal
6466
- });
6467
- if (!executionId) throw new NetworkError("Prompt stream dropped before execution.started; cannot reconnect", {
6493
+ }
6494
+ async *rejoinPromptStream(state) {
6495
+ if (!state.executionId) throw new NetworkError("Prompt stream dropped before execution.started; cannot reconnect", {
6468
6496
  endpoint: "/agents/run/stream",
6469
6497
  origin: "runtime"
6470
6498
  });
6471
- const resumeExecutionId = executionId;
6499
+ const resumeExecutionId = state.executionId;
6472
6500
  const interrupted = (reason, detail, cause) => {
6473
- const replayStatusText = lastReplayStatus !== void 0 ? `; last replay status ${lastReplayStatus}` : "";
6474
- const execStatusText = lastExecutionStatus ? `; last known execution status ${lastExecutionStatus}` : "";
6501
+ const replayStatusText = state.lastReplayStatus !== void 0 ? `; last replay status ${state.lastReplayStatus}` : "";
6502
+ const execStatusText = state.lastExecutionStatus ? `; last known execution status ${state.lastExecutionStatus}` : "";
6475
6503
  console.warn(`[sandbox-sdk] Stopped rejoining execution ${resumeExecutionId}: ${detail}`);
6476
6504
  return new StreamInterruptedError({
6477
6505
  message: `Prompt stream for execution ${resumeExecutionId} ended before a terminal event and could not be rejoined (${detail}); the execution's outcome is unknown${replayStatusText}${execStatusText}`,
6478
6506
  executionId: resumeExecutionId,
6479
- ...sessionId ? { sessionId } : {},
6480
- ...lastEventId ? { lastEventId } : {},
6507
+ ...state.sessionId ? { sessionId: state.sessionId } : {},
6508
+ ...state.lastEventId ? { lastEventId: state.lastEventId } : {},
6481
6509
  reason,
6482
- ...lastReplayStatus !== void 0 ? { lastReplayStatus } : {},
6483
- ...lastExecutionStatus ? { lastExecutionStatus } : {},
6510
+ ...state.lastReplayStatus !== void 0 ? { lastReplayStatus: state.lastReplayStatus } : {},
6511
+ ...state.lastExecutionStatus ? { lastExecutionStatus: state.lastExecutionStatus } : {},
6484
6512
  ...cause !== void 0 ? { cause } : {}
6485
6513
  });
6486
6514
  };
@@ -6488,69 +6516,69 @@ var SandboxPromptTransportCapabilities = class extends SandboxSessionAdmissionCa
6488
6516
  let consecutiveFailures = 0;
6489
6517
  let notFoundSince;
6490
6518
  for (let attempt = 1;; attempt++) {
6491
- throwIfTimedOut();
6492
- if (options?.signal?.aborted || streamSignal?.aborted) return;
6519
+ state.throwIfTimedOut();
6520
+ if (state.options?.signal?.aborted || state.streamSignal?.aborted) return;
6493
6521
  const outageMs = Date.now() - outageStartedAt;
6494
- if (outageMs >= reconnectWindowMs) throw interrupted("reconnect-window-elapsed", `unreachable for ${outageMs}ms of a ${reconnectWindowMs}ms reconnect window`);
6522
+ if (outageMs >= state.reconnectWindowMs) throw interrupted("reconnect-window-elapsed", `unreachable for ${outageMs}ms of a ${state.reconnectWindowMs}ms reconnect window`);
6495
6523
  consecutiveFailures += 1;
6496
- const delayMs = Math.min(reconnectDelayMs(consecutiveFailures), reconnectWindowMs - outageMs);
6497
- console.warn(`[sandbox-sdk] Stream dropped without terminal event, reconnecting (attempt ${attempt}; unreachable ${Math.round(outageMs / 1e3)}s of ${Math.round(reconnectWindowMs / 1e3)}s)`);
6498
- logStreamCheckpoint("reconnect_attempt_start", {
6524
+ const delayMs = Math.min(reconnectDelayMs(consecutiveFailures), state.reconnectWindowMs - outageMs);
6525
+ console.warn(`[sandbox-sdk] Stream dropped without terminal event, reconnecting (attempt ${attempt}; unreachable ${Math.round(outageMs / 1e3)}s of ${Math.round(state.reconnectWindowMs / 1e3)}s)`);
6526
+ state.logStreamCheckpoint("reconnect_attempt_start", {
6499
6527
  attempt,
6500
- executionId,
6501
- sessionId,
6502
- lastEventId,
6528
+ executionId: state.executionId,
6529
+ sessionId: state.sessionId,
6530
+ lastEventId: state.lastEventId,
6503
6531
  outageMs,
6504
6532
  delayMs
6505
6533
  });
6506
- await waitForReconnect(delayMs, streamSignal);
6507
- throwIfTimedOut();
6508
- if (options?.signal?.aborted || streamSignal?.aborted) return;
6534
+ await waitForReconnect(delayMs, state.streamSignal);
6535
+ state.throwIfTimedOut();
6536
+ if (state.options?.signal?.aborted || state.streamSignal?.aborted) return;
6509
6537
  let connectedAt;
6510
- let deliveredThisConnection = 0;
6538
+ state.deliveredThisConnection = 0;
6511
6539
  try {
6512
6540
  const queryParams = new URLSearchParams();
6513
- if (lastEventId) queryParams.set("lastEventId", lastEventId);
6541
+ if (state.lastEventId) queryParams.set("lastEventId", state.lastEventId);
6514
6542
  queryParams.set("format", "sse");
6515
- appendSessionIdQuery(queryParams, internal?.replaySessionId);
6543
+ appendSessionIdQuery(queryParams, state.internal?.replaySessionId);
6516
6544
  const replayResponse = await this.runtimeFetch(`/agents/run/${encodeURIComponent(resumeExecutionId)}/events?${queryParams}`, {
6517
6545
  method: "GET",
6518
- signal: streamSignal,
6519
- headers: traceHeaders
6546
+ signal: state.streamSignal,
6547
+ headers: state.traceHeaders
6520
6548
  });
6521
- logStreamCheckpoint("replay_response_status", {
6549
+ state.logStreamCheckpoint("replay_response_status", {
6522
6550
  attempt,
6523
6551
  status: replayResponse.status,
6524
6552
  ok: replayResponse.ok
6525
6553
  });
6526
6554
  if (!replayResponse.ok) {
6527
- lastReplayStatus = replayResponse.status;
6555
+ state.lastReplayStatus = replayResponse.status;
6528
6556
  await replayResponse.body?.cancel().catch(() => void 0);
6529
- await reconcileRuntimeRefusal(replayResponse.status);
6557
+ await state.reconcileRuntimeRefusal(replayResponse.status);
6530
6558
  console.warn(`[sandbox-sdk] Replay endpoint returned ${replayResponse.status}, attempt ${attempt}`);
6531
6559
  if (replayResponse.status !== 404) {
6532
6560
  notFoundSince = void 0;
6533
6561
  continue;
6534
6562
  }
6535
6563
  notFoundSince ??= Date.now();
6536
- if (sessionId) try {
6537
- const info = await this._sessionStatus(sessionId);
6564
+ if (state.sessionId) try {
6565
+ const info = await this._sessionStatus(state.sessionId);
6538
6566
  if (info) {
6539
- lastExecutionStatus = info.status;
6567
+ state.lastExecutionStatus = info.status;
6540
6568
  if (info.status === "completed" || info.status === "failed" || info.status === "cancelled") {
6541
- console.warn(`[sandbox-sdk] Replay 404 but session ${sessionId} is terminal (${info.status}); ending stream gracefully`);
6542
- logStreamCheckpoint("terminal_event", {
6569
+ console.warn(`[sandbox-sdk] Replay 404 but session ${state.sessionId} is terminal (${info.status}); ending stream gracefully`);
6570
+ state.logStreamCheckpoint("terminal_event", {
6543
6571
  eventType: "done",
6544
6572
  synthetic: true,
6545
6573
  reason: "replay_unavailable_terminal_session",
6546
- sessionId,
6547
- executionId
6574
+ sessionId: state.sessionId,
6575
+ executionId: state.executionId
6548
6576
  });
6549
6577
  yield {
6550
6578
  type: "done",
6551
6579
  data: {
6552
- sessionId,
6553
- executionId,
6580
+ sessionId: state.sessionId,
6581
+ executionId: state.executionId,
6554
6582
  status: info.status,
6555
6583
  ...info.status === "completed" ? { outcome: { type: "completed" } } : {},
6556
6584
  replayUnavailable: true
@@ -6567,64 +6595,33 @@ var SandboxPromptTransportCapabilities = class extends SandboxSessionAdmissionCa
6567
6595
  }
6568
6596
  notFoundSince = void 0;
6569
6597
  connectedAt = Date.now();
6570
- let previousId;
6571
- for await (const event of this.parseSSEStream(replayResponse, streamSignal)) {
6572
- if (!firstSseEventSeen) {
6573
- firstSseEventSeen = true;
6574
- logStreamCheckpoint("first_sse_event", {
6575
- eventType: event.type,
6576
- eventId: event.id,
6577
- replay: true
6578
- });
6579
- }
6580
- if (event.type === "history.replay.start" || event.type === "history.replay.end") continue;
6581
- const repeated = isDuplicateDelivery(delivered, event, previousId);
6582
- if (event.id) previousId = event.id;
6583
- if (repeated) continue;
6584
- delivered.record(event.id);
6585
- deliveredThisConnection += 1;
6586
- if (event.id) lastEventId = event.id;
6587
- const eventSessionId = event.data?.sessionId;
6588
- if (sessionId === void 0 && event.type === "execution.started" && typeof eventSessionId === "string" && eventSessionId.length > 0) sessionId = eventSessionId;
6589
- if (event.type === "done" || event.type === "error") {
6590
- receivedTerminal = true;
6591
- logStreamCheckpoint("terminal_event", {
6592
- eventType: event.type,
6593
- eventId: event.id,
6594
- replay: true,
6595
- sessionId,
6596
- executionId
6597
- });
6598
- }
6599
- recordedEnd ??= receivedTerminal ? void 0 : recordedExecutionEnd(event);
6600
- yield event;
6601
- }
6602
- if (!receivedTerminal && recordedEnd) {
6603
- yield endFromRecord(recordedEnd);
6598
+ yield* this.readPromptStream(replayResponse, state, true);
6599
+ if (!state.receivedTerminal && state.recordedEnd) {
6600
+ yield this.endPromptStreamFromRecord(state, state.recordedEnd);
6604
6601
  return;
6605
6602
  }
6606
- if (receivedTerminal) {
6607
- logStreamCheckpoint("reconnect_attempt_end", {
6603
+ if (state.receivedTerminal) {
6604
+ state.logStreamCheckpoint("reconnect_attempt_end", {
6608
6605
  attempt,
6609
6606
  status: "terminal_received"
6610
6607
  });
6611
6608
  return;
6612
6609
  }
6613
- throwIfTimedOut();
6614
- if (options?.signal?.aborted || streamSignal?.aborted) return;
6610
+ state.throwIfTimedOut();
6611
+ if (state.options?.signal?.aborted || state.streamSignal?.aborted) return;
6615
6612
  } catch (err) {
6616
- throwIfTimedOut();
6613
+ state.throwIfTimedOut();
6617
6614
  if (err instanceof StreamInterruptedError) throw err;
6618
- if (options?.signal?.aborted || streamSignal?.aborted) return;
6615
+ if (state.options?.signal?.aborted || state.streamSignal?.aborted) return;
6619
6616
  if (err instanceof StateError && isFinalSandboxStatus(this.status)) throw interrupted("sandbox-not-running", `the sandbox is ${this.status}`, err);
6620
- logStreamCheckpoint("reconnect_attempt_end", {
6617
+ state.logStreamCheckpoint("reconnect_attempt_end", {
6621
6618
  attempt,
6622
6619
  status: "failed",
6623
6620
  error: err instanceof Error ? err.message : String(err)
6624
6621
  });
6625
6622
  console.warn(`[sandbox-sdk] Reconnection attempt ${attempt} failed: ${err instanceof Error ? err.message : String(err)}`);
6626
6623
  }
6627
- if (connectedAt !== void 0 && (deliveredThisConnection > 0 || Date.now() - connectedAt >= 3e4)) {
6624
+ if (connectedAt !== void 0 && (state.deliveredThisConnection > 0 || Date.now() - connectedAt >= 3e4)) {
6628
6625
  outageStartedAt = Date.now();
6629
6626
  consecutiveFailures = 0;
6630
6627
  }
@@ -1,2 +1,2 @@
1
- import { C as JsonResponseParamTypes, E as SandboxIdParamTypes, S as JOB_SANDBOX_DELETE, T as SandboxCreateResponseParamTypes, _ as TANGLE_JOBS_CONTRACT, a as fetchQuote, b as AgentSandboxBlueprintAbi, c as parseQuoteResponse, d as OperatorSession, f as OperatorSessionError, g as TANGLE_CHAIN_ID, h as TangleSandboxClient, i as SignedQuote, l as validateQuote, m as SignMessage, n as QuoteDomain, o as inputsHashOf, p as OperatorSessionToken, r as QuoteError, s as jobQuoteDigest, t as JobQuoteDetails, u as OperatorChallenge, v as TangleSandboxClientConfig, w as SandboxCreateParamTypes, x as JOB_SANDBOX_CREATE, y as ITangleJobsAbi } from "../index-D7VkrwXt.js";
1
+ import { C as JsonResponseParamTypes, E as SandboxIdParamTypes, S as JOB_SANDBOX_DELETE, T as SandboxCreateResponseParamTypes, _ as TANGLE_JOBS_CONTRACT, a as fetchQuote, b as AgentSandboxBlueprintAbi, c as parseQuoteResponse, d as OperatorSession, f as OperatorSessionError, g as TANGLE_CHAIN_ID, h as TangleSandboxClient, i as SignedQuote, l as validateQuote, m as SignMessage, n as QuoteDomain, o as inputsHashOf, p as OperatorSessionToken, r as QuoteError, s as jobQuoteDigest, t as JobQuoteDetails, u as OperatorChallenge, v as TangleSandboxClientConfig, w as SandboxCreateParamTypes, x as JOB_SANDBOX_CREATE, y as ITangleJobsAbi } from "../index-iYdJi4O8.js";
2
2
  export { AgentSandboxBlueprintAbi, ITangleJobsAbi, JOB_SANDBOX_CREATE, JOB_SANDBOX_DELETE, JobQuoteDetails, JsonResponseParamTypes, OperatorChallenge, OperatorSession, OperatorSessionError, OperatorSessionToken, QuoteDomain, QuoteError, SandboxCreateParamTypes, SandboxCreateResponseParamTypes, SandboxIdParamTypes, SignMessage, SignedQuote, TANGLE_CHAIN_ID, TANGLE_JOBS_CONTRACT, TangleSandboxClient, TangleSandboxClientConfig, fetchQuote, inputsHashOf, jobQuoteDigest, parseQuoteResponse, validateQuote };
@@ -1,2 +1,2 @@
1
- import { _ as SandboxCreateParamTypes, a as parseQuoteResponse, c as OperatorSession, d as TANGLE_JOBS_CONTRACT, f as ITangleJobsAbi, g as JsonResponseParamTypes, h as JOB_SANDBOX_DELETE, i as jobQuoteDigest, l as OperatorSessionError, m as JOB_SANDBOX_CREATE, n as fetchQuote, o as validateQuote, p as AgentSandboxBlueprintAbi, r as inputsHashOf, s as TangleSandboxClient, t as QuoteError, u as TANGLE_CHAIN_ID, v as SandboxCreateResponseParamTypes, y as SandboxIdParamTypes } from "../tangle-DXYPV6rH.js";
1
+ import { _ as SandboxCreateParamTypes, a as parseQuoteResponse, c as OperatorSession, d as TANGLE_JOBS_CONTRACT, f as ITangleJobsAbi, g as JsonResponseParamTypes, h as JOB_SANDBOX_DELETE, i as jobQuoteDigest, l as OperatorSessionError, m as JOB_SANDBOX_CREATE, n as fetchQuote, o as validateQuote, p as AgentSandboxBlueprintAbi, r as inputsHashOf, s as TangleSandboxClient, t as QuoteError, u as TANGLE_CHAIN_ID, v as SandboxCreateResponseParamTypes, y as SandboxIdParamTypes } from "../tangle-DA1aBXXG.js";
2
2
  export { AgentSandboxBlueprintAbi, ITangleJobsAbi, JOB_SANDBOX_CREATE, JOB_SANDBOX_DELETE, JsonResponseParamTypes, OperatorSession, OperatorSessionError, QuoteError, SandboxCreateParamTypes, SandboxCreateResponseParamTypes, SandboxIdParamTypes, TANGLE_CHAIN_ID, TANGLE_JOBS_CONTRACT, TangleSandboxClient, fetchQuote, inputsHashOf, jobQuoteDigest, parseQuoteResponse, validateQuote };
@@ -1,5 +1,5 @@
1
1
  import { i as readResponseJson } from "./errors-BfbOP_rx.js";
2
- import { n as createSandboxInstanceFromResponse } from "./sandbox-dxjJMlUt.js";
2
+ import { n as createSandboxInstanceFromResponse } from "./sandbox-CICD7KcJ.js";
3
3
  import { _ as rotlBH, a as anumber, b as rotlSL, d as createXOFer, g as u32, h as toBytes$1, l as createHasher, m as swap32IfBE, n as abytes, o as aoutput, r as aexists, s as clean, t as Hash, v as rotlBL, x as split, y as rotlSH } from "./utils-BGvM02yJ.js";
4
4
  //#region ../../../packages/runtime-contracts/dist/tangle-blueprint-abi.js
5
5
  /**