@opengeni/worker-bundle 1.0.0-canary.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/dist/activities/agent-run-admission.d.ts +3 -1
  2. package/dist/activities/agent-turn/admission.d.ts +24 -3
  3. package/dist/activities/agent-turn/agent-build.d.ts +4 -0
  4. package/dist/activities/agent-turn/claude-usage-observer.d.ts +58 -0
  5. package/dist/activities/agent-turn/code-search.d.ts +60 -0
  6. package/dist/activities/agent-turn/codex-capacity.d.ts +13 -0
  7. package/dist/activities/agent-turn/codex-plan-entitlement.d.ts +105 -0
  8. package/dist/activities/agent-turn/codex.d.ts +3 -2
  9. package/dist/activities/agent-turn/compaction-prep.d.ts +21 -5
  10. package/dist/activities/agent-turn/credential-leases.d.ts +19 -33
  11. package/dist/activities/agent-turn/credential-restriction.d.ts +3 -0
  12. package/dist/activities/agent-turn/errors.d.ts +82 -11
  13. package/dist/activities/agent-turn/failure-settlement.d.ts +6 -3
  14. package/dist/activities/agent-turn/final-reply.d.ts +18 -0
  15. package/dist/activities/agent-turn/finalization-monitor.d.ts +17 -0
  16. package/dist/activities/agent-turn/finalization.d.ts +4 -2
  17. package/dist/activities/agent-turn/github-repository-bindings.d.ts +2 -0
  18. package/dist/activities/agent-turn/governance-model.d.ts +9 -2
  19. package/dist/activities/agent-turn/history-sink.d.ts +2 -0
  20. package/dist/activities/agent-turn/history.d.ts +2 -0
  21. package/dist/activities/agent-turn/input-wait-reply.d.ts +41 -0
  22. package/dist/activities/agent-turn/media-artifacts.d.ts +5 -3
  23. package/dist/activities/agent-turn/model-call-admission.d.ts +15 -0
  24. package/dist/activities/agent-turn/model-usage.d.ts +6 -0
  25. package/dist/activities/agent-turn/model-wire-dispatch.d.ts +15 -0
  26. package/dist/activities/agent-turn/optional-repositories.d.ts +59 -0
  27. package/dist/activities/agent-turn/provider-dispatch-barrier.d.ts +12 -1
  28. package/dist/activities/agent-turn/quiescence.d.ts +7 -7
  29. package/dist/activities/agent-turn/recovery-warning.d.ts +9 -0
  30. package/dist/activities/agent-turn/refresh-credentials.d.ts +6 -0
  31. package/dist/activities/agent-turn/run-credentials.d.ts +8 -3
  32. package/dist/activities/agent-turn/sandbox-establish.d.ts +2 -1
  33. package/dist/activities/agent-turn/sandbox-provision.d.ts +3 -1
  34. package/dist/activities/agent-turn/sandbox-route.d.ts +3 -20
  35. package/dist/activities/agent-turn/sandbox-runtime.d.ts +2 -2
  36. package/dist/activities/agent-turn/session-title.d.ts +34 -2
  37. package/dist/activities/agent-turn/skill-checkout.d.ts +25 -6
  38. package/dist/activities/agent-turn/skill-read.d.ts +70 -2
  39. package/dist/activities/agent-turn/skill-remove.d.ts +14 -0
  40. package/dist/activities/agent-turn/skill-search.d.ts +3 -1
  41. package/dist/activities/agent-turn/skill-tools.d.ts +15 -2
  42. package/dist/activities/agent-turn/skill-transfer.d.ts +18 -6
  43. package/dist/activities/agent-turn/stream-attempt.d.ts +7 -3
  44. package/dist/activities/agent-turn/subscription-lease.d.ts +38 -0
  45. package/dist/activities/agent-turn/tool-environment.d.ts +56 -6
  46. package/dist/activities/agent-turn/tool-policy.d.ts +43 -0
  47. package/dist/activities/agent-turn/turn-context.d.ts +29 -0
  48. package/dist/activities/agent-turn/turn-sandbox-access.d.ts +3 -0
  49. package/dist/activities/agent-turn/xai-capacity.d.ts +2 -1
  50. package/dist/activities/automations.d.ts +3 -1
  51. package/dist/activities/browser-deadline-checkpoint.d.ts +29 -0
  52. package/dist/activities/codemode-dispatcher.d.ts +9 -2
  53. package/dist/activities/codex-capacity.d.ts +18 -2
  54. package/dist/activities/codex-rotation.d.ts +7 -1
  55. package/dist/activities/context-compaction.d.ts +16 -2
  56. package/dist/activities/gmail-files.d.ts +32 -0
  57. package/dist/activities/goals.d.ts +8 -0
  58. package/dist/activities/knowledge-indexing.d.ts +19 -0
  59. package/dist/activities/mcp-account-routes.d.ts +3 -0
  60. package/dist/activities/mcp-credentials.d.ts +12 -13
  61. package/dist/activities/mcp-operation-authority.d.ts +0 -5
  62. package/dist/activities/model-call-fact-reconciler.d.ts +34 -0
  63. package/dist/activities/open-suffix-resume.d.ts +13 -0
  64. package/dist/activities/parent-wake.d.ts +6 -12
  65. package/dist/activities/retained-screenshots.d.ts +7 -2
  66. package/dist/activities/rig-verification.d.ts +2 -3
  67. package/dist/activities/run-credential-renewal.d.ts +1 -0
  68. package/dist/activities/run-credentials.d.ts +15 -3
  69. package/dist/activities/sandbox-images.d.ts +1 -1
  70. package/dist/activities/sandbox-lease.d.ts +47 -9
  71. package/dist/activities/scheduled-tasks.d.ts +4 -35
  72. package/dist/activities/session-state.d.ts +70 -3
  73. package/dist/activities/types.d.ts +55 -6
  74. package/dist/activities/workspace-capture.d.ts +2 -0
  75. package/dist/activities/workspace-credential-provider.d.ts +46 -0
  76. package/dist/{activities-control-HMFGSKC5.js → activities-control-BNPTRTOE.js} +1896 -418
  77. package/dist/activities-control-BNPTRTOE.js.map +1 -0
  78. package/dist/activities-control.d.ts +182 -4
  79. package/dist/{activities-turn-AP67JADS.js → activities-turn-5LGZOSVU.js} +4476 -1327
  80. package/dist/activities-turn-5LGZOSVU.js.map +1 -0
  81. package/dist/activities.d.ts +182 -4
  82. package/dist/artifact-materializer-entry.js +5 -2
  83. package/dist/artifact-materializer-entry.js.map +1 -1
  84. package/dist/artifact-outbox-entry.js +5 -2
  85. package/dist/artifact-outbox-entry.js.map +1 -1
  86. package/dist/browser-deadline-checkpoint-contract.d.ts +2 -0
  87. package/dist/{chunk-A4XQWVZK.js → chunk-3ZTRWDMN.js} +307 -4
  88. package/dist/chunk-3ZTRWDMN.js.map +1 -0
  89. package/dist/{chunk-RAMNYSAW.js → chunk-4ER3YXOT.js} +22 -4
  90. package/dist/chunk-4ER3YXOT.js.map +1 -0
  91. package/dist/{chunk-CYITU5UH.js → chunk-LJX7Z2KP.js} +1445 -343
  92. package/dist/chunk-LJX7Z2KP.js.map +1 -0
  93. package/dist/editable-artifact-materializer-service.d.ts +2 -2
  94. package/dist/editable-artifact-outbox-service.d.ts +2 -2
  95. package/dist/host-export-pump.d.ts +3 -1
  96. package/dist/host-export.d.ts +1 -1
  97. package/dist/host-export.js +1 -1
  98. package/dist/http.d.ts +1 -1
  99. package/dist/index.d.ts +95 -3
  100. package/dist/index.js +137 -43
  101. package/dist/index.js.map +1 -1
  102. package/dist/observability-metrics.d.ts +118 -8
  103. package/dist/retained-process-diagnostics.d.ts +4 -0
  104. package/dist/retained-process-retry.d.ts +7 -0
  105. package/dist/sandbox-resume.d.ts +55 -13
  106. package/dist/sandbox-routing.d.ts +5 -3
  107. package/dist/sandbox-snapshot-diagnostics.d.ts +20 -0
  108. package/dist/session-event-fanout.d.ts +6 -0
  109. package/dist/warm-capture-holder.d.ts +3 -0
  110. package/dist/worker-service-lifecycle.d.ts +12 -0
  111. package/dist/workflow-bundle.js +273 -41
  112. package/dist/workflows/activities.d.ts +1 -1
  113. package/dist/workflows/browser-deadline-checkpoint.d.ts +9 -0
  114. package/dist/workflows/scheduled-tasks.d.ts +4 -0
  115. package/dist/workflows/session.d.ts +36 -0
  116. package/dist/workflows.d.ts +1 -0
  117. package/package.json +21 -19
  118. package/src/activities/agent-run-admission.ts +17 -1
  119. package/src/activities/agent-turn/admission.ts +66 -3
  120. package/src/activities/agent-turn/agent-build.ts +84 -10
  121. package/src/activities/agent-turn/claim.ts +186 -43
  122. package/src/activities/agent-turn/claude-usage-observer.ts +221 -0
  123. package/src/activities/agent-turn/code-search.ts +275 -0
  124. package/src/activities/agent-turn/codex-capacity.ts +172 -8
  125. package/src/activities/agent-turn/codex-plan-entitlement.ts +254 -0
  126. package/src/activities/agent-turn/codex.ts +13 -5
  127. package/src/activities/agent-turn/compaction-prep.ts +170 -102
  128. package/src/activities/agent-turn/credential-leases.ts +122 -216
  129. package/src/activities/agent-turn/credential-restriction.ts +14 -0
  130. package/src/activities/agent-turn/errors.ts +647 -48
  131. package/src/activities/agent-turn/failure-settlement.ts +682 -130
  132. package/src/activities/agent-turn/final-reply.ts +46 -0
  133. package/src/activities/agent-turn/finalization-monitor.ts +120 -0
  134. package/src/activities/agent-turn/finalization.ts +146 -43
  135. package/src/activities/agent-turn/github-repository-bindings.ts +3 -1
  136. package/src/activities/agent-turn/governance-model.ts +69 -28
  137. package/src/activities/agent-turn/history-sink.ts +16 -2
  138. package/src/activities/agent-turn/history.ts +38 -11
  139. package/src/activities/agent-turn/input-wait-reply.ts +103 -0
  140. package/src/activities/agent-turn/knowledge-source-tools.ts +2 -0
  141. package/src/activities/agent-turn/media-artifacts.ts +2 -1
  142. package/src/activities/agent-turn/model-call-admission.ts +94 -0
  143. package/src/activities/agent-turn/model-usage.ts +64 -3
  144. package/src/activities/agent-turn/model-wire-dispatch.ts +27 -0
  145. package/src/activities/agent-turn/optional-repositories.ts +224 -0
  146. package/src/activities/agent-turn/provider-dispatch-barrier.ts +22 -0
  147. package/src/activities/agent-turn/quiescence.ts +10 -7
  148. package/src/activities/agent-turn/recovery-warning.ts +16 -0
  149. package/src/activities/agent-turn/refresh-credentials.ts +44 -0
  150. package/src/activities/agent-turn/run-credentials.ts +116 -55
  151. package/src/activities/agent-turn/run.ts +320 -93
  152. package/src/activities/agent-turn/sandbox-establish.ts +84 -8
  153. package/src/activities/agent-turn/sandbox-provision.ts +3 -1
  154. package/src/activities/agent-turn/sandbox-route.ts +4 -21
  155. package/src/activities/agent-turn/sandbox-runtime.ts +343 -18
  156. package/src/activities/agent-turn/session-title.ts +81 -5
  157. package/src/activities/agent-turn/skill-checkout.ts +111 -24
  158. package/src/activities/agent-turn/skill-install.ts +1 -1
  159. package/src/activities/agent-turn/skill-read.ts +374 -28
  160. package/src/activities/agent-turn/skill-remove.ts +46 -0
  161. package/src/activities/agent-turn/skill-save.ts +1 -1
  162. package/src/activities/agent-turn/skill-search.ts +10 -1
  163. package/src/activities/agent-turn/skill-selection.ts +4 -0
  164. package/src/activities/agent-turn/skill-tools.ts +112 -18
  165. package/src/activities/agent-turn/skill-transfer.ts +68 -23
  166. package/src/activities/agent-turn/stream-attempt.ts +313 -77
  167. package/src/activities/agent-turn/subscription-lease.ts +115 -0
  168. package/src/activities/agent-turn/tool-environment.ts +316 -167
  169. package/src/activities/agent-turn/tool-policy.ts +80 -1
  170. package/src/activities/agent-turn/turn-context.ts +35 -0
  171. package/src/activities/agent-turn/turn-sandbox-access.ts +7 -1
  172. package/src/activities/agent-turn/xai-capacity.ts +94 -51
  173. package/src/activities/automations.ts +76 -4
  174. package/src/activities/browser-deadline-checkpoint.ts +279 -0
  175. package/src/activities/capabilities.ts +108 -11
  176. package/src/activities/codemode-dispatcher.ts +36 -8
  177. package/src/activities/codex-capacity.ts +60 -25
  178. package/src/activities/codex-rotation.ts +39 -17
  179. package/src/activities/context-compaction.ts +75 -18
  180. package/src/activities/gmail-files.ts +88 -0
  181. package/src/activities/goals.ts +116 -121
  182. package/src/activities/google-drive-publication.ts +1 -3
  183. package/src/activities/image-generation-operation.ts +1 -1
  184. package/src/activities/knowledge-indexing.ts +269 -15
  185. package/src/activities/knowledge-source-sync.ts +10 -0
  186. package/src/activities/mcp-account-routes.ts +17 -0
  187. package/src/activities/mcp-credentials.ts +83 -194
  188. package/src/activities/mcp-operation-authority.ts +16 -41
  189. package/src/activities/model-call-fact-reconciler.ts +112 -0
  190. package/src/activities/open-suffix-resume.ts +15 -2
  191. package/src/activities/parent-wake.ts +46 -21
  192. package/src/activities/retained-screenshots.ts +82 -11
  193. package/src/activities/rig-verification.ts +38 -37
  194. package/src/activities/run-credential-renewal.ts +13 -1
  195. package/src/activities/run-credentials.ts +59 -17
  196. package/src/activities/run-input.ts +25 -16
  197. package/src/activities/sandbox-images.ts +0 -1
  198. package/src/activities/sandbox-lease.ts +798 -82
  199. package/src/activities/scheduled-tasks.ts +550 -178
  200. package/src/activities/session-state.ts +245 -6
  201. package/src/activities/site-auth-maintenance.ts +3 -0
  202. package/src/activities/types.ts +72 -5
  203. package/src/activities/workflow-wake.ts +2 -17
  204. package/src/activities/workspace-capture.ts +13 -2
  205. package/src/activities/workspace-credential-provider.ts +283 -0
  206. package/src/activities-control.ts +4 -0
  207. package/src/activities-turn.ts +5 -0
  208. package/src/activities.ts +13 -0
  209. package/src/activity-services.ts +16 -4
  210. package/src/browser-deadline-checkpoint-contract.ts +5 -0
  211. package/src/editable-artifact-hint-broker.ts +3 -0
  212. package/src/editable-artifact-materializer-service.ts +7 -3
  213. package/src/editable-artifact-outbox-service.ts +4 -4
  214. package/src/github-rest-mcp.ts +1 -2
  215. package/src/host-export-pump.ts +26 -4
  216. package/src/host-export.ts +3 -0
  217. package/src/http.ts +4 -2
  218. package/src/index.ts +99 -37
  219. package/src/observability-metrics.ts +510 -5
  220. package/src/personal-github-git-credentials.ts +2 -1
  221. package/src/pr-review-credentials.ts +1 -3
  222. package/src/retained-process-diagnostics.ts +50 -0
  223. package/src/retained-process-retry.ts +36 -0
  224. package/src/sandbox-resume.ts +388 -101
  225. package/src/sandbox-routing.ts +150 -25
  226. package/src/sandbox-snapshot-diagnostics.ts +112 -0
  227. package/src/session-event-fanout.ts +23 -0
  228. package/src/warm-capture-holder.ts +15 -0
  229. package/src/worker-service-lifecycle.ts +53 -0
  230. package/src/workflows/activities.ts +16 -1
  231. package/src/workflows/browser-deadline-checkpoint.ts +50 -0
  232. package/src/workflows/file-upload-reaper.ts +2 -0
  233. package/src/workflows/scheduled-tasks.ts +26 -13
  234. package/src/workflows/session.ts +242 -22
  235. package/src/workflows.ts +4 -0
  236. package/dist/activities/agent-turn/knowledge-sources.d.ts +0 -20
  237. package/dist/activities/packs.d.ts +0 -55
  238. package/dist/activities-control-HMFGSKC5.js.map +0 -1
  239. package/dist/activities-turn-AP67JADS.js.map +0 -1
  240. package/dist/chunk-A4XQWVZK.js.map +0 -1
  241. package/dist/chunk-CYITU5UH.js.map +0 -1
  242. package/dist/chunk-RAMNYSAW.js.map +0 -1
  243. package/src/activities/agent-turn/knowledge-sources.ts +0 -86
  244. package/src/activities/packs.ts +0 -166
