@opengeni/worker-bundle 2.2.0 → 2.2.1-canary.36919050519001

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 (74) hide show
  1. package/dist/activities/agent-run-admission.d.ts +3 -1
  2. package/dist/activities/agent-turn/admission.d.ts +24 -3
  3. package/dist/activities/agent-turn/agent-build.d.ts +1 -0
  4. package/dist/activities/agent-turn/claude-usage-observer.d.ts +13 -1
  5. package/dist/activities/agent-turn/compaction-prep.d.ts +20 -0
  6. package/dist/activities/agent-turn/final-reply.d.ts +18 -0
  7. package/dist/activities/agent-turn/governance-model.d.ts +6 -0
  8. package/dist/activities/agent-turn/model-call-admission.d.ts +15 -0
  9. package/dist/activities/agent-turn/run-credentials.d.ts +2 -0
  10. package/dist/activities/agent-turn/sandbox-establish.d.ts +1 -0
  11. package/dist/activities/agent-turn/session-title.d.ts +3 -1
  12. package/dist/activities/agent-turn/stream-attempt.d.ts +1 -0
  13. package/dist/activities/agent-turn/turn-context.d.ts +1 -0
  14. package/dist/activities/automations.d.ts +3 -1
  15. package/dist/activities/browser-deadline-checkpoint.d.ts +29 -0
  16. package/dist/activities/goals.d.ts +8 -0
  17. package/dist/activities/run-credentials.d.ts +4 -2
  18. package/dist/activities/types.d.ts +1 -1
  19. package/dist/{activities-control-MHNA3CYV.js → activities-control-55ECL47G.js} +403 -116
  20. package/dist/activities-control-55ECL47G.js.map +1 -0
  21. package/dist/activities-control.d.ts +30 -0
  22. package/dist/{activities-turn-FQ5OO2WW.js → activities-turn-T7Y3BWYO.js} +678 -246
  23. package/dist/activities-turn-T7Y3BWYO.js.map +1 -0
  24. package/dist/activities.d.ts +30 -0
  25. package/dist/browser-deadline-checkpoint-contract.d.ts +2 -0
  26. package/dist/{chunk-RZAAGRFQ.js → chunk-OWNLATJL.js} +189 -80
  27. package/dist/chunk-OWNLATJL.js.map +1 -0
  28. package/dist/index.d.ts +15 -0
  29. package/dist/index.js +45 -23
  30. package/dist/index.js.map +1 -1
  31. package/dist/sandbox-resume.d.ts +4 -1
  32. package/dist/workflow-bundle.js +72 -10
  33. package/dist/workflows/browser-deadline-checkpoint.d.ts +9 -0
  34. package/dist/workflows.d.ts +1 -0
  35. package/package.json +21 -20
  36. package/src/activities/agent-run-admission.ts +17 -1
  37. package/src/activities/agent-turn/admission.ts +64 -1
  38. package/src/activities/agent-turn/agent-build.ts +24 -3
  39. package/src/activities/agent-turn/claim.ts +56 -14
  40. package/src/activities/agent-turn/claude-usage-observer.ts +33 -1
  41. package/src/activities/agent-turn/compaction-prep.ts +67 -16
  42. package/src/activities/agent-turn/errors.ts +55 -0
  43. package/src/activities/agent-turn/failure-settlement.ts +26 -6
  44. package/src/activities/agent-turn/final-reply.ts +46 -0
  45. package/src/activities/agent-turn/governance-model.ts +12 -0
  46. package/src/activities/agent-turn/model-call-admission.ts +94 -0
  47. package/src/activities/agent-turn/run-credentials.ts +15 -3
  48. package/src/activities/agent-turn/run.ts +43 -5
  49. package/src/activities/agent-turn/sandbox-establish.ts +9 -5
  50. package/src/activities/agent-turn/session-title.ts +8 -2
  51. package/src/activities/agent-turn/stream-attempt.ts +144 -38
  52. package/src/activities/agent-turn/tool-environment.ts +51 -39
  53. package/src/activities/agent-turn/turn-context.ts +1 -0
  54. package/src/activities/automations.ts +55 -3
  55. package/src/activities/browser-deadline-checkpoint.ts +279 -0
  56. package/src/activities/capabilities.ts +52 -14
  57. package/src/activities/goals.ts +67 -95
  58. package/src/activities/knowledge-indexing.ts +29 -0
  59. package/src/activities/open-suffix-resume.ts +2 -1
  60. package/src/activities/run-credentials.ts +22 -16
  61. package/src/activities/scheduled-tasks.ts +83 -13
  62. package/src/activities/types.ts +1 -0
  63. package/src/activities/workspace-credential-provider.ts +12 -0
  64. package/src/activities-control.ts +2 -0
  65. package/src/activities.ts +3 -0
  66. package/src/browser-deadline-checkpoint-contract.ts +5 -0
  67. package/src/index.ts +53 -25
  68. package/src/sandbox-resume.ts +23 -8
  69. package/src/sandbox-routing.ts +4 -2
  70. package/src/workflows/browser-deadline-checkpoint.ts +50 -0
  71. package/src/workflows.ts +4 -0
  72. package/dist/activities-control-MHNA3CYV.js.map +0 -1
  73. package/dist/activities-turn-FQ5OO2WW.js.map +0 -1
  74. package/dist/chunk-RZAAGRFQ.js.map +0 -1
