@opengeni/worker-bundle 0.23.4 → 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 (115) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +17 -2
  2. package/dist/activities/agent-turn/agent-build.d.ts +3 -10
  3. package/dist/activities/agent-turn/claim.d.ts +8 -0
  4. package/dist/activities/agent-turn/codex.d.ts +2 -2
  5. package/dist/activities/agent-turn/credential-leases.d.ts +8 -0
  6. package/dist/activities/agent-turn/errors.d.ts +1 -1
  7. package/dist/activities/agent-turn/failure-settlement.d.ts +43 -1
  8. package/dist/activities/agent-turn/list-models.d.ts +16 -0
  9. package/dist/activities/agent-turn/model-usage.d.ts +15 -1
  10. package/dist/activities/agent-turn/quiescence.d.ts +11 -6
  11. package/dist/activities/agent-turn/run.d.ts +9 -0
  12. package/dist/activities/agent-turn/sandbox-runtime.d.ts +15 -0
  13. package/dist/activities/agent-turn/session-title.d.ts +21 -0
  14. package/dist/activities/agent-turn/stream-attempt.d.ts +4 -0
  15. package/dist/activities/agent-turn/tool-environment.d.ts +4 -13
  16. package/dist/activities/agent-turn/tool-policy.d.ts +40 -5
  17. package/dist/activities/agent-turn/turn-context.d.ts +13 -2
  18. package/dist/activities/agent-turn.d.ts +1 -1
  19. package/dist/activities/automations.d.ts +1 -0
  20. package/dist/activities/capabilities.d.ts +3 -1
  21. package/dist/activities/codemode-dispatcher.d.ts +10 -1
  22. package/dist/activities/codex-capacity.d.ts +32 -3
  23. package/dist/activities/codex-fleet-shadow.d.ts +1 -1
  24. package/dist/activities/codex-image-generation.d.ts +1 -1
  25. package/dist/activities/codex-rotation.d.ts +8 -67
  26. package/dist/activities/context-compaction.d.ts +2 -0
  27. package/dist/activities/goals.d.ts +12 -1
  28. package/dist/activities/google-drive-publication.d.ts +2 -13
  29. package/dist/activities/image-generation-operation.d.ts +13 -4
  30. package/dist/activities/image-generation-references.d.ts +2 -1
  31. package/dist/activities/scheduled-tasks.d.ts +1 -0
  32. package/dist/activities/session-state.d.ts +4 -2
  33. package/dist/activities/types.d.ts +19 -1
  34. package/dist/{activities-control-52W5IDWM.js → activities-control-CTEMLTHG.js} +339 -195
  35. package/dist/activities-control-CTEMLTHG.js.map +1 -0
  36. package/dist/activities-control.d.ts +4 -0
  37. package/dist/{activities-turn-A2G2KLSY.js → activities-turn-S5IU347A.js} +1846 -1136
  38. package/dist/activities-turn-S5IU347A.js.map +1 -0
  39. package/dist/activities.d.ts +4 -0
  40. package/dist/{chunk-GFNXVZVQ.js → chunk-D4ZEFOYH.js} +107 -7
  41. package/dist/chunk-D4ZEFOYH.js.map +1 -0
  42. package/dist/{chunk-GRFQTTSQ.js → chunk-GDCLDKSH.js} +7 -3
  43. package/dist/{chunk-GRFQTTSQ.js.map → chunk-GDCLDKSH.js.map} +1 -1
  44. package/dist/{chunk-IPVMCAW5.js → chunk-TAUE3GYT.js} +225 -154
  45. package/dist/chunk-TAUE3GYT.js.map +1 -0
  46. package/dist/github-rest-mcp.d.ts +0 -2
  47. package/dist/index.d.ts +2 -0
  48. package/dist/index.js +43 -7
  49. package/dist/index.js.map +1 -1
  50. package/dist/observability-metrics.d.ts +35 -8
  51. package/dist/sandbox-reaper-timeout.d.ts +2 -2
  52. package/dist/sandbox-resume.d.ts +6 -1
  53. package/dist/workflow-bundle.js +96 -10
  54. package/dist/workflows/activities.d.ts +6 -1
  55. package/dist/workflows/automations.d.ts +5 -0
  56. package/dist/workflows/session.d.ts +3 -0
  57. package/package.json +17 -17
  58. package/src/activities/agent-run-admission.ts +7 -1
  59. package/src/activities/agent-turn/admission.ts +47 -6
  60. package/src/activities/agent-turn/agent-build.ts +20 -26
  61. package/src/activities/agent-turn/claim.ts +59 -6
  62. package/src/activities/agent-turn/codex-capacity.ts +311 -234
  63. package/src/activities/agent-turn/codex.ts +2 -2
  64. package/src/activities/agent-turn/compaction-prep.ts +8 -1
  65. package/src/activities/agent-turn/credential-leases.ts +36 -0
  66. package/src/activities/agent-turn/errors.ts +29 -1
  67. package/src/activities/agent-turn/failure-settlement.ts +451 -323
  68. package/src/activities/agent-turn/finalization.ts +31 -17
  69. package/src/activities/agent-turn/list-models.ts +101 -0
  70. package/src/activities/agent-turn/model-usage.ts +120 -45
  71. package/src/activities/agent-turn/quiescence.ts +32 -17
  72. package/src/activities/agent-turn/run.ts +98 -9
  73. package/src/activities/agent-turn/sandbox-runtime.ts +78 -81
  74. package/src/activities/agent-turn/session-title.ts +55 -2
  75. package/src/activities/agent-turn/stream-attempt.ts +281 -136
  76. package/src/activities/agent-turn/tool-environment.ts +132 -39
  77. package/src/activities/agent-turn/tool-policy.ts +71 -12
  78. package/src/activities/agent-turn/turn-context.ts +21 -2
  79. package/src/activities/agent-turn.ts +5 -1
  80. package/src/activities/automations.ts +122 -67
  81. package/src/activities/capabilities.ts +129 -2
  82. package/src/activities/codemode-dispatcher.ts +235 -59
  83. package/src/activities/codex-capacity.ts +89 -10
  84. package/src/activities/codex-fleet-shadow.ts +8 -1
  85. package/src/activities/codex-image-generation.ts +19 -2
  86. package/src/activities/codex-rotation.ts +45 -142
  87. package/src/activities/context-compaction.ts +3 -0
  88. package/src/activities/goals.ts +116 -39
  89. package/src/activities/google-drive-publication.ts +4 -81
  90. package/src/activities/image-generation-operation.ts +28 -3
  91. package/src/activities/image-generation-references.ts +9 -9
  92. package/src/activities/mcp-credentials.ts +53 -0
  93. package/src/activities/rig-verification.ts +5 -3
  94. package/src/activities/sandbox-lease.ts +29 -12
  95. package/src/activities/scheduled-tasks.ts +217 -110
  96. package/src/activities/session-state.ts +17 -0
  97. package/src/activities/site-auth-maintenance.ts +12 -12
  98. package/src/activities/types.ts +22 -8
  99. package/src/activities.ts +2 -0
  100. package/src/activity-services.ts +4 -1
  101. package/src/github-rest-mcp.ts +2 -83
  102. package/src/index.ts +34 -4
  103. package/src/observability-metrics.ts +158 -14
  104. package/src/sandbox-reaper-timeout.ts +10 -4
  105. package/src/sandbox-resume.ts +58 -8
  106. package/src/sandbox-routing.ts +71 -16
  107. package/src/workflows/activities.ts +16 -0
  108. package/src/workflows/automations.ts +21 -2
  109. package/src/workflows/session.ts +85 -7
  110. package/dist/activities/api-integrations.d.ts +0 -21
  111. package/dist/activities-control-52W5IDWM.js.map +0 -1
  112. package/dist/activities-turn-A2G2KLSY.js.map +0 -1
  113. package/dist/chunk-GFNXVZVQ.js.map +0 -1
  114. package/dist/chunk-IPVMCAW5.js.map +0 -1
  115. package/src/activities/api-integrations.ts +0 -141
