@opengeni/worker-bundle 0.16.17 → 0.16.29

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 (51) hide show
  1. package/dist/activities/agent-turn.d.ts +83 -32
  2. package/dist/activities/context-compaction.d.ts +2 -0
  3. package/dist/activities/environment.d.ts +1 -0
  4. package/dist/activities/expiring-material-renewal.d.ts +5 -3
  5. package/dist/activities/file-upload-reaper.d.ts +6 -0
  6. package/dist/activities/git-credential-renewal.d.ts +1 -1
  7. package/dist/activities/retained-screenshot-reaper.d.ts +32 -0
  8. package/dist/activities/retained-screenshots.d.ts +93 -0
  9. package/dist/activities/run-credential-renewal.d.ts +1 -1
  10. package/dist/activities/run-input.d.ts +2 -0
  11. package/dist/activities/toolspace-token-renewal.d.ts +1 -1
  12. package/dist/activities/workspace-capture.d.ts +1 -0
  13. package/dist/activities.d.ts +3 -0
  14. package/dist/{chunk-BJUW5LCM.js → chunk-RAMNYSAW.js} +15 -12
  15. package/dist/chunk-RAMNYSAW.js.map +1 -0
  16. package/dist/host-export.js +1 -1
  17. package/dist/index.js +1465 -453
  18. package/dist/index.js.map +1 -1
  19. package/dist/sandbox-resume.d.ts +6 -0
  20. package/dist/sandbox-routing.d.ts +11 -6
  21. package/dist/workflow-bundle.js +2 -1
  22. package/package.json +12 -12
  23. package/src/activities/agent-turn.ts +559 -434
  24. package/src/activities/codex-capacity.ts +10 -1
  25. package/src/activities/codex-rotation.ts +19 -5
  26. package/src/activities/context-compaction.ts +9 -5
  27. package/src/activities/environment.ts +13 -24
  28. package/src/activities/expiring-material-renewal.ts +16 -7
  29. package/src/activities/file-upload-reaper.ts +108 -7
  30. package/src/activities/git-credential-renewal.ts +3 -3
  31. package/src/activities/recording.ts +4 -5
  32. package/src/activities/retained-screenshot-reaper.ts +202 -0
  33. package/src/activities/retained-screenshots.ts +892 -0
  34. package/src/activities/rig-verification.ts +13 -34
  35. package/src/activities/run-credential-renewal.ts +9 -2
  36. package/src/activities/run-input.ts +18 -4
  37. package/src/activities/sandbox-lease.ts +5 -2
  38. package/src/activities/scheduled-tasks.ts +19 -3
  39. package/src/activities/toolspace-token-renewal.ts +9 -2
  40. package/src/activities/workspace-capture.ts +33 -3
  41. package/src/activities.ts +10 -2
  42. package/src/host-export-pump.ts +28 -11
  43. package/src/http.ts +3 -6
  44. package/src/observability-metrics.ts +3 -3
  45. package/src/sandbox-resume.ts +45 -12
  46. package/src/sandbox-routing.ts +35 -17
  47. package/src/worker-service-lifecycle.ts +8 -4
  48. package/src/workflows/file-upload-reaper.ts +4 -1
  49. package/dist/activities/redaction.d.ts +0 -1
  50. package/dist/chunk-BJUW5LCM.js.map +0 -1
  51. package/src/activities/redaction.ts +0 -9
@@ -1,17 +1,20 @@
1
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";
2
+ import { modelResponseServiceTierFromSdkEvent, modelTerminalResponseFromSdkEvent, type SandboxFileDownload, type ComputerToolMode, type ModelResponseUsage, type ModelCallUsageInput, type ModelCallUsageNormalization, type TurnToolCancellationFence, type BackendUnresolvableCode } from "@opengeni/runtime";
3
3
  import { resolveTurnExecutionPolicyV1, type ModelUsageInput, type ModelProviderApi, type RegistryProviderKind, type Settings } from "@opengeni/config";
4
4
  import { ApplicationFailure, CancelledFailure } from "@temporalio/activity";
5
5
  import type { CodexAccountStatus } from "@opengeni/db";
6
6
  import { type GitCredentialRenewalController } from "./git-credential-renewal";
7
7
  import { type RunCredentialRenewalController } from "./run-credential-renewal";
8
8
  import { type ToolspaceTokenRenewalController } from "./toolspace-token-renewal";
9
- import { type SecretForRedaction } from "./redaction";
10
9
  import { type ModelAttachmentInputPolicy } from "./run-input";
11
10
  import type { ActivityServices, EscapedMcpTimeoutRecoveryDetail, RunAgentTurnInput, RunAgentTurnResult, SessionAttemptQuiescenceProof } from "./types";
12
11
  import { type TurnSandboxLeaseHolderId } from "../sandbox-resume";
13
12
  import { type LatencyMode, type SessionEvent, type SessionEventType, type SessionTurn, type ToolAuthNeededPayload, type TurnExecutionPolicyV1 } from "@opengeni/contracts";
14
13
  export declare const PROVIDER_BACKPRESSURE_DELAY_MS = 60000;
14
+ export declare class WorkspaceHumanInputDisabledError extends Error {
15
+ constructor(kind: "resume" | "interruption");
16
+ }
17
+ export declare function assertWorkspaceHumanInputAllowed(enabled: boolean, kind: "resume" | "interruption", attempted: boolean): void;
15
18
  /** Broad personal lookup is allowed only for a direct human/API command. */
16
19
  export declare function credentialSubjectIdForTurnInitiator(turn: Pick<SessionTurn, "source" | "initiator" | "initiatorContext">): string | undefined;
17
20
  /**
@@ -168,19 +171,47 @@ export declare function waitForTurnFinalizerStep<T>(operation: Promise<T>, signa
168
171
  * may pin the activity behind cancellation after durable writes are fenced.
169
172
  */
170
173
  export declare function waitForTurnStreamCleanup(batcherFlush: Promise<unknown>, providerCompleted: Promise<unknown>, signal: AbortSignal | undefined): Promise<void>;