@@ -20,6 +20,21 @@ export declare function createActivityTestHarness(dependencies?: ActivityDepende
20
20
  } | null>;
21
21
  reconcileCodexCapacityWait: (input: import("./activities.js").ReconcileCodexCapacityWaitInput) => Promise<import("./activities.js").ReconcileCodexCapacityWaitResult>;
22
22
  maintainBrowserStateArtifacts: () => Promise<import("./activities/browser-state-artifact-reaper.js").MaintainBrowserStateArtifactsResult>;
23
+ listDueBrowserCheckpoints(): Promise<{
24
+ accountId: string;
25
+ workspaceId: string;
26
+ sandboxGroupId: string;
27
+ leaseId: string;
28
+ leaseEpoch: number;
29
+ instanceId: string;
30
+ browserSessionId: string;
31
+ controllerGeneration: string;
32
+ }[]>;
33
+ checkpointBrowserBeforeDeadline(target: import("@opengeni/db").BrowserDeadlineCheckpointTarget): Promise<{
34
+ status: "skipped";
35
+ } | {
36
+ status: "suspended";
37
+ }>;
23
38
  settleAutomationRunFailure: (input: import("./activities.js").DispatchAutomationRunInput) => Promise<void>;
24
39
  dispatchAutomationRun: (input: import("./activities.js").DispatchAutomationRunInput) => Promise<import("./activities.js").DispatchAutomationRunResult>;
