@opengeni/worker-bundle 1.3.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 (45) hide show
  1. package/dist/activities/agent-turn/errors.d.ts +1 -13
  2. package/dist/activities/agent-turn/sandbox-provision.d.ts +22 -0
  3. package/dist/activities/agent-turn/subscription-lease.d.ts +1 -0
  4. package/dist/activities/agent-turn/tool-policy.d.ts +10 -1
  5. package/dist/activities/agent-turn/turn-context.d.ts +6 -0
  6. package/dist/activities/agent-turn/web-search.d.ts +37 -0
  7. package/dist/activities/codemode-dispatcher.d.ts +8 -0
  8. package/dist/activities/sandbox-lease.d.ts +4 -0
  9. package/dist/{activities-control-PEXBWKQJ.js → activities-control-AKJZHDTY.js} +53 -13
  10. package/dist/activities-control-AKJZHDTY.js.map +1 -0
  11. package/dist/{activities-turn-W27A2SBO.js → activities-turn-AOXNE6BM.js} +5984 -5571
  12. package/dist/activities-turn-AOXNE6BM.js.map +1 -0
  13. package/dist/{chunk-XONQEVAD.js → chunk-DCQ7XTXW.js} +108 -3
  14. package/dist/chunk-DCQ7XTXW.js.map +1 -0
  15. package/dist/{chunk-QUX5LT2B.js → chunk-WVZQJBGD.js} +166 -45
  16. package/dist/chunk-WVZQJBGD.js.map +1 -0
  17. package/dist/index.js +2 -2
  18. package/dist/observability-metrics.d.ts +51 -13
  19. package/dist/sandbox-resume.d.ts +3 -0
  20. package/package.json +21 -21
  21. package/src/activities/agent-turn/agent-build.ts +4 -2
  22. package/src/activities/agent-turn/errors.ts +89 -10
  23. package/src/activities/agent-turn/finalization.ts +16 -0
  24. package/src/activities/agent-turn/governance-model.ts +8 -8
  25. package/src/activities/agent-turn/run.ts +12 -0
  26. package/src/activities/agent-turn/sandbox-establish.ts +87 -80
  27. package/src/activities/agent-turn/sandbox-provision.ts +51 -0
  28. package/src/activities/agent-turn/sandbox-runtime.ts +16 -0
  29. package/src/activities/agent-turn/stream-attempt.ts +36 -15
  30. package/src/activities/agent-turn/subscription-lease.ts +10 -1
  31. package/src/activities/agent-turn/tool-environment.ts +19 -0
  32. package/src/activities/agent-turn/tool-policy.ts +25 -0
  33. package/src/activities/agent-turn/turn-context.ts +8 -0
  34. package/src/activities/agent-turn/web-search.ts +381 -0
  35. package/src/activities/codemode-dispatcher.ts +57 -8
  36. package/src/activities/connector-attachments.ts +3 -1
  37. package/src/activities/sandbox-lease.ts +63 -10
  38. package/src/activity-services.ts +8 -0
  39. package/src/observability-metrics.ts +130 -17
  40. package/src/sandbox-resume.ts +24 -5
  41. package/src/sandbox-routing.ts +70 -24
  42. package/dist/activities-control-PEXBWKQJ.js.map +0 -1
  43. package/dist/activities-turn-W27A2SBO.js.map +0 -1
  44. package/dist/chunk-QUX5LT2B.js.map +0 -1
  45. package/dist/chunk-XONQEVAD.js.map +0 -1
@@ -131,19 +131,7 @@ export declare function modelPreparationFailureEventPayload(error: unknown, dura
131
131
  failureCode?: "capture_in_progress" | "provider_recovery_in_progress" | "rotation_in_progress";
132
132
  retryable?: boolean;
133
133
  };
134
- /**
135
- * Recognize active-route transitions that cannot finish inside their
136
- * originating attempt. A Modal-home session may start on a Connected Machine
137
- * without creating or leasing its managed home box. When an explicit attach
138
- * clears the active pointer back to home, the pointer commit is authoritative,
139
- * but this attempt has no home session to serve the next sandbox operation.
140
- *
141
- * The Agents SDK may retain the typed routing error directly, through `cause`,
142
- * or inside an AggregateError from a parallel function-tool batch. Traverse
143
- * only those structural error links with a strict bound; never classify from
144
- * message text, which could originate in model or tool content.
145
- */
146
- export declare function sandboxRouteTransitionCode(error: unknown): "home_unavailable_this_turn" | "workspace_root_changed_this_turn" | "native_capabilities_changed_this_attempt" | null;
134
+ export declare function sandboxRouteTransitionCode(error: unknown): "home_unavailable_this_turn" | "workspace_root_changed_this_turn" | "native_capabilities_changed_this_attempt" | "home_backend_recovery_pending" | null;
147
135
  export declare function isSandboxRouteTransitionError(error: unknown): boolean;
