@opengeni/worker-bundle 0.24.2-canary.0 → 0.26.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/activities/agent-turn/agent-build.d.ts +3 -10
  2. package/dist/activities/agent-turn/claim.d.ts +7 -0
  3. package/dist/activities/agent-turn/credential-leases.d.ts +8 -0
  4. package/dist/activities/agent-turn/errors.d.ts +1 -1
  5. package/dist/activities/agent-turn/failure-settlement.d.ts +43 -1
  6. package/dist/activities/agent-turn/quiescence.d.ts +9 -6
  7. package/dist/activities/agent-turn/tool-environment.d.ts +2 -13
  8. package/dist/activities/agent-turn/tool-policy.d.ts +4 -0
  9. package/dist/activities/agent-turn/turn-context.d.ts +9 -1
  10. package/dist/activities/codemode-dispatcher.d.ts +10 -1
  11. package/dist/activities/codex-capacity.d.ts +32 -3
  12. package/dist/activities/codex-fleet-shadow.d.ts +1 -1
  13. package/dist/activities/codex-image-generation.d.ts +1 -1
  14. package/dist/activities/codex-rotation.d.ts +8 -67
  15. package/dist/activities/goals.d.ts +1 -1
  16. package/dist/activities/google-drive-publication.d.ts +2 -13
  17. package/dist/activities/image-generation-operation.d.ts +13 -4
  18. package/dist/activities/session-state.d.ts +4 -2
  19. package/dist/activities/types.d.ts +11 -1
  20. package/dist/{activities-control-ZWH7J4KZ.js → activities-control-CTEMLTHG.js} +45 -18
  21. package/dist/activities-control-CTEMLTHG.js.map +1 -0
  22. package/dist/activities-control.d.ts +2 -0
  23. package/dist/{activities-turn-I4OPLQLS.js → activities-turn-S5IU347A.js} +960 -815
  24. package/dist/activities-turn-S5IU347A.js.map +1 -0
  25. package/dist/activities.d.ts +2 -0
  26. package/dist/{chunk-65JEWP2Q.js → chunk-D4ZEFOYH.js} +1 -1
  27. package/dist/chunk-D4ZEFOYH.js.map +1 -0
  28. package/dist/{chunk-RQNH6CGR.js → chunk-TAUE3GYT.js} +117 -95
  29. package/dist/chunk-TAUE3GYT.js.map +1 -0
  30. package/dist/github-rest-mcp.d.ts +0 -2
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.js +2 -2
  33. package/dist/index.js.map +1 -1
  34. package/dist/observability-metrics.d.ts +1 -1
  35. package/dist/workflow-bundle.js +71 -8
  36. package/dist/workflows/activities.d.ts +1 -1
  37. package/dist/workflows/session.d.ts +3 -0
  38. package/package.json +17 -17
  39. package/src/activities/agent-turn/agent-build.ts +20 -26
  40. package/src/activities/agent-turn/claim.ts +26 -1
  41. package/src/activities/agent-turn/codex-capacity.ts +311 -234
  42. package/src/activities/agent-turn/credential-leases.ts +36 -0
  43. package/src/activities/agent-turn/errors.ts +29 -1
  44. package/src/activities/agent-turn/failure-settlement.ts +451 -323
  45. package/src/activities/agent-turn/quiescence.ts +21 -15
  46. package/src/activities/agent-turn/run.ts +18 -5
  47. package/src/activities/agent-turn/stream-attempt.ts +15 -1
  48. package/src/activities/agent-turn/tool-environment.ts +30 -32
  49. package/src/activities/agent-turn/tool-policy.ts +14 -8
  50. package/src/activities/agent-turn/turn-context.ts +13 -0
  51. package/src/activities/codemode-dispatcher.ts +235 -59
  52. package/src/activities/codex-capacity.ts +89 -10
  53. package/src/activities/codex-fleet-shadow.ts +8 -1
  54. package/src/activities/codex-image-generation.ts +19 -2
  55. package/src/activities/codex-rotation.ts +45 -142
  56. package/src/activities/goals.ts +9 -9
  57. package/src/activities/google-drive-publication.ts +4 -81
  58. package/src/activities/image-generation-operation.ts +28 -3
  59. package/src/activities/sandbox-lease.ts +29 -12
  60. package/src/activities/session-state.ts +17 -0
  61. package/src/activities/types.ts +16 -8
  62. package/src/activities.ts +1 -0
  63. package/src/github-rest-mcp.ts +0 -82
  64. package/src/observability-metrics.ts +4 -0
  65. package/src/sandbox-routing.ts +71 -16
  66. package/src/workflows/activities.ts +1 -0
  67. package/src/workflows/session.ts +85 -7
  68. package/dist/activities/api-integrations.d.ts +0 -21
  69. package/dist/activities-control-ZWH7J4KZ.js.map +0 -1
  70. package/dist/activities-turn-I4OPLQLS.js.map +0 -1
  71. package/dist/chunk-65JEWP2Q.js.map +0 -1
  72. package/dist/chunk-RQNH6CGR.js.map +0 -1
  73. package/src/activities/api-integrations.ts +0 -151
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  observabilityEventLogger
3
- } from "./chunk-65JEWP2Q.js";
3
+ } from "./chunk-D4ZEFOYH.js";
4
4
 
