@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.
Files changed (72) hide show
  1. package/dist/activities/agent-turn.d.ts +778 -0
  2. package/dist/activities/capabilities.d.ts +18 -0
  3. package/dist/activities/codex-auth.d.ts +1 -0
  4. package/dist/activities/codex-capacity.d.ts +31 -0
  5. package/dist/activities/codex-fleet-shadow.d.ts +74 -0
  6. package/dist/activities/codex-rotation.d.ts +261 -0
  7. package/dist/activities/common.d.ts +17 -0
  8. package/dist/activities/context-compaction.d.ts +81 -0
  9. package/dist/activities/documents.d.ts +39 -0
  10. package/dist/activities/environment.d.ts +97 -0
  11. package/dist/activities/expiring-material-renewal.d.ts +38 -0
  12. package/dist/activities/file-upload-reaper.d.ts +25 -0
  13. package/dist/activities/git-credential-renewal.d.ts +41 -0
  14. package/dist/activities/goals.d.ts +16 -0
  15. package/dist/activities/mcp-credentials.d.ts +14 -0
  16. package/dist/activities/packs.d.ts +77 -0
  17. package/dist/activities/parent-wake.d.ts +54 -0
  18. package/dist/activities/recording.d.ts +90 -0
  19. package/dist/activities/redaction.d.ts +1 -0
  20. package/dist/activities/rig-verification.d.ts +131 -0
  21. package/dist/activities/run-credential-renewal.d.ts +28 -0
  22. package/dist/activities/run-credentials.d.ts +36 -0
  23. package/dist/activities/run-input.d.ts +106 -0
  24. package/dist/activities/sandbox-lease.d.ts +128 -0
  25. package/dist/activities/scheduled-tasks.d.ts +4 -0
  26. package/dist/activities/session-state.d.ts +39 -0
  27. package/dist/activities/streaming.d.ts +24 -0
  28. package/dist/activities/toolspace-token-renewal.d.ts +23 -0
  29. package/dist/activities/turn-attempt-fenced.d.ts +11 -0
  30. package/dist/activities/types.d.ts +240 -0
  31. package/dist/activities/workflow-wake.d.ts +15 -0
  32. package/dist/activities/workspace-capture.d.ts +105 -0
  33. package/dist/activities.d.ts +312 -0
  34. package/dist/concurrency.d.ts +19 -0
  35. package/dist/host-export-pump.d.ts +66 -0
  36. package/dist/host-export.d.ts +6 -67
  37. package/dist/http.d.ts +32 -0
  38. package/dist/index.d.ts +27 -388
  39. package/dist/index.js +2730 -1211
  40. package/dist/index.js.map +1 -1
  41. package/dist/observability-metrics.d.ts +200 -0
  42. package/dist/op-journal.d.ts +10 -0
  43. package/dist/sandbox-resume.d.ts +152 -0
  44. package/dist/sandbox-routing.d.ts +159 -0
  45. package/dist/worker-service-lifecycle.d.ts +20 -0
  46. package/dist/workflow-bundle.js +88 -20
  47. package/dist/workflows/activities.d.ts +27 -0
  48. package/dist/workflows/document-index.d.ts +41 -0
  49. package/dist/workflows/file-upload-reaper.d.ts +2 -0
  50. package/dist/workflows/rig-verification.d.ts +3 -0
  51. package/dist/workflows/sandbox-reaper.d.ts +1 -0
  52. package/dist/workflows/scheduled-tasks.d.ts +17 -0
  53. package/dist/workflows/session.d.ts +58 -0
  54. package/dist/workflows/workflow-wake.d.ts +3 -0
  55. package/dist/workflows.d.ts +7 -0
  56. package/package.json +13 -13
  57. package/src/activities/agent-turn.ts +874 -134
  58. package/src/activities/context-compaction.ts +265 -76
  59. package/src/activities/environment.ts +1 -0
  60. package/src/activities/goals.ts +14 -0
  61. package/src/activities/rig-verification.ts +2 -0
  62. package/src/activities/run-input.ts +18 -4
  63. package/src/activities/sandbox-lease.ts +787 -133
  64. package/src/activities/session-state.ts +56 -0
  65. package/src/activities/types.ts +21 -0
  66. package/src/activities/workspace-capture.ts +95 -4
  67. package/src/activities.ts +3 -0
  68. package/src/observability-metrics.ts +94 -0
  69. package/src/sandbox-resume.ts +383 -90
  70. package/src/sandbox-routing.ts +32 -10
  71. package/src/workflows/activities.ts +1 -0
  72. package/src/workflows/session.ts +70 -0