174
+ /**
175
+ * Terminal settlement closes the active attempt before turn finalization. The
176
+ * ordinary workspace admission therefore correctly returns `attempt_fenced`
177
+ * for the final attempt-qualified credential deletion. Retry only that exact
178
+ * settled-attempt case directly; every other fence/status and the direct
179
+ * deletion itself remain fail-closed.
180
+ */
181
+ export declare function clearAttemptCredentialsWithSettledFence(input: {
182
+ activityStatus: RunAgentTurnResult["status"] | "unknown";
183
+ runWorkspaceFencedClear: () => Promise<void>;
184
+ clearExactAttempt: () => Promise<void>;
185
+ onSettledAttemptFence: () => void;
186
+ }): Promise<void>;
187
+ export type MandatoryHistoryPersistenceStage = "history_append" | "sandbox_envelope";
188
+ /**
189
+ * Preserve the exact storage failure for the permission-controlled turn event
190
+ * while attaching only a stable, non-secret operation token to public worker
191
+ * diagnostics. Mandatory history failures remain terminal and never inherit a
192
+ * provider-retry classification from coincidental source text or status.
193
+ */
194
+ export declare class MandatoryHistoryPersistenceError extends Error {
195
+ readonly stage: MandatoryHistoryPersistenceStage;
196
+ readonly name = "MandatoryHistoryPersistenceError";
197
+ readonly cause: unknown;
198
+ constructor(stage: MandatoryHistoryPersistenceStage, cause: unknown);
199
+ }
200
+ export declare function runMandatoryHistoryPersistenceStep<T>(stage: MandatoryHistoryPersistenceStage, operation: () => Promise<T>): Promise<T>;
171
201
  export type SafeErrorDiagnostic = {
172
- name: string;
173
- message: string;
202
+ errorClass: "WorkerOperationError";
203
+ errorCode: "worker_operation_failed";
174
204
  status?: number;
175
- code?: string;
205
+ origin: "worker";
206
+ historyPersistenceStage?: MandatoryHistoryPersistenceStage;
176
207
  };
177
208
  /**
178
209
  * Produce the only exception shape allowed in worker logs. It deliberately
179
- * excludes stack, cause, response/request bodies, and arbitrary enumerable
180
- * properties while retaining bounded, redacted diagnostics.
210
+ * excludes the arbitrary source message, stack, cause, response/request
211
+ * bodies, and enumerable properties. Exact failure content belongs in the
212
+ * permission-controlled session event, not stdout or telemetry.
181
213
  */
182
- export declare function safeErrorDiagnostic(error: unknown, redactText?: (value: string) => string): SafeErrorDiagnostic;
183
- export declare function headerSecretRedactions(prefix: string, headers: Readonly<Record<string, string>> | undefined, credentialHeaderNames?: Iterable<string>): SecretForRedaction[];
214
+ export declare function safeErrorDiagnostic(error: unknown): SafeErrorDiagnostic;
184
215
  export declare function shouldRecoverCompactionProviderFailure(error: unknown): boolean;
