@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
@@ -0,0 +1,253 @@
1
+ import { type McpTransportRequestFailureDiagnostic } from "@opengeni/runtime/mcp-network";
2
+ import { ApplicationFailure } from "@temporalio/activity";
3
+ import type { CodexAccountStatus } from "@opengeni/db";
4
+ import type { EscapedMcpTimeoutRecoveryDetail } from "../types.js";
5
+ import { type MandatoryHistoryPersistenceStage } from "./quiescence.js";
6
+ export declare const PROVIDER_BACKPRESSURE_DELAY_MS = 60000;
7
+ export declare const PROVIDER_CONNECTIVITY_BACKOFF_MS: readonly [2000, 5000, 15000, 30000, 60000];
8
+ export declare const MAX_AUTOMATIC_PROVIDER_RECOVERIES: 5;
9
+ export type ProviderRecoveryResult = {
10
+ status: "recovering";
11
+ continueDelayMs: number;
12
+ } | {
13
+ status: "exhausted";
14
+ providerRecoveryCount: number;
15
+ maxProviderRecoveryCount: number;
16
+ };
17
+ export declare function providerRecoveryResult(input: {
18
+ failureCode: string | undefined;
19
+ attemptNumber: number;
20
+ retryAfterMs?: number | null;
21
+ }): ProviderRecoveryResult;
22
+ export declare function providerRecoveryExhaustedFailure<T extends Record<string, unknown> & {
23
+ error: string;
24
+ }>(failure: T, recovery: Extract<ProviderRecoveryResult, {
25
+ status: "exhausted";
26
+ }>): T & {
27
+ retryable: false;
28
+ recoveryExhausted: true;
29
+ providerRecoveryCount: number;
30
+ maxProviderRecoveryCount: number;
31
+ lastRetryableError: string;
32
+ };
33
+ export declare function providerRecoveryCountFromMetadata(metadata: Record<string, unknown>): number;
34
+ export declare function headerValue(headers: unknown, name: string): string | null;
35
+ /** Read a provider Retry-After hint without retaining response headers/body. */
36
+ export declare function providerRetryAfterMs(error: unknown, nowMs?: number): number | null;
37
+ /**
38
+ * Tell the model when durable MCP policy references are unavailable for this
39
+ * exact turn. The policy projection already bounds and validates these ids;
40
+ * this notice prevents a graceful runtime drop from becoming a silent source-
41
+ * of-truth substitution or a false claim that the disconnected system was read.
42
+ */
43
+ export declare function unavailableMcpOperationalContext(input: {
44
+ droppedIds: readonly string[];
45
+ droppedCount: number;
46
+ }): string | undefined;
47
+ /**
48
+ * Preserve one precise recovery obligation across Temporal's activity boundary.
49
+ * This is intentionally narrower than the ordinary retryable-provider path:
50
+ * only a recovered turn (generation > 1) whose MCP timeout happened before a
51
+ * model request may ask the workflow's DB-only control activity to finish the
52
+ * same-turn checkpoint. The original transport/recovery errors are excluded
53
+ * from details so raw MCP response data can never enter workflow history.
54
+ */
55
+ export declare function escapedMcpTimeoutRecoveryFailure(input: {
56
+ failureCode: string | undefined;
57
+ modelRequestStarted: boolean;
58
+ detail: EscapedMcpTimeoutRecoveryDetail;
59
+ }): ApplicationFailure | null;
60
+ /**
61
+ * Convert the atomic claim transaction's failure into a small, stable
62
+ * Temporal wire contract. The original error remains in activity diagnostics,
63
+ * but SQL text, parameters, and arbitrary invariant messages never enter
64
+ * workflow history. Contention and operational database unavailability are
65
+ * safe to re-read after backoff because the claim transaction contains no
66
+ * model/tool effects; permanent database and state failures require terminal
67
+ * settlement.
68
+ */
69
+ export declare function preClaimAdmissionFailure(error: unknown): ApplicationFailure;
70
+ /**
71
+ * Resolve which Codex account a turn runs on (multi-account P1): session-pin >
72
+ * workspace-active. No rotation in P1. The selected id must still be in the
73
+ * connected set — a disconnected pin was FK-nulled, so a stale id can't appear,
74
+ * but we guard anyway. Returns null when there is no usable account (the turn
75
+ * then fails with the existing relogin error path).
76
+ */
77
+ export declare function isWorkerShutdownCancellation(error: unknown): boolean;
78
+ /**
79
+ * Recognize the one active-route transition that cannot finish inside its
80
+ * originating attempt. A Modal-home session may start on a Connected Machine
81
+ * without creating or leasing its managed home box. When an explicit attach
82
+ * clears the active pointer back to home, the pointer commit is authoritative,
83
+ * but this attempt has no home session to serve the next sandbox operation.
84
+ *
85
+ * The Agents SDK may retain the typed routing error directly, through `cause`,
86
+ * or inside an AggregateError from a parallel function-tool batch. Traverse
87
+ * only those structural error links with a strict bound; never classify from
88
+ * message text, which could originate in model or tool content.
89
+ */
90
+ export declare function sandboxRouteTransitionCode(error: unknown): "home_unavailable_this_turn" | "workspace_root_changed_this_turn" | null;
91
+ export declare function isSandboxRouteTransitionError(error: unknown): boolean;
92
+ /** Backward-compatible name for callers/tests that only exercised the original
93
+ * machine-to-home transition. */
94
+ export declare function isHomeSandboxTurnTransitionError(error: unknown): boolean;
95
+ /**
96
+ * Review captures and protective snapshots are cache/persistence housekeeping,
97
+ * never part of cancellation correctness. A control-fenced or Temporal-cancelled
98
+ * attempt must release its physical activity promptly so Steer/Pause can advance.
99
+ */
100
+ export declare function compactionFailureReason(reason: string): string;
101
+ export type SafeErrorDiagnostic = {
102
+ errorClass: "WorkerOperationError";
103
+ errorCode: "worker_operation_failed";
104
+ status?: number;
105
+ origin: "worker";
106
+ historyPersistenceStage?: MandatoryHistoryPersistenceStage;
107
+ };
108
+ /**
109
+ * Produce the only exception shape allowed in worker logs. It deliberately
110
+ * excludes the arbitrary source message, stack, cause, response/request
111
+ * bodies, and enumerable properties. Exact failure content belongs in the
112
+ * permission-controlled session event, not stdout or telemetry.
113
+ */
114
+ export declare function safeErrorDiagnostic(error: unknown): SafeErrorDiagnostic;
115
+ export declare function safeErrorForTelemetry(error: unknown): Error;
116
+ export declare function compactionFailureReasonFromError(error: unknown): string;
117
+ export declare function isCompactionSummaryFailure(error: unknown): boolean;
118
+ export declare function shouldRecoverCompactionProviderFailure(error: unknown): boolean;
119
+ export declare function classifyContextWindowOverflowError(error: unknown): {
120
+ message: string;
121
+ code?: string;
122
+ detail?: string;
123
+ } | null;
124
+ /**
125
+ * Recognize an MCP transport/request timeout that escaped the SDK's per-tool
126
+ * `mcpConfig.errorFunction` boundary. A thrown tool invocation is normally
127
+ * converted to an `{isError:true}` tool output; however, connect/tools-list or
128
+ * next-loop transport work can reject the stream iterator after a prior tool
129
+ * output was already published. That is transient external backpressure, not a
130
+ * terminal session error. Match MCP-qualified timeout text only: an unrelated
131
+ * sandbox/model timeout and MCP's application-defined Authentication required signal must
132
+ * retain their existing semantics.
133
+ */
134
+ export declare function classifyMcpTransportTimeoutError(error: unknown): {
135
+ message: string;
136
+ detail?: string;
137
+ } | null;
138
+ export declare function collectErrorStrings(value: unknown, seen?: WeakSet<object>): string[];
139
+ /**
140
+ * Compute the conversation-truth rows a reconcile pass should append, given the
141
+ * SDK's current `state.history` and the count already persisted.
142
+ *
143
+ * `state.history` is a computed getter that runs the SDK's orphan-tool-call
144
+ * pruning on every access, so it is non-monotonic: a `function_call` with no
145
+ * settling result yet is transiently absent and a later access yields a
146
+ * different, possibly shorter/reordered list. The old code sliced this list by
147
+ * a blind length watermark and appended at fixed positions with
148
+ * onConflictDoNothing, which could freeze a position with one shape and later
149
+ * persist a `function_call_result` whose `function_call` had been pruned away in
150
+ * an earlier slice — the orphaned tool output that 400s the Responses API and
151
+ * bricks the session on every replay.
152
+ *
153
+ * Defending: structurally repair the full current history into an API-valid sequence (the
154
+ * same pure rules the read path uses), then append only the new tail beyond the
155
+ * watermark. A trailing dangling call is dropped here and re-evaluated next
156
+ * pass once its result lands, so a call and its result are written together at
157
+ * consecutive positions and a result is never persisted without its call. The
158
+ * watermark advances to the repaired length — never past anything unwritten —
159
+ * so a non-monotonic history can never desync it. When previously-persisted
160
+ * rows already exceed the repaired length (e.g. legacy orphans written before
161
+ * this fix), nothing new is appended and the watermark holds steady.
162
+ */
163
+ /**
164
+ * Stable+unique usage source key for one model call, used to build the per-call
165
+ * idempotency key (`usage:model.tokens:${turnId}:${sourceKey}`). The turnId is
166
+ * shared across a new attempt of the SAME turn (recovery, approval
167
+ * rerun, activity retry), so the sourceKey alone must distinguish calls.
168
+ *
169
+ * - A provider responseId is globally stable+unique, so reuse it verbatim: a
170
+ * true activity retry that re-emits the same responseId correctly DEDUPES
171
+ * (one charge), while two distinct calls get distinct ids.
172
+ * - Without a responseId the old synthesized key was only POSITIONAL ("response-1",
173
+ * "aggregate"), which collides across a re-dispatch — dispatch B's first
174
+ * call reuses dispatch A's "response-1" key and its charge is silently
175
+ * dropped (undercharge). Qualifying the synthesized key with the
176
+ * per-execution dispatch id (the Temporal activityId, unique per scheduled
177
+ * execution) makes re-dispatched calls distinct while still deduping a
178
+ * same-execution retry.
179
+ */
180
+ export declare const STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE = "unable to connect. is the computer able to access the url?";
181
+ export declare function isExactStatuslessUpstreamConnectivityMessage(message: string): boolean;
182
+ export declare function isTransientProviderError(error: unknown): boolean;
183
+ export type XaiCredentialFailure = {
184
+ kind: "auth" | "forbidden" | "rate_limit";
185
+ cooldownMs: number | null;
186
+ };
187
+ /**
188
+ * Only definitive SuperGrok account refusals may move the same logical turn to
189
+ * another credential. A marked HTTP 401/403/429, or an HTTP 200 SSE terminal
190
+ * that is a rate-limit/capacity diagnostic, proves inference was refused
191
+ * without an accepted model response; refresh relogin is equally definitive.
192
+ */
193
+ export declare function classifyXaiCredentialFailure(error: unknown): XaiCredentialFailure | null;
194
+ export declare function agentRunFailurePayload(error: unknown, options?: {
195
+ isCodexTurn?: boolean;
196
+ }): {
197
+ error: string;
198
+ code?: string;
199
+ retryable?: boolean;
200
+ detail?: string;
201
+ timeoutClass?: string;
202
+ responseObserved?: boolean;
203
+ requestId?: string;
204
+ eventCount?: number;
205
+ lastEventType?: string;
206
+ silenceDurationMs?: number;
207
+ correlationId?: string;
208
+ stage?: string;
209
+ sqlState?: string | null;
210
+ attempts?: number;
211
+ retryOutcome?: string;
212
+ database?: Record<string, string>;
213
+ historyPersistenceStage?: MandatoryHistoryPersistenceStage;
214
+ mcpTransportDiagnostic?: McpTransportRequestFailureDiagnostic;
215
+ };
216
+ export type CodexCredentialFailure = {
217
+ kind: "auth" | "forbidden" | "rate_limit" | "quota";
218
+ cooldownSeconds: number | null;
219
+ };
220
+ export declare const CODEX_ALLOWANCE_FALLBACK_MS: number;
221
+ /**
222
+ * Resolve a deterministic quarantine end. Generic request throttling honors
223
+ * provider retry-after (or one minute); allowance/quota refusal waits for the
224
+ * LAST of provider reset and every still-binding cached window (five-hour and
225
+ * weekly both bind), falling back to one complete five-hour window when no reset
226
+ * metadata exists.
227
+ */
228
+ export declare function codexCredentialCooldownUntil(failure: CodexCredentialFailure, account: Pick<CodexAccountStatus, "primaryUsedPercent" | "primaryResetAt" | "secondaryUsedPercent" | "secondaryResetAt"> | null, now: Date): Date | null;
229
+ /**
230
+ * Only definitive credential/account refusals are safe rotation signals.
231
+ * Ambiguous network failures, malformed/partial streams, invalid model content,
232
+ * prompt 4xx, and provider 5xx may already have consumed tokens or persisted
233
+ * progress and therefore MUST NOT walk the credential pool automatically.
234
+ */
235
+ export declare function classifyCodexCredentialFailure(error: unknown): CodexCredentialFailure | null;
236
+ /** Humanize a seconds duration into a short "2h 5m" / "9m" / "in under a minute" string. */
237
+ export declare function humanizeResetWindow(resetsInSeconds: number | null): string;
238
+ /**
239
+ * Build the turn.failed payload for a ChatGPT/Codex usage cap: a precise,
240
+ * actionable message naming the reset window, the stable `codex_usage_limit_reached`
241
+ * code, and retryable:false (an auto-retry would just re-hit the cap).
242
+ */
243
+ export declare function codexUsageLimitFailurePayload(info: {
244
+ resetsInSeconds: number | null;
245
+ }, detail: string, opts?: {
246
+ allAccounts?: boolean;
247
+ }): {
248
+ error: string;
249
+ code: string;
250
+ retryable: boolean;
251
+ detail?: string;
252
+ };
253
+ export declare const CODEX_USAGE_LIMIT_MAX_RESUME_MS: number;
@@ -0,0 +1,33 @@
1
+ import type { Settings } from "@opengeni/config";
2
+ import type { TurnActivityServices as ActivityServices, RunAgentTurnInput, RunAgentTurnResult } from "../types.js";
3
+ import { createTurnCredentialLeases } from "./credential-leases.js";
4
+ import { createTurnHistorySink } from "./history-sink.js";
5
+ import type { AttemptIdentityState, BillingState, EventingState, ProviderTurnState, TurnControlState } from "./turn-context.js";
6
+ export type TurnFailureDeps = {
7
+ error: unknown;
8
+ input: RunAgentTurnInput;
9
+ settings: Settings;
10
+ db: ActivityServices["db"];
11
+ bus: ActivityServices["bus"];
12
+ observability: ActivityServices["observability"];
13
+ wakeSessionWorkflow: ActivityServices["wakeSessionWorkflow"];
14
+ signalCodexCapacityWorkflow: ActivityServices["signalCodexCapacityWorkflow"];
15
+ cancellationSignal: AbortSignal | undefined;
16
+ sandboxRotationController: AbortController;
17
+ noteCancellationRequested: () => void;
18
+ codexWorkspaceKey: string;
19
+ control: TurnControlState;
20
+ attempt: AttemptIdentityState;
21
+ billingState: BillingState;
22
+ eventing: EventingState;
23
+ providerTurn: ProviderTurnState;
24
+ leases: ReturnType<typeof createTurnCredentialLeases>;
25
+ historySink: ReturnType<typeof createTurnHistorySink>;
26
+ claimedResult: (result: Omit<Extract<RunAgentTurnResult, {
27
+ status: Exclude<RunAgentTurnResult["status"], "unclaimed">;
28
+ }>, "turnId" | "attemptId">) => RunAgentTurnResult;
29
+ flushRuntimeBatcher: () => Promise<void>;
30
+ acknowledgeLostAttemptOwnership: () => void;
31
+ acknowledgeRecoveryQuiescence: () => void;
32
+ };
33
+ export declare function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgentTurnResult>;
@@ -0,0 +1,37 @@
1
+ import { areGitHubRepositoriesAllowedForWorkspace } from "@opengeni/db";
2
+ import { type SandboxFileDownload, type SandboxFileDownloadFailure } from "@opengeni/runtime";
3
+ import { type Settings } from "@opengeni/config";
4
+ import { type GitHubTokenMintAuthorization } from "../environment.js";
5
+ import type { TurnActivityServices as ActivityServices } from "../types.js";
6
+ import { type ObjectStorage } from "@opengeni/storage";
7
+ import { type ResourceRef } from "@opengeni/contracts";
8
+ export declare function filterUnmaterializedSandboxFileDownloads(downloads: SandboxFileDownload[], materializedFileIds: Set<string>): SandboxFileDownload[];
9
+ export declare function runtimeResourcesForTurn(sessionResources: readonly ResourceRef[], currentTurnResources: readonly ResourceRef[]): ResourceRef[];
10
+ export declare function sandboxFileMaterializationOutcome(failures: readonly SandboxFileDownloadFailure[]): "completed" | "failed";
11
+ /** Fixed-length one-way tenant correlation for metrics/alerts; never a raw id. */
12
+ export declare function assertGitHubResourcesRemainAuthorized(db: Parameters<typeof areGitHubRepositoriesAllowedForWorkspace>[0], workspaceId: string, resources: ResourceRef[], authorize?: GitHubTokenMintAuthorization): Promise<void>;
13
+ export declare function assertFileResourcesRemainAuthorized(db: ActivityServices["db"], accountId: string, workspaceId: string, subjectId: string | null, resources: ResourceRef[]): Promise<void>;
14
+ export declare function assertGitHubTokenMintSelectionAuthorized(db: Parameters<typeof areGitHubRepositoriesAllowedForWorkspace>[0], workspaceId: string, installationId: number, repositoryIds: number[]): Promise<void>;
15
+ /**
16
+ * True when the error is transient upstream backpressure — a model-provider 5xx,
17
+ * a "server had a bad minute" body, or a dropped/again-able network connection —
18
+ * rather than a request the session got wrong. These are safe to recover as a new
19
+ * fenced attempt of the SAME turn after PROVIDER_BACKPRESSURE_DELAY_MS. Durable
20
+ * tool results are preserved and ambiguous in-flight effects are closed before
21
+ * the new attempt, independent of whether the session has an active goal.
22
+ *
23
+ * This is the classification gap that hard-failed a fleet of prod sessions during a
24
+ * provider degradation window: their errors ("Our servers are currently overloaded",
25
+ * the generic 500 "An error occurred while processing your request", "Connection
26
+ * error") carried no retryable marker and fell through to a terminal session.failed.
27
+ *
28
+ * HTTP status is authoritative when present — EVERY 5xx is a server-side failure that
29
+ * is safe to retry, while 4xx (validation, auth, 404) is a request fault that must
30
+ * still hard-fail. The code/message matches are the fallback for network faults and
31
+ * SDK-rethrown bare Errors that carry no status. A ChatGPT/Codex usage cap (a 429
32
+ * that will NOT clear on retry) is classified and returned BEFORE this in
33
+ * agentRunFailurePayload, so it never reaches here.
34
+ */
35
+ export declare function sandboxFileDownloadsForRun(settings: Settings, db: ActivityServices["db"], objectStorage: ObjectStorage | null, accountId: string, workspaceId: string, subjectId: string | null, resources: ResourceRef[], activeSandboxBackend?: Settings["sandboxBackend"]): Promise<SandboxFileDownload[]>;
36
+ export declare function requiresSignedFileResourceDownloads(settings: Settings, activeSandboxBackend?: Settings["sandboxBackend"]): boolean;
37
+ export declare function objectStorageForSandboxDownloads(settings: Settings, objectStorage: ObjectStorage, activeSandboxBackend?: Settings["sandboxBackend"]): ObjectStorage;
@@ -0,0 +1,42 @@
1
+ import type { Settings } from "@opengeni/config";
2
+ import type { currentActivityContext } from "../streaming.js";
3
+ import type { RunAgentTurnInput, TurnActivityServices as ActivityServices } from "../types.js";
4
+ import { createModelCheckpointMemoryCollector } from "../../model-checkpoint-memory-collector.js";
5
+ import { makeMachineOpObserver } from "../../observability-metrics.js";
6
+ import { type ResumedTurnSandbox } from "../../sandbox-resume.js";
7
+ import { createTurnCredentialLeases } from "./credential-leases.js";
8
+ import type { AttemptIdentityState, EventingState, ProviderTurnState, RecordingState, RenewalState, SandboxRuntimeState, TurnControlState, WorkspaceRefState } from "./turn-context.js";
9
+ export type TurnFinalizationDeps = {
10
+ input: RunAgentTurnInput;
11
+ settings: Settings;
12
+ db: ActivityServices["db"];
13
+ bus: ActivityServices["bus"];
14
+ objectStorage: ActivityServices["objectStorage"];
15
+ observability: ActivityServices["observability"];
16
+ wakeSessionWorkflow: ActivityServices["wakeSessionWorkflow"];
17
+ signalSessionAttemptQuiesced: ActivityServices["signalSessionAttemptQuiesced"];
18
+ signalCodexCapacityWorkflow: ActivityServices["signalCodexCapacityWorkflow"];
19
+ cancellationSignal: AbortSignal | undefined;
20
+ sandboxResumeController: AbortController;
21
+ activityContext: ReturnType<typeof currentActivityContext>;
22
+ activityStarted: number;
23
+ activitySpan: ReturnType<ActivityServices["observability"]["startSpan"]>;
24
+ dispatchId: string;
25
+ noteCancellationRequested: () => void;
26
+ machineOpObserver: ReturnType<typeof makeMachineOpObserver>;
27
+ leases: ReturnType<typeof createTurnCredentialLeases>;
28
+ control: TurnControlState;
29
+ attempt: AttemptIdentityState;
30
+ sandboxState: SandboxRuntimeState;
31
+ renewals: RenewalState;
32
+ recordingState: RecordingState;
33
+ eventing: EventingState;
34
+ providerTurn: ProviderTurnState;
35
+ workspaceRefs: WorkspaceRefState;
36
+ runWorkspaceMutationForSandbox: <T>(sandbox: ResumedTurnSandbox, operation: string, mutation: () => Promise<T>) => Promise<T>;
37
+ requireResolvedSandboxForMutation: (message: string) => ResumedTurnSandbox;
38
+ stopLeaseHeartbeat: () => void;
39
+ abandonActiveRecording: (reason: string, disposition?: "failed" | "discard") => Promise<void>;
40
+ turnCompletionMemoryCollector: ReturnType<typeof createModelCheckpointMemoryCollector>;
41
+ };
42
+ export declare function finalizeTurnAttempt(deps: TurnFinalizationDeps): Promise<void>;
@@ -0,0 +1,105 @@
1
+ import type { Settings } from "@opengeni/config";
2
+ import type { CredentialAuthNeededPayload, ResourceRef } from "@opengeni/contracts";
3
+ import { type GitHubRepositoryBinding, type GitHubRepositoryBindingCandidate, type GitHubRepositoryBindingLookup, type GitHubRepositoryBindingResolution } from "@opengeni/core";
4
+ import type { Database } from "@opengeni/db";
5
+ /**
6
+ * Turn-time GitHub App binding resolution for bare repository URIs.
7
+ *
8
+ * The web composer and the MCP repository catalog stamp
9
+ * `githubInstallationId`/`githubRepositoryId` on every bound repository, but an
10
+ * API caller, an older session, or an agent-spawned child may still carry a
11
+ * bare `https://github.com/<owner>/<repo>` resource. The workspace allowlist
12
+ * stores repository ids only, so the worker (which already talks to GitHub to
13
+ * mint the sandbox token) resolves the URI here: the owner selects the
14
+ * workspace's auditable installation(s) from Postgres, one server-side
15
+ * metadata-read supplies GitHub's repository id, and the allowlist decides.
16
+ * Exactly one allowlisted match stamps the ids for this turn's in-memory
17
+ * resources; every other case keeps the resource bare (anonymous clone, as
18
+ * before) and reports a visible warning. Nothing here is durable and nothing
19
+ * can fail the turn.
20
+ */
21
+ /** Process-local lookup memo: recovered turns and sibling children reuse it. */
22
+ export declare const GITHUB_REPOSITORY_LOOKUP_CACHE_TTL_MS: number;
23
+ type LookupCacheEntry = {
24
+ value: {
25
+ id: number;
26
+ } | null;
27
+ expiresAt: number;
28
+ };
29
+ export type GitHubRepositoryLookupCache = {
30
+ get: (key: string, now: number) => LookupCacheEntry | undefined;
31
+ set: (key: string, entry: LookupCacheEntry) => void;
32
+ clear: () => void;
33
+ };
34
+ export declare function createGitHubRepositoryLookupCache(maxEntries?: number): GitHubRepositoryLookupCache;
35
+ /**
36
+ * Wrap a live lookup with the process-local TTL memo. Successful ids and
37
+ * negative (not visible through this installation) answers are both cached;
38
+ * failures are not, so a GitHub blip is retried on the next turn.
39
+ */
40
+ export declare function cachedGitHubRepositoryBindingLookup(input: {
41
+ workspaceId: string;
42
+ lookup: GitHubRepositoryBindingLookup;
43
+ cache?: GitHubRepositoryLookupCache;
44
+ now?: () => number;
45
+ ttlMs?: number;
46
+ }): GitHubRepositoryBindingLookup;
47
+ export type TurnGitHubRepositoryBindings = {
48
+ resources: ResourceRef[];
49
+ bindings: Map<string, GitHubRepositoryBinding>;
50
+ resolutions: GitHubRepositoryBindingResolution[];
51
+ warnings: CredentialAuthNeededPayload[];
52
+ /** Apply the same bindings to a sibling resource list (runtime resources). */
53
+ apply: (resources: readonly ResourceRef[]) => ResourceRef[];
54
+ };
55
+ export declare function resolveTurnGitHubRepositoryBindings(input: {
56
+ db: Database;
57
+ settings: Settings;
58
+ workspaceId: string;
59
+ resources: readonly ResourceRef[];
60
+ /** Test seam; defaults to the workspace's auditable bindings under RLS. */
61
+ listCandidates?: (db: Database, workspaceId: string) => Promise<GitHubRepositoryBindingCandidate[]>;
62
+ /** Test seam; defaults to one live GitHub App lookup client per call. */
63
+ lookup?: GitHubRepositoryBindingLookup;
64
+ /** Test seam; defaults to the process-local TTL memo. */
65
+ lookupCache?: GitHubRepositoryLookupCache;
66
+ }): Promise<TurnGitHubRepositoryBindings>;
67
+ /**
68
+ * The visible warning for a bound-but-unusable repository. An unbound owner
69
+ * is the ordinary anonymous public clone and produces no warning; a resolved
70
+ * repository needs none.
71
+ */
72
+ export declare function gitHubRepositoryBindingWarning(resolution: GitHubRepositoryBindingResolution): CredentialAuthNeededPayload | null;
73
+ export type ApplyTurnGitHubRepositoryBindingsInput = {
74
+ db: Database;
75
+ settings: Settings;
76
+ workspaceId: string;
77
+ sessionId: string;
78
+ activeSandboxBackend: Settings["sandboxBackend"] | undefined;
79
+ claimedTurnResources: readonly ResourceRef[];
80
+ claimedRuntimeResources: readonly ResourceRef[];
81
+ /** Publishes one attempt-fenced session event batch. */
82
+ publish: (events: Array<{
83
+ type: "credential.auth_needed";
84
+ payload: CredentialAuthNeededPayload;
85
+ }>) => Promise<void>;
86
+ /** Operational log for a resolution that threw; the turn proceeds bare. */
87
+ warn: (message: string, fields: Record<string, string>) => void;
88
+ /** Test seam for the resolver itself. */
89
+ resolve?: typeof resolveTurnGitHubRepositoryBindings;
90
+ /** Test seam for the per-session warning dedupe memo. */
91
+ warningCache?: GitHubRepositoryLookupCache;
92
+ now?: () => number;
93
+ };
94
+ /**
95
+ * The run.ts wiring in one testable seam: skip for a Connected Machine,
96
+ * proceed bare when resolution throws, stamp both the turn and runtime
97
+ * resource lists from one resolution, and publish a bound-but-unusable
98
+ * warning once per session and URI within the memo window (the resolution
99
+ * itself already runs once per attempt).
100
+ */
101
+ export declare function applyTurnGitHubRepositoryBindings(input: ApplyTurnGitHubRepositoryBindingsInput): Promise<{
102
+ turnResources: ResourceRef[];
103
+ runtimeResources: ResourceRef[];
104
+ }>;
105
+ export {};
@@ -0,0 +1,66 @@
1
+ import { materializeRigVersionForAttempt } from "@opengeni/db";
2
+ import { renderWorkspaceGovernanceContext, type OpenGeniRuntime } from "@opengeni/runtime";
3
+ import { type Settings } from "@opengeni/config";
4
+ import { resolveWorkspacePackRuntime, resolveWorkspaceInstalledSkillRuntime } from "../packs.js";
5
+ import { createModelHistoryAttachmentProjector } from "../run-input.js";
6
+ import type { TurnActivityServices as ActivityServices, RunAgentTurnInput, RunAgentTurnResult } from "../types.js";
7
+ import { buildCompanyBrainContributionReceipt } from "../../model-context-contributions.js";
8
+ import { createTurnMediaArtifacts } from "./media-artifacts.js";
9
+ import { lazyToolTransportForTurn, openAiHostedImageProviderBindingForTurn, modelAttachmentInputPolicyForTurn } from "./tool-policy.js";
10
+ import type { ClaimTurnOk } from "./claim.js";
11
+ import type { EventingState, WorkspaceRefState } from "./turn-context.js";
12
+ export type GovernanceModelDeps = {
13
+ input: RunAgentTurnInput;
14
+ db: ActivityServices["db"];
15
+ runtime: ActivityServices["runtime"];
16
+ objectStorage: ActivityServices["objectStorage"];
17
+ eventing: EventingState;
18
+ workspaceRefs: WorkspaceRefState;
19
+ media: ReturnType<typeof createTurnMediaArtifacts>;
20
+ turn: ClaimTurnOk["turn"];
21
+ session: ClaimTurnOk["session"];
22
+ capabilitySettings: ClaimTurnOk["capabilitySettings"];
23
+ fileAuthoritySubjectId: ClaimTurnOk["fileAuthoritySubjectId"];
24
+ humanInputResume: ClaimTurnOk["humanInputResume"];
25
+ turnExecutionPolicy: ClaimTurnOk["turnExecutionPolicy"];
26
+ requiredGeneratedVideoFiles: Array<{
27
+ operationId: string;
28
+ artifactId: string;
29
+ fileId: string;
30
+ objectKey: string;
31
+ sizeBytes: number;
32
+ sha256: string;
33
+ filename: string;
34
+ }>;
35
+ };
36
+ export type GovernanceModelOk = {
37
+ runtimePreparationStartedAt: number;
38
+ packRuntime: Awaited<ReturnType<typeof resolveWorkspacePackRuntime>>;
39
+ installedSkillRuntime: Awaited<ReturnType<typeof resolveWorkspaceInstalledSkillRuntime>>;
40
+ rigVersion: NonNullable<Awaited<ReturnType<typeof materializeRigVersionForAttempt>>>["version"] | null;
41
+ rigName: string | null;
42
+ agentHumanInputEnabled: boolean;
43
+ workspaceAgentInstructions: string | null | undefined;
44
+ workspaceGovernance: ReturnType<typeof renderWorkspaceGovernanceContext>;
45
+ structuredWorkspacePolicyActive: boolean;
46
+ workspaceMemory: string | null | undefined;
47
+ buildCompanyBrainContributionReceiptFor: (skillActivations: Parameters<typeof buildCompanyBrainContributionReceipt>[0]["skillActivations"]) => ReturnType<typeof buildCompanyBrainContributionReceipt>;
48
+ logicalSandboxSettings: Settings;
49
+ verifiedRigProviderImageId: string | undefined;
50
+ runSettings: Settings;
51
+ resolvedModel: ReturnType<OpenGeniRuntime["resolveTurnModel"]>;
52
+ providerApi: NonNullable<ReturnType<OpenGeniRuntime["resolveTurnModel"]>>["provider"]["api"] | "responses";
53
+ nativeImageProviderBinding: ReturnType<typeof openAiHostedImageProviderBindingForTurn>;
54
+ lazyToolTransport: ReturnType<typeof lazyToolTransportForTurn>;
55
+ modelInputPolicy: ReturnType<typeof modelAttachmentInputPolicyForTurn>;
56
+ supportsImageInput: boolean;
57
+ modelHistoryProjector: (items: Array<Record<string, unknown>>, projectionOptions?: Parameters<ReturnType<typeof createModelHistoryAttachmentProjector>>[1]) => Promise<Array<Record<string, unknown>>>;
58
+ generatedImageHistoryProjector: (items: Array<Record<string, unknown>>) => Promise<Array<Record<string, unknown>>>;
59
+ compactionModelHistoryProjector: (items: Array<Record<string, unknown>>) => Promise<Array<Record<string, unknown>>>;
60
+ };
61
+ export type GovernanceModelOutcome = {
62
+ exit: RunAgentTurnResult;
63
+ } | {
64
+ ok: GovernanceModelOk;
65
+ };
66
+ export declare function prepareGovernanceAndModel(deps: GovernanceModelDeps): Promise<GovernanceModelOutcome>;
@@ -0,0 +1,52 @@
1
+ import { type OpenGeniRuntime } from "@opengeni/runtime";
2
+ import type { Settings } from "@opengeni/config";
3
+ import type { SharedActivityServices } from "../types.js";
4
+ import type { turnInput } from "../run-input.js";
5
+ import type { TurnMediaArtifacts } from "./media-artifacts.js";
6
+ export type TurnHistorySinkDeps = {
7
+ db: SharedActivityServices["db"];
8
+ accountId: string;
9
+ workspaceId: string;
10
+ sessionId: string;
11
+ attemptId: string;
12
+ media: TurnMediaArtifacts;
13
+ getTurnId: () => string | undefined;
14
+ getStream: () => Awaited<ReturnType<OpenGeniRuntime["runStream"]>> | undefined;
15
+ getModelRunSettings: () => Settings;
16
+ getExecutionGeneration: () => number;
17
+ };
18
+ /**
19
+ * Dual-write of conversation truth (issue #35): completed items are reconciled
20
+ * into session_history_items after every model response and at every turn-end
21
+ * path (idempotent on position), and the sandbox recovery envelope is upserted
22
+ * alongside. Best-effort by design: persistence problems must never fail the
23
+ * run.
24
+ *
25
+ * Orphaned-tool-output guard: `stream.state.history` is NOT a plain
26
+ * append-only array — it is a computed getter
27
+ * (`getTurnInput(originalInput, generatedItems)`) that runs the SDK's
28
+ * `dropOrphanToolCalls` on every access, so a `function_call` with no settling
29
+ * result yet is transiently ABSENT from history and a later reconcile sees a
30
+ * DIFFERENT, shorter/reordered list. A blind length watermark with
31
+ * onConflictDoNothing-on-position then freezes the first shape of a position
32
+ * and can persist a `function_call_result` at a tail position while its
33
+ * `function_call` was pruned away in an earlier slice and never written — the
34
+ * orphan that bricks the session. We defend against it at the stream boundary
35
+ * with the turn-scoped pending-tool ledger. A partial parallel batch records
36
+ * raw results but does not call this reconciler. Once every registered call has
37
+ * a result, the SDK history is stable and this scalar append watermark is valid
38
+ * again. The sanitizer remains the final call/result pairing guard for every
39
+ * other reconcile.
40
+ */
41
+ export declare class TurnHistorySink {
42
+ private readonly deps;
43
+ persistedHistoryCount: number;
44
+ nextHistoryPosition: number;
45
+ providerArtifactCandidates: Awaited<ReturnType<typeof turnInput>>["providerArtifactCandidates"];
46
+ constructor(deps: TurnHistorySinkDeps);
47
+ reconcileConversationTruth: (options?: {
48
+ skipInputOnlyRows?: boolean;
49
+ requireDurable?: boolean;
50
+ }) => Promise<void>;
51
+ }
52
+ export declare function createTurnHistorySink(deps: TurnHistorySinkDeps): TurnHistorySink;
@@ -0,0 +1,63 @@
1
+ export declare function historyRowsToAppend(rawHistory: Array<Record<string, unknown>>, persistedHistoryCount: number, nextPosition?: number, toolOutputTruncationTokens?: number): {
2
+ rows: Array<{
3
+ position: number;
4
+ item: Record<string, unknown>;
5
+ }>;
6
+ nextWatermark: number;
7
+ nextPosition: number;
8
+ };
9
+ /** Select only opaque rows that participated in the provider's rejected wire request. */
10
+ export declare function selectRejectedProviderArtifactHistoryIds(activeHistory: ReadonlyArray<{
11
+ id: string;
12
+ item: Record<string, unknown>;
13
+ providerArtifactInvalidatedAt: Date | null;
14
+ }>, candidates: {
15
+ knownHistoryItemIds: readonly string[];
16
+ historyItemIds: readonly string[];
17
+ }, wireFingerprints: readonly string[]): string[];
18
+ /** Literal final per-call boundary for replayed and current-turn model input. */
19
+ export declare function isModelOrToolProgressHistoryItem(item: Record<string, unknown>): boolean;
20
+ /**
21
+ * Resolve the EFFECTIVE/active compute backend a turn should gate
22
+ * filesystem-touching agent lifecycle hooks on (today: the repository clone).
23
+ *
24
+ * WHY (Case B — clone-onto-real-disk hazard): a session keeps its CLOUD HOME
25
+ * backend (`settings.sandboxBackend`, e.g. "modal") but its ACTIVE sandbox may
26
+ * have been swapped to a connected machine (`active_sandbox_id` → a selfhosted
27
+ * lease). `runtime.buildAgent`'s repository-clone hook keys off the backend it is
28
+ * told; if the worker passes nothing it defaults to the HOME backend and the hook
29
+ * would `git clone` a private GitHub-App repo onto the user's REAL disk — a
30
+ * bring-your-own machine owns its own filesystem and must NEVER be cloned onto. So
31
+ * we look at where the agent ACTUALLY runs, not where the session was created.
32
+ *
33
+ * Returns "selfhosted" ONLY when the selfhosted feature is on AND the session has
34
+ * a non-null active pointer whose sandbox `kind` is "selfhosted". Otherwise
35
+ * returns undefined so buildAgent falls back to the home backend — byte-for-byte
36
+ * unchanged cloud behavior.
37
+ *
38
+ * Total + best-effort by contract: it NEVER throws (a lookup failure is logged and
39
+ * falls back to the home default), so wiring it at turn start can't fail the turn.
40
+ * The DB I/O is injected (the real call site passes readActiveSandbox + getSandbox,
41
+ * the same helpers wrapTurnBoxWithRouting reuses) so the gate/decision/safety
42
+ * contract is unit-testable without a live database.
43
+ */
44
+ export declare function pendingToolCallFromSdkEvent(event: unknown): {
45
+ callId: string;
46
+ callType: string;
47
+ callName: string | null;
48
+ callItem: Record<string, unknown>;
49
+ } | null;
50
+ /** Tools whose intentional visual result must survive inline-media sanitization. */
51
+ export declare function toolCallProducesRetainableSessionImage(name: string | null): boolean;
52
+ export declare function completedToolCallFromSdkEvent(event: unknown): {
53
+ callId: string;
54
+ resultItem: Record<string, unknown>;
55
+ } | null;
56
+ /**
57
+ * Budget/limit exhaustion detected between model calls. This is account
58
+ * state, not an agent failure: the segment ends gracefully (session idles,
59
+ * run state preserved) so a top-up or limit reset lets the same session
60
+ * continue — a failed session would reject the user's next message. An
61
+ * active goal pauses visibly (reason "limits") at the next continuation
62
+ * evaluation without consuming continuation budget.
63
+ */