@opengeni/worker-bundle 1.4.0 → 1.4.2

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 (36) hide show
  1. package/dist/activities/agent-turn/sandbox-provision.d.ts +22 -0
  2. package/dist/activities/agent-turn/turn-context.d.ts +6 -0
  3. package/dist/activities/agent-turn/web-search.d.ts +5 -1
  4. package/dist/activities/codemode-dispatcher.d.ts +8 -0
  5. package/dist/activities/programmatic-approvals.d.ts +0 -17
  6. package/dist/activities/sandbox-lease.d.ts +4 -0
  7. package/dist/{activities-control-D5KVEPHI.js → activities-control-AKJZHDTY.js} +53 -13
  8. package/dist/activities-control-AKJZHDTY.js.map +1 -0
  9. package/dist/{activities-turn-4Z3M7Z3F.js → activities-turn-AOXNE6BM.js} +6038 -5890
  10. package/dist/activities-turn-AOXNE6BM.js.map +1 -0
  11. package/dist/{chunk-FF4HPY7L.js → chunk-DCQ7XTXW.js} +108 -3
  12. package/dist/chunk-DCQ7XTXW.js.map +1 -0
  13. package/dist/{chunk-BMTWULF7.js → chunk-WVZQJBGD.js} +55 -17
  14. package/dist/chunk-WVZQJBGD.js.map +1 -0
  15. package/dist/index.js +2 -2
  16. package/dist/observability-metrics.d.ts +52 -14
  17. package/dist/sandbox-resume.d.ts +3 -0
  18. package/package.json +21 -21
  19. package/src/activities/agent-turn/errors.ts +7 -7
  20. package/src/activities/agent-turn/finalization.ts +16 -0
  21. package/src/activities/agent-turn/run.ts +12 -0
  22. package/src/activities/agent-turn/sandbox-establish.ts +87 -80
  23. package/src/activities/agent-turn/sandbox-provision.ts +51 -0
  24. package/src/activities/agent-turn/stream-attempt.ts +37 -50
  25. package/src/activities/agent-turn/turn-context.ts +8 -0
  26. package/src/activities/agent-turn/web-search.ts +135 -6
  27. package/src/activities/codemode-dispatcher.ts +57 -8
  28. package/src/activities/programmatic-approvals.ts +0 -26
  29. package/src/activities/sandbox-lease.ts +63 -10
  30. package/src/observability-metrics.ts +130 -18
  31. package/src/sandbox-resume.ts +24 -5
  32. package/src/sandbox-routing.ts +12 -0
  33. package/dist/activities-control-D5KVEPHI.js.map +0 -1
  34. package/dist/activities-turn-4Z3M7Z3F.js.map +0 -1
  35. package/dist/chunk-BMTWULF7.js.map +0 -1
  36. package/dist/chunk-FF4HPY7L.js.map +0 -1
