@opengeni/worker-bundle 0.20.3 → 0.22.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +52 -0
  2. package/dist/activities/agent-turn/agent-build.d.ts +89 -0
  3. package/dist/activities/agent-turn/claim.d.ts +67 -0
  4. package/dist/activities/agent-turn/codex-capacity.d.ts +40 -0
  5. package/dist/activities/agent-turn/codex.d.ts +32 -0
  6. package/dist/activities/agent-turn/compaction-prep.d.ts +88 -0
  7. package/dist/activities/agent-turn/credential-leases.d.ts +56 -0
  8. package/dist/activities/agent-turn/errors.d.ts +253 -0
  9. package/dist/activities/agent-turn/failure-settlement.d.ts +33 -0
  10. package/dist/activities/agent-turn/file-resources.d.ts +37 -0
  11. package/dist/activities/agent-turn/finalization.d.ts +42 -0
  12. package/dist/activities/agent-turn/github-repository-bindings.d.ts +105 -0
  13. package/dist/activities/agent-turn/governance-model.d.ts +66 -0
  14. package/dist/activities/agent-turn/history-sink.d.ts +52 -0
  15. package/dist/activities/agent-turn/history.d.ts +63 -0
  16. package/dist/activities/agent-turn/media-artifacts.d.ts +145 -0
  17. package/dist/activities/agent-turn/model-usage.d.ts +218 -0
  18. package/dist/activities/agent-turn/quiescence.d.ts +135 -0
  19. package/dist/activities/agent-turn/run-credentials.d.ts +84 -0
  20. package/dist/activities/agent-turn/run.d.ts +3 -0
  21. package/dist/activities/agent-turn/sandbox-establish.d.ts +93 -0
  22. package/dist/activities/agent-turn/sandbox-provision.d.ts +89 -0
  23. package/dist/activities/agent-turn/sandbox-route.d.ts +151 -0
  24. package/dist/activities/agent-turn/sandbox-runtime.d.ts +44 -0
  25. package/dist/activities/agent-turn/stream-attempt.d.ts +107 -0
  26. package/dist/activities/agent-turn/tool-environment.d.ts +142 -0
  27. package/dist/activities/agent-turn/tool-policy.d.ts +127 -0
  28. package/dist/activities/agent-turn/tool-result-spill.d.ts +59 -0
  29. package/dist/activities/agent-turn/turn-context.d.ts +144 -0
  30. package/dist/activities/agent-turn/xai-capacity.d.ts +2 -0
  31. package/dist/activities/agent-turn.d.ts +12 -954
  32. package/dist/activities/automations.d.ts +16 -0
  33. package/dist/activities/common.d.ts +1 -1
  34. package/dist/activities/connector-attachments.d.ts +13 -0
  35. package/dist/activities/documents.d.ts +1 -0
  36. package/dist/activities/environment.d.ts +26 -15
  37. package/dist/activities/generated-images.d.ts +1 -1
  38. package/dist/activities/git-credential-renewal.d.ts +3 -1
  39. package/dist/activities/goals.d.ts +4 -1
  40. package/dist/activities/google-drive-provider.d.ts +29 -0
  41. package/dist/activities/google-drive-publication.d.ts +17 -4
  42. package/dist/activities/incident-telemetry-authority.d.ts +52 -0
  43. package/dist/activities/incident-telemetry-preflight.d.ts +71 -0
  44. package/dist/activities/knowledge-source-sync.d.ts +4 -0
  45. package/dist/activities/mcp-credentials.d.ts +9 -3
  46. package/dist/activities/open-suffix-resume.d.ts +77 -0
  47. package/dist/activities/packs.d.ts +3 -11
  48. package/dist/activities/parent-wake.d.ts +19 -0
  49. package/dist/activities/retained-screenshot-reaper.d.ts +1 -1
  50. package/dist/activities/retained-screenshots.d.ts +1 -1
  51. package/dist/activities/rig-verification.d.ts +1 -1
  52. package/dist/activities/run-input.d.ts +9 -10
  53. package/dist/activities/sandbox-images.d.ts +1 -14
  54. package/dist/activities/sandbox-lease.d.ts +21 -3
  55. package/dist/activities/scheduled-tasks.d.ts +47 -0
  56. package/dist/activities/types.d.ts +23 -2
  57. package/dist/activities/video-media-validation.d.ts +1 -1
  58. package/dist/activities/video-output-retention.d.ts +1 -2
  59. package/dist/activities/xai-auth.d.ts +3 -0
  60. package/dist/{activities-control-BJSDRSIP.js → activities-control-DKG22ONJ.js} +2646 -551
  61. package/dist/activities-control-DKG22ONJ.js.map +1 -0
  62. package/dist/activities-control.d.ts +6 -2
  63. package/dist/activities-turn-4IMC3MAA.js +21326 -0
  64. package/dist/activities-turn-4IMC3MAA.js.map +1 -0
  65. package/dist/activities.d.ts +7 -3
  66. package/dist/artifact-materializer-entry.js +41 -22
  67. package/dist/artifact-materializer-entry.js.map +1 -1
  68. package/dist/{chunk-N5TJIFCE.js → chunk-CE7TPKBS.js} +468 -1
  69. package/dist/chunk-CE7TPKBS.js.map +1 -0
  70. package/dist/chunk-CNYGVRKF.js +4698 -0
  71. package/dist/chunk-CNYGVRKF.js.map +1 -0
  72. package/dist/connection-provider-use.d.ts +18 -0
  73. package/dist/editable-artifact-materializer.d.ts +4 -3
  74. package/dist/github-rest-mcp.d.ts +26 -0
  75. package/dist/index.d.ts +10 -2
  76. package/dist/index.js +58 -14
  77. package/dist/index.js.map +1 -1
  78. package/dist/knowledge-source-sync-activity-policy.d.ts +2 -0
  79. package/dist/model-context-contributions.d.ts +8 -4
  80. package/dist/observability-metrics.d.ts +63 -4
  81. package/dist/opensandbox-kubernetes-inventory.d.ts +21 -0
  82. package/dist/personal-github-git-credentials.d.ts +9 -0
  83. package/dist/pr-review-credentials.d.ts +6 -0
  84. package/dist/sandbox-archive-storage.d.ts +45 -0
  85. package/dist/sandbox-resume.d.ts +65 -6
  86. package/dist/sandbox-routing.d.ts +38 -2
  87. package/dist/scheduled-alert-occurrence.d.ts +33 -0
  88. package/dist/workflow-bundle.js +87 -28
  89. package/dist/workflows/activities.d.ts +1 -0
  90. package/dist/workflows/automations.d.ts +6 -0
  91. package/dist/workflows/document-index.d.ts +1 -0
  92. package/dist/workflows.d.ts +1 -0
  93. package/package.json +17 -17
  94. package/src/activities/agent-turn/admission.ts +292 -0
  95. package/src/activities/agent-turn/agent-build.ts +802 -0
  96. package/src/activities/agent-turn/claim.ts +590 -0
  97. package/src/activities/agent-turn/codex-capacity.ts +720 -0
  98. package/src/activities/agent-turn/codex.ts +94 -0
  99. package/src/activities/agent-turn/compaction-prep.ts +722 -0
  100. package/src/activities/agent-turn/credential-leases.ts +240 -0
  101. package/src/activities/agent-turn/errors.ts +1068 -0
  102. package/src/activities/agent-turn/failure-settlement.ts +1436 -0
  103. package/src/activities/agent-turn/file-resources.ts +227 -0
  104. package/src/activities/agent-turn/finalization.ts +754 -0
  105. package/src/activities/agent-turn/github-repository-bindings.ts +300 -0
  106. package/src/activities/agent-turn/governance-model.ts +465 -0
  107. package/src/activities/agent-turn/history-sink.ts +139 -0
  108. package/src/activities/agent-turn/history.ts +200 -0
  109. package/src/activities/agent-turn/media-artifacts.ts +359 -0
  110. package/src/activities/agent-turn/model-usage.ts +823 -0
  111. package/src/activities/agent-turn/quiescence.ts +353 -0
  112. package/src/activities/agent-turn/run-credentials.ts +761 -0
  113. package/src/activities/agent-turn/run.ts +1530 -0
  114. package/src/activities/agent-turn/sandbox-establish.ts +1207 -0
  115. package/src/activities/agent-turn/sandbox-provision.ts +569 -0
  116. package/src/activities/agent-turn/sandbox-route.ts +358 -0
  117. package/src/activities/agent-turn/sandbox-runtime.ts +731 -0
  118. package/src/activities/agent-turn/stream-attempt.ts +1670 -0
  119. package/src/activities/agent-turn/tool-environment.ts +729 -0
  120. package/src/activities/agent-turn/tool-policy.ts +216 -0
  121. package/src/activities/agent-turn/tool-result-spill.ts +265 -0
  122. package/src/activities/agent-turn/turn-context.ts +281 -0
  123. package/src/activities/agent-turn/xai-capacity.ts +229 -0
  124. package/src/activities/agent-turn.ts +12 -12701
  125. package/src/activities/api-integrations.ts +3 -0
  126. package/src/activities/automations.ts +214 -0
  127. package/src/activities/codemode-dispatcher.ts +12 -1
  128. package/src/activities/common.ts +1 -5
  129. package/src/activities/connector-attachments.ts +168 -0
  130. package/src/activities/context-compaction.ts +18 -0
  131. package/src/activities/environment.ts +151 -55
  132. package/src/activities/generated-images.ts +26 -11
  133. package/src/activities/git-credential-renewal.ts +13 -3
  134. package/src/activities/goals.ts +85 -19
  135. package/src/activities/google-drive-provider.ts +178 -0
  136. package/src/activities/google-drive-publication.ts +147 -49
  137. package/src/activities/incident-telemetry-authority.ts +327 -0
  138. package/src/activities/incident-telemetry-preflight.ts +317 -0
  139. package/src/activities/knowledge-source-sync.ts +178 -37
  140. package/src/activities/mcp-credentials.ts +191 -17
  141. package/src/activities/open-suffix-resume.ts +422 -0
  142. package/src/activities/packs.ts +12 -60
  143. package/src/activities/parent-wake.ts +64 -14
  144. package/src/activities/retained-screenshot-reaper.ts +6 -3
  145. package/src/activities/retained-screenshots.ts +15 -47
  146. package/src/activities/rig-verification.ts +1 -1
  147. package/src/activities/run-input.ts +102 -142
  148. package/src/activities/sandbox-images.ts +7 -166
  149. package/src/activities/sandbox-lease.ts +406 -15
  150. package/src/activities/scheduled-tasks.ts +2103 -411
  151. package/src/activities/session-state.ts +10 -2
  152. package/src/activities/types.ts +32 -2
  153. package/src/activities/video-media-validation.ts +3 -3
  154. package/src/activities/video-output-retention.ts +2 -57
  155. package/src/activities/xai-auth.ts +8 -0
  156. package/src/activities-control.ts +2 -0
  157. package/src/activities.ts +3 -0
  158. package/src/activity-services.ts +13 -4
  159. package/src/connection-provider-use.ts +36 -0
  160. package/src/editable-artifact-materializer-subprocess.ts +25 -14
  161. package/src/editable-artifact-materializer.ts +29 -18
  162. package/src/github-rest-mcp.ts +713 -0
  163. package/src/http.ts +16 -6
  164. package/src/index.ts +40 -5
  165. package/src/knowledge-source-sync-activity-policy.ts +2 -0
  166. package/src/model-context-contributions.ts +33 -10
  167. package/src/observability-metrics.ts +357 -0
  168. package/src/opensandbox-kubernetes-inventory.ts +292 -0
  169. package/src/personal-github-git-credentials.ts +331 -0
  170. package/src/pr-review-credentials.ts +163 -0
  171. package/src/sandbox-archive-storage.ts +159 -0
  172. package/src/sandbox-resume.ts +449 -63
  173. package/src/sandbox-routing.ts +314 -16
  174. package/src/scheduled-alert-occurrence.ts +176 -0
  175. package/src/workflows/activities.ts +18 -2
  176. package/src/workflows/automations.ts +11 -0
  177. package/src/workflows/session.ts +13 -3
  178. package/src/workflows.ts +1 -0
  179. package/dist/activities-control-BJSDRSIP.js.map +0 -1
  180. package/dist/activities-turn-J5YO7XXX.js +0 -17243
  181. package/dist/activities-turn-J5YO7XXX.js.map +0 -1
  182. package/dist/chunk-N5TJIFCE.js.map +0 -1
  183. package/dist/chunk-P6Z2SLAA.js +0 -3092
  184. package/dist/chunk-P6Z2SLAA.js.map +0 -1
