@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
@@ -1,5 +1,8 @@
1
1
  import { measureMcpPhase, withMcpCallIdentity } from "@opengeni/observability";
2
2
  import {
3
+ appendSessionHistoryItems,
4
+ sessionTurnFinalReplyFacts,
5
+ sessionTurnHasFinalReplyNudge,
3
6
  getSessionEvent,
4
7
  getHumanInputResumeForEvent,
5
8
  getSessionHumanInputRequest,
@@ -85,19 +88,20 @@ import {
85
88
  import {
86
89
  OPEN_SUFFIX_RUN_STATE_BLOB,
87
90
  resolveWorkspaceAgentHumanInputEnabled,
91
+ withPublicApprovalFields,
88
92
  type RetainedArtifactMetadata,
89
93
  type SessionEvent,
90
94
  type SessionTurn,
91
95
  } from "@opengeni/contracts";
92
96
  import { createModelCheckpointMemoryCollector } from "../../model-checkpoint-memory-collector";
97
+ import { createModelCallAdmission } from "./model-call-admission";
93
98
 
94
99
  import {
95
100
  assertWorkspaceHumanInputAllowed,
96
101
  stableHumanInputRequestId,
97
102
  stableInteractionInterventionId,
98
103
  stableInteractionInterventionOperationId,
99
- BudgetExhaustedError,
100
- ensureRunAllowed,
104
+ ensureRunAllowedBetweenModelCalls,
101
105
  } from "./admission";
102
106
  import {
103
107
  compactionFailureReason,
@@ -141,6 +145,7 @@ import {
141
145
  import { inputWaitReply, latestDurableTurnMessageText } from "./input-wait-reply";
142
146
  import { waitForTurnOperation } from "./sandbox-provision";
143
147
  import { createSharedRigSetupCoordinator } from "./sandbox-shared-preparation";
148
+ import { finalReplyNudge, needsFinalReply } from "./final-reply";
144
149
 
145
150
  import type { CompactionSummarizer } from "../context-compaction";
146
151
  import type { TurnExecutionPolicyV1 } from "@opengeni/contracts";
@@ -235,6 +240,7 @@ export type TurnStreamAttemptDeps = {
235
240
  groupBoxBackend: Settings["sandboxBackend"];
236
241
  turnExecutionPolicy: TurnExecutionPolicyV1;
237
242
  turn: Pick<SessionTurn, "initiator" | "initiatorContext"> & {
243
+ initiatingHumanSubjectId: string | null;
238
244
  id: string;
239
245
  executionGeneration: number;
240
246
  model: string;
@@ -583,14 +589,41 @@ export async function runTurnStreamAttempt(
583
589
  // durably: the reply a wait-ended human turn records on turn.completed.
584
590
  let latestAssistantMessageText: string | null = null;
585
591
  let workerPreparationTotalRecorded = false;
592
+ let toolsExecuted = false;
593
+ let finalReplyNudged = false;
594
+ const revalidateModelCallAdmission = async () => {
595
+ await historySink.reconcileConversationTruth({ requireDurable: true });
596
+ await ensureRunAllowedBetweenModelCalls({
597
+ settings,
598
+ db,
599
+ accountId: input.accountId,
600
+ workspaceId: input.workspaceId,
601
+ isExternallyBilledTurn: billingState.isExternallyBilledTurn,
602
+ entitlements,
603
+ chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
604
+ countsTowardTokenCap: billingState.countsTowardTokenCap,
605
+ initiatingHumanSubjectId: turn.initiatingHumanSubjectId,
606
+ });
607
+ };
586
608
  const runStreamAttempt = async (options: {
587
609
  requireTerminalModelResponse: boolean;
588
- }): Promise<RunAgentTurnResult> => {
610
+ }): Promise<RunAgentTurnResult | "reply_nudge"> => {
589
611
  if (!runInput) {
590
612
  throw new Error("Run input was not prepared");
591
613
  }
592
- const responseCountBeforeStream = modelResponseState.responseCount;
614
+ // The previous stream was persisted before compaction; the sink is now
615
+ // seeded from its durable replacement. Do not reconcile the old prefix
616
+ // against that replacement while checking the next stream's admission.
593
617
  eventing.stream = undefined;
618
+ // Compaction commits its paid usage and replacement history before this
619
+ // boundary, both during preparation and in-activity recovery. Revalidate
620
+ // the accepted turn's frozen human before another stream can dispatch.
621
+ if (options.requireTerminalModelResponse) await revalidateModelCallAdmission();
622
+ const modelCallAdmission = createModelCallAdmission({
623
+ signal: runtimeCancellationSignal,
624
+ admit: revalidateModelCallAdmission,
625
+ });
626
+ const responseCountBeforeStream = modelResponseState.responseCount;
594
627
  eventing.batcher = null;
595
628
  // The SDK emits every processed call item for one model response before
596
629
  // it emits any result for that response. Keep that response-local batch
@@ -806,6 +839,8 @@ export async function runTurnStreamAttempt(
806
839
  }
807
840
  attempt.modelRequestStarted = true;
808
841
  return await runtime.runStream(agent, runInput!, eventing.modelRunSettings, {
842
+ beforeModelRequest: modelCallAdmission.beforeModelRequest,
843
+ onModelResponse: modelCallAdmission.onModelResponse,
809
844
  signal: runtimeCancellationSignal,
810
845
  sandboxEnvironment,
811
846
  onModelVisibleContext: async (snapshot) => {
@@ -941,7 +976,13 @@ export async function runTurnStreamAttempt(
941
976
  if (leases.xai.lost) {
942
977
  throw new Error("xAI credential lease expired before the model run");
943
978
  }
944
- eventing.stream = await withProviderRequestContext(runStreamOnce);
979
+ try {
980
+ eventing.stream = await withProviderRequestContext(runStreamOnce);
981
+ } catch (error) {
982
+ modelCallAdmission.fail(error);
983
+ modelCallAdmission.close();
984
+ throw error;
985
+ }
945
986
  // Bounded provider label for the streaming SLIs — the resolved registry
946
987
  // provider id (or the built-in OpenAI/Azure provider), never a raw
947
988
  // user-supplied model string.
@@ -1094,35 +1135,22 @@ export async function runTurnStreamAttempt(
1094
1135
  await historySink.reconcileConversationTruth();
1095
1136
  turnLifecycleMetricsFor(observability).progress({ attemptId: input.attemptId });
1096
1137
  modelCheckpointMemoryCollector.schedule(observability);
1097
- try {
1098
- await ensureRunAllowed(
1099
- settings,
1100
- db,
1101
- input.accountId,
1102
- input.workspaceId,
1103
- billingState.isExternallyBilledTurn,
1104
- entitlements,
1105
- billingState.chargesOpenGeniCredits,
1106
- billingState.countsTowardTokenCap,
1107
- );
1108
- } catch (limitError) {
1109
- // Capture the run state at the boundary so the budget valve in
1110
- // the outer catch can end this segment gracefully with full
1111
- // conversation context preserved for the post-top-up resume.
1112
- let serializedRunState: string | null = null;
1113
- try {
1114
- serializedRunState = media.compactMediaRunState(
1115
- String(eventing.stream.state.toString()),
1116
- );
1117
- } catch {
1118
- serializedRunState = null;
1119
- }
1120
- throw new BudgetExhaustedError(
1121
- limitError instanceof Error ? limitError.message : String(limitError),
1122
- serializedRunState,
1123
- );
1124
- }
1138
+ await ensureRunAllowedBetweenModelCalls({
1139
+ settings,
1140
+ db,
1141
+ accountId: input.accountId,
1142
+ workspaceId: input.workspaceId,
1143
+ isExternallyBilledTurn: billingState.isExternallyBilledTurn,
1144
+ entitlements,
1145
+ chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
1146
+ countsTowardTokenCap: billingState.countsTowardTokenCap,
1147
+ initiatingHumanSubjectId: turn.initiatingHumanSubjectId,
1148
+ serializedRunState: () =>
1149
+ media.compactMediaRunState(String(eventing.stream!.state.toString())),
1150
+ });
1125
1151
  }
1152
+ // Release only after both the debit and frozen-human admission finish.
1153
+ modelCallAdmission.settle(next.value);
1126
1154
  const durableSdkEvent = generatedImageReceipt
1127
1155
  ? compactGeneratedImageSdkEvent(next.value, generatedImageReceipt)
1128
1156
  : next.value;
@@ -1159,6 +1187,7 @@ export async function runTurnStreamAttempt(
1159
1187
  }
1160
1188
  const completedToolCall = completedToolCallFromSdkEvent(durableSdkEvent);
1161
1189
  if (completedToolCall) {
1190
+ toolsExecuted = true;
1162
1191
  retainedScreenshotMetadata =
1163
1192
  media.retainedScreenshotReceiptsByCallId.get(completedToolCall.callId) ?? null;
1164
1193
  const typedScreenshot = retainedScreenshotMetadata
@@ -1396,6 +1425,7 @@ export async function runTurnStreamAttempt(
1396
1425
  }
1397
1426
  }
1398
1427
  } catch (error) {
1428
+ modelCallAdmission.fail(error);
1399
1429
  // Event processing can fail while SDK completion is still pending.
1400
1430
  // Close this stream before any failure publication; a legitimate
1401
1431
  // compaction retry may start a new, independently fenced generation.
@@ -1451,6 +1481,7 @@ export async function runTurnStreamAttempt(
1451
1481
  }
1452
1482
  throw error;
1453
1483
  } finally {
1484
+ modelCallAdmission.close();
1454
1485
  if (!streamDone) {
1455
1486
  // ReadableStream cancellation synchronously trips the Agents SDK's
1456
1487
  // abort controller, but its returned promise may wait for an
@@ -1472,7 +1503,10 @@ export async function runTurnStreamAttempt(
1472
1503
  // External Codemode stays reachable until finalization. Close wait
1473
1504
  // admission before any terminal output/history decision, and drain an
1474
1505
  // already-admitted wait before consulting the actual runner-yield latch.
1475
- await eventing.preparedTools?.inputWaitYield?.sealForSettlement(runtimeCancellationSignal);
1506
+ // Drain trusted receipts before deciding whether an empty stream may need
1507
+ // a handoff. Do not terminally seal the attempt until that decision: the
1508
+ // one same-turn stream still uses the ordinary input-wait admission gate.
1509
+ await eventing.preparedTools?.inputWaitYield?.drainForHandoff(runtimeCancellationSignal);
1476
1510
  if (
1477
1511
  options.requireTerminalModelResponse &&
1478
1512
  !eventing.preparedTools?.inputWaitYield?.yielded &&
@@ -1585,6 +1619,7 @@ export async function runTurnStreamAttempt(
1585
1619
  }
1586
1620
  }
1587
1621
  if (eventing.stream.interruptions.length > 0) {
1622
+ await eventing.preparedTools?.inputWaitYield?.sealForSettlement(runtimeCancellationSignal);
1588
1623
  await historySink.reconcileConversationTruth({ requireDurable: true });
1589
1624
  const approvals = runtime.serializeApprovals(eventing.stream.interruptions);
1590
1625
  const humanInputInterruptions =
@@ -1702,9 +1737,11 @@ export async function runTurnStreamAttempt(
1702
1737
  type: "session.requiresAction" as const,
1703
1738
  payload: {
1704
1739
  approvals: approvals.map((approval) =>
1705
- withMcpToolDisplayMetadata(
1706
- eventing.preparedTools?.mcpServers ?? [],
1707
- approval,
1740
+ withPublicApprovalFields(
1741
+ withMcpToolDisplayMetadata(
1742
+ eventing.preparedTools?.mcpServers ?? [],
1743
+ approval,
1744
+ ),
1708
1745
  ),
1709
1746
  ),
1710
1747
  },
@@ -1739,6 +1776,60 @@ export async function runTurnStreamAttempt(
1739
1776
  const finalOutput = String(
1740
1777
  requireAgentStreamFinalOutput(eventing.stream.finalOutput, inputWaitYielded),
1741
1778
  );
1779
+ const durableReplyFacts =
1780
+ !inputWaitYielded && finalOutput.trim().length === 0
1781
+ ? await sessionTurnFinalReplyFacts(db, input.workspaceId, input.sessionId, activeTurnId)
1782
+ : { toolsExecuted: false, completedGoal: false };
1783
+ let emptyFinalReply = false;
1784
+ if (
1785
+ needsFinalReply({
1786
+ output: finalOutput,
1787
+ inputWaitYielded:
1788
+ inputWaitYielded || eventing.preparedTools?.inputWaitYield?.requested === true,
1789
+ interrupted: false, // interruption settlement returned above
1790
+ maintenance: turn.source === "compaction",
1791
+ toolsExecuted: toolsExecuted || finalReplyNudged || durableReplyFacts.toolsExecuted,
1792
+ completedGoal: durableReplyFacts.completedGoal,
1793
+ })
1794
+ ) {
1795
+ await historySink.reconcileConversationTruth({ requireDurable: true });
1796
+ // Consult retained truth, including inactive compacted rows, so an
1797
+ // attempt replacement or compaction cannot spend this bound again.
1798
+ if (
1799
+ finalReplyNudged ||
1800
+ (await sessionTurnHasFinalReplyNudge(
1801
+ db,
1802
+ input.workspaceId,
1803
+ input.sessionId,
1804
+ activeTurnId,
1805
+ finalReplyNudge(activeTurnId).content[0]!.text,
1806
+ ))
1807
+ ) {
1808
+ // A second empty response is a delivery-quality notice, not failed
1809
+ // execution: preserve goal continuation and later machine-input wakes.
1810
+ emptyFinalReply = true;
1811
+ } else {
1812
+ const appended = await appendSessionHistoryItems(db, {
1813
+ accountId: input.accountId,
1814
+ workspaceId: input.workspaceId,
1815
+ sessionId: input.sessionId,
1816
+ turnId: activeTurnId,
1817
+ expectedExecutionGeneration: attempt.executionGeneration,
1818
+ expectedAttemptId: input.attemptId,
1819
+ items: [
1820
+ {
1821
+ position: await nextSessionHistoryPosition(db, input.workspaceId, input.sessionId),
1822
+ item: finalReplyNudge(activeTurnId),
1823
+ },
1824
+ ],
1825
+ });
1826
+ if (!appended) throw new TurnAttemptFencedError("turn ended before final reply handoff");
1827
+ finalReplyNudged = true;
1828
+ await prepareRunAttemptInput();
1829
+ return "reply_nudge";
1830
+ }
1831
+ }
1832
+ await eventing.preparedTools?.inputWaitYield?.sealForSettlement(runtimeCancellationSignal);
1742
1833
  // The final output is the newest message this stream completed, already
1743
1834
  // durable with its provider identity and phase. A phase-less settlement
1744
1835
  // copy is published only when this stream did not complete that text.
@@ -1773,7 +1864,11 @@ export async function runTurnStreamAttempt(
1773
1864
  : [{ type: "agent.message.completed" as const, payload: { text: finalOutput } }]),
1774
1865
  {
1775
1866
  type: "turn.completed",
1776
- payload: { output: finalOutput, ...(reply === null ? {} : { reply }) },
1867
+ payload: {
1868
+ output: finalOutput,
1869
+ ...(reply === null ? {} : { reply }),
1870
+ ...(emptyFinalReply ? { emptyFinalReply: true } : {}),
1871
+ },
1777
1872
  },
1778
1873
  { type: "session.status.changed", payload: { status: "idle" } },
1779
1874
  ],
@@ -1834,6 +1929,9 @@ export async function runTurnStreamAttempt(
1834
1929
  ) {
1835
1930
  return claimedResult({ status: "cancelled" });
1836
1931
  }
1932
+ // Preparation may have spent the last allowance on a completed summary.
1933
+ // Neither the title sidecar nor ordinary inference may dispatch afterward.
1934
+ await revalidateModelCallAdmission();
1837
1935
  if (
1838
1936
  turn.source !== "compaction" &&
1839
1937
  generateSessionTitleInParallel &&
@@ -1871,11 +1969,19 @@ export async function runTurnStreamAttempt(
1871
1969
  }
1872
1970
  try {
1873
1971
  let retriedAfterCompaction = false;
1972
+ finalReplyNudged = await sessionTurnHasFinalReplyNudge(
1973
+ db,
1974
+ input.workspaceId,
1975
+ input.sessionId,
1976
+ activeTurnId,
1977
+ finalReplyNudge(activeTurnId).content[0]!.text,
1978
+ );
1874
1979
  while (true) {
1875
1980
  try {
1876
1981
  const result = await runStreamAttempt({
1877
1982
  requireTerminalModelResponse: retriedAfterCompaction,
1878
1983
  });
1984
+ if (result === "reply_nudge") continue;
1879
1985
  if (retriedAfterCompaction) {
1880
1986
  observability.info("context compaction recovery succeeded after in-activity retry", {
1881
1987
  sessionId: input.sessionId,
@@ -68,8 +68,10 @@ import {
68
68
  buildApiIntegrationMcpServers,
69
69
  resolveCatalogSettings,
70
70
  resolveWorkspaceModelSelection,
71
+ loadWorkspaceCodexModelAvailability,
71
72
  withFrozenPersonalConnectionDelegations,
72
- resolveSessionToolPolicy,
73
+ resolveTurnToolPolicy,
74
+ scheduledTurnMcpServerIds,
73
75
  hasPermission,
74
76
  } from "@opengeni/core";
75
77
  import { loadWorkspaceEnvironmentForRunWithCredentials } from "../environment";
@@ -87,6 +89,7 @@ import { SandboxChannelAService } from "@opengeni/runtime/sandbox";
87
89
  import { sandboxRunAs } from "@opengeni/runtime";
88
90
  import {
89
91
  DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,
92
+ resolveAgentToolFamilies,
90
93
  type ResourceRef,
91
94
  type ToolAuthNeededPayload,
92
95
  } from "@opengeni/contracts";
@@ -223,38 +226,36 @@ export async function prepareTurnToolPolicy(deps: PrepareTurnToolPolicyDeps) {
223
226
  // sessions follow the current configured MCP set,
224
227
  // while explicit, inherited-fixed, and legacy sessions remain narrowed
225
228
  // to their stored materialized allow-list.
226
- const scheduledEffectiveMcpServerIds = (() => {
227
- const value =
228
- turn.metadata && typeof turn.metadata === "object" && !Array.isArray(turn.metadata)
229
- ? (turn.metadata as Record<string, unknown>).scheduledEffectiveMcpServerIds
230
- : null;
231
- return Array.isArray(value) && value.every((id) => typeof id === "string")
232
- ? [...new Set(value)].sort()
233
- : null;
234
- })();
235
- const currentMcpServerIds = new Set(runSettings.mcpServers.map((server) => server.id));
236
- const resolvedToolPolicy = resolveSessionToolPolicy({
229
+ const resolvedToolPolicy = resolveTurnToolPolicy({
237
230
  toolPolicy: session.toolPolicy,
238
- sessionTools: scheduledEffectiveMcpServerIds ? turn.tools : session.tools,
239
- availableMcpServerIds: scheduledEffectiveMcpServerIds
240
- ? scheduledEffectiveMcpServerIds.filter((id) => currentMcpServerIds.has(id))
241
- : [...currentMcpServerIds],
231
+ session,
232
+ turn,
233
+ availableMcpServerIds: runSettings.mcpServers.map((server) => server.id),
242
234
  defaultMcpServerIds:
243
- scheduledEffectiveMcpServerIds ??
244
- (session.toolPolicy.mode === "workspace_default"
235
+ scheduledTurnMcpServerIds(turn) === null && session.toolPolicy.mode === "workspace_default"
245
236
  ? await workspaceSessionToolPolicyDefaultServerIds(
246
237
  db,
247
238
  input.workspaceId,
248
239
  capabilitySettings,
249
240
  fileAuthoritySubjectId ?? undefined,
250
241
  )
251
- : []),
242
+ : [],
252
243
  });
253
244
  const mcpAvailabilityNote = unavailableMcpOperationalContext({
254
245
  droppedIds: resolvedToolPolicy.effectivePolicy.droppedIds,
255
246
  droppedCount: resolvedToolPolicy.effectivePolicy.counts.dropped,
256
247
  });
257
- const effectivePolicyTools = resolvedToolPolicy.toolRefs;
248
+ const families = resolveAgentToolFamilies(session.agent, {
249
+ productServerIds: new Set([
250
+ ...session.mcpServers.map((server) => server.id),
251
+ ...(session.toolPolicy.mode !== "workspace_default"
252
+ ? session.tools.map((tool) => tool.id)
253
+ : []),
254
+ ]),
255
+ });
256
+ const effectivePolicyTools = resolvedToolPolicy.toolRefs.filter(
257
+ (tool) => tool.kind !== "mcp" || families.allowsMcpServer(tool.id),
258
+ );
258
259
  const turnTools = withFirstPartyTools(runSettings, effectivePolicyTools);
259
260
  // §7.6 connection-credential provider — load (and decrypt) selected Variable Sets via the
260
261
  // host `sandboxSecrets` provider when bound; unset → today's local decrypt. Preserve the
@@ -590,14 +591,16 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
590
591
  (permission) => hasPermission(linkedAuthority.permissions, permission),
591
592
  )
592
593
  : session.firstPartyMcpPermissions;
593
- const selectedFirstPartyMcpTools = allowedFirstPartyMcpToolsForSession(
594
- runSettings,
595
- session.firstPartyMcpTools,
594
+ const toolFamilies = resolveAgentToolFamilies(session.agent);
595
+ const selectedFirstPartyMcpTools = toolFamilies.firstPartyTools(
596
+ allowedFirstPartyMcpToolsForSession(runSettings, session.firstPartyMcpTools),
596
597
  );
597
598
  const titleToolPlan = sessionTitleToolPlan({
599
+ agentConfig: session.agent,
598
600
  tools: turnTools,
599
601
  selectedFirstPartyMcpTools,
600
602
  shouldRequestTitle: shouldRequestMissingSessionTitle({
603
+ agentConfig: session.agent,
601
604
  title: session.title,
602
605
  titleSource: session.titleSource,
603
606
  firstPartyMcpTools: selectedFirstPartyMcpTools,
@@ -669,20 +672,23 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
669
672
  workspaceId: input.workspaceId,
670
673
  ...(deps.fileAuthoritySubjectId ? { subjectId: deps.fileAuthoritySubjectId } : {}),
671
674
  });
672
- const skillCatalog = [
673
- ...sharedSkillDescriptors
674
- .filter((entry) => entry.activationMode === "workspace_managed")
675
- .map((entry) => ({
676
- id: entry.id,
677
- name: entry.title,
678
- description: entry.description,
679
- })),
680
- ...selectedSkills.map((entry) => ({
681
- id: entry.id,
682
- name: entry.artifact.name,
683
- description: entry.artifact.description || entry.artifact.name,
684
- })),
685
- ];
675
+ const skillCatalog =
676
+ toolFamilies.skills === false
677
+ ? []
678
+ : [
679
+ ...sharedSkillDescriptors
680
+ .filter((entry) => entry.activationMode === "workspace_managed")
681
+ .map((entry) => ({
682
+ id: entry.id,
683
+ name: entry.title,
684
+ description: entry.description,
685
+ })),
686
+ ...selectedSkills.map((entry) => ({
687
+ id: entry.id,
688
+ name: entry.artifact.name,
689
+ description: entry.artifact.description || entry.artifact.name,
690
+ })),
691
+ ];
686
692
  const skillTools = createWorkspaceSkillTools({
687
693
  db,
688
694
  settings: runSettings,
@@ -861,6 +867,9 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
861
867
  );
862
868
  },
863
869
  });
870
+ const attemptToolFamilies = resolveAgentToolFamilies(session.agent, {
871
+ hasSkills: skillCatalog.length > 0,
872
+ });
864
873
  const attemptToolDefinitions = [
865
874
  ...(operationReadStore
866
875
  ? [
@@ -908,6 +917,7 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
908
917
  organizationGatewayCustomModels,
909
918
  organizationOpenRouterConnectionActive,
910
919
  organizationOpenRouterCustomModels,
920
+ codexModelAvailability,
911
921
  ] = await Promise.all([
912
922
  getWorkspaceConnectionModelRestrictions(
913
923
  db,
@@ -953,9 +963,11 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
953
963
  workspaceId: input.workspaceId,
954
964
  providerKind: "openrouter",
955
965
  }),
966
+ loadWorkspaceCodexModelAvailability(db, currentSettings, input.workspaceId),
956
967
  ]);
957
968
  return {
958
969
  selections: resolveWorkspaceModelSelection({
970
+ observations: codexModelAvailability,
959
971
  connectionModelRestrictions,
960
972
  settings: currentSettings,
961
973
  policy,
@@ -1017,7 +1029,7 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
1017
1029
  ? [googleDrivePublicationTool]
1018
1030
  : []),
1019
1031
  ...codeSearchTools,
1020
- ];
1032
+ ].filter((tool) => attemptToolFamilies.allowsFunctionTool(tool.modelName));
1021
1033
  recordTurnStartupPhase(observability, {
1022
1034
  phase: "tool_context_preparation",
1023
1035
  provider: turnExecutionPolicy.providerId,
@@ -1110,7 +1122,7 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
1110
1122
  sessionAttachedRemoteMcpTargets: selectedSessionRemoteMcpTargets(
1111
1123
  githubRestMcp.settings,
1112
1124
  session.mcpServers ?? [],
1113
- turn.tools ?? [],
1125
+ githubRestMcp.tools,
1114
1126
  localMcpServers,
1115
1127
  ),
1116
1128
  ...(deps.runMcpCredentials ? { runMcpCredentials: deps.runMcpCredentials } : {}),
@@ -48,6 +48,7 @@ export type TurnSettleFn = (input: {
48
48
  sessionStatus: SessionStatus;
49
49
  activeTurnId: string | null;
50
50
  suppressGoalContinuation?: boolean;
51
+ allowanceGoalPause?: ApplySessionTurnSettlementInput["allowanceGoalPause"];
51
52
  consumeRequestedCompactionFailure?: boolean;
52
53
  runState?: ApplySessionTurnSettlementInput["runState"];
53
54
  }) => Promise<boolean>;
@@ -4,8 +4,11 @@ import {
4
4
  WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
5
5
  } from "@opengeni/config";
6
6
  import {
7
+ agentConfigMayResolve,
8
+ applySessionAgentConfigWriteThrough,
7
9
  assertWorkspaceModelPolicyAllows,
8
10
  canonicalConfiguredModel,
11
+ resolveSessionAgentConfigForCreate,
9
12
  createAndStartSessionWithOutcome,
10
13
  recordWorkspaceUsage,
11
14
  resolveCatalogSettings,
@@ -16,6 +19,7 @@ import {
16
19
  assertAutomationRunAuthorityInTransaction,
17
20
  claimAutomationRun,
18
21
  settleAutomationRun,
22
+ requireWorkspace,
19
23
  } from "@opengeni/db";
20
24
  import { SessionSkills } from "@opengeni/contracts";
21
25
  import { agentRunAdmissionDenial } from "./agent-run-admission";
@@ -30,6 +34,8 @@ export type AutomationActivityOptions = {
30
34
  settle?: typeof settleAutomationRun;
31
35
  assertAuthority?: typeof assertAutomationRunAuthorityInTransaction;
32
36
  createSession?: typeof createAndStartSessionWithOutcome;
37
+ /** Workspace read for agent-configuration defaults (tests inject it). */
38
+ readWorkspace?: typeof requireWorkspace;
33
39
  admit?: typeof agentRunAdmissionDenial;
34
40
  assertModelPolicy?: typeof assertWorkspaceModelPolicyAllows;
35
41
  recordUsage?: typeof recordWorkspaceUsage;
@@ -43,6 +49,7 @@ export function createAutomationActivities(
43
49
  const settle = options.settle ?? settleAutomationRun;
44
50
  const assertAuthority = options.assertAuthority ?? assertAutomationRunAuthorityInTransaction;
45
51
  const createSession = options.createSession ?? createAndStartSessionWithOutcome;
52
+ const readWorkspace = options.readWorkspace ?? requireWorkspace;
46
53
  const admit = options.admit ?? agentRunAdmissionDenial;
47
54
  const assertModelPolicy = options.assertModelPolicy ?? assertWorkspaceModelPolicyAllows;
48
55
  const recordUsage = options.recordUsage ?? recordWorkspaceUsage;
@@ -158,6 +165,50 @@ export function createAutomationActivities(
158
165
  reason: "interactive_compute_not_allowed",
159
166
  };
160
167
  }
168
+ // Agent configuration for the generated session (null = legacy). The
169
+ // template's explicit tools are its baseline; capabilities only narrow.
170
+ let agentWriteThrough: {
171
+ config: import("@opengeni/contracts").ResolvedAgentConfig | null;
172
+ instructions: string | undefined;
173
+ firstPartyMcpTools: typeof template.firstPartyMcpTools;
174
+ tools: typeof template.tools;
175
+ };
176
+ try {
177
+ const workspaceSettings = agentConfigMayResolve(catalogSettings, template.agent)
178
+ ? (await readWorkspace(service.db, input.workspaceId)).settings
179
+ : {};
180
+ const resolution = resolveSessionAgentConfigForCreate({
181
+ settings: catalogSettings,
182
+ creator: "automation",
183
+ request: template.agent,
184
+ instructions: template.instructions ?? undefined,
185
+ workspaceSettings,
186
+ parent: null,
187
+ goal: false,
188
+ });
189
+ const written = applySessionAgentConfigWriteThrough({
190
+ config: resolution.config,
191
+ firstPartyMcpTools: template.firstPartyMcpTools,
192
+ tools: template.tools,
193
+ toolPolicy: { mode: "explicit", inheritedFromSessionId: null },
194
+ productServerIds: template.tools.map((tool) => tool.id),
195
+ });
196
+ agentWriteThrough = {
197
+ config: resolution.config,
198
+ instructions: resolution.instructions,
199
+ firstPartyMcpTools: written.firstPartyMcpTools,
200
+ tools: written.tools,
201
+ };
202
+ } catch (error) {
203
+ if (!isUnprocessableEntity(error)) throw error;
204
+ await settle(service.db, {
205
+ workspaceId: input.workspaceId,
206
+ runId: run.id,
207
+ status: "failed",
208
+ errorCode: "dispatch_failed",
209
+ });
210
+ return { action: "failed", reason: "dispatch_failed" };
211
+ }
161
212
  const turnExecutionPolicy = resolveTurnExecutionPolicyV1(catalogSettings, {
162
213
  modelId: model,
163
214
  requestedModelId: template.model,
@@ -193,7 +244,7 @@ export function createAutomationActivities(
193
244
  resources: template.resources,
194
245
  skills: SessionSkills.parse(template.skills),
195
246
  bundledSkillIds: template.bundledSkillIds,
196
- tools: template.tools,
247
+ tools: agentWriteThrough.tools,
197
248
  toolPolicy: { mode: "explicit", inheritedFromSessionId: null },
198
249
  model,
199
250
  reasoningEffort,
@@ -212,10 +263,11 @@ export function createAutomationActivities(
212
263
  label: accepted.serviceLabel,
213
264
  },
214
265
  createdByContext: accepted.provenance,
215
- instructions: template.instructions,
266
+ instructions: agentWriteThrough.instructions ?? template.instructions,
216
267
  policyRole: template.policyRole,
217
268
  firstPartyMcpPermissions: template.firstPartyMcpPermissions,
218
- firstPartyMcpTools: template.firstPartyMcpTools,
269
+ firstPartyMcpTools: agentWriteThrough.firstPartyMcpTools,
270
+ ...(agentWriteThrough.config ? { agentConfig: agentWriteThrough.config } : {}),
219
271
  retainWorkspaceCustomModel:
220
272
  model.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||
221
273
  model.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX),