@opengeni/worker-bundle 0.12.7 → 0.13.4
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.
- package/dist/activities/agent-turn.d.ts +778 -0
- package/dist/activities/capabilities.d.ts +18 -0
- package/dist/activities/codex-auth.d.ts +1 -0
- package/dist/activities/codex-capacity.d.ts +31 -0
- package/dist/activities/codex-fleet-shadow.d.ts +74 -0
- package/dist/activities/codex-rotation.d.ts +261 -0
- package/dist/activities/common.d.ts +17 -0
- package/dist/activities/context-compaction.d.ts +81 -0
- package/dist/activities/documents.d.ts +39 -0
- package/dist/activities/environment.d.ts +97 -0
- package/dist/activities/expiring-material-renewal.d.ts +38 -0
- package/dist/activities/file-upload-reaper.d.ts +25 -0
- package/dist/activities/git-credential-renewal.d.ts +41 -0
- package/dist/activities/goals.d.ts +16 -0
- package/dist/activities/mcp-credentials.d.ts +14 -0
- package/dist/activities/packs.d.ts +77 -0
- package/dist/activities/parent-wake.d.ts +54 -0
- package/dist/activities/recording.d.ts +90 -0
- package/dist/activities/redaction.d.ts +1 -0
- package/dist/activities/rig-verification.d.ts +131 -0
- package/dist/activities/run-credential-renewal.d.ts +28 -0
- package/dist/activities/run-credentials.d.ts +36 -0
- package/dist/activities/run-input.d.ts +106 -0
- package/dist/activities/sandbox-lease.d.ts +128 -0
- package/dist/activities/scheduled-tasks.d.ts +4 -0
- package/dist/activities/session-state.d.ts +39 -0
- package/dist/activities/streaming.d.ts +24 -0
- package/dist/activities/toolspace-token-renewal.d.ts +23 -0
- package/dist/activities/turn-attempt-fenced.d.ts +11 -0
- package/dist/activities/types.d.ts +240 -0
- package/dist/activities/workflow-wake.d.ts +15 -0
- package/dist/activities/workspace-capture.d.ts +105 -0
- package/dist/activities.d.ts +312 -0
- package/dist/concurrency.d.ts +19 -0
- package/dist/host-export-pump.d.ts +66 -0
- package/dist/host-export.d.ts +6 -67
- package/dist/http.d.ts +32 -0
- package/dist/index.d.ts +27 -388
- package/dist/index.js +2730 -1211
- package/dist/index.js.map +1 -1
- package/dist/observability-metrics.d.ts +200 -0
- package/dist/op-journal.d.ts +10 -0
- package/dist/sandbox-resume.d.ts +152 -0
- package/dist/sandbox-routing.d.ts +159 -0
- package/dist/worker-service-lifecycle.d.ts +20 -0
- package/dist/workflow-bundle.js +88 -20
- package/dist/workflows/activities.d.ts +27 -0
- package/dist/workflows/document-index.d.ts +41 -0
- package/dist/workflows/file-upload-reaper.d.ts +2 -0
- package/dist/workflows/rig-verification.d.ts +3 -0
- package/dist/workflows/sandbox-reaper.d.ts +1 -0
- package/dist/workflows/scheduled-tasks.d.ts +17 -0
- package/dist/workflows/session.d.ts +58 -0
- package/dist/workflows/workflow-wake.d.ts +3 -0
- package/dist/workflows.d.ts +7 -0
- package/package.json +13 -13
- package/src/activities/agent-turn.ts +874 -134
- package/src/activities/context-compaction.ts +265 -76
- package/src/activities/environment.ts +1 -0
- package/src/activities/goals.ts +14 -0
- package/src/activities/rig-verification.ts +2 -0
- package/src/activities/run-input.ts +18 -4
- package/src/activities/sandbox-lease.ts +787 -133
- package/src/activities/session-state.ts +56 -0
- package/src/activities/types.ts +21 -0
- package/src/activities/workspace-capture.ts +95 -4
- package/src/activities.ts +3 -0
- package/src/observability-metrics.ts +94 -0
- package/src/sandbox-resume.ts +383 -90
- package/src/sandbox-routing.ts +32 -10
- package/src/workflows/activities.ts +1 -0
- package/src/workflows/session.ts +70 -0
|
@@ -0,0 +1,778 @@
|
|
|
1
|
+
import { type AppendEventInput, type ActiveSandboxPointer, type SandboxRecord } from "@opengeni/db";
|
|
2
|
+
import { modelResponseServiceTierFromSdkEvent, modelResponseUsageFromSdkEvent, type SandboxFileDownload, type ComputerToolMode, type ModelResponseUsage, type ModelCallUsageInput, type ModelCallUsageNormalization, type RunAgentStreamOptions, type TurnToolCancellationFence, type BackendUnresolvableCode } from "@opengeni/runtime";
|
|
3
|
+
import { resolveTurnExecutionPolicyV1, type ModelUsageInput, type ModelProviderApi, type RegistryProviderKind, type Settings } from "@opengeni/config";
|
|
4
|
+
import { ApplicationFailure, CancelledFailure } from "@temporalio/activity";
|
|
5
|
+
import type { CodexAccountStatus } from "@opengeni/db";
|
|
6
|
+
import { type GitCredentialRenewalController } from "./git-credential-renewal";
|
|
7
|
+
import { type RunCredentialRenewalController } from "./run-credential-renewal";
|
|
8
|
+
import { type ToolspaceTokenRenewalController } from "./toolspace-token-renewal";
|
|
9
|
+
import { type SecretForRedaction } from "./redaction";
|
|
10
|
+
import { type TurnCodexAccount } from "./run-input";
|
|
11
|
+
import type { ActivityServices, EscapedMcpTimeoutRecoveryDetail, RunAgentTurnInput, RunAgentTurnResult, SessionAttemptQuiescenceProof } from "./types";
|
|
12
|
+
import { type TurnSandboxLeaseHolderId } from "../sandbox-resume";
|
|
13
|
+
import { type LatencyMode, type SessionEvent, type SessionEventType, type SessionTurn, type ToolAuthNeededPayload, type TurnExecutionPolicyV1, type TurnInitiator } from "@opengeni/contracts";
|
|
14
|
+
export declare const PROVIDER_BACKPRESSURE_DELAY_MS = 60000;
|
|
15
|
+
/** Personal connection authority follows the immutable human turn initiator, never the worker. */
|
|
16
|
+
export declare function credentialSubjectIdForTurnInitiator(initiator: Pick<TurnInitiator, "kind" | "subjectId">): string | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* Direct authenticated-human work is the persisted human source with subject
|
|
19
|
+
* authority and no inherited agent or legacy provenance. Use this complete
|
|
20
|
+
* immutable turn authority instead of inferring causality from a
|
|
21
|
+
* `user.message` event shape or the root initiator alone.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isDirectHumanTurnInitiation(turn: Pick<SessionTurn, "source" | "initiator" | "initiatorContext">): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* A disconnected personal Slack server is prepared best-effort before the model
|
|
26
|
+
* runs. Its initialize/tools-list credential miss is setup state, not evidence
|
|
27
|
+
* that an unrelated turn wants Slack. Keep concrete tool-call failures
|
|
28
|
+
* actionable, but gate setup-time Slack prompts to a human message that names
|
|
29
|
+
* Slack explicitly. Other providers retain the existing generic behavior.
|
|
30
|
+
*/
|
|
31
|
+
export declare function shouldPublishToolAuthNeededForTurn(payload: Pick<ToolAuthNeededPayload, "providerDomain" | "toolName">, trigger: Pick<SessionEvent, "type" | "payload">, turn: Pick<SessionTurn, "source" | "initiator" | "initiatorContext">): boolean;
|
|
32
|
+
export declare function turnExecutionPolicyBillingIdentity(policy: TurnExecutionPolicyV1): {
|
|
33
|
+
externallyBilled: boolean;
|
|
34
|
+
codexSubscription: boolean;
|
|
35
|
+
};
|
|
36
|
+
export declare function legacyTurnExecutionPolicyInput(turn: Pick<SessionTurn, "source" | "model" | "reasoningEffort" | "latencyMode">): Parameters<typeof resolveTurnExecutionPolicyV1>[1];
|
|
37
|
+
/** A retryable provider fault recovers the accepted turn itself. Goal state is
|
|
38
|
+
* irrelevant: autonomous continuation and infrastructure recovery are separate
|
|
39
|
+
* concerns. */
|
|
40
|
+
export declare function providerRecoveryResult(): {
|
|
41
|
+
status: "recovering";
|
|
42
|
+
continueDelayMs: number;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Tell the model when durable MCP policy references are unavailable for this
|
|
46
|
+
* exact turn. The policy projection already bounds and validates these ids;
|
|
47
|
+
* this notice prevents a graceful runtime drop from becoming a silent source-
|
|
48
|
+
* of-truth substitution or a false claim that the disconnected system was read.
|
|
49
|
+
*/
|
|
50
|
+
export declare function unavailableMcpTurnInstructions(input: {
|
|
51
|
+
droppedIds: readonly string[];
|
|
52
|
+
droppedCount: number;
|
|
53
|
+
}): string | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* Preserve one precise recovery obligation across Temporal's activity boundary.
|
|
56
|
+
* This is intentionally narrower than the ordinary retryable-provider path:
|
|
57
|
+
* only a recovered turn (generation > 1) whose MCP timeout happened before a
|
|
58
|
+
* model request may ask the workflow's DB-only control activity to finish the
|
|
59
|
+
* same-turn checkpoint. The original transport/recovery errors are excluded
|
|
60
|
+
* from details so raw MCP response data can never enter workflow history.
|
|
61
|
+
*/
|
|
62
|
+
export declare function escapedMcpTimeoutRecoveryFailure(input: {
|
|
63
|
+
failureCode: string | undefined;
|
|
64
|
+
modelRequestStarted: boolean;
|
|
65
|
+
detail: EscapedMcpTimeoutRecoveryDetail;
|
|
66
|
+
}): ApplicationFailure | null;
|
|
67
|
+
/**
|
|
68
|
+
* Resolve which Codex account a turn runs on (multi-account P1): session-pin >
|
|
69
|
+
* workspace-active. No rotation in P1. The selected id must still be in the
|
|
70
|
+
* connected set — a disconnected pin was FK-nulled, so a stale id can't appear,
|
|
71
|
+
* but we guard anyway. Returns null when there is no usable account (the turn
|
|
72
|
+
* then fails with the existing relogin error path).
|
|
73
|
+
*/
|
|
74
|
+
export declare function selectCodexCredentialForTurn(args: {
|
|
75
|
+
sessionPinnedCredentialId: string | null;
|
|
76
|
+
activeCredentialId: string | null;
|
|
77
|
+
connectedIds: Set<string>;
|
|
78
|
+
}): string | null;
|
|
79
|
+
export declare function filterUnmaterializedSandboxFileDownloads(downloads: SandboxFileDownload[], materializedFileIds: Set<string>): SandboxFileDownload[];
|
|
80
|
+
/** Fixed-length one-way tenant correlation for metrics/alerts; never a raw id. */
|
|
81
|
+
export declare function codexWorkspaceMetricKey(workspaceId: string): string;
|
|
82
|
+
/** Stable public request identity across partial resumes and activity retries. */
|
|
83
|
+
export declare function stableHumanInputRequestId(sessionId: string, turnId: string, toolCallId: string): string;
|
|
84
|
+
/**
|
|
85
|
+
* True when this activity attempt was cancelled because its hosting worker is
|
|
86
|
+
* shutting down gracefully (SIGTERM during a deploy), as opposed to a
|
|
87
|
+
* workflow-requested Pause/Steer cancellation or a server-side timeout.
|
|
88
|
+
*/
|
|
89
|
+
export declare function isWorkerShutdownCancellation(error: unknown): boolean;
|
|
90
|
+
/**
|
|
91
|
+
* Review captures and protective snapshots are cache/persistence housekeeping,
|
|
92
|
+
* never part of cancellation correctness. A control-fenced or Temporal-cancelled
|
|
93
|
+
* attempt must release its physical activity promptly so Steer/Pause can advance.
|
|
94
|
+
*/
|
|
95
|
+
export declare function shouldRunTurnEndWorkspacePersistence(input: {
|
|
96
|
+
activityStatus: RunAgentTurnResult["status"] | "unknown";
|
|
97
|
+
cancellationRequested: boolean;
|
|
98
|
+
}): boolean;
|
|
99
|
+
/**
|
|
100
|
+
* Temporal cancellation is delivery/transport state, never proof that the
|
|
101
|
+
* dying activity crossed its mandatory sandbox-tool fence. If that fence
|
|
102
|
+
* fails, surface the fence failure instead of retaining a misleading typed
|
|
103
|
+
* cancellation; replacement admission remains closed because no durable
|
|
104
|
+
* quiescence receipt was written.
|
|
105
|
+
*/
|
|
106
|
+
export declare function assertPhysicalToolQuiescenceForCancellation(input: {
|
|
107
|
+
acknowledgeQuiescence: boolean;
|
|
108
|
+
physicalToolQuiescenceConfirmed: boolean;
|
|
109
|
+
failure: unknown;
|
|
110
|
+
}): void;
|
|
111
|
+
/** A physically drained attempt must leave one durable recovery producer. The
|
|
112
|
+
* direct Postgres receipt is preferred; after its bounded retries exhaust, an
|
|
113
|
+
* exact Temporal proof signal is sufficient because the workflow persists it
|
|
114
|
+
* through an independently retrying DB-only control activity. */
|
|
115
|
+
export declare function assertSessionAttemptQuiescenceRecoveryDurable(input: {
|
|
116
|
+
acknowledgeQuiescence: boolean;
|
|
117
|
+
physicalToolQuiescenceConfirmed: boolean;
|
|
118
|
+
receiptOrProofDurable: boolean;
|
|
119
|
+
failure: unknown;
|
|
120
|
+
}): void;
|
|
121
|
+
/** Persist the authoritative receipt or durably hand the exact physical proof
|
|
122
|
+
* to Temporal. This retries signal delivery, not DB eligibility or workflow
|
|
123
|
+
* state. The proof object never changes between attempts. */
|
|
124
|
+
export declare function persistOrSignalSessionAttemptQuiescence(input: {
|
|
125
|
+
proof: SessionAttemptQuiescenceProof;
|
|
126
|
+
persistReceipt: () => Promise<SessionEvent[]>;
|
|
127
|
+
publishEvents: (events: SessionEvent[]) => Promise<unknown>;
|
|
128
|
+
signalProof: ActivityServices["signalSessionAttemptQuiesced"];
|
|
129
|
+
sleep?: (ms: number) => Promise<void>;
|
|
130
|
+
heartbeat?: (attempt: number, delayMs: number) => void;
|
|
131
|
+
onReceiptFailure?: (error: unknown) => void;
|
|
132
|
+
onPublishFailure?: (error: unknown) => void;
|
|
133
|
+
onSignalFailure?: (error: unknown, attempt: number, delayMs: number) => void;
|
|
134
|
+
}): Promise<"receipt" | "signal">;
|
|
135
|
+
/**
|
|
136
|
+
* Cross the non-detachable physical boundary for one dying attempt. Temporal's
|
|
137
|
+
* cancellation signal is intentionally absent: cancellation is transport, not
|
|
138
|
+
* proof that sandbox tools and attempt-owned credential writers have drained.
|
|
139
|
+
* A replacement may be admitted only after this function resolves and the
|
|
140
|
+
* caller durably persists or signals the exact quiescence receipt.
|
|
141
|
+
*/
|
|
142
|
+
export declare function drainAttemptOwnedSandboxWriters(input: {
|
|
143
|
+
toolCancellationFence: Pick<TurnToolCancellationFence, "cancel" | "waitForQuiescence"> | null;
|
|
144
|
+
cancellationReason?: unknown;
|
|
145
|
+
gitCredentialRenewals: readonly Pick<GitCredentialRenewalController, "stop">[];
|
|
146
|
+
toolspaceTokenRenewal: Pick<ToolspaceTokenRenewalController, "stop"> | null;
|
|
147
|
+
runCredentialRenewal: Pick<RunCredentialRenewalController, "stop"> | null;
|
|
148
|
+
}): Promise<void>;
|
|
149
|
+
/**
|
|
150
|
+
* Await a finalizer operation only while this Temporal activity still owns its
|
|
151
|
+
* execution window. Once Pause/Steer cancellation arrives, the operation keeps
|
|
152
|
+
* its own rejection handler and may finish its idempotent, attempt-scoped
|
|
153
|
+
* cleanup in the background, but it cannot pin activity terminalization or
|
|
154
|
+
* delay the separately receipt-gated replacement dispatch.
|
|
155
|
+
*/
|
|
156
|
+
export declare function waitForTurnFinalizerStep<T>(operation: Promise<T>, signal: AbortSignal | undefined): Promise<T | undefined>;
|
|
157
|
+
/**
|
|
158
|
+
* Flush provider-facing stream state while the attempt still owns its activity
|
|
159
|
+
* window. On Pause/Steer, both promises are detached with rejection handlers:
|
|
160
|
+
* neither a runtime batcher nor an uncooperative provider completion promise
|
|
161
|
+
* may pin the activity behind cancellation after durable writes are fenced.
|
|
162
|
+
*/
|
|
163
|
+
export declare function waitForTurnStreamCleanup(batcherFlush: Promise<unknown>, providerCompleted: Promise<unknown>, signal: AbortSignal | undefined): Promise<void>;
|
|
164
|
+
export type SafeErrorDiagnostic = {
|
|
165
|
+
name: string;
|
|
166
|
+
message: string;
|
|
167
|
+
status?: number;
|
|
168
|
+
code?: string;
|
|
169
|
+
};
|
|
170
|
+
/**
|
|
171
|
+
* Produce the only exception shape allowed in worker logs. It deliberately
|
|
172
|
+
* excludes stack, cause, response/request bodies, and arbitrary enumerable
|
|
173
|
+
* properties while retaining bounded, redacted diagnostics.
|
|
174
|
+
*/
|
|
175
|
+
export declare function safeErrorDiagnostic(error: unknown, redactText?: (value: string) => string): SafeErrorDiagnostic;
|
|
176
|
+
export declare function headerSecretRedactions(prefix: string, headers: Readonly<Record<string, string>> | undefined, credentialHeaderNames?: Iterable<string>): SecretForRedaction[];
|
|
177
|
+
export declare function shouldRecoverCompactionProviderFailure(error: unknown): boolean;
|
|
178
|
+
export declare function classifyContextWindowOverflowError(error: unknown): {
|
|
179
|
+
message: string;
|
|
180
|
+
code?: string;
|
|
181
|
+
detail?: string;
|
|
182
|
+
} | null;
|
|
183
|
+
/**
|
|
184
|
+
* Recognize an MCP transport/request timeout that escaped the SDK's per-tool
|
|
185
|
+
* `mcpConfig.errorFunction` boundary. A thrown tool invocation is normally
|
|
186
|
+
* converted to an `{isError:true}` tool output; however, connect/tools-list or
|
|
187
|
+
* next-loop transport work can reject the stream iterator after a prior tool
|
|
188
|
+
* output was already published. That is transient external backpressure, not a
|
|
189
|
+
* terminal session error. Match MCP-qualified timeout text only: an unrelated
|
|
190
|
+
* sandbox/model timeout and MCP's application-defined Authentication required signal must
|
|
191
|
+
* retain their existing semantics.
|
|
192
|
+
*/
|
|
193
|
+
export declare function classifyMcpTransportTimeoutError(error: unknown): {
|
|
194
|
+
message: string;
|
|
195
|
+
detail?: string;
|
|
196
|
+
} | null;
|
|
197
|
+
/**
|
|
198
|
+
* Compute the conversation-truth rows a reconcile pass should append, given the
|
|
199
|
+
* SDK's current `state.history` and the count already persisted.
|
|
200
|
+
*
|
|
201
|
+
* `state.history` is a computed getter that runs the SDK's orphan-tool-call
|
|
202
|
+
* pruning on every access, so it is non-monotonic: a `function_call` with no
|
|
203
|
+
* settling result yet is transiently absent and a later access yields a
|
|
204
|
+
* different, possibly shorter/reordered list. The old code sliced this list by
|
|
205
|
+
* a blind length watermark and appended at fixed positions with
|
|
206
|
+
* onConflictDoNothing, which could freeze a position with one shape and later
|
|
207
|
+
* persist a `function_call_result` whose `function_call` had been pruned away in
|
|
208
|
+
* an earlier slice — the orphaned tool output that 400s the Responses API and
|
|
209
|
+
* bricks the session on every replay.
|
|
210
|
+
*
|
|
211
|
+
* Defending: sanitize the full current history into an API-valid sequence (the
|
|
212
|
+
* same pure rules the read path uses), then append only the new tail beyond the
|
|
213
|
+
* watermark. A trailing dangling call is dropped here and re-evaluated next
|
|
214
|
+
* pass once its result lands, so a call and its result are written together at
|
|
215
|
+
* consecutive positions and a result is never persisted without its call. The
|
|
216
|
+
* watermark advances to the sanitized length — never past anything unwritten —
|
|
217
|
+
* so a non-monotonic history can never desync it. When previously-persisted
|
|
218
|
+
* rows already exceed the sanitized length (e.g. legacy orphans written before
|
|
219
|
+
* this fix), nothing new is appended and the watermark holds steady.
|
|
220
|
+
*/
|
|
221
|
+
/**
|
|
222
|
+
* Stable+unique usage source key for one model call, used to build the per-call
|
|
223
|
+
* idempotency key (`usage:model.tokens:${turnId}:${sourceKey}`). The turnId is
|
|
224
|
+
* shared across a new attempt of the SAME turn (recovery, approval
|
|
225
|
+
* rerun, activity retry), so the sourceKey alone must distinguish calls.
|
|
226
|
+
*
|
|
227
|
+
* - A provider responseId is globally stable+unique, so reuse it verbatim: a
|
|
228
|
+
* true activity retry that re-emits the same responseId correctly DEDUPES
|
|
229
|
+
* (one charge), while two distinct calls get distinct ids.
|
|
230
|
+
* - Without a responseId the old synthesized key was only POSITIONAL ("response-1",
|
|
231
|
+
* "aggregate"), which collides across a re-dispatch — dispatch B's first
|
|
232
|
+
* call reuses dispatch A's "response-1" key and its charge is silently
|
|
233
|
+
* dropped (undercharge). Qualifying the synthesized key with the
|
|
234
|
+
* per-execution dispatch id (the Temporal activityId, unique per scheduled
|
|
235
|
+
* execution) makes re-dispatched calls distinct while still deduping a
|
|
236
|
+
* same-execution retry.
|
|
237
|
+
*/
|
|
238
|
+
export declare function modelUsageSourceKey(input: {
|
|
239
|
+
responseId?: string | null | undefined;
|
|
240
|
+
dispatchId: string | null;
|
|
241
|
+
positionalKey: string;
|
|
242
|
+
}): string;
|
|
243
|
+
export declare function providerContextTokens(usage: {
|
|
244
|
+
inputTokens?: number;
|
|
245
|
+
outputTokens?: number;
|
|
246
|
+
totalTokens?: number;
|
|
247
|
+
} | null | undefined): number | null;
|
|
248
|
+
/**
|
|
249
|
+
* A provider call has already consumed tokens by the time its usage frame is
|
|
250
|
+
* available. Losing the Codex credential lease at the renewal checkpoint must
|
|
251
|
+
* stop the result from becoming authoritative, but it must not erase accounting
|
|
252
|
+
* truth for the call that already happened. Meter first, then surface the lost
|
|
253
|
+
* lease, then write attempt-owned token/context signals. A replaced attempt can
|
|
254
|
+
* reject those signals without erasing the provider usage already incurred.
|
|
255
|
+
*/
|
|
256
|
+
export declare function recordCompletedModelCallBeforeOwnershipFences(input: {
|
|
257
|
+
renewLease: () => Promise<void>;
|
|
258
|
+
recordUsage: () => Promise<void>;
|
|
259
|
+
leaseLost: () => boolean;
|
|
260
|
+
leaseLostMessage: string;
|
|
261
|
+
recordAttemptSignals?: () => Promise<void>;
|
|
262
|
+
}): Promise<void>;
|
|
263
|
+
type TurnEventPublisher = (events: Array<Omit<AppendEventInput, "producerId" | "producerSeq" | "turnId">>, immediate?: boolean) => Promise<{
|
|
264
|
+
events: SessionEvent[];
|
|
265
|
+
accepted: boolean;
|
|
266
|
+
}>;
|
|
267
|
+
export type ModelResponseUsageEventState = {
|
|
268
|
+
responseUsageCount: number;
|
|
269
|
+
providerContextRevision: number;
|
|
270
|
+
lastProviderContextTokensObserved: number | null;
|
|
271
|
+
claimedSourceKeys: Set<string>;
|
|
272
|
+
};
|
|
273
|
+
export type CompactionModelUsageEventState = {
|
|
274
|
+
usageCount: number;
|
|
275
|
+
claimedSourceKeys: Set<string>;
|
|
276
|
+
};
|
|
277
|
+
export declare function createModelResponseUsageEventState(claimedSourceKeys?: Set<string>): ModelResponseUsageEventState;
|
|
278
|
+
export declare function createCompactionModelUsageEventState(claimedSourceKeys?: Set<string>): CompactionModelUsageEventState;
|
|
279
|
+
export declare function modelResponseUsageContextSignal(state: ModelResponseUsageEventState): {
|
|
280
|
+
revision: number;
|
|
281
|
+
totalTokens: number;
|
|
282
|
+
} | null;
|
|
283
|
+
export declare function assertModelResponseLatencyMode(input: {
|
|
284
|
+
event: Parameters<typeof modelResponseServiceTierFromSdkEvent>[0];
|
|
285
|
+
requested: LatencyMode;
|
|
286
|
+
model: string;
|
|
287
|
+
/** When set to Codex ChatGPT auth, response `service_tier` is not an honor signal. */
|
|
288
|
+
providerId?: string;
|
|
289
|
+
}): void;
|
|
290
|
+
/**
|
|
291
|
+
* Process one SDK stream event through the exact production usage path.
|
|
292
|
+
*
|
|
293
|
+
* The pinned Responses SDK mirrors one provider terminal response as both a
|
|
294
|
+
* normalized `response_done` and a raw `model/response.completed` event. Claim
|
|
295
|
+
* the stable response/source key before lease renewal or any usage side effect,
|
|
296
|
+
* and advance the positional ordinal only for a newly claimed response. The
|
|
297
|
+
* durable `agent.model.usage` source-key fence remains the cross-restart
|
|
298
|
+
* authority: a replay may retry the idempotent billing write, but it cannot
|
|
299
|
+
* advance process-local metrics, provider context, or attempt-owned signals.
|
|
300
|
+
*/
|
|
301
|
+
export declare function processModelResponseUsageEvent(input: {
|
|
302
|
+
event: Parameters<typeof modelResponseUsageFromSdkEvent>[0];
|
|
303
|
+
state: ModelResponseUsageEventState;
|
|
304
|
+
dispatchId: string | null;
|
|
305
|
+
settings: Settings;
|
|
306
|
+
db: ActivityServices["db"];
|
|
307
|
+
observability: ActivityServices["observability"];
|
|
308
|
+
publish: TurnEventPublisher | null;
|
|
309
|
+
accountId: string;
|
|
310
|
+
workspaceId: string;
|
|
311
|
+
sessionId: string;
|
|
312
|
+
turnId: string;
|
|
313
|
+
turnAttemptId: string;
|
|
314
|
+
provider: string;
|
|
315
|
+
providerApi: ModelProviderApi;
|
|
316
|
+
model: string;
|
|
317
|
+
latencyMode?: LatencyMode;
|
|
318
|
+
metricProvider: string;
|
|
319
|
+
externallyBilled: boolean;
|
|
320
|
+
servingCredentialId: string | null;
|
|
321
|
+
priorSessionCredentialId: string | null;
|
|
322
|
+
emittedSourceKeys: Set<string>;
|
|
323
|
+
renewLease: () => Promise<void>;
|
|
324
|
+
leaseLost: () => boolean;
|
|
325
|
+
leaseLostMessage: string;
|
|
326
|
+
setLastInputTokens: (tokens: number) => Promise<void>;
|
|
327
|
+
}): Promise<{
|
|
328
|
+
status: "not_usage";
|
|
329
|
+
} | {
|
|
330
|
+
status: "duplicate";
|
|
331
|
+
sourceKey: string;
|
|
332
|
+
} | {
|
|
333
|
+
status: "processed";
|
|
334
|
+
sourceKey: string;
|
|
335
|
+
authoritative: boolean;
|
|
336
|
+
}>;
|
|
337
|
+
/**
|
|
338
|
+
* Apply the same source-key authority ordering to the compaction summarizer's
|
|
339
|
+
* usage callback. The summarizer can retry or mirror a terminal response just
|
|
340
|
+
* like the main stream, so claim before lease renewal, billing, durable usage,
|
|
341
|
+
* logging, or cache metrics. Durable source-key idempotency remains the
|
|
342
|
+
* cross-process authority after a worker restart.
|
|
343
|
+
*/
|
|
344
|
+
export declare function processCompactionModelUsageEvent(input: {
|
|
345
|
+
usage: ModelResponseUsage;
|
|
346
|
+
state: CompactionModelUsageEventState;
|
|
347
|
+
dispatchId: string | null;
|
|
348
|
+
settings: Settings;
|
|
349
|
+
db: ActivityServices["db"];
|
|
350
|
+
observability: ActivityServices["observability"];
|
|
351
|
+
publish: TurnEventPublisher | null;
|
|
352
|
+
accountId: string;
|
|
353
|
+
workspaceId: string;
|
|
354
|
+
sessionId: string;
|
|
355
|
+
turnId: string;
|
|
356
|
+
turnAttemptId: string;
|
|
357
|
+
provider: string;
|
|
358
|
+
providerApi: ModelProviderApi;
|
|
359
|
+
model: string;
|
|
360
|
+
externallyBilled: boolean;
|
|
361
|
+
servingCredentialId: string | null;
|
|
362
|
+
priorSessionCredentialId: string | null;
|
|
363
|
+
emittedSourceKeys: Set<string>;
|
|
364
|
+
renewLease: () => Promise<void>;
|
|
365
|
+
leaseLost: () => boolean;
|
|
366
|
+
leaseLostMessage: string;
|
|
367
|
+
}): Promise<{
|
|
368
|
+
status: "duplicate";
|
|
369
|
+
sourceKey: string;
|
|
370
|
+
} | {
|
|
371
|
+
status: "processed";
|
|
372
|
+
sourceKey: string;
|
|
373
|
+
authoritative: boolean;
|
|
374
|
+
}>;
|
|
375
|
+
export declare function emitModelCallUsage(input: {
|
|
376
|
+
observability: ActivityServices["observability"];
|
|
377
|
+
publish: TurnEventPublisher | null;
|
|
378
|
+
accountId: string;
|
|
379
|
+
workspaceId: string;
|
|
380
|
+
sessionId: string;
|
|
381
|
+
turnId: string;
|
|
382
|
+
provider: string;
|
|
383
|
+
providerApi: ModelProviderApi;
|
|
384
|
+
model: string;
|
|
385
|
+
sourceKey: string;
|
|
386
|
+
usage: ModelResponseUsage | {
|
|
387
|
+
usage?: unknown | null;
|
|
388
|
+
} | null;
|
|
389
|
+
normalizedUsage?: ModelCallUsageNormalization;
|
|
390
|
+
servingAccountHash?: string;
|
|
391
|
+
accountChangedFromPrevCall?: boolean;
|
|
392
|
+
emittedSourceKeys?: Set<string>;
|
|
393
|
+
}): Promise<boolean>;
|
|
394
|
+
/**
|
|
395
|
+
* Apply one authoritative, normalized model-call usage frame to the shared
|
|
396
|
+
* prompt-cache metrics. The durable source-key fence in `emitModelCallUsage`
|
|
397
|
+
* owns idempotency; this helper must never receive raw provider values.
|
|
398
|
+
*/
|
|
399
|
+
export declare function applyCodexCacheTelemetry(observability: ActivityServices["observability"], provider: string, normalizedUsage: ModelCallUsageNormalization): void;
|
|
400
|
+
export declare function historyRowsToAppend(rawHistory: Array<Record<string, unknown>>, persistedHistoryCount: number, nextPosition?: number, toolOutputTruncationTokens?: number, redactValue?: (value: unknown) => unknown): {
|
|
401
|
+
rows: Array<{
|
|
402
|
+
position: number;
|
|
403
|
+
item: Record<string, unknown>;
|
|
404
|
+
}>;
|
|
405
|
+
nextWatermark: number;
|
|
406
|
+
nextPosition: number;
|
|
407
|
+
};
|
|
408
|
+
/** Literal final per-call boundary for replayed and current-turn model input. */
|
|
409
|
+
export declare function secretRedactionModelInputFilter(redactValue: (value: unknown) => unknown): NonNullable<RunAgentStreamOptions["callModelInputFilter"]>;
|
|
410
|
+
/**
|
|
411
|
+
* Seed the turn-end reconcile watermark (`persistedHistoryCount`) from EXACTLY the
|
|
412
|
+
* view `state.history` was seeded from, so the model-input length and the watermark
|
|
413
|
+
* can NEVER disagree. The watermark is the slice index the reconcile cuts the
|
|
414
|
+
* (re-sanitized) `state.history` at to find this turn's genuinely-new items, so it
|
|
415
|
+
* must equal the length of `state.history`'s already-persisted leading prefix.
|
|
416
|
+
*
|
|
417
|
+
* The cross-account reasoning strip drops foreign reasoning items, so the prefix
|
|
418
|
+
* length is PATH-DEPENDENT, captured by `modelHistoryFromItems`:
|
|
419
|
+
*
|
|
420
|
+
* - items read path (`modelHistoryFromItems === true`) — `state.history` was seeded
|
|
421
|
+
* from the cross-account-STRIPPED active items (foreign reasoning DROPPED), so it
|
|
422
|
+
* starts K shorter than the raw active-row count. Seed from the SAME strip
|
|
423
|
+
* (HOLE D); seeding from the un-stripped count would slice K genuinely-new items
|
|
424
|
+
* off the reconcile and silently lose them (incl. the user's switch-turn message).
|
|
425
|
+
*
|
|
426
|
+
* - approval RunState path (`modelHistoryFromItems === false`) — `state.history` was seeded
|
|
427
|
+
* from the blob, where foreign reasoning is NEUTRALIZED-IN-PLACE (the item is
|
|
428
|
+
* KEPT, only its id/encrypted_content go — see resumeRunStateForCodexAccount), so
|
|
429
|
+
* the blob's history length still COUNTS those items. Applying the strip here
|
|
430
|
+
* under-counts by K and the reconcile re-appends K already-persisted items at
|
|
431
|
+
* fresh positions — HOLE E. So the blob path must NOT strip: count the raw
|
|
432
|
+
* sanitized active length, which mirrors the blob's completed prefix.
|
|
433
|
+
*
|
|
434
|
+
* On a same-account / non-codex turn the strip is a no-op, so both branches reduce
|
|
435
|
+
* to the same raw sanitized count (byte-identical to the pre-strip behaviour).
|
|
436
|
+
* Pure; exported for unit testing the D/E seed invariant.
|
|
437
|
+
*/
|
|
438
|
+
export declare function reconcileSeedCount(activeSeedRows: ReadonlyArray<{
|
|
439
|
+
item: Record<string, unknown>;
|
|
440
|
+
producerCodexCredentialId: string | null;
|
|
441
|
+
}>, modelHistoryFromItems: boolean, current: TurnCodexAccount): number;
|
|
442
|
+
/**
|
|
443
|
+
* Resolve the EFFECTIVE/active compute backend a turn should gate
|
|
444
|
+
* filesystem-touching agent lifecycle hooks on (today: the repository clone).
|
|
445
|
+
*
|
|
446
|
+
* WHY (Case B — clone-onto-real-disk hazard): a session keeps its CLOUD HOME
|
|
447
|
+
* backend (`settings.sandboxBackend`, e.g. "modal") but its ACTIVE sandbox may
|
|
448
|
+
* have been swapped to a connected machine (`active_sandbox_id` → a selfhosted
|
|
449
|
+
* lease). `runtime.buildAgent`'s repository-clone hook keys off the backend it is
|
|
450
|
+
* told; if the worker passes nothing it defaults to the HOME backend and the hook
|
|
451
|
+
* would `git clone` a private GitHub-App repo onto the user's REAL disk — a
|
|
452
|
+
* bring-your-own machine owns its own filesystem and must NEVER be cloned onto. So
|
|
453
|
+
* we look at where the agent ACTUALLY runs, not where the session was created.
|
|
454
|
+
*
|
|
455
|
+
* Returns "selfhosted" ONLY when the selfhosted feature is on AND the session has
|
|
456
|
+
* a non-null active pointer whose sandbox `kind` is "selfhosted". Otherwise
|
|
457
|
+
* returns undefined so buildAgent falls back to the home backend — byte-for-byte
|
|
458
|
+
* unchanged cloud behavior.
|
|
459
|
+
*
|
|
460
|
+
* Total + best-effort by contract: it NEVER throws (a lookup failure is logged and
|
|
461
|
+
* falls back to the home default), so wiring it at turn start can't fail the turn.
|
|
462
|
+
* The DB I/O is injected (the real call site passes readActiveSandbox + getSandbox,
|
|
463
|
+
* the same helpers wrapTurnBoxWithRouting reuses) so the gate/decision/safety
|
|
464
|
+
* contract is unit-testable without a live database.
|
|
465
|
+
*/
|
|
466
|
+
export declare function resolveActiveSandboxBackend(routingOn: boolean, loadPointer: () => Promise<{
|
|
467
|
+
activeSandboxId: string | null;
|
|
468
|
+
} | null>, loadSandboxKind: (sandboxId: string) => Promise<string | null>): Promise<Settings["sandboxBackend"] | undefined>;
|
|
469
|
+
/**
|
|
470
|
+
* Managed-sandbox ownership exists only when this turn actually uses the
|
|
471
|
+
* managed home. A Connected Machine is fenced by its active-route epoch and
|
|
472
|
+
* must remain independent from cloud recovery state for the same session.
|
|
473
|
+
*/
|
|
474
|
+
export declare function managedSandboxOwnershipForTurn(machinePrimary: boolean, attemptId: string, sandboxGroupId: string): {
|
|
475
|
+
holderId: TurnSandboxLeaseHolderId;
|
|
476
|
+
sandboxGroupId: string;
|
|
477
|
+
} | null;
|
|
478
|
+
/**
|
|
479
|
+
* Classify a persisted active-sandbox pointer for TURN-START RECONCILE (issue #341
|
|
480
|
+
* invariant B). Returns the typed reason to RESET the pointer to the session HOME,
|
|
481
|
+
* or null to leave it in place. STRUCTURAL unestablishability only:
|
|
482
|
+
* - no record → the pointed-at sandbox row is gone (`stale_pointer`);
|
|
483
|
+
* - an unestablishable kind (a non-group Modal sibling, or an unknown backend) per
|
|
484
|
+
* the SHARED `swapTargetEstablishability` predicate (`unsupported_backend_context`);
|
|
485
|
+
* - a selfhosted sandbox with no enrollment id to address (`offline_enrollment`).
|
|
486
|
+
* A selfhosted sandbox WITH an enrollment is deliberately left in place even when it
|
|
487
|
+
* is momentarily offline: the machine may recover mid-turn and its ops surface
|
|
488
|
+
* agent_offline lazily, so the user's explicit machine target is never abandoned for
|
|
489
|
+
* a transient control-plane blip (that is #339's concern, not this one).
|
|
490
|
+
*/
|
|
491
|
+
export declare function pointerReconcileReason(record: {
|
|
492
|
+
kind: string;
|
|
493
|
+
enrollmentId: string | null;
|
|
494
|
+
} | null): BackendUnresolvableCode | null;
|
|
495
|
+
/** The active pointer + its sandbox row, loaded once at turn start and threaded
|
|
496
|
+
* through the reconcile so the establish branch reads the SAME (possibly reset)
|
|
497
|
+
* values with no second query. */
|
|
498
|
+
export type LoadedActivePointer = {
|
|
499
|
+
pointer: ActiveSandboxPointer | null;
|
|
500
|
+
record: SandboxRecord | null;
|
|
501
|
+
};
|
|
502
|
+
/**
|
|
503
|
+
* TURN-START RECONCILE (issue #341 invariant B / Shapes 1+2). If the persisted pointer's
|
|
504
|
+
* target is STRUCTURALLY unestablishable ({@link pointerReconcileReason}) reset the pointer
|
|
505
|
+
* to the session HOME (null) under the epoch fence, emit a VISIBLE `session.route.reconciled`
|
|
506
|
+
* event, and return the reconciled pointer/record so the rest of the turn runs on home. NEVER
|
|
507
|
+
* a silent downgrade. Bounded to ONE attempt: a lost CAS means a concurrent user swap won a
|
|
508
|
+
* higher epoch, so re-read + honor it rather than clobber a newer, user-directed pointer. The
|
|
509
|
+
* event publish is best-effort — a publish failure never fails the turn.
|
|
510
|
+
*
|
|
511
|
+
* FAIL-OPEN on a lookup failure (issue #341 review): the sandbox row is fetched HERE via the
|
|
512
|
+
* caller's NON-swallowing `loadRecord`, so a null decision means the row is genuinely absent,
|
|
513
|
+
* never a suppressed transient DB error. If `loadRecord` THROWS, reconciliation is skipped
|
|
514
|
+
* entirely this turn — the pointer is left UNTOUCHED (record null → the turn runs
|
|
515
|
+
* machinePrimary:false on the group box exactly as before reconcile existed), no CAS, no
|
|
516
|
+
* event — and the next turn retries. A TRANSIENT LOOKUP FAILURE MUST NEVER MUTATE THE POINTER.
|
|
517
|
+
*/
|
|
518
|
+
export declare function reconcileActiveSandboxPointer(db: ActivityServices["db"], ids: {
|
|
519
|
+
accountId: string;
|
|
520
|
+
workspaceId: string;
|
|
521
|
+
sessionId: string;
|
|
522
|
+
}, pointer: ActiveSandboxPointer | null, loadRecord: (sandboxId: string) => Promise<SandboxRecord | null>, publish?: (events: Array<{
|
|
523
|
+
type: SessionEventType;
|
|
524
|
+
payload: unknown;
|
|
525
|
+
}>) => Promise<void> | void): Promise<LoadedActivePointer>;
|
|
526
|
+
/**
|
|
527
|
+
* Warm the Modal private-registry image for the image ref this turn actually
|
|
528
|
+
* resolved, not only the deployment-global OPENGENI_MODAL_IMAGE_REF warmed at
|
|
529
|
+
* worker boot. Packs can override `modalImageRef` per workspace/turn, so a
|
|
530
|
+
* private pack image must be resolved before sandbox creation or Modal falls
|
|
531
|
+
* back to the unauthenticated `fromTag` path.
|
|
532
|
+
*/
|
|
533
|
+
export declare function ensureTurnModalRegistryImage(runSettings: Settings, sandboxCreationBackend: Settings["sandboxBackend"] | undefined, ensureRegistryImage?: (settings: Settings) => Promise<void>): Promise<void>;
|
|
534
|
+
/**
|
|
535
|
+
* Decide whether the first actual computer action may start a proof recording.
|
|
536
|
+
*
|
|
537
|
+
* On-turn recording runs ffmpeg/x11grab INSIDE the box and reads the .mp4 back
|
|
538
|
+
* out of the box's /tmp — plumbing that exists only for OpenGeni-operated cloud
|
|
539
|
+
* boxes (the Modal desktop backend). A turn whose EFFECTIVE backend is a connected
|
|
540
|
+
* machine ("selfhosted") runs on the user's REAL computer, which has none of that
|
|
541
|
+
* capture plumbing (and the platform must never shell ffmpeg onto a user's machine
|
|
542
|
+
* — the same reason the runtime skips its setup hooks for selfhosted). Left ungated
|
|
543
|
+
* it films nothing, finds no /tmp file, and emits recording.started followed by
|
|
544
|
+
* recording.failed{box-death} on EVERY machine-primary turn — misleading timeline
|
|
545
|
+
* noise + wasted work. So gate it off, exactly like a recording-disabled deployment:
|
|
546
|
+
* skip silently, emit nothing (no new event shape).
|
|
547
|
+
*
|
|
548
|
+
* `effectiveBackend` is the resolved ACTIVE backend for the turn
|
|
549
|
+
* (resolveActiveSandboxBackend) — NOT the session's home backend. A modal-home
|
|
550
|
+
* session actively swapped onto a machine resolves to "selfhosted" here and
|
|
551
|
+
* correctly skips; a machine-home turn that degraded back to its cloud group box
|
|
552
|
+
* (swap-away / flag-off) resolves to undefined and records as before.
|
|
553
|
+
*
|
|
554
|
+
* EDGE — mid-turn swap: this is evaluated once when computer-use first runs. A swap
|
|
555
|
+
* after recording starts is deliberately ignored; the partial recording already has
|
|
556
|
+
* defined failure semantics, so there is no stop/restart machinery.
|
|
557
|
+
*/
|
|
558
|
+
export declare function shouldStartOnTurnRecording(params: {
|
|
559
|
+
recordingEnabled: boolean;
|
|
560
|
+
desktopEnabled: boolean;
|
|
561
|
+
establishedBackendId: string;
|
|
562
|
+
effectiveBackend: Settings["sandboxBackend"] | undefined;
|
|
563
|
+
}): boolean;
|
|
564
|
+
/**
|
|
565
|
+
* Decide the EXPLICIT computer-use tool transport for THIS turn.
|
|
566
|
+
*
|
|
567
|
+
* The runtime's SDK-mirrored capability would otherwise pick hosted-vs-function
|
|
568
|
+
* tools by string-sniffing the bound model instance's constructor name for
|
|
569
|
+
* "ChatCompletions" (supportsStructuredToolOutputTransport). That is fragile: a
|
|
570
|
+
* wrapped / proxied / minified model instance defeats the sniff and a
|
|
571
|
+
* chat-completions provider would silently get the HOSTED `computer_use_preview`
|
|
572
|
+
* tool it 400s on every turn. So the mode is decided HERE — the worker's model
|
|
573
|
+
* resolution is the ONE place a provider's true wire identity is authoritative —
|
|
574
|
+
* and threaded to the runtime as an explicit flag (buildAgent → computerToolMode):
|
|
575
|
+
* • codex-subscription → "function-image": the ChatGPT/Codex backend rejects
|
|
576
|
+
* hosted tool types but SEES structured `input_image` tool results.
|
|
577
|
+
* • a "chat" (OpenAIChatCompletionsModel wire) provider → "disabled": it cannot
|
|
578
|
+
* receive a screenshot through a proven visual transport, so computer use fails
|
|
579
|
+
* closed instead of serializing the image as text.
|
|
580
|
+
* • everything else — built-in Azure/OpenAI responses, registry "responses"
|
|
581
|
+
* providers, AND the LEGACY global-client fallback (resolveTurnModel returned
|
|
582
|
+
* null) — → "hosted": real Responses hosted-tool support.
|
|
583
|
+
*
|
|
584
|
+
* Pure + exported so the mapping is unit-testable without a live turn.
|
|
585
|
+
*/
|
|
586
|
+
export declare function computerToolModeForTurn(resolvedModel: {
|
|
587
|
+
provider: {
|
|
588
|
+
kind: RegistryProviderKind;
|
|
589
|
+
api: ModelProviderApi;
|
|
590
|
+
};
|
|
591
|
+
} | null): ComputerToolMode;
|
|
592
|
+
/**
|
|
593
|
+
* Native web search is a runtime capability, not part of the session's MCP
|
|
594
|
+
* allow-list. Attach it whenever the resolved provider advertises runnable
|
|
595
|
+
* support. The null model is the legacy built-in Responses path, whose
|
|
596
|
+
* deployment flag is its provider capability gate. There is deliberately no
|
|
597
|
+
* cross-provider or sandbox/curl fallback.
|
|
598
|
+
*/
|
|
599
|
+
export declare function hostedWebSearchForTurn(resolvedModel: {
|
|
600
|
+
configured: {
|
|
601
|
+
hostedWebSearch: boolean;
|
|
602
|
+
};
|
|
603
|
+
} | null, deploymentWebSearchEnabled: boolean): boolean;
|
|
604
|
+
/**
|
|
605
|
+
* Decide whether this turn's provider accepts typed file/image content in a
|
|
606
|
+
* user message. The legacy built-in client and registry Responses clients use
|
|
607
|
+
* the Agents SDK Responses converter, which supports `input_image` and
|
|
608
|
+
* `input_file`. Chat-completions providers retain the sandbox-path projection
|
|
609
|
+
* until that transport declares and proves an equivalent capability.
|
|
610
|
+
*/
|
|
611
|
+
export declare function modelAcceptsTypedAttachmentContentForTurn(resolvedModel: {
|
|
612
|
+
provider: {
|
|
613
|
+
api: ModelProviderApi;
|
|
614
|
+
};
|
|
615
|
+
} | null): boolean;
|
|
616
|
+
export type TurnSandboxProvisioner<T> = {
|
|
617
|
+
get(): Promise<T>;
|
|
618
|
+
hasStarted(): boolean;
|
|
619
|
+
waitForSettled(timeoutMs: number): Promise<T | null>;
|
|
620
|
+
};
|
|
621
|
+
export declare class TurnOperationCancelledError extends Error {
|
|
622
|
+
readonly reason: unknown;
|
|
623
|
+
readonly name = "TurnOperationCancelledError";
|
|
624
|
+
constructor(reason: unknown);
|
|
625
|
+
}
|
|
626
|
+
export declare class SandboxDeadlineRotationError extends Error {
|
|
627
|
+
readonly sandboxGroupId: string;
|
|
628
|
+
readonly leaseEpoch: number;
|
|
629
|
+
readonly name = "SandboxDeadlineRotationError";
|
|
630
|
+
constructor(sandboxGroupId: string, leaseEpoch: number);
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Normalize a preparation/provisioning cancellation race back to the Temporal
|
|
634
|
+
* cancellation that owns the activity. Several provider APIs expose no portable
|
|
635
|
+
* abort primitive, so the worker stops awaiting them and disposes any late
|
|
636
|
+
* resource. The wrapper error must never fall through as an ordinary turn
|
|
637
|
+
* failure: doing so would omit the quiescence receipt and strand a committed
|
|
638
|
+
* Steer/Pause behind `control-pending`.
|
|
639
|
+
*/
|
|
640
|
+
export declare function turnOperationCancellationFailure(error: unknown): CancelledFailure | null;
|
|
641
|
+
export declare function waitForTurnOperation<T>(operation: Promise<T>, signal: AbortSignal | undefined, disposeLateResult: ((result: T) => Promise<void> | void) | undefined): Promise<T>;
|
|
642
|
+
export declare function isLazySandboxProvisionRetryable(error: unknown): boolean;
|
|
643
|
+
/**
|
|
644
|
+
* Deadline recovery cannot re-admit the same turn until the global reaper has
|
|
645
|
+
* observed the released holder, captured the final archive, terminated the old
|
|
646
|
+
* provider box, and committed the lease cold. Give that full sequence one
|
|
647
|
+
* snapshot budget plus two schedule periods. This is workflow-visible pacing,
|
|
648
|
+
* not an in-memory sleep, so Pause/Steer/new user intent can still wake the
|
|
649
|
+
* durable session immediately.
|
|
650
|
+
*/
|
|
651
|
+
export declare function sandboxDeadlineRotationRecoveryDelayMs(settings: Pick<Settings, "sandboxLeaseReaperPeriodMs" | "sandboxSnapshotTimeoutMs">): number;
|
|
652
|
+
export declare function createTurnSandboxProvisioner<T>(establish: () => Promise<T>, options?: {
|
|
653
|
+
maxRetries?: number;
|
|
654
|
+
backoffMs?: number;
|
|
655
|
+
signal?: AbortSignal;
|
|
656
|
+
onStarted?: () => Promise<void> | void;
|
|
657
|
+
onCompleted?: (result: T) => Promise<void> | void;
|
|
658
|
+
onFailed?: (error: unknown) => Promise<void> | void;
|
|
659
|
+
disposeResult?: (result: T) => Promise<void> | void;
|
|
660
|
+
}): TurnSandboxProvisioner<T>;
|
|
661
|
+
/**
|
|
662
|
+
* Decide whether THIS turn may send OpenAI's `prompt_cache_key` request field.
|
|
663
|
+
*
|
|
664
|
+
* Accepted transports:
|
|
665
|
+
* - legacy/built-in OpenAI or Azure Responses fallback (resolvedModel null);
|
|
666
|
+
* - resolved built-in OpenAI/Azure providers;
|
|
667
|
+
* - ChatGPT/Codex subscription backend (its strict allowlist permits the field).
|
|
668
|
+
*
|
|
669
|
+
* Registry API-key providers are intentionally excluded. Fireworks' prompt-cache
|
|
670
|
+
* docs prescribe `user` or `x-session-affinity`, not `prompt_cache_key`; Z.AI/GLM
|
|
671
|
+
* documents automatic context caching plus `user_id`. Sending OpenAI-only fields
|
|
672
|
+
* to unknown OpenAI-compatible providers risks unsupported-parameter 400s.
|
|
673
|
+
*/
|
|
674
|
+
export declare function acceptsPromptCacheKeyForTurn(resolvedModel: {
|
|
675
|
+
provider: {
|
|
676
|
+
kind: RegistryProviderKind;
|
|
677
|
+
builtin?: boolean;
|
|
678
|
+
};
|
|
679
|
+
} | null): boolean;
|
|
680
|
+
/**
|
|
681
|
+
* True once the lifetime last confirmed by Postgres is no longer trustworthy.
|
|
682
|
+
* A missing or malformed deadline fails closed for a holder that claims to be
|
|
683
|
+
* leased; callers check this before accepting an in-flight heartbeat promise.
|
|
684
|
+
*/
|
|
685
|
+
export declare function codexCredentialLeaseDeadlineExpired(confirmedUntilMs: number | null, nowMs?: number): boolean;
|
|
686
|
+
export declare function createRunAgentTurnActivity(services: () => Promise<ActivityServices>): (input: RunAgentTurnInput) => Promise<RunAgentTurnResult>;
|
|
687
|
+
export declare function isTransientProviderError(error: unknown): boolean;
|
|
688
|
+
export declare function agentRunFailurePayload(error: unknown, options?: {
|
|
689
|
+
isCodexTurn?: boolean;
|
|
690
|
+
}): {
|
|
691
|
+
error: string;
|
|
692
|
+
code?: string;
|
|
693
|
+
retryable?: boolean;
|
|
694
|
+
detail?: string;
|
|
695
|
+
timeoutClass?: string;
|
|
696
|
+
responseObserved?: boolean;
|
|
697
|
+
requestId?: string;
|
|
698
|
+
correlationId?: string;
|
|
699
|
+
stage?: string;
|
|
700
|
+
sqlState?: string | null;
|
|
701
|
+
attempts?: number;
|
|
702
|
+
retryOutcome?: string;
|
|
703
|
+
database?: Record<string, string>;
|
|
704
|
+
};
|
|
705
|
+
export type CodexCredentialFailure = {
|
|
706
|
+
kind: "auth" | "forbidden" | "rate_limit" | "quota";
|
|
707
|
+
cooldownSeconds: number | null;
|
|
708
|
+
};
|
|
709
|
+
export declare const CODEX_ALLOWANCE_FALLBACK_MS: number;
|
|
710
|
+
/**
|
|
711
|
+
* Resolve a deterministic quarantine end. Generic request throttling honors
|
|
712
|
+
* provider retry-after (or one minute); allowance/quota refusal waits for the
|
|
713
|
+
* LAST of provider reset and every still-binding cached window (five-hour and
|
|
714
|
+
* weekly both bind), falling back to one complete five-hour window when no reset
|
|
715
|
+
* metadata exists.
|
|
716
|
+
*/
|
|
717
|
+
export declare function codexCredentialCooldownUntil(failure: CodexCredentialFailure, account: Pick<CodexAccountStatus, "primaryUsedPercent" | "primaryResetAt" | "secondaryUsedPercent" | "secondaryResetAt"> | null, now: Date): Date | null;
|
|
718
|
+
/**
|
|
719
|
+
* Only definitive credential/account refusals are safe rotation signals.
|
|
720
|
+
* Ambiguous network failures, malformed/partial streams, invalid model content,
|
|
721
|
+
* prompt 4xx, and provider 5xx may already have consumed tokens or persisted
|
|
722
|
+
* progress and therefore MUST NOT walk the credential pool automatically.
|
|
723
|
+
*/
|
|
724
|
+
export declare function classifyCodexCredentialFailure(error: unknown): CodexCredentialFailure | null;
|
|
725
|
+
/** Humanize a seconds duration into a short "2h 5m" / "9m" / "in under a minute" string. */
|
|
726
|
+
export declare function humanizeResetWindow(resetsInSeconds: number | null): string;
|
|
727
|
+
/**
|
|
728
|
+
* Build the turn.failed payload for a ChatGPT/Codex usage cap: a precise,
|
|
729
|
+
* actionable message naming the reset window, the stable `codex_usage_limit_reached`
|
|
730
|
+
* code, and retryable:false (an auto-retry would just re-hit the cap).
|
|
731
|
+
*/
|
|
732
|
+
export declare function codexUsageLimitFailurePayload(info: {
|
|
733
|
+
resetsInSeconds: number | null;
|
|
734
|
+
}, detail: string, opts?: {
|
|
735
|
+
allAccounts?: boolean;
|
|
736
|
+
}): {
|
|
737
|
+
error: string;
|
|
738
|
+
code: string;
|
|
739
|
+
retryable: boolean;
|
|
740
|
+
detail?: string;
|
|
741
|
+
};
|
|
742
|
+
export declare function ensureRunAllowed(settings: Settings, db: ActivityServices["db"], accountId: string, workspaceId: string, isExternallyBilledTurn: boolean, entitlements?: ActivityServices["entitlements"]): Promise<void>;
|
|
743
|
+
export type ModelUsageBillingRecord = {
|
|
744
|
+
billingPath: "opengeni_credits" | "external";
|
|
745
|
+
/** Same quantity written to usage_events.model.cost when present; else 0. */
|
|
746
|
+
pricedCostMicros: number;
|
|
747
|
+
normalizedUsage: ModelCallUsageNormalization;
|
|
748
|
+
};
|
|
749
|
+
export declare function recordModelUsageAndDebitCredits(settings: Settings, db: ActivityServices["db"], input: {
|
|
750
|
+
accountId: string;
|
|
751
|
+
workspaceId: string;
|
|
752
|
+
sessionId: string;
|
|
753
|
+
turnId: string;
|
|
754
|
+
turnAttemptId: string;
|
|
755
|
+
model: string;
|
|
756
|
+
externallyBilled: boolean;
|
|
757
|
+
usage?: ModelUsageInput | ModelCallUsageInput | null;
|
|
758
|
+
normalizedUsage?: ModelCallUsageNormalization;
|
|
759
|
+
sourceKey: string;
|
|
760
|
+
latencyMode?: LatencyMode;
|
|
761
|
+
observability?: ActivityServices["observability"];
|
|
762
|
+
}): Promise<ModelUsageBillingRecord | null>;
|
|
763
|
+
/** Soft-fail Insights fact write — never throws into the billing/emit path. */
|
|
764
|
+
export declare function recordAuthoritativeModelCallFact(input: {
|
|
765
|
+
db: ActivityServices["db"];
|
|
766
|
+
observability: ActivityServices["observability"];
|
|
767
|
+
accountId: string;
|
|
768
|
+
workspaceId: string;
|
|
769
|
+
sessionId: string;
|
|
770
|
+
turnId: string;
|
|
771
|
+
turnAttemptId: string;
|
|
772
|
+
sourceKey: string;
|
|
773
|
+
provider: string;
|
|
774
|
+
providerApi: ModelProviderApi;
|
|
775
|
+
model: string;
|
|
776
|
+
billing: ModelUsageBillingRecord;
|
|
777
|
+
}): Promise<void>;
|
|
778
|
+
export {};
|