@@ -105,6 +105,9 @@ function integrationCredentialResolver(
105
105
  name,
106
106
  value,
107
107
  })),
108
+ ...(result.authorizeProviderRequest
109
+ ? { authorizeProviderRequest: result.authorizeProviderRequest }
110
+ : {}),
108
111
  ...(result.expiresAt ? { expiresAt: result.expiresAt.toISOString() } : {}),
109
112
  ...(connectionRef.scopes ? { scope: [...connectionRef.scopes] } : {}),
110
113
  };
@@ -0,0 +1,214 @@
1
+ import { resolveTurnExecutionPolicyV1 } from "@opengeni/config";
2
+ import {
3
+ assertWorkspaceModelPolicyAllows,
4
+ canonicalConfiguredModel,
5
+ createAndStartSessionWithOutcome,
6
+ recordWorkspaceUsage,
7
+ } from "@opengeni/core";
8
+ import {
9
+ AutomationAuthorityRevokedError,
10
+ assertAutomationRunAuthorityInTransaction,
11
+ claimAutomationRun,
12
+ settleAutomationRun,
13
+ } from "@opengeni/db";
14
+ import { agentRunAdmissionDenial } from "./agent-run-admission";
15
+ import type {
16
+ ControlActivityServices,
17
+ DispatchAutomationRunInput,
18
+ DispatchAutomationRunResult,
19
+ } from "./types";
20
+
21
+ export type AutomationActivityOptions = {
22
+ claim?: typeof claimAutomationRun;
23
+ settle?: typeof settleAutomationRun;
24
+ assertAuthority?: typeof assertAutomationRunAuthorityInTransaction;
25
+ createSession?: typeof createAndStartSessionWithOutcome;
26
+ admit?: typeof agentRunAdmissionDenial;
27
+ assertModelPolicy?: typeof assertWorkspaceModelPolicyAllows;
28
+ recordUsage?: typeof recordWorkspaceUsage;
29
+ };
30
+
31
+ export function createAutomationActivities(
32
+ services: () => Promise<ControlActivityServices>,
33
+ options: AutomationActivityOptions = {},
34
+ ) {
35
+ const claim = options.claim ?? claimAutomationRun;
36
+ const settle = options.settle ?? settleAutomationRun;
37
+ const assertAuthority = options.assertAuthority ?? assertAutomationRunAuthorityInTransaction;
38
+ const createSession = options.createSession ?? createAndStartSessionWithOutcome;
39
+ const admit = options.admit ?? agentRunAdmissionDenial;
40
+ const assertModelPolicy = options.assertModelPolicy ?? assertWorkspaceModelPolicyAllows;
41
+ const recordUsage = options.recordUsage ?? recordWorkspaceUsage;
42
+ return {
43
+ dispatchAutomationRun: async (
44
+ input: DispatchAutomationRunInput,
45
+ ): Promise<DispatchAutomationRunResult> => {
46
+ const service = await services();
47
+ const run = await claim(service.db, input);
48
+ if (!run) return { action: "not_found" };
49
+ if (run.status === "dispatched") {
50
+ if (!run.sessionId) throw new Error("dispatched automation run is missing its session");
51
+ return { action: "already_dispatched", sessionId: run.sessionId };
52
+ }
53
+ if (run.status === "skipped") {
54
+ return { action: "skipped", reason: run.errorCode ?? "authority_revoked" };
55
+ }
56
+
57
+ const accepted = run.acceptedExecution;
58
+ if (
59
+ accepted.accountId !== input.accountId ||
60
+ accepted.workspaceId !== input.workspaceId ||
61
+ accepted.sourceId !== run.sourceId ||
62
+ accepted.triggerId !== run.triggerId ||
63
+ accepted.triggerRevision !== run.triggerRevision ||
64
+ accepted.eventId !== run.eventId
65
+ ) {
66
+ await settle(service.db, {
67
+ workspaceId: input.workspaceId,
68
+ runId: run.id,
69
+ status: "skipped",
70
+ errorCode: "accepted_execution_mismatch",
71
+ });
72
+ return { action: "skipped", reason: "accepted_execution_mismatch" };
73
+ }
74
+
75
+ const template = accepted.sessionTemplate;
76
+ const model = canonicalConfiguredModel(
77
+ service.settings,
78
+ template.model ?? service.settings.openaiModel,
79
+ );
80
+ if (!model) throw new Error("automation has no configured model");
81
+ await assertModelPolicy(service.db, service.settings, input.workspaceId, model);
82
+ const denial = await admit(service, {
83
+ accountId: input.accountId,
84
+ workspaceId: input.workspaceId,
85
+ model,
86
+ requestedAgentRuns: 1,
87
+ });
88
+ if (denial) {
89
+ await settle(service.db, {
90
+ workspaceId: input.workspaceId,
91
+ runId: run.id,
92
+ status: "failed",
93
+ errorCode: denial,
94
+ });
95
+ throw new Error(`automation admission denied: ${denial}`);
96
+ }
97
+ const reasoningEffort = template.reasoningEffort ?? service.settings.openaiReasoningEffort;
98
+ const sandboxBackend = template.sandboxBackend ?? service.settings.sandboxBackend;
99
+ if (sandboxBackend === "selfhosted") {
100
+ await settle(service.db, {
101
+ workspaceId: input.workspaceId,
102
+ runId: run.id,
103
+ status: "skipped",
104
+ errorCode: "interactive_compute_not_allowed",
105
+ });
106
+ return { action: "skipped", reason: "interactive_compute_not_allowed" };
107
+ }
108
+ const turnExecutionPolicy = resolveTurnExecutionPolicyV1(service.settings, {
109
+ modelId: model,
110
+ requestedModelId: template.model,
111
+ modelSource: template.model ? "explicit" : "deployment",
112
+ reasoningEffort,
113
+ reasoningSource: template.reasoningEffort ? "explicit" : "deployment",
114
+ latencyMode: "standard",
115
+ latencyModeSource: "deployment",
116
+ });
117
+
118
+ try {
119
+ const created = await createSession({
120
+ db: service.db,
121
+ bus: service.bus,
122
+ workflowClient: {
123
+ wakeSessionWorkflow: async (wake) => {
124
+ await service.wakeSessionWorkflow?.(wake);
125
+ },
126
+ },
127
+ beforeCreateCommit: async (tx, sessionId) => {
128
+ await assertAuthority(tx, {
129
+ workspaceId: input.workspaceId,
130
+ runId: run.id,
131
+ triggerId: accepted.triggerId,
132
+ triggerRevision: accepted.triggerRevision,
133
+ sourceId: accepted.sourceId,
134
+ sourceVersion: accepted.sourceVersion,
135
+ sessionId,
136
+ });
137
+ },
138
+ accountId: input.accountId,
139
+ workspaceId: input.workspaceId,
140
+ initialMessage: accepted.initialMessage,
141
+ resources: template.resources,
142
+ skills: template.skills,
143
+ tools: template.tools,
144
+ toolPolicy: { mode: "explicit", inheritedFromSessionId: null },
145
+ model,
146
+ reasoningEffort,
147
+ turnExecutionPolicy,
148
+ sandboxBackend,
149
+ metadata: {
150
+ ...template.metadata,
151
+ automationRunId: run.id,
152
+ automationSourceId: run.sourceId,
153
+ automationTriggerId: run.triggerId,
154
+ automationTriggerRevision: run.triggerRevision,
155
+ },
156
+ createdBy: {
157
+ kind: "service",
158
+ subjectId: accepted.serviceSubjectId,
159
+ label: accepted.serviceLabel,
160
+ },
161
+ createdByContext: accepted.provenance,
162
+ instructions: template.instructions,
163
+ policyRole: template.policyRole,
164
+ firstPartyMcpPermissions: template.firstPartyMcpPermissions,
165
+ firstPartyMcpTools: template.firstPartyMcpTools,
166
+ createIdempotencyKey: `automation-run:${run.id}`,
167
+ subjectId: accepted.serviceSubjectId,
168
+ });
169
+ await recordUsage(
170
+ { db: service.db, settings: service.settings },
171
+ {
172
+ accountId: input.accountId,
173
+ workspaceId: input.workspaceId,
174
+ subjectId: accepted.serviceSubjectId,
175
+ eventType: "agent_run.created",
176
+ quantity: 1,
177
+ unit: "run",
178
+ sourceResourceType: "automation_run",
179
+ sourceResourceId: run.id,
180
+ sessionId: created.session.id,
181
+ initiator: created.session.createdBy,
182
+ initiatorContext: created.session.createdByContext,
183
+ origin: "system",
184
+ idempotencyKey: `agent_run.created:automation:${run.id}`,
185
+ },
186
+ ).catch((error) => {
187
+ service.observability.warn("automation usage recording failed", {
188
+ workspaceId: input.workspaceId,
189
+ runId: run.id,
190
+ errorCategory: error instanceof Error ? error.name : "unknown",
191
+ });
192
+ });
193
+ return { action: "started", sessionId: created.session.id };
194
+ } catch (error) {
195
+ if (error instanceof AutomationAuthorityRevokedError) {
196
+ await settle(service.db, {
197
+ workspaceId: input.workspaceId,
198
+ runId: run.id,
199
+ status: "skipped",
200
+ errorCode: "authority_revoked",
201
+ });
202
+ return { action: "skipped", reason: "authority_revoked" };
203
+ }
204
+ await settle(service.db, {
205
+ workspaceId: input.workspaceId,
206
+ runId: run.id,
207
+ status: "failed",
208
+ errorCode: "dispatch_failed",
209
+ });
210
+ throw error;
211
+ }
212
+ },
213
+ };
214
+ }
@@ -251,7 +251,8 @@ export class CodemodeAttemptDispatcher {
251
251
  const knownPreExecution =
252
252
  error instanceof AttemptToolApprovalRequiredError ||
253
253
  error instanceof AttemptToolCatalogStaleError ||
254
- error instanceof AttemptToolNotFoundError;
254
+ error instanceof AttemptToolNotFoundError ||
255
+ connectorActionWasNotExecuted(error);
255
256
  await this.settleWithOutput(operation, claimId, {
256
257
  state: knownPreExecution ? "failed" : "outcome_unknown",
257
258
  errorCode: errorCode(error, signal),
@@ -310,12 +311,22 @@ export class CodemodeAttemptDispatcher {
310
311
  }
311
312
  }
312
313
 
314
+ function connectorActionWasNotExecuted(error: unknown): boolean {
315
+ return Boolean(
316
+ error &&
317
+ typeof error === "object" &&
318
+ "connectorActionOutcome" in error &&
319
+ (error as { connectorActionOutcome?: unknown }).connectorActionOutcome === "not_executed",
320
+ );
321
+ }
322
+
313
323
  function combinedSignal(primary: AbortSignal, secondary?: AbortSignal): AbortSignal {
314
324
  return secondary ? AbortSignal.any([primary, secondary]) : primary;
315
325
  }
316
326
 
317
327
  function errorCode(error: unknown, signal: AbortSignal): string {
318
328
  if (signal.aborted) return "attempt_cancelled_during_execution";
329
+ if (connectorActionWasNotExecuted(error)) return "connector_action_not_executed";
319
330
  if (typeof error === "object" && error !== null && "code" in error) {
320
331
  const code = (error as { code?: unknown }).code;
321
332
  if (typeof code === "string" && /^[a-z0-9_]{1,128}$/u.test(code)) return code;
@@ -5,11 +5,7 @@ import type {
5
5
  ToolRef,
6
6
  } from "@opengeni/contracts";
7
7
 
8
- export {
9
- mergeResourceRefs,
10
- mergeToolRefs,
11
- reasoningEffortForMetadata as reasoningEffortForSession,
12
- } from "@opengeni/contracts";
8
+ export { mergeResourceRefs, mergeToolRefs } from "@opengeni/contracts";
13
9
 
14
10
  /**
15
11
  * Refuse to revive a terminal reusable session on a scheduled fire. Mirrors the
@@ -0,0 +1,168 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ CONNECTOR_ATTACHMENT_RECEIPT_VERSION,
4
+ ConnectorAttachmentReceiptEnvelope,
5
+ type ConnectorAttachmentReceiptEnvelope as ConnectorAttachmentReceiptEnvelopeValue,
6
+ type ConnectorAttachmentTransfer,
7
+ } from "@opengeni/contracts";
8
+ import {
9
+ connectorAttachmentSandboxPath,
10
+ type ConnectorAttachmentMaterializationRequest,
11
+ } from "@opengeni/runtime";
12
+ import {
13
+ ChannelAPartialMutationError,
14
+ RoutingMutationOutcomeUnknownError,
15
+ SandboxChannelAService,
16
+ } from "@opengeni/runtime/sandbox";
17
+
18
+ export class ConnectorAttachmentMaterializationError extends Error {
19
+ constructor() {
20
+ super("Connector attachment could not be materialized in the sandbox");
21
+ this.name = "ConnectorAttachmentMaterializationError";
22
+ }
23
+ }
24
+
25
+ type ConnectorAttachmentChannel = Pick<
26
+ SandboxChannelAService,
27
+ "importWorkspaceFiles" | "inspectWorkspaceFiles"
28
+ >;
29
+
30
+ type ConnectorAttachmentMaterializationOptions = Readonly<{
31
+ runMutation?: <T>(mutation: () => Promise<T>) => Promise<T>;
32
+ }>;
33
+
34
+ function digestParts(...parts: readonly string[]): Buffer {
35
+ const hash = createHash("sha256");
36
+ for (const part of parts) {
37
+ const bytes = Buffer.from(part, "utf8");
38
+ hash.update(String(bytes.byteLength));
39
+ hash.update(":");
40
+ hash.update(bytes);
41
+ hash.update(";");
42
+ }
43
+ return hash.digest();
44
+ }
45
+
46
+ function uuidFromDigest(digest: Buffer): string {
47
+ const bytes = Uint8Array.from(digest.subarray(0, 16));
48
+ bytes[6] = (bytes[6]! & 0x0f) | 0x50;
49
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
50
+ const hex = Buffer.from(bytes).toString("hex");
51
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
52
+ }
53
+
54
+ export { connectorAttachmentSandboxPath } from "@opengeni/runtime";
55
+
56
+ export function connectorAttachmentImportOperationId(
57
+ request: Pick<
58
+ ConnectorAttachmentMaterializationRequest,
59
+ "serverId" | "toolName" | "operationId" | "connectionId"
60
+ >,
61
+ attachment: ConnectorAttachmentTransfer,
62
+ index: number,
63
+ ): string {
64
+ return uuidFromDigest(
65
+ digestParts(
66
+ "opengeni-connector-attachment-import-v1",
67
+ request.serverId,
68
+ request.toolName,
69
+ request.operationId,
70
+ request.connectionId,
71
+ String(index),
72
+ attachment.providerAttachmentId.provider,
73
+ attachment.providerAttachmentId.value,
74
+ attachment.contentSha256,
75
+ ),
76
+ );
77
+ }
78
+
79
+ export async function materializeConnectorAttachmentsInChannel(
80
+ channel: ConnectorAttachmentChannel,
81
+ request: ConnectorAttachmentMaterializationRequest,
82
+ options: ConnectorAttachmentMaterializationOptions = {},
83
+ ): Promise<ConnectorAttachmentReceiptEnvelopeValue> {
84
+ try {
85
+ const imports = request.attachments.map((attachment, index) => {
86
+ const destinationPath = connectorAttachmentSandboxPath(request, attachment);
87
+ return {
88
+ operationId: connectorAttachmentImportOperationId(request, attachment, index),
89
+ destinationPath,
90
+ overwrite: false,
91
+ mayReplaceExisting: false,
92
+ createParents: true,
93
+ sizeBytes: attachment.byteSize,
94
+ sha256: attachment.contentSha256,
95
+ source: attachment.source,
96
+ };
97
+ });
98
+ const replayedFiles = await channel.inspectWorkspaceFiles(imports);
99
+ const importExactBytes = async () => {
100
+ const importedFiles = [];
101
+ if (imports.length === 0) return await channel.importWorkspaceFiles([]);
102
+ for (const item of imports) {
103
+ try {
104
+ if (request.authorizeProviderRequest) {
105
+ let authorized = false;
106
+ try {
107
+ authorized = await request.authorizeProviderRequest();
108
+ } catch {
109
+ authorized = false;
110
+ }
111
+ if (!authorized) throw new ConnectorAttachmentMaterializationError();
112
+ }
113
+ const [imported] = await channel.importWorkspaceFiles([item]);
114
+ if (!imported) throw new ConnectorAttachmentMaterializationError();
115
+ importedFiles.push(imported);
116
+ } catch (error) {
117
+ if (importedFiles.length > 0 && !(error instanceof RoutingMutationOutcomeUnknownError)) {
118
+ throw new ChannelAPartialMutationError(
119
+ "connector attachment materialization committed an earlier exact file",
120
+ { cause: error },
121
+ );
122
+ }
123
+ throw error;
124
+ }
125
+ }
126
+ return importedFiles;
127
+ };
128
+ const importedFiles =
129
+ replayedFiles ??
130
+ (options.runMutation
131
+ ? await options.runMutation(importExactBytes)
132
+ : await importExactBytes());
133
+ const receipts = [];
134
+ for (const [index, attachment] of request.attachments.entries()) {
135
+ const sandboxPath = imports[index]?.destinationPath;
136
+ const imported = importedFiles[index];
137
+ if (
138
+ !sandboxPath ||
139
+ !imported ||
140
+ imported.destinationPath !== sandboxPath ||
141
+ imported.sizeBytes !== attachment.byteSize ||
142
+ imported.sha256 !== attachment.contentSha256
143
+ ) {
144
+ throw new ConnectorAttachmentMaterializationError();
145
+ }
146
+ receipts.push({
147
+ providerAttachmentId: attachment.providerAttachmentId,
148
+ fileName: attachment.fileName,
149
+ mediaType: attachment.mediaType,
150
+ byteSize: attachment.byteSize,
151
+ contentSha256: attachment.contentSha256,
152
+ sandboxPath,
153
+ });
154
+ }
155
+ return ConnectorAttachmentReceiptEnvelope.parse({
156
+ version: CONNECTOR_ATTACHMENT_RECEIPT_VERSION,
157
+ attachments: receipts,
158
+ });
159
+ } catch (error) {
160
+ if (
161
+ error instanceof ChannelAPartialMutationError ||
162
+ error instanceof RoutingMutationOutcomeUnknownError
163
+ ) {
164
+ throw error;
165
+ }
166
+ throw new ConnectorAttachmentMaterializationError();
167
+ }
168
+ }
@@ -11,6 +11,7 @@ import {
11
11
  SUMMARY_BUFFER_TOKENS,
12
12
  buildCompactionReplacementHistory,
13
13
  buildRemoteV2ReplacementHistory,
14
+ compactionThresholdTokens,
14
15
  compactionReplacementFingerprint,
15
16
  decideCompaction,
16
17
  estimateTokens,
@@ -113,6 +114,23 @@ export async function maybeCompactContext(
113
114
  }
114
115
  const useRemoteV2 = options.codexCompactionMode === "remote_v2";
115
116
 
117
+ // An automatic check below the provider-accounted threshold cannot compact.
118
+ // Avoid loading and projecting the same complete history that the ordinary
119
+ // model-input path will load immediately afterward. Operator requests still
120
+ // load history so their durable requested/skipped semantics stay unchanged.
121
+ if (!options.force && !options.clearRequestedCompaction) {
122
+ const providerInputTokens =
123
+ typeof lastInputTokens === "number" && lastInputTokens > 0 ? lastInputTokens : 0;
124
+ if (providerInputTokens < compactionThresholdTokens(settings)) {
125
+ return {
126
+ compacted: false,
127
+ reason: "below_threshold",
128
+ events: [],
129
+ requestConsumed: false,
130
+ };
131
+ }
132
+ }
133
+
116
134
  // Preserve the complete ordered transcript while bounding each Postgres
117
135
  // driver result frame beside the decoded history already held by this turn.
118
136
  const active = await getActiveSessionHistoryItemsPaged(db, scope.workspaceId, scope.sessionId);