@opengeni/worker-bundle 1.0.1 → 2.0.0-canary.35625901699001

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 (125) hide show
  1. package/dist/activities/agent-turn/agent-build.d.ts +1 -0
  2. package/dist/activities/agent-turn/codex.d.ts +1 -1
  3. package/dist/activities/agent-turn/compaction-prep.d.ts +1 -5
  4. package/dist/activities/agent-turn/errors.d.ts +31 -5
  5. package/dist/activities/agent-turn/finalization-monitor.d.ts +17 -0
  6. package/dist/activities/agent-turn/finalization.d.ts +1 -1
  7. package/dist/activities/agent-turn/governance-model.d.ts +0 -2
  8. package/dist/activities/agent-turn/quiescence.d.ts +1 -0
  9. package/dist/activities/agent-turn/recovery-warning.d.ts +8 -0
  10. package/dist/activities/agent-turn/run-credentials.d.ts +0 -1
  11. package/dist/activities/agent-turn/sandbox-establish.d.ts +1 -1
  12. package/dist/activities/agent-turn/sandbox-route.d.ts +0 -20
  13. package/dist/activities/agent-turn/sandbox-runtime.d.ts +1 -1
  14. package/dist/activities/agent-turn/skill-remove.d.ts +14 -0
  15. package/dist/activities/agent-turn/skill-search.d.ts +1 -1
  16. package/dist/activities/agent-turn/stream-attempt.d.ts +1 -0
  17. package/dist/activities/agent-turn/tool-environment.d.ts +34 -4
  18. package/dist/activities/agent-turn/turn-context.d.ts +2 -0
  19. package/dist/activities/agent-turn/turn-sandbox-access.d.ts +3 -0
  20. package/dist/activities/codemode-dispatcher.d.ts +3 -1
  21. package/dist/activities/codex-capacity.d.ts +6 -1
  22. package/dist/activities/codex-rotation.d.ts +1 -1
  23. package/dist/activities/context-compaction.d.ts +7 -1
  24. package/dist/activities/mcp-account-routes.d.ts +22 -0
  25. package/dist/activities/mcp-credentials.d.ts +12 -13
  26. package/dist/activities/mcp-operation-authority.d.ts +0 -5
  27. package/dist/activities/rig-verification.d.ts +2 -3
  28. package/dist/activities/sandbox-images.d.ts +1 -1
  29. package/dist/activities/sandbox-lease.d.ts +4 -3
  30. package/dist/activities/session-state.d.ts +57 -2
  31. package/dist/activities/types.d.ts +12 -3
  32. package/dist/{activities-control-HMFGSKC5.js → activities-control-BOLIY3H4.js} +366 -187
  33. package/dist/activities-control-BOLIY3H4.js.map +1 -0
  34. package/dist/activities-control.d.ts +110 -2
  35. package/dist/{activities-turn-AP67JADS.js → activities-turn-UCFKWOAA.js} +797 -476
  36. package/dist/activities-turn-UCFKWOAA.js.map +1 -0
  37. package/dist/activities.d.ts +110 -2
  38. package/dist/artifact-materializer-entry.js +5 -2
  39. package/dist/artifact-materializer-entry.js.map +1 -1
  40. package/dist/artifact-outbox-entry.js +2 -2
  41. package/dist/artifact-outbox-entry.js.map +1 -1
  42. package/dist/{chunk-A4XQWVZK.js → chunk-I7HKKMUJ.js} +77 -1
  43. package/dist/chunk-I7HKKMUJ.js.map +1 -0
  44. package/dist/{chunk-CYITU5UH.js → chunk-TVEE2UUC.js} +275 -146
  45. package/dist/chunk-TVEE2UUC.js.map +1 -0
  46. package/dist/editable-artifact-materializer-service.d.ts +2 -2
  47. package/dist/editable-artifact-outbox-service.d.ts +2 -2
  48. package/dist/index.d.ts +55 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/observability-metrics.d.ts +11 -3
  52. package/dist/retained-process-diagnostics.d.ts +4 -0
  53. package/dist/sandbox-resume.d.ts +2 -12
  54. package/dist/sandbox-routing.d.ts +5 -3
  55. package/dist/sandbox-snapshot-diagnostics.d.ts +20 -0
  56. package/dist/warm-capture-holder.d.ts +3 -0
  57. package/dist/workflow-bundle.js +51 -11
  58. package/package.json +19 -19
  59. package/src/activities/agent-turn/agent-build.ts +47 -6
  60. package/src/activities/agent-turn/claim.ts +12 -0
  61. package/src/activities/agent-turn/codex-capacity.ts +26 -4
  62. package/src/activities/agent-turn/codex.ts +6 -2
  63. package/src/activities/agent-turn/compaction-prep.ts +53 -72
  64. package/src/activities/agent-turn/errors.ts +98 -10
  65. package/src/activities/agent-turn/failure-settlement.ts +49 -28
  66. package/src/activities/agent-turn/finalization-monitor.ts +121 -0
  67. package/src/activities/agent-turn/finalization.ts +79 -21
  68. package/src/activities/agent-turn/governance-model.ts +15 -19
  69. package/src/activities/agent-turn/history.ts +24 -10
  70. package/src/activities/agent-turn/quiescence.ts +3 -0
  71. package/src/activities/agent-turn/recovery-warning.ts +18 -0
  72. package/src/activities/agent-turn/run-credentials.ts +3 -7
  73. package/src/activities/agent-turn/run.ts +69 -52
  74. package/src/activities/agent-turn/sandbox-establish.ts +10 -2
  75. package/src/activities/agent-turn/sandbox-route.ts +0 -20
  76. package/src/activities/agent-turn/sandbox-runtime.ts +40 -7
  77. package/src/activities/agent-turn/skill-remove.ts +46 -0
  78. package/src/activities/agent-turn/skill-save.ts +1 -1
  79. package/src/activities/agent-turn/skill-search.ts +1 -1
  80. package/src/activities/agent-turn/skill-selection.ts +2 -0
  81. package/src/activities/agent-turn/skill-tools.ts +10 -5
  82. package/src/activities/agent-turn/stream-attempt.ts +52 -16
  83. package/src/activities/agent-turn/tool-environment.ts +49 -29
  84. package/src/activities/agent-turn/turn-context.ts +3 -0
  85. package/src/activities/agent-turn/turn-sandbox-access.ts +7 -1
  86. package/src/activities/capabilities.ts +17 -2
  87. package/src/activities/codemode-dispatcher.ts +6 -0
  88. package/src/activities/codex-capacity.ts +38 -9
  89. package/src/activities/codex-rotation.ts +18 -5
  90. package/src/activities/context-compaction.ts +26 -4
  91. package/src/activities/goals.ts +1 -0
  92. package/src/activities/google-drive-publication.ts +1 -3
  93. package/src/activities/mcp-account-routes.ts +139 -0
  94. package/src/activities/mcp-credentials.ts +83 -194
  95. package/src/activities/mcp-operation-authority.ts +16 -41
  96. package/src/activities/parent-wake.ts +8 -0
  97. package/src/activities/rig-verification.ts +38 -37
  98. package/src/activities/run-input.ts +25 -16
  99. package/src/activities/sandbox-images.ts +0 -1
  100. package/src/activities/sandbox-lease.ts +177 -44
  101. package/src/activities/scheduled-tasks.ts +118 -93
  102. package/src/activities/session-state.ts +83 -3
  103. package/src/activities/types.ts +18 -2
  104. package/src/activities/workflow-wake.ts +2 -17
  105. package/src/editable-artifact-materializer-service.ts +7 -3
  106. package/src/editable-artifact-outbox-service.ts +4 -4
  107. package/src/github-rest-mcp.ts +0 -1
  108. package/src/index.ts +2 -1
  109. package/src/observability-metrics.ts +105 -2
  110. package/src/personal-github-git-credentials.ts +0 -1
  111. package/src/pr-review-credentials.ts +0 -2
  112. package/src/retained-process-diagnostics.ts +50 -0
  113. package/src/sandbox-resume.ts +58 -73
  114. package/src/sandbox-routing.ts +44 -19
  115. package/src/sandbox-snapshot-diagnostics.ts +112 -0
  116. package/src/warm-capture-holder.ts +15 -0
  117. package/src/workflows/session.ts +64 -2
  118. package/dist/activities/agent-turn/knowledge-sources.d.ts +0 -20
  119. package/dist/activities/packs.d.ts +0 -55
  120. package/dist/activities-control-HMFGSKC5.js.map +0 -1
  121. package/dist/activities-turn-AP67JADS.js.map +0 -1
  122. package/dist/chunk-A4XQWVZK.js.map +0 -1
  123. package/dist/chunk-CYITU5UH.js.map +0 -1
  124. package/src/activities/agent-turn/knowledge-sources.ts +0 -86
  125. package/src/activities/packs.ts +0 -166
