glove-foundry 0.8.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,
@@ -727,6 +735,7 @@ var MemoryObservabilityAdapter = class {
727
735
  function categoryForAgentEvent(type) {
728
736
  if (type === "foundry.guidance.state") return "memory";
729
737
  if (type.startsWith("tool_")) return "tool";
738
+ if (type.startsWith("turn_")) return "run";
730
739
  if (type.startsWith("foundry.installation")) return "application";
731
740
  if (type.startsWith("foundry.layer") || type.startsWith("foundry.subscriber")) {
732
741
  return "extension";
@@ -1089,11 +1098,6 @@ ${error.stderrTail}
1089
1098
  getAdapter() {
1090
1099
  return { ping: () => this.ping() };
1091
1100
  }
1092
- schedules = {
1093
- add: (schedule) => this.request({ method: "schedule.add", schedule }),
1094
- delete: (id2) => this.request({ method: "schedule.delete", id: id2 }),
1095
- ping: () => this.ping()
1096
- };
1097
1101
  async waitForRun(id2, options = {}) {
1098
1102
  const deadline = Date.now() + (options.timeoutMs ?? 6e4);
1099
1103
  do {
@@ -1105,11 +1109,6 @@ ${error.stderrTail}
1105
1109
  }
1106
1110
  };
1107
1111
 
1108
- // src/runtime.ts
1109
- import {
1110
- nextCronOccurrence
1111
- } from "station-schedules";
1112
-
1113
1112
  // src/conversation-gate.ts
1114
1113
  var ConversationGate = class {
1115
1114
  constructor(hooks) {
@@ -1731,7 +1730,6 @@ var FoundryRuntime = class _FoundryRuntime {
1731
1730
  execution;
1732
1731
  observer;
1733
1732
  signalRunner;
1734
- scheduleAdapter;
1735
1733
  services;
1736
1734
  runnerLoops = [];
1737
1735
  materializedActivations = /* @__PURE__ */ new Set();
@@ -1739,6 +1737,14 @@ var FoundryRuntime = class _FoundryRuntime {
1739
1737
  activationTransitions = Effect5.unsafeMakeSemaphore(1);
1740
1738
  activationDispatches = /* @__PURE__ */ new Map();
1741
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();
1742
1748
  /** Whether each run's child process still holds its conversation, from FOUNDRY_RUN_PROCESS_EVENT. */
1743
1749
  runProcesses = /* @__PURE__ */ new Map();
1744
1750
  approvalDirectory = join2(
@@ -1968,7 +1974,6 @@ var FoundryRuntime = class _FoundryRuntime {
1968
1974
  ...options.config?.observability?.modelRequests === false ? { [FOUNDRY_MODEL_REQUESTS_ENV]: "off" } : {}
1969
1975
  }
1970
1976
  });
1971
- this.scheduleAdapter = this.signalRunner.schedules;
1972
1977
  const topologyLayer = memoryTopologyStore;
1973
1978
  const defaultServices = Layer3.mergeAll(
1974
1979
  memoryAccountDirectory(this.application.accounts ?? []),
@@ -2291,7 +2296,7 @@ var FoundryRuntime = class _FoundryRuntime {
2291
2296
  await this.withActivationTransition(async () => {
2292
2297
  for (const activation of await Effect5.runPromise(this.data.listActivations(current.workspaceId))) {
2293
2298
  if (activation.agentId !== current.id || ["cancelled", "completed"].includes(activation.status)) continue;
2294
- await this.disarmActivation(activation);
2299
+ await this.disarmActivation(activation, "paused");
2295
2300
  await Effect5.runPromise(this.data.putActivation({ ...activation, status: "paused", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }));
2296
2301
  }
2297
2302
  });
@@ -3387,7 +3392,7 @@ var FoundryRuntime = class _FoundryRuntime {
3387
3392
  const [execution, environment, activations] = await Promise.all([
3388
3393
  this.signalRunner.getAdapter().ping(),
3389
3394
  this.signalRunner.ping(),
3390
- this.scheduleAdapter.ping()
3395
+ this.signalRunner.ping()
3391
3396
  ]);
3392
3397
  return {
3393
3398
  ok: execution && environment && activations,
@@ -4833,6 +4838,17 @@ var FoundryRuntime = class _FoundryRuntime {
4833
4838
  }
4834
4839
  async handleRunSettled(event) {
4835
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
+ });
4836
4852
  this.releaseConversationRun(event.run.id);
4837
4853
  void this.waitForRunProcessRelease(this.toFoundryRun(event.run), event.route).finally(() => this.gate.settled(event.run.id));
4838
4854
  const finishDelivery = async () => {
@@ -5190,21 +5206,20 @@ var FoundryRuntime = class _FoundryRuntime {
5190
5206
  throw new Error(`Scheduled activation "${activation.id}" is not owned by this agent instance.`);
5191
5207
  }
5192
5208
  }
5193
- backendScheduleId(activationId) {
5194
- return `activation/${activationId.replaceAll("_", "-")}`;
5195
- }
5196
- async disarmActivation(activation) {
5209
+ async disarmActivation(activation, reason) {
5197
5210
  this.activationDispatches.delete(activation.id);
5198
5211
  const timer = this.activationTimers.get(activation.id);
5199
5212
  if (timer) {
5200
5213
  clearTimeout(timer);
5201
5214
  this.activationTimers.delete(activation.id);
5202
5215
  }
5203
- if (activation.timing.kind === "every" || activation.timing.kind === "cron") {
5204
- await this.scheduleAdapter.delete(this.backendScheduleId(activation.id));
5205
- } else if (activation.lastRunId) {
5216
+ if (activation.timing.kind === "at" && activation.lastRunId) {
5206
5217
  await this.signalRunner.cancel(activation.lastRunId);
5207
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
+ }
5208
5223
  this.materializedActivations.delete(activation.id);
5209
5224
  }
5210
5225
  async syncDefinitionSchedules(command, parentRunId) {
@@ -5213,7 +5228,7 @@ var FoundryRuntime = class _FoundryRuntime {
5213
5228
  );
5214
5229
  const desiredIds = new Set(command.schedules.map((item) => item.id));
5215
5230
  for (const stale of current.filter((item) => !desiredIds.has(item.id))) {
5216
- await this.disarmActivation(stale);
5231
+ await this.disarmActivation(stale, "cancelled");
5217
5232
  await Effect5.runPromise(this.data.putActivation({
5218
5233
  ...stale,
5219
5234
  status: "cancelled",
@@ -5225,7 +5240,7 @@ var FoundryRuntime = class _FoundryRuntime {
5225
5240
  if (existing) this.assertActivationOwnership(existing, command);
5226
5241
  if (!desired.enabled) {
5227
5242
  if (existing && existing.status !== "cancelled") {
5228
- await this.disarmActivation(existing);
5243
+ await this.disarmActivation(existing, "cancelled");
5229
5244
  await Effect5.runPromise(this.data.putActivation({
5230
5245
  ...existing,
5231
5246
  status: "cancelled",
@@ -5236,7 +5251,7 @@ var FoundryRuntime = class _FoundryRuntime {
5236
5251
  }
5237
5252
  const unchanged = existing?.definitionRevision === desired.revision;
5238
5253
  if (unchanged || existing?.status === "cancelled") continue;
5239
- if (existing) await this.disarmActivation(existing);
5254
+ if (existing) await this.disarmActivation(existing, "superseded");
5240
5255
  const now = (/* @__PURE__ */ new Date()).toISOString();
5241
5256
  const activation = {
5242
5257
  id: desired.id,
@@ -5264,9 +5279,10 @@ var FoundryRuntime = class _FoundryRuntime {
5264
5279
  const existing = await Effect5.runPromise(this.data.getActivation(command.activationId));
5265
5280
  if (!existing) throw new Error(`Scheduled activation "${command.activationId}" was not found.`);
5266
5281
  this.assertActivationOwnership(existing, command);
5267
- await this.disarmActivation(existing);
5282
+ await this.disarmActivation(existing, "superseded");
5283
+ const { nextOccurrenceAt: _cursor, scheduleRevision: _revision, ...unarmed } = existing;
5268
5284
  const updated = {
5269
- ...existing,
5285
+ ...unarmed,
5270
5286
  ...command.patch,
5271
5287
  status: existing.status === "paused" ? "paused" : "pending",
5272
5288
  createdByRunId: parentRunId,
@@ -5291,7 +5307,7 @@ var FoundryRuntime = class _FoundryRuntime {
5291
5307
  throw new Error(`Scheduled activation "${command.activationId}" cannot be paused from status "${existing.status}".`);
5292
5308
  }
5293
5309
  if (existing.status !== "paused") {
5294
- await this.disarmActivation(existing);
5310
+ await this.disarmActivation(existing, "paused");
5295
5311
  await Effect5.runPromise(this.data.putActivation({
5296
5312
  ...existing,
5297
5313
  status: "paused",
@@ -5313,8 +5329,9 @@ var FoundryRuntime = class _FoundryRuntime {
5313
5329
  if (existing.status !== "paused") {
5314
5330
  throw new Error(`Scheduled activation "${command.activationId}" is not paused.`);
5315
5331
  }
5332
+ const { nextOccurrenceAt: _paused, scheduleRevision: _revision, ...unpaused } = existing;
5316
5333
  const resumed = {
5317
- ...existing,
5334
+ ...unpaused,
5318
5335
  status: "pending",
5319
5336
  createdByRunId: parentRunId,
5320
5337
  lastRunId: void 0,
@@ -5334,7 +5351,7 @@ var FoundryRuntime = class _FoundryRuntime {
5334
5351
  const existing = await Effect5.runPromise(this.data.getActivation(command.activationId));
5335
5352
  if (!existing) throw new Error(`Scheduled activation "${command.activationId}" was not found.`);
5336
5353
  this.assertActivationOwnership(existing, command);
5337
- await this.disarmActivation(existing);
5354
+ await this.disarmActivation(existing, "cancelled");
5338
5355
  await Effect5.runPromise(this.data.putActivation({
5339
5356
  ...existing,
5340
5357
  status: "cancelled",
@@ -5350,12 +5367,37 @@ var FoundryRuntime = class _FoundryRuntime {
5350
5367
  }
5351
5368
  reconstructActivations() {
5352
5369
  return this.withActivationTransition(async () => {
5370
+ await this.replayScheduleOccurrences();
5353
5371
  for (const activation of await Effect5.runPromise(this.data.listActivations())) {
5354
5372
  if (activation.status === "paused" || activation.status === "completed" || activation.status === "cancelled") continue;
5355
5373
  await this.materializeActivation(activation);
5356
5374
  }
5357
5375
  });
5358
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
+ }
5359
5401
  async materializeActivation(activation) {
5360
5402
  if (this.materializedActivations.has(activation.id)) return;
5361
5403
  this.materializedActivations.add(activation.id);
@@ -5383,141 +5425,270 @@ var FoundryRuntime = class _FoundryRuntime {
5383
5425
  if (activation.timing.kind === "at" && Number.isNaN(new Date(activation.timing.at).getTime())) {
5384
5426
  throw new Error(`Activation "${activation.id}" has an invalid wake time.`);
5385
5427
  }
5386
- const request = {
5387
- agentId: activation.agentId,
5388
- conversationId: activation.conversationId,
5389
- workspaceId: activation.workspaceId,
5390
- message: activation.message,
5391
- ...activation.payload !== void 0 ? { payload: activation.payload } : {},
5392
- 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()
5393
5440
  };
5394
- if (activation.timing.kind === "every" || activation.timing.kind === "cron") {
5395
- const now = /* @__PURE__ */ new Date();
5396
- const schedule = {
5397
- id: this.backendScheduleId(activation.id),
5398
- kind: "signal",
5399
- target: discovered.executionName,
5400
- ...activation.timing.kind === "every" ? { interval: `${activation.timing.intervalMs}ms` } : { cron: activation.timing.expression, timezone: activation.timing.timezone },
5401
- // Station checks overlap per signal, and a signal is a whole
5402
- // definition: "skip" would drop one agent's run because another
5403
- // agent of the same definition is busy. Runs overlap like messages
5404
- // do, and the conversation gate still runs one at a time per conversation.
5405
- overlapPolicy: "allow",
5406
- misfirePolicy: "fire-once",
5407
- misfireGraceMs: 6e4,
5408
- input: await this.executionEnvelope(request),
5409
- enabled: true,
5410
- nextRunAt: activation.timing.kind === "every" ? new Date(now.getTime() + activation.timing.intervalMs) : nextCronOccurrence(
5411
- activation.timing.expression,
5412
- activation.timing.timezone,
5413
- now
5414
- ),
5415
- createdAt: now,
5416
- updatedAt: now,
5417
- createdBy: `core:${activation.createdByRunId}`
5418
- };
5419
- await this.scheduleAdapter.add(schedule);
5420
- await Effect5.runPromise(this.data.putActivation({
5421
- ...activation,
5422
- status: "active",
5423
- updatedAt: now.toISOString()
5424
- }));
5425
- this.observability.append({
5426
- type: "scheduled-action.created",
5427
- category: "activation",
5428
- agent: activation.definitionId,
5429
- runId: activation.createdByRunId,
5430
- data: { commandId: activation.id, recurring: true, nextRunAt: schedule.nextRunAt }
5431
- });
5441
+ if (!cursor) {
5442
+ await this.settleFiredOneShot(active);
5432
5443
  return;
5433
5444
  }
5434
- 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);
5435
5454
  } catch (cause) {
5436
5455
  this.materializedActivations.delete(activation.id);
5437
5456
  throw cause;
5438
5457
  }
5439
5458
  }
5440
- async armOneShotActivation(activation, request) {
5441
- if (activation.timing.kind !== "at") {
5442
- throw new Error(`Activation "${activation.id}" is not a one-shot activation.`);
5443
- }
5444
- const target = new Date(activation.timing.at).getTime();
5445
- 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({
5446
5465
  ...activation,
5447
- status: "active",
5448
- lastRunId: void 0,
5449
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5450
- };
5451
- 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;
5452
5475
  const generation = {};
5453
- this.activationDispatches.set(activation.id, generation);
5454
- const dispatch = () => this.withActivationTransition(async () => {
5455
- if (this.activationDispatches.get(activation.id) !== generation) return;
5456
- this.activationDispatches.delete(activation.id);
5457
- this.activationTimers.delete(activation.id);
5458
- if (this.disposed || !this.started) return;
5459
- const current = await Effect5.runPromise(this.data.getActivation(activation.id));
5460
- if (!current || current.status === "paused" || current.status === "cancelled" || current.status === "completed") return;
5461
- const runId = await this.enqueueCoreRequest(activation.definitionId, request);
5462
- const running = {
5463
- ...current,
5464
- status: "active",
5465
- lastRunId: runId,
5466
- 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()
5467
5528
  };
5468
- 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
+ }
5469
5616
  this.observability.append({
5470
5617
  type: "core.command.accepted",
5471
5618
  category: "system",
5472
- agent: activation.definitionId,
5619
+ agent: occurrence.definitionId,
5473
5620
  runId: activation.createdByRunId,
5474
- 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
5475
5652
  });
5476
- void this.waitForRun(runId).then((run) => this.withActivationTransition(async () => {
5477
- if (!run || run.status !== "completed" && run.status !== "failed" && run.status !== "cancelled") return;
5478
- const latest = await Effect5.runPromise(this.data.getActivation(activation.id));
5479
- 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) {
5480
5656
  await Effect5.runPromise(this.data.putActivation({
5481
- ...latest,
5482
- status: run.status === "cancelled" ? "cancelled" : "completed",
5483
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5657
+ ...activation,
5658
+ status: status === "cancelled" ? "cancelled" : "completed",
5659
+ updatedAt: now
5484
5660
  }));
5485
- })).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) {
5486
5684
  this.observability.append({
5487
- type: "activation.persistence.error",
5685
+ type: "activation.dispatch.error",
5488
5686
  category: "activation",
5489
- agent: activation.definitionId,
5490
- runId,
5491
- 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) }
5492
5689
  });
5493
- });
5494
- });
5495
- const arm = () => {
5496
- const remaining = target - Date.now();
5497
- if (remaining <= 0) {
5498
- void dispatch().catch((cause) => {
5499
- this.materializedActivations.delete(activation.id);
5500
- this.observability.append({
5501
- type: "activation.dispatch.error",
5502
- category: "activation",
5503
- agent: activation.definitionId,
5504
- runId: activation.createdByRunId,
5505
- data: { error: cause instanceof Error ? cause.message : String(cause) }
5506
- });
5507
- });
5508
- return;
5509
5690
  }
5510
- const timer = setTimeout(arm, Math.min(remaining, 2147483647));
5511
- this.activationTimers.set(activation.id, timer);
5512
- };
5513
- this.observability.append({
5514
- type: "scheduled-action.created",
5515
- category: "activation",
5516
- agent: activation.definitionId,
5517
- runId: activation.createdByRunId,
5518
- data: { commandId: activation.id, recurring: false, nextRunAt: activation.timing.at }
5519
- });
5520
- arm();
5691
+ }
5521
5692
  }
5522
5693
  async deliverOutbound(command, parentRunId, signal) {
5523
5694
  return this.dispatchOutbound({
@@ -5636,10 +5807,10 @@ function renderGloveMark() {
5636
5807
 
5637
5808
  // src/dashboard-run.ts
5638
5809
  var DASHBOARD_RUN_SCRIPT = String.raw`
5639
- const RUN_TABS=[["summary","Summary","overview"],["network","Network","network"],["console","Console","terminal"],["context","Context","context"]];
5810
+ const RUN_TABS=[["summary","Summary","overview"],["network","Network","network"],["console","Console","terminal"],["context","Context","context"],["composition","Composition","definitions"],["queues","Queues","integrations"],["chain","Call chain","agent"]];
5640
5811
  function runView(){
5641
5812
  const params=new URLSearchParams(location.search);const tab=params.get("tab");
5642
- return{tab:RUN_TABS.some(t=>t[0]===tab)?tab:"network",item:params.get("item")||"",pane:params.get("pane")||"",node:params.get("node")||"",request:params.get("request")||""};
5813
+ return{tab:RUN_TABS.some(t=>t[0]===tab)?tab:"network",item:params.get("item")||"",pane:params.get("pane")||"",node:params.get("node")||"",request:params.get("request")||"",cnode:params.get("cnode")||"",queue:params.get("queue")||""};
5643
5814
  }
5644
5815
  function setRunView(patch){
5645
5816
  const params=new URLSearchParams(location.search);
@@ -5734,23 +5905,66 @@ function netMatches(item,kind,term){
5734
5905
  const text=[item.name,item.model,item.fn,tracePreview(item.input,600),item.kind==="model"?(item.response||[]).map(message=>message.text).join(" "):tracePreview(item.result&&item.result.data,600)].join(" ").toLowerCase();
5735
5906
  return text.includes(term);
5736
5907
  }
5737
- function netRow(item,trace,selectedKey){
5908
+ /* Like DevTools' Timing tab: the phases of one row, in order. */
5909
+ function itemPhases(item){
5910
+ const phases=[];
5911
+ if(item.kind==="model"){
5912
+ if(Number.isFinite(item.ttftMs)){phases.push(["Waiting for the first token",item.ttftMs,"wait"]);phases.push(["Streaming the response",Math.max(0,item.durationMs-item.ttftMs),"run"])}
5913
+ else if(Number.isFinite(item.durationMs))phases.push(["Model request",item.durationMs,"run"]);
5914
+ }else if(item.kind==="tool"){
5915
+ if(item.queuedMs>0)phases.push(["Queued behind earlier calls",item.queuedMs,"queue"]);
5916
+ if(Number.isFinite(item.runMs)){phases.push([item.approval?"Waiting for approval":"Permission check and validation",Math.max(0,item.durationMs-item.runMs),"wait"]);phases.push(["Running",item.runMs,"run"])}
5917
+ else if(Number.isFinite(item.durationMs))phases.push(["Running",item.durationMs,"run"]);
5918
+ }else if(Number.isFinite(item.durationMs))phases.push(["Running",item.durationMs,"run"]);
5919
+ return phases;
5920
+ }
5921
+ function wfBar(item,trace){
5738
5922
  const span=Math.max(1,trace.end-trace.start);const pending=item.status==="pending";
5739
- const left=Number.isFinite(item.startAt)?Math.min(99.4,Math.max(0,(item.startAt-trace.start)/span*100)):0;
5740
- const width=Number.isFinite(item.durationMs)?Math.max(.6,item.durationMs/span*100):pending?100-left:.6;
5923
+ const pct=(ms)=>ms/span*100;
5924
+ const left=Number.isFinite(item.startAt)?Math.min(99.4,Math.max(0,pct(item.startAt-trace.start))):0;
5925
+ const width=Math.min(Number.isFinite(item.durationMs)?Math.max(.6,pct(item.durationMs)):pending?100-left:.6,100-left);
5926
+ const lead=item.queuedMs>0?Math.min(left,pct(item.queuedMs)):0;
5927
+ // The light part is waiting (first token, a permission check); the solid part is work.
5928
+ const waitMs=item.kind==="model"?item.ttftMs:item.kind==="tool"&&Number.isFinite(item.runMs)?item.durationMs-item.runMs:NaN;
5929
+ const wait=Number.isFinite(waitMs)&&Number.isFinite(item.durationMs)&&item.durationMs>0?Math.max(0,Math.min(100,waitMs/item.durationMs*100)):0;
5930
+ const tip=itemPhases(item).map(phase=>phase[0]+": "+durationText(phase[1])).join(" · ");
5931
+ return'<span class="wf-track" title="'+attr(tip)+'">'+(lead?'<span class="wf-queue" style="left:'+(left-lead).toFixed(2)+'%;width:'+lead.toFixed(2)+'%"></span>':"")
5932
+ +'<span class="wf-bar'+(pending?" pending":"")+'" style="left:'+left.toFixed(2)+'%;width:'+width.toFixed(2)+'%">'+(wait&&!pending?'<i class="wf-wait" style="width:'+wait.toFixed(1)+'%"></i>':"")+'</span></span>';
5933
+ }
5934
+ function turnLabel(turn){return"Turn "+turn.index+" · "+(turn.trigger==="events"?"events woke the agent":turn.trigger==="resume"?"resumed at its tool step":"request")}
5935
+ function turnRow(turn){
5936
+ const st={success:["ok","ok"],error:["err","failed"],aborted:["warn","aborted"],suspended:["warn","suspended"],pending:["live","running"]}[turn.status]||["",turn.status];
5937
+ return'<tr class="net-turn"><td colspan="7"><span>'+esc(turnLabel(turn))+'</span><span class="st '+st[0]+'">'+esc(st[1])+'</span><span class="muted mono">'+esc(Number.isFinite(turn.durationMs)?durationText(turn.durationMs):"")+'</span>'+(turn.error?'<span class="sum-msg">'+esc(tracePreview(turn.error,120))+'</span>':"")+'</td></tr>';
5938
+ }
5939
+ function netRow(item,trace,selectedKey){
5940
+ const pending=item.status==="pending";
5741
5941
  const failed=["error","aborted","denied","limit"].includes(item.status);
5742
- return'<tr class="net-row kind-'+attr(item.kind)+(item.purpose==="compaction"?" compaction":"")+(item.key===selectedKey?" selected":"")+(failed?" failed":"")+'" data-net-item="'+attr(item.key)+'">'
5942
+ return'<tr class="net-row kind-'+attr(item.kind)+(item.purpose==="compaction"?" compaction":"")+(item.key===selectedKey?" selected":"")+(failed?" failed":"")+(item.depth?" nested":"")+'" data-net-item="'+attr(item.key)+'"'+(item.depth?' style="--depth:'+Math.min(item.depth,6)+'"':"")+'>'
5743
5943
  +'<td class="c-name"><span class="net-name"><i class="net-glyph"></i><span><b>'+esc(item.name)+'</b><small>'+esc(itemSubtitle(item))+'</small></span></span></td>'
5744
5944
  +'<td class="c-type">'+esc(itemType(item))+'</td>'
5745
5945
  +'<td class="c-status">'+itemStatus(item)+'</td>'
5746
5946
  +'<td class="c-init">'+(item.initiator.key?'<button type="button" class="net-link" data-net-item="'+attr(item.initiator.key)+'">'+esc(item.initiator.label)+'</button>':'<span class="muted">'+esc(item.initiator.label)+'</span>')+'</td>'
5747
5947
  +'<td class="c-size">'+esc(itemSize(item))+'</td>'
5748
5948
  +'<td class="c-time">'+(pending?'<span class="st live">…</span>':esc(durationText(item.durationMs)))+'</td>'
5749
- +'<td class="c-wf"><span class="wf-track"><span class="wf-bar'+(pending?" pending":"")+'" style="left:'+left.toFixed(2)+'%;width:'+Math.min(width,100-left).toFixed(2)+'%"></span></span></td></tr>';
5949
+ +'<td class="c-wf">'+wfBar(item,trace)+'</td></tr>';
5950
+ }
5951
+ function modelPanes(item){return[["overview","Overview"],["prompt","Prompt"],["messages","Messages",item.messages.length],["context","Context",item.context.length],["tools","Tools",item.toolNames.length],["response","Response"],["timing","Timing"],["raw","Raw"]]}
5952
+ function toolPanes(){return[["overview","Overview"],["input","Input"],["result","Result"],["timing","Timing"],["raw","Raw"]]}
5953
+ function timingPane(item,run){
5954
+ const base=new Date(runStartedAt(run)).getTime();
5955
+ const phases=itemPhases(item);
5956
+ if(!phases.length)return'<p class="dt-note">'+(item.status==="pending"?"Still running.":"No timing recorded.")+'</p>';
5957
+ const total=phases.reduce((sum,phase)=>sum+phase[1],0)||1;
5958
+ const notes={"Waiting for the first token":"From sending the request to the first streamed text or tool call.","Streaming the response":"From the first token to the end of the response.","Queued behind earlier calls":"The model asked for this call; the calls before it in the same step ran first.","Permission check and validation":"Checking whether the call may run, then validating its input.","Waiting for approval":"A person had to decide before the call could run.","Running":"The tool itself."};
5959
+ return kv([
5960
+ Number.isFinite(item.askedAt)&&item.kind==="tool"?["Asked for",esc(offsetFrom(base,isoAt(item.askedAt)))]:null,
5961
+ Number.isFinite(item.startAt)?["Started",esc(offsetFrom(base,isoAt(item.startAt)))]:null,
5962
+ Number.isFinite(item.endAt)?["Finished",esc(offsetFrom(base,isoAt(item.endAt)))]:null,
5963
+ ])+'<div class="timing">'+phases.map((phase,index)=>{const left=phases.slice(0,index).reduce((sum,prior)=>sum+prior[1],0)/total*100;return'<div class="timing-row"><span class="timing-name">'+esc(phase[0])+'<small>'+esc(notes[phase[0]]||"")+'</small></span><span class="timing-track"><i class="timing-bar '+attr(phase[2])+'" style="left:'+Math.min(99,left).toFixed(1)+'%;width:'+Math.max(.8,phase[1]/total*100).toFixed(1)+'%"></i></span><span class="mono">'+esc(durationText(phase[1]))+'</span></div>'}).join("")
5964
+ +'<div class="timing-row total"><span class="timing-name">Total</span><span></span><span class="mono">'+esc(durationText(total))+'</span></div></div>'
5965
+ +(item.kind==="model"&&item.streamed?'<div class="dt-section">Streamed text</div><pre class="dt-pre">'+esc(item.streamed)+'</pre>':"");
5750
5966
  }
5751
- function modelPanes(item){return[["overview","Overview"],["prompt","Prompt"],["messages","Messages",item.messages.length],["context","Context",item.context.length],["tools","Tools",item.toolNames.length],["response","Response"],["raw","Raw"]]}
5752
- function toolPanes(){return[["overview","Overview"],["input","Input"],["result","Result"],["raw","Raw"]]}
5753
- function detailPanes(item){return item.kind==="model"?modelPanes(item):item.kind==="tool"?toolPanes():[["overview","Overview"],["raw","Raw"]]}
5967
+ function detailPanes(item){return item.kind==="model"?modelPanes(item):item.kind==="tool"?toolPanes():[["overview","Overview"],["timing","Timing"],["raw","Raw"]]}
5754
5968
  function kv(rows){return'<dl class="dt-kv">'+rows.filter(Boolean).map(row=>'<dt>'+esc(row[0])+'</dt><dd>'+row[1]+'</dd>').join("")+'</dl>'}
5755
5969
  function itemLink(key,label){return'<button type="button" class="net-link" data-net-item="'+attr(key)+'">'+esc(label)+'</button>'}
5756
5970
  function requestJson(item){return jsonText({model:item.model,system:item.systemPrompt??null,messages:item.messages,context:item.context,tools:item.tools||item.toolNames})}
@@ -5780,13 +5994,14 @@ function modelDetail(item,trace,run,pane){
5780
5994
  +(item.response||[]).map((message,index)=>traceMessageHtml(message,item.key+":r"+index,false)).join("");
5781
5995
  }
5782
5996
  if(pane==="raw")return'<div class="dt-bar"><span>'+count(item.events.length,"event")+'</span>'+copyButton(jsonText(item.events),"raw events")+'</div>'+jsonBlock(item.events.map(event=>({type:event.type,timestamp:event.timestamp,data:event.data})),item.key+":raw");
5997
+ if(pane==="timing")return timingPane(item,run);
5783
5998
  const fresh=item.messages.slice(item.newFrom);const calls=(item.response||[]).flatMap(message=>message.tool_calls||[]);
5784
5999
  return kv([
5785
6000
  ["Request",'<span class="mono">'+esc(item.id)+'</span> '+copyButton(item.id,"request id")],
5786
6001
  ["Model",esc(item.model||"—")],
5787
6002
  ["Status",itemStatus(item)+(item.error?' <span class="muted">'+esc(item.error)+'</span>':"")],
5788
6003
  ["Started",esc(offsetFrom(base,isoAt(item.startAt)))+' <span class="muted">'+esc(fmtTime(isoAt(item.startAt)))+'</span>'],
5789
- ["Duration",esc(durationText(item.durationMs))],
6004
+ ["Duration",esc(durationText(item.durationMs))+(Number.isFinite(item.ttftMs)?' <span class="muted">· first token after '+esc(durationText(item.ttftMs))+'</span>':"")],
5790
6005
  ["Tokens",esc(fmtTokens(item.tokensIn))+" in · "+esc(fmtTokens(item.tokensOut))+" out"+(item.cacheRead?" · "+esc(fmtTokens(item.cacheRead))+" read from cache":"")+(item.cacheWrite?" · "+esc(fmtTokens(item.cacheWrite))+" written to cache":"")],
5791
6006
  item.stopReason?["Stop reason",esc(item.stopReason)]:null,
5792
6007
  ["Initiator",item.initiator.key?itemLink(item.initiator.key,item.initiator.label):esc(item.initiator.label)],
@@ -5806,13 +6021,14 @@ function toolDetail(item,run,pane){
5806
6021
  return kv([["Status",itemStatus(item)],item.result.message?["Message",esc(item.result.message)]:null,["Size",esc(fmtBytes(jsonSize(item.result.data)))]])+(typeof item.result.data==="string"&&!/^\s*[\[{]/.test(item.result.data)?'<pre class="dt-pre">'+esc(item.result.data)+'</pre>':jsonBlock(item.result.data,item.key+":result"));
5807
6022
  }
5808
6023
  if(pane==="raw")return'<div class="dt-bar"><span>'+count(item.events.length,"event")+'</span>'+copyButton(jsonText(item.events),"raw events")+'</div>'+jsonBlock(item.events.map(event=>({type:event.type,timestamp:event.timestamp,data:event.data})),item.key+":raw");
6024
+ if(pane==="timing")return timingPane(item,run);
5809
6025
  if(item.kind==="subagent")return kv([["Subagent",esc(item.name)],["Status",itemStatus(item)],["Duration",esc(durationText(item.durationMs))],item.message?["Result",esc(item.message)]:null])+'<div class="dt-section">Prompt</div><pre class="dt-pre">'+esc(item.prompt||"")+'</pre>';
5810
6026
  return kv([
5811
6027
  item.id?["Call",'<span class="mono">'+esc(item.id)+'</span> '+copyButton(item.id,"call id")]:null,
5812
6028
  ["Tool",esc(item.name)+(item.via==="repl"?' <span class="muted">· '+esc(item.fn||"")+'() from the REPL</span>':"")],
5813
6029
  ["Status",itemStatus(item)],
5814
6030
  Number.isFinite(item.startAt)?["Started",esc(offsetFrom(base,isoAt(item.startAt)))]:null,
5815
- ["Duration",esc(durationText(item.durationMs))],
6031
+ ["Duration",esc(durationText(item.durationMs))+(item.queuedMs>0?' <span class="muted">· queued '+esc(durationText(item.queuedMs))+' first</span>':"")],
5816
6032
  ["Called by",item.initiator.key?itemLink(item.initiator.key,item.initiator.label):esc(item.initiator.label)],
5817
6033
  item.approval?["Approval",'<span class="st '+(item.approval.status==="approved"?"ok":item.approval.status==="pending"?"warn":"err")+'">'+esc(item.approval.status)+'</span> <span class="muted">requested '+esc(fmtTime(item.approval.requestedAt))+(item.approval.settledAt?", settled "+esc(fmtTime(item.approval.settledAt)):"")+'</span>']:null,
5818
6034
  item.result?["Result",esc(fmtBytes(jsonSize(item.result.data)))+" · "+'<button type="button" class="net-link" data-net-pane="result">view</button>']:null,
@@ -5826,6 +6042,15 @@ function netDetail(item,trace,run,view){
5826
6042
  +(item.kind==="model"&&item.request?'<span class="nd-actions">'+'<button type="button" class="button" data-copy="'+attr(requestJson(item))+'" title="The system prompt, messages, context and tools of this request as JSON">'+icon("copy")+'<span>Copy request</span></button></span>':"")
5827
6043
  +'</div><div class="nd-title"><b>'+esc(item.name)+'</b><span>'+esc(itemType(item))+(item.model?" · "+esc(item.model):"")+'</span></div><div class="nd-body" data-scroll-key="nd:'+attr(item.key+":"+pane)+'">'+body+'</div></aside>';
5828
6044
  }
6045
+ function netRows(visible,trace,selectedKey){
6046
+ // A run with more than one turn (a resume, an event wake) shows where each began.
6047
+ const divide=(trace.turns||[]).length>1;let shown=0;
6048
+ return visible.map(item=>{
6049
+ let head="";
6050
+ if(divide&&item.turn&&item.turn!==shown){shown=item.turn;const turn=trace.turns[item.turn-1];if(turn)head=turnRow(turn)}
6051
+ return head+netRow(item,trace,selectedKey);
6052
+ }).join("");
6053
+ }
5829
6054
  function runNetwork(run,trace,view){
5830
6055
  const term=state.network.filter.trim().toLowerCase();
5831
6056
  const visible=trace.items.filter(item=>netMatches(item,state.network.kind,term));
@@ -5836,7 +6061,7 @@ function runNetwork(run,trace,view){
5836
6061
  +'<div class="dt-chips" role="group" aria-label="Request type">'+kinds.map(kind=>'<button type="button" class="dt-chip'+(state.network.kind===kind[0]?" active":"")+'" data-net-kind="'+kind[0]+'">'+kind[1]+'</button>').join("")+'</div></div>';
5837
6062
  html+='<div class="net-split'+(selected?" has-detail":"")+'"><div class="net-list" data-scroll-key="net-list">';
5838
6063
  if(!trace.items.length)html+=empty("No requests recorded","Model requests and tool calls appear here as the run makes them. Runs recorded before request tracing, or with observability.modelRequests off, list only tool calls and responses.");
5839
- else html+='<table class="net-table">'+(selected?"":'<colgroup><col class="w-name"><col class="w-type"><col class="w-status"><col class="w-init"><col class="w-size"><col class="w-time"><col class="w-wf"></colgroup>')+'<thead><tr><th class="c-name">Name</th><th class="c-type">Type</th><th class="c-status">Status</th><th class="c-init">Initiator</th><th class="c-size" title="Tokens in → out for model requests, result size for tools">Size</th><th class="c-time">Time</th><th class="c-wf">Waterfall</th></tr></thead><tbody>'+visible.map(item=>netRow(item,trace,view.item)).join("")+'</tbody></table>'+(visible.length?"":empty("Nothing matches","Clear the filter to see every request."));
6064
+ else html+='<table class="net-table">'+(selected?"":'<colgroup><col class="w-name"><col class="w-type"><col class="w-status"><col class="w-init"><col class="w-size"><col class="w-time"><col class="w-wf"></colgroup>')+'<thead><tr><th class="c-name">Name</th><th class="c-type">Type</th><th class="c-status">Status</th><th class="c-init">Initiator</th><th class="c-size" title="Tokens in → out for model requests, result size for tools">Size</th><th class="c-time">Time</th><th class="c-wf">Waterfall</th></tr></thead><tbody>'+netRows(visible,trace,view.item)+'</tbody></table>'+(visible.length?"":empty("Nothing matches","Clear the filter to see every request."));
5840
6065
  html+='</div>'+(selected?netDetail(selected,trace,run,view):"")+'</div>';
5841
6066
  html+='<div class="net-foot"><span>'+(visible.length===trace.items.length?"":visible.length+" / ")+count(t.requests,"model request")+'</span><span>'+count(t.tools,"tool call")+'</span><span>'+esc(fmtTokens(t.tokensIn))+' in · '+esc(fmtTokens(t.tokensOut))+' out'+(t.cacheRead?" · "+esc(fmtTokens(t.cacheRead))+" cached":"")+'</span><span>model '+esc(durationText(t.modelMs))+' · tools '+esc(durationText(t.toolMs))+'</span>'+(t.errors?'<span class="st err">'+count(t.errors,"error")+'</span>':"")+'<span class="net-foot-right">finished in '+esc(durationText(runDurationMs(run)))+'</span></div>';
5842
6067
  return html;
@@ -5847,7 +6072,8 @@ const CONSOLE_LEVELS={default:["error","warn","info"],all:["error","warn","info"
5847
6072
  function revealKey(row){
5848
6073
  const type=String(row.type||"").replace(/^agent\./,"");const data=row.data||{};
5849
6074
  if(type==="model_request"||type==="model_request_end")return"m:"+data.request_id;
5850
- if(type==="tool_use")return data.id?"t:"+data.id:"";
6075
+ if(type==="tool_use"||type==="tool_use_start")return data.id?"t:"+data.id:"";
6076
+ if(type==="text_delta")return data.request_id?"m:"+data.request_id:"";
5851
6077
  if(type==="tool_use_result")return(data.id||data.call_id)?"t:"+(data.id||data.call_id):"";
5852
6078
  return"";
5853
6079
  }
@@ -5933,10 +6159,11 @@ function renderRun(id){
5933
6159
  +'<div><label>Agent instance</label><strong>'+(run.agentId?'<a class="link mono" href="/instances/'+attr(run.agentId)+'" data-link>'+esc(short(run.agentId))+'</a>':"Not recorded")+'</strong></div>'
5934
6160
  +'</div>';
5935
6161
  const errors=rows.filter(row=>row.level==="error").length;const warnings=rows.filter(row=>row.level==="warn").length;
5936
- const badge={network:trace.items.length?'<span class="dt-badge">'+trace.items.length+'</span>':"",console:(errors?'<span class="dt-badge err">'+errors+'</span>':"")+(warnings?'<span class="dt-badge warn">'+warnings+'</span>':"")};
6162
+ const crossings=buildQueues(events,run,trace).length;
6163
+ const badge={queues:crossings?'<span class="dt-badge">'+crossings+'</span>':"",network:trace.items.length?'<span class="dt-badge">'+trace.items.length+'</span>':"",console:(errors?'<span class="dt-badge err">'+errors+'</span>':"")+(warnings?'<span class="dt-badge warn">'+warnings+'</span>':"")};
5937
6164
  html+='<section class="devtools"><div class="dt-tabs" role="tablist" aria-label="Run views">'+RUN_TABS.map(tab=>'<button type="button" role="tab" class="dt-tab'+(view.tab===tab[0]?" active":"")+'" aria-selected="'+(view.tab===tab[0])+'" data-run-tab="'+tab[0]+'">'+icon(tab[2])+esc(tab[1])+(badge[tab[0]]||"")+'</button>').join("")
5938
- +(isLiveRun(run)?'<span class="dt-live"><i class="pulse-dot"></i>Live</span>':"")+'<span class="dt-hint">1–4 views · j / k requests · / filter · Esc close</span></div><div class="dt-body dt-'+view.tab+'">'
5939
- +(view.tab==="summary"?runSummary(run,events,trace):view.tab==="console"?runConsole(run,rows):view.tab==="context"?runContext(run,trace,events,view):runNetwork(run,trace,view))+'</div></section>';
6165
+ +(isLiveRun(run)?'<span class="dt-live"><i class="pulse-dot"></i>Live</span>':"")+'<span class="dt-hint">1–7 views · j / k requests · / filter · Esc close</span></div><div class="dt-body dt-'+view.tab+'">'
6166
+ +(view.tab==="summary"?runSummary(run,events,trace):view.tab==="console"?runConsole(run,rows):view.tab==="context"?runContext(run,trace,events,view):view.tab==="composition"?compositionView(run,trace,events,view):view.tab==="queues"?queuesView(run,trace,events,view):view.tab==="chain"?chainView(run,events):runNetwork(run,trace,view))+'</div></section>';
5940
6167
  $("content").innerHTML=html;
5941
6168
  bindRun(id,run,trace,events);
5942
6169
  }
@@ -5962,12 +6189,13 @@ function bindRun(id,run,trace,events){
5962
6189
  if(rerun)rerun.onclick=()=>openRunDrawer(state.instances.find(x=>x.id===run.agentId)?.definitionId,run.agentId,typeof run.input?.message?.text==="string"?run.input.message.text:typeof run.input?.message==="string"?run.input.message:"");
5963
6190
  const exportButton=document.querySelector("[data-export-trace]");
5964
6191
  if(exportButton)exportButton.onclick=()=>{const blob=new Blob([JSON.stringify({run,events},null,2)+"\n"],{type:"application/json"});const url=URL.createObjectURL(blob);const link=document.createElement("a");link.href=url;link.download="run-"+run.id+".json";document.body.appendChild(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);toast("Trace exported")};
6192
+ bindRunFoundry(id);
5965
6193
  dataLinks();
5966
6194
  }
5967
6195
  /* Keys on the run page: 1-4 switch views, j/k walk the requests, Esc closes the open one. */
5968
6196
  function runKeys(e){
5969
6197
  const current=route();if(current.section!=="runs"||!current.id)return false;
5970
- const index=["1","2","3","4"].indexOf(e.key);
6198
+ const index=["1","2","3","4","5","6","7"].indexOf(e.key);
5971
6199
  if(index>=0){setRunView({tab:RUN_TABS[index][0]});rerenderRun(current.id);return true}
5972
6200
  const view=runView();
5973
6201
  if(view.tab==="network"&&(e.key==="j"||e.key==="k"||e.key==="ArrowDown"||e.key==="ArrowUp")){
@@ -5977,6 +6205,7 @@ function runKeys(e){
5977
6205
  e.preventDefault();selectRunItem(current.id,next.dataset.netItem);return true;
5978
6206
  }
5979
6207
  if(e.key==="Escape"&&view.item){setRunView({item:"",pane:""});rerenderRun(current.id);return true}
6208
+ if(e.key==="Escape"&&view.tab==="queues"&&view.queue){setRunView({queue:""});rerenderRun(current.id);return true}
5980
6209
  return false;
5981
6210
  }
5982
6211
  `;
@@ -5984,6 +6213,7 @@ function runKeys(e){
5984
6213
  // src/dashboard-trace.ts
5985
6214
  var DASHBOARD_TRACE_SCRIPT = String.raw`
5986
6215
  function traceTime(iso){const t=Date.parse(iso);return Number.isFinite(t)?t:NaN}
6216
+ function tracePlural(n,word){return n+" "+word+(n===1?"":"s")}
5987
6217
  function traceType(event){return String(event.type||"").replace(/^agent\./,"")}
5988
6218
  function tracePreview(value,limit){
5989
6219
  let text;
@@ -5994,9 +6224,15 @@ function tracePreview(value,limit){
5994
6224
  }
5995
6225
  function buildRunTrace(events,run){
5996
6226
  const ordered=[...(events||[])].sort((a,b)=>(a.sequence??0)-(b.sequence??0));
5997
- const prompts={},toolSets={},requests={},calls={},items=[],pendingByName={};
6227
+ const prompts={},toolSets={},requests={},calls={},items=[],pendingByName={},turns=[];
5998
6228
  const totals={requests:0,tools:0,tokensIn:0,tokensOut:0,cacheRead:0,cacheWrite:0,modelMs:0,toolMs:0,errors:0};
5999
- let open=null,previous=null,first=NaN,last=NaN;
6229
+ let first=NaN,last=NaN;
6230
+ // One frame per agent: the run's own, then one per subagent running inside it.
6231
+ const frames=[{open:null,previous:null,subagent:null}];
6232
+ const frame=()=>frames[frames.length-1];
6233
+ let turn=null;
6234
+ const place=(item)=>{const f=frame();item.depth=frames.length-1;if(f.subagent)item.parent=f.subagent.key;if(turn)item.turn=turn.index;return item};
6235
+ const requestFor=(data)=>(data.request_id&&requests[data.request_id])||frame().open;
6000
6236
  const runStart=run?traceTime(run.startedAt||run.createdAt):NaN;
6001
6237
  const runEnd=run&&run.completedAt?traceTime(run.completedAt):NaN;
6002
6238
  const runningTool=()=>{for(let i=items.length-1;i>=0;i--){const item=items[i];if(item.kind==="tool"&&item.status==="pending"&&!item.via)return item}return null};
@@ -6016,15 +6252,18 @@ function buildRunTrace(events,run){
6016
6252
  let newFrom=messages.length-added.length;
6017
6253
  // A run's first request carries the conversation so far; what's new starts at the run's own message.
6018
6254
  if(!base)for(let i=messages.length-1;i>=0;i--){const m=messages[i];if(m&&m.sender==="user"&&!m.framework_context&&!(m.tool_results||[]).length&&!m.is_compaction){newFrom=i;break}}
6019
- const initiator=data.purpose==="compaction"?{label:"compaction"}:previous&&previous.calls.length?{label:"after "+[...new Set(previous.calls.map(id=>calls[id]&&calls[id].name).filter(Boolean))].join(", "),key:previous.key}:previous?{label:"continues #"+previous.index,key:previous.key}:{label:"run input"};
6255
+ const f=frame();const previous=f.previous;
6256
+ const initiator=data.purpose==="compaction"?{label:"compaction"}:previous&&previous.calls.length?{label:"after "+[...new Set(previous.calls.map(id=>calls[id]&&calls[id].name).filter(Boolean))].join(", "),key:previous.key}:previous?{label:"continues #"+previous.index,key:previous.key}:f.subagent?{label:"subagent "+f.subagent.name,key:f.subagent.key}:turn&&turn.trigger!=="request"?{label:turn.trigger==="events"?"event wake":"resumed",key:"turn:"+turn.index}:{label:"run input"};
6020
6257
  const item={kind:"model",key:"m:"+data.request_id,id:data.request_id,index:++totals.requests,name:"#"+(totals.requests)+" "+(data.purpose==="compaction"?"compaction":"request"),model:data.model||"",purpose:data.purpose||"turn",status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:data,end:null,promptHash:data.system_prompt&&data.system_prompt.hash,promptChars:data.system_prompt&&data.system_prompt.chars,toolsHash:data.tools&&data.tools.hash,toolNames:(data.tools&&data.tools.names)||[],messages,newFrom,context:data.context||[],response:[],calls:[],initiator,events:[event]};
6021
- requests[data.request_id]=item;items.push(item);open=item;previous=item;continue;
6258
+ place(item);requests[data.request_id]=item;items.push(item);f.open=item;f.previous=item;continue;
6022
6259
  }
6023
6260
  if(type==="model_request_end"){
6024
6261
  const item=requests[data.request_id];if(!item)continue;
6025
6262
  item.end=data;item.events.push(event);item.status=data.status||"success";item.endAt=at;
6026
6263
  item.durationMs=Number.isFinite(data.duration_ms)?data.duration_ms:at-item.startAt;
6027
6264
  if(Number.isFinite(data.duration_ms)&&Number.isFinite(at))item.startAt=at-data.duration_ms;
6265
+ // Time to first token: waiting on the model, then streaming its answer.
6266
+ if(Number.isFinite(item.firstTokenAt))item.ttftMs=Math.max(0,Math.min(item.durationMs,item.firstTokenAt-item.startAt));
6028
6267
  item.tokensIn=data.tokens_in;item.tokensOut=data.tokens_out;item.cacheRead=data.cache_read_input_tokens;item.cacheWrite=data.cache_creation_input_tokens;
6029
6268
  item.response=data.response||[];item.error=data.error;
6030
6269
  totals.tokensIn+=data.tokens_in||0;totals.tokensOut+=data.tokens_out||0;totals.cacheRead+=data.cache_read_input_tokens||0;totals.cacheWrite+=data.cache_creation_input_tokens||0;
@@ -6034,38 +6273,68 @@ function buildRunTrace(events,run){
6034
6273
  if(!call.id)continue;
6035
6274
  item.calls.push(call.id);calls[call.id]=calls[call.id]||{name:call.tool_name,request:item};
6036
6275
  // Adapters that don't stream tool_use: the call starts when the response arrives.
6037
- if(!calls[call.id].item)calls[call.id].item=addTool({kind:"tool",key:"t:"+call.id,id:call.id,name:call.tool_name,input:call.input_args,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:item.key,initiator:{label:"#"+item.index+" "+(item.purpose==="compaction"?"compaction":"request"),key:item.key},events:[]});
6276
+ if(!calls[call.id].item)calls[call.id].item=addTool(place({kind:"tool",key:"t:"+call.id,id:call.id,name:call.tool_name,input:call.input_args,status:"pending",startAt:at,askedAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:item.key,initiator:{label:"#"+item.index+" "+(item.purpose==="compaction"?"compaction":"request"),key:item.key},events:[]}));
6038
6277
  }
6039
- if(open===item)open=null;continue;
6278
+ for(const f of frames)if(f.open===item)f.open=null;
6279
+ continue;
6280
+ }
6281
+ if(type==="text_delta"){
6282
+ const target=requestFor(data);
6283
+ if(target){if(!Number.isFinite(target.firstTokenAt))target.firstTokenAt=at;target.streamed=(target.streamed||"")+String(data.text||"")}
6284
+ continue;
6040
6285
  }
6041
6286
  if(type==="model_response_complete"||type==="model_response"){
6042
- const target=open||previous;
6043
- if(target&&(target===open||!target.stopReason)){target.stopReason=data.stop_reason;target.events.push(event);continue}
6287
+ const f=frame();const target=(data.request_id&&requests[data.request_id])||f.open||f.previous;
6288
+ if(target&&(target===f.open||target.id===data.request_id||!target.stopReason)){target.stopReason=data.stop_reason;target.events.push(event);continue}
6044
6289
  if(!target){
6045
6290
  // A runtime without request events: the response is all there is.
6046
6291
  const item={kind:"model",key:"m:"+(event.id||event.sequence),id:String(event.id||event.sequence),index:++totals.requests,name:"#"+totals.requests+" response",model:"",purpose:"turn",status:"success",startAt:at,endAt:at,durationMs:NaN,sequence:event.sequence,request:null,end:null,messages:[],newFrom:0,context:[],response:[{sender:"agent",text:data.text||"",tool_calls:data.tool_calls}],calls:[],toolNames:[],initiator:{label:"run"},stopReason:data.stop_reason,tokensIn:data.tokens_in,tokensOut:data.tokens_out,events:[event],legacy:true};
6047
- totals.tokensIn+=data.tokens_in||0;totals.tokensOut+=data.tokens_out||0;items.push(item);
6292
+ totals.tokensIn+=data.tokens_in||0;totals.tokensOut+=data.tokens_out||0;items.push(place(item));
6048
6293
  }
6049
6294
  continue;
6050
6295
  }
6051
6296
  if(type==="tool_use"){
6052
- const request=open||previous;
6053
- const item=addTool({kind:"tool",key:"t:"+(data.id||event.id||event.sequence),id:data.id,name:data.name||"tool",input:data.input,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:request?request.key:null,initiator:request?{label:"#"+request.index+" "+(request.purpose==="compaction"?"compaction":"request"),key:request.key}:{label:"model"},events:[event]});
6297
+ const request=requestFor(data)||frame().previous;
6298
+ if(request&&!Number.isFinite(request.firstTokenAt))request.firstTokenAt=at;
6299
+ const item=addTool(place({kind:"tool",key:"t:"+(data.id||event.id||event.sequence),id:data.id,name:data.name||"tool",input:data.input,status:"pending",startAt:at,askedAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:request?request.key:null,initiator:request?{label:"#"+request.index+" "+(request.purpose==="compaction"?"compaction":"request"),key:request.key}:{label:"model"},events:[event]}));
6054
6300
  if(data.id){calls[data.id]=calls[data.id]||{name:item.name,request};calls[data.id].item=item}
6055
6301
  continue;
6056
6302
  }
6303
+ if(type==="tool_use_start"){
6304
+ // The call starts running now: after the calls ahead of it, its permission check and validation.
6305
+ const name=data.name||"tool";
6306
+ let item=data.id&&calls[data.id]&&calls[data.id].item;
6307
+ if(!item)item=(pendingByName[name]||[]).find(candidate=>candidate.status==="pending"&&!candidate.via&&!Number.isFinite(candidate.runAt));
6308
+ if(!item){item=addTool(place({kind:"tool",key:"t:"+(data.id||event.id||event.sequence),id:data.id,name,input:data.input,status:"pending",startAt:at,askedAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:null,initiator:{label:"model"},events:[]}));if(data.id){calls[data.id]=calls[data.id]||{name};calls[data.id].item=item}}
6309
+ item.runAt=at;item.waitedMs=Number.isFinite(data.waited_ms)?data.waited_ms:undefined;item.events.push(event);
6310
+ continue;
6311
+ }
6057
6312
  if(type==="tool_use_result"){
6058
6313
  const id=data.id||data.call_id;const name=data.name||data.tool_name||"tool";
6059
6314
  let item=id&&calls[id]&&calls[id].item;
6060
6315
  const queue=pendingByName[name]||[];
6061
6316
  if(!item)item=queue.find(candidate=>candidate.status==="pending"&&!candidate.via);
6062
- if(!item)item=addTool({kind:"tool",key:"t:"+(id||event.id||event.sequence),id,name,input:undefined,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:null,initiator:{label:"model"},events:[]});
6317
+ if(!item)item=addTool(place({kind:"tool",key:"t:"+(id||event.id||event.sequence),id,name,input:undefined,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:null,initiator:{label:"model"},events:[]}));
6063
6318
  const index=queue.indexOf(item);if(index>=0)queue.splice(index,1);
6064
6319
  item.events.push(event);item.result=data.result||{};item.status=(data.result&&data.result.status)||"success";item.endAt=at;
6320
+ if(item.status==="error"&&/^Permission denied for tool/.test(String(item.result.message||"")))item.status="denied";
6065
6321
  item.durationMs=Number.isFinite(data.duration_ms)?data.duration_ms:at-item.startAt;
6066
6322
  if(Number.isFinite(data.duration_ms)&&Number.isFinite(at))item.startAt=at-data.duration_ms;
6323
+ // Asked for, then queued behind the calls ahead of it, then checked, then run.
6324
+ if(Number.isFinite(item.askedAt))item.queuedMs=Math.max(0,item.startAt-item.askedAt);
6325
+ if(Number.isFinite(item.runAt))item.runMs=Math.max(0,at-item.runAt);
6067
6326
  if(Number.isFinite(item.durationMs))totals.toolMs+=item.durationMs;
6068
- if(item.status==="error")totals.errors++;
6327
+ if(item.status==="error"||item.status==="denied")totals.errors++;
6328
+ continue;
6329
+ }
6330
+ if(type==="turn_start"){
6331
+ // A subagent's turns sit inside its parent's; only the run's own are listed.
6332
+ if(frames.length===1){turn={kind:"turn",key:"turn:"+(turns.length+1),index:turns.length+1,id:data.turn_id,trigger:data.trigger||"request",status:"pending",startAt:at,endAt:NaN,durationMs:NaN,events:[event]};turns.push(turn)}
6333
+ continue;
6334
+ }
6335
+ if(type==="turn_end"){
6336
+ const ended=turns.find(candidate=>candidate.id===data.turn_id);
6337
+ if(ended){ended.status=data.status||"success";ended.endAt=at;ended.durationMs=Number.isFinite(data.duration_ms)?data.duration_ms:at-ended.startAt;if(Number.isFinite(data.duration_ms))ended.startAt=at-data.duration_ms;ended.error=data.error;ended.events.push(event)}
6069
6338
  continue;
6070
6339
  }
6071
6340
  if(/^foundry\.approval\./.test(type)){
@@ -6076,20 +6345,31 @@ function buildRunTrace(events,run){
6076
6345
  }
6077
6346
  if(/^foundry\.repl\.programmatic-tool\./.test(type)){
6078
6347
  const name=data.tool||"tool";
6079
- if(type==="foundry.repl.programmatic-tool.started"){const parent=runningTool();addTool({kind:"tool",via:"repl",key:"p:"+(event.id||event.sequence),name,fn:data.function,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:parent?parent.request:null,initiator:parent?{label:parent.name+" (REPL)",key:parent.key}:{label:"REPL"},events:[event]});continue}
6348
+ if(type==="foundry.repl.programmatic-tool.started"){const parent=runningTool();addTool(place({kind:"tool",via:"repl",key:"p:"+(event.id||event.sequence),name,fn:data.function,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:parent?parent.request:null,initiator:parent?{label:parent.name+" (REPL)",key:parent.key}:{label:"REPL"},events:[event]}));continue}
6080
6349
  const item=[...items].reverse().find(candidate=>candidate.via==="repl"&&candidate.name===name&&candidate.status==="pending");
6081
6350
  if(item){item.events.push(event);item.endAt=at;item.durationMs=data.durationMs;item.status=type.endsWith("completed")?"success":type.endsWith("failed")?"error":"denied";if(Number.isFinite(data.durationMs)&&Number.isFinite(at))item.startAt=at-data.durationMs;if(item.status!=="success")totals.errors++}
6082
6351
  else if(!type.endsWith("completed")){totals.tools++;totals.errors++;items.push({kind:"tool",via:"repl",key:"p:"+(event.id||event.sequence),name,fn:data.function,status:type.split(".").pop(),startAt:at,endAt:at,durationMs:0,sequence:event.sequence,initiator:{label:"REPL"},result:{status:"error",message:data.reason},events:[event]})}
6083
6352
  continue;
6084
6353
  }
6085
- if(type==="subagent_invoked"){items.push({kind:"subagent",key:"s:"+(event.id||event.sequence),name:data.name,prompt:data.prompt,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,initiator:{label:"subagent"},events:[event]});continue}
6086
- if(type==="subagent_completed"){const item=[...items].reverse().find(candidate=>candidate.kind==="subagent"&&candidate.name===data.name&&candidate.status==="pending");if(item){item.status=data.status||"success";item.endAt=at;item.durationMs=at-item.startAt;item.message=data.message;item.events.push(event)}continue}
6354
+ if(type==="subagent_invoked"){
6355
+ const call=data.call_id&&calls[data.call_id]&&calls[data.call_id].item;
6356
+ const item=place({kind:"subagent",key:"s:"+(data.call_id||event.id||event.sequence),call:call?call.key:undefined,name:data.name,prompt:data.prompt,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,initiator:call?{label:call.name,key:call.key}:{label:"subagent"},events:[event]});
6357
+ items.push(item);frames.push({open:null,previous:null,subagent:item});continue;
6358
+ }
6359
+ if(type==="subagent_completed"){
6360
+ const index=frames.findLastIndex(candidate=>candidate.subagent&&(data.call_id?candidate.subagent.key==="s:"+data.call_id:candidate.subagent.name===data.name));
6361
+ const item=index>0?frames[index].subagent:[...items].reverse().find(candidate=>candidate.kind==="subagent"&&candidate.name===data.name&&candidate.status==="pending");
6362
+ if(index>0)frames.splice(index);
6363
+ if(item){item.status=data.status||"success";item.endAt=at;item.durationMs=at-item.startAt;item.message=data.message;item.events.push(event)}
6364
+ continue;
6365
+ }
6087
6366
  }
6088
6367
  const start=Number.isFinite(runStart)?Math.min(runStart,Number.isFinite(first)?first:runStart):first;
6089
6368
  const live=run&&(run.status==="running"||run.status==="pending");
6090
6369
  const end=live?Math.max(Date.now(),Number.isFinite(last)?last:0):Number.isFinite(runEnd)?Math.max(runEnd,Number.isFinite(last)?last:runEnd):last;
6091
6370
  for(const item of items){if(item.kind==="model"){item.systemPrompt=prompts[item.promptHash];item.tools=toolSets[item.toolsHash]}}
6092
- return{items,prompts,toolSets,totals,start,end};
6371
+ for(const item of turns)if(item.status==="pending"&&!live&&Number.isFinite(end)){item.endAt=end;item.durationMs=end-item.startAt}
6372
+ return{items,turns,prompts,toolSets,totals,start,end};
6093
6373
  }
6094
6374
 
6095
6375
  /* Console levels follow DevTools: errors, warnings, info, and verbose detail hidden by default. */
@@ -6113,6 +6393,25 @@ function describeEvent(event){
6113
6393
  if(type==="model_response_complete"||type==="model_response")return level("verbose","Response"+(data.stop_reason?" ("+data.stop_reason+")":"")+": "+tracePreview(data.text||"",120));
6114
6394
  if(type==="text_delta")return level("verbose","Streamed text: "+tracePreview(data.text,160));
6115
6395
  if(type==="tool_use")return level("info","Tool call "+data.name+"("+tracePreview(data.input,100)+")");
6396
+ if(type==="tool_use_start")return level("verbose",data.name+" started"+(data.waited_ms>=1000?" after "+data.waited_ms+"ms of permission checks":""),"tool");
6397
+ if(type==="turn_start")return level("info",data.trigger==="events"?"Turn started: events woke the agent":data.trigger==="resume"?"Turn resumed at its tool step":"Turn started","run");
6398
+ if(type==="turn_end"){
6399
+ const time=Number.isFinite(data.duration_ms)?" after "+data.duration_ms+"ms":"";
6400
+ if(data.status==="error")return level("error","Turn failed"+time+(data.error?": "+tracePreview(data.error,140):""),"run");
6401
+ if(data.status==="aborted")return level("warn","Turn aborted"+time,"run");
6402
+ if(data.status==="suspended")return level("warn","Turn suspended"+time+": a tool call is waiting for a decision","run");
6403
+ return level("info","Turn finished"+time,"run");
6404
+ }
6405
+ if(type==="inbox_injected")return level("info","Inbox: "+(data.ids||[]).length+" resolved item"+((data.ids||[]).length===1?"":"s")+" joined the conversation "+(data.phase==="loop"?"between tool steps":"before the request")+((data.tags||[]).length?" ("+data.tags.join(", ")+")":""),"inbox");
6406
+ if(type==="event_received"){
6407
+ const what=(data.kind?data.kind+" from ":"")+data.source;const preview=data.preview?": "+tracePreview(data.preview,120):"";
6408
+ if(data.disposition==="dropped")return level("warn","Event dropped: "+what+preview,"queue");
6409
+ if(data.disposition==="duplicate")return level("verbose","Duplicate event ignored: "+what,"queue");
6410
+ return level("info","Event "+({queued:"queued",woke:"woke the agent",deferred:"deferred"}[data.disposition]||data.disposition)+": "+what+preview,"queue");
6411
+ }
6412
+ if(type==="event_injected")return level("info",tracePlural((data.ids||[]).length,"event")+" joined the conversation "+({loop:"between tool steps",request:"before the request",wake:"as the turn's message"}[data.phase]||""),"queue");
6413
+ if(type==="event_dropped")return level("warn","Event "+data.id+" dropped ("+data.reason+")","queue");
6414
+ if(type==="event_wake_failed")return level("error","A turn for "+tracePlural((data.ids||[]).length,"event")+" failed: "+tracePreview(data.message,140),"queue");
6116
6415
  if(type==="tool_use_result"){
6117
6416
  const status=data.result&&data.result.status;const name=data.name||data.tool_name;const time=Number.isFinite(data.duration_ms)?" in "+data.duration_ms+"ms":"";
6118
6417
  if(status==="error")return level("error",name+" failed"+time+": "+tracePreview(data.result.message||data.result.data,140));
@@ -6138,13 +6437,18 @@ function describeEvent(event){
6138
6437
  return level("verbose",type);
6139
6438
  }
6140
6439
  function buildConsole(events){
6141
- const rows=[];let stream=null;
6440
+ // A streamed reply is one line: chunks of one request join, wherever they arrive.
6441
+ const rows=[];let stream=null;const streams={};
6142
6442
  for(const event of [...(events||[])].sort((a,b)=>(a.sequence??0)-(b.sequence??0))){
6143
6443
  if(traceType(event)==="text_delta"){
6144
- if(!stream){stream={key:"c:"+(event.id||event.sequence),level:"verbose",source:"model",timestamp:event.timestamp,type:"text_delta",text:"",chunks:0,events:[]};rows.push(stream)}
6145
- stream.text+=String((event.data&&event.data.text)||"");stream.chunks++;stream.events.push(event);
6146
- stream.message="Streamed text ("+stream.chunks+" chunk"+(stream.chunks===1?"":"s")+"): "+tracePreview(stream.text,160);
6147
- stream.data={text:stream.text,chunks:stream.chunks};
6444
+ const request=event.data&&event.data.request_id;
6445
+ const current=request?streams[request]:stream;
6446
+ const row=current||{key:"c:"+(event.id||event.sequence),level:"verbose",source:"model",timestamp:event.timestamp,type:"text_delta",text:"",chunks:0,events:[]};
6447
+ if(!current){rows.push(row);if(request)streams[request]=row}
6448
+ stream=row;
6449
+ row.text+=String((event.data&&event.data.text)||"");row.chunks++;row.events.push(event);
6450
+ row.message="Streamed text ("+row.chunks+" chunk"+(row.chunks===1?"":"s")+"): "+tracePreview(row.text,160);
6451
+ row.data={text:row.text,chunks:row.chunks,...(request?{request_id:request}:{})};
6148
6452
  continue;
6149
6453
  }
6150
6454
  stream=null;
@@ -6155,6 +6459,366 @@ function buildConsole(events){
6155
6459
  }
6156
6460
  `;
6157
6461
 
6462
+ // src/dashboard-foundry.ts
6463
+ var DASHBOARD_FOUNDRY_SCRIPT = String.raw`
6464
+ function foundryAt(event){const t=Date.parse(event&&event.timestamp);return Number.isFinite(t)?t:NaN}
6465
+ function foundrySorted(events){return[...(events||[])].sort((a,b)=>(a.sequence??0)-(b.sequence??0))}
6466
+
6467
+ /* ---- Composition ---- */
6468
+ const COMPOSITION_LEGACY_STEPS={"foundry.application.transmission-tools.mounted":["transmissions","App transmissions"],"foundry.working-environment.mounted":["workbench","Working environment"]};
6469
+ function buildComposition(events){
6470
+ const ordered=foundrySorted(events);
6471
+ const result={composed:null,resolves:[],steps:[],tools:[],origins:{},apps:[],installations:[],playbooks:[],schedules:[],scheduled:[],delegates:[],durableSubagents:[],mesh:null,memory:[],layers:[],subscribers:[],hooks:[],skills:[],subagents:[],calls:[],workingEnvironment:null,repl:null,inboxes:null,delegation:null,startAt:NaN,endAt:NaN,durationMs:NaN,legacy:true};
6472
+ const open={};
6473
+ for(const event of ordered){
6474
+ const type=traceType(event);const data=event.data||{};const at=foundryAt(event);
6475
+ if(type==="foundry.assembly.resolve.start"){if(!(result.startAt<=at))result.startAt=at;open[data.field]={field:data.field,startAt:at,endAt:NaN,durationMs:NaN};result.resolves.push(open[data.field]);continue}
6476
+ if(type==="foundry.assembly.resolve.complete"){const item=open[data.field];if(item){item.endAt=at;item.durationMs=at-item.startAt;if(data.count!==undefined)item.count=data.count;delete open[data.field]}continue}
6477
+ if(type==="foundry.assembly.composed"){
6478
+ result.composed=data;result.legacy=false;result.endAt=at;
6479
+ if(Number.isFinite(data.durationMs)&&!(result.startAt<=at-data.durationMs))result.startAt=at-data.durationMs;
6480
+ result.steps=(data.steps||[]).map(step=>({...step,tools:[...(step.tools||[])]}));
6481
+ result.tools=[...(data.tools||[])];result.installations=data.installations||[];
6482
+ result.apps=data.apps||[];result.playbooks=data.playbooks||[];result.schedules=data.schedules||[];
6483
+ result.delegates=data.delegates||[];result.durableSubagents=data.durableSubagents||[];result.mesh=data.mesh||null;
6484
+ result.hooks=data.hooks||[];result.skills=data.skills||[];result.subagents=data.subagents||[];result.calls=data.calls||[];
6485
+ result.delegation=data.delegation||null;
6486
+ if(data.repl&&!result.repl)result.repl={};
6487
+ if(data.workingEnvironment&&!result.workingEnvironment)result.workingEnvironment={};
6488
+ continue;
6489
+ }
6490
+ if(type==="foundry.definition.memory.mounted"){result.memory.push(data.id);continue}
6491
+ if(type==="foundry.layer.mounted"){result.layers.push(data.id);continue}
6492
+ if(type==="foundry.subscriber.mounted"){result.subscribers.push(data.id);continue}
6493
+ if(type==="foundry.working-environment.mounted"){result.workingEnvironment={...(result.workingEnvironment||{}),...data}}
6494
+ if(type==="foundry.repl.mounted"){result.repl={...(result.repl||{}),...data};continue}
6495
+ if(type==="foundry.definition.inboxes.loaded"){result.inboxes=data;continue}
6496
+ if(type==="scheduled-action.created"){result.scheduled.push({id:data.commandId,recurring:data.recurring,nextRunAt:data.nextRunAt});continue}
6497
+ if(result.legacy){
6498
+ // Runs recorded before foundry.assembly.composed: what the mount events say.
6499
+ if(COMPOSITION_LEGACY_STEPS[type]&&(data.tools||[]).length){const step=COMPOSITION_LEGACY_STEPS[type];result.steps.push({step:step[0],label:step[1],tools:[...data.tools],ms:NaN})}
6500
+ if(type==="foundry.application.mcp.mounted")result.steps.push({step:"mcp",label:data.id,id:data.id,tools:[...(data.tools||[])],ms:NaN});
6501
+ if(type==="foundry.installation.completed"){result.installations.push({kind:data.kind,id:data.id});result.steps.push({step:"installation",label:data.id,kind:data.kind,id:data.id,tools:[],ms:NaN})}
6502
+ if(type==="foundry.definition.playbooks.composed")result.playbooks=(data.names||[]).map(name=>({name}));
6503
+ if(type==="foundry.definition.schedules.loaded")result.schedules=(data.names||[]).map(name=>({name}));
6504
+ if(type==="foundry.definition.delegates.loaded")result.delegates=(data.delegates||[]).map(agent=>({agent}));
6505
+ if(type==="foundry.mesh.mounted")result.mesh={hosted:true,threads:data.open,...(data.thread?{thread:data.thread}:{})};
6506
+ }
6507
+ if(type==="turn_start"&&!Number.isFinite(result.endAt))result.endAt=at;
6508
+ }
6509
+ if(Number.isFinite(result.startAt)&&Number.isFinite(result.endAt))result.durationMs=Math.max(0,result.endAt-result.startAt);
6510
+ for(const step of result.steps)for(const name of step.tools)if(!result.origins[name])result.origins[name]={step:step.step,label:step.label};
6511
+ if(!result.tools.length)result.tools=Object.keys(result.origins);
6512
+ return result;
6513
+ }
6514
+
6515
+ /* ---- Queues: what crossed the run's boundary ---- */
6516
+ function queueChannel(kind,source){
6517
+ const k=String(kind||"");
6518
+ if(k==="transmission"||/^foundry:route:/.test(String(source||"")))return"transmission";
6519
+ if(k==="agent-message")return"agent message";
6520
+ if(k==="mesh")return"mesh";
6521
+ if(/^delegation|^reply$/.test(k))return"delegation";
6522
+ if(/approval/.test(k))return"approval";
6523
+ return k||"event";
6524
+ }
6525
+ const QUEUE_PHASE={wake:"as the turn's message",request:"before the request",loop:"between tool steps"};
6526
+ function queueCommand(data){
6527
+ const type=data.type||"command";
6528
+ const timing=data.timing?(data.timing.kind==="at"?"at "+data.timing.at:data.timing.kind==="every"?"every "+Math.round(data.timing.intervalMs/1000)+"s":data.timing.kind==="cron"?data.timing.expression+" ("+data.timing.timezone+")":""):"";
6529
+ if(type==="transmit")return{channel:"transmission",title:"Transmission "+(data.routeId||data.transmissionId||""),preview:tracePreview(data.payload,160)};
6530
+ if(type==="spawn")return{channel:"spawn",title:"Spawn "+(data.definitionId||""),preview:tracePreview(data.message,160)};
6531
+ if(type==="schedule")return{channel:"schedule",title:"Schedule "+timing,preview:tracePreview(data.message,160)};
6532
+ if(/^schedule\./.test(type))return{channel:"schedule",title:"Schedule "+type.slice(9)+" "+(data.activationId||""),preview:data.patch?tracePreview(data.patch,160):""};
6533
+ if(type==="sleep")return{channel:"sleep",title:"Sleep until "+(data.wakeAt||""),preview:tracePreview(data.message,160)};
6534
+ if(type==="background")return{channel:"background",title:"Background run",preview:tracePreview(data.message,160)};
6535
+ if(type==="delegate")return{channel:"delegation",title:"Delegate to "+data.to,preview:tracePreview(data.task,160)};
6536
+ if(type==="delegate.reply")return{channel:"delegation",title:"Reply to worker",preview:tracePreview(data.message,160)};
6537
+ if(type==="delegate.ask")return{channel:"delegation",title:"Ask the delegator",preview:tracePreview(data.question,160)};
6538
+ if(type==="agent.message")return{channel:"agent message",title:"Message "+data.to,preview:tracePreview(data.message,160)};
6539
+ if(type==="mesh.send")return{channel:"mesh",title:"Mesh message to "+((data.message&&data.message.to)||""),preview:tracePreview(data.message&&(data.message.text||data.message.body||data.message),160)};
6540
+ if(/^mesh\./.test(type))return{channel:"mesh",title:"Mesh "+type.slice(5),preview:""};
6541
+ return{channel:"command",title:type,preview:""};
6542
+ }
6543
+ function buildQueues(events,run,trace){
6544
+ const ordered=foundrySorted(events);
6545
+ const rows=[];const byEvent={};const byCommand={};const byDelegation={};const approvals={};
6546
+ const models=((trace&&trace.items)||[]).filter(item=>item.kind==="model"&&!item.legacy);
6547
+ const seenAfter=(sequence)=>models.find(item=>(item.sequence??0)>sequence)||null;
6548
+ const source=run&&run.input&&run.input.source;
6549
+ if(run){
6550
+ const message=run.input&&run.input.message;
6551
+ const text=typeof message==="string"?message:Array.isArray(message)?message.filter(part=>part&&part.type==="text").map(part=>part.text).join(" "):"";
6552
+ const kind=(source&&source.kind)||"direct";
6553
+ const delegationTitle=source&&/^result:/.test(String(source.id||""))?"Delegation result":source&&/^delegation_/.test(String(source.id||""))?"Delegated task":"Delegation update";
6554
+ const titles={direct:"Message",transmission:"Transmission "+((source&&source.id)||""),activation:"Schedule or sleep fired",spawn:"Spawned",background:"Background run",delegation:delegationTitle,["agent-message"]:"Agent message",mesh:"Mesh thread"};
6555
+ const first=models[0]||null;
6556
+ rows.push({key:"q:trigger",dir:"in",channel:kind==="direct"?"message":queueChannel(kind),title:titles[kind]||kind,preview:tracePreview(text,200),status:"started the run",at:Date.parse(run.createdAt),seenBy:first?first.key:null,detail:{source:source||{kind:"direct"},...(source&&source.eventId?{eventId:source.eventId}:{}),...(source&&source.threadKey?{threadKey:source.threadKey}:{})},events:[]});
6557
+ }
6558
+ let turnSeen=false;
6559
+ for(const event of ordered){
6560
+ const type=traceType(event);const data=event.data||{};const at=foundryAt(event);
6561
+ if(type==="turn_start")turnSeen=true;
6562
+ if(type==="event_received"){
6563
+ const row={key:"q:e:"+data.id,dir:"in",channel:queueChannel(data.kind,data.source),title:data.source,preview:data.preview||"",status:data.disposition,at,seenBy:null,detail:{id:data.id,source:data.source,kind:data.kind,disposition:data.disposition},events:[event]};
6564
+ // The first delivery of an event turn is what started the run.
6565
+ if(!turnSeen&&rows[0]&&rows[0].key==="q:trigger"&&!rows[0].event&&source&&source.kind!=="direct"){rows[0].event=data.id;rows[0].events.push(event);byEvent[data.id]=rows[0];continue}
6566
+ byEvent[data.id]=row;rows.push(row);continue;
6567
+ }
6568
+ if(type==="event_injected"){
6569
+ for(const id of data.ids||[]){const row=byEvent[id];if(!row)continue;const seen=seenAfter(event.sequence??0);if(row.key!=="q:trigger")row.status="joined "+(QUEUE_PHASE[data.phase]||data.phase);row.injectedAt=at;row.seenBy=seen?seen.key:row.seenBy;row.events.push(event)}
6570
+ continue;
6571
+ }
6572
+ if(type==="event_dropped"){const row=byEvent[data.id];if(row){row.status="dropped ("+data.reason+")";row.events.push(event)}continue}
6573
+ if(type==="inbox_injected"){
6574
+ const seen=seenAfter(event.sequence??0);
6575
+ rows.push({key:"q:i:"+(event.id||event.sequence),dir:"in",channel:"inbox",title:"Resolved: "+(data.tags||[]).join(", "),preview:(data.ids||[]).join(", "),status:"joined "+(QUEUE_PHASE[data.phase]||data.phase),at,seenBy:seen?seen.key:null,detail:data,events:[event]});continue;
6576
+ }
6577
+ if(type==="tool_use"&&data.name==="glove_post_to_inbox"){
6578
+ const input=data.input||{};
6579
+ rows.push({key:"q:p:"+(data.id||event.sequence),dir:"out",channel:"inbox",title:"Posted: "+(input.tag||"item"),preview:tracePreview(input.request,200),status:input.blocking?"posted, blocking":"posted",at,call:data.id?"t:"+data.id:null,detail:input,events:[event]});continue;
6580
+ }
6581
+ if(type==="foundry.core.command"){
6582
+ if(data.type==="playbook.sync"||data.type==="schedule.sync")continue;
6583
+ const described=queueCommand(data);
6584
+ const row={key:"q:c:"+(data.id||event.sequence),dir:"out",...described,status:"sent",at,detail:data,events:[event]};
6585
+ if(data.id)byCommand[data.id]=row;if(data.delegationId)byDelegation[data.delegationId]=row;
6586
+ rows.push(row);continue;
6587
+ }
6588
+ if(type==="core.command.accepted"){const row=byCommand[data.commandId];if(row){row.status="accepted";if(data.childRunId)row.childRunId=data.childRunId;row.events.push(event)}continue}
6589
+ if(type==="core.command.failed"){const row=byCommand[data.command&&data.command.id];if(row){row.status="failed";row.error=data.error;row.events.push(event)}continue}
6590
+ if(type==="scheduled-action.created"){const row=byCommand[data.commandId];if(row){row.status="scheduled";row.nextRunAt=data.nextRunAt;row.events.push(event)}continue}
6591
+ if(type==="transmission.outbound.delivered"){const row=byCommand[data.commandId];if(row){row.status="delivered";row.events.push(event)}else rows.push({key:"q:o:"+(event.id||event.sequence),dir:"out",channel:"transmission",title:"Transmission "+(data.routeId||""),preview:"",status:"delivered",at,detail:data,events:[event]});continue}
6592
+ if(type==="delegation.started"){const row=byDelegation[data.delegationId];if(row){row.status="started";row.childRunId=data.workerRunId;row.events.push(event)}continue}
6593
+ if(type==="delegation.question"||type==="delegation.replied"){const row=[...rows].reverse().find(candidate=>candidate.dir==="out"&&candidate.detail&&candidate.detail.delegationId===data.delegationId&&candidate.status==="sent");if(row){row.status="delivered";row.events.push(event)}continue}
6594
+ if(type==="delegation.delivered"&&data.mode==="live"){
6595
+ // Answers and updates handed to this run while it ran: a waiting question is answered.
6596
+ const asked=[...rows].reverse().find(candidate=>candidate.dir==="out"&&candidate.detail&&candidate.detail.type==="delegate.ask"&&candidate.status!=="answered");
6597
+ if(asked){asked.status="answered";asked.events.push(event)}
6598
+ rows.push({key:"q:l:"+(event.id||event.sequence),dir:"in",channel:/^delegation_/.test(String(data.conversationId||""))?"delegation":"mailbox",title:asked?"Answer to: "+tracePreview(asked.preview,60):"Delivered while running",preview:tracePlural(data.count||1,"delivery")+" handed to the live run",status:"delivered",at,seenBy:null,detail:data,events:[event]});
6599
+ continue;
6600
+ }
6601
+ if(type==="foundry.approval.requested"){const row={key:"q:a:"+data.id,dir:"out",channel:"approval",title:"Approval for "+data.toolName,preview:tracePreview(data.toolInput,160),status:"waiting",at,detail:data,events:[event]};approvals[data.id]=row;rows.push(row);continue}
6602
+ if(type==="foundry.approval.settled"||type==="foundry.approval.failed"||type==="foundry.approval.unavailable"){
6603
+ const row=approvals[data.approvalId]||[...rows].reverse().find(candidate=>candidate.channel==="approval"&&candidate.detail.toolName===data.toolName&&candidate.status==="waiting");
6604
+ if(row){row.status=data.status||type.split(".").pop();row.settledAt=at;row.events.push(event)}continue;
6605
+ }
6606
+ }
6607
+ return rows.sort((a,b)=>(Number.isFinite(a.at)?a.at:0)-(Number.isFinite(b.at)?b.at:0));
6608
+ }
6609
+
6610
+ /* ---- Call chain: the run among the runs it came from and started ---- */
6611
+ const CHAIN_COMMANDS={spawn:"spawned",schedule:"scheduled",sleep:"woke from sleep",background:"background run",["agent.message"]:"messaged"};
6612
+ function buildRunChain(runId,runs,events){
6613
+ const byId={};for(const run of runs||[])byId[run.id]=run;
6614
+ const parents={};const children={};const seen=new Set();
6615
+ const link=(from,to,label,detail)=>{
6616
+ if(!from||!to||from===to)return;const key=from+">"+to+">"+label;if(seen.has(key))return;seen.add(key);
6617
+ const edge={from,to,label,...(detail?{detail}:{})};(children[from]=children[from]||[]).push(edge);(parents[to]=parents[to]||[]).push(edge);
6618
+ };
6619
+ const delegations={};const commands={};const replies=[];
6620
+ for(const event of foundrySorted(events)){
6621
+ const type=traceType(event);const data=event.data||{};
6622
+ if(type==="foundry.core.command"&&data.id){commands[data.id]={runId:event.runId,type:data.type};continue}
6623
+ if(type==="delegation.started"){delegations[data.delegationId]={to:data.to,runId:event.runId,workerRunId:data.workerRunId};link(event.runId,data.workerRunId,"delegated to "+data.to,data.delegationId);continue}
6624
+ if(type==="delegation.replied"){replies.push({from:event.runId,delegationId:data.delegationId});continue}
6625
+ if(type==="core.command.accepted"){link(event.runId,data.childRunId,CHAIN_COMMANDS[data.type]||data.type||"started");continue}
6626
+ if(type==="run.steered"){link(data.fromRunId,data.toRunId||event.runId,"steered");continue}
6627
+ }
6628
+ // Answers reach a worker that is still running.
6629
+ for(const reply of replies){const delegation=delegations[reply.delegationId];if(delegation)link(reply.from,delegation.workerRunId,"replied",reply.delegationId)}
6630
+ // What a run hears back arrives as a run of its own, named by what it answers.
6631
+ const COMMAND_EDGES={["delegate.ask"]:"asked",["delegate.reply"]:"replied",["agent.message"]:"messaged"};
6632
+ for(const run of runs||[]){
6633
+ const source=run.input&&run.input.source;
6634
+ if(!source||!source.id||source.kind==="direct")continue;
6635
+ const id=String(source.id);
6636
+ if(/^result:/.test(id)){link(id.slice(7),run.id,"reported back");continue}
6637
+ if(commands[id]){link(commands[id].runId,run.id,COMMAND_EDGES[commands[id].type]||commands[id].type);continue}
6638
+ const delegation=source.kind==="delegation"&&delegations[id];
6639
+ if(delegation&&run.id!==delegation.workerRunId&&run.agent!==delegation.to&&delegation.workerRunId)link(delegation.workerRunId,run.id,"reported back",id);
6640
+ }
6641
+ const node=(id,edge)=>{const run=byId[id];return{id,run:run||null,edge:edge||null}};
6642
+ const ancestors=[];const visited=new Set([runId]);let current=runId;
6643
+ while(parents[current]&&parents[current].length&&ancestors.length<12){const edge=parents[current][0];if(visited.has(edge.from))break;visited.add(edge.from);ancestors.unshift(node(edge.from,edge));current=edge.from}
6644
+ const top=ancestors.length?ancestors[0].run:byId[runId];
6645
+ const origin=top&&top.input&&top.input.source&&top.input.source.kind!=="direct"?{kind:top.input.source.kind,id:top.input.source.id,provider:top.input.source.provider,eventId:top.input.source.eventId,threadKey:top.input.source.threadKey}:null;
6646
+ const started=(id)=>{const run=byId[id];const at=run?Date.parse(run.createdAt):NaN;return Number.isFinite(at)?at:Infinity};
6647
+ const descend=(id,depth,path)=>[...(children[id]||[])].sort((a,b)=>started(a.to)-started(b.to)).map(edge=>{const child=node(edge.to,edge);child.children=depth<4&&!path.has(edge.to)?descend(edge.to,depth+1,new Set([...path,edge.to])):[];return child});
6648
+ const self=node(runId,parents[runId]&&parents[runId][0]);
6649
+ self.children=descend(runId,0,new Set([runId]));
6650
+ return{origin,ancestors,self,parents:parents[runId]||[]};
6651
+ }
6652
+ `;
6653
+
6654
+ // src/dashboard-run-foundry.ts
6655
+ var DASHBOARD_RUN_FOUNDRY_SCRIPT = String.raw`
6656
+ /* ---- Composition ---- */
6657
+ const COMPOSITION_NODES=[["Assembly","timeline","Timeline"],["Assembly","tools","Tools by origin"],["Capabilities","apps","Apps and installations"],["Capabilities","workbench","Working environment and REPL"],["Automation","playbooks","Playbooks"],["Automation","schedules","Schedules"],["Agents","delegates","Delegates and workers"],["Agents","mesh","Mesh"],["Extensions","extensions","Memory, layers and subscribers"],["Extensions","surface","Hooks, skills, subagents and calls"]];
6658
+ function toolCallCounts(trace){const counts={};for(const item of trace.items)if(item.kind==="tool"&&!item.via)counts[item.name]=(counts[item.name]||0)+1;return counts}
6659
+ function toolChip(name,counts,extra){
6660
+ const calls=counts[name]||0;
6661
+ return'<button type="button" class="cap tool-chip'+(calls?" called":"")+'" data-tool-filter="'+attr(name)+'" title="'+attr(calls?"Show its "+count(calls,"call")+" in Network":"Not called in this run")+'">'+esc(name)+(extra||"")+(calls?'<small>'+calls+'</small>':"")+'</button>';
6662
+ }
6663
+ function compositionTimeline(comp){
6664
+ const rows=[];
6665
+ for(const item of comp.resolves)rows.push({name:item.field,note:"resolve"+(item.count!==undefined?" · "+count(item.count,"item"):""),startAt:item.startAt,durationMs:item.durationMs,kind:"resolve"});
6666
+ if(comp.composed&&Number.isFinite(comp.endAt)){
6667
+ let at=comp.endAt-(comp.composed.durationMs||0);
6668
+ for(const step of comp.steps){rows.push({name:step.label,note:step.tools.length?count(step.tools.length,"tool"):step.kind||"",startAt:at,durationMs:step.ms,kind:step.step});at+=step.ms||0}
6669
+ }
6670
+ if(!rows.length)return empty("No assembly recorded","Runs record their assembly as they start. Runs from before Foundry recorded it, or handler-only runs, have none.");
6671
+ const start=Math.min(...rows.map(row=>row.startAt).filter(Number.isFinite));const end=Math.max(...rows.map(row=>row.startAt+(row.durationMs||0)).filter(Number.isFinite),comp.endAt||0);const span=Math.max(1,end-start);
6672
+ return'<p class="dt-note">How Foundry put this run’s agent together before its first turn'+(Number.isFinite(comp.durationMs)?", in "+esc(durationText(comp.durationMs)):"")+'. Definition fields resolve in parallel, then each step mounts its part.</p>'
6673
+ +'<table class="net-table comp-table"><thead><tr><th>Step</th><th></th><th class="c-time">Time</th><th class="c-wf">Waterfall</th></tr></thead><tbody>'
6674
+ +rows.map(row=>{const left=Number.isFinite(row.startAt)?(row.startAt-start)/span*100:0;const width=Math.max(.6,(row.durationMs||0)/span*100);return'<tr class="comp-row kind-'+attr(row.kind)+'"><td><b>'+esc(row.name)+'</b></td><td class="muted">'+esc(row.note)+'</td><td class="c-time mono">'+esc(durationText(row.durationMs))+'</td><td class="c-wf"><span class="wf-track"><span class="wf-bar" style="left:'+Math.min(99.4,left).toFixed(2)+'%;width:'+Math.min(width,100-left).toFixed(2)+'%"></span></span></td></tr>'}).join("")
6675
+ +'</tbody></table>';
6676
+ }
6677
+ function compositionTools(comp,trace,counts){
6678
+ const offered=(trace.items.filter(item=>item.kind==="model"&&!item.legacy).at(-1)||{}).toolNames||[];
6679
+ const unattributed=offered.filter(name=>!comp.origins[name]);
6680
+ const steps=comp.steps.filter(step=>step.tools.length);
6681
+ if(!steps.length&&!offered.length)return empty("No tools recorded","");
6682
+ return'<p class="dt-note">Each tool the agent had, under the step that added it. Click one to see its calls in Network.'+(comp.legacy?" This run was recorded before Foundry kept each step’s tools, so only steps that reported theirs are listed.":"")+'</p>'
6683
+ +steps.map(step=>'<section class="comp-group"><header><b>'+esc(step.label)+'</b>'+(step.kind?'<span class="muted">'+esc(step.kind)+'</span>':"")+'<span class="muted mono">'+count(step.tools.length,"tool")+'</span></header><div class="cap-list">'+step.tools.map(name=>toolChip(name,counts)).join("")+'</div></section>').join("")
6684
+ +(unattributed.length?'<section class="comp-group"><header><b>Offered, origin not recorded</b><span class="muted mono">'+count(unattributed.length,"tool")+'</span></header><div class="cap-list">'+unattributed.map(name=>toolChip(name,counts)).join("")+'</div></section>':"");
6685
+ }
6686
+ function compositionApps(comp,counts,instance){
6687
+ const installs=comp.installations.length?comp.installations:(instance?instance.installations:[]);
6688
+ const apps=comp.apps;
6689
+ if(!installs.length&&!apps.length)return empty("Nothing installed","Apps, MCP servers and shared tools installed on the instance appear here with the tools each gave the agent.");
6690
+ const stepFor=(install)=>comp.steps.find(step=>step.step==="installation"&&step.id===install.id);
6691
+ const mcp=comp.steps.find(step=>step.step==="mcp"&&!step.id);
6692
+ return'<p class="dt-note">What the instance has installed, and what each installation gave this run.</p>'
6693
+ +installs.map(install=>{
6694
+ const app=apps.find(item=>item.id===install.id);const step=stepFor(install);
6695
+ const tools=app?app.tools:step?step.tools.map(name=>({name})):[];
6696
+ return'<section class="comp-group"><header><b>'+esc(install.id)+'</b><span class="dt-badge">'+esc(install.kind)+'</span>'+(install.accountId?'<span class="muted">account '+esc(install.accountId)+'</span>':"")+(step&&Number.isFinite(step.ms)?'<span class="muted mono">'+esc(durationText(step.ms))+'</span>':"")+'</header>'
6697
+ +(app&&app.description?'<p class="dt-note">'+esc(app.description)+'</p>':"")
6698
+ +(tools.length?'<div class="cap-list">'+tools.map(tool=>toolChip(tool.name,counts,tool.readOnly===false?'<i class="tool-writes" title="Changes things">writes</i>':"")).join("")+'</div>':'<p class="dt-note">'+(install.kind==="mcp"?"Mounted with the other MCP servers below.":"No tools of its own.")+'</p>')
6699
+ +'</section>';
6700
+ }).join("")
6701
+ +(mcp&&mcp.tools.length?'<section class="comp-group"><header><b>MCP servers</b><span class="muted mono">'+count(mcp.tools.length,"tool")+'</span></header><div class="cap-list">'+mcp.tools.map(name=>toolChip(name,counts)).join("")+'</div></section>':"");
6702
+ }
6703
+ function compositionView(run,trace,events,view){
6704
+ const comp=buildComposition(events);const counts=toolCallCounts(trace);
6705
+ const instance=state.instances.find(item=>item.id===run.agentId);
6706
+ const node=COMPOSITION_NODES.some(entry=>entry[1]===view.cnode)?view.cnode:"timeline";
6707
+ const toolCount=comp.steps.reduce((sum,step)=>sum+step.tools.length,0);
6708
+ const counted={timeline:comp.steps.length+comp.resolves.length||"",tools:toolCount||"",apps:(comp.installations.length||(instance?instance.installations.length:0))||"",playbooks:(comp.playbooks.length||(instance?instance.playbooks.length:0))||"",schedules:comp.schedules.length||"",delegates:(comp.delegates.length+comp.durableSubagents.length)||"",extensions:(comp.memory.length+comp.layers.length+comp.subscribers.length)||"",surface:(comp.hooks.length+comp.skills.length+comp.subagents.length+comp.calls.length)||""};
6709
+ let tree="";let group="";
6710
+ COMPOSITION_NODES.forEach(entry=>{if(entry[0]!==group){group=entry[0];tree+='<div class="ctx-group">'+esc(group)+'</div>'}tree+='<button type="button" class="ctx-node'+(entry[1]===node?" active":"")+'" data-comp-node="'+entry[1]+'">'+esc(entry[2])+(counted[entry[1]]?'<small>'+esc(counted[entry[1]])+'</small>':"")+'</button>'});
6711
+ const list=(items,format)=>items.length?'<div class="cap-list">'+items.map(format).join("")+'</div>':'<p class="dt-note">None.</p>';
6712
+ let body="";
6713
+ if(node==="timeline")body=compositionTimeline(comp);
6714
+ else if(node==="tools")body=compositionTools(comp,trace,counts);
6715
+ else if(node==="apps")body=compositionApps(comp,counts,instance);
6716
+ else if(node==="playbooks"){
6717
+ const stored=instance?instance.playbooks:[];
6718
+ body='<p class="dt-note">Playbooks tell the agent how to handle what arrives on its transmissions. The definition composes them; the instance stores them.</p>'
6719
+ +'<div class="dt-section">Composed by the definition</div>'+list(comp.playbooks,item=>'<span class="cap">'+esc(item.name||item.id)+'</span>')
6720
+ +'<div class="dt-section">Stored on the instance</div>'+(stored.length?jsonBlock(stored,"comp:playbooks"):'<p class="dt-note">None.</p>');
6721
+ }
6722
+ else if(node==="schedules"){
6723
+ const activations=(state.activations||[]).filter(item=>item.agentId===run.agentId||item.createdByRunId===run.id);
6724
+ const timing=(t)=>!t?"":t.kind==="cron"?t.expression+" · "+t.timezone:t.kind==="every"?"every "+durationText(t.intervalMs):t.kind==="at"?"at "+fmtTime(t.at):"";
6725
+ body='<p class="dt-note">The definition’s schedules, synced when the run starts, and the instance’s activations: schedules and sleeps the runtime will fire.</p>'
6726
+ +'<div class="dt-section">Defined</div>'+(comp.schedules.length?kv(comp.schedules.map(item=>[item.name,esc(timing(item.timing))+(item.enabled===false?' <span class="st warn">disabled</span>':"")])):'<p class="dt-note">None.</p>')
6727
+ +(comp.scheduled.length?'<div class="dt-section">Created by this run</div>'+kv(comp.scheduled.map(item=>[short(item.id),(item.recurring?"recurring · ":"")+"next "+esc(fmtTime(item.nextRunAt))])):"")
6728
+ +'<div class="dt-section">Activations for this instance</div>'+(activations.length?'<table class="net-table"><thead><tr><th>Activation</th><th>Kind</th><th>Status</th><th>Next</th><th>Last run</th></tr></thead><tbody>'+activations.map(item=>'<tr><td class="mono">'+esc(item.scheduleName||short(item.id))+'</td><td>'+esc(item.kind||"")+'</td><td>'+esc(item.status||"")+'</td><td>'+esc(item.nextRunAt?fmtTime(item.nextRunAt):"—")+'</td><td>'+(item.lastRunId?'<a class="link mono" href="/runs/'+attr(item.lastRunId)+'" data-link>'+esc(short(item.lastRunId))+'</a>':"—")+'</td></tr>').join("")+'</tbody></table>':'<p class="dt-note">None.</p>');
6729
+ }
6730
+ else if(node==="delegates"){
6731
+ body='<p class="dt-note">Other agents this one can hand work to. Each delegation runs in the worker’s own conversation and reports back; see Call chain for the runs.</p>'
6732
+ +(comp.delegation?'<div class="dt-section">This run works for</div>'+kv([["Delegator",esc(comp.delegation.from)],["Task",esc(comp.delegation.task)],["Delegation",'<span class="mono">'+esc(comp.delegation.id)+'</span>']]):"")
6733
+ +'<div class="dt-section">Delegates</div>'+(comp.delegates.length?kv(comp.delegates.map(item=>[item.agent,esc(item.description||"")])):'<p class="dt-note">None.</p>')
6734
+ +'<div class="dt-section">Durable subagents</div>'+list(comp.durableSubagents,name=>'<span class="cap">'+esc(name)+'</span>')
6735
+ +(comp.composed?'<p class="dt-note">'+count(comp.composed.openDelegations||0,"delegation")+' open when the run started.</p>':"");
6736
+ }
6737
+ else if(node==="mesh")body=comp.mesh?kv([["Hosted mesh",comp.mesh.hosted?"mounted":"no"],["Your own transport",comp.mesh.transport?"mounted":"no"],["Open threads",esc(comp.mesh.threads??0)],comp.mesh.thread?["This run’s thread",'<span class="mono">'+esc(comp.mesh.thread)+'</span>']:null]):empty("No mesh","This agent doesn’t talk to peers over the mesh.");
6738
+ else if(node==="extensions")body='<div class="dt-section">Memory</div>'+list(comp.memory,id=>'<span class="cap">'+esc(id)+'</span>')+'<div class="dt-section">Layers</div>'+list(comp.layers,id=>'<span class="cap">'+esc(id)+'</span>')+'<div class="dt-section">Subscribers</div>'+list(comp.subscribers,id=>'<span class="cap">'+esc(id)+'</span>')+(comp.inboxes?'<div class="dt-section">Inbox</div><p class="dt-note">'+esc(count(comp.inboxes.count||0,"item"))+" loaded, "+esc(comp.inboxes.added||0)+" added, "+esc(comp.inboxes.updated||0)+' updated.</p>':"");
6739
+ else if(node==="surface")body='<div class="dt-section">Hooks</div>'+list(comp.hooks,name=>'<span class="cap">/'+esc(name)+'</span>')+'<div class="dt-section">Skills</div>'+list(comp.skills,name=>'<span class="cap">'+esc(name)+'</span>')+'<div class="dt-section">Subagents</div>'+list(comp.subagents,name=>'<span class="cap">'+esc(name)+'</span>')+'<div class="dt-section">Calls</div>'+list(comp.calls,call=>'<span class="cap">'+esc(call.name)+(call.exposed===false?' <small>not offered to the model</small>':"")+'</span>');
6740
+ else if(node==="workbench")body=(comp.workingEnvironment?'<div class="dt-section">Working environment</div>'+jsonBlock(comp.workingEnvironment,"comp:we"):'<div class="dt-section">Working environment</div><p class="dt-note">Not mounted.</p>')+(comp.repl?'<div class="dt-section">REPL</div>'+jsonBlock(comp.repl,"comp:repl"):'<div class="dt-section">REPL</div><p class="dt-note">Not mounted.</p>');
6741
+ return'<div class="ctx"><nav class="ctx-tree" aria-label="Composition">'+tree+'</nav><div class="ctx-view" data-scroll-key="comp:'+attr(node)+'">'+body+'</div></div>';
6742
+ }
6743
+
6744
+ /* ---- Queues ---- */
6745
+ function queueStatusClass(status){const s=String(status||"");return/fail|dropped|denied|rejected/.test(s)?"err":/waiting|deferred|queued|sent|posted/.test(s)?"warn":/joined|started|accepted|delivered|scheduled|approved|woke/.test(s)?"ok":""}
6746
+ function queuesView(run,trace,events,view){
6747
+ state.queues=state.queues||{filter:"",dir:"all"};
6748
+ const q=state.queues;const rows=buildQueues(events,run,trace);const term=q.filter.trim().toLowerCase();
6749
+ const visible=rows.filter(row=>(q.dir==="all"||row.dir===q.dir)&&(!term||(row.channel+" "+row.title+" "+row.preview+" "+row.status).toLowerCase().includes(term)));
6750
+ const selected=rows.find(row=>row.key===view.queue);const base=new Date(runStartedAt(run)).getTime();
6751
+ const models=Object.fromEntries(trace.items.filter(item=>item.kind==="model").map(item=>[item.key,item]));
6752
+ const inbound=rows.filter(row=>row.dir==="in").length;
6753
+ let html='<div class="dt-toolbar"><label class="dt-filter">'+icon("search")+'<input id="queue-filter" value="'+attr(q.filter)+'" placeholder="Filter by channel, source or content" aria-label="Filter messages" /></label>'
6754
+ +'<div class="dt-chips" role="group" aria-label="Direction">'+[["all","All"],["in","Inbound"],["out","Outbound"]].map(entry=>'<button type="button" class="dt-chip'+(q.dir===entry[0]?" active":"")+'" data-queue-dir="'+entry[0]+'">'+entry[1]+'</button>').join("")+'</div>'
6755
+ +'<span class="dt-summary">'+esc(inbound)+' in · '+esc(rows.length-inbound)+' out</span></div>';
6756
+ html+='<div class="net-split'+(selected?" has-detail":"")+'"><div class="net-list" data-scroll-key="queue-list">';
6757
+ if(!rows.length)html+=empty("Nothing crossed this run’s boundary","What starts a run, what arrives while it works and what it sends out appear here.");
6758
+ else html+='<table class="net-table q-table">'+(selected?"":'<colgroup><col style="width:34px"><col style="width:13%"><col><col style="width:16%"><col style="width:15%"><col style="width:80px"></colgroup>')+'<thead><tr><th class="q-dir"></th><th>Channel</th><th>What</th><th>Status</th><th title="Inbound: the model request that first saw it. Outbound: the run it started.">Reached</th><th class="c-time">Time</th></tr></thead><tbody>'
6759
+ +visible.map(row=>'<tr class="net-row q-row'+(row.key===view.queue?" selected":"")+'" data-queue-item="'+attr(row.key)+'"><td class="q-dir"><span class="q-arrow '+row.dir+'" title="'+(row.dir==="in"?"Inbound":"Outbound")+'">'+(row.dir==="in"?"↓":"↑")+'</span></td><td class="mono">'+esc(row.channel)+'</td><td><span class="net-name"><span><b>'+esc(row.title)+'</b><small>'+esc(row.preview)+'</small></span></span></td><td><span class="st '+queueStatusClass(row.status)+'">'+esc(row.status)+'</span></td><td>'+(row.seenBy&&models[row.seenBy]?itemLink(row.seenBy,models[row.seenBy].name):row.childRunId?'<a class="link mono" href="/runs/'+attr(row.childRunId)+'" data-link>'+esc(short(row.childRunId))+'</a>':'<span class="muted">—</span>')+'</td><td class="c-time mono">'+esc(offsetFrom(base,isoAt(row.at)))+'</td></tr>').join("")
6760
+ +'</tbody></table>'+(visible.length?"":empty("Nothing matches","Clear the filter to see every message."));
6761
+ html+='</div>'+(selected?queueDetail(selected,run,models):"")+'</div>';
6762
+ return html;
6763
+ }
6764
+ function queueDetail(row,run,models){
6765
+ const base=new Date(runStartedAt(run)).getTime();
6766
+ return'<aside class="net-detail" aria-label="'+attr(row.title)+'"><div class="nd-head"><button type="button" class="nd-close" data-queue-close title="Close (Esc)" aria-label="Close">'+icon("close")+'</button><span class="nd-tab active">Message</span></div>'
6767
+ +'<div class="nd-title"><b>'+esc(row.title)+'</b><span>'+(row.dir==="in"?"inbound":"outbound")+" · "+esc(row.channel)+'</span></div><div class="nd-body">'
6768
+ +kv([["Status",'<span class="st '+queueStatusClass(row.status)+'">'+esc(row.status)+'</span>'+(row.error?' <span class="muted">'+esc(row.error)+'</span>':"")],
6769
+ [row.dir==="in"?"Arrived":"Sent",esc(offsetFrom(base,isoAt(row.at)))+' <span class="muted">'+esc(fmtTime(isoAt(row.at)))+'</span>'],
6770
+ Number.isFinite(row.injectedAt)?["Joined the conversation",esc(offsetFrom(base,isoAt(row.injectedAt)))]:null,
6771
+ row.seenBy&&models[row.seenBy]?["First seen by",itemLink(row.seenBy,models[row.seenBy].name)]:null,
6772
+ row.call?["Tool call",itemLink(row.call,"Open in Network")]:null,
6773
+ row.childRunId?["Run",'<a class="link mono" href="/runs/'+attr(row.childRunId)+'" data-link>'+esc(row.childRunId)+'</a>']:null,
6774
+ row.nextRunAt?["Next run",esc(fmtTime(row.nextRunAt))]:null])
6775
+ +(row.preview?'<div class="dt-section">Content</div><pre class="dt-pre">'+esc(row.preview)+'</pre>':"")
6776
+ +'<div class="dt-section">Detail</div>'+jsonBlock(row.detail,row.key+":detail")
6777
+ +(row.events.length?'<div class="dt-section">Events</div>'+jsonBlock(row.events.map(event=>({type:event.type,timestamp:event.timestamp,data:event.data})),row.key+":raw"):"")
6778
+ +'</div></aside>';
6779
+ }
6780
+
6781
+ /* ---- Call chain ---- */
6782
+ function ensureChainEvents(id){
6783
+ state.chain=state.chain||{events:null,at:0,loading:false};
6784
+ const c=state.chain;if(c.loading||(c.events&&Date.now()-c.at<10000))return;
6785
+ c.loading=true;
6786
+ api("/api/events?category=system&limit=5000").then(events=>{c.events=events;c.at=Date.now()}).catch(()=>{c.events=c.events||[]}).finally(()=>{c.loading=false;if(route().id===id&&runView().tab==="chain")rerenderRun(id)});
6787
+ }
6788
+ function chainCard(node){
6789
+ const run=node.run;
6790
+ return'<div class="chain-card">'+(run?'<a class="link" href="/runs/'+attr(node.id)+'?tab=chain" data-link><b>'+esc(run.agent)+'</b></a> '+status(run.status)+' <span class="muted mono">'+esc(short(node.id))+'</span> <span class="muted">'+esc(fmtTime(run.createdAt))+(run.completedAt?" · "+esc(durationText(Date.parse(run.completedAt)-Date.parse(runStartedAt(run)))):"")+'</span>':'<span class="mono">'+esc(short(node.id))+'</span> <span class="muted">not retained</span>')+'</div>';
6791
+ }
6792
+ function chainNode(node,self){
6793
+ const run=node.run;const edge=node.edge;
6794
+ const head=run?'<a class="link" href="/runs/'+attr(node.id)+'?tab=chain" data-link><b>'+esc(run.agent)+'</b></a> '+status(run.status)+' <span class="muted mono">'+esc(short(node.id))+'</span> <span class="muted">'+esc(fmtTime(run.createdAt))+(run.completedAt?" · "+esc(durationText(Date.parse(run.completedAt)-Date.parse(runStartedAt(run)))):"")+'</span>':'<span class="mono">'+esc(short(node.id))+'</span> <span class="muted">not retained</span>';
6795
+ return'<div class="chain-node'+(self?" self":"")+'">'+(edge?'<span class="chain-edge">'+esc(edge.label)+'</span>':"")+'<div class="chain-card">'+head+'</div>'
6796
+ +((node.children||[]).length?'<div class="chain-children">'+node.children.map(child=>chainNode(child,false)).join("")+'</div>':"")+'</div>';
6797
+ }
6798
+ function chainView(run,events){
6799
+ ensureChainEvents(run.id);
6800
+ const loaded=state.chain&&state.chain.events;
6801
+ const all=(loaded||[]).concat(events);
6802
+ const chain=buildRunChain(run.id,state.runs,all);
6803
+ const origin=chain.origin?'<div class="chain-node origin"><div class="chain-card"><b>'+esc(chain.origin.kind)+'</b> '+esc([chain.origin.provider,chain.origin.id,chain.origin.eventId,chain.origin.threadKey].filter(Boolean).join(" · "))+'</div></div>':"";
6804
+ let html='<div class="dt-pad"><p class="dt-note">The runs this one came from and the runs it started: delegations and their reports, spawns, schedules and sleeps, steering. Each links to its own run.'+(loaded?"":" Loading the runtime’s events…")+'</p><div class="chain">'+origin;
6805
+ // Each ancestor, then how it led to the run below it.
6806
+ for(const ancestor of chain.ancestors)html+='<div class="chain-node">'+chainCard(ancestor)+'<span class="chain-edge">'+esc(ancestor.edge.label)+'</span></div>';
6807
+ html+=chainNode({...chain.self,edge:null},true)+'</div>';
6808
+ if(!chain.ancestors.length&&!(chain.self.children||[]).length&&!chain.origin)html+=empty("A run on its own","Nothing recorded started this run, and it started no other runs.");
6809
+ return html+'</div>';
6810
+ }
6811
+ function bindRunFoundry(id){
6812
+ document.querySelectorAll("[data-comp-node]").forEach(node=>node.onclick=()=>{setRunView({cnode:node.dataset.compNode});rerenderRun(id)});
6813
+ document.querySelectorAll("[data-tool-filter]").forEach(node=>node.onclick=()=>{state.network.filter=node.dataset.toolFilter;state.network.kind="tools";setRunView({tab:"network",item:""});rerenderRun(id)});
6814
+ document.querySelectorAll("[data-queue-item]").forEach(node=>node.onclick=event=>{if(event.target.closest("a,[data-net-item]"))return;setRunView({queue:node.dataset.queueItem});rerenderRun(id)});
6815
+ document.querySelectorAll("[data-queue-dir]").forEach(node=>node.onclick=()=>{state.queues.dir=node.dataset.queueDir;rerenderRun(id)});
6816
+ const close=document.querySelector("[data-queue-close]");if(close)close.onclick=()=>{setRunView({queue:""});rerenderRun(id)};
6817
+ const input=$("queue-filter");
6818
+ if(input)input.oninput=event=>{const caret=event.target.selectionStart;state.queues.filter=event.target.value;rerenderRun(id);const next=$("queue-filter");if(next){next.focus();try{next.setSelectionRange(caret,caret)}catch{}}};
6819
+ }
6820
+ `;
6821
+
6158
6822
  // src/dashboard-script.ts
6159
6823
  var ICON_PATHS_JSON = JSON.stringify(PHOSPHOR_ICON_PATHS);
6160
6824
  var DASHBOARD_SCRIPT = String.raw`
@@ -6234,7 +6898,9 @@ async function copyValue(button){
6234
6898
  }
6235
6899
 
6236
6900
  ${DASHBOARD_TRACE_SCRIPT}
6901
+ ${DASHBOARD_FOUNDRY_SCRIPT}
6237
6902
  ${DASHBOARD_RUN_SCRIPT}
6903
+ ${DASHBOARD_RUN_FOUNDRY_SCRIPT}
6238
6904
  /* ---- View state. Live updates repaint the page, so the parts a person is
6239
6905
  actively using -- scroll, focus, caret, expanded rows -- survive it. ---- */
6240
6906
  function captureView(){
@@ -7080,6 +7746,45 @@ tr.cursor,.definition-card.cursor{outline:1px solid var(--accent-soft);outline-o
7080
7746
  .kind-tool .wf-bar{background:var(--network)}
7081
7747
  .kind-subagent .wf-bar{background:var(--deploy)}
7082
7748
  .net-row.failed .wf-bar{background:var(--danger)}
7749
+ .wf-bar{overflow:hidden}
7750
+ .comp-table td{padding:6px 10px}
7751
+ .comp-row.kind-resolve .wf-bar{background:var(--interface)}
7752
+ .comp-row.kind-installation .wf-bar,.comp-row.kind-mcp .wf-bar{background:var(--network)}
7753
+ .comp-group{border:1px solid var(--border);border-radius:6px;padding:10px 12px;margin:0 0 10px}
7754
+ .comp-group>header{display:flex;gap:10px;align-items:baseline;margin-bottom:8px;font-size:12px}
7755
+ .comp-group>header .muted{font-size:10px}
7756
+ .comp-group>header .muted.mono{margin-left:auto}
7757
+ .tool-chip{cursor:pointer;border:1px solid var(--border);background:transparent;color:var(--text-secondary);font:10px var(--mono);padding:4px 8px;border-radius:4px}
7758
+ .tool-chip.called{color:var(--text-primary);border-color:var(--accent-dim)}
7759
+ .tool-chip small{margin-left:6px;padding:0 5px;border-radius:8px;background:var(--accent-dim);color:var(--text-primary);font-size:9px}
7760
+ .tool-chip:hover{border-color:var(--accent)}
7761
+ .tool-writes{margin-left:6px;font-style:normal;font-size:9px;color:var(--warning, #e0b25b)}
7762
+ .q-table .q-dir{width:28px;text-align:center}
7763
+ .q-arrow{font-weight:700}
7764
+ .q-arrow.in{color:var(--network)}
7765
+ .q-arrow.out{color:var(--accent)}
7766
+ .chain{display:grid;gap:4px;margin-top:10px}
7767
+ .chain-node{position:relative}
7768
+ .chain-edge{display:block;margin:6px 0 4px 14px;font:10px var(--mono);color:var(--text-tertiary)}
7769
+ .chain-edge::before{content:"↳ ";color:var(--text-tertiary)}
7770
+ .chain-card{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px 12px;border:1px solid var(--border);border-radius:6px;background:rgba(20,29,24,.4);font-size:12px}
7771
+ .chain-card .muted{font-size:10px}
7772
+ .chain-node.self>.chain-card{border-color:var(--accent);box-shadow:inset 2px 0 0 var(--accent)}
7773
+ .chain-node.origin>.chain-card{border-style:dashed}
7774
+ .chain-children{margin-left:22px;padding-left:12px;border-left:1px dashed var(--border)}
7775
+ .wf-wait{position:absolute;left:0;top:0;bottom:0;background:rgba(255,255,255,.55);mix-blend-mode:soft-light}
7776
+ .wf-queue{position:absolute;top:5.5px;height:1px;background:var(--text-tertiary);opacity:.7}
7777
+ .net-row.nested .c-name{padding-left:calc(10px + var(--depth,1) * 16px)}
7778
+ .net-turn td{padding:7px 10px 5px;background:rgba(20,29,24,.55);border-top:1px solid var(--border);font:10px var(--mono);color:var(--text-secondary)}
7779
+ .net-turn td>span{margin-right:12px}
7780
+ .timing{display:grid;gap:6px;margin-top:12px}
7781
+ .timing-row{display:grid;grid-template-columns:minmax(150px,1.3fr) 2fr 70px;gap:12px;align-items:center;font-size:11px}
7782
+ .timing-row.total{border-top:1px solid var(--border);padding-top:6px;font-weight:600}
7783
+ .timing-name small{display:block;color:var(--text-tertiary);font-size:10px;margin-top:2px}
7784
+ .timing-track{position:relative;height:8px;background:rgba(255,255,255,.04);border-radius:2px}
7785
+ .timing-bar{position:absolute;left:0;top:0;bottom:0;border-radius:2px;background:var(--accent-soft)}
7786
+ .timing-bar.wait{background:rgba(255,255,255,.28)}
7787
+ .timing-bar.queue{background:var(--text-tertiary);opacity:.6}
7083
7788
  .wf-bar.pending{background:repeating-linear-gradient(90deg,var(--accent) 0 5px,transparent 5px 9px);opacity:.8}
7084
7789
  .net-split.has-detail .c-type,.net-split.has-detail .c-init,.net-split.has-detail .c-size,.net-split.has-detail .c-wf{display:none}
7085
7790
  .net-split.has-detail th.c-status,.net-split.has-detail th.c-time{width:72px}
@@ -7964,6 +8669,20 @@ var FoundryServer = class {
7964
8669
  );
7965
8670
  return;
7966
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
+ }
7967
8686
  if (url.pathname === "/api/activations" && method === "GET") {
7968
8687
  json(
7969
8688
  response,