glove-foundry 0.7.0 → 0.9.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.
@@ -5,25 +5,33 @@ import {
5
5
  executionEvents
6
6
  } from "./chunk-J7ZBJM54.js";
7
7
  import {
8
+ DEFAULT_APPROVAL_EXPIRES_AFTER_MS,
9
+ DEFAULT_APPROVAL_WAIT_MS,
8
10
  EMPTY_AGENT_COMPOSITION,
9
11
  EMPTY_FOUNDRY_APPLICATION,
10
12
  FOUNDRY_APPROVAL_DIRECTORY_ENV,
13
+ FOUNDRY_APPROVAL_POLICY_ENV,
11
14
  FOUNDRY_CORE_COMMAND_EVENT,
15
+ FOUNDRY_MODEL_REQUESTS_ENV,
12
16
  MemoryFoundryDataAdapter,
13
17
  createAgentInstance,
14
18
  createConversation,
15
19
  createManifest,
16
20
  definePlaybookSubscription,
17
21
  discoverAgents,
22
+ foundryApprovalRequested,
23
+ foundryApprovalSuspended,
18
24
  freezeGloveMessage,
19
25
  id,
20
26
  listFoundryApprovals,
27
+ markFoundryApprovalSuspended,
21
28
  normalizeAgentInstallations,
29
+ readFoundryApprovalResolution,
22
30
  reconstructPlaybook,
23
31
  reconstructPlaybookSubscription,
24
32
  resolveFoundryApproval,
25
33
  transmissionPredicate
26
- } from "./chunk-EJZJAVNG.js";
34
+ } from "./chunk-EUGKVW3J.js";
27
35
  import {
28
36
  FOUNDRY_CONVERSATION_LEASE_EVENT,
29
37
  FOUNDRY_CONVERSATION_LISTEN_EVENT,
@@ -32,14 +40,22 @@ import {
32
40
  deliveryEvent,
33
41
  drainMailbox,
34
42
  isDelegationId,
43
+ isMeshCommand,
35
44
  isOpenDelegation,
45
+ isOpenThread,
46
+ isThreadId,
47
+ meshIdentity,
48
+ newMessageId,
36
49
  renderDelegatedTask,
37
50
  renderDeliveries,
51
+ startedThreadIds,
52
+ threadFromContext,
53
+ threadSubject,
38
54
  undeliveredUpdate,
39
55
  workerAgentId,
40
56
  writeConversationLease,
41
57
  writeMailboxDelivery
42
- } from "./chunk-AC6SRI5V.js";
58
+ } from "./chunk-J6NHL4SM.js";
43
59
  import {
44
60
  EMPTY_CAPABILITY_REGISTRY,
45
61
  EMPTY_NATIVE_REGISTRY,
@@ -66,12 +82,13 @@ import {
66
82
  eventRecordId,
67
83
  foundryEventSchema,
68
84
  getFoundryCoreCommandRequest,
85
+ hostedMeshOptions,
69
86
  inheritedInstallations,
70
87
  installationKey,
71
88
  messageOptionsSchema,
72
89
  monitorFoundryCoreCommandRequest,
73
90
  settleFoundryCoreCommandRequest
74
- } from "./chunk-64UBLGYM.js";
91
+ } from "./chunk-CYOIHSUX.js";
75
92
 
76
93
  // src/codegen.ts
77
94
  import { mkdir, writeFile } from "node:fs/promises";
