@opengeni/worker-bundle 0.12.5 → 0.12.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import { Database, RuntimeDatabasePostureOptions } from '@opengeni/db';
4
4
  import { EventBus } from '@opengeni/events';
5
5
  import { Observability } from '@opengeni/observability';
6
6
  import { Worker, NativeConnection, WorkflowBundleOption } from '@temporalio/worker';
7
- import { EntitlementsPort, ConnectionCredentialsPort, ScheduledTaskTriggerType } from '@opengeni/contracts';
7
+ import { EntitlementsPort, ConnectionCredentialsPort, ScheduledTaskTriggerType, TurnInitiator } from '@opengeni/contracts';
8
8
  export { HostEventExport, HostEventExportBatch, HostEventSink, HostUsageExport, HostUsageExportBatch, HostUsageSink } from '@opengeni/contracts';
9
9
  import { DocumentServices } from '@opengeni/documents';
10
10
  import { OpenGeniRuntime } from '@opengeni/runtime';
@@ -39,6 +39,11 @@ type SessionAttemptQuiescenceProof = {
39
39
  activityId: string;
40
40
  };
41
41
  type SignalSessionAttemptQuiesced = (input: SessionAttemptQuiescenceProof) => Promise<void>;
42
+ type InspectSessionAttemptActivity = (input: {
43
+ workflowId: string;
44
+ workflowRunId: string;
45
+ activityId: string;
46
+ }) => Promise<"pending" | "settled">;
42
47
  type ActivityServices = {
43
48
  settings: Settings;
44
49
  db: Database;
@@ -51,6 +56,9 @@ type ActivityServices = {
51
56
  /** Durable signalWithStart fallback used only after the activity's direct
52
57
  * physical-quiescence receipt write exhausts its bounded DB retries. */
53
58
  signalSessionAttemptQuiesced: SignalSessionAttemptQuiesced | null;
59
+ /** Server-authoritative Temporal activity lease inspection used only to
60
+ * recover a missing quiescence receipt after the original activity vanished. */
61
+ inspectSessionAttemptActivity: InspectSessionAttemptActivity | null;
54
62
  /** Revision-carrying capacity nudge; generic outbox repair is also sufficient. */
55
63
  signalCodexCapacityWorkflow?: SignalCodexCapacityWorkflow | null;
56
64
  entitlements?: EntitlementsPort | null;
@@ -108,6 +116,16 @@ type SettleSessionInterruptionsInput = {
108
116
  phase?: "logical" | "attempt_quiesced";
109
117
  };
110
118
  type PersistSessionAttemptQuiescenceInput = SessionAttemptQuiescenceProof;
119
+ type ReconcileSessionAttemptQuiescenceInput = {
120
+ accountId: string;
121
+ workspaceId: string;
122
+ sessionId: string;
123
+ attemptId: string;
124
+ workflowId: string;
125
+ };
126
+ type ReconcileSessionAttemptQuiescenceResult = {
127
+ action: "quiesced" | "pending" | "stale";
128
+ };
111
129
  type FailSessionAttemptInput = {
112
130
  accountId: string;
113
131
  workspaceId: string;
@@ -164,12 +182,24 @@ type MaybeContinueGoalResult = {
164
182
  type DispatchScheduledTaskRunInput = {
165
183
  workspaceId: string;
166
184
  taskId: string;
167
- triggerType: ScheduledTaskTriggerType;
168
185
  /** Stable Temporal workflow identity; retries must reuse the same source row. */
169
186
  producerKey?: string;
170
- agentRunUsageIdempotencyKey?: string;
171
- };
187
+ } & ({
188
+ triggerType: Extract<ScheduledTaskTriggerType, "scheduled">;
189
+ agentRunUsageIdempotencyKey?: never;
190
+ initiator?: never;
191
+ } | {
192
+ triggerType: Extract<ScheduledTaskTriggerType, "manual">;
193
+ agentRunUsageIdempotencyKey: string;
194
+ /** Exact identity used by the API-side charge for this same trigger. */
195
+ initiator: TurnInitiator;
196
+ });
172
197
  type DispatchScheduledTaskRunResult = {
198
+ action: "deleted";
199
+ } | {
200
+ action: "blocked";
201
+ reason: "insufficient_credits" | "monthly_model_cost_limit" | "monthly_agent_run_limit" | "malformed_manual_trigger";
202
+ } | {
173
203
  action: "start" | "signal";
174
204
  accountId: string;
175
205
  workspaceId: string;
@@ -288,6 +318,7 @@ declare function createControlActivities(dependencies?: ActivityDependencies): {
288
318
  action: "paused" | "continue" | "stale";
289
319
  }>;
290
320
  persistSessionAttemptQuiescence: (input: PersistSessionAttemptQuiescenceInput) => Promise<void>;
321
+ reconcileSessionAttemptQuiescence: (input: ReconcileSessionAttemptQuiescenceInput) => Promise<ReconcileSessionAttemptQuiescenceResult>;
291
322
  recoverDispatch: (input: RecoverDispatchInput) => Promise<RecoverDispatchResult>;
292
323
  peekSessionWork: (input: PeekSessionWorkInput) => Promise<_opengeni_db.SessionWorkPeek>;
293
324
  expireSessionHumanInput: (input: ExpireSessionHumanInputInput) => Promise<ExpireSessionHumanInputResult>;
@@ -316,7 +347,7 @@ declare function createControlActivities(dependencies?: ActivityDependencies): {
316
347
  agentAccess: boolean;
317
348
  summary: string | null;
318
349
  topics: string[];
319
- curationStatus: "none" | "failed" | "pending" | "suggested" | "auto_filed";
350
+ curationStatus: "none" | "pending" | "failed" | "suggested" | "auto_filed";
320
351
  curation: {
321
352
  suggestedBaseId: string | null;
322
353
  suggestedBaseName: string | null;
@@ -346,6 +377,23 @@ type WorkerOptions = {
346
377
  /** Override the release-coherent workflow artifact. Most hosts should omit this. */
347
378
  workflowBundle?: WorkflowBundleOption;
348
379
  };
380
+ type TemporalActivityLease = {
381
+ lastHeartbeatTime?: {
382
+ seconds?: unknown;
383
+ nanos?: number | null;
384
+ } | null;
385
+ lastStartedTime?: {
386
+ seconds?: unknown;
387
+ nanos?: number | null;
388
+ } | null;
389
+ activityOptions?: {
390
+ heartbeatTimeout?: {
391
+ seconds?: unknown;
392
+ nanos?: number | null;
393
+ } | null;
394
+ } | null;
395
+ };
396
+ declare function temporalActivityLeaseSettled(pending: TemporalActivityLease | null | undefined, nowMs?: number): boolean;
349
397
  type WorkerWorkflowDefinition = {
350
398
  workflowBundle: WorkflowBundleOption;
351
399
  } | {
@@ -365,6 +413,7 @@ declare function createOpenGeniWorker(options: WorkerOptions): Promise<{
365
413
  declare function createWorkerWorkflowSignaler(settings: Settings, db: Database): Promise<{
366
414
  wakeSessionWorkflow: WakeSessionWorkflowSignal;
367
415
  signalSessionAttemptQuiesced: SignalSessionAttemptQuiesced;
416
+ inspectSessionAttemptActivity: InspectSessionAttemptActivity;
368
417
  signalCodexCapacityWorkflow: SignalCodexCapacityWorkflow;
369
418
  check: () => Promise<void>;
370
419
  close: () => Promise<void>;
@@ -456,4 +505,4 @@ type RunOpenGeniWorkerOptions = OpenGeniWorkerServiceOptions & {
456
505
  declare function runOpenGeniWorker(options: RunOpenGeniWorkerOptions): Promise<void>;
457
506
  declare function startWorker(): Promise<void>;
458
507
 
459
- export { FILE_UPLOAD_REAPER_PERIOD_MS, FILE_UPLOAD_REAPER_SCHEDULE_ID, type OpenGeniWorkerRole, type OpenGeniWorkerService, type OpenGeniWorkerServiceOptions, type RunOpenGeniWorkerOptions, type WorkerOptions, createOpenGeniWorker, createOpenGeniWorkerService, createWorkerWorkflowSignaler, registerFileUploadReaperSchedule, registerSandboxReaperSchedule, registerSessionWorkflowWakeDispatcherSchedule, resolveOpenGeniWorkflowDefinition, runOpenGeniWorker, startWorker, workerOwnsInternalSchedules };
508
+ export { FILE_UPLOAD_REAPER_PERIOD_MS, FILE_UPLOAD_REAPER_SCHEDULE_ID, type OpenGeniWorkerRole, type OpenGeniWorkerService, type OpenGeniWorkerServiceOptions, type RunOpenGeniWorkerOptions, type WorkerOptions, createOpenGeniWorker, createOpenGeniWorkerService, createWorkerWorkflowSignaler, registerFileUploadReaperSchedule, registerSandboxReaperSchedule, registerSessionWorkflowWakeDispatcherSchedule, resolveOpenGeniWorkflowDefinition, runOpenGeniWorker, startWorker, temporalActivityLeaseSettled, workerOwnsInternalSchedules };
package/dist/index.js CHANGED
@@ -119,7 +119,6 @@ import {
119
119
  normalizeModelCallUsage,
120
120
  normalizeSdkEvent,
121
121
  sanitizeHistoryItemsForModel as sanitizeHistoryItemsForModel2,
122
- isEphemeralInternalContext,
123
122
  appendPersistentSessionSettings,
124
123
  appendSessionInstructions,
125
124
  appendWorkspaceMemory,
@@ -188,23 +187,12 @@ import {
188
187
  environmentsEncryptionKeyBytes,
189
188
  withCodexCatalogProvider
190
189
  } from "@opengeni/config";
191
- import { settingsWithMcpCapabilityServers } from "@opengeni/core";
190
+ import { settingsWithEnabledCapabilityMcpServers } from "@opengeni/core";
192
191
  import {
193
- CODEX_APPS_MCP_SERVER_ID,
194
- CODEX_APPS_MCP_SERVER_NAME,
195
- CODEX_APPS_MCP_URL,
196
- CODEX_APPS_STARTUP_TIMEOUT_MS
197
- } from "@opengeni/codex";
198
- import {
199
- listEnabledMcpCapabilityServers,
200
192
  listSessionMcpServerMetadata,
201
193
  listSessionMcpServersForRun,
202
194
  workspaceCodexSubscriptionActive
203
195
  } from "@opengeni/db";
204
- async function settingsWithEnabledCapabilityMcpServers(db, workspaceId, settings) {
205
- const enabled = await listEnabledMcpCapabilityServers(db, workspaceId);
206
- return settingsWithMcpCapabilityServers(settings, enabled);
207
- }
208
196
  async function settingsWithSessionMcpServersForRun(db, workspaceId, sessionId, attemptId, settings, options) {
209
197
  const encryptionKey = environmentsEncryptionKeyBytes(settings);
210
198
  if (!encryptionKey) {
@@ -257,31 +245,7 @@ async function settingsWithCodexCredential(db, workspaceId, settings, activeOver
257
245
  return settings;
258
246
  }
259
247
  const withProvider = withCodexProvider(settings);
260
- if (!settings.codexConnectedAppsEnabled) {
261
- return withProvider;
262
- }
263
- return withCodexAppsMcpServer(withProvider);
264
- }
265
- function withCodexAppsMcpServer(settings) {
266
- if (settings.mcpServers.some((server) => server.id === CODEX_APPS_MCP_SERVER_ID)) {
267
- return settings;
268
- }
269
- return {
270
- ...settings,
271
- mcpServers: [
272
- ...settings.mcpServers,
273
- {
274
- id: CODEX_APPS_MCP_SERVER_ID,
275
- name: CODEX_APPS_MCP_SERVER_NAME,
276
- url: CODEX_APPS_MCP_URL,
277
- timeoutMs: CODEX_APPS_STARTUP_TIMEOUT_MS,
278
- // Connector availability is per-credential and must re-discover each
279
- // run; never poison a process-global tools-list cache.
280
- cacheToolsList: false
281
- // deliberately NO `headers` — the refreshing bearer is dynamic
282
- }
283
- ]
284
- };
248
+ return withProvider;
285
249
  }
286
250
  function withCodexProvider(settings) {
287
251
  return withCodexCatalogProvider(settings);
@@ -2241,12 +2205,6 @@ function withFirstPartyTools(settings, tools) {
2241
2205
  }
2242
2206
  return mergeToolRefs2(tools, [{ kind: "mcp", id: "opengeni" }]);
2243
2207
  }
2244
- function withCodexAppsTool(settings, tools) {
2245
- if (!settings.mcpServers.some((server) => server.id === "codex_apps")) {
2246
- return tools;
2247
- }
2248
- return mergeToolRefs2(tools, [{ kind: "mcp", id: "codex_apps" }]);
2249
- }
2250
2208
  async function goalRunBudgetBlocked(settings, db, accountId, workspaceId, isCodexRun) {
2251
2209
  if (!isCodexRun && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
2252
2210
  const balance = await getBillingBalance(db, accountId);
@@ -2824,13 +2782,19 @@ async function turnInput(db, runtime, agent, trigger, current = NON_CODEX_TURN,
2824
2782
  trigger.sessionId,
2825
2783
  options.turnId
2826
2784
  );
2827
- const updateContext = systemUpdateContext(updates);
2785
+ if (updates.length > 0) {
2786
+ const historyItemIds = new Set(
2787
+ updates.map((update) => update.deliveredHistoryItemId).filter(Boolean)
2788
+ );
2789
+ if (historyItemIds.size !== 1 || updates.some((update) => !update.deliveredHistoryItemId)) {
2790
+ throw new Error("Delivered internal updates have no single durable model-memory batch");
2791
+ }
2792
+ }
2828
2793
  const internalContext = joinInternalContext(
2829
2794
  options.recovering ? [
2830
2795
  "[OpenGeni inference recovery]",
2831
2796
  "Continue the same inference from durable conversation and sandbox state. A previous execution stopped before it could finish. Do not repeat completed side effects; inspect actual state when uncertain."
2832
2797
  ].join("\n") : void 0,
2833
- updateContext,
2834
2798
  options.unavailableSandboxFilesNote,
2835
2799
  options.runCredentialsNote
2836
2800
  );
@@ -2862,7 +2826,9 @@ async function turnInput(db, runtime, agent, trigger, current = NON_CODEX_TURN,
2862
2826
  );
2863
2827
  }
2864
2828
  if (trigger.type === "system.update.delivered") {
2865
- if (!internalContext) throw new Error("Internal update inference has no delivered updates");
2829
+ if (updates.length === 0) {
2830
+ throw new Error("Internal update inference has no delivered updates");
2831
+ }
2866
2832
  return await messageInput(db, runtime, agent, trigger, void 0, internalContext, current);
2867
2833
  }
2868
2834
  if (trigger.type === "user.approvalDecision") {
@@ -2915,24 +2881,6 @@ function joinInternalContext(...parts) {
2915
2881
  const content = parts.map((part) => part?.trim()).filter((part) => Boolean(part));
2916
2882
  return content.length > 0 ? content.join("\n\n") : void 0;
2917
2883
  }
2918
- function systemUpdateContext(updates) {
2919
- if (updates.length === 0) return void 0;
2920
- return [
2921
- "[OpenGeni internal updates]",
2922
- "These platform updates were delivered together for this inference. They are not human prompts.",
2923
- JSON.stringify({
2924
- updates: updates.map((update) => ({
2925
- id: update.id,
2926
- kind: update.kind,
2927
- classification: update.classification,
2928
- sourceId: update.sourceId,
2929
- summary: update.summary,
2930
- payload: update.payload,
2931
- lineage: update.lineage
2932
- }))
2933
- })
2934
- ].join("\n");
2935
- }
2936
2884
  async function messageInput(db, runtime, agent, trigger, text, internalContext, current = NON_CODEX_TURN, modelAttachments = []) {
2937
2885
  const stored = await getActiveSessionHistoryItems2(db, trigger.workspaceId, trigger.sessionId);
2938
2886
  const envelope = await getSandboxSessionEnvelope(db, trigger.workspaceId, trigger.sessionId);
@@ -5886,6 +5834,7 @@ import {
5886
5834
  } from "@opengeni/runtime";
5887
5835
  import {
5888
5836
  CAPABILITY_DESCRIPTORS,
5837
+ DEFAULT_FIRST_PARTY_MCP_TOOLS,
5889
5838
  evaluateWorkspaceModelPolicy as evaluateWorkspaceModelPolicy2,
5890
5839
  readTurnExecutionPolicyV1
5891
5840
  } from "@opengeni/contracts";
@@ -6401,11 +6350,13 @@ function applyCodexCacheTelemetry(observability, provider, normalizedUsage) {
6401
6350
  });
6402
6351
  }
6403
6352
  function historyRowsToAppend(rawHistory, persistedHistoryCount, nextPosition = persistedHistoryCount, toolOutputTruncationTokens, redactValue = (value) => value) {
6404
- const sanitized = sanitizeHistoryItemsForModel2(rawHistory, toolOutputTruncationTokens).filter((item) => !isEphemeralInternalContext(item)).map((item) => redactValue(item));
6353
+ const sanitized = sanitizeHistoryItemsForModel2(rawHistory, toolOutputTruncationTokens).map(
6354
+ (item) => redactValue(item)
6355
+ );
6405
6356
  if (sanitized.length <= persistedHistoryCount) {
6406
6357
  return { rows: [], nextWatermark: persistedHistoryCount, nextPosition };
6407
6358
  }
6408
- const rows = sanitized.slice(persistedHistoryCount).map((item, offset) => ({
6359
+ const rows = sanitized.slice(persistedHistoryCount).filter((item) => !(item.type === "message" && item.role === "system")).map((item, offset) => ({
6409
6360
  position: nextPosition + offset,
6410
6361
  item
6411
6362
  }));
@@ -8339,10 +8290,7 @@ function createRunAgentTurnActivity(services) {
8339
8290
  defaultNativeToolsAllowed = sessionToolPolicyAllowsDefaultNativeTools(
8340
8291
  resolvedToolPolicy.effectivePolicy
8341
8292
  );
8342
- const turnTools = withCodexAppsTool(
8343
- runSettings,
8344
- withFirstPartyTools(runSettings, effectivePolicyTools)
8345
- );
8293
+ const turnTools = withFirstPartyTools(runSettings, effectivePolicyTools);
8346
8294
  const connectionScope = {
8347
8295
  accountId: input.accountId,
8348
8296
  workspaceId: input.workspaceId
@@ -9022,7 +8970,8 @@ function createRunAgentTurnActivity(services) {
9022
8970
  },
9023
8971
  // Manager-style sessions carry a creation-validated permission set
9024
8972
  // for their first-party MCP token; null keeps the fixed default.
9025
- ...session.firstPartyMcpPermissions?.length ? { firstPartyPermissions: session.firstPartyMcpPermissions } : {}
8973
+ ...session.firstPartyMcpPermissions?.length ? { firstPartyPermissions: session.firstPartyMcpPermissions } : {},
8974
+ firstPartyTools: session.firstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS]
9026
8975
  })
9027
8976
  ),
9028
8977
  cancellationSignal,
@@ -12567,12 +12516,12 @@ import {
12567
12516
  createSessionGoal,
12568
12517
  enqueueSessionWorkflowWakeIfRunnable as enqueueSessionWorkflowWakeIfRunnable2,
12569
12518
  getBillingBalance as getBillingBalance5,
12519
+ getScheduledTask,
12570
12520
  getRig,
12571
12521
  getVariableSet,
12572
12522
  isCodexBilledTurn as isCodexBilledTurn2,
12573
12523
  markScheduledTaskRunFailedIfQueued,
12574
12524
  recordUsageEvent as recordUsageEvent3,
12575
- requireScheduledTask,
12576
12525
  requireSession as requireSession3,
12577
12526
  setTemporalWorkflowId,
12578
12527
  settleScheduledTaskRunInTransaction,
@@ -12587,7 +12536,13 @@ function createScheduledTaskActivities(services) {
12587
12536
  return {
12588
12537
  dispatchScheduledTaskRun: async (input) => {
12589
12538
  const { settings, db, bus, wakeSessionWorkflow } = await services();
12590
- const task = await requireScheduledTask(db, input.workspaceId, input.taskId);
12539
+ if (input.triggerType === "manual" && !input.initiator) {
12540
+ return { action: "blocked", reason: "malformed_manual_trigger" };
12541
+ }
12542
+ const task = await getScheduledTask(db, input.workspaceId, input.taskId);
12543
+ if (!task) {
12544
+ return { action: "deleted" };
12545
+ }
12591
12546
  const slackBotConnection = task.agentConfig.slackBotConnectionId ? await requireOpenGeniSlackBotConnection(
12592
12547
  db,
12593
12548
  task.workspaceId,
@@ -12604,7 +12559,7 @@ function createScheduledTaskActivities(services) {
12604
12559
  workspaceId: task.workspaceId,
12605
12560
  model
12606
12561
  });
12607
- await ensureScheduledRunAllowed(
12562
+ const admissionDenial = await scheduledRunAdmissionDenial(
12608
12563
  settings,
12609
12564
  db,
12610
12565
  task.accountId,
@@ -12612,6 +12567,9 @@ function createScheduledTaskActivities(services) {
12612
12567
  input.agentRunUsageIdempotencyKey ? 0 : 1,
12613
12568
  isCodexRun
12614
12569
  );
12570
+ if (admissionDenial) {
12571
+ return { action: "blocked", reason: admissionDenial };
12572
+ }
12615
12573
  const run = await createScheduledTaskRun(db, {
12616
12574
  workspaceId: task.workspaceId,
12617
12575
  taskId: task.id,
@@ -12627,7 +12585,7 @@ function createScheduledTaskActivities(services) {
12627
12585
  unit: "run",
12628
12586
  sourceResourceType: "scheduled_task_run",
12629
12587
  sourceResourceId: run.id,
12630
- initiator: { kind: "service", subjectId: "scheduler" },
12588
+ initiator: input.initiator ?? { kind: "service", subjectId: "scheduler" },
12631
12589
  initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
12632
12590
  origin: "scheduled_task",
12633
12591
  idempotencyKey: `usage:scheduled_task.fired:${run.id}`
@@ -12642,7 +12600,7 @@ function createScheduledTaskActivities(services) {
12642
12600
  sourceResourceType: "scheduled_task_run",
12643
12601
  sourceResourceId: run.id,
12644
12602
  sessionId: run.sessionId,
12645
- initiator: { kind: "service", subjectId: "scheduler" },
12603
+ initiator: input.initiator ?? { kind: "service", subjectId: "scheduler" },
12646
12604
  initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
12647
12605
  origin: "scheduled_task",
12648
12606
  idempotencyKey: input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`
@@ -12958,7 +12916,7 @@ function createScheduledTaskActivities(services) {
12958
12916
  sourceResourceType: "scheduled_task_run",
12959
12917
  sourceResourceId: run.id,
12960
12918
  sessionId: result.sessionId,
12961
- initiator: { kind: "service", subjectId: "scheduler" },
12919
+ initiator: input.initiator ?? { kind: "service", subjectId: "scheduler" },
12962
12920
  initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
12963
12921
  origin: "scheduled_task",
12964
12922
  idempotencyKey: input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`
@@ -12976,11 +12934,11 @@ function createScheduledTaskActivities(services) {
12976
12934
  }
12977
12935
  };
12978
12936
  }
12979
- async function ensureScheduledRunAllowed(settings, db, accountId, workspaceId, requestedAgentRuns, isCodexRun) {
12937
+ async function scheduledRunAdmissionDenial(settings, db, accountId, workspaceId, requestedAgentRuns, isCodexRun) {
12980
12938
  if (!isCodexRun && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
12981
12939
  const balance = await getBillingBalance5(db, accountId);
12982
12940
  if (balance.balanceMicros <= 0) {
12983
- throw new Error("insufficient OpenGeni credits");
12941
+ return "insufficient_credits";
12984
12942
  }
12985
12943
  }
12986
12944
  if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
@@ -12992,9 +12950,7 @@ async function ensureScheduledRunAllowed(settings, db, accountId, workspaceId, r
12992
12950
  since: startOfUtcMonth4()
12993
12951
  });
12994
12952
  if (used >= limits.maxMonthlyCostMicrosPerAccount) {
12995
- throw new Error(
12996
- `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`
12997
- );
12953
+ return "monthly_model_cost_limit";
12998
12954
  }
12999
12955
  }
13000
12956
  if (limits.maxMonthlyAgentRunsPerWorkspace) {
@@ -13004,12 +12960,11 @@ async function ensureScheduledRunAllowed(settings, db, accountId, workspaceId, r
13004
12960
  since: startOfUtcMonth4()
13005
12961
  });
13006
12962
  if (used + requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {
13007
- throw new Error(
13008
- `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`
13009
- );
12963
+ return "monthly_agent_run_limit";
13010
12964
  }
13011
12965
  }
13012
12966
  }
12967
+ return null;
13013
12968
  }
13014
12969
  function startOfUtcMonth4() {
13015
12970
  const now = /* @__PURE__ */ new Date();
@@ -13021,8 +12976,10 @@ import {
13021
12976
  settleSessionAttemptInterruptions,
13022
12977
  applySessionTurnSettlement as applySessionTurnSettlement2,
13023
12978
  recoverSessionDispatch,
12979
+ reconcileSessionAttemptQuiescence,
13024
12980
  peekSessionWork as peekSessionWorkDb,
13025
12981
  countQueuedTurns as countQueuedTurns2,
12982
+ getSessionAttemptActivityRef,
13026
12983
  getSessionEvent as getSessionEvent3,
13027
12984
  getSessionTurnForAttempt,
13028
12985
  expireSessionHumanInputRequest,
@@ -13036,8 +12993,10 @@ function createSessionStateActivities(services, overrides = {}) {
13036
12993
  const settleSessionAttemptInterruptionsFn = overrides.settleSessionAttemptInterruptions ?? settleSessionAttemptInterruptions;
13037
12994
  const applySessionTurnSettlementFn = overrides.applySessionTurnSettlement ?? applySessionTurnSettlement2;
13038
12995
  const recoverSessionDispatchFn = overrides.recoverSessionDispatch ?? recoverSessionDispatch;
12996
+ const reconcileSessionAttemptQuiescenceFn = overrides.reconcileSessionAttemptQuiescence ?? reconcileSessionAttemptQuiescence;
13039
12997
  const peekSessionWorkFn = overrides.peekSessionWork ?? peekSessionWorkDb;
13040
12998
  const countQueuedTurnsFn = overrides.countQueuedTurns ?? countQueuedTurns2;
12999
+ const getSessionAttemptActivityRefFn = overrides.getSessionAttemptActivityRef ?? getSessionAttemptActivityRef;
13041
13000
  const getSessionEventFn = overrides.getSessionEvent ?? getSessionEvent3;
13042
13001
  const getSessionTurnForAttemptFn = overrides.getSessionTurnForAttempt ?? getSessionTurnForAttempt;
13043
13002
  const expireSessionHumanInputRequestFn = overrides.expireSessionHumanInputRequest ?? expireSessionHumanInputRequest;
@@ -13139,6 +13098,38 @@ function createSessionStateActivities(services, overrides = {}) {
13139
13098
  });
13140
13099
  }
13141
13100
  }
13101
+ async function reconcileSessionAttemptQuiescenceActivity(input) {
13102
+ const { db, bus, inspectSessionAttemptActivity } = await services();
13103
+ const activityRef = await getSessionAttemptActivityRefFn(db, {
13104
+ ...input,
13105
+ temporalWorkflowId: input.workflowId
13106
+ });
13107
+ if (!activityRef) return { action: "stale" };
13108
+ if (!activityRef.quiesced) {
13109
+ if (!inspectSessionAttemptActivity) return { action: "pending" };
13110
+ const state = await inspectSessionAttemptActivity(activityRef);
13111
+ if (state === "pending") return { action: "pending" };
13112
+ }
13113
+ const result = await reconcileSessionAttemptQuiescenceFn(db, {
13114
+ accountId: input.accountId,
13115
+ workspaceId: input.workspaceId,
13116
+ sessionId: input.sessionId,
13117
+ attemptId: input.attemptId,
13118
+ temporalWorkflowId: input.workflowId,
13119
+ temporalWorkflowRunId: activityRef.workflowRunId,
13120
+ temporalActivityId: activityRef.activityId,
13121
+ activitySettled: true
13122
+ });
13123
+ if (result.events.length > 0) {
13124
+ await publishDurableSessionEventsFn(
13125
+ bus,
13126
+ input.workspaceId,
13127
+ input.sessionId,
13128
+ result.events
13129
+ ).catch(() => void 0);
13130
+ }
13131
+ return { action: result.action };
13132
+ }
13142
13133
  async function recoverDispatch2(input) {
13143
13134
  const { settings, db, bus, observability, wakeSessionWorkflow } = await services();
13144
13135
  const result = await recoverSessionDispatchFn(db, input.workspaceId, {
@@ -13213,6 +13204,7 @@ function createSessionStateActivities(services, overrides = {}) {
13213
13204
  failSessionAttempt: failSessionAttempt2,
13214
13205
  settleSessionInterruptions: settleSessionInterruptions2,
13215
13206
  persistSessionAttemptQuiescence: persistSessionAttemptQuiescence2,
13207
+ reconcileSessionAttemptQuiescence: reconcileSessionAttemptQuiescenceActivity,
13216
13208
  recoverDispatch: recoverDispatch2,
13217
13209
  peekSessionWork: peekSessionWork2,
13218
13210
  expireSessionHumanInput: expireSessionHumanInput2,
@@ -14143,6 +14135,7 @@ function createActivityServices(dependencies) {
14143
14135
  observability,
14144
14136
  wakeSessionWorkflow: dependencies.wakeSessionWorkflow ?? null,
14145
14137
  signalSessionAttemptQuiesced: dependencies.signalSessionAttemptQuiesced ?? null,
14138
+ inspectSessionAttemptActivity: dependencies.inspectSessionAttemptActivity ?? null,
14146
14139
  signalCodexCapacityWorkflow: dependencies.signalCodexCapacityWorkflow ?? null,
14147
14140
  // §7.5 P3 — host-entitlements port. No constructed default: standalone
14148
14141
  // has no host meter, so unset → null → `ensureRunAllowed` reads the
@@ -14189,6 +14182,7 @@ var indexDocument = defaultControlActivities.indexDocument;
14189
14182
  var failSessionAttempt = defaultControlActivities.failSessionAttempt;
14190
14183
  var settleSessionInterruptions = defaultControlActivities.settleSessionInterruptions;
14191
14184
  var persistSessionAttemptQuiescence = defaultControlActivities.persistSessionAttemptQuiescence;
14185
+ var reconcileSessionAttemptQuiescence2 = defaultControlActivities.reconcileSessionAttemptQuiescence;
14192
14186
  var recoverDispatch = defaultControlActivities.recoverDispatch;
14193
14187
  var peekSessionWork = defaultControlActivities.peekSessionWork;
14194
14188
  var expireSessionHumanInput = defaultControlActivities.expireSessionHumanInput;
@@ -14214,6 +14208,15 @@ var activity = proxyActivities({
14214
14208
  maximumInterval: "30 seconds"
14215
14209
  }
14216
14210
  });
14211
+ var scheduledTaskActivity = proxyActivities({
14212
+ startToCloseTimeout: "2 minutes",
14213
+ retry: {
14214
+ initialInterval: "1 second",
14215
+ backoffCoefficient: 2,
14216
+ maximumInterval: "30 seconds",
14217
+ maximumAttempts: 5
14218
+ }
14219
+ });
14217
14220
  var goalActivity = proxyActivities({
14218
14221
  startToCloseTimeout: "30 seconds",
14219
14222
  retry: {
@@ -14475,6 +14478,16 @@ function createWorkerServiceLifecycle(input) {
14475
14478
  var SANDBOX_REAPER_SCHEDULE_ID = "opengeni-sandbox-lease-reaper";
14476
14479
  var FILE_UPLOAD_REAPER_SCHEDULE_ID = "opengeni-file-upload-reaper";
14477
14480
  var FILE_UPLOAD_REAPER_PERIOD_MS = 15 * 60 * 1e3;
14481
+ function temporalTimeMs(value) {
14482
+ if (value?.seconds === void 0 || value.seconds === null) return null;
14483
+ return Number(String(value.seconds)) * 1e3 + Math.floor((value.nanos ?? 0) / 1e6);
14484
+ }
14485
+ function temporalActivityLeaseSettled(pending, nowMs = Date.now()) {
14486
+ if (!pending) return true;
14487
+ const heartbeatAt = temporalTimeMs(pending.lastHeartbeatTime) ?? temporalTimeMs(pending.lastStartedTime);
14488
+ const heartbeatTimeoutMs = temporalTimeMs(pending.activityOptions?.heartbeatTimeout);
14489
+ return heartbeatAt !== null && heartbeatTimeoutMs !== null && nowMs >= heartbeatAt + heartbeatTimeoutMs;
14490
+ }
14478
14491
  function resolveOpenGeniWorkflowDefinition(moduleUrl = import.meta.url) {
14479
14492
  const modulePath = fileURLToPath(moduleUrl).replaceAll("\\", "/");
14480
14493
  if (modulePath.endsWith("/src/index.ts")) {
@@ -14607,6 +14620,16 @@ async function createWorkerWorkflowSignaler(settings, db) {
14607
14620
  signalArgs: [proof]
14608
14621
  });
14609
14622
  },
14623
+ inspectSessionAttemptActivity: async ({ workflowId, workflowRunId, activityId }) => {
14624
+ const description = await connection.workflowService.describeWorkflowExecution({
14625
+ namespace: settings.temporalNamespace,
14626
+ execution: { workflowId, runId: workflowRunId }
14627
+ });
14628
+ const pending = description.pendingActivities?.find(
14629
+ (activity2) => activity2.activityId === activityId
14630
+ );
14631
+ return temporalActivityLeaseSettled(pending) ? "settled" : "pending";
14632
+ },
14610
14633
  signalCodexCapacityWorkflow: async ({
14611
14634
  accountId,
14612
14635
  workspaceId,
@@ -14766,7 +14789,7 @@ async function createOpenGeniWorkerService(options) {
14766
14789
  const schedules = [];
14767
14790
  let httpServer;
14768
14791
  try {
14769
- const needsSignaler = !options.activityDependencies.wakeSessionWorkflow || !options.activityDependencies.signalSessionAttemptQuiesced || !options.activityDependencies.signalCodexCapacityWorkflow;
14792
+ const needsSignaler = !options.activityDependencies.wakeSessionWorkflow || !options.activityDependencies.signalSessionAttemptQuiesced || !options.activityDependencies.inspectSessionAttemptActivity || !options.activityDependencies.signalCodexCapacityWorkflow;
14770
14793
  if (needsSignaler) {
14771
14794
  signaler = await retryStartupDependency(
14772
14795
  "Temporal client",
@@ -14776,8 +14799,9 @@ async function createOpenGeniWorkerService(options) {
14776
14799
  }
14777
14800
  const wakeSessionWorkflow = options.activityDependencies.wakeSessionWorkflow ?? signaler?.wakeSessionWorkflow;
14778
14801
  const signalSessionAttemptQuiesced = options.activityDependencies.signalSessionAttemptQuiesced ?? signaler?.signalSessionAttemptQuiesced;
14802
+ const inspectSessionAttemptActivity = options.activityDependencies.inspectSessionAttemptActivity ?? signaler?.inspectSessionAttemptActivity;
14779
14803
  const signalCodexCapacityWorkflow = options.activityDependencies.signalCodexCapacityWorkflow ?? signaler?.signalCodexCapacityWorkflow;
14780
- if (!wakeSessionWorkflow || !signalSessionAttemptQuiesced || !signalCodexCapacityWorkflow) {
14804
+ if (!wakeSessionWorkflow || !signalSessionAttemptQuiesced || !inspectSessionAttemptActivity || !signalCodexCapacityWorkflow) {
14781
14805
  throw new Error("OpenGeni worker lifecycle could not resolve its workflow signalers");
14782
14806
  }
14783
14807
  workerBundle = await createOpenGeniWorker({
@@ -14791,6 +14815,7 @@ async function createOpenGeniWorkerService(options) {
14791
14815
  observability,
14792
14816
  wakeSessionWorkflow,
14793
14817
  signalSessionAttemptQuiesced,
14818
+ inspectSessionAttemptActivity,
14794
14819
  signalCodexCapacityWorkflow
14795
14820
  }
14796
14821
  });
@@ -14964,6 +14989,7 @@ export {
14964
14989
  resolveOpenGeniWorkflowDefinition,
14965
14990
  runOpenGeniWorker,
14966
14991
  startWorker,
14992
+ temporalActivityLeaseSettled,
14967
14993
  workerOwnsInternalSchedules
14968
14994
  };
14969
14995
  //# sourceMappingURL=index.js.map