148
136
  /** Backward-compatible name for callers/tests that only exercised the original
149
137
  * machine-to-home transition. */
@@ -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;
@@ -27,6 +27,7 @@ export declare class SubscriptionTurnLease {
27
27
  private heartbeatInFlight;
28
28
  private heartbeatTimer;
29
29
  private readonly now;
30
+ private readonly renewalIntervalMs;
30
31
  constructor(leaseDeps: SubscriptionLeaseDeps);
31
32
  private expired;
32
33
  markLost: (reason: LeaseLossReason) => void;
@@ -1,4 +1,5 @@
1
- import { type ComputerToolMode, type LazyToolTransport } from "@opengeni/runtime";
1
+ import { type ComputerToolMode, type LazyToolTransport, type OpenGeniRuntime } from "@opengeni/runtime";
2
+ import type { TurnExecutionPolicyV1 } from "@opengeni/contracts";
2
3
  import { type ModelProviderApi, type ResolvedModelProvider, type Settings } from "@opengeni/config";
3
4
  import { type ModelAttachmentInputPolicy } from "../run-input.js";
4
5
  export declare function shouldStartOnTurnRecording(params: {
@@ -112,6 +113,14 @@ export declare function shouldDeferNonEagerToolPreparation(args: {
112
113
  triggerKind: "next" | "approval";
113
114
  triggerType: string;
114
115
  }): boolean;
116
+ /**
117
+ * Resolve the provider routing/gating shape for an accepted turn. The current
118
+ * definition is projected back onto the verified frozen policy: a turn
119
+ * accepted before hosted web search was enabled keeps its frozen tool set on
120
+ * every recovery attempt (stable tool prefix, exact accepted definition); the
121
+ * next accepted logical turn resolves the newly enabled tool.
122
+ */
123
+ export declare function resolveAcceptedTurnModel(runtime: Pick<OpenGeniRuntime, "resolveTurnModel">, settings: Settings, policy: TurnExecutionPolicyV1): ReturnType<OpenGeniRuntime["resolveTurnModel"]>;
115
124
  /**
116
125
  * Native web search is a runtime capability, not part of the session's MCP
117
126
  * allow-list. Attach it whenever the resolved provider advertises runnable
@@ -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;
@@ -0,0 +1,37 @@
1
+ import type { AttemptToolDefinition } from "@opengeni/codemode";
2
+ import { type WebSearchProviderToolName, type WebSearchSettings } from "@opengeni/config";
3
+ import { type WebSearchBilling, type WebSearchCallScope } from "@opengeni/core";
4
+ import type { Observability } from "@opengeni/observability";
5
+ /**
6
+ * Which web search one turn gets: the provider's hosted tool, Opengeni's
7
+ * provider tools, or neither. Tool preparation and agent construction both
8
+ * call this with the same accepted model and settings, so they agree.
9
+ */
10
+ export declare function turnWebSearchPlan(resolvedModel: {
11
+ configured: {
12
+ hostedWebSearch: boolean;
13
+ };
14
+ provider: {
15
+ kind?: string;
16
+ };
17
+ } | null, settings: WebSearchSettings): {
18
+ hostedWebSearch: boolean;
19
+ providerTools: WebSearchProviderToolName[];
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">;
24
+ /**
25
+ * The `web_search` and `web_fetch` attempt tools for one turn. The caller
26
+ * decides which names the turn gets ({@link webSearchToolPlan}); this only
27
+ * builds them. Provider keys stay in the worker and never reach a sandbox.
28
+ */
29
+ export declare function webSearchToolDefinitions(input: {
30
+ settings: WebSearchSettings;
31
+ tools: readonly WebSearchProviderToolName[];
32
+ scope: WebSearchCallScope;
33
+ billing: WebSearchBilling;
34
+ observability: WebSearchObservability;
35
+ fetch?: typeof fetch;
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;
@@ -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-QUX5LT2B.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-XONQEVAD.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-PEXBWKQJ.js.map
8856
+ //# sourceMappingURL=activities-control-AKJZHDTY.js.map