@@ -0,0 +1,18 @@
1
+ import { type Settings } from "@opengeni/config";
2
+ import { settingsWithEnabledCapabilityMcpServers } from "@opengeni/core";
3
+ import { type Database, type SessionMcpServerForRun } from "@opengeni/db";
4
+ export { settingsWithEnabledCapabilityMcpServers };
5
+ export declare function settingsWithSessionMcpServersForRun(db: Database, workspaceId: string, sessionId: string, attemptId: string, settings: Settings, options?: {
6
+ onResolvedServers?: (servers: readonly SessionMcpServerForRun[]) => void;
7
+ }): Promise<Settings>;
8
+ export declare function settingsWithSessionMcpServers(settings: Settings, servers: SessionMcpServerForRun[]): Settings;
9
+ /**
10
+ * When the workspace has an active Codex subscription connected and the feature
11
+ * is enabled, inject a synthetic "codex-subscription" registry provider so a
12
+ * `codex/<slug>` model id routes through the ChatGPT backend. No secrets touch
13
+ * this overlay (metadata-only read); the per-request bearer is resolved later via
14
+ * codexRequestStorage. Idempotent and a no-op when not applicable.
15
+ */
16
+ export declare function settingsWithCodexCredential(db: Database, workspaceId: string, settings: Settings, activeOverride?: boolean): Promise<Settings>;
17
+ /** Pure: append the synthetic codex-subscription provider, idempotently. */
18
+ export declare function withCodexProvider(settings: Settings): Settings;
@@ -0,0 +1 @@
1
+ export { buildCodexTokenResolver, type CodexAuthDeps } from "@opengeni/db";
@@ -0,0 +1,31 @@
1
+ import { reconcileCodexCapacityWait as reconcileCodexCapacityWaitDb, type CodexCapacityWakeTarget, type CodexCapacitySelectionContext } from "@opengeni/db";
2
+ import type { Settings } from "@opengeni/config";
3
+ import type { ActivityServices, GetCodexCapacityWaitInput, ReconcileCodexCapacityWaitInput, ReconcileCodexCapacityWaitResult } from "./types";
4
+ type CodexCapacitySignalServices = {
5
+ signalCodexCapacityWorkflow?: NonNullable<ActivityServices["signalCodexCapacityWorkflow"]> | null | undefined;
6
+ wakeSessionWorkflow: ActivityServices["wakeSessionWorkflow"];
7
+ };
8
+ /**
9
+ * Run a bounded set of usage refreshes, then repair every committed waiter
10
+ * revision even when an individual provider refresh failed. The database
11
+ * outbox remains authoritative; this helper only guarantees that every worker
12
+ * refresh path reaches the same post-commit delivery seam.
13
+ */
14
+ export declare function refreshCodexUsageAndRepairCapacityWaiters(refreshes: readonly (() => Promise<unknown>)[], repairPendingWakes: () => Promise<void>): Promise<void>;
15
+ /** Deliver committed waiter revisions; Postgres remains the repairable outbox. */
16
+ export declare function signalCodexCapacityWakeTargets(services: CodexCapacitySignalServices, targets: readonly CodexCapacityWakeTarget[]): Promise<void>;
17
+ /** Repair a commit/signal crash edge by redelivering every pending revision. */
18
+ export declare function signalPendingCodexCapacityWakeTargets(services: CodexCapacitySignalServices & {
19
+ db: ActivityServices["db"];
20
+ }, workspaceId: string): Promise<void>;
21
+ export declare function codexCapacityDecision(context: CodexCapacitySelectionContext, settings: Settings): ReturnType<Parameters<typeof reconcileCodexCapacityWaitDb>[2]>;
22
+ export declare function createCodexCapacityActivities(services: () => Promise<ActivityServices>): {
23
+ getCodexCapacityWait: (input: GetCodexCapacityWaitInput) => Promise<{
24
+ waiterId: string;
25
+ generation: number;
26
+ nextCheckAt: string;
27
+ wakeRevision: number;
28
+ } | null>;
29
+ reconcileCodexCapacityWait: (input: ReconcileCodexCapacityWaitInput) => Promise<ReconcileCodexCapacityWaitResult>;
30
+ };
31
+ export {};
@@ -0,0 +1,74 @@
1
+ import { type CodexFleetReplayRecordV1 } from "@opengeni/contracts";
2
+ import type { CodexLeaseAccountStatus } from "@opengeni/db";
3
+ export declare const CODEX_FLEET_SHADOW_MAX_PAYLOAD_BYTES: number;
4
+ export type CodexFleetActualDecisionV1 = {
5
+ outcome: "selected" | "waiting" | "none";
6
+ candidateKey: string | null;
7
+ reason: "lease_reused" | "pin" | "rotation" | "active" | "all_capped" | "none";
8
+ };
9
+ export type CodexFleetShadowComparisonV1 = "match" | "different_candidate" | "different_outcome" | "not_comparable_truncated";
10
+ export type CodexFleetShadowPayloadV1 = {
11
+ schemaVersion: 1;
12
+ mode: "shadow";
13
+ actual: CodexFleetActualDecisionV1;
14
+ comparison: CodexFleetShadowComparisonV1;
15
+ replay: CodexFleetReplayRecordV1;
16
+ };
17
+ export type CodexFleetShadowBuildInputV1 = {
18
+ accounts: readonly CodexLeaseAccountStatus[];
19
+ actualCredentialId: string | null;
20
+ actualOutcome: CodexFleetActualDecisionV1["outcome"];
21
+ actualReason: CodexFleetActualDecisionV1["reason"];
22
+ affinityCredentialId: string | null;
23
+ fencedInFlight: boolean;
24
+ nearExhaustionPct: number;
25
+ now: Date;
26
+ /** Per-event entropy used only to unlink account aliases; never persisted. */
27
+ aliasSeed: string;
28
+ };
29
+ export type CodexFleetShadowPublicationResultV1 = {
30
+ outcome: "disabled";
31
+ } | {
32
+ outcome: "published";
33
+ payload: CodexFleetShadowPayloadV1;
34
+ payloadBytes: number;
35
+ } | {
36
+ outcome: "failed";
37
+ stage: "build" | "serialize" | "publish";
38
+ reason: "payload_too_large" | "unexpected";
39
+ errorName: string;
40
+ payloadBytes: number | null;
41
+ };
42
+ export declare const CODEX_FLEET_SHADOW_DECISION_MAX_METRIC_SERIES: number;
43
+ export declare const CODEX_FLEET_SHADOW_ERROR_MAX_METRIC_SERIES: number;
44
+ /** Fixed low-cardinality labels; workspace/account/tenant identity is structurally absent. */
45
+ export declare function codexFleetShadowDecisionMetricLabelsV1(payload: CodexFleetShadowPayloadV1): {
46
+ readonly actual_outcome: "none" | "selected" | "waiting";
47
+ readonly shadow_outcome: "none" | "paced" | "selected";
48
+ readonly comparison: CodexFleetShadowComparisonV1;
49
+ readonly confidence: import("@opengeni/contracts").CodexFleetConfidence;
50
+ readonly truncated: "false" | "true";
51
+ };
52
+ export declare function codexFleetShadowErrorMetricLabelsV1(result: Extract<CodexFleetShadowPublicationResultV1, {
53
+ outcome: "failed";
54
+ }>): {
55
+ readonly stage: "build" | "publish" | "serialize";
56
+ readonly reason: "payload_too_large" | "unexpected";
57
+ };
58
+ /**
59
+ * Default-off, bounded, fail-open runtime seam for the shadow record.
60
+ *
61
+ * The typed result intentionally carries no error message: provider, database,
62
+ * or transport errors can include private metadata. Callers may count/log only
63
+ * the bounded stage, reason, name, and size fields returned here. A failure can
64
+ * never replace or clear the credential already selected by the allocator.
65
+ */
66
+ export declare function publishCodexFleetShadowDecisionV1(input: {
67
+ enabled: boolean;
68
+ decision: CodexFleetShadowBuildInputV1;
69
+ publish: (events: Array<{
70
+ type: "codex.fleet.decision";
71
+ payload: CodexFleetShadowPayloadV1;
72
+ }>) => Promise<unknown>;
73
+ }): Promise<CodexFleetShadowPublicationResultV1>;
74
+ export declare function buildCodexFleetShadowPayloadV1(input: CodexFleetShadowBuildInputV1): CodexFleetShadowPayloadV1;
@@ -0,0 +1,261 @@
1
+ import type { CodexAccountStatus, CodexCredentialLeaseSelectionContext, CodexLeaseAccountStatus, CodexPinSource } from "@opengeni/db";
2
+ export type CodexRotationAccount = CodexAccountStatus | CodexLeaseAccountStatus;
3
+ export type CodexRotationStrategy = "most_remaining" | "round_robin" | "drain_then_next" | "sharded";
4
+ /**
5
+ * The ONE strategy rotation-enabled workspaces run: sticky-sharded. The legacy
6
+ * strategies are all strictly dominated post-cache-affinity — session
7
+ * stickiness is worth ~half the prompt-cache hit rate, and round_robin /
8
+ * most_remaining churn accounts per turn while drain_then_next concentrates
9
+ * every concurrent session on ONE account (the measured concurrency-eviction
10
+ * failure sharding replaced). Stored `rotation_strategy` values are therefore
11
+ * NORMALIZED here at every read site: legacy values (and any future unknown
12
+ * string) behave as "sharded". The column and the legacy branch code are kept
13
+ * intact for old-binary rollback safety — they are simply unreachable through
14
+ * this normalization. The API accepts-but-ignores strategy writes for the same
15
+ * reason (no SDK caller breaks). User-facing choice is intentionally gone: the
16
+ * remaining real intents are rotation on/off, per-account allocator
17
+ * include/exclude, and manual pins — not algorithm selection.
18
+ */
19
+ export declare function effectiveRotationStrategy(_stored: string): CodexRotationStrategy;
20
+ /**
21
+ * How a session's codex pin governs THIS turn's account selection (pure). Encodes the
22
+ * policy-pin LIFECYCLE rule: a 'policy' pin is meaningful ONLY while the sharded policy
23
+ * is active.
24
+ * • "manual" — a manual pin: honored under EVERY strategy; never moved or cleared.
25
+ * • "sharded" — the sharded policy is active and the pin is non-manual: assign / keep
26
+ * / re-shard the deterministic home (covers an unpinned first turn AND
27
+ * an existing policy pin).
28
+ * • "clearStale" — a 'policy' pin while the sharded policy is NOT active: IGNORE it
29
+ * (never honor it as a sticky pin — that is the no-escape trap) and
30
+ * clear it lazily so the session converges to the active strategy.
31
+ * • "unpinned" — no pin (or none that applies): follow the active strategy / workspace
32
+ * active pointer, unchanged.
33
+ */
34
+ export type CodexPinDisposition = "manual" | "sharded" | "clearStale" | "unpinned";
35
+ /** Classify a session's codex pin against the active rotation regime (see {@link CodexPinDisposition}). */
36
+ export declare function classifyCodexPin(args: {
37
+ pinnedCredentialId: string | null;
38
+ pinSource: CodexPinSource | null;
39
+ strategy: CodexRotationStrategy;
40
+ rotationEnabled: boolean;
41
+ }): CodexPinDisposition;
42
+ export type RotationDecision = {
43
+ kind: "active";
44
+ credentialId: string;
45
+ moved: boolean;
46
+ droppedConnectors?: string[];
47
+ } | {
48
+ kind: "allCapped";
49
+ earliestResetAt: Date;
50
+ } | {
51
+ kind: "none";
52
+ };
53
+ export type CodexTurnLeaseSelection = {
54
+ credentialId: string | null;
55
+ decision: RotationDecision;
56
+ /** Policy/manual homes never move the workspace-global legacy pointer. */
57
+ advanceActivePointer?: boolean;
58
+ };
59
+ /** The minimum all-capped idle: continueDelayMs is clamped to at least this (never 0). */
60
+ export declare const MIN_IDLE_MS = 60000;
61
+ /**
62
+ * Cooldown applied to an exhausted account whose cached reset is null / unknown
63
+ * / already-elapsed (the turn hot path never refreshes usage, so a capped window's
64
+ * reset reads stale). Treating it as "available after a default cooldown" keeps
65
+ * availableAt — and therefore earliestReset — ALWAYS in the future.
66
+ */
67
+ export declare const DEFAULT_RESET_COOLDOWN_MS = 60000;
68
+ /** Cached provider usage becomes unavailable only at actual exhaustion. */
69
+ export declare const CODEX_USAGE_EXHAUSTED_PCT = 100;
70
+ /**
71
+ * Healthy for an already-frozen/in-flight turn = connected/usable (status
72
+ * "active", excludes needs_relogin/error), not cooling, and not exhausted in
73
+ * either provider window. Allocator eligibility is
74
+ * deliberately separate so disabling NEW work cannot break refresh/resume.
75
+ */
76
+ export declare function isCodexCredentialHealthy(acct: CodexRotationAccount, now: Date): boolean;
77
+ /** New automatic allocation requires both health and explicit allocator eligibility. */
78
+ export declare function isCodexCredentialEligible(acct: CodexRotationAccount, now: Date): boolean;
79
+ /**
80
+ * Public eligibility predicate (same definition as the private `eligible`): an
81
+ * account is usable this turn iff it is connected/active, not cooling, and below
82
+ * actual exhaustion on both windows. The worker's sharded home
83
+ * health-check uses this to decide whether a session's existing policy pin is still
84
+ * a valid home or must be re-sharded.
85
+ */
86
+ export declare function isCodexAccountEligible(acct: CodexRotationAccount, now: Date): boolean;
87
+ /**
88
+ * Session-sharded HOME account (AM-6): the deterministic account a session runs on
89
+ * under the "sharded" strategy — `stableAccountList[ hash(sessionId) % N ]` over the
90
+ * ELIGIBLE (connected, not cooling, not exhausted) accounts in stable created_at
91
+ * order (`listCodexAccountStatuses`).
92
+ *
93
+ * Why deterministic hash over "least-loaded by session count" (AM-6): it needs ZERO
94
+ * coordination — every worker computes the same home for a given (sessionId,
95
+ * eligible-set), so a burst of concurrent first-turns can't all read the same
96
+ * "least-loaded" account and stampede it (read-then-write skew), and there is no
97
+ * shared round-robin cursor to contend on. It is balanced in expectation.
98
+ *
99
+ * Re-shard (AM-5): pass the just-capped account as already-cooling (or simply let it
100
+ * fall over its threshold) and this reshuffles the SURVIVORS deterministically — the
101
+ * sessions that shared a capped account spread across the remaining pool by their own
102
+ * hashes instead of all re-concentrating on one first-eligible failover.
103
+ *
104
+ * Returns null when NO account is eligible (the caller idles until reset).
105
+ */
106
+ export declare function shardCredentialForSession(args: {
107
+ sessionId: string;
108
+ accounts: CodexRotationAccount[];
109
+ now: Date;
110
+ }): string | null;
111
+ /** earliestResetAt across ALL connected accounts — exported for the sharded all-capped idle. */
112
+ export declare function earliestCodexReset(accounts: CodexRotationAccount[], now: Date): Date;
113
+ /**
114
+ * The proactive SHARDED home decision (pure — zero I/O, like {@link chooseRotationActive}).
115
+ * Decides the account a session should run on THIS turn under the "sharded" strategy,
116
+ * given its current POLICY pin (null on the first turn) and the accounts snapshot:
117
+ *
118
+ * - keepPin: the current policy pin is still ELIGIBLE → run there, no rewrite. This
119
+ * is the steady-state cache-warm path (a session stays on its one home account).
120
+ * - reshard: no policy pin yet (first-turn lazy assignment, AM-7) OR the policy pin
121
+ * is capped/ineligible (proactive re-shard, AM-4) → deterministically shard over the
122
+ * ELIGIBLE set (AM-6) and durably (re)write the pin (`rewritePin:true`, AM-3/AM-5).
123
+ * - allCapped: no account is eligible → the caller idles until the earliest reset.
124
+ *
125
+ * A MANUAL pin is handled by the CALLER (it never reaches here); this function only
126
+ * governs policy homes. Pure so the assignment/re-shard/keep logic is unit-testable
127
+ * without a worker/db env; the caller wraps it with a self-heal usage refresh between
128
+ * two evaluations exactly like chooseRotationActive's allCapped path.
129
+ */
130
+ export declare function chooseShardedHome(args: {
131
+ sessionId: string;
132
+ currentPolicyPin: string | null;
133
+ accounts: CodexRotationAccount[];
134
+ now: Date;
135
+ }): {
136
+ kind: "home";
137
+ credentialId: string;
138
+ rewritePin: boolean;
139
+ } | {
140
+ kind: "allCapped";
141
+ earliestResetAt: Date;
142
+ };
143
+ /**
144
+ * The soonest instant `acct` clears EVERY blocking condition: its cooldown end,
145
+ * and each window's reset (only when that window is at/over the threshold). The
146
+ * literal multi-account generalization of #143's single-account resetsInSeconds.
147
+ *
148
+ * GUARANTEE (invariant 4): the result is ALWAYS in the future. A blocking window
149
+ * whose cached reset is null / unknown / already-elapsed does NOT contribute a past
150
+ * instant (the old EPOCH0 seed bug that made earliestReset land in 1970 → a 0
151
+ * continueDelayMs → a tight idle loop). Such a window is treated as clearing after a
152
+ * default cooldown (now + DEFAULT_RESET_COOLDOWN_MS), so the caller always idles a
153
+ * bounded positive time and re-checks (which refreshes usage and self-heals).
154
+ */
155
+ export declare function availableAt(acct: CodexRotationAccount, now: Date): Date;
156
+ /**
157
+ * Earliest provider/cooldown timestamp that is actually authoritative. The
158
+ * ranker's `availableAt` deliberately synthesizes a positive default for
159
+ * unknown/stale state; durable capacity waits must distinguish that bounded
160
+ * refresh backoff from a real provider reset timer.
161
+ */
162
+ export declare function authoritativeCodexCapacityResetAt(accounts: CodexRotationAccount[], now: Date): Date | null;
163
+ /**
164
+ * The bounded all-capped idle delay: clamp(earliestResetAt − now) into
165
+ * [MIN_IDLE_MS, maxMs]. NEVER 0 and NEVER negative, so a null / elapsed / unknown
166
+ * reset cannot collapse the hold into a tight re-dispatch loop (invariant 4). The two
167
+ * agent-turn call sites (proactive turn-start + reactive 429) feed allCapped's
168
+ * earliestResetAt through this before returning continueDelayMs.
169
+ */
170
+ export declare function computeIdleDelayMs(earliestResetAt: Date, now: Date, maxMs: number): number;
171
+ /**
172
+ * Slow-retry floor (Finding 1a) for the double-fault where the just-served
173
+ * account's cooldown write could NOT be confirmed persisted: the next proactive
174
+ * rank might re-select the same capped account (stale-low cached usedPercent, not
175
+ * cooling). A positive floor degrades that to a SLOW retry instead of a
176
+ * model-paced hot loop. A few seconds — long enough to break the loop, short
177
+ * enough to stay responsive once the transient write fault clears.
178
+ */
179
+ export declare const REACTIVE_PERSISTENCE_FAULT_FLOOR_MS = 5000;
180
+ /**
181
+ * Circuit-breaker slack (Finding 1b) added to the connected-account count to bound
182
+ * consecutive reactive failovers. Each legitimate failover cools one account, so
183
+ * after at most N failovers every account is capped and the reactive path takes the
184
+ * all-capped idle instead; the +margin absorbs benign re-ranks (a connector-covering
185
+ * pick order) without tripping the breaker in normal use.
186
+ */
187
+ export declare const REACTIVE_ROTATION_MARGIN = 2;
188
+ /**
189
+ * The FIXED positive idle the reactive path falls to once consecutive reactive
190
+ * failovers exceed the bound (a double-fault where cooldown writes are not sticking
191
+ * AND the 429s carry no usage headers, so the same account keeps getting re-picked).
192
+ * Mirrors the all-capped floor — a mandatory, bounded hold, never another 0-delay
193
+ * re-dispatch — so the loop can never hammer the capped backend + DB (invariant 4).
194
+ */
195
+ export declare const REACTIVE_CIRCUIT_BREAKER_IDLE_MS = 60000;
196
+ /** The reactive-resume shape returned to the goal-continuation caller. */
197
+ export type ReactiveRotationResume = {
198
+ continueDelayMs: number;
199
+ idleUntilReset: boolean;
200
+ };
201
+ /**
202
+ * Decide the continueDelayMs for a reactive 429 failover onto a LIVE candidate,
203
+ * bounding the (otherwise 0-delay) re-dispatch against two second-order faults:
204
+ *
205
+ * 1. Circuit breaker (1b): if the consecutive reactive-failover streak (prior
206
+ * rotated 429 failovers since the last successful turn, PLUS this one) exceeds
207
+ * `connectedAccountCount + REACTIVE_ROTATION_MARGIN`, fall to a FIXED positive,
208
+ * MANDATORY idle. Covers the double-fault (cooldown write not persisted + a
209
+ * header-less cap 429) where the same capped account is re-picked every turn.
210
+ * 2. Persistence-fault floor (1a): if the just-served account's cooldown could NOT
211
+ * be confirmed persisted, use a positive floor (slow retry) instead of 0.
212
+ *
213
+ * Otherwise (a confirmed cooldown + an in-bounds streak) returns the unchanged
214
+ * 0-delay fast re-dispatch — the happy single-rotation path is byte-identical.
215
+ * Pure so the boundedness contract is unit-testable without a worker/db env.
216
+ */
217
+ export declare function computeReactiveRotationResume(args: {
218
+ cooldownPersisted: boolean;
219
+ priorConsecutiveRotations: number;
220
+ connectedAccountCount: number;
221
+ }): ReactiveRotationResume;
222
+ /**
223
+ * THE pure rotation ranker. `accounts` arrives in stable created_at order
224
+ * (listCodexAccountStatuses), which deterministically breaks ranking ties.
225
+ */
226
+ export declare function chooseRotationActive(args: {
227
+ rotationStrategy: CodexRotationStrategy;
228
+ activeCredentialId: string | null;
229
+ priorCredentialId: string | null;
230
+ accounts: CodexRotationAccount[];
231
+ now: Date;
232
+ usedConnectors?: string[];
233
+ }): RotationDecision;
234
+ /**
235
+ * Exact pre-0053 selector used while the lease cutover is off.
236
+ *
237
+ * Old workers keep a healthy `most_remaining` active pointer sticky and know
238
+ * nothing about lease counts or fairness cursors. A compatible worker must do
239
+ * the same until BOTH the deployment flag and workspace cutover are enabled;
240
+ * otherwise a rolling fleet would run two allocators at once. When the active
241
+ * pointer is no longer eligible, zeroing the additive metadata delegates to the
242
+ * same capacity/connector ranking that the old selector used.
243
+ */
244
+ export declare function chooseLegacyRotationActive(args: Parameters<typeof chooseRotationActive>[0]): RotationDecision;
245
+ /**
246
+ * Full pure policy at the transaction boundary. A live same-turn lease is
247
+ * idempotent; the rollout-off/manual path preserves pin>pointer behavior; a
248
+ * healthy pin wins only while eligible, so quota/auth quarantine cannot trap a
249
+ * session on one subscription.
250
+ */
251
+ export declare function selectCodexCredentialLeaseForTurn(args: {
252
+ context: CodexCredentialLeaseSelectionContext;
253
+ leasingEnabled: boolean;
254
+ sessionId: string;
255
+ sessionPinnedCredentialId: string | null;
256
+ sessionPinSource: CodexPinSource | null;
257
+ sessionLastCredentialId: string | null;
258
+ /** Same-turn checkpoint/frozen account; temporary disable cannot move it. */
259
+ continuationCredentialId?: string | null;
260
+ now: Date;
261
+ }): CodexTurnLeaseSelection;
@@ -0,0 +1,17 @@
1
+ import type { ResourceRef, SessionStatus, SessionSystemUpdatePayload, ToolRef } from "@opengeni/contracts";
2
+ export { mergeResourceRefs, mergeToolRefs, reasoningEffortForMetadata as reasoningEffortForSession, } from "@opengeni/contracts";
3
+ /**
4
+ * Refuse to revive a terminal reusable session on a scheduled fire. Mirrors the
5
+ * API-level guard in apps/api/src/domain/sessions.ts (post a user message ->
6
+ * 409 when cancelled): "cancelled" is the one terminal state, an explicit user
7
+ * act, so a recurring task must NOT silently resurrect and re-bill it. Failed
8
+ * and idle sessions stay revivable (talking to a session is how it resumes), so
9
+ * only "cancelled" is rejected. Throwing inside the FOR UPDATE locked-update
10
+ * callback aborts the whole append+enqueue transaction atomically, and the
11
+ * dispatch catch marks the scheduled_task_run "failed" rather than dispatched.
12
+ */
13
+ export declare function assertReusableSessionRevivable(status: SessionStatus): void;
14
+ export declare function scheduledUserMessagePayload(prompt: string, resources: ResourceRef[], tools: ToolRef[], taskId: string, runId: string): Extract<SessionSystemUpdatePayload, {
15
+ type: "scheduled_occurrence";
16
+ }>;
17
+ export declare function workflowIdForSession(sessionId: string): string;
@@ -0,0 +1,81 @@
1
+ import { type Database } from "@opengeni/db";
2
+ import { type CompactionItem } from "@opengeni/runtime";
3
+ import { type Settings } from "@opengeni/config";
4
+ import type { SessionEvent } from "@opengeni/contracts";
5
+ import { type TurnCodexAccount } from "./run-input";
6
+ export type MaybeCompactResult = {
7
+ compacted: false;
8
+ reason: string;
9
+ events: SessionEvent[];
10
+ requestConsumed: boolean;
11
+ } | {
12
+ compacted: true;
13
+ supersededFrom: number;
14
+ summaryPosition: number;
15
+ signalTokens: number;
16
+ thresholdTokens: number;
17
+ estimatedTokensBefore: number;
18
+ estimatedTokensAfter: number;
19
+ replacementFingerprint: string;
20
+ events: SessionEvent[];
21
+ };
22
+ /**
23
+ * Durable context compaction.
24
+ *
25
+ * Portable path: Codex CLI local plaintext checkpoint for every provider and
26
+ * for Codex sessions frozen on `portable`.
27
+ *
28
+ * Remote v2 path: when the session is frozen on `remote_v2` and the turn is
29
+ * Codex, call Codex `/codex/responses` with `compaction_trigger` and persist the
30
+ * opaque compaction item. Fail closed — never silently fall back to portable.
31
+ */
32
+ export type CompactionSummarizer = (settings: Settings, input: CompactionItem[]) => Promise<string>;
33
+ /** Returns the opaque Codex remote compaction v2 item. */
34
+ export type RemoteCompactionV2Requester = (settings: Settings, input: CompactionItem[]) => Promise<CompactionItem>;
35
+ export declare function maybeCompactContext(db: Database, settings: Settings, scope: {
36
+ accountId: string;
37
+ workspaceId: string;
38
+ sessionId: string;
39
+ turnId: string;
40
+ executionGeneration: number;
41
+ attemptId: string;
42
+ }, lastInputTokens: number | null, summarize?: CompactionSummarizer, options?: {
43
+ force?: boolean;
44
+ clearRequestedCompaction?: boolean;
45
+ trigger?: "auto" | "operator" | "proactive" | "overflow";
46
+ codexAccount?: TurnCodexAccount;
47
+ /** Frozen session mode; remote_v2 selects the Codex opaque path. */
48
+ codexCompactionMode?: "remote_v2" | "portable";
49
+ /** True when this turn's resolved provider is codex-subscription. */
50
+ isCodexSubscriptionTurn?: boolean;
51
+ /** Injected remote requester; required for the remote_v2 branch. */
52
+ requestRemoteCompactionV2?: RemoteCompactionV2Requester;
53
+ /** Tag persisted history with the Codex credential that produced it. */
54
+ producerCodexCredentialId?: string | null;
55
+ /**
56
+ * Live fanout for the attempt-fenced `compaction.started` event so the
57
+ * timeline can show progress before the provider call returns. Must never
58
+ * append again — the event is already durable.
59
+ */
60
+ publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;
61
+ }): Promise<MaybeCompactResult>;
62
+ /**
63
+ * After `compaction.started`, record a visible skip so the timeline cannot
64
+ * stick on "Compacting…". Used when the provider/summarizer throws a terminal
65
+ * (non-retryable) failure — including auto/overflow paths that never set
66
+ * `compactRequested`.
67
+ */
68
+ export declare function settleFailedContextCompactionLandmark(db: Database, scope: {
69
+ accountId: string;
70
+ workspaceId: string;
71
+ sessionId: string;
72
+ turnId: string;
73
+ executionGeneration: number;
74
+ attemptId: string;
75
+ }, options?: {
76
+ clearRequestedCompaction?: boolean;
77
+ publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;
78
+ }): Promise<Extract<MaybeCompactResult, {
79
+ compacted: false;
80
+ }>>;
81
+ export declare function isContextWindowExceeded(error: unknown, seen?: WeakSet<object>): boolean;
@@ -0,0 +1,39 @@
1
+ import type { ActivityServices, IndexDocumentInput } from "./types";
2
+ export declare function createDocumentActivities(services: () => Promise<ActivityServices>): {
3
+ indexDocument: (input: IndexDocumentInput) => Promise<{
4
+ id: string;
5
+ workspaceId: string;
6
+ baseId: string;
7
+ fileId: string;
8
+ status: "failed" | "indexing" | "queued" | "ready";
9
+ title: string;
10
+ parser: string;
11
+ chunkCount: number;
12
+ error: string | null;
13
+ sourceKind: "chat" | "document" | "email" | "manual_upload" | "meeting_transcript" | "other" | "repository" | "web";
14
+ sourceUri: string | null;
15
+ sourceExternalId: string | null;
16
+ sourceTitle: string | null;
17
+ sourceAuthor: string | null;
18
+ sourceCreatedAt: string | null;
19
+ sourceUpdatedAt: string | null;
20
+ sourceVersion: string | null;
21
+ aclTags: string[];
22
+ visibility: "private" | "workspace";
23
+ createdBy: string | null;
24
+ agentAccess: boolean;
25
+ summary: string | null;
26
+ topics: string[];
27
+ curationStatus: "auto_filed" | "failed" | "none" | "pending" | "suggested";
28
+ curation: {
29
+ suggestedBaseId: string | null;
30
+ suggestedBaseName: string | null;
31
+ confidence: number;
32
+ reason: string | null;
33
+ originalTitle: string | null;
34
+ model: string | null;
35
+ } | null;
36
+ createdAt: string;
37
+ updatedAt: string;
38
+ }>;
39
+ };
@@ -0,0 +1,97 @@
1
+ import { type Settings } from "@opengeni/config";
2
+ import { type ConnectionCredentialsPort, type GitCredentialProvider, type GitCredentialTransport, type ResourceRef, type SessionTurn, type TurnInitiator, type TurnInitiatorContext } from "@opengeni/contracts";
3
+ import { loadVariableSetForRun as loadWorkspaceEnvironmentForRunFromDb, type Database, type VariableSetForRun as WorkspaceEnvironmentForRun } from "@opengeni/db";
4
+ export { loadWorkspaceEnvironmentForRunFromDb as loadWorkspaceEnvironmentForRun, type WorkspaceEnvironmentForRun, };
5
+ export type ConnectionScope = {
6
+ accountId: string;
7
+ workspaceId: string;
8
+ };
9
+ export type GitTokenSeeds = Partial<Record<GitCredentialProvider, string>>;
10
+ export type GitTokenExpiries = Partial<Record<GitCredentialProvider, string>>;
11
+ export type GitCredentialBindingSeed = {
12
+ credentialBindingId: string;
13
+ provider: GitCredentialProvider;
14
+ token: string;
15
+ transport?: GitCredentialTransport;
16
+ expiresAt?: string;
17
+ providerBindingCount?: number;
18
+ };
19
+ export type MintedRunGitCredentials = {
20
+ bindings: GitCredentialBindingSeed[];
21
+ gitTokens: GitTokenSeeds;
22
+ expiresAt: GitTokenExpiries;
23
+ };
24
+ export type GitHubTokenMintAuthorization = (selection: {
25
+ installationId: number;
26
+ repositoryIds: number[];
27
+ }) => Promise<void>;
28
+ export declare const TOOLSPACE_TOKEN_TTL_SECONDS: number;
29
+ export type MintedSandboxToolspaceToken = {
30
+ token: string;
31
+ expiresAt: Date;
32
+ };
33
+ export type SandboxToolspaceAuthority = {
34
+ sessionId: string;
35
+ };
36
+ export declare function mintSandboxToolspaceToken(settings: Settings, scope: ConnectionScope, authority: SandboxToolspaceAuthority, nowMs?: number): Promise<MintedSandboxToolspaceToken | undefined>;
37
+ export type GitCredentialAuthority = {
38
+ sessionId: string;
39
+ rootSessionId: string;
40
+ turnId: string;
41
+ attemptId: string;
42
+ executionGeneration: number;
43
+ initiator: TurnInitiator;
44
+ initiatorContext: TurnInitiatorContext;
45
+ };
46
+ export declare function gitCredentialAuthorityForTurn(input: {
47
+ sessionId: string;
48
+ rootSessionId: string;
49
+ attemptId: string;
50
+ turn: Pick<SessionTurn, "id" | "executionGeneration" | "initiator" | "initiatorContext">;
51
+ }): GitCredentialAuthority;
52
+ type RunGitCredentialOptions = {
53
+ scope?: ConnectionScope;
54
+ authority?: GitCredentialAuthority;
55
+ gitCredentials?: ConnectionCredentialsPort["gitCredentials"];
56
+ authorizeGitHubTokenMint?: GitHubTokenMintAuthorization;
57
+ };
58
+ export declare function loadWorkspaceEnvironmentForRunWithCredentials(db: Database, settings: Settings, scope: ConnectionScope, environmentId: string | null, sandboxSecrets?: ConnectionCredentialsPort["sandboxSecrets"]): Promise<WorkspaceEnvironmentForRun | null>;
59
+ export declare function sandboxEnvironmentForRun(settings: Settings, resources: ResourceRef[], workspaceEnvironment?: Record<string, string>, options?: RunGitCredentialOptions & {
60
+ skipGitHubToken?: boolean;
61
+ deferGitHubToken?: boolean;
62
+ toolspaceAuthority?: SandboxToolspaceAuthority;
63
+ }): Promise<{
64
+ environment: Record<string, string>;
65
+ gitToken?: string;
66
+ gitTokens?: GitTokenSeeds;
67
+ gitTokenExpiresAt?: GitTokenExpiries;
68
+ gitCredentialBindings?: GitCredentialBindingSeed[];
69
+ toolspaceToken?: string;
70
+ toolspaceTokenExpiresAt?: Date;
71
+ }>;
72
+ export declare function mintRunGitCredentials(settings: Settings, resources: ResourceRef[], options?: RunGitCredentialOptions): Promise<MintedRunGitCredentials | undefined>;
73
+ export declare function mintRunGitCredentialBinding(settings: Settings, resources: ResourceRef[], provider: GitCredentialProvider, credentialBindingId: string, options?: RunGitCredentialOptions): Promise<GitCredentialBindingSeed | undefined>;
74
+ export declare function mintRunGitTokens(settings: Settings, resources: ResourceRef[], options?: RunGitCredentialOptions): Promise<GitTokenSeeds | undefined>;
75
+ export declare function mintRunGitToken(settings: Settings, resources: ResourceRef[], options?: RunGitCredentialOptions): Promise<string | undefined>;
76
+ export declare function resolveRunGitIdentity(settings: Settings, resources: ResourceRef[], options?: RunGitCredentialOptions): Promise<{
77
+ name: string;
78
+ email: string;
79
+ } | null>;
80
+ export declare function assertGitCredentialRenewalTransportUnchanged(initial: GitCredentialBindingSeed, renewed: GitCredentialBindingSeed): void;
81
+ /**
82
+ * The GitHub App installation + repository ids a run's git-credential mint
83
+ * would use for these resources, or null when no GitHub token would be minted.
84
+ * Derived from gitCredentialSelections so workspace-authorization rechecks
85
+ * cover exactly the ids that reach createGitHubAppInstallationToken —
86
+ * including legacy string-typed installationId/repositoryId refs, which the
87
+ * mint path coerces via positiveInteger.
88
+ */
89
+ export declare function gitHubTokenMintSelections(resources: ResourceRef[]): Array<{
90
+ installationId: number;
91
+ repositoryIds: number[];
92
+ }>;
93
+ /** @deprecated Use gitHubTokenMintSelections for multi-installation sessions. */
94
+ export declare function gitHubTokenMintSelection(resources: ResourceRef[]): {
95
+ installationId: number;
96
+ repositoryIds: number[];
97
+ } | null;