@@ -113,9 +113,17 @@ export type RotationDecision =
113
113
  // No connected accounts at all (preserves today's relogin-fail path).
114
114
  | { kind: "none" };
115
115
 
116
+ export type CodexTurnLeaseDecision =
117
+ | RotationDecision
118
+ // The user's manual pin or rotation-off active pointer names a connected row
119
+ // that is disabled for NEW allocations. This is policy-constrained capacity,
120
+ // not a disconnected-account relogin failure: the accepted turn must wait
121
+ // until the row is re-enabled or the governing policy changes.
122
+ | { kind: "allocatorDisabled"; credentialId: string };
123
+
116
124
  export type CodexTurnLeaseSelection = {
117
125
  credentialId: string | null;
118
- decision: RotationDecision;
126
+ decision: CodexTurnLeaseDecision;
119
127
  /** Policy/manual homes never move the workspace-global legacy pointer. */
120
128
  advanceActivePointer?: boolean;
121
129
  };
@@ -391,74 +399,6 @@ export function computeIdleDelayMs(earliestResetAt: Date, now: Date, maxMs: numb
391
399
  return Math.min(Math.max(delta, MIN_IDLE_MS), maxMs);
392
400
  }
393
401
 
394
- // --- P3 reactive-rotation boundedness (Finding 1). The reactive 429 catch, on a
395
- // LIVE failover candidate, normally returns continueDelayMs:0 (skip the hold and
396
- // re-dispatch NOW — the just-served account is cooling so the next rank cannot
397
- // re-pick it). Two independent second-order faults can break that "cannot
398
- // re-pick it" premise and turn the 0-delay re-dispatch into a hot loop, so this
399
- // pure decision applies two backstops before allowing the 0.
400
-
401
- /**
402
- * Slow-retry floor (Finding 1a) for the double-fault where the just-served
403
- * account's cooldown write could NOT be confirmed persisted: the next proactive
404
- * rank might re-select the same capped account (stale-low cached usedPercent, not
405
- * cooling). A positive floor degrades that to a SLOW retry instead of a
406
- * model-paced hot loop. A few seconds — long enough to break the loop, short
407
- * enough to stay responsive once the transient write fault clears.
408
- */
409
- export const REACTIVE_PERSISTENCE_FAULT_FLOOR_MS = 5_000; // 5s
410
- /**
411
- * Circuit-breaker slack (Finding 1b) added to the connected-account count to bound
412
- * consecutive reactive failovers. Each legitimate failover cools one account, so
413
- * after at most N failovers every account is capped and the reactive path takes the
414
- * all-capped idle instead; the +margin absorbs benign capacity re-ranks without
415
- * tripping the breaker in normal use.
416
- */
417
- export const REACTIVE_ROTATION_MARGIN = 2;
418
- /**
419
- * The FIXED positive idle the reactive path falls to once consecutive reactive
420
- * failovers exceed the bound (a double-fault where cooldown writes are not sticking
421
- * AND the 429s carry no usage headers, so the same account keeps getting re-picked).
422
- * Mirrors the all-capped floor — a mandatory, bounded hold, never another 0-delay
423
- * re-dispatch — so the loop can never hammer the capped backend + DB (invariant 4).
424
- */
425
- export const REACTIVE_CIRCUIT_BREAKER_IDLE_MS = MIN_IDLE_MS; // 60s
426
-
427
- /** The reactive-resume shape returned to the goal-continuation caller. */
428
- export type ReactiveRotationResume = { continueDelayMs: number; idleUntilReset: boolean };
429
-
430
- /**
431
- * Decide the continueDelayMs for a reactive 429 failover onto a LIVE candidate,
432
- * bounding the (otherwise 0-delay) re-dispatch against two second-order faults:
433
- *
434
- * 1. Circuit breaker (1b): if the consecutive reactive-failover streak (prior
435
- * rotated 429 failovers since the last successful turn, PLUS this one) exceeds
436
- * `connectedAccountCount + REACTIVE_ROTATION_MARGIN`, fall to a FIXED positive,
437
- * MANDATORY idle. Covers the double-fault (cooldown write not persisted + a
438
- * header-less cap 429) where the same capped account is re-picked every turn.
439
- * 2. Persistence-fault floor (1a): if the just-served account's cooldown could NOT
440
- * be confirmed persisted, use a positive floor (slow retry) instead of 0.
441
- *
442
- * Otherwise (a confirmed cooldown + an in-bounds streak) returns the unchanged
443
- * 0-delay fast re-dispatch — the happy single-rotation path is byte-identical.
444
- * Pure so the boundedness contract is unit-testable without a worker/db env.
445
- */
446
- export function computeReactiveRotationResume(args: {
447
- cooldownPersisted: boolean;
448
- priorConsecutiveRotations: number; // reactive rotated failovers since last success (excludes this one)
449
- connectedAccountCount: number;
450
- }): ReactiveRotationResume {
451
- const streak = args.priorConsecutiveRotations + 1; // include the failover about to be published
452
- const bound = args.connectedAccountCount + REACTIVE_ROTATION_MARGIN;
453
- if (streak > bound) {
454
- return { continueDelayMs: REACTIVE_CIRCUIT_BREAKER_IDLE_MS, idleUntilReset: true };
455
- }
456
- if (!args.cooldownPersisted) {
457
- return { continueDelayMs: REACTIVE_PERSISTENCE_FAULT_FLOOR_MS, idleUntilReset: false };
458
- }
459
- return { continueDelayMs: 0, idleUntilReset: false };
460
- }
461
-
462
402
  /**
463
403
  * THE pure rotation ranker. `accounts` arrives in stable created_at order
464
404
  * (listCodexAccountStatuses), which deterministically breaks ranking ties.
@@ -567,69 +507,37 @@ export function chooseRotationActive(args: {
567
507
  return decide(chosen);
568
508
  }
569
509
 
570
- /**
571
- * Exact pre-0053 selector used while the lease cutover is off.
572
- *
573
- * Old workers keep a healthy `most_remaining` active pointer sticky and know
574
- * nothing about lease counts or fairness cursors. A compatible worker must do
575
- * the same until BOTH the deployment flag and workspace cutover are enabled;
576
- * otherwise a rolling fleet would run two allocators at once. When the active
577
- * pointer is no longer eligible, zeroing the additive metadata delegates to the
578
- * same capacity ranking that the old selector used.
579
- */
580
- export function chooseLegacyRotationActive(
581
- args: Parameters<typeof chooseRotationActive>[0],
582
- ): RotationDecision {
583
- if (args.rotationStrategy === "most_remaining") {
584
- const active = args.activeCredentialId
585
- ? args.accounts.find((account) => account.id === args.activeCredentialId)
586
- : undefined;
587
- if (active && isCodexCredentialEligible(active, args.now)) {
588
- return { kind: "active", credentialId: active.id, moved: false };
589
- }
590
- }
591
- return chooseRotationActive({
592
- ...args,
593
- accounts: args.accounts.map((account) => ({
594
- ...account,
595
- activeLeaseCount: 0,
596
- selectionCount: 0,
597
- lastSelectedAt: null,
598
- })),
599
- });
600
- }
601
-
602
510
  /**
603
511
  * Full pure policy at the transaction boundary. A live same-turn lease is
604
- * idempotent; the rollout-off/manual path preserves pin>pointer behavior; a
512
+ * idempotent; manual and rotation-off policy preserve pin>pointer behavior; a
605
513
  * healthy pin wins only while eligible, so quota/auth quarantine cannot trap a
606
514
  * session on one subscription.
607
515
  */
