glove-foundry 0.9.0 → 0.10.0

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.
@@ -14,24 +14,32 @@ import {
14
14
  FOUNDRY_CORE_COMMAND_EVENT,
15
15
  FOUNDRY_MODEL_REQUESTS_ENV,
16
16
  MemoryFoundryDataAdapter,
17
+ TERMINAL_OCCURRENCE_STATUSES,
18
+ activationScheduleRevision,
19
+ compareOccurrences,
17
20
  createAgentInstance,
18
21
  createConversation,
19
22
  createManifest,
20
23
  definePlaybookSubscription,
21
24
  discoverAgents,
25
+ firstScheduledTime,
22
26
  foundryApprovalRequested,
23
27
  foundryApprovalSuspended,
24
28
  freezeGloveMessage,
25
29
  id,
26
30
  listFoundryApprovals,
27
31
  markFoundryApprovalSuspended,
32
+ matchesOccurrenceFilter,
28
33
  normalizeAgentInstallations,
34
+ planScheduleOccurrence,
35
+ prunableOccurrences,
29
36
  readFoundryApprovalResolution,
30
37
  reconstructPlaybook,
31
38
  reconstructPlaybookSubscription,
32
39
  resolveFoundryApproval,
40
+ scheduleOccurrenceId,
33
41
  transmissionPredicate
34
- } from "./chunk-EUGKVW3J.js";
42
+ } from "./chunk-T6YLIGER.js";
35
43
  import {
36
44
  FOUNDRY_CONVERSATION_LEASE_EVENT,
37
45
  FOUNDRY_CONVERSATION_LISTEN_EVENT,
@@ -1090,11 +1098,6 @@ ${error.stderrTail}
1090
1098
  getAdapter() {
1091
1099
  return { ping: () => this.ping() };
1092
1100
  }
1093
- schedules = {
1094
- add: (schedule) => this.request({ method: "schedule.add", schedule }),
1095
- delete: (id2) => this.request({ method: "schedule.delete", id: id2 }),
1096
- ping: () => this.ping()
1097
- };
1098
1101
  async waitForRun(id2, options = {}) {
1099
1102
  const deadline = Date.now() + (options.timeoutMs ?? 6e4);
1100
1103
  do {
@@ -1106,11 +1109,6 @@ ${error.stderrTail}
1106
1109
  }
1107
1110
  };
1108
1111
 
1109
- // src/runtime.ts
1110
- import {
1111
- nextCronOccurrence
1112
- } from "station-schedules";
1113
-
1114
1112
  // src/conversation-gate.ts
1115
1113
  var ConversationGate = class {
1116
1114
  constructor(hooks) {
@@ -1732,7 +1730,6 @@ var FoundryRuntime = class _FoundryRuntime {
1732
1730
  execution;
1733
1731
  observer;
1734
1732
  signalRunner;
1735
- scheduleAdapter;
1736
1733
  services;
1737
1734
  runnerLoops = [];
1738
1735
  materializedActivations = /* @__PURE__ */ new Set();
@@ -1740,6 +1737,14 @@ var FoundryRuntime = class _FoundryRuntime {
1740
1737
  activationTransitions = Effect5.unsafeMakeSemaphore(1);
1741
1738
  activationDispatches = /* @__PURE__ */ new Map();
1742
1739
  activationTimers = /* @__PURE__ */ new Map();
1740
+ /** Occurrences when the data adapter does not store them. */
1741
+ memoryOccurrences = /* @__PURE__ */ new Map();
1742
+ /** Occurrences this process handed (or is handing) to a run. */
1743
+ occurrencesInHand = /* @__PURE__ */ new Set();
1744
+ /** Run id to the occurrence it delivers. */
1745
+ occurrenceRuns = /* @__PURE__ */ new Map();
1746
+ /** How recent runs settled, for an occurrence recorded after its run already finished. */
1747
+ recentlySettledRuns = /* @__PURE__ */ new Map();
1743
1748
  /** Whether each run's child process still holds its conversation, from FOUNDRY_RUN_PROCESS_EVENT. */
1744
1749
  runProcesses = /* @__PURE__ */ new Map();
1745
1750
  approvalDirectory = join2(
@@ -1969,7 +1974,6 @@ var FoundryRuntime = class _FoundryRuntime {
1969
1974
  ...options.config?.observability?.modelRequests === false ? { [FOUNDRY_MODEL_REQUESTS_ENV]: "off" } : {}
1970
1975
  }
1971
1976
  });
1972
- this.scheduleAdapter = this.signalRunner.schedules;
1973
1977
  const topologyLayer = memoryTopologyStore;
1974
1978
  const defaultServices = Layer3.mergeAll(
1975
1979
  memoryAccountDirectory(this.application.accounts ?? []),
@@ -2292,7 +2296,7 @@ var FoundryRuntime = class _FoundryRuntime {
2292
2296
  await this.withActivationTransition(async () => {
2293
2297
  for (const activation of await Effect5.runPromise(this.data.listActivations(current.workspaceId))) {
2294
2298
  if (activation.agentId !== current.id || ["cancelled", "completed"].includes(activation.status)) continue;
2295
- await this.disarmActivation(activation);
2299
+ await this.disarmActivation(activation, "paused");
2296
2300
  await Effect5.runPromise(this.data.putActivation({ ...activation, status: "paused", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }));
2297
2301
  }
2298
2302
  });
@@ -3388,7 +3392,7 @@ var FoundryRuntime = class _FoundryRuntime {
3388
3392
  const [execution, environment, activations] = await Promise.all([
3389
3393
  this.signalRunner.getAdapter().ping(),
3390
3394
  this.signalRunner.ping(),
3391
- this.scheduleAdapter.ping()
3395
+ this.signalRunner.ping()
3392
3396
  ]);
3393
3397
  return {
3394
3398
  ok: execution && environment && activations,
@@ -4834,6 +4838,17 @@ var FoundryRuntime = class _FoundryRuntime {
4834
4838
  }
4835
4839
  async handleRunSettled(event) {
4836
4840
  void this.settleApprovalsOf(event.run.id).catch((cause) => this.reportApprovalFailure(event.run.id, cause));
4841
+ this.recentlySettledRuns.set(event.run.id, event.status);
4842
+ if (this.recentlySettledRuns.size > 1e3) this.recentlySettledRuns.delete(this.recentlySettledRuns.keys().next().value);
4843
+ void this.settleOccurrence(event.run.id, event.status).catch((cause) => {
4844
+ this.observability.append({
4845
+ type: "activation.persistence.error",
4846
+ category: "activation",
4847
+ agent: event.route,
4848
+ runId: event.run.id,
4849
+ data: { error: cause instanceof Error ? cause.message : String(cause) }
4850
+ });
4851
+ });
4837
4852
  this.releaseConversationRun(event.run.id);
4838
4853
  void this.waitForRunProcessRelease(this.toFoundryRun(event.run), event.route).finally(() => this.gate.settled(event.run.id));
4839
4854
  const finishDelivery = async () => {
@@ -5191,21 +5206,20 @@ var FoundryRuntime = class _FoundryRuntime {
5191
5206
  throw new Error(`Scheduled activation "${activation.id}" is not owned by this agent instance.`);
5192
5207
  }
5193
5208
  }
5194
- backendScheduleId(activationId) {
5195
- return `activation/${activationId.replaceAll("_", "-")}`;
5196
- }
5197
- async disarmActivation(activation) {
5209
+ async disarmActivation(activation, reason) {
5198
5210
  this.activationDispatches.delete(activation.id);
5199
5211
  const timer = this.activationTimers.get(activation.id);
5200
5212
  if (timer) {
5201
5213
  clearTimeout(timer);
5202
5214
  this.activationTimers.delete(activation.id);
5203
5215
  }
5204
- if (activation.timing.kind === "every" || activation.timing.kind === "cron") {
5205
- await this.scheduleAdapter.delete(this.backendScheduleId(activation.id));
5206
- } else if (activation.lastRunId) {
5216
+ if (activation.timing.kind === "at" && activation.lastRunId) {
5207
5217
  await this.signalRunner.cancel(activation.lastRunId);
5208
5218
  }
5219
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5220
+ for (const occurrence of await this.listScheduleOccurrences({ activationId: activation.id, status: "pending" })) {
5221
+ await this.putOccurrence({ ...occurrence, status: "cancelled", reason, updatedAt: now, settledAt: now });
5222
+ }
5209
5223
  this.materializedActivations.delete(activation.id);
5210
5224
  }
5211
5225
  async syncDefinitionSchedules(command, parentRunId) {
@@ -5214,7 +5228,7 @@ var FoundryRuntime = class _FoundryRuntime {
5214
5228
  );
5215
5229
  const desiredIds = new Set(command.schedules.map((item) => item.id));
5216
5230
  for (const stale of current.filter((item) => !desiredIds.has(item.id))) {
5217
- await this.disarmActivation(stale);
5231
+ await this.disarmActivation(stale, "cancelled");
5218
5232
  await Effect5.runPromise(this.data.putActivation({
5219
5233
  ...stale,
5220
5234
  status: "cancelled",
@@ -5226,7 +5240,7 @@ var FoundryRuntime = class _FoundryRuntime {
5226
5240
  if (existing) this.assertActivationOwnership(existing, command);
5227
5241
  if (!desired.enabled) {
5228
5242
  if (existing && existing.status !== "cancelled") {
5229
- await this.disarmActivation(existing);
5243
+ await this.disarmActivation(existing, "cancelled");
5230
5244
  await Effect5.runPromise(this.data.putActivation({
5231
5245
  ...existing,
5232
5246
  status: "cancelled",
@@ -5237,7 +5251,7 @@ var FoundryRuntime = class _FoundryRuntime {
5237
5251
  }
5238
5252
  const unchanged = existing?.definitionRevision === desired.revision;
5239
5253
  if (unchanged || existing?.status === "cancelled") continue;
5240
- if (existing) await this.disarmActivation(existing);
5254
+ if (existing) await this.disarmActivation(existing, "superseded");
5241
5255
  const now = (/* @__PURE__ */ new Date()).toISOString();
5242
5256
  const activation = {
5243
5257
  id: desired.id,
@@ -5265,9 +5279,10 @@ var FoundryRuntime = class _FoundryRuntime {
5265
5279
  const existing = await Effect5.runPromise(this.data.getActivation(command.activationId));
5266
5280
  if (!existing) throw new Error(`Scheduled activation "${command.activationId}" was not found.`);
5267
5281
  this.assertActivationOwnership(existing, command);
5268
- await this.disarmActivation(existing);
5282
+ await this.disarmActivation(existing, "superseded");
5283
+ const { nextOccurrenceAt: _cursor, scheduleRevision: _revision, ...unarmed } = existing;
5269
5284
  const updated = {
5270
- ...existing,
5285
+ ...unarmed,
5271
5286
  ...command.patch,
5272
5287
  status: existing.status === "paused" ? "paused" : "pending",
5273
5288
  createdByRunId: parentRunId,
@@ -5292,7 +5307,7 @@ var FoundryRuntime = class _FoundryRuntime {
5292
5307
  throw new Error(`Scheduled activation "${command.activationId}" cannot be paused from status "${existing.status}".`);
5293
5308
  }
5294
5309
  if (existing.status !== "paused") {
5295
- await this.disarmActivation(existing);
5310
+ await this.disarmActivation(existing, "paused");
5296
5311
  await Effect5.runPromise(this.data.putActivation({
5297
5312
  ...existing,
5298
5313
  status: "paused",
@@ -5314,8 +5329,9 @@ var FoundryRuntime = class _FoundryRuntime {
5314
5329
  if (existing.status !== "paused") {
5315
5330
  throw new Error(`Scheduled activation "${command.activationId}" is not paused.`);
5316
5331
  }
5332
+ const { nextOccurrenceAt: _paused, scheduleRevision: _revision, ...unpaused } = existing;
5317
5333
  const resumed = {
5318
- ...existing,
5334
+ ...unpaused,
5319
5335
  status: "pending",
5320
5336
  createdByRunId: parentRunId,
5321
5337
  lastRunId: void 0,
@@ -5335,7 +5351,7 @@ var FoundryRuntime = class _FoundryRuntime {
5335
5351
  const existing = await Effect5.runPromise(this.data.getActivation(command.activationId));
5336
5352
  if (!existing) throw new Error(`Scheduled activation "${command.activationId}" was not found.`);
5337
5353
  this.assertActivationOwnership(existing, command);
5338
- await this.disarmActivation(existing);
5354
+ await this.disarmActivation(existing, "cancelled");
5339
5355
  await Effect5.runPromise(this.data.putActivation({
5340
5356
  ...existing,
5341
5357
  status: "cancelled",
@@ -5351,12 +5367,37 @@ var FoundryRuntime = class _FoundryRuntime {
5351
5367
  }
5352
5368
  reconstructActivations() {
5353
5369
  return this.withActivationTransition(async () => {
5370
+ await this.replayScheduleOccurrences();
5354
5371
  for (const activation of await Effect5.runPromise(this.data.listActivations())) {
5355
5372
  if (activation.status === "paused" || activation.status === "completed" || activation.status === "cancelled") continue;
5356
5373
  await this.materializeActivation(activation);
5357
5374
  }
5358
5375
  });
5359
5376
  }
5377
+ /** List occurrences of schedules and sleeps: what came due, when it was meant for, and what became of it. */
5378
+ async listScheduleOccurrences(filter = {}) {
5379
+ if (this.durableOccurrences()) return Effect5.runPromise(this.data.listScheduleOccurrences(filter));
5380
+ return [...this.memoryOccurrences.values()].filter((item) => matchesOccurrenceFilter(item, filter)).sort(compareOccurrences).map((item) => structuredClone(item));
5381
+ }
5382
+ durableOccurrences() {
5383
+ return Boolean(this.data.claimScheduleOccurrence && this.data.putScheduleOccurrence && this.data.getScheduleOccurrence && this.data.listScheduleOccurrences);
5384
+ }
5385
+ async claimOccurrence(occurrence) {
5386
+ if (this.durableOccurrences()) return Effect5.runPromise(this.data.claimScheduleOccurrence(occurrence));
5387
+ if (this.memoryOccurrences.has(occurrence.id)) return false;
5388
+ this.memoryOccurrences.set(occurrence.id, structuredClone(occurrence));
5389
+ return true;
5390
+ }
5391
+ async putOccurrence(occurrence) {
5392
+ if (this.durableOccurrences()) return Effect5.runPromise(this.data.putScheduleOccurrence(occurrence));
5393
+ this.memoryOccurrences.set(occurrence.id, structuredClone(occurrence));
5394
+ for (const id2 of prunableOccurrences(this.memoryOccurrences.values(), occurrence.activationId)) this.memoryOccurrences.delete(id2);
5395
+ }
5396
+ async getOccurrence(id2) {
5397
+ if (this.durableOccurrences()) return Effect5.runPromise(this.data.getScheduleOccurrence(id2));
5398
+ const occurrence = this.memoryOccurrences.get(id2);
5399
+ return occurrence ? structuredClone(occurrence) : null;
5400
+ }
5360
5401
  async materializeActivation(activation) {
5361
5402
  if (this.materializedActivations.has(activation.id)) return;
5362
5403
  this.materializedActivations.add(activation.id);
@@ -5384,141 +5425,270 @@ var FoundryRuntime = class _FoundryRuntime {
5384
5425
  if (activation.timing.kind === "at" && Number.isNaN(new Date(activation.timing.at).getTime())) {
5385
5426
  throw new Error(`Activation "${activation.id}" has an invalid wake time.`);
5386
5427
  }
5387
- const request = {
5388
- agentId: activation.agentId,
5389
- conversationId: activation.conversationId,
5390
- workspaceId: activation.workspaceId,
5391
- message: activation.message,
5392
- ...activation.payload !== void 0 ? { payload: activation.payload } : {},
5393
- source: { kind: "activation", id: activation.id }
5428
+ const revision = activationScheduleRevision(activation);
5429
+ const now = /* @__PURE__ */ new Date();
5430
+ const resumes = activation.scheduleRevision === revision;
5431
+ const cursor = resumes ? activation.nextOccurrenceAt : firstScheduledTime(activation.timing, now).toISOString();
5432
+ const { nextOccurrenceAt: _previous, ...rest } = activation;
5433
+ const active = {
5434
+ ...rest,
5435
+ status: "active",
5436
+ ...activation.timing.kind === "at" && !resumes ? { lastRunId: void 0 } : {},
5437
+ scheduleRevision: revision,
5438
+ ...cursor ? { nextOccurrenceAt: cursor } : {},
5439
+ updatedAt: now.toISOString()
5394
5440
  };
5395
- if (activation.timing.kind === "every" || activation.timing.kind === "cron") {
5396
- const now = /* @__PURE__ */ new Date();
5397
- const schedule = {
5398
- id: this.backendScheduleId(activation.id),
5399
- kind: "signal",
5400
- target: discovered.executionName,
5401
- ...activation.timing.kind === "every" ? { interval: `${activation.timing.intervalMs}ms` } : { cron: activation.timing.expression, timezone: activation.timing.timezone },
5402
- // Station checks overlap per signal, and a signal is a whole
5403
- // definition: "skip" would drop one agent's run because another
5404
- // agent of the same definition is busy. Runs overlap like messages
5405
- // do, and the conversation gate still runs one at a time per conversation.
5406
- overlapPolicy: "allow",
5407
- misfirePolicy: "fire-once",
5408
- misfireGraceMs: 6e4,
5409
- input: await this.executionEnvelope(request),
5410
- enabled: true,
5411
- nextRunAt: activation.timing.kind === "every" ? new Date(now.getTime() + activation.timing.intervalMs) : nextCronOccurrence(
5412
- activation.timing.expression,
5413
- activation.timing.timezone,
5414
- now
5415
- ),
5416
- createdAt: now,
5417
- updatedAt: now,
5418
- createdBy: `core:${activation.createdByRunId}`
5419
- };
5420
- await this.scheduleAdapter.add(schedule);
5421
- await Effect5.runPromise(this.data.putActivation({
5422
- ...activation,
5423
- status: "active",
5424
- updatedAt: now.toISOString()
5425
- }));
5426
- this.observability.append({
5427
- type: "scheduled-action.created",
5428
- category: "activation",
5429
- agent: activation.definitionId,
5430
- runId: activation.createdByRunId,
5431
- data: { commandId: activation.id, recurring: true, nextRunAt: schedule.nextRunAt }
5432
- });
5441
+ if (!cursor) {
5442
+ await this.settleFiredOneShot(active);
5433
5443
  return;
5434
5444
  }
5435
- await this.armOneShotActivation(activation, request);
5445
+ await Effect5.runPromise(this.data.putActivation(active));
5446
+ this.observability.append({
5447
+ type: "scheduled-action.created",
5448
+ category: "activation",
5449
+ agent: activation.definitionId,
5450
+ runId: activation.createdByRunId,
5451
+ data: { commandId: activation.id, recurring: activation.timing.kind !== "at", nextRunAt: cursor }
5452
+ });
5453
+ this.armActivation(active);
5436
5454
  } catch (cause) {
5437
5455
  this.materializedActivations.delete(activation.id);
5438
5456
  throw cause;
5439
5457
  }
5440
5458
  }
5441
- async armOneShotActivation(activation, request) {
5442
- if (activation.timing.kind !== "at") {
5443
- throw new Error(`Activation "${activation.id}" is not a one-shot activation.`);
5444
- }
5445
- const target = new Date(activation.timing.at).getTime();
5446
- const active = {
5459
+ /** A one-shot that fired before a restart: finish it if its occurrence has settled. */
5460
+ async settleFiredOneShot(activation) {
5461
+ const occurrences = (await this.listScheduleOccurrences({ activationId: activation.id })).filter((item) => item.revision === activation.scheduleRevision);
5462
+ const latest = occurrences.at(-1);
5463
+ if (latest && !TERMINAL_OCCURRENCE_STATUSES.has(latest.status)) return;
5464
+ await Effect5.runPromise(this.data.putActivation({
5447
5465
  ...activation,
5448
- status: "active",
5449
- lastRunId: void 0,
5450
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5451
- };
5452
- await Effect5.runPromise(this.data.putActivation(active));
5466
+ status: latest && latest.status !== "cancelled" && latest.status !== "skipped" ? "completed" : "cancelled"
5467
+ }));
5468
+ }
5469
+ /** Wait for the activation's cursor, then fire; repeat while it has one. */
5470
+ armActivation(activation) {
5471
+ const id2 = activation.id;
5472
+ const revision = activation.scheduleRevision;
5473
+ let dueAt = activation.nextOccurrenceAt;
5474
+ let failures = 0;
5453
5475
  const generation = {};
5454
- this.activationDispatches.set(activation.id, generation);
5455
- const dispatch = () => this.withActivationTransition(async () => {
5456
- if (this.activationDispatches.get(activation.id) !== generation) return;
5457
- this.activationDispatches.delete(activation.id);
5458
- this.activationTimers.delete(activation.id);
5459
- if (this.disposed || !this.started) return;
5460
- const current = await Effect5.runPromise(this.data.getActivation(activation.id));
5461
- if (!current || current.status === "paused" || current.status === "cancelled" || current.status === "completed") return;
5462
- const runId = await this.enqueueCoreRequest(activation.definitionId, request);
5463
- const running = {
5464
- ...current,
5465
- status: "active",
5466
- lastRunId: runId,
5467
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5476
+ this.activationDispatches.set(id2, generation);
5477
+ const arm = () => {
5478
+ if (this.activationDispatches.get(id2) !== generation || !dueAt || this.stopping || this.disposed) {
5479
+ if (this.activationDispatches.get(id2) === generation) this.activationDispatches.delete(id2);
5480
+ return;
5481
+ }
5482
+ const remaining = Date.parse(dueAt) - Date.now();
5483
+ if (remaining > 0) {
5484
+ this.activationTimers.set(id2, setTimeout(arm, Math.min(remaining, 2147483647)));
5485
+ return;
5486
+ }
5487
+ this.activationTimers.delete(id2);
5488
+ void this.fireActivation(id2, revision, generation).then((next) => {
5489
+ failures = 0;
5490
+ dueAt = next;
5491
+ arm();
5492
+ }, (cause) => {
5493
+ failures++;
5494
+ this.observability.append({
5495
+ type: "activation.dispatch.error",
5496
+ category: "activation",
5497
+ agent: activation.definitionId,
5498
+ runId: activation.createdByRunId,
5499
+ data: { activationId: id2, error: cause instanceof Error ? cause.message : String(cause) }
5500
+ });
5501
+ if (this.activationDispatches.get(id2) !== generation) return;
5502
+ this.activationTimers.set(id2, setTimeout(arm, Math.min(1e3 * 2 ** Math.min(failures - 1, 8), 3e5)));
5503
+ });
5504
+ };
5505
+ arm();
5506
+ }
5507
+ /**
5508
+ * Take the occurrence at the activation's cursor: store it, then move the
5509
+ * cursor past it, then hand it to a run. Returns the new cursor.
5510
+ */
5511
+ fireActivation(id2, revision, generation) {
5512
+ return this.withActivationTransition(async () => {
5513
+ if (this.activationDispatches.get(id2) !== generation || this.stopping || this.disposed) return void 0;
5514
+ const current = await Effect5.runPromise(this.data.getActivation(id2));
5515
+ if (!current || current.status !== "active" || current.scheduleRevision !== revision || !current.nextOccurrenceAt) {
5516
+ return void 0;
5517
+ }
5518
+ const scheduledFor = new Date(current.nextOccurrenceAt);
5519
+ const now = /* @__PURE__ */ new Date();
5520
+ const plan = planScheduleOccurrence(current.timing, scheduledFor, now);
5521
+ const occurrence = this.newOccurrence(current, scheduledFor, plan, now);
5522
+ const fresh = await this.claimOccurrence(occurrence);
5523
+ const { nextOccurrenceAt: _fired, ...rest } = current;
5524
+ const advanced = {
5525
+ ...rest,
5526
+ ...plan.next ? { nextOccurrenceAt: plan.next.toISOString() } : {},
5527
+ updatedAt: now.toISOString()
5468
5528
  };
5469
- await Effect5.runPromise(this.data.putActivation(running));
5529
+ await Effect5.runPromise(this.data.putActivation(advanced));
5530
+ const stored = fresh ? occurrence : await this.getOccurrence(occurrence.id);
5531
+ if (stored?.status === "pending" || stored?.status === "accepted" && !fresh) {
5532
+ await this.deliverOccurrence(stored, advanced);
5533
+ } else if (stored?.status === "skipped" && fresh) {
5534
+ this.observability.append({
5535
+ type: "scheduled-action.skipped",
5536
+ category: "activation",
5537
+ agent: current.definitionId,
5538
+ runId: current.createdByRunId,
5539
+ data: { activationId: id2, occurrenceId: stored.id, scheduledFor: stored.scheduledFor, reason: stored.reason }
5540
+ });
5541
+ } else if (stored && TERMINAL_OCCURRENCE_STATUSES.has(stored.status) && !plan.next) {
5542
+ await this.settleFiredOneShot(advanced);
5543
+ }
5544
+ return plan.next?.toISOString();
5545
+ });
5546
+ }
5547
+ newOccurrence(activation, scheduledFor, plan, now) {
5548
+ const at = scheduledFor.toISOString();
5549
+ const timestamp = now.toISOString();
5550
+ const id2 = scheduleOccurrenceId(activation.id, activation.scheduleRevision, at);
5551
+ return {
5552
+ id: id2,
5553
+ activationId: activation.id,
5554
+ revision: activation.scheduleRevision,
5555
+ scheduledFor: at,
5556
+ definitionId: activation.definitionId,
5557
+ agentId: activation.agentId,
5558
+ conversationId: activation.conversationId,
5559
+ workspaceId: activation.workspaceId,
5560
+ request: {
5561
+ agentId: activation.agentId,
5562
+ conversationId: activation.conversationId,
5563
+ workspaceId: activation.workspaceId,
5564
+ message: activation.message,
5565
+ ...activation.payload !== void 0 ? { payload: activation.payload } : {},
5566
+ source: { kind: "activation", id: activation.id, occurrenceId: id2, scheduledFor: at }
5567
+ },
5568
+ status: plan.deliver ? "pending" : "skipped",
5569
+ ...plan.deliver ? {} : { reason: "misfire", settledAt: timestamp },
5570
+ attempts: 0,
5571
+ ...plan.coalesced ? { coalesced: plan.coalesced } : {},
5572
+ createdAt: timestamp,
5573
+ updatedAt: timestamp
5574
+ };
5575
+ }
5576
+ /**
5577
+ * Hand an occurrence to its conversation. Runs under the activation lock,
5578
+ * so a pause or cancel never sees it half handed over.
5579
+ */
5580
+ async deliverOccurrence(occurrence, activation) {
5581
+ if (this.occurrencesInHand.has(occurrence.id)) return;
5582
+ this.occurrencesInHand.add(occurrence.id);
5583
+ try {
5584
+ const agent = await Effect5.runPromise(this.data.getAgent(occurrence.agentId));
5585
+ let inactive = !agent;
5586
+ if (agent?.durableSubagent) {
5587
+ try {
5588
+ await this.assertDurableActive(agent);
5589
+ } catch {
5590
+ inactive = true;
5591
+ }
5592
+ }
5593
+ if (inactive) {
5594
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
5595
+ await this.putOccurrence({ ...occurrence, status: "cancelled", reason: "agent-inactive", updatedAt: now2, settledAt: now2 });
5596
+ this.occurrencesInHand.delete(occurrence.id);
5597
+ return;
5598
+ }
5599
+ const runId = await this.enqueueCoreRequest(occurrence.definitionId, occurrence.request);
5600
+ this.occurrenceRuns.set(runId, occurrence.id);
5601
+ const latest = await this.getOccurrence(occurrence.id) ?? occurrence;
5602
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5603
+ await this.putOccurrence({
5604
+ ...latest,
5605
+ status: "accepted",
5606
+ runId,
5607
+ runIds: [...latest.runIds ?? [], runId],
5608
+ attempts: latest.attempts + 1,
5609
+ acceptedAt: now,
5610
+ updatedAt: now
5611
+ });
5612
+ const current = await Effect5.runPromise(this.data.getActivation(activation.id));
5613
+ if (current && current.status !== "cancelled" && current.status !== "completed") {
5614
+ await Effect5.runPromise(this.data.putActivation({ ...current, lastRunId: runId, updatedAt: now }));
5615
+ }
5470
5616
  this.observability.append({
5471
5617
  type: "core.command.accepted",
5472
5618
  category: "system",
5473
- agent: activation.definitionId,
5619
+ agent: occurrence.definitionId,
5474
5620
  runId: activation.createdByRunId,
5475
- data: { commandId: activation.id, childRunId: runId, type: activation.kind }
5621
+ data: {
5622
+ commandId: activation.id,
5623
+ childRunId: runId,
5624
+ type: activation.kind,
5625
+ occurrenceId: occurrence.id,
5626
+ scheduledFor: occurrence.scheduledFor,
5627
+ attempt: latest.attempts + 1
5628
+ }
5629
+ });
5630
+ const settled = this.recentlySettledRuns.get(runId);
5631
+ if (settled) await this.settleOccurrence(runId, settled, { locked: true });
5632
+ } catch (cause) {
5633
+ this.occurrencesInHand.delete(occurrence.id);
5634
+ throw cause;
5635
+ }
5636
+ }
5637
+ /** The run handling an occurrence settled. A run stopped by shutdown did not: the next start delivers it again. */
5638
+ async settleOccurrence(runId, status, options = {}) {
5639
+ const occurrenceId = this.occurrenceRuns.get(runId);
5640
+ if (!occurrenceId || this.stopping) return;
5641
+ const work = async () => {
5642
+ const occurrence = await this.getOccurrence(occurrenceId);
5643
+ this.occurrenceRuns.delete(runId);
5644
+ if (!occurrence || occurrence.runId !== runId || TERMINAL_OCCURRENCE_STATUSES.has(occurrence.status)) return;
5645
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5646
+ await this.putOccurrence({
5647
+ ...occurrence,
5648
+ status,
5649
+ ...status === "cancelled" ? { reason: "run-cancelled" } : {},
5650
+ updatedAt: now,
5651
+ settledAt: now
5476
5652
  });
5477
- void this.waitForRun(runId).then((run) => this.withActivationTransition(async () => {
5478
- if (!run || run.status !== "completed" && run.status !== "failed" && run.status !== "cancelled") return;
5479
- const latest = await Effect5.runPromise(this.data.getActivation(activation.id));
5480
- if (!latest || latest.status !== "active" || latest.lastRunId !== runId) return;
5653
+ this.occurrencesInHand.delete(occurrenceId);
5654
+ const activation = await Effect5.runPromise(this.data.getActivation(occurrence.activationId));
5655
+ if (activation?.timing.kind === "at" && activation.status === "active" && activation.scheduleRevision === occurrence.revision && activation.lastRunId === runId) {
5481
5656
  await Effect5.runPromise(this.data.putActivation({
5482
- ...latest,
5483
- status: run.status === "cancelled" ? "cancelled" : "completed",
5484
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5657
+ ...activation,
5658
+ status: status === "cancelled" ? "cancelled" : "completed",
5659
+ updatedAt: now
5485
5660
  }));
5486
- })).catch((cause) => {
5661
+ }
5662
+ };
5663
+ await (options.locked ? work() : this.withActivationTransition(work));
5664
+ }
5665
+ /**
5666
+ * After a restart: hand over every occurrence a previous process claimed
5667
+ * and no run finished, unless its activation has since been paused,
5668
+ * cancelled or changed.
5669
+ */
5670
+ async replayScheduleOccurrences() {
5671
+ for (const occurrence of await this.listScheduleOccurrences({ status: ["pending", "accepted"] })) {
5672
+ if (this.occurrencesInHand.has(occurrence.id)) continue;
5673
+ if (occurrence.runId && await this.signalRunner.getRun(occurrence.runId)) continue;
5674
+ const activation = await Effect5.runPromise(this.data.getActivation(occurrence.activationId));
5675
+ const reason = !activation || activation.status === "cancelled" || activation.status === "completed" ? "cancelled" : activation.status === "paused" ? "paused" : activationScheduleRevision(activation) !== occurrence.revision ? "superseded" : void 0;
5676
+ if (reason) {
5677
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5678
+ await this.putOccurrence({ ...occurrence, status: "cancelled", reason, updatedAt: now, settledAt: now });
5679
+ continue;
5680
+ }
5681
+ try {
5682
+ await this.deliverOccurrence(occurrence, activation);
5683
+ } catch (cause) {
5487
5684
  this.observability.append({
5488
- type: "activation.persistence.error",
5685
+ type: "activation.dispatch.error",
5489
5686
  category: "activation",
5490
- agent: activation.definitionId,
5491
- runId,
5492
- data: { error: cause instanceof Error ? cause.message : String(cause) }
5687
+ agent: occurrence.definitionId,
5688
+ data: { activationId: occurrence.activationId, occurrenceId: occurrence.id, error: cause instanceof Error ? cause.message : String(cause) }
5493
5689
  });
5494
- });
5495
- });
5496
- const arm = () => {
5497
- const remaining = target - Date.now();
5498
- if (remaining <= 0) {
5499
- void dispatch().catch((cause) => {
5500
- this.materializedActivations.delete(activation.id);
5501
- this.observability.append({
5502
- type: "activation.dispatch.error",
5503
- category: "activation",
5504
- agent: activation.definitionId,
5505
- runId: activation.createdByRunId,
5506
- data: { error: cause instanceof Error ? cause.message : String(cause) }
5507
- });
5508
- });
5509
- return;
5510
5690
  }
5511
- const timer = setTimeout(arm, Math.min(remaining, 2147483647));
5512
- this.activationTimers.set(activation.id, timer);
5513
- };
5514
- this.observability.append({
5515
- type: "scheduled-action.created",
5516
- category: "activation",
5517
- agent: activation.definitionId,
5518
- runId: activation.createdByRunId,
5519
- data: { commandId: activation.id, recurring: false, nextRunAt: activation.timing.at }
5520
- });
5521
- arm();
5691
+ }
5522
5692
  }
5523
5693
  async deliverOutbound(command, parentRunId, signal) {
5524
5694
  return this.dispatchOutbound({
@@ -8499,6 +8669,20 @@ var FoundryServer = class {
8499
8669
  );
8500
8670
  return;
8501
8671
  }
8672
+ if (url.pathname === "/api/schedule-occurrences" && method === "GET") {
8673
+ const status = url.searchParams.getAll("status").filter(Boolean);
8674
+ json(
8675
+ response,
8676
+ 200,
8677
+ await this.runtime.listScheduleOccurrences({
8678
+ ...url.searchParams.get("activation") ? { activationId: url.searchParams.get("activation") } : {},
8679
+ ...url.searchParams.get("workspace") ? { workspaceId: url.searchParams.get("workspace") } : {},
8680
+ ...url.searchParams.get("agent") ? { agentId: url.searchParams.get("agent") } : {},
8681
+ ...status.length ? { status } : {}
8682
+ })
8683
+ );
8684
+ return;
8685
+ }
8502
8686
  if (url.pathname === "/api/activations" && method === "GET") {
8503
8687
  json(
8504
8688
  response,