25
40
  indexDocument: (input: import("./activities.js").IndexDocumentInput) => Promise<{
@@ -368,6 +383,21 @@ export declare const getCodexCapacityWait: (input: import("./activities.js").Get
368
383
  } | null>;
369
384
  export declare const reconcileCodexCapacityWait: (input: import("./activities.js").ReconcileCodexCapacityWaitInput) => Promise<import("./activities.js").ReconcileCodexCapacityWaitResult>;
370
385
  export declare const prepareSandboxLeaseSweep: () => Promise<import("./activities/sandbox-lease.js").SandboxLeaseSweepPlan>;
386
+ export declare const listDueBrowserCheckpoints: () => Promise<{
387
+ accountId: string;
388
+ workspaceId: string;
389
+ sandboxGroupId: string;
390
+ leaseId: string;
391
+ leaseEpoch: number;
392
+ instanceId: string;
393
+ browserSessionId: string;
394
+ controllerGeneration: string;
395
+ }[]>;
396
+ export declare const checkpointBrowserBeforeDeadline: (target: import("@opengeni/db").BrowserDeadlineCheckpointTarget) => Promise<{
397
+ status: "skipped";
398
+ } | {
399
+ status: "suspended";
400
+ }>;
371
401
  export declare const drainSandboxLease: (input: import("./sandbox-reaper-contract.js").SandboxDrainActivityInput) => Promise<import("./activities/sandbox-lease.js").SandboxDrainActivityResult>;
372
402
  export declare const maintainSandboxLeaseSweep: (input: import("./sandbox-reaper-contract.js").SandboxLeaseSweepMaintenanceInput) => Promise<import("./activities/sandbox-lease.js").SandboxLeaseSweepMaintenanceResult>;
373
403
  export declare const reapSandboxLeases: () => Promise<import("./activities/sandbox-lease.js").ReapSandboxLeasesResult>;
@@ -0,0 +1,2 @@
1
+ export declare const BROWSER_DEADLINE_CHECKPOINT_SWEEP_ID = "opengeni-browser-deadline-checkpoints-v1";
2
+ export declare function browserDeadlineCheckpointTaskQueue(base: string): string;
@@ -1242,7 +1242,8 @@ function createDocumentActivities(services, resolveDocumentServices) {
1242
1242
  // src/activities/goals.ts
1243
1243
  import {
1244
1244
  allowedFirstPartyMcpToolsForSession,
1245
- configuredStaticUsageLimits,
1245
+ configuredStaticUsageLimits as configuredStaticUsageLimits2,
1246
+ isModelAvailableForNewSelection,
1246
1247
  policyProviderIdForModel,
1247
1248
  resolveModelProvider,
1248
1249
  resolveTurnExecutionPolicyV1,
@@ -1258,19 +1259,92 @@ import {
1258
1259
  import { isCodexBilledModel } from "@opengeni/codex";
1259
1260
  import {
1260
1261
  enqueueSessionWorkflowWakeIfRunnable,
1261
- getBillingBalance,
1262
1262
  getWorkspaceModelPolicy,
1263
1263
  getSessionGoal,
1264
- isCodexBilledTurn,
1265
1264
  materializeGoalContinuation,
1266
- requireSession,
1267
- sumUsageQuantity
1265
+ requireSession
1268
1266
  } from "@opengeni/db";
1269
1267
  import {
1270
- modelFundingForAdmission,
1268
+ modelFundingForAdmission as modelFundingForAdmission2,
1271
1269
  resolveCatalogSettings as resolveCatalogSettings2,
1272
1270
  resolveWorkspaceCatalogSettings
1273
1271
  } from "@opengeni/core";
1272
+
1273
+ // src/activities/agent-run-admission.ts
1274
+ import { configuredStaticUsageLimits } from "@opengeni/config";
1275
+ import { modelFundingForAdmission } from "@opengeni/core";
1276
+ import {
1277
+ checkWorkspaceAllowance,
1278
+ getBillingBalance,
1279
+ isCodexBilledTurn,
1280
+ sumUsageQuantity
1281
+ } from "@opengeni/db";
1282
+ async function agentRunAdmissionDenial(services, input) {
1283
+ const codexBilled = await isCodexBilledTurn({
1284
+ db: services.db,
1285
+ settings: services.settings,
1286
+ workspaceId: input.workspaceId,
1287
+ model: input.model
1288
+ });
1289
+ const externallyBilled = modelFundingForAdmission(
1290
+ services.settings,
1291
+ input.model,
1292
+ codexBilled
1293
+ ).fundedWithoutCredits;
1294
+ if (!externallyBilled && (services.settings.billingMode === "stripe" || services.settings.usageLimitsMode === "managed")) {
1295
+ if (services.entitlements) {
1296
+ const decision = await services.entitlements.admitRun({
1297
+ accountId: input.accountId,
1298
+ workspaceId: input.workspaceId,
1299
+ action: "agent_run:create",
1300
+ quantity: input.requestedAgentRuns
1301
+ });
1302
+ if (!decision.allowed) return "insufficient_credits";
1303
+ } else {
1304
+ const balance = await getBillingBalance(services.db, input.accountId);
1305
+ if (balance.balanceMicros <= 0) return "insufficient_credits";
1306
+ }
1307
+ }
1308
+ if (!externallyBilled) {
1309
+ const refusal = await checkWorkspaceAllowance(services.db, {
1310
+ accountId: input.accountId,
1311
+ workspaceId: input.workspaceId,
1312
+ subjectId: input.initiatingHumanSubjectId ?? null
1313
+ });
1314
+ if (refusal) return refusal.code;
1315
+ }
1316
+ if (services.settings.usageLimitsMode !== "static" && services.settings.usageLimitsMode !== "managed") {
1317
+ return null;
1318
+ }
1319
+ const limits = configuredStaticUsageLimits(services.settings);
1320
+ if (!externallyBilled && limits.maxMonthlyCostMicrosPerAccount) {
1321
+ const used = await sumUsageQuantity(services.db, {
1322
+ accountId: input.accountId,
1323
+ eventType: "model.cost",
1324
+ since: startOfUtcMonth()
1325
+ });
1326
+ if (used >= limits.maxMonthlyCostMicrosPerAccount) {
1327
+ return "monthly_model_cost_limit";
1328
+ }
1329
+ }
1330
+ if (limits.maxMonthlyAgentRunsPerWorkspace) {
1331
+ const used = await sumUsageQuantity(services.db, {
1332
+ workspaceId: input.workspaceId,
1333
+ eventType: "agent_run.created",
1334
+ since: startOfUtcMonth()
1335
+ });
1336
+ if (used + input.requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {
1337
+ return "monthly_agent_run_limit";
1338
+ }
1339
+ }
1340
+ return null;
1341
+ }
1342
+ function startOfUtcMonth() {
1343
+ const now = /* @__PURE__ */ new Date();
1344
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
1345
+ }
1346
+
1347
+ // src/activities/goals.ts
1274
1348
  function createGoalActivities(services) {
1275
1349
  async function enqueueGoalRetryWake(input) {
1276
1350
  const { db } = await services();
@@ -1293,8 +1367,11 @@ function createGoalActivities(services) {
1293
1367
  if (!existingGoal || existingGoal.status !== "active") {
1294
1368
  return { action: "none" };
1295
1369
  }
1296
- let settings = (await resolveCatalogSettings2(db, catalogSourceSettings)).settings;
1297
1370
  const session = await requireSession(db, input.workspaceId, input.sessionId);
1371
+ if (session.status === "failed" || session.status === "cancelled") {
1372
+ return { action: "none" };
1373
+ }
1374
+ let settings = (await resolveCatalogSettings2(db, catalogSourceSettings)).settings;
1298
1375
  const inheritedContinuationModel = session.model;
1299
1376
  let continuationModel = inheritedContinuationModel;
1300
1377
  const continuationReasoningEffort = session.reasoningEffort;
@@ -1317,25 +1394,7 @@ function createGoalActivities(services) {
1317
1394
  if (!modelPolicyBlocked && session.codexCompactionMode === "remote_v2" && !isCodexBilledModel(continuationModel)) {
1318
1395
  modelPolicyBlocked = `session is locked to Codex remote compaction v2; model "${continuationModel}" is not a Codex subscription model`;
1319
1396
  }
1320
- const isCodexRun = await isCodexBilledTurn({
1321
- db,
1322
- settings,
1323
- workspaceId: input.workspaceId,
1324
- model: continuationModel
1325
- });
1326
- const fundedWithoutCredits = goalContinuationFundedWithoutCredits(
1327
- settings,
1328
- continuationModel,
1329
- isCodexRun
1330
- );
1331
- const budgetBlocked = await goalRunBudgetBlocked(
1332
- settings,
1333
- db,
1334
- input.accountId,
1335
- input.workspaceId,
1336
- fundedWithoutCredits
1337
- );
1338
- const turnExecutionPolicy = resolveTurnExecutionPolicyV1(settings, {
1397
+ const turnExecutionPolicy = modelPolicyBlocked ? void 0 : resolveTurnExecutionPolicyV1(settings, {
1339
1398
  modelId: continuationModel,
1340
1399
  requestedModelId: null,
1341
1400
  modelSource: "continuation",
@@ -1359,12 +1418,26 @@ function createGoalActivities(services) {
1359
1418
  // A model-policy block takes precedence: it is deterministic (a budget
1360
1419
  // pause can clear on its own; a policy pause needs a model/policy change)
1361
1420
  // and rides the same visible-pause channel.
1362
- budgetBlocked: modelPolicyBlocked ?? budgetBlocked,
1421
+ admission: async (tx, causalTurn) => {
1422
+ const budgetBlocked = modelPolicyBlocked ? null : await goalRunBudgetBlocked(
1423
+ { ...service, settings, db: tx },
1424
+ {
1425
+ accountId: input.accountId,
1426
+ workspaceId: input.workspaceId,
1427
+ model: continuationModel,
1428
+ initiatingHumanSubjectId: causalTurn?.initiatingHumanSubjectId ?? null
1429
+ }
1430
+ );
1431
+ return {
1432
+ budgetBlocked: modelPolicyBlocked ?? budgetBlocked?.message ?? null,
1433
+ budgetPausedReason: modelPolicyBlocked ? "limits" : budgetBlocked?.pausedReason ?? "limits"
1434
+ };
1435
+ },
1363
1436
  policy: {
1364
1437
  model: continuationModel,
1365
1438
  reasoningEffort: continuationReasoningEffort,
1366
1439
  latencyMode: continuationLatencyMode,
1367
- turnExecutionPolicy,
1440
+ ...turnExecutionPolicy ? { turnExecutionPolicy } : {},
1368
1441
  tools: withFirstPartyTools(settings, session.tools),
1369
1442
  sandboxBackend: session.sandboxBackend
1370
1443
  },
@@ -1403,23 +1476,26 @@ function goalContinuationModelDecision(input) {
1403
1476
  providerId: policyProviderIdForModel(catalogSettings, modelId),
1404
1477
  modelId
1405
1478
  }).allowed;
1406
- if (resolveModelProvider(catalogSettings, input.inheritedModel) && !policyBlocks(input.inheritedModel)) {
1407
- return { model: input.inheritedModel, blocked: null };
1408
- }
1409
1479
  if (!resolveModelProvider(catalogSettings, input.inheritedModel)) {
1410
1480
  return {
1411
1481
  model: input.inheritedModel,
1412
1482
  blocked: `model "${input.inheritedModel}" is no longer in the deployment or workspace catalog; choose an available model before resuming the goal`
1413
1483
  };
1414
1484
  }
1485
+ if (!isModelAvailableForNewSelection(catalogSettings, input.inheritedModel)) {
1486
+ return {
1487
+ model: input.inheritedModel,
1488
+ blocked: `model "${input.inheritedModel}" is retired from new selection; choose an available model before resuming the goal`
1489
+ };
1490
+ }
1491
+ if (!policyBlocks(input.inheritedModel)) {
1492
+ return { model: input.inheritedModel, blocked: null };
1493
+ }
1415
1494
  return {
1416
1495
  model: input.inheritedModel,
1417
1496
  blocked: `workspace model policy blocks model "${input.inheritedModel}"; pick an allowed model or change the workspace model policy`
1418
1497
  };
1419
1498
  }
1420
- function goalContinuationFundedWithoutCredits(settings, model, codexBilled) {
1421
- return modelFundingForAdmission(settings, model, codexBilled).fundedWithoutCredits;
1422
- }
1423
1499
  function goalContinuationPrompt(_goal, _autoContinuation, _cap, options = {}) {
1424
1500
  const waitingGuidance = options.inputWaitAvailable ? [
1425
1501
  "Waiting on child sessions, background commands, or external events:",
@@ -1475,6 +1551,8 @@ function goalContinuationPrompt(_goal, _autoContinuation, _cap, options = {}) {
1475
1551
  "- For document report deliverables (a document the user asked for, or a large report meant to be kept or shared), follow the Documents Skill: create the durable native document first, inspect its relevant final head after the last edit, and provide the returned artifact reference. Declare report requirements through the available goal tools before authoring and satisfy every persisted report requirement with verified artifact delivery evidence before completion. Sandbox paths and raw file IDs do not prove report delivery. If artifact tooling or access is unavailable, keep that deliverable incomplete and state the blocker; never invent proof or silently substitute a local report. Ordinary chat answers, short progress updates, source-code links, and explicitly requested local-file work remain outside this report contract.",
1476
1552
  "",
1477
1553
  "Do not rely on intent, partial progress, memory of earlier work, or a plausible final answer as proof of completion. Call opengeni__goal_complete with concrete evidence only when the full objective is actually achieved and no required work remains.",
1554
+ "Goal evidence is a short proof for the ledger, not the deliverable. After goal_complete succeeds, finish this same turn with the requested user-facing answer, or a concise summary and retained artifact link. Goal completion stops future automatic continuations; it does not send the answer or end this turn. Never compress a report into evidence or omit the final reply.",
1555
+ "Goal progress notes are short human-readable milestone statuses, not raw transcripts or continuation instructions. Keep normal spaces and summarize detail instead of squeezing words into a ledger field. The text and successCriteria fields each allow 8192 UTF-8 bytes, progressNote allows 8192 UTF-8 bytes, rationale allows 2048 UTF-8 bytes, and evidence allows 8192 characters.",
1478
1556
  "",
1479
1557
  ...waitingGuidance,
1480
1558
  ...childNoticeGuidance,
@@ -1494,41 +1572,19 @@ function withFirstPartyTools(settings, tools) {
1494
1572
  }
1495
1573
  return mergeToolRefs(tools, [{ kind: "mcp", id: "opengeni" }]);
1496
1574
  }
1497
- async function goalRunBudgetBlocked(settings, db, accountId, workspaceId, fundedWithoutCredits) {
1498
- if (!fundedWithoutCredits && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
1499
- const balance = await getBillingBalance(db, accountId);
1500
- if (balance.balanceMicros <= 0) {
1501
- return "insufficient OpenGeni credits";
1502
- }
1503
- }
1504
- if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
1505
- const limits = configuredStaticUsageLimits(settings);
1506
- if (!fundedWithoutCredits && limits.maxMonthlyCostMicrosPerAccount) {
1507
- const used = await sumUsageQuantity(db, {
1508
- accountId,
1509
- eventType: "model.cost",
1510
- since: startOfUtcMonth()
1511
- });
1512
- if (used >= limits.maxMonthlyCostMicrosPerAccount) {
1513
- return `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`;
1514
- }
1515
- }
1516
- if (limits.maxMonthlyAgentRunsPerWorkspace) {
1517
- const used = await sumUsageQuantity(db, {
1518
- workspaceId,
1519
- eventType: "agent_run.created",
1520
- since: startOfUtcMonth()
1521
- });
1522
- if (used + 1 > limits.maxMonthlyAgentRunsPerWorkspace) {
1523
- return `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`;
1524
- }
1525
- }
1526
- }
1527
- return null;
1528
- }
1529
- function startOfUtcMonth() {
1530
- const now = /* @__PURE__ */ new Date();
1531
- return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
1575
+ async function goalRunBudgetBlocked(services, input) {
1576
+ const denial = await agentRunAdmissionDenial(services, { ...input, requestedAgentRuns: 1 });
1577
+ if (denial === null) return null;
1578
+ if (denial === "allowance_exhausted") {
1579
+ return { pausedReason: "allowance", message: "OpenGeni usage allowance exhausted" };
1580
+ }
1581
+ const limits = configuredStaticUsageLimits2(services.settings);
1582
+ const messages = {
1583
+ insufficient_credits: "insufficient OpenGeni credits",
1584
+ monthly_model_cost_limit: `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`,
1585
+ monthly_agent_run_limit: `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`
1586
+ };
1587
+ return { pausedReason: "limits", message: messages[denial] };
1532
1588
  }
1533
1589
 
1534
1590
  // src/activities/knowledge-source-sync.ts
@@ -5250,9 +5306,9 @@ var WARMING_POLL_INTERVAL_MS = 250;
5250
5306
  async function sleep(ms) {
5251
5307
  await new Promise((resolve) => setTimeout(resolve, ms));
5252
5308
  }
5253
- async function waitForSandboxExecReadiness(established, timeoutMs = MODAL_EXEC_READINESS_TIMEOUT_MS, identity = {}) {
5309
+ async function waitForSandboxExecReadiness(established, timeoutMs = MODAL_EXEC_READINESS_TIMEOUT_MS, identity = {}, signal) {
5254
5310
  try {
5255
- await verifySandboxExecReadiness(established, timeoutMs);
5311
+ await verifySandboxExecReadiness(established, timeoutMs, signal);
5256
5312
  } catch (error) {
5257
5313
  if (error instanceof SandboxExecReadinessError && error.code === "exec_probe_timeout") {
5258
5314
  throw new SandboxExecReadinessTimeoutError(established.backendId, timeoutMs, {
@@ -5830,11 +5886,12 @@ async function resumeBoxForTurnOnce(services, ids, kind, holderId) {
5830
5886
  },
5831
5887
  os,
5832
5888
  // IMAGE IS SHARED STATE (B3): thread the resolved image so the lease stamps it +
5833
- // conflicts on a live box already running a different image. A
5889
+ // conflicts on a live box already running a different required image. A
5834
5890
  // SandboxImageConflictError propagates while another holder is active; a
5835
5891
  // solo change requests a capture-and-drain rotation and this attempt retries
5836
5892
  // after the cold successor can safely stamp the new image.
5837
5893
  ...ids.image ? { image: ids.image } : {},
5894
+ ...ids.imagePolicy ? { imagePolicy: ids.imagePolicy } : {},
5838
5895
  // RIG IS SHARED STATE (M3): thread the frozen rig version so the lease stamps it
5839
5896
  // + conflicts on a live box under a different rig. A SandboxRigConflictError
5840
5897
  // propagates while another holder is active; a solo change uses the same
@@ -6236,9 +6293,14 @@ async function resumeBoxForTurnOnce(services, ids, kind, holderId) {
6236
6293
  sandboxGroupId: ids.sandboxGroupId
6237
6294
  });
6238
6295
  } else {
6239
- await waitForSandboxExecReadiness(established, MODAL_EXEC_READINESS_TIMEOUT_MS, {
6240
- sandboxGroupId: ids.sandboxGroupId
6241
- });
6296
+ await waitForSandboxExecReadiness(
6297
+ established,
6298
+ MODAL_EXEC_READINESS_TIMEOUT_MS,
6299
+ {
6300
+ sandboxGroupId: ids.sandboxGroupId
6301
+ },
6302
+ cancellationSignal
6303
+ );
6242
6304
  }
6243
6305
  await maybeRenewProviderExpiration(true);
6244
6306
  throwIfReleasedOrCancelled();
@@ -6364,9 +6426,14 @@ async function resumeBoxForTurnOnce(services, ids, kind, holderId) {
6364
6426
  if (services.verifyAttachedSandboxReadiness) {
6365
6427
  await services.verifyAttachedSandboxReadiness(established);
6366
6428
  } else {
6367
- await waitForSandboxExecReadiness(established, MODAL_EXEC_READINESS_TIMEOUT_MS, {
6368
- sandboxGroupId: ids.sandboxGroupId
6369
- });
6429
+ await waitForSandboxExecReadiness(
6430
+ established,
6431
+ MODAL_EXEC_READINESS_TIMEOUT_MS,
6432
+ {
6433
+ sandboxGroupId: ids.sandboxGroupId
6434
+ },
6435
+ cancellationSignal
6436
+ );
6370
6437
  }
6371
6438
  providerRenewalTarget = {
6372
6439
  backend: ids.backend,
@@ -6626,7 +6693,7 @@ function afterPersistableHomeMutation(services, ids, home) {
6626
6693
  if (!exactAdmission || typeof exactAdmission.id !== "string" || typeof exactAdmission.workspaceGeneration !== "number" || !("providerBinding" in boundAdmission)) {
6627
6694
  throw new Error("Persistable home mutation settlement lacked its bound admission");
6628
6695
  }
6629
- if (outcome === "resolved" && retainedProcess) {
6696
+ if ((outcome === "resolved" || outcome === "outcome_unknown") && retainedProcess) {
6630
6697
  try {
6631
6698
  await retainWorkspaceProviderCommand(services.db, {
6632
6699
  accountId: fence.accountId,
@@ -6671,6 +6738,8 @@ function afterPersistableHomeMutation(services, ids, home) {
6671
6738
  }
6672
6739
  return;
6673
6740
  }
6741
+ if (outcome === "outcome_unknown")
6742
+ throw new Error("Outcome-unknown command settlement requires its exact retained invocation");
6674
6743
  await verifyWorkspaceMutationSettlement(services.db, {
6675
6744
  accountId: fence.accountId,
6676
6745
  workspaceId: ids.workspaceId,
@@ -8868,8 +8937,10 @@ import {
8868
8937
  isMcpRequestTimeoutError,
8869
8938
  isMcpTransportConnectivityError,
8870
8939
  isModalTaskExecStartPreDispatchUnavailableError,
8940
+ isModalCommandStartOutcomeUnknownError,
8871
8941
  isRoutingMutationOutcomeUnknownError,
8872
8942
  RoutingWorkspaceRootChangedError,
8943
+ ResponsesStreamingTerminalError,
8873
8944
  SandboxMaterializationVerificationError,
8874
8945
  materializationVerificationDiagnostic,
8875
8946
  PROVIDER_QUOTA_EXHAUSTED_CODE,
@@ -9834,6 +9905,7 @@ function shouldRecoverCompactionProviderFailure(error) {
9834
9905
  return agentRunFailurePayload(error).retryable === true;
9835
9906
  }
9836
9907
  function classifyContextWindowOverflowError(error) {
9908
+ if (isProviderSafetyRefusal(error)) return null;
9837
9909
  const fields = collectErrorStrings(error);
9838
9910
  const matched = fields.find(
9839
9911
  (value) => /context[_\s-]*length[_\s-]*exceeded/i.test(value) || /exceeds?\s+(?:the\s+)?context\s+window/i.test(value) || /maximum\s+context\s+length/i.test(value) || /context\s+window[^.]*exceed/i.test(value)
@@ -9879,6 +9951,7 @@ function collectErrorStrings(value, seen = /* @__PURE__ */ new WeakSet()) {
9879
9951
  }
9880
9952
  seen.add(value);
9881
9953
  const out = [];
9954
+ if (value instanceof ResponsesStreamingTerminalError) out.push(value.detail);
9882
9955
  const record = value;
9883
9956
  for (const key of ["message", "code", "type", "name", "param"]) {
9884
9957
  const field = record[key];
@@ -9896,6 +9969,9 @@ function isExactStatuslessUpstreamConnectivityMessage(message) {
9896
9969
  return message.trim().toLowerCase() === STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE;
9897
9970
  }
9898
9971
  function providerSafetyRefusalDiagnostic(error) {
9972
+ if (error instanceof ResponsesStreamingTerminalError) {
9973
+ return error.category === "safety" ? error.detail : void 0;
9974
+ }
9899
9975
  return collectErrorStrings(error).find(
9900
9976
  (value) => /^(?:content_policy_violation|content_filter|safety_violation|bio_policy|cyber_policy)$/.test(
9901
9977
  value
@@ -9906,6 +9982,9 @@ function isProviderSafetyRefusal(error) {
9906
9982
  return providerSafetyRefusalDiagnostic(error) !== void 0;
9907
9983
  }
9908
9984
  function isTransientProviderError(error) {
9985
+ if (error instanceof ResponsesStreamingTerminalError) {
9986
+ return error.category === "unavailable";
9987
+ }
9909
9988
  if (isProviderSafetyRefusal(error)) return false;
9910
9989
  const status = typeof error === "object" && error !== null ? Number(
9911
9990
  error.status ?? error.statusCode
@@ -10021,6 +10100,28 @@ function baseAgentRunFailurePayload(error, options = {}) {
10021
10100
  detail: safetyRefusalDiagnostic
10022
10101
  };
10023
10102
  }
10103
+ if (error instanceof ResponsesStreamingTerminalError) {
10104
+ const quota2 = error.category === "unknown" || error.category === "rate_limit" ? classifyProviderQuotaExhaustionError({
10105
+ code: error.code,
10106
+ error: { code: error.code, type: error.type, message: error.detail },
10107
+ retryAfterSeconds: error.retryAfterSeconds
10108
+ }) : null;
10109
+ if (quota2) {
10110
+ return {
10111
+ error: providerQuotaExhaustedMessage(quota2.scope),
10112
+ code: PROVIDER_QUOTA_EXHAUSTED_CODE,
10113
+ retryable: false,
10114
+ quotaScope: quota2.scope,
10115
+ detail: error.detail
10116
+ };
10117
+ }
10118
+ return {
10119
+ error: error.category === "rate_limit" ? "Model provider rate limit hit. Try again in a minute or lower the reasoning effort." : error.category === "unavailable" ? "The model provider is temporarily unavailable. The same turn will retry after a short delay." : "The model provider rejected the response. Automatic retries stopped.",
10120
+ code: error.category === "rate_limit" ? "provider_rate_limited" : error.category === "unavailable" ? "provider_unavailable" : "provider_request_rejected",
10121
+ retryable: error.category === "rate_limit" || error.category === "unavailable",
10122
+ detail: error.detail
10123
+ };
10124
+ }
10024
10125
  const message = error instanceof Error ? error.message : String(error);
10025
10126
  const status = typeof error === "object" && error !== null ? Number(
10026
10127
  error.status ?? error.statusCode
@@ -10049,6 +10150,13 @@ function baseAgentRunFailurePayload(error, options = {}) {
10049
10150
  retryable: true
10050
10151
  };
10051
10152
  }
10153
+ if (isModalCommandStartOutcomeUnknownError(error)) {
10154
+ return {
10155
+ error: "A managed sandbox command may have started, but its acknowledgement was lost. Automatic replay is disabled; inspect the sandbox state before retrying.",
10156
+ code: "sandbox_command_start_outcome_unknown",
10157
+ retryable: false
10158
+ };
10159
+ }
10052
10160
  if (!isRoutingMutationOutcomeUnknownError(error) && isModalTaskExecStartPreDispatchUnavailableError(error)) {
10053
10161
  return {
10054
10162
  error: "The managed sandbox command router was not ready before the command was sent. The same turn will retry after a short delay.",
@@ -10326,6 +10434,7 @@ export {
10326
10434
  signalPendingCodexCapacityWakeTargets,
10327
10435
  armAndReconcileCodexCapacityWait,
10328
10436
  createCodexCapacityActivities,
10437
+ agentRunAdmissionDenial,
10329
10438
  createDocumentActivities,
10330
10439
  createGoalActivities,
10331
10440
  withFirstPartyTools,
@@ -10428,4 +10537,4 @@ export {
10428
10537
  codexUsageLimitFailurePayload,
10429
10538
  CODEX_USAGE_LIMIT_MAX_RESUME_MS
10430
10539
  };
10431
- //# sourceMappingURL=chunk-RZAAGRFQ.js.map
10540
+ //# sourceMappingURL=chunk-OWNLATJL.js.map