@@ -710,6 +727,7 @@ var MemoryObservabilityAdapter = class {
710
727
  function categoryForAgentEvent(type) {
711
728
  if (type === "foundry.guidance.state") return "memory";
712
729
  if (type.startsWith("tool_")) return "tool";
730
+ if (type.startsWith("turn_")) return "run";
713
731
  if (type.startsWith("foundry.installation")) return "application";
714
732
  if (type.startsWith("foundry.layer") || type.startsWith("foundry.subscriber")) {
715
733
  return "extension";
@@ -891,6 +909,26 @@ import { mkdtemp, rm } from "node:fs/promises";
891
909
  import { tmpdir } from "node:os";
892
910
  import { join } from "node:path";
893
911
  import { fileURLToPath } from "node:url";
912
+ var DaemonDisconnectedError = class extends Error {
913
+ exitCode;
914
+ signal;
915
+ /** The end of what the daemon wrote to stderr, with known secret values masked. */
916
+ stderrTail;
917
+ constructor(exitCode, signal, stderrTail) {
918
+ const how = exitCode !== null ? ` (exit code ${exitCode})` : signal ? ` (signal ${signal})` : "";
919
+ super(`Foundry execution daemon disconnected${how}. A pending mutation may have completed; inspect state before retrying.`);
920
+ this.name = "DaemonDisconnectedError";
921
+ this.exitCode = exitCode;
922
+ this.signal = signal;
923
+ this.stderrTail = stderrTail;
924
+ }
925
+ };
926
+ var STDERR_TAIL_BYTES = 4096;
927
+ var SECRET_NAME = /(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/i;
928
+ function redactor(env) {
929
+ const values = Object.entries(env).filter(([name, value]) => typeof value === "string" && value.length >= 8 && SECRET_NAME.test(name)).map(([, value]) => value).sort((a, b) => b.length - a.length);
930
+ return (text) => values.reduce((out, value) => out.split(value).join("[redacted]"), text);
931
+ }
894
932
  function entry(name) {
895
933
  const built = fileURLToPath(new URL(`./${name}.js`, import.meta.url));
896
934
  return existsSync(built) ? built : fileURLToPath(new URL(`./${name}.ts`, import.meta.url));
@@ -908,6 +946,7 @@ var FoundryExecutionBackend = class {
908
946
  loopResolve;
909
947
  loopReject;
910
948
  loop;
949
+ stderrTail = "";
911
950
  get processId() {
912
951
  return this.child?.pid;
913
952
  }
@@ -923,7 +962,10 @@ var FoundryExecutionBackend = class {
923
962
  execArgv: ["--import", import.meta.resolve("tsx")],
924
963
  stdio: ["ignore", "ignore", "pipe", "ipc"]
925
964
  });
926
- child.stderr?.resume();
965
+ const redact = redactor(env);
966
+ child.stderr?.on("data", (chunk) => {
967
+ this.stderrTail = redact((this.stderrTail + chunk.toString("utf8")).slice(-STDERR_TAIL_BYTES * 2)).slice(-STDERR_TAIL_BYTES);
968
+ });
927
969
  this.loop = new Promise((resolve3, reject) => {
928
970
  this.loopResolve = resolve3;
929
971
  this.loopReject = reject;
@@ -946,7 +988,11 @@ var FoundryExecutionBackend = class {
946
988
  else request.resolve(message.value);
947
989
  });
948
990
  const failed = () => {
949
- const error = new Error("Foundry execution daemon disconnected. A pending mutation may have completed; inspect state before retrying.");
991
+ const error = new DaemonDisconnectedError(child.exitCode, child.signalCode, this.stderrTail);
992
+ if (!this.stopped && error.stderrTail) process.stderr.write(`${error.message}
993
+ The daemon's last output:
994
+ ${error.stderrTail}
995
+ `);
950
996
  for (const request of this.pending.values()) {
951
997
  clearTimeout(request.timer);
952
998
  request.reject(error);
@@ -1001,6 +1047,8 @@ var FoundryExecutionBackend = class {
1001
1047
  if (child) {
1002
1048
  try {
1003
1049
  if (child.connected) await this.request({ method: "stop" }, 15e3);
1050
+ } catch (error) {
1051
+ if (!(error instanceof DaemonDisconnectedError)) throw error;
1004
1052
  } finally {
1005
1053
  if (child.exitCode === null && child.signalCode === null) {
1006
1054
  await new Promise((resolve3) => {
@@ -1617,8 +1665,13 @@ var FoundryRuntimeError = class extends Schema3.TaggedError(
1617
1665
  message: Schema3.String
1618
1666
  }) {
1619
1667
  };
1668
+ function clipTitle(text) {
1669
+ const flat = text.replace(/\s+/g, " ").trim();
1670
+ return flat.length > 60 ? `${flat.slice(0, 59)}\u2026` : flat;
1671
+ }
1620
1672
  function deliverySource(deliveries) {
1621
1673
  const first = deliveries[0];
1674
+ if (first.kind === "mesh") return { kind: "mesh", id: first.message.threadId };
1622
1675
  if (first.durable?.event.kind?.startsWith("delegation.")) return { kind: "delegation", id: first.durable.event.id };
1623
1676
  if (first.kind === "agent-message") return { kind: "agent-message", id: first.pendingId };
1624
1677
  if (deliveries.every((delivery) => delivery.kind === "transmission")) {
@@ -1734,6 +1787,10 @@ var FoundryRuntime = class _FoundryRuntime {
1734
1787
  pendingInboundByRun = /* @__PURE__ */ new Map();
1735
1788
  /** Recently settled runs, for a record assigned to a run that already finished. */
1736
1789
  settledRuns = /* @__PURE__ */ new Set();
1790
+ /** How runs treat approvals; durable when the data adapter can keep them. */
1791
+ approvalPolicy;
1792
+ /** Approval records change one at a time. */
1793
+ approvalWrites = Promise.resolve();
1737
1794
  started = false;
1738
1795
  stopping = false;
1739
1796
  disposed = false;
@@ -1790,6 +1847,14 @@ var FoundryRuntime = class _FoundryRuntime {
1790
1847
  maxEvents: options.config?.observability?.maxEvents
1791
1848
  });
1792
1849
  this.data = this.application.data ?? new MemoryFoundryDataAdapter();
1850
+ const durableApprovals = Boolean(
1851
+ this.data.putApproval && this.data.getApproval && this.data.listApprovals && this.data.claimEvent && this.data.putEvent && this.data.listEvents
1852
+ );
1853
+ this.approvalPolicy = {
1854
+ durable: durableApprovals,
1855
+ waitMs: this.application.approvals?.waitMs ?? (durableApprovals ? DEFAULT_APPROVAL_WAIT_MS : 3e5),
1856
+ expiresAfterMs: this.application.approvals?.expiresAfterMs ?? DEFAULT_APPROVAL_EXPIRES_AFTER_MS
1857
+ };
1793
1858
  for (const discovered of this.agents) {
1794
1859
  this.byRoute.set(discovered.route, discovered);
1795
1860
  this.routeBySignalName.set(discovered.executionName, discovered.route);
@@ -1818,6 +1883,10 @@ var FoundryRuntime = class _FoundryRuntime {
1818
1883
  void this.gate.claim(conversationId, runId).then(() => writeConversationLease(this.mailboxDirectory, runId)).catch((cause) => this.reportDeliveryFailure(conversationId, cause));
1819
1884
  return;
1820
1885
  }
1886
+ if (event.type === "foundry.approval.requested" || event.type === "foundry.approval.suspended" || event.type === "foundry.approval.settled") {
1887
+ void this.recordApprovalEvent(event.type, event.data).catch((cause) => this.reportApprovalFailure(event.run.id, cause));
1888
+ return;
1889
+ }
1821
1890
  if (event.type === FOUNDRY_CORE_COMMAND_EVENT) {
1822
1891
  void this.executeCoreCommand(event.data, event.run.id).catch((cause) => {
1823
1892
  this.observability.append({
@@ -1893,9 +1962,11 @@ var FoundryRuntime = class _FoundryRuntime {
1893
1962
  observer: this.observer,
1894
1963
  env: {
1895
1964
  [FOUNDRY_APPROVAL_DIRECTORY_ENV]: this.approvalDirectory,
1965
+ [FOUNDRY_APPROVAL_POLICY_ENV]: JSON.stringify(this.approvalPolicy),
1896
1966
  [FOUNDRY_CORE_COMMAND_DIRECTORY_ENV]: this.coreCommandDirectory,
1897
1967
  [FOUNDRY_MAILBOX_DIRECTORY_ENV]: this.mailboxDirectory,
1898
- ...this.applicationFilePath ? { [FOUNDRY_APPLICATION_ENV]: this.applicationFilePath } : {}
1968
+ ...this.applicationFilePath ? { [FOUNDRY_APPLICATION_ENV]: this.applicationFilePath } : {},
1969
+ ...options.config?.observability?.modelRequests === false ? { [FOUNDRY_MODEL_REQUESTS_ENV]: "off" } : {}
1899
1970
  }
1900
1971
  });
1901
1972
  this.scheduleAdapter = this.signalRunner.schedules;
@@ -1972,7 +2043,7 @@ var FoundryRuntime = class _FoundryRuntime {
1972
2043
  await this.reconstructActivations();
1973
2044
  this.runInBackground("signal", this.signalRunner.start());
1974
2045
  await this.reconcileApplicationConnections();
1975
- void this.redeliverInbound().then(() => this.redeliverDelegations()).then(() => this.redeliverEvents()).catch((cause) => this.reportDeliveryFailure("startup", cause));
2046
+ void this.redeliverInbound().then(() => this.redeliverDelegations()).then(() => this.redeliverThreads()).then(() => this.redeliverEvents()).then(() => this.reconcileApprovals()).catch((cause) => this.reportDeliveryFailure("startup", cause));
1976
2047
  } catch (cause) {
1977
2048
  try {
1978
2049
  await this.stop();
@@ -2358,6 +2429,8 @@ var FoundryRuntime = class _FoundryRuntime {
2358
2429
  this.validatePlaybooks(current.definitionId, playbooks, installations);
2359
2430
  const agent = Object.freeze({
2360
2431
  ...current,
2432
+ ...options.name !== void 0 ? { name: options.name } : {},
2433
+ ...options.description !== void 0 ? { description: options.description } : {},
2361
2434
  ...options.context ? { context: Object.freeze(structuredClone(options.context)) } : {},
2362
2435
  installations,
2363
2436
  playbooks,
@@ -2544,7 +2617,8 @@ var FoundryRuntime = class _FoundryRuntime {
2544
2617
  const run = await this.signalRunner.waitForRun(runId, options);
2545
2618
  return run ? this.toFoundryRun(run) : null;
2546
2619
  }
2547
- cancel(runId) {
2620
+ async cancel(runId) {
2621
+ await this.cancelApprovalsOf(runId).catch((cause) => this.reportApprovalFailure(runId, cause));
2548
2622
  return this.signalRunner.cancel(runId);
2549
2623
  }
2550
2624
  trackRunProcess(runId, state) {
@@ -2648,15 +2722,56 @@ var FoundryRuntime = class _FoundryRuntime {
2648
2722
  });
2649
2723
  return { fromRunId: runId, interrupted, run };
2650
2724
  }
2651
- listApprovals(filter = {}) {
2652
- return listFoundryApprovals(this.approvalDirectory, filter);
2725
+ async listApprovals(filter = {}) {
2726
+ if (!this.approvalPolicy.durable) return listFoundryApprovals(this.approvalDirectory, filter);
2727
+ return (await this.withApprovals(() => this.currentApprovals())).filter((item) => (!filter.runId || item.runId === filter.runId) && (!filter.status || item.status === filter.status)).sort((a, b) => a.requestedAt.localeCompare(b.requestedAt));
2728
+ }
2729
+ /** One approval: what a link to it opens. Null when there is no such approval. */
2730
+ async getApproval(approvalId) {
2731
+ if (!this.approvalPolicy.durable) {
2732
+ return (await listFoundryApprovals(this.approvalDirectory)).find((item) => item.id === approvalId) ?? null;
2733
+ }
2734
+ return (await this.withApprovals(() => this.currentApprovals())).find((item) => item.id === approvalId) ?? null;
2653
2735
  }
2736
+ /**
2737
+ * Decide an approval. When the run that asked is still waiting, it reads the
2738
+ * decision and carries on. When it is not (it suspended, timed out, or the
2739
+ * runtime restarted since), the decision goes to the conversation as a
2740
+ * durable event, and the run that takes it resumes the turn at the tool
2741
+ * call that asked: approved, the call runs; denied, it is refused.
2742
+ */
2654
2743
  async resolveApproval(approvalId, decision) {
2655
- const approval = await resolveFoundryApproval(
2656
- this.approvalDirectory,
2657
- approvalId,
2658
- decision
2659
- );
2744
+ if (!this.approvalPolicy.durable) {
2745
+ const approval = await resolveFoundryApproval(this.approvalDirectory, approvalId, decision);
2746
+ this.reportResolved(approval, decision);
2747
+ return approval;
2748
+ }
2749
+ const { decided, live } = await this.withApprovals(async () => {
2750
+ const current = (await this.currentApprovals()).find((item) => item.id === approvalId);
2751
+ if (!current) throw new Error(`Foundry approval "${approvalId}" was not found.`);
2752
+ if (current.status !== "pending") throw new Error(`Foundry approval "${approvalId}" is already ${current.status}.`);
2753
+ let waiting = false;
2754
+ if (!current.suspendedAt && await foundryApprovalRequested(this.approvalDirectory, approvalId)) {
2755
+ await resolveFoundryApproval(this.approvalDirectory, approvalId, decision).catch(() => void 0);
2756
+ waiting = !this.settledRuns.has(current.runId) && !await foundryApprovalSuspended(this.approvalDirectory, approvalId);
2757
+ }
2758
+ const decided2 = {
2759
+ ...current,
2760
+ status: decision === "approve" ? "approved" : "denied",
2761
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
2762
+ ...waiting ? {} : { suspendedAt: current.suspendedAt ?? (/* @__PURE__ */ new Date()).toISOString() }
2763
+ };
2764
+ await Effect5.runPromise(this.data.putApproval(decided2));
2765
+ return { decided: decided2, live: waiting };
2766
+ });
2767
+ this.reportResolved(decided, decision);
2768
+ if (live) return decided;
2769
+ return this.resumeApproval(decided).catch((cause) => {
2770
+ this.reportApprovalFailure(decided.runId, cause);
2771
+ return decided;
2772
+ });
2773
+ }
2774
+ reportResolved(approval, decision) {
2660
2775
  this.observability.append({
2661
2776
  type: "approval.resolved",
2662
2777
  category: "system",
@@ -2669,7 +2784,164 @@ var FoundryRuntime = class _FoundryRuntime {
2669
2784
  status: approval.status
2670
2785
  }
2671
2786
  });
2672
- return approval;
2787
+ }
2788
+ withApprovals(work) {
2789
+ const next = this.approvalWrites.then(work, work);
2790
+ this.approvalWrites = next.catch(() => void 0);
2791
+ return next;
2792
+ }
2793
+ reportApprovalFailure(runId, cause) {
2794
+ this.observability.append({
2795
+ type: "approval.failed",
2796
+ category: "system",
2797
+ runId,
2798
+ data: { error: cause instanceof Error ? cause.message : String(cause) }
2799
+ });
2800
+ }
2801
+ /** Stored approvals, expired where their time ran out, plus requests not recorded yet. Call inside withApprovals. */
2802
+ async currentApprovals() {
2803
+ const now = Date.now();
2804
+ const byId = /* @__PURE__ */ new Map();
2805
+ for (const approval of await Effect5.runPromise(this.data.listApprovals())) {
2806
+ if (approval.status === "pending" && Date.parse(approval.expiresAt) <= now) {
2807
+ const expired = { ...approval, status: "expired", resolvedAt: new Date(now).toISOString() };
2808
+ await Effect5.runPromise(this.data.putApproval(expired));
2809
+ byId.set(expired.id, expired);
2810
+ } else {
2811
+ byId.set(approval.id, approval);
2812
+ }
2813
+ }
2814
+ for (const live of await listFoundryApprovals(this.approvalDirectory)) {
2815
+ if (!byId.has(live.id)) byId.set(live.id, this.withApprovalUrl(live));
2816
+ }
2817
+ return [...byId.values()];
2818
+ }
2819
+ withApprovalUrl(approval) {
2820
+ let url;
2821
+ try {
2822
+ url = this.application.approvals?.url?.(approval) || void 0;
2823
+ } catch {
2824
+ url = void 0;
2825
+ }
2826
+ return url ? { ...approval, url } : approval;
2827
+ }
2828
+ /** What a run reported about one of its approvals, kept in the data adapter. */
2829
+ async recordApprovalEvent(type, data2) {
2830
+ if (!this.approvalPolicy.durable || !data2 || typeof data2 !== "object") return;
2831
+ await this.withApprovals(async () => {
2832
+ if (type === "foundry.approval.requested") {
2833
+ const requested = data2;
2834
+ if (typeof requested.id !== "string" || await Effect5.runPromise(this.data.getApproval(requested.id))) return;
2835
+ await Effect5.runPromise(this.data.putApproval(this.withApprovalUrl({ ...requested, status: "pending" })));
2836
+ return;
2837
+ }
2838
+ const { approvalId, status } = data2;
2839
+ if (typeof approvalId !== "string") return;
2840
+ const stored = await Effect5.runPromise(this.data.getApproval(approvalId));
2841
+ if (!stored) return;
2842
+ if (type === "foundry.approval.suspended") {
2843
+ if (!stored.suspendedAt) await Effect5.runPromise(this.data.putApproval({ ...stored, suspendedAt: (/* @__PURE__ */ new Date()).toISOString() }));
2844
+ return;
2845
+ }
2846
+ const settled = typeof status === "string" && ["approved", "denied", "expired", "cancelled"].includes(status) ? status : void 0;
2847
+ await Effect5.runPromise(this.data.putApproval({
2848
+ ...stored,
2849
+ settledInRun: true,
2850
+ ...stored.status === "pending" && settled ? { status: settled, resolvedAt: (/* @__PURE__ */ new Date()).toISOString() } : {}
2851
+ }));
2852
+ });
2853
+ }
2854
+ /**
2855
+ * A run ended. Its approvals still open no longer have anyone waiting:
2856
+ * they stay open, and a decision resumes the conversation. A decision the
2857
+ * run never read (it ended first) is handed over now.
2858
+ */
2859
+ async settleApprovalsOf(runId) {
2860
+ if (!this.approvalPolicy.durable) return;
2861
+ const owed = await this.withApprovals(async () => {
2862
+ const owed2 = [];
2863
+ for (const approval of await Effect5.runPromise(this.data.listApprovals())) {
2864
+ if (approval.runId !== runId) continue;
2865
+ if (approval.status === "pending" && !approval.suspendedAt) {
2866
+ await markFoundryApprovalSuspended(this.approvalDirectory, approval.id).catch(() => false);
2867
+ await Effect5.runPromise(this.data.putApproval({ ...approval, suspendedAt: (/* @__PURE__ */ new Date()).toISOString() }));
2868
+ } else if ((approval.status === "approved" || approval.status === "denied") && !approval.settledInRun && !approval.resumedAt) {
2869
+ owed2.push(approval);
2870
+ }
2871
+ }
2872
+ return owed2;
2873
+ });
2874
+ for (const approval of owed) await this.resumeApproval(approval);
2875
+ }
2876
+ async cancelApprovalsOf(runId) {
2877
+ if (!this.approvalPolicy.durable) return;
2878
+ await this.withApprovals(async () => {
2879
+ for (const approval of await Effect5.runPromise(this.data.listApprovals())) {
2880
+ if (approval.runId !== runId || approval.status !== "pending") continue;
2881
+ if (await foundryApprovalRequested(this.approvalDirectory, approval.id) && !await readFoundryApprovalResolution(this.approvalDirectory, approval.id)) {
2882
+ await resolveFoundryApproval(this.approvalDirectory, approval.id, "deny").catch(() => void 0);
2883
+ }
2884
+ await Effect5.runPromise(this.data.putApproval({ ...approval, status: "cancelled", resolvedAt: (/* @__PURE__ */ new Date()).toISOString(), settledInRun: true }));
2885
+ }
2886
+ });
2887
+ }
2888
+ /** After a restart: open approvals have no run waiting, and decided ones may still be owed. */
2889
+ async reconcileApprovals() {
2890
+ if (!this.approvalPolicy.durable) return;
2891
+ const owed = await this.withApprovals(async () => {
2892
+ const owed2 = [];
2893
+ for (const approval of await this.currentApprovals()) {
2894
+ if (approval.status === "pending" && !approval.suspendedAt) {
2895
+ await Effect5.runPromise(this.data.putApproval({ ...approval, suspendedAt: (/* @__PURE__ */ new Date()).toISOString() }));
2896
+ } else if ((approval.status === "approved" || approval.status === "denied") && !approval.settledInRun && !approval.resumedAt) {
2897
+ owed2.push(approval);
2898
+ }
2899
+ }
2900
+ return owed2;
2901
+ });
2902
+ for (const approval of owed) await this.resumeApproval(approval).catch((cause) => this.reportApprovalFailure(approval.runId, cause));
2903
+ }
2904
+ /**
2905
+ * Hand a decision to the conversation that asked, as a durable event. The
2906
+ * run that takes it resumes the turn at the waiting tool call. If the
2907
+ * conversation moved on, the event tells the agent what was decided.
2908
+ */
2909
+ async resumeApproval(approval) {
2910
+ const approved = approval.status === "approved";
2911
+ const content = approved ? `The person approved your earlier request to run ${approval.toolName} (approval ${approval.id}). It has not run yet. To do it now, call ${approval.toolName} again with the same input.` : `The person denied your earlier request to run ${approval.toolName} (approval ${approval.id}). Do not run it.`;
2912
+ const receipt = await this.emitEvent(
2913
+ { agentId: approval.agentId, conversationId: approval.conversationId },
2914
+ {
2915
+ id: `approval:${approval.id}`,
2916
+ source: "foundry:approval",
2917
+ kind: "approval.decided",
2918
+ content,
2919
+ metadata: {
2920
+ approval: {
2921
+ id: approval.id,
2922
+ toolName: approval.toolName,
2923
+ toolInput: approval.toolInput,
2924
+ status: approval.status,
2925
+ ...approval.toolCallId ? { toolCallId: approval.toolCallId } : {}
2926
+ }
2927
+ }
2928
+ },
2929
+ { whenIdle: "wake" }
2930
+ );
2931
+ const resumed = {
2932
+ ...approval,
2933
+ resumedAt: (/* @__PURE__ */ new Date()).toISOString(),
2934
+ ...receipt.runId ? { resumeRunId: receipt.runId } : {}
2935
+ };
2936
+ await this.withApprovals(() => Effect5.runPromise(this.data.putApproval(resumed)));
2937
+ this.observability.append({
2938
+ type: "approval.resumed",
2939
+ category: "system",
2940
+ agent: approval.definitionId,
2941
+ runId: receipt.runId ?? approval.runId,
2942
+ data: { approvalId: approval.id, toolName: approval.toolName, status: approval.status }
2943
+ });
2944
+ return resumed;
2673
2945
  }
2674
2946
  capabilityManifest(definitionId) {
2675
2947
  if (!this.compositionByDefinition.has(definitionId)) {
@@ -3331,7 +3603,9 @@ var FoundryRuntime = class _FoundryRuntime {
3331
3603
  (route) => route.transmissionId === requirement.playbook.transmissionId && (!requirement.playbook.match?.routeIds || requirement.playbook.match.routeIds.includes(route.id))
3332
3604
  );
3333
3605
  for (const route of matchingRoutes) {
3334
- const account = route.accountId ? this.application.accounts?.find((candidate) => candidate.id === route.accountId) : void 0;
3606
+ const account = route.accountId ? await this.services.runPromise(Effect5.gen(function* () {
3607
+ return yield* (yield* AccountDirectory).get(route.accountId);
3608
+ })).catch(() => void 0) : void 0;
3335
3609
  const id2 = [
3336
3610
  requirement.definitionId,
3337
3611
  requirement.workspaceId,
@@ -3684,7 +3958,7 @@ var FoundryRuntime = class _FoundryRuntime {
3684
3958
  }
3685
3959
  /** Take back deliveries a listener did not read, to deliver as a run. */
3686
3960
  async reclaimMailbox(conversationId) {
3687
- const deliveries = await drainMailbox(this.mailboxDirectory, conversationId);
3961
+ const deliveries = (await drainMailbox(this.mailboxDirectory, conversationId)).filter((delivery) => !(delivery.kind === "mesh" && delivery.message.kind === "ack"));
3688
3962
  if (deliveries.length === 0) return;
3689
3963
  const target = await this.deliveryTargetFor(conversationId);
3690
3964
  if (!target) return;
@@ -3895,6 +4169,7 @@ var FoundryRuntime = class _FoundryRuntime {
3895
4169
  /** Clear the bookkeeping that lets a restart hand these deliveries over again. */
3896
4170
  async markLegacyHandedOver(deliveries, runId) {
3897
4171
  for (const delivery of deliveries) {
4172
+ if (delivery.kind === "mesh") continue;
3898
4173
  if (delivery.kind === "transmission" || delivery.kind === "agent-message") {
3899
4174
  await this.assignPendingInbound(delivery.pendingId, runId);
3900
4175
  } else if (delivery.kind === "reply") {
@@ -4234,7 +4509,331 @@ var FoundryRuntime = class _FoundryRuntime {
4234
4509
  });
4235
4510
  }
4236
4511
  /** Report a worker's finished run back to whoever delegated to it. */
4512
+ // ── Mesh ────────────────────────────────────────────────────────────────
4513
+ //
4514
+ // Foundry hosts Glove Mesh for agents that are peers: existing instances in
4515
+ // one workspace, addressed by instance id. A new message starts a thread: a
4516
+ // conversation on the recipient whose context carries the record. Messages
4517
+ // travel as "mesh" deliveries on the same durable path as delegation
4518
+ // updates: into the run working on that conversation, or as one run once it
4519
+ // is free. The recipient's final reply goes back on its own.
4520
+ /** Every thread, newest first, optionally narrowed to who started it or who it went to. */
4521
+ async listThreads(filter = {}) {
4522
+ const found = [];
4523
+ for (const agent of await Effect5.runPromise(this.data.listAgents())) {
4524
+ if (filter.to && agent.id !== filter.to) continue;
4525
+ for (const conversation of await Effect5.runPromise(this.data.listConversations(agent.id))) {
4526
+ const thread = threadFromContext(conversation.context);
4527
+ if (!thread || thread.to.agentId !== agent.id || thread.id !== conversation.id) continue;
4528
+ if (filter.agentId && thread.from.agentId !== filter.agentId) continue;
4529
+ if (filter.conversationId && thread.from.conversationId !== filter.conversationId) continue;
4530
+ if (filter.status && thread.status !== filter.status) continue;
4531
+ found.push(thread);
4532
+ }
4533
+ }
4534
+ return found.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
4535
+ }
4536
+ /**
4537
+ * Older thread records kept their own lists of messages not handed over yet.
4538
+ * Move them to the event journal once; message ids keep a retry from
4539
+ * delivering twice.
4540
+ */
4541
+ async redeliverThreads() {
4542
+ for (const thread of await this.listThreads()) {
4543
+ if (!thread.undelivered?.length && !thread.pending?.length) continue;
4544
+ if (thread.undelivered?.length) await this.deliverMesh(this.starterTarget(thread), "starter", thread.undelivered);
4545
+ if (thread.pending?.length) await this.deliverMesh(this.recipientTarget(thread), "recipient", thread.pending);
4546
+ await this.updateThread(thread.id, { status: thread.status });
4547
+ }
4548
+ }
4549
+ /** The open threads a conversation started, oldest first. */
4550
+ async openThreadsFrom(conversation) {
4551
+ const open = [];
4552
+ for (const id2 of startedThreadIds(conversation.context)) {
4553
+ const thread = await this.loadThread(id2);
4554
+ if (thread && thread.from.conversationId === conversation.id && isOpenThread(thread)) open.push(thread);
4555
+ }
4556
+ return open.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
4557
+ }
4558
+ async loadThread(id2) {
4559
+ const conversation = await Effect5.runPromise(this.data.getConversation(id2));
4560
+ return threadFromContext(conversation?.context) ?? null;
4561
+ }
4562
+ updateThread(id2, change) {
4563
+ return this.inConversation(`record:${id2}`, async () => {
4564
+ const conversation = await Effect5.runPromise(this.data.getConversation(id2));
4565
+ const current = threadFromContext(conversation?.context);
4566
+ if (!conversation || !current) return null;
4567
+ const patch = typeof change === "function" ? change(current) : change;
4568
+ if (Object.keys(patch).length === 0) return current;
4569
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4570
+ const merged = { ...current, ...patch, updatedAt: now };
4571
+ delete merged.undelivered;
4572
+ delete merged.pending;
4573
+ for (const key of Object.keys(merged)) if (merged[key] === void 0) delete merged[key];
4574
+ const next = Object.freeze(merged);
4575
+ await Effect5.runPromise(this.data.putConversation(Object.freeze({
4576
+ ...conversation,
4577
+ context: Object.freeze({ ...conversation.context, meshThread: next }),
4578
+ updatedAt: now
4579
+ })));
4580
+ return next;
4581
+ });
4582
+ }
4583
+ starterTarget(thread) {
4584
+ return {
4585
+ definitionId: thread.from.definitionId,
4586
+ agentId: thread.from.agentId,
4587
+ conversationId: thread.from.conversationId,
4588
+ workspaceId: thread.workspaceId
4589
+ };
4590
+ }
4591
+ recipientTarget(thread) {
4592
+ return {
4593
+ definitionId: thread.to.definitionId,
4594
+ agentId: thread.to.agentId,
4595
+ conversationId: thread.id,
4596
+ workspaceId: thread.workspaceId
4597
+ };
4598
+ }
4599
+ /**
4600
+ * Hand mesh messages to one side of a thread. Messages, replies and
4601
+ * failures go through durable delivery. A read receipt only ever reaches a
4602
+ * run that is listening, and is dropped otherwise.
4603
+ */
4604
+ async deliverMesh(target, side, messages) {
4605
+ const delivery = (message) => ({ kind: "mesh", side, message, deliveryId: message.id });
4606
+ const receipts = messages.filter((message) => message.kind === "ack");
4607
+ if (receipts.length) {
4608
+ await this.inConversation(target.conversationId, async () => {
4609
+ if (!this.conversationListeners.has(target.conversationId)) return;
4610
+ for (const message of receipts) await writeMailboxDelivery(this.mailboxDirectory, target.conversationId, delivery(message));
4611
+ });
4612
+ }
4613
+ const durable = messages.filter((message) => message.kind !== "ack");
4614
+ if (durable.length) await this.deliver(target, durable.map(delivery));
4615
+ }
4616
+ /** A run's mesh call: answered through its request, so the tool hears the outcome. */
4617
+ async runMeshCommand(command, parentRunId) {
4618
+ const request = await getFoundryCoreCommandRequest(this.coreCommandDirectory, command.id);
4619
+ if (!request) {
4620
+ await this.executeMeshCommand(command, parentRunId);
4621
+ return;
4622
+ }
4623
+ if (!await claimFoundryCoreCommandRequest(this.coreCommandDirectory, command.id)) return;
4624
+ try {
4625
+ if (request.runId !== parentRunId) throw new Error("This mesh call does not belong to this run.");
4626
+ const output = await this.executeMeshCommand(command, parentRunId);
4627
+ await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "success", output });
4628
+ } catch (cause) {
4629
+ const error = cause instanceof Error ? cause.message : String(cause);
4630
+ this.observability.append({
4631
+ type: "mesh.refused",
4632
+ category: "system",
4633
+ agent: command.definitionId,
4634
+ runId: parentRunId,
4635
+ data: { type: command.type, error }
4636
+ });
4637
+ await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "error", error });
4638
+ }
4639
+ }
4640
+ /** The agents an agent may see and message: its workspace, narrowed by its definition's rule. */
4641
+ async meshPeers(sender) {
4642
+ const peers = hostedMeshOptions(this.byRoute.get(sender.definitionId)?.definition.mesh)?.peers;
4643
+ return (await Effect5.runPromise(this.data.listAgents())).filter((agent) => agent.workspaceId === sender.workspaceId && agent.id !== sender.id && this.byRoute.has(agent.definitionId) && (peers?.(sender, agent) ?? true));
4644
+ }
4645
+ async executeMeshCommand(command, parentRunId) {
4646
+ const sender = await Effect5.runPromise(this.data.getAgent(command.agentId));
4647
+ if (!sender || sender.workspaceId !== command.workspaceId) {
4648
+ throw new Error("A mesh call must come from an agent instance in its workspace.");
4649
+ }
4650
+ if (command.type === "mesh.list") {
4651
+ const filter = command.name?.toLowerCase();
4652
+ return (await this.meshPeers(sender)).map(meshIdentity).filter((identity) => !filter || identity.name.toLowerCase().includes(filter));
4653
+ }
4654
+ const conversation = await Effect5.runPromise(this.data.getConversation(command.conversationId));
4655
+ if (!conversation || conversation.agentId !== sender.id) {
4656
+ throw new Error("A mesh call must come from one of the agent's own conversations.");
4657
+ }
4658
+ const own = threadFromContext(conversation.context);
4659
+ const ownThread = own && own.id === conversation.id && own.to.agentId === sender.id ? own : void 0;
4660
+ const startedThreads = async () => {
4661
+ const threads = [];
4662
+ for (const id2 of startedThreadIds(conversation.context)) {
4663
+ const thread2 = await this.loadThread(id2);
4664
+ if (thread2 && thread2.from.conversationId === conversation.id) threads.push(thread2);
4665
+ }
4666
+ return threads;
4667
+ };
4668
+ if (command.type === "mesh.ack") {
4669
+ const thread2 = ownThread?.messageIds.includes(command.messageId) ? ownThread : (await startedThreads()).find((item) => item.messageIds.includes(command.messageId));
4670
+ if (!thread2) throw new Error(`There is no message "${command.messageId}" in your threads.`);
4671
+ const toStarter = thread2.id === ownThread?.id;
4672
+ await this.deliverMesh(toStarter ? this.starterTarget(thread2) : this.recipientTarget(thread2), toStarter ? "starter" : "recipient", [{
4673
+ kind: "ack",
4674
+ id: newMessageId(),
4675
+ threadId: thread2.id,
4676
+ from: { agentId: sender.id, name: sender.name ?? sender.id },
4677
+ to: toStarter ? thread2.from.agentId : thread2.to.agentId,
4678
+ content: command.note,
4679
+ inReplyTo: command.messageId,
4680
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4681
+ }]);
4682
+ return { acknowledged: command.messageId };
4683
+ }
4684
+ const { message: input } = command;
4685
+ const message = (threadId) => ({
4686
+ kind: "message",
4687
+ id: input.id,
4688
+ threadId,
4689
+ from: { agentId: sender.id, name: sender.name ?? sender.id },
4690
+ to: input.to,
4691
+ content: input.content,
4692
+ ...input.inReplyTo ? { inReplyTo: input.inReplyTo } : {},
4693
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4694
+ });
4695
+ const sent = (thread2, direction) => {
4696
+ this.observability.append({
4697
+ type: direction === "new" ? "mesh.thread.started" : "mesh.message.sent",
4698
+ category: "system",
4699
+ agent: command.definitionId,
4700
+ runId: parentRunId,
4701
+ data: { threadId: thread2.id, messageId: input.id, from: sender.id, to: input.to }
4702
+ });
4703
+ return { messageId: input.id, threadId: thread2.id, to: input.to, direction };
4704
+ };
4705
+ if (ownThread && input.to === ownThread.from.agentId && (!input.inReplyTo || ownThread.messageIds.includes(input.inReplyTo))) {
4706
+ const outgoing2 = message(ownThread.id);
4707
+ await this.updateThread(ownThread.id, (current) => ({
4708
+ status: "waiting",
4709
+ question: outgoing2.content,
4710
+ messageIds: [...current.messageIds, outgoing2.id]
4711
+ }));
4712
+ await this.deliverMesh(this.starterTarget(ownThread), "starter", [outgoing2]);
4713
+ return sent(ownThread, "to-starter");
4714
+ }
4715
+ if (input.inReplyTo) {
4716
+ const thread2 = (await startedThreads()).find((item) => item.to.agentId === input.to && item.messageIds.includes(input.inReplyTo));
4717
+ if (!thread2) {
4718
+ throw new Error(`There is no message "${input.inReplyTo}" in your threads with "${input.to}". Leave in_reply_to out to start a new thread.`);
4719
+ }
4720
+ const outgoing2 = message(thread2.id);
4721
+ await this.updateThread(thread2.id, (current) => ({
4722
+ status: "working",
4723
+ question: void 0,
4724
+ messageIds: [...current.messageIds, outgoing2.id]
4725
+ }));
4726
+ await this.deliverMesh(this.recipientTarget(thread2), "recipient", [outgoing2]);
4727
+ return sent(thread2, "to-recipient");
4728
+ }
4729
+ if (!isThreadId(input.threadId)) throw new Error(`"${input.threadId}" is not a thread id.`);
4730
+ if (input.to === sender.id) throw new Error("That is you.");
4731
+ const recipient = (await this.meshPeers(sender)).find((agent) => agent.id === input.to);
4732
+ if (!recipient) {
4733
+ throw new Error(`There is no agent "${input.to}" you can message. Use glove_mesh_list_agents to see who there is.`);
4734
+ }
4735
+ const outgoing = message(input.threadId);
4736
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4737
+ const thread = Object.freeze({
4738
+ id: input.threadId,
4739
+ workspaceId: sender.workspaceId,
4740
+ from: Object.freeze({
4741
+ agentId: sender.id,
4742
+ name: sender.name ?? sender.id,
4743
+ definitionId: sender.definitionId,
4744
+ conversationId: conversation.id,
4745
+ runId: parentRunId
4746
+ }),
4747
+ to: Object.freeze({
4748
+ agentId: recipient.id,
4749
+ name: recipient.name ?? recipient.id,
4750
+ definitionId: recipient.definitionId
4751
+ }),
4752
+ subject: threadSubject(outgoing.content),
4753
+ status: "working",
4754
+ messageIds: Object.freeze([outgoing.id]),
4755
+ createdAt: now,
4756
+ updatedAt: now
4757
+ });
4758
+ await this.createConversation(recipient.id, {
4759
+ id: thread.id,
4760
+ workspaceId: sender.workspaceId,
4761
+ title: `${thread.from.name}: ${clipTitle(outgoing.content)}`,
4762
+ context: { meshThread: thread }
4763
+ });
4764
+ await this.inConversation(`record:${conversation.id}`, async () => {
4765
+ const current = await Effect5.runPromise(this.data.getConversation(conversation.id));
4766
+ if (!current) return;
4767
+ await Effect5.runPromise(this.data.putConversation({
4768
+ ...current,
4769
+ context: Object.freeze({
4770
+ ...current.context,
4771
+ meshThreads: [...startedThreadIds(current.context), thread.id]
4772
+ }),
4773
+ updatedAt: now
4774
+ }));
4775
+ });
4776
+ await this.deliverMesh(this.recipientTarget(thread), "recipient", [outgoing]);
4777
+ return sent(thread, "new");
4778
+ }
4779
+ /** When the recipient's run on a thread ends, its reply (or its failure) goes back. */
4780
+ async settleThread(event, run, steered) {
4781
+ const thread = await this.loadThread(run.conversationId);
4782
+ if (!thread || run.agentId !== thread.to.agentId) return;
4783
+ if (this.stopping && event.status !== "completed") return;
4784
+ const reply = (kind, content) => ({
4785
+ kind,
4786
+ id: `msg_${kind}_${event.run.id}`,
4787
+ threadId: thread.id,
4788
+ from: { agentId: thread.to.agentId, name: thread.to.name },
4789
+ to: thread.from.agentId,
4790
+ content,
4791
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4792
+ });
4793
+ if (event.status === "completed") {
4794
+ const output = parseJson(event.output);
4795
+ if (output?.status === "suspended") return;
4796
+ const text = deliveryText(output?.value);
4797
+ if (!text.trim()) {
4798
+ await this.updateThread(thread.id, { status: "replied", question: void 0 });
4799
+ return;
4800
+ }
4801
+ const message2 = reply("reply", text);
4802
+ await this.updateThread(thread.id, (current) => ({
4803
+ status: "replied",
4804
+ reply: text,
4805
+ question: void 0,
4806
+ messageIds: current.messageIds.includes(message2.id) ? current.messageIds : [...current.messageIds, message2.id]
4807
+ }));
4808
+ await this.deliverMesh(this.starterTarget(thread), "starter", [message2]);
4809
+ this.observability.append({
4810
+ type: "mesh.thread.replied",
4811
+ category: "system",
4812
+ agent: thread.to.definitionId,
4813
+ runId: event.run.id,
4814
+ data: { threadId: thread.id }
4815
+ });
4816
+ return;
4817
+ }
4818
+ if (event.status === "cancelled" && steered) return;
4819
+ const error = event.status === "cancelled" ? "The work was cancelled." : event.error ?? "The run failed.";
4820
+ const message = reply("failed", error);
4821
+ await this.updateThread(thread.id, (current) => ({
4822
+ status: event.status === "cancelled" ? "cancelled" : "failed",
4823
+ error,
4824
+ messageIds: current.messageIds.includes(message.id) ? current.messageIds : [...current.messageIds, message.id]
4825
+ }));
4826
+ await this.deliverMesh(this.starterTarget(thread), "starter", [message]);
4827
+ this.observability.append({
4828
+ type: event.status === "cancelled" ? "mesh.thread.cancelled" : "mesh.thread.failed",
4829
+ category: "system",
4830
+ agent: thread.to.definitionId,
4831
+ runId: event.run.id,
4832
+ data: { threadId: thread.id, error }
4833
+ });
4834
+ }
4237
4835
  async handleRunSettled(event) {
4836
+ void this.settleApprovalsOf(event.run.id).catch((cause) => this.reportApprovalFailure(event.run.id, cause));
4238
4837
  this.releaseConversationRun(event.run.id);
4239
4838
  void this.waitForRunProcessRelease(this.toFoundryRun(event.run), event.route).finally(() => this.gate.settled(event.run.id));
4240
4839
  const finishDelivery = async () => {
@@ -4248,6 +4847,11 @@ var FoundryRuntime = class _FoundryRuntime {
4248
4847
  };
4249
4848
  const steered = this.steeredRuns.delete(event.run.id);
4250
4849
  const run = this.toFoundryRun(event.run);
4850
+ if (run.conversationId && isThreadId(run.conversationId)) {
4851
+ await finishDelivery();
4852
+ await this.settleThread(event, run, steered);
4853
+ return;
4854
+ }
4251
4855
  if (!run.conversationId || !isDelegationId(run.conversationId)) {
4252
4856
  await finishDelivery();
4253
4857
  return;
@@ -4364,6 +4968,10 @@ var FoundryRuntime = class _FoundryRuntime {
4364
4968
  return this.executeCoreCommandUnlocked(command, parentRunId);
4365
4969
  }
4366
4970
  async executeCoreCommandUnlocked(command, parentRunId) {
4971
+ if (isMeshCommand(command)) {
4972
+ await this.runMeshCommand(command, parentRunId);
4973
+ return;
4974
+ }
4367
4975
  if (command.type === "agent.message") {
4368
4976
  try {
4369
4977
  const output = await this.executeAgentMessage(command);
@@ -4791,7 +5399,11 @@ var FoundryRuntime = class _FoundryRuntime {
4791
5399
  kind: "signal",
4792
5400
  target: discovered.executionName,
4793
5401
  ...activation.timing.kind === "every" ? { interval: `${activation.timing.intervalMs}ms` } : { cron: activation.timing.expression, timezone: activation.timing.timezone },
4794
- overlapPolicy: "skip",
5402
+ // Station checks overlap per signal, and a signal is a whole
5403
+ // definition: "skip" would drop one agent's run because another
5404
+ // agent of the same definition is busy. Runs overlap like messages
5405
+ // do, and the conversation gate still runs one at a time per conversation.
5406
+ overlapPolicy: "allow",
4795
5407
  misfirePolicy: "fire-once",
4796
5408
  misfireGraceMs: 6e4,
4797
5409
  input: await this.executionEnvelope(request),
@@ -4933,6 +5545,7 @@ var FoundryRuntime = class _FoundryRuntime {
4933
5545
  }
4934
5546
  const activations = (await Effect5.runPromise(this.data.listActivations(request.workspaceId))).filter((activation) => activation.agentId === request.agentId);
4935
5547
  const delegations = await this.openDelegationsFrom(request.agentId, request.conversationId);
5548
+ const threads = await this.openThreadsFrom(conversation);
4936
5549
  return {
4937
5550
  [FOUNDRY_EXECUTION_MARKER]: true,
4938
5551
  request: { ...request, context: { ...request.context, durableMemoryOwners: owners } },
@@ -4941,6 +5554,7 @@ var FoundryRuntime = class _FoundryRuntime {
4941
5554
  conversation,
4942
5555
  activations,
4943
5556
  delegations,
5557
+ threads,
4944
5558
  events: options.leased && this.data.listEvents ? (await Effect5.runPromise(this.data.listEvents())).filter((record) => record.status === "pending" && record.target.agentId === agent.id && record.target.conversationId === conversation.id).map((record) => ({ ...record.delivery, durable: { id: record.id, event: record.event, policy: record.policy } })) : [],
4945
5559
  ...options.leased ? { conversationLease: true } : {}
4946
5560
  };
@@ -5004,7 +5618,13 @@ var PHOSPHOR_ICON_PATHS = {
5004
5618
  refresh: "M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z",
5005
5619
  warning: "M236.8,188.09,149.35,36.22h0a24.76,24.76,0,0,0-42.7,0L19.2,188.09a23.51,23.51,0,0,0,0,23.72A24.35,24.35,0,0,0,40.55,224h174.9a24.35,24.35,0,0,0,21.33-12.19A23.51,23.51,0,0,0,236.8,188.09ZM222.93,203.8a8.5,8.5,0,0,1-7.48,4.2H40.55a8.5,8.5,0,0,1-7.48-4.2,7.59,7.59,0,0,1,0-7.72L120.52,44.21a8.75,8.75,0,0,1,15,0l87.45,151.87A7.59,7.59,0,0,1,222.93,203.8ZM120,144V104a8,8,0,0,1,16,0v40a8,8,0,0,1-16,0Zm20,36a12,12,0,1,1-12-12A12,12,0,0,1,140,180Z",
5006
5620
  caretDown: "M213.66,101.66l-80,80a8,8,0,0,1-11.32,0l-80-80A8,8,0,0,1,53.66,90.34L128,164.69l74.34-74.35a8,8,0,0,1,11.32,11.32Z",
5007
- funnel: "M200,136a8,8,0,0,1-8,8H64a8,8,0,0,1,0-16H192A8,8,0,0,1,200,136Zm32-56H24a8,8,0,0,0,0,16H232a8,8,0,0,0,0-16Zm-80,96H104a8,8,0,0,0,0,16h48a8,8,0,0,0,0-16Z"
5621
+ funnel: "M200,136a8,8,0,0,1-8,8H64a8,8,0,0,1,0-16H192A8,8,0,0,1,200,136Zm32-56H24a8,8,0,0,0,0,16H232a8,8,0,0,0,0-16Zm-80,96H104a8,8,0,0,0,0,16h48a8,8,0,0,0,0-16Z",
5622
+ download: "M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0Zm-101.66,5.66a8,8,0,0,0,11.32,0l40-40a8,8,0,0,0-11.32-11.32L136,124.69V32a8,8,0,0,0-16,0v92.69L93.66,98.34a8,8,0,0,0-11.32,11.32Z",
5623
+ terminal: "M128,128a8,8,0,0,1-3,6.25l-40,32a8,8,0,1,1-10-12.5L107.19,128,75,102.25a8,8,0,1,1,10-12.5l40,32A8,8,0,0,1,128,128Zm48,24H136a8,8,0,0,0,0,16h40a8,8,0,0,0,0-16Zm56-96V200a16,16,0,0,1-16,16H40a16,16,0,0,1-16-16V56A16,16,0,0,1,40,40H216A16,16,0,0,1,232,56ZM216,200V56H40V200H216Z",
5624
+ network: "M117.66,170.34a8,8,0,0,1,0,11.32l-32,32a8,8,0,0,1-11.32,0l-32-32a8,8,0,0,1,11.32-11.32L72,188.69V48a8,8,0,0,1,16,0V188.69l18.34-18.35A8,8,0,0,1,117.66,170.34Zm96-96-32-32a8,8,0,0,0-11.32,0l-32,32a8,8,0,0,0,11.32,11.32L168,67.31V208a8,8,0,0,0,16,0V67.31l18.34,18.35a8,8,0,0,0,11.32-11.32Z",
5625
+ context: "M160,112h48a16,16,0,0,0,16-16V48a16,16,0,0,0-16-16H160a16,16,0,0,0-16,16V64H128a24,24,0,0,0-24,24v32H72v-8A16,16,0,0,0,56,96H24A16,16,0,0,0,8,112v32a16,16,0,0,0,16,16H56a16,16,0,0,0,16-16v-8h32v32a24,24,0,0,0,24,24h16v16a16,16,0,0,0,16,16h48a16,16,0,0,0,16-16V160a16,16,0,0,0-16-16H160a16,16,0,0,0-16,16v16H128a8,8,0,0,1-8-8V88a8,8,0,0,1,8-8h16V96A16,16,0,0,0,160,112ZM56,144H24V112H56v32Zm104,16h48v48H160Zm0-112h48V96H160Z",
5626
+ memory: "M248,124a56.11,56.11,0,0,0-32-50.61V72a48,48,0,0,0-88-26.49A48,48,0,0,0,40,72v1.39a56,56,0,0,0,0,101.2V176a48,48,0,0,0,88,26.49A48,48,0,0,0,216,176v-1.41A56.09,56.09,0,0,0,248,124ZM88,208a32,32,0,0,1-31.81-28.56A55.87,55.87,0,0,0,64,180h8a8,8,0,0,0,0-16H64A40,40,0,0,1,50.67,86.27,8,8,0,0,0,56,78.73V72a32,32,0,0,1,64,0v68.26A47.8,47.8,0,0,0,88,128a8,8,0,0,0,0,16,32,32,0,0,1,0,64Zm104-44h-8a8,8,0,0,0,0,16h8a55.87,55.87,0,0,0,7.81-.56A32,32,0,1,1,168,144a8,8,0,0,0,0-16,47.8,47.8,0,0,0-32,12.26V72a32,32,0,0,1,64,0v6.73a8,8,0,0,0,5.33,7.54A40,40,0,0,1,192,164Zm16-52a8,8,0,0,1-8,8h-4a36,36,0,0,1-36-36V80a8,8,0,0,1,16,0v4a20,20,0,0,0,20,20h4A8,8,0,0,1,208,112ZM60,120H56a8,8,0,0,1,0-16h4A20,20,0,0,0,80,84V80a8,8,0,0,1,16,0v4A36,36,0,0,1,60,120Z",
5627
+ list: "M80,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H88A8,8,0,0,1,80,64Zm136,56H88a8,8,0,0,0,0,16H216a8,8,0,0,0,0-16Zm0,64H88a8,8,0,0,0,0,16H216a8,8,0,0,0,0-16ZM44,52A12,12,0,1,0,56,64,12,12,0,0,0,44,52Zm0,64a12,12,0,1,0,12,12A12,12,0,0,0,44,116Zm0,64a12,12,0,1,0,12,12A12,12,0,0,0,44,180Z"
5008
5628
  };
5009
5629
  function renderPhosphorIcon(name, className = "icon") {
5010
5630
  return `<svg class="${className}" data-phosphor="${name}" viewBox="0 0 256 256" fill="currentColor" aria-hidden="true"><path d="${PHOSPHOR_ICON_PATHS[name]}"/></svg>`;
@@ -5015,11 +5635,1025 @@ function renderGloveMark() {
5015
5635
  return `<svg class="brand-mark" data-brand="glove" viewBox="0 0 1024 1024" fill="none" aria-hidden="true"><path d="${GLOVE_HAND_PATH}" fill="currentColor"/><path d="${GLOVE_CUFF_PATH}" fill="currentColor"/></svg>`;
5016
5636
  }
5017
5637
 
5638
+ // src/dashboard-run.ts
5639
+ var DASHBOARD_RUN_SCRIPT = String.raw`
5640
+ 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"]];
5641
+ function runView(){
5642
+ const params=new URLSearchParams(location.search);const tab=params.get("tab");
5643
+ 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")||""};
5644
+ }
5645
+ function setRunView(patch){
5646
+ const params=new URLSearchParams(location.search);
5647
+ Object.entries(patch).forEach(([key,value])=>{if(value)params.set(key,value);else params.delete(key)});
5648
+ if(params.get("tab")==="network")params.delete("tab");
5649
+ const search=params.toString();history.replaceState({},"",location.pathname+(search?"?"+search:""));
5650
+ }
5651
+ async function ensureRunEvents(id){
5652
+ const cached=state.runEvents[id];
5653
+ const after=cached&&cached.length?cached[cached.length-1].sequence:null;
5654
+ const fresh=await api("/api/runs/"+encodeURIComponent(id)+"/events"+(after===null?"":"?after="+after));
5655
+ state.runEvents[id]=after===null?fresh:cached.concat(fresh);
5656
+ }
5657
+ function runEventsFor(id){return state.runEvents[id]||eventsFor(id)}
5658
+ function fmtTokens(value){const n=Number(value);if(!Number.isFinite(n))return"—";if(n<1000)return String(n);if(n<1e6)return(n/1000).toFixed(n<10000?1:0)+"k";return(n/1e6).toFixed(1)+"M"}
5659
+ function jsonSize(value){try{return(JSON.stringify(value)??"").length}catch{return 0}}
5660
+ function isoAt(ms){return Number.isFinite(ms)?new Date(ms).toISOString():""}
5661
+ function offsetFrom(base,iso){const at=new Date(iso).getTime();return Number.isFinite(base)&&Number.isFinite(at)?"+"+durationText(Math.max(0,at-base)):""}
5662
+
5663
+ /* ---- A JSON tree, like DevTools': collapsed past two levels, strings that hold JSON opened up. ---- */
5664
+ function jsonTree(value,key,depth){
5665
+ depth=depth||0;
5666
+ if(value===undefined)return'<span class="jv null">not recorded</span>';
5667
+ if(value===null)return'<span class="jv null">null</span>';
5668
+ if(typeof value==="string"){
5669
+ const text=value.trim();
5670
+ if(depth===0&&/^[\[{]/.test(text)){try{return'<span class="jv-note">JSON in a string</span>'+jsonTree(JSON.parse(text),key,0)}catch{}}
5671
+ return'<span class="jv str">"'+esc(value)+'"</span>';
5672
+ }
5673
+ if(typeof value==="number")return'<span class="jv num">'+esc(value)+'</span>';
5674
+ if(typeof value==="boolean")return'<span class="jv bool">'+value+'</span>';
5675
+ const isArray=Array.isArray(value);const entries=isArray?value.map((item,index)=>[index,item]):Object.entries(value);
5676
+ if(!entries.length)return'<span class="jv">'+(isArray?"[]":"{}")+'</span>';
5677
+ const preview=isArray?"Array("+entries.length+")":"{"+entries.slice(0,4).map(entry=>esc(entry[0])).join(", ")+(entries.length>4?", …":"")+"}";
5678
+ return'<details class="jt" data-persist="jt:'+attr(key)+'"'+(depth<2?" open":"")+'><summary>'+preview+'</summary><div class="jt-body">'
5679
+ +entries.slice(0,400).map(entry=>'<div class="jt-row"><span class="jk">'+esc(entry[0])+'</span>: '+jsonTree(entry[1],key+"."+entry[0],depth+1)+'</div>').join("")
5680
+ +(entries.length>400?'<div class="muted">… '+(entries.length-400)+' more</div>':"")+'</div></details>';
5681
+ }
5682
+ function jsonBlock(value,key){return'<div class="jt-root">'+jsonTree(value,key)+'</div>'}
5683
+
5684
+ /* ---- Messages as the model received them. ---- */
5685
+ function traceRole(message){
5686
+ if(message.framework_context==="runtime")return{label:"Runtime context",cls:"runtime"};
5687
+ if(message.framework_context==="inbox")return{label:"Inbox",cls:"runtime"};
5688
+ if(message.is_compaction)return{label:"Compaction summary",cls:"system"};
5689
+ if(message.is_compaction_request)return{label:"Compaction request",cls:"system"};
5690
+ if(message.is_skill_injection)return{label:"Skill",cls:"system"};
5691
+ if(message.sender==="user"&&(message.tool_results||[]).length)return{label:"Tool results",cls:"tool"};
5692
+ return message.sender==="user"?{label:"User",cls:"user"}:{label:"Agent",cls:"agent"};
5693
+ }
5694
+ function traceMessageHtml(message,key,isNew){
5695
+ if(!message)return'<article class="tm missing"><header><span class="tm-role">Not retained</span></header><p class="tm-note">An earlier request recorded this message, and its events are no longer retained.</p></article>';
5696
+ const role=traceRole(message);let body="";
5697
+ const toolText=(message.tool_results||[]).length&&message.text==="tool results";
5698
+ if(message.text&&!toolText)body+='<div class="tm-text">'+esc(message.text)+'</div>';
5699
+ if(message.text_chars)body+='<p class="tm-note">Recorded the first '+esc(message.text.length.toLocaleString())+' of '+esc(message.text_chars.toLocaleString())+' characters.</p>';
5700
+ const media=(message.content||[]).filter(part=>part.type!=="text");
5701
+ if(media.length)body+='<div class="tm-media-row">'+media.map(part=>'<span class="tm-media">'+icon("paperclip")+esc(part.type)+(part.name?" · "+esc(part.name):"")+(part.media_type?" · "+esc(part.media_type):"")+'</span>').join("")+'</div>';
5702
+ (message.tool_calls||[]).forEach((call,index)=>{body+='<div class="tm-call"><span>Calls '+(call.id?'<button type="button" class="net-link" data-net-item="t:'+attr(call.id)+'">'+esc(call.tool_name)+'</button>':'<b>'+esc(call.tool_name)+'</b>')+(call.id?' <span class="muted">'+esc(short(call.id))+'</span>':"")+'</span>'+jsonBlock(call.input_args,key+":call"+index)+'</div>'});
5703
+ (message.tool_results||[]).forEach((result,index)=>{body+='<div class="tm-result status-'+attr(result.status)+'"><span>'+(result.call_id?'<button type="button" class="net-link" data-net-item="t:'+attr(result.call_id)+'">'+esc(result.tool_name)+'</button>':'<b>'+esc(result.tool_name)+'</b>')+' · '+esc(result.status)+(Number.isFinite(result.duration_ms)?" · "+esc(durationText(result.duration_ms)):"")+'</span>'+(result.message?'<p class="tm-note">'+esc(result.message)+'</p>':"")+jsonBlock(result.data,key+":result"+index)+'</div>'});
5704
+ if(message.reasoning_omitted)body+='<p class="tm-note">The provider’s reasoning was sent back with this message. It isn’t recorded.</p>';
5705
+ return'<article class="tm '+role.cls+(isNew?" new":"")+'"><header><span class="tm-role">'+esc(role.label)+'</span>'+(isNew?'<span class="tm-new">new</span>':"")+'</header>'+(body||'<p class="tm-note">Empty.</p>')+'</article>';
5706
+ }
5707
+ function messagesHtml(messages,newFrom,key){
5708
+ const earlier=messages.slice(0,newFrom);const fresh=messages.slice(newFrom);
5709
+ return(earlier.length?'<details class="msg-earlier" data-persist="'+attr(key)+':earlier"><summary>'+count(earlier.length,"earlier message")+' <span class="muted">· already in the conversation</span></summary>'+earlier.map((message,index)=>traceMessageHtml(message,key+":"+index,false)).join("")+'</details>':"")
5710
+ +(fresh.length?fresh.map((message,index)=>traceMessageHtml(message,key+":"+(newFrom+index),Boolean(earlier.length))).join(""):'<p class="dt-note">No messages.</p>');
5711
+ }
5712
+
5713
+ /* ---- Network ---- */
5714
+ function itemStatus(item){
5715
+ if(item.approval&&item.approval.status==="pending")return'<span class="st warn">approval</span>';
5716
+ const map={success:["ok","ok"],error:["err","error"],aborted:["warn","aborted"],denied:["warn","denied"],limit:["warn","limit"],pending:["live","pending"]};
5717
+ const value=map[item.status]||["",item.status||"—"];
5718
+ return'<span class="st '+value[0]+'">'+esc(value[1])+'</span>';
5719
+ }
5720
+ function itemType(item){return item.kind==="model"?(item.purpose==="compaction"?"compaction":"model"):item.via==="repl"?"repl call":item.kind}
5721
+ function itemSubtitle(item){
5722
+ if(item.kind==="model")return(item.model||"model")+(item.messages.length?" · "+count(item.messages.length,"message"):"")+(item.context.length?" · "+item.context.length+" context":"");
5723
+ if(item.kind==="tool")return item.via==="repl"?(item.fn||item.name)+"()":tracePreview(item.input,80);
5724
+ return tracePreview(item.prompt,80);
5725
+ }
5726
+ function itemSize(item){
5727
+ if(item.kind==="model")return item.tokensIn!==undefined?fmtTokens(item.tokensIn)+" → "+fmtTokens(item.tokensOut):"—";
5728
+ return item.result?fmtBytes(jsonSize(item.result.data)):"—";
5729
+ }
5730
+ function netMatches(item,kind,term){
5731
+ if(kind==="model"&&item.kind!=="model")return false;
5732
+ if(kind==="tools"&&item.kind!=="tool")return false;
5733
+ if(kind==="errors"&&!["error","aborted","denied","limit"].includes(item.status))return false;
5734
+ if(!term)return true;
5735
+ 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();
5736
+ return text.includes(term);
5737
+ }
5738
+ /* Like DevTools' Timing tab: the phases of one row, in order. */
5739
+ function itemPhases(item){
5740
+ const phases=[];
5741
+ if(item.kind==="model"){
5742
+ 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"])}
5743
+ else if(Number.isFinite(item.durationMs))phases.push(["Model request",item.durationMs,"run"]);
5744
+ }else if(item.kind==="tool"){
5745
+ if(item.queuedMs>0)phases.push(["Queued behind earlier calls",item.queuedMs,"queue"]);
5746
+ 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"])}
5747
+ else if(Number.isFinite(item.durationMs))phases.push(["Running",item.durationMs,"run"]);
5748
+ }else if(Number.isFinite(item.durationMs))phases.push(["Running",item.durationMs,"run"]);
5749
+ return phases;
5750
+ }
5751
+ function wfBar(item,trace){
5752
+ const span=Math.max(1,trace.end-trace.start);const pending=item.status==="pending";
5753
+ const pct=(ms)=>ms/span*100;
5754
+ const left=Number.isFinite(item.startAt)?Math.min(99.4,Math.max(0,pct(item.startAt-trace.start))):0;
5755
+ const width=Math.min(Number.isFinite(item.durationMs)?Math.max(.6,pct(item.durationMs)):pending?100-left:.6,100-left);
5756
+ const lead=item.queuedMs>0?Math.min(left,pct(item.queuedMs)):0;
5757
+ // The light part is waiting (first token, a permission check); the solid part is work.
5758
+ const waitMs=item.kind==="model"?item.ttftMs:item.kind==="tool"&&Number.isFinite(item.runMs)?item.durationMs-item.runMs:NaN;
5759
+ const wait=Number.isFinite(waitMs)&&Number.isFinite(item.durationMs)&&item.durationMs>0?Math.max(0,Math.min(100,waitMs/item.durationMs*100)):0;
5760
+ const tip=itemPhases(item).map(phase=>phase[0]+": "+durationText(phase[1])).join(" · ");
5761
+ return'<span class="wf-track" title="'+attr(tip)+'">'+(lead?'<span class="wf-queue" style="left:'+(left-lead).toFixed(2)+'%;width:'+lead.toFixed(2)+'%"></span>':"")
5762
+ +'<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>';
5763
+ }
5764
+ function turnLabel(turn){return"Turn "+turn.index+" · "+(turn.trigger==="events"?"events woke the agent":turn.trigger==="resume"?"resumed at its tool step":"request")}
5765
+ function turnRow(turn){
5766
+ const st={success:["ok","ok"],error:["err","failed"],aborted:["warn","aborted"],suspended:["warn","suspended"],pending:["live","running"]}[turn.status]||["",turn.status];
5767
+ 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>';
5768
+ }
5769
+ function netRow(item,trace,selectedKey){
5770
+ const pending=item.status==="pending";
5771
+ const failed=["error","aborted","denied","limit"].includes(item.status);
5772
+ 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)+'"':"")+'>'
5773
+ +'<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>'
5774
+ +'<td class="c-type">'+esc(itemType(item))+'</td>'
5775
+ +'<td class="c-status">'+itemStatus(item)+'</td>'
5776
+ +'<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>'
5777
+ +'<td class="c-size">'+esc(itemSize(item))+'</td>'
5778
+ +'<td class="c-time">'+(pending?'<span class="st live">…</span>':esc(durationText(item.durationMs)))+'</td>'
5779
+ +'<td class="c-wf">'+wfBar(item,trace)+'</td></tr>';
5780
+ }
5781
+ 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"]]}
5782
+ function toolPanes(){return[["overview","Overview"],["input","Input"],["result","Result"],["timing","Timing"],["raw","Raw"]]}
5783
+ function timingPane(item,run){
5784
+ const base=new Date(runStartedAt(run)).getTime();
5785
+ const phases=itemPhases(item);
5786
+ if(!phases.length)return'<p class="dt-note">'+(item.status==="pending"?"Still running.":"No timing recorded.")+'</p>';
5787
+ const total=phases.reduce((sum,phase)=>sum+phase[1],0)||1;
5788
+ 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."};
5789
+ return kv([
5790
+ Number.isFinite(item.askedAt)&&item.kind==="tool"?["Asked for",esc(offsetFrom(base,isoAt(item.askedAt)))]:null,
5791
+ Number.isFinite(item.startAt)?["Started",esc(offsetFrom(base,isoAt(item.startAt)))]:null,
5792
+ Number.isFinite(item.endAt)?["Finished",esc(offsetFrom(base,isoAt(item.endAt)))]:null,
5793
+ ])+'<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("")
5794
+ +'<div class="timing-row total"><span class="timing-name">Total</span><span></span><span class="mono">'+esc(durationText(total))+'</span></div></div>'
5795
+ +(item.kind==="model"&&item.streamed?'<div class="dt-section">Streamed text</div><pre class="dt-pre">'+esc(item.streamed)+'</pre>':"");
5796
+ }
5797
+ function detailPanes(item){return item.kind==="model"?modelPanes(item):item.kind==="tool"?toolPanes():[["overview","Overview"],["timing","Timing"],["raw","Raw"]]}
5798
+ function kv(rows){return'<dl class="dt-kv">'+rows.filter(Boolean).map(row=>'<dt>'+esc(row[0])+'</dt><dd>'+row[1]+'</dd>').join("")+'</dl>'}
5799
+ function itemLink(key,label){return'<button type="button" class="net-link" data-net-item="'+attr(key)+'">'+esc(label)+'</button>'}
5800
+ function requestJson(item){return jsonText({model:item.model,system:item.systemPrompt??null,messages:item.messages,context:item.context,tools:item.tools||item.toolNames})}
5801
+ function modelDetail(item,trace,run,pane){
5802
+ const base=new Date(runStartedAt(run)).getTime();
5803
+ if(item.legacy&&["prompt","messages","context","tools"].includes(pane))return'<p class="dt-note">This run was recorded before Foundry kept what each model request was sent, or with <code>observability.modelRequests</code> off. Its response and tool calls are here; its prompt, messages, context and tools aren’t.</p>';
5804
+ if(pane==="prompt"){
5805
+ if(item.systemPrompt===undefined)return'<p class="dt-note">This request’s system prompt ('+esc((item.promptChars||0).toLocaleString())+' characters) was recorded with an earlier request whose events are no longer retained.</p>';
5806
+ const versions=Object.keys(trace.prompts).length;
5807
+ return'<div class="dt-bar"><span>'+esc((item.promptChars??item.systemPrompt.length).toLocaleString())+' characters'+(versions>1?" · one of "+versions+" system prompts in this run":"")+'</span>'+copyButton(item.systemPrompt,"system prompt")+'</div>'+(item.systemPrompt?'<pre class="dt-pre">'+esc(item.systemPrompt)+'</pre>':'<p class="dt-note">The system prompt was empty.</p>');
5808
+ }
5809
+ if(pane==="messages")return'<p class="dt-note">The conversation as this request sent it'+(item.newFrom?", with what’s new since the last request at the end":"")+'. Runtime context is under Context.</p>'+messagesHtml(item.messages,item.newFrom,item.key+":m");
5810
+ if(pane==="context"){
5811
+ if(!item.context.length)return'<p class="dt-note">No runtime context. Context providers (memory, goals, forms, or the agent’s own) add it at the end of each request, outside the stored conversation.</p>';
5812
+ const before=trace.items.filter(other=>other.kind==="model"&&other.index<item.index).at(-1);
5813
+ return'<p class="dt-note">Added at the end of this request by context providers (memory, goals, forms, or the agent’s own). It isn’t stored in the conversation, and it is worked out again before every request.</p>'
5814
+ +item.context.map((message,index)=>{const prior=before&&before.context[index];const change=!before?"":!prior?"new":prior.text!==message.text?"changed":"same as #"+before.index;return'<article class="tm runtime"><header><span class="tm-role">Context '+(index+1)+'</span>'+(change?'<span class="tm-new'+(change.startsWith("same")?" quiet":"")+'">'+esc(change)+'</span>':"")+'</header><div class="tm-text">'+esc(message.text)+'</div>'+((message.content||[]).filter(part=>part.type!=="text").map(part=>'<span class="tm-media">'+icon("paperclip")+esc(part.type)+'</span>').join(""))+'</article>'}).join("");
5815
+ }
5816
+ if(pane==="tools"){
5817
+ if(!item.tools)return'<p class="dt-note">'+count(item.toolNames.length,"tool")+' offered. Their descriptions were recorded with an earlier request whose events are no longer retained.</p><div class="cap-list">'+item.toolNames.map(name=>'<span class="cap">'+esc(name)+'</span>').join("")+'</div>';
5818
+ return'<p class="dt-note">What the model was told about each tool it could call.</p>'+item.tools.map(tool=>'<details class="tool-def" data-persist="'+attr(item.key+":tool:"+tool.name)+'"><summary><b>'+esc(tool.name)+'</b><span>'+esc(tracePreview(tool.description,110))+'</span></summary><p class="dt-note">'+esc(tool.description)+'</p>'+jsonBlock(tool.input_schema,item.key+":schema:"+tool.name)+'</details>').join("");
5819
+ }
5820
+ if(pane==="response"){
5821
+ if(item.status==="pending")return'<p class="dt-note">Waiting for the model.</p>';
5822
+ return(item.error?'<div class="alert danger"><span class="symbol">'+icon("warning")+'</span><div><b>The request '+esc(item.status==="aborted"?"was aborted":"failed")+'.</b><p>'+esc(item.error)+'</p></div></div>':"")
5823
+ +kv([item.stopReason?["Stop reason",esc(item.stopReason)]:null,["Tokens",esc(fmtTokens(item.tokensIn))+" in · "+esc(fmtTokens(item.tokensOut))+" out"]])
5824
+ +(item.response||[]).map((message,index)=>traceMessageHtml(message,item.key+":r"+index,false)).join("");
5825
+ }
5826
+ 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");
5827
+ if(pane==="timing")return timingPane(item,run);
5828
+ const fresh=item.messages.slice(item.newFrom);const calls=(item.response||[]).flatMap(message=>message.tool_calls||[]);
5829
+ return kv([
5830
+ ["Request",'<span class="mono">'+esc(item.id)+'</span> '+copyButton(item.id,"request id")],
5831
+ ["Model",esc(item.model||"—")],
5832
+ ["Status",itemStatus(item)+(item.error?' <span class="muted">'+esc(item.error)+'</span>':"")],
5833
+ ["Started",esc(offsetFrom(base,isoAt(item.startAt)))+' <span class="muted">'+esc(fmtTime(isoAt(item.startAt)))+'</span>'],
5834
+ ["Duration",esc(durationText(item.durationMs))+(Number.isFinite(item.ttftMs)?' <span class="muted">· first token after '+esc(durationText(item.ttftMs))+'</span>':"")],
5835
+ ["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":"")],
5836
+ item.stopReason?["Stop reason",esc(item.stopReason)]:null,
5837
+ ["Initiator",item.initiator.key?itemLink(item.initiator.key,item.initiator.label):esc(item.initiator.label)],
5838
+ ["System prompt",(item.promptChars!==undefined?esc(item.promptChars.toLocaleString())+" characters":"—")+" · "+'<button type="button" class="net-link" data-net-pane="prompt">view</button>'],
5839
+ ["Messages",esc(count(item.messages.length,"message"))+(fresh.length&&item.newFrom?" · "+fresh.length+" new":"")+" · "+'<button type="button" class="net-link" data-net-pane="messages">view</button>'],
5840
+ ["Runtime context",esc(count(item.context.length,"entry","entries"))+(item.context.length?" · "+'<button type="button" class="net-link" data-net-pane="context">view</button>':"")],
5841
+ ["Tools offered",esc(item.toolNames.length)+(item.toolNames.length?" · "+'<button type="button" class="net-link" data-net-pane="tools">view</button>':"")],
5842
+ ])
5843
+ +(calls.length?'<div class="dt-section">Tool calls in the response</div><div class="cap-list">'+calls.map(call=>call.id?itemLink("t:"+call.id,call.tool_name):'<span class="cap">'+esc(call.tool_name)+'</span>').join("")+'</div>':"")
5844
+ +((item.response||[]).some(message=>message.text)?'<div class="dt-section">Reply</div><div class="dt-pre">'+esc((item.response||[]).map(message=>message.text).filter(Boolean).join("\n\n"))+'</div>':"");
5845
+ }
5846
+ function toolDetail(item,run,pane){
5847
+ const base=new Date(runStartedAt(run)).getTime();
5848
+ if(pane==="input")return item.via==="repl"?'<p class="dt-note">Calls made from inside the REPL record their function and timing. Their input stays in the REPL program; see the REPL tool call that made it.</p>':jsonBlock(item.input,item.key+":input");
5849
+ if(pane==="result"){
5850
+ if(!item.result)return'<p class="dt-note">'+(item.status==="pending"?"Still running.":"No result recorded.")+'</p>';
5851
+ 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"));
5852
+ }
5853
+ 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");
5854
+ if(pane==="timing")return timingPane(item,run);
5855
+ 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>';
5856
+ return kv([
5857
+ item.id?["Call",'<span class="mono">'+esc(item.id)+'</span> '+copyButton(item.id,"call id")]:null,
5858
+ ["Tool",esc(item.name)+(item.via==="repl"?' <span class="muted">· '+esc(item.fn||"")+'() from the REPL</span>':"")],
5859
+ ["Status",itemStatus(item)],
5860
+ Number.isFinite(item.startAt)?["Started",esc(offsetFrom(base,isoAt(item.startAt)))]:null,
5861
+ ["Duration",esc(durationText(item.durationMs))+(item.queuedMs>0?' <span class="muted">· queued '+esc(durationText(item.queuedMs))+' first</span>':"")],
5862
+ ["Called by",item.initiator.key?itemLink(item.initiator.key,item.initiator.label):esc(item.initiator.label)],
5863
+ 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,
5864
+ item.result?["Result",esc(fmtBytes(jsonSize(item.result.data)))+" · "+'<button type="button" class="net-link" data-net-pane="result">view</button>']:null,
5865
+ ])+(item.via==="repl"?"":'<div class="dt-section">Input</div>'+jsonBlock(item.input,item.key+":overview-input"));
5866
+ }
5867
+ function netDetail(item,trace,run,view){
5868
+ const panes=detailPanes(item);const pane=panes.some(entry=>entry[0]===view.pane)?view.pane:"overview";
5869
+ const body=item.kind==="model"?modelDetail(item,trace,run,pane):toolDetail(item,run,pane);
5870
+ return'<aside class="net-detail" aria-label="'+attr(item.name)+'"><div class="nd-head"><button type="button" class="nd-close" data-net-close title="Close (Esc)" aria-label="Close">'+icon("close")+'</button>'
5871
+ +panes.map(entry=>'<button type="button" class="nd-tab'+(entry[0]===pane?" active":"")+'" data-net-pane="'+attr(entry[0])+'">'+esc(entry[1])+(entry[2]?'<span class="dt-badge">'+entry[2]+'</span>':"")+'</button>').join("")
5872
+ +(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>':"")
5873
+ +'</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>';
5874
+ }
5875
+ function netRows(visible,trace,selectedKey){
5876
+ // A run with more than one turn (a resume, an event wake) shows where each began.
5877
+ const divide=(trace.turns||[]).length>1;let shown=0;
5878
+ return visible.map(item=>{
5879
+ let head="";
5880
+ if(divide&&item.turn&&item.turn!==shown){shown=item.turn;const turn=trace.turns[item.turn-1];if(turn)head=turnRow(turn)}
5881
+ return head+netRow(item,trace,selectedKey);
5882
+ }).join("");
5883
+ }
5884
+ function runNetwork(run,trace,view){
5885
+ const term=state.network.filter.trim().toLowerCase();
5886
+ const visible=trace.items.filter(item=>netMatches(item,state.network.kind,term));
5887
+ const selected=trace.items.find(item=>item.key===view.item);
5888
+ const kinds=[["all","All"],["model","Model"],["tools","Tools"],["errors","Errors"]];
5889
+ const t=trace.totals;
5890
+ let html='<div class="dt-toolbar"><label class="dt-filter">'+icon("search")+'<input id="net-filter" value="'+attr(state.network.filter)+'" placeholder="Filter by name, input or result" aria-label="Filter requests" /></label>'
5891
+ +'<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>';
5892
+ html+='<div class="net-split'+(selected?" has-detail":"")+'"><div class="net-list" data-scroll-key="net-list">';
5893
+ 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.");
5894
+ 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."));
5895
+ html+='</div>'+(selected?netDetail(selected,trace,run,view):"")+'</div>';
5896
+ 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>';
5897
+ return html;
5898
+ }
5899
+
5900
+ /* ---- Console ---- */
5901
+ const CONSOLE_LEVELS={default:["error","warn","info"],all:["error","warn","info","verbose"],warnings:["error","warn"],errors:["error"]};
5902
+ function revealKey(row){
5903
+ const type=String(row.type||"").replace(/^agent\./,"");const data=row.data||{};
5904
+ if(type==="model_request"||type==="model_request_end")return"m:"+data.request_id;
5905
+ if(type==="tool_use"||type==="tool_use_start")return data.id?"t:"+data.id:"";
5906
+ if(type==="text_delta")return data.request_id?"m:"+data.request_id:"";
5907
+ if(type==="tool_use_result")return(data.id||data.call_id)?"t:"+(data.id||data.call_id):"";
5908
+ return"";
5909
+ }
5910
+ function consoleRow(row,base){
5911
+ const reveal=revealKey(row);
5912
+ const glyph=row.level==="error"||row.level==="warn"?icon("warning"):"";
5913
+ return'<div class="con-row lvl-'+attr(row.level)+'" data-event-key="'+attr(row.key)+'"><button type="button" class="con-line"><span class="con-time" title="'+attr(fullDate(row.timestamp))+'">'+esc(offsetFrom(base,row.timestamp))+'</span><span class="con-lvl">'+glyph+'</span><span class="con-msg">'+esc(row.message)+'</span><span class="con-src">'+esc(row.source)+'</span></button>'
5914
+ +'<div class="con-detail"><div class="con-detail-head"><span class="mono muted">'+esc(row.type)+" · "+esc(fmtTime(row.timestamp))+'</span>'+(reveal?'<button type="button" class="net-link" data-reveal="'+attr(reveal)+'">Open in Network</button>':"")+copyButton(jsonText(row.data),"event data")+'</div>'+(row.type==="text_delta"?'<pre class="dt-pre">'+esc(row.data.text)+'</pre>':jsonBlock(row.data,row.key))+'</div></div>';
5915
+ }
5916
+ function runConsole(run,rows){
5917
+ const c=state.console;const levels=CONSOLE_LEVELS[c.level]||CONSOLE_LEVELS.default;const term=c.filter.trim().toLowerCase();
5918
+ const sources=[...new Set(rows.map(row=>row.source))].sort();
5919
+ const visible=rows.filter(row=>levels.includes(row.level)&&(c.source==="all"||row.source===c.source)&&(!term||(row.message+" "+row.type).toLowerCase().includes(term)));
5920
+ const shown=visible.slice(-1500);const base=new Date(runStartedAt(run)).getTime();
5921
+ const errors=rows.filter(row=>row.level==="error").length;const warnings=rows.filter(row=>row.level==="warn").length;const hidden=rows.length-visible.length;
5922
+ return'<div class="dt-toolbar"><label class="dt-filter">'+icon("search")+'<input id="con-filter" value="'+attr(c.filter)+'" placeholder="Filter" aria-label="Filter the console" /></label>'
5923
+ +'<select class="dt-select" id="con-level" aria-label="Levels">'+[["default","Default levels"],["all","All levels"],["warnings","Warnings and errors"],["errors","Errors"]].map(option=>'<option value="'+option[0]+'"'+(c.level===option[0]?" selected":"")+'>'+option[1]+'</option>').join("")+'</select>'
5924
+ +'<select class="dt-select" id="con-source" aria-label="Source"><option value="all">All sources</option>'+sources.map(source=>'<option value="'+attr(source)+'"'+(c.source===source?" selected":"")+'>'+esc(source)+'</option>').join("")+'</select>'
5925
+ +'<span class="dt-summary">'+(errors?'<span class="st err">'+count(errors,"error")+'</span> ':"")+(warnings?'<span class="st warn">'+count(warnings,"warning")+'</span> ':"")+(hidden?esc(hidden)+" hidden":"")+'</span></div>'
5926
+ +'<div class="con-list" data-scroll-key="con-list" data-follow>'+(visible.length>shown.length?'<p class="dt-note con-more">'+esc(visible.length-shown.length)+' earlier lines aren’t shown. Narrow the filter to see them.</p>':"")+(shown.length?shown.map(row=>consoleRow(row,base)).join(""):empty(rows.length?"Nothing at these levels":"Nothing logged yet",rows.length?"Choose All levels to include verbose detail, such as assembly and streamed text.":"The run’s log appears here as it works."))+'</div>';
5927
+ }
5928
+
5929
+ /* ---- Context: what the agent had, like DevTools' Application panel. ---- */
5930
+ const CONTEXT_NODES=[["Model request","prompt","System prompt"],["Model request","runtime","Runtime context"],["Model request","tools","Tools"],["Model request","messages","Messages"],["Run","input","Input"],["Run","output","Output"],["Agent","instance","Instance context"],["Agent","installations","Installations"],["Agent","playbooks","Playbooks"],["Memory","guidance","Goals, facts and forms"],["Memory","memory","Memory"]];
5931
+ function runContext(run,trace,events,view){
5932
+ const models=trace.items.filter(item=>item.kind==="model"&&!item.legacy);
5933
+ const request=models.find(item=>item.id===view.request)||models.at(-1);
5934
+ const node=CONTEXT_NODES.some(entry=>entry[1]===view.node)?view.node:"prompt";
5935
+ const instance=state.instances.find(item=>item.id===run.agentId);
5936
+ const memoryEvents=events.filter(event=>event.category==="memory");
5937
+ const counts={prompt:Object.keys(trace.prompts).length||"",runtime:request?request.context.length:"",tools:request?request.toolNames.length:"",messages:request?request.messages.length:"",installations:instance?instance.installations.length:"",playbooks:instance?instance.playbooks.length:"",memory:memoryEvents.length||""};
5938
+ let tree="";let group="";
5939
+ CONTEXT_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-ctx-node="'+entry[1]+'">'+esc(entry[2])+(counts[entry[1]]!==undefined&&counts[entry[1]]!==""?'<small>'+esc(counts[entry[1]])+'</small>':"")+'</button>'});
5940
+ const scoped=["prompt","runtime","tools","messages"].includes(node);
5941
+ let body="";
5942
+ if(scoped&&!request)body=empty("No model requests recorded","Runs recorded before request tracing, or with observability.modelRequests off, don’t carry what the model was sent. Tool calls and results are under Network.");
5943
+ else if(node==="prompt")body=modelDetail(request,trace,run,"prompt")+(Object.keys(trace.prompts).length>1?'<div class="dt-section">System prompts in this run</div>'+Object.keys(trace.prompts).map(hash=>{const users=models.filter(item=>item.promptHash===hash);return'<p class="dt-note">'+users.map(item=>itemLink(item.key,"#"+item.index)).join(" ")+' · '+esc(tracePreview(trace.prompts[hash],140))+'</p>'}).join(""):"");
5944
+ else if(node==="runtime")body=modelDetail(request,trace,run,"context");
5945
+ else if(node==="tools")body=modelDetail(request,trace,run,"tools");
5946
+ else if(node==="messages")body=modelDetail(request,trace,run,"messages");
5947
+ else if(node==="input"){const message=run.input&&run.input.message;const text=typeof message==="string"?message:message&&typeof message.text==="string"?message.text:"";body=(text?'<div class="dt-section">Message</div><pre class="dt-pre">'+esc(text)+'</pre>':"")+'<div class="dt-section">Recorded input</div>'+jsonBlock(run.input,"ctx:input")}
5948
+ else if(node==="output")body=run.status==="failed"?'<div class="alert danger"><span class="symbol">'+icon("warning")+'</span><div><b>The run failed.</b><p>'+esc(runErrorText(run))+'</p></div></div>':run.output===undefined?'<p class="dt-note">'+(isLiveRun(run)?"The run hasn’t finished.":"No output recorded.")+'</p>':jsonBlock(run.output,"ctx:output");
5949
+ else if(node==="instance")body=instance?kv([["Instance",'<a class="link mono" href="/instances/'+attr(instance.id)+'" data-link>'+esc(instance.name||instance.id)+'</a>'],["Definition",esc(instance.definitionId)],["Workspace",'<a class="link mono" href="/workspaces/'+attr(instance.workspaceId)+'" data-link>'+esc(instance.workspaceId)+'</a>'],["Conversation",run.conversationId?'<a class="link mono" href="'+attr(chatPath(instance.id,run.conversationId))+'" data-link>'+esc(short(run.conversationId))+'</a>':"—"]])+'<div class="dt-section">Context</div><p class="dt-note">The instance’s stored context as it is now. A run reads it when it starts.</p>'+jsonBlock(instance.context||{},"ctx:instance"):empty("Instance not found","This run’s agent instance is no longer stored.");
5950
+ else if(node==="installations")body=instance?(instance.installations.length?jsonBlock(instance.installations,"ctx:installations"):empty("Nothing installed","Applications, MCP servers and shared tools installed on this instance appear here.")):empty("Instance not found","");
5951
+ else if(node==="playbooks")body=instance?(instance.playbooks.length?jsonBlock(instance.playbooks,"ctx:playbooks"):empty("No playbooks","")):empty("Instance not found","");
5952
+ else if(node==="guidance"){const card=guidanceCard(events);const latest=[...events].reverse().find(event=>/(?:^|\.)foundry\.guidance\.state$/.test(event.type));body=card?card+'<div class="dt-section">Latest state</div>'+jsonBlock(latest.data,"ctx:guidance"):empty("No goals, facts or forms","This run didn’t mount guidance, or it hasn’t reported yet.")}
5953
+ else if(node==="memory")body='<p class="dt-note">What the run mounted for memory, and memory events it recorded. What memory put in front of the model is in each request’s runtime context.</p>'+(request&&request.context.length?'<p class="dt-note">'+itemLink(request.key,"Open #"+request.index+"’s runtime context")+'</p>':"")+(memoryEvents.length?memoryEvents.map(event=>'<div class="dt-section">'+esc(event.type.replace(/^agent\./,""))+" · "+esc(fmtTime(event.timestamp))+'</div>'+jsonBlock(event.data,"ctx:mem:"+event.id)).join(""):empty("No memory events","This run recorded no memory events."));
5954
+ const select=scoped&&models.length?'<label class="ctx-request"><span>As of</span><select class="dt-select" id="ctx-request">'+models.map(item=>'<option value="'+attr(item.id)+'"'+(item===request?" selected":"")+'>'+esc(item.name)+" · "+esc(fmtTime(isoAt(item.startAt)))+'</option>').join("")+'</select></label>':"";
5955
+ return'<div class="ctx"><nav class="ctx-tree" aria-label="Context">'+tree+'</nav><div class="ctx-view" data-scroll-key="ctx:'+attr(node)+'">'+select+body+'</div></div>';
5956
+ }
5957
+
5958
+ /* ---- Summary ---- */
5959
+ function runSummary(run,events,trace){
5960
+ const slow=trace.items.filter(item=>Number.isFinite(item.durationMs)).sort((a,b)=>b.durationMs-a.durationMs).slice(0,5);
5961
+ const failed=trace.items.filter(item=>["error","aborted","denied","limit"].includes(item.status));
5962
+ let html='<div class="dt-pad">'+guidanceCard(events)+'<div class="grid cols-3"><section class="card span-2"><div class="card-head"><h2>Run spine</h2><span class="meta">'+count(events.length,"event")+'</span></div><div class="card-body"><div class="trace-note">Observable work only: what was sent, called and returned. A model’s hidden reasoning isn’t recorded.</div><div class="run-spine">'+phaseData(run,events).map(p=>'<div class="phase '+p.state+'"><span class="phase-dot"></span><div><strong>'+esc(p.name)+'</strong><p>'+esc(p.detail)+'</p></div><time title="'+attr(fullDate(p.time))+'">'+esc(fmtTime(p.time))+'</time></div>').join("")+'</div></div></section>';
5963
+ html+=card("Result",'<div class="card-body"><div class="summary-box"><dl><dt>Created</dt><dd>'+relCell(run.createdAt)+'</dd><dt>Started</dt><dd>'+relCell(run.startedAt)+'</dd><dt>Finished</dt><dd>'+relCell(run.completedAt)+'</dd><dt>Timeout</dt><dd>'+esc(durationText(run.timeoutMs))+'</dd></dl></div><details data-persist="output" open><summary class="link">Output</summary>'+jsonBlock(run.output??run.error??null,"summary:output")+'</details><details data-persist="input"><summary class="link">Input</summary>'+jsonBlock(run.input,"summary:input")+'</details></div>',"Recorded outcome");
5964
+ html+='</div><div class="grid cols-2">';
5965
+ html+=card("Slowest steps",slow.length?'<div class="card-body">'+slow.map(item=>'<div class="sum-row">'+itemLink(item.key,item.name)+'<span class="muted">'+esc(itemType(item))+'</span><span class="mono">'+esc(durationText(item.durationMs))+'</span></div>').join("")+'</div>':empty("Nothing timed yet",""),"Network");
5966
+ html+=card("Errors",failed.length?'<div class="card-body">'+failed.map(item=>'<div class="sum-row">'+itemLink(item.key,item.name)+'<span class="muted">'+esc(item.status)+'</span><span class="sum-msg">'+esc(tracePreview(item.error||(item.result&&(item.result.message||item.result.data))||"",120))+'</span></div>').join("")+'</div>':empty("No failed requests or tool calls",""),count(failed.length,"error"));
5967
+ return html+'</div></div>';
5968
+ }
5969
+
5970
+ function renderRun(id){
5971
+ const run=state.runs.find(x=>x.id===id);if(!run)return renderNotFound("Run");
5972
+ const events=runEventsFor(id);const trace=buildRunTrace(events,run);const rows=buildConsole(events);const view=runView();
5973
+ crumbs([{label:"Runs",href:"/runs"},{label:short(id)}]);
5974
+ const actions=(isLiveRun(run)?'<button class="button danger" data-cancel>Cancel run</button>':"")
5975
+ +'<button class="button" data-copy="'+attr(run.id)+'">'+icon("copy")+'<span>Copy run id</span></button>'
5976
+ +'<button class="button" data-export-trace title="The run and every event, as JSON">'+icon("download")+'<span>Export trace</span></button>'
5977
+ +'<button class="button primary" data-rerun>'+icon("refresh")+'<span>Run again</span></button>';
5978
+ let html=pageHead("Run",run.agent+" · "+short(id),explainRun(run),actions);
5979
+ const failure=runErrorText(run);
5980
+ if(failure)html+='<div class="alert danger"><span class="symbol">'+icon("warning")+'</span><div><b>This run failed'+(run.attempts>1?" after "+count(run.attempts,"attempt"):"")+'.</b><p>'+esc(failure)+'</p></div></div>';
5981
+ html+=approvalRail(pendingApprovals(run.id),"This run is waiting for a decision");
5982
+ const t=trace.totals;
5983
+ html+='<div class="detail-strip">'
5984
+ +'<div><label>Status</label><strong>'+status(run.status)+'</strong></div>'
5985
+ +'<div><label>Duration</label><strong>'+durCell(run)+'</strong></div>'
5986
+ +'<div><label>Model requests</label><strong>'+esc(t.requests)+(t.errors?' <span class="st err">'+count(t.errors,"error")+'</span>':"")+'</strong></div>'
5987
+ +'<div><label>Tool calls</label><strong>'+esc(t.tools)+'</strong></div>'
5988
+ +'<div><label>Tokens</label><strong>'+esc(fmtTokens(t.tokensIn))+" in · "+esc(fmtTokens(t.tokensOut))+" out"+'</strong></div>'
5989
+ +'<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>'
5990
+ +'</div>';
5991
+ const errors=rows.filter(row=>row.level==="error").length;const warnings=rows.filter(row=>row.level==="warn").length;
5992
+ const crossings=buildQueues(events,run,trace).length;
5993
+ 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>':"")};
5994
+ 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("")
5995
+ +(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+'">'
5996
+ +(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>';
5997
+ $("content").innerHTML=html;
5998
+ bindRun(id,run,trace,events);
5999
+ }
6000
+ function rerenderRun(id){const view=captureView();renderRun(id);restoreView(view)}
6001
+ function selectRunItem(id,key){if(!key)return;setRunView({tab:"network",item:key});rerenderRun(id);requestAnimationFrame(()=>document.querySelector('.net-row.selected')?.scrollIntoView({block:"nearest"}))}
6002
+ function bindRun(id,run,trace,events){
6003
+ document.querySelectorAll("[data-run-tab]").forEach(node=>node.onclick=()=>{setRunView({tab:node.dataset.runTab});rerenderRun(id)});
6004
+ document.querySelectorAll("[data-net-item]").forEach(node=>node.onclick=event=>{event.preventDefault();event.stopPropagation();selectRunItem(id,node.dataset.netItem)});
6005
+ document.querySelectorAll("[data-reveal]").forEach(node=>node.onclick=event=>{event.stopPropagation();selectRunItem(id,node.dataset.reveal)});
6006
+ document.querySelectorAll("[data-net-pane]").forEach(node=>node.onclick=()=>{setRunView({pane:node.dataset.netPane});rerenderRun(id)});
6007
+ document.querySelectorAll("[data-net-kind]").forEach(node=>node.onclick=()=>{state.network.kind=node.dataset.netKind;rerenderRun(id)});
6008
+ const close=document.querySelector("[data-net-close]");if(close)close.onclick=()=>{setRunView({item:"",pane:""});rerenderRun(id)};
6009
+ const keepTyping=(input,apply)=>input&&(input.oninput=event=>{const caret=event.target.selectionStart;apply(event.target.value);rerenderRun(id);const next=$(input.id);if(next){next.focus();try{next.setSelectionRange(caret,caret)}catch{}}});
6010
+ keepTyping($("net-filter"),value=>{state.network.filter=value});
6011
+ keepTyping($("con-filter"),value=>{state.console.filter=value});
6012
+ const level=$("con-level");if(level)level.onchange=event=>{state.console.level=event.target.value;rerenderRun(id)};
6013
+ const source=$("con-source");if(source)source.onchange=event=>{state.console.source=event.target.value;rerenderRun(id)};
6014
+ document.querySelectorAll(".con-line").forEach(node=>node.onclick=()=>node.parentElement.classList.toggle("open"));
6015
+ document.querySelectorAll("[data-ctx-node]").forEach(node=>node.onclick=()=>{setRunView({node:node.dataset.ctxNode});rerenderRun(id)});
6016
+ const request=$("ctx-request");if(request)request.onchange=event=>{setRunView({request:event.target.value});rerenderRun(id)};
6017
+ const cancel=document.querySelector("[data-cancel]");if(cancel)cancel.onclick=()=>void cancelRun(id);
6018
+ const rerun=document.querySelector("[data-rerun]");
6019
+ 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:"");
6020
+ const exportButton=document.querySelector("[data-export-trace]");
6021
+ 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")};
6022
+ bindRunFoundry(id);
6023
+ dataLinks();
6024
+ }
6025
+ /* Keys on the run page: 1-4 switch views, j/k walk the requests, Esc closes the open one. */
6026
+ function runKeys(e){
6027
+ const current=route();if(current.section!=="runs"||!current.id)return false;
6028
+ const index=["1","2","3","4","5","6","7"].indexOf(e.key);
6029
+ if(index>=0){setRunView({tab:RUN_TABS[index][0]});rerenderRun(current.id);return true}
6030
+ const view=runView();
6031
+ if(view.tab==="network"&&(e.key==="j"||e.key==="k"||e.key==="ArrowDown"||e.key==="ArrowUp")){
6032
+ const rows=[...document.querySelectorAll(".net-row")];if(!rows.length)return false;
6033
+ const at=rows.findIndex(row=>row.dataset.netItem===view.item);
6034
+ const next=rows[Math.min(rows.length-1,Math.max(0,at<0?0:at+(e.key==="j"||e.key==="ArrowDown"?1:-1)))];
6035
+ e.preventDefault();selectRunItem(current.id,next.dataset.netItem);return true;
6036
+ }
6037
+ if(e.key==="Escape"&&view.item){setRunView({item:"",pane:""});rerenderRun(current.id);return true}
6038
+ if(e.key==="Escape"&&view.tab==="queues"&&view.queue){setRunView({queue:""});rerenderRun(current.id);return true}
6039
+ return false;
6040
+ }
6041
+ `;
6042
+
6043
+ // src/dashboard-trace.ts
6044
+ var DASHBOARD_TRACE_SCRIPT = String.raw`
6045
+ function traceTime(iso){const t=Date.parse(iso);return Number.isFinite(t)?t:NaN}
6046
+ function tracePlural(n,word){return n+" "+word+(n===1?"":"s")}
6047
+ function traceType(event){return String(event.type||"").replace(/^agent\./,"")}
6048
+ function tracePreview(value,limit){
6049
+ let text;
6050
+ if(typeof value==="string")text=value;
6051
+ else{try{text=JSON.stringify(value)}catch{text=String(value)}}
6052
+ text=String(text??"").replace(/\s+/g," ").trim();
6053
+ return text.length>(limit||90)?text.slice(0,(limit||90)-1)+"…":text;
6054
+ }
6055
+ function buildRunTrace(events,run){
6056
+ const ordered=[...(events||[])].sort((a,b)=>(a.sequence??0)-(b.sequence??0));
6057
+ const prompts={},toolSets={},requests={},calls={},items=[],pendingByName={},turns=[];
6058
+ const totals={requests:0,tools:0,tokensIn:0,tokensOut:0,cacheRead:0,cacheWrite:0,modelMs:0,toolMs:0,errors:0};
6059
+ let first=NaN,last=NaN;
6060
+ // One frame per agent: the run's own, then one per subagent running inside it.
6061
+ const frames=[{open:null,previous:null,subagent:null}];
6062
+ const frame=()=>frames[frames.length-1];
6063
+ let turn=null;
6064
+ 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};
6065
+ const requestFor=(data)=>(data.request_id&&requests[data.request_id])||frame().open;
6066
+ const runStart=run?traceTime(run.startedAt||run.createdAt):NaN;
6067
+ const runEnd=run&&run.completedAt?traceTime(run.completedAt):NaN;
6068
+ 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};
6069
+ const addTool=(item)=>{totals.tools++;items.push(item);(pendingByName[item.name]=pendingByName[item.name]||[]).push(item);return item};
6070
+ for(const event of ordered){
6071
+ const at=traceTime(event.timestamp);
6072
+ if(Number.isFinite(at)){if(!(at>=first))first=at;if(!(at<=last))last=at}
6073
+ const type=traceType(event);const data=event.data||{};
6074
+ if(type==="model_request"){
6075
+ if(data.system_prompt&&typeof data.system_prompt.text==="string")prompts[data.system_prompt.hash]=data.system_prompt.text;
6076
+ if(data.tools&&data.tools.list)toolSets[data.tools.hash]=data.tools.list;
6077
+ const traced=data.messages||{};const added=traced.added||[];
6078
+ const base=traced.base?requests[traced.base]:null;const kept=traced.kept||0;
6079
+ const prefix=base?base.messages.slice(0,kept):Array.from({length:kept},()=>null);
6080
+ while(prefix.length<kept)prefix.push(null);
6081
+ const messages=prefix.concat(Array.from({length:traced.skipped||0},()=>null),added);
6082
+ let newFrom=messages.length-added.length;
6083
+ // A run's first request carries the conversation so far; what's new starts at the run's own message.
6084
+ 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}}
6085
+ const f=frame();const previous=f.previous;
6086
+ 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"};
6087
+ 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]};
6088
+ place(item);requests[data.request_id]=item;items.push(item);f.open=item;f.previous=item;continue;
6089
+ }
6090
+ if(type==="model_request_end"){
6091
+ const item=requests[data.request_id];if(!item)continue;
6092
+ item.end=data;item.events.push(event);item.status=data.status||"success";item.endAt=at;
6093
+ item.durationMs=Number.isFinite(data.duration_ms)?data.duration_ms:at-item.startAt;
6094
+ if(Number.isFinite(data.duration_ms)&&Number.isFinite(at))item.startAt=at-data.duration_ms;
6095
+ // Time to first token: waiting on the model, then streaming its answer.
6096
+ if(Number.isFinite(item.firstTokenAt))item.ttftMs=Math.max(0,Math.min(item.durationMs,item.firstTokenAt-item.startAt));
6097
+ item.tokensIn=data.tokens_in;item.tokensOut=data.tokens_out;item.cacheRead=data.cache_read_input_tokens;item.cacheWrite=data.cache_creation_input_tokens;
6098
+ item.response=data.response||[];item.error=data.error;
6099
+ 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;
6100
+ if(Number.isFinite(item.durationMs))totals.modelMs+=item.durationMs;
6101
+ if(item.status!=="success")totals.errors++;
6102
+ for(const message of item.response)for(const call of message.tool_calls||[]){
6103
+ if(!call.id)continue;
6104
+ item.calls.push(call.id);calls[call.id]=calls[call.id]||{name:call.tool_name,request:item};
6105
+ // Adapters that don't stream tool_use: the call starts when the response arrives.
6106
+ 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:[]}));
6107
+ }
6108
+ for(const f of frames)if(f.open===item)f.open=null;
6109
+ continue;
6110
+ }
6111
+ if(type==="text_delta"){
6112
+ const target=requestFor(data);
6113
+ if(target){if(!Number.isFinite(target.firstTokenAt))target.firstTokenAt=at;target.streamed=(target.streamed||"")+String(data.text||"")}
6114
+ continue;
6115
+ }
6116
+ if(type==="model_response_complete"||type==="model_response"){
6117
+ const f=frame();const target=(data.request_id&&requests[data.request_id])||f.open||f.previous;
6118
+ if(target&&(target===f.open||target.id===data.request_id||!target.stopReason)){target.stopReason=data.stop_reason;target.events.push(event);continue}
6119
+ if(!target){
6120
+ // A runtime without request events: the response is all there is.
6121
+ 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};
6122
+ totals.tokensIn+=data.tokens_in||0;totals.tokensOut+=data.tokens_out||0;items.push(place(item));
6123
+ }
6124
+ continue;
6125
+ }
6126
+ if(type==="tool_use"){
6127
+ const request=requestFor(data)||frame().previous;
6128
+ if(request&&!Number.isFinite(request.firstTokenAt))request.firstTokenAt=at;
6129
+ 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]}));
6130
+ if(data.id){calls[data.id]=calls[data.id]||{name:item.name,request};calls[data.id].item=item}
6131
+ continue;
6132
+ }
6133
+ if(type==="tool_use_start"){
6134
+ // The call starts running now: after the calls ahead of it, its permission check and validation.
6135
+ const name=data.name||"tool";
6136
+ let item=data.id&&calls[data.id]&&calls[data.id].item;
6137
+ if(!item)item=(pendingByName[name]||[]).find(candidate=>candidate.status==="pending"&&!candidate.via&&!Number.isFinite(candidate.runAt));
6138
+ 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}}
6139
+ item.runAt=at;item.waitedMs=Number.isFinite(data.waited_ms)?data.waited_ms:undefined;item.events.push(event);
6140
+ continue;
6141
+ }
6142
+ if(type==="tool_use_result"){
6143
+ const id=data.id||data.call_id;const name=data.name||data.tool_name||"tool";
6144
+ let item=id&&calls[id]&&calls[id].item;
6145
+ const queue=pendingByName[name]||[];
6146
+ if(!item)item=queue.find(candidate=>candidate.status==="pending"&&!candidate.via);
6147
+ 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:[]}));
6148
+ const index=queue.indexOf(item);if(index>=0)queue.splice(index,1);
6149
+ item.events.push(event);item.result=data.result||{};item.status=(data.result&&data.result.status)||"success";item.endAt=at;
6150
+ if(item.status==="error"&&/^Permission denied for tool/.test(String(item.result.message||"")))item.status="denied";
6151
+ item.durationMs=Number.isFinite(data.duration_ms)?data.duration_ms:at-item.startAt;
6152
+ if(Number.isFinite(data.duration_ms)&&Number.isFinite(at))item.startAt=at-data.duration_ms;
6153
+ // Asked for, then queued behind the calls ahead of it, then checked, then run.
6154
+ if(Number.isFinite(item.askedAt))item.queuedMs=Math.max(0,item.startAt-item.askedAt);
6155
+ if(Number.isFinite(item.runAt))item.runMs=Math.max(0,at-item.runAt);
6156
+ if(Number.isFinite(item.durationMs))totals.toolMs+=item.durationMs;
6157
+ if(item.status==="error"||item.status==="denied")totals.errors++;
6158
+ continue;
6159
+ }
6160
+ if(type==="turn_start"){
6161
+ // A subagent's turns sit inside its parent's; only the run's own are listed.
6162
+ 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)}
6163
+ continue;
6164
+ }
6165
+ if(type==="turn_end"){
6166
+ const ended=turns.find(candidate=>candidate.id===data.turn_id);
6167
+ 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)}
6168
+ continue;
6169
+ }
6170
+ if(/^foundry\.approval\./.test(type)){
6171
+ const name=data.toolName;const queue=pendingByName[name]||[];
6172
+ if(type==="foundry.approval.requested"){const item=queue.find(candidate=>!candidate.approval&&!candidate.via);if(item){item.approval={id:data.id,status:"pending",requestedAt:event.timestamp,input:data.toolInput};item.events.push(event)}}
6173
+ else{const item=[...items].reverse().find(candidate=>candidate.approval&&(candidate.approval.id===data.approvalId||(candidate.name===name&&candidate.approval.status==="pending")));if(item){item.approval.status=data.status||(type==="foundry.approval.failed"?"failed":type==="foundry.approval.unavailable"?"unavailable":"settled");item.approval.settledAt=event.timestamp;item.events.push(event)}}
6174
+ continue;
6175
+ }
6176
+ if(/^foundry\.repl\.programmatic-tool\./.test(type)){
6177
+ const name=data.tool||"tool";
6178
+ 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}
6179
+ const item=[...items].reverse().find(candidate=>candidate.via==="repl"&&candidate.name===name&&candidate.status==="pending");
6180
+ 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++}
6181
+ 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]})}
6182
+ continue;
6183
+ }
6184
+ if(type==="subagent_invoked"){
6185
+ const call=data.call_id&&calls[data.call_id]&&calls[data.call_id].item;
6186
+ 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]});
6187
+ items.push(item);frames.push({open:null,previous:null,subagent:item});continue;
6188
+ }
6189
+ if(type==="subagent_completed"){
6190
+ const index=frames.findLastIndex(candidate=>candidate.subagent&&(data.call_id?candidate.subagent.key==="s:"+data.call_id:candidate.subagent.name===data.name));
6191
+ const item=index>0?frames[index].subagent:[...items].reverse().find(candidate=>candidate.kind==="subagent"&&candidate.name===data.name&&candidate.status==="pending");
6192
+ if(index>0)frames.splice(index);
6193
+ if(item){item.status=data.status||"success";item.endAt=at;item.durationMs=at-item.startAt;item.message=data.message;item.events.push(event)}
6194
+ continue;
6195
+ }
6196
+ }
6197
+ const start=Number.isFinite(runStart)?Math.min(runStart,Number.isFinite(first)?first:runStart):first;
6198
+ const live=run&&(run.status==="running"||run.status==="pending");
6199
+ const end=live?Math.max(Date.now(),Number.isFinite(last)?last:0):Number.isFinite(runEnd)?Math.max(runEnd,Number.isFinite(last)?last:runEnd):last;
6200
+ for(const item of items){if(item.kind==="model"){item.systemPrompt=prompts[item.promptHash];item.tools=toolSets[item.toolsHash]}}
6201
+ for(const item of turns)if(item.status==="pending"&&!live&&Number.isFinite(end)){item.endAt=end;item.durationMs=end-item.startAt}
6202
+ return{items,turns,prompts,toolSets,totals,start,end};
6203
+ }
6204
+
6205
+ /* Console levels follow DevTools: errors, warnings, info, and verbose detail hidden by default. */
6206
+ function describeEvent(event){
6207
+ const type=traceType(event);const data=event.data||{};
6208
+ const level=(value,message,source)=>({level:value,message,source:source||event.category||"system"});
6209
+ if(type==="log.stderr")return level("warn",String(data.message??""),"stderr");
6210
+ if(type==="log.stdout")return level("info",String(data.message??""),"stdout");
6211
+ if(type==="run.failed")return level("error","Run failed"+(data.error?": "+data.error:""));
6212
+ if(type==="run.timeout")return level("error","Run timed out");
6213
+ if(type==="run.cancelled")return level("warn","Run cancelled");
6214
+ if(type==="run.retry")return level("warn","Retrying: attempt "+data.attempt+" of "+data.maxAttempts);
6215
+ if(/^run\./.test(type))return level("info","Run "+type.slice(4).replace(/-/g," "));
6216
+ if(type==="model_request"){const m=data.messages||{};const added=(m.added||[]).length;return level("info","→ Model request "+tracePreview(data.model,40)+" · "+(m.total??0)+" messages"+(added&&m.base?" ("+added+" new)":"")+" · "+(data.context||[]).length+" context · "+((data.tools&&data.tools.names)||[]).length+" tools"+(data.purpose==="compaction"?" · compaction":""))}
6217
+ if(type==="model_request_end"){
6218
+ if(data.status==="error")return level("error","← Model request failed after "+data.duration_ms+"ms: "+(data.error||"unknown error"));
6219
+ if(data.status==="aborted")return level("warn","← Model request aborted after "+data.duration_ms+"ms");
6220
+ const calls=(data.response||[]).reduce((n,m)=>n+(m.tool_calls||[]).length,0);
6221
+ return level("info","← Model response in "+data.duration_ms+"ms · "+(data.tokens_in??"?")+" in / "+(data.tokens_out??"?")+" out"+(calls?" · "+calls+" tool call"+(calls===1?"":"s"):""));
6222
+ }
6223
+ if(type==="model_response_complete"||type==="model_response")return level("verbose","Response"+(data.stop_reason?" ("+data.stop_reason+")":"")+": "+tracePreview(data.text||"",120));
6224
+ if(type==="text_delta")return level("verbose","Streamed text: "+tracePreview(data.text,160));
6225
+ if(type==="tool_use")return level("info","Tool call "+data.name+"("+tracePreview(data.input,100)+")");
6226
+ if(type==="tool_use_start")return level("verbose",data.name+" started"+(data.waited_ms>=1000?" after "+data.waited_ms+"ms of permission checks":""),"tool");
6227
+ 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");
6228
+ if(type==="turn_end"){
6229
+ const time=Number.isFinite(data.duration_ms)?" after "+data.duration_ms+"ms":"";
6230
+ if(data.status==="error")return level("error","Turn failed"+time+(data.error?": "+tracePreview(data.error,140):""),"run");
6231
+ if(data.status==="aborted")return level("warn","Turn aborted"+time,"run");
6232
+ if(data.status==="suspended")return level("warn","Turn suspended"+time+": a tool call is waiting for a decision","run");
6233
+ return level("info","Turn finished"+time,"run");
6234
+ }
6235
+ 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");
6236
+ if(type==="event_received"){
6237
+ const what=(data.kind?data.kind+" from ":"")+data.source;const preview=data.preview?": "+tracePreview(data.preview,120):"";
6238
+ if(data.disposition==="dropped")return level("warn","Event dropped: "+what+preview,"queue");
6239
+ if(data.disposition==="duplicate")return level("verbose","Duplicate event ignored: "+what,"queue");
6240
+ return level("info","Event "+({queued:"queued",woke:"woke the agent",deferred:"deferred"}[data.disposition]||data.disposition)+": "+what+preview,"queue");
6241
+ }
6242
+ 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");
6243
+ if(type==="event_dropped")return level("warn","Event "+data.id+" dropped ("+data.reason+")","queue");
6244
+ if(type==="event_wake_failed")return level("error","A turn for "+tracePlural((data.ids||[]).length,"event")+" failed: "+tracePreview(data.message,140),"queue");
6245
+ if(type==="tool_use_result"){
6246
+ 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":"";
6247
+ if(status==="error")return level("error",name+" failed"+time+": "+tracePreview(data.result.message||data.result.data,140));
6248
+ if(status==="aborted")return level("warn",name+" aborted"+time);
6249
+ return level("info",name+" returned"+time+": "+tracePreview(data.result&&data.result.data,120));
6250
+ }
6251
+ if(type==="token_consumption")return level("verbose","Tokens: "+tracePreview(data.consumption,120));
6252
+ if(type==="runtime_context")return level("verbose","Runtime context: "+(data.messages||[]).map(m=>tracePreview(m.text,60)).join(" | "));
6253
+ if(type==="compaction_start")return level("info","Compacting the conversation at "+data.current_token_consumption+" tokens");
6254
+ if(type==="compaction_end")return level("info","Compaction finished");
6255
+ if(type==="foundry.approval.requested")return level("warn","Waiting for approval: "+data.toolName+"("+tracePreview(data.toolInput,80)+")");
6256
+ if(type==="foundry.approval.settled")return level(data.status==="approved"?"info":"warn","Approval "+data.status+": "+data.toolName);
6257
+ if(type==="foundry.approval.failed"||type==="foundry.approval.unavailable")return level("error","Approval "+type.split(".").pop()+": "+(data.toolName||"")+(data.error?" · "+data.error:""));
6258
+ if(/^foundry\.repl\.programmatic-tool\./.test(type)){const what=type.split(".").pop();return level(what==="completed"||what==="started"?"verbose":"error","REPL "+data.function+"() "+what+(data.durationMs!==undefined?" in "+data.durationMs+"ms":"")+(data.reason?": "+data.reason:""))}
6259
+ if(type==="hook_invoked")return level("info","Hook /"+data.name);
6260
+ if(type==="skill_invoked")return level("info","Skill "+data.name+" ("+data.source+")");
6261
+ if(type==="subagent_invoked")return level("info","Subagent "+data.name+": "+tracePreview(data.prompt,100));
6262
+ if(type==="subagent_completed")return level(data.status==="error"?"error":"info","Subagent "+data.name+" "+data.status+(data.message?": "+tracePreview(data.message,100):""));
6263
+ if(type==="foundry.guidance.state")return level("verbose","Guidance state");
6264
+ if(/fail|error/.test(type))return level("error",type+(data.error?": "+tracePreview(data.error,140):""));
6265
+ if(/denied|limit|warn|unavailable/.test(type))return level("warn",type);
6266
+ if(/^foundry\.(assembly|definition|layer|subscriber|repl|mesh|working-environment|installation|application)\./.test(type))return level("verbose",type.replace(/^foundry\./,""),"assembly");
6267
+ return level("verbose",type);
6268
+ }
6269
+ function buildConsole(events){
6270
+ // A streamed reply is one line: chunks of one request join, wherever they arrive.
6271
+ const rows=[];let stream=null;const streams={};
6272
+ for(const event of [...(events||[])].sort((a,b)=>(a.sequence??0)-(b.sequence??0))){
6273
+ if(traceType(event)==="text_delta"){
6274
+ const request=event.data&&event.data.request_id;
6275
+ const current=request?streams[request]:stream;
6276
+ const row=current||{key:"c:"+(event.id||event.sequence),level:"verbose",source:"model",timestamp:event.timestamp,type:"text_delta",text:"",chunks:0,events:[]};
6277
+ if(!current){rows.push(row);if(request)streams[request]=row}
6278
+ stream=row;
6279
+ row.text+=String((event.data&&event.data.text)||"");row.chunks++;row.events.push(event);
6280
+ row.message="Streamed text ("+row.chunks+" chunk"+(row.chunks===1?"":"s")+"): "+tracePreview(row.text,160);
6281
+ row.data={text:row.text,chunks:row.chunks,...(request?{request_id:request}:{})};
6282
+ continue;
6283
+ }
6284
+ stream=null;
6285
+ const described=describeEvent(event);
6286
+ rows.push({key:"c:"+(event.id||event.sequence),level:described.level,source:described.source,message:described.message,timestamp:event.timestamp,type:event.type,data:event.data,events:[event]});
6287
+ }
6288
+ return rows;
6289
+ }
6290
+ `;
6291
+
6292
+ // src/dashboard-foundry.ts
6293
+ var DASHBOARD_FOUNDRY_SCRIPT = String.raw`
6294
+ function foundryAt(event){const t=Date.parse(event&&event.timestamp);return Number.isFinite(t)?t:NaN}
6295
+ function foundrySorted(events){return[...(events||[])].sort((a,b)=>(a.sequence??0)-(b.sequence??0))}
6296
+
6297
+ /* ---- Composition ---- */
6298
+ const COMPOSITION_LEGACY_STEPS={"foundry.application.transmission-tools.mounted":["transmissions","App transmissions"],"foundry.working-environment.mounted":["workbench","Working environment"]};
6299
+ function buildComposition(events){
6300
+ const ordered=foundrySorted(events);
6301
+ 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};
6302
+ const open={};
6303
+ for(const event of ordered){
6304
+ const type=traceType(event);const data=event.data||{};const at=foundryAt(event);
6305
+ 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}
6306
+ 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}
6307
+ if(type==="foundry.assembly.composed"){
6308
+ result.composed=data;result.legacy=false;result.endAt=at;
6309
+ if(Number.isFinite(data.durationMs)&&!(result.startAt<=at-data.durationMs))result.startAt=at-data.durationMs;
6310
+ result.steps=(data.steps||[]).map(step=>({...step,tools:[...(step.tools||[])]}));
6311
+ result.tools=[...(data.tools||[])];result.installations=data.installations||[];
6312
+ result.apps=data.apps||[];result.playbooks=data.playbooks||[];result.schedules=data.schedules||[];
6313
+ result.delegates=data.delegates||[];result.durableSubagents=data.durableSubagents||[];result.mesh=data.mesh||null;
6314
+ result.hooks=data.hooks||[];result.skills=data.skills||[];result.subagents=data.subagents||[];result.calls=data.calls||[];
6315
+ result.delegation=data.delegation||null;
6316
+ if(data.repl&&!result.repl)result.repl={};
6317
+ if(data.workingEnvironment&&!result.workingEnvironment)result.workingEnvironment={};
6318
+ continue;
6319
+ }
6320
+ if(type==="foundry.definition.memory.mounted"){result.memory.push(data.id);continue}
6321
+ if(type==="foundry.layer.mounted"){result.layers.push(data.id);continue}
6322
+ if(type==="foundry.subscriber.mounted"){result.subscribers.push(data.id);continue}
6323
+ if(type==="foundry.working-environment.mounted"){result.workingEnvironment={...(result.workingEnvironment||{}),...data}}
6324
+ if(type==="foundry.repl.mounted"){result.repl={...(result.repl||{}),...data};continue}
6325
+ if(type==="foundry.definition.inboxes.loaded"){result.inboxes=data;continue}
6326
+ if(type==="scheduled-action.created"){result.scheduled.push({id:data.commandId,recurring:data.recurring,nextRunAt:data.nextRunAt});continue}
6327
+ if(result.legacy){
6328
+ // Runs recorded before foundry.assembly.composed: what the mount events say.
6329
+ 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})}
6330
+ if(type==="foundry.application.mcp.mounted")result.steps.push({step:"mcp",label:data.id,id:data.id,tools:[...(data.tools||[])],ms:NaN});
6331
+ 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})}
6332
+ if(type==="foundry.definition.playbooks.composed")result.playbooks=(data.names||[]).map(name=>({name}));
6333
+ if(type==="foundry.definition.schedules.loaded")result.schedules=(data.names||[]).map(name=>({name}));
6334
+ if(type==="foundry.definition.delegates.loaded")result.delegates=(data.delegates||[]).map(agent=>({agent}));
6335
+ if(type==="foundry.mesh.mounted")result.mesh={hosted:true,threads:data.open,...(data.thread?{thread:data.thread}:{})};
6336
+ }
6337
+ if(type==="turn_start"&&!Number.isFinite(result.endAt))result.endAt=at;
6338
+ }
6339
+ if(Number.isFinite(result.startAt)&&Number.isFinite(result.endAt))result.durationMs=Math.max(0,result.endAt-result.startAt);
6340
+ 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};
6341
+ if(!result.tools.length)result.tools=Object.keys(result.origins);
6342
+ return result;
6343
+ }
6344
+
6345
+ /* ---- Queues: what crossed the run's boundary ---- */
6346
+ function queueChannel(kind,source){
6347
+ const k=String(kind||"");
6348
+ if(k==="transmission"||/^foundry:route:/.test(String(source||"")))return"transmission";
6349
+ if(k==="agent-message")return"agent message";
6350
+ if(k==="mesh")return"mesh";
6351
+ if(/^delegation|^reply$/.test(k))return"delegation";
6352
+ if(/approval/.test(k))return"approval";
6353
+ return k||"event";
6354
+ }
6355
+ const QUEUE_PHASE={wake:"as the turn's message",request:"before the request",loop:"between tool steps"};
6356
+ function queueCommand(data){
6357
+ const type=data.type||"command";
6358
+ 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+")":""):"";
6359
+ if(type==="transmit")return{channel:"transmission",title:"Transmission "+(data.routeId||data.transmissionId||""),preview:tracePreview(data.payload,160)};
6360
+ if(type==="spawn")return{channel:"spawn",title:"Spawn "+(data.definitionId||""),preview:tracePreview(data.message,160)};
6361
+ if(type==="schedule")return{channel:"schedule",title:"Schedule "+timing,preview:tracePreview(data.message,160)};
6362
+ if(/^schedule\./.test(type))return{channel:"schedule",title:"Schedule "+type.slice(9)+" "+(data.activationId||""),preview:data.patch?tracePreview(data.patch,160):""};
6363
+ if(type==="sleep")return{channel:"sleep",title:"Sleep until "+(data.wakeAt||""),preview:tracePreview(data.message,160)};
6364
+ if(type==="background")return{channel:"background",title:"Background run",preview:tracePreview(data.message,160)};
6365
+ if(type==="delegate")return{channel:"delegation",title:"Delegate to "+data.to,preview:tracePreview(data.task,160)};
6366
+ if(type==="delegate.reply")return{channel:"delegation",title:"Reply to worker",preview:tracePreview(data.message,160)};
6367
+ if(type==="delegate.ask")return{channel:"delegation",title:"Ask the delegator",preview:tracePreview(data.question,160)};
6368
+ if(type==="agent.message")return{channel:"agent message",title:"Message "+data.to,preview:tracePreview(data.message,160)};
6369
+ 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)};
6370
+ if(/^mesh\./.test(type))return{channel:"mesh",title:"Mesh "+type.slice(5),preview:""};
6371
+ return{channel:"command",title:type,preview:""};
6372
+ }
6373
+ function buildQueues(events,run,trace){
6374
+ const ordered=foundrySorted(events);
6375
+ const rows=[];const byEvent={};const byCommand={};const byDelegation={};const approvals={};
6376
+ const models=((trace&&trace.items)||[]).filter(item=>item.kind==="model"&&!item.legacy);
6377
+ const seenAfter=(sequence)=>models.find(item=>(item.sequence??0)>sequence)||null;
6378
+ const source=run&&run.input&&run.input.source;
6379
+ if(run){
6380
+ const message=run.input&&run.input.message;
6381
+ const text=typeof message==="string"?message:Array.isArray(message)?message.filter(part=>part&&part.type==="text").map(part=>part.text).join(" "):"";
6382
+ const kind=(source&&source.kind)||"direct";
6383
+ const delegationTitle=source&&/^result:/.test(String(source.id||""))?"Delegation result":source&&/^delegation_/.test(String(source.id||""))?"Delegated task":"Delegation update";
6384
+ 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"};
6385
+ const first=models[0]||null;
6386
+ 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:[]});
6387
+ }
6388
+ let turnSeen=false;
6389
+ for(const event of ordered){
6390
+ const type=traceType(event);const data=event.data||{};const at=foundryAt(event);
6391
+ if(type==="turn_start")turnSeen=true;
6392
+ if(type==="event_received"){
6393
+ 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]};
6394
+ // The first delivery of an event turn is what started the run.
6395
+ 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}
6396
+ byEvent[data.id]=row;rows.push(row);continue;
6397
+ }
6398
+ if(type==="event_injected"){
6399
+ 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)}
6400
+ continue;
6401
+ }
6402
+ if(type==="event_dropped"){const row=byEvent[data.id];if(row){row.status="dropped ("+data.reason+")";row.events.push(event)}continue}
6403
+ if(type==="inbox_injected"){
6404
+ const seen=seenAfter(event.sequence??0);
6405
+ 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;
6406
+ }
6407
+ if(type==="tool_use"&&data.name==="glove_post_to_inbox"){
6408
+ const input=data.input||{};
6409
+ 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;
6410
+ }
6411
+ if(type==="foundry.core.command"){
6412
+ if(data.type==="playbook.sync"||data.type==="schedule.sync")continue;
6413
+ const described=queueCommand(data);
6414
+ const row={key:"q:c:"+(data.id||event.sequence),dir:"out",...described,status:"sent",at,detail:data,events:[event]};
6415
+ if(data.id)byCommand[data.id]=row;if(data.delegationId)byDelegation[data.delegationId]=row;
6416
+ rows.push(row);continue;
6417
+ }
6418
+ 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}
6419
+ 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}
6420
+ if(type==="scheduled-action.created"){const row=byCommand[data.commandId];if(row){row.status="scheduled";row.nextRunAt=data.nextRunAt;row.events.push(event)}continue}
6421
+ 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}
6422
+ if(type==="delegation.started"){const row=byDelegation[data.delegationId];if(row){row.status="started";row.childRunId=data.workerRunId;row.events.push(event)}continue}
6423
+ 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}
6424
+ if(type==="delegation.delivered"&&data.mode==="live"){
6425
+ // Answers and updates handed to this run while it ran: a waiting question is answered.
6426
+ const asked=[...rows].reverse().find(candidate=>candidate.dir==="out"&&candidate.detail&&candidate.detail.type==="delegate.ask"&&candidate.status!=="answered");
6427
+ if(asked){asked.status="answered";asked.events.push(event)}
6428
+ 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]});
6429
+ continue;
6430
+ }
6431
+ 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}
6432
+ if(type==="foundry.approval.settled"||type==="foundry.approval.failed"||type==="foundry.approval.unavailable"){
6433
+ const row=approvals[data.approvalId]||[...rows].reverse().find(candidate=>candidate.channel==="approval"&&candidate.detail.toolName===data.toolName&&candidate.status==="waiting");
6434
+ if(row){row.status=data.status||type.split(".").pop();row.settledAt=at;row.events.push(event)}continue;
6435
+ }
6436
+ }
6437
+ return rows.sort((a,b)=>(Number.isFinite(a.at)?a.at:0)-(Number.isFinite(b.at)?b.at:0));
6438
+ }
6439
+
6440
+ /* ---- Call chain: the run among the runs it came from and started ---- */
6441
+ const CHAIN_COMMANDS={spawn:"spawned",schedule:"scheduled",sleep:"woke from sleep",background:"background run",["agent.message"]:"messaged"};
6442
+ function buildRunChain(runId,runs,events){
6443
+ const byId={};for(const run of runs||[])byId[run.id]=run;
6444
+ const parents={};const children={};const seen=new Set();
6445
+ const link=(from,to,label,detail)=>{
6446
+ if(!from||!to||from===to)return;const key=from+">"+to+">"+label;if(seen.has(key))return;seen.add(key);
6447
+ const edge={from,to,label,...(detail?{detail}:{})};(children[from]=children[from]||[]).push(edge);(parents[to]=parents[to]||[]).push(edge);
6448
+ };
6449
+ const delegations={};const commands={};const replies=[];
6450
+ for(const event of foundrySorted(events)){
6451
+ const type=traceType(event);const data=event.data||{};
6452
+ if(type==="foundry.core.command"&&data.id){commands[data.id]={runId:event.runId,type:data.type};continue}
6453
+ 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}
6454
+ if(type==="delegation.replied"){replies.push({from:event.runId,delegationId:data.delegationId});continue}
6455
+ if(type==="core.command.accepted"){link(event.runId,data.childRunId,CHAIN_COMMANDS[data.type]||data.type||"started");continue}
6456
+ if(type==="run.steered"){link(data.fromRunId,data.toRunId||event.runId,"steered");continue}
6457
+ }
6458
+ // Answers reach a worker that is still running.
6459
+ for(const reply of replies){const delegation=delegations[reply.delegationId];if(delegation)link(reply.from,delegation.workerRunId,"replied",reply.delegationId)}
6460
+ // What a run hears back arrives as a run of its own, named by what it answers.
6461
+ const COMMAND_EDGES={["delegate.ask"]:"asked",["delegate.reply"]:"replied",["agent.message"]:"messaged"};
6462
+ for(const run of runs||[]){
6463
+ const source=run.input&&run.input.source;
6464
+ if(!source||!source.id||source.kind==="direct")continue;
6465
+ const id=String(source.id);
6466
+ if(/^result:/.test(id)){link(id.slice(7),run.id,"reported back");continue}
6467
+ if(commands[id]){link(commands[id].runId,run.id,COMMAND_EDGES[commands[id].type]||commands[id].type);continue}
6468
+ const delegation=source.kind==="delegation"&&delegations[id];
6469
+ if(delegation&&run.id!==delegation.workerRunId&&run.agent!==delegation.to&&delegation.workerRunId)link(delegation.workerRunId,run.id,"reported back",id);
6470
+ }
6471
+ const node=(id,edge)=>{const run=byId[id];return{id,run:run||null,edge:edge||null}};
6472
+ const ancestors=[];const visited=new Set([runId]);let current=runId;
6473
+ 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}
6474
+ const top=ancestors.length?ancestors[0].run:byId[runId];
6475
+ 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;
6476
+ const started=(id)=>{const run=byId[id];const at=run?Date.parse(run.createdAt):NaN;return Number.isFinite(at)?at:Infinity};
6477
+ 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});
6478
+ const self=node(runId,parents[runId]&&parents[runId][0]);
6479
+ self.children=descend(runId,0,new Set([runId]));
6480
+ return{origin,ancestors,self,parents:parents[runId]||[]};
6481
+ }
6482
+ `;
6483
+
6484
+ // src/dashboard-run-foundry.ts
6485
+ var DASHBOARD_RUN_FOUNDRY_SCRIPT = String.raw`
6486
+ /* ---- Composition ---- */
6487
+ 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"]];
6488
+ 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}
6489
+ function toolChip(name,counts,extra){
6490
+ const calls=counts[name]||0;
6491
+ 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>';
6492
+ }
6493
+ function compositionTimeline(comp){
6494
+ const rows=[];
6495
+ 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"});
6496
+ if(comp.composed&&Number.isFinite(comp.endAt)){
6497
+ let at=comp.endAt-(comp.composed.durationMs||0);
6498
+ 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}
6499
+ }
6500
+ 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.");
6501
+ 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);
6502
+ 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>'
6503
+ +'<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>'
6504
+ +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("")
6505
+ +'</tbody></table>';
6506
+ }
6507
+ function compositionTools(comp,trace,counts){
6508
+ const offered=(trace.items.filter(item=>item.kind==="model"&&!item.legacy).at(-1)||{}).toolNames||[];
6509
+ const unattributed=offered.filter(name=>!comp.origins[name]);
6510
+ const steps=comp.steps.filter(step=>step.tools.length);
6511
+ if(!steps.length&&!offered.length)return empty("No tools recorded","");
6512
+ 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>'
6513
+ +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("")
6514
+ +(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>':"");
6515
+ }
6516
+ function compositionApps(comp,counts,instance){
6517
+ const installs=comp.installations.length?comp.installations:(instance?instance.installations:[]);
6518
+ const apps=comp.apps;
6519
+ 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.");
6520
+ const stepFor=(install)=>comp.steps.find(step=>step.step==="installation"&&step.id===install.id);
6521
+ const mcp=comp.steps.find(step=>step.step==="mcp"&&!step.id);
6522
+ return'<p class="dt-note">What the instance has installed, and what each installation gave this run.</p>'
6523
+ +installs.map(install=>{
6524
+ const app=apps.find(item=>item.id===install.id);const step=stepFor(install);
6525
+ const tools=app?app.tools:step?step.tools.map(name=>({name})):[];
6526
+ 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>'
6527
+ +(app&&app.description?'<p class="dt-note">'+esc(app.description)+'</p>':"")
6528
+ +(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>')
6529
+ +'</section>';
6530
+ }).join("")
6531
+ +(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>':"");
6532
+ }
6533
+ function compositionView(run,trace,events,view){
6534
+ const comp=buildComposition(events);const counts=toolCallCounts(trace);
6535
+ const instance=state.instances.find(item=>item.id===run.agentId);
6536
+ const node=COMPOSITION_NODES.some(entry=>entry[1]===view.cnode)?view.cnode:"timeline";
6537
+ const toolCount=comp.steps.reduce((sum,step)=>sum+step.tools.length,0);
6538
+ 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)||""};
6539
+ let tree="";let group="";
6540
+ 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>'});
6541
+ const list=(items,format)=>items.length?'<div class="cap-list">'+items.map(format).join("")+'</div>':'<p class="dt-note">None.</p>';
6542
+ let body="";
6543
+ if(node==="timeline")body=compositionTimeline(comp);
6544
+ else if(node==="tools")body=compositionTools(comp,trace,counts);
6545
+ else if(node==="apps")body=compositionApps(comp,counts,instance);
6546
+ else if(node==="playbooks"){
6547
+ const stored=instance?instance.playbooks:[];
6548
+ 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>'
6549
+ +'<div class="dt-section">Composed by the definition</div>'+list(comp.playbooks,item=>'<span class="cap">'+esc(item.name||item.id)+'</span>')
6550
+ +'<div class="dt-section">Stored on the instance</div>'+(stored.length?jsonBlock(stored,"comp:playbooks"):'<p class="dt-note">None.</p>');
6551
+ }
6552
+ else if(node==="schedules"){
6553
+ const activations=(state.activations||[]).filter(item=>item.agentId===run.agentId||item.createdByRunId===run.id);
6554
+ 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):"";
6555
+ 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>'
6556
+ +'<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>')
6557
+ +(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))])):"")
6558
+ +'<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>');
6559
+ }
6560
+ else if(node==="delegates"){
6561
+ 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>'
6562
+ +(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>']]):"")
6563
+ +'<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>')
6564
+ +'<div class="dt-section">Durable subagents</div>'+list(comp.durableSubagents,name=>'<span class="cap">'+esc(name)+'</span>')
6565
+ +(comp.composed?'<p class="dt-note">'+count(comp.composed.openDelegations||0,"delegation")+' open when the run started.</p>':"");
6566
+ }
6567
+ 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.");
6568
+ 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>':"");
6569
+ 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>');
6570
+ 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>');
6571
+ 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>';
6572
+ }
6573
+
6574
+ /* ---- Queues ---- */
6575
+ 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":""}
6576
+ function queuesView(run,trace,events,view){
6577
+ state.queues=state.queues||{filter:"",dir:"all"};
6578
+ const q=state.queues;const rows=buildQueues(events,run,trace);const term=q.filter.trim().toLowerCase();
6579
+ const visible=rows.filter(row=>(q.dir==="all"||row.dir===q.dir)&&(!term||(row.channel+" "+row.title+" "+row.preview+" "+row.status).toLowerCase().includes(term)));
6580
+ const selected=rows.find(row=>row.key===view.queue);const base=new Date(runStartedAt(run)).getTime();
6581
+ const models=Object.fromEntries(trace.items.filter(item=>item.kind==="model").map(item=>[item.key,item]));
6582
+ const inbound=rows.filter(row=>row.dir==="in").length;
6583
+ 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>'
6584
+ +'<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>'
6585
+ +'<span class="dt-summary">'+esc(inbound)+' in · '+esc(rows.length-inbound)+' out</span></div>';
6586
+ html+='<div class="net-split'+(selected?" has-detail":"")+'"><div class="net-list" data-scroll-key="queue-list">';
6587
+ 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.");
6588
+ 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>'
6589
+ +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("")
6590
+ +'</tbody></table>'+(visible.length?"":empty("Nothing matches","Clear the filter to see every message."));
6591
+ html+='</div>'+(selected?queueDetail(selected,run,models):"")+'</div>';
6592
+ return html;
6593
+ }
6594
+ function queueDetail(row,run,models){
6595
+ const base=new Date(runStartedAt(run)).getTime();
6596
+ 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>'
6597
+ +'<div class="nd-title"><b>'+esc(row.title)+'</b><span>'+(row.dir==="in"?"inbound":"outbound")+" · "+esc(row.channel)+'</span></div><div class="nd-body">'
6598
+ +kv([["Status",'<span class="st '+queueStatusClass(row.status)+'">'+esc(row.status)+'</span>'+(row.error?' <span class="muted">'+esc(row.error)+'</span>':"")],
6599
+ [row.dir==="in"?"Arrived":"Sent",esc(offsetFrom(base,isoAt(row.at)))+' <span class="muted">'+esc(fmtTime(isoAt(row.at)))+'</span>'],
6600
+ Number.isFinite(row.injectedAt)?["Joined the conversation",esc(offsetFrom(base,isoAt(row.injectedAt)))]:null,
6601
+ row.seenBy&&models[row.seenBy]?["First seen by",itemLink(row.seenBy,models[row.seenBy].name)]:null,
6602
+ row.call?["Tool call",itemLink(row.call,"Open in Network")]:null,
6603
+ row.childRunId?["Run",'<a class="link mono" href="/runs/'+attr(row.childRunId)+'" data-link>'+esc(row.childRunId)+'</a>']:null,
6604
+ row.nextRunAt?["Next run",esc(fmtTime(row.nextRunAt))]:null])
6605
+ +(row.preview?'<div class="dt-section">Content</div><pre class="dt-pre">'+esc(row.preview)+'</pre>':"")
6606
+ +'<div class="dt-section">Detail</div>'+jsonBlock(row.detail,row.key+":detail")
6607
+ +(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"):"")
6608
+ +'</div></aside>';
6609
+ }
6610
+
6611
+ /* ---- Call chain ---- */
6612
+ function ensureChainEvents(id){
6613
+ state.chain=state.chain||{events:null,at:0,loading:false};
6614
+ const c=state.chain;if(c.loading||(c.events&&Date.now()-c.at<10000))return;
6615
+ c.loading=true;
6616
+ 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)});
6617
+ }
6618
+ function chainCard(node){
6619
+ const run=node.run;
6620
+ 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>';
6621
+ }
6622
+ function chainNode(node,self){
6623
+ const run=node.run;const edge=node.edge;
6624
+ 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>';
6625
+ return'<div class="chain-node'+(self?" self":"")+'">'+(edge?'<span class="chain-edge">'+esc(edge.label)+'</span>':"")+'<div class="chain-card">'+head+'</div>'
6626
+ +((node.children||[]).length?'<div class="chain-children">'+node.children.map(child=>chainNode(child,false)).join("")+'</div>':"")+'</div>';
6627
+ }
6628
+ function chainView(run,events){
6629
+ ensureChainEvents(run.id);
6630
+ const loaded=state.chain&&state.chain.events;
6631
+ const all=(loaded||[]).concat(events);
6632
+ const chain=buildRunChain(run.id,state.runs,all);
6633
+ 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>':"";
6634
+ 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;
6635
+ // Each ancestor, then how it led to the run below it.
6636
+ for(const ancestor of chain.ancestors)html+='<div class="chain-node">'+chainCard(ancestor)+'<span class="chain-edge">'+esc(ancestor.edge.label)+'</span></div>';
6637
+ html+=chainNode({...chain.self,edge:null},true)+'</div>';
6638
+ 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.");
6639
+ return html+'</div>';
6640
+ }
6641
+ function bindRunFoundry(id){
6642
+ document.querySelectorAll("[data-comp-node]").forEach(node=>node.onclick=()=>{setRunView({cnode:node.dataset.compNode});rerenderRun(id)});
6643
+ 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)});
6644
+ 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)});
6645
+ document.querySelectorAll("[data-queue-dir]").forEach(node=>node.onclick=()=>{state.queues.dir=node.dataset.queueDir;rerenderRun(id)});
6646
+ const close=document.querySelector("[data-queue-close]");if(close)close.onclick=()=>{setRunView({queue:""});rerenderRun(id)};
6647
+ const input=$("queue-filter");
6648
+ 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{}}};
6649
+ }
6650
+ `;
6651
+
5018
6652
  // src/dashboard-script.ts
5019
6653
  var ICON_PATHS_JSON = JSON.stringify(PHOSPHOR_ICON_PATHS);
5020
6654
  var DASHBOARD_SCRIPT = String.raw`
5021
6655
  const ICON_PATHS=${ICON_PATHS_JSON};
5022
- const state={manifest:null,instances:[],subscriptions:[],connections:[],runs:[],events:[],health:null,transmissions:[],accounts:[],routes:[],bindings:[],activations:[],approvals:[],conversations:{},workspaces:{},chat:{agentId:"",conversationId:"",transcript:null,query:"",draft:"",files:[],sending:false,error:"",optimistic:null,historyOffset:null,renderedConversationId:"",scrollToBottom:false,scrollToTop:false},showAllEvents:false,eventCategory:"all",ready:false,cursor:-1,liveAt:null};
6656
+ const state={manifest:null,instances:[],subscriptions:[],connections:[],runs:[],events:[],health:null,transmissions:[],accounts:[],routes:[],bindings:[],activations:[],approvals:[],conversations:{},workspaces:{},chat:{agentId:"",conversationId:"",transcript:null,query:"",draft:"",files:[],sending:false,error:"",optimistic:null,historyOffset:null,renderedConversationId:"",scrollToBottom:false,scrollToTop:false},runEvents:{},network:{filter:"",kind:"all"},console:{filter:"",level:"default",source:"all"},ready:false,cursor:-1,liveAt:null};
5023
6657
  const $=id=>document.getElementById(id);
5024
6658
  const esc=value=>String(value??"").replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","'":"&#39;"}[c]));
5025
6659
  const attr=value=>esc(value).replace(/\x60/g,"&#96;");
@@ -5093,6 +6727,10 @@ async function copyValue(button){
5093
6727
  }catch{toast("Could not copy to the clipboard")}
5094
6728
  }
5095
6729
 
6730
+ ${DASHBOARD_TRACE_SCRIPT}
6731
+ ${DASHBOARD_FOUNDRY_SCRIPT}
6732
+ ${DASHBOARD_RUN_SCRIPT}
6733
+ ${DASHBOARD_RUN_FOUNDRY_SCRIPT}
5096
6734
  /* ---- View state. Live updates repaint the page, so the parts a person is
5097
6735
  actively using -- scroll, focus, caret, expanded rows -- survive it. ---- */
5098
6736
  function captureView(){
@@ -5104,13 +6742,17 @@ function captureView(){
5104
6742
  caret:active&&typeof active.selectionStart==="number"?active.selectionStart:null,
5105
6743
  open:[...document.querySelectorAll("[data-event-key].open")].map(node=>node.dataset.eventKey),
5106
6744
  details:[...document.querySelectorAll("details[data-persist]")].filter(node=>node.open).map(node=>node.dataset.persist),
6745
+ closed:[...document.querySelectorAll("details[data-persist]")].filter(node=>!node.open).map(node=>node.dataset.persist),
6746
+ scrolls:[...document.querySelectorAll("[data-scroll-key]")].map(node=>({key:node.dataset.scrollKey,top:node.scrollTop,bottom:node.scrollHeight-node.scrollTop-node.clientHeight<40})),
5107
6747
  chatScroll:chatScroll?{top:chatScroll.scrollTop,nearBottom:chatScroll.scrollHeight-chatScroll.scrollTop-chatScroll.clientHeight<80}:null
5108
6748
  };
5109
6749
  }
5110
6750
  function restoreView(view){
5111
6751
  if(!view)return;
5112
6752
  if(view.open.length)document.querySelectorAll("[data-event-key]").forEach(node=>{if(view.open.includes(node.dataset.eventKey))node.classList.add("open")});
5113
- if(view.details.length)document.querySelectorAll("details[data-persist]").forEach(node=>{if(view.details.includes(node.dataset.persist))node.open=true});
6753
+ if(view.details.length||view.closed.length)document.querySelectorAll("details[data-persist]").forEach(node=>{if(view.details.includes(node.dataset.persist))node.open=true;else if(view.closed.includes(node.dataset.persist))node.open=false});
6754
+ /* Panes that scroll on their own keep their place; a live console that was at the bottom stays there. */
6755
+ view.scrolls.forEach(saved=>{const node=document.querySelector('[data-scroll-key="'+CSS.escape(saved.key)+'"]');if(!node)return;node.scrollTop=saved.bottom&&node.hasAttribute("data-follow")?node.scrollHeight:saved.top});
5114
6756
  if(view.focus){
5115
6757
  const node=$(view.focus);
5116
6758
  if(node&&node!==document.activeElement){
@@ -5192,7 +6834,7 @@ function recent(array){return[...array].sort((a,b)=>String(b.updatedAt||b.create
5192
6834
  function approvalRail(approvals,heading){
5193
6835
  if(!approvals.length)return"";
5194
6836
  return'<section class="approval-rail" aria-label="Effect approvals"><header><div><span class="approval-kicker">Decision required</span><h2>'+esc(heading||"An agent is waiting for you")+'</h2><p>Review the exact tool input. Nothing runs unless you approve it.</p></div><span class="approval-count">'+count(approvals.length,"request")+'</span></header><div class="approval-list">'
5195
- +approvals.map(item=>'<article class="approval-item" data-approval="'+attr(item.id)+'"><div class="approval-context"><span class="approval-tool">'+esc(item.toolName)+'</span><a class="approval-run" href="/runs/'+attr(item.runId)+'" data-link>Run '+esc(short(item.runId))+'</a></div><pre class="approval-input">'+esc(jsonText(item.toolInput))+'</pre><div class="approval-foot"><span>Requested '+relCell(item.requestedAt)+' · expires '+relCell(item.expiresAt)+'</span><div class="approval-actions"><button class="button" type="button" data-approval-id="'+attr(item.id)+'" data-approval-decision="deny">Deny</button><button class="button approve" type="button" data-approval-id="'+attr(item.id)+'" data-approval-decision="approve">Approve this input</button></div></div></article>').join("")
6837
+ +approvals.map(item=>'<article class="approval-item" data-approval="'+attr(item.id)+'"><div class="approval-context"><span class="approval-tool">'+esc(item.toolName)+'</span><a class="approval-run" href="/approvals/'+attr(item.id)+'" data-link>Approval '+esc(short(item.id))+'</a><a class="approval-run" href="/runs/'+attr(item.runId)+'" data-link>Run '+esc(short(item.runId))+'</a></div><pre class="approval-input">'+esc(jsonText(item.toolInput))+'</pre><div class="approval-foot"><span>Requested '+relCell(item.requestedAt)+' · expires '+relCell(item.expiresAt)+'</span><div class="approval-actions"><button class="button" type="button" data-approval-id="'+attr(item.id)+'" data-approval-decision="deny">Deny</button><button class="button approve" type="button" data-approval-id="'+attr(item.id)+'" data-approval-decision="approve">Approve this input</button></div></div></article>').join("")
5196
6838
  +'</div></section>';
5197
6839
  }
5198
6840
  function explainRun(run){
@@ -5203,6 +6845,7 @@ function explainRun(run){
5203
6845
  if(source==="spawn")return"Spawned by another agent run.";
5204
6846
  if(source==="background")return"Continued as background work.";
5205
6847
  if(source==="delegation")return"Delegated work, or a delegation result or question coming back.";
6848
+ if(source==="mesh")return"A message from another agent on the mesh, or its reply coming back.";
5206
6849
  if(run.status==="completed")return"The agent completed the requested work.";
5207
6850
  return"The agent is processing a direct message.";
5208
6851
  }
@@ -5233,7 +6876,7 @@ function renderAgents(){
5233
6876
  let html=pageHead("Code and runtime","Agents","A definition is the code-discovered recipe. An instance is persisted runtime data with its own context, apps, playbooks, and conversations.",'<button class="button primary" data-new-run>Start a run</button>');
5234
6877
  html+='<div class="callout"><span class="symbol">'+icon("definitions")+'</span><div><b>Definitions and instances are intentionally separate.</b><p>Editing a file changes what can be assembled. Updating an instance changes what one runtime identity actually has installed.</p></div></div>';
5235
6878
  html+='<div class="definition-grid">'+definitions.map(def=>{const instances=state.instances.filter(x=>x.definitionId===def.id);const features=[def.workingEnvironment?"VFS":null,def.repl?def.repl+" repl":null,def.mesh?"mesh":null].filter(Boolean);return'<a class="definition-card" href="/agents/'+attr(def.id)+'" data-link><span class="definition-icon">'+icon("agent")+'</span><span class="definition-open">'+icon("external")+'</span><h3>'+esc(def.id)+'</h3><p>'+esc(def.description)+'</p><div>'+tags(features)+'</div><div class="definition-meta"><b>'+count(instances.length,"instance")+'</b><span class="muted mono" style="font-size:9px">'+esc(def.file)+'</span></div></a>'}).join("")+'</div>';
5236
- const rows=recent(state.instances).map(instance=>'<tr class="clickable" data-go="/instances/'+attr(instance.id)+'"><td>'+idCell(instance.id)+'<span class="secondary">'+esc(instance.workspaceId)+'</span></td><td><a class="link" href="/agents/'+attr(instance.definitionId)+'" data-link>'+esc(instance.definitionId)+'</a></td><td>'+instance.installations.length+'</td><td>'+instance.playbooks.length+'</td><td>'+relCell(instance.updatedAt)+'</td></tr>').join("");
6879
+ const rows=recent(state.instances).map(instance=>'<tr class="clickable" data-go="/instances/'+attr(instance.id)+'"><td>'+(instance.name?'<strong>'+esc(instance.name)+'</strong> ':'')+idCell(instance.id)+'<span class="secondary">'+esc(instance.workspaceId)+'</span></td><td><a class="link" href="/agents/'+attr(instance.definitionId)+'" data-link>'+esc(instance.definitionId)+'</a></td><td>'+instance.installations.length+'</td><td>'+instance.playbooks.length+'</td><td>'+relCell(instance.updatedAt)+'</td></tr>').join("");
5237
6880
  html+=card("Runtime instances",'<div class="table-wrap"><table class="table"><thead><tr><th>Instance</th><th>Definition</th><th>Installed</th><th>Playbooks</th><th>Updated</th></tr></thead><tbody>'+rows+'</tbody></table></div>'+(rows?"":empty("No runtime instances","Start a run or create an instance from a definition.")),count(state.instances.length,"instance"));
5238
6881
  $("content").innerHTML=html;document.querySelectorAll("[data-new-run]").forEach(x=>x.onclick=openRunDrawer);dataLinks();
5239
6882
  }
@@ -5258,7 +6901,7 @@ function renderInstance(id){
5258
6901
  const instance=state.instances.find(x=>x.id===id);if(!instance)return renderNotFound("Agent instance");
5259
6902
  crumbs([{label:"Agents",href:"/agents"},{label:instance.definitionId,href:"/agents/"+instance.definitionId},{label:short(id)}]);
5260
6903
  const conversations=state.conversations[id]||[];const runs=recent(state.runs.filter(x=>x.agentId===id));
5261
- let html=pageHead("Runtime instance",short(id),"Persisted runtime data assembled from "+instance.definitionId+". This identity can be updated without changing the code definition.",'<button class="button" data-copy="'+attr(id)+'">'+icon("copy")+'<span>Copy instance id</span></button><button class="button primary" data-instance-run>Send message</button>');
6904
+ let html=pageHead("Runtime instance",instance.name||short(id),"Persisted runtime data assembled from "+instance.definitionId+". This identity can be updated without changing the code definition.",'<button class="button" data-copy="'+attr(id)+'">'+icon("copy")+'<span>Copy instance id</span></button><button class="button primary" data-instance-run>Send message</button>');
5262
6905
  html+='<div class="detail-strip"><div><label>Definition</label><strong><a class="link" href="/agents/'+attr(instance.definitionId)+'" data-link>'+esc(instance.definitionId)+'</a></strong></div><div><label>Workspace</label><strong><a class="link mono" href="/workspaces/'+attr(instance.workspaceId)+'" data-link>'+esc(instance.workspaceId)+'</a></strong></div><div><label>Conversations</label><strong>'+conversations.length+'</strong></div><div><label>Last updated</label><strong>'+relCell(instance.updatedAt)+'</strong></div></div>';
5263
6906
  html+='<div class="grid cols-2">';
5264
6907
  const convRows=recent(conversations).map(c=>'<tr class="clickable" data-go="'+attr(chatPath(id,c.id))+'"><td><span class="primary-cell">'+esc(c.title||"Untitled conversation")+'</span>'+idCell(c.id)+'</td><td>'+relCell(c.updatedAt)+'</td></tr>').join("");
@@ -5337,14 +6980,14 @@ function renderChat(){
5337
6980
  const streaming=state.chat.historyOffset===null?liveAssistantMessage(run):null;if(streaming)messages.push(streaming);
5338
6981
  let html='<section class="chat-shell">';
5339
6982
  html+='<aside class="session-rail"><div class="session-head"><div><span class="eyebrow">WebChat</span><h1>Conversations</h1></div><button class="button icon-button" type="button" data-new-chat title="New conversation" aria-label="New conversation">'+icon("plus")+'</button></div>';
5340
- html+='<label class="session-agent"><span>Agent instance</span><select id="chat-agent">'+state.instances.map(item=>'<option value="'+attr(item.id)+'"'+(item.id===agent.id?" selected":"")+'>'+esc(item.definitionId)+" · "+esc(short(item.id))+'</option>').join("")+'</select></label>';
6983
+ html+='<label class="session-agent"><span>Agent instance</span><select id="chat-agent">'+state.instances.map(item=>'<option value="'+attr(item.id)+'"'+(item.id===agent.id?" selected":"")+'>'+esc(item.name||item.definitionId)+" · "+esc(short(item.id))+'</option>').join("")+'</select></label>';
5341
6984
  html+='<label class="session-search">'+icon("search")+'<input id="chat-search" value="'+attr(state.chat.query)+'" placeholder="Search conversations" /></label>';
5342
6985
  html+='<div class="session-list">'+(visible.length?visible.map(item=>'<button type="button" class="chat-session'+(item.id===conversation?.id?" active":"")+'" data-chat-conversation="'+attr(item.id)+'"><span>'+esc(item.title||"Untitled conversation")+'</span><small>'+esc(relTime(item.updatedAt))+' · '+esc(short(item.id))+'</small></button>').join(""):empty(term?"No matching conversations":"No conversations yet",term?"Try another search.":"Create one to start talking with this instance."))+'</div></aside>';
5343
6986
  html+='<section class="conversation-pane">';
5344
6987
  if(!conversation){
5345
6988
  html+='<div class="chat-empty">'+icon("chat","chat-empty-icon")+'<h2>Start a conversation</h2><p>Messages route to this exact runtime instance and become part of its durable context.</p><button class="button primary" type="button" data-new-chat>'+icon("plus")+' New conversation</button></div>';
5346
6989
  }else{
5347
- html+='<header class="conversation-head"><div><span class="conversation-kicker">'+esc(agent.definitionId)+" · "+esc(short(agent.id))+'</span><h2>'+esc(conversation.title||"Untitled conversation")+'</h2></div><div class="conversation-meta">'+(run?status(run.status):lastRun?status(lastRun.status):'<span class="status">ready</span>')+'<span>'+esc(transcript?.turnCount??0)+' turns</span><span>'+esc(transcript?.tokenCount??0)+' tokens</span><button type="button" class="conversation-rename" data-export-chat>Export</button><button type="button" class="conversation-rename" data-rename-chat>Rename</button></div></header>';
6990
+ html+='<header class="conversation-head"><div><span class="conversation-kicker">'+esc(agent.name||agent.definitionId)+" · "+esc(short(agent.id))+'</span><h2>'+esc(conversation.title||"Untitled conversation")+'</h2></div><div class="conversation-meta">'+(run?status(run.status):lastRun?status(lastRun.status):'<span class="status">ready</span>')+'<span>'+esc(transcript?.turnCount??0)+' turns</span><span>'+esc(transcript?.tokenCount??0)+' tokens</span><button type="button" class="conversation-rename" data-export-chat>Export</button><button type="button" class="conversation-rename" data-rename-chat>Rename</button></div></header>';
5348
6991
  if(transcript&&!transcript.persisted)html+='<div class="chat-store-warning">This agent has no conversation store. New turns can run, but history cannot be reopened after the worker exits.</div>';
5349
6992
  const page=transcript?.page;const paging=page&&(page.hasEarlier||page.hasLater)?'<div class="load-history">'+(page.hasEarlier?'<button class="button" type="button" data-history-page="earlier">Earlier</button>':"")+'<span>Showing '+esc(page.offset+1)+'–'+esc(page.offset+(transcript?.messages?.length||0))+' of '+esc(page.total)+'</span>'+(page.hasLater?'<button class="button" type="button" data-history-page="later">Newer</button>':"")+'</div>':"";
5350
6993
  html+='<div class="message-scroll" id="message-scroll">'+paging+(messages.length?messages.map((message,index)=>renderChatMessage(message,index===messages.length-1&&Boolean(state.chat.optimistic))).join(""):'<div class="chat-empty compact">'+icon("chat","chat-empty-icon")+'<h2>What should '+esc(agent.definitionId)+' work on?</h2><p>This conversation can include text, images, video, and documents.</p></div>')+'</div>';
@@ -5495,11 +7138,6 @@ function phaseData(run,events){
5495
7138
  {name:run.status==="failed"?"Failed":run.status==="cancelled"?"Cancelled":run.status==="completed"?"Completed":"In progress",detail:explainRun(run),state:run.status==="failed"||run.status==="cancelled"?"error":run.status==="completed"?"complete":"active",time:run.completedAt||time(/run\.(completed|failed|cancelled)/)}
5496
7139
  ];
5497
7140
  }
5498
- function eventOffset(run,event){
5499
- const base=new Date(run.createdAt).getTime();const at=new Date(event.timestamp).getTime();
5500
- if(!Number.isFinite(base)||!Number.isFinite(at))return"";
5501
- return"+"+durationText(Math.max(0,at-base));
5502
- }
5503
7141
  function runErrorText(run){
5504
7142
  if(run.status!=="failed")return"";
5505
7143
  if(typeof run.error==="string")return run.error;
@@ -5518,51 +7156,6 @@ function guidanceCard(events){
5518
7156
  const formBody=forms?.length?forms.map(f=>'<p><strong>'+esc(f.definitionId)+'</strong> · '+esc(f.status)+'</p><p>'+count(f.answered,"answered field")+' · '+count(f.pendingHooks,"pending effect batch","pending effect batches")+(f.blockedOn?' · waiting on '+esc(f.blockedOn):'')+'</p>').join(""):'<p class="muted">No form instances started.</p>';
5519
7157
  return '<section class="card"><div class="card-head"><h2>Conversation guidance</h2><span class="meta">Observed '+esc(fmtTime(event.timestamp))+'</span></div><div class="card-body"><div class="grid cols-3"><div><h3>Goals</h3>'+goalBody+'</div><div><h3>Facts</h3>'+factBody+'</div><div><h3>Forms</h3>'+formBody+'</div></div><p class="muted">Latest state observed by this run, not a live database view. '+count(data.contextProviders||0,"custom context provider")+'. Answer values and fact bodies are not included in this summary.</p></div></section>';
5520
7158
  }
5521
- function renderRun(id){
5522
- const run=state.runs.find(x=>x.id===id);if(!run)return renderNotFound("Run");
5523
- const events=eventsFor(id);
5524
- const categories=[...new Set(events.map(event=>event.category))].filter(Boolean).sort();
5525
- let visibleEvents=state.showAllEvents?events:events.filter(isKeyRunEvent);
5526
- if(state.eventCategory!=="all")visibleEvents=visibleEvents.filter(event=>event.category===state.eventCategory);
5527
- crumbs([{label:"Runs",href:"/runs"},{label:short(id)}]);
5528
- const actions=(isLiveRun(run)?'<button class="button danger" data-cancel>Cancel run</button>':"")
5529
- +'<button class="button" data-copy="'+attr(run.id)+'">'+icon("copy")+'<span>Copy run id</span></button>'
5530
- +'<button class="button primary" data-rerun>'+icon("refresh")+'<span>Run again</span></button>';
5531
- let html=pageHead("Run detail",run.agent+" · "+short(id),"Follow the high-level phases first. Expand individual events only when you need raw adapter or model evidence.",actions);
5532
- const failure=runErrorText(run);
5533
- if(failure)html+='<div class="alert danger"><span class="symbol">'+icon("warning")+'</span><div><b>This run failed'+(run.attempts>1?" after "+count(run.attempts,"attempt"):"")+'.</b><p>'+esc(failure)+'</p></div></div>';
5534
- if(isLiveRun(run))html+='<div class="alert live"><span class="symbol"><i class="pulse-dot"></i></span><div><b>This run is still '+esc(run.status)+'.</b><p>New events stream in below as the runtime records them.</p></div></div>';
5535
- html+=approvalRail(pendingApprovals(run.id),"This run is waiting for a decision");
5536
- html+=guidanceCard(events);
5537
- html+='<div class="detail-strip">'
5538
- +'<div><label>Status</label><strong>'+status(run.status)+'</strong></div>'
5539
- +'<div><label>Duration</label><strong>'+durCell(run)+'</strong></div>'
5540
- +'<div><label>Source</label><strong>'+esc(runSource(run))+'</strong></div>'
5541
- +'<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>'
5542
- +'<div><label>Attempts</label><strong>'+run.attempts+" of "+run.maxAttempts+'</strong></div>'
5543
- +'</div>';
5544
- html+='<div class="grid cols-3"><section class="card span-2"><div class="card-head"><h2>Run spine</h2><span class="meta">'+count(events.length,"event")+'</span></div><div class="card-body"><div class="trace-note">This shows observable work intent and outcomes. It does not expose private hidden chain-of-thought.</div><div class="run-spine">'+phaseData(run,events).map(p=>'<div class="phase '+p.state+'"><span class="phase-dot"></span><div><strong>'+esc(p.name)+'</strong><p>'+esc(p.detail)+'</p></div><time title="'+attr(fullDate(p.time))+'">'+esc(fmtTime(p.time))+'</time></div>').join("")+'</div></div></section>';
5545
- html+=card("Result",'<div class="card-body"><div class="summary-box"><dl><dt>Created</dt><dd>'+relCell(run.createdAt)+'</dd><dt>Started</dt><dd>'+relCell(run.startedAt)+'</dd><dt>Finished</dt><dd>'+relCell(run.completedAt)+'</dd><dt>Timeout</dt><dd>'+esc(durationText(run.timeoutMs))+'</dd></dl></div><details data-persist="output" open><summary class="link">Output</summary><pre class="json">'+esc(jsonText(run.output??run.error??null))+'</pre></details><details data-persist="input"><summary class="link">Input</summary><pre class="json">'+esc(jsonText(run.input))+'</pre></details></div>',"Recorded outcome");
5546
- html+='</div>';
5547
- const eventRows=visibleEvents.map((event,index)=>{
5548
- const key=event.id||event.type+":"+event.timestamp+":"+index;
5549
- return'<div class="event-row" data-event-key="'+attr(key)+'">'
5550
- +'<button class="event-toggle" type="button"><span class="event-time">'+esc(fmtTime(event.timestamp))+'</span><span class="event-offset mono">'+esc(eventOffset(run,event))+'</span><span class="event-category">'+esc(event.category)+'</span><span class="event-type">'+esc(event.type)+'</span><span class="event-caret">'+icon("caretDown")+'</span></button>'
5551
- +'<div class="event-detail"><div class="event-detail-head"><span class="muted mono">'+esc(event.type)+'</span>'+copyButton(jsonText(event.data),"event payload")+'</div><pre class="json">'+esc(jsonText(event.data))+'</pre></div></div>';
5552
- }).join("");
5553
- const categoryChips=categories.length>1?'<div class="chips">'+['all'].concat(categories).map(name=>'<button type="button" class="chip'+(state.eventCategory===name?" active":"")+'" data-category="'+attr(name)+'">'+esc(name==="all"?"All categories":name)+'</button>').join("")+'</div>':"";
5554
- const eventControl='<div class="event-controls">'+categoryChips+'<div class="event-controls-right"><span class="muted">'+esc(state.showAllEvents?"Showing every retained event, including assembly and process detail.":"Showing the lifecycle events that explain this run.")+'</span><button class="button" type="button" data-toggle-events>'+esc(state.showAllEvents?"Show key events":"Show all "+events.length+" events")+'</button></div></div>';
5555
- html+=card("Observable event trace",eventControl+'<div class="event-list">'+(eventRows||empty("No events to show","Clear the category filter or show every retained event."))+'</div>',count(visibleEvents.length,"event"));
5556
- $("content").innerHTML=html;
5557
- document.querySelectorAll(".event-toggle").forEach(node=>node.onclick=()=>node.parentElement.classList.toggle("open"));
5558
- document.querySelectorAll("[data-category]").forEach(node=>node.onclick=()=>{state.eventCategory=node.dataset.category;renderRun(id)});
5559
- document.querySelector("[data-toggle-events]").onclick=()=>{state.showAllEvents=!state.showAllEvents;renderRun(id)};
5560
- const cancel=document.querySelector("[data-cancel]");if(cancel)cancel.onclick=()=>void cancelRun(id);
5561
- const rerun=document.querySelector("[data-rerun]");
5562
- 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:"");
5563
- dataLinks();
5564
- }
5565
-
5566
7159
  function renderAutomations(){
5567
7160
  crumbs([{label:"Automations"}]);let html=pageHead("Background work","Automations","Schedules and sleeps create future activations. Playbook subscriptions listen for inbound transmissions and can provision one or many agent instances.","");
5568
7161
  html+='<div class="grid cols-3">'+metric("Scheduled activations",state.activations.length,"Future triggers and sleeping runs",true)+metric("Playbook subscriptions",state.subscriptions.length,"Inbound event policies")+metric("Application connections",state.connections.length,"Long-lived inbound workers")+'</div>';
@@ -5623,6 +7216,21 @@ function renderWorkspacePanel(data){
5623
7216
  $("workspace-panel").innerHTML=card(active[0].toUpperCase()+active.slice(1),'<div class="card-body">'+body+'</div>',count(values.length,"item"));
5624
7217
  }
5625
7218
 
7219
+ function renderApproval(id){
7220
+ const item=state.approvals.find(x=>x.id===id);if(!item)return renderNotFound("Approval");
7221
+ crumbs([{label:"Runs",href:"/runs"},{label:"Approval "+short(id)}]);
7222
+ const open=item.status==="pending";
7223
+ let html=pageHead("Approval",item.toolName,open?(item.suspendedAt?"The agent stopped at this call and waits for you. Deciding now resumes it.":"The agent is waiting on this call now."):"This request was "+item.status+".",'<button class="button" data-copy="'+attr(location.origin+"/approvals/"+item.id)+'">'+icon("copy")+'<span>Copy link</span></button>');
7224
+ html+=open?approvalRail([item],"Decide this request"):'<pre class="approval-input">'+esc(jsonText(item.toolInput))+'</pre>';
7225
+ html+='<div class="detail-strip">'
7226
+ +'<div><label>Status</label><strong>'+status(item.status)+'</strong></div>'
7227
+ +'<div><label>Asked by run</label><strong><a class="link mono" href="/runs/'+attr(item.runId)+'" data-link>'+esc(short(item.runId))+'</a></strong></div>'
7228
+ +'<div><label>Requested</label><strong>'+relCell(item.requestedAt)+'</strong></div>'
7229
+ +'<div><label>'+(open?"Expires":"Decided")+'</label><strong>'+relCell(open?item.expiresAt:item.resolvedAt)+'</strong></div>'
7230
+ +(item.resumeRunId?'<div><label>Resumed in run</label><strong><a class="link mono" href="/runs/'+attr(item.resumeRunId)+'" data-link>'+esc(short(item.resumeRunId))+'</a></strong></div>':"")
7231
+ +'</div>';
7232
+ $("content").innerHTML=html;dataLinks();
7233
+ }
5626
7234
  function renderNotFound(label){crumbs([{label:"Not found"}]);$("content").innerHTML=pageHead("Inspector",label+" not found","The requested runtime record does not exist or is no longer retained.",'<a class="button" href="/" data-link>Return to overview</a>');dataLinks()}
5627
7235
  async function loadBase(){
5628
7236
  const endpoints=["/api/manifest","/api/agent-instances","/api/playbook-subscriptions","/api/application-connections","/api/runs","/api/events","/health","/api/transmissions","/api/accounts","/api/routes","/api/bindings","/api/activations","/api/approvals"];
@@ -5650,6 +7258,7 @@ async function refreshActivity(){
5650
7258
  const endpoints=["/api/agent-instances","/api/playbook-subscriptions","/api/application-connections","/api/runs","/api/events","/api/activations","/api/approvals","/health"];
5651
7259
  const values=await Promise.all(endpoints.map(url=>api(url)));
5652
7260
  [state.instances,state.subscriptions,state.connections,state.runs,state.events,state.activations,state.approvals,state.health]=values;
7261
+ const current=route();if(current.section==="runs"&&current.id)await ensureRunEvents(current.id);
5653
7262
  renderHealth();
5654
7263
  $("event-state").textContent="Live updates";
5655
7264
  await navigate(false,true);
@@ -5667,8 +7276,9 @@ async function navigate(load=true,preserve=false){
5667
7276
  try{
5668
7277
  if(load&&current.section==="instances"&&current.id)await ensureConversations(current.id);
5669
7278
  if(load&&current.section==="workspaces"&&current.id)await ensureWorkspace(current.id);
7279
+ if(load&&current.section==="runs"&&current.id)await ensureRunEvents(current.id);
5670
7280
  if(current.section==="chat")await loadChat(current);
5671
- if(current.section==="overview")renderOverview();else if(current.section==="agents"&&!current.id)renderAgents();else if(current.section==="agents")renderDefinition(current.id);else if(current.section==="instances")renderInstance(current.id);else if(current.section==="chat")renderChat();else if(current.section==="runs"&&!current.id)renderRuns();else if(current.section==="runs")renderRun(current.id);else if(current.section==="automations")renderAutomations();else if(current.section==="integrations")renderIntegrations();else if(current.section==="workspaces")renderWorkspaces(current.id);else renderNotFound("Page");
7281
+ if(current.section==="overview")renderOverview();else if(current.section==="agents"&&!current.id)renderAgents();else if(current.section==="agents")renderDefinition(current.id);else if(current.section==="instances")renderInstance(current.id);else if(current.section==="chat")renderChat();else if(current.section==="runs"&&!current.id)renderRuns();else if(current.section==="runs")renderRun(current.id);else if(current.section==="approvals"&&current.id)renderApproval(current.id);else if(current.section==="automations")renderAutomations();else if(current.section==="integrations")renderIntegrations();else if(current.section==="workspaces")renderWorkspaces(current.id);else renderNotFound("Page");
5672
7282
  }catch(error){$("content").innerHTML='<div class="form-error">'+esc(error.message)+'</div>';console.error(error)}
5673
7283
  restoreView(view);
5674
7284
  tickTimes();
@@ -5724,13 +7334,15 @@ $("new-run").onclick=()=>openRunDrawer();$("close-drawer").onclick=closeRunDrawe
5724
7334
  $("run-message").addEventListener("keydown",e=>{if((e.metaKey||e.ctrlKey)&&e.key==="Enter"){e.preventDefault();$("run-form").requestSubmit()}});
5725
7335
  document.addEventListener("keydown",e=>{
5726
7336
  if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==="k"){e.preventDefault();openSearch();return}
5727
- if(e.key==="Escape"){closeSearch();closeRunDrawer();return}
5728
- if(e.metaKey||e.ctrlKey||e.altKey||isTyping())return;
5729
- if($("drawer").classList.contains("open")||$("search-modal").classList.contains("open"))return;
7337
+ const modal=$("drawer").classList.contains("open")||$("search-modal").classList.contains("open");
7338
+ if(e.key==="Escape"&&modal){closeSearch();closeRunDrawer();return}
7339
+ if(e.key==="Escape"&&isTyping()){document.activeElement.blur();return}
7340
+ if(e.metaKey||e.ctrlKey||e.altKey||isTyping()||modal)return;
7341
+ if(runKeys(e)){e.preventDefault();return}
5730
7342
  if(e.key==="j"){e.preventDefault();moveCursor(1)}
5731
7343
  else if(e.key==="k"){e.preventDefault();moveCursor(-1)}
5732
7344
  else if(e.key==="Enter"||e.key==="o"){if(state.cursor>=0){e.preventDefault();openCursor()}}
5733
- else if(e.key==="/"){const box=$("run-search");if(box){e.preventDefault();box.focus();box.select()}else{e.preventDefault();openSearch()}}
7345
+ else if(e.key==="/"){const box=$("run-search")||$("net-filter")||$("con-filter");if(box){e.preventDefault();box.focus();box.select()}else{e.preventDefault();openSearch()}}
5734
7346
  else if(e.key==="c"){e.preventDefault();const current=route();if(current.section==="chat"){const agent=chatAgent();if(agent)void createChatConversation(agent.id)}else openRunDrawer()}
5735
7347
  else if(e.key==="r"){e.preventDefault();void refreshActivity()}
5736
7348
  });
@@ -5781,12 +7393,11 @@ button,input,textarea,select{font:inherit;color:inherit}button,a{touch-action:ma
5781
7393
  .definition-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;margin-bottom:16px}.definition-card{display:block;color:inherit;text-decoration:none;background:var(--bg-elevated);border:1px solid var(--border-subtle);border-radius:var(--radius-lg);padding:19px;min-height:196px;position:relative;overflow:hidden;transition:transform .2s ease,border-color .2s ease,background .2s}.definition-card:before{content:"";position:absolute;inset:0;opacity:0;background:radial-gradient(110% 80% at 100% 0%,var(--accent-dim),transparent 60%);transition:opacity .2s}.definition-card:hover{transform:translateY(-2px);border-color:var(--accent-line);background:var(--bg-surface)}.definition-card:hover:before{opacity:1}.definition-icon{width:31px;height:31px;display:grid;place-items:center;border:1px solid var(--accent-line);border-radius:8px;color:var(--accent);background:var(--accent-dim);margin-bottom:15px;position:relative}.definition-icon .icon{width:17px;height:17px}.definition-open{position:absolute;right:17px;top:17px;color:var(--text-tertiary);transition:color .18s,transform .18s}.definition-open .icon{width:14px;height:14px}.definition-card:hover .definition-open{color:var(--accent);transform:translate(1px,-1px)}.definition-card h3{margin:0;font-size:17px;font-weight:500;position:relative}.definition-card p{color:var(--text-secondary);font-size:12px;font-weight:300;line-height:1.6;margin:9px 0 18px;position:relative}.definition-meta{position:absolute;left:19px;right:19px;bottom:17px;display:flex;justify-content:space-between;align-items:end}.definition-meta b{font:9px var(--mono);color:var(--accent-soft)}
5782
7394
  .cap-list{display:flex;flex-wrap:wrap;gap:6px}.cap{border:1px solid var(--border);background:var(--bg-surface);border-radius:5px;padding:7px 9px;font:9px var(--mono);margin-bottom:6px;color:var(--text-secondary)}.detail-strip{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));border:1px solid var(--border-subtle);border-radius:var(--radius);background:var(--bg-elevated);margin-bottom:14px;overflow:hidden}.detail-strip>div{padding:15px;border-right:1px solid var(--border-subtle);min-width:0}.detail-strip>div:last-child{border-right:0}.detail-strip label{display:block;color:var(--text-tertiary);font:8px var(--mono);text-transform:uppercase;letter-spacing:.1em}.detail-strip strong{display:block;margin-top:8px;font-size:12px;font-weight:500;overflow-wrap:anywhere}.json{margin:0;background:#070A09;color:var(--text-secondary);border:1px solid var(--border-subtle);border-radius:7px;padding:14px;font:9px/1.65 var(--mono);white-space:pre-wrap;overflow:auto;max-height:360px}.summary-box{font-size:12px;line-height:1.65;overflow-wrap:anywhere}.summary-box dl{display:grid;grid-template-columns:130px 1fr;gap:9px 14px;margin:0}.summary-box dt{color:var(--text-tertiary);font:8px var(--mono);text-transform:uppercase;letter-spacing:.08em}.summary-box dd{margin:0;color:var(--text-secondary)}
5783
7395
  .run-spine{position:relative;padding:4px 0}.run-spine:before{content:"";position:absolute;left:19px;top:14px;bottom:14px;width:1px;background:var(--border)}.phase{position:relative;display:grid;grid-template-columns:40px 1fr auto;gap:12px;padding:11px 4px}.phase-dot{width:12px;height:12px;border-radius:50%;background:var(--bg-elevated);border:2px solid var(--text-tertiary);margin:2px 0 0 13px;z-index:1}.phase.complete .phase-dot{border-color:var(--success);box-shadow:0 0 8px rgba(140,196,148,.2)}.phase.active .phase-dot{border-color:var(--network);box-shadow:0 0 0 5px rgba(131,179,226,.09)}.phase.error .phase-dot{border-color:var(--danger)}.phase strong{font-size:12px;font-weight:500}.phase p{margin:4px 0 0;color:var(--text-secondary);font-size:11px;font-weight:300;line-height:1.5}.phase time{font:8px var(--mono);color:var(--text-tertiary)}
5784
- .event-row{border-top:1px solid var(--border-subtle)}.event-toggle{width:100%;border:0;background:transparent;padding:12px 15px;display:grid;grid-template-columns:82px 110px minmax(0,1fr) auto;gap:11px;text-align:left;align-items:center;cursor:pointer}.event-toggle:hover,.event-row.open .event-toggle{background:var(--accent-glow)}.event-time,.event-category{font:8px var(--mono);color:var(--text-tertiary)}.event-type{font:9px var(--mono);overflow:hidden;text-overflow:ellipsis}.event-detail{display:none;padding:0 15px 14px}.event-row.open .event-detail{display:block}.trace-note{border-left:2px solid var(--accent);padding:10px 12px;background:var(--accent-dim);font-size:11px;line-height:1.5;color:var(--text-secondary);margin-bottom:14px}
5785
7396
  .workspace-tabs{display:flex;gap:2px;border-bottom:1px solid var(--border-subtle);margin:20px 0 14px}.workspace-tabs button{border:0;background:transparent;padding:11px 13px;color:var(--text-secondary);font-size:11px;cursor:pointer;border-bottom:2px solid transparent}.workspace-tabs button.active{color:var(--accent);border-color:var(--accent);font-weight:500}.kv{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}.kv-item{border:1px solid var(--border-subtle);border-radius:7px;padding:13px;background:var(--bg-surface)}.kv-item strong{font:10px var(--mono)}.kv-item small{display:block;color:var(--text-tertiary);margin-top:6px}.kv-value{margin-top:12px;color:var(--text-secondary);font-size:11px;line-height:1.5;overflow-wrap:anywhere}.callout{border:1px solid var(--accent-line);background:var(--accent-glow);border-radius:8px;padding:15px 17px;display:flex;align-items:flex-start;gap:12px;margin-bottom:14px}.callout b{font-size:12px;font-weight:500}.callout p{margin:4px 0 0;color:var(--text-secondary);font-size:11px;line-height:1.5}.callout .symbol{width:31px;height:31px;display:grid;place-items:center;flex:0 0 auto;border:1px solid var(--accent-line);border-radius:7px;color:var(--accent);background:var(--accent-dim)}.callout .symbol .icon{width:16px;height:16px}
5786
7397
  .drawer-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.62);backdrop-filter:blur(3px);z-index:40;display:none}.drawer-backdrop.open{display:block}.drawer{position:absolute;right:0;top:0;bottom:0;width:min(520px,100%);background:var(--bg-elevated);border-left:1px solid var(--border);box-shadow:-20px 0 60px rgba(0,0,0,.35);padding:26px;overflow:auto}.drawer-head{display:flex;align-items:flex-start;margin-bottom:28px}.drawer h2{margin:0;font-size:23px;font-weight:400;letter-spacing:-.025em}.drawer-head button{margin-left:auto;border:0;background:transparent;color:var(--text-secondary);cursor:pointer}.drawer-head button:hover{color:var(--text-primary);background:var(--bg-surface)}.field{margin-bottom:17px}.field label{display:block;font:8px var(--mono);text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary);margin-bottom:7px}.field input,.field textarea,.field select{width:100%;border:1px solid var(--border);background:var(--bg);border-radius:7px;padding:11px 12px;font-size:12px}.field textarea{min-height:120px;resize:vertical}.form-error{background:rgba(226,155,168,.08);color:var(--danger);border:1px solid rgba(226,155,168,.18);border-radius:7px;padding:10px 12px;font-size:11px;margin-bottom:13px}.drawer-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:22px}
5787
7398
  .search-modal{position:fixed;inset:0;background:rgba(0,0,0,.64);backdrop-filter:blur(4px);z-index:50;display:none;padding:12vh 20px}.search-modal.open{display:block}.search-box{max-width:650px;margin:auto;background:var(--bg-elevated);border:1px solid var(--border);border-radius:10px;box-shadow:var(--shadow);overflow:hidden}.search-input-wrap{display:flex;align-items:center;gap:12px;padding:0 20px;border-bottom:1px solid var(--border);color:var(--text-tertiary)}.search-input-wrap>.icon{width:19px;height:19px}.search-box input{width:100%;border:0;background:var(--bg-elevated);padding:18px 0;font-size:15px}.search-results{max-height:420px;overflow:auto;padding:8px}.search-result{display:block;padding:11px 12px;border-radius:6px;text-decoration:none;color:inherit}.search-result:hover{background:var(--accent-glow)}.search-result strong{font-size:12px;font-weight:500}.search-result small{display:block;color:var(--text-tertiary);margin-top:3px}.toast{position:fixed;right:24px;bottom:24px;background:var(--accent);color:var(--bg);border-radius:7px;padding:12px 15px;font-size:11px;font-weight:600;box-shadow:var(--shadow);z-index:60;transform:translateY(20px);opacity:0;pointer-events:none;transition:.2s}.toast.show{transform:none;opacity:1}
5788
7399
  @media(max-width:1100px){.cols-4{grid-template-columns:repeat(2,1fr)}.definition-grid{grid-template-columns:repeat(2,1fr)}.cols-3{grid-template-columns:1fr 1fr}}
5789
- @media(max-width:760px){:root{--sidebar:0px}.sidebar{transform:translateX(-248px);width:248px;transition:transform .2s ease}.sidebar.open{transform:none}.mobile-toggle{display:inline-flex}.topbar{padding:0 16px}.live-chip{display:none}.content{padding:24px 16px 55px}.page-head{display:block}.page-head .actions{margin:18px 0 0}.cols-4,.cols-3,.cols-2,.definition-grid,.kv{grid-template-columns:1fr}.span-2{grid-column:auto}.detail-strip{display:block}.detail-strip>div{border-right:0;border-bottom:1px solid var(--border-subtle)}.filters{flex-wrap:wrap}.filters input{min-width:100%;width:100%}.event-toggle{grid-template-columns:70px 90px 1fr}.event-toggle span:last-child{display:none}.top-actions .button.primary span{display:none}}
7400
+ @media(max-width:760px){:root{--sidebar:0px}.sidebar{transform:translateX(-248px);width:248px;transition:transform .2s ease}.sidebar.open{transform:none}.mobile-toggle{display:inline-flex}.topbar{padding:0 16px}.live-chip{display:none}.content{padding:24px 16px 55px}.page-head{display:block}.page-head .actions{margin:18px 0 0}.cols-4,.cols-3,.cols-2,.definition-grid,.kv{grid-template-columns:1fr}.span-2{grid-column:auto}.detail-strip{display:block}.detail-strip>div{border-right:0;border-bottom:1px solid var(--border-subtle)}.filters{flex-wrap:wrap}.filters input{min-width:100%;width:100%}.top-actions .button.primary span{display:none}}
5790
7401
 
5791
7402
  /* ---- Elapsed time and duration ---- */
5792
7403
  .rel{color:var(--text-secondary);white-space:nowrap;font-variant-numeric:tabular-nums;cursor:help;border-bottom:1px dotted var(--border-strong)}
@@ -5860,23 +7471,6 @@ tr.cursor,.definition-card.cursor{outline:1px solid var(--accent-soft);outline-o
5860
7471
  .approval-list{display:grid}.approval-item{padding:16px 18px;border-top:1px solid var(--border-subtle)}.approval-item:first-child{border-top:0}.approval-context{display:flex;align-items:center;gap:10px;margin-bottom:10px}.approval-tool{font:10px var(--mono);color:var(--text-primary);background:rgba(228,184,121,.08);border:1px solid rgba(228,184,121,.18);border-radius:5px;padding:5px 8px}.approval-run{margin-left:auto;color:var(--text-secondary);font:9px var(--mono);text-decoration:none}.approval-run:hover{color:var(--warn)}
5861
7472
  .approval-input{margin:0;max-height:220px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;border:1px solid var(--border-subtle);border-radius:7px;background:#070A09;padding:12px;color:var(--text-secondary);font:9px/1.65 var(--mono)}.approval-foot{display:flex;align-items:center;gap:16px;margin-top:12px;color:var(--text-tertiary);font:9px var(--mono)}.approval-actions{display:flex;gap:8px;margin-left:auto}.button.approve{border-color:var(--warn);background:var(--warn);color:#14110A;font-weight:600}.button.approve:hover{border-color:#F0C98D;background:#F0C98D;transform:translateY(-1px)}.approval-actions button:disabled{opacity:.55;cursor:wait;transform:none}
5862
7473
 
5863
- /* ---- Event trace ---- */
5864
- .event-controls{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:12px 15px;border-bottom:1px solid var(--border-subtle)}
5865
- .event-controls-right{display:flex;align-items:center;gap:12px;margin-left:auto;flex-wrap:wrap}
5866
- .event-controls-right .muted{font-size:11px}
5867
- .event-list{max-height:640px;overflow:auto}
5868
- .chips{display:flex;gap:5px;flex-wrap:wrap}
5869
- .chip{border:1px solid var(--border-subtle);background:var(--bg-elevated);color:var(--text-secondary);border-radius:20px;padding:5px 11px;font:9px var(--mono);text-transform:uppercase;letter-spacing:.07em;cursor:pointer;transition:border-color .16s,color .16s,background .16s}
5870
- .chip:hover{color:var(--text-primary);border-color:var(--border)}
5871
- .chip.active{background:var(--accent-dim);border-color:var(--accent-line);color:var(--accent)}
5872
- .event-toggle{grid-template-columns:74px 62px 104px minmax(0,1fr) auto!important}
5873
- .event-offset{color:var(--accent-soft);font-size:9px;font-variant-numeric:tabular-nums}
5874
- .event-caret{display:flex;color:var(--text-tertiary)}
5875
- .event-caret .icon{width:13px;height:13px;transition:transform .18s}
5876
- .event-row.open .event-caret .icon{transform:rotate(180deg)}
5877
- .event-detail-head{display:flex;align-items:center;gap:8px;padding:9px 15px 0}
5878
- .event-detail-head .copy-btn{opacity:1;margin-left:auto}
5879
-
5880
7474
  /* ---- Skeletons ---- */
5881
7475
  .skeleton{padding:6px 0}
5882
7476
  .skeleton-row{display:flex;align-items:center;gap:16px;padding:13px 15px;border-bottom:1px solid var(--border-subtle)}
@@ -5920,12 +7514,215 @@ tr.cursor,.definition-card.cursor{outline:1px solid var(--accent-soft);outline-o
5920
7514
  @media(max-width:760px){
5921
7515
  .toolbar-right{margin-left:0;width:100%}
5922
7516
  .search-field,.search-field input{width:100%;min-width:0}
5923
- .event-toggle{grid-template-columns:60px 54px minmax(0,1fr) auto!important}
5924
- .event-toggle .event-category{display:none}
5925
7517
  .approval-rail>header,.approval-foot{display:block}.approval-count{display:inline-flex;margin:10px 0 0}.approval-context{align-items:flex-start}.approval-run{margin-left:0}.approval-actions{margin:12px 0 0}.approval-actions .button{flex:1}
5926
7518
  .hint{display:none}
5927
7519
  .content.chat-content{height:calc(100vh - 72px);padding:0}.chat-shell{grid-template-columns:1fr;grid-template-rows:auto minmax(0,1fr)}.session-rail{max-height:235px;border-right:0;border-bottom:1px solid var(--border-subtle)}.session-head{height:58px;padding:10px 14px}.session-head .eyebrow{display:none}.session-head h1{font-size:15px}.session-agent{padding:8px 12px 4px}.session-search{margin:4px 12px 7px}.session-list{display:flex;gap:5px;padding:2px 10px 10px;overflow:auto}.chat-session{min-width:180px;margin:0}.conversation-head{height:62px;padding:10px 14px}.conversation-meta span:not(.status){display:none}.message-scroll{padding:20px 13px}.message-body{max-width:88%}.chat-progress{margin:0 10px 8px}.chat-progress-actions a{display:none}.chat-composer{margin:0 10px 10px}.composer-actions>span{display:none}
5928
7520
  }
7521
+ /* ---- Run workbench: DevTools for an agent run. Dense rows, panes that scroll on their own. ---- */
7522
+ .devtools{border:1px solid var(--border-subtle);border-radius:var(--radius);background:rgba(15,22,19,.95);overflow:hidden;margin-bottom:14px}
7523
+ .dt-tabs{display:flex;align-items:stretch;gap:2px;border-bottom:1px solid var(--border-subtle);background:rgba(20,29,24,.5);padding:0 8px;overflow-x:auto}
7524
+ .dt-tab{border:0;background:transparent;color:var(--text-secondary);font-size:12px;font-weight:500;padding:11px 12px 9px;display:inline-flex;align-items:center;gap:7px;cursor:pointer;border-bottom:2px solid transparent;white-space:nowrap}
7525
+ .dt-tab .icon{width:14px;height:14px}
7526
+ .dt-tab:hover{color:var(--text-primary)}
7527
+ .dt-tab.active{color:var(--accent);border-bottom-color:var(--accent)}
7528
+ .dt-badge{font:9px var(--mono);border-radius:10px;padding:1px 6px;background:var(--bg);color:var(--text-tertiary);font-variant-numeric:tabular-nums}
7529
+ .dt-badge.err{background:rgba(226,155,168,.14);color:var(--danger)}
7530
+ .dt-badge.warn{background:rgba(228,184,121,.14);color:var(--warn)}
7531
+ .dt-live{display:inline-flex;align-items:center;gap:7px;align-self:center;margin-left:10px;font:9px var(--mono);text-transform:uppercase;letter-spacing:.1em;color:var(--accent)}
7532
+ .dt-live .pulse-dot{width:7px;height:7px;margin:0}
7533
+ .dt-hint{margin-left:auto;align-self:center;font:9px var(--mono);color:var(--text-tertiary);padding-left:16px;white-space:nowrap}
7534
+ .dt-body{height:min(74vh,820px);min-height:460px;display:flex;flex-direction:column;min-width:0}
7535
+ .dt-body.dt-summary{height:auto;min-height:0}
7536
+ .dt-toolbar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px 10px;border-bottom:1px solid var(--border-subtle);background:rgba(8,11,10,.35);flex:0 0 auto}
7537
+ .dt-filter{position:relative;display:flex;align-items:center}
7538
+ .dt-filter .icon{position:absolute;left:9px;width:12px;height:12px;color:var(--text-tertiary)}
7539
+ .dt-filter input{background:var(--bg);border:1px solid var(--border-subtle);border-radius:6px;padding:6px 10px 6px 27px;font-size:11px;min-width:250px;color:var(--text-primary)}
7540
+ .dt-filter input:focus,.dt-select:focus{outline:none;border-color:var(--border-strong)}
7541
+ .dt-select{background:var(--bg);border:1px solid var(--border-subtle);border-radius:6px;padding:6px 8px;font-size:11px;color:var(--text-primary)}
7542
+ .dt-chips{display:flex;gap:2px}
7543
+ .dt-chip{border:1px solid transparent;background:transparent;color:var(--text-secondary);border-radius:5px;padding:5px 9px;font-size:11px;cursor:pointer}
7544
+ .dt-chip:hover{color:var(--text-primary)}
7545
+ .dt-chip.active{background:var(--bg-surface-2);border-color:var(--border);color:var(--text-primary)}
7546
+ .dt-summary{margin-left:auto;display:flex;gap:10px;font:10px var(--mono);color:var(--text-tertiary)}
7547
+ .dt-pad{padding:16px;overflow:auto}
7548
+ .st{font:9px var(--mono);text-transform:uppercase;letter-spacing:.05em;color:var(--text-secondary)}
7549
+ .st.ok{color:var(--success)}.st.err{color:var(--danger)}.st.warn{color:var(--warn)}.st.live{color:var(--accent)}
7550
+ .net-link{border:0;background:transparent;padding:0;color:var(--network);font:inherit;font-size:inherit;cursor:pointer;text-decoration:underline;text-decoration-color:rgba(131,179,226,.35);text-underline-offset:2px}
7551
+ .net-link:hover{color:var(--text-primary)}
7552
+
7553
+ .net-split{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr)}
7554
+ .net-split.has-detail{grid-template-columns:minmax(280px,36%) minmax(0,1fr)}
7555
+ .net-list{overflow:auto;min-height:0}
7556
+ .net-table{width:100%;border-collapse:collapse;table-layout:fixed;font-size:11px}
7557
+ .net-table col.w-name{width:30%}.net-table col.w-type{width:9%}.net-table col.w-status{width:8%}.net-table col.w-init{width:13%}.net-table col.w-size{width:10%}.net-table col.w-time{width:8%}.net-table col.w-wf{width:22%}
7558
+ .net-table th{position:sticky;top:0;z-index:1;background:var(--bg-elevated);text-align:left;font:9px var(--mono);text-transform:uppercase;letter-spacing:.08em;color:var(--text-tertiary);padding:7px 10px;border-bottom:1px solid var(--border);border-right:1px solid var(--border-subtle);white-space:nowrap;overflow:hidden}
7559
+ .net-table td{padding:5px 10px;border-bottom:1px solid var(--border-subtle);border-right:1px solid rgba(24,33,28,.7);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;vertical-align:middle;color:var(--text-secondary)}
7560
+ .net-row{cursor:pointer}
7561
+ .net-row:nth-child(even){background:rgba(20,29,24,.32)}
7562
+ .net-row:hover{background:var(--accent-glow)}
7563
+ .net-row.selected{background:var(--accent-dim);box-shadow:inset 2px 0 0 var(--accent)}
7564
+ .net-name{display:flex;align-items:center;gap:9px;min-width:0}
7565
+ .net-name>span{min-width:0}
7566
+ .net-name b{display:block;font-weight:500;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis}
7567
+ .net-name small{display:block;color:var(--text-tertiary);font:9px var(--mono);overflow:hidden;text-overflow:ellipsis;margin-top:1px}
7568
+ .net-row.failed .net-name b{color:var(--danger)}
7569
+ .net-glyph{flex:0 0 auto;width:8px;height:8px;border-radius:2px;background:var(--accent)}
7570
+ .kind-tool .net-glyph{background:var(--network);border-radius:50%}
7571
+ .kind-subagent .net-glyph{background:var(--deploy)}
7572
+ .net-row.compaction .net-glyph{background:var(--interface)}
7573
+ .c-size,.c-time{font-family:var(--mono);font-size:10px;font-variant-numeric:tabular-nums}
7574
+ .wf-track{position:relative;display:block;height:12px}
7575
+ .wf-bar{position:absolute;top:3px;height:6px;border-radius:2px;background:var(--accent-soft);min-width:2px}
7576
+ .kind-tool .wf-bar{background:var(--network)}
7577
+ .kind-subagent .wf-bar{background:var(--deploy)}
7578
+ .net-row.failed .wf-bar{background:var(--danger)}
7579
+ .wf-bar{overflow:hidden}
7580
+ .comp-table td{padding:6px 10px}
7581
+ .comp-row.kind-resolve .wf-bar{background:var(--interface)}
7582
+ .comp-row.kind-installation .wf-bar,.comp-row.kind-mcp .wf-bar{background:var(--network)}
7583
+ .comp-group{border:1px solid var(--border);border-radius:6px;padding:10px 12px;margin:0 0 10px}
7584
+ .comp-group>header{display:flex;gap:10px;align-items:baseline;margin-bottom:8px;font-size:12px}
7585
+ .comp-group>header .muted{font-size:10px}
7586
+ .comp-group>header .muted.mono{margin-left:auto}
7587
+ .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}
7588
+ .tool-chip.called{color:var(--text-primary);border-color:var(--accent-dim)}
7589
+ .tool-chip small{margin-left:6px;padding:0 5px;border-radius:8px;background:var(--accent-dim);color:var(--text-primary);font-size:9px}
7590
+ .tool-chip:hover{border-color:var(--accent)}
7591
+ .tool-writes{margin-left:6px;font-style:normal;font-size:9px;color:var(--warning, #e0b25b)}
7592
+ .q-table .q-dir{width:28px;text-align:center}
7593
+ .q-arrow{font-weight:700}
7594
+ .q-arrow.in{color:var(--network)}
7595
+ .q-arrow.out{color:var(--accent)}
7596
+ .chain{display:grid;gap:4px;margin-top:10px}
7597
+ .chain-node{position:relative}
7598
+ .chain-edge{display:block;margin:6px 0 4px 14px;font:10px var(--mono);color:var(--text-tertiary)}
7599
+ .chain-edge::before{content:"↳ ";color:var(--text-tertiary)}
7600
+ .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}
7601
+ .chain-card .muted{font-size:10px}
7602
+ .chain-node.self>.chain-card{border-color:var(--accent);box-shadow:inset 2px 0 0 var(--accent)}
7603
+ .chain-node.origin>.chain-card{border-style:dashed}
7604
+ .chain-children{margin-left:22px;padding-left:12px;border-left:1px dashed var(--border)}
7605
+ .wf-wait{position:absolute;left:0;top:0;bottom:0;background:rgba(255,255,255,.55);mix-blend-mode:soft-light}
7606
+ .wf-queue{position:absolute;top:5.5px;height:1px;background:var(--text-tertiary);opacity:.7}
7607
+ .net-row.nested .c-name{padding-left:calc(10px + var(--depth,1) * 16px)}
7608
+ .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)}
7609
+ .net-turn td>span{margin-right:12px}
7610
+ .timing{display:grid;gap:6px;margin-top:12px}
7611
+ .timing-row{display:grid;grid-template-columns:minmax(150px,1.3fr) 2fr 70px;gap:12px;align-items:center;font-size:11px}
7612
+ .timing-row.total{border-top:1px solid var(--border);padding-top:6px;font-weight:600}
7613
+ .timing-name small{display:block;color:var(--text-tertiary);font-size:10px;margin-top:2px}
7614
+ .timing-track{position:relative;height:8px;background:rgba(255,255,255,.04);border-radius:2px}
7615
+ .timing-bar{position:absolute;left:0;top:0;bottom:0;border-radius:2px;background:var(--accent-soft)}
7616
+ .timing-bar.wait{background:rgba(255,255,255,.28)}
7617
+ .timing-bar.queue{background:var(--text-tertiary);opacity:.6}
7618
+ .wf-bar.pending{background:repeating-linear-gradient(90deg,var(--accent) 0 5px,transparent 5px 9px);opacity:.8}
7619
+ .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}
7620
+ .net-split.has-detail th.c-status,.net-split.has-detail th.c-time{width:72px}
7621
+ .net-foot{flex:0 0 auto;display:flex;flex-wrap:wrap;gap:6px 16px;padding:7px 12px;border-top:1px solid var(--border-subtle);font:10px var(--mono);color:var(--text-tertiary);background:rgba(8,11,10,.4)}
7622
+ .net-foot-right{margin-left:auto}
7623
+ .net-detail{border-left:1px solid var(--border);display:flex;flex-direction:column;min-width:0;min-height:0;background:var(--bg-elevated)}
7624
+ .nd-head{display:flex;align-items:stretch;border-bottom:1px solid var(--border-subtle);overflow-x:auto;flex:0 0 auto}
7625
+ .nd-close{border:0;background:transparent;color:var(--text-tertiary);padding:0 10px;cursor:pointer;display:flex;align-items:center}
7626
+ .nd-close:hover{color:var(--text-primary)}
7627
+ .nd-close .icon{width:13px;height:13px}
7628
+ .nd-tab{border:0;background:transparent;color:var(--text-secondary);font-size:11px;padding:9px 10px 7px;border-bottom:2px solid transparent;cursor:pointer;white-space:nowrap;display:inline-flex;align-items:center;gap:6px}
7629
+ .nd-tab:hover{color:var(--text-primary)}
7630
+ .nd-tab.active{color:var(--text-primary);border-bottom-color:var(--accent)}
7631
+ .nd-actions{margin-left:auto;display:flex;align-items:center;padding:0 8px}
7632
+ .nd-actions .button{padding:5px 9px;font-size:10px}
7633
+ .nd-title{display:flex;align-items:baseline;gap:10px;padding:12px 16px 0;flex:0 0 auto}
7634
+ .nd-title b{font-size:14px;font-weight:500}.nd-title span{font:10px var(--mono);color:var(--text-tertiary)}
7635
+ .nd-body{overflow:auto;padding:14px 16px 20px;min-height:0;flex:1}
7636
+ .dt-kv{display:grid;grid-template-columns:140px minmax(0,1fr);gap:8px 14px;margin:0 0 14px;font-size:11px;line-height:1.5}
7637
+ .dt-kv dt{color:var(--text-tertiary);font:9px var(--mono);text-transform:uppercase;letter-spacing:.08em;padding-top:3px}
7638
+ .dt-kv dd{margin:0;color:var(--text-primary);overflow-wrap:anywhere}
7639
+ .dt-kv .copy-btn{opacity:1;vertical-align:middle}
7640
+ .dt-section{font:9px var(--mono);text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary);margin:18px 0 8px}
7641
+ .dt-note{font-size:11px;color:var(--text-secondary);line-height:1.55;margin:0 0 12px}
7642
+ .dt-bar{display:flex;align-items:center;gap:8px;margin-bottom:8px;font:10px var(--mono);color:var(--text-tertiary)}
7643
+ .dt-bar .copy-btn{opacity:1}
7644
+ .dt-pre{margin:0;white-space:pre-wrap;overflow-wrap:anywhere;font:11px/1.6 var(--mono);color:var(--text-primary);background:#070A09;border:1px solid var(--border-subtle);border-radius:7px;padding:12px 14px}
7645
+ .tool-def{border:1px solid var(--border-subtle);border-radius:7px;margin-bottom:6px;background:var(--bg)}
7646
+ .tool-def>summary{display:flex;gap:10px;align-items:baseline;padding:8px 11px;cursor:pointer;font-size:11px}
7647
+ .tool-def>summary b{font:500 11px var(--mono);color:var(--network)}
7648
+ .tool-def>summary span{color:var(--text-tertiary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
7649
+ .tool-def>.dt-note,.tool-def>.jt-root{margin:0 11px 10px}
7650
+ .sum-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:12px;align-items:baseline;padding:7px 0;border-bottom:1px solid var(--border-subtle);font-size:11px}
7651
+ .sum-row:last-child{border-bottom:0}
7652
+ .sum-row .sum-msg{grid-column:1/-1;color:var(--text-secondary);font:10px var(--mono)}
7653
+
7654
+ /* Messages, as the model received them. */
7655
+ .tm{border:1px solid var(--border-subtle);border-radius:8px;background:var(--bg);margin-bottom:8px;overflow:hidden}
7656
+ .tm>header{display:flex;align-items:center;gap:8px;padding:6px 11px;border-bottom:1px solid var(--border-subtle);background:rgba(20,29,24,.45)}
7657
+ .tm-role{font:9px var(--mono);text-transform:uppercase;letter-spacing:.1em;color:var(--text-secondary)}
7658
+ .tm.user .tm-role{color:var(--accent)}.tm.agent .tm-role{color:var(--text-primary)}.tm.tool .tm-role{color:var(--network)}.tm.runtime .tm-role{color:var(--interface)}.tm.system .tm-role{color:var(--deploy)}
7659
+ .tm.runtime{border-color:rgba(228,184,121,.2)}
7660
+ .tm.new{border-color:var(--accent-line)}
7661
+ .tm.missing{opacity:.6;border-style:dashed}
7662
+ .tm-new{margin-left:auto;font:8px var(--mono);text-transform:uppercase;letter-spacing:.08em;color:var(--accent);background:var(--accent-dim);border-radius:10px;padding:2px 7px}
7663
+ .tm-new.quiet{color:var(--text-tertiary);background:var(--bg-surface)}
7664
+ .tm-text{padding:10px 12px;white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px;line-height:1.55;max-height:480px;overflow:auto;color:var(--text-primary)}
7665
+ .tm-call,.tm-result{padding:8px 12px;border-top:1px solid var(--border-subtle)}
7666
+ .tm-call>span,.tm-result>span{display:block;font:10px var(--mono);color:var(--text-secondary);margin-bottom:6px}
7667
+ .tm-result.status-error>span{color:var(--danger)}
7668
+ .tm-note{font:10px/1.5 var(--mono);color:var(--text-tertiary);padding:6px 12px 8px;margin:0}
7669
+ .tm-media-row{padding:0 12px 8px}
7670
+ .tm-media{display:inline-flex;gap:6px;align-items:center;margin:0 6px 4px 0;font:10px var(--mono);border:1px solid var(--border);border-radius:5px;padding:4px 7px;color:var(--text-secondary)}
7671
+ .tm-media .icon{width:11px;height:11px}
7672
+ .msg-earlier{margin-bottom:10px}
7673
+ .msg-earlier>summary{cursor:pointer;font-size:11px;color:var(--text-secondary);padding:8px 11px;border:1px dashed var(--border);border-radius:7px;margin-bottom:8px}
7674
+ .msg-earlier[open]>summary{border-style:solid}
7675
+
7676
+ /* JSON trees */
7677
+ .jt-root{font:11px/1.6 var(--mono);color:var(--text-secondary);overflow-wrap:anywhere}
7678
+ .jt>summary{cursor:pointer;color:var(--text-tertiary)}
7679
+ .jt[open]>summary{color:var(--text-tertiary)}
7680
+ .jt-body{padding-left:14px;border-left:1px solid var(--border-subtle);margin-left:3px}
7681
+ .jk{color:var(--deploy)}.jv.str{color:var(--accent-strong);white-space:pre-wrap}.jv.num{color:var(--network)}.jv.bool{color:var(--interface)}.jv.null{color:var(--text-tertiary);font-style:italic}
7682
+ .jv-note{display:block;font-size:9px;color:var(--text-tertiary);text-transform:uppercase;letter-spacing:.08em;margin-bottom:2px}
7683
+
7684
+ /* Console */
7685
+ .con-list{flex:1;min-height:0;overflow:auto;font:11px/1.5 var(--mono)}
7686
+ .con-row{border-bottom:1px solid var(--border-subtle)}
7687
+ .con-line{width:100%;border:0;background:transparent;display:grid;grid-template-columns:62px 14px minmax(0,1fr) auto;gap:8px;padding:4px 12px;text-align:left;cursor:pointer;align-items:start;font:inherit;color:var(--text-primary)}
7688
+ .con-line:hover{background:var(--accent-glow)}
7689
+ .con-time{color:var(--text-tertiary);font-variant-numeric:tabular-nums}
7690
+ .con-lvl{display:flex;padding-top:2px}.con-lvl .icon{width:12px;height:12px}
7691
+ .con-msg{white-space:pre-wrap;overflow-wrap:anywhere}
7692
+ .con-src{color:var(--text-tertiary);font-size:9px;padding-top:2px}
7693
+ .con-row.lvl-error{background:rgba(226,155,168,.06)}.con-row.lvl-error .con-line{color:var(--danger)}
7694
+ .con-row.lvl-warn{background:rgba(228,184,121,.06)}.con-row.lvl-warn .con-line{color:var(--warn)}
7695
+ .con-row.lvl-verbose .con-msg{color:var(--text-secondary)}
7696
+ .con-detail{display:none;padding:4px 12px 12px 96px}
7697
+ .con-row.open .con-detail{display:block}
7698
+ .con-row.open .con-line{background:var(--accent-glow)}
7699
+ .con-detail-head{display:flex;align-items:center;gap:12px;margin-bottom:6px;font-size:10px}
7700
+ .con-detail-head .copy-btn{opacity:1;margin-left:auto}
7701
+ .con-more{padding:10px 12px;margin:0}
7702
+
7703
+ /* Context */
7704
+ .ctx{flex:1;min-height:0;display:grid;grid-template-columns:220px minmax(0,1fr)}
7705
+ .ctx-tree{border-right:1px solid var(--border-subtle);overflow:auto;padding:6px 0 16px;background:rgba(8,11,10,.35)}
7706
+ .ctx-group{font:9px var(--mono);text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary);padding:12px 14px 5px}
7707
+ .ctx-node{display:flex;align-items:center;gap:8px;width:100%;border:0;background:transparent;color:var(--text-secondary);font-size:12px;padding:6px 14px 6px 20px;cursor:pointer;text-align:left}
7708
+ .ctx-node:hover{color:var(--text-primary);background:var(--accent-glow)}
7709
+ .ctx-node.active{background:var(--accent-dim);color:var(--text-primary);box-shadow:inset 2px 0 0 var(--accent)}
7710
+ .ctx-node small{margin-left:auto;font:9px var(--mono);color:var(--text-tertiary)}
7711
+ .ctx-view{overflow:auto;padding:16px 18px 24px;min-height:0}
7712
+ .ctx-request{display:flex;align-items:center;gap:8px;margin-bottom:14px;font:9px var(--mono);text-transform:uppercase;letter-spacing:.1em;color:var(--text-tertiary)}
7713
+
7714
+ @media(max-width:1100px){.dt-hint{display:none}}
7715
+ @media(max-width:900px){
7716
+ .net-split.has-detail{grid-template-columns:1fr;grid-template-rows:minmax(160px,38%) minmax(0,1fr)}
7717
+ .net-detail{border-left:0;border-top:1px solid var(--border)}
7718
+ .c-init,.c-size,.c-type{display:none}
7719
+ .ctx{grid-template-columns:1fr;grid-template-rows:auto minmax(0,1fr)}
7720
+ .ctx-tree{display:flex;flex-wrap:nowrap;overflow-x:auto;padding:4px;border-right:0;border-bottom:1px solid var(--border-subtle)}
7721
+ .ctx-group{display:none}.ctx-node{width:auto;white-space:nowrap;padding:7px 10px}
7722
+ .con-detail{padding-left:12px}
7723
+ .dt-filter input{min-width:0;width:100%}.dt-filter{flex:1 1 200px}
7724
+ .dt-kv{grid-template-columns:1fr}
7725
+ }
5929
7726
  @media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}
5930
7727
  `;
5931
7728
 
@@ -6226,7 +8023,7 @@ ${current.content}
6226
8023
  }
6227
8024
  function openAiOutput(value) {
6228
8025
  if (typeof value === "string") return value;
6229
- if (value === void 0) return "";
8026
+ if (value === void 0 || value === null) return "";
6230
8027
  return JSON.stringify(value);
6231
8028
  }
6232
8029
  function responseContentPart(value) {
@@ -6572,6 +8369,12 @@ var FoundryServer = class {
6572
8369
  return;
6573
8370
  }
6574
8371
  const v1Approval = url.pathname.match(/^\/v1\/approvals\/([^/]+)$/);
8372
+ if (v1Approval && method === "GET") {
8373
+ const approval = await this.runtime.getApproval(decodeURIComponent(v1Approval[1]));
8374
+ if (!approval) throw new RequestError(404, "Foundry approval was not found.");
8375
+ json(response, 200, approval);
8376
+ return;
8377
+ }
6575
8378
  if (v1Approval && method === "POST") {
6576
8379
  json(response, 200, await this.runtime.resolveApproval(
6577
8380
  decodeURIComponent(v1Approval[1]),
@@ -6610,6 +8413,8 @@ var FoundryServer = class {
6610
8413
  json(response, 201, await this.runtime.createAgent(body.definitionId, {
6611
8414
  ...typeof body.id === "string" ? { id: body.id } : {},
6612
8415
  ...typeof body.workspaceId === "string" ? { workspaceId: body.workspaceId } : {},
8416
+ ...typeof body.name === "string" ? { name: body.name } : {},
8417
+ ...typeof body.description === "string" ? { description: body.description } : {},
6613
8418
  ...body.context && typeof body.context === "object" ? { context: body.context } : {},
6614
8419
  ...Array.isArray(body.installations) ? { installations: body.installations } : {},
6615
8420
  ...Array.isArray(body.playbooks) ? { playbooks: body.playbooks } : {}
@@ -6665,6 +8470,8 @@ var FoundryServer = class {
6665
8470
  json(response, 200, await this.runtime.configureAgent(
6666
8471
  decodeURIComponent(instanceConfiguration[1]),
6667
8472
  {
8473
+ ...typeof body.name === "string" ? { name: body.name } : {},
8474
+ ...typeof body.description === "string" ? { description: body.description } : {},
6668
8475
  ...body.context && typeof body.context === "object" ? { context: body.context } : {},
6669
8476
  ...Array.isArray(body.installations) ? { installations: body.installations } : {},
6670
8477
  ...Array.isArray(body.playbooks) ? { playbooks: body.playbooks } : {}
@@ -7013,6 +8820,12 @@ var FoundryServer = class {
7013
8820
  return;
7014
8821
  }
7015
8822
  const approvalMatch = url.pathname.match(/^\/api\/approvals\/([^/]+)$/);
8823
+ if (approvalMatch && method === "GET") {
8824
+ const approval = await this.runtime.getApproval(decodeURIComponent(approvalMatch[1]));
8825
+ if (!approval) throw new RequestError(404, "Foundry approval was not found.");
8826
+ json(response, 200, approval);
8827
+ return;
8828
+ }
7016
8829
  if (approvalMatch && method === "POST") {
7017
8830
  json(response, 200, await this.runtime.resolveApproval(
7018
8831
  decodeURIComponent(approvalMatch[1]),
@@ -7083,7 +8896,9 @@ var FoundryServer = class {
7083
8896
  json(
7084
8897
  response,
7085
8898
  200,
8899
+ // `after` lets a live view fetch only what it hasn't seen.
7086
8900
  this.runtime.observability.list({
8901
+ ...eventFilter(url),
7087
8902
  runId: decodeURIComponent(eventsMatch[1]),
7088
8903
  limit: 5e3
7089
8904
  })