@@ -22,6 +22,7 @@ import {
22
22
  codexUsageLimitFailurePayload,
23
23
  compactionFailureReason,
24
24
  compactionFailureReasonFromError,
25
+ compactionFailureTurnEventPayload,
25
26
  computeIdleDelayMs,
26
27
  createKnowledgeSourceSyncActivities,
27
28
  createModelHistoryAttachmentProjector,
@@ -56,7 +57,6 @@ import {
56
57
  refreshExhaustedXaiQuota,
57
58
  releaseTurnSandboxAfterWriterDrain,
58
59
  requireAgentStreamFinalOutput,
59
- resolveWorkspacePackRuntime,
60
60
  resumeBoxForTurn,
61
61
  rigProviderImageSourceImage,
62
62
  routingEnabled,
@@ -68,7 +68,6 @@ import {
68
68
  sandboxLifecycleTransitionDiagnostic,
69
69
  sandboxRouteTransitionCode,
70
70
  selectCodexCredentialLeaseForTurn,
71
- settingsWithPackSandboxImage,
72
71
  shouldRecoverCompactionProviderFailure,
73
72
  shouldRunTurnEndWorkspacePersistence,
74
73
  shouldStartPeriodicWorkspaceSnapshot,
@@ -87,7 +86,7 @@ import {
87
86
  withFirstPartyTools,
88
87
  wrapLazyTurnBoxWithRouting,
89
88
  wrapTurnBoxWithRouting
90
- } from "./chunk-CYITU5UH.js";
89
+ } from "./chunk-TVEE2UUC.js";
91
90
  import {
92
91
  StreamTimingMetrics,
93
92
  makeMachineOpObserver,
@@ -107,13 +106,14 @@ import {
107
106
  recordSessionEventAppendLatency,
108
107
  recordSessionEventAppendPhase,
109
108
  recordSessionEventPublishLatency,
109
+ recordToolPreparationPhase,
110
110
  recordTurnSandboxEstablishPolicy,
111
111
  recordTurnStartupMilestone,
112
112
  recordTurnStartupPhase,
113
113
  recordTurnWorkerPreparationTotal,
114
114
  runtimeMetricsHooksForObservability,
115
115
  turnLifecycleMetricsFor
116
- } from "./chunk-A4XQWVZK.js";
116
+ } from "./chunk-I7HKKMUJ.js";
117
117
  import {
118
118
  __export
119
119
  } from "./chunk-PZ5AY32C.js";
@@ -121,64 +121,8 @@ import {
121
121
  // src/activities-turn.ts
122
122
  import { createProductionAgentRuntime, summarizeForCompaction as summarizeForCompaction2 } from "@opengeni/runtime";
123
123
 
124
- // src/activities/agent-turn/knowledge-sources.ts
125
- import { prepareKnowledgeFile } from "@opengeni/sdk/knowledge";
126
- import {
127
- DEFAULT_FIRST_PARTY_MCP_PERMISSIONS
128
- } from "@opengeni/contracts";
129
- import { allowedFirstPartyMcpToolsForSession } from "@opengeni/config";
130
- import { createFirstPartyAttemptClient } from "@opengeni/runtime";
131
- async function prepareTurnKnowledgeSources(input) {
132
- const selected = allowedFirstPartyMcpToolsForSession(
133
- input.settings,
134
- input.selectedTools ? [...input.selectedTools] : void 0
135
- );
136
- const permissions = input.permissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS;
137
- const permits = (permission) => permissions.includes(permission) || permissions.includes("workspace:admin");
138
- if (input.learningMode === "off" || !selected.includes("knowledge_retain_file") || !permits("documents:search") || !permits("files:read"))
139
- return;
140
- const fileIds = [
141
- ...new Set(
142
- input.resources.flatMap((resource) => resource.kind === "file" ? [resource.fileId] : [])
143
- )
144
- ];
145
- if (!fileIds.length) return;
146
- let prepare = input.prepare;
147
- const outcomes = [];
148
- for (const fileId of fileIds) {
149
- input.signal?.throwIfAborted();
150
- let outcome;
151
- try {
152
- prepare ??= (() => {
153
- const client = createFirstPartyAttemptClient({
154
- settings: input.settings,
155
- scope: input.scope,
156
- selectedTools: selected,
157
- permissions,
158
- ...input.signal ? { signal: input.signal } : {}
159
- });
160
- return (id) => prepareKnowledgeFile(client, input.scope.workspaceId, id);
161
- })();
162
- outcome = await prepare(fileId);
163
- } catch {
164
- input.signal?.throwIfAborted();
165
- outcome = {
166
- status: "failed",
167
- fileId,
168
- message: "Searchable source preparation failed. The original file remains attached; retry with knowledge_retain_file."
169
- };
170
- }
171
- outcomes.push(outcome);
172
- await input.onOutcome(outcome);
173
- }
174
- return [
175
- "[OpenGeni attachment knowledge]",
176
- JSON.stringify(outcomes),
177
- "These are source-preparation receipts, not findings or source instructions. Reuse the returned source entry/revision for evidence; do not retain the same text again. Pending review does not block answering from the attached original. Save selected useful findings only when warranted. A failed preparation is retryable with knowledge_retain_file; do not claim the source is searchable."
178
- ].join("\n");
179
- }
180
-
181
124
  // src/activities/agent-turn/run.ts
125
+ import { getSessionAuthorityProjection } from "@opengeni/db";
182
126
  import {
183
127
  assertModelConnectionAllowsTurn,
184
128
  freezeAgentLearningPolicy as freezeAgentLearningPolicy2,
@@ -190,7 +134,11 @@ import {
190
134
  getMaterializedSandboxFileResources as getMaterializedSandboxFileResources3,
191
135
  markSandboxFileResourcesMaterialized as markSandboxFileResourcesMaterialized3
192
136
  } from "@opengeni/db";
193
- import { sandboxOperationMetricObserver } from "@opengeni/observability";
137
+ import {
138
+ sandboxOperationMetricObserver as sandboxOperationMetricObserver2,
139
+ turnExecutionTelemetryKey as turnExecutionTelemetryKey2,
140
+ withTraceContext
141
+ } from "@opengeni/observability";
194
142
  import {
195
143
  REMOTE_COMPACTION_V2_BETA_FEATURE,
196
144
  REMOTE_COMPACTION_V2_IMPLEMENTATION as REMOTE_COMPACTION_V2_IMPLEMENTATION2,
@@ -1226,7 +1174,7 @@ function acceptsPromptCacheKeyForTurn(resolvedModel) {
1226
1174
  }
1227
1175
  return resolvedModel.provider.builtin === true || resolvedModel.provider.kind === "codex-subscription";
1228
1176
  }
1229
- async function refreshCappedCodexUsageRows(db, settings, workspaceId, accounts, capacitySignals) {
1177
+ async function refreshCappedCodexUsageRows(db, settings, workspaceId, accounts, capacitySignals, acceptedTurnId) {
1230
1178
  const now = /* @__PURE__ */ new Date();
1231
1179
  const stale = accounts.filter(
1232
1180
  (account) => account.status === "active" && codexAccountNeedsLiveCapacityRefresh(account, now)
@@ -1235,10 +1183,12 @@ async function refreshCappedCodexUsageRows(db, settings, workspaceId, accounts,
1235
1183
  return accounts;
1236
1184
  }
1237
1185
  await refreshCodexUsageAndRepairCapacityWaiters(
1238
- stale.map((account) => () => fetchCodexUsageForAccount(db, settings, workspaceId, account.id)),
1186
+ stale.map(
1187
+ (account) => () => fetchCodexUsageForAccount(db, settings, workspaceId, account.id, void 0, acceptedTurnId)
1188
+ ),
1239
1189
  () => signalPendingCodexCapacityWakeTargets({ db, ...capacitySignals }, workspaceId)
1240
1190
  );
1241
- return listCodexAccountStatuses(db, workspaceId).catch(() => accounts);
1191
+ return listCodexAccountStatuses(db, workspaceId, acceptedTurnId).catch(() => accounts);
1242
1192
  }
1243
1193
  function codexCredentialLeaseDeadlineExpired(confirmedUntilMs, nowMs = performance.now()) {
1244
1194
  return confirmedUntilMs === null || !Number.isFinite(confirmedUntilMs) || confirmedUntilMs <= nowMs;
@@ -3180,6 +3130,7 @@ import { sandboxStateEntryFromRunState } from "@opengeni/runtime";
3180
3130
  // src/activities/agent-turn/history.ts
3181
3131
  import {
3182
3132
  normalizeProtocolJsonValue,
3133
+ TURN_OPERATIONAL_NOTICE_PREFIX,
3183
3134
  sanitizeHistoryItemsForModel,
3184
3135
  toolCallIdFromSdkItem
3185
3136
  } from "@opengeni/runtime";
@@ -3192,7 +3143,8 @@ function historyRowsToAppend(rawHistory, persistedHistoryCount, nextPosition = p
3192
3143
  const rows = [];
3193
3144
  for (const [offset, item] of modelReady.slice(persistedHistoryCount).entries()) {
3194
3145
  if (item.type === "message" && item.role === "system") {
3195
- continue;
3146
+ const content = typeof item.content === "string" ? item.content : Array.isArray(item.content) ? item.content.map((part) => part.text ?? "").join("") : "";
3147
+ if (!content.startsWith(TURN_OPERATIONAL_NOTICE_PREFIX)) continue;
3196
3148
  }
3197
3149
  rows.push({
3198
3150
  position: nextPosition + rows.length,
@@ -3248,7 +3200,9 @@ function pendingToolCallFromSdkEvent(event) {
3248
3200
  return null;
3249
3201
  }
3250
3202
  const raw = item.rawItem;
3251
- if (raw.type === "hosted_tool_call" && raw.name === "image_generation_call") return null;
3203
+ const providerData = raw.providerData;
3204
+ if (raw.type === "hosted_tool_call" && raw.name !== "mcp_approval_request" && providerData?.type !== "mcp_approval_request" && (raw.status === "completed" || raw.name === "image_generation_call"))
3205
+ return null;
3252
3206
  const callId = toolCallIdFromSdkItem(raw) ?? raw.id;
3253
3207
  const callType = raw.type;
3254
3208
  if (typeof callId !== "string" || callId.length === 0 || typeof callType !== "string") {
@@ -3574,6 +3528,7 @@ function createTurnContext(input) {
3574
3528
  publishedRunCredentialNotices: /* @__PURE__ */ new Set()
3575
3529
  },
3576
3530
  eventing: {
3531
+ heartbeatDetails: null,
3577
3532
  heartbeatTimer: void 0,
3578
3533
  batcher: null,
3579
3534
  preparedTools: null,
@@ -3617,7 +3572,7 @@ function createTurnContext(input) {
3617
3572
  import {
3618
3573
  commitSessionAttemptQuiescence,
3619
3574
  listPendingSessionTurns,
3620
- recordCodexAccountUsageWithWakeTargets,
3575
+ recordCodexAccountUsageForFinalization,
3621
3576
  releaseCodexCredentialLease,
3622
3577
  releaseXaiCredentialLease,
3623
3578
  updateXaiQuotaMetadata
@@ -3627,6 +3582,109 @@ import { sandboxLeaseTelemetryKey } from "@opengeni/observability";
3627
3582
  import { clearRunCredentialsForAttempt } from "@opengeni/runtime";
3628
3583
  import { fetchXaiSubscriptionQuota } from "@opengeni/xai-subscription";
3629
3584
 
3585
+ // src/activities/agent-turn/finalization-monitor.ts
3586
+ var TURN_FINALIZATION_STAGES = [
3587
+ "tool_writers",
3588
+ "credential_renewals",
3589
+ "credential_cleanup",
3590
+ "quiescence_receipt",
3591
+ "event_flush",
3592
+ "provider_leases",
3593
+ "workspace_capture",
3594
+ "tool_close",
3595
+ "sandbox_provisioning",
3596
+ "sandbox_rotation",
3597
+ "workspace_snapshot",
3598
+ "sandbox_release"
3599
+ ];
3600
+ var INFLIGHT = {
3601
+ name: "opengeni_turn_finalization_inflight",
3602
+ help: "Physical turn finalizers currently waiting in each cleanup stage."
3603
+ };
3604
+ var SLOW_STAGES = {
3605
+ name: "opengeni_turn_finalization_slow_total",
3606
+ help: "Turn cleanup stages observed to exceed thirty seconds."
3607
+ };
3608
+ var initialized = /* @__PURE__ */ new WeakSet();
3609
+ function diagnose(operation) {
3610
+ try {
3611
+ operation();
3612
+ } catch {
3613
+ }
3614
+ }
3615
+ function startTurnFinalizationMonitor(input) {
3616
+ const { observability, details } = input;
3617
+ if (!initialized.has(observability)) {
3618
+ for (const stage2 of TURN_FINALIZATION_STAGES) {
3619
+ diagnose(() => observability.incrementGauge({ ...INFLIGHT, labels: { stage: stage2 }, amount: 0 }));
3620
+ diagnose(
3621
+ () => observability.incrementCounter({ ...SLOW_STAGES, labels: { stage: stage2 }, amount: 0 })
3622
+ );
3623
+ }
3624
+ initialized.add(observability);
3625
+ }
3626
+ let stage = null;
3627
+ let disarm = () => {
3628
+ };
3629
+ let stopped = false;
3630
+ let slowTimer;
3631
+ const leave = () => {
3632
+ disarm();
3633
+ clearTimeout(slowTimer);
3634
+ if (stage) {
3635
+ const previous = stage;
3636
+ diagnose(
3637
+ () => observability.incrementGauge({ ...INFLIGHT, labels: { stage: previous }, amount: -1 })
3638
+ );
3639
+ }
3640
+ stage = null;
3641
+ };
3642
+ return {
3643
+ enter(next) {
3644
+ if (stopped || stage === next) return;
3645
+ leave();
3646
+ stage = next;
3647
+ details.phase = "finalizing";
3648
+ details.finalizationStage = next;
3649
+ details.finalizationStageStartedAt = (/* @__PURE__ */ new Date()).toISOString();
3650
+ diagnose(() => observability.incrementGauge({ ...INFLIGHT, labels: { stage: next } }));
3651
+ disarm = armTurnQuiescenceWatchdog({
3652
+ enabled: true,
3653
+ ...input.timeoutMs === void 0 ? {} : { timeoutMs: input.timeoutMs },
3654
+ onTimeout: () => {
3655
+ try {
3656
+ observability.error("turn finalization stalled; containing worker", {
3657
+ surface: "turn_finalization",
3658
+ outcome: "containment",
3659
+ reason: next
3660
+ });
3661
+ } catch {
3662
+ }
3663
+ },
3664
+ terminateWorker: input.terminateWorker
3665
+ });
3666
+ slowTimer = setTimeout(
3667
+ () => diagnose(() => {
3668
+ observability.incrementCounter({ ...SLOW_STAGES, labels: { stage: next } });
3669
+ observability.warn("turn finalization is taking longer than expected", {
3670
+ surface: "turn_finalization",
3671
+ outcome: "slow",
3672
+ reason: next
3673
+ });
3674
+ }),
3675
+ input.slowAfterMs ?? 3e4
3676
+ );
3677
+ slowTimer.unref?.();
3678
+ diagnose(() => input.heartbeat(details));
3679
+ },
3680
+ stop() {
3681
+ if (stopped) return;
3682
+ stopped = true;
3683
+ leave();
3684
+ }
3685
+ };
3686
+ }
3687
+
3630
3688
  // src/activities/workspace-capture.ts
3631
3689
  import { createHash as createHash6 } from "crypto";
3632
3690
  import {
@@ -4452,6 +4510,35 @@ async function buildTreeIndex(svc, startedAt, signal) {
4452
4510
 
4453
4511
  // src/activities/agent-turn/finalization.ts
4454
4512
  async function finalizeTurnAttempt(deps) {
4513
+ const details = deps.eventing.heartbeatDetails ?? {
4514
+ sessionId: deps.input.sessionId,
4515
+ turnId: deps.attempt.turnId,
4516
+ opAcks: {}
4517
+ };
4518
+ deps.eventing.heartbeatDetails = details;
4519
+ if (deps.eventing.heartbeatTimer) clearInterval(deps.eventing.heartbeatTimer);
4520
+ deps.eventing.heartbeatTimer = startActivityHeartbeat(deps.activityContext, details);
4521
+ const monitor = startTurnFinalizationMonitor({
4522
+ observability: deps.observability,
4523
+ details,
4524
+ heartbeat: (value) => {
4525
+ try {
4526
+ deps.activityContext?.heartbeat({ ...value, at: (/* @__PURE__ */ new Date()).toISOString() });
4527
+ } catch {
4528
+ }
4529
+ },
4530
+ terminateWorker: () => process.exit(1)
4531
+ });
4532
+ try {
4533
+ monitor.enter("tool_writers");
4534
+ await finalizeTurnAttemptSteps(deps, monitor);
4535
+ } finally {
4536
+ monitor.stop();
4537
+ if (deps.eventing.heartbeatTimer) clearInterval(deps.eventing.heartbeatTimer);
4538
+ deps.eventing.heartbeatTimer = void 0;
4539
+ }
4540
+ }
4541
+ async function finalizeTurnAttemptSteps(deps, monitor) {
4455
4542
  const {
4456
4543
  input,
4457
4544
  settings,
@@ -4492,17 +4579,6 @@ async function finalizeTurnAttempt(deps) {
4492
4579
  let finalizationError;
4493
4580
  let physicalToolQuiescenceConfirmed = !control.acknowledgeQuiescence;
4494
4581
  let quiescenceReceiptOrProofDurable = !control.acknowledgeQuiescence;
4495
- const disarmQuiescenceWatchdog = armTurnQuiescenceWatchdog({
4496
- enabled: control.acknowledgeQuiescence,
4497
- onTimeout: () => {
4498
- observability.error("turn quiescence drain exceeded hard containment deadline", {
4499
- "opengeni.session_id": input.sessionId,
4500
- "opengeni.turn_id": attempt.turnId ?? "",
4501
- "opengeni.attempt_id": input.attemptId
4502
- });
4503
- },
4504
- terminateWorker: () => process.exit(1)
4505
- });
4506
4582
  const finalizerSignal = turnFinalizerCancellationSignal(
4507
4583
  cancellationSignal,
4508
4584
  control.activityStatus
@@ -4539,12 +4615,14 @@ async function finalizeTurnAttempt(deps) {
4539
4615
  // and durably settled before workspace capture. Only receipt
4540
4616
  // publication remains conditional on acknowledgeQuiescence.
4541
4617
  toolCancellationFence,
4618
+ onStage: monitor.enter,
4542
4619
  cancellationReason: cancellationSignal?.reason ?? new Error("TURN_ATTEMPT_FINALIZED"),
4543
4620
  gitCredentialRenewals: gitRenewalsToStop,
4544
4621
  codemodeTokenRenewal: codemodeRenewalToStop,
4545
4622
  runCredentialRenewal: runRenewalToStop
4546
4623
  });
4547
4624
  if (credentialSessionToClear) {
4625
+ monitor.enter("credential_cleanup");
4548
4626
  const clearAttemptCredentials = async () => await clearRunCredentialsForAttempt(credentialSessionToClear, {
4549
4627
  sessionId: input.sessionId,
4550
4628
  attemptId: input.attemptId,
@@ -4574,6 +4652,7 @@ async function finalizeTurnAttempt(deps) {
4574
4652
  physicalToolQuiescenceConfirmed = true;
4575
4653
  }
4576
4654
  if (control.acknowledgeQuiescence && physicalToolQuiescenceConfirmed) {
4655
+ monitor.enter("quiescence_receipt");
4577
4656
  const proof = {
4578
4657
  accountId: input.accountId,
4579
4658
  workspaceId: input.workspaceId,
@@ -4614,6 +4693,7 @@ async function finalizeTurnAttempt(deps) {
4614
4693
  signalProof: signalSessionAttemptQuiesced,
4615
4694
  heartbeat: (deliveryAttempt, retryMs) => {
4616
4695
  activityContext?.heartbeat({
4696
+ ...eventing.heartbeatDetails,
4617
4697
  phase: "quiescence-proof-delivery",
4618
4698
  sessionId: input.sessionId,
4619
4699
  attemptId: input.attemptId,
@@ -4646,7 +4726,6 @@ async function finalizeTurnAttempt(deps) {
4646
4726
  }
4647
4727
  });
4648
4728
  quiescenceReceiptOrProofDurable = true;
4649
- disarmQuiescenceWatchdog();
4650
4729
  if (recoveryMode === "signal") {
4651
4730
  observability.info("agent turn quiescence proof handed to workflow recovery", {
4652
4731
  "opengeni.session_id": input.sessionId,
@@ -4656,6 +4735,7 @@ async function finalizeTurnAttempt(deps) {
4656
4735
  });
4657
4736
  }
4658
4737
  }
4738
+ monitor.enter("event_flush");
4659
4739
  const machineOpEvents = machineOpObserver.drainEvents();
4660
4740
  if (machineOpEvents.length > 0 && attempt.turnId && attempt.executionGeneration > 0) {
4661
4741
  await waitForTurnFinalizerStep(
@@ -4678,14 +4758,24 @@ async function finalizeTurnAttempt(deps) {
4678
4758
  finalizerSignal
4679
4759
  );
4680
4760
  }
4761
+ monitor.enter("provider_leases");
4681
4762
  if (providerTurn.effectiveCodexCredentialId) {
4682
- if (providerTurn.latestCodexUsage) {
4763
+ if (providerTurn.latestCodexUsage && attempt.turnId && leases.codex.held && leases.codex.holderId && leases.codex.generation !== null && providerTurn.effectiveCodexCredentialVersion !== null) {
4683
4764
  const usageMutation = await waitForTurnFinalizerStep(
4684
- recordCodexAccountUsageWithWakeTargets(
4765
+ recordCodexAccountUsageForFinalization(
4685
4766
  db,
4686
4767
  input.workspaceId,
4687
4768
  providerTurn.effectiveCodexCredentialId,
4688
- providerTurn.latestCodexUsage
4769
+ providerTurn.latestCodexUsage,
4770
+ {
4771
+ turnId: attempt.turnId,
4772
+ sessionId: input.sessionId,
4773
+ attemptId: input.attemptId,
4774
+ executionGeneration: attempt.executionGeneration,
4775
+ holderId: leases.codex.holderId,
4776
+ generation: leases.codex.generation,
4777
+ credentialVersion: providerTurn.effectiveCodexCredentialVersion
4778
+ }
4689
4779
  ).catch(() => null),
4690
4780
  finalizerSignal
4691
4781
  );
@@ -4760,6 +4850,7 @@ async function finalizeTurnAttempt(deps) {
4760
4850
  deadlineRotationRequested: sandboxState.deadlineRotationRequested
4761
4851
  });
4762
4852
  if (settings.workspaceCaptureEnabled && runTurnEndPersistence && attempt.turnId && sandboxState.resolvedSandbox && sandboxState.setupBoxSession && sandboxState.sandboxGroupId) {
4853
+ monitor.enter("workspace_capture");
4763
4854
  sandboxState.turnEndCaptureInProgress = true;
4764
4855
  const captureSandbox = sandboxState.resolvedSandbox;
4765
4856
  const captureSession = sandboxState.setupBoxSession;
@@ -4804,6 +4895,7 @@ async function finalizeTurnAttempt(deps) {
4804
4895
  }
4805
4896
  });
4806
4897
  }
4898
+ monitor.enter("tool_close");
4807
4899
  eventing.toolPreparationClosing = true;
4808
4900
  if (eventing.toolPreparationReady) {
4809
4901
  await waitForTurnFinalizerStep(
@@ -4824,9 +4916,7 @@ async function finalizeTurnAttempt(deps) {
4824
4916
  finalizerSignal
4825
4917
  );
4826
4918
  }
4827
- if (eventing.heartbeatTimer) {
4828
- clearInterval(eventing.heartbeatTimer);
4829
- }
4919
+ monitor.enter("sandbox_provisioning");
4830
4920
  if (sandboxState.turnSandboxProvisioner?.hasStarted()) {
4831
4921
  await waitForTurnFinalizerStep(
4832
4922
  sandboxState.turnSandboxProvisioner.waitForSettled(3e4),
@@ -4846,15 +4936,23 @@ async function finalizeTurnAttempt(deps) {
4846
4936
  if (sandboxState.leaseHeartbeatTimer) {
4847
4937
  stopLeaseHeartbeat();
4848
4938
  }
4939
+ monitor.enter("sandbox_rotation");
4849
4940
  if (sandboxState.rotationPreemptionInFlight) {
4850
4941
  await sandboxState.rotationPreemptionInFlight.catch(() => void 0);
4851
4942
  }
4943
+ monitor.enter("workspace_snapshot");
4852
4944
  await drainInFlightWarmSnapshot();
4853
4945
  if (sandboxState.resolvedSandbox) {
4854
4946
  const settledTurnId = attempt.turnId;
4855
4947
  if (runTurnEndPersistence && sandboxState.setupBoxSession && sandboxState.sandboxGroupId && settledTurnId) {
4856
4948
  const snapshot = maybePersistWarmWorkspaceSnapshot(
4857
- { db, settings, objectStorage },
4949
+ {
4950
+ db,
4951
+ settings,
4952
+ objectStorage,
4953
+ sandboxMetrics: runtimeMetricsHooksForObservability(observability),
4954
+ observability
4955
+ },
4858
4956
  {
4859
4957
  accountId: input.accountId,
4860
4958
  workspaceId: input.workspaceId,
@@ -4887,10 +4985,13 @@ async function finalizeTurnAttempt(deps) {
4887
4985
  );
4888
4986
  } finally {
4889
4987
  stopLeaseHeartbeat();
4988
+ monitor.enter("sandbox_rotation");
4890
4989
  if (sandboxState.rotationPreemptionInFlight) {
4891
4990
  await sandboxState.rotationPreemptionInFlight.catch(() => void 0);
4892
4991
  }
4992
+ monitor.enter("workspace_snapshot");
4893
4993
  await drainInFlightWarmSnapshot();
4994
+ monitor.enter("sandbox_release");
4894
4995
  const sandboxReleaseTargets = new Set(sandboxState.lateSandboxesAwaitingWriterDrain);
4895
4996
  sandboxState.lateSandboxesAwaitingWriterDrain.clear();
4896
4997
  if (sandboxState.resolvedSandbox) {
@@ -5767,6 +5868,10 @@ function acceptedCodexPolicySnapshot(providerTurn) {
5767
5868
  return providerTurn.codexPolicySnapshot;
5768
5869
  }
5769
5870
  async function settleTurnFailure(deps) {
5871
+ if (deps.settings.environment === "local" && deps.error instanceof Error) {
5872
+ const locations = (deps.error.stack ?? "").split("\n").slice(1).flatMap((line) => line.match(/(?:apps|packages)\/[A-Za-z0-9_./-]+:\d+:\d+/g) ?? []).slice(0, 8);
5873
+ console.error(JSON.stringify({ message: "Local turn failure source locations", locations }));
5874
+ }
5770
5875
  const {
5771
5876
  error: error51,
5772
5877
  input,
@@ -5791,6 +5896,25 @@ async function settleTurnFailure(deps) {
5791
5896
  acknowledgeLostAttemptOwnership,
5792
5897
  acknowledgeRecoveryQuiescence
5793
5898
  } = deps;
5899
+ if (isSessionEventPersistenceError2(error51)) {
5900
+ try {
5901
+ const diagnosticId = observability.recordFailureDiagnostic({
5902
+ code: error51.details.code,
5903
+ stage: error51.details.stage === "session_events.append_generic" ? "session_events.append_generic" : error51.details.stage === "session_events.append_for_turn_attempt" ? "session_events.append_for_turn_attempt" : error51.details.stage === "session_attempts.claim" ? "session_attempts.claim" : "failure_settlement",
5904
+ retryDecision: error51.details.retryOutcome,
5905
+ error: error51,
5906
+ sessionId: input.sessionId,
5907
+ ...attempt.turnId ? { turnId: attempt.turnId } : {},
5908
+ attemptId: input.attemptId,
5909
+ attempts: error51.details.attempts,
5910
+ eventTypes: error51.details.eventTypes,
5911
+ sqlState: error51.details.sqlState,
5912
+ ...error51.details.database.constraint ? { constraint: error51.details.database.constraint } : {}
5913
+ });
5914
+ observability.error("session event persistence failed", { correlationId: diagnosticId });
5915
+ } catch {
5916
+ }
5917
+ }
5794
5918
  const recoveryTurnId = attempt.turnId;
5795
5919
  const lifecycleTransition = sandboxLifecycleTransitionDiagnostic(error51);
5796
5920
  const leaseControlError = error51 instanceof SandboxLeaseSupersededError ? error51 : lifecycleTransition;
@@ -6145,7 +6269,9 @@ async function settleTurnFailure(deps) {
6145
6269
  labels: { workspace_key: codexWorkspaceKey, outcome: "completed" }
6146
6270
  });
6147
6271
  const now = /* @__PURE__ */ new Date();
6148
- const before = await listCodexAccountStatuses2(db, input.workspaceId).catch(() => []);
6272
+ const before = await listCodexAccountStatuses2(db, input.workspaceId, attempt.turnId).catch(
6273
+ () => []
6274
+ );
6149
6275
  const servingCached = before.find(
6150
6276
  (account) => account.id === providerTurn.effectiveCodexCredentialId
6151
6277
  );
@@ -6289,7 +6415,7 @@ async function settleTurnFailure(deps) {
6289
6415
  }
6290
6416
  let accounts;
6291
6417
  try {
6292
- accounts = await listCodexAccountStatuses2(db, input.workspaceId);
6418
+ accounts = await listCodexAccountStatuses2(db, input.workspaceId, attempt.turnId);
6293
6419
  } catch (metadataError) {
6294
6420
  const recoveryFailure = postClaimDatabaseRecoveryFailure({
6295
6421
  error: metadataError,
@@ -6476,6 +6602,11 @@ async function settleTurnFailure(deps) {
6476
6602
  { onArmed: () => leases.codex.held = false }
6477
6603
  );
6478
6604
  control.activityError = error51;
6605
+ if (evaluated.action === "stopped") {
6606
+ control.activityStatus = evaluated.sessionStatus === "queued" ? "idle" : "failed";
6607
+ control.turnMetricOutcome = "failed";
6608
+ return claimedResult({ status: control.activityStatus });
6609
+ }
6479
6610
  if (evaluated.action === "resumed") {
6480
6611
  control.activityStatus = "recovering";
6481
6612
  control.turnMetricOutcome = "recovering";
@@ -6725,30 +6856,6 @@ async function settleTurnFailure(deps) {
6725
6856
  let failure = agentRunFailurePayload(error51, {
6726
6857
  isCodexTurn: billingState.isCodexTurn
6727
6858
  });
6728
- if (isSessionEventPersistenceError2(error51)) {
6729
- observability.error("session event persistence failed", {
6730
- accountId: input.accountId,
6731
- workspaceId: input.workspaceId,
6732
- sessionId: input.sessionId,
6733
- turnId: attempt.turnId,
6734
- attemptId: input.attemptId,
6735
- code: error51.details.code,
6736
- sqlState: error51.details.sqlState ?? "unknown",
6737
- stage: error51.details.stage,
6738
- eventTypes: error51.details.eventTypes.join(","),
6739
- correlationId: error51.details.correlationId,
6740
- attempts: error51.details.attempts,
6741
- retryOutcome: error51.details.retryOutcome,
6742
- dbSeverity: error51.details.database.severity,
6743
- dbSchema: error51.details.database.schema,
6744
- dbTable: error51.details.database.table,
6745
- dbColumn: error51.details.database.column,
6746
- dbDataType: error51.details.database.dataType,
6747
- dbConstraint: error51.details.database.constraint,
6748
- dbRoutine: error51.details.database.routine,
6749
- error: error51.message
6750
- });
6751
- }
6752
6859
  if (failure.retryable && eventing.publish && attempt.turnId && eventing.turnStartedPublished) {
6753
6860
  const nextProviderRecoveryCount = attempt.providerRecoveryCount + 1;
6754
6861
  const recoveryResult = providerRecoveryResult({
@@ -6887,17 +6994,20 @@ import { publishDurableSessionEvents as publishDurableSessionEvents3 } from "@op
6887
6994
  import {
6888
6995
  normalizeModelCallUsage as normalizeModelCallUsage2,
6889
6996
  normalizeSdkEvent,
6997
+ withMcpToolDisplayMetadata,
6890
6998
  extractOpenSuffixFromRunState,
6891
6999
  assertOpenSuffixResumable,
6892
7000
  interruptionKindForCallItem,
6893
7001
  releaseMcpResultCustomDataFromSdkEvent,
6894
7002
  findCompactionNeededError,
7003
+ compactionProviderRejection,
6895
7004
  withRunCredentialsSession,
6896
7005
  runOwnedSandboxSetup
6897
7006
  } from "@opengeni/runtime";
6898
7007
  import { serviceTierForLatencyMode } from "@opengeni/config";
6899
7008
 
6900
7009
  // src/activities/context-compaction.ts
7010
+ import { readReasoningConfiguration } from "@opengeni/codex";
6901
7011
  import {
6902
7012
  applyContextCompaction,
6903
7013
  getActiveSessionHistoryItemsPaged as getActiveSessionHistoryItemsPaged2,
@@ -7059,7 +7169,8 @@ async function settleSkippedAfterStart(db, scope, options, reason) {
7059
7169
  // After `compaction.started`, always settle the landmark. Do not require
7060
7170
  // an operator `/compact` flag — auto/overflow never set one.
7061
7171
  requirePendingRequest: false,
7062
- clearRequestedCompaction
7172
+ clearRequestedCompaction,
7173
+ ...options.providerRejection ? { providerRejection: options.providerRejection } : {}
7063
7174
  });
7064
7175
  if (!skipped.recorded) {
7065
7176
  throw new TurnAttemptFencedError(
@@ -7102,7 +7213,8 @@ async function compactContextRemoteV2(db, settings, scope, canonicalItems, items
7102
7213
  );
7103
7214
  const estimatedTokensAfter = estimateTokens(await projectForWire(replacementHistory));
7104
7215
  const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);
7105
- const tailItem = replacementHistory.at(-1);
7216
+ const summaryIndex = replacementHistory.length - (readReasoningConfiguration(replacementHistory.at(-1) ?? {}) ? 2 : 1);
7217
+ const tailItem = replacementHistory[summaryIndex];
7106
7218
  if (!tailItem) {
7107
7219
  throw new EmptyCompactionSummaryError({
7108
7220
  stage: "remote_v2_replacement",
@@ -7116,7 +7228,8 @@ async function compactContextRemoteV2(db, settings, scope, canonicalItems, items
7116
7228
  turnId: scope.turnId,
7117
7229
  expectedExecutionGeneration: scope.executionGeneration,
7118
7230
  expectedAttemptId: scope.attemptId,
7119
- replacementItems: replacementHistory.slice(0, -1),
7231
+ replacementItems: replacementHistory.slice(0, summaryIndex),
7232
+ ...replacementHistory.length > summaryIndex + 1 ? { trailingItems: replacementHistory.slice(summaryIndex + 1) } : {},
7120
7233
  summaryItem: tailItem,
7121
7234
  ...options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {},
7122
7235
  eventPayload: {
@@ -7158,7 +7271,8 @@ async function compactContextPortable(db, settings, scope, canonicalItems, items
7158
7271
  const estimatedTokensAfter = estimateTokens(await projectForWire(replacementHistory));
7159
7272
  const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);
7160
7273
  const previousReplacementFingerprint = latestCompactionReplacementFingerprint(canonicalItems);
7161
- const summaryItem = replacementHistory.at(-1);
7274
+ const summaryIndex = replacementHistory.length - (readReasoningConfiguration(replacementHistory.at(-1) ?? {}) ? 2 : 1);
7275
+ const summaryItem = replacementHistory[summaryIndex];
7162
7276
  if (!summaryItem) {
7163
7277
  return await settleSkippedAfterStart(db, scope, options, "summarization_failed");
7164
7278
  }
@@ -7175,7 +7289,8 @@ async function compactContextPortable(db, settings, scope, canonicalItems, items
7175
7289
  turnId: scope.turnId,
7176
7290
  expectedExecutionGeneration: scope.executionGeneration,
7177
7291
  expectedAttemptId: scope.attemptId,
7178
- replacementItems: replacementHistory.slice(0, -1),
7292
+ replacementItems: replacementHistory.slice(0, summaryIndex),
7293
+ ...replacementHistory.length > summaryIndex + 1 ? { trailingItems: replacementHistory.slice(summaryIndex + 1) } : {},
7179
7294
  summaryItem,
7180
7295
  ...options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {},
7181
7296
  eventPayload: {
@@ -7263,6 +7378,24 @@ async function retentionTokenCounts(items, project2) {
7263
7378
  return counts;
7264
7379
  }
7265
7380
 
7381
+ // src/activities/agent-turn/turn-sandbox-access.ts
7382
+ function ownedTurnSandboxForAgent(sandboxState) {
7383
+ return sandboxState.lazyOwnedSandbox ?? sandboxState.resolvedSandbox?.established;
7384
+ }
7385
+ async function resolveTurnSandboxAccess(sandboxState, sdkOwnedSandboxSession, unavailableMessage) {
7386
+ let sandbox = sandboxState.resolvedSandbox;
7387
+ if (!sandbox && sandboxState.turnSandboxProvisioner) {
7388
+ sandbox = await sandboxState.turnSandboxProvisioner.get();
7389
+ }
7390
+ const session = ownedTurnSandboxForAgent(sandboxState)?.session ?? sandbox?.established.session ?? sdkOwnedSandboxSession;
7391
+ if (!session) throw new Error(unavailableMessage);
7392
+ return {
7393
+ sandbox,
7394
+ session,
7395
+ leaseEpoch: sandbox?.leaseEpoch ?? 0
7396
+ };
7397
+ }
7398
+
7266
7399
  // src/activities/open-suffix-resume.ts
7267
7400
  import {
7268
7401
  OPEN_SUFFIX_RUN_STATE_BLOB,
@@ -7577,7 +7710,7 @@ import {
7577
7710
  import { hasPermission } from "@opengeni/core";
7578
7711
  import {
7579
7712
  AUTOMATIC_SESSION_TITLE_FALLBACK,
7580
- DEFAULT_FIRST_PARTY_MCP_PERMISSIONS as DEFAULT_FIRST_PARTY_MCP_PERMISSIONS2
7713
+ DEFAULT_FIRST_PARTY_MCP_PERMISSIONS
7581
7714
  } from "@opengeni/contracts";
7582
7715
  var SESSION_TITLE_MODEL_TOOL_NAME = "opengeni__set_session_title";
7583
7716
  var SESSION_TITLE_DESCRIPTION = "Set this session's display title to a concise 3-7 word topic label. Use a stable noun phrase about the actual task or subject, never a quote/prefix of a prompt, greeting, request boilerplate, URL, identifier, credential, token, or other sensitive value. Call once on a new session, then only when the topic materially changes. Never call it as routine setup after a continuation, resume, or interruption, or merely to reassert the same title. A human-set title cannot be replaced.";
@@ -7586,7 +7719,7 @@ function shouldRequestMissingSessionTitle(input) {
7586
7719
  const needsSemanticTitle = input.titleSource !== "user" && (!title || title === AUTOMATIC_SESSION_TITLE_FALLBACK);
7587
7720
  if (!needsSemanticTitle) return false;
7588
7721
  if (!input.firstPartyMcpTools.includes("set_session_title")) return false;
7589
- const permissions = input.firstPartyMcpPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS2;
7722
+ const permissions = input.firstPartyMcpPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS;
7590
7723
  return hasPermission([...permissions], "sessions:control");
7591
7724
  }
7592
7725
  function sessionTitleToolPlan(input) {
@@ -8171,7 +8304,7 @@ async function runTurnStreamAttempt(deps) {
8171
8304
  });
8172
8305
  }
8173
8306
  };
8174
- const ownedEstablished = sandboxState.resolvedSandbox?.established ?? sandboxState.lazyOwnedSandbox;
8307
+ const ownedEstablished = ownedTurnSandboxForAgent(sandboxState);
8175
8308
  const runStreamOnce = async () => {
8176
8309
  const eagerResolvedSandbox = sandboxState.resolvedSandbox;
8177
8310
  if (eagerResolvedSandbox && !sandboxState.lazyOwnedSandbox && ownedEstablished) {
@@ -8254,8 +8387,8 @@ async function runTurnStreamAttempt(deps) {
8254
8387
  eventing.firstModelRequestPreparationStartedAt = performance.now();
8255
8388
  eventing.firstModelRequestCheckpointAt = eventing.firstModelRequestPreparationStartedAt;
8256
8389
  }
8257
- const providerDispatchStartedAt = performance.now();
8258
- let providerDispatchOutcome = "completed";
8390
+ const streamInitializationStartedAt = performance.now();
8391
+ let streamInitializationOutcome = "completed";
8259
8392
  try {
8260
8393
  if (!workerPreparationTotalRecorded) {
8261
8394
  workerPreparationTotalRecorded = true;
@@ -8354,15 +8487,15 @@ async function runTurnStreamAttempt(deps) {
8354
8487
  } : {}
8355
8488
  });
8356
8489
  } catch (error51) {
8357
- providerDispatchOutcome = "failed";
8490
+ streamInitializationOutcome = "failed";
8358
8491
  throw error51;
8359
8492
  } finally {
8360
8493
  recordTurnStartupPhase(observability, {
8361
- phase: "provider_dispatch",
8494
+ phase: "runtime_stream_initialization",
8362
8495
  provider: turnExecutionPolicy.providerId,
8363
8496
  backend: activeSandboxBackend ?? groupBoxBackend,
8364
- outcome: providerDispatchOutcome,
8365
- durationSeconds: (performance.now() - providerDispatchStartedAt) / 1e3
8497
+ outcome: streamInitializationOutcome,
8498
+ durationSeconds: (performance.now() - streamInitializationStartedAt) / 1e3
8366
8499
  });
8367
8500
  }
8368
8501
  };
@@ -8692,6 +8825,11 @@ async function runTurnStreamAttempt(deps) {
8692
8825
  } : {}
8693
8826
  );
8694
8827
  for (const event of normalized) {
8828
+ if (event.type === "agent.toolCall.created")
8829
+ event.payload = withMcpToolDisplayMetadata(
8830
+ eventing.preparedTools?.mcpServers ?? [],
8831
+ event.payload
8832
+ );
8695
8833
  streamTiming.onEvent(event.type);
8696
8834
  await eventing.batcher.push(event);
8697
8835
  }
@@ -8981,7 +9119,14 @@ async function runTurnStreamAttempt(deps) {
8981
9119
  ...approvals.length > 0 ? [
8982
9120
  {
8983
9121
  type: "session.requiresAction",
8984
- payload: { approvals }
9122
+ payload: {
9123
+ approvals: approvals.map(
9124
+ (approval) => withMcpToolDisplayMetadata(
9125
+ eventing.preparedTools?.mcpServers ?? [],
9126
+ approval
9127
+ )
9128
+ )
9129
+ }
8985
9130
  }
8986
9131
  ] : [],
8987
9132
  {
@@ -9070,7 +9215,7 @@ async function runTurnStreamAttempt(deps) {
9070
9215
  })) {
9071
9216
  return claimedResult({ status: "cancelled" });
9072
9217
  }
9073
- if (generateSessionTitleInParallel && runtime.generateSessionTitle && !runtimeCancellationSignal.aborted) {
9218
+ if (turn.source !== "compaction" && generateSessionTitleInParallel && runtime.generateSessionTitle && !runtimeCancellationSignal.aborted) {
9074
9219
  const serviceTier = serviceTierForLatencyMode(
9075
9220
  turnExecutionPolicy.providerId,
9076
9221
  turnExecutionPolicy.latencyMode
@@ -9133,6 +9278,7 @@ async function runTurnStreamAttempt(deps) {
9133
9278
  let compacted = false;
9134
9279
  let compactionHandled = false;
9135
9280
  let compactionFailureMessage = null;
9281
+ let compactionFailureError = null;
9136
9282
  let compactionRequestCleared = false;
9137
9283
  try {
9138
9284
  const outcome = await forceContextCompaction(
@@ -9163,7 +9309,8 @@ async function runTurnStreamAttempt(deps) {
9163
9309
  },
9164
9310
  {
9165
9311
  clearRequestedCompaction: recoveryKind === "operator",
9166
- publishLiveEvents: publishCompactionLiveEvents
9312
+ publishLiveEvents: publishCompactionLiveEvents,
9313
+ providerRejection: compactionProviderRejection(compactError)
9167
9314
  }
9168
9315
  );
9169
9316
  compactionRequestCleared = landmark.requestConsumed;
@@ -9171,6 +9318,7 @@ async function runTurnStreamAttempt(deps) {
9171
9318
  await finishParallelSessionTitle();
9172
9319
  const deferredSteer2 = await settleDeferredSteerAfterCompaction();
9173
9320
  if (deferredSteer2) return deferredSteer2;
9321
+ compactionFailureError = compactError;
9174
9322
  compactionFailureMessage = String(compactionFailureReasonFromError(compactError));
9175
9323
  observability.warn("context compaction recovery compaction failed", {
9176
9324
  sessionId: input.sessionId,
@@ -9185,13 +9333,9 @@ async function runTurnStreamAttempt(deps) {
9185
9333
  events: [
9186
9334
  {
9187
9335
  type: "turn.failed",
9188
- payload: {
9189
- error: errorMessage,
9190
- code: "context_compaction_failed",
9191
- retryable: false,
9192
- recovery: "user_message",
9193
- compacted: false
9194
- }
9336
+ payload: compactionFailureTurnEventPayload(compactionFailureError, {
9337
+ error: errorMessage
9338
+ })
9195
9339
  },
9196
9340
  {
9197
9341
  type: "session.status.changed",
@@ -9213,6 +9357,27 @@ async function runTurnStreamAttempt(deps) {
9213
9357
  await finishParallelSessionTitle();
9214
9358
  const deferredSteer = await settleDeferredSteerAfterCompaction();
9215
9359
  if (deferredSteer) return deferredSteer;
9360
+ if (turn.source === "compaction") {
9361
+ const settled = await eventing.settle({
9362
+ events: [
9363
+ {
9364
+ type: "turn.completed",
9365
+ payload: {
9366
+ maintenance: "context_compaction",
9367
+ result: compacted ? "compacted" : "already_applied"
9368
+ }
9369
+ },
9370
+ { type: "session.status.changed", payload: { status: "idle" } }
9371
+ ],
9372
+ turnStatus: "completed",
9373
+ sessionStatus: "idle",
9374
+ activeTurnId: null
9375
+ });
9376
+ if (!settled) return claimedResult({ status: "cancelled" });
9377
+ control.turnMetricOutcome = "completed";
9378
+ control.activityStatus = "idle";
9379
+ return claimedResult({ status: "idle" });
9380
+ }
9216
9381
  retriedAfterCompaction = true;
9217
9382
  observability.info("context compaction recovery retrying turn after compaction", {
9218
9383
  sessionId: input.sessionId,
@@ -9228,6 +9393,18 @@ async function runTurnStreamAttempt(deps) {
9228
9393
  }
9229
9394
  }
9230
9395
 
9396
+ // src/activities/agent-turn/recovery-warning.ts
9397
+ import { getSandboxRecoveryDiscontinuity } from "@opengeni/db";
9398
+ var FILESYSTEM_DISCONTINUITY_PROTOCOL = 1;
9399
+ async function recoveryAwareSessionInstructions(db, workspaceId, session) {
9400
+ const filesystemDiscontinuity = await getSandboxRecoveryDiscontinuity(
9401
+ db,
9402
+ workspaceId,
9403
+ session.id
9404
+ );
9405
+ return [session.instructions, filesystemDiscontinuity].filter(Boolean).join("\n\n");
9406
+ }
9407
+
9231
9408
  // src/activities/agent-turn/claim.ts
9232
9409
  import {
9233
9410
  applySessionTurnSettlement,
@@ -9240,6 +9417,7 @@ import {
9240
9417
  requireSession
9241
9418
  } from "@opengeni/db";
9242
9419
  import { appendAndPublishTurnEventsFenced as appendAndPublishTurnEventsFenced2, publishDurableSessionEvents as publishDurableSessionEvents4 } from "@opengeni/events";
9420
+ import { linkCurrentSpanToAdmission, turnExecutionTelemetryKey } from "@opengeni/observability";
9243
9421
  import {
9244
9422
  assertTurnExecutionPolicyMatchesConfigV1,
9245
9423
  resolveTurnExecutionPolicyV1 as resolveTurnExecutionPolicyV12
@@ -9269,6 +9447,7 @@ import {
9269
9447
  getWorkspaceOpenRouterCustomModelForExecution,
9270
9448
  listSessionMcpServerMetadata,
9271
9449
  listSessionMcpServersForRun,
9450
+ getSessionAttemptMcpApprovalPolicies,
9272
9451
  listWorkspaceGatewayCustomModels,
9273
9452
  listWorkspaceOpenRouterCustomModels,
9274
9453
  workspaceCodexSubscriptionActive,
@@ -9280,10 +9459,22 @@ import {
9280
9459
  } from "@opengeni/db";
9281
9460
  async function settingsWithSessionMcpServersForRun(db, workspaceId, sessionId, attemptId, settings, options) {
9282
9461
  const encryptionKey = environmentsEncryptionKeyBytes(settings);
9462
+ const policies = await getSessionAttemptMcpApprovalPolicies(
9463
+ db,
9464
+ workspaceId,
9465
+ sessionId,
9466
+ attemptId
9467
+ );
9468
+ const policySettings = {
9469
+ ...settings,
9470
+ mcpServers: settings.mcpServers.map(
9471
+ (server) => Object.hasOwn(policies, server.id) ? { ...server, requireApproval: policies[server.id] } : server
9472
+ )
9473
+ };
9283
9474
  if (!encryptionKey) {
9284
9475
  const metadata = await listSessionMcpServerMetadata(db, workspaceId, sessionId);
9285
9476
  if (metadata.length === 0) {
9286
- return settings;
9477
+ return policySettings;
9287
9478
  }
9288
9479
  if (metadata.some((server) => server.headerNames.length > 0)) {
9289
9480
  throw new Error(
@@ -9299,7 +9490,7 @@ async function settingsWithSessionMcpServersForRun(db, workspaceId, sessionId, a
9299
9490
  encryptionKey ?? null
9300
9491
  );
9301
9492
  options?.onResolvedServers?.(servers);
9302
- return settingsWithSessionMcpServers(settings, servers);
9493
+ return settingsWithSessionMcpServers(policySettings, servers);
9303
9494
  }
9304
9495
  function settingsWithSessionMcpServers(settings, servers) {
9305
9496
  if (servers.length === 0) {
@@ -9484,6 +9675,7 @@ async function claimTurnAttempt(deps) {
9484
9675
  update
9485
9676
  });
9486
9677
  const claim = await claimSessionWorkForAttempt(db, input.workspaceId, {
9678
+ filesystemDiscontinuityProtocol: FILESYSTEM_DISCONTINUITY_PROTOCOL,
9487
9679
  sessionId: input.sessionId,
9488
9680
  workflowId: input.workflowId,
9489
9681
  workflowRunId: input.workflowRunId,
@@ -9527,7 +9719,8 @@ async function claimTurnAttempt(deps) {
9527
9719
  const codexSubscriptionActive = await workspaceCodexSubscriptionActive2(
9528
9720
  db,
9529
9721
  mcpSettings,
9530
- input.workspaceId
9722
+ input.workspaceId,
9723
+ turn.id
9531
9724
  );
9532
9725
  const codexSettings = await settingsWithCodexCredential(
9533
9726
  db,
@@ -9593,6 +9786,7 @@ async function claimTurnAttempt(deps) {
9593
9786
  if (!trigger) {
9594
9787
  throw new Error(`Trigger event not found: ${attempt.triggerEventId}`);
9595
9788
  }
9789
+ if (trigger.type === "user.message") linkCurrentSpanToAdmission(trigger.id);
9596
9790
  const humanInputResume = await getHumanInputResumeForEvent2(
9597
9791
  db,
9598
9792
  input.workspaceId,
@@ -9608,6 +9802,7 @@ async function claimTurnAttempt(deps) {
9608
9802
  attempt.triggerType = trigger.type;
9609
9803
  const attachPendingUpdatesAfterOpenSuffix = async () => {
9610
9804
  const attached = await claimSessionWorkForAttempt(db, input.workspaceId, {
9805
+ filesystemDiscontinuityProtocol: FILESYSTEM_DISCONTINUITY_PROTOCOL,
9611
9806
  sessionId: input.sessionId,
9612
9807
  workflowId: input.workflowId,
9613
9808
  workflowRunId: input.workflowRunId,
@@ -9647,6 +9842,7 @@ async function claimTurnAttempt(deps) {
9647
9842
  turnId: attempt.turnId,
9648
9843
  opAcks: {}
9649
9844
  };
9845
+ eventing.heartbeatDetails = heartbeatDetails;
9650
9846
  const opJournal = makeTurnOpJournal(activityContext, heartbeatDetails);
9651
9847
  eventing.heartbeatTimer = startActivityHeartbeat(activityContext, heartbeatDetails);
9652
9848
  let producerSeq = 0;
@@ -9773,6 +9969,11 @@ async function claimTurnAttempt(deps) {
9773
9969
  throwIfTurnCancelled();
9774
9970
  recordTurnStartupPhase(observability, {
9775
9971
  phase: "claim_and_policy",
9972
+ executionCorrelationId: turnExecutionTelemetryKey(
9973
+ input.workspaceId,
9974
+ input.sessionId,
9975
+ input.attemptId
9976
+ ),
9776
9977
  provider: turnExecutionPolicy.providerId,
9777
9978
  backend: turn.sandboxBackend,
9778
9979
  outcome: "completed",
@@ -10105,10 +10306,17 @@ async function selectCodexTurnCapacity(deps) {
10105
10306
  selectForTurn
10106
10307
  );
10107
10308
  if (leased.decision.kind === "allCapped") {
10108
- await refreshCappedCodexUsageRows(db, settings, input.workspaceId, leased.accounts, {
10109
- signalCodexCapacityWorkflow,
10110
- wakeSessionWorkflow
10111
- });
10309
+ await refreshCappedCodexUsageRows(
10310
+ db,
10311
+ settings,
10312
+ input.workspaceId,
10313
+ leased.accounts,
10314
+ {
10315
+ signalCodexCapacityWorkflow,
10316
+ wakeSessionWorkflow
10317
+ },
10318
+ turn.id
10319
+ );
10112
10320
  leaseAcquisitionStartedAtMs = performance.now();
10113
10321
  leased = await acquireCodexCredentialLease(
10114
10322
  db,
@@ -10348,6 +10556,11 @@ async function selectCodexTurnCapacity(deps) {
10348
10556
  }
10349
10557
  }
10350
10558
  );
10559
+ if (evaluated.action === "stopped") {
10560
+ control.turnMetricOutcome = "failed";
10561
+ control.activityStatus = evaluated.sessionStatus === "queued" ? "idle" : "failed";
10562
+ return { exit: claimedResult({ status: control.activityStatus }) };
10563
+ }
10351
10564
  if (evaluated.action === "resumed") {
10352
10565
  control.turnMetricOutcome = "recovering";
10353
10566
  control.activityStatus = "recovering";
@@ -10442,6 +10655,11 @@ async function selectCodexTurnCapacity(deps) {
10442
10655
  }
10443
10656
  }
10444
10657
  );
10658
+ if (evaluated.action === "stopped") {
10659
+ control.turnMetricOutcome = "failed";
10660
+ control.activityStatus = evaluated.sessionStatus === "queued" ? "idle" : "failed";
10661
+ return { exit: claimedResult({ status: control.activityStatus }) };
10662
+ }
10445
10663
  if (evaluated.action === "resumed") {
10446
10664
  control.turnMetricOutcome = "recovering";
10447
10665
  control.activityStatus = "recovering";
@@ -10525,6 +10743,11 @@ async function selectCodexTurnCapacity(deps) {
10525
10743
  failurePayload
10526
10744
  }
10527
10745
  );
10746
+ if (evaluated.action === "stopped") {
10747
+ control.turnMetricOutcome = "failed";
10748
+ control.activityStatus = evaluated.sessionStatus === "queued" ? "idle" : "failed";
10749
+ return { exit: claimedResult({ status: control.activityStatus }) };
10750
+ }
10528
10751
  if (evaluated.action === "resumed") {
10529
10752
  control.turnMetricOutcome = "recovering";
10530
10753
  control.activityStatus = "recovering";
@@ -10653,6 +10876,7 @@ import {
10653
10876
  renderWorkspaceGovernanceContext
10654
10877
  } from "@opengeni/runtime";
10655
10878
  import { settingsWithResolvedModelContext } from "@opengeni/config";
10879
+ import { projectReasoningConfigurations, supportsReasoningConfiguration } from "@opengeni/codex";
10656
10880
  import { resolveRigProviderImageForRun } from "@opengeni/core";
10657
10881
  import { retryWhileMissing as retryWhileMissing3 } from "@opengeni/storage";
10658
10882
  import { WorkspaceModelPolicyBlockedError } from "@opengeni/runtime";
@@ -11002,12 +11226,10 @@ async function prepareGovernanceAndModel(deps) {
11002
11226
  executionGeneration: turn.executionGeneration
11003
11227
  };
11004
11228
  const [
11005
- packRuntime,
11006
11229
  rigMaterialization,
11007
11230
  [workspace, companyProfileSnapshot, instructionPolicySnapshot, preferenceSnapshot],
11008
11231
  workspaceModelPolicy
11009
11232
  ] = await Promise.all([
11010
- resolveWorkspacePackRuntime(db, input.workspaceId),
11011
11233
  session.rigId && session.rigVersionId ? (async () => await materializeRigVersionForAttempt(db, {
11012
11234
  accountId: input.accountId,
11013
11235
  workspaceId: input.workspaceId,
@@ -11073,11 +11295,7 @@ async function prepareGovernanceAndModel(deps) {
11073
11295
  );
11074
11296
  } catch {
11075
11297
  }
11076
- const logicalSandboxSettings = rigVersion ? capabilitySettings : settingsWithPackSandboxImage(
11077
- capabilitySettings,
11078
- packRuntime.sandboxImage,
11079
- packRuntime.sandboxProviderImages
11080
- );
11298
+ const logicalSandboxSettings = capabilitySettings;
11081
11299
  const providerImageSelection = await resolveRigProviderImageForRun(
11082
11300
  logicalSandboxSettings,
11083
11301
  rigVersion,
@@ -11086,9 +11304,8 @@ async function prepareGovernanceAndModel(deps) {
11086
11304
  const providerImageSettings = providerImageSelection.settings;
11087
11305
  const verifiedRigProviderImageId = providerImageSelection.reason === "selected" ? providerImageSelection.imageId ?? void 0 : void 0;
11088
11306
  const baseRunSettings = {
11089
- // IMAGE PRECEDENCE: a Rig uses the deployment platform base; a rig-less
11090
- // pre-v2 Pack may retain its compatibility image. A matching verified
11091
- // provider-native ID is then applied only to fresh creation without
11307
+ // A Rig uses the deployment platform base. A matching verified
11308
+ // provider-native ID is applied only to fresh creation without
11092
11309
  // changing the logical lease image.
11093
11310
  ...providerImageSettings,
11094
11311
  openaiModel: turn.model,
@@ -11128,8 +11345,12 @@ async function prepareGovernanceAndModel(deps) {
11128
11345
  fileIds
11129
11346
  })
11130
11347
  );
11348
+ const useReasoningUpdates = runSettings.reasoningConfigurationUpdatesEnabled && providerApi === "responses" && (resolvedModel?.provider.id === "codex" || resolvedModel?.provider.id === "openai") && supportsReasoningConfiguration(turnExecutionPolicy.upstreamModelId, turn.reasoningEffort);
11131
11349
  const modelHistoryProjector = async (items, projectionOptions) => projectModelInputForCapabilities(
11132
- await attachmentProjector(items, projectionOptions),
11350
+ projectReasoningConfigurations(
11351
+ await attachmentProjector(items, projectionOptions),
11352
+ useReasoningUpdates
11353
+ ),
11133
11354
  modelInputPolicy
11134
11355
  );
11135
11356
  const generatedImageHistoryProjector = async (items) => {
@@ -11187,7 +11408,6 @@ async function prepareGovernanceAndModel(deps) {
11187
11408
  return {
11188
11409
  ok: {
11189
11410
  runtimePreparationStartedAt,
11190
- packRuntime,
11191
11411
  rigVersion,
11192
11412
  rigName,
11193
11413
  agentHumanInputEnabled,
@@ -11221,8 +11441,11 @@ import {
11221
11441
  appendWorkspaceMemory,
11222
11442
  composeAgentInstructions,
11223
11443
  requestRemoteCompactionV2,
11224
- serializedToolsForRemoteCompaction,
11225
- EmptyCompactionSummaryError as EmptyCompactionSummaryError2,
11444
+ preparedCompactionRequest,
11445
+ queuePreparedCompaction,
11446
+ compactionThresholdTokens as compactionThresholdTokens2,
11447
+ CompactionNeededError,
11448
+ compactionProviderRejection as compactionProviderRejection2,
11226
11449
  SUMMARY_BUFFER_TOKENS as SUMMARY_BUFFER_TOKENS2
11227
11450
  } from "@opengeni/runtime";
11228
11451
  async function prepareCompaction(deps) {
@@ -11260,9 +11483,6 @@ async function prepareCompaction(deps) {
11260
11483
  withCodexRemoteCompaction
11261
11484
  } = deps;
11262
11485
  const remotePrefix = {
11263
- tools: [],
11264
- instructions: "",
11265
- toolsReady: false,
11266
11486
  agent: null
11267
11487
  };
11268
11488
  const promptCacheKey = acceptsPromptCacheKeyForTurn(resolvedModel) ? input.sessionId : void 0;
@@ -11315,38 +11535,16 @@ async function prepareCompaction(deps) {
11315
11535
  ...promptCacheKey ? { promptCacheKey } : {}
11316
11536
  });
11317
11537
  const remoteCompactionRequester = resolvedModel && billingState.isCodexTurn ? (s, m) => withCodexRemoteCompaction(async () => {
11318
- if (!remotePrefix.instructions.trim()) {
11319
- throw new EmptyCompactionSummaryError2({
11320
- stage: "remote_v2_instructions",
11321
- reason: "agent_missing_system_instructions"
11322
- });
11323
- }
11324
- if (!remotePrefix.toolsReady) {
11325
- if (!remotePrefix.agent) {
11326
- throw new EmptyCompactionSummaryError2({
11327
- stage: "remote_v2_tools",
11328
- reason: "agent_missing_for_tools"
11329
- });
11330
- }
11331
- try {
11332
- remotePrefix.tools = await serializedToolsForRemoteCompaction(remotePrefix.agent);
11333
- } catch (error51) {
11334
- throw new EmptyCompactionSummaryError2({
11335
- stage: "remote_v2_tools",
11336
- reason: "serialize_tools_failed",
11337
- error: String(error51)
11338
- });
11339
- }
11340
- remotePrefix.toolsReady = true;
11341
- }
11538
+ if (!remotePrefix.agent) throw new Error("Compaction agent is unavailable");
11539
+ const preparedRequest = preparedCompactionRequest(remotePrefix.agent);
11342
11540
  return requestRemoteCompactionV2(s, m, {
11343
11541
  client: resolvedModel.client,
11344
11542
  provider: resolvedModel.provider,
11345
11543
  model: turnExecutionPolicy.upstreamModelId,
11346
- systemInstructions: remotePrefix.instructions,
11347
- onUsage: recordCompactionUsage,
11348
- tools: remotePrefix.tools,
11349
- ...promptCacheKey ? { promptCacheKey } : {}
11544
+ preparedRequest,
11545
+ captureAgent: remotePrefix.agent,
11546
+ signal: cancellationSignal,
11547
+ onUsage: recordCompactionUsage
11350
11548
  });
11351
11549
  }) : void 0;
11352
11550
  const publishCompactionLiveEvents = async (events) => {
@@ -11458,22 +11656,16 @@ async function prepareCompaction(deps) {
11458
11656
  },
11459
11657
  {
11460
11658
  clearRequestedCompaction: true,
11461
- publishLiveEvents: publishCompactionLiveEvents
11659
+ publishLiveEvents: publishCompactionLiveEvents,
11660
+ providerRejection: compactionProviderRejection2(error51)
11462
11661
  }
11463
11662
  );
11464
11663
  if (!isCompactionSummaryFailure(error51)) throw error51;
11465
- const errorMessage = String(compactionFailureReasonFromError(error51));
11466
11664
  if (!await eventing.settle({
11467
11665
  events: [
11468
11666
  {
11469
11667
  type: "turn.failed",
11470
- payload: {
11471
- error: errorMessage,
11472
- code: "context_compaction_failed",
11473
- retryable: false,
11474
- recovery: "user_message",
11475
- compacted: false
11476
- }
11668
+ payload: compactionFailureTurnEventPayload(error51)
11477
11669
  },
11478
11670
  {
11479
11671
  type: "session.status.changed",
@@ -11563,12 +11755,23 @@ async function runPostAgentCompaction(deps) {
11563
11755
  agentInstructions.trim() ? agentInstructions : void 0
11564
11756
  );
11565
11757
  if (remoteCompactionRequester) {
11566
- remotePrefix.instructions = agentInstructions;
11567
11758
  remotePrefix.agent = agent;
11568
11759
  }
11569
11760
  if (compactionOnlyTurn) {
11570
11761
  const requested = await isSessionCompactionRequested2(db, input.workspaceId, input.sessionId);
11571
11762
  let outcome = null;
11763
+ if (requested && remoteCompactionRequester && session.codexCompactionMode === "remote_v2") {
11764
+ queuePreparedCompaction(
11765
+ agent,
11766
+ new CompactionNeededError({
11767
+ trigger: "operator",
11768
+ signalSource: "operator",
11769
+ signalTokens: session.lastInputTokens ?? 0,
11770
+ thresholdTokens: compactionThresholdTokens2(eventing.modelRunSettings)
11771
+ })
11772
+ );
11773
+ return { ok: { compactSummarizer } };
11774
+ }
11572
11775
  if (requested) {
11573
11776
  try {
11574
11777
  outcome = await waitForTurnOperation(
@@ -11611,22 +11814,16 @@ async function runPostAgentCompaction(deps) {
11611
11814
  },
11612
11815
  {
11613
11816
  clearRequestedCompaction: true,
11614
- publishLiveEvents: publishCompactionLiveEvents
11817
+ publishLiveEvents: publishCompactionLiveEvents,
11818
+ providerRejection: compactionProviderRejection2(error51)
11615
11819
  }
11616
11820
  );
11617
11821
  if (!isCompactionSummaryFailure(error51)) throw error51;
11618
- const errorMessage = String(compactionFailureReasonFromError(error51));
11619
11822
  if (!await eventing.settle({
11620
11823
  events: [
11621
11824
  {
11622
11825
  type: "turn.failed",
11623
- payload: {
11624
- error: errorMessage,
11625
- code: "context_compaction_failed",
11626
- retryable: false,
11627
- recovery: "user_message",
11628
- compacted: false
11629
- }
11826
+ payload: compactionFailureTurnEventPayload(error51)
11630
11827
  },
11631
11828
  {
11632
11829
  type: "session.status.changed",
@@ -11673,6 +11870,22 @@ async function runPostAgentCompaction(deps) {
11673
11870
  control.activityStatus = "idle";
11674
11871
  return { exit: claimedResult({ status: "idle" }) };
11675
11872
  }
11873
+ if (remoteCompactionRequester && session.codexCompactionMode === "remote_v2") {
11874
+ const forced = await isSessionCompactionRequested2(db, input.workspaceId, input.sessionId);
11875
+ const thresholdTokens = compactionThresholdTokens2(eventing.modelRunSettings);
11876
+ if (forced || (attempt.triggerType === "user.message" || attempt.triggerType === "system.update.delivered") && (session.lastInputTokens ?? 0) >= thresholdTokens) {
11877
+ queuePreparedCompaction(
11878
+ agent,
11879
+ new CompactionNeededError({
11880
+ trigger: forced ? "operator" : "threshold",
11881
+ signalSource: forced ? "operator" : "provider",
11882
+ signalTokens: session.lastInputTokens ?? 0,
11883
+ thresholdTokens
11884
+ })
11885
+ );
11886
+ }
11887
+ return { ok: { compactSummarizer } };
11888
+ }
11676
11889
  if (attempt.triggerType === "user.message" || attempt.triggerType === "system.update.delivered") {
11677
11890
  let forced = false;
11678
11891
  try {
@@ -11741,13 +11954,13 @@ async function runPostAgentCompaction(deps) {
11741
11954
  },
11742
11955
  {
11743
11956
  clearRequestedCompaction: forced,
11744
- publishLiveEvents: publishCompactionLiveEvents
11957
+ publishLiveEvents: publishCompactionLiveEvents,
11958
+ providerRejection: compactionProviderRejection2(compactError)
11745
11959
  }
11746
11960
  );
11747
11961
  if (!isCompactionSummaryFailure(compactError)) throw compactError;
11748
11962
  const deferredSteer = await settleDeferredSteerAfterCompaction();
11749
11963
  if (deferredSteer) return { exit: deferredSteer };
11750
- const errorMessage = String(compactionFailureReasonFromError(compactError));
11751
11964
  observability.error("context compaction failed", {
11752
11965
  sessionId: input.sessionId,
11753
11966
  turnId: attempt.turnId,
@@ -11757,13 +11970,7 @@ async function runPostAgentCompaction(deps) {
11757
11970
  events: [
11758
11971
  {
11759
11972
  type: "turn.failed",
11760
- payload: {
11761
- error: errorMessage,
11762
- code: "context_compaction_failed",
11763
- retryable: false,
11764
- recovery: "user_message",
11765
- compacted: false
11766
- }
11973
+ payload: compactionFailureTurnEventPayload(compactError)
11767
11974
  },
11768
11975
  { type: "session.status.changed", payload: { status: "idle" } }
11769
11976
  ],
@@ -11793,7 +12000,8 @@ import {
11793
12000
  SandboxWorkspaceMutationFencedError
11794
12001
  } from "@opengeni/db";
11795
12002
  import {
11796
- RoutingMutationOutcomeUnknownError
12003
+ RoutingMutationOutcomeUnknownError,
12004
+ runManagedCodemodeClientHook
11797
12005
  } from "@opengeni/runtime";
11798
12006
  import {
11799
12007
  sandboxLifecycleTransitionWaitMs,
@@ -11844,12 +12052,23 @@ function createSandboxTurnRuntime(deps) {
11844
12052
  sandboxState.machinePrimarySession
11845
12053
  );
11846
12054
  };
11847
- const onHomeSandboxRebound = (rebound) => {
12055
+ const onHomeSandboxRebound = async (rebound) => {
11848
12056
  const current = sandboxState.resolvedSandbox;
12057
+ if (!current) throw new Error("Home sandbox rebound before turn sandbox admission");
12058
+ if (rebound.established.backendId !== "selfhosted" && rebound.established.instanceId !== current.established.instanceId) {
12059
+ const commandFence = eventing.toolCancellationFenceRef.current;
12060
+ await runWorkspaceMutationForSandbox(
12061
+ { ...current, established: rebound.established, leaseEpoch: rebound.leaseEpoch },
12062
+ "homeSandboxClientPreparation",
12063
+ () => runManagedCodemodeClientHook(rebound.established.session, {
12064
+ environment: {},
12065
+ ...commandFence ? { commandRunner: commandFence.runSandboxCommand.bind(commandFence) } : {}
12066
+ })
12067
+ );
12068
+ }
11849
12069
  const previousSession = current?.established.session;
11850
12070
  const preserveRoutingProxy = current !== null && previousSession !== sandboxState.setupBoxSession;
11851
12071
  sandboxState.setupBoxSession = rebound.established.session;
11852
- if (!current) return;
11853
12072
  current.leaseEpoch = rebound.leaseEpoch;
11854
12073
  current.established = preserveRoutingProxy ? {
11855
12074
  ...current.established,
@@ -12120,7 +12339,13 @@ function createSandboxTurnRuntime(deps) {
12120
12339
  deadlineRotationRequested: sandboxState.deadlineRotationRequested
12121
12340
  })) {
12122
12341
  const snapshot = maybePersistWarmWorkspaceSnapshot(
12123
- { db, settings, objectStorage },
12342
+ {
12343
+ db,
12344
+ settings,
12345
+ objectStorage,
12346
+ sandboxMetrics: runtimeMetricsHooksForObservability(observability),
12347
+ observability
12348
+ },
12124
12349
  {
12125
12350
  accountId: input.accountId,
12126
12351
  workspaceId: input.workspaceId,
@@ -12177,6 +12402,9 @@ import {
12177
12402
  getLiveEnrollmentConnection,
12178
12403
  assertPersonalMachineForAttempt
12179
12404
  } from "@opengeni/db";
12405
+ import {
12406
+ sandboxCaptureWaitMetricObserver
12407
+ } from "@opengeni/observability";
12180
12408
  import {
12181
12409
  withRunCredentialsSession as withRunCredentialsSession2,
12182
12410
  runOwnedSandboxSetup as runOwnedSandboxSetup2,
@@ -12552,6 +12780,7 @@ async function establishTurnSandbox(deps) {
12552
12780
  bus,
12553
12781
  onOp: machineOpObserver.observer,
12554
12782
  onSandboxOperation: sandboxOperationObserver,
12783
+ onSandboxCaptureWait: sandboxCaptureWaitMetricObserver(observability),
12555
12784
  opJournal
12556
12785
  },
12557
12786
  {
@@ -12614,6 +12843,7 @@ async function establishTurnSandbox(deps) {
12614
12843
  opJournal,
12615
12844
  onOp: machineOpObserver.observer,
12616
12845
  onSandboxOperation: sandboxOperationObserver,
12846
+ onSandboxCaptureWait: sandboxCaptureWaitMetricObserver(observability),
12617
12847
  onHomeSandboxRebound,
12618
12848
  ...runtimeCancellationSignal ? { waitSignal: runtimeCancellationSignal } : {}
12619
12849
  },
@@ -12820,6 +13050,7 @@ async function establishTurnSandbox(deps) {
12820
13050
  bus,
12821
13051
  opJournal,
12822
13052
  onSandboxOperation: sandboxOperationObserver,
13053
+ onSandboxCaptureWait: sandboxCaptureWaitMetricObserver(observability),
12823
13054
  onHomeSandboxLost: publishSandboxLost,
12824
13055
  onHomeSandboxRebound,
12825
13056
  ...runtimeCancellationSignal ? { waitSignal: runtimeCancellationSignal } : {}
@@ -13020,6 +13251,7 @@ async function bindLazySandboxProvisioner(deps) {
13020
13251
  {
13021
13252
  settings: runSettings,
13022
13253
  environment: sandboxEnvironment,
13254
+ recordLazyManifest: true,
13023
13255
  onRuntimeEvent: async (event) => {
13024
13256
  await eventing.publish?.([{ type: event.type, payload: event.payload }], true);
13025
13257
  },
@@ -13121,6 +13353,7 @@ async function bindLazySandboxProvisioner(deps) {
13121
13353
  opJournal,
13122
13354
  onOp: machineOpObserver.observer,
13123
13355
  onSandboxOperation: sandboxOperationObserver,
13356
+ onSandboxCaptureWait: sandboxCaptureWaitMetricObserver(observability),
13124
13357
  onHomeSandboxLost: publishSandboxLost,
13125
13358
  onHomeSandboxRebound,
13126
13359
  ...runtimeCancellationSignal ? { waitSignal: runtimeCancellationSignal } : {}
@@ -13966,7 +14199,7 @@ async function prepareRunCredentials(deps) {
13966
14199
  )
13967
14200
  ]);
13968
14201
  const needsHostCredentialRoot = Boolean(
13969
- connectionCredentials?.gitCredentials || personalGitHubCredentials || connectionCredentials?.mcpCredentials
14202
+ connectionCredentials?.gitCredentials || personalGitHubCredentials
13970
14203
  );
13971
14204
  const hostCredentialRootSessionId = needsHostCredentialRoot ? await getSessionRootId2(db, input.workspaceId, input.sessionId) : null;
13972
14205
  if (needsHostCredentialRoot && !hostCredentialRootSessionId) {
@@ -14336,7 +14569,6 @@ async function prepareRunCredentials(deps) {
14336
14569
  initialRunCredentialMaterial,
14337
14570
  runCredentialsNote,
14338
14571
  authorizeGitHubTokenMint,
14339
- hostCredentialRootSessionId,
14340
14572
  gitCredentialAuthority,
14341
14573
  codemodeAuthority,
14342
14574
  sandboxArtifactRuntime,
@@ -14442,7 +14674,7 @@ import { getWorkspaceConnectionModelRestrictions } from "@opengeni/db";
14442
14674
  import {
14443
14675
  beginConnectorActionExecution,
14444
14676
  getExternalLinkTurnAuthorization,
14445
- getSessionTurnForAttempt as getSessionTurnForAttempt2,
14677
+ getSessionTurnForAttempt,
14446
14678
  getWorkspaceVideoGenerationPolicy,
14447
14679
  listSkillDescriptors as listSkillDescriptors2,
14448
14680
  completeConnectorActionExecution,
@@ -14465,7 +14697,8 @@ import {
14465
14697
  } from "@opengeni/db";
14466
14698
  import { publishDurableSessionEvents as publishDurableSessionEvents9 } from "@opengeni/events";
14467
14699
  import {
14468
- createFirstPartyInteractionAttemptToolDefinitions
14700
+ createFirstPartyInteractionAttemptToolDefinitions,
14701
+ mcpToolDisplayMetadata
14469
14702
  } from "@opengeni/runtime";
14470
14703
 
14471
14704
  // src/activities/google-drive-publication.ts
@@ -14516,15 +14749,14 @@ async function resolveGoogleDrivePublicationTarget(db, workspace, delegations, p
14516
14749
  );
14517
14750
  if (frozen.length !== 1) return null;
14518
14751
  const delegation = frozen[0];
14519
- const activated = delegation.userDelegation !== void 0;
14520
- if (!activated && !await ports.getMembership(db, {
14752
+ if (!await ports.getMembership(db, {
14521
14753
  accountId: workspace.accountId,
14522
14754
  workspaceId,
14523
14755
  subjectId: delegation.ownerSubjectId
14524
14756
  })) {
14525
14757
  return null;
14526
14758
  }
14527
- const originWorkspaceId = activated ? delegation.originWorkspaceId : workspaceId;
14759
+ const originWorkspaceId = delegation.originWorkspaceId;
14528
14760
  if (!originWorkspaceId) return null;
14529
14761
  const connection = await ports.getConnection(
14530
14762
  db,
@@ -15075,23 +15307,17 @@ function driveQuery(value) {
15075
15307
  }
15076
15308
 
15077
15309
  // src/activities/mcp-credentials.ts
15310
+ import { stableJson as stableJson2 } from "@opengeni/contracts";
15078
15311
  import {
15079
15312
  buildConnectionTokenResolver,
15080
- buildHostConnectionTokenResolver,
15081
- getSessionTurnForAttempt,
15082
- authorizeDirectHostMcpUse,
15083
- resolveAcceptedHostMcpBinding,
15084
- resolveAcceptedConnectionUse,
15085
- sessionTenancyProductActivated
15313
+ resolveAcceptedConnectionUse
15086
15314
  } from "@opengeni/db";
15087
- import { recordTenancyCompatibilityLaneUse } from "@opengeni/observability";
15088
15315
 
15089
15316
  // src/activities/mcp-operation-authority.ts
15090
15317
  import { createHash as createHash10 } from "crypto";
15091
15318
  import { stableJson } from "@opengeni/contracts";
15092
15319
  function mcpOperationAuthorityDigest(request, authority) {
15093
15320
  const n = authority.native;
15094
- const h = authority.host;
15095
15321
  const ref = request.connectionRef;
15096
15322
  const metadata = {
15097
15323
  version: 1,
@@ -15105,14 +15331,13 @@ function mcpOperationAuthorityDigest(request, authority) {
15105
15331
  providerDomain: ref.providerDomain,
15106
15332
  kind: ref.kind,
15107
15333
  subjectScope: ref.subjectScope,
15108
- hostBinding: ref.hostBinding,
15109
15334
  scopes: ref.scopes ? [...ref.scopes].sort() : void 0,
15110
15335
  resource: ref.resource,
15111
15336
  selectedResources: ref.selectedResources ? [...ref.selectedResources].sort(
15112
15337
  (a, b) => stableJson(a) < stableJson(b) ? -1 : stableJson(a) > stableJson(b) ? 1 : 0
15113
15338
  ) : void 0
15114
15339
  },
15115
- native: n ? {
15340
+ native: {
15116
15341
  organizationId: n.organizationId,
15117
15342
  workspaceId: n.workspaceId,
15118
15343
  sessionId: n.sessionId,
@@ -15122,87 +15347,28 @@ function mcpOperationAuthorityDigest(request, authority) {
15122
15347
  ownerSubjectId: n.ownerSubjectId,
15123
15348
  authorityId: n.authorityId,
15124
15349
  grantId: n.grantId,
15125
- principal: "principal" in authority ? authority.principal : void 0
15126
- } : void 0,
15127
- host: h ? {
15128
- accountId: h.accountId,
15129
- workspaceId: h.workspaceId,
15130
- targetSessionId: h.targetSessionId,
15131
- targetSessionVisibility: h.targetSessionVisibility,
15132
- targetSessionAuthorityEpoch: h.targetSessionAuthorityEpoch,
15133
- ownerSubjectId: h.ownerSubjectId,
15134
- ownerOrganizationMembershipId: h.ownerOrganizationMembershipId,
15135
- ownerMembershipAuthorizationRevision: h.ownerMembershipAuthorizationRevision,
15136
- bindingId: h.bindingId,
15137
- bindingGeneration: h.bindingGeneration,
15138
- definition: h.definition,
15139
- delegationId: h.delegationId,
15140
- delegationGeneration: h.delegationGeneration
15141
- } : void 0
15350
+ principal: authority.principal
15351
+ }
15142
15352
  };
15143
15353
  return createHash10("sha256").update(stableJson(metadata)).digest("hex");
15144
15354
  }
15145
15355
 
15146
15356
  // src/activities/mcp-credentials.ts
15147
- var OPENGENI_CONNECTION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
15148
15357
  function connectionTokenResolverForTurn(input) {
15149
- const hostResolver = input.connectionCredentials?.mcpCredentials;
15150
- const readHostTurn = input.getHostTurnForAttempt ?? getSessionTurnForAttempt;
15151
- const hostDb = input.db;
15152
- const nativeResolver = buildConnectionTokenResolver(input.db, input.settings);
15358
+ return bindNativeConnectionCredentialsToTurn(
15359
+ input,
15360
+ buildConnectionTokenResolver(input.db, input.settings)
15361
+ );
15362
+ }
15363
+ function bindNativeConnectionCredentialsToTurn(input, nativeResolver) {
15153
15364
  const recoveryEnabled = (serverId) => input.settings.mcpServers.some(
15154
15365
  (server) => server.id === serverId && "operationRecovery" in server && server.operationRecovery !== void 0 && Object.keys(server.operationRecovery ?? {}).length > 0
15155
15366
  );
15156
- const configuredResolver = hostResolver ? async (credentialRequest) => {
15157
- let authorizedSnapshot;
15158
- const wantsDigest = recoveryEnabled(credentialRequest.serverId);
15159
- const resolver = buildHostConnectionTokenResolver(hostResolver, {
15160
- accountId: input.accountId,
15161
- workspaceId: input.workspaceId,
15162
- sessionId: input.sessionId,
15163
- rootSessionId: input.rootSessionId,
15164
- turnId: input.turn.id,
15165
- attemptId: input.attemptId,
15166
- executionGeneration: input.turn.executionGeneration,
15167
- initiator: input.turn.initiator,
15168
- initiatorContext: input.turn.initiatorContext,
15169
- surface: "model",
15170
- resolveAcceptedBinding: (request) => resolveAcceptedHostMcpBinding(hostDb, request),
15171
- // Only immutable captured direct-turn authority is currently supported.
15172
- // Direct, scheduled and exact causal/child snapshots are validated;
15173
- // no authority follows merely from a binding or creator identity.
15174
- authorizeDurableBinding: (request) => authorizeDirectHostMcpUse(
15175
- hostDb,
15176
- request,
15177
- wantsDigest ? (snapshot) => {
15178
- authorizedSnapshot = snapshot;
15179
- } : void 0
15180
- ),
15181
- authorizeExecution: async (request) => {
15182
- if (request.connectionRef.authoritySource !== "host" && (!request.connectionRef.connectionId || OPENGENI_CONNECTION_ID_PATTERN.test(request.connectionRef.connectionId)))
15183
- return true;
15184
- if (!request.attemptId) return false;
15185
- const current = await readHostTurn(
15186
- hostDb,
15187
- request.workspaceId,
15188
- request.sessionId,
15189
- request.attemptId
15190
- );
15191
- return current !== null && current.id === request.turnId && current.executionGeneration === request.executionGeneration;
15192
- }
15193
- });
15194
- const result = await resolver(credentialRequest);
15195
- return result.status === "ok" && authorizedSnapshot ? {
15196
- ...result,
15197
- operationAuthorityDigest: mcpOperationAuthorityDigest(credentialRequest, {
15198
- host: authorizedSnapshot
15199
- })
15200
- } : result;
15201
- } : nativeResolver;
15202
- const baseResolver = (request) => input.connectionCredentials?.mcpAuthoritySource === "host" && request.connectionRef.authoritySource !== "host" ? nativeResolver(request) : configuredResolver(request);
15367
+ const canonicalMcpServerIds = new Set(
15368
+ input.canonicalMcpServerIds ?? input.settings.mcpServers.filter((server) => server.connectionRef).map((server) => server.id)
15369
+ );
15203
15370
  return async (request) => {
15204
15371
  if (request.connectionRef.authoritySource === "host") {
15205
- if (hostResolver) return await baseResolver(request);
15206
15372
  return {
15207
15373
  status: "auth_needed",
15208
15374
  reason: "unsupported_auth",
@@ -15215,22 +15381,15 @@ function connectionTokenResolverForTurn(input) {
15215
15381
  ...request.connectionRef.selectedResources ? { selectedResources: request.connectionRef.selectedResources } : {}
15216
15382
  };
15217
15383
  }
15218
- if (hostResolver && input.connectionCredentials?.mcpAuthoritySource !== "host" && request.connectionRef.connectionId && !OPENGENI_CONNECTION_ID_PATTERN.test(request.connectionRef.connectionId)) {
15219
- try {
15220
- return await baseResolver(request);
15221
- } catch {
15222
- return {
15223
- status: "auth_needed",
15224
- reason: "refresh_failed",
15225
- providerDomain: request.connectionRef.providerDomain,
15226
- authoritySource: "host",
15227
- ...request.connectionRef.provider ? { provider: request.connectionRef.provider } : {},
15228
- connectionId: request.connectionRef.connectionId,
15229
- ...request.connectionRef.scopes ? { scopes: request.connectionRef.scopes } : {},
15230
- ...request.connectionRef.resource ? { resource: request.connectionRef.resource } : {},
15231
- ...request.connectionRef.selectedResources ? { selectedResources: request.connectionRef.selectedResources } : {}
15232
- };
15233
- }
15384
+ const accountBindings = input.turn.mcpAccountBindings ?? [];
15385
+ const accountBinding = accountBindings.find((binding) => binding.serverId === request.serverId);
15386
+ if (input.turn.mcpAccountBindings != null && !accountBinding && canonicalMcpServerIds.has(request.serverId) || !accountBinding && accountBindings.some((binding) => binding.canonicalServerId === request.serverId) || accountBinding && (request.connectionRef.connectionId !== accountBinding.connectionId || request.connectionRef.providerDomain !== accountBinding.providerDomain || request.connectionRef.kind !== accountBinding.kind || request.connectionRef.subjectScope !== accountBinding.subjectScope || stableJson2(request.connectionRef) !== stableJson2(accountBinding.connectionRef) || accountBinding.subjectScope === "subject" && request.subjectId !== accountBinding.ownerSubjectId)) {
15387
+ return {
15388
+ status: "auth_needed",
15389
+ reason: "personal_authority_unavailable",
15390
+ providerDomain: request.connectionRef.providerDomain,
15391
+ ...request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}
15392
+ };
15234
15393
  }
15235
15394
  const acceptedDelegation = input.turn.personalConnectionDelegations.find(
15236
15395
  (delegation) => (delegation.connectionType === void 0 || delegation.connectionType === "mcp" || delegation.connectionType === "github_personal" && delegation.serverId === "github:personal" && request.serverId === "github:personal" && request.connectionRef.provider === "github" && request.connectionRef.kind === "oauth2" && request.connectionRef.providerDomain === "github.com" && request.credentialTarget === "http_api" && isGitHubApiDestination(request.destinationUrl)) && delegation.serverId === request.serverId && delegation.connectionId === request.connectionRef.connectionId
@@ -15245,19 +15404,12 @@ function connectionTokenResolverForTurn(input) {
15245
15404
  };
15246
15405
  }
15247
15406
  if (subjectScope === "workspace" && !request.connectionRef.connectionId) {
15248
- if (await (input.isSessionTenancyProductActivated ?? sessionTenancyProductActivated)(
15249
- input.db,
15250
- input.workspaceId
15251
- )) {
15252
- return {
15253
- status: "auth_needed",
15254
- reason: "missing_connection",
15255
- providerDomain: request.connectionRef.providerDomain,
15256
- ...request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}
15257
- };
15258
- }
15259
- recordTenancyCompatibilityLaneUse(input.observability, "connection_pre_snapshot_ref");
15260
- return await baseResolver(request);
15407
+ return {
15408
+ status: "auth_needed",
15409
+ reason: "missing_connection",
15410
+ providerDomain: request.connectionRef.providerDomain,
15411
+ ...request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}
15412
+ };
15261
15413
  }
15262
15414
  const credentialUseContext = {
15263
15415
  accountId: input.accountId,
@@ -15299,51 +15451,32 @@ function connectionTokenResolverForTurn(input) {
15299
15451
  })
15300
15452
  } : {},
15301
15453
  authorizeProviderRequest: async () => {
15302
- const authorization2 = await authorize({
15454
+ const authorization = await authorize({
15303
15455
  ...credentialUseContext,
15304
15456
  physicalRequestId: crypto.randomUUID(),
15305
15457
  usePhase: "provider_request"
15306
15458
  });
15307
- return authorization2.status === "authorized";
15459
+ return authorization.status === "authorized";
15308
15460
  }
15309
15461
  };
15310
15462
  };
15311
- const recordAuthorizedScope = (scope) => {
15312
- if (scope === "legacy_user") {
15313
- recordTenancyCompatibilityLaneUse(input.observability, "connection_legacy_user");
15314
- }
15315
- };
15316
- if (!hostResolver) {
15317
- const result2 = await baseResolver({
15318
- ...request,
15319
- connectionUseContext: credentialUseContext
15320
- });
15321
- if (result2.status === "ok") recordAuthorizedScope(result2.connectionUseAttribution?.scope);
15322
- return withProviderRequestAuthorization(result2);
15323
- }
15324
- const authorization = await authorize(credentialUseContext);
15325
- if (authorization.status === "denied") {
15463
+ const { subjectId: requestSubjectId, ...requestWithoutSubject } = request;
15464
+ const result = await nativeResolver({
15465
+ ...requestWithoutSubject,
15466
+ ...accountBinding?.connectionAuthorityGeneration !== void 0 ? { expectedAuthorityGeneration: accountBinding.connectionAuthorityGeneration } : {},
15467
+ // Workspace authority has no personal owner, even when the turn has a
15468
+ // causal human. Do not pass that human as credential ownership context.
15469
+ ...accountBinding?.subjectScope !== "workspace" && requestSubjectId !== void 0 ? { subjectId: requestSubjectId } : {},
15470
+ connectionUseContext: credentialUseContext
15471
+ });
15472
+ if (accountBinding && result.status === "ok" && result.connectionId !== accountBinding.connectionId) {
15326
15473
  return {
15327
15474
  status: "auth_needed",
15328
- reason: request.connectionRef.subjectScope === "subject" ? "personal_authority_unavailable" : "missing_connection",
15329
- providerDomain: request.connectionRef.providerDomain,
15330
- ...request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}
15475
+ reason: "personal_authority_unavailable",
15476
+ providerDomain: accountBinding.providerDomain
15331
15477
  };
15332
15478
  }
15333
- recordAuthorizedScope(authorization.attribution.scope);
15334
- const result = await baseResolver({
15335
- ...request,
15336
- connectionUseContext: credentialUseContext,
15337
- connectionUseAuthority: authorization.attribution,
15338
- connectionRef: {
15339
- ...request.connectionRef,
15340
- connectionId: authorization.attribution.connectionId,
15341
- kind: authorization.connectionKind,
15342
- subjectScope: authorization.attribution.scope === "workspace" ? "workspace" : "subject"
15343
- },
15344
- ...authorization.attribution.ownerSubjectId ? { subjectId: authorization.attribution.ownerSubjectId } : {}
15345
- });
15346
- return withProviderRequestAuthorization(result, authorization.attribution);
15479
+ return withProviderRequestAuthorization(result);
15347
15480
  };
15348
15481
  }
15349
15482
  function isGitHubApiDestination(value) {
@@ -15355,6 +15488,100 @@ function isGitHubApiDestination(value) {
15355
15488
  }
15356
15489
  }
15357
15490
 
15491
+ // src/activities/mcp-account-routes.ts
15492
+ function accountRouteAuthNeededPayload(payload, bindings) {
15493
+ const binding = bindings?.find((candidate) => candidate.serverId === payload.serverId);
15494
+ return binding ? {
15495
+ ...payload,
15496
+ canonicalServerId: binding.canonicalServerId,
15497
+ connectionSubjectScope: binding.subjectScope
15498
+ } : payload;
15499
+ }
15500
+ function expandMcpAccountRoutes(input) {
15501
+ if (input.bindings == null) {
15502
+ return { settings: input.settings, tools: input.tools, accountLabels: /* @__PURE__ */ new Map() };
15503
+ }
15504
+ const configured = new Map(input.settings.mcpServers.map((server) => [server.id, server]));
15505
+ const byCanonical = /* @__PURE__ */ new Map();
15506
+ const routes = /* @__PURE__ */ new Set();
15507
+ const accounts = /* @__PURE__ */ new Set();
15508
+ for (const binding of input.bindings) {
15509
+ const account = JSON.stringify([binding.canonicalServerId, binding.connectionId]);
15510
+ if (routes.has(binding.serverId) || accounts.has(account) || configured.has(binding.serverId) || binding.subjectScope === "subject" !== (binding.ownerSubjectId !== null) || binding.connectionRef.authoritySource === "host" || binding.connectionRef.connectionId !== binding.connectionId || binding.connectionRef.subjectScope !== binding.subjectScope || binding.connectionRef.providerDomain !== binding.providerDomain || binding.connectionRef.kind !== binding.kind) {
15511
+ throw new Error("Invalid accepted MCP account route");
15512
+ }
15513
+ routes.add(binding.serverId);
15514
+ accounts.add(account);
15515
+ const siblings = byCanonical.get(binding.canonicalServerId) ?? [];
15516
+ siblings.push(binding);
15517
+ byCanonical.set(binding.canonicalServerId, siblings);
15518
+ }
15519
+ const servers = [];
15520
+ const tools = [];
15521
+ const accountLabels = /* @__PURE__ */ new Map();
15522
+ for (const tool of input.tools) {
15523
+ const bindings = byCanonical.get(tool.id);
15524
+ if (!bindings) {
15525
+ if (!configured.get(tool.id)?.connectionRef) tools.push(tool);
15526
+ continue;
15527
+ }
15528
+ const canonical = configured.get(tool.id);
15529
+ if (!canonical?.connectionRef) {
15530
+ throw new Error("Accepted MCP account route has no canonical connection configuration");
15531
+ }
15532
+ for (const binding of bindings) {
15533
+ if (canonical.connectionRef.authoritySource === "host" || canonical.connectionRef.providerDomain !== binding.providerDomain || canonical.connectionRef.kind && canonical.connectionRef.kind !== binding.kind) {
15534
+ throw new Error("Accepted MCP account route does not match canonical provider");
15535
+ }
15536
+ const { headers: _headers, ...config2 } = canonical;
15537
+ const label = `${canonical.name ?? canonical.id} \u2014 ${binding.subjectScope === "subject" ? "Personal" : "Workspace"}: ${binding.accountLabel}`;
15538
+ servers.push({
15539
+ ...config2,
15540
+ id: binding.serverId,
15541
+ name: label,
15542
+ connectionRef: structuredClone(binding.connectionRef)
15543
+ });
15544
+ tools.push({ ...tool, id: binding.serverId });
15545
+ accountLabels.set(binding.serverId, label);
15546
+ }
15547
+ }
15548
+ return {
15549
+ settings: {
15550
+ ...input.settings,
15551
+ mcpServers: [
15552
+ ...input.settings.mcpServers.filter((server) => !server.connectionRef),
15553
+ ...servers
15554
+ ]
15555
+ },
15556
+ tools,
15557
+ accountLabels
15558
+ };
15559
+ }
15560
+ function expandApiIntegrationAccountRoutes(input) {
15561
+ const selected = new Set(input.tools.map((tool) => tool.id));
15562
+ if (input.bindings == null)
15563
+ return input.integrations.filter((item) => selected.has(item.serverId));
15564
+ const acceptedBindings = input.bindings;
15565
+ return input.integrations.flatMap((integration) => {
15566
+ const bindings = acceptedBindings.filter(
15567
+ (binding) => binding.canonicalServerId === integration.serverId
15568
+ );
15569
+ if (bindings.length === 0)
15570
+ return !integration.connectionRef && selected.has(integration.serverId) ? [integration] : [];
15571
+ return bindings.filter((binding) => selected.has(binding.serverId)).map((binding) => {
15572
+ if (binding.connectionAuthorityGeneration === void 0) {
15573
+ throw new Error("Accepted API integration account route has no authority generation");
15574
+ }
15575
+ return {
15576
+ ...integration,
15577
+ serverId: binding.serverId,
15578
+ connectionRef: structuredClone(binding.connectionRef),
15579
+ connectionAuthorityGeneration: binding.connectionAuthorityGeneration
15580
+ };
15581
+ });
15582
+ });
15583
+ }
15584
+
15358
15585
  // src/activities/agent-turn/tool-environment.ts
15359
15586
  import { createMcpOperationPersistence } from "@opengeni/db/mcp-operations";
15360
15587
 
@@ -30486,7 +30713,7 @@ function exactPersonalDelegation(delegations) {
30486
30713
  (delegation2) => delegation2.serverId === PERSONAL_GITHUB_DELEGATION_SERVER_ID && delegation2.connectionType === "github_personal"
30487
30714
  );
30488
30715
  const delegation = matches[0];
30489
- if (matches.length !== 1 || !delegation || delegation.providerDomain !== "github.com" || delegation.kind !== "oauth2" || !delegation.originWorkspaceId || !delegation.userDelegation || !delegation.personalGitHubRepositorySelection) {
30716
+ if (matches.length !== 1 || !delegation || delegation.providerDomain !== "github.com" || delegation.kind !== "oauth2" || !delegation.originWorkspaceId || !delegation.personalGitHubRepositorySelection) {
30490
30717
  throw new GitHubRestAuthorityError("Personal GitHub delegation is unavailable");
30491
30718
  }
30492
30719
  return delegation;
@@ -30686,7 +30913,7 @@ async function materializeConnectorAttachmentsInChannel(channel, request, option
30686
30913
  }
30687
30914
 
30688
30915
  // src/activities/agent-turn/tool-environment.ts
30689
- import { allowedFirstPartyMcpToolsForSession as allowedFirstPartyMcpToolsForSession2 } from "@opengeni/config";
30916
+ import { allowedFirstPartyMcpToolsForSession } from "@opengeni/config";
30690
30917
 
30691
30918
  // src/activities/codemode-dispatcher.ts
30692
30919
  import { randomUUID as randomUUID3 } from "crypto";
@@ -30719,13 +30946,14 @@ import {
30719
30946
  publishDurableSessionEvents as publishDurableSessionEvents8
30720
30947
  } from "@opengeni/events";
30721
30948
  var CodemodeAttemptDispatcher = class {
30722
- constructor(db, bus, environment, scope, turnSignal, maxConcurrentCalls = CODEMODE_MAX_CONCURRENT_CALLS_PER_ATTEMPT, timings = {}) {
30949
+ constructor(db, bus, environment, scope, turnSignal, maxConcurrentCalls = CODEMODE_MAX_CONCURRENT_CALLS_PER_ATTEMPT, timings = {}, toolDisplayMetadata) {
30723
30950
  this.db = db;
30724
30951
  this.bus = bus;
30725
30952
  this.environment = environment;
30726
30953
  this.scope = scope;
30727
30954
  this.turnSignal = turnSignal;
30728
30955
  this.maxConcurrentCalls = maxConcurrentCalls;
30956
+ this.toolDisplayMetadata = toolDisplayMetadata;
30729
30957
  if (environment.catalog.accountId !== scope.accountId || environment.catalog.workspaceId !== scope.workspaceId || environment.catalog.sessionId !== scope.sessionId || environment.catalog.turnId !== scope.turnId || environment.catalog.attemptId !== scope.attemptId || environment.catalog.executionGeneration !== scope.executionGeneration) {
30730
30958
  throw new Error("Codemode dispatcher scope does not match its tool environment");
30731
30959
  }
@@ -30983,6 +31211,10 @@ var CodemodeAttemptDispatcher = class {
30983
31211
  payload: {
30984
31212
  id: operation.operationId,
30985
31213
  name: entry.modelName,
31214
+ display: this.toolDisplayMetadata?.(entry.modelName) ?? {
31215
+ toolName: entry.identity.toolName,
31216
+ ...entry.title ? { title: entry.title } : {}
31217
+ },
30986
31218
  arguments: operation.arguments,
30987
31219
  origin: "codemode",
30988
31220
  subjectId: operation.caller.subjectId,
@@ -31080,7 +31312,7 @@ function safeErrorMessage(error51) {
31080
31312
  // src/activities/agent-turn/tool-environment.ts
31081
31313
  import { CODEX_CLIENT_VERSION } from "@opengeni/codex";
31082
31314
  import {
31083
- defaultSessionMcpServerIds,
31315
+ workspaceSessionToolPolicyDefaultServerIds,
31084
31316
  loadRigDefaultVariableSetEnvironment,
31085
31317
  mergeRigDefaultVariableSetEnvironment,
31086
31318
  buildApiIntegrationMcpServers,
@@ -31093,24 +31325,9 @@ import {
31093
31325
  import { SandboxChannelAService as SandboxChannelAService3 } from "@opengeni/runtime/sandbox";
31094
31326
  import { sandboxRunAs as sandboxRunAs4 } from "@opengeni/runtime";
31095
31327
  import {
31096
- DEFAULT_FIRST_PARTY_MCP_PERMISSIONS as DEFAULT_FIRST_PARTY_MCP_PERMISSIONS3
31328
+ DEFAULT_FIRST_PARTY_MCP_PERMISSIONS as DEFAULT_FIRST_PARTY_MCP_PERMISSIONS2
31097
31329
  } from "@opengeni/contracts";
31098
31330
 
31099
- // src/activities/agent-turn/turn-sandbox-access.ts
31100
- async function resolveTurnSandboxAccess(sandboxState, sdkOwnedSandboxSession, unavailableMessage) {
31101
- let sandbox = sandboxState.resolvedSandbox;
31102
- if (!sandbox && sandboxState.turnSandboxProvisioner) {
31103
- sandbox = await sandboxState.turnSandboxProvisioner.get();
31104
- }
31105
- const session = sandboxState.lazyOwnedSandbox?.session ?? sandbox?.established.session ?? sdkOwnedSandboxSession;
31106
- if (!session) throw new Error(unavailableMessage);
31107
- return {
31108
- sandbox,
31109
- session,
31110
- leaseEpoch: sandbox?.leaseEpoch ?? 0
31111
- };
31112
- }
31113
-
31114
31331
  // src/activities/agent-turn/list-models.ts
31115
31332
  import {
31116
31333
  compareModelPickerOrder,
@@ -31204,7 +31421,8 @@ import {
31204
31421
  portableSkillPluginKey,
31205
31422
  readSkill,
31206
31423
  resolveSkillImport,
31207
- saveSkill
31424
+ saveSkill,
31425
+ removeSkill
31208
31426
  } from "@opengeni/core";
31209
31427
  import {
31210
31428
  buildPortableSkillArtifact as buildPortableSkillArtifact3,
@@ -31369,7 +31587,7 @@ function createSkillSaveAttemptToolDefinition(input) {
31369
31587
  modelName: "skill_save",
31370
31588
  codemodePath: ["opengeni", "skill_save"],
31371
31589
  title: "Save Skill text",
31372
- description: "Create or edit a workspace Skill without a sandbox. Supply only changed UTF-8 text files and explicit deletions; omitted files are preserved. Use the revision and scope version returned by Skill discovery for stale-write protection. For creation choose a new UUID, set expectedRevisionId to null and expectedScopeVersion to 1. The effective Skills setting governs publication: Automatic publishes, Review first saves a pending revision in Knowledge > Needs review while the task continues, and Off prevents agent authoring. Report the actual receipt without asking an approval question. Private chats save personal Skills; shared chats save workspace Skills.",
31590
+ description: "Create or edit a Skill for reusable procedures or context-specific and personal behavioral preferences, not retrieval-only facts. Put its applicability in the SKILL.md description so the prompt index can guide skill_read; the full body is loaded when relevant. Short always-on workspace rules use instruction_policy_save. Supply only changed UTF-8 text files and explicit deletions; omitted files are preserved. No sandbox is needed. Use the revision and scope version returned by Skill discovery for stale-write protection. For creation choose a new UUID, set expectedRevisionId to null and expectedScopeVersion to 1. The effective Skills setting governs publication: Automatic publishes, Review first saves a pending revision in Knowledge > Needs review while the task continues, and Off prevents agent authoring. Report the actual receipt without asking an approval question. Private chats save personal Skills; shared chats save workspace Skills. Preserve the intended scope; another destination is not a workaround for unavailable scope or learning restrictions.",
31373
31591
  inputSchema: {
31374
31592
  type: "object",
31375
31593
  properties: {
@@ -31492,6 +31710,43 @@ function createSkillInstallAttemptToolDefinition(input) {
31492
31710
  };
31493
31711
  }
31494
31712
 
31713
+ // src/activities/agent-turn/skill-remove.ts
31714
+ var SkillRemoveRequest = external_exports.object({
31715
+ operationId: external_exports.uuid(),
31716
+ skillId: external_exports.uuid(),
31717
+ expectedRevisionId: external_exports.uuid().nullable(),
31718
+ expectedScopeVersion: external_exports.number().int().positive(),
31719
+ reason: external_exports.string().min(1).max(2e3)
31720
+ }).strict();
31721
+ function createSkillRemoveAttemptToolDefinition(input) {
31722
+ return {
31723
+ identity: { serverId: "opengeni", toolName: "skill_remove" },
31724
+ modelName: "skill_remove",
31725
+ codemodePath: ["opengeni", "skill_remove"],
31726
+ title: "Permanently remove Skill",
31727
+ description: "Permanently delete a saved Skill and ALL its stored revisions, not a recoverable hide. Conversations remain unchanged. Read the exact Skill first; supply its current active revision and scope version. Built-in, repository and inline session Skills cannot be removed. Automatic applies deletion; Review first retains an explicitly labeled deletion proposal for human review in Knowledge > Needs review; Off refuses changes. Reuse the same operationId and exact arguments after an uncertain result. Never report a pending proposal as deleted.",
31728
+ inputSchema: JSON.parse(JSON.stringify(external_exports.toJSONSchema(SkillRemoveRequest))),
31729
+ annotations: {
31730
+ readOnlyHint: false,
31731
+ destructiveHint: true,
31732
+ idempotentHint: true,
31733
+ openWorldHint: false
31734
+ },
31735
+ source: "opengeni",
31736
+ approval: "none",
31737
+ execute: async (args) => {
31738
+ await input.authorize();
31739
+ const output = await input.remove(SkillRemoveRequest.parse(args));
31740
+ const text = JSON.stringify(output);
31741
+ return {
31742
+ isError: false,
31743
+ content: [{ type: "text", text }],
31744
+ structuredContent: JSON.parse(text)
31745
+ };
31746
+ }
31747
+ };
31748
+ }
31749
+
31495
31750
  // src/activities/agent-turn/skill-transfer.ts
31496
31751
  import { posix } from "path";
31497
31752
  import {
@@ -31768,6 +32023,12 @@ function createWorkspaceSkillTools(input) {
31768
32023
  );
31769
32024
  };
31770
32025
  return [
32026
+ createSkillRemoveAttemptToolDefinition({
32027
+ authorize,
32028
+ remove: async (request) => withReviewState(
32029
+ await removeSkill(input.db, { ...context, ...request, actor: input.actor })
32030
+ )
32031
+ }),
31771
32032
  createSkillReadAttemptToolDefinition({ authorize, load }),
31772
32033
  createSkillSearchAttemptToolDefinition({
31773
32034
  authorize,
@@ -31784,7 +32045,7 @@ function createWorkspaceSkillTools(input) {
31784
32045
  id: entry.id,
31785
32046
  name: entry.artifact.name,
31786
32047
  description: entry.artifact.description || entry.artifact.name,
31787
- source: entry.id.startsWith("builtin:") ? "builtin" : entry.id.startsWith("session:") ? "session" : "pack"
32048
+ source: entry.id.startsWith("builtin:") ? "builtin" : "session"
31788
32049
  }))
31789
32050
  ],
31790
32051
  publicSearch: createPublicSkillSearchClient(input.settings)
@@ -31904,6 +32165,8 @@ function configuredBundledSkillNames(context) {
31904
32165
  const tools = new Set(context.firstPartyTools);
31905
32166
  const artifacts = () => tools.has("editable_artifact_list") && tools.has("editable_artifact_get");
31906
32167
  const definitions = [
32168
+ { name: "opengeni-help", include: () => true },
32169
+ { name: "opengeni-client", include: () => true },
31907
32170
  { name: "opengeni-visualize", include: () => true },
31908
32171
  { name: "document-parsing", include: () => true },
31909
32172
  { name: "opengeni-skills", include: () => true },
@@ -31962,7 +32225,12 @@ async function prepareTurnToolPolicy(deps) {
31962
32225
  toolPolicy: session.toolPolicy,
31963
32226
  sessionTools: scheduledEffectiveMcpServerIds ? turn.tools : session.tools,
31964
32227
  availableMcpServerIds: scheduledEffectiveMcpServerIds ? scheduledEffectiveMcpServerIds.filter((id) => currentMcpServerIds.has(id)) : [...currentMcpServerIds],
31965
- defaultMcpServerIds: scheduledEffectiveMcpServerIds ?? defaultSessionMcpServerIds(capabilitySettings.mcpServers)
32228
+ defaultMcpServerIds: scheduledEffectiveMcpServerIds ?? (session.toolPolicy.mode === "workspace_default" ? await workspaceSessionToolPolicyDefaultServerIds(
32229
+ db,
32230
+ input.workspaceId,
32231
+ capabilitySettings,
32232
+ fileAuthoritySubjectId ?? void 0
32233
+ ) : [])
31966
32234
  });
31967
32235
  const mcpAvailabilityNote = unavailableMcpOperationalContext({
31968
32236
  droppedIds: resolvedToolPolicy.effectivePolicy.droppedIds,
@@ -32064,7 +32332,6 @@ async function prepareTurnToolRuntime(deps) {
32064
32332
  objectStorage,
32065
32333
  observability,
32066
32334
  cancellationSignal,
32067
- connectionCredentials,
32068
32335
  eventing,
32069
32336
  attempt,
32070
32337
  sandboxState,
@@ -32076,10 +32343,9 @@ async function prepareTurnToolRuntime(deps) {
32076
32343
  codexAppsCredentialId,
32077
32344
  turnExecutionPolicy,
32078
32345
  trigger,
32079
- runSettings,
32346
+ runSettings: canonicalRunSettings,
32080
32347
  lazyToolTransport,
32081
- turnTools,
32082
- hostCredentialRootSessionId,
32348
+ turnTools: canonicalTurnTools,
32083
32349
  sandboxArtifactRuntime,
32084
32350
  activeSandboxBackend,
32085
32351
  groupBoxBackend,
@@ -32091,21 +32357,25 @@ async function prepareTurnToolRuntime(deps) {
32091
32357
  throwIfWorkerShuttingDown,
32092
32358
  throwIfTurnCancelled
32093
32359
  } = deps;
32360
+ const accountRoutes = expandMcpAccountRoutes({
32361
+ settings: canonicalRunSettings,
32362
+ tools: canonicalTurnTools,
32363
+ bindings: turn.mcpAccountBindings
32364
+ });
32365
+ const runSettings = accountRoutes.settings;
32366
+ const turnTools = accountRoutes.tools;
32094
32367
  const toolContextPreparationStartedAt = performance.now();
32095
32368
  throwIfWorkerShuttingDown();
32096
32369
  throwIfTurnCancelled();
32097
- const mcpCredentialRootSessionId = connectionCredentials?.mcpCredentials && hostCredentialRootSessionId ? hostCredentialRootSessionId : input.sessionId;
32098
32370
  const rawResolveCredential = connectionTokenResolverForTurn({
32099
32371
  db,
32100
32372
  settings: runSettings,
32101
- connectionCredentials: connectionCredentials ?? null,
32373
+ canonicalMcpServerIds: canonicalRunSettings.mcpServers.filter((server) => server.connectionRef).map((server) => server.id),
32102
32374
  accountId: input.accountId,
32103
32375
  workspaceId: input.workspaceId,
32104
32376
  sessionId: input.sessionId,
32105
- rootSessionId: mcpCredentialRootSessionId,
32106
32377
  attemptId: input.attemptId,
32107
- turn,
32108
- observability
32378
+ turn
32109
32379
  });
32110
32380
  const personalConnectionDelegations = turn.personalConnectionDelegations;
32111
32381
  const delegatedMembershipChecks = /* @__PURE__ */ new Map();
@@ -32163,16 +32433,24 @@ async function prepareTurnToolRuntime(deps) {
32163
32433
  return;
32164
32434
  }
32165
32435
  await eventing.publish(
32166
- [{ type: "tool.auth_needed", payload: rollingSafeToolAuthNeededPayload(payload) }],
32436
+ [
32437
+ {
32438
+ type: "tool.auth_needed",
32439
+ payload: rollingSafeToolAuthNeededPayload(
32440
+ accountRouteAuthNeededPayload(payload, turn.mcpAccountBindings)
32441
+ )
32442
+ }
32443
+ ],
32167
32444
  true
32168
32445
  );
32169
32446
  };
32170
- const selectedApiIntegrationServerIds = new Set(turnTools.map((tool) => tool.id));
32171
32447
  const apiIntegrationMcpServers = buildApiIntegrationMcpServers({
32172
32448
  settings: runSettings,
32173
- integrations: installedApiIntegrations.filter(
32174
- (integration) => selectedApiIntegrationServerIds.has(integration.serverId)
32175
- ),
32449
+ integrations: expandApiIntegrationAccountRoutes({
32450
+ integrations: installedApiIntegrations,
32451
+ bindings: turn.mcpAccountBindings,
32452
+ tools: turnTools
32453
+ }),
32176
32454
  authority: {
32177
32455
  accountId: input.accountId,
32178
32456
  workspaceId: input.workspaceId,
@@ -32230,10 +32508,10 @@ async function prepareTurnToolRuntime(deps) {
32230
32508
  );
32231
32509
  if (linkedAuthority && !linkedAuthority.authorized)
32232
32510
  throw new Error("Native identity link was revoked");
32233
- const effectiveFirstPartyPermissions = linkedAuthority ? (session.firstPartyMcpPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS3).filter(
32511
+ const effectiveFirstPartyPermissions = linkedAuthority ? (session.firstPartyMcpPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS2).filter(
32234
32512
  (permission) => hasPermission2(linkedAuthority.permissions, permission)
32235
32513
  ) : session.firstPartyMcpPermissions;
32236
- const selectedFirstPartyMcpTools = allowedFirstPartyMcpToolsForSession2(
32514
+ const selectedFirstPartyMcpTools = allowedFirstPartyMcpToolsForSession(
32237
32515
  runSettings,
32238
32516
  session.firstPartyMcpTools
32239
32517
  );
@@ -32249,10 +32527,10 @@ async function prepareTurnToolRuntime(deps) {
32249
32527
  parallelGenerationAvailable: typeof runtime.generateSessionTitle === "function"
32250
32528
  });
32251
32529
  const googleDrivePublicationAllowed = selectedFirstPartyMcpTools.includes("editable_artifact_export") && selectedFirstPartyMcpTools.includes("editable_artifact_export_status") && hasPermission2(
32252
- [...effectiveFirstPartyPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS3],
32530
+ [...effectiveFirstPartyPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS2],
32253
32531
  "artifacts:read"
32254
32532
  ) && hasPermission2(
32255
- [...effectiveFirstPartyPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS3],
32533
+ [...effectiveFirstPartyPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS2],
32256
32534
  "artifacts:publish"
32257
32535
  );
32258
32536
  const googleDriveConnectorBindings = googleDrivePublicationTool && googleDrivePublicationTarget && googleDrivePublicationAllowed ? [
@@ -32289,7 +32567,6 @@ async function prepareTurnToolRuntime(deps) {
32289
32567
  });
32290
32568
  const selectedSkills = [
32291
32569
  ...bundledSkills,
32292
- ...deps.selectedSkillActivations.map((entry) => ({ id: entry.id, artifact: entry.artifact })),
32293
32570
  ...session.skills.map((skill) => ({
32294
32571
  id: `session:${session.id}:${skill.name}`,
32295
32572
  artifact: skill
@@ -32391,7 +32668,7 @@ async function prepareTurnToolRuntime(deps) {
32391
32668
  assertAttempt: async () => {
32392
32669
  throwIfWorkerShuttingDown();
32393
32670
  throwIfTurnCancelled();
32394
- const current = await getSessionTurnForAttempt2(
32671
+ const current = await getSessionTurnForAttempt(
32395
32672
  db,
32396
32673
  input.workspaceId,
32397
32674
  input.sessionId,
@@ -32597,6 +32874,7 @@ async function prepareTurnToolRuntime(deps) {
32597
32874
  try {
32598
32875
  eventing.preparedTools = await waitForTurnOperation(
32599
32876
  runtime.prepareTools(githubRestMcp.settings, githubRestMcp.tools, {
32877
+ mcpAccountLabels: accountRoutes.accountLabels,
32600
32878
  accountId: input.accountId,
32601
32879
  workspaceId: input.workspaceId,
32602
32880
  sessionId: input.sessionId,
@@ -32614,7 +32892,7 @@ async function prepareTurnToolRuntime(deps) {
32614
32892
  ...operationPersistence ? { mcpOperationPersistence: operationPersistence } : {},
32615
32893
  ...linkedAuthority ? {
32616
32894
  authorizeAttemptExecution: async () => {
32617
- const current = await getSessionTurnForAttempt2(
32895
+ const current = await getSessionTurnForAttempt(
32618
32896
  db,
32619
32897
  input.workspaceId,
32620
32898
  input.sessionId,
@@ -32636,13 +32914,10 @@ async function prepareTurnToolRuntime(deps) {
32636
32914
  localMcpServers,
32637
32915
  ...deferNonEagerToolPreparation ? { deferNonEagerUntilToolDemand: true } : {},
32638
32916
  onPreparationPhase: (measurement) => {
32639
- recordTurnStartupPhase(observability, {
32640
- phase: `tool_${measurement.phase}`,
32917
+ recordToolPreparationPhase(observability, {
32918
+ ...measurement,
32641
32919
  provider: turnExecutionPolicy.providerId,
32642
- backend: activeSandboxBackend ?? groupBoxBackend,
32643
- outcome: measurement.outcome,
32644
- durationSeconds: measurement.durationSeconds,
32645
- count: githubRestMcp.tools.length
32920
+ backend: activeSandboxBackend ?? groupBoxBackend
32646
32921
  });
32647
32922
  },
32648
32923
  onAttemptToolCatalog: async (catalog) => {
@@ -32701,7 +32976,10 @@ async function prepareTurnToolRuntime(deps) {
32701
32976
  attemptId: input.attemptId,
32702
32977
  executionGeneration: attempt.executionGeneration
32703
32978
  },
32704
- cancellationSignal
32979
+ cancellationSignal,
32980
+ void 0,
32981
+ {},
32982
+ (name) => mcpToolDisplayMetadata(tools.mcpServers, name)
32705
32983
  );
32706
32984
  eventing.codemodeDispatcher.start();
32707
32985
  };
@@ -32717,6 +32995,7 @@ async function prepareTurnToolRuntime(deps) {
32717
32995
  return {
32718
32996
  attemptConnectorActionBindings,
32719
32997
  connectorActionPolicy,
32998
+ mcpServers: runSettings.mcpServers,
32720
32999
  generateSessionTitleInParallel: titleToolPlan.generateTitleInParallel,
32721
33000
  postToolPreparationStartedAt,
32722
33001
  preparationIndependentToolNames: [
@@ -32920,7 +33199,9 @@ import {
32920
33199
  getWorkspaceVideoGenerationPolicy as getWorkspaceVideoGenerationPolicy2,
32921
33200
  loadWorkspaceVercelAiGatewayCredentialLease,
32922
33201
  getExternalLinkTurnAuthorization as getExternalLinkTurnAuthorization2,
32923
- getSessionTurnForAttempt as getSessionTurnForAttempt3
33202
+ getSessionTurnForAttempt as getSessionTurnForAttempt2,
33203
+ ensureSessionReasoningConfiguration,
33204
+ ensureSessionSkillCatalog
32924
33205
  } from "@opengeni/db";
32925
33206
  import {
32926
33207
  formatSkillCatalog
@@ -32931,6 +33212,7 @@ import {
32931
33212
  WORKSPACE_GATEWAY_PROVIDER_ID as WORKSPACE_GATEWAY_PROVIDER_ID2,
32932
33213
  resolveModelProvider as resolveModelProvider2
32933
33214
  } from "@opengeni/config";
33215
+ import { supportsReasoningConfiguration as supportsReasoningConfiguration2 } from "@opengeni/codex";
32934
33216
 
32935
33217
  // src/activities/xai-image-generation.ts
32936
33218
  import {
@@ -34089,6 +34371,7 @@ async function resolveVideoReferenceSandboxAccess(request, sandboxState, sdkOwne
34089
34371
  // src/activities/agent-turn/agent-build.ts
34090
34372
  async function buildTurnAgent(deps) {
34091
34373
  const {
34374
+ mcpServers,
34092
34375
  input,
34093
34376
  db,
34094
34377
  runtime,
@@ -34144,6 +34427,11 @@ async function buildTurnAgent(deps) {
34144
34427
  codexContext
34145
34428
  } = deps;
34146
34429
  const preparedTools = eventing.preparedTools;
34430
+ const sessionInstructions = await recoveryAwareSessionInstructions(
34431
+ db,
34432
+ input.workspaceId,
34433
+ session
34434
+ );
34147
34435
  const missingSessionTitleHint = preparationIndependentToolNames.includes(
34148
34436
  SESSION_TITLE_MODEL_TOOL_NAME
34149
34437
  );
@@ -34455,7 +34743,15 @@ async function buildTurnAgent(deps) {
34455
34743
  turnExecutionPolicy.latencyMode
34456
34744
  );
34457
34745
  const approvedToolCallId = approvedConnectorActionCallId(trigger);
34458
- const modelVisibleSkillCatalogText = formatSkillCatalog(deps.skillCatalog);
34746
+ const modelVisibleSkillCatalogText = await ensureSessionSkillCatalog(db, {
34747
+ accountId: input.accountId,
34748
+ workspaceId: input.workspaceId,
34749
+ sessionId: input.sessionId,
34750
+ turnId: turn.id,
34751
+ expectedExecutionGeneration: turn.executionGeneration,
34752
+ expectedAttemptId: input.attemptId,
34753
+ catalog: formatSkillCatalog(deps.skillCatalog)
34754
+ });
34459
34755
  try {
34460
34756
  eventing.companyBrainContextContributions = summarizeCompanyBrainContributions(
34461
34757
  buildCompanyBrainContributionReceiptFor(modelVisibleSkillCatalogText)
@@ -34479,14 +34775,24 @@ async function buildTurnAgent(deps) {
34479
34775
  );
34480
34776
  if (linkedToolAuthority && !linkedToolAuthority.authorized)
34481
34777
  throw new Error("Native identity link was revoked");
34778
+ const useReasoningUpdates = eventing.modelRunSettings.reasoningConfigurationUpdatesEnabled && resolvedModel?.provider.api === "responses" && (resolvedModel.provider.id === "codex" || resolvedModel.provider.id === "openai") && supportsReasoningConfiguration2(turnExecutionPolicy.upstreamModelId, turn.reasoningEffort);
34779
+ const requestReasoningEffort = useReasoningUpdates && supportsReasoningConfiguration2(turnExecutionPolicy.upstreamModelId, turn.reasoningEffort) ? await ensureSessionReasoningConfiguration(db, {
34780
+ accountId: input.accountId,
34781
+ workspaceId: input.workspaceId,
34782
+ sessionId: input.sessionId,
34783
+ turnId: turn.id,
34784
+ expectedExecutionGeneration: turn.executionGeneration,
34785
+ expectedAttemptId: input.attemptId,
34786
+ effort: turn.reasoningEffort
34787
+ }) : turn.reasoningEffort;
34482
34788
  const agent = (() => {
34483
34789
  const agentConstructionStartedAt = performance.now();
34484
34790
  let agentConstructionOutcome = "completed";
34485
34791
  try {
34486
- return runtime.buildAgent(eventing.modelRunSettings, runtimeResources, {
34792
+ return runtime.buildAgent({ ...eventing.modelRunSettings, mcpServers }, runtimeResources, {
34487
34793
  ...linkedToolAuthority ? {
34488
34794
  authorizeAttemptExecution: async () => {
34489
- const current = await getSessionTurnForAttempt3(
34795
+ const current = await getSessionTurnForAttempt2(
34490
34796
  db,
34491
34797
  input.workspaceId,
34492
34798
  input.sessionId,
@@ -34497,7 +34803,7 @@ async function buildTurnAgent(deps) {
34497
34803
  }
34498
34804
  } : {},
34499
34805
  ...preparedTools.inputWaitYield ? { inputWaitYield: preparedTools.inputWaitYield } : {},
34500
- reasoningEffort: turn.reasoningEffort,
34806
+ reasoningEffort: requestReasoningEffort,
34501
34807
  latencyMode: turnExecutionPolicy.latencyMode,
34502
34808
  ...serviceTier ? { serviceTier } : {},
34503
34809
  ...humanInputResume ? { humanInputResponse: humanInputResume } : {},
@@ -34582,13 +34888,14 @@ async function buildTurnAgent(deps) {
34582
34888
  ),
34583
34889
  onRetainableSessionImageOutput: media.retainSessionImageAtToolBoundary,
34584
34890
  skillCatalog: deps.skillCatalog,
34891
+ skillCatalogInHistory: true,
34585
34892
  ...!structuredWorkspacePolicyActive && workspaceAgentInstructions ? { instructionsTemplate: workspaceAgentInstructions } : {},
34586
34893
  ...workspaceGovernance ? { workspaceGovernance } : {},
34587
34894
  ...workspaceMemory ? { workspaceMemory } : {},
34588
34895
  // Per-session persona tier (session > workspace > deployment default).
34589
34896
  // Composed system-level AFTER the workspace persona so it refines it for
34590
34897
  // this one session; absent ⇒ byte-identical to today's composition.
34591
- ...session.instructions ? { sessionInstructions: session.instructions } : {},
34898
+ ...sessionInstructions ? { sessionInstructions } : {},
34592
34899
  ...workspaceEnvironmentOption,
34593
34900
  // RIG RUNTIME (M3): the doctrine block, the setup-script hook (only when
34594
34901
  // the frozen version carries a non-empty script), and the rig credential
@@ -34687,7 +34994,7 @@ function createRunAgentTurnActivity(services) {
34687
34994
  });
34688
34995
  const modelCheckpointMemoryCollector = createModelCheckpointMemoryCollector();
34689
34996
  const turnCompletionMemoryCollector = createModelCheckpointMemoryCollector();
34690
- return async function runAgentTurn(input) {
34997
+ const runAgentTurn = async (input, resolvedServices, activitySpan) => {
34691
34998
  const {
34692
34999
  settings,
34693
35000
  catalogSourceSettings = settings,
@@ -34704,7 +35011,7 @@ function createRunAgentTurnActivity(services) {
34704
35011
  connectionCredentials,
34705
35012
  personalGitHubCredentials,
34706
35013
  startVideoGenerationWorkflow
34707
- } = await services();
35014
+ } = resolvedServices;
34708
35015
  const activityContext = currentActivityContext();
34709
35016
  const cancellationSignal = activityContext?.cancellationSignal;
34710
35017
  const sandboxResumeController = new AbortController();
@@ -34732,11 +35039,6 @@ function createRunAgentTurnActivity(services) {
34732
35039
  });
34733
35040
  const dispatchId = activityContext?.info.activityId ?? randomUUID6();
34734
35041
  const activityStarted = performance.now();
34735
- const activitySpan = observability.startSpan("worker.run_agent_segment", {
34736
- "opengeni.session_id": input.sessionId,
34737
- "opengeni.workflow_id": input.workflowId,
34738
- "opengeni.trigger_kind": input.trigger.kind
34739
- });
34740
35042
  const acknowledgeLostAttemptOwnership = () => {
34741
35043
  control.acknowledgeQuiescence = true;
34742
35044
  noteCancellationRequested();
@@ -34757,7 +35059,7 @@ function createRunAgentTurnActivity(services) {
34757
35059
  const machineOpObserver = makeMachineOpObserver(
34758
35060
  runtimeMetricsHooksForObservability(observability)
34759
35061
  );
34760
- const sandboxOperationObserver = sandboxOperationMetricObserver(observability);
35062
+ const sandboxOperationObserver = sandboxOperationMetricObserver2(observability);
34761
35063
  const setLastInputTokensFenced = async (lastInputTokens) => {
34762
35064
  if (!attempt.turnId || attempt.executionGeneration <= 0) {
34763
35065
  throw new Error("Turn attempt was not initialized before token accounting");
@@ -34918,8 +35220,26 @@ function createRunAgentTurnActivity(services) {
34918
35220
  executionGeneration: attempt.executionGeneration
34919
35221
  }
34920
35222
  });
35223
+ const attachmentAuthority = await getSessionAuthorityProjection(
35224
+ db,
35225
+ input.workspaceId,
35226
+ input.sessionId
35227
+ );
35228
+ if (!attachmentAuthority) throw new Error("Session attachment authority unavailable");
34921
35229
  return await withSessionRlsActorContext(
34922
35230
  {
35231
+ sessionAttachmentReadAccess: {
35232
+ sessionId: input.sessionId,
35233
+ authorityEpoch: attachmentAuthority.authorityEpoch,
35234
+ actor: {
35235
+ kind: "agent_attempt",
35236
+ subjectId: "service:agent-turn",
35237
+ callerSessionId: input.sessionId,
35238
+ turnId: attempt.turnId,
35239
+ attemptId: input.attemptId,
35240
+ executionGeneration: attempt.executionGeneration
35241
+ }
35242
+ },
34923
35243
  subjectId: "service:agent-turn",
34924
35244
  initiatingHumanSubjectId: fileAuthoritySubjectId,
34925
35245
  privateFileOwnerSubjectId: learning.defaultScope === "personal" ? learning.subjectId : null
@@ -34987,7 +35307,6 @@ function createRunAgentTurnActivity(services) {
34987
35307
  });
34988
35308
  const {
34989
35309
  runtimePreparationStartedAt,
34990
- packRuntime,
34991
35310
  rigVersion,
34992
35311
  rigName,
34993
35312
  agentHumanInputEnabled,
@@ -35017,7 +35336,13 @@ function createRunAgentTurnActivity(services) {
35017
35336
  db,
35018
35337
  runSettings,
35019
35338
  input.workspaceId,
35020
- providerTurn.effectiveCodexCredentialId ?? ""
35339
+ providerTurn.effectiveCodexCredentialId ?? "",
35340
+ void 0,
35341
+ {
35342
+ turnId: turn.id,
35343
+ holderId: leases.codex.holderId,
35344
+ generation: leases.codex.generation
35345
+ }
35021
35346
  );
35022
35347
  const resolveTrackedToken = async (resolve) => {
35023
35348
  const token = await resolve();
@@ -35408,38 +35733,7 @@ These are publication receipts for the human's earlier answer. Do not call the r
35408
35733
  cancellationSignal?.throwIfAborted();
35409
35734
  knowledgeRecoveryNote = "[OpenGeni confirmation recovery unavailable] Do not assume an earlier remember confirmation was published. Inspect the current Knowledge or instruction review.";
35410
35735
  }
35411
- const attachmentPreparationNote = await prepareTurnKnowledgeSources({
35412
- settings: runSettings,
35413
- scope: {
35414
- accountId: input.accountId,
35415
- workspaceId: input.workspaceId,
35416
- sessionId: input.sessionId,
35417
- turnId: turn.id,
35418
- attemptId: input.attemptId,
35419
- executionGeneration: attempt.executionGeneration
35420
- },
35421
- // Only attachments on this accepted turn are new source inputs.
35422
- // Session-level file receipts remain historical context and must
35423
- // never trigger metadata reads, downloads, or re-preparation.
35424
- resources: turn.resources,
35425
- selectedTools: session.firstPartyMcpTools,
35426
- permissions: session.firstPartyMcpPermissions,
35427
- learningMode: learning.effective.knowledge,
35428
- signal: cancellationSignal,
35429
- onOutcome: async (outcome) => {
35430
- if (outcome.status === "disabled") return;
35431
- await eventing.publish(
35432
- [
35433
- {
35434
- type: outcome.status === "failed" ? "knowledge.source.failed" : "knowledge.source.prepared",
35435
- payload: outcome
35436
- }
35437
- ],
35438
- true
35439
- );
35440
- }
35441
- });
35442
- const knowledgeSourcePreparationNote = [knowledgeRecoveryNote, attachmentPreparationNote].filter(Boolean).join("\n\n") || void 0;
35736
+ const knowledgeSourcePreparationNote = knowledgeRecoveryNote;
35443
35737
  const sandboxRoute = await resolveSandboxRoute({
35444
35738
  input,
35445
35739
  settings,
@@ -35510,7 +35804,6 @@ These are publication receipts for the human's earlier answer. Do not call the r
35510
35804
  establishPolicy,
35511
35805
  initialRunCredentialMaterial,
35512
35806
  runCredentialsNote,
35513
- hostCredentialRootSessionId,
35514
35807
  codemodeAuthority,
35515
35808
  sandboxArtifactRuntime,
35516
35809
  sandboxEnvironment,
@@ -35628,7 +35921,6 @@ These are publication receipts for the human's earlier answer. Do not call the r
35628
35921
  ];
35629
35922
  const toolRuntime = await prepareTurnToolRuntime({
35630
35923
  fetchKnowledgeSource: sourceActivities.runKnowledgeSourceSyncBatch,
35631
- selectedSkillActivations: packRuntime.skillActivations,
35632
35924
  input,
35633
35925
  catalogSourceSettings,
35634
35926
  db,
@@ -35637,7 +35929,6 @@ These are publication receipts for the human's earlier answer. Do not call the r
35637
35929
  objectStorage,
35638
35930
  observability,
35639
35931
  cancellationSignal,
35640
- connectionCredentials,
35641
35932
  eventing,
35642
35933
  attempt,
35643
35934
  sandboxState,
@@ -35655,7 +35946,6 @@ These are publication receipts for the human's earlier answer. Do not call the r
35655
35946
  lazyToolTransport,
35656
35947
  turnTools,
35657
35948
  connectionScope,
35658
- hostCredentialRootSessionId,
35659
35949
  sandboxArtifactRuntime,
35660
35950
  activeSandboxBackend,
35661
35951
  groupBoxBackend,
@@ -35676,6 +35966,7 @@ These are publication receipts for the human's earlier answer. Do not call the r
35676
35966
  } = toolRuntime;
35677
35967
  const builtAgent = await buildTurnAgent({
35678
35968
  skillCatalog: toolRuntime.skillCatalog,
35969
+ mcpServers: toolRuntime.mcpServers,
35679
35970
  input,
35680
35971
  db,
35681
35972
  runtime,
@@ -36103,6 +36394,36 @@ These are publication receipts for the human's earlier answer. Do not call the r
36103
36394
  });
36104
36395
  }
36105
36396
  };
36397
+ return async (input) => {
36398
+ const resolvedServices = await services();
36399
+ const correlationId = turnExecutionTelemetryKey2(
36400
+ input.workspaceId,
36401
+ input.sessionId,
36402
+ input.attemptId
36403
+ );
36404
+ const span = resolvedServices.observability.startSpan(
36405
+ "worker.run_agent_segment",
36406
+ {
36407
+ "opengeni.trigger_kind": input.trigger.kind,
36408
+ correlationId
36409
+ },
36410
+ { parent: null }
36411
+ );
36412
+ try {
36413
+ return await withTraceContext(span, () => {
36414
+ try {
36415
+ resolvedServices.observability.info("worker execution started", { correlationId });
36416
+ } catch {
36417
+ }
36418
+ return runAgentTurn(input, resolvedServices, span);
36419
+ });
36420
+ } catch (error51) {
36421
+ span.end({ error: error51 });
36422
+ throw error51;
36423
+ } finally {
36424
+ span.end();
36425
+ }
36426
+ };
36106
36427
  }
36107
36428
 
36108
36429
  // src/activities/video-generation-reconciliation.ts
@@ -37202,4 +37523,4 @@ export {
37202
37523
  createTurnActivities,
37203
37524
  createTurnActivitiesFromServices
37204
37525
  };
37205
- //# sourceMappingURL=activities-turn-AP67JADS.js.map
37526
+ //# sourceMappingURL=activities-turn-UCFKWOAA.js.map