@tangle-network/sandbox 0.16.0 → 0.17.2-develop.20260803000136.6dc5f0b

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.
@@ -1,4 +1,4 @@
1
- import { a as uploadChunked, c as combineAbortSignals, d as applyRequestedModel, f as assertCurrentBackendType, i as sessionHeaders, l as encodePromptForWire, n as normalizeSessionInfo, p as normalizeRuntimeBackendConfig, r as appendSessionIdQuery, t as SandboxRuntimeApi } from "./runtime-api-Bd9NAChb.js";
1
+ import { a as uploadChunked, c as combineAbortSignals, d as applyRequestedModel, f as assertCurrentBackendType, i as sessionHeaders, l as encodePromptForWire, n as normalizeSessionInfo, p as normalizeRuntimeBackendConfig, r as appendSessionIdQuery, t as SandboxRuntimeApi } from "./runtime-api-BRQkJnW4.js";
2
2
  import { a as NetworkError, c as QuotaError, d as StateError, f as TimeoutError, l as SandboxError, m as parseErrorResponse, n as CapabilityError, o as NotFoundError, p as ValidationError, t as AuthError, u as ServerError } from "./errors-Bf-A-4SA.js";
3
3
  import { readTokenCostUsd, readTokenUsage } from "@tangle-network/agent-core";
4
4
  //#region src/lib/sse-parser.ts
