@opengeni/worker-bundle 0.12.2 → 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,11 +5834,15 @@ 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";
5892
5841
  import { createHash as createHash4, randomUUID } from "crypto";
5893
5842
  var PROVIDER_BACKPRESSURE_DELAY_MS = 6e4;
5843
+ function credentialSubjectIdForTurnInitiator(initiator) {
5844
+ return initiator.kind === "subject" ? initiator.subjectId : void 0;
5845
+ }
5894
5846
  function turnExecutionPolicyBillingIdentity(policy) {
5895
5847
  return {
5896
5848
  externallyBilled: policy.billing.metering === "external",
@@ -6398,11 +6350,13 @@ function applyCodexCacheTelemetry(observability, provider, normalizedUsage) {
6398
6350
  });
6399
6351
  }
6400
6352
  function historyRowsToAppend(rawHistory, persistedHistoryCount, nextPosition = persistedHistoryCount, toolOutputTruncationTokens, redactValue = (value) => value) {
6401
- 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
+ );
6402
6356
  if (sanitized.length <= persistedHistoryCount) {
6403
6357
  return { rows: [], nextWatermark: persistedHistoryCount, nextPosition };
6404
6358
  }
6405
- 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) => ({
6406
6360
  position: nextPosition + offset,
6407
6361
  item
6408
6362
  }));
