@opengeni/worker-bundle 0.12.5 → 0.12.10

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
  }));
@@ -8326,10 +8277,8 @@ function createRunAgentTurnActivity(services) {
8326
8277
  }
8327
8278
  const turnResources = mergeResourceRefs(session.resources, turn.resources);
8328
8279
  const resolvedToolPolicy = resolveSessionToolPolicy({
8329
- ...session.toolPolicy ? { toolPolicy: session.toolPolicy } : {},
8280
+ toolPolicy: session.toolPolicy,
8330
8281
  sessionTools: session.tools,
8331
- turnTools: turn.tools,
8332
- ...turn.toolsProvided !== void 0 ? { turnToolsProvided: turn.toolsProvided } : {},
8333
8282
  availableMcpServerIds: runSettings.mcpServers.map((server) => server.id),
8334
8283
  defaultMcpServerIds: enabledCapabilityMcpToolRefs(settings, mcpSettings).map(
8335
8284
  (tool) => tool.id
@@ -8339,10 +8288,7 @@ function createRunAgentTurnActivity(services) {
8339
8288
  defaultNativeToolsAllowed = sessionToolPolicyAllowsDefaultNativeTools(
8340
8289
  resolvedToolPolicy.effectivePolicy
8341
8290
  );
8342
- const turnTools = withCodexAppsTool(
8343
- runSettings,
8344
- withFirstPartyTools(runSettings, effectivePolicyTools)
8345
- );
8291
+ const turnTools = withFirstPartyTools(runSettings, effectivePolicyTools);
8346
8292
  const connectionScope = {
8347
8293
  accountId: input.accountId,
8348
8294
  workspaceId: input.workspaceId
@@ -9022,7 +8968,8 @@ function createRunAgentTurnActivity(services) {
9022
8968
  },
9023
8969
  // Manager-style sessions carry a creation-validated permission set
9024
8970
  // for their first-party MCP token; null keeps the fixed default.
9025
- ...session.firstPartyMcpPermissions?.length ? { firstPartyPermissions: session.firstPartyMcpPermissions } : {}
8971
+ ...session.firstPartyMcpPermissions?.length ? { firstPartyPermissions: session.firstPartyMcpPermissions } : {},
8972
+ firstPartyTools: session.firstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS]
9026
8973
  })
9027
8974
  ),
9028
8975
  cancellationSignal,
@@ -12567,12 +12514,12 @@ import {
12567
12514
  createSessionGoal,
12568
12515
  enqueueSessionWorkflowWakeIfRunnable as enqueueSessionWorkflowWakeIfRunnable2,
12569
12516
  getBillingBalance as getBillingBalance5,
12517
+ getScheduledTask,
12570
12518
  getRig,
12571
12519
  getVariableSet,
12572
12520
  isCodexBilledTurn as isCodexBilledTurn2,
12573
12521
  markScheduledTaskRunFailedIfQueued,
12574
12522
  recordUsageEvent as recordUsageEvent3,
12575
- requireScheduledTask,
12576
12523
  requireSession as requireSession3,
12577
12524
  setTemporalWorkflowId,
12578
12525
  settleScheduledTaskRunInTransaction,
@@ -12587,7 +12534,13 @@ function createScheduledTaskActivities(services) {
12587
12534
  return {
12588
12535
  dispatchScheduledTaskRun: async (input) => {
12589
12536
  const { settings, db, bus, wakeSessionWorkflow } = await services();
12590
- const task = await requireScheduledTask(db, input.workspaceId, input.taskId);
12537
+ if (input.triggerType === "manual" && !input.initiator) {
12538
+ return { action: "blocked", reason: "malformed_manual_trigger" };
12539
+ }
12540
+ const task = await getScheduledTask(db, input.workspaceId, input.taskId);
12541
+ if (!task) {
12542
+ return { action: "deleted" };
12543
+ }
12591
12544
  const slackBotConnection = task.agentConfig.slackBotConnectionId ? await requireOpenGeniSlackBotConnection(
12592
12545
  db,
12593
12546
  task.workspaceId,
@@ -12604,7 +12557,7 @@ function createScheduledTaskActivities(services) {
12604
12557
  workspaceId: task.workspaceId,
12605
12558
  model
12606
12559
  });
12607
- await ensureScheduledRunAllowed(
12560
+ const admissionDenial = await scheduledRunAdmissionDenial(
12608
12561
  settings,
12609
12562
  db,
12610
12563
  task.accountId,
@@ -12612,6 +12565,9 @@ function createScheduledTaskActivities(services) {
12612
12565
  input.agentRunUsageIdempotencyKey ? 0 : 1,
12613
12566
  isCodexRun
12614
12567
  );
12568
+ if (admissionDenial) {
12569
+ return { action: "blocked", reason: admissionDenial };
12570
+ }
12615
12571
  const run = await createScheduledTaskRun(db, {
12616
12572
  workspaceId: task.workspaceId,
12617
12573
  taskId: task.id,
@@ -12627,7 +12583,7 @@ function createScheduledTaskActivities(services) {
12627
12583
  unit: "run",
12628
12584
  sourceResourceType: "scheduled_task_run",
12629
12585
  sourceResourceId: run.id,
12630
- initiator: { kind: "service", subjectId: "scheduler" },
12586
+ initiator: input.initiator ?? { kind: "service", subjectId: "scheduler" },
12631
12587
  initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
12632
12588
  origin: "scheduled_task",
12633
12589
  idempotencyKey: `usage:scheduled_task.fired:${run.id}`
@@ -12642,7 +12598,7 @@ function createScheduledTaskActivities(services) {
12642
12598
  sourceResourceType: "scheduled_task_run",
12643
12599
  sourceResourceId: run.id,
12644
12600
  sessionId: run.sessionId,
12645
- initiator: { kind: "service", subjectId: "scheduler" },
12601
+ initiator: input.initiator ?? { kind: "service", subjectId: "scheduler" },
12646
12602
  initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
12647
12603
  origin: "scheduled_task",
12648
12604
  idempotencyKey: input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`
@@ -12958,7 +12914,7 @@ function createScheduledTaskActivities(services) {
12958
12914
  sourceResourceType: "scheduled_task_run",
12959
12915
  sourceResourceId: run.id,
12960
12916
  sessionId: result.sessionId,
12961
- initiator: { kind: "service", subjectId: "scheduler" },
12917
+ initiator: input.initiator ?? { kind: "service", subjectId: "scheduler" },
12962
12918
  initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
12963
12919
  origin: "scheduled_task",
12964
12920
  idempotencyKey: input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`
@@ -12976,11 +12932,11 @@ function createScheduledTaskActivities(services) {
12976
12932
  }
12977
12933
  };
12978
12934
  }
12979
- async function ensureScheduledRunAllowed(settings, db, accountId, workspaceId, requestedAgentRuns, isCodexRun) {
12935
+ async function scheduledRunAdmissionDenial(settings, db, accountId, workspaceId, requestedAgentRuns, isCodexRun) {
12980
12936
  if (!isCodexRun && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
12981
12937
  const balance = await getBillingBalance5(db, accountId);
12982
12938
  if (balance.balanceMicros <= 0) {
12983
- throw new Error("insufficient OpenGeni credits");
12939
+ return "insufficient_credits";
12984
12940
  }
12985
12941
  }
12986
12942
  if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
@@ -12992,9 +12948,7 @@ async function ensureScheduledRunAllowed(settings, db, accountId, workspaceId, r
12992
12948
  since: startOfUtcMonth4()
12993
12949
  });
12994
12950
  if (used >= limits.maxMonthlyCostMicrosPerAccount) {
12995
- throw new Error(
12996
- `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`
12997
- );
12951
+ return "monthly_model_cost_limit";
12998
12952
  }
12999
12953
  }
13000
12954
  if (limits.maxMonthlyAgentRunsPerWorkspace) {
@@ -13004,12 +12958,11 @@ async function ensureScheduledRunAllowed(settings, db, accountId, workspaceId, r
13004
12958
  since: startOfUtcMonth4()
13005
12959
  });
13006
12960
  if (used + requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {
13007
- throw new Error(
13008
- `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`
13009
- );
12961
+ return "monthly_agent_run_limit";
13010
12962
  }
13011
12963
  }
13012
12964
  }
12965
+ return null;
13013
12966
  }
13014
12967
  function startOfUtcMonth4() {
13015
12968
  const now = /* @__PURE__ */ new Date();
@@ -13021,8 +12974,10 @@ import {
13021
12974
  settleSessionAttemptInterruptions,
13022
12975
  applySessionTurnSettlement as applySessionTurnSettlement2,
13023
12976
  recoverSessionDispatch,
12977
+ reconcileSessionAttemptQuiescence,
13024
12978
  peekSessionWork as peekSessionWorkDb,
13025
12979
  countQueuedTurns as countQueuedTurns2,
12980
+ getSessionAttemptActivityRef,
13026
12981
  getSessionEvent as getSessionEvent3,
13027
12982
  getSessionTurnForAttempt,
13028
12983
  expireSessionHumanInputRequest,
@@ -13036,8 +12991,10 @@ function createSessionStateActivities(services, overrides = {}) {
13036
12991
  const settleSessionAttemptInterruptionsFn = overrides.settleSessionAttemptInterruptions ?? settleSessionAttemptInterruptions;
13037
12992
  const applySessionTurnSettlementFn = overrides.applySessionTurnSettlement ?? applySessionTurnSettlement2;
13038
12993
  const recoverSessionDispatchFn = overrides.recoverSessionDispatch ?? recoverSessionDispatch;
12994
+ const reconcileSessionAttemptQuiescenceFn = overrides.reconcileSessionAttemptQuiescence ?? reconcileSessionAttemptQuiescence;
13039
12995
  const peekSessionWorkFn = overrides.peekSessionWork ?? peekSessionWorkDb;
13040
12996
  const countQueuedTurnsFn = overrides.countQueuedTurns ?? countQueuedTurns2;
12997
+ const getSessionAttemptActivityRefFn = overrides.getSessionAttemptActivityRef ?? getSessionAttemptActivityRef;
13041
12998
  const getSessionEventFn = overrides.getSessionEvent ?? getSessionEvent3;
13042
12999
  const getSessionTurnForAttemptFn = overrides.getSessionTurnForAttempt ?? getSessionTurnForAttempt;
13043
13000
  const expireSessionHumanInputRequestFn = overrides.expireSessionHumanInputRequest ?? expireSessionHumanInputRequest;
@@ -13139,6 +13096,38 @@ function createSessionStateActivities(services, overrides = {}) {
13139
13096
  });
13140
13097
  }
13141
13098
  }
13099
+ async function reconcileSessionAttemptQuiescenceActivity(input) {
13100
+ const { db, bus, inspectSessionAttemptActivity } = await services();
13101
+ const activityRef = await getSessionAttemptActivityRefFn(db, {
13102
+ ...input,
13103
+ temporalWorkflowId: input.workflowId
13104
+ });
13105
+ if (!activityRef) return { action: "stale" };
13106
+ if (!activityRef.quiesced) {
13107
+ if (!inspectSessionAttemptActivity) return { action: "pending" };
13108
+ const state = await inspectSessionAttemptActivity(activityRef);
13109
+ if (state === "pending") return { action: "pending" };
13110
+ }
13111
+ const result = await reconcileSessionAttemptQuiescenceFn(db, {
13112
+ accountId: input.accountId,
13113
+ workspaceId: input.workspaceId,
13114
+ sessionId: input.sessionId,
13115
+ attemptId: input.attemptId,
13116
+ temporalWorkflowId: input.workflowId,
13117
+ temporalWorkflowRunId: activityRef.workflowRunId,
13118
+ temporalActivityId: activityRef.activityId,
13119
+ activitySettled: true
13120
+ });
13121
+ if (result.events.length > 0) {
13122
+ await publishDurableSessionEventsFn(
13123
+ bus,
13124
+ input.workspaceId,
13125
+ input.sessionId,
13126
+ result.events
13127
+ ).catch(() => void 0);
13128
+ }
13129
+ return { action: result.action };
13130
+ }
13142
13131
  async function recoverDispatch2(input) {
13143
13132
  const { settings, db, bus, observability, wakeSessionWorkflow } = await services();
13144
13133
  const result = await recoverSessionDispatchFn(db, input.workspaceId, {
@@ -13213,6 +13202,7 @@ function createSessionStateActivities(services, overrides = {}) {
13213
13202
  failSessionAttempt: failSessionAttempt2,
13214
13203
  settleSessionInterruptions: settleSessionInterruptions2,
13215
13204
  persistSessionAttemptQuiescence: persistSessionAttemptQuiescence2,
13205
+ reconcileSessionAttemptQuiescence: reconcileSessionAttemptQuiescenceActivity,
13216
13206
  recoverDispatch: recoverDispatch2,
13217
13207
  peekSessionWork: peekSessionWork2,
13218
13208
  expireSessionHumanInput: expireSessionHumanInput2,
@@ -14143,6 +14133,7 @@ function createActivityServices(dependencies) {
14143
14133
  observability,
14144
14134
  wakeSessionWorkflow: dependencies.wakeSessionWorkflow ?? null,
14145
14135
  signalSessionAttemptQuiesced: dependencies.signalSessionAttemptQuiesced ?? null,
14136
+ inspectSessionAttemptActivity: dependencies.inspectSessionAttemptActivity ?? null,
14146
14137
  signalCodexCapacityWorkflow: dependencies.signalCodexCapacityWorkflow ?? null,
14147
14138
  // §7.5 P3 — host-entitlements port. No constructed default: standalone
14148
14139
  // has no host meter, so unset → null → `ensureRunAllowed` reads the
@@ -14189,6 +14180,7 @@ var indexDocument = defaultControlActivities.indexDocument;
14189
14180
  var failSessionAttempt = defaultControlActivities.failSessionAttempt;
14190
14181
  var settleSessionInterruptions = defaultControlActivities.settleSessionInterruptions;
14191
14182
  var persistSessionAttemptQuiescence = defaultControlActivities.persistSessionAttemptQuiescence;
14183
+ var reconcileSessionAttemptQuiescence2 = defaultControlActivities.reconcileSessionAttemptQuiescence;
14192
14184
  var recoverDispatch = defaultControlActivities.recoverDispatch;
14193
14185
  var peekSessionWork = defaultControlActivities.peekSessionWork;
14194
14186
  var expireSessionHumanInput = defaultControlActivities.expireSessionHumanInput;
@@ -14214,6 +14206,15 @@ var activity = proxyActivities({
14214
14206
  maximumInterval: "30 seconds"
14215
14207
  }
14216
14208
  });
14209
+ var scheduledTaskActivity = proxyActivities({
14210
+ startToCloseTimeout: "2 minutes",
14211
+ retry: {
14212
+ initialInterval: "1 second",
14213
+ backoffCoefficient: 2,
14214
+ maximumInterval: "30 seconds",
14215
+ maximumAttempts: 5
14216
+ }
14217
+ });
14217
14218
  var goalActivity = proxyActivities({
14218
14219
  startToCloseTimeout: "30 seconds",
14219
14220
  retry: {
@@ -14475,6 +14476,16 @@ function createWorkerServiceLifecycle(input) {
14475
14476
  var SANDBOX_REAPER_SCHEDULE_ID = "opengeni-sandbox-lease-reaper";
14476
14477
  var FILE_UPLOAD_REAPER_SCHEDULE_ID = "opengeni-file-upload-reaper";
14477
14478
  var FILE_UPLOAD_REAPER_PERIOD_MS = 15 * 60 * 1e3;
14479
+ function temporalTimeMs(value) {
14480
+ if (value?.seconds === void 0 || value.seconds === null) return null;
14481
+ return Number(String(value.seconds)) * 1e3 + Math.floor((value.nanos ?? 0) / 1e6);
14482
+ }
14483
+ function temporalActivityLeaseSettled(pending, nowMs = Date.now()) {
14484
+ if (!pending) return true;
14485
+ const heartbeatAt = temporalTimeMs(pending.lastHeartbeatTime) ?? temporalTimeMs(pending.lastStartedTime);
14486
+ const heartbeatTimeoutMs = temporalTimeMs(pending.activityOptions?.heartbeatTimeout);
14487
+ return heartbeatAt !== null && heartbeatTimeoutMs !== null && nowMs >= heartbeatAt + heartbeatTimeoutMs;
14488
+ }
14478
14489
  function resolveOpenGeniWorkflowDefinition(moduleUrl = import.meta.url) {
14479
14490
  const modulePath = fileURLToPath(moduleUrl).replaceAll("\\", "/");
14480
14491
  if (modulePath.endsWith("/src/index.ts")) {
@@ -14607,6 +14618,16 @@ async function createWorkerWorkflowSignaler(settings, db) {
14607
14618
  signalArgs: [proof]
14608
14619
  });
14609
14620
  },
14621
+ inspectSessionAttemptActivity: async ({ workflowId, workflowRunId, activityId }) => {
14622
+ const description = await connection.workflowService.describeWorkflowExecution({
14623
+ namespace: settings.temporalNamespace,
14624
+ execution: { workflowId, runId: workflowRunId }
14625
+ });
14626
+ const pending = description.pendingActivities?.find(
14627
+ (activity2) => activity2.activityId === activityId
14628
+ );
14629
+ return temporalActivityLeaseSettled(pending) ? "settled" : "pending";
14630
+ },
14610
14631
  signalCodexCapacityWorkflow: async ({
14611
14632
  accountId,
14612
14633
  workspaceId,
@@ -14766,7 +14787,7 @@ async function createOpenGeniWorkerService(options) {
14766
14787
  const schedules = [];
14767
14788
  let httpServer;
14768
14789
  try {
14769
- const needsSignaler = !options.activityDependencies.wakeSessionWorkflow || !options.activityDependencies.signalSessionAttemptQuiesced || !options.activityDependencies.signalCodexCapacityWorkflow;
14790
+ const needsSignaler = !options.activityDependencies.wakeSessionWorkflow || !options.activityDependencies.signalSessionAttemptQuiesced || !options.activityDependencies.inspectSessionAttemptActivity || !options.activityDependencies.signalCodexCapacityWorkflow;
14770
14791
  if (needsSignaler) {
14771
14792
  signaler = await retryStartupDependency(
14772
14793
  "Temporal client",
@@ -14776,8 +14797,9 @@ async function createOpenGeniWorkerService(options) {
14776
14797
  }
14777
14798
  const wakeSessionWorkflow = options.activityDependencies.wakeSessionWorkflow ?? signaler?.wakeSessionWorkflow;
14778
14799
  const signalSessionAttemptQuiesced = options.activityDependencies.signalSessionAttemptQuiesced ?? signaler?.signalSessionAttemptQuiesced;
14800
+ const inspectSessionAttemptActivity = options.activityDependencies.inspectSessionAttemptActivity ?? signaler?.inspectSessionAttemptActivity;
14779
14801
  const signalCodexCapacityWorkflow = options.activityDependencies.signalCodexCapacityWorkflow ?? signaler?.signalCodexCapacityWorkflow;
14780
- if (!wakeSessionWorkflow || !signalSessionAttemptQuiesced || !signalCodexCapacityWorkflow) {
14802
+ if (!wakeSessionWorkflow || !signalSessionAttemptQuiesced || !inspectSessionAttemptActivity || !signalCodexCapacityWorkflow) {
14781
14803
  throw new Error("OpenGeni worker lifecycle could not resolve its workflow signalers");
14782
14804
  }
14783
14805
  workerBundle = await createOpenGeniWorker({
@@ -14791,6 +14813,7 @@ async function createOpenGeniWorkerService(options) {
14791
14813
  observability,
14792
14814
  wakeSessionWorkflow,
14793
14815
  signalSessionAttemptQuiesced,
14816
+ inspectSessionAttemptActivity,
14794
14817
  signalCodexCapacityWorkflow
14795
14818
  }
14796
14819
  });
@@ -14964,6 +14987,7 @@ export {
14964
14987
  resolveOpenGeniWorkflowDefinition,
14965
14988
  runOpenGeniWorker,
14966
14989
  startWorker,
14990
+ temporalActivityLeaseSettled,
14967
14991
  workerOwnsInternalSchedules
14968
14992
  };
14969
14993
  //# sourceMappingURL=index.js.map