@@ -512,8 +512,9 @@ var InteractiveSessionHandle = class {
512
512
  * routes: `status` reads `GET /agents/sessions/{id}`, `events` opens an
513
513
  * SSE stream against `/agents/events?sessionId=...` (with `since` for
514
514
  * replay), `prompt` continues the session via `/agents/run/stream`,
515
- * `interrupt` calls `/agents/sessions/{id}/abort`. No new sidecar surface
516
- * is required — every endpoint already exists.
515
+ * `interrupt` calls `/agents/sessions/{id}/abort` by default or the
516
+ * execution-scoped cancel route when an execution id is supplied. No new
517
+ * sidecar surface is required — every endpoint already exists.
517
518
  *
518
519
  * Construction is private to the SDK: get a Session from
519
520
  * `box.session(id)` (lazy reference, no network) or `box.sessions(...)`
@@ -555,16 +556,15 @@ var SandboxSession = class SandboxSession {
555
556
  return this.box._sessionEvents(this.id, opts);
556
557
  }
557
558
  /**
558
- * Await the session's terminal result. Reads status and drains events
559
- * from the latest execution until the session reaches a terminal state,
560
- * then returns the aggregated `PromptResult`. Event replay makes this safe
561
- * to call after the execution has already finished.
559
+ * Await a terminal result. With `executionId`, drains only that execution;
560
+ * without it, reads status and selects the latest execution. Event replay
561
+ * makes either form safe after the execution has already finished.
562
562
  *
563
563
  * Use this to wait for a session that was started by another caller
564
564
  * (e.g. `dispatchPrompt`).
565
565
  */
566
- async result() {
567
- return this.box._sessionResult(this.id);
566
+ async result(options) {
567
+ return options ? this.box._sessionResult(this.id, options) : this.box._sessionResult(this.id);
568
568
  }
569
569
  /**
570
570
  * List persisted messages for this session, including in-flight assistant
@@ -630,12 +630,13 @@ var SandboxSession = class SandboxSession {
630
630
  return this.box._respondToPermission(this.id, permissionID, options);
631
631
  }
632
632
  /**
633
- * Interrupt the session's current execution without deleting it. Returns
634
- * `{ cancelled: false }` when nothing was running — the no-op is reported
635
- * explicitly rather than masked as success.
633
+ * Interrupt an execution without deleting the session. Pass `executionId`
634
+ * to make the cancellation exact: a newer run on the same session is never
635
+ * touched. Without it, the current execution is selected. Returns
636
+ * `{ cancelled: false }` when the selected execution is not running.
636
637
  */
637
- async interrupt() {
638
- return this.box._interrupt(this.id);
638
+ async interrupt(options) {
639
+ return options ? this.box._interrupt(this.id, options) : this.box._interrupt(this.id);
639
640
  }
640
641
  /**
641
642
  * Answer a question the agent asked via a question tool invocation. `answers`
@@ -2164,6 +2165,7 @@ var SandboxInstance = class SandboxInstance {
2164
2165
  let responseText;
2165
2166
  let runError;
2166
2167
  let runErrorCode;
2168
+ let executionId = options?.lastEventId ? options.executionId : void 0;
2167
2169
  let traceId;
2168
2170
  let usage;
2169
2171
  let costUsd;
@@ -2179,6 +2181,8 @@ var SandboxInstance = class SandboxInstance {
2179
2181
  signal
2180
2182
  })) {
2181
2183
  responseText = applySandboxEventText(responseText, event);
2184
+ const eventExecutionId = event.data.executionId;
2185
+ if (typeof eventExecutionId === "string" && eventExecutionId.length > 0) executionId = eventExecutionId;
2182
2186
  if (event.type === "result" || event.type === "done") {
2183
2187
  usage = readTokenUsage(event.data) ?? usage;
2184
2188
  costUsd = readTokenCostUsd(event.data) ?? costUsd;
@@ -2206,6 +2210,7 @@ var SandboxInstance = class SandboxInstance {
2206
2210
  return {
2207
2211
  success: outcome.success,
2208
2212
  status: outcome.status,
2213
+ ...executionId ? { executionId } : {},
2209
2214
  response: responseText,
2210
2215
  error: outcome.error,
2211
2216
  errorCode: outcome.errorCode,
@@ -2222,6 +2227,7 @@ var SandboxInstance = class SandboxInstance {
2222
2227
  return {
2223
2228
  success: false,
2224
2229
  status: "failed",
2230
+ ...executionId ? { executionId } : {},
2225
2231
  error: err instanceof Error ? err.message : String(err),
2226
2232
  durationMs: Date.now() - startTime
2227
2233
  };
@@ -2323,7 +2329,7 @@ var SandboxInstance = class SandboxInstance {
2323
2329
  const isCallerAbort = () => options?.signal?.aborted === true;
2324
2330
  let receivedTerminal = false;
2325
2331
  let sessionId = options?.sessionId;
2326
- let executionId = options?.executionId;
2332
+ let executionId = options?.lastEventId ? options.executionId : void 0;
2327
2333
  let profileResendAttempted = false;
2328
2334
  try {
2329
2335
  for (;;) {
@@ -5118,14 +5124,14 @@ var SandboxInstance = class SandboxInstance {
5118
5124
  * already in flight or already finished — never on the mere existence
5119
5125
  * of a session with the same id:
5120
5126
  *
5121
- * 1. The session is in flight — `running`, or `queued` with a
5122
- * `latestExecutionId` — → a second dispatch would run two agents
5123
- * against one session, so return the live status with
5124
- * `dispatched: false`.
5125
- * 2. `opts.turnId` is set and the completed-turn cache has it → the
5127
+ * 1. `opts.turnId` is set and the completed-turn cache has it → the
5126
5128
  * turn already finished; return `dispatched: false`. This is the
5127
5129
  * only durable idempotency key, and it outlives the session (the
5128
5130
  * cache survives session eviction, see `findCompletedTurn`).
5131
+ * 2. Otherwise, the session is in flight — `running`, or `queued` with a
5132
+ * `latestExecutionId` — → a second dispatch would run two agents
5133
+ * against one session, so return the live status with
5134
+ * `dispatched: false`.
5129
5135
  *
5130
5136
  * Anything else dispatches. Two cases in particular:
5131
5137
  *
@@ -5149,17 +5155,26 @@ var SandboxInstance = class SandboxInstance {
5149
5155
  let existing = null;
5150
5156
  if (opts?.sessionId) {
5151
5157
  existing = await this._sessionStatus(opts.sessionId);
5152
- if (existing && isSessionInFlight(existing)) return {
5153
- sessionId: existing.id,
5154
- status: existing.status,
5155
- alreadyExisted: true,
5156
- dispatched: false
5157
- };
5158
5158
  if (opts.turnId) {
5159
- if (await this.findCompletedTurn(opts.turnId, { sessionId: opts.sessionId })) return {
5160
- sessionId: existing?.id ?? opts.sessionId,
5161
- status: existing?.status ?? "completed",
5162
- alreadyExisted: existing !== null,
5159
+ const cached = await this.findCompletedTurn(opts.turnId, { sessionId: opts.sessionId });
5160
+ if (cached) {
5161
+ const cachedExecutionId = typeof cached.result.executionId === "string" && cached.result.executionId.length > 0 ? cached.result.executionId : void 0;
5162
+ return {
5163
+ sessionId: existing?.id ?? opts.sessionId,
5164
+ ...cachedExecutionId ? { executionId: cachedExecutionId } : {},
5165
+ status: existing?.status ?? "completed",
5166
+ alreadyExisted: existing !== null,
5167
+ dispatched: false
5168
+ };
5169
+ }
5170
+ }
5171
+ if (existing && isSessionInFlight(existing)) {
5172
+ const existingExecutionId = existing.activeExecutionId ?? existing.latestExecutionId;
5173
+ return {
5174
+ sessionId: existing.id,
5175
+ ...existingExecutionId ? { executionId: existingExecutionId } : {},
5176
+ status: existing.status,
5177
+ alreadyExisted: true,
5163
5178
  dispatched: false
5164
5179
  };
5165
5180
  }
@@ -5171,20 +5186,29 @@ var SandboxInstance = class SandboxInstance {
5171
5186
  signal: ctrl.signal
5172
5187
  });
5173
5188
  let resolvedSessionId = opts?.sessionId;
5189
+ let resolvedExecutionId;
5190
+ let admissionObserved = false;
5191
+ let dispatchError;
5174
5192
  try {
5175
5193
  for await (const event of stream) {
5176
- const id = event.data?.sessionId;
5177
- if (typeof id === "string" && id.length > 0) {
5178
- resolvedSessionId = id;
5179
- break;
5194
+ const data = event.data;
5195
+ if (event.type === "error") dispatchError = typeof data?.message === "string" ? data.message : "sandbox rejected the prompt before admission";
5196
+ if (event.type === "execution.started") {
5197
+ const id = data?.sessionId;
5198
+ const executionId = data?.executionId;
5199
+ if (typeof executionId === "string" && executionId.length > 0) resolvedExecutionId = executionId;
5200
+ if (typeof id === "string" && id.length > 0) resolvedSessionId = id;
5201
+ admissionObserved = Boolean(resolvedSessionId && resolvedExecutionId);
5180
5202
  }
5203
+ if (admissionObserved || event.type === "result" || event.type === "done") break;
5181
5204
  }
5182
5205
  } finally {
5183
5206
  ctrl.abort();
5184
5207
  }
5185
- if (!resolvedSessionId) throw new ServerError("dispatchPrompt did not receive a session id from the sandbox");
5208
+ if (!admissionObserved || !resolvedSessionId || !resolvedExecutionId) throw new ServerError(dispatchError ?? "dispatchPrompt did not receive an execution admission from the sandbox");
5186
5209
  return {
5187
5210
  sessionId: resolvedSessionId,
5211
+ ...resolvedExecutionId ? { executionId: resolvedExecutionId } : {},
5188
5212
  status: "running",
5189
5213
  alreadyExisted: existing !== null,
5190
5214
  dispatched: true
@@ -5304,7 +5328,7 @@ var SandboxInstance = class SandboxInstance {
5304
5328
  const startedAt = info.startedAt ?? info.createdAt;
5305
5329
  const elapsedMs = startedAt ? Date.now() - startedAt.getTime() : void 0;
5306
5330
  if (opts.wallCapMs !== void 0 && elapsedMs !== void 0 && elapsedMs > opts.wallCapMs) {
5307
- await this._interrupt(opts.sessionId);
5331
+ await this._interrupt(opts.sessionId, info.activeExecutionId ? { executionId: info.activeExecutionId } : void 0);
5308
5332
  return {
5309
5333
  state: "failed",
5310
5334
  error: `session ${opts.sessionId} exceeded the ${opts.wallCapMs}ms wall-clock cap and was cancelled`
@@ -5321,7 +5345,7 @@ var SandboxInstance = class SandboxInstance {
5321
5345
  state: "failed",
5322
5346
  error: `session ${opts.sessionId} ${info.status}: no execution result is available`
5323
5347
  };
5324
- const result = await this._sessionResult(opts.sessionId, info);
5348
+ const result = await this._sessionResult(opts.sessionId, { executionId: info.latestExecutionId }, info);
5325
5349
  const settled = settleTurnDrive({ ...result });
5326
5350
  if (settled.state === "awaiting_plan_decision") return settled;
5327
5351
  if (!result.success) return {
@@ -5398,18 +5422,42 @@ var SandboxInstance = class SandboxInstance {
5398
5422
  if ((stopOnTurnTerminal || opts?.executionId !== void 0) && turnTerminal) return;
5399
5423
  }
5400
5424
  }
5425
+ /** Replay one execution without subscribing to other runs on its session. */
5426
+ async *_executionEvents(sessionId, executionId) {
5427
+ await this.ensureRunning();
5428
+ const search = new URLSearchParams({
5429
+ lastEventId: "0",
5430
+ format: "sse",
5431
+ sessionId
5432
+ });
5433
+ const response = await this.runtimeFetch(`/agents/run/${encodeURIComponent(executionId)}/events?${search.toString()}`);
5434
+ if (!response.ok) {
5435
+ const body = await response.text();
5436
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
5437
+ }
5438
+ for await (const event of this.parseSSEStream(response)) {
5439
+ yield event;
5440
+ if (event.type === "result" || event.type === "done" || event.type === "error") return;
5441
+ }
5442
+ }
5401
5443
  /** @internal — invoked by SandboxSession.result(). */
5402
- async _sessionResult(id, knownSession) {
5444
+ async _sessionResult(id, options, knownSession) {
5445
+ if (options?.executionId !== void 0 && !options.executionId) throw new ValidationError("executionId must not be empty", { executionId: "Expected a non-empty runtime execution id" });
5403
5446
  const startTime = Date.now();
5404
- const session = knownSession ?? await this._sessionStatus(id);
5405
- if (!session) throw new NotFoundError("Session", id, {
5406
- origin: "runtime",
5407
- endpoint: `/agents/sessions/${encodeURIComponent(id)}`
5408
- });
5409
- if (!session.latestExecutionId) throw new StateError(`Session ${id} has no execution result to await`, session.status, "session with an admitted execution", {
5410
- origin: "runtime",
5411
- endpoint: `/agents/sessions/${encodeURIComponent(id)}`
5412
- }, "SESSION_EXECUTION_MISSING");
5447
+ let executionId = options?.executionId;
5448
+ if (!executionId) {
5449
+ const session = knownSession ?? await this._sessionStatus(id);
5450
+ if (!session) throw new NotFoundError("Session", id, {
5451
+ origin: "runtime",
5452
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}`
5453
+ });
5454
+ if (!session.latestExecutionId) throw new StateError(`Session ${id} has no execution result to await`, session.status, "session with an admitted execution", {
5455
+ origin: "runtime",
5456
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}`
5457
+ }, "SESSION_EXECUTION_MISSING");
5458
+ executionId = session.latestExecutionId;
5459
+ }
5460
+ let resultExecutionId = executionId;
5413
5461
  let response;
5414
5462
  let runError;
5415
5463
  let runErrorCode;
@@ -5420,13 +5468,15 @@ var SandboxInstance = class SandboxInstance {
5420
5468
  let question;
5421
5469
  let plan;
5422
5470
  let terminalReached = false;
5423
- for await (const event of this._sessionEvents(id, {
5471
+ const events = options?.executionId ? this._executionEvents(id, executionId) : this._sessionEvents(id, {
5424
5472
  since: "0",
5425
- executionId: session.latestExecutionId
5426
- }, true)) {
5473
+ executionId
5474
+ }, true);
5475
+ for await (const event of events) {
5427
5476
  response = applySandboxEventText(response, event);
5428
5477
  if (event.type === "result" || event.type === "done") {
5429
5478
  const data = event.data;
5479
+ if (typeof data.executionId === "string" && data.executionId) resultExecutionId = data.executionId;
5430
5480
  usage = readTokenUsage(data) ?? usage;
5431
5481
  costUsd = readTokenCostUsd(data) ?? costUsd;
5432
5482
  }
@@ -5460,6 +5510,7 @@ var SandboxInstance = class SandboxInstance {
5460
5510
  return {
5461
5511
  success: outcome.success,
5462
5512
  status: outcome.status,
5513
+ executionId: resultExecutionId,
5463
5514
  response,
5464
5515
  error: outcome.error,
5465
5516
  errorCode: outcome.errorCode,
@@ -5630,15 +5681,24 @@ var SandboxInstance = class SandboxInstance {
5630
5681
  }
5631
5682
  }
5632
5683
  /** @internal — invoked by SandboxSession.interrupt(). */
5633
- async _interrupt(id) {
5684
+ async _interrupt(id, options) {
5685
+ if (options?.executionId !== void 0 && !options.executionId) throw new ValidationError("executionId must not be empty", { executionId: "Expected a non-empty runtime execution id" });
5634
5686
  await this.ensureRunning();
5635
- const response = await this.runtimeFetch(`/agents/sessions/${encodeURIComponent(id)}/abort`, { method: "POST" });
5687
+ const response = options?.executionId ? await this.runtimeFetch("/agents/run/cancel", {
5688
+ method: "POST",
5689
+ headers: { "content-type": "application/json" },
5690
+ body: JSON.stringify({
5691
+ executionId: options.executionId,
5692
+ sessionId: id
5693
+ })
5694
+ }) : await this.runtimeFetch(`/agents/sessions/${encodeURIComponent(id)}/abort`, { method: "POST" });
5636
5695
  if (response.status === 404) return { cancelled: false };
5637
5696
  if (!response.ok) {
5638
5697
  const body = await response.text();
5639
5698
  throw parseErrorResponse(response.status, body, void 0, response.headers);
5640
5699
  }
5641
- return { cancelled: (await response.json()).data?.cancelled === true };
5700
+ const json = await response.json();
5701
+ return { cancelled: options?.executionId ? json.success === true : json.data?.cancelled === true };
5642
5702
  }
5643
5703
  /**
5644
5704
  * @internal — invoked by SandboxSession.answer(). Resolves the session's
@@ -1,2 +1,2 @@
1
- import { a as TANGLE_JOBS_CONTRACT, c as AgentSandboxBlueprintAbi, d as SandboxCreateParamTypes, f as SandboxCreateResponseParamTypes, i as TANGLE_CHAIN_ID, l as ITangleJobsAbi, n as JOB_SANDBOX_CREATE, o as TANGLE_MAINNET_RPC, p as SandboxIdParamTypes, r as JOB_SANDBOX_DELETE, s as TangleSandboxClientConfig, t as TangleSandboxClient, u as JsonResponseParamTypes } from "../index-C89k_hW1.js";
1
+ import { a as TANGLE_JOBS_CONTRACT, c as AgentSandboxBlueprintAbi, d as SandboxCreateParamTypes, f as SandboxCreateResponseParamTypes, i as TANGLE_CHAIN_ID, l as ITangleJobsAbi, n as JOB_SANDBOX_CREATE, o as TANGLE_MAINNET_RPC, p as SandboxIdParamTypes, r as JOB_SANDBOX_DELETE, s as TangleSandboxClientConfig, t as TangleSandboxClient, u as JsonResponseParamTypes } from "../index-DXwZxrlU.js";
2
2
  export { AgentSandboxBlueprintAbi, ITangleJobsAbi, JOB_SANDBOX_CREATE, JOB_SANDBOX_DELETE, JsonResponseParamTypes, SandboxCreateParamTypes, SandboxCreateResponseParamTypes, SandboxIdParamTypes, TANGLE_CHAIN_ID, TANGLE_JOBS_CONTRACT, TANGLE_MAINNET_RPC, TangleSandboxClient, TangleSandboxClientConfig };
@@ -1,2 +1,2 @@
1
- import { a as TANGLE_JOBS_CONTRACT, c as ITangleJobsAbi, d as SandboxCreateResponseParamTypes, f as SandboxIdParamTypes, i as TANGLE_CHAIN_ID, l as JsonResponseParamTypes, n as JOB_SANDBOX_CREATE, o as TANGLE_MAINNET_RPC, r as JOB_SANDBOX_DELETE, s as AgentSandboxBlueprintAbi, t as TangleSandboxClient, u as SandboxCreateParamTypes } from "../tangle-Cxe2HYQb.js";
1
+ import { a as TANGLE_JOBS_CONTRACT, c as ITangleJobsAbi, d as SandboxCreateResponseParamTypes, f as SandboxIdParamTypes, i as TANGLE_CHAIN_ID, l as JsonResponseParamTypes, n as JOB_SANDBOX_CREATE, o as TANGLE_MAINNET_RPC, r as JOB_SANDBOX_DELETE, s as AgentSandboxBlueprintAbi, t as TangleSandboxClient, u as SandboxCreateParamTypes } from "../tangle-Bbf2QqDC.js";
2
2
  export { AgentSandboxBlueprintAbi, ITangleJobsAbi, JOB_SANDBOX_CREATE, JOB_SANDBOX_DELETE, JsonResponseParamTypes, SandboxCreateParamTypes, SandboxCreateResponseParamTypes, SandboxIdParamTypes, TANGLE_CHAIN_ID, TANGLE_JOBS_CONTRACT, TANGLE_MAINNET_RPC, TangleSandboxClient };
@@ -1,5 +1,5 @@
1
1
  import { m as parseErrorResponse } from "./errors-Bf-A-4SA.js";
2
- import { n as createSandboxInstanceFromResponse } from "./sandbox-CkaqBz54.js";
2
+ import { n as createSandboxInstanceFromResponse } from "./sandbox-DQ1yf_nX.js";
3
3
  //#region src/tangle/abi.ts
4
4
  /**
5
5
  * Tangle Contract ABI Definitions