@@ -48,6 +48,28 @@ export declare class SandboxDeadlineRotationError extends Error {
48
48
  export declare function turnOperationCancellationFailure(error: unknown): CancelledFailure | null;
49
49
  export declare function throwIfTurnOperationCancelled(signal: AbortSignal | undefined): void;
50
50
  export declare function waitForTurnOperation<T>(operation: Promise<T>, signal: AbortSignal | undefined, disposeLateResult: ((result: T) => Promise<void> | void) | undefined): Promise<T>;
51
+ /**
52
+ * Upper bound for joining a cancelled attempt's in-flight provider establish.
53
+ * Worker shutdown cancels activities 5s after SIGTERM and force-stops 100s
54
+ * after it; this leaves room for the remaining finalization steps.
55
+ */
56
+ export declare const PHYSICAL_SANDBOX_RESUME_DRAIN_TIMEOUT_MS = 60000;
57
+ /** Register the PHYSICAL lease acquire/provider establish promise, not the
58
+ * cancellable wrapper awaiting it. */
59
+ export declare function trackPhysicalSandboxResume<T>(inFlight: Set<Promise<unknown>>, operation: Promise<T>): Promise<T>;
60
+ /**
61
+ * Join every lease acquire/provider establish this attempt started, even after
62
+ * the turn-facing wrapper rejected on cancellation. An establish has no
63
+ * portable abort: after cancellation it still finishes its own exact cleanup
64
+ * (terminate an unpublished box and roll warming back to cold, or keep a
65
+ * published box and drop its holder). If the activity returned first, a
66
+ * shutting-down worker exited mid-cleanup and stranded a warming lease naming a
67
+ * terminated box; the replacement attempt then waited out the warming TTL and
68
+ * inherited a lost-workspace verdict. This wait is deliberately independent of
69
+ * the finalizer cancellation signal (cancellation is what started it) and is
70
+ * bounded so an uncooperative provider call cannot pin the activity.
71
+ */
72
+ export declare function drainPhysicalSandboxResumes(inFlight: Set<Promise<unknown>>, timeoutMs?: number): Promise<"none" | "settled" | "timed_out">;
51
73
  export declare function sleep(ms: number): Promise<void>;
52
74
  export declare function sandboxProvisionErrorChain(error: unknown): unknown[];
53
75
  export declare function firstProvisionError<T>(chain: readonly unknown[], constructor: abstract new (...args: never[]) => T): T | null;
@@ -78,6 +78,9 @@ export type SandboxRuntimeState = {
78
78
  }>;
79
79
  turnSandboxProvisioner: TurnSandboxProvisioner<ResumedTurnSandbox> | null;
80
80
  resumeManagedGroupBox: (() => Promise<ResumedTurnSandbox>) | null;
81
+ /** Physical resumeBoxForTurn promises still running for this attempt; the
82
+ * finalizer joins them so a cancelled establish completes its own cleanup. */
83
+ inFlightSandboxResumes: Set<Promise<unknown>>;
81
84
  prefetchedManagedBox: Promise<ResumedTurnSandbox> | null;
82
85
  prefetchedManagedBoxResult: ResumedTurnSandbox | null;
83
86
  setupBoxSession: unknown;
@@ -127,6 +130,9 @@ export type EventingState = {
127
130
  firstModelRequestPreparationRecorded: boolean;
128
131
  firstModelRequestCheckpointAt: number | null;
129
132
  initialModelWireDispatch: InitialModelWireDispatchClock;
133
+ /** Diagnostic only: the current stream's timing hook for a native transport's
134
+ * literal provider dispatch. Never joins, fences or fails the request. */
135
+ providerDispatchObserver: (() => void) | null;
130
136
  companyBrainContextContributions: readonly ModelContextContributionSummary[] | null;
131
137
  /** Skill ids in this turn's frozen, model-visible Skill index; telemetry only. */
132
138
  modelVisibleSkillIds: ReadonlySet<string> | null;
@@ -18,6 +18,9 @@ export declare function turnWebSearchPlan(resolvedModel: {
18
18
  hostedWebSearch: boolean;
19
19
  providerTools: WebSearchProviderToolName[];
20
20
  };
21
+ /** Closed outcome set for `opengeni_web_search_calls_total`. */
22
+ export type WebSearchCallOutcome = "ok" | "provider_error" | "provider_retryable" | "billing_refused" | "error";
23
+ type WebSearchObservability = Pick<Observability, "warn" | "incrementCounter" | "observeHistogram">;
21
24
  /**
22
25
  * The `web_search` and `web_fetch` attempt tools for one turn. The caller
23
26
  * decides which names the turn gets ({@link webSearchToolPlan}); this only
@@ -28,6 +31,7 @@ export declare function webSearchToolDefinitions(input: {
28
31
  tools: readonly WebSearchProviderToolName[];
29
32
  scope: WebSearchCallScope;
30
33
  billing: WebSearchBilling;
31
- observability: Pick<Observability, "warn">;
34
+ observability: WebSearchObservability;
32
35
  fetch?: typeof fetch;
33
36
  }): AttemptToolDefinition[];
37
+ export {};
@@ -43,7 +43,15 @@ export declare class CodemodeAttemptDispatcher {
43
43
  beginWait(): (accepted: boolean) => void;
44
44
  } | undefined);
45
45
  start(): void;
46
+ /**
47
+ * Join-on-use recovery before the first model request. The journal read needs
48
+ * no tool environment, so a turn with nothing unfinished returns at once and
49
+ * never waits on lazy MCP preparation. Only a stored waiting/queued/running
50
+ * operation awaits the prepared dispatcher to adopt and execute it.
51
+ */
52
+ static resumeApproved(db: Database, scope: CodemodeDispatcherScope, callerSubjectId: string, decisionOperationId: string | undefined, prepared: () => Promise<CodemodeAttemptDispatcher | null>): Promise<CodemodeOperation[]>;
46
53
  resumeApproved(callerSubjectId: string, decisionOperationId?: string): Promise<CodemodeOperation[]>;
54
+ private resumeOperations;
47
55
  close(reason?: string): Promise<void>;
48
56
  private execute;
49
57
  private executeClaimed;
@@ -8,20 +8,3 @@ export declare function programmaticApproval(operation: CodemodeOperation): {
8
8
  requestId: string | undefined;
9
9
  };
10
10
  export declare function programmaticContinuationNote(operations: readonly CodemodeOperation[]): string | undefined;
11
- /**
12
- * Recover committed programmatic approval waits/results before the first model
13
- * request without turning lazy MCP preparation into a first-request barrier.
14
- *
15
- * Only eager servers may gate the first request. Resuming a stored operation
16
- * needs the prepared attempt tool environment, so this waits for full tool
17
- * preparation only when there is something to resume: an approval decision
18
- * trigger, or a cheap durable read showing unfinished operations for this
19
- * logical turn (which covers every recovery that has stored work). Every other
20
- * turn sends its first request without waiting on any lazy server.
21
- */
22
- export declare function recoverProgrammaticOperationsBeforeFirstRequest(input: {
23
- approvalDecisionId: string | undefined;
24
- hasUnfinishedOperations: () => Promise<boolean>;
25
- toolPreparationReady: Promise<void> | null;
26
- resumeApproved: (decisionOperationId: string | undefined) => Promise<CodemodeOperation[]> | undefined;
27
- }): Promise<CodemodeOperation[]>;
@@ -209,6 +209,10 @@ export declare function probeRetainedProcessAtProvider(settings: ActivityService
209
209
  export declare function classifyRetainedProcessPollResult(result: unknown, providerSessionId: number, source?: object): RetainedProcessProbeResult;
210
210
  export declare function reconcileModalProviderCreates(db: ActivityServices["db"], settings: ActivityServices["settings"], observability: ActivityServices["observability"], discover?: typeof findModalProviderCreateReceipt): Promise<void>;
211
211
  export declare function modalOrphanTerminationStillEligible(latest: Awaited<ReturnType<typeof listLiveModalSandboxLeaseAttributions>>, candidate: ModalOrphanSweepTermination): boolean;
212
+ /** Whether no live lease owns the candidate box by exact instance or by its
213
+ * attribution tags. Unlike termination eligibility this ignores the pending
214
+ * create postponement: a postponed orphan is still running without a lease. */
215
+ export declare function modalOrphanCandidateStillUnowned(latest: Awaited<ReturnType<typeof listLiveModalSandboxLeaseAttributions>>, candidate: ModalOrphanSweepTermination): boolean;
212
216
  export type SandboxDrainReason = "idle" | "provider_deadline" | "operator" | "teardown_claim" | "rotation_requested";
213
217
  /** The bounded drain reason carried on `sandbox.box.terminated`: the lease's
214
218
  * rotation reason when a rotation was requested, otherwise the ordinary idle
@@ -34,7 +34,7 @@ import {
34
34
  warnDrainSnapshotFailure,
35
35
  withFirstPartyTools,
36
36
  workflowIdForSession
37
- } from "./chunk-BMTWULF7.js";
37
+ } from "./chunk-WVZQJBGD.js";
38
38
  import {
39
39
  inspectOpenSandboxKubernetesInventory,
40
40
  recordActiveUserGauges,
@@ -42,7 +42,9 @@ import {
42
42
  recordCreditGrantGauges,
43
43
  recordCreditMicros,
44
44
  recordExpiredDrainingSandboxLeaseGauges,
45
+ recordInteractionOnlyLeaseGauges,
45
46
  recordManagedAuthNewSignupsSwitchGauge,
47
+ recordModalSandboxInventoryGauges,
46
48
  recordOpenSandboxKubernetesInventoryGauges,
47
49
  recordRetainedProcessInventoryGauges,
48
50
  recordRetainedProcessReconciliation,
@@ -62,7 +64,7 @@ import {
62
64
  recordVerifiedSignupTrialSwitchGauge,
63
65
  recordWorkerDeathRecoveryMetrics,
64
66
  runtimeMetricsHooksForObservability
65
- } from "./chunk-FF4HPY7L.js";
67
+ } from "./chunk-DCQ7XTXW.js";
66
68
  import "./chunk-PZ5AY32C.js";
67
69
 
68
70
  // src/activities/knowledge-indexing.ts
@@ -2790,6 +2792,7 @@ import {
2790
2792
  recordRecoveredModalProviderCreate,
2791
2793
  markWarmBillingStopCutoff,
2792
2794
  listMeterableWarmLeases,
2795
+ countInteractionOnlyWarmLeasesByIdle,
2793
2796
  listSandboxViewerForceDrainWorkspaceIds,
2794
2797
  markSandboxCheckpointArtifactDeletePending as markSandboxCheckpointArtifactDeletePending2,
2795
2798
  persistDrainSnapshot,
@@ -4599,6 +4602,17 @@ async function refreshQueueLeaseAndCreditGauges(db, settings, observability, ins
4599
4602
  );
4600
4603
  }
4601
4604
  ),
4605
+ refreshSandboxInventoryGauge(
4606
+ observability,
4607
+ "interaction_idle",
4608
+ "interaction-only-lease",
4609
+ async () => {
4610
+ recordInteractionOnlyLeaseGauges(
4611
+ observability,
4612
+ await countInteractionOnlyWarmLeasesByIdle(db, await listMeterableWarmLeases(db))
4613
+ );
4614
+ }
4615
+ ),
4602
4616
  refreshSandboxInventoryGauge(observability, "expired_drains", "expired-draining", async () => {
4603
4617
  recordExpiredDrainingSandboxLeaseGauges(
4604
4618
  observability,
@@ -4751,6 +4765,9 @@ function modalOrphanTerminationStillEligible(latest, candidate) {
4751
4765
  if (latest.some((lease) => lease.liveness === "warming" && lease.instanceId === null)) {
4752
4766
  return false;
4753
4767
  }
4768
+ return modalOrphanCandidateStillUnowned(latest, candidate);
4769
+ }
4770
+ function modalOrphanCandidateStillUnowned(latest, candidate) {
4754
4771
  if (latest.some((lease) => lease.instanceId === candidate.sandboxId)) {
4755
4772
  return false;
4756
4773
  }
@@ -4786,6 +4803,26 @@ async function sweepModalOrphansForConfiguredBackend(settings, db, observability
4786
4803
  return modalOrphanTerminationStillEligible(latest, candidate);
4787
4804
  }
4788
4805
  });
4806
+ if (result.inventory.complete) {
4807
+ try {
4808
+ const latest = await listLiveModalSandboxLeaseAttributions(db);
4809
+ recordModalSandboxInventoryGauges(observability, {
4810
+ running: result.inventory.running,
4811
+ unleased: result.inventory.unterminated.filter(
4812
+ (candidate) => modalOrphanCandidateStillUnowned(latest, candidate)
4813
+ ).length,
4814
+ liveLeaseInstancesMissing: result.inventory.missingLiveLeaseInstanceIds.filter(
4815
+ (instanceId) => latest.some((lease) => lease.instanceId === instanceId)
4816
+ ).length
4817
+ });
4818
+ recordSandboxInventoryProjectionSuccess(observability, "modal_provider");
4819
+ } catch (error) {
4820
+ recordSandboxInventoryProjectionFailure(observability, "modal_provider");
4821
+ observability.warn("sandbox reaper: Modal inventory ownership re-read failed", {
4822
+ error: error instanceof Error ? error.message : String(error)
4823
+ });
4824
+ }
4825
+ }
4789
4826
  for (const terminated of result.terminated) {
4790
4827
  observability.warn("sandbox reaper: terminated Modal orphan sandbox", {
4791
4828
  sandboxId: terminated.sandboxId,
@@ -5174,15 +5211,18 @@ async function terminateDrainableBox(db, settings, row, observability, terminate
5174
5211
  }
5175
5212
  }
5176
5213
  const providerMissing = providerMissingBeforeCapture || (typeof termination === "boolean" ? false : termination.providerMissingBeforeCapture);
5177
- const { wentCold, backgroundCommandEvents } = await confirmDrainCold(db, {
5178
- accountId,
5179
- workspaceId: row.workspaceId,
5180
- sandboxGroupId: row.sandboxGroupId,
5181
- expectedEpoch: row.leaseEpoch,
5182
- ...captureClaim ? { expectedCaptureId: captureClaim.id } : {},
5183
- providerMissingBeforeCapture: providerMissing,
5184
- idleCommandContainmentMs: settings.sandboxIdleCommandContainmentMs
5185
- });
5214
+ const { wentCold, unpublishedProviderLost, backgroundCommandEvents } = await confirmDrainCold(
5215
+ db,
5216
+ {
5217
+ accountId,
5218
+ workspaceId: row.workspaceId,
5219
+ sandboxGroupId: row.sandboxGroupId,
5220
+ expectedEpoch: row.leaseEpoch,
5221
+ ...captureClaim ? { expectedCaptureId: captureClaim.id } : {},
5222
+ providerMissingBeforeCapture: providerMissing,
5223
+ idleCommandContainmentMs: settings.sandboxIdleCommandContainmentMs
5224
+ }
5225
+ );
5186
5226
  await publishDurableSessionEvents(bus, row.workspaceId, backgroundCommandEvents, (error) => {
5187
5227
  observability.warn("sandbox reaper: contained command event fanout failed", {
5188
5228
  sandboxGroupId: row.sandboxGroupId,
@@ -5190,7 +5230,7 @@ async function terminateDrainableBox(db, settings, row, observability, terminate
5190
5230
  });
5191
5231
  });
5192
5232
  if (wentCold) {
5193
- if (providerMissing) {
5233
+ if (providerMissing && !unpublishedProviderLost) {
5194
5234
  recordSandboxProviderMissingBeforeCapture(observability, backend);
5195
5235
  }
5196
5236
  if (lease.unobservableCommandDrainIds?.length) {
@@ -8813,4 +8853,4 @@ export {
8813
8853
  createControlActivities,
8814
8854
  createControlActivitiesFromServices
8815
8855
  };
8816
- //# sourceMappingURL=activities-control-D5KVEPHI.js.map
8856
+ //# sourceMappingURL=activities-control-AKJZHDTY.js.map