5
5
  // src/activity-services.ts
6
6
  import { dbSearchPath, getSettings, resolveNatsControlPlaneAuth } from "@opengeni/config";
@@ -431,6 +431,7 @@ function createSharedActivityServices(dependencies) {
431
431
 
432
432
  // src/activities/codex-capacity.ts
433
433
  import {
434
+ armCodexCapacityWait,
434
435
  fetchCodexUsageForAccount,
435
436
  getCodexCapacityWaitForSession,
436
437
  getXaiCapacityWaitForSession,
@@ -439,6 +440,7 @@ import {
439
440
  reconcileCodexCapacityWait as reconcileCodexCapacityWaitDb,
440
441
  reconcileXaiCapacityWait as reconcileXaiCapacityWaitDb
441
442
  } from "@opengeni/db";
443
+ import { publishDurableSessionEvents } from "@opengeni/events";
442
444
 
443
445
  // src/activities/codex-rotation.ts
444
446
  function codexAccountNeedsLiveCapacityRefresh(account, now) {
@@ -505,9 +507,6 @@ function shardCredentialForSession(args) {
505
507
  const index = fnv1a32(sessionId) % eligibles.length;
506
508
  return eligibles[index].id;
507
509
  }
508
- function earliestCodexReset(accounts, now) {
509
- return earliestReset(accounts, now);
510
- }
511
510
  function chooseShardedHome(args) {
512
511
  const { sessionId, currentPolicyPin, accounts, now } = args;
513
512
  const pinRow = currentPolicyPin ? accounts.find((acct) => acct.id === currentPolicyPin) ?? null : null;
@@ -570,20 +569,6 @@ function computeIdleDelayMs(earliestResetAt, now, maxMs) {
570
569
  const delta = earliestResetAt.getTime() - now.getTime();
571
570
  return Math.min(Math.max(delta, MIN_IDLE_MS), maxMs);
572
571
  }
573
- var REACTIVE_PERSISTENCE_FAULT_FLOOR_MS = 5e3;
574
- var REACTIVE_ROTATION_MARGIN = 2;
575
- var REACTIVE_CIRCUIT_BREAKER_IDLE_MS = MIN_IDLE_MS;
576
- function computeReactiveRotationResume(args) {
577
- const streak = args.priorConsecutiveRotations + 1;
578
- const bound = args.connectedAccountCount + REACTIVE_ROTATION_MARGIN;
579
- if (streak > bound) {
580
- return { continueDelayMs: REACTIVE_CIRCUIT_BREAKER_IDLE_MS, idleUntilReset: true };
581
- }
582
- if (!args.cooldownPersisted) {
583
- return { continueDelayMs: REACTIVE_PERSISTENCE_FAULT_FLOOR_MS, idleUntilReset: false };
584
- }
585
- return { continueDelayMs: 0, idleUntilReset: false };
586
- }
587
572
  function chooseRotationActive(args) {
588
573
  const { activeCredentialId, priorCredentialId, accounts, now } = args;
589
574
  const rotationStrategy = effectiveRotationStrategy(args.rotationStrategy);
@@ -647,36 +632,12 @@ function chooseRotationActive(args) {
647
632
  }, void 0);
648
633
  return decide(chosen);
649
634
  }
650
- function chooseLegacyRotationActive(args) {
651
- if (args.rotationStrategy === "most_remaining") {
652
- const active = args.activeCredentialId ? args.accounts.find((account) => account.id === args.activeCredentialId) : void 0;
653
- if (active && isCodexCredentialEligible(active, args.now)) {
654
- return { kind: "active", credentialId: active.id, moved: false };
655
- }
656
- }
657
- return chooseRotationActive({
658
- ...args,
659
- accounts: args.accounts.map((account) => ({
660
- ...account,
661
- activeLeaseCount: 0,
662
- selectionCount: 0,
663
- lastSelectedAt: null
664
- }))
665
- });
666
- }
667
635
  function selectCodexCredentialLeaseForTurn(args) {
668
- const {
669
- accounts,
670
- activeCredentialId,
671
- rotationEnabled,
672
- leaseRotationEnabled,
673
- rotationStrategy,
674
- existingCredentialId
675
- } = args.context;
676
- const leasingEnabled = args.leasingEnabled && leaseRotationEnabled;
636
+ const { accounts, activeCredentialId, rotationEnabled, rotationStrategy, existingCredentialId } = args.context;
637
+ const failedCredentialIds = new Set(args.context.failedCredentialIds ?? []);
677
638
  const strategy = effectiveRotationStrategy(rotationStrategy);
678
639
  const existing = existingCredentialId ? accounts.find((account) => account.id === existingCredentialId) : void 0;
679
- if (existing && isCodexCredentialHealthy(existing, args.now)) {
640
+ if (existing && !failedCredentialIds.has(existing.id) && isCodexCredentialHealthy(existing, args.now)) {
680
641
  return {
681
642
  credentialId: existing.id,
682
643
  advanceActivePointer: false,
@@ -687,9 +648,6 @@ function selectCodexCredentialLeaseForTurn(args) {
687
648
  }
688
649
  };
689
650
  }
690
- const connectedIds = new Set(
691
- accounts.filter((account) => account.allocatorEnabled).map((account) => account.id)
692
- );
693
651
  const pinDisposition = classifyCodexPin({
694
652
  pinnedCredentialId: args.sessionPinnedCredentialId,
695
653
  pinSource: args.sessionPinSource,
@@ -698,9 +656,16 @@ function selectCodexCredentialLeaseForTurn(args) {
698
656
  });
699
657
  if (pinDisposition === "manual" && args.sessionPinnedCredentialId) {
700
658
  const pinned = accounts.find((account) => account.id === args.sessionPinnedCredentialId);
701
- if (!pinned?.allocatorEnabled) {
659
+ if (!pinned) {
702
660
  return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
703
661
  }
662
+ if (!pinned.allocatorEnabled) {
663
+ return {
664
+ credentialId: null,
665
+ decision: { kind: "allocatorDisabled", credentialId: pinned.id },
666
+ advanceActivePointer: false
667
+ };
668
+ }
704
669
  if (isCodexCredentialHealthy(pinned, args.now)) {
705
670
  return {
706
671
  credentialId: pinned.id,
@@ -718,13 +683,14 @@ function selectCodexCredentialLeaseForTurn(args) {
718
683
  };
719
684
  }
720
685
  if (pinDisposition === "sharded") {
721
- if (accounts.length === 0) {
686
+ const unattemptedAccounts2 = accounts.filter((account) => !failedCredentialIds.has(account.id));
687
+ if (unattemptedAccounts2.length === 0) {
722
688
  return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
723
689
  }
724
690
  const shard = chooseShardedHome({
725
691
  sessionId: args.sessionId,
726
692
  currentPolicyPin: args.sessionPinSource === "policy" ? args.sessionPinnedCredentialId : null,
727
- accounts,
693
+ accounts: unattemptedAccounts2,
728
694
  now: args.now
729
695
  });
730
696
  if (shard.kind === "allCapped") {
@@ -746,9 +712,16 @@ function selectCodexCredentialLeaseForTurn(args) {
746
712
  }
747
713
  if (!rotationEnabled) {
748
714
  const active = activeCredentialId ? accounts.find((account) => account.id === activeCredentialId) : void 0;
749
- if (!active?.allocatorEnabled) {
715
+ if (!active) {
750
716
  return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
751
717
  }
718
+ if (!active.allocatorEnabled) {
719
+ return {
720
+ credentialId: null,
721
+ decision: { kind: "allocatorDisabled", credentialId: active.id },
722
+ advanceActivePointer: false
723
+ };
724
+ }
752
725
  if (!isCodexCredentialHealthy(active, args.now)) {
753
726
  return {
754
727
  credentialId: null,
@@ -762,22 +735,15 @@ function selectCodexCredentialLeaseForTurn(args) {
762
735
  advanceActivePointer: false
763
736
  };
764
737
  }
765
- if (!leasingEnabled && pinDisposition !== "clearStale" && args.sessionPinnedCredentialId) {
766
- const credentialId = connectedIds.has(args.sessionPinnedCredentialId) ? args.sessionPinnedCredentialId : activeCredentialId && connectedIds.has(activeCredentialId) ? activeCredentialId : null;
767
- return {
768
- credentialId,
769
- decision: credentialId ? { kind: "active", credentialId, moved: false } : { kind: "none" }
770
- };
771
- }
772
738
  const priorId = args.sessionLastCredentialId ?? activeCredentialId;
773
- const choose = leasingEnabled ? chooseRotationActive : chooseLegacyRotationActive;
774
- const decision = choose({
739
+ const unattemptedAccounts = accounts.filter((account) => !failedCredentialIds.has(account.id));
740
+ const decision = chooseRotationActive({
775
741
  rotationStrategy: strategy,
776
742
  activeCredentialId,
777
743
  // Per-session continuity is the round-robin/drain cursor. Falling back to
778
744
  // the workspace pointer is only correct when this session has never run.
779
745
  priorCredentialId: priorId,
780
- accounts,
746
+ accounts: unattemptedAccounts,
781
747
  now: args.now
782
748
  });
783
749
  return {
@@ -816,11 +782,10 @@ async function signalPendingCodexCapacityWakeTargets(services, workspaceId) {
816
782
  );
817
783
  await signalCodexCapacityWakeTargets(services, targets);
818
784
  }
819
- function codexCapacityDecision(context, settings) {
785
+ function codexCapacityDecision(context) {
820
786
  const now = /* @__PURE__ */ new Date();
821
787
  const selected = selectCodexCredentialLeaseForTurn({
822
788
  context,
823
- leasingEnabled: settings.codexCredentialLeasingEnabled,
824
789
  sessionId: context.sessionId,
825
790
  sessionPinnedCredentialId: context.sessionPinnedCredentialId,
826
791
  sessionPinSource: context.sessionPinSource,
@@ -839,21 +804,54 @@ function codexCapacityDecision(context, settings) {
839
804
  }
840
805
  };
841
806
  }
842
- const authoritativeReset = authoritativeCodexCapacityResetAt(context.accounts, now);
843
- const hasReconcilableQuotaCooldown = context.accounts.some(
807
+ const policyCredentialId = context.sessionPinSource === "manual" && context.sessionPinnedCredentialId ? context.sessionPinnedCredentialId : !context.rotationEnabled ? context.activeCredentialId : null;
808
+ const capacityAccounts = policyCredentialId ? context.accounts.filter((account) => account.id === policyCredentialId) : context.accounts;
809
+ const authoritativeReset = authoritativeCodexCapacityResetAt(capacityAccounts, now);
810
+ const hasReconcilableQuotaCooldown = capacityAccounts.some(
844
811
  (account) => account.status === "active" && account.allocatorEnabled && account.exhaustedKind === "quota" && account.exhaustedUntil !== null && account.exhaustedUntil > now
845
812
  );
813
+ const policyAccount = capacityAccounts[0] ?? null;
814
+ const mutationOnlyStatusBlock = policyAccount != null && (!policyAccount.allocatorEnabled || policyAccount.status !== "active") || authoritativeReset === null && capacityAccounts.length > 0 && capacityAccounts.every(
815
+ (account) => !account.allocatorEnabled || account.status !== "active"
816
+ );
817
+ const noneReason = selected.decision.kind === "none" ? context.sessionPinSource === "manual" && context.sessionPinnedCredentialId !== null ? "manual_pin_missing" : !context.rotationEnabled && context.activeCredentialId === null ? "rotation_off_active_pointer_missing" : context.policyScope !== null && context.accounts.length === 0 ? "policy_filtered_pool_empty" : context.accounts.length === 0 ? "no_connected_credentials" : "no_eligible_credential" : null;
846
818
  return {
847
819
  kind: "unavailable",
848
820
  earliestResetAt: authoritativeReset,
849
- resetKind: authoritativeReset && !hasReconcilableQuotaCooldown ? "authoritative" : "bounded_refresh",
821
+ resetKind: selected.decision.kind === "none" || selected.decision.kind === "allocatorDisabled" || mutationOnlyStatusBlock ? "mutation_only" : authoritativeReset && !hasReconcilableQuotaCooldown ? "authoritative" : "bounded_refresh",
850
822
  diagnostic: {
851
823
  connectedCount: context.accounts.length,
852
824
  allocatorEnabledCount: context.accounts.filter((account) => account.allocatorEnabled).length,
853
- policyHash: context.policyHash
825
+ policyHash: context.policyHash,
826
+ ...noneReason ? { reason: noneReason } : {}
854
827
  }
855
828
  };
856
829
  }
830
+ async function armAndReconcileCodexCapacityWait(services, input, options = {}) {
831
+ const armed = await armCodexCapacityWait(services.db, input);
832
+ if (armed.action !== "waiting") return armed;
833
+ options.onArmed?.();
834
+ await publishDurableSessionEvents(services.bus, input.workspaceId, input.sessionId, armed.events);
835
+ const evaluated = await reconcileCodexCapacityWaitDb(
836
+ services.db,
837
+ {
838
+ accountId: input.accountId,
839
+ workspaceId: input.workspaceId,
840
+ sessionId: input.sessionId,
841
+ waiterId: armed.waiter.id,
842
+ generation: armed.waiter.generation,
843
+ ...input.now ? { now: input.now } : {}
844
+ },
845
+ (context) => codexCapacityDecision(context)
846
+ );
847
+ await publishDurableSessionEvents(
848
+ services.bus,
849
+ input.workspaceId,
850
+ input.sessionId,
851
+ evaluated.events
852
+ );
853
+ return evaluated;
854
+ }
857
855
  async function refreshCapacityMetadata(services, workspaceId) {
858
856
  const accounts = await listCodexAccountStatuses(services.db, workspaceId).catch(() => []);
859
857
  const now = /* @__PURE__ */ new Date();
@@ -934,7 +932,8 @@ function createCodexCapacityActivities(services) {
934
932
  if (!current || current.id !== input.waiterId || current.generation !== input.generation) {
935
933
  return { action: "stale" };
936
934
  }
937
- if (input.cause === "timer" && current.nextCheckAt.getTime() <= Date.now()) {
935
+ const boundedRefreshAttempted = current.resetKind === "bounded_refresh" && input.cause === "timer" && current.nextCheckAt.getTime() <= Date.now();
936
+ if (boundedRefreshAttempted) {
938
937
  await refreshCapacityMetadata(resolved, input.workspaceId);
939
938
  }
940
939
  const result = await reconcileCodexCapacityWaitDb(
@@ -944,9 +943,10 @@ function createCodexCapacityActivities(services) {
944
943
  workspaceId: input.workspaceId,
945
944
  sessionId: input.sessionId,
946
945
  waiterId: input.waiterId,
947
- generation: input.generation
946
+ generation: input.generation,
947
+ boundedRefreshAttempted
948
948
  },
949
- (context) => codexCapacityDecision(context, resolved.settings)
949
+ (context) => codexCapacityDecision(context)
950
950
  );
951
951
  if (result.events.length > 0) {
952
952
  try {
@@ -1107,7 +1107,7 @@ function createGoalActivities(services) {
1107
1107
  tools: withFirstPartyTools(settings, session.tools),
1108
1108
  sandboxBackend: session.sandboxBackend
1109
1109
  },
1110
- // The hold guidance is only given when `goal_wait` is actually in this
1110
+ // Long-wait guidance is only given when `wait_for_input` is actually in this
1111
1111
  // session's effective first-party selection (the same source the worker
1112
1112
  // signs into the delegated token and the API uses to register tools), so
1113
1113
  // a pre-existing narrowed selection is never told to call a missing tool.
@@ -1117,7 +1117,7 @@ function createGoalActivities(services) {
1117
1117
  session.firstPartyMcpTools
1118
1118
  );
1119
1119
  return goalContinuationPrompt(goal, autoContinuation, cap, {
1120
- goalWaitAvailable: effectiveFirstPartyTools.includes("goal_wait"),
1120
+ inputWaitAvailable: effectiveFirstPartyTools.includes("wait_for_input"),
1121
1121
  humanInputRespondAvailable: effectiveFirstPartyTools.includes(
1122
1122
  "session_human_input_respond"
1123
1123
  )
@@ -1163,12 +1163,12 @@ function goalContinuationFundedWithoutCredits(settings, model, codexBilled) {
1163
1163
  return modelFundingForAdmission(settings, model, codexBilled).fundedWithoutCredits;
1164
1164
  }
1165
1165
  function goalContinuationPrompt(_goal, _autoContinuation, _cap, options = {}) {
1166
- const waitingGuidance = options.goalWaitAvailable ? [
1167
- "Waiting on child sessions or external events:",
1168
- "- When the next progress depends on child sessions you spawned or on an external event, do not sleep, loop, or poll sessions_list/session_get/session_events to wait for it.",
1169
- "- Re-check sessions_list or session_get once; if the work is still in flight, call opengeni__goal_wait with a concrete reason and a deadline (untilSeconds), then end your turn immediately. You will be woken by a child result, a message, a human prompt, or at the deadline, and this goal stays active.",
1170
- "- If the immediately preceding user-facing update already reported this same unchanged wait, do not restate it or produce another equivalent final answer. Call opengeni__goal_wait and end the turn. Report only material new state or a newly discovered blocker.",
1171
- "- A hold is for child/external progress only. If you are blocked on a human decision, use opengeni__goal_pause under the blocked audit below instead.",
1166
+ const waitingGuidance = options.inputWaitAvailable ? [
1167
+ "Waiting on child sessions, background commands, or external events:",
1168
+ "- When further progress depends on work already in flight, do not sleep, loop, or poll session or command state repeatedly.",
1169
+ "- Re-check once; if the work is still in flight and the wait is long or uncertain, call opengeni__wait_for_input with a concrete reason and timeoutSeconds, then end your turn immediately. Relevant session input or the safety deadline will start a new turn, and this goal stays active.",
1170
+ "- If the immediately preceding user-facing update already reported this same unchanged wait, do not restate it or produce another equivalent final answer. Call opengeni__wait_for_input and end the turn. Report only material new state or a newly discovered blocker.",
1171
+ "- If you are blocked on a human decision, use opengeni__goal_pause under the blocked audit below instead.",
1172
1172
  ""
1173
1173
  ] : [];
1174
1174
  const childNoticeGuidance = [
@@ -4005,6 +4005,7 @@ function assertSessionAttemptQuiescenceRecoveryDurable(input) {
4005
4005
  var QUIESCENCE_PROOF_SIGNAL_INITIAL_RETRY_MS = 250;
4006
4006
  var QUIESCENCE_PROOF_SIGNAL_MAX_RETRY_MS = 5e3;
4007
4007
  var TURN_QUIESCENCE_WATCHDOG_MS = 5 * 6e4;
4008
+ var TURN_FINALIZER_STEP_TIMEOUT_MS = 3e4;
4008
4009
  function armTurnQuiescenceWatchdog(input) {
4009
4010
  if (!input.enabled) return () => void 0;
4010
4011
  let armed = true;
@@ -4093,25 +4094,27 @@ async function releaseTurnSandboxAfterWriterDrain(sandbox, options = {}) {
4093
4094
  }
4094
4095
  throw lastError;
4095
4096
  }
4096
- async function waitForTurnFinalizerStep(operation, signal) {
4097
- if (!signal) return await operation;
4098
- if (signal.aborted) {
4097
+ async function waitForTurnFinalizerStep(operation, signal, timeoutMs = TURN_FINALIZER_STEP_TIMEOUT_MS) {
4098
+ if (signal?.aborted) {
4099
4099
  void operation.catch(() => void 0);
4100
4100
  return void 0;
4101
4101
  }
4102
- let resolveCancellation;
4103
- const cancelled = new Promise((resolve) => {
4104
- resolveCancellation = () => resolve(void 0);
4102
+ let resolveDetached;
4103
+ const detached = new Promise((resolve) => {
4104
+ resolveDetached = () => resolve(void 0);
4105
4105
  });
4106
- const cancel = () => {
4106
+ const detach = () => {
4107
4107
  void operation.catch(() => void 0);
4108
- resolveCancellation?.();
4108
+ resolveDetached?.();
4109
4109
  };
4110
- signal.addEventListener("abort", cancel, { once: true });
4110
+ signal?.addEventListener("abort", detach, { once: true });
4111
+ const timeout = setTimeout(detach, Math.max(1, timeoutMs));
4112
+ timeout.unref?.();
4111
4113
  try {
4112
- return await Promise.race([operation, cancelled]);
4114
+ return await Promise.race([operation, detached]);
4113
4115
  } finally {
4114
- signal.removeEventListener("abort", cancel);
4116
+ clearTimeout(timeout);
4117
+ signal?.removeEventListener("abort", detach);
4115
4118
  }
4116
4119
  }
4117
4120
  async function waitForTurnStreamCleanup(batcherFlush, providerCompleted, signal) {
@@ -4568,7 +4571,18 @@ var STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE = "unable to connect. is the comput
4568
4571
  function isExactStatuslessUpstreamConnectivityMessage(message) {
4569
4572
  return message.trim().toLowerCase() === STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE;
4570
4573
  }
4574
+ function providerSafetyRefusalDiagnostic(error) {
4575
+ return collectErrorStrings(error).find(
4576
+ (value) => /^(?:content_policy_violation|content_filter|safety_violation|bio_policy|cyber_policy)$/.test(
4577
+ value
4578
+ ) || /\bthis request was blocked by our safety systems\b/i.test(value)
4579
+ );
4580
+ }
4581
+ function isProviderSafetyRefusal(error) {
4582
+ return providerSafetyRefusalDiagnostic(error) !== void 0;
4583
+ }
4571
4584
  function isTransientProviderError(error) {
4585
+ if (isProviderSafetyRefusal(error)) return false;
4572
4586
  const status = typeof error === "object" && error !== null ? Number(
4573
4587
  error.status ?? error.statusCode
4574
4588
  ) : void 0;
@@ -4588,6 +4602,7 @@ function isTransientProviderError(error) {
4588
4602
  );
4589
4603
  }
4590
4604
  function classifyXaiCredentialFailure(error) {
4605
+ if (isProviderSafetyRefusal(error)) return null;
4591
4606
  let relogin = error;
4592
4607
  for (let depth = 0; depth < 6 && relogin && typeof relogin === "object"; depth += 1) {
4593
4608
  if (relogin instanceof XaiSubscriptionReloginRequired) {
@@ -4633,6 +4648,15 @@ function agentRunFailurePayload(error, options = {}) {
4633
4648
  historyPersistenceStage: error.stage
4634
4649
  };
4635
4650
  }
4651
+ const safetyRefusalDiagnostic = providerSafetyRefusalDiagnostic(error);
4652
+ if (safetyRefusalDiagnostic !== void 0) {
4653
+ return {
4654
+ error: "The model provider blocked this request through its safety systems. Automatic retries stopped.",
4655
+ code: "provider_safety_refusal",
4656
+ retryable: false,
4657
+ detail: safetyRefusalDiagnostic
4658
+ };
4659
+ }
4636
4660
  const message = error instanceof Error ? error.message : String(error);
4637
4661
  const status = typeof error === "object" && error !== null ? Number(
4638
4662
  error.status ?? error.statusCode
@@ -4809,6 +4833,7 @@ function codexCredentialCooldownUntil(failure, account, now) {
4809
4833
  );
4810
4834
  }
4811
4835
  function classifyCodexCredentialFailure(error) {
4836
+ if (isProviderSafetyRefusal(error)) return null;
4812
4837
  let refreshError = error;
4813
4838
  for (let depth = 0; depth < 6 && refreshError && typeof refreshError === "object"; depth += 1) {
4814
4839
  if (refreshError instanceof CodexReloginRequired) {
@@ -4884,16 +4909,13 @@ export {
4884
4909
  codexAccountNeedsLiveCapacityRefresh,
4885
4910
  classifyCodexPin,
4886
4911
  isCodexCredentialEligible,
4887
- shardCredentialForSession,
4888
- earliestCodexReset,
4889
4912
  authoritativeCodexCapacityResetAt,
4890
4913
  computeIdleDelayMs,
4891
- computeReactiveRotationResume,
4892
- chooseRotationActive,
4893
4914
  selectCodexCredentialLeaseForTurn,
4894
4915
  refreshCodexUsageAndRepairCapacityWaiters,
4895
4916
  signalCodexCapacityWakeTargets,
4896
4917
  signalPendingCodexCapacityWakeTargets,
4918
+ armAndReconcileCodexCapacityWait,
4897
4919
  createCodexCapacityActivities,
4898
4920
  createGoalActivities,
4899
4921
  withFirstPartyTools,
@@ -4981,4 +5003,4 @@ export {
4981
5003
  codexUsageLimitFailurePayload,
4982
5004
  CODEX_USAGE_LIMIT_MAX_RESUME_MS
4983
5005
  };
4984
- //# sourceMappingURL=chunk-RQNH6CGR.js.map
5006
+ //# sourceMappingURL=chunk-TAUE3GYT.js.map