@opengeni/worker-bundle 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/index.d.ts +182 -67
  2. package/dist/index.js +7113 -1652
  3. package/dist/index.js.map +1 -1
  4. package/package.json +18 -18
  5. package/src/activities/agent-turn.ts +4337 -1052
  6. package/src/activities/capabilities.ts +43 -8
  7. package/src/activities/codex-capacity.ts +223 -0
  8. package/src/activities/codex-rotation.ts +550 -54
  9. package/src/activities/common.ts +7 -1
  10. package/src/activities/context-compaction.ts +152 -118
  11. package/src/activities/documents.ts +32 -27
  12. package/src/activities/environment.ts +318 -75
  13. package/src/activities/file-upload-reaper.ts +79 -0
  14. package/src/activities/git-credential-renewal.ts +183 -0
  15. package/src/activities/goals.ts +142 -123
  16. package/src/activities/packs.ts +55 -5
  17. package/src/activities/parent-wake.ts +228 -41
  18. package/src/activities/recording.ts +154 -122
  19. package/src/activities/redaction.ts +3 -1
  20. package/src/activities/rig-verification.ts +441 -0
  21. package/src/activities/run-input.ts +110 -122
  22. package/src/activities/sandbox-lease.ts +186 -51
  23. package/src/activities/scheduled-tasks.ts +287 -171
  24. package/src/activities/session-state.ts +168 -157
  25. package/src/activities/streaming.ts +143 -19
  26. package/src/activities/turn-attempt-fenced.ts +14 -0
  27. package/src/activities/types.ts +102 -32
  28. package/src/activities/workflow-wake.ts +44 -0
  29. package/src/activities/workspace-capture.ts +964 -0
  30. package/src/activities.ts +75 -35
  31. package/src/concurrency.ts +11 -0
  32. package/src/http.ts +16 -6
  33. package/src/index.ts +322 -49
  34. package/src/observability-metrics.ts +441 -8
  35. package/src/op-journal.ts +46 -0
  36. package/src/sandbox-resume.ts +431 -201
  37. package/src/sandbox-routing.ts +209 -22
  38. package/src/workflow-wake-contract.ts +5 -0
  39. package/src/workflows/activities.ts +58 -7
  40. package/src/workflows/file-upload-reaper.ts +12 -0
  41. package/src/workflows/rig-verification.ts +28 -0
  42. package/src/workflows/scheduled-tasks.ts +12 -26
  43. package/src/workflows/session.ts +330 -173
  44. package/src/workflows/workflow-wake.ts +12 -0
  45. package/src/workflows.ts +9 -7
@@ -1,27 +1,28 @@
1
1
  import {
2
2
  appendSessionEventsWithLockedSessionUpdate,
3
+ addSessionSystemUpdateWithSourceMutation,
3
4
  createScheduledTaskRun,
4
5
  createSession,
5
6
  createSessionGoal,
6
- enqueueSessionTurn,
7
+ enqueueSessionWorkflowWakeIfRunnable,
7
8
  getBillingBalance,
8
- getWorkspaceEnvironment,
9
+ getRig,
10
+ getVariableSet,
9
11
  isCodexBilledTurn,
12
+ markScheduledTaskRunFailedIfQueued,
10
13
  recordUsageEvent,
11
14
  requireScheduledTask,
12
15
  requireSession,
13
16
  setTemporalWorkflowId,
17
+ settleScheduledTaskRunInTransaction,
14
18
  sumUsageQuantity,
15
19
  updateScheduledTask,
16
- updateScheduledTaskRun,
17
20
  upsertSessionGoal,
18
21
  } from "@opengeni/db";
19
- import { appendAndPublishEvents } from "@opengeni/events";
22
+ import { appendAndPublishEvents, publishDurableSessionEvents } from "@opengeni/events";
20
23
  import { configuredStaticUsageLimits, type Settings } from "@opengeni/config";
21
24
  import {
22
25
  assertReusableSessionRevivable,
23
- mergeResourceRefs,
24
- mergeToolRefs,
25
26
  scheduledUserMessagePayload,
26
27
  workflowIdForSession,
27
28
  } from "./common";