608
- export function selectCodexCredentialLeaseForTurn(args: {
609
- context: CodexCredentialLeaseSelectionContext;
610
- leasingEnabled: boolean;
516
+ export function selectCodexCredentialLeaseForTurn<
517
+ TPolicyScope = never,
518
+ TUnavailableDiagnostic = never,
519
+ >(args: {
520
+ context: CodexCredentialLeaseSelectionContext<TPolicyScope, TUnavailableDiagnostic>;
611
521
  sessionId: string;
612
522
  sessionPinnedCredentialId: string | null;
613
523
  sessionPinSource: CodexPinSource | null;
614
524
  sessionLastCredentialId: string | null;
615
525
  now: Date;
616
526
  }): CodexTurnLeaseSelection {
617
- const {
618
- accounts,
619
- activeCredentialId,
620
- rotationEnabled,
621
- leaseRotationEnabled,
622
- rotationStrategy,
623
- existingCredentialId,
624
- } = args.context;
625
- const leasingEnabled = args.leasingEnabled && leaseRotationEnabled;
527
+ const { accounts, activeCredentialId, rotationEnabled, rotationStrategy, existingCredentialId } =
528
+ args.context;
529
+ const failedCredentialIds = new Set(args.context.failedCredentialIds ?? []);
626
530
  // Normalized: rotation-enabled always behaves as sharded (see
627
531
  // effectiveRotationStrategy); the stored value is only ever legacy residue.
628
532
  const strategy = effectiveRotationStrategy(rotationStrategy);
629
533
  const existing = existingCredentialId
630
534
  ? accounts.find((account) => account.id === existingCredentialId)
631
535
  : undefined;
632
- if (existing && isCodexCredentialHealthy(existing, args.now)) {
536
+ if (
537
+ existing &&
538
+ !failedCredentialIds.has(existing.id) &&
539
+ isCodexCredentialHealthy(existing, args.now)
540
+ ) {
633
541
  return {
634
542
  credentialId: existing.id,
635
543
  advanceActivePointer: false,
@@ -641,10 +549,6 @@ export function selectCodexCredentialLeaseForTurn(args: {
641
549
  };
642
550
  }
643
551
 
644
- const connectedIds = new Set(
645
- accounts.filter((account) => account.allocatorEnabled).map((account) => account.id),
646
- );
647
-
648
552
  const pinDisposition = classifyCodexPin({
649
553
  pinnedCredentialId: args.sessionPinnedCredentialId,
650
554
  pinSource: args.sessionPinSource,
@@ -657,9 +561,16 @@ export function selectCodexCredentialLeaseForTurn(args: {
657
561
  // same-turn lease already returned above before this admission filter.
658
562
  if (pinDisposition === "manual" && args.sessionPinnedCredentialId) {
659
563
  const pinned = accounts.find((account) => account.id === args.sessionPinnedCredentialId);
660
- if (!pinned?.allocatorEnabled) {
564
+ if (!pinned) {
661
565
  return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
662
566
  }
567
+ if (!pinned.allocatorEnabled) {
568
+ return {
569
+ credentialId: null,
570
+ decision: { kind: "allocatorDisabled", credentialId: pinned.id },
571
+ advanceActivePointer: false,
572
+ };
573
+ }
663
574
  if (isCodexCredentialHealthy(pinned, args.now)) {
664
575
  return {
665
576
  credentialId: pinned.id,
@@ -682,13 +593,14 @@ export function selectCodexCredentialLeaseForTurn(args: {
682
593
  // primary/fallback pool before this ranker runs; accounts from different pools
683
594
  // are never union-ranked here.
684
595
  if (pinDisposition === "sharded") {
685
- if (accounts.length === 0) {
596
+ const unattemptedAccounts = accounts.filter((account) => !failedCredentialIds.has(account.id));
597
+ if (unattemptedAccounts.length === 0) {
686
598
  return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
687
599
  }
688
600
  const shard = chooseShardedHome({
689
601
  sessionId: args.sessionId,
690
602
  currentPolicyPin: args.sessionPinSource === "policy" ? args.sessionPinnedCredentialId : null,
691
- accounts,
603
+ accounts: unattemptedAccounts,
692
604
  now: args.now,
693
605
  });
694
606
  if (shard.kind === "allCapped") {
@@ -718,9 +630,16 @@ export function selectCodexCredentialLeaseForTurn(args: {
718
630
  const active = activeCredentialId
719
631
  ? accounts.find((account) => account.id === activeCredentialId)
720
632
  : undefined;
721
- if (!active?.allocatorEnabled) {
633
+ if (!active) {
722
634
  return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
723
635
  }
636
+ if (!active.allocatorEnabled) {
637
+ return {
638
+ credentialId: null,
639
+ decision: { kind: "allocatorDisabled", credentialId: active.id },
640
+ advanceActivePointer: false,
641
+ };
642
+ }
724
643
  if (!isCodexCredentialHealthy(active, args.now)) {
725
644
  return {
726
645
  credentialId: null,
@@ -735,31 +654,15 @@ export function selectCodexCredentialLeaseForTurn(args: {
735
654
  };
736
655
  }
737
656
 
738
- // Before the workspace cutover bit is enabled (or after the deployment kill
739
- // switch is turned off), preserve the exact legacy policy used by old workers:
740
- // a pin stays sticky; otherwise an enabled workspace runs the pure legacy
741
- // rotation ranker without touching lease/cursor state.
742
- if (!leasingEnabled && pinDisposition !== "clearStale" && args.sessionPinnedCredentialId) {
743
- const credentialId = connectedIds.has(args.sessionPinnedCredentialId)
744
- ? args.sessionPinnedCredentialId
745
- : activeCredentialId && connectedIds.has(activeCredentialId)
746
- ? activeCredentialId
747
- : null;
748
- return {
749
- credentialId,
750
- decision: credentialId ? { kind: "active", credentialId, moved: false } : { kind: "none" },
751
- };
752
- }
753
-
754
657
  const priorId = args.sessionLastCredentialId ?? activeCredentialId;
755
- const choose = leasingEnabled ? chooseRotationActive : chooseLegacyRotationActive;
756
- const decision = choose({
658
+ const unattemptedAccounts = accounts.filter((account) => !failedCredentialIds.has(account.id));
659
+ const decision = chooseRotationActive({
757
660
  rotationStrategy: strategy,
758
661
  activeCredentialId,
759
662
  // Per-session continuity is the round-robin/drain cursor. Falling back to
760
663
  // the workspace pointer is only correct when this session has never run.
761
664
  priorCredentialId: priorId,
762
- accounts,
665
+ accounts: unattemptedAccounts,
763
666
  now: args.now,
764
667
  });
765
668
  return {
@@ -99,6 +99,8 @@ export async function maybeCompactContext(
99
99
  * append again — the event is already durable.
100
100
  */
101
101
  publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;
102
+ /** Observe the durable start immediately after its attempt-fenced commit. */
103
+ onCompactionStarted?: (trigger: "auto" | "operator" | "proactive" | "overflow") => void;
102
104
  /** Materialize retained screenshot receipts only in the attempt-local model view. */
103
105
  materializeHistory?: (items: CompactionItem[]) => Promise<CompactionItem[]>;
104
106
  /** Turn-scoped attachment/modality view; canonical persisted rows stay untouched. */
@@ -208,6 +210,7 @@ export async function maybeCompactContext(
208
210
  `turn attempt was fenced while recording context compaction start: ${started.reason}`,
209
211
  );
210
212
  }
213
+ options.onCompactionStarted?.(trigger);
211
214
  await options.publishLiveEvents?.(started.events);
212
215
 
213
216
  if (useRemoteV2) {
@@ -2,6 +2,12 @@ import {
2
2
  allowedFirstPartyMcpToolsForSession,
3
3
  configuredStaticUsageLimits,
4
4
  policyProviderIdForModel,
5
+ resolveModelProvider,
6
+ resolveTurnExecutionPolicyV1,
7
+ withCodexCatalogProvider,
8
+ withXaiSubscriptionCatalogProvider,
9
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
10
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
5
11
  type Settings,
6
12
  } from "@opengeni/config";
7
13
  import {
@@ -28,6 +34,11 @@ import type {
28
34
  MaybeContinueGoalInput,
29
35
  MaybeContinueGoalResult,
30
36
  } from "./types";
37
+ import {
38
+ modelFundingForAdmission,
39
+ resolveCatalogSettings,
40
+ resolveWorkspaceCatalogSettings,
41
+ } from "@opengeni/core";
31
42
 
32
43
  export function createGoalActivities(services: () => Promise<ControlActivityServices>) {
33
44
  async function enqueueGoalRetryWake(input: MaybeContinueGoalInput): Promise<void> {
@@ -47,12 +58,15 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
47
58
  async function maybeContinueGoal(
48
59
  input: MaybeContinueGoalInput,
49
60
  ): Promise<MaybeContinueGoalResult> {
50
- const { settings, db, bus } = await services();
61
+ const service = await services();
62
+ const { db, bus } = service;
63
+ const catalogSourceSettings = service.catalogSourceSettings ?? service.settings;
51
64
  // Cheap pre-read: the common goal-less session skips the budget queries.
52
65
  const existingGoal = await getSessionGoal(db, input.workspaceId, input.sessionId);
53
66
  if (!existingGoal || existingGoal.status !== "active") {
54
67
  return { action: "none" };
55
68
  }
69
+ let settings = (await resolveCatalogSettings(db, catalogSourceSettings)).settings;
56
70
  // Loaded before the budget check so the codex-billed predicate and the
57
71
  // synthesized turn use the SAME effective policy. An explicit per-turn
58
72
  // model can differ from the persisted session default; follow-up goal work
@@ -66,34 +80,34 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
66
80
  input.workspaceId,
67
81
  input.sessionId,
68
82
  );
69
- let continuationModel = latestStartedTurn?.model ?? session.model;
83
+ const inheritedContinuationModel = latestStartedTurn?.model ?? session.model;
84
+ let continuationModel = inheritedContinuationModel;
70
85
  const continuationReasoningEffort =
71
86
  latestStartedTurn?.reasoningEffort ?? session.reasoningEffort;
72
87
  const continuationLatencyMode = latestStartedTurn?.latencyMode ?? session.latencyMode;
73
- // Workspace model policy: a continuation inherits the last STARTED turn's
74
- // model, so a single policy-violating turn would otherwise re-arm itself on
75
- // every continuation (exactly how one bare-model turn kept a goal loop on
76
- // the paid built-in provider all night). If the inherited model is blocked
77
- // but the session's own default is allowed, recover to the default; if
78
- // both are blocked, pause the goal visibly (the budget-pause channel, with
79
- // a truthful rationale) instead of synthesizing a turn the worker's hard
80
- // gate would fail over and over.
81
- let modelPolicyBlocked: string | null = null;
82
88
  const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);
83
- if (workspaceModelPolicy) {
84
- const policyBlocks = (modelId: string): boolean =>
85
- !evaluateWorkspaceModelPolicy(workspaceModelPolicy, {
86
- providerId: policyProviderIdForModel(settings, modelId),
87
- modelId,
88
- }).allowed;
89
- if (policyBlocks(continuationModel)) {
90
- if (continuationModel !== session.model && !policyBlocks(session.model)) {
91
- continuationModel = session.model;
92
- } else {
93
- modelPolicyBlocked = `workspace model policy blocks model "${continuationModel}"; pick an allowed model or change the workspace model policy`;
94
- }
95
- }
89
+ if (
90
+ inheritedContinuationModel.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||
91
+ inheritedContinuationModel.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX) ||
92
+ session.model.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||
93
+ session.model.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX)
94
+ ) {
95
+ settings = (
96
+ await resolveWorkspaceCatalogSettings(db, catalogSourceSettings, {
97
+ accountId: input.accountId,
98
+ workspaceId: input.workspaceId,
99
+ retainedProductModelIds: [inheritedContinuationModel, session.model],
100
+ })
101
+ ).settings;
96
102
  }
103
+ const modelDecision = goalContinuationModelDecision({
104
+ settings,
105
+ workspaceModelPolicy,
106
+ inheritedModel: inheritedContinuationModel,
107
+ sessionModel: session.model,
108
+ });
109
+ continuationModel = modelDecision.model;
110
+ let modelPolicyBlocked = modelDecision.blocked;
97
111
  // remote_v2 sessions may only continue on Codex models — refuse synthesis
98
112
  // that would leave the portable/non-Codex path (and mixed history shapes).
99
113
  if (
@@ -112,6 +126,11 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
112
126
  workspaceId: input.workspaceId,
113
127
  model: continuationModel,
114
128
  });
129
+ const fundedWithoutCredits = goalContinuationFundedWithoutCredits(
130
+ settings,
131
+ continuationModel,
132
+ isCodexRun,
133
+ );
115
134
  // Budget exhaustion pauses the goal visibly instead of failing the
116
135
  // session. Computed up front and applied inside the locked decision so a
117
136
  // limits pause never consumes continuation budget.
@@ -120,8 +139,17 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
120
139
  db,
121
140
  input.accountId,
122
141
  input.workspaceId,
123
- isCodexRun,
142
+ fundedWithoutCredits,
124
143
  );
144
+ const turnExecutionPolicy = resolveTurnExecutionPolicyV1(settings, {
145
+ modelId: continuationModel,
146
+ requestedModelId: null,
147
+ modelSource: "continuation",
148
+ reasoningEffort: continuationReasoningEffort,
149
+ reasoningSource: "continuation",
150
+ latencyMode: continuationLatencyMode,
151
+ latencyModeSource: "continuation",
152
+ });
125
153
  const decision = await materializeGoalContinuation(db, {
126
154
  accountId: input.accountId,
127
155
  workspaceId: input.workspaceId,
@@ -142,10 +170,11 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
142
170
  model: continuationModel,
143
171
  reasoningEffort: continuationReasoningEffort,
144
172
  latencyMode: continuationLatencyMode,
173
+ turnExecutionPolicy,
145
174
  tools: withFirstPartyTools(settings, session.tools),
146
175
  sandboxBackend: session.sandboxBackend,
147
176
  },
148
- // The hold guidance is only given when `goal_wait` is actually in this
177
+ // Long-wait guidance is only given when `wait_for_input` is actually in this
149
178
  // session's effective first-party selection (the same source the worker
150
179
  // signs into the delegated token and the API uses to register tools), so
151
180
  // a pre-existing narrowed selection is never told to call a missing tool.
@@ -155,7 +184,7 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
155
184
  session.firstPartyMcpTools,
156
185
  );
157
186
  return goalContinuationPrompt(goal, autoContinuation, cap, {
158
- goalWaitAvailable: effectiveFirstPartyTools.includes("goal_wait"),
187
+ inputWaitAvailable: effectiveFirstPartyTools.includes("wait_for_input"),
159
188
  humanInputRespondAvailable: effectiveFirstPartyTools.includes(
160
189
  "session_human_input_respond",
161
190
  ),
@@ -174,18 +203,66 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
174
203
  };
175
204
  }
176
205
 
206
+ export function goalContinuationModelDecision(input: {
207
+ settings: Settings;
208
+ workspaceModelPolicy: Awaited<ReturnType<typeof getWorkspaceModelPolicy>>;
209
+ inheritedModel: string;
210
+ sessionModel: string;
211
+ }): { model: string; blocked: string | null } {
212
+ const catalogSettings = input.settings.supergrokSubscriptionEnabled
213
+ ? withXaiSubscriptionCatalogProvider(
214
+ input.settings.codexSubscriptionEnabled
215
+ ? withCodexCatalogProvider(input.settings)
216
+ : input.settings,
217
+ )
218
+ : input.settings.codexSubscriptionEnabled
219
+ ? withCodexCatalogProvider(input.settings)
220
+ : input.settings;
221
+ const policyBlocks = (modelId: string): boolean =>
222
+ input.workspaceModelPolicy !== null &&
223
+ !evaluateWorkspaceModelPolicy(input.workspaceModelPolicy, {
224
+ providerId: policyProviderIdForModel(catalogSettings, modelId),
225
+ modelId,
226
+ }).allowed;
227
+ const candidates = [...new Set([input.inheritedModel, input.sessionModel])];
228
+ for (const model of candidates) {
229
+ if (resolveModelProvider(catalogSettings, model) && !policyBlocks(model)) {
230
+ return { model, blocked: null };
231
+ }
232
+ }
233
+ if (!resolveModelProvider(catalogSettings, input.inheritedModel)) {
234
+ return {
235
+ model: input.inheritedModel,
236
+ blocked: `model "${input.inheritedModel}" is no longer in the deployment or workspace catalog; choose an available model before resuming the goal`,
237
+ };
238
+ }
239
+ return {
240
+ model: input.inheritedModel,
241
+ blocked: `workspace model policy blocks model "${input.inheritedModel}"; pick an allowed model or change the workspace model policy`,
242
+ };
243
+ }
244
+
245
+ export function goalContinuationFundedWithoutCredits(
246
+ settings: Settings,
247
+ model: string,
248
+ codexBilled: boolean,
249
+ ): boolean {
250
+ return modelFundingForAdmission(settings, model, codexBilled).fundedWithoutCredits;
251
+ }
252
+
177
253
  export function goalContinuationPrompt(
178
254
  _goal: SessionGoal,
179
255
  _autoContinuation: number,
180
256
  _cap: number | null,
181
- options: { goalWaitAvailable?: boolean; humanInputRespondAvailable?: boolean } = {},
257
+ options: { inputWaitAvailable?: boolean; humanInputRespondAvailable?: boolean } = {},
182
258
  ): string {
183
- const waitingGuidance = options.goalWaitAvailable
259
+ const waitingGuidance = options.inputWaitAvailable
184
260
  ? [
185
- "Waiting on child sessions or external events:",
186
- "- 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.",
187
- "- 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.",
188
- "- 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.",
261
+ "Waiting on child sessions, background commands, or external events:",
262
+ "- When further progress depends on work already in flight, do not sleep, loop, or poll session or command state repeatedly.",
263
+ "- 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.",
264
+ "- 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.",
265
+ "- If you are blocked on a human decision, use opengeni__goal_pause under the blocked audit below instead.",
189
266
  "",
190
267
  ]
191
268
  : [];
@@ -269,13 +346,13 @@ async function goalRunBudgetBlocked(
269
346
  db: Database,
270
347
  accountId: string,
271
348
  workspaceId: string,
272
- isCodexRun: boolean,
349
+ fundedWithoutCredits: boolean,
273
350
  ): Promise<string | null> {
274
- // Codex-billed continuations are paid by the user's ChatGPT/Codex plan: skip
275
- // the credit-balance gate and the monthly model-cost cap. The agent-run COUNT
276
- // cap below is a volume quota (not a credit/cost gate) and is intentionally kept.
351
+ // Free, subscription, and workspace-funded continuations skip OpenGeni's
352
+ // credit-balance gate and monthly model-cost cap. The agent-run COUNT cap
353
+ // below is a volume quota (not a credit/cost gate) and remains enforced.
277
354
  if (
278
- !isCodexRun &&
355
+ !fundedWithoutCredits &&
279
356
  (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")
280
357
  ) {
281
358
  const balance = await getBillingBalance(db, accountId);
@@ -285,7 +362,7 @@ async function goalRunBudgetBlocked(
285
362
  }
286
363
  if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
287
364
  const limits = configuredStaticUsageLimits(settings);
288
- if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {
365
+ if (!fundedWithoutCredits && limits.maxMonthlyCostMicrosPerAccount) {
289
366
  const used = await sumUsageQuantity(db, {
290
367
  accountId,
291
368
  eventType: "model.cost",