@tangle-network/agent-app 0.61.2 → 0.61.4

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.
@@ -46,7 +46,7 @@ import {
46
46
  createSandboxRunTool,
47
47
  escalationHints,
48
48
  flattenHistory
49
- } from "../chunk-DJIN3YUJ.js";
49
+ } from "../chunk-L7LQRJGD.js";
50
50
  import "../chunk-F4TUZYMX.js";
51
51
  import "../chunk-4LBCTFBP.js";
52
52
  import "../chunk-DSMGS4IV.js";
@@ -78,7 +78,7 @@ import {
78
78
  rowIdOf,
79
79
  storeSupportsDraftPersistence,
80
80
  streamChatRouteAsSandboxEvents
81
- } from "../chunk-7FUY6O4V.js";
81
+ } from "../chunk-Y43PXON2.js";
82
82
  import {
83
83
  redactErrorMessage
84
84
  } from "../chunk-MH74DY2I.js";
@@ -256,18 +256,20 @@ export interface ChatTurnProduceArgs<TContext> {
256
256
  * is the only way to name a REUSED row (which `priorMessages` excludes).
257
257
  *
258
258
  * Three states, all meaningful:
259
- * - `undefined` — not resolved yet. `turnLock.acquire` is the one seam that
260
- * sees this: it runs before any side effect by contract, so the row does
261
- * not exist when it reads the args.
259
+ * - `undefined` — a new row is not inserted yet. The dispatch-first policy
260
+ * and `turnLock.acquire` see this for a fresh turn; a reused row's id is
261
+ * already available from the history read, without another query.
262
262
  * - `null` — resolved, no row: `authorize` returned `insertUserMessage:
263
263
  * false` on a turn with nothing to reuse, or the store's `appendMessage`
264
264
  * resolved without a usable id.
265
- * - a string — the row id, for `contextGate`, `beforeTurn`, and `produce`. */
265
+ * - a string — the row id, including a reused row before dispatch policy;
266
+ * also supplied to `contextGate`, `beforeTurn`, and `produce`. */
266
267
  userMessageId?: string | null;
267
268
  /** True when this turn's own insert created `userMessageId`, so no earlier
268
269
  * attempt can have answered it; false when retry-dedup reused the row or no
269
270
  * row was written. A gate that refuses an already-answered retry can skip
270
- * its read when this is true. Undefined until `userMessageId` resolves. */
271
+ * its read when this is true. Already false for a reused row at dispatch
272
+ * policy and lock acquisition; undefined for a fresh row until insertion. */
271
273
  userMessageInserted?: boolean;
272
274
  /**
273
275
  * Transfer completion ownership to a product-owned durable runner. The
@@ -2434,22 +2434,51 @@ async function assertExistingBoxEgress(box, desired, migrate, stage, name, prefe
2434
2434
  }
2435
2435
 
2436
2436
  // src/sandbox/box-health.ts
2437
- async function isBoxAlive(box, probe) {
2437
+ function plannedHostRestart(error) {
2438
+ const seen = /* @__PURE__ */ new Set();
2439
+ for (let depth = 0; error && typeof error === "object" && depth < 8 && !seen.has(error); depth++) {
2440
+ seen.add(error);
2441
+ const cause = error;
2442
+ if (cause.code === "HOST_AGENT_RESTARTING" && cause.status === 503) return true;
2443
+ error = cause.cause;
2444
+ }
2445
+ return false;
2446
+ }
2447
+ async function readDuringPlannedHostRestart(read, deadline) {
2448
+ let waited = false;
2449
+ for (; ; ) {
2450
+ try {
2451
+ return { value: await read(), waited };
2452
+ } catch (error) {
2453
+ if (!plannedHostRestart(error)) throw error;
2454
+ const hint = error.retryAfterMs;
2455
+ const delay = typeof hint === "number" && Number.isFinite(hint) && hint > 0 ? hint : sandboxTransientBackoffMs(1);
2456
+ if (Date.now() + delay >= deadline) throw error;
2457
+ waited = true;
2458
+ await new Promise((resolve) => setTimeout(resolve, delay));
2459
+ }
2460
+ }
2461
+ }
2462
+ async function isBoxAlive(box, probe, deadline) {
2438
2463
  if (!probe) return ok(void 0);
2439
2464
  try {
2440
- const alive = await box.exec("echo alive", { timeoutMs: probe.execTimeoutMs ?? 5e3 });
2465
+ const { value: alive } = await readDuringPlannedHostRestart(
2466
+ () => box.exec("echo alive", { timeoutMs: probe.execTimeoutMs ?? 5e3 }),
2467
+ deadline
2468
+ );
2441
2469
  if (alive.exitCode !== 0 || alive.stdout.trim() !== "alive") {
2442
2470
  return fail(new Error("alive check did not return a successful alive marker"));
2443
2471
  }
2444
2472
  return ok(void 0);
2445
2473
  } catch (cause) {
2474
+ if (plannedHostRestart(cause)) throw cause;
2446
2475
  return fail(new Error("alive check failed", { cause }));
2447
2476
  }
2448
2477
  }
2449
2478
  function hasRecentLivenessVerification(box, probe, now = Date.now()) {
2450
2479
  return isRecent(checksFor(box)?.alive, probe.cacheTtlMs ?? TRUSTED_REUSE_TTL_MS, now);
2451
2480
  }