@@ -1,6 +1,7 @@
1
1
  import { createKnowledgeSourceAttemptTools } from "./knowledge-source-tools";
2
- import { getWorkspaceConnectionModelRestrictions } from "@opengeni/db";
3
2
  import {
3
+ resolveInitiatingHuman,
4
+ buildSlackApiRateLimiter,
4
5
  beginConnectorActionExecution,
5
6
  getExternalLinkTurnAuthorization,
6
7
  getSessionTurnForAttempt,
@@ -8,29 +9,25 @@ import {
8
9
  listSkillDescriptors,
9
10
  completeConnectorActionExecution,
10
11
  getScheduledVariableSetExpectedGenerationForAttempt,
11
- getWorkspaceModelPolicy,
12
- listWorkspaceGatewayCustomModels,
13
- listWorkspaceOpenRouterCustomModels,
14
- listOrganizationModelProviderCustomModelsForWorkspace,
15
- organizationModelProviderConnectionActiveForWorkspace,
16
12
  persistAttemptToolCatalog,
17
13
  prepareConnectorActionApproval,
14
+ recordUsageEvent,
18
15
  previewConnectorActionApproval,
19
16
  namedSubjectHasLiveWorkspaceAuthority,
20
17
  updateSessionTitleWithEvent,
21
18
  withCodexAppsRequestAuthorization,
22
- workspaceCodexSubscriptionActive,
23
- workspaceVercelAiGatewayConnectionActive,
24
- workspaceOpenRouterConnectionActive,
25
- workspaceXaiSubscriptionActiveForAuthority,
26
19
  } from "@opengeni/db";
27
20
  import { publishDurableSessionEvents } from "@opengeni/events";
28
21
  import {
29
22
  type OpenGeniRuntime,
23
+ type RunMcpCredentials,
24
+ selectedSessionRemoteMcpTargets,
30
25
  type AttemptConnectorActionBinding,
31
26
  type ConnectorAttachmentMaterializationRequest,
32
27
  type ConnectorActionPolicyHooks,
33
28
  createFirstPartyInteractionAttemptToolDefinitions,
29
+ mcpToolDisplayMetadata,
30
+ toolFamilyForCatalogIdentity,
34
31
  } from "@opengeni/runtime";
35
32
  import {
36
33
  createGoogleDrivePublicationAttemptTool,
@@ -38,6 +35,11 @@ import {
38
35
  resolveGoogleDrivePublicationTarget,
39
36
  } from "../google-drive-publication";
40
37
  import { connectionTokenResolverForTurn } from "../mcp-credentials";
38
+ import {
39
+ accountRouteAuthNeededPayload,
40
+ expandApiIntegrationAccountRoutes,
41
+ expandMcpAccountRoutes,
42
+ } from "../mcp-account-routes";
41
43
  import { createMcpOperationPersistence } from "@opengeni/db/mcp-operations";
42
44
  import { createMcpOperationReadStore } from "../mcp-operation-store";
43
45
  import { createMcpOperationObserverResolver } from "../mcp-operation-observer";
@@ -45,40 +47,49 @@ import { readMcpOperation } from "../mcp-operation-reader";
45
47
  import { createOperationReadAttemptToolDefinition } from "./mcp-operation-read-tool";
46
48
  import { buildGitHubRestMcpForTurn } from "../../github-rest-mcp";
47
49
  import { materializeConnectorAttachmentsInChannel } from "../connector-attachments";
50
+ import { materializeGmailFile, readGmailFileFromChannel } from "../gmail-files";
51
+ import { objectStorageForSandboxDownloads } from "./file-resources";
48
52
  import { allowedFirstPartyMcpToolsForSession, type Settings } from "@opengeni/config";
49
53
  import { CodemodeAttemptDispatcher } from "../codemode-dispatcher";
50
54
  import { buildCodexTokenResolver } from "../codex-auth";
51
55
  import { CODEX_CLIENT_VERSION } from "@opengeni/codex";
52
56
  import { mergeResourceRefs } from "../common";
53
57
  import {
54
- defaultSessionMcpServerIds,
58
+ workspaceSessionToolPolicyDefaultServerIds,
55
59
  loadRigDefaultVariableSetEnvironment,
56
60
  mergeRigDefaultVariableSetEnvironment,
57
61
  buildApiIntegrationMcpServers,
58
62
  resolveCatalogSettings,
59
63
  resolveWorkspaceModelSelection,
64
+ loadWorkspaceModelSelectionInput,
60
65
  withFrozenPersonalConnectionDelegations,
61
- resolveSessionToolPolicy,
66
+ resolveTurnToolPolicy,
67
+ scheduledTurnMcpServerIds,
62
68
  hasPermission,
69
+ requireExplicitPermissionDelegation,
63
70
  } from "@opengeni/core";
64
71
  import { loadWorkspaceEnvironmentForRunWithCredentials } from "../environment";
65
72
  import { withFirstPartyTools } from "../goals";
66
73
  import type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from "../types";
67
- import { recordTurnStartupPhase } from "../../observability-metrics";
74
+ import {
75
+ recordSkillCheckout,
76
+ recordSkillRead,
77
+ recordToolPreparationPhase,
78
+ recordTurnStartupPhase,
79
+ } from "../../observability-metrics";
68
80
  import { ToolResultSpill } from "./tool-result-spill";
69
81
  import { createTurnMediaArtifacts } from "./media-artifacts";
70
82
  import { SandboxChannelAService } from "@opengeni/runtime/sandbox";
71
83
  import { sandboxRunAs } from "@opengeni/runtime";
72
84
  import {
73
85
  DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,
86
+ resolveAgentToolFamilies,
87
+ type ResourceRef,
88
+ type Permission,
74
89
  type ToolAuthNeededPayload,
75
90
  } from "@opengeni/contracts";
76
91
 
77
- import {
78
- rollingSafeToolAuthNeededPayload,
79
- shouldPublishToolAuthNeededForTurn,
80
- xaiCatalogReadinessAuthority,
81
- } from "./admission";
92
+ import { rollingSafeToolAuthNeededPayload, shouldPublishToolAuthNeededForTurn } from "./admission";
82
93
  import { unavailableMcpOperationalContext } from "./errors";
83
94
  import { runtimeResourcesForTurn } from "./file-resources";
84
95
  import { waitForTurnOperation } from "./sandbox-provision";
@@ -90,20 +101,37 @@ import type { sandboxArtifactRuntimeAdmission } from "./sandbox-route";
90
101
  import type {
91
102
  AttemptIdentityState,
92
103
  EventingState,
104
+ RenewalState,
93
105
  SandboxRuntimeState,
94
106
  WorkspaceRefState,
95
107
  } from "./turn-context";
96
108
  import {
97
109
  createSessionTitleAttemptToolDefinition,
110
+ routeAllowsSessionTitleRequests,
98
111
  sessionTitleToolPlan,
99
112
  shouldRequestMissingSessionTitle,
100
113
  } from "./session-title";
101
114
  import { resolveTurnSandboxAccess } from "./turn-sandbox-access";
102
115
  import { createListModelsAttemptToolDefinition } from "./list-models";
116
+ import { createRefreshCredentialsAttemptToolDefinition } from "./refresh-credentials";
117
+ import { codeSearchToolDefinitions, codeSearchWorkspaceFromChannel } from "./code-search";
103
118
  import { createWorkspaceSkillTools } from "./skill-tools";
104
119
  import { loadConfiguredBundledSkills } from "./skill-selection";
105
120
  import { guardSkillFilesystem } from "./skill-transfer";
106
- import type { RuntimeSkillActivation } from "@opengeni/runtime";
121
+ import { turnCredentialRestriction } from "./credential-restriction";
122
+
123
+ /** A linked turn's immutable policy must survive array and token boundaries. */
124
+ export function linkedTurnFirstPartyPermissions(
125
+ selected: Permission[] | null,
126
+ linked: { permissions: Permission[]; permissionMode?: "legacy" | "explicit" } | null,
127
+ ): Permission[] | null {
128
+ if (!linked) return selected;
129
+ const permissions = (selected ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS).filter((permission) =>
130
+ hasPermission(linked.permissions, permission, linked.permissionMode),
131
+ );
132
+ requireExplicitPermissionDelegation(linked, permissions);
133
+ return permissions;
134
+ }
107
135
 
108
136
  export type PrepareTurnToolPolicyDeps = {
109
137
  input: RunAgentTurnInput;
@@ -125,7 +153,6 @@ export type PrepareTurnToolRuntimeDeps = {
125
153
  input: import("../types").RunKnowledgeSourceSyncBatchInput,
126
154
  ) => Promise<import("../types").RunKnowledgeSourceSyncBatchResult>)
127
155
  | undefined;
128
- selectedSkillActivations: readonly RuntimeSkillActivation[];
129
156
  input: RunAgentTurnInput;
130
157
  catalogSourceSettings: Settings;
131
158
  db: ActivityServices["db"];
@@ -134,7 +161,6 @@ export type PrepareTurnToolRuntimeDeps = {
134
161
  objectStorage: ActivityServices["objectStorage"];
135
162
  observability: ActivityServices["observability"];
136
163
  cancellationSignal: AbortSignal | undefined;
137
- connectionCredentials: ActivityServices["connectionCredentials"];
138
164
  eventing: EventingState;
139
165
  attempt: AttemptIdentityState;
140
166
  sandboxState: SandboxRuntimeState;
@@ -149,10 +175,10 @@ export type PrepareTurnToolRuntimeDeps = {
149
175
  turnExecutionPolicy: ClaimTurnOk["turnExecutionPolicy"];
150
176
  trigger: ClaimTurnOk["trigger"];
151
177
  runSettings: GovernanceModelOk["runSettings"];
178
+ resolvedModel: GovernanceModelOk["resolvedModel"];
152
179
  lazyToolTransport: GovernanceModelOk["lazyToolTransport"];
153
180
  turnTools: ReturnType<typeof withFirstPartyTools>;
154
181
  connectionScope: { accountId: string; workspaceId: string };
155
- hostCredentialRootSessionId: string | null;
156
182
  sandboxArtifactRuntime: ReturnType<typeof sandboxArtifactRuntimeAdmission>;
157
183
  activeSandboxBackend: Settings["sandboxBackend"] | undefined;
158
184
  groupBoxBackend: Settings["sandboxBackend"];
@@ -161,8 +187,18 @@ export type PrepareTurnToolRuntimeDeps = {
161
187
  credentialSubjectId: ClaimTurnOk["credentialSubjectId"];
162
188
  interactionInterventionResume: ClaimTurnOk["interactionInterventionResume"];
163
189
  runWorkspaceMutationForSandbox: SandboxTurnRuntime["runWorkspaceMutationForSandbox"];
190
+ /** Deployment and workspace allow the Jev-backed code_search tool. */
191
+ codeSearchEnabled: boolean;
192
+ /**
193
+ * False for an optional repository that sits this turn out after losing
194
+ * access (dropUnavailableOptionalRepositories), so no tool surface offers it.
195
+ */
196
+ retainsOptionalRepository?: (resource: ResourceRef) => boolean;
164
197
  throwIfWorkerShuttingDown: () => void;
165
198
  throwIfTurnCancelled: () => void;
199
+ /** Present when this turn resolves host-managed run credentials. */
200
+ runCredentialRenewals?: RenewalState | undefined;
201
+ runMcpCredentials?: RunMcpCredentials;
166
202
  };
167
203
 
168
204
  export async function prepareTurnToolPolicy(deps: PrepareTurnToolPolicyDeps) {
@@ -195,30 +231,36 @@ export async function prepareTurnToolPolicy(deps: PrepareTurnToolPolicyDeps) {
195
231
  // sessions follow the current configured MCP set,
196
232
  // while explicit, inherited-fixed, and legacy sessions remain narrowed
197
233
  // to their stored materialized allow-list.
198
- const scheduledEffectiveMcpServerIds = (() => {
199
- const value =
200
- turn.metadata && typeof turn.metadata === "object" && !Array.isArray(turn.metadata)
201
- ? (turn.metadata as Record<string, unknown>).scheduledEffectiveMcpServerIds
202
- : null;
203
- return Array.isArray(value) && value.every((id) => typeof id === "string")
204
- ? [...new Set(value)].sort()
205
- : null;
206
- })();
207
- const currentMcpServerIds = new Set(runSettings.mcpServers.map((server) => server.id));
208
- const resolvedToolPolicy = resolveSessionToolPolicy({
234
+ const resolvedToolPolicy = resolveTurnToolPolicy({
209
235
  toolPolicy: session.toolPolicy,
210
- sessionTools: scheduledEffectiveMcpServerIds ? turn.tools : session.tools,
211
- availableMcpServerIds: scheduledEffectiveMcpServerIds
212
- ? scheduledEffectiveMcpServerIds.filter((id) => currentMcpServerIds.has(id))
213
- : [...currentMcpServerIds],
236
+ session,
237
+ turn,
238
+ availableMcpServerIds: runSettings.mcpServers.map((server) => server.id),
214
239
  defaultMcpServerIds:
215
- scheduledEffectiveMcpServerIds ?? defaultSessionMcpServerIds(capabilitySettings.mcpServers),
240
+ scheduledTurnMcpServerIds(turn) === null && session.toolPolicy.mode === "workspace_default"
241
+ ? await workspaceSessionToolPolicyDefaultServerIds(
242
+ db,
243
+ input.workspaceId,
244
+ capabilitySettings,
245
+ fileAuthoritySubjectId ?? undefined,
246
+ )
247
+ : [],
216
248
  });
217
249
  const mcpAvailabilityNote = unavailableMcpOperationalContext({
218
250
  droppedIds: resolvedToolPolicy.effectivePolicy.droppedIds,
219
251
  droppedCount: resolvedToolPolicy.effectivePolicy.counts.dropped,
220
252
  });
221
- const effectivePolicyTools = resolvedToolPolicy.toolRefs;
253
+ const families = resolveAgentToolFamilies(session.agent, {
254
+ productServerIds: new Set([
255
+ ...session.mcpServers.map((server) => server.id),
256
+ ...(session.toolPolicy.mode !== "workspace_default"
257
+ ? session.tools.map((tool) => tool.id)
258
+ : []),
259
+ ]),
260
+ });
261
+ const effectivePolicyTools = resolvedToolPolicy.toolRefs.filter(
262
+ (tool) => tool.kind !== "mcp" || families.allowsMcpServer(tool.id),
263
+ );
222
264
  const turnTools = withFirstPartyTools(runSettings, effectivePolicyTools);
223
265
  // §7.6 connection-credential provider — load (and decrypt) selected Variable Sets via the
224
266
  // host `sandboxSecrets` provider when bound; unset → today's local decrypt. Preserve the
@@ -349,7 +391,6 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
349
391
  objectStorage,
350
392
  observability,
351
393
  cancellationSignal,
352
- connectionCredentials,
353
394
  eventing,
354
395
  attempt,
355
396
  sandboxState,
@@ -361,10 +402,10 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
361
402
  codexAppsCredentialId,
362
403
  turnExecutionPolicy,
363
404
  trigger,
364
- runSettings,
405
+ runSettings: canonicalRunSettings,
406
+ resolvedModel,
365
407
  lazyToolTransport,
366
- turnTools,
367
- hostCredentialRootSessionId,
408
+ turnTools: canonicalTurnTools,
368
409
  sandboxArtifactRuntime,
369
410
  activeSandboxBackend,
370
411
  groupBoxBackend,
@@ -373,30 +414,36 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
373
414
  credentialSubjectId,
374
415
  interactionInterventionResume,
375
416
  runWorkspaceMutationForSandbox,
417
+ codeSearchEnabled,
418
+ retainsOptionalRepository,
376
419
  throwIfWorkerShuttingDown,
377
420
  throwIfTurnCancelled,
378
421
  } = deps;
379
422
 
423
+ const accountRoutes = expandMcpAccountRoutes({
424
+ settings: canonicalRunSettings,
425
+ tools: canonicalTurnTools,
426
+ bindings: turn.mcpAccountBindings,
427
+ });
428
+ const runSettings = accountRoutes.settings;
429
+ const turnTools = accountRoutes.tools;
430
+ const credentialRestriction = turnCredentialRestriction(turnExecutionPolicy, session.metadata);
380
431
  const toolContextPreparationStartedAt = performance.now();
381
432
  throwIfWorkerShuttingDown();
382
433
  throwIfTurnCancelled();
383
- const mcpCredentialRootSessionId =
384
- connectionCredentials?.mcpCredentials && hostCredentialRootSessionId
385
- ? hostCredentialRootSessionId
386
- : input.sessionId;
387
434
  // Connection credentials and the optional Apps credential are resolved
388
435
  // independently. Inference auth is never an Apps fallback.
389
436
  const rawResolveCredential = connectionTokenResolverForTurn({
390
437
  db,
391
438
  settings: runSettings,
392
- connectionCredentials: connectionCredentials ?? null,
439
+ canonicalMcpServerIds: canonicalRunSettings.mcpServers
440
+ .filter((server) => server.connectionRef)
441
+ .map((server) => server.id),
393
442
  accountId: input.accountId,
394
443
  workspaceId: input.workspaceId,
395
444
  sessionId: input.sessionId,
396
- rootSessionId: mcpCredentialRootSessionId,
397
445
  attemptId: input.attemptId,
398
446
  turn,
399
- observability,
400
447
  });
401
448
  const personalConnectionDelegations = turn.personalConnectionDelegations;
402
449
  const delegatedMembershipChecks = new Map<string, Promise<boolean>>();
@@ -463,16 +510,24 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
463
510
  return;
464
511
  }
465
512
  await eventing.publish!(
466
- [{ type: "tool.auth_needed", payload: rollingSafeToolAuthNeededPayload(payload) }],
513
+ [
514
+ {
515
+ type: "tool.auth_needed",
516
+ payload: rollingSafeToolAuthNeededPayload(
517
+ accountRouteAuthNeededPayload(payload, turn.mcpAccountBindings),
518
+ ),
519
+ },
520
+ ],
467
521
  true,
468
522
  );
469
523
  };
470
- const selectedApiIntegrationServerIds = new Set(turnTools.map((tool) => tool.id));
471
524
  const apiIntegrationMcpServers = buildApiIntegrationMcpServers({
472
525
  settings: runSettings,
473
- integrations: installedApiIntegrations.filter((integration) =>
474
- selectedApiIntegrationServerIds.has(integration.serverId),
475
- ),
526
+ integrations: expandApiIntegrationAccountRoutes({
527
+ integrations: installedApiIntegrations,
528
+ bindings: turn.mcpAccountBindings,
529
+ tools: turnTools,
530
+ }),
476
531
  authority: {
477
532
  accountId: input.accountId,
478
533
  workspaceId: input.workspaceId,
@@ -493,7 +548,9 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
493
548
  sessionId: input.sessionId,
494
549
  attemptId: input.attemptId,
495
550
  turn,
496
- resources: mergeResourceRefs(session.resources, turn.resources),
551
+ resources: mergeResourceRefs(session.resources, turn.resources).filter(
552
+ (resource) => retainsOptionalRepository?.(resource) ?? true,
553
+ ),
497
554
  tools: turnTools,
498
555
  resolveCredential,
499
556
  });
@@ -535,25 +592,27 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
535
592
  );
536
593
  if (linkedAuthority && !linkedAuthority.authorized)
537
594
  throw new Error("Native identity link was revoked");
538
- const effectiveFirstPartyPermissions = linkedAuthority
539
- ? (session.firstPartyMcpPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS).filter(
540
- (permission) => hasPermission(linkedAuthority.permissions, permission),
541
- )
542
- : session.firstPartyMcpPermissions;
543
- const selectedFirstPartyMcpTools = allowedFirstPartyMcpToolsForSession(
544
- runSettings,
545
- session.firstPartyMcpTools,
595
+ const effectiveFirstPartyPermissions = linkedTurnFirstPartyPermissions(
596
+ session.firstPartyMcpPermissions,
597
+ linkedAuthority,
598
+ );
599
+ const toolFamilies = resolveAgentToolFamilies(session.agent);
600
+ const selectedFirstPartyMcpTools = toolFamilies.firstPartyTools(
601
+ allowedFirstPartyMcpToolsForSession(runSettings, session.firstPartyMcpTools),
546
602
  );
547
603
  const titleToolPlan = sessionTitleToolPlan({
604
+ agentConfig: session.agent,
548
605
  tools: turnTools,
549
606
  selectedFirstPartyMcpTools,
550
607
  shouldRequestTitle: shouldRequestMissingSessionTitle({
608
+ agentConfig: session.agent,
551
609
  title: session.title,
552
610
  titleSource: session.titleSource,
553
611
  firstPartyMcpTools: selectedFirstPartyMcpTools,
554
612
  firstPartyMcpPermissions: effectiveFirstPartyPermissions,
555
613
  }),
556
614
  parallelGenerationAvailable: typeof runtime.generateSessionTitle === "function",
615
+ routeAllowsTitleRequests: routeAllowsSessionTitleRequests(resolvedModel),
557
616
  });
558
617
  const googleDrivePublicationAllowed =
559
618
  selectedFirstPartyMcpTools.includes("editable_artifact_export") &&
@@ -599,7 +658,16 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
599
658
  outcome,
600
659
  }),
601
660
  };
602
- const skillConfiguration = await getWorkspaceVideoGenerationPolicy(db, input.workspaceId);
661
+ // Independent scoped reads after the native-link authority check. Both
662
+ // finish before assembling the Skill index or preparing executable tools.
663
+ const [skillConfiguration, sharedSkillDescriptors] = await Promise.all([
664
+ getWorkspaceVideoGenerationPolicy(db, input.workspaceId),
665
+ listSkillDescriptors(db, {
666
+ accountId: input.accountId,
667
+ workspaceId: input.workspaceId,
668
+ ...(deps.fileAuthoritySubjectId ? { subjectId: deps.fileAuthoritySubjectId } : {}),
669
+ }),
670
+ ]);
603
671
  const bundledSkills = loadConfiguredBundledSkills({
604
672
  bundledSkillIds: session.bundledSkillIds,
605
673
  firstPartyTools: selectedFirstPartyMcpTools,
@@ -608,31 +676,28 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
608
676
  });
609
677
  const selectedSkills = [
610
678
  ...bundledSkills,
611
- ...deps.selectedSkillActivations.map((entry) => ({ id: entry.id, artifact: entry.artifact })),
612
679
  ...session.skills.map((skill) => ({
613
680
  id: `session:${session.id}:${skill.name}`,
614
681
  artifact: skill,
615
682
  })),
616
683
  ];
617
- const sharedSkillDescriptors = await listSkillDescriptors(db, {
618
- accountId: input.accountId,
619
- workspaceId: input.workspaceId,
620
- ...(deps.fileAuthoritySubjectId ? { subjectId: deps.fileAuthoritySubjectId } : {}),
621
- });
622
- const skillCatalog = [
623
- ...sharedSkillDescriptors
624
- .filter((entry) => entry.activationMode === "workspace_managed")
625
- .map((entry) => ({
626
- id: entry.id,
627
- name: entry.title,
628
- description: entry.description,
629
- })),
630
- ...selectedSkills.map((entry) => ({
631
- id: entry.id,
632
- name: entry.artifact.name,
633
- description: entry.artifact.description || entry.artifact.name,
634
- })),
635
- ];
684
+ const skillCatalog =
685
+ toolFamilies.skills === false
686
+ ? []
687
+ : [
688
+ ...sharedSkillDescriptors
689
+ .filter((entry) => entry.activationMode === "workspace_managed")
690
+ .map((entry) => ({
691
+ id: entry.id,
692
+ name: entry.title,
693
+ description: entry.description,
694
+ })),
695
+ ...selectedSkills.map((entry) => ({
696
+ id: entry.id,
697
+ name: entry.artifact.name,
698
+ description: entry.artifact.description || entry.artifact.name,
699
+ })),
700
+ ];
636
701
  const skillTools = createWorkspaceSkillTools({
637
702
  db,
638
703
  settings: runSettings,
@@ -647,6 +712,19 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
647
712
  executionGeneration: attempt.executionGeneration,
648
713
  },
649
714
  selected: selectedSkills,
715
+ modelToolOutputTruncationTokens: () =>
716
+ eventing.modelRunSettings.modelToolOutputTruncationTokens,
717
+ onSkillReadHistoryLookupFailed: () =>
718
+ observability.warn("skill_read history lookup failed; returning the full Skill text", {
719
+ errorCode: "skill_read_history_lookup_failed",
720
+ origin: "worker",
721
+ }),
722
+ skillReadTelemetry: {
723
+ // Set once agent build freezes this turn's model-visible Skill index.
724
+ indexedSkillIds: () => eventing.modelVisibleSkillIds,
725
+ observe: (observation) => recordSkillRead(observability, observation),
726
+ },
727
+ observeSkillCheckout: (observation) => recordSkillCheckout(observability, observation),
650
728
  filesystem: async () => {
651
729
  throwIfWorkerShuttingDown();
652
730
  throwIfTurnCancelled();
@@ -744,6 +822,63 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
744
822
  return ((await prepared.ready) ?? prepared).attemptToolEnvironment;
745
823
  },
746
824
  });
825
+ const codeSearchTools = codeSearchToolDefinitions({
826
+ enabled: codeSearchEnabled,
827
+ settings: runSettings,
828
+ backend: activeSandboxBackend ?? groupBoxBackend,
829
+ machineWorkspaceRoot: sandboxState.machinePrimarySession?.workspaceRoot ?? null,
830
+ observability,
831
+ // OpenGeni's Jev key pays for these calls whatever model billing the
832
+ // workspace uses; record them per workspace so the cost stays visible.
833
+ recordUsage: async (usage) => {
834
+ const shared = {
835
+ accountId: input.accountId,
836
+ workspaceId: input.workspaceId,
837
+ sourceResourceType: "code_search",
838
+ sourceResourceId: usage.operationId,
839
+ sessionId: input.sessionId,
840
+ turnId: turn.id,
841
+ turnAttemptId: input.attemptId,
842
+ };
843
+ await recordUsageEvent(db, {
844
+ ...shared,
845
+ eventType: "code_search.jev_input_tokens",
846
+ quantity: usage.jevInputTokens,
847
+ unit: "tokens",
848
+ idempotencyKey: `usage:code_search.jev_input_tokens:${input.attemptId}:${usage.operationId}`,
849
+ });
850
+ await recordUsageEvent(db, {
851
+ ...shared,
852
+ eventType: "code_search.jev_cost",
853
+ quantity: Math.round(usage.jevCostUsd * 1_000_000),
854
+ unit: "usd_micros",
855
+ idempotencyKey: `usage:code_search.jev_cost:${input.attemptId}:${usage.operationId}`,
856
+ });
857
+ },
858
+ workspace: async () => {
859
+ throwIfWorkerShuttingDown();
860
+ throwIfTurnCancelled();
861
+ const access = await resolveTurnSandboxAccess(
862
+ sandboxState,
863
+ media.sdkOwnedSandboxSession,
864
+ "code_search requires a sandbox or Connected Machine.",
865
+ );
866
+ const machineRoot = sandboxState.machinePrimarySession?.workspaceRoot;
867
+ const runAs = sandboxRunAs(runSettings);
868
+ return codeSearchWorkspaceFromChannel(
869
+ new SandboxChannelAService({
870
+ session: access.session,
871
+ workspaceRoot: machineRoot ?? "/workspace",
872
+ ...(machineRoot ? { providerPathMode: "workspace-relative" as const } : {}),
873
+ leaseEpoch: access.leaseEpoch,
874
+ ...(runAs ? { runAs } : {}),
875
+ }),
876
+ );
877
+ },
878
+ });
879
+ const attemptToolFamilies = resolveAgentToolFamilies(session.agent, {
880
+ hasSkills: skillCatalog.length > 0,
881
+ });
747
882
  const attemptToolDefinitions = [
748
883
  ...(operationReadStore
749
884
  ? [
@@ -758,87 +893,34 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
758
893
  : []),
759
894
  ...skillTools,
760
895
  ...sourceTools,
896
+ ...(deps.runCredentialRenewals
897
+ ? [
898
+ createRefreshCredentialsAttemptToolDefinition({
899
+ refresh: async () => {
900
+ const renewals = deps.runCredentialRenewals!;
901
+ const controller = renewals.runCredentialRenewal;
902
+ if (!controller) return "not_provisioned";
903
+ renewals.runCredentialRenewalOutcome = null;
904
+ await controller.refreshNow();
905
+ return renewals.runCredentialRenewalOutcome ?? "completed";
906
+ },
907
+ }),
908
+ ]
909
+ : []),
761
910
  createListModelsAttemptToolDefinition({
762
911
  currentModelId: turnExecutionPolicy.productModelId,
763
912
  load: async () => {
764
913
  const currentCatalog = await resolveCatalogSettings(db, catalogSourceSettings);
765
914
  const currentSettings = currentCatalog.settings;
766
- const xaiReadinessAuthority = xaiCatalogReadinessAuthority(turn, credentialSubjectId);
767
- const [
768
- connectionModelRestrictions,
769
- policy,
770
- codexSubscriptionActive,
771
- xaiSubscriptionActive,
772
- workspaceGatewayConnectionActive,
773
- workspaceGatewayCustomModels,
774
- openRouterConnectionActive,
775
- workspaceOpenRouterCustomModels,
776
- organizationGatewayConnectionActive,
777
- organizationGatewayCustomModels,
778
- organizationOpenRouterConnectionActive,
779
- organizationOpenRouterCustomModels,
780
- ] = await Promise.all([
781
- getWorkspaceConnectionModelRestrictions(
782
- db,
783
- input.workspaceId,
784
- xaiReadinessAuthority?.subjectId ?? credentialSubjectId ?? "worker:model-access",
785
- xaiReadinessAuthority?.authoritySnapshot,
786
- ),
787
- getWorkspaceModelPolicy(db, input.workspaceId),
788
- workspaceCodexSubscriptionActive(db, currentSettings, input.workspaceId),
789
- xaiReadinessAuthority && currentSettings.supergrokSubscriptionEnabled
790
- ? workspaceXaiSubscriptionActiveForAuthority(db, currentSettings, {
791
- workspaceId: input.workspaceId,
792
- ...xaiReadinessAuthority,
793
- })
794
- : false,
795
- workspaceVercelAiGatewayConnectionActive(db, input.workspaceId),
796
- listWorkspaceGatewayCustomModels(db, {
797
- accountId: input.accountId,
798
- workspaceId: input.workspaceId,
799
- }),
800
- workspaceOpenRouterConnectionActive(db, input.workspaceId),
801
- listWorkspaceOpenRouterCustomModels(db, {
802
- accountId: input.accountId,
803
- workspaceId: input.workspaceId,
804
- }),
805
- organizationModelProviderConnectionActiveForWorkspace(db, {
806
- accountId: input.accountId,
807
- workspaceId: input.workspaceId,
808
- providerKind: "vercel_gateway",
809
- }),
810
- listOrganizationModelProviderCustomModelsForWorkspace(db, {
811
- accountId: input.accountId,
812
- workspaceId: input.workspaceId,
813
- providerKind: "vercel_gateway",
814
- }),
815
- organizationModelProviderConnectionActiveForWorkspace(db, {
816
- accountId: input.accountId,
817
- workspaceId: input.workspaceId,
818
- providerKind: "openrouter",
819
- }),
820
- listOrganizationModelProviderCustomModelsForWorkspace(db, {
821
- accountId: input.accountId,
822
- workspaceId: input.workspaceId,
823
- providerKind: "openrouter",
824
- }),
825
- ]);
915
+ const selectionInput = await loadWorkspaceModelSelectionInput(db, currentSettings, {
916
+ accountId: input.accountId,
917
+ workspaceId: input.workspaceId,
918
+ subjectId: turn.initiatingHumanSubjectId ?? credentialSubjectId ?? "worker:model-access",
919
+ xaiAuthoritySnapshot: turn.xaiProviderAccountAuthoritySnapshot,
920
+ claudeAuthoritySnapshot: turn.claudeProviderAccountAuthoritySnapshot,
921
+ });
826
922
  return {
827
- selections: resolveWorkspaceModelSelection({
828
- connectionModelRestrictions,
829
- settings: currentSettings,
830
- policy,
831
- codexSubscriptionActive,
832
- xaiSubscriptionActive,
833
- workspaceGatewayConnectionActive,
834
- workspaceGatewayCustomModels,
835
- workspaceOpenRouterConnectionActive: openRouterConnectionActive,
836
- workspaceOpenRouterCustomModels,
837
- organizationGatewayConnectionActive,
838
- organizationGatewayCustomModels,
839
- organizationOpenRouterConnectionActive,
840
- organizationOpenRouterCustomModels,
841
- }),
923
+ selections: resolveWorkspaceModelSelection(selectionInput),
842
924
  modelNotes: currentCatalog.modelNotes,
843
925
  };
844
926
  },
@@ -866,6 +948,7 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
866
948
  : []),
867
949
  ...createFirstPartyInteractionAttemptToolDefinitions({
868
950
  settings: runSettings,
951
+ ...(credentialRestriction ? { credentialRestriction } : {}),
869
952
  scope: {
870
953
  accountId: input.accountId,
871
954
  workspaceId: input.workspaceId,
@@ -885,7 +968,8 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
885
968
  ...(googleDrivePublicationTool && googleDrivePublicationAllowed
886
969
  ? [googleDrivePublicationTool]
887
970
  : []),
888
- ];
971
+ ...codeSearchTools,
972
+ ].filter((tool) => attemptToolFamilies.allowsFunctionTool(tool.modelName));
889
973
  recordTurnStartupPhase(observability, {
890
974
  phase: "tool_context_preparation",
891
975
  provider: turnExecutionPolicy.providerId,
@@ -924,10 +1008,12 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
924
1008
  "Connector attachment sandbox is unavailable",
925
1009
  );
926
1010
  const sandbox = sandboxAccess.sandbox;
1011
+ const machineRoot = sandboxState.machinePrimarySession?.workspaceRoot;
927
1012
  const runAs = sandboxRunAs(runSettings);
928
1013
  const channel = new SandboxChannelAService({
929
1014
  session: sandboxAccess.session,
930
- workspaceRoot: "/workspace",
1015
+ workspaceRoot: machineRoot ?? "/workspace",
1016
+ ...(machineRoot ? { providerPathMode: "workspace-relative" as const } : {}),
931
1017
  leaseEpoch: sandboxAccess.leaseEpoch,
932
1018
  emit: async (events) => {
933
1019
  await eventing.publish?.(events, true);
@@ -947,9 +1033,21 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
947
1033
  },
948
1034
  });
949
1035
  };
1036
+ const initiatingHuman = await waitForTurnOperation(
1037
+ resolveInitiatingHuman(
1038
+ db,
1039
+ deps.connectionScope,
1040
+ turn.initiatingHumanSubjectId ?? null,
1041
+ turn.id,
1042
+ ),
1043
+ cancellationSignal,
1044
+ undefined,
1045
+ );
950
1046
  try {
951
1047
  eventing.preparedTools = await waitForTurnOperation(
952
1048
  runtime.prepareTools(githubRestMcp.settings, githubRestMcp.tools, {
1049
+ ...(credentialRestriction ? { credentialRestriction } : {}),
1050
+ mcpAccountLabels: accountRoutes.accountLabels,
953
1051
  accountId: input.accountId,
954
1052
  workspaceId: input.workspaceId,
955
1053
  sessionId: input.sessionId,
@@ -962,8 +1060,18 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
962
1060
  subjectId: "worker:first-party-mcp",
963
1061
  subjectLabel: "OpenGeni worker",
964
1062
  ...(credentialSubjectId ? { credentialSubjectId } : {}),
1063
+ initiatingHumanSubjectId: turn.initiatingHumanSubjectId ?? null,
1064
+ initiatingHumanExternalIdentity: initiatingHuman?.externalIdentity ?? null,
1065
+ sessionAttachedRemoteMcpTargets: selectedSessionRemoteMcpTargets(
1066
+ githubRestMcp.settings,
1067
+ session.mcpServers ?? [],
1068
+ githubRestMcp.tools,
1069
+ localMcpServers,
1070
+ ),
1071
+ ...(deps.runMcpCredentials ? { runMcpCredentials: deps.runMcpCredentials } : {}),
965
1072
  ...(codexAppsAuth ? { codexAppsAuth } : {}),
966
1073
  resolveCredential,
1074
+ slackRateLimit: buildSlackApiRateLimiter(db, githubRestMcp.settings),
967
1075
  ...(operationPersistence ? { mcpOperationPersistence: operationPersistence } : {}),
968
1076
  ...(linkedAuthority
969
1077
  ? {
@@ -985,6 +1093,44 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
985
1093
  : {}),
986
1094
  onAuthNeeded: publishToolAuthNeeded,
987
1095
  materializeConnectorAttachments,
1096
+ materializeGmailFile: async (request) => {
1097
+ throwIfWorkerShuttingDown();
1098
+ throwIfTurnCancelled();
1099
+ if (!deps.objectStorage) throw new Error("Gmail file delivery requires object storage");
1100
+ return await materializeGmailFile(request, {
1101
+ workspaceId: input.workspaceId,
1102
+ storage: deps.objectStorage,
1103
+ downloadStorage: objectStorageForSandboxDownloads(
1104
+ runSettings,
1105
+ deps.objectStorage,
1106
+ deps.activeSandboxBackend ?? deps.groupBoxBackend,
1107
+ ),
1108
+ materialize: materializeConnectorAttachments,
1109
+ onCleanupFailure: (key) =>
1110
+ console.warn("[gmail] Temporary transfer cleanup requires operator retry", {
1111
+ objectKey: key,
1112
+ }),
1113
+ });
1114
+ },
1115
+ readGmailFile: async (request) => {
1116
+ throwIfWorkerShuttingDown();
1117
+ throwIfTurnCancelled();
1118
+ const access = await resolveTurnSandboxAccess(
1119
+ sandboxState,
1120
+ media.sdkOwnedSandboxSession,
1121
+ "Gmail attachment filesystem is unavailable",
1122
+ );
1123
+ const runAs = sandboxRunAs(runSettings);
1124
+ const machineRoot = sandboxState.machinePrimarySession?.workspaceRoot;
1125
+ const channel = new SandboxChannelAService({
1126
+ session: access.session,
1127
+ workspaceRoot: machineRoot ?? "/workspace",
1128
+ ...(machineRoot ? { providerPathMode: "workspace-relative" as const } : {}),
1129
+ leaseEpoch: access.leaseEpoch,
1130
+ ...(runAs ? { runAs } : {}),
1131
+ });
1132
+ return await readGmailFileFromChannel(channel, request);
1133
+ },
988
1134
  refreshOwnedCommand: async (commandId) => {
989
1135
  throwIfWorkerShuttingDown();
990
1136
  throwIfTurnCancelled();
@@ -1002,13 +1148,10 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
1002
1148
  localMcpServers,
1003
1149
  ...(deferNonEagerToolPreparation ? { deferNonEagerUntilToolDemand: true } : {}),
1004
1150
  onPreparationPhase: (measurement) => {
1005
- recordTurnStartupPhase(observability, {
1006
- phase: `tool_${measurement.phase}`,
1151
+ recordToolPreparationPhase(observability, {
1152
+ ...measurement,
1007
1153
  provider: turnExecutionPolicy.providerId,
1008
1154
  backend: activeSandboxBackend ?? groupBoxBackend,
1009
- outcome: measurement.outcome,
1010
- durationSeconds: measurement.durationSeconds,
1011
- count: githubRestMcp.tools.length,
1012
1155
  });
1013
1156
  },
1014
1157
  onAttemptToolCatalog: async (catalog) => {
@@ -1080,6 +1223,10 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
1080
1223
  executionGeneration: attempt.executionGeneration,
1081
1224
  },
1082
1225
  cancellationSignal,
1226
+ undefined,
1227
+ {},
1228
+ (name) => mcpToolDisplayMetadata(tools.mcpServers, name),
1229
+ (entry) => toolFamilyForCatalogIdentity(entry, runSettings.mcpServers),
1083
1230
  );
1084
1231
  eventing.codemodeDispatcher.start();
1085
1232
  };
@@ -1098,12 +1245,14 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
1098
1245
  return {
1099
1246
  attemptConnectorActionBindings,
1100
1247
  connectorActionPolicy,
1248
+ mcpServers: runSettings.mcpServers,
1101
1249
  generateSessionTitleInParallel: titleToolPlan.generateTitleInParallel,
1102
1250
  postToolPreparationStartedAt,
1103
1251
  preparationIndependentToolNames: [
1104
1252
  ...titleToolPlan.preparationIndependentToolNames,
1105
1253
  "skill_read",
1106
1254
  ],
1255
+ codeSearchAvailable: codeSearchTools.length > 0,
1107
1256
  skillCatalog,
1108
1257
  };
1109
1258
  }