@@ -8336,10 +8290,7 @@ function createRunAgentTurnActivity(services) {
8336
8290
  defaultNativeToolsAllowed = sessionToolPolicyAllowsDefaultNativeTools(
8337
8291
  resolvedToolPolicy.effectivePolicy
8338
8292
  );
8339
- const turnTools = withCodexAppsTool(
8340
- runSettings,
8341
- withFirstPartyTools(runSettings, effectivePolicyTools)
8342
- );
8293
+ const turnTools = withFirstPartyTools(runSettings, effectivePolicyTools);
8343
8294
  const connectionScope = {
8344
8295
  accountId: input.accountId,
8345
8296
  workspaceId: input.workspaceId
@@ -8997,6 +8948,7 @@ function createRunAgentTurnActivity(services) {
8997
8948
  }
8998
8949
  return result;
8999
8950
  };
8951
+ const credentialSubjectId = credentialSubjectIdForTurnInitiator(turn.initiator);
9000
8952
  preparedTools = await waitForTurnOperation(
9001
8953
  withCodex(
9002
8954
  () => runtime.prepareTools(runSettings, turnTools, {
@@ -9011,13 +8963,15 @@ function createRunAgentTurnActivity(services) {
9011
8963
  executionGeneration,
9012
8964
  subjectId: "worker:first-party-mcp",
9013
8965
  subjectLabel: "OpenGeni worker",
8966
+ ...credentialSubjectId ? { credentialSubjectId } : {},
9014
8967
  resolveCredential,
9015
8968
  onAuthNeeded: async (payload) => {
9016
8969
  await publish([{ type: "tool.auth_needed", payload }], true);
9017
8970
  },
9018
8971
  // Manager-style sessions carry a creation-validated permission set
9019
8972
  // for their first-party MCP token; null keeps the fixed default.
9020
- ...session.firstPartyMcpPermissions?.length ? { firstPartyPermissions: session.firstPartyMcpPermissions } : {}
8973
+ ...session.firstPartyMcpPermissions?.length ? { firstPartyPermissions: session.firstPartyMcpPermissions } : {},
8974
+ firstPartyTools: session.firstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS]
9021
8975
  })
9022
8976
  ),
9023
8977
  cancellationSignal,
@@ -9131,6 +9085,7 @@ function createRunAgentTurnActivity(services) {
9131
9085
  await maybeStartOnTurnRecording(resolvedSandbox, activeSandboxBackend);
9132
9086
  },
9133
9087
  ...packRuntime.skills.length > 0 ? { packSkills: packRuntime.skills } : {},
9088
+ ...session.skills.length > 0 ? { sessionSkills: session.skills } : {},
9134
9089
  ...skillLibraryRuntime.skillLibrarySkills.length > 0 ? {
9135
9090
  skillLibrarySkills: skillLibraryRuntime.skillLibrarySkills,
9136
9091
  skillLibrarySelections: skillLibraryRuntime.skillLibrarySelections
@@ -12561,12 +12516,12 @@ import {
12561
12516
  createSessionGoal,
12562
12517
  enqueueSessionWorkflowWakeIfRunnable as enqueueSessionWorkflowWakeIfRunnable2,
12563
12518
  getBillingBalance as getBillingBalance5,
12519
+ getScheduledTask,
12564
12520
  getRig,
12565
12521
  getVariableSet,
12566
12522
  isCodexBilledTurn as isCodexBilledTurn2,
12567
12523
  markScheduledTaskRunFailedIfQueued,
12568
12524
  recordUsageEvent as recordUsageEvent3,
12569
- requireScheduledTask,
12570
12525
  requireSession as requireSession3,
12571
12526
  setTemporalWorkflowId,
12572
12527
  settleScheduledTaskRunInTransaction,
@@ -12581,7 +12536,13 @@ function createScheduledTaskActivities(services) {
12581
12536
  return {
12582
12537
  dispatchScheduledTaskRun: async (input) => {
12583
12538
  const { settings, db, bus, wakeSessionWorkflow } = await services();
12584
- 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
+ }
12585
12546
  const slackBotConnection = task.agentConfig.slackBotConnectionId ? await requireOpenGeniSlackBotConnection(
12586
12547
  db,
12587
12548
  task.workspaceId,
@@ -12598,7 +12559,7 @@ function createScheduledTaskActivities(services) {
12598
12559
  workspaceId: task.workspaceId,
12599
12560
  model
12600
12561
  });
12601
- await ensureScheduledRunAllowed(
12562
+ const admissionDenial = await scheduledRunAdmissionDenial(
12602
12563
  settings,
12603
12564
  db,
12604
12565
  task.accountId,
@@ -12606,6 +12567,9 @@ function createScheduledTaskActivities(services) {
12606
12567
  input.agentRunUsageIdempotencyKey ? 0 : 1,
12607
12568
  isCodexRun
12608
12569
  );
12570
+ if (admissionDenial) {
12571
+ return { action: "blocked", reason: admissionDenial };
12572
+ }
12609
12573
  const run = await createScheduledTaskRun(db, {
12610
12574
  workspaceId: task.workspaceId,
12611
12575
  taskId: task.id,
@@ -12621,7 +12585,7 @@ function createScheduledTaskActivities(services) {
12621
12585
  unit: "run",
12622
12586
  sourceResourceType: "scheduled_task_run",
12623
12587
  sourceResourceId: run.id,
12624
- initiator: { kind: "service", subjectId: "scheduler" },
12588
+ initiator: input.initiator ?? { kind: "service", subjectId: "scheduler" },
12625
12589
  initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
12626
12590
  origin: "scheduled_task",
12627
12591
  idempotencyKey: `usage:scheduled_task.fired:${run.id}`
@@ -12636,7 +12600,7 @@ function createScheduledTaskActivities(services) {
12636
12600
  sourceResourceType: "scheduled_task_run",
12637
12601
  sourceResourceId: run.id,
12638
12602
  sessionId: run.sessionId,
12639
- initiator: { kind: "service", subjectId: "scheduler" },
12603
+ initiator: input.initiator ?? { kind: "service", subjectId: "scheduler" },
12640
12604
  initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
12641
12605
  origin: "scheduled_task",
12642
12606
  idempotencyKey: input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`
@@ -12952,7 +12916,7 @@ function createScheduledTaskActivities(services) {
12952
12916
  sourceResourceType: "scheduled_task_run",
12953
12917
  sourceResourceId: run.id,
12954
12918
  sessionId: result.sessionId,
12955
- initiator: { kind: "service", subjectId: "scheduler" },
12919
+ initiator: input.initiator ?? { kind: "service", subjectId: "scheduler" },
12956
12920
  initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
12957
12921
  origin: "scheduled_task",
12958
12922
  idempotencyKey: input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`
@@ -12970,11 +12934,11 @@ function createScheduledTaskActivities(services) {
12970
12934
  }
12971
12935
  };
12972
12936
  }
12973
- async function ensureScheduledRunAllowed(settings, db, accountId, workspaceId, requestedAgentRuns, isCodexRun) {
12937
+ async function scheduledRunAdmissionDenial(settings, db, accountId, workspaceId, requestedAgentRuns, isCodexRun) {
12974
12938
  if (!isCodexRun && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
12975
12939
  const balance = await getBillingBalance5(db, accountId);
12976
12940
  if (balance.balanceMicros <= 0) {
12977
- throw new Error("insufficient OpenGeni credits");
12941
+ return "insufficient_credits";
12978
12942
  }
12979
12943
  }
12980
12944
  if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
@@ -12986,9 +12950,7 @@ async function ensureScheduledRunAllowed(settings, db, accountId, workspaceId, r
12986
12950
  since: startOfUtcMonth4()
12987
12951
  });
12988
12952
  if (used >= limits.maxMonthlyCostMicrosPerAccount) {
12989
- throw new Error(
12990
- `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`
12991
- );
12953
+ return "monthly_model_cost_limit";
12992
12954
  }
12993
12955
  }
12994
12956
  if (limits.maxMonthlyAgentRunsPerWorkspace) {
@@ -12998,12 +12960,11 @@ async function ensureScheduledRunAllowed(settings, db, accountId, workspaceId, r
12998
12960
  since: startOfUtcMonth4()
12999
12961
  });
13000
12962
  if (used + requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {
13001
- throw new Error(
13002
- `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`
13003
- );
12963
+ return "monthly_agent_run_limit";
13004
12964
  }
13005
12965
  }
13006
12966
  }
12967
+ return null;
13007
12968
  }
13008
12969
  function startOfUtcMonth4() {
13009
12970
  const now = /* @__PURE__ */ new Date();
@@ -13015,8 +12976,10 @@ import {
13015
12976
  settleSessionAttemptInterruptions,
13016
12977
  applySessionTurnSettlement as applySessionTurnSettlement2,
13017
12978
  recoverSessionDispatch,
12979
+ reconcileSessionAttemptQuiescence,
13018
12980
  peekSessionWork as peekSessionWorkDb,
13019
12981
  countQueuedTurns as countQueuedTurns2,
12982
+ getSessionAttemptActivityRef,
13020
12983
  getSessionEvent as getSessionEvent3,
13021
12984
  getSessionTurnForAttempt,
13022
12985
  expireSessionHumanInputRequest,
@@ -13030,8 +12993,10 @@ function createSessionStateActivities(services, overrides = {}) {
13030
12993
  const settleSessionAttemptInterruptionsFn = overrides.settleSessionAttemptInterruptions ?? settleSessionAttemptInterruptions;
13031
12994
  const applySessionTurnSettlementFn = overrides.applySessionTurnSettlement ?? applySessionTurnSettlement2;
13032
12995
  const recoverSessionDispatchFn = overrides.recoverSessionDispatch ?? recoverSessionDispatch;
12996
+ const reconcileSessionAttemptQuiescenceFn = overrides.reconcileSessionAttemptQuiescence ?? reconcileSessionAttemptQuiescence;
13033
12997
  const peekSessionWorkFn = overrides.peekSessionWork ?? peekSessionWorkDb;
13034
12998
  const countQueuedTurnsFn = overrides.countQueuedTurns ?? countQueuedTurns2;
12999
+ const getSessionAttemptActivityRefFn = overrides.getSessionAttemptActivityRef ?? getSessionAttemptActivityRef;
13035
13000
  const getSessionEventFn = overrides.getSessionEvent ?? getSessionEvent3;
13036
13001
  const getSessionTurnForAttemptFn = overrides.getSessionTurnForAttempt ?? getSessionTurnForAttempt;
13037
13002
  const expireSessionHumanInputRequestFn = overrides.expireSessionHumanInputRequest ?? expireSessionHumanInputRequest;
@@ -13133,6 +13098,38 @@ function createSessionStateActivities(services, overrides = {}) {
13133
13098
  });
13134
13099
  }
13135
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
+ }
13136
13133
  async function recoverDispatch2(input) {
13137
13134
  const { settings, db, bus, observability, wakeSessionWorkflow } = await services();
13138
13135
  const result = await recoverSessionDispatchFn(db, input.workspaceId, {
@@ -13207,6 +13204,7 @@ function createSessionStateActivities(services, overrides = {}) {
13207
13204
  failSessionAttempt: failSessionAttempt2,
13208
13205
  settleSessionInterruptions: settleSessionInterruptions2,
13209
13206
  persistSessionAttemptQuiescence: persistSessionAttemptQuiescence2,
13207
+ reconcileSessionAttemptQuiescence: reconcileSessionAttemptQuiescenceActivity,
13210
13208
  recoverDispatch: recoverDispatch2,
13211
13209
  peekSessionWork: peekSessionWork2,
13212
13210
  expireSessionHumanInput: expireSessionHumanInput2,
@@ -14137,6 +14135,7 @@ function createActivityServices(dependencies) {
14137
14135
  observability,
14138
14136
  wakeSessionWorkflow: dependencies.wakeSessionWorkflow ?? null,
14139
14137
  signalSessionAttemptQuiesced: dependencies.signalSessionAttemptQuiesced ?? null,
14138
+ inspectSessionAttemptActivity: dependencies.inspectSessionAttemptActivity ?? null,
14140
14139
  signalCodexCapacityWorkflow: dependencies.signalCodexCapacityWorkflow ?? null,
14141
14140
  // §7.5 P3 — host-entitlements port. No constructed default: standalone
14142
14141
  // has no host meter, so unset → null → `ensureRunAllowed` reads the
@@ -14183,6 +14182,7 @@ var indexDocument = defaultControlActivities.indexDocument;
14183
14182
  var failSessionAttempt = defaultControlActivities.failSessionAttempt;
14184
14183
  var settleSessionInterruptions = defaultControlActivities.settleSessionInterruptions;
14185
14184
  var persistSessionAttemptQuiescence = defaultControlActivities.persistSessionAttemptQuiescence;
14185
+ var reconcileSessionAttemptQuiescence2 = defaultControlActivities.reconcileSessionAttemptQuiescence;
14186
14186
  var recoverDispatch = defaultControlActivities.recoverDispatch;
14187
14187
  var peekSessionWork = defaultControlActivities.peekSessionWork;
14188
14188
  var expireSessionHumanInput = defaultControlActivities.expireSessionHumanInput;
@@ -14208,6 +14208,15 @@ var activity = proxyActivities({
14208
14208
  maximumInterval: "30 seconds"
14209
14209
  }
14210
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
+ });
14211
14220
  var goalActivity = proxyActivities({
14212
14221
  startToCloseTimeout: "30 seconds",
14213
14222
  retry: {
@@ -14469,6 +14478,16 @@ function createWorkerServiceLifecycle(input) {
14469
14478
  var SANDBOX_REAPER_SCHEDULE_ID = "opengeni-sandbox-lease-reaper";
14470
14479
  var FILE_UPLOAD_REAPER_SCHEDULE_ID = "opengeni-file-upload-reaper";
14471
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
+ }
14472
14491
  function resolveOpenGeniWorkflowDefinition(moduleUrl = import.meta.url) {
14473
14492
  const modulePath = fileURLToPath(moduleUrl).replaceAll("\\", "/");
14474
14493
  if (modulePath.endsWith("/src/index.ts")) {
@@ -14601,6 +14620,16 @@ async function createWorkerWorkflowSignaler(settings, db) {
14601
14620
  signalArgs: [proof]
14602
14621
  });
14603
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
+ },
14604
14633
  signalCodexCapacityWorkflow: async ({
14605
14634
  accountId,
14606
14635
  workspaceId,
@@ -14760,7 +14789,7 @@ async function createOpenGeniWorkerService(options) {
14760
14789
  const schedules = [];
14761
14790
  let httpServer;
14762
14791
  try {
14763
- 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;
14764
14793
  if (needsSignaler) {
14765
14794
  signaler = await retryStartupDependency(
14766
14795
  "Temporal client",
@@ -14770,8 +14799,9 @@ async function createOpenGeniWorkerService(options) {
14770
14799
  }
14771
14800
  const wakeSessionWorkflow = options.activityDependencies.wakeSessionWorkflow ?? signaler?.wakeSessionWorkflow;
14772
14801
  const signalSessionAttemptQuiesced = options.activityDependencies.signalSessionAttemptQuiesced ?? signaler?.signalSessionAttemptQuiesced;
14802
+ const inspectSessionAttemptActivity = options.activityDependencies.inspectSessionAttemptActivity ?? signaler?.inspectSessionAttemptActivity;
14773
14803
  const signalCodexCapacityWorkflow = options.activityDependencies.signalCodexCapacityWorkflow ?? signaler?.signalCodexCapacityWorkflow;
14774
- if (!wakeSessionWorkflow || !signalSessionAttemptQuiesced || !signalCodexCapacityWorkflow) {
14804
+ if (!wakeSessionWorkflow || !signalSessionAttemptQuiesced || !inspectSessionAttemptActivity || !signalCodexCapacityWorkflow) {
14775
14805
  throw new Error("OpenGeni worker lifecycle could not resolve its workflow signalers");
14776
14806
  }
14777
14807
  workerBundle = await createOpenGeniWorker({
@@ -14785,6 +14815,7 @@ async function createOpenGeniWorkerService(options) {
14785
14815
  observability,
14786
14816
  wakeSessionWorkflow,
14787
14817
  signalSessionAttemptQuiesced,
14818
+ inspectSessionAttemptActivity,
14788
14819
  signalCodexCapacityWorkflow
14789
14820
  }
14790
14821
  });
@@ -14958,6 +14989,7 @@ export {
14958
14989
  resolveOpenGeniWorkflowDefinition,
14959
14990
  runOpenGeniWorker,
14960
14991
  startWorker,
14992
+ temporalActivityLeaseSettled,
14961
14993
  workerOwnsInternalSchedules
14962
14994
  };
14963
14995
  //# sourceMappingURL=index.js.map