2452
- async function isReusableBox(box, probe) {
2481
+ async function isReusableBox(box, probe, restartTimeoutMs = probe?.execTimeoutMs ?? 5e3) {
2453
2482
  if (sandboxEdgeFailed(box) || !sandboxRuntimeUrl(box)) {
2454
2483
  forgetBox(box.id);
2455
2484
  return fail(new Error(sandboxEdgeFailed(box) ? "runtime edge readiness failed" : "runtime URL is missing"));
@@ -2459,7 +2488,7 @@ async function isReusableBox(box, probe) {
2459
2488
  trustedBoxes.add(box);
2460
2489
  return ok(void 0);
2461
2490
  }
2462
- const alive = await isBoxAlive(box, probe);
2491
+ const alive = await isBoxAlive(box, probe, Date.now() + restartTimeoutMs);
2463
2492
  if (alive.succeeded) recordCheck(box, { alive: Date.now() });
2464
2493
  else forgetBox(box.id);
2465
2494
  return alive;
@@ -2519,18 +2548,21 @@ function resumeEnvRequiredKeys(cause) {
2519
2548
  if (code !== "RESUME_ENV_REQUIRED" || !Array.isArray(missingEnvKeys)) return void 0;
2520
2549
  return missingEnvKeys.filter((key) => typeof key === "string");
2521
2550
  }
2522
- async function runningSessionCount(box) {
2551
+ async function runningSessionCount(box, deadline) {
2523
2552
  try {
2524
- const sessions = await box.sessions();
2525
- return sessions.filter(
2553
+ const { value: sessions, waited } = await readDuringPlannedHostRestart(() => box.sessions(), deadline);
2554
+ return { waited, running: sessions.filter(
2526
2555
  ({ info }) => info.status === "running" || Boolean(info.activeExecutionId) || info.status === "queued" && Boolean(info.latestExecutionId)
2527
- ).length;
2528
- } catch {
2529
- return void 0;
2556
+ ).length };
2557
+ } catch (error) {
2558
+ if (plannedHostRestart(error)) throw error;
2559
+ return { waited: false };
2530
2560
  }
2531
2561
  }
2532
2562
  async function recoverUnresponsiveBox(client, box, probe, stage, name, resumeTimeout, runtimeEnv, onProgress) {
2533
- const running = await runningSessionCount(box);
2563
+ const deadline = Date.now() + resumeTimeout;
2564
+ const { running, waited } = await runningSessionCount(box, deadline);
2565
+ if (waited && (await isReusableBox(box, probe, Math.max(1, deadline - Date.now()))).succeeded) return box;
2534
2566
  if (running) {
2535
2567
  if (sandboxRuntimeUrl(box) && !sandboxEdgeFailed(box)) return box;
2536
2568
  throw new SandboxBoxBusyError(
@@ -2562,7 +2594,7 @@ async function recoverUnresponsiveBox(client, box, probe, stage, name, resumeTim
2562
2594
  );
2563
2595
  }
2564
2596
  const recovered = await refreshRuntimeConnection(client, resumed.value);
2565
- const reusable = await isReusableBox(recovered, probe);
2597
+ const reusable = await isReusableBox(recovered, probe, resumeTimeout);
2566
2598
  if (!reusable.succeeded) {
2567
2599
  throw new SandboxRecoveryFailedError(
2568
2600
  stage,
@@ -2665,7 +2697,7 @@ async function provisionWorkspaceSandbox(shell, options, gate, reuseOnly) {
2665
2697
  try {
2666
2698
  if (readyResult.status === "rejected") throw readyResult.reason;
2667
2699
  const ready = readyResult.value;
2668
- if ((await measure("liveness", () => isReusableBox(ready, shell.livenessProbe))).succeeded) {
2700
+ if ((await measure("liveness", () => isReusableBox(ready, shell.livenessProbe, resumeTimeout))).succeeded) {
2669
2701
  if (!trustedBoxes.has(ready)) await gateBeforeUse();
2670
2702
  const finalBox = await measure("finalize", () => finalizeExistingBox(shell, client, ready, "reused", name, workspaceId, userId, harness, scope, runtimeEnv2, prefetch));
2671
2703
  if (trustedBoxes.has(ready)) trustedBoxes.add(finalBox);
@@ -2731,7 +2763,7 @@ async function provisionWorkspaceSandbox(shell, options, gate, reuseOnly) {
2731
2763
  } else {
2732
2764
  try {
2733
2765
  const box2 = await refreshRuntimeConnection(client, resumed.value);
2734
- if ((await isReusableBox(box2, shell.livenessProbe)).succeeded) {
2766
+ if ((await isReusableBox(box2, shell.livenessProbe, resumeTimeout)).succeeded) {
2735
2767
  return rememberRunningBox(name, await finalizeExistingBox(shell, client, box2, "resumed", name, workspaceId, userId, harness, scope, runtimeEnv2));
2736
2768
  }
2737
2769
  const recovered = await recoverUnresponsiveBox(
@@ -3662,4 +3694,4 @@ export {
3662
3694
  deleteSecret,
3663
3695
  mintSandboxScopedToken
3664
3696
  };
3665
- //# sourceMappingURL=chunk-DJIN3YUJ.js.map
3697
+ //# sourceMappingURL=chunk-L7LQRJGD.js.map