@@ -34,20 +35,38 @@ import type {
34
35
 
35
36
  export function createScheduledTaskActivities(services: () => Promise<ActivityServices>) {
36
37
  return {
37
- dispatchScheduledTaskRun: async (input: DispatchScheduledTaskRunInput): Promise<DispatchScheduledTaskRunResult> => {
38
- const { settings, db, bus } = await services();
38
+ dispatchScheduledTaskRun: async (
39
+ input: DispatchScheduledTaskRunInput,
40
+ ): Promise<DispatchScheduledTaskRunResult> => {
41
+ const { settings, db, bus, wakeSessionWorkflow } = await services();
39
42
  const task = await requireScheduledTask(db, input.workspaceId, input.taskId);
40
43
  // The scheduled task's model can be codex/<slug>; resolve it here so the
41
44
  // admission gate can skip the credit/cost gates for a codex-billed run
42
45
  // (paid by the user's ChatGPT/Codex plan). This file uses BASE settings (no
43
46
  // codex overlay), so the predicate does its own active-credential read.
44
47
  const model = task.agentConfig.model ?? settings.openaiModel;
45
- const isCodexRun = await isCodexBilledTurn({ db, settings, workspaceId: task.workspaceId, model });
46
- await ensureScheduledRunAllowed(settings, db, task.accountId, task.workspaceId, input.agentRunUsageIdempotencyKey ? 0 : 1, isCodexRun);
48
+ const isCodexRun = await isCodexBilledTurn({
49
+ db,
50
+ settings,
51
+ workspaceId: task.workspaceId,
52
+ model,
53
+ });
54
+ await ensureScheduledRunAllowed(
55
+ settings,
56
+ db,
57
+ task.accountId,
58
+ task.workspaceId,
59
+ input.agentRunUsageIdempotencyKey ? 0 : 1,
60
+ isCodexRun,
61
+ );
47
62
  const run = await createScheduledTaskRun(db, {
48
63
  workspaceId: task.workspaceId,
49
64
  taskId: task.id,
50
65
  triggerType: input.triggerType,
66
+ producerKey:
67
+ input.producerKey ??
68
+ input.agentRunUsageIdempotencyKey ??
69
+ `scheduled:${crypto.randomUUID()}`,
51
70
  scheduledAt: null,
52
71
  });
53
72
  await recordUsageEvent(db, {
@@ -60,6 +79,46 @@ export function createScheduledTaskActivities(services: () => Promise<ActivitySe
60
79
  sourceResourceId: run.id,
61
80
  idempotencyKey: `usage:scheduled_task.fired:${run.id}`,
62
81
  });
82
+ if (run.status === "dispatched" && run.sessionId && run.triggerEventId) {
83
+ await recordUsageEvent(db, {
84
+ accountId: task.accountId,
85
+ workspaceId: task.workspaceId,
86
+ eventType: "agent_run.created",
87
+ quantity: 1,
88
+ unit: "run",
89
+ sourceResourceType: "scheduled_task_run",
90
+ sourceResourceId: run.id,
91
+ idempotencyKey:
92
+ input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`,
93
+ });
94
+ const workflowId = workflowIdForSession(run.sessionId);
95
+ const workflowWakeRevision = await enqueueSessionWorkflowWakeIfRunnable(db, {
96
+ accountId: task.accountId,
97
+ workspaceId: task.workspaceId,
98
+ sessionId: run.sessionId,
99
+ temporalWorkflowId: workflowId,
100
+ reason: "scheduled_retry",
101
+ });
102
+ const result = {
103
+ action: task.runMode === "new_session_per_run" ? "start" : "signal",
104
+ accountId: task.accountId,
105
+ workspaceId: task.workspaceId,
106
+ sessionId: run.sessionId,
107
+ triggerEventId: run.triggerEventId,
108
+ workflowId,
109
+ workflowWakeRevision,
110
+ } as const;
111
+ if (wakeSessionWorkflow && workflowWakeRevision !== null) {
112
+ await wakeSessionWorkflow({
113
+ accountId: result.accountId,
114
+ workspaceId: result.workspaceId,
115
+ sessionId: result.sessionId,
116
+ workflowId: result.workflowId,
117
+ wakeRevision: workflowWakeRevision,
118
+ });
119
+ }
120
+ return result;
121
+ }
63
122
  let result: DispatchScheduledTaskRunResult;
64
123
  try {
65
124
  const reasoningEffort = task.agentConfig.reasoningEffort ?? settings.openaiReasoningEffort;
@@ -69,13 +128,28 @@ export function createScheduledTaskActivities(services: () => Promise<ActivitySe
69
128
  // goal tools, and the permission-gated tools), matching the API path.
70
129
  const taskTools = withFirstPartyTools(settings, task.agentConfig.tools);
71
130
  if (task.runMode === "new_session_per_run" || !task.reusableSessionId) {
72
- // The FK on scheduled_tasks.environment_id is ON DELETE RESTRICT, so
73
- // an attached environment must still exist here; fail closed if not.
74
- const environment = task.environmentId
75
- ? await getWorkspaceEnvironment(db, task.workspaceId, task.environmentId)
131
+ // The FK on scheduled_tasks.variable_set_id is ON DELETE RESTRICT, so
132
+ // an attached variableSet must still exist here; fail closed if not.
133
+ const variableSet = task.variableSetId
134
+ ? await getVariableSet(db, task.workspaceId, task.variableSetId)
76
135
  : null;
77
- if (task.environmentId && !environment) {
78
- throw new Error(`workspace environment not found: ${task.environmentId}`);
136
+ if (task.variableSetId && !variableSet) {
137
+ throw new Error(`variable set not found: ${task.variableSetId}`);
138
+ }
139
+ // RIG BINDING (M3): resolve the task's rig to its CURRENTLY-ACTIVE
140
+ // version at FIRE time (not task-create time) and freeze that version
141
+ // onto the new session — a task always runs the rig's latest active
142
+ // version. A deleted rig FK-nulls task.rigId (rig-less run); a rig that
143
+ // somehow has no active version fails the fire closed.
144
+ let frozenRigId: string | null = null;
145
+ let frozenRigVersionId: string | null = null;
146
+ if (task.rigId) {
147
+ const rig = await getRig(db, task.workspaceId, task.rigId);
148
+ if (!rig || !rig.activeVersion) {
149
+ throw new Error(`rig has no active version to bind: ${task.rigId}`);
150
+ }
151
+ frozenRigId = rig.id;
152
+ frozenRigVersionId = rig.activeVersion.id;
79
153
  }
80
154
  const session = await createSession(db, {
81
155
  accountId: task.accountId,
@@ -92,91 +166,108 @@ export function createScheduledTaskActivities(services: () => Promise<ActivitySe
92
166
  },
93
167
  model,
94
168
  sandboxBackend,
95
- environmentId: task.environmentId ?? null,
169
+ variableSetId: task.variableSetId ?? null,
170
+ rigId: frozenRigId,
171
+ rigVersionId: frozenRigVersionId,
96
172
  });
97
173
  const goal = goalSpec
98
174
  ? await createSessionGoal(db, {
99
- accountId: task.accountId,
100
- workspaceId: task.workspaceId,
101
- sessionId: session.id,
102
- text: goalSpec.text,
103
- successCriteria: goalSpec.successCriteria ?? null,
104
- maxAutoContinuations: goalSpec.maxAutoContinuations ?? null,
105
- createdBy: "scheduled_task",
106
- })
175
+ accountId: task.accountId,
176
+ workspaceId: task.workspaceId,
177
+ sessionId: session.id,
178
+ text: goalSpec.text,
179
+ successCriteria: goalSpec.successCriteria ?? null,
180
+ maxAutoContinuations: goalSpec.maxAutoContinuations ?? null,
181
+ createdBy: "scheduled_task",
182
+ })
107
183
  : null;
108
184
  const workflowId = workflowIdForSession(session.id);
109
185
  await setTemporalWorkflowId(db, task.workspaceId, session.id, workflowId);
110
186
  if (task.runMode === "reusable_session") {
111
- await updateScheduledTask(db, task.workspaceId, task.id, { reusableSessionId: session.id });
187
+ await updateScheduledTask(db, task.workspaceId, task.id, {
188
+ reusableSessionId: session.id,
189
+ });
112
190
  }
113
- const events = await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [
191
+ await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [
114
192
  {
115
193
  type: "session.created",
116
194
  payload: {
117
- status: "queued",
195
+ status: session.status,
118
196
  scheduledTaskId: task.id,
119
197
  scheduledTaskRunId: run.id,
120
198
  // Names/ids only; never values.
121
- ...(environment ? { environmentId: environment.id, environmentName: environment.name } : {}),
199
+ ...(variableSet
200
+ ? { variableSetId: variableSet.id, variableSetName: variableSet.name }
201
+ : {}),
122
202
  },
123
203
  },
124
- ...(goal ? [{
125
- type: "goal.set" as const,
126
- payload: {
127
- goalId: goal.id,
128
- text: goal.text,
129
- ...(goal.successCriteria ? { successCriteria: goal.successCriteria } : {}),
130
- version: goal.version,
131
- actor: "scheduled_task",
132
- replaced: false,
133
- },
134
- }] : []),
204
+ ...(goal
205
+ ? [
206
+ {
207
+ type: "goal.set" as const,
208
+ payload: {
209
+ goalId: goal.id,
210
+ text: goal.text,
211
+ ...(goal.successCriteria ? { successCriteria: goal.successCriteria } : {}),
212
+ version: goal.version,
213
+ actor: "scheduled_task",
214
+ replaced: false,
215
+ },
216
+ },
217
+ ]
218
+ : []),
219
+ { type: "session.status.changed", payload: { status: session.status } },
220
+ ]);
221
+ const scheduledUpdate = await addSessionSystemUpdateWithSourceMutation(
222
+ db,
135
223
  {
136
- type: "user.message",
137
- payload: scheduledUserMessagePayload(task.agentConfig.prompt, task.agentConfig.resources, taskTools, task.id, run.id),
224
+ accountId: task.accountId,
225
+ workspaceId: task.workspaceId,
226
+ sessionId: session.id,
227
+ kind: "scheduled_wake",
228
+ classification: "info",
229
+ sourceId: run.id,
230
+ dedupeKey: `scheduled-wake:${run.id}`,
231
+ summary: task.agentConfig.prompt,
232
+ payload: scheduledUserMessagePayload(
233
+ task.agentConfig.prompt,
234
+ task.agentConfig.resources,
235
+ taskTools,
236
+ task.id,
237
+ run.id,
238
+ ),
239
+ lineage: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
138
240
  },
139
- { type: "session.status.changed", payload: { status: "queued" } },
140
- ]);
141
- const trigger = events.find((event) => event.type === "user.message");
142
- if (!trigger) {
143
- throw new Error("failed to append scheduled task trigger event");
144
- }
145
- const turn = await enqueueSessionTurn(db, {
146
- accountId: task.accountId,
147
- workspaceId: task.workspaceId,
148
- sessionId: session.id,
149
- triggerEventId: trigger.id,
150
- temporalWorkflowId: workflowId,
151
- source: "scheduled_task",
152
- prompt: task.agentConfig.prompt,
153
- resources: task.agentConfig.resources,
154
- tools: taskTools,
155
- model,
156
- reasoningEffort,
157
- sandboxBackend,
158
- metadata: {
159
- scheduledTaskId: task.id,
160
- scheduledTaskRunId: run.id,
241
+ async (tx, wakeEventId) => {
242
+ if (!wakeEventId) throw new Error("Scheduled delivery has no wake event");
243
+ await settleScheduledTaskRunInTransaction(tx, {
244
+ workspaceId: task.workspaceId,
245
+ runId: run.id,
246
+ sessionId: session.id,
247
+ triggerEventId: wakeEventId,
248
+ status: "dispatched",
249
+ });
161
250
  },
162
- });
163
- await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [{
164
- type: "turn.queued",
165
- turnId: turn.id,
166
- payload: { turnId: turn.id, triggerEventId: trigger.id, source: turn.source },
167
- }]);
168
- await updateScheduledTaskRun(db, task.workspaceId, run.id, {
169
- status: "dispatched",
170
- sessionId: session.id,
171
- triggerEventId: trigger.id,
172
- });
251
+ );
252
+ if (scheduledUpdate.reason === "session_cancelled") {
253
+ throw new Error("new scheduled session was cancelled during dispatch");
254
+ }
255
+ if (scheduledUpdate.added && scheduledUpdate.events.length > 0) {
256
+ await publishDurableSessionEvents(
257
+ bus,
258
+ task.workspaceId,
259
+ session.id,
260
+ scheduledUpdate.events,
261
+ );
262
+ }
173
263
  result = {
174
264
  action: "start",
175
265
  accountId: task.accountId,
176
266
  workspaceId: task.workspaceId,
177
267
  sessionId: session.id,
178
- triggerEventId: trigger.id,
268
+ triggerEventId: scheduledUpdate.wakeEventId,
179
269
  workflowId,
270
+ workflowWakeRevision: scheduledUpdate.workflowWakeRevision,
180
271
  };
181
272
  } else {
182
273
  const session = await requireSession(db, task.workspaceId, task.reusableSessionId);
@@ -188,99 +279,107 @@ export function createScheduledTaskActivities(services: () => Promise<ActivitySe
188
279
  // Defensive backstop for the API-level 409: a reusable session keeps
189
280
  // its creation-time attachment, so a diverged task attachment must
190
281
  // fail the run instead of silently running with the wrong secrets.
191
- if ((session.environmentId ?? null) !== (task.environmentId ?? null)) {
192
- throw new Error("scheduled task environment attachment does not match its reusable session");
282
+ if ((session.variableSetId ?? null) !== (task.variableSetId ?? null)) {
283
+ throw new Error(
284
+ "scheduled task variableSet attachment does not match its reusable session",
285
+ );
193
286
  }
194
287
  // A recurring "maintain X" task re-establishes its objective on every
195
288
  // fire: replace the goal text, reactivate it, and reset the counters.
196
- const reusableGoal = goalSpec
197
- ? await upsertSessionGoal(db, {
289
+ const reusableGoal =
290
+ goalSpec && run.status === "queued"
291
+ ? await upsertSessionGoal(db, {
292
+ accountId: task.accountId,
293
+ workspaceId: task.workspaceId,
294
+ sessionId: session.id,
295
+ text: goalSpec.text,
296
+ successCriteria: goalSpec.successCriteria ?? null,
297
+ maxAutoContinuations: goalSpec.maxAutoContinuations ?? null,
298
+ createdBy: "scheduled_task",
299
+ })
300
+ : null;
301
+ if (reusableGoal) {
302
+ const goalEvents = await appendSessionEventsWithLockedSessionUpdate(
303
+ db,
304
+ task.workspaceId,
305
+ session.id,
306
+ (locked) => {
307
+ assertReusableSessionRevivable(locked.status);
308
+ return {
309
+ events: [
310
+ {
311
+ type: "goal.set" as const,
312
+ payload: {
313
+ goalId: reusableGoal.goal.id,
314
+ text: reusableGoal.goal.text,
315
+ ...(reusableGoal.goal.successCriteria
316
+ ? { successCriteria: reusableGoal.goal.successCriteria }
317
+ : {}),
318
+ version: reusableGoal.goal.version,
319
+ actor: "scheduled_task",
320
+ replaced: reusableGoal.replaced,
321
+ },
322
+ },
323
+ ],
324
+ };
325
+ },
326
+ );
327
+ await publishDurableSessionEvents(bus, task.workspaceId, session.id, goalEvents);
328
+ }
329
+ const bundled = await addSessionSystemUpdateWithSourceMutation(
330
+ db,
331
+ {
198
332
  accountId: task.accountId,
199
333
  workspaceId: task.workspaceId,
200
334
  sessionId: session.id,
201
- text: goalSpec.text,
202
- successCriteria: goalSpec.successCriteria ?? null,
203
- maxAutoContinuations: goalSpec.maxAutoContinuations ?? null,
204
- createdBy: "scheduled_task",
205
- })
206
- : null;
207
- const events = await appendSessionEventsWithLockedSessionUpdate(db, task.workspaceId, session.id, (locked) => {
208
- // Authoritative guard under the FOR UPDATE row lock: re-check the
209
- // current status to close the TOCTOU between the early read and the
210
- // lock (a cancel could land in between). Throwing aborts the whole
211
- // append+update transaction, so no user.message is persisted.
212
- assertReusableSessionRevivable(locked.status);
213
- return {
214
- events: [
215
- ...(reusableGoal ? [{
216
- type: "goal.set" as const,
217
- payload: {
218
- goalId: reusableGoal.goal.id,
219
- text: reusableGoal.goal.text,
220
- ...(reusableGoal.goal.successCriteria ? { successCriteria: reusableGoal.goal.successCriteria } : {}),
221
- version: reusableGoal.goal.version,
222
- actor: "scheduled_task",
223
- replaced: reusableGoal.replaced,
224
- },
225
- }] : []),
226
- {
227
- type: "user.message",
228
- payload: scheduledUserMessagePayload(task.agentConfig.prompt, task.agentConfig.resources, taskTools, task.id, run.id),
229
- },
230
- ],
231
- update: {
232
- resources: mergeResourceRefs(locked.resources, task.agentConfig.resources),
233
- tools: mergeToolRefs(locked.tools, taskTools),
234
- },
235
- };
236
- });
237
- await bus.publish(task.workspaceId, session.id, events);
238
- const trigger = events.find((event) => event.type === "user.message");
239
- if (!trigger) {
240
- throw new Error("failed to append scheduled task trigger event");
241
- }
242
- const turn = await enqueueSessionTurn(db, {
243
- accountId: task.accountId,
244
- workspaceId: task.workspaceId,
245
- sessionId: session.id,
246
- triggerEventId: trigger.id,
247
- temporalWorkflowId: workflowIdForSession(session.id),
248
- source: "scheduled_task",
249
- prompt: task.agentConfig.prompt,
250
- resources: task.agentConfig.resources,
251
- tools: taskTools,
252
- model,
253
- reasoningEffort,
254
- sandboxBackend,
255
- metadata: {
256
- scheduledTaskId: task.id,
257
- scheduledTaskRunId: run.id,
335
+ kind: "scheduled_wake",
336
+ classification: "info",
337
+ sourceId: run.id,
338
+ dedupeKey: `scheduled-wake:${run.id}`,
339
+ summary: task.agentConfig.prompt,
340
+ payload: scheduledUserMessagePayload(
341
+ task.agentConfig.prompt,
342
+ task.agentConfig.resources,
343
+ taskTools,
344
+ task.id,
345
+ run.id,
346
+ ),
347
+ lineage: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
258
348
  },
259
- });
260
- await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [{
261
- type: "turn.queued",
262
- turnId: turn.id,
263
- payload: { turnId: turn.id, triggerEventId: trigger.id, source: turn.source },
264
- }]);
265
- await updateScheduledTaskRun(db, task.workspaceId, run.id, {
266
- status: "dispatched",
267
- sessionId: session.id,
268
- triggerEventId: trigger.id,
269
- });
349
+ async (tx, wakeEventId) => {
350
+ if (!wakeEventId) throw new Error("Scheduled delivery has no wake event");
351
+ await settleScheduledTaskRunInTransaction(tx, {
352
+ workspaceId: task.workspaceId,
353
+ runId: run.id,
354
+ sessionId: session.id,
355
+ triggerEventId: wakeEventId,
356
+ status: "dispatched",
357
+ });
358
+ },
359
+ );
360
+ if (bundled.reason === "session_cancelled") {
361
+ throw new Error(`scheduled wake was not added: ${bundled.reason}`);
362
+ }
363
+ if (bundled.added && bundled.events.length > 0) {
364
+ await publishDurableSessionEvents(bus, task.workspaceId, session.id, bundled.events);
365
+ }
270
366
  result = {
271
367
  action: "signal",
272
368
  accountId: task.accountId,
273
369
  workspaceId: task.workspaceId,
274
370
  sessionId: session.id,
275
- triggerEventId: trigger.id,
371
+ triggerEventId: bundled.wakeEventId,
276
372
  workflowId: workflowIdForSession(session.id),
373
+ workflowWakeRevision: bundled.workflowWakeRevision,
277
374
  };
278
375
  }
279
376
  } catch (error) {
280
- await updateScheduledTaskRun(db, task.workspaceId, run.id, {
281
- status: "failed",
282
- error: error instanceof Error ? error.message : String(error),
283
- }).catch(() => undefined);
377
+ await markScheduledTaskRunFailedIfQueued(
378
+ db,
379
+ task.workspaceId,
380
+ run.id,
381
+ error instanceof Error ? error.message : String(error),
382
+ ).catch(() => undefined);
284
383
  throw error;
285
384
  }
286
385
  await recordUsageEvent(db, {
@@ -291,8 +390,18 @@ export function createScheduledTaskActivities(services: () => Promise<ActivitySe
291
390
  unit: "run",
292
391
  sourceResourceType: "scheduled_task_run",
293
392
  sourceResourceId: run.id,
294
- idempotencyKey: input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`,
393
+ idempotencyKey:
394
+ input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`,
295
395
  });
396
+ if (wakeSessionWorkflow && result.workflowWakeRevision !== null) {
397
+ await wakeSessionWorkflow({
398
+ accountId: result.accountId,
399
+ workspaceId: result.workspaceId,
400
+ sessionId: result.sessionId,
401
+ workflowId: result.workflowId,
402
+ wakeRevision: result.workflowWakeRevision,
403
+ });
404
+ }
296
405
  return result;
297
406
  },
298
407
  };
@@ -309,32 +418,39 @@ async function ensureScheduledRunAllowed(
309
418
  // Codex-billed runs are paid by the user's ChatGPT/Codex plan: skip the
310
419
  // credit-balance gate and the monthly model-cost cap. The agent-run COUNT cap
311
420
  // below is a volume quota (not a credit/cost gate) and is intentionally kept.
312
- if (!isCodexRun && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
421
+ if (
422
+ !isCodexRun &&
423
+ (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")
424
+ ) {
313
425
  const balance = await getBillingBalance(db, accountId);
314
426
  if (balance.balanceMicros <= 0) {
315
427
  throw new Error("insufficient OpenGeni credits");
316
428
  }
317
429
  }
318
- if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
319
- const limits = configuredStaticUsageLimits(settings);
320
- if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {
321
- const used = await sumUsageQuantity(db, {
322
- accountId,
323
- eventType: "model.cost",
324
- since: startOfUtcMonth(),
325
- });
326
- if (used >= limits.maxMonthlyCostMicrosPerAccount) {
327
- throw new Error(`monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`);
328
- }
329
- }
330
- if (limits.maxMonthlyAgentRunsPerWorkspace) {
331
- const used = await sumUsageQuantity(db, {
332
- workspaceId,
430
+ if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
431
+ const limits = configuredStaticUsageLimits(settings);
432
+ if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {
433
+ const used = await sumUsageQuantity(db, {
434
+ accountId,
435
+ eventType: "model.cost",
436
+ since: startOfUtcMonth(),
437
+ });
438
+ if (used >= limits.maxMonthlyCostMicrosPerAccount) {
439
+ throw new Error(
440
+ `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`,
441
+ );
442
+ }
443
+ }
444
+ if (limits.maxMonthlyAgentRunsPerWorkspace) {
445
+ const used = await sumUsageQuantity(db, {
446
+ workspaceId,
333
447
  eventType: "agent_run.created",
334
448
  since: startOfUtcMonth(),
335
449
  });
336
450
  if (used + requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {
337
- throw new Error(`monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`);
451
+ throw new Error(
452
+ `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`,
453
+ );
338
454
  }
339
455
  }
340
456
  }