185
216
  export declare function classifyContextWindowOverflowError(error: unknown): {
186
217
  message: string;
@@ -215,14 +246,14 @@ export declare function classifyMcpTransportTimeoutError(error: unknown): {
215
246
  * an earlier slice — the orphaned tool output that 400s the Responses API and
216
247
  * bricks the session on every replay.
217
248
  *
218
- * Defending: sanitize the full current history into an API-valid sequence (the
249
+ * Defending: structurally repair the full current history into an API-valid sequence (the
219
250
  * same pure rules the read path uses), then append only the new tail beyond the
220
251
  * watermark. A trailing dangling call is dropped here and re-evaluated next
221
252
  * pass once its result lands, so a call and its result are written together at
222
253
  * consecutive positions and a result is never persisted without its call. The
223
- * watermark advances to the sanitized length — never past anything unwritten —
254
+ * watermark advances to the repaired length — never past anything unwritten —
224
255
  * so a non-monotonic history can never desync it. When previously-persisted
225
- * rows already exceed the sanitized length (e.g. legacy orphans written before
256
+ * rows already exceed the repaired length (e.g. legacy orphans written before
226
257
  * this fix), nothing new is appended and the watermark holds steady.
227
258
  */
228
259
  /**
@@ -271,19 +302,21 @@ type TurnEventPublisher = (events: Array<Omit<AppendEventInput, "producerId" | "
271
302
  events: SessionEvent[];
272
303
  accepted: boolean;
273
304
  }>;
274
- export type ModelResponseUsageEventState = {
275
- responseUsageCount: number;
276
- providerContextRevision: number;
277
- lastProviderContextTokensObserved: number | null;
305
+ export type ModelResponseEventState = {
306
+ responseCount: number;
307
+ contextSignal: {
308
+ revision: number;
309
+ totalTokens: number;
310
+ } | null;
278
311
  claimedSourceKeys: Set<string>;
279
312
  };
280
313
  export type CompactionModelUsageEventState = {
281
314
  usageCount: number;
282
315
  claimedSourceKeys: Set<string>;
283
316
  };
284
- export declare function createModelResponseUsageEventState(claimedSourceKeys?: Set<string>): ModelResponseUsageEventState;
317
+ export declare function createModelResponseEventState(claimedSourceKeys?: Set<string>): ModelResponseEventState;
285
318
  export declare function createCompactionModelUsageEventState(claimedSourceKeys?: Set<string>): CompactionModelUsageEventState;
286
- export declare function modelResponseUsageContextSignal(state: ModelResponseUsageEventState): {
319
+ export declare function modelResponseContextSignal(state: ModelResponseEventState): {
287
320
  revision: number;
288
321
  totalTokens: number;
289
322
  } | null;
@@ -295,19 +328,20 @@ export declare function assertModelResponseLatencyMode(input: {
295
328
  providerId?: string;
296
329
  }): void;
297
330
  /**
298
- * Process one SDK stream event through the exact production usage path.
331
+ * Process one SDK terminal-response event through the production authority path.
299
332
  *
300
333
  * The pinned Responses SDK mirrors one provider terminal response as both a
301
334
  * normalized `response_done` and a raw `model/response.completed` event. Claim
302
- * the stable response/source key before lease renewal or any usage side effect,
303
- * and advance the positional ordinal only for a newly claimed response. The
304
- * durable `agent.model.usage` source-key fence remains the cross-restart
305
- * authority: a replay may retry the idempotent billing write, but it cannot
306
- * advance process-local metrics, provider context, or attempt-owned signals.
307
- */
308
- export declare function processModelResponseUsageEvent(input: {
309
- event: Parameters<typeof modelResponseUsageFromSdkEvent>[0];
310
- state: ModelResponseUsageEventState;
335
+ * the stable response/source key before lease renewal or any side effect, and
336
+ * use that one positional ordinal for both response identity and same-run
337
+ * context binding. A response without usage still clears attempt-owned token
338
+ * state. When usage exists, the durable `agent.model.usage` source-key fence
339
+ * remains the cross-restart authority: a replay may retry the idempotent billing
340
+ * write, but it cannot advance metrics, context, or attempt-owned signals.
341
+ */
342
+ export declare function processModelResponseTerminalEvent(input: {
343
+ event: Parameters<typeof modelTerminalResponseFromSdkEvent>[0];
344
+ state: ModelResponseEventState;
311
345
  dispatchId: string | null;
312
346
  settings: Settings;
313
347
  db: ActivityServices["db"];
@@ -330,9 +364,9 @@ export declare function processModelResponseUsageEvent(input: {
330
364
  renewLease: () => Promise<void>;
331
365
  leaseLost: () => boolean;
332
366
  leaseLostMessage: string;
333
- setLastInputTokens: (tokens: number) => Promise<void>;
367
+ setLastInputTokens: (tokens: number | null) => Promise<void>;
334
368
  }): Promise<{
335
- status: "not_usage";
369
+ status: "not_response";
336
370
  } | {
337
371
  status: "duplicate";
338
372
  sourceKey: string;
@@ -340,6 +374,7 @@ export declare function processModelResponseUsageEvent(input: {
340
374
  status: "processed";
341
375
  sourceKey: string;
342
376
  authoritative: boolean;
377
+ usageReported: boolean;
343
378
  }>;
344
379
  /**
345
380
  * Apply the same source-key authority ordering to the compaction summarizer's
@@ -404,7 +439,7 @@ export declare function emitModelCallUsage(input: {
404
439
  * owns idempotency; this helper must never receive raw provider values.
405
440
  */
406
441
  export declare function applyCodexCacheTelemetry(observability: ActivityServices["observability"], provider: string, normalizedUsage: ModelCallUsageNormalization): void;
407
- export declare function historyRowsToAppend(rawHistory: Array<Record<string, unknown>>, persistedHistoryCount: number, nextPosition?: number, toolOutputTruncationTokens?: number, redactValue?: (value: unknown) => unknown): {
442
+ export declare function historyRowsToAppend(rawHistory: Array<Record<string, unknown>>, persistedHistoryCount: number, nextPosition?: number, toolOutputTruncationTokens?: number): {
408
443
  rows: Array<{
409
444
  position: number;
410
445
  item: Record<string, unknown>;
@@ -422,7 +457,7 @@ export declare function selectRejectedProviderArtifactHistoryIds(activeHistory:
422
457
  historyItemIds: readonly string[];
423
458
  }, wireFingerprints: readonly string[]): string[];
424
459
  /** Literal final per-call boundary for replayed and current-turn model input. */
425
- export declare function secretRedactionModelInputFilter(redactValue: (value: unknown) => unknown): NonNullable<RunAgentStreamOptions["callModelInputFilter"]>;
460
+ export declare function isModelOrToolProgressHistoryItem(item: Record<string, unknown>): boolean;
426
461
  /**
427
462
  * Resolve the EFFECTIVE/active compute backend a turn should gate
428
463
  * filesystem-touching agent lifecycle hooks on (today: the repository clone).
@@ -690,6 +725,11 @@ export declare function acceptsPromptCacheKeyForTurn(resolvedModel: {
690
725
  * leased; callers check this before accepting an in-flight heartbeat promise.
691
726
  */
692
727
  export declare function codexCredentialLeaseDeadlineExpired(confirmedUntilMs: number | null, nowMs?: number): boolean;
728
+ type OpStreamFinalizer = {
729
+ finalizeOpStreamOps(): Promise<void>;
730
+ };
731
+ /** Release retained Connected Machine output only after the turn is durable. */
732
+ export declare function finalizeDurableTurnOpStreams(sessions: readonly unknown[], fallback: OpStreamFinalizer | null): Promise<void>;
693
733
  export declare function createRunAgentTurnActivity(services: () => Promise<ActivityServices>): (input: RunAgentTurnInput) => Promise<RunAgentTurnResult>;
694
734
  export declare function isTransientProviderError(error: unknown): boolean;
695
735
  export declare function agentRunFailurePayload(error: unknown, options?: {
@@ -708,6 +748,7 @@ export declare function agentRunFailurePayload(error: unknown, options?: {
708
748
  attempts?: number;
709
749
  retryOutcome?: string;
710
750
  database?: Record<string, string>;
751
+ historyPersistenceStage?: MandatoryHistoryPersistenceStage;
711
752
  };
712
753
  export type CodexCredentialFailure = {
713
754
  kind: "auth" | "forbidden" | "rate_limit" | "quota";
@@ -746,6 +787,16 @@ export declare function codexUsageLimitFailurePayload(info: {
746
787
  retryable: boolean;
747
788
  detail?: string;
748
789
  };
790
+ export declare function pendingToolCallFromSdkEvent(event: unknown): {
791
+ callId: string;
792
+ callType: string;
793
+ callName: string | null;
794
+ callItem: Record<string, unknown>;
795
+ } | null;
796
+ export declare function completedToolCallFromSdkEvent(event: unknown): {
797
+ callId: string;
798
+ resultItem: Record<string, unknown>;
799
+ } | null;
749
800
  export declare function ensureRunAllowed(settings: Settings, db: ActivityServices["db"], accountId: string, workspaceId: string, isExternallyBilledTurn: boolean, entitlements?: ActivityServices["entitlements"]): Promise<void>;
750
801
  export type ModelUsageBillingRecord = {
751
802
  billingPath: "opengeni_credits" | "external";
@@ -54,6 +54,8 @@ export declare function maybeCompactContext(db: Database, settings: Settings, sc
54
54
  * append again — the event is already durable.
55
55
  */
56
56
  publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;
57
+ /** Materialize retained screenshot receipts only in the attempt-local model view. */
58
+ materializeHistory?: (items: CompactionItem[]) => Promise<CompactionItem[]>;
57
59
  /** Turn-scoped attachment/modality view; canonical persisted rows stay untouched. */
58
60
  projectModelInput?: (items: CompactionItem[]) => Promise<CompactionItem[]>;
59
61
  }): Promise<MaybeCompactResult>;
@@ -58,6 +58,7 @@ type RunGitCredentialOptions = {
58
58
  export declare function loadWorkspaceEnvironmentForRunWithCredentials(db: Database, settings: Settings, scope: ConnectionScope, environmentId: string | null, sandboxSecrets?: ConnectionCredentialsPort["sandboxSecrets"]): Promise<WorkspaceEnvironmentForRun | null>;
59
59
  export declare function sandboxEnvironmentForRun(settings: Settings, resources: ResourceRef[], workspaceEnvironment?: Record<string, string>, options?: RunGitCredentialOptions & {
60
60
  skipGitHubToken?: boolean;
61
+ skipToolspace?: boolean;
61
62
  deferGitHubToken?: boolean;
62
63
  toolspaceAuthority?: SandboxToolspaceAuthority;
63
64
  }): Promise<{
@@ -9,11 +9,13 @@ export type ExpiringMaterialRenewalController = {
9
9
  refreshNow(): Promise<void>;
10
10
  stop(): Promise<void>;
11
11
  };
12
- export type ExpiringMaterialRenewalOptions<T> = {
12
+ export type ExpiringMaterialRenewalPublicErrorClass = "RunCredentialRenewalOperationError" | "ToolspaceTokenRenewalOperationError";
13
+ export type ExpiringMaterialRenewalOptions<T, ErrorClass extends ExpiringMaterialRenewalPublicErrorClass> = {
13
14
  initialExpiresAt: Date | null;
14
15
  resolve: () => Promise<T>;
15
16
  write: (material: T) => Promise<void>;
16
17
  expiresAt: (material: T) => Date | null;
18
+ publicErrorClass: ErrorClass;
17
19
  policy: ExpiringMaterialRenewalPolicy;
18
20
  now?: () => number;
19
21
  schedule?: (callback: () => void, delayMs: number) => RenewalTimer;
@@ -24,7 +26,7 @@ export type ExpiringMaterialRenewalOptions<T> = {
24
26
  }) => void;
25
27
  onFailure?: (failure: {
26
28
  retryDelayMs: number;
27
- errorClass: string;
29
+ errorClass: ErrorClass;
28
30
  }) => void;
29
31
  };
30
32
  export declare function nextExpiringMaterialRenewalDelay(expiresAt: Date | null, policy: ExpiringMaterialRenewalPolicy, nowMs?: number): number;
@@ -34,5 +36,5 @@ export declare function nextExpiringMaterialRenewalDelay(expiresAt: Date | null,
34
36
  * A late resolver cannot write after stop. A physical sandbox write that already
35
37
  * started is drained so turn settlement cannot race a stale mutation.
36
38
  */
37
- export declare function startExpiringMaterialRenewalLoop<T>(options: ExpiringMaterialRenewalOptions<T>): ExpiringMaterialRenewalController;
39
+ export declare function startExpiringMaterialRenewalLoop<T, ErrorClass extends ExpiringMaterialRenewalPublicErrorClass>(options: ExpiringMaterialRenewalOptions<T, ErrorClass>): ExpiringMaterialRenewalController;
38
40
  export {};
@@ -1,3 +1,4 @@
1
+ import { claimDueTranscriptionRecordingObjectCleanup, claimExpiredFileUploadCleanup, completeDueTranscriptionRecordingObjectCleanup, completeExpiredFileUploadCleanup, purgeExpiredTranscriptionRecordings } from "@opengeni/db";
1
2
  import type { ObjectStorage } from "@opengeni/storage";
2
3
  import type { ActivityServices } from "./types";
3
4
  export declare const FILE_UPLOAD_CLEANUP_GRACE_MS: number;
@@ -14,6 +15,11 @@ export type FileUploadReaperActivityOptions = {
14
15
  batchSize?: number;
15
16
  /** Failure-injection seam; production uses the configured provider delete. */
16
17
  deleteObject?: (storage: ObjectStorage, key: string) => Promise<void>;
18
+ claimFileUploads?: typeof claimExpiredFileUploadCleanup;
19
+ completeFileUpload?: typeof completeExpiredFileUploadCleanup;
20
+ claimTranscriptionObjects?: typeof claimDueTranscriptionRecordingObjectCleanup;
21
+ completeTranscriptionObject?: typeof completeDueTranscriptionRecordingObjectCleanup;
22
+ purgeTranscriptionRecordings?: typeof purgeExpiredTranscriptionRecordings;
17
23
  };
18
24
  /**
19
25
  * Build the provider-neutral expired direct-upload reaper. Claims are durable
@@ -12,7 +12,7 @@ export type GitCredentialRenewalResult = {
12
12
  export type GitCredentialRenewalFailure = {
13
13
  providers: readonly GitCredentialProvider[];
14
14
  retryDelayMs: number;
15
- errorClass: string;
15
+ errorClass: "GitCredentialRenewalOperationError";
16
16
  };
17
17
  export type GitCredentialRenewalController = {
18
18
  refreshNow(): Promise<void>;
@@ -0,0 +1,32 @@
1
+ import type { FileAsset } from "@opengeni/contracts";
2
+ import type { ObjectHead, ObjectStorage } from "@opengeni/storage";
3
+ import type { ActivityServices } from "./types";
4
+ export declare const RETAINED_SCREENSHOT_PENDING_GRACE_MS: number;
5
+ export declare const RETAINED_SCREENSHOT_CLAIM_TIMEOUT_MS: number;
6
+ export declare const RETAINED_SCREENSHOT_MAINTENANCE_BATCH_SIZE = 100;
7
+ export type MaintainRetainedScreenshotsResult = {
8
+ claimed: number;
9
+ ready: number;
10
+ deleted: number;
11
+ failed: number;
12
+ retryable: number;
13
+ };
14
+ export type RetainedScreenshotMaintenanceActivityOptions = {
15
+ pendingGraceMs?: number;
16
+ claimTimeoutMs?: number;
17
+ batchSize?: number;
18
+ /** Provider seams used by deterministic unit tests. */
19
+ fileExists?: (storage: ObjectStorage, file: FileAsset) => Promise<boolean>;
20
+ headFile?: (storage: ObjectStorage, file: FileAsset) => Promise<ObjectHead>;
21
+ deleteObject?: (storage: ObjectStorage, key: string) => Promise<void>;
22
+ };
23
+ /**
24
+ * Reconcile interrupted screenshot writes and reap expired screenshot objects.
25
+ * Claims move rows out of the readable `ready`/writable `pending` states before
26
+ * provider access. Provider failures leave the durable claim reclaimable; DB
27
+ * completion happens only after exact metadata verification or an idempotent
28
+ * object delete.
29
+ */
30
+ export declare function createRetainedScreenshotMaintenanceActivities(services: () => Promise<ActivityServices>, options?: RetainedScreenshotMaintenanceActivityOptions): {
31
+ maintainRetainedScreenshots: () => Promise<MaintainRetainedScreenshotsResult>;
32
+ };
@@ -0,0 +1,93 @@
1
+ import { type RetainedArtifactMetadata, type RetainedOutputUnavailableReason } from "@opengeni/contracts";
2
+ import { type Database } from "@opengeni/db";
3
+ import type { ObjectStorage } from "@opengeni/storage";
4
+ export type TypedScreenshotToolOutput = {
5
+ callId: string;
6
+ toolOutputId: string;
7
+ bytes: Uint8Array;
8
+ mediaType: string;
9
+ };
10
+ export type ValidatedScreenshot = {
11
+ bytes: Uint8Array;
12
+ mediaType: "image/png";
13
+ sizeBytes: number;
14
+ sha256: string;
15
+ width: number;
16
+ height: number;
17
+ };
18
+ export declare class ScreenshotValidationError extends Error {
19
+ readonly reason: "invalid_content" | "oversized" | "unsupported";
20
+ constructor(reason: "invalid_content" | "oversized" | "unsupported", message: string);
21
+ }
22
+ export declare class RetainedScreenshotUnavailableError extends Error {
23
+ readonly artifactId: string;
24
+ readonly reason: RetainedOutputUnavailableReason;
25
+ constructor(artifactId: string, reason: RetainedOutputUnavailableReason);
26
+ }
27
+ /** Read the SDK's trusted typed image before event/history serialization. */
28
+ export declare function typedScreenshotFromSdkEvent(event: unknown): TypedScreenshotToolOutput | null;
29
+ /** Validate the complete canonical PNG and derive exact integrity metadata. */
30
+ export declare function validateComputerScreenshot(input: {
31
+ bytes: Uint8Array;
32
+ mediaType: string;
33
+ }, limits?: {
34
+ maxBytes?: number;
35
+ maxDimension?: number;
36
+ maxPixels?: number;
37
+ }): ValidatedScreenshot;
38
+ export declare function retainedScreenshotIdentity(input: {
39
+ sessionId: string;
40
+ turnId: string;
41
+ attemptId: string;
42
+ toolCallId: string;
43
+ toolOutputId: string;
44
+ }): {
45
+ artifactId: string;
46
+ settlementKey: string;
47
+ };
48
+ export declare function retainComputerScreenshot(input: {
49
+ db: Database;
50
+ objectStorage: ObjectStorage | null;
51
+ accountId: string;
52
+ workspaceId: string;
53
+ sessionId: string;
54
+ turnId: string;
55
+ attemptId: string;
56
+ output: TypedScreenshotToolOutput;
57
+ now?: Date;
58
+ retentionMs?: number;
59
+ workspaceQuotaBytes?: number;
60
+ }): Promise<RetainedArtifactMetadata>;
61
+ /** Replace only new screenshot bytes with a compact receipt before first persistence. */
62
+ export declare function compactRetainedScreenshotHistory(history: Array<Record<string, unknown>>, receiptsByCallId: ReadonlyMap<string, RetainedArtifactMetadata>): Array<Record<string, unknown>>;
63
+ /** Collect durable screenshot receipts before their provider-only expansion. */
64
+ export declare function collectRetainedScreenshotReceipts(history: ReadonlyArray<Record<string, unknown>>, target?: Map<string, RetainedArtifactMetadata>): Map<string, RetainedArtifactMetadata>;
65
+ /**
66
+ * Compact every protocol-item copy inside an SDK RunState before persistence.
67
+ * The traversal intentionally mirrors the repository's existing serialized
68
+ * RunState sanitizers. A parse failure or no-op returns the original string.
69
+ */
70
+ export declare function compactRetainedScreenshotRunState(serialized: string, receiptsByCallId: ReadonlyMap<string, RetainedArtifactMetadata>): string;
71
+ export declare function collectRetainedScreenshotRunStateReceipts(serialized: string, target?: Map<string, RetainedArtifactMetadata>): Map<string, RetainedArtifactMetadata>;
72
+ /**
73
+ * Materialize canonical receipts to the exact SDK input_image data URL shape.
74
+ * Missing/deleted/expired/corrupt bytes fail closed; no item is omitted,
75
+ * reordered, rewritten in storage, or converted to text.
76
+ */
77
+ export declare function materializeRetainedScreenshotHistory(input: {
78
+ db: Database;
79
+ objectStorage: ObjectStorage | null;
80
+ workspaceId: string;
81
+ sessionId: string;
82
+ history: Array<Record<string, unknown>>;
83
+ now?: Date;
84
+ }): Promise<Array<Record<string, unknown>>>;
85
+ /** Expand durable markers in an SDK RunState immediately before resume. */
86
+ export declare function materializeRetainedScreenshotRunState(input: {
87
+ db: Database;
88
+ objectStorage: ObjectStorage | null;
89
+ workspaceId: string;
90
+ sessionId: string;
91
+ serialized: string;
92
+ now?: Date;
93
+ }): Promise<string>;
@@ -19,7 +19,7 @@ export type RunCredentialRenewalOptions = {
19
19
  }) => void;
20
20
  onFailure?: (failure: {
21
21
  retryDelayMs: number;
22
- errorClass: string;
22
+ errorClass: "RunCredentialRenewalOperationError";
23
23
  }) => void;
24
24
  };
25
25
  export declare function nextRunCredentialRenewalDelay(expiresAt: Date | null, nowMs?: number): number;
@@ -27,6 +27,8 @@ export type TurnInputOptions = {
27
27
  unavailableSandboxFilesNote?: string;
28
28
  runCredentialsNote?: string;
29
29
  providerApi: HistoryProviderApi;
30
+ materializeModelHistory?: ModelHistoryAttachmentProjector;
31
+ materializeSerializedRunState?: (serialized: string) => Promise<string>;
30
32
  projectModelHistory?: ModelHistoryAttachmentProjector;
31
33
  };
32
34
  export declare const MAX_INLINE_MODEL_ATTACHMENT_BYTES: number;
@@ -17,7 +17,7 @@ export type ToolspaceTokenRenewalOptions = {
17
17
  }) => void;
18
18
  onFailure?: (failure: {
19
19
  retryDelayMs: number;
20
- errorClass: string;
20
+ errorClass: "ToolspaceTokenRenewalOperationError";
21
21
  }) => void;
22
22
  };
23
23
  export declare function startToolspaceTokenRenewalLoop(options: ToolspaceTokenRenewalOptions): ToolspaceTokenRenewalController;
@@ -72,6 +72,7 @@ type CaptureRepositoryReadResult = {
72
72
  complete: true;
73
73
  status: Awaited<ReturnType<SandboxChannelAService["gitStatus"]>>;
74
74
  diff: Awaited<ReturnType<SandboxChannelAService["gitDiff"]>>;
75
+ branchDiff?: Awaited<ReturnType<SandboxChannelAService["gitDiff"]>> | undefined;
75
76
  } | {
76
77
  complete: false;
77
78
  degradedReason: "repository_read_unavailable";
@@ -104,6 +104,7 @@ export declare function createControlActivities(dependencies?: ActivityDependenc
104
104
  command: string;
105
105
  }[];
106
106
  }>;
107
+ maintainRetainedScreenshots: () => Promise<import("./activities/retained-screenshot-reaper").MaintainRetainedScreenshotsResult>;
107
108
  };
108
109
  export declare function createTurnActivities(dependencies?: ActivityDependencies): {
109
110
  runAgentTurn: (input: import("./activities").RunAgentTurnInput) => Promise<import("./activities").RunAgentTurnResult>;
@@ -213,6 +214,7 @@ export declare function createActivityTestHarness(dependencies?: ActivityDepende
213
214
  command: string;
214
215
  }[];
215
216
  }>;
217
+ maintainRetainedScreenshots: () => Promise<import("./activities/retained-screenshot-reaper").MaintainRetainedScreenshotsResult>;
216
218
  runAgentTurn: (input: import("./activities").RunAgentTurnInput) => Promise<import("./activities").RunAgentTurnResult>;
217
219
  };
218
220
  export declare const runAgentTurn: (input: import("./activities").RunAgentTurnInput) => Promise<import("./activities").RunAgentTurnResult>;
@@ -278,6 +280,7 @@ export declare const getCodexCapacityWait: (input: import("./activities").GetCod
278
280
  export declare const reconcileCodexCapacityWait: (input: import("./activities").ReconcileCodexCapacityWaitInput) => Promise<import("./activities").ReconcileCodexCapacityWaitResult>;
279
281
  export declare const reapSandboxLeases: () => Promise<import("./activities/sandbox-lease").ReapSandboxLeasesResult>;
280
282
  export declare const reapExpiredFileUploads: () => Promise<import("./activities/file-upload-reaper").ReapExpiredFileUploadsResult>;
283
+ export declare const maintainRetainedScreenshots: () => Promise<import("./activities/retained-screenshot-reaper").MaintainRetainedScreenshotsResult>;
281
284
  export declare const dispatchSessionWorkflowWakes: () => Promise<import("./activities/workflow-wake").DispatchSessionWorkflowWakesResult>;
282
285
  export declare const verifyRigChange: (input: {
283
286
  workspaceId: string;
@@ -93,7 +93,7 @@ function createHostExportPump(options) {
93
93
  maxBytes: batchMaxBytes
94
94
  };
95
95
  const settleFailure = async (error) => {
96
- const message = safeErrorMessage(error);
96
+ const message = exactHostExportErrorMessage(error);
97
97
  let failures = 0;
98
98
  try {
99
99
  failures = await failHostExportBatch(options.db, {
@@ -106,17 +106,15 @@ function createHostExportPump(options) {
106
106
  } catch (settlementError) {
107
107
  options.observability?.warn("host export failure settlement was stale", {
108
108
  kind,
109
- consumerId,
110
- error: safeErrorMessage(settlementError)
109
+ ...hostExportPublicErrorFields(settlementError, "host_export_failure_settlement_stale")
111
110
  });
112
111
  }
113
112
  const blocked = failures >= maxFailures;
114
113
  options.observability?.warn("host export batch failed", {
115
114
  kind,
116
- consumerId,
117
115
  failures,
118
116
  blocked,
119
- error: message
117
+ ...hostExportPublicErrorFields(error, "host_export_batch_delivery_failed")
120
118
  });
121
119
  const result2 = {
122
120
  kind,
@@ -143,8 +141,7 @@ function createHostExportPump(options) {
143
141
  } catch (error) {
144
142
  options.observability?.error("host export retention prune failed", {
145
143
  kind,
146
- consumerId,
147
- error: safeErrorMessage(error)
144
+ ...hostExportPublicErrorFields(error, "host_export_retention_prune_failed")
148
145
  });
149
146
  }
150
147
  const result2 = {
@@ -258,7 +255,7 @@ function createHostExportPump(options) {
258
255
  }
259
256
  } catch (error) {
260
257
  options.observability?.error("host export pump iteration failed", {
261
- error: safeErrorMessage(error)
258
+ ...hostExportPublicErrorFields(error, "host_export_pump_iteration_failed")
262
259
  });
263
260
  }
264
261
  if (running) await waitForPoll();
@@ -314,12 +311,18 @@ function validateInstanceId(value) {
314
311
  }
315
312
  return value;
316
313
  }
317
- function safeErrorMessage(error) {
318
- const message = error instanceof Error ? error.message : String(error);
319
- return message.trim().slice(0, 500) || "host sink failed";
314
+ function exactHostExportErrorMessage(error) {
315
+ return error instanceof Error ? error.message : String(error);
316
+ }
317
+ function hostExportPublicErrorFields(_error, errorCode) {
318
+ return {
319
+ errorClass: "HostExportOperationError",
320
+ errorCode,
321
+ origin: "host-export"
322
+ };
320
323
  }
321
324
 
322
325
  export {
323
326
  createHostExportPump
324
327
  };
325
- //# sourceMappingURL=chunk-BJUW5LCM.js.map
328
+ //# sourceMappingURL=chunk-RAMNYSAW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/host-export-pump.ts"],"sourcesContent":["import type { HostEventSink, HostUsageSink } from \"@opengeni/contracts\";\nimport {\n acknowledgeHostExportBatch,\n claimHostExportBatch,\n disableHostExportConsumer,\n failHostExportBatch,\n getHostExportConsumerStatus,\n pruneHostExportOutbox,\n registerHostExportConsumer,\n retireHostExportConsumer,\n type Database,\n type HostExportConsumerStatus,\n type HostExportKind,\n} from \"@opengeni/db\";\nimport type { Observability } from \"@opengeni/observability\";\n\nexport type HostExportDrainResult =\n | { kind: HostExportKind; outcome: \"not_configured\" | \"idle\" }\n | { kind: HostExportKind; outcome: \"blocked\"; failures: number }\n | {\n kind: HostExportKind;\n outcome: \"delivered\";\n count: number;\n throughCursor: string;\n }\n | {\n kind: HostExportKind;\n outcome: \"failed\";\n failures: number;\n blocked: boolean;\n };\n\nexport type HostExportPumpOptions = {\n /** A handle authenticated as the separately provisioned host-export role. */\n db: Database;\n eventSink?: HostEventSink;\n usageSink?: HostUsageSink;\n observability?: Observability;\n instanceId?: string;\n pollIntervalMs?: number;\n leaseSeconds?: number;\n batchLimit?: number;\n batchMaxBytes?: number;\n maxFailures?: number;\n /** Maximum catch-up batches per poll tick; bounds one iteration's work. */\n maxBatchesPerPoll?: number;\n /** Acked rows younger than this remain available for replay. */\n pruneGraceSeconds?: number;\n /** Maximum rows pruned after one successful acknowledgement. */\n pruneLimit?: number;\n};\n\nexport type HostExportPump = {\n /** Register configured consumers and start the non-overlapping poll loop. */\n start: () => Promise<void>;\n /** Stop polling and wait for the currently executing sink call, if any. */\n stop: () => Promise<void>;\n /** Execute at most one bounded batch for each configured sink. */\n drainOnce: () => Promise<HostExportDrainResult[]>;\n /**\n * Disable this named consumer while retaining its replay checkpoint. If it is\n * the last enabled consumer of the kind, capture stops and that interval is\n * intentionally unrecoverable. Normal process shutdown must not call this.\n */\n disable: (kind: HostExportKind) => Promise<void>;\n /** Permanently remove a stopped consumer and release its retention floor. */\n retire: (kind: HostExportKind) => Promise<void>;\n status: (kind: HostExportKind) => Promise<HostExportConsumerStatus | null>;\n};\n\n/**\n * Build the durable delivery loop used by embedded hosts.\n *\n * The source transaction writes the outbox; this pump only leases, delivers,\n * and checkpoints it. Delivery is intentionally at least once: a process death\n * after sink success but before acknowledgement repeats the same idempotency\n * keys. Sink implementations must therefore deduplicate those keys.\n */\nexport function createHostExportPump(options: HostExportPumpOptions): HostExportPump {\n if (!options.eventSink && !options.usageSink) {\n throw new Error(\"createHostExportPump requires at least one host sink\");\n }\n const instanceId = validateInstanceId(\n options.instanceId ?? `worker-${process.pid}-${crypto.randomUUID()}`,\n );\n const pollIntervalMs = boundedInteger(options.pollIntervalMs, 1_000, 25, 60_000);\n const leaseSeconds = boundedInteger(options.leaseSeconds, 60, 5, 300);\n const batchLimit = boundedInteger(options.batchLimit, 100, 1, 256);\n const batchMaxBytes = boundedInteger(options.batchMaxBytes, 1_048_576, 98_304, 4_194_304);\n const maxFailures = boundedInteger(options.maxFailures, 20, 1, 1_000);\n const maxBatchesPerPoll = boundedInteger(options.maxBatchesPerPoll, 32, 1, 1_000);\n const pruneGraceSeconds = boundedInteger(options.pruneGraceSeconds, 3_600, 0, 604_800);\n const pruneLimit = boundedInteger(options.pruneLimit, 1_000, 1, 10_000);\n let running = false;\n let loopPromise: Promise<void> | null = null;\n let waitTimer: ReturnType<typeof setTimeout> | null = null;\n let wakeWait: (() => void) | null = null;\n let lifecycleTail: Promise<void> = Promise.resolve();\n let drainTail: Promise<void> = Promise.resolve();\n const retiringKinds = new Set<HostExportKind>();\n\n const configuredConsumer = (kind: HostExportKind): string | null =>\n kind === \"session_event\"\n ? (options.eventSink?.consumerId ?? null)\n : (options.usageSink?.consumerId ?? null);\n\n const recordResult = (result: HostExportDrainResult, durationSeconds: number) => {\n const labels = { kind: result.kind, outcome: result.outcome };\n options.observability?.incrementCounter({\n name: \"opengeni_host_export_batches_total\",\n help: \"Durable host export batch attempts by outcome.\",\n labels,\n });\n options.observability?.observeHistogram({\n name: \"opengeni_host_export_batch_duration_seconds\",\n help: \"Duration of durable host export batch attempts.\",\n labels: { kind: result.kind },\n value: durationSeconds,\n });\n if (result.outcome === \"delivered\") {\n options.observability?.incrementCounter({\n name: \"opengeni_host_export_records_total\",\n help: \"Durable host export records acknowledged by a host sink.\",\n labels: { kind: result.kind },\n amount: result.count,\n });\n options.observability?.setGauge({\n name: \"opengeni_host_export_consumer_blocked\",\n help: \"Whether the durable host export consumer is blocked.\",\n labels: { kind: result.kind },\n value: 0,\n });\n } else if (result.outcome === \"failed\") {\n options.observability?.setGauge({\n name: \"opengeni_host_export_consumer_blocked\",\n help: \"Whether the durable host export consumer is blocked.\",\n labels: { kind: result.kind },\n value: result.blocked ? 1 : 0,\n });\n } else if (result.outcome === \"blocked\") {\n options.observability?.setGauge({\n name: \"opengeni_host_export_consumer_blocked\",\n help: \"Whether the durable host export consumer is blocked.\",\n labels: { kind: result.kind },\n value: 1,\n });\n }\n };\n\n const drainKind = async (kind: HostExportKind): Promise<HostExportDrainResult> => {\n if (retiringKinds.has(kind)) return { kind, outcome: \"not_configured\" };\n const startedAt = performance.now();\n const consumerId = configuredConsumer(kind);\n if (!consumerId) {\n const result: HostExportDrainResult = { kind, outcome: \"not_configured\" };\n recordResult(result, (performance.now() - startedAt) / 1_000);\n return result;\n }\n const leaseToken = crypto.randomUUID();\n const common = {\n consumerId,\n leaseToken,\n leaseHolderId: instanceId,\n leaseSeconds,\n limit: batchLimit,\n maxBytes: batchMaxBytes,\n };\n const settleFailure = async (error: unknown): Promise<HostExportDrainResult> => {\n const message = exactHostExportErrorMessage(error);\n let failures = 0;\n try {\n failures = await failHostExportBatch(options.db, {\n kind,\n consumerId,\n leaseToken,\n error: message,\n maxFailures,\n });\n } catch (settlementError) {\n options.observability?.warn(\"host export failure settlement was stale\", {\n kind,\n ...hostExportPublicErrorFields(settlementError, \"host_export_failure_settlement_stale\"),\n });\n }\n const blocked = failures >= maxFailures;\n options.observability?.warn(\"host export batch failed\", {\n kind,\n failures,\n blocked,\n ...hostExportPublicErrorFields(error, \"host_export_batch_delivery_failed\"),\n });\n const result: HostExportDrainResult = {\n kind,\n outcome: \"failed\",\n failures,\n blocked,\n };\n recordResult(result, (performance.now() - startedAt) / 1_000);\n return result;\n };\n const deliverClaim = async (\n count: number,\n deliver: () => Promise<void>,\n ): Promise<HostExportDrainResult> => {\n await deliver();\n const throughCursor = await acknowledgeHostExportBatch(options.db, {\n kind,\n consumerId,\n leaseToken,\n });\n try {\n await pruneHostExportOutbox(options.db, {\n kind,\n graceSeconds: pruneGraceSeconds,\n limit: pruneLimit,\n });\n } catch (error) {\n // The sink and checkpoint are already committed. A retention failure\n // must be visible, but must never turn into a false delivery failure or\n // a duplicate settlement attempt for the now-stale lease.\n options.observability?.error(\"host export retention prune failed\", {\n kind,\n ...hostExportPublicErrorFields(error, \"host_export_retention_prune_failed\"),\n });\n }\n const result: HostExportDrainResult = {\n kind,\n outcome: \"delivered\",\n count,\n throughCursor,\n };\n recordResult(result, (performance.now() - startedAt) / 1_000);\n return result;\n };\n\n try {\n if (kind === \"session_event\") {\n const sink = options.eventSink;\n if (!sink) return { kind, outcome: \"not_configured\" };\n const batch = await claimHostExportBatch(options.db, {\n kind,\n ...common,\n });\n if (batch) return await deliverClaim(batch.events.length, () => sink.deliverEvents(batch));\n } else {\n const sink = options.usageSink;\n if (!sink) return { kind, outcome: \"not_configured\" };\n const batch = await claimHostExportBatch(options.db, {\n kind,\n ...common,\n });\n if (batch) return await deliverClaim(batch.events.length, () => sink.deliverUsage(batch));\n }\n } catch (error) {\n return await settleFailure(error);\n }\n const status = await getHostExportConsumerStatus(options.db, {\n kind,\n consumerId,\n });\n if (status?.blockedAt) {\n const result: HostExportDrainResult = {\n kind,\n outcome: \"blocked\",\n failures: status.consecutiveFailures,\n };\n recordResult(result, (performance.now() - startedAt) / 1_000);\n return result;\n }\n const result: HostExportDrainResult = { kind, outcome: \"idle\" };\n recordResult(result, (performance.now() - startedAt) / 1_000);\n return result;\n };\n\n const drainConfiguredOnce = async (): Promise<HostExportDrainResult[]> => {\n const results: HostExportDrainResult[] = [];\n if (options.eventSink) results.push(await drainKind(\"session_event\"));\n if (options.usageSink) results.push(await drainKind(\"usage_event\"));\n return results;\n };\n\n const drainOnce = (): Promise<HostExportDrainResult[]> => {\n const next = drainTail.then(drainConfiguredOnce);\n drainTail = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n };\n\n const serializeLifecycle = <T>(operation: () => Promise<T>): Promise<T> => {\n const next = lifecycleTail.then(operation);\n lifecycleTail = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n };\n\n const waitForPoll = async (): Promise<void> => {\n await new Promise<void>((resolve) => {\n wakeWait = resolve;\n waitTimer = setTimeout(resolve, pollIntervalMs);\n waitTimer.unref?.();\n });\n wakeWait = null;\n if (waitTimer) clearTimeout(waitTimer);\n waitTimer = null;\n };\n\n return {\n start: () =>\n serializeLifecycle(async () => {\n if (running) return;\n await options.db.transaction(async (tx) => {\n const scoped = tx as unknown as Database;\n if (options.eventSink) {\n await registerHostExportConsumer(scoped, {\n kind: \"session_event\",\n consumerId: options.eventSink.consumerId,\n });\n }\n if (options.usageSink) {\n await registerHostExportConsumer(scoped, {\n kind: \"usage_event\",\n consumerId: options.usageSink.consumerId,\n });\n }\n });\n if (options.eventSink) retiringKinds.delete(\"session_event\");\n if (options.usageSink) retiringKinds.delete(\"usage_event\");\n running = true;\n loopPromise = (async () => {\n while (true) {\n if (!running) break;\n try {\n for (let batch = 0; batch < maxBatchesPerPoll; batch += 1) {\n if (!running) break;\n const results = await drainOnce();\n if (!results.some((result) => result.outcome === \"delivered\")) break;\n }\n } catch (error) {\n options.observability?.error(\"host export pump iteration failed\", {\n ...hostExportPublicErrorFields(error, \"host_export_pump_iteration_failed\"),\n });\n }\n if (running) await waitForPoll();\n }\n })();\n }),\n stop: () =>\n serializeLifecycle(async () => {\n running = false;\n if (waitTimer) clearTimeout(waitTimer);\n wakeWait?.();\n await loopPromise;\n loopPromise = null;\n }),\n drainOnce,\n disable: async (kind) => {\n const consumerId = configuredConsumer(kind);\n if (!consumerId) throw new Error(`No ${kind} sink is configured`);\n await disableHostExportConsumer(options.db, { kind, consumerId });\n },\n retire: (kind) =>\n serializeLifecycle(async () => {\n if (running) throw new Error(\"Stop the host export pump before retiring a consumer\");\n const consumerId = configuredConsumer(kind);\n if (!consumerId) throw new Error(`No ${kind} sink is configured`);\n retiringKinds.add(kind);\n try {\n await drainTail;\n await retireHostExportConsumer(options.db, { kind, consumerId });\n } catch (error) {\n retiringKinds.delete(kind);\n throw error;\n }\n }),\n status: async (kind) => {\n const consumerId = configuredConsumer(kind);\n if (!consumerId) return null;\n return await getHostExportConsumerStatus(options.db, {\n kind,\n consumerId,\n });\n },\n };\n}\n\nfunction boundedInteger(\n value: number | undefined,\n fallback: number,\n minimum: number,\n maximum: number,\n): number {\n const candidate = value ?? fallback;\n if (!Number.isInteger(candidate) || candidate < minimum || candidate > maximum) {\n throw new Error(`Expected an integer between ${minimum} and ${maximum}`);\n }\n return candidate;\n}\n\nfunction validateInstanceId(value: string): string {\n if (value.length < 1 || value.length > 128) {\n throw new Error(\"Host export instanceId must contain 1 to 128 characters\");\n }\n return value;\n}\n\nfunction exactHostExportErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype HostExportPublicFailureCode =\n | \"host_export_failure_settlement_stale\"\n | \"host_export_batch_delivery_failed\"\n | \"host_export_retention_prune_failed\"\n | \"host_export_pump_iteration_failed\";\n\nfunction hostExportPublicErrorFields(\n _error: unknown,\n errorCode: HostExportPublicFailureCode,\n): {\n errorClass: \"HostExportOperationError\";\n errorCode: HostExportPublicFailureCode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aAAO,MAAM,4BAA4B,QAAQ,IAAI;AAAA,QACnD;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,SAAS,eACP,OACA,UACA,SACA,SACQ;AACR,QAAM,YAAY,SAAS;AAC3B,MAAI,CAAC,OAAO,UAAU,SAAS,KAAK,YAAY,WAAW,YAAY,SAAS;AAC9E,UAAM,IAAI,MAAM,+BAA+B,OAAO,QAAQ,OAAO,EAAE;AAAA,EACzE;AACA,SAAO;AACT;AAEA,SAAS,mBAAmB,OAAuB;AACjD,MAAI,MAAM,SAAS,KAAK,MAAM,SAAS,KAAK;AAC1C,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC3E;AACA,SAAO;AACT;AAEA,SAAS,4BAA4B,OAAwB;AAC3D,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAQA,SAAS,4BACP,QACA,WAKA;AACA,SAAO;AAAA,IACL,YAAY;AAAA,IACZ;AAAA,IACA,QAAQ;AAAA,EACV;AACF;","names":["result"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createHostExportPump
3
- } from "./chunk-BJUW5LCM.js";
3
+ } from "./chunk-RAMNYSAW.js";
4
4
  export {
5
5
  createHostExportPump
6
6
  };