glove-foundry 0.6.1 → 0.8.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.
- package/README.md +80 -4
- package/dist/chunk-CYOIHSUX.js +1365 -0
- package/dist/{chunk-X6EWEWWM.js → chunk-DTFCEX67.js} +2003 -200
- package/dist/{chunk-OBTOFA7W.js → chunk-EUGKVW3J.js} +470 -638
- package/dist/{chunk-B36BGF5R.js → chunk-J6NHL4SM.js} +370 -74
- package/dist/{chunk-7F7QVO6I.js → chunk-L5JQVTHD.js} +30 -0
- package/dist/{chunk-RSU7NEDK.js → chunk-X3HZYVZS.js} +36 -1
- package/dist/cli.js +4 -4
- package/dist/{client-DWPYe_Nc.d.ts → client-CekanYLW.d.ts} +252 -161
- package/dist/client.d.ts +3 -3
- package/dist/client.js +1 -1
- package/dist/config.d.ts +7 -0
- package/dist/{definition-A8o11aez.d.ts → event-delivery-CNCsVqi8.d.ts} +1380 -871
- package/dist/execution-agent.d.ts +0 -1
- package/dist/execution-agent.js +3 -14
- package/dist/execution-daemon.js +10 -5
- package/dist/execution-loader.js +1171 -8
- package/dist/index.d.ts +21 -6
- package/dist/index.js +178 -32
- package/dist/voice.d.ts +12 -8
- package/dist/voice.js +51 -10
- package/docs/README.md +1 -1
- package/docs/architecture.md +8 -0
- package/docs/building-with-foundry.md +137 -5
- package/docs/durable-subagents.md +337 -0
- package/docs/execution.md +4 -0
- package/docs/inspector.md +137 -29
- package/package.json +12 -11
- package/templates/travel-concierge/README.md +1 -1
- package/dist/chunk-K2EU63MB.js +0 -468
- package/dist/chunk-TFGETZYH.js +0 -917
|
@@ -5,62 +5,90 @@ 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
|
-
EMPTY_CAPABILITY_REGISTRY,
|
|
10
11
|
EMPTY_FOUNDRY_APPLICATION,
|
|
11
|
-
FOUNDRY_AGENT_APPLICATION_BRAND,
|
|
12
12
|
FOUNDRY_APPROVAL_DIRECTORY_ENV,
|
|
13
|
-
|
|
13
|
+
FOUNDRY_APPROVAL_POLICY_ENV,
|
|
14
14
|
FOUNDRY_CORE_COMMAND_EVENT,
|
|
15
|
-
|
|
16
|
-
FOUNDRY_MEMORY_BRAND,
|
|
17
|
-
FOUNDRY_SHARED_TOOL_BRAND,
|
|
15
|
+
FOUNDRY_MODEL_REQUESTS_ENV,
|
|
18
16
|
MemoryFoundryDataAdapter,
|
|
19
|
-
claimFoundryCoreCommandRequest,
|
|
20
17
|
createAgentInstance,
|
|
21
18
|
createConversation,
|
|
22
19
|
createManifest,
|
|
23
20
|
definePlaybookSubscription,
|
|
24
|
-
defineSharedTool,
|
|
25
21
|
discoverAgents,
|
|
22
|
+
foundryApprovalRequested,
|
|
23
|
+
foundryApprovalSuspended,
|
|
26
24
|
freezeGloveMessage,
|
|
27
|
-
getFoundryCoreCommandRequest,
|
|
28
25
|
id,
|
|
29
|
-
installationKey,
|
|
30
26
|
listFoundryApprovals,
|
|
31
|
-
|
|
27
|
+
markFoundryApprovalSuspended,
|
|
32
28
|
normalizeAgentInstallations,
|
|
29
|
+
readFoundryApprovalResolution,
|
|
33
30
|
reconstructPlaybook,
|
|
34
31
|
reconstructPlaybookSubscription,
|
|
35
32
|
resolveFoundryApproval,
|
|
36
|
-
settleFoundryCoreCommandRequest,
|
|
37
33
|
transmissionPredicate
|
|
38
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-EUGKVW3J.js";
|
|
39
35
|
import {
|
|
40
36
|
FOUNDRY_CONVERSATION_LEASE_EVENT,
|
|
41
37
|
FOUNDRY_CONVERSATION_LISTEN_EVENT,
|
|
42
38
|
FOUNDRY_MAILBOX_DIRECTORY_ENV,
|
|
43
39
|
delegationFromContext,
|
|
40
|
+
deliveryEvent,
|
|
44
41
|
drainMailbox,
|
|
45
42
|
isDelegationId,
|
|
43
|
+
isMeshCommand,
|
|
46
44
|
isOpenDelegation,
|
|
45
|
+
isOpenThread,
|
|
46
|
+
isThreadId,
|
|
47
|
+
meshIdentity,
|
|
48
|
+
newMessageId,
|
|
47
49
|
renderDelegatedTask,
|
|
48
50
|
renderDeliveries,
|
|
51
|
+
startedThreadIds,
|
|
52
|
+
threadFromContext,
|
|
53
|
+
threadSubject,
|
|
49
54
|
undeliveredUpdate,
|
|
50
55
|
workerAgentId,
|
|
51
56
|
writeConversationLease,
|
|
52
57
|
writeMailboxDelivery
|
|
53
|
-
} from "./chunk-
|
|
58
|
+
} from "./chunk-J6NHL4SM.js";
|
|
54
59
|
import {
|
|
60
|
+
EMPTY_CAPABILITY_REGISTRY,
|
|
55
61
|
EMPTY_NATIVE_REGISTRY,
|
|
62
|
+
FOUNDRY_AGENT_APPLICATION_BRAND,
|
|
56
63
|
FOUNDRY_APPLICATION_ENV,
|
|
64
|
+
FOUNDRY_CORE_COMMAND_DIRECTORY_ENV,
|
|
57
65
|
FOUNDRY_EVENT_PREFIX,
|
|
58
66
|
FOUNDRY_EXECUTION_MARKER,
|
|
59
67
|
FOUNDRY_LAYER_BRAND,
|
|
68
|
+
FOUNDRY_MCP_BRAND,
|
|
69
|
+
FOUNDRY_MEMORY_BRAND,
|
|
60
70
|
FOUNDRY_RUN_PROCESS_EVENT,
|
|
71
|
+
FOUNDRY_SHARED_TOOL_BRAND,
|
|
61
72
|
FOUNDRY_SUBSCRIBER_BRAND,
|
|
62
|
-
|
|
63
|
-
|
|
73
|
+
agentInboxId,
|
|
74
|
+
bindFileIdentity,
|
|
75
|
+
claimFoundryCoreCommandRequest,
|
|
76
|
+
defineSharedTool,
|
|
77
|
+
durableInstanceId,
|
|
78
|
+
durableKey,
|
|
79
|
+
durableRoute,
|
|
80
|
+
eventDue,
|
|
81
|
+
eventPolicySchema,
|
|
82
|
+
eventRecordId,
|
|
83
|
+
foundryEventSchema,
|
|
84
|
+
getFoundryCoreCommandRequest,
|
|
85
|
+
hostedMeshOptions,
|
|
86
|
+
inheritedInstallations,
|
|
87
|
+
installationKey,
|
|
88
|
+
messageOptionsSchema,
|
|
89
|
+
monitorFoundryCoreCommandRequest,
|
|
90
|
+
settleFoundryCoreCommandRequest
|
|
91
|
+
} from "./chunk-CYOIHSUX.js";
|
|
64
92
|
|
|
65
93
|
// src/codegen.ts
|
|
66
94
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
@@ -861,6 +889,7 @@ var FoundryObserver = class {
|
|
|
861
889
|
};
|
|
862
890
|
|
|
863
891
|
// src/runtime.ts
|
|
892
|
+
import { isDeepStrictEqual } from "node:util";
|
|
864
893
|
import { mkdir as mkdir2, rm as rm2 } from "node:fs/promises";
|
|
865
894
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
866
895
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
@@ -879,6 +908,26 @@ import { mkdtemp, rm } from "node:fs/promises";
|
|
|
879
908
|
import { tmpdir } from "node:os";
|
|
880
909
|
import { join } from "node:path";
|
|
881
910
|
import { fileURLToPath } from "node:url";
|
|
911
|
+
var DaemonDisconnectedError = class extends Error {
|
|
912
|
+
exitCode;
|
|
913
|
+
signal;
|
|
914
|
+
/** The end of what the daemon wrote to stderr, with known secret values masked. */
|
|
915
|
+
stderrTail;
|
|
916
|
+
constructor(exitCode, signal, stderrTail) {
|
|
917
|
+
const how = exitCode !== null ? ` (exit code ${exitCode})` : signal ? ` (signal ${signal})` : "";
|
|
918
|
+
super(`Foundry execution daemon disconnected${how}. A pending mutation may have completed; inspect state before retrying.`);
|
|
919
|
+
this.name = "DaemonDisconnectedError";
|
|
920
|
+
this.exitCode = exitCode;
|
|
921
|
+
this.signal = signal;
|
|
922
|
+
this.stderrTail = stderrTail;
|
|
923
|
+
}
|
|
924
|
+
};
|
|
925
|
+
var STDERR_TAIL_BYTES = 4096;
|
|
926
|
+
var SECRET_NAME = /(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/i;
|
|
927
|
+
function redactor(env) {
|
|
928
|
+
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);
|
|
929
|
+
return (text) => values.reduce((out, value) => out.split(value).join("[redacted]"), text);
|
|
930
|
+
}
|
|
882
931
|
function entry(name) {
|
|
883
932
|
const built = fileURLToPath(new URL(`./${name}.js`, import.meta.url));
|
|
884
933
|
return existsSync(built) ? built : fileURLToPath(new URL(`./${name}.ts`, import.meta.url));
|
|
@@ -896,6 +945,7 @@ var FoundryExecutionBackend = class {
|
|
|
896
945
|
loopResolve;
|
|
897
946
|
loopReject;
|
|
898
947
|
loop;
|
|
948
|
+
stderrTail = "";
|
|
899
949
|
get processId() {
|
|
900
950
|
return this.child?.pid;
|
|
901
951
|
}
|
|
@@ -911,7 +961,10 @@ var FoundryExecutionBackend = class {
|
|
|
911
961
|
execArgv: ["--import", import.meta.resolve("tsx")],
|
|
912
962
|
stdio: ["ignore", "ignore", "pipe", "ipc"]
|
|
913
963
|
});
|
|
914
|
-
|
|
964
|
+
const redact = redactor(env);
|
|
965
|
+
child.stderr?.on("data", (chunk) => {
|
|
966
|
+
this.stderrTail = redact((this.stderrTail + chunk.toString("utf8")).slice(-STDERR_TAIL_BYTES * 2)).slice(-STDERR_TAIL_BYTES);
|
|
967
|
+
});
|
|
915
968
|
this.loop = new Promise((resolve3, reject) => {
|
|
916
969
|
this.loopResolve = resolve3;
|
|
917
970
|
this.loopReject = reject;
|
|
@@ -934,7 +987,11 @@ var FoundryExecutionBackend = class {
|
|
|
934
987
|
else request.resolve(message.value);
|
|
935
988
|
});
|
|
936
989
|
const failed = () => {
|
|
937
|
-
const error = new
|
|
990
|
+
const error = new DaemonDisconnectedError(child.exitCode, child.signalCode, this.stderrTail);
|
|
991
|
+
if (!this.stopped && error.stderrTail) process.stderr.write(`${error.message}
|
|
992
|
+
The daemon's last output:
|
|
993
|
+
${error.stderrTail}
|
|
994
|
+
`);
|
|
938
995
|
for (const request of this.pending.values()) {
|
|
939
996
|
clearTimeout(request.timer);
|
|
940
997
|
request.reject(error);
|
|
@@ -989,6 +1046,8 @@ var FoundryExecutionBackend = class {
|
|
|
989
1046
|
if (child) {
|
|
990
1047
|
try {
|
|
991
1048
|
if (child.connected) await this.request({ method: "stop" }, 15e3);
|
|
1049
|
+
} catch (error) {
|
|
1050
|
+
if (!(error instanceof DaemonDisconnectedError)) throw error;
|
|
992
1051
|
} finally {
|
|
993
1052
|
if (child.exitCode === null && child.signalCode === null) {
|
|
994
1053
|
await new Promise((resolve3) => {
|
|
@@ -1605,8 +1664,15 @@ var FoundryRuntimeError = class extends Schema3.TaggedError(
|
|
|
1605
1664
|
message: Schema3.String
|
|
1606
1665
|
}) {
|
|
1607
1666
|
};
|
|
1667
|
+
function clipTitle(text) {
|
|
1668
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
1669
|
+
return flat.length > 60 ? `${flat.slice(0, 59)}\u2026` : flat;
|
|
1670
|
+
}
|
|
1608
1671
|
function deliverySource(deliveries) {
|
|
1609
1672
|
const first = deliveries[0];
|
|
1673
|
+
if (first.kind === "mesh") return { kind: "mesh", id: first.message.threadId };
|
|
1674
|
+
if (first.durable?.event.kind?.startsWith("delegation.")) return { kind: "delegation", id: first.durable.event.id };
|
|
1675
|
+
if (first.kind === "agent-message") return { kind: "agent-message", id: first.pendingId };
|
|
1610
1676
|
if (deliveries.every((delivery) => delivery.kind === "transmission")) {
|
|
1611
1677
|
return first.kind === "transmission" ? { kind: "transmission", id: first.routeId, eventId: first.eventId } : { kind: "transmission" };
|
|
1612
1678
|
}
|
|
@@ -1715,9 +1781,15 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1715
1781
|
}
|
|
1716
1782
|
});
|
|
1717
1783
|
/** Pending inbound records each run is handling, so they are cleared when it settles. */
|
|
1784
|
+
eventTimers = /* @__PURE__ */ new Map();
|
|
1785
|
+
completedEventRuns = /* @__PURE__ */ new Map();
|
|
1718
1786
|
pendingInboundByRun = /* @__PURE__ */ new Map();
|
|
1719
1787
|
/** Recently settled runs, for a record assigned to a run that already finished. */
|
|
1720
1788
|
settledRuns = /* @__PURE__ */ new Set();
|
|
1789
|
+
/** How runs treat approvals; durable when the data adapter can keep them. */
|
|
1790
|
+
approvalPolicy;
|
|
1791
|
+
/** Approval records change one at a time. */
|
|
1792
|
+
approvalWrites = Promise.resolve();
|
|
1721
1793
|
started = false;
|
|
1722
1794
|
stopping = false;
|
|
1723
1795
|
disposed = false;
|
|
@@ -1774,6 +1846,14 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1774
1846
|
maxEvents: options.config?.observability?.maxEvents
|
|
1775
1847
|
});
|
|
1776
1848
|
this.data = this.application.data ?? new MemoryFoundryDataAdapter();
|
|
1849
|
+
const durableApprovals = Boolean(
|
|
1850
|
+
this.data.putApproval && this.data.getApproval && this.data.listApprovals && this.data.claimEvent && this.data.putEvent && this.data.listEvents
|
|
1851
|
+
);
|
|
1852
|
+
this.approvalPolicy = {
|
|
1853
|
+
durable: durableApprovals,
|
|
1854
|
+
waitMs: this.application.approvals?.waitMs ?? (durableApprovals ? DEFAULT_APPROVAL_WAIT_MS : 3e5),
|
|
1855
|
+
expiresAfterMs: this.application.approvals?.expiresAfterMs ?? DEFAULT_APPROVAL_EXPIRES_AFTER_MS
|
|
1856
|
+
};
|
|
1777
1857
|
for (const discovered of this.agents) {
|
|
1778
1858
|
this.byRoute.set(discovered.route, discovered);
|
|
1779
1859
|
this.routeBySignalName.set(discovered.executionName, discovered.route);
|
|
@@ -1802,6 +1882,10 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1802
1882
|
void this.gate.claim(conversationId, runId).then(() => writeConversationLease(this.mailboxDirectory, runId)).catch((cause) => this.reportDeliveryFailure(conversationId, cause));
|
|
1803
1883
|
return;
|
|
1804
1884
|
}
|
|
1885
|
+
if (event.type === "foundry.approval.requested" || event.type === "foundry.approval.suspended" || event.type === "foundry.approval.settled") {
|
|
1886
|
+
void this.recordApprovalEvent(event.type, event.data).catch((cause) => this.reportApprovalFailure(event.run.id, cause));
|
|
1887
|
+
return;
|
|
1888
|
+
}
|
|
1805
1889
|
if (event.type === FOUNDRY_CORE_COMMAND_EVENT) {
|
|
1806
1890
|
void this.executeCoreCommand(event.data, event.run.id).catch((cause) => {
|
|
1807
1891
|
this.observability.append({
|
|
@@ -1877,9 +1961,11 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1877
1961
|
observer: this.observer,
|
|
1878
1962
|
env: {
|
|
1879
1963
|
[FOUNDRY_APPROVAL_DIRECTORY_ENV]: this.approvalDirectory,
|
|
1964
|
+
[FOUNDRY_APPROVAL_POLICY_ENV]: JSON.stringify(this.approvalPolicy),
|
|
1880
1965
|
[FOUNDRY_CORE_COMMAND_DIRECTORY_ENV]: this.coreCommandDirectory,
|
|
1881
1966
|
[FOUNDRY_MAILBOX_DIRECTORY_ENV]: this.mailboxDirectory,
|
|
1882
|
-
...this.applicationFilePath ? { [FOUNDRY_APPLICATION_ENV]: this.applicationFilePath } : {}
|
|
1967
|
+
...this.applicationFilePath ? { [FOUNDRY_APPLICATION_ENV]: this.applicationFilePath } : {},
|
|
1968
|
+
...options.config?.observability?.modelRequests === false ? { [FOUNDRY_MODEL_REQUESTS_ENV]: "off" } : {}
|
|
1883
1969
|
}
|
|
1884
1970
|
});
|
|
1885
1971
|
this.scheduleAdapter = this.signalRunner.schedules;
|
|
@@ -1934,6 +2020,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1934
2020
|
]);
|
|
1935
2021
|
await this.seedTopology();
|
|
1936
2022
|
for (const instance of await this.listAgentInstances()) {
|
|
2023
|
+
if (instance.durableSubagent) continue;
|
|
1937
2024
|
if (!this.byRoute.has(instance.definitionId)) {
|
|
1938
2025
|
throw new Error(
|
|
1939
2026
|
`Agent instance "${instance.id}" references unknown definition "${instance.definitionId}".`
|
|
@@ -1955,8 +2042,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1955
2042
|
await this.reconstructActivations();
|
|
1956
2043
|
this.runInBackground("signal", this.signalRunner.start());
|
|
1957
2044
|
await this.reconcileApplicationConnections();
|
|
1958
|
-
void this.redeliverDelegations().catch((cause) => this.reportDeliveryFailure("startup", cause));
|
|
1959
|
-
void this.redeliverInbound().catch((cause) => this.reportDeliveryFailure("startup", cause));
|
|
2045
|
+
void this.redeliverInbound().then(() => this.redeliverDelegations()).then(() => this.redeliverThreads()).then(() => this.redeliverEvents()).then(() => this.reconcileApprovals()).catch((cause) => this.reportDeliveryFailure("startup", cause));
|
|
1960
2046
|
} catch (cause) {
|
|
1961
2047
|
try {
|
|
1962
2048
|
await this.stop();
|
|
@@ -1983,6 +2069,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1983
2069
|
return;
|
|
1984
2070
|
}
|
|
1985
2071
|
this.stopping = true;
|
|
2072
|
+
for (const timer of this.eventTimers.values()) clearTimeout(timer);
|
|
2073
|
+
this.eventTimers.clear();
|
|
1986
2074
|
for (const timer of this.activationTimers.values()) clearTimeout(timer);
|
|
1987
2075
|
this.activationTimers.clear();
|
|
1988
2076
|
this.activationDispatches.clear();
|
|
@@ -2013,6 +2101,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2013
2101
|
if (!discovered) throw new Error(`Foundry agent "${route}" was not found.`);
|
|
2014
2102
|
const agent = await Effect5.runPromise(this.data.getAgent(request.agentId));
|
|
2015
2103
|
if (!agent) throw new Error(`Foundry agent instance "${request.agentId}" was not found.`);
|
|
2104
|
+
await this.assertDurableActive(agent);
|
|
2016
2105
|
if (agent.definitionId !== route) {
|
|
2017
2106
|
throw new Error(`Agent instance "${request.agentId}" uses definition "${agent.definitionId}", not "${route}".`);
|
|
2018
2107
|
}
|
|
@@ -2041,6 +2130,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2041
2130
|
return Effect5.runPromise(this.requestEffect(route, request));
|
|
2042
2131
|
}
|
|
2043
2132
|
async createAgent(definitionId, options = {}) {
|
|
2133
|
+
if (definitionId.includes("/workers/") || options.durableSubagent) throw new Error("Create durable workers through subagent(parentAgentId, name).");
|
|
2044
2134
|
if (!this.byRoute.has(definitionId)) {
|
|
2045
2135
|
throw new Error(`Foundry agent definition "${definitionId}" was not found.`);
|
|
2046
2136
|
}
|
|
@@ -2057,6 +2147,208 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2057
2147
|
if (this.started) await this.reconcileApplicationConnections();
|
|
2058
2148
|
return agent;
|
|
2059
2149
|
}
|
|
2150
|
+
/** Provision exactly one owned worker per parent instance and declared slot. */
|
|
2151
|
+
subagent(parentAgentId, name) {
|
|
2152
|
+
return this.inConversation("durable:mutations", () => this.ensureSubagent(parentAgentId, name));
|
|
2153
|
+
}
|
|
2154
|
+
async ensureSubagent(parentAgentId, name) {
|
|
2155
|
+
const parent = await Effect5.runPromise(this.data.getAgent(parentAgentId));
|
|
2156
|
+
if (!parent) throw new Error(`Parent agent "${parentAgentId}" does not exist.`);
|
|
2157
|
+
await this.assertDurableActive(parent);
|
|
2158
|
+
const selection = this.byRoute.get(parent.definitionId)?.definition.durableSubagents?.[name];
|
|
2159
|
+
if (!selection || !Object.hasOwn(this.byRoute.get(parent.definitionId).definition.durableSubagents ?? {}, name)) throw new Error(`Agent "${parentAgentId}" has no durable worker "${name}".`);
|
|
2160
|
+
const route = durableRoute(parent.definitionId, name);
|
|
2161
|
+
const child = await Effect5.runPromise(this.data.provisionAgent({
|
|
2162
|
+
id: durableInstanceId(parent.id, name),
|
|
2163
|
+
definitionId: route,
|
|
2164
|
+
provisioningKey: durableKey(parent.id, name),
|
|
2165
|
+
workspaceId: parent.workspaceId,
|
|
2166
|
+
context: selection.inherit?.context ? parent.context : {},
|
|
2167
|
+
durableSubagent: { parentAgentId: parent.id, name, status: "active" }
|
|
2168
|
+
}));
|
|
2169
|
+
if (child.definitionId !== route || child.workspaceId !== parent.workspaceId || child.durableSubagent?.parentAgentId !== parent.id || child.durableSubagent.name !== name) throw new Error("Durable worker ownership conflict.");
|
|
2170
|
+
await this.assertDurableActive(child);
|
|
2171
|
+
return child;
|
|
2172
|
+
}
|
|
2173
|
+
async listSubagents(parentAgentId) {
|
|
2174
|
+
return (await this.listAgentInstances()).filter((agent) => agent.durableSubagent?.parentAgentId === parentAgentId);
|
|
2175
|
+
}
|
|
2176
|
+
async assertDurableActive(agent) {
|
|
2177
|
+
if (agent.definitionId.includes("/workers/") && !agent.durableSubagent) throw new Error("Durable worker ownership is missing.");
|
|
2178
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2179
|
+
let current = agent;
|
|
2180
|
+
while (current.durableSubagent) {
|
|
2181
|
+
if (seen.has(current.id)) throw new Error("Cyclic durable worker ownership.");
|
|
2182
|
+
seen.add(current.id);
|
|
2183
|
+
const ownership = current.durableSubagent;
|
|
2184
|
+
if (ownership.status !== "active") throw new Error(`Durable worker "${current.id}" is ${ownership.status}.`);
|
|
2185
|
+
const parent = await Effect5.runPromise(this.data.getAgent(ownership.parentAgentId));
|
|
2186
|
+
if (!parent || parent.workspaceId !== current.workspaceId || !this.byRoute.get(parent.definitionId)?.definition.durableSubagents?.[ownership.name] || current.definitionId !== durableRoute(parent.definitionId, ownership.name)) throw new Error(`Durable worker "${current.id}" is detached from its definition or parent.`);
|
|
2187
|
+
current = parent;
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
async effectiveAgent(agent) {
|
|
2191
|
+
await this.assertDurableActive(agent);
|
|
2192
|
+
if (!agent.durableSubagent) return agent;
|
|
2193
|
+
const parent = await this.effectiveAgent(await Effect5.runPromise(this.data.getAgent(agent.durableSubagent.parentAgentId)));
|
|
2194
|
+
const definition = this.byRoute.get(agent.definitionId).definition;
|
|
2195
|
+
const selection = this.byRoute.get(parent.definitionId).definition.durableSubagents[agent.durableSubagent.name];
|
|
2196
|
+
const inheritedIds = new Set((selection.inherit?.apps ?? []).map((app) => typeof app === "string" ? app : app.id));
|
|
2197
|
+
return { ...agent, installations: [
|
|
2198
|
+
...agent.installations.filter((item) => item.kind !== "application" || !inheritedIds.has(item.id)),
|
|
2199
|
+
...inheritedInstallations(parent, definition, selection)
|
|
2200
|
+
] };
|
|
2201
|
+
}
|
|
2202
|
+
async ensureAgentEventConversation(agent) {
|
|
2203
|
+
const id2 = agentInboxId(agent.id);
|
|
2204
|
+
return this.inConversation(`agent-events:${id2}`, async () => {
|
|
2205
|
+
const existing = await Effect5.runPromise(this.data.getConversation(id2));
|
|
2206
|
+
if (existing) {
|
|
2207
|
+
if (existing.agentId !== agent.id || existing.workspaceId !== agent.workspaceId) throw new Error("Agent event conversation ownership conflict.");
|
|
2208
|
+
return existing;
|
|
2209
|
+
}
|
|
2210
|
+
return this.createConversation(agent.id, { id: id2, title: "Agent events" });
|
|
2211
|
+
});
|
|
2212
|
+
}
|
|
2213
|
+
/** A message to an owned worker, independent of any delegated task. */
|
|
2214
|
+
async messageSubagent(parentAgentId, name, message, options = {}) {
|
|
2215
|
+
return this.inConversation("durable:mutations", async () => {
|
|
2216
|
+
const child = await this.ensureSubagent(parentAgentId, name);
|
|
2217
|
+
return this.postAgentMessage(child, message, parentAgentId, options.id, options);
|
|
2218
|
+
});
|
|
2219
|
+
}
|
|
2220
|
+
async postAgentMessage(target, message, from, messageId = `message_${randomUUID2()}`, options = {}, replyTo) {
|
|
2221
|
+
options = messageOptionsSchema.parse(options);
|
|
2222
|
+
if (typeof message !== "string" || !message.trim()) throw new Error("Agent messages must not be empty.");
|
|
2223
|
+
const conversationId = options.conversationId ?? (await this.ensureAgentEventConversation(target)).id;
|
|
2224
|
+
return this.acceptEvent({ agentId: target.id, conversationId }, {
|
|
2225
|
+
id: options.id ?? messageId,
|
|
2226
|
+
source: `foundry:agent:${from}`,
|
|
2227
|
+
kind: "agent-message",
|
|
2228
|
+
content: message,
|
|
2229
|
+
...options.expiresAt ? { expiresAt: options.expiresAt } : {},
|
|
2230
|
+
metadata: { from, ...replyTo ? { replyTo } : {} }
|
|
2231
|
+
}, options);
|
|
2232
|
+
}
|
|
2233
|
+
/** Persist a spontaneous event before dispatching it to one exact runtime context. */
|
|
2234
|
+
async emitEvent(target, event, policy = {}) {
|
|
2235
|
+
return this.inConversation("durable:mutations", () => this.acceptEvent(target, event, policy));
|
|
2236
|
+
}
|
|
2237
|
+
async acceptEvent(target, event, policy) {
|
|
2238
|
+
foundryEventSchema.parse(event);
|
|
2239
|
+
eventPolicySchema.parse(policy);
|
|
2240
|
+
const agent = await Effect5.runPromise(this.data.getAgent(target.agentId));
|
|
2241
|
+
const conversation = await Effect5.runPromise(this.data.getConversation(target.conversationId));
|
|
2242
|
+
if (!agent || conversation?.agentId !== agent.id || conversation.workspaceId !== agent.workspaceId) throw new Error("Event target must name a conversation owned by the addressed agent.");
|
|
2243
|
+
await this.assertDurableActive(agent);
|
|
2244
|
+
const defaults = this.byRoute.get(agent.definitionId)?.definition.eventDelivery;
|
|
2245
|
+
const resolved = eventPolicySchema.parse({ ...defaults, ...event.whenIdle && event.whenIdle !== "auto" ? { whenIdle: event.whenIdle } : {}, ...policy });
|
|
2246
|
+
const id2 = eventRecordId(target, event.id);
|
|
2247
|
+
await this.deliver({ ...target, definitionId: agent.definitionId, workspaceId: agent.workspaceId }, [{
|
|
2248
|
+
kind: "agent-message",
|
|
2249
|
+
pendingId: id2,
|
|
2250
|
+
message: typeof event.content === "string" ? event.content : JSON.stringify(event.content),
|
|
2251
|
+
durable: { id: id2, event, policy: resolved }
|
|
2252
|
+
}]);
|
|
2253
|
+
const record = (await Effect5.runPromise(this.data.listEvents())).find((item) => item.id === id2);
|
|
2254
|
+
return { messageId: event.id, ...target, ...record?.runId ? { runId: record.runId } : {} };
|
|
2255
|
+
}
|
|
2256
|
+
async executeAgentMessage(command) {
|
|
2257
|
+
return this.inConversation("durable:mutations", async () => {
|
|
2258
|
+
const sender = await Effect5.runPromise(this.data.getAgent(command.agentId));
|
|
2259
|
+
const conversation = await Effect5.runPromise(this.data.getConversation(command.conversationId));
|
|
2260
|
+
if (!sender || sender.definitionId !== command.definitionId || sender.workspaceId !== command.workspaceId || conversation?.agentId !== sender.id) throw new Error("Invalid agent message sender.");
|
|
2261
|
+
await this.assertDurableActive(sender);
|
|
2262
|
+
const target = command.to === "parent" ? sender.durableSubagent && await Effect5.runPromise(this.data.getAgent(sender.durableSubagent.parentAgentId)) : await this.ensureSubagent(sender.id, command.to);
|
|
2263
|
+
if (!target || target.workspaceId !== sender.workspaceId) throw new Error("Agent message recipient is not an owned worker or parent.");
|
|
2264
|
+
return this.postAgentMessage(target, command.message, sender.id, command.id, command.delivery, { agentId: sender.id, conversationId: command.conversationId });
|
|
2265
|
+
});
|
|
2266
|
+
}
|
|
2267
|
+
/** Inspect owned records without provisioning or requiring the declaration to still exist. */
|
|
2268
|
+
async subagentData(parentAgentId, name) {
|
|
2269
|
+
const agent = (await this.listSubagents(parentAgentId)).find((item) => item.durableSubagent?.name === name);
|
|
2270
|
+
if (!agent) throw new Error(`Durable worker "${name}" was not found.`);
|
|
2271
|
+
const conversations = await Effect5.runPromise(this.data.listConversations(agent.id));
|
|
2272
|
+
return {
|
|
2273
|
+
agent,
|
|
2274
|
+
conversations,
|
|
2275
|
+
events: this.data.listEvents ? (await Effect5.runPromise(this.data.listEvents())).filter((item) => item.target.agentId === agent.id) : [],
|
|
2276
|
+
children: await this.listSubagents(agent.id),
|
|
2277
|
+
activations: (await Effect5.runPromise(this.data.listActivations(agent.workspaceId))).filter((item) => item.agentId === agent.id),
|
|
2278
|
+
pendingMessages: this.data.listPendingInbound ? (await Effect5.runPromise(this.data.listPendingInbound())).filter((item) => item.request.agentId === agent.id) : [],
|
|
2279
|
+
tasks: (await Effect5.runPromise(this.data.listTasks(agent.workspaceId))).filter((item) => item.agentId === agent.id),
|
|
2280
|
+
inbox: (await Effect5.runPromise(this.data.listInboxItems(agent.workspaceId))).filter((item) => item.agentId === agent.id)
|
|
2281
|
+
};
|
|
2282
|
+
}
|
|
2283
|
+
async archiveSubagent(parentAgentId, name) {
|
|
2284
|
+
return this.inConversation("durable:mutations", async () => {
|
|
2285
|
+
const { agent } = await this.subagentData(parentAgentId, name);
|
|
2286
|
+
const archive = async (current) => {
|
|
2287
|
+
if (current.durableSubagent.status === "purged") return current;
|
|
2288
|
+
const archived2 = { ...current, durableSubagent: { ...current.durableSubagent, status: "archived" }, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
2289
|
+
await Effect5.runPromise(this.data.putAgent(archived2));
|
|
2290
|
+
for (const child of await this.listSubagents(current.id)) await archive(child);
|
|
2291
|
+
await this.withActivationTransition(async () => {
|
|
2292
|
+
for (const activation of await Effect5.runPromise(this.data.listActivations(current.workspaceId))) {
|
|
2293
|
+
if (activation.agentId !== current.id || ["cancelled", "completed"].includes(activation.status)) continue;
|
|
2294
|
+
await this.disarmActivation(activation);
|
|
2295
|
+
await Effect5.runPromise(this.data.putActivation({ ...activation, status: "paused", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
2296
|
+
}
|
|
2297
|
+
});
|
|
2298
|
+
for (const conversation of await Effect5.runPromise(this.data.listConversations(current.id))) {
|
|
2299
|
+
this.heldDeliveries.delete(conversation.id);
|
|
2300
|
+
this.conversationListeners.delete(conversation.id);
|
|
2301
|
+
await drainMailbox(this.mailboxDirectory, conversation.id);
|
|
2302
|
+
}
|
|
2303
|
+
for (const run of await this.listRuns(current.definitionId)) {
|
|
2304
|
+
if (run.agentId === current.id && !["completed", "cancelled", "failed"].includes(run.status)) {
|
|
2305
|
+
await this.cancel(run.id);
|
|
2306
|
+
const settled = await this.waitForRun(run.id, { timeoutMs: 3e4 });
|
|
2307
|
+
if (settled && !["completed", "cancelled", "failed"].includes(settled.status)) throw new Error("Worker is still stopping; retry archival before purging.");
|
|
2308
|
+
if (settled) await this.waitForRunProcessRelease(settled, current.definitionId);
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
return archived2;
|
|
2312
|
+
};
|
|
2313
|
+
const archived = await archive(agent);
|
|
2314
|
+
if (this.started) await this.reconcileApplicationConnections();
|
|
2315
|
+
this.observability.append({ type: "agent.subagent.archived", category: "agent", agent: agent.definitionId, data: { agentId: agent.id } });
|
|
2316
|
+
return archived;
|
|
2317
|
+
});
|
|
2318
|
+
}
|
|
2319
|
+
async resumeSubagent(parentAgentId, name) {
|
|
2320
|
+
return this.inConversation("durable:mutations", async () => {
|
|
2321
|
+
const { agent } = await this.subagentData(parentAgentId, name);
|
|
2322
|
+
if (agent.durableSubagent.status === "purged") throw new Error("A purged worker cannot be resumed.");
|
|
2323
|
+
if (agent.durableSubagent.status === "active") return agent;
|
|
2324
|
+
const resumed = { ...agent, durableSubagent: { ...agent.durableSubagent, status: "active" }, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
2325
|
+
await this.assertDurableActive(resumed);
|
|
2326
|
+
await Effect5.runPromise(this.data.putAgent(resumed));
|
|
2327
|
+
for (const pending of this.data.listPendingInbound ? await Effect5.runPromise(this.data.listPendingInbound()) : []) {
|
|
2328
|
+
if (pending.request.agentId === agent.id) await this.admitInbound(pending);
|
|
2329
|
+
}
|
|
2330
|
+
await this.redeliverEvents(agent.id);
|
|
2331
|
+
return resumed;
|
|
2332
|
+
});
|
|
2333
|
+
}
|
|
2334
|
+
/** Purge requires archival and an explicit application cleanup hook. Shared data is never passed to it. */
|
|
2335
|
+
async purgeSubagent(parentAgentId, name) {
|
|
2336
|
+
return this.inConversation("durable:mutations", async () => {
|
|
2337
|
+
const { agent, conversations, children } = await this.subagentData(parentAgentId, name);
|
|
2338
|
+
if (agent.durableSubagent.status === "purged") return;
|
|
2339
|
+
if (agent.durableSubagent.status !== "archived") throw new Error("Archive the worker before purging it.");
|
|
2340
|
+
const running = (await this.listRuns(agent.definitionId)).some((run) => run.agentId === agent.id && !["completed", "failed", "cancelled"].includes(run.status));
|
|
2341
|
+
if (running) throw new Error("Wait for worker runs to stop before purging.");
|
|
2342
|
+
if (children.some((child) => child.durableSubagent?.status !== "purged")) throw new Error("Purge owned child workers first.");
|
|
2343
|
+
if (!this.data.purgeAgentData) throw new Error("The data adapter does not support purging agent data.");
|
|
2344
|
+
const parent = await Effect5.runPromise(this.data.getAgent(parentAgentId));
|
|
2345
|
+
const selection = parent && this.byRoute.get(parent.definitionId)?.definition.durableSubagents?.[name];
|
|
2346
|
+
if (!selection?.cleanup) throw new Error("Define an idempotent durable subagent cleanup hook to purge private external memory, transcripts, and files. Keep the declaration until cleanup completes.");
|
|
2347
|
+
await selection.cleanup({ agent, conversationIds: conversations.map((item) => item.id) });
|
|
2348
|
+
await Effect5.runPromise(this.data.purgeAgentData(agent.id));
|
|
2349
|
+
this.observability.append({ type: "agent.subagent.purged", category: "agent", agent: agent.definitionId, data: { agentId: agent.id } });
|
|
2350
|
+
});
|
|
2351
|
+
}
|
|
2060
2352
|
async createConversation(agentId, options = {}) {
|
|
2061
2353
|
const agent = await Effect5.runPromise(this.data.getAgent(agentId));
|
|
2062
2354
|
if (!agent) throw new Error(`Foundry agent instance "${agentId}" was not found.`);
|
|
@@ -2127,6 +2419,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2127
2419
|
async configureAgent(agentId, options) {
|
|
2128
2420
|
const current = await Effect5.runPromise(this.data.getAgent(agentId));
|
|
2129
2421
|
if (!current) throw new Error(`Foundry agent instance "${agentId}" was not found.`);
|
|
2422
|
+
await this.assertDurableActive(current);
|
|
2130
2423
|
const installations = options.installations ? normalizeAgentInstallations(options.installations) : current.installations;
|
|
2131
2424
|
for (const installation of installations) {
|
|
2132
2425
|
this.assertRegisteredInstallation(current.definitionId, installation);
|
|
@@ -2135,6 +2428,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2135
2428
|
this.validatePlaybooks(current.definitionId, playbooks, installations);
|
|
2136
2429
|
const agent = Object.freeze({
|
|
2137
2430
|
...current,
|
|
2431
|
+
...options.name !== void 0 ? { name: options.name } : {},
|
|
2432
|
+
...options.description !== void 0 ? { description: options.description } : {},
|
|
2138
2433
|
...options.context ? { context: Object.freeze(structuredClone(options.context)) } : {},
|
|
2139
2434
|
installations,
|
|
2140
2435
|
playbooks,
|
|
@@ -2321,7 +2616,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2321
2616
|
const run = await this.signalRunner.waitForRun(runId, options);
|
|
2322
2617
|
return run ? this.toFoundryRun(run) : null;
|
|
2323
2618
|
}
|
|
2324
|
-
cancel(runId) {
|
|
2619
|
+
async cancel(runId) {
|
|
2620
|
+
await this.cancelApprovalsOf(runId).catch((cause) => this.reportApprovalFailure(runId, cause));
|
|
2325
2621
|
return this.signalRunner.cancel(runId);
|
|
2326
2622
|
}
|
|
2327
2623
|
trackRunProcess(runId, state) {
|
|
@@ -2425,15 +2721,56 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2425
2721
|
});
|
|
2426
2722
|
return { fromRunId: runId, interrupted, run };
|
|
2427
2723
|
}
|
|
2428
|
-
listApprovals(filter = {}) {
|
|
2429
|
-
return listFoundryApprovals(this.approvalDirectory, filter);
|
|
2724
|
+
async listApprovals(filter = {}) {
|
|
2725
|
+
if (!this.approvalPolicy.durable) return listFoundryApprovals(this.approvalDirectory, filter);
|
|
2726
|
+
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));
|
|
2430
2727
|
}
|
|
2728
|
+
/** One approval: what a link to it opens. Null when there is no such approval. */
|
|
2729
|
+
async getApproval(approvalId) {
|
|
2730
|
+
if (!this.approvalPolicy.durable) {
|
|
2731
|
+
return (await listFoundryApprovals(this.approvalDirectory)).find((item) => item.id === approvalId) ?? null;
|
|
2732
|
+
}
|
|
2733
|
+
return (await this.withApprovals(() => this.currentApprovals())).find((item) => item.id === approvalId) ?? null;
|
|
2734
|
+
}
|
|
2735
|
+
/**
|
|
2736
|
+
* Decide an approval. When the run that asked is still waiting, it reads the
|
|
2737
|
+
* decision and carries on. When it is not (it suspended, timed out, or the
|
|
2738
|
+
* runtime restarted since), the decision goes to the conversation as a
|
|
2739
|
+
* durable event, and the run that takes it resumes the turn at the tool
|
|
2740
|
+
* call that asked: approved, the call runs; denied, it is refused.
|
|
2741
|
+
*/
|
|
2431
2742
|
async resolveApproval(approvalId, decision) {
|
|
2432
|
-
|
|
2433
|
-
this.approvalDirectory,
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2743
|
+
if (!this.approvalPolicy.durable) {
|
|
2744
|
+
const approval = await resolveFoundryApproval(this.approvalDirectory, approvalId, decision);
|
|
2745
|
+
this.reportResolved(approval, decision);
|
|
2746
|
+
return approval;
|
|
2747
|
+
}
|
|
2748
|
+
const { decided, live } = await this.withApprovals(async () => {
|
|
2749
|
+
const current = (await this.currentApprovals()).find((item) => item.id === approvalId);
|
|
2750
|
+
if (!current) throw new Error(`Foundry approval "${approvalId}" was not found.`);
|
|
2751
|
+
if (current.status !== "pending") throw new Error(`Foundry approval "${approvalId}" is already ${current.status}.`);
|
|
2752
|
+
let waiting = false;
|
|
2753
|
+
if (!current.suspendedAt && await foundryApprovalRequested(this.approvalDirectory, approvalId)) {
|
|
2754
|
+
await resolveFoundryApproval(this.approvalDirectory, approvalId, decision).catch(() => void 0);
|
|
2755
|
+
waiting = !this.settledRuns.has(current.runId) && !await foundryApprovalSuspended(this.approvalDirectory, approvalId);
|
|
2756
|
+
}
|
|
2757
|
+
const decided2 = {
|
|
2758
|
+
...current,
|
|
2759
|
+
status: decision === "approve" ? "approved" : "denied",
|
|
2760
|
+
resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2761
|
+
...waiting ? {} : { suspendedAt: current.suspendedAt ?? (/* @__PURE__ */ new Date()).toISOString() }
|
|
2762
|
+
};
|
|
2763
|
+
await Effect5.runPromise(this.data.putApproval(decided2));
|
|
2764
|
+
return { decided: decided2, live: waiting };
|
|
2765
|
+
});
|
|
2766
|
+
this.reportResolved(decided, decision);
|
|
2767
|
+
if (live) return decided;
|
|
2768
|
+
return this.resumeApproval(decided).catch((cause) => {
|
|
2769
|
+
this.reportApprovalFailure(decided.runId, cause);
|
|
2770
|
+
return decided;
|
|
2771
|
+
});
|
|
2772
|
+
}
|
|
2773
|
+
reportResolved(approval, decision) {
|
|
2437
2774
|
this.observability.append({
|
|
2438
2775
|
type: "approval.resolved",
|
|
2439
2776
|
category: "system",
|
|
@@ -2446,7 +2783,164 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2446
2783
|
status: approval.status
|
|
2447
2784
|
}
|
|
2448
2785
|
});
|
|
2449
|
-
|
|
2786
|
+
}
|
|
2787
|
+
withApprovals(work) {
|
|
2788
|
+
const next = this.approvalWrites.then(work, work);
|
|
2789
|
+
this.approvalWrites = next.catch(() => void 0);
|
|
2790
|
+
return next;
|
|
2791
|
+
}
|
|
2792
|
+
reportApprovalFailure(runId, cause) {
|
|
2793
|
+
this.observability.append({
|
|
2794
|
+
type: "approval.failed",
|
|
2795
|
+
category: "system",
|
|
2796
|
+
runId,
|
|
2797
|
+
data: { error: cause instanceof Error ? cause.message : String(cause) }
|
|
2798
|
+
});
|
|
2799
|
+
}
|
|
2800
|
+
/** Stored approvals, expired where their time ran out, plus requests not recorded yet. Call inside withApprovals. */
|
|
2801
|
+
async currentApprovals() {
|
|
2802
|
+
const now = Date.now();
|
|
2803
|
+
const byId = /* @__PURE__ */ new Map();
|
|
2804
|
+
for (const approval of await Effect5.runPromise(this.data.listApprovals())) {
|
|
2805
|
+
if (approval.status === "pending" && Date.parse(approval.expiresAt) <= now) {
|
|
2806
|
+
const expired = { ...approval, status: "expired", resolvedAt: new Date(now).toISOString() };
|
|
2807
|
+
await Effect5.runPromise(this.data.putApproval(expired));
|
|
2808
|
+
byId.set(expired.id, expired);
|
|
2809
|
+
} else {
|
|
2810
|
+
byId.set(approval.id, approval);
|
|
2811
|
+
}
|
|
2812
|
+
}
|
|
2813
|
+
for (const live of await listFoundryApprovals(this.approvalDirectory)) {
|
|
2814
|
+
if (!byId.has(live.id)) byId.set(live.id, this.withApprovalUrl(live));
|
|
2815
|
+
}
|
|
2816
|
+
return [...byId.values()];
|
|
2817
|
+
}
|
|
2818
|
+
withApprovalUrl(approval) {
|
|
2819
|
+
let url;
|
|
2820
|
+
try {
|
|
2821
|
+
url = this.application.approvals?.url?.(approval) || void 0;
|
|
2822
|
+
} catch {
|
|
2823
|
+
url = void 0;
|
|
2824
|
+
}
|
|
2825
|
+
return url ? { ...approval, url } : approval;
|
|
2826
|
+
}
|
|
2827
|
+
/** What a run reported about one of its approvals, kept in the data adapter. */
|
|
2828
|
+
async recordApprovalEvent(type, data2) {
|
|
2829
|
+
if (!this.approvalPolicy.durable || !data2 || typeof data2 !== "object") return;
|
|
2830
|
+
await this.withApprovals(async () => {
|
|
2831
|
+
if (type === "foundry.approval.requested") {
|
|
2832
|
+
const requested = data2;
|
|
2833
|
+
if (typeof requested.id !== "string" || await Effect5.runPromise(this.data.getApproval(requested.id))) return;
|
|
2834
|
+
await Effect5.runPromise(this.data.putApproval(this.withApprovalUrl({ ...requested, status: "pending" })));
|
|
2835
|
+
return;
|
|
2836
|
+
}
|
|
2837
|
+
const { approvalId, status } = data2;
|
|
2838
|
+
if (typeof approvalId !== "string") return;
|
|
2839
|
+
const stored = await Effect5.runPromise(this.data.getApproval(approvalId));
|
|
2840
|
+
if (!stored) return;
|
|
2841
|
+
if (type === "foundry.approval.suspended") {
|
|
2842
|
+
if (!stored.suspendedAt) await Effect5.runPromise(this.data.putApproval({ ...stored, suspendedAt: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
2843
|
+
return;
|
|
2844
|
+
}
|
|
2845
|
+
const settled = typeof status === "string" && ["approved", "denied", "expired", "cancelled"].includes(status) ? status : void 0;
|
|
2846
|
+
await Effect5.runPromise(this.data.putApproval({
|
|
2847
|
+
...stored,
|
|
2848
|
+
settledInRun: true,
|
|
2849
|
+
...stored.status === "pending" && settled ? { status: settled, resolvedAt: (/* @__PURE__ */ new Date()).toISOString() } : {}
|
|
2850
|
+
}));
|
|
2851
|
+
});
|
|
2852
|
+
}
|
|
2853
|
+
/**
|
|
2854
|
+
* A run ended. Its approvals still open no longer have anyone waiting:
|
|
2855
|
+
* they stay open, and a decision resumes the conversation. A decision the
|
|
2856
|
+
* run never read (it ended first) is handed over now.
|
|
2857
|
+
*/
|
|
2858
|
+
async settleApprovalsOf(runId) {
|
|
2859
|
+
if (!this.approvalPolicy.durable) return;
|
|
2860
|
+
const owed = await this.withApprovals(async () => {
|
|
2861
|
+
const owed2 = [];
|
|
2862
|
+
for (const approval of await Effect5.runPromise(this.data.listApprovals())) {
|
|
2863
|
+
if (approval.runId !== runId) continue;
|
|
2864
|
+
if (approval.status === "pending" && !approval.suspendedAt) {
|
|
2865
|
+
await markFoundryApprovalSuspended(this.approvalDirectory, approval.id).catch(() => false);
|
|
2866
|
+
await Effect5.runPromise(this.data.putApproval({ ...approval, suspendedAt: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
2867
|
+
} else if ((approval.status === "approved" || approval.status === "denied") && !approval.settledInRun && !approval.resumedAt) {
|
|
2868
|
+
owed2.push(approval);
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
return owed2;
|
|
2872
|
+
});
|
|
2873
|
+
for (const approval of owed) await this.resumeApproval(approval);
|
|
2874
|
+
}
|
|
2875
|
+
async cancelApprovalsOf(runId) {
|
|
2876
|
+
if (!this.approvalPolicy.durable) return;
|
|
2877
|
+
await this.withApprovals(async () => {
|
|
2878
|
+
for (const approval of await Effect5.runPromise(this.data.listApprovals())) {
|
|
2879
|
+
if (approval.runId !== runId || approval.status !== "pending") continue;
|
|
2880
|
+
if (await foundryApprovalRequested(this.approvalDirectory, approval.id) && !await readFoundryApprovalResolution(this.approvalDirectory, approval.id)) {
|
|
2881
|
+
await resolveFoundryApproval(this.approvalDirectory, approval.id, "deny").catch(() => void 0);
|
|
2882
|
+
}
|
|
2883
|
+
await Effect5.runPromise(this.data.putApproval({ ...approval, status: "cancelled", resolvedAt: (/* @__PURE__ */ new Date()).toISOString(), settledInRun: true }));
|
|
2884
|
+
}
|
|
2885
|
+
});
|
|
2886
|
+
}
|
|
2887
|
+
/** After a restart: open approvals have no run waiting, and decided ones may still be owed. */
|
|
2888
|
+
async reconcileApprovals() {
|
|
2889
|
+
if (!this.approvalPolicy.durable) return;
|
|
2890
|
+
const owed = await this.withApprovals(async () => {
|
|
2891
|
+
const owed2 = [];
|
|
2892
|
+
for (const approval of await this.currentApprovals()) {
|
|
2893
|
+
if (approval.status === "pending" && !approval.suspendedAt) {
|
|
2894
|
+
await Effect5.runPromise(this.data.putApproval({ ...approval, suspendedAt: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
2895
|
+
} else if ((approval.status === "approved" || approval.status === "denied") && !approval.settledInRun && !approval.resumedAt) {
|
|
2896
|
+
owed2.push(approval);
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
return owed2;
|
|
2900
|
+
});
|
|
2901
|
+
for (const approval of owed) await this.resumeApproval(approval).catch((cause) => this.reportApprovalFailure(approval.runId, cause));
|
|
2902
|
+
}
|
|
2903
|
+
/**
|
|
2904
|
+
* Hand a decision to the conversation that asked, as a durable event. The
|
|
2905
|
+
* run that takes it resumes the turn at the waiting tool call. If the
|
|
2906
|
+
* conversation moved on, the event tells the agent what was decided.
|
|
2907
|
+
*/
|
|
2908
|
+
async resumeApproval(approval) {
|
|
2909
|
+
const approved = approval.status === "approved";
|
|
2910
|
+
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.`;
|
|
2911
|
+
const receipt = await this.emitEvent(
|
|
2912
|
+
{ agentId: approval.agentId, conversationId: approval.conversationId },
|
|
2913
|
+
{
|
|
2914
|
+
id: `approval:${approval.id}`,
|
|
2915
|
+
source: "foundry:approval",
|
|
2916
|
+
kind: "approval.decided",
|
|
2917
|
+
content,
|
|
2918
|
+
metadata: {
|
|
2919
|
+
approval: {
|
|
2920
|
+
id: approval.id,
|
|
2921
|
+
toolName: approval.toolName,
|
|
2922
|
+
toolInput: approval.toolInput,
|
|
2923
|
+
status: approval.status,
|
|
2924
|
+
...approval.toolCallId ? { toolCallId: approval.toolCallId } : {}
|
|
2925
|
+
}
|
|
2926
|
+
}
|
|
2927
|
+
},
|
|
2928
|
+
{ whenIdle: "wake" }
|
|
2929
|
+
);
|
|
2930
|
+
const resumed = {
|
|
2931
|
+
...approval,
|
|
2932
|
+
resumedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2933
|
+
...receipt.runId ? { resumeRunId: receipt.runId } : {}
|
|
2934
|
+
};
|
|
2935
|
+
await this.withApprovals(() => Effect5.runPromise(this.data.putApproval(resumed)));
|
|
2936
|
+
this.observability.append({
|
|
2937
|
+
type: "approval.resumed",
|
|
2938
|
+
category: "system",
|
|
2939
|
+
agent: approval.definitionId,
|
|
2940
|
+
runId: receipt.runId ?? approval.runId,
|
|
2941
|
+
data: { approvalId: approval.id, toolName: approval.toolName, status: approval.status }
|
|
2942
|
+
});
|
|
2943
|
+
return resumed;
|
|
2450
2944
|
}
|
|
2451
2945
|
capabilityManifest(definitionId) {
|
|
2452
2946
|
if (!this.compositionByDefinition.has(definitionId)) {
|
|
@@ -2505,6 +2999,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2505
2999
|
if (!agent) {
|
|
2506
3000
|
throw new Error(`Foundry agent instance "${agentId}" was not found.`);
|
|
2507
3001
|
}
|
|
3002
|
+
await this.assertDurableActive(agent);
|
|
2508
3003
|
this.assertRegisteredInstallation(agent.definitionId, installation);
|
|
2509
3004
|
const installations = normalizeAgentInstallations([
|
|
2510
3005
|
...agent.installations,
|
|
@@ -2656,12 +3151,19 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2656
3151
|
const runs = [];
|
|
2657
3152
|
const deliveries = [];
|
|
2658
3153
|
const matchedByAgent = /* @__PURE__ */ new Map();
|
|
2659
|
-
for (const
|
|
3154
|
+
for (const stored of instances) {
|
|
3155
|
+
let agent;
|
|
3156
|
+
try {
|
|
3157
|
+
agent = await this.effectiveAgent(stored);
|
|
3158
|
+
} catch {
|
|
3159
|
+
if (stored.durableSubagent) continue;
|
|
3160
|
+
throw new Error(`Cannot resolve agent "${stored.id}".`);
|
|
3161
|
+
}
|
|
2660
3162
|
const installedApplications = new Set(
|
|
2661
3163
|
agent.installations.filter((installation) => installation.kind === "application").map((installation) => installation.id)
|
|
2662
3164
|
);
|
|
2663
3165
|
const hasInstalledOwner = (this.compositionByDefinition.get(agent.definitionId)?.capabilities.applications ?? []).some(
|
|
2664
|
-
(application) => installedApplications.has(application.id) && application.transmissions?.some(
|
|
3166
|
+
(application) => installedApplications.has(application.id) && (!application.restrictions || application.restrictions.transmissions?.includes(integration.id)) && application.transmissions?.some(
|
|
2665
3167
|
(candidate) => candidate.id === integration.id && candidate.inbound
|
|
2666
3168
|
)
|
|
2667
3169
|
);
|
|
@@ -2812,7 +3314,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2812
3314
|
`Outbound route "${route.id}" does not belong to transmission "${input.transmissionId}".`
|
|
2813
3315
|
);
|
|
2814
3316
|
}
|
|
2815
|
-
const
|
|
3317
|
+
const storedAgent = await Effect5.runPromise(this.data.getAgent(input.agentId));
|
|
3318
|
+
const agent = storedAgent ? await this.effectiveAgent(storedAgent) : null;
|
|
2816
3319
|
if (!agent) {
|
|
2817
3320
|
throw new Error(`Agent instance "${input.agentId}" does not exist.`);
|
|
2818
3321
|
}
|
|
@@ -2830,6 +3333,9 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2830
3333
|
);
|
|
2831
3334
|
}
|
|
2832
3335
|
}
|
|
3336
|
+
const owners = this.compositionByDefinition.get(agent.definitionId)?.capabilities.applications.filter((app) => (!input.applicationId || app.id === input.applicationId) && agent.installations.some((item) => item.kind === "application" && item.id === app.id) && app.transmissions?.some((transmission2) => transmission2.id === route.transmissionId)) ?? [];
|
|
3337
|
+
if (owners.length && !owners.some((app) => !app.restrictions || app.restrictions.transmissions?.includes(route.transmissionId))) throw new Error("Application restrictions deny this outbound transmission.");
|
|
3338
|
+
if (agent.durableSubagent && !owners.length) throw new Error("Durable workers require an installed application for outbound transmissions.");
|
|
2833
3339
|
const grant = await this.resolveGrant({
|
|
2834
3340
|
runId: input.runId,
|
|
2835
3341
|
agentId: input.agentId
|
|
@@ -2853,7 +3359,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2853
3359
|
grant,
|
|
2854
3360
|
signal: input.signal ?? new AbortController().signal,
|
|
2855
3361
|
...account && accountSessions ? {
|
|
2856
|
-
withAccountSession: (operation, use) => accountSessions.withSession({
|
|
3362
|
+
withAccountSession: (operation, use) => owners.length && !owners.some((app) => !app.restrictions || app.restrictions.transmissions?.includes(route.transmissionId) && app.restrictions.operations?.includes(operation)) ? Effect5.fail(new Error(`Application restrictions deny account operation "${operation}".`)) : accountSessions.withSession({
|
|
2857
3363
|
accountId: account.id,
|
|
2858
3364
|
operation,
|
|
2859
3365
|
agentId: agent.id,
|
|
@@ -3054,7 +3560,14 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3054
3560
|
});
|
|
3055
3561
|
}
|
|
3056
3562
|
}
|
|
3057
|
-
for (const
|
|
3563
|
+
for (const stored of await this.listAgentInstances()) {
|
|
3564
|
+
let agent;
|
|
3565
|
+
try {
|
|
3566
|
+
agent = await this.effectiveAgent(stored);
|
|
3567
|
+
} catch {
|
|
3568
|
+
if (stored.durableSubagent) continue;
|
|
3569
|
+
throw new Error(`Cannot resolve agent "${stored.id}".`);
|
|
3570
|
+
}
|
|
3058
3571
|
const installedApplications = new Set(
|
|
3059
3572
|
agent.installations.filter((installation) => installation.kind === "application").map((installation) => installation.id)
|
|
3060
3573
|
);
|
|
@@ -3076,6 +3589,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3076
3589
|
const composition = this.compositionByDefinition.get(requirement.definitionId);
|
|
3077
3590
|
if (!composition) continue;
|
|
3078
3591
|
for (const application of composition.capabilities.applications) {
|
|
3592
|
+
if (application.restrictions && !application.restrictions.transmissions?.includes(requirement.playbook.transmissionId)) continue;
|
|
3079
3593
|
if (requirement.installedApplications && !requirement.installedApplications.has(application.id)) continue;
|
|
3080
3594
|
if (!application.transmissions?.some(
|
|
3081
3595
|
(transmission) => transmission.id === requirement.playbook.transmissionId
|
|
@@ -3088,7 +3602,9 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3088
3602
|
(route) => route.transmissionId === requirement.playbook.transmissionId && (!requirement.playbook.match?.routeIds || requirement.playbook.match.routeIds.includes(route.id))
|
|
3089
3603
|
);
|
|
3090
3604
|
for (const route of matchingRoutes) {
|
|
3091
|
-
const account = route.accountId ? this.
|
|
3605
|
+
const account = route.accountId ? await this.services.runPromise(Effect5.gen(function* () {
|
|
3606
|
+
return yield* (yield* AccountDirectory).get(route.accountId);
|
|
3607
|
+
})).catch(() => void 0) : void 0;
|
|
3092
3608
|
const id2 = [
|
|
3093
3609
|
requirement.definitionId,
|
|
3094
3610
|
requirement.workspaceId,
|
|
@@ -3155,7 +3671,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3155
3671
|
(candidate) => candidate.id === playbook.transmissionId && candidate.inbound
|
|
3156
3672
|
)
|
|
3157
3673
|
);
|
|
3158
|
-
if (!inboundOwners.some((application) => installedApplications.has(application.id))) {
|
|
3674
|
+
if (!inboundOwners.some((application) => installedApplications.has(application.id) && (!application.restrictions || application.restrictions.transmissions?.includes(playbook.transmissionId)))) {
|
|
3159
3675
|
throw new Error(
|
|
3160
3676
|
`Playbook "${playbook.id}" requires an installed application that owns inbound transmission "${playbook.transmissionId}".`
|
|
3161
3677
|
);
|
|
@@ -3375,18 +3891,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3375
3891
|
return found.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
3376
3892
|
}
|
|
3377
3893
|
async openDelegationsFrom(agentId, conversationId) {
|
|
3378
|
-
|
|
3379
|
-
for (const route of this.byRoute.keys()) {
|
|
3380
|
-
const workerId = workerAgentId(agentId, route);
|
|
3381
|
-
if (!await Effect5.runPromise(this.data.getAgent(workerId))) continue;
|
|
3382
|
-
for (const conversation of await Effect5.runPromise(this.data.listConversations(workerId))) {
|
|
3383
|
-
const delegation = delegationFromContext(conversation.context);
|
|
3384
|
-
if (delegation && delegation.from.conversationId === conversationId && isOpenDelegation(delegation)) {
|
|
3385
|
-
open.push(delegation);
|
|
3386
|
-
}
|
|
3387
|
-
}
|
|
3388
|
-
}
|
|
3389
|
-
return open.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
3894
|
+
return (await this.listDelegations({ agentId, conversationId })).filter(isOpenDelegation).sort((left, right) => left.createdAt.localeCompare(right.createdAt));
|
|
3390
3895
|
}
|
|
3391
3896
|
/** Run work for one conversation after the work already queued for it. */
|
|
3392
3897
|
inConversation(conversationId, work) {
|
|
@@ -3452,13 +3957,14 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3452
3957
|
}
|
|
3453
3958
|
/** Take back deliveries a listener did not read, to deliver as a run. */
|
|
3454
3959
|
async reclaimMailbox(conversationId) {
|
|
3455
|
-
const deliveries = await drainMailbox(this.mailboxDirectory, conversationId);
|
|
3960
|
+
const deliveries = (await drainMailbox(this.mailboxDirectory, conversationId)).filter((delivery) => !(delivery.kind === "mesh" && delivery.message.kind === "ack"));
|
|
3456
3961
|
if (deliveries.length === 0) return;
|
|
3457
3962
|
const target = await this.deliveryTargetFor(conversationId);
|
|
3458
3963
|
if (!target) return;
|
|
3459
3964
|
for (const delivery of deliveries) {
|
|
3460
|
-
if (delivery.kind === "transmission") await this.assignPendingInbound(delivery.pendingId, void 0);
|
|
3965
|
+
if (delivery.kind === "transmission" || delivery.kind === "agent-message") await this.assignPendingInbound(delivery.pendingId, void 0);
|
|
3461
3966
|
}
|
|
3967
|
+
await this.markHandedOver(deliveries, void 0);
|
|
3462
3968
|
this.holdDeliveries(target, deliveries);
|
|
3463
3969
|
}
|
|
3464
3970
|
async deliveryTargetFor(conversationId) {
|
|
@@ -3475,11 +3981,56 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3475
3981
|
}
|
|
3476
3982
|
holdDeliveries(target, deliveries) {
|
|
3477
3983
|
const held = this.heldDeliveries.get(target.conversationId);
|
|
3478
|
-
if (held) held.deliveries.push(...deliveries);
|
|
3984
|
+
if (held) held.deliveries.push(...deliveries.filter((delivery) => !delivery.durable || !held.deliveries.some((item) => item.durable?.id === delivery.durable.id)));
|
|
3479
3985
|
else this.heldDeliveries.set(target.conversationId, { target, deliveries: [...deliveries] });
|
|
3480
3986
|
}
|
|
3481
|
-
deliver(target, deliveries) {
|
|
3987
|
+
deliver(target, deliveries, replay = false) {
|
|
3482
3988
|
return this.inConversation(target.conversationId, async () => {
|
|
3989
|
+
if (!this.data.claimEvent || !this.data.putEvent || !this.data.listEvents) throw new Error("Durable event delivery requires claimEvent, putEvent, and listEvents on the data adapter.");
|
|
3990
|
+
const accepted = [];
|
|
3991
|
+
for (const delivery of deliveries) {
|
|
3992
|
+
const event = JSON.parse(JSON.stringify(delivery.durable?.event ?? deliveryEvent(delivery)));
|
|
3993
|
+
const id2 = eventRecordId(target, event.id);
|
|
3994
|
+
const policy = JSON.parse(JSON.stringify(delivery.durable?.policy ?? this.byRoute.get(target.definitionId)?.definition.eventDelivery ?? {}));
|
|
3995
|
+
const { durable: _transport, ...body } = delivery;
|
|
3996
|
+
const record = {
|
|
3997
|
+
id: id2,
|
|
3998
|
+
target: { agentId: target.agentId, conversationId: target.conversationId },
|
|
3999
|
+
definitionId: target.definitionId,
|
|
4000
|
+
workspaceId: target.workspaceId,
|
|
4001
|
+
event,
|
|
4002
|
+
policy,
|
|
4003
|
+
delivery: body,
|
|
4004
|
+
status: "pending",
|
|
4005
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4006
|
+
};
|
|
4007
|
+
const fresh = await Effect5.runPromise(this.data.claimEvent(record));
|
|
4008
|
+
const existing = fresh ? record : (await Effect5.runPromise(this.data.listEvents())).find((item) => item.id === id2);
|
|
4009
|
+
if (!fresh && !replay && delivery.durable && (!isDeepStrictEqual(existing.event, event) || !isDeepStrictEqual(existing.policy, policy))) {
|
|
4010
|
+
throw new Error(`Event id "${event.id}" already belongs to a different event or delivery policy at this target.`);
|
|
4011
|
+
}
|
|
4012
|
+
await this.markLegacyHandedOver([body], void 0);
|
|
4013
|
+
if (existing.status !== "pending") {
|
|
4014
|
+
if ((body.kind === "agent-message" || body.kind === "transmission") && this.data.deletePendingInbound) await Effect5.runPromise(this.data.deletePendingInbound(body.pendingId));
|
|
4015
|
+
continue;
|
|
4016
|
+
}
|
|
4017
|
+
if (!fresh && !replay) continue;
|
|
4018
|
+
if (existing.event.expiresAt && Date.parse(existing.event.expiresAt) <= Date.now()) {
|
|
4019
|
+
await Effect5.runPromise(this.data.putEvent({ ...existing, status: "expired", runId: void 0 }));
|
|
4020
|
+
continue;
|
|
4021
|
+
}
|
|
4022
|
+
accepted.push({ ...existing.delivery, durable: { id: id2, event: existing.event, policy: existing.policy } });
|
|
4023
|
+
}
|
|
4024
|
+
deliveries = accepted;
|
|
4025
|
+
if (!deliveries.length) return;
|
|
4026
|
+
const recipient = await Effect5.runPromise(this.data.getAgent(target.agentId));
|
|
4027
|
+
if (recipient?.durableSubagent) {
|
|
4028
|
+
try {
|
|
4029
|
+
await this.assertDurableActive(recipient);
|
|
4030
|
+
} catch {
|
|
4031
|
+
return;
|
|
4032
|
+
}
|
|
4033
|
+
}
|
|
3483
4034
|
if (this.conversationListeners.has(target.conversationId)) {
|
|
3484
4035
|
for (const delivery of deliveries) {
|
|
3485
4036
|
await writeMailboxDelivery(this.mailboxDirectory, target.conversationId, delivery);
|
|
@@ -3500,21 +4051,58 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3500
4051
|
}
|
|
3501
4052
|
/** Start one run with everything held for a conversation, once nothing else holds it. */
|
|
3502
4053
|
async flushHeldDeliveries(conversationId) {
|
|
3503
|
-
if (!this.started) return;
|
|
4054
|
+
if (!this.started || this.stopping) return;
|
|
3504
4055
|
if (this.gate.busy(conversationId)) return;
|
|
3505
4056
|
if (this.conversationListeners.has(conversationId)) return;
|
|
3506
4057
|
const held = this.heldDeliveries.get(conversationId);
|
|
3507
4058
|
if (!held || held.deliveries.length === 0) return;
|
|
4059
|
+
const records = this.data.listEvents ? await Effect5.runPromise(this.data.listEvents()) : [];
|
|
4060
|
+
const pending = records.filter((record) => held.deliveries.some((delivery) => delivery.durable?.id === record.id) && record.status === "pending");
|
|
4061
|
+
const now = Date.now();
|
|
4062
|
+
for (const record of pending) {
|
|
4063
|
+
if (record.event.expiresAt && Date.parse(record.event.expiresAt) <= now) await Effect5.runPromise(this.data.putEvent({ ...record, status: "expired", runId: void 0 }));
|
|
4064
|
+
}
|
|
4065
|
+
const live = pending.filter((record) => !record.event.expiresAt || Date.parse(record.event.expiresAt) > now);
|
|
4066
|
+
held.deliveries = held.deliveries.filter((delivery) => live.some((record) => record.id === delivery.durable?.id));
|
|
4067
|
+
if (!held.deliveries.length) {
|
|
4068
|
+
this.heldDeliveries.delete(conversationId);
|
|
4069
|
+
return;
|
|
4070
|
+
}
|
|
4071
|
+
if (!live.some((record) => eventDue(record, now))) {
|
|
4072
|
+
const deadlines = live.flatMap((record) => [
|
|
4073
|
+
...record.policy.deferTimeoutMs !== void 0 ? [Date.parse(record.createdAt) + record.policy.deferTimeoutMs] : [],
|
|
4074
|
+
...record.event.expiresAt ? [Date.parse(record.event.expiresAt)] : []
|
|
4075
|
+
]);
|
|
4076
|
+
const previous = this.eventTimers.get(conversationId);
|
|
4077
|
+
if (previous) clearTimeout(previous);
|
|
4078
|
+
if (deadlines.length) {
|
|
4079
|
+
const timer = setTimeout(() => {
|
|
4080
|
+
this.eventTimers.delete(conversationId);
|
|
4081
|
+
void this.inConversation(conversationId, () => this.flushHeldDeliveries(conversationId)).catch((cause) => this.reportDeliveryFailure(conversationId, cause));
|
|
4082
|
+
}, Math.max(1, Math.min(2147483647, Math.min(...deadlines) - now)));
|
|
4083
|
+
timer.unref();
|
|
4084
|
+
this.eventTimers.set(conversationId, timer);
|
|
4085
|
+
}
|
|
4086
|
+
return;
|
|
4087
|
+
}
|
|
3508
4088
|
this.heldDeliveries.delete(conversationId);
|
|
3509
4089
|
const { target, deliveries } = held;
|
|
4090
|
+
const owner = await Effect5.runPromise(this.data.getAgent(target.agentId));
|
|
4091
|
+
if (owner?.durableSubagent) {
|
|
4092
|
+
try {
|
|
4093
|
+
await this.assertDurableActive(owner);
|
|
4094
|
+
} catch {
|
|
4095
|
+
return;
|
|
4096
|
+
}
|
|
4097
|
+
}
|
|
3510
4098
|
const runId = await this.enqueueCoreRequest(target.definitionId, {
|
|
3511
4099
|
agentId: target.agentId,
|
|
3512
4100
|
conversationId,
|
|
3513
4101
|
workspaceId: target.workspaceId,
|
|
4102
|
+
...deliveries.length === 1 ? deliveries[0].request : {},
|
|
3514
4103
|
message: renderDeliveries(deliveries),
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
});
|
|
4104
|
+
source: deliveries.length === 1 && deliveries[0].request?.source ? deliveries[0].request.source : deliverySource(deliveries)
|
|
4105
|
+
}, { eventTurn: true });
|
|
3518
4106
|
this.occupyConversation(conversationId, runId);
|
|
3519
4107
|
await this.markHandedOver(deliveries, runId);
|
|
3520
4108
|
this.observability.append({
|
|
@@ -3525,20 +4113,77 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3525
4113
|
data: { conversationId, mode: "run", count: deliveries.length }
|
|
3526
4114
|
});
|
|
3527
4115
|
}
|
|
3528
|
-
/** Clear the bookkeeping that lets a restart hand these deliveries over again. */
|
|
3529
4116
|
async markHandedOver(deliveries, runId) {
|
|
4117
|
+
if (!this.data.listEvents || !this.data.putEvent) return;
|
|
4118
|
+
const ids = new Set(deliveries.flatMap((delivery) => delivery.durable ? [delivery.durable.id] : []));
|
|
4119
|
+
for (const record of await Effect5.runPromise(this.data.listEvents())) {
|
|
4120
|
+
if (!ids.has(record.id) || record.status !== "pending") continue;
|
|
4121
|
+
const acknowledged = runId && this.completedEventRuns.get(runId)?.has(record.id);
|
|
4122
|
+
await Effect5.runPromise(this.data.putEvent({ ...record, runId, ...acknowledged ? { status: "acknowledged" } : {} }));
|
|
4123
|
+
}
|
|
4124
|
+
}
|
|
4125
|
+
async finishEvents(runId, consumed) {
|
|
4126
|
+
if (!this.data.listEvents || !this.data.putEvent || this.stopping) return;
|
|
4127
|
+
const run = await this.getRun(runId);
|
|
4128
|
+
const ids = new Set(consumed);
|
|
4129
|
+
this.completedEventRuns.set(runId, ids);
|
|
4130
|
+
if (this.completedEventRuns.size > 1e3) this.completedEventRuns.delete(this.completedEventRuns.keys().next().value);
|
|
4131
|
+
for (const record of await Effect5.runPromise(this.data.listEvents())) {
|
|
4132
|
+
if (record.status !== "pending" || !ids.has(record.id) || record.target.agentId !== run?.agentId || record.target.conversationId !== run?.conversationId) continue;
|
|
4133
|
+
const owner = await Effect5.runPromise(this.data.getAgent(record.target.agentId));
|
|
4134
|
+
if (!owner) continue;
|
|
4135
|
+
try {
|
|
4136
|
+
await this.assertDurableActive(owner);
|
|
4137
|
+
} catch {
|
|
4138
|
+
continue;
|
|
4139
|
+
}
|
|
4140
|
+
await Effect5.runPromise(this.data.putEvent({ ...record, status: record.event.expiresAt && Date.parse(record.event.expiresAt) <= Date.now() ? "expired" : "acknowledged", runId }));
|
|
4141
|
+
if ((record.delivery.kind === "transmission" || record.delivery.kind === "agent-message") && this.data.deletePendingInbound) {
|
|
4142
|
+
await Effect5.runPromise(this.data.deletePendingInbound(record.delivery.pendingId));
|
|
4143
|
+
}
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
async redeliverEvents(agentId) {
|
|
4147
|
+
if (!this.data.listEvents) return;
|
|
4148
|
+
for (const record of await Effect5.runPromise(this.data.listEvents())) {
|
|
4149
|
+
if (record.status !== "pending" || agentId && record.target.agentId !== agentId) continue;
|
|
4150
|
+
if (record.runId) {
|
|
4151
|
+
const run = await this.getRun(record.runId);
|
|
4152
|
+
if (run && !["completed", "failed", "cancelled"].includes(run.status)) continue;
|
|
4153
|
+
if (run?.status === "completed" && run.output?.consumedEventIds?.includes(record.id)) {
|
|
4154
|
+
await this.finishEvents(run.id, [record.id]);
|
|
4155
|
+
continue;
|
|
4156
|
+
}
|
|
4157
|
+
}
|
|
4158
|
+
const owner = await Effect5.runPromise(this.data.getAgent(record.target.agentId));
|
|
4159
|
+
if (!owner) continue;
|
|
4160
|
+
try {
|
|
4161
|
+
await this.assertDurableActive(owner);
|
|
4162
|
+
} catch {
|
|
4163
|
+
continue;
|
|
4164
|
+
}
|
|
4165
|
+
await this.deliver({ ...record.target, definitionId: record.definitionId, workspaceId: record.workspaceId }, [{ ...record.delivery, durable: { id: record.id, event: record.event, policy: record.policy } }], true);
|
|
4166
|
+
}
|
|
4167
|
+
}
|
|
4168
|
+
/** Clear the bookkeeping that lets a restart hand these deliveries over again. */
|
|
4169
|
+
async markLegacyHandedOver(deliveries, runId) {
|
|
3530
4170
|
for (const delivery of deliveries) {
|
|
3531
|
-
if (delivery.kind === "
|
|
4171
|
+
if (delivery.kind === "mesh") continue;
|
|
4172
|
+
if (delivery.kind === "transmission" || delivery.kind === "agent-message") {
|
|
3532
4173
|
await this.assignPendingInbound(delivery.pendingId, runId);
|
|
3533
4174
|
} else if (delivery.kind === "reply") {
|
|
3534
4175
|
await this.updateDelegation(delivery.delegationId, (current) => {
|
|
3535
4176
|
const pending = [...current.pendingReplies ?? []];
|
|
3536
|
-
const
|
|
3537
|
-
|
|
3538
|
-
|
|
4177
|
+
const pendingIds = [...current.pendingReplyIds ?? []];
|
|
4178
|
+
const index = delivery.deliveryId ? pendingIds.indexOf(delivery.deliveryId) : pending.indexOf(delivery.message);
|
|
4179
|
+
if (index >= 0) {
|
|
4180
|
+
pending.splice(index, 1);
|
|
4181
|
+
pendingIds.splice(index, 1);
|
|
4182
|
+
}
|
|
4183
|
+
return { pendingReplies: pending.length > 0 ? pending : void 0, pendingReplyIds: pendingIds.length ? pendingIds : void 0 };
|
|
3539
4184
|
});
|
|
3540
4185
|
} else {
|
|
3541
|
-
await this.updateDelegation(delivery.delegationId, (current) => current.undelivered === delivery.kind ? { undelivered: void 0 } : {});
|
|
4186
|
+
await this.updateDelegation(delivery.delegationId, (current) => current.undelivered === delivery.kind && (!delivery.deliveryId || current.updateId === delivery.deliveryId) ? { undelivered: void 0 } : {});
|
|
3542
4187
|
}
|
|
3543
4188
|
}
|
|
3544
4189
|
}
|
|
@@ -3565,6 +4210,17 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3565
4210
|
if (!ids) return;
|
|
3566
4211
|
this.pendingInboundByRun.delete(runId);
|
|
3567
4212
|
if (this.stopping || !this.data.deletePendingInbound) return;
|
|
4213
|
+
const pending = this.data.listPendingInbound ? await Effect5.runPromise(this.data.listPendingInbound()) : [];
|
|
4214
|
+
for (const record of pending.filter((item) => ids.has(item.id))) {
|
|
4215
|
+
const agent = await Effect5.runPromise(this.data.getAgent(record.request.agentId));
|
|
4216
|
+
if (agent?.durableSubagent) {
|
|
4217
|
+
try {
|
|
4218
|
+
await this.assertDurableActive(agent);
|
|
4219
|
+
} catch {
|
|
4220
|
+
return;
|
|
4221
|
+
}
|
|
4222
|
+
}
|
|
4223
|
+
}
|
|
3568
4224
|
for (const id2 of ids) await Effect5.runPromise(this.data.deletePendingInbound(id2));
|
|
3569
4225
|
}
|
|
3570
4226
|
/**
|
|
@@ -3577,35 +4233,38 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3577
4233
|
async admitInbound(record) {
|
|
3578
4234
|
if (this.data.putPendingInbound) await Effect5.runPromise(this.data.putPendingInbound(record));
|
|
3579
4235
|
const { request } = record;
|
|
3580
|
-
if (!this.gate.busy(request.conversationId)) {
|
|
3581
|
-
const run = await this.request(record.definitionId, request);
|
|
3582
|
-
await this.assignPendingInbound(record.id, run.id);
|
|
3583
|
-
return run;
|
|
3584
|
-
}
|
|
3585
4236
|
const source = request.source;
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
|
|
3597
|
-
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
);
|
|
3601
|
-
const
|
|
3602
|
-
return
|
|
4237
|
+
let delivery = {
|
|
4238
|
+
kind: source?.kind === "agent-message" ? "agent-message" : "transmission",
|
|
4239
|
+
request,
|
|
4240
|
+
pendingId: record.id,
|
|
4241
|
+
routeId: source?.id ?? "",
|
|
4242
|
+
eventId: source?.eventId ?? "",
|
|
4243
|
+
message: typeof request.message === "string" ? request.message : JSON.stringify(request.message)
|
|
4244
|
+
};
|
|
4245
|
+
if (source?.kind === "delegation") {
|
|
4246
|
+
const event2 = { id: record.id, source: "foundry:delegation", kind: "delegation.task", content: typeof request.message === "string" ? request.message : JSON.stringify(request.message) };
|
|
4247
|
+
delivery = { ...delivery, durable: { id: eventRecordId(request, event2.id), event: event2, policy: this.byRoute.get(record.definitionId)?.definition.eventDelivery ?? {} } };
|
|
4248
|
+
}
|
|
4249
|
+
await this.deliver({ definitionId: record.definitionId, agentId: request.agentId, conversationId: request.conversationId, workspaceId: request.workspaceId }, [delivery]);
|
|
4250
|
+
const event = deliveryEvent(delivery);
|
|
4251
|
+
const journal = this.data.listEvents && (await Effect5.runPromise(this.data.listEvents())).find((item) => item.id === eventRecordId(request, event.id));
|
|
4252
|
+
const handlingRunId = journal?.runId ?? this.gate.activeRun(request.conversationId);
|
|
4253
|
+
return handlingRunId ? this.getRun(handlingRunId) : null;
|
|
3603
4254
|
}
|
|
3604
4255
|
/** After a restart, deliver the inbound events no run had finished with. */
|
|
3605
4256
|
async redeliverInbound() {
|
|
3606
4257
|
if (!this.data.listPendingInbound) return;
|
|
3607
4258
|
const pending = [...await Effect5.runPromise(this.data.listPendingInbound())].sort((left, right) => left.createdAt.localeCompare(right.createdAt));
|
|
3608
4259
|
for (const record of pending) {
|
|
4260
|
+
const owner = await Effect5.runPromise(this.data.getAgent(record.request.agentId));
|
|
4261
|
+
if (owner?.durableSubagent) {
|
|
4262
|
+
try {
|
|
4263
|
+
await this.assertDurableActive(owner);
|
|
4264
|
+
} catch {
|
|
4265
|
+
continue;
|
|
4266
|
+
}
|
|
4267
|
+
}
|
|
3609
4268
|
const { runId: _lost, ...waiting } = record;
|
|
3610
4269
|
await this.admitInbound(waiting);
|
|
3611
4270
|
}
|
|
@@ -3613,6 +4272,31 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3613
4272
|
/** After a restart, hand over whatever was waiting when the runtime stopped. */
|
|
3614
4273
|
async redeliverDelegations() {
|
|
3615
4274
|
for (const delegation of await this.listDelegations()) {
|
|
4275
|
+
const worker = await Effect5.runPromise(this.data.getAgent(delegation.workerAgentId));
|
|
4276
|
+
if (worker && delegation.status === "working" && !delegation.pendingReplies?.length && this.data.listPendingInbound) {
|
|
4277
|
+
let active = true;
|
|
4278
|
+
try {
|
|
4279
|
+
await this.assertDurableActive(worker);
|
|
4280
|
+
} catch {
|
|
4281
|
+
active = false;
|
|
4282
|
+
}
|
|
4283
|
+
const pending = await Effect5.runPromise(this.data.listPendingInbound());
|
|
4284
|
+
if (active && !(this.data.listEvents && (await Effect5.runPromise(this.data.listEvents())).some((item) => item.target.conversationId === delegation.id)) && !pending.some((item) => item.request.conversationId === delegation.id) && (await this.loadDelegation(delegation.id))?.status === "working") {
|
|
4285
|
+
await this.admitInbound({
|
|
4286
|
+
id: `task:${delegation.id}`,
|
|
4287
|
+
definitionId: worker.definitionId,
|
|
4288
|
+
createdAt: delegation.createdAt,
|
|
4289
|
+
request: {
|
|
4290
|
+
agentId: worker.id,
|
|
4291
|
+
conversationId: delegation.id,
|
|
4292
|
+
workspaceId: worker.workspaceId,
|
|
4293
|
+
message: renderDelegatedTask({ delegationId: delegation.id, from: delegation.from.definitionId, task: delegation.task }),
|
|
4294
|
+
payload: { delegation },
|
|
4295
|
+
source: { kind: "delegation", id: delegation.id }
|
|
4296
|
+
}
|
|
4297
|
+
});
|
|
4298
|
+
}
|
|
4299
|
+
}
|
|
3616
4300
|
const update = undeliveredUpdate(delegation);
|
|
3617
4301
|
if (update) await this.deliver(this.delegatorTarget(delegation), [update]);
|
|
3618
4302
|
if (delegation.pendingReplies?.length) {
|
|
@@ -3623,7 +4307,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3623
4307
|
conversationId: delegation.id,
|
|
3624
4308
|
workspaceId: delegation.workspaceId
|
|
3625
4309
|
},
|
|
3626
|
-
delegation.pendingReplies.map((message) => ({
|
|
4310
|
+
delegation.pendingReplies.map((message, index) => ({
|
|
4311
|
+
deliveryId: delegation.pendingReplyIds?.[index],
|
|
3627
4312
|
kind: "reply",
|
|
3628
4313
|
delegationId: delegation.id,
|
|
3629
4314
|
from: delegation.from.definitionId,
|
|
@@ -3688,7 +4373,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3688
4373
|
status: "working",
|
|
3689
4374
|
question: void 0,
|
|
3690
4375
|
...current.undelivered === "question" ? { undelivered: void 0 } : {},
|
|
3691
|
-
pendingReplies: [...current.pendingReplies ?? [], command.message]
|
|
4376
|
+
pendingReplies: [...current.pendingReplies ?? [], command.message],
|
|
4377
|
+
pendingReplyIds: [...current.pendingReplyIds ?? [], command.id]
|
|
3692
4378
|
}));
|
|
3693
4379
|
await this.deliver(
|
|
3694
4380
|
{
|
|
@@ -3697,7 +4383,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3697
4383
|
conversationId: delegation.id,
|
|
3698
4384
|
workspaceId: delegation.workspaceId
|
|
3699
4385
|
},
|
|
3700
|
-
[{ kind: "reply", delegationId: delegation.id, from: command.definitionId, message: command.message }]
|
|
4386
|
+
[{ kind: "reply", deliveryId: command.id, delegationId: delegation.id, from: command.definitionId, message: command.message }]
|
|
3701
4387
|
);
|
|
3702
4388
|
this.observability.append({
|
|
3703
4389
|
type: "delegation.replied",
|
|
@@ -3714,10 +4400,12 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3714
4400
|
await this.updateDelegation(delegation.id, {
|
|
3715
4401
|
status: "waiting",
|
|
3716
4402
|
question: command.question,
|
|
3717
|
-
undelivered: "question"
|
|
4403
|
+
undelivered: "question",
|
|
4404
|
+
updateId: command.id
|
|
3718
4405
|
});
|
|
3719
4406
|
await this.deliver(this.delegatorTarget(delegation), [{
|
|
3720
4407
|
kind: "question",
|
|
4408
|
+
deliveryId: command.id,
|
|
3721
4409
|
delegationId: delegation.id,
|
|
3722
4410
|
agent: delegation.to,
|
|
3723
4411
|
task: delegation.task,
|
|
@@ -3738,7 +4426,10 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3738
4426
|
conversationId: command.conversationId,
|
|
3739
4427
|
workspaceId: command.workspaceId
|
|
3740
4428
|
};
|
|
3741
|
-
|
|
4429
|
+
const parentDefinition = this.byRoute.get(command.definitionId)?.definition;
|
|
4430
|
+
const durable = Object.hasOwn(parentDefinition?.durableSubagents ?? {}, command.to) ? parentDefinition.durableSubagents[command.to] : void 0;
|
|
4431
|
+
const targetRoute = durable ? durableRoute(command.definitionId, command.to) : command.to;
|
|
4432
|
+
if (!this.byRoute.has(targetRoute)) {
|
|
3742
4433
|
await this.deliver(from, [{
|
|
3743
4434
|
kind: "failed",
|
|
3744
4435
|
delegationId: command.delegationId,
|
|
@@ -3752,8 +4443,18 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3752
4443
|
if (!delegator || delegator.workspaceId !== command.workspaceId) {
|
|
3753
4444
|
throw new Error("A delegation must come from an agent instance in its workspace.");
|
|
3754
4445
|
}
|
|
3755
|
-
|
|
3756
|
-
|
|
4446
|
+
let ownedWorker;
|
|
4447
|
+
if (durable) {
|
|
4448
|
+
try {
|
|
4449
|
+
if (!this.data.putPendingInbound || !this.data.listPendingInbound || !this.data.deletePendingInbound) throw new Error("Durable delegation requires pending inbound persistence.");
|
|
4450
|
+
ownedWorker = await this.ensureSubagent(command.agentId, command.to);
|
|
4451
|
+
} catch (cause) {
|
|
4452
|
+
await this.deliver(from, [{ kind: "failed", delegationId: command.delegationId, agent: command.to, task: command.task, error: cause instanceof Error ? cause.message : String(cause) }]);
|
|
4453
|
+
return;
|
|
4454
|
+
}
|
|
4455
|
+
}
|
|
4456
|
+
const workerId = ownedWorker?.id ?? workerAgentId(command.agentId, command.to);
|
|
4457
|
+
const worker = ownedWorker ?? await Effect5.runPromise(this.data.getAgent(workerId)) ?? await this.createAgent(command.to, {
|
|
3757
4458
|
id: workerId,
|
|
3758
4459
|
workspaceId: command.workspaceId,
|
|
3759
4460
|
context: {
|
|
@@ -3761,13 +4462,13 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3761
4462
|
delegatedBy: { agentId: command.agentId, definitionId: command.definitionId }
|
|
3762
4463
|
}
|
|
3763
4464
|
});
|
|
3764
|
-
if (worker.definitionId !==
|
|
4465
|
+
if (worker.definitionId !== targetRoute || worker.workspaceId !== command.workspaceId) {
|
|
3765
4466
|
throw new Error(`Agent instance "${workerId}" is not a ${command.to} worker in this workspace.`);
|
|
3766
4467
|
}
|
|
3767
4468
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3768
4469
|
const delegation = Object.freeze({
|
|
3769
4470
|
id: command.delegationId,
|
|
3770
|
-
to:
|
|
4471
|
+
to: targetRoute,
|
|
3771
4472
|
workerAgentId: workerId,
|
|
3772
4473
|
workspaceId: command.workspaceId,
|
|
3773
4474
|
from: Object.freeze({
|
|
@@ -3788,15 +4489,16 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3788
4489
|
title: title.length > 80 ? `${title.slice(0, 79)}\u2026` : title,
|
|
3789
4490
|
context: { delegation }
|
|
3790
4491
|
});
|
|
3791
|
-
const
|
|
4492
|
+
const workerRequest = {
|
|
3792
4493
|
agentId: workerId,
|
|
3793
4494
|
conversationId: delegation.id,
|
|
3794
4495
|
workspaceId: command.workspaceId,
|
|
3795
4496
|
message: renderDelegatedTask({ delegationId: delegation.id, from: command.definitionId, task: command.task }),
|
|
3796
4497
|
payload: { delegation },
|
|
3797
4498
|
source: { kind: "delegation", id: delegation.id }
|
|
3798
|
-
}
|
|
3799
|
-
this.
|
|
4499
|
+
};
|
|
4500
|
+
const runId = (await this.admitInbound({ id: `task:${delegation.id}`, definitionId: targetRoute, request: workerRequest, createdAt: now }))?.id;
|
|
4501
|
+
if (runId) this.occupyConversation(delegation.id, runId);
|
|
3800
4502
|
this.observability.append({
|
|
3801
4503
|
type: "delegation.started",
|
|
3802
4504
|
category: "system",
|
|
@@ -3806,29 +4508,380 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3806
4508
|
});
|
|
3807
4509
|
}
|
|
3808
4510
|
/** Report a worker's finished run back to whoever delegated to it. */
|
|
4511
|
+
// ── Mesh ────────────────────────────────────────────────────────────────
|
|
4512
|
+
//
|
|
4513
|
+
// Foundry hosts Glove Mesh for agents that are peers: existing instances in
|
|
4514
|
+
// one workspace, addressed by instance id. A new message starts a thread: a
|
|
4515
|
+
// conversation on the recipient whose context carries the record. Messages
|
|
4516
|
+
// travel as "mesh" deliveries on the same durable path as delegation
|
|
4517
|
+
// updates: into the run working on that conversation, or as one run once it
|
|
4518
|
+
// is free. The recipient's final reply goes back on its own.
|
|
4519
|
+
/** Every thread, newest first, optionally narrowed to who started it or who it went to. */
|
|
4520
|
+
async listThreads(filter = {}) {
|
|
4521
|
+
const found = [];
|
|
4522
|
+
for (const agent of await Effect5.runPromise(this.data.listAgents())) {
|
|
4523
|
+
if (filter.to && agent.id !== filter.to) continue;
|
|
4524
|
+
for (const conversation of await Effect5.runPromise(this.data.listConversations(agent.id))) {
|
|
4525
|
+
const thread = threadFromContext(conversation.context);
|
|
4526
|
+
if (!thread || thread.to.agentId !== agent.id || thread.id !== conversation.id) continue;
|
|
4527
|
+
if (filter.agentId && thread.from.agentId !== filter.agentId) continue;
|
|
4528
|
+
if (filter.conversationId && thread.from.conversationId !== filter.conversationId) continue;
|
|
4529
|
+
if (filter.status && thread.status !== filter.status) continue;
|
|
4530
|
+
found.push(thread);
|
|
4531
|
+
}
|
|
4532
|
+
}
|
|
4533
|
+
return found.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
4534
|
+
}
|
|
4535
|
+
/**
|
|
4536
|
+
* Older thread records kept their own lists of messages not handed over yet.
|
|
4537
|
+
* Move them to the event journal once; message ids keep a retry from
|
|
4538
|
+
* delivering twice.
|
|
4539
|
+
*/
|
|
4540
|
+
async redeliverThreads() {
|
|
4541
|
+
for (const thread of await this.listThreads()) {
|
|
4542
|
+
if (!thread.undelivered?.length && !thread.pending?.length) continue;
|
|
4543
|
+
if (thread.undelivered?.length) await this.deliverMesh(this.starterTarget(thread), "starter", thread.undelivered);
|
|
4544
|
+
if (thread.pending?.length) await this.deliverMesh(this.recipientTarget(thread), "recipient", thread.pending);
|
|
4545
|
+
await this.updateThread(thread.id, { status: thread.status });
|
|
4546
|
+
}
|
|
4547
|
+
}
|
|
4548
|
+
/** The open threads a conversation started, oldest first. */
|
|
4549
|
+
async openThreadsFrom(conversation) {
|
|
4550
|
+
const open = [];
|
|
4551
|
+
for (const id2 of startedThreadIds(conversation.context)) {
|
|
4552
|
+
const thread = await this.loadThread(id2);
|
|
4553
|
+
if (thread && thread.from.conversationId === conversation.id && isOpenThread(thread)) open.push(thread);
|
|
4554
|
+
}
|
|
4555
|
+
return open.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
4556
|
+
}
|
|
4557
|
+
async loadThread(id2) {
|
|
4558
|
+
const conversation = await Effect5.runPromise(this.data.getConversation(id2));
|
|
4559
|
+
return threadFromContext(conversation?.context) ?? null;
|
|
4560
|
+
}
|
|
4561
|
+
updateThread(id2, change) {
|
|
4562
|
+
return this.inConversation(`record:${id2}`, async () => {
|
|
4563
|
+
const conversation = await Effect5.runPromise(this.data.getConversation(id2));
|
|
4564
|
+
const current = threadFromContext(conversation?.context);
|
|
4565
|
+
if (!conversation || !current) return null;
|
|
4566
|
+
const patch = typeof change === "function" ? change(current) : change;
|
|
4567
|
+
if (Object.keys(patch).length === 0) return current;
|
|
4568
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4569
|
+
const merged = { ...current, ...patch, updatedAt: now };
|
|
4570
|
+
delete merged.undelivered;
|
|
4571
|
+
delete merged.pending;
|
|
4572
|
+
for (const key of Object.keys(merged)) if (merged[key] === void 0) delete merged[key];
|
|
4573
|
+
const next = Object.freeze(merged);
|
|
4574
|
+
await Effect5.runPromise(this.data.putConversation(Object.freeze({
|
|
4575
|
+
...conversation,
|
|
4576
|
+
context: Object.freeze({ ...conversation.context, meshThread: next }),
|
|
4577
|
+
updatedAt: now
|
|
4578
|
+
})));
|
|
4579
|
+
return next;
|
|
4580
|
+
});
|
|
4581
|
+
}
|
|
4582
|
+
starterTarget(thread) {
|
|
4583
|
+
return {
|
|
4584
|
+
definitionId: thread.from.definitionId,
|
|
4585
|
+
agentId: thread.from.agentId,
|
|
4586
|
+
conversationId: thread.from.conversationId,
|
|
4587
|
+
workspaceId: thread.workspaceId
|
|
4588
|
+
};
|
|
4589
|
+
}
|
|
4590
|
+
recipientTarget(thread) {
|
|
4591
|
+
return {
|
|
4592
|
+
definitionId: thread.to.definitionId,
|
|
4593
|
+
agentId: thread.to.agentId,
|
|
4594
|
+
conversationId: thread.id,
|
|
4595
|
+
workspaceId: thread.workspaceId
|
|
4596
|
+
};
|
|
4597
|
+
}
|
|
4598
|
+
/**
|
|
4599
|
+
* Hand mesh messages to one side of a thread. Messages, replies and
|
|
4600
|
+
* failures go through durable delivery. A read receipt only ever reaches a
|
|
4601
|
+
* run that is listening, and is dropped otherwise.
|
|
4602
|
+
*/
|
|
4603
|
+
async deliverMesh(target, side, messages) {
|
|
4604
|
+
const delivery = (message) => ({ kind: "mesh", side, message, deliveryId: message.id });
|
|
4605
|
+
const receipts = messages.filter((message) => message.kind === "ack");
|
|
4606
|
+
if (receipts.length) {
|
|
4607
|
+
await this.inConversation(target.conversationId, async () => {
|
|
4608
|
+
if (!this.conversationListeners.has(target.conversationId)) return;
|
|
4609
|
+
for (const message of receipts) await writeMailboxDelivery(this.mailboxDirectory, target.conversationId, delivery(message));
|
|
4610
|
+
});
|
|
4611
|
+
}
|
|
4612
|
+
const durable = messages.filter((message) => message.kind !== "ack");
|
|
4613
|
+
if (durable.length) await this.deliver(target, durable.map(delivery));
|
|
4614
|
+
}
|
|
4615
|
+
/** A run's mesh call: answered through its request, so the tool hears the outcome. */
|
|
4616
|
+
async runMeshCommand(command, parentRunId) {
|
|
4617
|
+
const request = await getFoundryCoreCommandRequest(this.coreCommandDirectory, command.id);
|
|
4618
|
+
if (!request) {
|
|
4619
|
+
await this.executeMeshCommand(command, parentRunId);
|
|
4620
|
+
return;
|
|
4621
|
+
}
|
|
4622
|
+
if (!await claimFoundryCoreCommandRequest(this.coreCommandDirectory, command.id)) return;
|
|
4623
|
+
try {
|
|
4624
|
+
if (request.runId !== parentRunId) throw new Error("This mesh call does not belong to this run.");
|
|
4625
|
+
const output = await this.executeMeshCommand(command, parentRunId);
|
|
4626
|
+
await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "success", output });
|
|
4627
|
+
} catch (cause) {
|
|
4628
|
+
const error = cause instanceof Error ? cause.message : String(cause);
|
|
4629
|
+
this.observability.append({
|
|
4630
|
+
type: "mesh.refused",
|
|
4631
|
+
category: "system",
|
|
4632
|
+
agent: command.definitionId,
|
|
4633
|
+
runId: parentRunId,
|
|
4634
|
+
data: { type: command.type, error }
|
|
4635
|
+
});
|
|
4636
|
+
await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "error", error });
|
|
4637
|
+
}
|
|
4638
|
+
}
|
|
4639
|
+
/** The agents an agent may see and message: its workspace, narrowed by its definition's rule. */
|
|
4640
|
+
async meshPeers(sender) {
|
|
4641
|
+
const peers = hostedMeshOptions(this.byRoute.get(sender.definitionId)?.definition.mesh)?.peers;
|
|
4642
|
+
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));
|
|
4643
|
+
}
|
|
4644
|
+
async executeMeshCommand(command, parentRunId) {
|
|
4645
|
+
const sender = await Effect5.runPromise(this.data.getAgent(command.agentId));
|
|
4646
|
+
if (!sender || sender.workspaceId !== command.workspaceId) {
|
|
4647
|
+
throw new Error("A mesh call must come from an agent instance in its workspace.");
|
|
4648
|
+
}
|
|
4649
|
+
if (command.type === "mesh.list") {
|
|
4650
|
+
const filter = command.name?.toLowerCase();
|
|
4651
|
+
return (await this.meshPeers(sender)).map(meshIdentity).filter((identity) => !filter || identity.name.toLowerCase().includes(filter));
|
|
4652
|
+
}
|
|
4653
|
+
const conversation = await Effect5.runPromise(this.data.getConversation(command.conversationId));
|
|
4654
|
+
if (!conversation || conversation.agentId !== sender.id) {
|
|
4655
|
+
throw new Error("A mesh call must come from one of the agent's own conversations.");
|
|
4656
|
+
}
|
|
4657
|
+
const own = threadFromContext(conversation.context);
|
|
4658
|
+
const ownThread = own && own.id === conversation.id && own.to.agentId === sender.id ? own : void 0;
|
|
4659
|
+
const startedThreads = async () => {
|
|
4660
|
+
const threads = [];
|
|
4661
|
+
for (const id2 of startedThreadIds(conversation.context)) {
|
|
4662
|
+
const thread2 = await this.loadThread(id2);
|
|
4663
|
+
if (thread2 && thread2.from.conversationId === conversation.id) threads.push(thread2);
|
|
4664
|
+
}
|
|
4665
|
+
return threads;
|
|
4666
|
+
};
|
|
4667
|
+
if (command.type === "mesh.ack") {
|
|
4668
|
+
const thread2 = ownThread?.messageIds.includes(command.messageId) ? ownThread : (await startedThreads()).find((item) => item.messageIds.includes(command.messageId));
|
|
4669
|
+
if (!thread2) throw new Error(`There is no message "${command.messageId}" in your threads.`);
|
|
4670
|
+
const toStarter = thread2.id === ownThread?.id;
|
|
4671
|
+
await this.deliverMesh(toStarter ? this.starterTarget(thread2) : this.recipientTarget(thread2), toStarter ? "starter" : "recipient", [{
|
|
4672
|
+
kind: "ack",
|
|
4673
|
+
id: newMessageId(),
|
|
4674
|
+
threadId: thread2.id,
|
|
4675
|
+
from: { agentId: sender.id, name: sender.name ?? sender.id },
|
|
4676
|
+
to: toStarter ? thread2.from.agentId : thread2.to.agentId,
|
|
4677
|
+
content: command.note,
|
|
4678
|
+
inReplyTo: command.messageId,
|
|
4679
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4680
|
+
}]);
|
|
4681
|
+
return { acknowledged: command.messageId };
|
|
4682
|
+
}
|
|
4683
|
+
const { message: input } = command;
|
|
4684
|
+
const message = (threadId) => ({
|
|
4685
|
+
kind: "message",
|
|
4686
|
+
id: input.id,
|
|
4687
|
+
threadId,
|
|
4688
|
+
from: { agentId: sender.id, name: sender.name ?? sender.id },
|
|
4689
|
+
to: input.to,
|
|
4690
|
+
content: input.content,
|
|
4691
|
+
...input.inReplyTo ? { inReplyTo: input.inReplyTo } : {},
|
|
4692
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4693
|
+
});
|
|
4694
|
+
const sent = (thread2, direction) => {
|
|
4695
|
+
this.observability.append({
|
|
4696
|
+
type: direction === "new" ? "mesh.thread.started" : "mesh.message.sent",
|
|
4697
|
+
category: "system",
|
|
4698
|
+
agent: command.definitionId,
|
|
4699
|
+
runId: parentRunId,
|
|
4700
|
+
data: { threadId: thread2.id, messageId: input.id, from: sender.id, to: input.to }
|
|
4701
|
+
});
|
|
4702
|
+
return { messageId: input.id, threadId: thread2.id, to: input.to, direction };
|
|
4703
|
+
};
|
|
4704
|
+
if (ownThread && input.to === ownThread.from.agentId && (!input.inReplyTo || ownThread.messageIds.includes(input.inReplyTo))) {
|
|
4705
|
+
const outgoing2 = message(ownThread.id);
|
|
4706
|
+
await this.updateThread(ownThread.id, (current) => ({
|
|
4707
|
+
status: "waiting",
|
|
4708
|
+
question: outgoing2.content,
|
|
4709
|
+
messageIds: [...current.messageIds, outgoing2.id]
|
|
4710
|
+
}));
|
|
4711
|
+
await this.deliverMesh(this.starterTarget(ownThread), "starter", [outgoing2]);
|
|
4712
|
+
return sent(ownThread, "to-starter");
|
|
4713
|
+
}
|
|
4714
|
+
if (input.inReplyTo) {
|
|
4715
|
+
const thread2 = (await startedThreads()).find((item) => item.to.agentId === input.to && item.messageIds.includes(input.inReplyTo));
|
|
4716
|
+
if (!thread2) {
|
|
4717
|
+
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.`);
|
|
4718
|
+
}
|
|
4719
|
+
const outgoing2 = message(thread2.id);
|
|
4720
|
+
await this.updateThread(thread2.id, (current) => ({
|
|
4721
|
+
status: "working",
|
|
4722
|
+
question: void 0,
|
|
4723
|
+
messageIds: [...current.messageIds, outgoing2.id]
|
|
4724
|
+
}));
|
|
4725
|
+
await this.deliverMesh(this.recipientTarget(thread2), "recipient", [outgoing2]);
|
|
4726
|
+
return sent(thread2, "to-recipient");
|
|
4727
|
+
}
|
|
4728
|
+
if (!isThreadId(input.threadId)) throw new Error(`"${input.threadId}" is not a thread id.`);
|
|
4729
|
+
if (input.to === sender.id) throw new Error("That is you.");
|
|
4730
|
+
const recipient = (await this.meshPeers(sender)).find((agent) => agent.id === input.to);
|
|
4731
|
+
if (!recipient) {
|
|
4732
|
+
throw new Error(`There is no agent "${input.to}" you can message. Use glove_mesh_list_agents to see who there is.`);
|
|
4733
|
+
}
|
|
4734
|
+
const outgoing = message(input.threadId);
|
|
4735
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4736
|
+
const thread = Object.freeze({
|
|
4737
|
+
id: input.threadId,
|
|
4738
|
+
workspaceId: sender.workspaceId,
|
|
4739
|
+
from: Object.freeze({
|
|
4740
|
+
agentId: sender.id,
|
|
4741
|
+
name: sender.name ?? sender.id,
|
|
4742
|
+
definitionId: sender.definitionId,
|
|
4743
|
+
conversationId: conversation.id,
|
|
4744
|
+
runId: parentRunId
|
|
4745
|
+
}),
|
|
4746
|
+
to: Object.freeze({
|
|
4747
|
+
agentId: recipient.id,
|
|
4748
|
+
name: recipient.name ?? recipient.id,
|
|
4749
|
+
definitionId: recipient.definitionId
|
|
4750
|
+
}),
|
|
4751
|
+
subject: threadSubject(outgoing.content),
|
|
4752
|
+
status: "working",
|
|
4753
|
+
messageIds: Object.freeze([outgoing.id]),
|
|
4754
|
+
createdAt: now,
|
|
4755
|
+
updatedAt: now
|
|
4756
|
+
});
|
|
4757
|
+
await this.createConversation(recipient.id, {
|
|
4758
|
+
id: thread.id,
|
|
4759
|
+
workspaceId: sender.workspaceId,
|
|
4760
|
+
title: `${thread.from.name}: ${clipTitle(outgoing.content)}`,
|
|
4761
|
+
context: { meshThread: thread }
|
|
4762
|
+
});
|
|
4763
|
+
await this.inConversation(`record:${conversation.id}`, async () => {
|
|
4764
|
+
const current = await Effect5.runPromise(this.data.getConversation(conversation.id));
|
|
4765
|
+
if (!current) return;
|
|
4766
|
+
await Effect5.runPromise(this.data.putConversation({
|
|
4767
|
+
...current,
|
|
4768
|
+
context: Object.freeze({
|
|
4769
|
+
...current.context,
|
|
4770
|
+
meshThreads: [...startedThreadIds(current.context), thread.id]
|
|
4771
|
+
}),
|
|
4772
|
+
updatedAt: now
|
|
4773
|
+
}));
|
|
4774
|
+
});
|
|
4775
|
+
await this.deliverMesh(this.recipientTarget(thread), "recipient", [outgoing]);
|
|
4776
|
+
return sent(thread, "new");
|
|
4777
|
+
}
|
|
4778
|
+
/** When the recipient's run on a thread ends, its reply (or its failure) goes back. */
|
|
4779
|
+
async settleThread(event, run, steered) {
|
|
4780
|
+
const thread = await this.loadThread(run.conversationId);
|
|
4781
|
+
if (!thread || run.agentId !== thread.to.agentId) return;
|
|
4782
|
+
if (this.stopping && event.status !== "completed") return;
|
|
4783
|
+
const reply = (kind, content) => ({
|
|
4784
|
+
kind,
|
|
4785
|
+
id: `msg_${kind}_${event.run.id}`,
|
|
4786
|
+
threadId: thread.id,
|
|
4787
|
+
from: { agentId: thread.to.agentId, name: thread.to.name },
|
|
4788
|
+
to: thread.from.agentId,
|
|
4789
|
+
content,
|
|
4790
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4791
|
+
});
|
|
4792
|
+
if (event.status === "completed") {
|
|
4793
|
+
const output = parseJson(event.output);
|
|
4794
|
+
if (output?.status === "suspended") return;
|
|
4795
|
+
const text = deliveryText(output?.value);
|
|
4796
|
+
if (!text.trim()) {
|
|
4797
|
+
await this.updateThread(thread.id, { status: "replied", question: void 0 });
|
|
4798
|
+
return;
|
|
4799
|
+
}
|
|
4800
|
+
const message2 = reply("reply", text);
|
|
4801
|
+
await this.updateThread(thread.id, (current) => ({
|
|
4802
|
+
status: "replied",
|
|
4803
|
+
reply: text,
|
|
4804
|
+
question: void 0,
|
|
4805
|
+
messageIds: current.messageIds.includes(message2.id) ? current.messageIds : [...current.messageIds, message2.id]
|
|
4806
|
+
}));
|
|
4807
|
+
await this.deliverMesh(this.starterTarget(thread), "starter", [message2]);
|
|
4808
|
+
this.observability.append({
|
|
4809
|
+
type: "mesh.thread.replied",
|
|
4810
|
+
category: "system",
|
|
4811
|
+
agent: thread.to.definitionId,
|
|
4812
|
+
runId: event.run.id,
|
|
4813
|
+
data: { threadId: thread.id }
|
|
4814
|
+
});
|
|
4815
|
+
return;
|
|
4816
|
+
}
|
|
4817
|
+
if (event.status === "cancelled" && steered) return;
|
|
4818
|
+
const error = event.status === "cancelled" ? "The work was cancelled." : event.error ?? "The run failed.";
|
|
4819
|
+
const message = reply("failed", error);
|
|
4820
|
+
await this.updateThread(thread.id, (current) => ({
|
|
4821
|
+
status: event.status === "cancelled" ? "cancelled" : "failed",
|
|
4822
|
+
error,
|
|
4823
|
+
messageIds: current.messageIds.includes(message.id) ? current.messageIds : [...current.messageIds, message.id]
|
|
4824
|
+
}));
|
|
4825
|
+
await this.deliverMesh(this.starterTarget(thread), "starter", [message]);
|
|
4826
|
+
this.observability.append({
|
|
4827
|
+
type: event.status === "cancelled" ? "mesh.thread.cancelled" : "mesh.thread.failed",
|
|
4828
|
+
category: "system",
|
|
4829
|
+
agent: thread.to.definitionId,
|
|
4830
|
+
runId: event.run.id,
|
|
4831
|
+
data: { threadId: thread.id, error }
|
|
4832
|
+
});
|
|
4833
|
+
}
|
|
3809
4834
|
async handleRunSettled(event) {
|
|
4835
|
+
void this.settleApprovalsOf(event.run.id).catch((cause) => this.reportApprovalFailure(event.run.id, cause));
|
|
3810
4836
|
this.releaseConversationRun(event.run.id);
|
|
3811
4837
|
void this.waitForRunProcessRelease(this.toFoundryRun(event.run), event.route).finally(() => this.gate.settled(event.run.id));
|
|
3812
|
-
|
|
3813
|
-
|
|
3814
|
-
|
|
4838
|
+
const finishDelivery = async () => {
|
|
4839
|
+
this.settledRuns.add(event.run.id);
|
|
4840
|
+
if (this.settledRuns.size > 1e3) this.settledRuns.delete(this.settledRuns.values().next().value);
|
|
4841
|
+
if (event.status === "completed") {
|
|
4842
|
+
const result = parseJson(event.output);
|
|
4843
|
+
await this.finishEvents(event.run.id, result?.consumedEventIds ?? []);
|
|
4844
|
+
}
|
|
4845
|
+
await this.finishPendingInbound(event.run.id).catch((cause) => this.reportDeliveryFailure(this.toFoundryRun(event.run).conversationId ?? "settle", cause));
|
|
4846
|
+
};
|
|
3815
4847
|
const steered = this.steeredRuns.delete(event.run.id);
|
|
3816
4848
|
const run = this.toFoundryRun(event.run);
|
|
3817
|
-
if (
|
|
4849
|
+
if (run.conversationId && isThreadId(run.conversationId)) {
|
|
4850
|
+
await finishDelivery();
|
|
4851
|
+
await this.settleThread(event, run, steered);
|
|
4852
|
+
return;
|
|
4853
|
+
}
|
|
4854
|
+
if (!run.conversationId || !isDelegationId(run.conversationId)) {
|
|
4855
|
+
await finishDelivery();
|
|
4856
|
+
return;
|
|
4857
|
+
}
|
|
3818
4858
|
const delegation = await this.loadDelegation(run.conversationId);
|
|
3819
|
-
if (!delegation || run.agentId !== delegation.workerAgentId)
|
|
4859
|
+
if (!delegation || run.agentId !== delegation.workerAgentId) {
|
|
4860
|
+
await finishDelivery();
|
|
4861
|
+
return;
|
|
4862
|
+
}
|
|
4863
|
+
if (this.stopping && event.status !== "completed") {
|
|
4864
|
+
const worker = await Effect5.runPromise(this.data.getAgent(delegation.workerAgentId));
|
|
4865
|
+
if (worker?.durableSubagent) return;
|
|
4866
|
+
}
|
|
3820
4867
|
if (event.status === "completed") {
|
|
3821
4868
|
const output = parseJson(event.output);
|
|
3822
|
-
if (output?.status === "suspended")
|
|
4869
|
+
if (output?.status === "suspended") {
|
|
4870
|
+
await finishDelivery();
|
|
4871
|
+
return;
|
|
4872
|
+
}
|
|
3823
4873
|
const result = deliveryText(output?.value);
|
|
3824
4874
|
await this.updateDelegation(delegation.id, {
|
|
3825
4875
|
status: "completed",
|
|
3826
4876
|
result,
|
|
3827
4877
|
question: void 0,
|
|
3828
|
-
undelivered: "result"
|
|
4878
|
+
undelivered: "result",
|
|
4879
|
+
updateId: `result:${event.run.id}`
|
|
3829
4880
|
});
|
|
4881
|
+
await finishDelivery();
|
|
3830
4882
|
await this.deliver(this.delegatorTarget(delegation), [{
|
|
3831
4883
|
kind: "result",
|
|
4884
|
+
deliveryId: `result:${event.run.id}`,
|
|
3832
4885
|
delegationId: delegation.id,
|
|
3833
4886
|
agent: delegation.to,
|
|
3834
4887
|
task: delegation.task,
|
|
@@ -3843,15 +4896,21 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3843
4896
|
});
|
|
3844
4897
|
return;
|
|
3845
4898
|
}
|
|
3846
|
-
if (event.status === "cancelled" && steered)
|
|
4899
|
+
if (event.status === "cancelled" && steered) {
|
|
4900
|
+
await finishDelivery();
|
|
4901
|
+
return;
|
|
4902
|
+
}
|
|
3847
4903
|
const error = event.status === "cancelled" ? "The work was cancelled." : event.error ?? "The run failed.";
|
|
3848
4904
|
await this.updateDelegation(delegation.id, {
|
|
3849
4905
|
status: event.status === "cancelled" ? "cancelled" : "failed",
|
|
3850
4906
|
error,
|
|
3851
|
-
undelivered: "failed"
|
|
4907
|
+
undelivered: "failed",
|
|
4908
|
+
updateId: `failed:${event.run.id}`
|
|
3852
4909
|
});
|
|
4910
|
+
await finishDelivery();
|
|
3853
4911
|
await this.deliver(this.delegatorTarget(delegation), [{
|
|
3854
4912
|
kind: "failed",
|
|
4913
|
+
deliveryId: `failed:${event.run.id}`,
|
|
3855
4914
|
delegationId: delegation.id,
|
|
3856
4915
|
agent: delegation.to,
|
|
3857
4916
|
task: delegation.task,
|
|
@@ -3865,13 +4924,13 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3865
4924
|
data: { delegationId: delegation.id, error }
|
|
3866
4925
|
});
|
|
3867
4926
|
}
|
|
3868
|
-
async enqueueCoreRequest(definitionId, request) {
|
|
4927
|
+
async enqueueCoreRequest(definitionId, request, options = {}) {
|
|
3869
4928
|
const discovered = this.byRoute.get(definitionId);
|
|
3870
4929
|
if (!discovered) throw new Error(`Foundry agent definition "${definitionId}" was not found.`);
|
|
3871
4930
|
const agent = await Effect5.runPromise(this.data.getAgent(request.agentId));
|
|
3872
4931
|
const conversation = await Effect5.runPromise(this.data.getConversation(request.conversationId));
|
|
3873
4932
|
if (!agent || !conversation) throw new Error("Core command references an unknown agent instance or conversation.");
|
|
3874
|
-
return this.admitRun(discovered.executionName, request);
|
|
4933
|
+
return this.admitRun(discovered.executionName, request, options);
|
|
3875
4934
|
}
|
|
3876
4935
|
/**
|
|
3877
4936
|
* Create the run for a request through its conversation's gate: it starts
|
|
@@ -3885,12 +4944,12 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3885
4944
|
request.conversationId,
|
|
3886
4945
|
async (parked) => this.signalRunner.triggerSignal(
|
|
3887
4946
|
executionName,
|
|
3888
|
-
await this.executionEnvelope(request, { leased: true }),
|
|
4947
|
+
await this.executionEnvelope(request, { leased: true, eventTurn: options.eventTurn }),
|
|
3889
4948
|
{ parked }
|
|
3890
4949
|
),
|
|
3891
4950
|
async (runId) => this.signalRunner.releaseRun(
|
|
3892
4951
|
runId,
|
|
3893
|
-
await this.executionEnvelope(request, { leased: true })
|
|
4952
|
+
await this.executionEnvelope(request, { leased: true, eventTurn: options.eventTurn })
|
|
3894
4953
|
),
|
|
3895
4954
|
options
|
|
3896
4955
|
);
|
|
@@ -3908,8 +4967,26 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3908
4967
|
return this.executeCoreCommandUnlocked(command, parentRunId);
|
|
3909
4968
|
}
|
|
3910
4969
|
async executeCoreCommandUnlocked(command, parentRunId) {
|
|
4970
|
+
if (isMeshCommand(command)) {
|
|
4971
|
+
await this.runMeshCommand(command, parentRunId);
|
|
4972
|
+
return;
|
|
4973
|
+
}
|
|
4974
|
+
if (command.type === "agent.message") {
|
|
4975
|
+
try {
|
|
4976
|
+
const output = await this.executeAgentMessage(command);
|
|
4977
|
+
await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "success", output });
|
|
4978
|
+
} catch (cause) {
|
|
4979
|
+
await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "error", error: cause instanceof Error ? cause.message : String(cause) });
|
|
4980
|
+
}
|
|
4981
|
+
return;
|
|
4982
|
+
}
|
|
4983
|
+
if (command.agentId) {
|
|
4984
|
+
const sender = await Effect5.runPromise(this.data.getAgent(command.agentId));
|
|
4985
|
+
if (sender) await this.assertDurableActive(sender);
|
|
4986
|
+
}
|
|
3911
4987
|
if (command.type === "delegate" || command.type === "delegate.reply" || command.type === "delegate.ask") {
|
|
3912
|
-
await this.executeDelegationCommand(command, parentRunId);
|
|
4988
|
+
if (command.type === "delegate") await this.inConversation("durable:mutations", () => this.executeDelegationCommand(command, parentRunId));
|
|
4989
|
+
else await this.executeDelegationCommand(command, parentRunId);
|
|
3913
4990
|
return;
|
|
3914
4991
|
}
|
|
3915
4992
|
if (command.type === "transmit") {
|
|
@@ -4094,7 +5171,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4094
5171
|
playbooks: Object.freeze([...instancePlaybooks, ...reconciled]),
|
|
4095
5172
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4096
5173
|
};
|
|
4097
|
-
this.validatePlaybooks(command.definitionId, updated.playbooks, updated.installations);
|
|
5174
|
+
this.validatePlaybooks(command.definitionId, updated.playbooks, (await this.effectiveAgent(updated)).installations);
|
|
4098
5175
|
await Effect5.runPromise(this.data.putAgent(updated));
|
|
4099
5176
|
await this.reconcileApplicationConnections();
|
|
4100
5177
|
this.observability.append({
|
|
@@ -4290,6 +5367,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4290
5367
|
);
|
|
4291
5368
|
}
|
|
4292
5369
|
const storedAgent = await Effect5.runPromise(this.data.getAgent(activation.agentId));
|
|
5370
|
+
if (storedAgent) await this.assertDurableActive(storedAgent);
|
|
4293
5371
|
const storedConversation = await Effect5.runPromise(
|
|
4294
5372
|
this.data.getConversation(activation.conversationId)
|
|
4295
5373
|
);
|
|
@@ -4320,7 +5398,11 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4320
5398
|
kind: "signal",
|
|
4321
5399
|
target: discovered.executionName,
|
|
4322
5400
|
...activation.timing.kind === "every" ? { interval: `${activation.timing.intervalMs}ms` } : { cron: activation.timing.expression, timezone: activation.timing.timezone },
|
|
4323
|
-
|
|
5401
|
+
// Station checks overlap per signal, and a signal is a whole
|
|
5402
|
+
// definition: "skip" would drop one agent's run because another
|
|
5403
|
+
// agent of the same definition is busy. Runs overlap like messages
|
|
5404
|
+
// do, and the conversation gate still runs one at a time per conversation.
|
|
5405
|
+
overlapPolicy: "allow",
|
|
4324
5406
|
misfirePolicy: "fire-once",
|
|
4325
5407
|
misfireGraceMs: 6e4,
|
|
4326
5408
|
input: await this.executionEnvelope(request),
|
|
@@ -4453,15 +5535,26 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4453
5535
|
const agent = await Effect5.runPromise(this.data.getAgent(request.agentId));
|
|
4454
5536
|
const conversation = await Effect5.runPromise(this.data.getConversation(request.conversationId));
|
|
4455
5537
|
if (!agent || !conversation) throw new Error("Cannot schedule an unknown agent instance or conversation.");
|
|
5538
|
+
const effective = await this.effectiveAgent(agent);
|
|
5539
|
+
const owners = {};
|
|
5540
|
+
let ancestor = agent;
|
|
5541
|
+
while (ancestor.durableSubagent) {
|
|
5542
|
+
ancestor = await Effect5.runPromise(this.data.getAgent(ancestor.durableSubagent.parentAgentId));
|
|
5543
|
+
owners[ancestor.definitionId] = { id: ancestor.id, definitionId: ancestor.definitionId, workspaceId: ancestor.workspaceId };
|
|
5544
|
+
}
|
|
4456
5545
|
const activations = (await Effect5.runPromise(this.data.listActivations(request.workspaceId))).filter((activation) => activation.agentId === request.agentId);
|
|
4457
5546
|
const delegations = await this.openDelegationsFrom(request.agentId, request.conversationId);
|
|
5547
|
+
const threads = await this.openThreadsFrom(conversation);
|
|
4458
5548
|
return {
|
|
4459
5549
|
[FOUNDRY_EXECUTION_MARKER]: true,
|
|
4460
|
-
request,
|
|
4461
|
-
|
|
5550
|
+
request: { ...request, context: { ...request.context, durableMemoryOwners: owners } },
|
|
5551
|
+
eventTurn: options.eventTurn ?? false,
|
|
5552
|
+
agent: effective,
|
|
4462
5553
|
conversation,
|
|
4463
5554
|
activations,
|
|
4464
5555
|
delegations,
|
|
5556
|
+
threads,
|
|
5557
|
+
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 } })) : [],
|
|
4465
5558
|
...options.leased ? { conversationLease: true } : {}
|
|
4466
5559
|
};
|
|
4467
5560
|
}
|
|
@@ -4524,7 +5617,13 @@ var PHOSPHOR_ICON_PATHS = {
|
|
|
4524
5617
|
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",
|
|
4525
5618
|
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",
|
|
4526
5619
|
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",
|
|
4527
|
-
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"
|
|
5620
|
+
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
|
+
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",
|
|
5622
|
+
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",
|
|
5623
|
+
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",
|
|
5624
|
+
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",
|
|
5625
|
+
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",
|
|
5626
|
+
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"
|
|
4528
5627
|
};
|
|
4529
5628
|
function renderPhosphorIcon(name, className = "icon") {
|
|
4530
5629
|
return `<svg class="${className}" data-phosphor="${name}" viewBox="0 0 256 256" fill="currentColor" aria-hidden="true"><path d="${PHOSPHOR_ICON_PATHS[name]}"/></svg>`;
|
|
@@ -4535,11 +5634,532 @@ function renderGloveMark() {
|
|
|
4535
5634
|
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>`;
|
|
4536
5635
|
}
|
|
4537
5636
|
|
|
5637
|
+
// src/dashboard-run.ts
|
|
5638
|
+
var DASHBOARD_RUN_SCRIPT = String.raw`
|
|
5639
|
+
const RUN_TABS=[["summary","Summary","overview"],["network","Network","network"],["console","Console","terminal"],["context","Context","context"]];
|
|
5640
|
+
function runView(){
|
|
5641
|
+
const params=new URLSearchParams(location.search);const tab=params.get("tab");
|
|
5642
|
+
return{tab:RUN_TABS.some(t=>t[0]===tab)?tab:"network",item:params.get("item")||"",pane:params.get("pane")||"",node:params.get("node")||"",request:params.get("request")||""};
|
|
5643
|
+
}
|
|
5644
|
+
function setRunView(patch){
|
|
5645
|
+
const params=new URLSearchParams(location.search);
|
|
5646
|
+
Object.entries(patch).forEach(([key,value])=>{if(value)params.set(key,value);else params.delete(key)});
|
|
5647
|
+
if(params.get("tab")==="network")params.delete("tab");
|
|
5648
|
+
const search=params.toString();history.replaceState({},"",location.pathname+(search?"?"+search:""));
|
|
5649
|
+
}
|
|
5650
|
+
async function ensureRunEvents(id){
|
|
5651
|
+
const cached=state.runEvents[id];
|
|
5652
|
+
const after=cached&&cached.length?cached[cached.length-1].sequence:null;
|
|
5653
|
+
const fresh=await api("/api/runs/"+encodeURIComponent(id)+"/events"+(after===null?"":"?after="+after));
|
|
5654
|
+
state.runEvents[id]=after===null?fresh:cached.concat(fresh);
|
|
5655
|
+
}
|
|
5656
|
+
function runEventsFor(id){return state.runEvents[id]||eventsFor(id)}
|
|
5657
|
+
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"}
|
|
5658
|
+
function jsonSize(value){try{return(JSON.stringify(value)??"").length}catch{return 0}}
|
|
5659
|
+
function isoAt(ms){return Number.isFinite(ms)?new Date(ms).toISOString():""}
|
|
5660
|
+
function offsetFrom(base,iso){const at=new Date(iso).getTime();return Number.isFinite(base)&&Number.isFinite(at)?"+"+durationText(Math.max(0,at-base)):""}
|
|
5661
|
+
|
|
5662
|
+
/* ---- A JSON tree, like DevTools': collapsed past two levels, strings that hold JSON opened up. ---- */
|
|
5663
|
+
function jsonTree(value,key,depth){
|
|
5664
|
+
depth=depth||0;
|
|
5665
|
+
if(value===undefined)return'<span class="jv null">not recorded</span>';
|
|
5666
|
+
if(value===null)return'<span class="jv null">null</span>';
|
|
5667
|
+
if(typeof value==="string"){
|
|
5668
|
+
const text=value.trim();
|
|
5669
|
+
if(depth===0&&/^[\[{]/.test(text)){try{return'<span class="jv-note">JSON in a string</span>'+jsonTree(JSON.parse(text),key,0)}catch{}}
|
|
5670
|
+
return'<span class="jv str">"'+esc(value)+'"</span>';
|
|
5671
|
+
}
|
|
5672
|
+
if(typeof value==="number")return'<span class="jv num">'+esc(value)+'</span>';
|
|
5673
|
+
if(typeof value==="boolean")return'<span class="jv bool">'+value+'</span>';
|
|
5674
|
+
const isArray=Array.isArray(value);const entries=isArray?value.map((item,index)=>[index,item]):Object.entries(value);
|
|
5675
|
+
if(!entries.length)return'<span class="jv">'+(isArray?"[]":"{}")+'</span>';
|
|
5676
|
+
const preview=isArray?"Array("+entries.length+")":"{"+entries.slice(0,4).map(entry=>esc(entry[0])).join(", ")+(entries.length>4?", …":"")+"}";
|
|
5677
|
+
return'<details class="jt" data-persist="jt:'+attr(key)+'"'+(depth<2?" open":"")+'><summary>'+preview+'</summary><div class="jt-body">'
|
|
5678
|
+
+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("")
|
|
5679
|
+
+(entries.length>400?'<div class="muted">… '+(entries.length-400)+' more</div>':"")+'</div></details>';
|
|
5680
|
+
}
|
|
5681
|
+
function jsonBlock(value,key){return'<div class="jt-root">'+jsonTree(value,key)+'</div>'}
|
|
5682
|
+
|
|
5683
|
+
/* ---- Messages as the model received them. ---- */
|
|
5684
|
+
function traceRole(message){
|
|
5685
|
+
if(message.framework_context==="runtime")return{label:"Runtime context",cls:"runtime"};
|
|
5686
|
+
if(message.framework_context==="inbox")return{label:"Inbox",cls:"runtime"};
|
|
5687
|
+
if(message.is_compaction)return{label:"Compaction summary",cls:"system"};
|
|
5688
|
+
if(message.is_compaction_request)return{label:"Compaction request",cls:"system"};
|
|
5689
|
+
if(message.is_skill_injection)return{label:"Skill",cls:"system"};
|
|
5690
|
+
if(message.sender==="user"&&(message.tool_results||[]).length)return{label:"Tool results",cls:"tool"};
|
|
5691
|
+
return message.sender==="user"?{label:"User",cls:"user"}:{label:"Agent",cls:"agent"};
|
|
5692
|
+
}
|
|
5693
|
+
function traceMessageHtml(message,key,isNew){
|
|
5694
|
+
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>';
|
|
5695
|
+
const role=traceRole(message);let body="";
|
|
5696
|
+
const toolText=(message.tool_results||[]).length&&message.text==="tool results";
|
|
5697
|
+
if(message.text&&!toolText)body+='<div class="tm-text">'+esc(message.text)+'</div>';
|
|
5698
|
+
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>';
|
|
5699
|
+
const media=(message.content||[]).filter(part=>part.type!=="text");
|
|
5700
|
+
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>';
|
|
5701
|
+
(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>'});
|
|
5702
|
+
(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>'});
|
|
5703
|
+
if(message.reasoning_omitted)body+='<p class="tm-note">The provider’s reasoning was sent back with this message. It isn’t recorded.</p>';
|
|
5704
|
+
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>';
|
|
5705
|
+
}
|
|
5706
|
+
function messagesHtml(messages,newFrom,key){
|
|
5707
|
+
const earlier=messages.slice(0,newFrom);const fresh=messages.slice(newFrom);
|
|
5708
|
+
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>':"")
|
|
5709
|
+
+(fresh.length?fresh.map((message,index)=>traceMessageHtml(message,key+":"+(newFrom+index),Boolean(earlier.length))).join(""):'<p class="dt-note">No messages.</p>');
|
|
5710
|
+
}
|
|
5711
|
+
|
|
5712
|
+
/* ---- Network ---- */
|
|
5713
|
+
function itemStatus(item){
|
|
5714
|
+
if(item.approval&&item.approval.status==="pending")return'<span class="st warn">approval</span>';
|
|
5715
|
+
const map={success:["ok","ok"],error:["err","error"],aborted:["warn","aborted"],denied:["warn","denied"],limit:["warn","limit"],pending:["live","pending"]};
|
|
5716
|
+
const value=map[item.status]||["",item.status||"—"];
|
|
5717
|
+
return'<span class="st '+value[0]+'">'+esc(value[1])+'</span>';
|
|
5718
|
+
}
|
|
5719
|
+
function itemType(item){return item.kind==="model"?(item.purpose==="compaction"?"compaction":"model"):item.via==="repl"?"repl call":item.kind}
|
|
5720
|
+
function itemSubtitle(item){
|
|
5721
|
+
if(item.kind==="model")return(item.model||"model")+(item.messages.length?" · "+count(item.messages.length,"message"):"")+(item.context.length?" · "+item.context.length+" context":"");
|
|
5722
|
+
if(item.kind==="tool")return item.via==="repl"?(item.fn||item.name)+"()":tracePreview(item.input,80);
|
|
5723
|
+
return tracePreview(item.prompt,80);
|
|
5724
|
+
}
|
|
5725
|
+
function itemSize(item){
|
|
5726
|
+
if(item.kind==="model")return item.tokensIn!==undefined?fmtTokens(item.tokensIn)+" → "+fmtTokens(item.tokensOut):"—";
|
|
5727
|
+
return item.result?fmtBytes(jsonSize(item.result.data)):"—";
|
|
5728
|
+
}
|
|
5729
|
+
function netMatches(item,kind,term){
|
|
5730
|
+
if(kind==="model"&&item.kind!=="model")return false;
|
|
5731
|
+
if(kind==="tools"&&item.kind!=="tool")return false;
|
|
5732
|
+
if(kind==="errors"&&!["error","aborted","denied","limit"].includes(item.status))return false;
|
|
5733
|
+
if(!term)return true;
|
|
5734
|
+
const text=[item.name,item.model,item.fn,tracePreview(item.input,600),item.kind==="model"?(item.response||[]).map(message=>message.text).join(" "):tracePreview(item.result&&item.result.data,600)].join(" ").toLowerCase();
|
|
5735
|
+
return text.includes(term);
|
|
5736
|
+
}
|
|
5737
|
+
function netRow(item,trace,selectedKey){
|
|
5738
|
+
const span=Math.max(1,trace.end-trace.start);const pending=item.status==="pending";
|
|
5739
|
+
const left=Number.isFinite(item.startAt)?Math.min(99.4,Math.max(0,(item.startAt-trace.start)/span*100)):0;
|
|
5740
|
+
const width=Number.isFinite(item.durationMs)?Math.max(.6,item.durationMs/span*100):pending?100-left:.6;
|
|
5741
|
+
const failed=["error","aborted","denied","limit"].includes(item.status);
|
|
5742
|
+
return'<tr class="net-row kind-'+attr(item.kind)+(item.purpose==="compaction"?" compaction":"")+(item.key===selectedKey?" selected":"")+(failed?" failed":"")+'" data-net-item="'+attr(item.key)+'">'
|
|
5743
|
+
+'<td class="c-name"><span class="net-name"><i class="net-glyph"></i><span><b>'+esc(item.name)+'</b><small>'+esc(itemSubtitle(item))+'</small></span></span></td>'
|
|
5744
|
+
+'<td class="c-type">'+esc(itemType(item))+'</td>'
|
|
5745
|
+
+'<td class="c-status">'+itemStatus(item)+'</td>'
|
|
5746
|
+
+'<td class="c-init">'+(item.initiator.key?'<button type="button" class="net-link" data-net-item="'+attr(item.initiator.key)+'">'+esc(item.initiator.label)+'</button>':'<span class="muted">'+esc(item.initiator.label)+'</span>')+'</td>'
|
|
5747
|
+
+'<td class="c-size">'+esc(itemSize(item))+'</td>'
|
|
5748
|
+
+'<td class="c-time">'+(pending?'<span class="st live">…</span>':esc(durationText(item.durationMs)))+'</td>'
|
|
5749
|
+
+'<td class="c-wf"><span class="wf-track"><span class="wf-bar'+(pending?" pending":"")+'" style="left:'+left.toFixed(2)+'%;width:'+Math.min(width,100-left).toFixed(2)+'%"></span></span></td></tr>';
|
|
5750
|
+
}
|
|
5751
|
+
function modelPanes(item){return[["overview","Overview"],["prompt","Prompt"],["messages","Messages",item.messages.length],["context","Context",item.context.length],["tools","Tools",item.toolNames.length],["response","Response"],["raw","Raw"]]}
|
|
5752
|
+
function toolPanes(){return[["overview","Overview"],["input","Input"],["result","Result"],["raw","Raw"]]}
|
|
5753
|
+
function detailPanes(item){return item.kind==="model"?modelPanes(item):item.kind==="tool"?toolPanes():[["overview","Overview"],["raw","Raw"]]}
|
|
5754
|
+
function kv(rows){return'<dl class="dt-kv">'+rows.filter(Boolean).map(row=>'<dt>'+esc(row[0])+'</dt><dd>'+row[1]+'</dd>').join("")+'</dl>'}
|
|
5755
|
+
function itemLink(key,label){return'<button type="button" class="net-link" data-net-item="'+attr(key)+'">'+esc(label)+'</button>'}
|
|
5756
|
+
function requestJson(item){return jsonText({model:item.model,system:item.systemPrompt??null,messages:item.messages,context:item.context,tools:item.tools||item.toolNames})}
|
|
5757
|
+
function modelDetail(item,trace,run,pane){
|
|
5758
|
+
const base=new Date(runStartedAt(run)).getTime();
|
|
5759
|
+
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>';
|
|
5760
|
+
if(pane==="prompt"){
|
|
5761
|
+
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>';
|
|
5762
|
+
const versions=Object.keys(trace.prompts).length;
|
|
5763
|
+
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>');
|
|
5764
|
+
}
|
|
5765
|
+
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");
|
|
5766
|
+
if(pane==="context"){
|
|
5767
|
+
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>';
|
|
5768
|
+
const before=trace.items.filter(other=>other.kind==="model"&&other.index<item.index).at(-1);
|
|
5769
|
+
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>'
|
|
5770
|
+
+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("");
|
|
5771
|
+
}
|
|
5772
|
+
if(pane==="tools"){
|
|
5773
|
+
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>';
|
|
5774
|
+
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("");
|
|
5775
|
+
}
|
|
5776
|
+
if(pane==="response"){
|
|
5777
|
+
if(item.status==="pending")return'<p class="dt-note">Waiting for the model.</p>';
|
|
5778
|
+
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>':"")
|
|
5779
|
+
+kv([item.stopReason?["Stop reason",esc(item.stopReason)]:null,["Tokens",esc(fmtTokens(item.tokensIn))+" in · "+esc(fmtTokens(item.tokensOut))+" out"]])
|
|
5780
|
+
+(item.response||[]).map((message,index)=>traceMessageHtml(message,item.key+":r"+index,false)).join("");
|
|
5781
|
+
}
|
|
5782
|
+
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");
|
|
5783
|
+
const fresh=item.messages.slice(item.newFrom);const calls=(item.response||[]).flatMap(message=>message.tool_calls||[]);
|
|
5784
|
+
return kv([
|
|
5785
|
+
["Request",'<span class="mono">'+esc(item.id)+'</span> '+copyButton(item.id,"request id")],
|
|
5786
|
+
["Model",esc(item.model||"—")],
|
|
5787
|
+
["Status",itemStatus(item)+(item.error?' <span class="muted">'+esc(item.error)+'</span>':"")],
|
|
5788
|
+
["Started",esc(offsetFrom(base,isoAt(item.startAt)))+' <span class="muted">'+esc(fmtTime(isoAt(item.startAt)))+'</span>'],
|
|
5789
|
+
["Duration",esc(durationText(item.durationMs))],
|
|
5790
|
+
["Tokens",esc(fmtTokens(item.tokensIn))+" in · "+esc(fmtTokens(item.tokensOut))+" out"+(item.cacheRead?" · "+esc(fmtTokens(item.cacheRead))+" read from cache":"")+(item.cacheWrite?" · "+esc(fmtTokens(item.cacheWrite))+" written to cache":"")],
|
|
5791
|
+
item.stopReason?["Stop reason",esc(item.stopReason)]:null,
|
|
5792
|
+
["Initiator",item.initiator.key?itemLink(item.initiator.key,item.initiator.label):esc(item.initiator.label)],
|
|
5793
|
+
["System prompt",(item.promptChars!==undefined?esc(item.promptChars.toLocaleString())+" characters":"—")+" · "+'<button type="button" class="net-link" data-net-pane="prompt">view</button>'],
|
|
5794
|
+
["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>'],
|
|
5795
|
+
["Runtime context",esc(count(item.context.length,"entry","entries"))+(item.context.length?" · "+'<button type="button" class="net-link" data-net-pane="context">view</button>':"")],
|
|
5796
|
+
["Tools offered",esc(item.toolNames.length)+(item.toolNames.length?" · "+'<button type="button" class="net-link" data-net-pane="tools">view</button>':"")],
|
|
5797
|
+
])
|
|
5798
|
+
+(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>':"")
|
|
5799
|
+
+((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>':"");
|
|
5800
|
+
}
|
|
5801
|
+
function toolDetail(item,run,pane){
|
|
5802
|
+
const base=new Date(runStartedAt(run)).getTime();
|
|
5803
|
+
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");
|
|
5804
|
+
if(pane==="result"){
|
|
5805
|
+
if(!item.result)return'<p class="dt-note">'+(item.status==="pending"?"Still running.":"No result recorded.")+'</p>';
|
|
5806
|
+
return kv([["Status",itemStatus(item)],item.result.message?["Message",esc(item.result.message)]:null,["Size",esc(fmtBytes(jsonSize(item.result.data)))]])+(typeof item.result.data==="string"&&!/^\s*[\[{]/.test(item.result.data)?'<pre class="dt-pre">'+esc(item.result.data)+'</pre>':jsonBlock(item.result.data,item.key+":result"));
|
|
5807
|
+
}
|
|
5808
|
+
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");
|
|
5809
|
+
if(item.kind==="subagent")return kv([["Subagent",esc(item.name)],["Status",itemStatus(item)],["Duration",esc(durationText(item.durationMs))],item.message?["Result",esc(item.message)]:null])+'<div class="dt-section">Prompt</div><pre class="dt-pre">'+esc(item.prompt||"")+'</pre>';
|
|
5810
|
+
return kv([
|
|
5811
|
+
item.id?["Call",'<span class="mono">'+esc(item.id)+'</span> '+copyButton(item.id,"call id")]:null,
|
|
5812
|
+
["Tool",esc(item.name)+(item.via==="repl"?' <span class="muted">· '+esc(item.fn||"")+'() from the REPL</span>':"")],
|
|
5813
|
+
["Status",itemStatus(item)],
|
|
5814
|
+
Number.isFinite(item.startAt)?["Started",esc(offsetFrom(base,isoAt(item.startAt)))]:null,
|
|
5815
|
+
["Duration",esc(durationText(item.durationMs))],
|
|
5816
|
+
["Called by",item.initiator.key?itemLink(item.initiator.key,item.initiator.label):esc(item.initiator.label)],
|
|
5817
|
+
item.approval?["Approval",'<span class="st '+(item.approval.status==="approved"?"ok":item.approval.status==="pending"?"warn":"err")+'">'+esc(item.approval.status)+'</span> <span class="muted">requested '+esc(fmtTime(item.approval.requestedAt))+(item.approval.settledAt?", settled "+esc(fmtTime(item.approval.settledAt)):"")+'</span>']:null,
|
|
5818
|
+
item.result?["Result",esc(fmtBytes(jsonSize(item.result.data)))+" · "+'<button type="button" class="net-link" data-net-pane="result">view</button>']:null,
|
|
5819
|
+
])+(item.via==="repl"?"":'<div class="dt-section">Input</div>'+jsonBlock(item.input,item.key+":overview-input"));
|
|
5820
|
+
}
|
|
5821
|
+
function netDetail(item,trace,run,view){
|
|
5822
|
+
const panes=detailPanes(item);const pane=panes.some(entry=>entry[0]===view.pane)?view.pane:"overview";
|
|
5823
|
+
const body=item.kind==="model"?modelDetail(item,trace,run,pane):toolDetail(item,run,pane);
|
|
5824
|
+
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>'
|
|
5825
|
+
+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("")
|
|
5826
|
+
+(item.kind==="model"&&item.request?'<span class="nd-actions">'+'<button type="button" class="button" data-copy="'+attr(requestJson(item))+'" title="The system prompt, messages, context and tools of this request as JSON">'+icon("copy")+'<span>Copy request</span></button></span>':"")
|
|
5827
|
+
+'</div><div class="nd-title"><b>'+esc(item.name)+'</b><span>'+esc(itemType(item))+(item.model?" · "+esc(item.model):"")+'</span></div><div class="nd-body" data-scroll-key="nd:'+attr(item.key+":"+pane)+'">'+body+'</div></aside>';
|
|
5828
|
+
}
|
|
5829
|
+
function runNetwork(run,trace,view){
|
|
5830
|
+
const term=state.network.filter.trim().toLowerCase();
|
|
5831
|
+
const visible=trace.items.filter(item=>netMatches(item,state.network.kind,term));
|
|
5832
|
+
const selected=trace.items.find(item=>item.key===view.item);
|
|
5833
|
+
const kinds=[["all","All"],["model","Model"],["tools","Tools"],["errors","Errors"]];
|
|
5834
|
+
const t=trace.totals;
|
|
5835
|
+
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>'
|
|
5836
|
+
+'<div class="dt-chips" role="group" aria-label="Request type">'+kinds.map(kind=>'<button type="button" class="dt-chip'+(state.network.kind===kind[0]?" active":"")+'" data-net-kind="'+kind[0]+'">'+kind[1]+'</button>').join("")+'</div></div>';
|
|
5837
|
+
html+='<div class="net-split'+(selected?" has-detail":"")+'"><div class="net-list" data-scroll-key="net-list">';
|
|
5838
|
+
if(!trace.items.length)html+=empty("No requests recorded","Model requests and tool calls appear here as the run makes them. Runs recorded before request tracing, or with observability.modelRequests off, list only tool calls and responses.");
|
|
5839
|
+
else html+='<table class="net-table">'+(selected?"":'<colgroup><col class="w-name"><col class="w-type"><col class="w-status"><col class="w-init"><col class="w-size"><col class="w-time"><col class="w-wf"></colgroup>')+'<thead><tr><th class="c-name">Name</th><th class="c-type">Type</th><th class="c-status">Status</th><th class="c-init">Initiator</th><th class="c-size" title="Tokens in → out for model requests, result size for tools">Size</th><th class="c-time">Time</th><th class="c-wf">Waterfall</th></tr></thead><tbody>'+visible.map(item=>netRow(item,trace,view.item)).join("")+'</tbody></table>'+(visible.length?"":empty("Nothing matches","Clear the filter to see every request."));
|
|
5840
|
+
html+='</div>'+(selected?netDetail(selected,trace,run,view):"")+'</div>';
|
|
5841
|
+
html+='<div class="net-foot"><span>'+(visible.length===trace.items.length?"":visible.length+" / ")+count(t.requests,"model request")+'</span><span>'+count(t.tools,"tool call")+'</span><span>'+esc(fmtTokens(t.tokensIn))+' in · '+esc(fmtTokens(t.tokensOut))+' out'+(t.cacheRead?" · "+esc(fmtTokens(t.cacheRead))+" cached":"")+'</span><span>model '+esc(durationText(t.modelMs))+' · tools '+esc(durationText(t.toolMs))+'</span>'+(t.errors?'<span class="st err">'+count(t.errors,"error")+'</span>':"")+'<span class="net-foot-right">finished in '+esc(durationText(runDurationMs(run)))+'</span></div>';
|
|
5842
|
+
return html;
|
|
5843
|
+
}
|
|
5844
|
+
|
|
5845
|
+
/* ---- Console ---- */
|
|
5846
|
+
const CONSOLE_LEVELS={default:["error","warn","info"],all:["error","warn","info","verbose"],warnings:["error","warn"],errors:["error"]};
|
|
5847
|
+
function revealKey(row){
|
|
5848
|
+
const type=String(row.type||"").replace(/^agent\./,"");const data=row.data||{};
|
|
5849
|
+
if(type==="model_request"||type==="model_request_end")return"m:"+data.request_id;
|
|
5850
|
+
if(type==="tool_use")return data.id?"t:"+data.id:"";
|
|
5851
|
+
if(type==="tool_use_result")return(data.id||data.call_id)?"t:"+(data.id||data.call_id):"";
|
|
5852
|
+
return"";
|
|
5853
|
+
}
|
|
5854
|
+
function consoleRow(row,base){
|
|
5855
|
+
const reveal=revealKey(row);
|
|
5856
|
+
const glyph=row.level==="error"||row.level==="warn"?icon("warning"):"";
|
|
5857
|
+
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>'
|
|
5858
|
+
+'<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>';
|
|
5859
|
+
}
|
|
5860
|
+
function runConsole(run,rows){
|
|
5861
|
+
const c=state.console;const levels=CONSOLE_LEVELS[c.level]||CONSOLE_LEVELS.default;const term=c.filter.trim().toLowerCase();
|
|
5862
|
+
const sources=[...new Set(rows.map(row=>row.source))].sort();
|
|
5863
|
+
const visible=rows.filter(row=>levels.includes(row.level)&&(c.source==="all"||row.source===c.source)&&(!term||(row.message+" "+row.type).toLowerCase().includes(term)));
|
|
5864
|
+
const shown=visible.slice(-1500);const base=new Date(runStartedAt(run)).getTime();
|
|
5865
|
+
const errors=rows.filter(row=>row.level==="error").length;const warnings=rows.filter(row=>row.level==="warn").length;const hidden=rows.length-visible.length;
|
|
5866
|
+
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>'
|
|
5867
|
+
+'<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>'
|
|
5868
|
+
+'<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>'
|
|
5869
|
+
+'<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>'
|
|
5870
|
+
+'<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>';
|
|
5871
|
+
}
|
|
5872
|
+
|
|
5873
|
+
/* ---- Context: what the agent had, like DevTools' Application panel. ---- */
|
|
5874
|
+
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"]];
|
|
5875
|
+
function runContext(run,trace,events,view){
|
|
5876
|
+
const models=trace.items.filter(item=>item.kind==="model"&&!item.legacy);
|
|
5877
|
+
const request=models.find(item=>item.id===view.request)||models.at(-1);
|
|
5878
|
+
const node=CONTEXT_NODES.some(entry=>entry[1]===view.node)?view.node:"prompt";
|
|
5879
|
+
const instance=state.instances.find(item=>item.id===run.agentId);
|
|
5880
|
+
const memoryEvents=events.filter(event=>event.category==="memory");
|
|
5881
|
+
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||""};
|
|
5882
|
+
let tree="";let group="";
|
|
5883
|
+
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>'});
|
|
5884
|
+
const scoped=["prompt","runtime","tools","messages"].includes(node);
|
|
5885
|
+
let body="";
|
|
5886
|
+
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.");
|
|
5887
|
+
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(""):"");
|
|
5888
|
+
else if(node==="runtime")body=modelDetail(request,trace,run,"context");
|
|
5889
|
+
else if(node==="tools")body=modelDetail(request,trace,run,"tools");
|
|
5890
|
+
else if(node==="messages")body=modelDetail(request,trace,run,"messages");
|
|
5891
|
+
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")}
|
|
5892
|
+
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");
|
|
5893
|
+
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.");
|
|
5894
|
+
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","");
|
|
5895
|
+
else if(node==="playbooks")body=instance?(instance.playbooks.length?jsonBlock(instance.playbooks,"ctx:playbooks"):empty("No playbooks","")):empty("Instance not found","");
|
|
5896
|
+
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.")}
|
|
5897
|
+
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."));
|
|
5898
|
+
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>':"";
|
|
5899
|
+
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>';
|
|
5900
|
+
}
|
|
5901
|
+
|
|
5902
|
+
/* ---- Summary ---- */
|
|
5903
|
+
function runSummary(run,events,trace){
|
|
5904
|
+
const slow=trace.items.filter(item=>Number.isFinite(item.durationMs)).sort((a,b)=>b.durationMs-a.durationMs).slice(0,5);
|
|
5905
|
+
const failed=trace.items.filter(item=>["error","aborted","denied","limit"].includes(item.status));
|
|
5906
|
+
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>';
|
|
5907
|
+
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");
|
|
5908
|
+
html+='</div><div class="grid cols-2">';
|
|
5909
|
+
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");
|
|
5910
|
+
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"));
|
|
5911
|
+
return html+'</div></div>';
|
|
5912
|
+
}
|
|
5913
|
+
|
|
5914
|
+
function renderRun(id){
|
|
5915
|
+
const run=state.runs.find(x=>x.id===id);if(!run)return renderNotFound("Run");
|
|
5916
|
+
const events=runEventsFor(id);const trace=buildRunTrace(events,run);const rows=buildConsole(events);const view=runView();
|
|
5917
|
+
crumbs([{label:"Runs",href:"/runs"},{label:short(id)}]);
|
|
5918
|
+
const actions=(isLiveRun(run)?'<button class="button danger" data-cancel>Cancel run</button>':"")
|
|
5919
|
+
+'<button class="button" data-copy="'+attr(run.id)+'">'+icon("copy")+'<span>Copy run id</span></button>'
|
|
5920
|
+
+'<button class="button" data-export-trace title="The run and every event, as JSON">'+icon("download")+'<span>Export trace</span></button>'
|
|
5921
|
+
+'<button class="button primary" data-rerun>'+icon("refresh")+'<span>Run again</span></button>';
|
|
5922
|
+
let html=pageHead("Run",run.agent+" · "+short(id),explainRun(run),actions);
|
|
5923
|
+
const failure=runErrorText(run);
|
|
5924
|
+
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>';
|
|
5925
|
+
html+=approvalRail(pendingApprovals(run.id),"This run is waiting for a decision");
|
|
5926
|
+
const t=trace.totals;
|
|
5927
|
+
html+='<div class="detail-strip">'
|
|
5928
|
+
+'<div><label>Status</label><strong>'+status(run.status)+'</strong></div>'
|
|
5929
|
+
+'<div><label>Duration</label><strong>'+durCell(run)+'</strong></div>'
|
|
5930
|
+
+'<div><label>Model requests</label><strong>'+esc(t.requests)+(t.errors?' <span class="st err">'+count(t.errors,"error")+'</span>':"")+'</strong></div>'
|
|
5931
|
+
+'<div><label>Tool calls</label><strong>'+esc(t.tools)+'</strong></div>'
|
|
5932
|
+
+'<div><label>Tokens</label><strong>'+esc(fmtTokens(t.tokensIn))+" in · "+esc(fmtTokens(t.tokensOut))+" out"+'</strong></div>'
|
|
5933
|
+
+'<div><label>Agent instance</label><strong>'+(run.agentId?'<a class="link mono" href="/instances/'+attr(run.agentId)+'" data-link>'+esc(short(run.agentId))+'</a>':"Not recorded")+'</strong></div>'
|
|
5934
|
+
+'</div>';
|
|
5935
|
+
const errors=rows.filter(row=>row.level==="error").length;const warnings=rows.filter(row=>row.level==="warn").length;
|
|
5936
|
+
const badge={network:trace.items.length?'<span class="dt-badge">'+trace.items.length+'</span>':"",console:(errors?'<span class="dt-badge err">'+errors+'</span>':"")+(warnings?'<span class="dt-badge warn">'+warnings+'</span>':"")};
|
|
5937
|
+
html+='<section class="devtools"><div class="dt-tabs" role="tablist" aria-label="Run views">'+RUN_TABS.map(tab=>'<button type="button" role="tab" class="dt-tab'+(view.tab===tab[0]?" active":"")+'" aria-selected="'+(view.tab===tab[0])+'" data-run-tab="'+tab[0]+'">'+icon(tab[2])+esc(tab[1])+(badge[tab[0]]||"")+'</button>').join("")
|
|
5938
|
+
+(isLiveRun(run)?'<span class="dt-live"><i class="pulse-dot"></i>Live</span>':"")+'<span class="dt-hint">1–4 views · j / k requests · / filter · Esc close</span></div><div class="dt-body dt-'+view.tab+'">'
|
|
5939
|
+
+(view.tab==="summary"?runSummary(run,events,trace):view.tab==="console"?runConsole(run,rows):view.tab==="context"?runContext(run,trace,events,view):runNetwork(run,trace,view))+'</div></section>';
|
|
5940
|
+
$("content").innerHTML=html;
|
|
5941
|
+
bindRun(id,run,trace,events);
|
|
5942
|
+
}
|
|
5943
|
+
function rerenderRun(id){const view=captureView();renderRun(id);restoreView(view)}
|
|
5944
|
+
function selectRunItem(id,key){if(!key)return;setRunView({tab:"network",item:key});rerenderRun(id);requestAnimationFrame(()=>document.querySelector('.net-row.selected')?.scrollIntoView({block:"nearest"}))}
|
|
5945
|
+
function bindRun(id,run,trace,events){
|
|
5946
|
+
document.querySelectorAll("[data-run-tab]").forEach(node=>node.onclick=()=>{setRunView({tab:node.dataset.runTab});rerenderRun(id)});
|
|
5947
|
+
document.querySelectorAll("[data-net-item]").forEach(node=>node.onclick=event=>{event.preventDefault();event.stopPropagation();selectRunItem(id,node.dataset.netItem)});
|
|
5948
|
+
document.querySelectorAll("[data-reveal]").forEach(node=>node.onclick=event=>{event.stopPropagation();selectRunItem(id,node.dataset.reveal)});
|
|
5949
|
+
document.querySelectorAll("[data-net-pane]").forEach(node=>node.onclick=()=>{setRunView({pane:node.dataset.netPane});rerenderRun(id)});
|
|
5950
|
+
document.querySelectorAll("[data-net-kind]").forEach(node=>node.onclick=()=>{state.network.kind=node.dataset.netKind;rerenderRun(id)});
|
|
5951
|
+
const close=document.querySelector("[data-net-close]");if(close)close.onclick=()=>{setRunView({item:"",pane:""});rerenderRun(id)};
|
|
5952
|
+
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{}}});
|
|
5953
|
+
keepTyping($("net-filter"),value=>{state.network.filter=value});
|
|
5954
|
+
keepTyping($("con-filter"),value=>{state.console.filter=value});
|
|
5955
|
+
const level=$("con-level");if(level)level.onchange=event=>{state.console.level=event.target.value;rerenderRun(id)};
|
|
5956
|
+
const source=$("con-source");if(source)source.onchange=event=>{state.console.source=event.target.value;rerenderRun(id)};
|
|
5957
|
+
document.querySelectorAll(".con-line").forEach(node=>node.onclick=()=>node.parentElement.classList.toggle("open"));
|
|
5958
|
+
document.querySelectorAll("[data-ctx-node]").forEach(node=>node.onclick=()=>{setRunView({node:node.dataset.ctxNode});rerenderRun(id)});
|
|
5959
|
+
const request=$("ctx-request");if(request)request.onchange=event=>{setRunView({request:event.target.value});rerenderRun(id)};
|
|
5960
|
+
const cancel=document.querySelector("[data-cancel]");if(cancel)cancel.onclick=()=>void cancelRun(id);
|
|
5961
|
+
const rerun=document.querySelector("[data-rerun]");
|
|
5962
|
+
if(rerun)rerun.onclick=()=>openRunDrawer(state.instances.find(x=>x.id===run.agentId)?.definitionId,run.agentId,typeof run.input?.message?.text==="string"?run.input.message.text:typeof run.input?.message==="string"?run.input.message:"");
|
|
5963
|
+
const exportButton=document.querySelector("[data-export-trace]");
|
|
5964
|
+
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")};
|
|
5965
|
+
dataLinks();
|
|
5966
|
+
}
|
|
5967
|
+
/* Keys on the run page: 1-4 switch views, j/k walk the requests, Esc closes the open one. */
|
|
5968
|
+
function runKeys(e){
|
|
5969
|
+
const current=route();if(current.section!=="runs"||!current.id)return false;
|
|
5970
|
+
const index=["1","2","3","4"].indexOf(e.key);
|
|
5971
|
+
if(index>=0){setRunView({tab:RUN_TABS[index][0]});rerenderRun(current.id);return true}
|
|
5972
|
+
const view=runView();
|
|
5973
|
+
if(view.tab==="network"&&(e.key==="j"||e.key==="k"||e.key==="ArrowDown"||e.key==="ArrowUp")){
|
|
5974
|
+
const rows=[...document.querySelectorAll(".net-row")];if(!rows.length)return false;
|
|
5975
|
+
const at=rows.findIndex(row=>row.dataset.netItem===view.item);
|
|
5976
|
+
const next=rows[Math.min(rows.length-1,Math.max(0,at<0?0:at+(e.key==="j"||e.key==="ArrowDown"?1:-1)))];
|
|
5977
|
+
e.preventDefault();selectRunItem(current.id,next.dataset.netItem);return true;
|
|
5978
|
+
}
|
|
5979
|
+
if(e.key==="Escape"&&view.item){setRunView({item:"",pane:""});rerenderRun(current.id);return true}
|
|
5980
|
+
return false;
|
|
5981
|
+
}
|
|
5982
|
+
`;
|
|
5983
|
+
|
|
5984
|
+
// src/dashboard-trace.ts
|
|
5985
|
+
var DASHBOARD_TRACE_SCRIPT = String.raw`
|
|
5986
|
+
function traceTime(iso){const t=Date.parse(iso);return Number.isFinite(t)?t:NaN}
|
|
5987
|
+
function traceType(event){return String(event.type||"").replace(/^agent\./,"")}
|
|
5988
|
+
function tracePreview(value,limit){
|
|
5989
|
+
let text;
|
|
5990
|
+
if(typeof value==="string")text=value;
|
|
5991
|
+
else{try{text=JSON.stringify(value)}catch{text=String(value)}}
|
|
5992
|
+
text=String(text??"").replace(/\s+/g," ").trim();
|
|
5993
|
+
return text.length>(limit||90)?text.slice(0,(limit||90)-1)+"…":text;
|
|
5994
|
+
}
|
|
5995
|
+
function buildRunTrace(events,run){
|
|
5996
|
+
const ordered=[...(events||[])].sort((a,b)=>(a.sequence??0)-(b.sequence??0));
|
|
5997
|
+
const prompts={},toolSets={},requests={},calls={},items=[],pendingByName={};
|
|
5998
|
+
const totals={requests:0,tools:0,tokensIn:0,tokensOut:0,cacheRead:0,cacheWrite:0,modelMs:0,toolMs:0,errors:0};
|
|
5999
|
+
let open=null,previous=null,first=NaN,last=NaN;
|
|
6000
|
+
const runStart=run?traceTime(run.startedAt||run.createdAt):NaN;
|
|
6001
|
+
const runEnd=run&&run.completedAt?traceTime(run.completedAt):NaN;
|
|
6002
|
+
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};
|
|
6003
|
+
const addTool=(item)=>{totals.tools++;items.push(item);(pendingByName[item.name]=pendingByName[item.name]||[]).push(item);return item};
|
|
6004
|
+
for(const event of ordered){
|
|
6005
|
+
const at=traceTime(event.timestamp);
|
|
6006
|
+
if(Number.isFinite(at)){if(!(at>=first))first=at;if(!(at<=last))last=at}
|
|
6007
|
+
const type=traceType(event);const data=event.data||{};
|
|
6008
|
+
if(type==="model_request"){
|
|
6009
|
+
if(data.system_prompt&&typeof data.system_prompt.text==="string")prompts[data.system_prompt.hash]=data.system_prompt.text;
|
|
6010
|
+
if(data.tools&&data.tools.list)toolSets[data.tools.hash]=data.tools.list;
|
|
6011
|
+
const traced=data.messages||{};const added=traced.added||[];
|
|
6012
|
+
const base=traced.base?requests[traced.base]:null;const kept=traced.kept||0;
|
|
6013
|
+
const prefix=base?base.messages.slice(0,kept):Array.from({length:kept},()=>null);
|
|
6014
|
+
while(prefix.length<kept)prefix.push(null);
|
|
6015
|
+
const messages=prefix.concat(Array.from({length:traced.skipped||0},()=>null),added);
|
|
6016
|
+
let newFrom=messages.length-added.length;
|
|
6017
|
+
// A run's first request carries the conversation so far; what's new starts at the run's own message.
|
|
6018
|
+
if(!base)for(let i=messages.length-1;i>=0;i--){const m=messages[i];if(m&&m.sender==="user"&&!m.framework_context&&!(m.tool_results||[]).length&&!m.is_compaction){newFrom=i;break}}
|
|
6019
|
+
const initiator=data.purpose==="compaction"?{label:"compaction"}:previous&&previous.calls.length?{label:"after "+[...new Set(previous.calls.map(id=>calls[id]&&calls[id].name).filter(Boolean))].join(", "),key:previous.key}:previous?{label:"continues #"+previous.index,key:previous.key}:{label:"run input"};
|
|
6020
|
+
const item={kind:"model",key:"m:"+data.request_id,id:data.request_id,index:++totals.requests,name:"#"+(totals.requests)+" "+(data.purpose==="compaction"?"compaction":"request"),model:data.model||"",purpose:data.purpose||"turn",status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:data,end:null,promptHash:data.system_prompt&&data.system_prompt.hash,promptChars:data.system_prompt&&data.system_prompt.chars,toolsHash:data.tools&&data.tools.hash,toolNames:(data.tools&&data.tools.names)||[],messages,newFrom,context:data.context||[],response:[],calls:[],initiator,events:[event]};
|
|
6021
|
+
requests[data.request_id]=item;items.push(item);open=item;previous=item;continue;
|
|
6022
|
+
}
|
|
6023
|
+
if(type==="model_request_end"){
|
|
6024
|
+
const item=requests[data.request_id];if(!item)continue;
|
|
6025
|
+
item.end=data;item.events.push(event);item.status=data.status||"success";item.endAt=at;
|
|
6026
|
+
item.durationMs=Number.isFinite(data.duration_ms)?data.duration_ms:at-item.startAt;
|
|
6027
|
+
if(Number.isFinite(data.duration_ms)&&Number.isFinite(at))item.startAt=at-data.duration_ms;
|
|
6028
|
+
item.tokensIn=data.tokens_in;item.tokensOut=data.tokens_out;item.cacheRead=data.cache_read_input_tokens;item.cacheWrite=data.cache_creation_input_tokens;
|
|
6029
|
+
item.response=data.response||[];item.error=data.error;
|
|
6030
|
+
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;
|
|
6031
|
+
if(Number.isFinite(item.durationMs))totals.modelMs+=item.durationMs;
|
|
6032
|
+
if(item.status!=="success")totals.errors++;
|
|
6033
|
+
for(const message of item.response)for(const call of message.tool_calls||[]){
|
|
6034
|
+
if(!call.id)continue;
|
|
6035
|
+
item.calls.push(call.id);calls[call.id]=calls[call.id]||{name:call.tool_name,request:item};
|
|
6036
|
+
// Adapters that don't stream tool_use: the call starts when the response arrives.
|
|
6037
|
+
if(!calls[call.id].item)calls[call.id].item=addTool({kind:"tool",key:"t:"+call.id,id:call.id,name:call.tool_name,input:call.input_args,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:item.key,initiator:{label:"#"+item.index+" "+(item.purpose==="compaction"?"compaction":"request"),key:item.key},events:[]});
|
|
6038
|
+
}
|
|
6039
|
+
if(open===item)open=null;continue;
|
|
6040
|
+
}
|
|
6041
|
+
if(type==="model_response_complete"||type==="model_response"){
|
|
6042
|
+
const target=open||previous;
|
|
6043
|
+
if(target&&(target===open||!target.stopReason)){target.stopReason=data.stop_reason;target.events.push(event);continue}
|
|
6044
|
+
if(!target){
|
|
6045
|
+
// A runtime without request events: the response is all there is.
|
|
6046
|
+
const item={kind:"model",key:"m:"+(event.id||event.sequence),id:String(event.id||event.sequence),index:++totals.requests,name:"#"+totals.requests+" response",model:"",purpose:"turn",status:"success",startAt:at,endAt:at,durationMs:NaN,sequence:event.sequence,request:null,end:null,messages:[],newFrom:0,context:[],response:[{sender:"agent",text:data.text||"",tool_calls:data.tool_calls}],calls:[],toolNames:[],initiator:{label:"run"},stopReason:data.stop_reason,tokensIn:data.tokens_in,tokensOut:data.tokens_out,events:[event],legacy:true};
|
|
6047
|
+
totals.tokensIn+=data.tokens_in||0;totals.tokensOut+=data.tokens_out||0;items.push(item);
|
|
6048
|
+
}
|
|
6049
|
+
continue;
|
|
6050
|
+
}
|
|
6051
|
+
if(type==="tool_use"){
|
|
6052
|
+
const request=open||previous;
|
|
6053
|
+
const item=addTool({kind:"tool",key:"t:"+(data.id||event.id||event.sequence),id:data.id,name:data.name||"tool",input:data.input,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:request?request.key:null,initiator:request?{label:"#"+request.index+" "+(request.purpose==="compaction"?"compaction":"request"),key:request.key}:{label:"model"},events:[event]});
|
|
6054
|
+
if(data.id){calls[data.id]=calls[data.id]||{name:item.name,request};calls[data.id].item=item}
|
|
6055
|
+
continue;
|
|
6056
|
+
}
|
|
6057
|
+
if(type==="tool_use_result"){
|
|
6058
|
+
const id=data.id||data.call_id;const name=data.name||data.tool_name||"tool";
|
|
6059
|
+
let item=id&&calls[id]&&calls[id].item;
|
|
6060
|
+
const queue=pendingByName[name]||[];
|
|
6061
|
+
if(!item)item=queue.find(candidate=>candidate.status==="pending"&&!candidate.via);
|
|
6062
|
+
if(!item)item=addTool({kind:"tool",key:"t:"+(id||event.id||event.sequence),id,name,input:undefined,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:null,initiator:{label:"model"},events:[]});
|
|
6063
|
+
const index=queue.indexOf(item);if(index>=0)queue.splice(index,1);
|
|
6064
|
+
item.events.push(event);item.result=data.result||{};item.status=(data.result&&data.result.status)||"success";item.endAt=at;
|
|
6065
|
+
item.durationMs=Number.isFinite(data.duration_ms)?data.duration_ms:at-item.startAt;
|
|
6066
|
+
if(Number.isFinite(data.duration_ms)&&Number.isFinite(at))item.startAt=at-data.duration_ms;
|
|
6067
|
+
if(Number.isFinite(item.durationMs))totals.toolMs+=item.durationMs;
|
|
6068
|
+
if(item.status==="error")totals.errors++;
|
|
6069
|
+
continue;
|
|
6070
|
+
}
|
|
6071
|
+
if(/^foundry\.approval\./.test(type)){
|
|
6072
|
+
const name=data.toolName;const queue=pendingByName[name]||[];
|
|
6073
|
+
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)}}
|
|
6074
|
+
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)}}
|
|
6075
|
+
continue;
|
|
6076
|
+
}
|
|
6077
|
+
if(/^foundry\.repl\.programmatic-tool\./.test(type)){
|
|
6078
|
+
const name=data.tool||"tool";
|
|
6079
|
+
if(type==="foundry.repl.programmatic-tool.started"){const parent=runningTool();addTool({kind:"tool",via:"repl",key:"p:"+(event.id||event.sequence),name,fn:data.function,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,request:parent?parent.request:null,initiator:parent?{label:parent.name+" (REPL)",key:parent.key}:{label:"REPL"},events:[event]});continue}
|
|
6080
|
+
const item=[...items].reverse().find(candidate=>candidate.via==="repl"&&candidate.name===name&&candidate.status==="pending");
|
|
6081
|
+
if(item){item.events.push(event);item.endAt=at;item.durationMs=data.durationMs;item.status=type.endsWith("completed")?"success":type.endsWith("failed")?"error":"denied";if(Number.isFinite(data.durationMs)&&Number.isFinite(at))item.startAt=at-data.durationMs;if(item.status!=="success")totals.errors++}
|
|
6082
|
+
else if(!type.endsWith("completed")){totals.tools++;totals.errors++;items.push({kind:"tool",via:"repl",key:"p:"+(event.id||event.sequence),name,fn:data.function,status:type.split(".").pop(),startAt:at,endAt:at,durationMs:0,sequence:event.sequence,initiator:{label:"REPL"},result:{status:"error",message:data.reason},events:[event]})}
|
|
6083
|
+
continue;
|
|
6084
|
+
}
|
|
6085
|
+
if(type==="subagent_invoked"){items.push({kind:"subagent",key:"s:"+(event.id||event.sequence),name:data.name,prompt:data.prompt,status:"pending",startAt:at,endAt:NaN,durationMs:NaN,sequence:event.sequence,initiator:{label:"subagent"},events:[event]});continue}
|
|
6086
|
+
if(type==="subagent_completed"){const item=[...items].reverse().find(candidate=>candidate.kind==="subagent"&&candidate.name===data.name&&candidate.status==="pending");if(item){item.status=data.status||"success";item.endAt=at;item.durationMs=at-item.startAt;item.message=data.message;item.events.push(event)}continue}
|
|
6087
|
+
}
|
|
6088
|
+
const start=Number.isFinite(runStart)?Math.min(runStart,Number.isFinite(first)?first:runStart):first;
|
|
6089
|
+
const live=run&&(run.status==="running"||run.status==="pending");
|
|
6090
|
+
const end=live?Math.max(Date.now(),Number.isFinite(last)?last:0):Number.isFinite(runEnd)?Math.max(runEnd,Number.isFinite(last)?last:runEnd):last;
|
|
6091
|
+
for(const item of items){if(item.kind==="model"){item.systemPrompt=prompts[item.promptHash];item.tools=toolSets[item.toolsHash]}}
|
|
6092
|
+
return{items,prompts,toolSets,totals,start,end};
|
|
6093
|
+
}
|
|
6094
|
+
|
|
6095
|
+
/* Console levels follow DevTools: errors, warnings, info, and verbose detail hidden by default. */
|
|
6096
|
+
function describeEvent(event){
|
|
6097
|
+
const type=traceType(event);const data=event.data||{};
|
|
6098
|
+
const level=(value,message,source)=>({level:value,message,source:source||event.category||"system"});
|
|
6099
|
+
if(type==="log.stderr")return level("warn",String(data.message??""),"stderr");
|
|
6100
|
+
if(type==="log.stdout")return level("info",String(data.message??""),"stdout");
|
|
6101
|
+
if(type==="run.failed")return level("error","Run failed"+(data.error?": "+data.error:""));
|
|
6102
|
+
if(type==="run.timeout")return level("error","Run timed out");
|
|
6103
|
+
if(type==="run.cancelled")return level("warn","Run cancelled");
|
|
6104
|
+
if(type==="run.retry")return level("warn","Retrying: attempt "+data.attempt+" of "+data.maxAttempts);
|
|
6105
|
+
if(/^run\./.test(type))return level("info","Run "+type.slice(4).replace(/-/g," "));
|
|
6106
|
+
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":""))}
|
|
6107
|
+
if(type==="model_request_end"){
|
|
6108
|
+
if(data.status==="error")return level("error","← Model request failed after "+data.duration_ms+"ms: "+(data.error||"unknown error"));
|
|
6109
|
+
if(data.status==="aborted")return level("warn","← Model request aborted after "+data.duration_ms+"ms");
|
|
6110
|
+
const calls=(data.response||[]).reduce((n,m)=>n+(m.tool_calls||[]).length,0);
|
|
6111
|
+
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"):""));
|
|
6112
|
+
}
|
|
6113
|
+
if(type==="model_response_complete"||type==="model_response")return level("verbose","Response"+(data.stop_reason?" ("+data.stop_reason+")":"")+": "+tracePreview(data.text||"",120));
|
|
6114
|
+
if(type==="text_delta")return level("verbose","Streamed text: "+tracePreview(data.text,160));
|
|
6115
|
+
if(type==="tool_use")return level("info","Tool call "+data.name+"("+tracePreview(data.input,100)+")");
|
|
6116
|
+
if(type==="tool_use_result"){
|
|
6117
|
+
const status=data.result&&data.result.status;const name=data.name||data.tool_name;const time=Number.isFinite(data.duration_ms)?" in "+data.duration_ms+"ms":"";
|
|
6118
|
+
if(status==="error")return level("error",name+" failed"+time+": "+tracePreview(data.result.message||data.result.data,140));
|
|
6119
|
+
if(status==="aborted")return level("warn",name+" aborted"+time);
|
|
6120
|
+
return level("info",name+" returned"+time+": "+tracePreview(data.result&&data.result.data,120));
|
|
6121
|
+
}
|
|
6122
|
+
if(type==="token_consumption")return level("verbose","Tokens: "+tracePreview(data.consumption,120));
|
|
6123
|
+
if(type==="runtime_context")return level("verbose","Runtime context: "+(data.messages||[]).map(m=>tracePreview(m.text,60)).join(" | "));
|
|
6124
|
+
if(type==="compaction_start")return level("info","Compacting the conversation at "+data.current_token_consumption+" tokens");
|
|
6125
|
+
if(type==="compaction_end")return level("info","Compaction finished");
|
|
6126
|
+
if(type==="foundry.approval.requested")return level("warn","Waiting for approval: "+data.toolName+"("+tracePreview(data.toolInput,80)+")");
|
|
6127
|
+
if(type==="foundry.approval.settled")return level(data.status==="approved"?"info":"warn","Approval "+data.status+": "+data.toolName);
|
|
6128
|
+
if(type==="foundry.approval.failed"||type==="foundry.approval.unavailable")return level("error","Approval "+type.split(".").pop()+": "+(data.toolName||"")+(data.error?" · "+data.error:""));
|
|
6129
|
+
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:""))}
|
|
6130
|
+
if(type==="hook_invoked")return level("info","Hook /"+data.name);
|
|
6131
|
+
if(type==="skill_invoked")return level("info","Skill "+data.name+" ("+data.source+")");
|
|
6132
|
+
if(type==="subagent_invoked")return level("info","Subagent "+data.name+": "+tracePreview(data.prompt,100));
|
|
6133
|
+
if(type==="subagent_completed")return level(data.status==="error"?"error":"info","Subagent "+data.name+" "+data.status+(data.message?": "+tracePreview(data.message,100):""));
|
|
6134
|
+
if(type==="foundry.guidance.state")return level("verbose","Guidance state");
|
|
6135
|
+
if(/fail|error/.test(type))return level("error",type+(data.error?": "+tracePreview(data.error,140):""));
|
|
6136
|
+
if(/denied|limit|warn|unavailable/.test(type))return level("warn",type);
|
|
6137
|
+
if(/^foundry\.(assembly|definition|layer|subscriber|repl|mesh|working-environment|installation|application)\./.test(type))return level("verbose",type.replace(/^foundry\./,""),"assembly");
|
|
6138
|
+
return level("verbose",type);
|
|
6139
|
+
}
|
|
6140
|
+
function buildConsole(events){
|
|
6141
|
+
const rows=[];let stream=null;
|
|
6142
|
+
for(const event of [...(events||[])].sort((a,b)=>(a.sequence??0)-(b.sequence??0))){
|
|
6143
|
+
if(traceType(event)==="text_delta"){
|
|
6144
|
+
if(!stream){stream={key:"c:"+(event.id||event.sequence),level:"verbose",source:"model",timestamp:event.timestamp,type:"text_delta",text:"",chunks:0,events:[]};rows.push(stream)}
|
|
6145
|
+
stream.text+=String((event.data&&event.data.text)||"");stream.chunks++;stream.events.push(event);
|
|
6146
|
+
stream.message="Streamed text ("+stream.chunks+" chunk"+(stream.chunks===1?"":"s")+"): "+tracePreview(stream.text,160);
|
|
6147
|
+
stream.data={text:stream.text,chunks:stream.chunks};
|
|
6148
|
+
continue;
|
|
6149
|
+
}
|
|
6150
|
+
stream=null;
|
|
6151
|
+
const described=describeEvent(event);
|
|
6152
|
+
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]});
|
|
6153
|
+
}
|
|
6154
|
+
return rows;
|
|
6155
|
+
}
|
|
6156
|
+
`;
|
|
6157
|
+
|
|
4538
6158
|
// src/dashboard-script.ts
|
|
4539
6159
|
var ICON_PATHS_JSON = JSON.stringify(PHOSPHOR_ICON_PATHS);
|
|
4540
6160
|
var DASHBOARD_SCRIPT = String.raw`
|
|
4541
6161
|
const ICON_PATHS=${ICON_PATHS_JSON};
|
|
4542
|
-
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},
|
|
6162
|
+
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};
|
|
4543
6163
|
const $=id=>document.getElementById(id);
|
|
4544
6164
|
const esc=value=>String(value??"").replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">","\"":""","'":"'"}[c]));
|
|
4545
6165
|
const attr=value=>esc(value).replace(/\x60/g,"`");
|
|
@@ -4613,6 +6233,8 @@ async function copyValue(button){
|
|
|
4613
6233
|
}catch{toast("Could not copy to the clipboard")}
|
|
4614
6234
|
}
|
|
4615
6235
|
|
|
6236
|
+
${DASHBOARD_TRACE_SCRIPT}
|
|
6237
|
+
${DASHBOARD_RUN_SCRIPT}
|
|
4616
6238
|
/* ---- View state. Live updates repaint the page, so the parts a person is
|
|
4617
6239
|
actively using -- scroll, focus, caret, expanded rows -- survive it. ---- */
|
|
4618
6240
|
function captureView(){
|
|
@@ -4624,13 +6246,17 @@ function captureView(){
|
|
|
4624
6246
|
caret:active&&typeof active.selectionStart==="number"?active.selectionStart:null,
|
|
4625
6247
|
open:[...document.querySelectorAll("[data-event-key].open")].map(node=>node.dataset.eventKey),
|
|
4626
6248
|
details:[...document.querySelectorAll("details[data-persist]")].filter(node=>node.open).map(node=>node.dataset.persist),
|
|
6249
|
+
closed:[...document.querySelectorAll("details[data-persist]")].filter(node=>!node.open).map(node=>node.dataset.persist),
|
|
6250
|
+
scrolls:[...document.querySelectorAll("[data-scroll-key]")].map(node=>({key:node.dataset.scrollKey,top:node.scrollTop,bottom:node.scrollHeight-node.scrollTop-node.clientHeight<40})),
|
|
4627
6251
|
chatScroll:chatScroll?{top:chatScroll.scrollTop,nearBottom:chatScroll.scrollHeight-chatScroll.scrollTop-chatScroll.clientHeight<80}:null
|
|
4628
6252
|
};
|
|
4629
6253
|
}
|
|
4630
6254
|
function restoreView(view){
|
|
4631
6255
|
if(!view)return;
|
|
4632
6256
|
if(view.open.length)document.querySelectorAll("[data-event-key]").forEach(node=>{if(view.open.includes(node.dataset.eventKey))node.classList.add("open")});
|
|
4633
|
-
if(view.details.length)document.querySelectorAll("details[data-persist]").forEach(node=>{if(view.details.includes(node.dataset.persist))node.open=true});
|
|
6257
|
+
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});
|
|
6258
|
+
/* Panes that scroll on their own keep their place; a live console that was at the bottom stays there. */
|
|
6259
|
+
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});
|
|
4634
6260
|
if(view.focus){
|
|
4635
6261
|
const node=$(view.focus);
|
|
4636
6262
|
if(node&&node!==document.activeElement){
|
|
@@ -4712,7 +6338,7 @@ function recent(array){return[...array].sort((a,b)=>String(b.updatedAt||b.create
|
|
|
4712
6338
|
function approvalRail(approvals,heading){
|
|
4713
6339
|
if(!approvals.length)return"";
|
|
4714
6340
|
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">'
|
|
4715
|
-
+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("")
|
|
6341
|
+
+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("")
|
|
4716
6342
|
+'</div></section>';
|
|
4717
6343
|
}
|
|
4718
6344
|
function explainRun(run){
|
|
@@ -4723,6 +6349,7 @@ function explainRun(run){
|
|
|
4723
6349
|
if(source==="spawn")return"Spawned by another agent run.";
|
|
4724
6350
|
if(source==="background")return"Continued as background work.";
|
|
4725
6351
|
if(source==="delegation")return"Delegated work, or a delegation result or question coming back.";
|
|
6352
|
+
if(source==="mesh")return"A message from another agent on the mesh, or its reply coming back.";
|
|
4726
6353
|
if(run.status==="completed")return"The agent completed the requested work.";
|
|
4727
6354
|
return"The agent is processing a direct message.";
|
|
4728
6355
|
}
|
|
@@ -4753,7 +6380,7 @@ function renderAgents(){
|
|
|
4753
6380
|
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>');
|
|
4754
6381
|
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>';
|
|
4755
6382
|
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>';
|
|
4756
|
-
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("");
|
|
6383
|
+
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("");
|
|
4757
6384
|
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"));
|
|
4758
6385
|
$("content").innerHTML=html;document.querySelectorAll("[data-new-run]").forEach(x=>x.onclick=openRunDrawer);dataLinks();
|
|
4759
6386
|
}
|
|
@@ -4778,7 +6405,7 @@ function renderInstance(id){
|
|
|
4778
6405
|
const instance=state.instances.find(x=>x.id===id);if(!instance)return renderNotFound("Agent instance");
|
|
4779
6406
|
crumbs([{label:"Agents",href:"/agents"},{label:instance.definitionId,href:"/agents/"+instance.definitionId},{label:short(id)}]);
|
|
4780
6407
|
const conversations=state.conversations[id]||[];const runs=recent(state.runs.filter(x=>x.agentId===id));
|
|
4781
|
-
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>');
|
|
6408
|
+
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>');
|
|
4782
6409
|
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>';
|
|
4783
6410
|
html+='<div class="grid cols-2">';
|
|
4784
6411
|
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("");
|
|
@@ -4857,14 +6484,14 @@ function renderChat(){
|
|
|
4857
6484
|
const streaming=state.chat.historyOffset===null?liveAssistantMessage(run):null;if(streaming)messages.push(streaming);
|
|
4858
6485
|
let html='<section class="chat-shell">';
|
|
4859
6486
|
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>';
|
|
4860
|
-
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>';
|
|
6487
|
+
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>';
|
|
4861
6488
|
html+='<label class="session-search">'+icon("search")+'<input id="chat-search" value="'+attr(state.chat.query)+'" placeholder="Search conversations" /></label>';
|
|
4862
6489
|
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>';
|
|
4863
6490
|
html+='<section class="conversation-pane">';
|
|
4864
6491
|
if(!conversation){
|
|
4865
6492
|
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>';
|
|
4866
6493
|
}else{
|
|
4867
|
-
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>';
|
|
6494
|
+
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>';
|
|
4868
6495
|
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>';
|
|
4869
6496
|
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>':"";
|
|
4870
6497
|
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>';
|
|
@@ -5015,11 +6642,6 @@ function phaseData(run,events){
|
|
|
5015
6642
|
{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)/)}
|
|
5016
6643
|
];
|
|
5017
6644
|
}
|
|
5018
|
-
function eventOffset(run,event){
|
|
5019
|
-
const base=new Date(run.createdAt).getTime();const at=new Date(event.timestamp).getTime();
|
|
5020
|
-
if(!Number.isFinite(base)||!Number.isFinite(at))return"";
|
|
5021
|
-
return"+"+durationText(Math.max(0,at-base));
|
|
5022
|
-
}
|
|
5023
6645
|
function runErrorText(run){
|
|
5024
6646
|
if(run.status!=="failed")return"";
|
|
5025
6647
|
if(typeof run.error==="string")return run.error;
|
|
@@ -5038,51 +6660,6 @@ function guidanceCard(events){
|
|
|
5038
6660
|
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>';
|
|
5039
6661
|
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>';
|
|
5040
6662
|
}
|
|
5041
|
-
function renderRun(id){
|
|
5042
|
-
const run=state.runs.find(x=>x.id===id);if(!run)return renderNotFound("Run");
|
|
5043
|
-
const events=eventsFor(id);
|
|
5044
|
-
const categories=[...new Set(events.map(event=>event.category))].filter(Boolean).sort();
|
|
5045
|
-
let visibleEvents=state.showAllEvents?events:events.filter(isKeyRunEvent);
|
|
5046
|
-
if(state.eventCategory!=="all")visibleEvents=visibleEvents.filter(event=>event.category===state.eventCategory);
|
|
5047
|
-
crumbs([{label:"Runs",href:"/runs"},{label:short(id)}]);
|
|
5048
|
-
const actions=(isLiveRun(run)?'<button class="button danger" data-cancel>Cancel run</button>':"")
|
|
5049
|
-
+'<button class="button" data-copy="'+attr(run.id)+'">'+icon("copy")+'<span>Copy run id</span></button>'
|
|
5050
|
-
+'<button class="button primary" data-rerun>'+icon("refresh")+'<span>Run again</span></button>';
|
|
5051
|
-
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);
|
|
5052
|
-
const failure=runErrorText(run);
|
|
5053
|
-
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>';
|
|
5054
|
-
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>';
|
|
5055
|
-
html+=approvalRail(pendingApprovals(run.id),"This run is waiting for a decision");
|
|
5056
|
-
html+=guidanceCard(events);
|
|
5057
|
-
html+='<div class="detail-strip">'
|
|
5058
|
-
+'<div><label>Status</label><strong>'+status(run.status)+'</strong></div>'
|
|
5059
|
-
+'<div><label>Duration</label><strong>'+durCell(run)+'</strong></div>'
|
|
5060
|
-
+'<div><label>Source</label><strong>'+esc(runSource(run))+'</strong></div>'
|
|
5061
|
-
+'<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>'
|
|
5062
|
-
+'<div><label>Attempts</label><strong>'+run.attempts+" of "+run.maxAttempts+'</strong></div>'
|
|
5063
|
-
+'</div>';
|
|
5064
|
-
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>';
|
|
5065
|
-
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");
|
|
5066
|
-
html+='</div>';
|
|
5067
|
-
const eventRows=visibleEvents.map((event,index)=>{
|
|
5068
|
-
const key=event.id||event.type+":"+event.timestamp+":"+index;
|
|
5069
|
-
return'<div class="event-row" data-event-key="'+attr(key)+'">'
|
|
5070
|
-
+'<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>'
|
|
5071
|
-
+'<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>';
|
|
5072
|
-
}).join("");
|
|
5073
|
-
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>':"";
|
|
5074
|
-
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>';
|
|
5075
|
-
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"));
|
|
5076
|
-
$("content").innerHTML=html;
|
|
5077
|
-
document.querySelectorAll(".event-toggle").forEach(node=>node.onclick=()=>node.parentElement.classList.toggle("open"));
|
|
5078
|
-
document.querySelectorAll("[data-category]").forEach(node=>node.onclick=()=>{state.eventCategory=node.dataset.category;renderRun(id)});
|
|
5079
|
-
document.querySelector("[data-toggle-events]").onclick=()=>{state.showAllEvents=!state.showAllEvents;renderRun(id)};
|
|
5080
|
-
const cancel=document.querySelector("[data-cancel]");if(cancel)cancel.onclick=()=>void cancelRun(id);
|
|
5081
|
-
const rerun=document.querySelector("[data-rerun]");
|
|
5082
|
-
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:"");
|
|
5083
|
-
dataLinks();
|
|
5084
|
-
}
|
|
5085
|
-
|
|
5086
6663
|
function renderAutomations(){
|
|
5087
6664
|
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.","");
|
|
5088
6665
|
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>';
|
|
@@ -5143,6 +6720,21 @@ function renderWorkspacePanel(data){
|
|
|
5143
6720
|
$("workspace-panel").innerHTML=card(active[0].toUpperCase()+active.slice(1),'<div class="card-body">'+body+'</div>',count(values.length,"item"));
|
|
5144
6721
|
}
|
|
5145
6722
|
|
|
6723
|
+
function renderApproval(id){
|
|
6724
|
+
const item=state.approvals.find(x=>x.id===id);if(!item)return renderNotFound("Approval");
|
|
6725
|
+
crumbs([{label:"Runs",href:"/runs"},{label:"Approval "+short(id)}]);
|
|
6726
|
+
const open=item.status==="pending";
|
|
6727
|
+
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>');
|
|
6728
|
+
html+=open?approvalRail([item],"Decide this request"):'<pre class="approval-input">'+esc(jsonText(item.toolInput))+'</pre>';
|
|
6729
|
+
html+='<div class="detail-strip">'
|
|
6730
|
+
+'<div><label>Status</label><strong>'+status(item.status)+'</strong></div>'
|
|
6731
|
+
+'<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>'
|
|
6732
|
+
+'<div><label>Requested</label><strong>'+relCell(item.requestedAt)+'</strong></div>'
|
|
6733
|
+
+'<div><label>'+(open?"Expires":"Decided")+'</label><strong>'+relCell(open?item.expiresAt:item.resolvedAt)+'</strong></div>'
|
|
6734
|
+
+(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>':"")
|
|
6735
|
+
+'</div>';
|
|
6736
|
+
$("content").innerHTML=html;dataLinks();
|
|
6737
|
+
}
|
|
5146
6738
|
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()}
|
|
5147
6739
|
async function loadBase(){
|
|
5148
6740
|
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"];
|
|
@@ -5170,6 +6762,7 @@ async function refreshActivity(){
|
|
|
5170
6762
|
const endpoints=["/api/agent-instances","/api/playbook-subscriptions","/api/application-connections","/api/runs","/api/events","/api/activations","/api/approvals","/health"];
|
|
5171
6763
|
const values=await Promise.all(endpoints.map(url=>api(url)));
|
|
5172
6764
|
[state.instances,state.subscriptions,state.connections,state.runs,state.events,state.activations,state.approvals,state.health]=values;
|
|
6765
|
+
const current=route();if(current.section==="runs"&¤t.id)await ensureRunEvents(current.id);
|
|
5173
6766
|
renderHealth();
|
|
5174
6767
|
$("event-state").textContent="Live updates";
|
|
5175
6768
|
await navigate(false,true);
|
|
@@ -5187,8 +6780,9 @@ async function navigate(load=true,preserve=false){
|
|
|
5187
6780
|
try{
|
|
5188
6781
|
if(load&¤t.section==="instances"&¤t.id)await ensureConversations(current.id);
|
|
5189
6782
|
if(load&¤t.section==="workspaces"&¤t.id)await ensureWorkspace(current.id);
|
|
6783
|
+
if(load&¤t.section==="runs"&¤t.id)await ensureRunEvents(current.id);
|
|
5190
6784
|
if(current.section==="chat")await loadChat(current);
|
|
5191
|
-
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");
|
|
6785
|
+
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"&¤t.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");
|
|
5192
6786
|
}catch(error){$("content").innerHTML='<div class="form-error">'+esc(error.message)+'</div>';console.error(error)}
|
|
5193
6787
|
restoreView(view);
|
|
5194
6788
|
tickTimes();
|
|
@@ -5244,13 +6838,15 @@ $("new-run").onclick=()=>openRunDrawer();$("close-drawer").onclick=closeRunDrawe
|
|
|
5244
6838
|
$("run-message").addEventListener("keydown",e=>{if((e.metaKey||e.ctrlKey)&&e.key==="Enter"){e.preventDefault();$("run-form").requestSubmit()}});
|
|
5245
6839
|
document.addEventListener("keydown",e=>{
|
|
5246
6840
|
if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==="k"){e.preventDefault();openSearch();return}
|
|
5247
|
-
|
|
5248
|
-
if(e.
|
|
5249
|
-
if(
|
|
6841
|
+
const modal=$("drawer").classList.contains("open")||$("search-modal").classList.contains("open");
|
|
6842
|
+
if(e.key==="Escape"&&modal){closeSearch();closeRunDrawer();return}
|
|
6843
|
+
if(e.key==="Escape"&&isTyping()){document.activeElement.blur();return}
|
|
6844
|
+
if(e.metaKey||e.ctrlKey||e.altKey||isTyping()||modal)return;
|
|
6845
|
+
if(runKeys(e)){e.preventDefault();return}
|
|
5250
6846
|
if(e.key==="j"){e.preventDefault();moveCursor(1)}
|
|
5251
6847
|
else if(e.key==="k"){e.preventDefault();moveCursor(-1)}
|
|
5252
6848
|
else if(e.key==="Enter"||e.key==="o"){if(state.cursor>=0){e.preventDefault();openCursor()}}
|
|
5253
|
-
else if(e.key==="/"){const box=$("run-search");if(box){e.preventDefault();box.focus();box.select()}else{e.preventDefault();openSearch()}}
|
|
6849
|
+
else if(e.key==="/"){const box=$("run-search")||$("net-filter")||$("con-filter");if(box){e.preventDefault();box.focus();box.select()}else{e.preventDefault();openSearch()}}
|
|
5254
6850
|
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()}
|
|
5255
6851
|
else if(e.key==="r"){e.preventDefault();void refreshActivity()}
|
|
5256
6852
|
});
|
|
@@ -5301,12 +6897,11 @@ button,input,textarea,select{font:inherit;color:inherit}button,a{touch-action:ma
|
|
|
5301
6897
|
.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)}
|
|
5302
6898
|
.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)}
|
|
5303
6899
|
.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)}
|
|
5304
|
-
.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}
|
|
5305
6900
|
.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}
|
|
5306
6901
|
.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}
|
|
5307
6902
|
.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}
|
|
5308
6903
|
@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}}
|
|
5309
|
-
@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%}.
|
|
6904
|
+
@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}}
|
|
5310
6905
|
|
|
5311
6906
|
/* ---- Elapsed time and duration ---- */
|
|
5312
6907
|
.rel{color:var(--text-secondary);white-space:nowrap;font-variant-numeric:tabular-nums;cursor:help;border-bottom:1px dotted var(--border-strong)}
|
|
@@ -5380,23 +6975,6 @@ tr.cursor,.definition-card.cursor{outline:1px solid var(--accent-soft);outline-o
|
|
|
5380
6975
|
.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)}
|
|
5381
6976
|
.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}
|
|
5382
6977
|
|
|
5383
|
-
/* ---- Event trace ---- */
|
|
5384
|
-
.event-controls{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:12px 15px;border-bottom:1px solid var(--border-subtle)}
|
|
5385
|
-
.event-controls-right{display:flex;align-items:center;gap:12px;margin-left:auto;flex-wrap:wrap}
|
|
5386
|
-
.event-controls-right .muted{font-size:11px}
|
|
5387
|
-
.event-list{max-height:640px;overflow:auto}
|
|
5388
|
-
.chips{display:flex;gap:5px;flex-wrap:wrap}
|
|
5389
|
-
.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}
|
|
5390
|
-
.chip:hover{color:var(--text-primary);border-color:var(--border)}
|
|
5391
|
-
.chip.active{background:var(--accent-dim);border-color:var(--accent-line);color:var(--accent)}
|
|
5392
|
-
.event-toggle{grid-template-columns:74px 62px 104px minmax(0,1fr) auto!important}
|
|
5393
|
-
.event-offset{color:var(--accent-soft);font-size:9px;font-variant-numeric:tabular-nums}
|
|
5394
|
-
.event-caret{display:flex;color:var(--text-tertiary)}
|
|
5395
|
-
.event-caret .icon{width:13px;height:13px;transition:transform .18s}
|
|
5396
|
-
.event-row.open .event-caret .icon{transform:rotate(180deg)}
|
|
5397
|
-
.event-detail-head{display:flex;align-items:center;gap:8px;padding:9px 15px 0}
|
|
5398
|
-
.event-detail-head .copy-btn{opacity:1;margin-left:auto}
|
|
5399
|
-
|
|
5400
6978
|
/* ---- Skeletons ---- */
|
|
5401
6979
|
.skeleton{padding:6px 0}
|
|
5402
6980
|
.skeleton-row{display:flex;align-items:center;gap:16px;padding:13px 15px;border-bottom:1px solid var(--border-subtle)}
|
|
@@ -5440,12 +7018,176 @@ tr.cursor,.definition-card.cursor{outline:1px solid var(--accent-soft);outline-o
|
|
|
5440
7018
|
@media(max-width:760px){
|
|
5441
7019
|
.toolbar-right{margin-left:0;width:100%}
|
|
5442
7020
|
.search-field,.search-field input{width:100%;min-width:0}
|
|
5443
|
-
.event-toggle{grid-template-columns:60px 54px minmax(0,1fr) auto!important}
|
|
5444
|
-
.event-toggle .event-category{display:none}
|
|
5445
7021
|
.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}
|
|
5446
7022
|
.hint{display:none}
|
|
5447
7023
|
.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}
|
|
5448
7024
|
}
|
|
7025
|
+
/* ---- Run workbench: DevTools for an agent run. Dense rows, panes that scroll on their own. ---- */
|
|
7026
|
+
.devtools{border:1px solid var(--border-subtle);border-radius:var(--radius);background:rgba(15,22,19,.95);overflow:hidden;margin-bottom:14px}
|
|
7027
|
+
.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}
|
|
7028
|
+
.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}
|
|
7029
|
+
.dt-tab .icon{width:14px;height:14px}
|
|
7030
|
+
.dt-tab:hover{color:var(--text-primary)}
|
|
7031
|
+
.dt-tab.active{color:var(--accent);border-bottom-color:var(--accent)}
|
|
7032
|
+
.dt-badge{font:9px var(--mono);border-radius:10px;padding:1px 6px;background:var(--bg);color:var(--text-tertiary);font-variant-numeric:tabular-nums}
|
|
7033
|
+
.dt-badge.err{background:rgba(226,155,168,.14);color:var(--danger)}
|
|
7034
|
+
.dt-badge.warn{background:rgba(228,184,121,.14);color:var(--warn)}
|
|
7035
|
+
.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)}
|
|
7036
|
+
.dt-live .pulse-dot{width:7px;height:7px;margin:0}
|
|
7037
|
+
.dt-hint{margin-left:auto;align-self:center;font:9px var(--mono);color:var(--text-tertiary);padding-left:16px;white-space:nowrap}
|
|
7038
|
+
.dt-body{height:min(74vh,820px);min-height:460px;display:flex;flex-direction:column;min-width:0}
|
|
7039
|
+
.dt-body.dt-summary{height:auto;min-height:0}
|
|
7040
|
+
.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}
|
|
7041
|
+
.dt-filter{position:relative;display:flex;align-items:center}
|
|
7042
|
+
.dt-filter .icon{position:absolute;left:9px;width:12px;height:12px;color:var(--text-tertiary)}
|
|
7043
|
+
.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)}
|
|
7044
|
+
.dt-filter input:focus,.dt-select:focus{outline:none;border-color:var(--border-strong)}
|
|
7045
|
+
.dt-select{background:var(--bg);border:1px solid var(--border-subtle);border-radius:6px;padding:6px 8px;font-size:11px;color:var(--text-primary)}
|
|
7046
|
+
.dt-chips{display:flex;gap:2px}
|
|
7047
|
+
.dt-chip{border:1px solid transparent;background:transparent;color:var(--text-secondary);border-radius:5px;padding:5px 9px;font-size:11px;cursor:pointer}
|
|
7048
|
+
.dt-chip:hover{color:var(--text-primary)}
|
|
7049
|
+
.dt-chip.active{background:var(--bg-surface-2);border-color:var(--border);color:var(--text-primary)}
|
|
7050
|
+
.dt-summary{margin-left:auto;display:flex;gap:10px;font:10px var(--mono);color:var(--text-tertiary)}
|
|
7051
|
+
.dt-pad{padding:16px;overflow:auto}
|
|
7052
|
+
.st{font:9px var(--mono);text-transform:uppercase;letter-spacing:.05em;color:var(--text-secondary)}
|
|
7053
|
+
.st.ok{color:var(--success)}.st.err{color:var(--danger)}.st.warn{color:var(--warn)}.st.live{color:var(--accent)}
|
|
7054
|
+
.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}
|
|
7055
|
+
.net-link:hover{color:var(--text-primary)}
|
|
7056
|
+
|
|
7057
|
+
.net-split{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr)}
|
|
7058
|
+
.net-split.has-detail{grid-template-columns:minmax(280px,36%) minmax(0,1fr)}
|
|
7059
|
+
.net-list{overflow:auto;min-height:0}
|
|
7060
|
+
.net-table{width:100%;border-collapse:collapse;table-layout:fixed;font-size:11px}
|
|
7061
|
+
.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%}
|
|
7062
|
+
.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}
|
|
7063
|
+
.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)}
|
|
7064
|
+
.net-row{cursor:pointer}
|
|
7065
|
+
.net-row:nth-child(even){background:rgba(20,29,24,.32)}
|
|
7066
|
+
.net-row:hover{background:var(--accent-glow)}
|
|
7067
|
+
.net-row.selected{background:var(--accent-dim);box-shadow:inset 2px 0 0 var(--accent)}
|
|
7068
|
+
.net-name{display:flex;align-items:center;gap:9px;min-width:0}
|
|
7069
|
+
.net-name>span{min-width:0}
|
|
7070
|
+
.net-name b{display:block;font-weight:500;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis}
|
|
7071
|
+
.net-name small{display:block;color:var(--text-tertiary);font:9px var(--mono);overflow:hidden;text-overflow:ellipsis;margin-top:1px}
|
|
7072
|
+
.net-row.failed .net-name b{color:var(--danger)}
|
|
7073
|
+
.net-glyph{flex:0 0 auto;width:8px;height:8px;border-radius:2px;background:var(--accent)}
|
|
7074
|
+
.kind-tool .net-glyph{background:var(--network);border-radius:50%}
|
|
7075
|
+
.kind-subagent .net-glyph{background:var(--deploy)}
|
|
7076
|
+
.net-row.compaction .net-glyph{background:var(--interface)}
|
|
7077
|
+
.c-size,.c-time{font-family:var(--mono);font-size:10px;font-variant-numeric:tabular-nums}
|
|
7078
|
+
.wf-track{position:relative;display:block;height:12px}
|
|
7079
|
+
.wf-bar{position:absolute;top:3px;height:6px;border-radius:2px;background:var(--accent-soft);min-width:2px}
|
|
7080
|
+
.kind-tool .wf-bar{background:var(--network)}
|
|
7081
|
+
.kind-subagent .wf-bar{background:var(--deploy)}
|
|
7082
|
+
.net-row.failed .wf-bar{background:var(--danger)}
|
|
7083
|
+
.wf-bar.pending{background:repeating-linear-gradient(90deg,var(--accent) 0 5px,transparent 5px 9px);opacity:.8}
|
|
7084
|
+
.net-split.has-detail .c-type,.net-split.has-detail .c-init,.net-split.has-detail .c-size,.net-split.has-detail .c-wf{display:none}
|
|
7085
|
+
.net-split.has-detail th.c-status,.net-split.has-detail th.c-time{width:72px}
|
|
7086
|
+
.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)}
|
|
7087
|
+
.net-foot-right{margin-left:auto}
|
|
7088
|
+
.net-detail{border-left:1px solid var(--border);display:flex;flex-direction:column;min-width:0;min-height:0;background:var(--bg-elevated)}
|
|
7089
|
+
.nd-head{display:flex;align-items:stretch;border-bottom:1px solid var(--border-subtle);overflow-x:auto;flex:0 0 auto}
|
|
7090
|
+
.nd-close{border:0;background:transparent;color:var(--text-tertiary);padding:0 10px;cursor:pointer;display:flex;align-items:center}
|
|
7091
|
+
.nd-close:hover{color:var(--text-primary)}
|
|
7092
|
+
.nd-close .icon{width:13px;height:13px}
|
|
7093
|
+
.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}
|
|
7094
|
+
.nd-tab:hover{color:var(--text-primary)}
|
|
7095
|
+
.nd-tab.active{color:var(--text-primary);border-bottom-color:var(--accent)}
|
|
7096
|
+
.nd-actions{margin-left:auto;display:flex;align-items:center;padding:0 8px}
|
|
7097
|
+
.nd-actions .button{padding:5px 9px;font-size:10px}
|
|
7098
|
+
.nd-title{display:flex;align-items:baseline;gap:10px;padding:12px 16px 0;flex:0 0 auto}
|
|
7099
|
+
.nd-title b{font-size:14px;font-weight:500}.nd-title span{font:10px var(--mono);color:var(--text-tertiary)}
|
|
7100
|
+
.nd-body{overflow:auto;padding:14px 16px 20px;min-height:0;flex:1}
|
|
7101
|
+
.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}
|
|
7102
|
+
.dt-kv dt{color:var(--text-tertiary);font:9px var(--mono);text-transform:uppercase;letter-spacing:.08em;padding-top:3px}
|
|
7103
|
+
.dt-kv dd{margin:0;color:var(--text-primary);overflow-wrap:anywhere}
|
|
7104
|
+
.dt-kv .copy-btn{opacity:1;vertical-align:middle}
|
|
7105
|
+
.dt-section{font:9px var(--mono);text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary);margin:18px 0 8px}
|
|
7106
|
+
.dt-note{font-size:11px;color:var(--text-secondary);line-height:1.55;margin:0 0 12px}
|
|
7107
|
+
.dt-bar{display:flex;align-items:center;gap:8px;margin-bottom:8px;font:10px var(--mono);color:var(--text-tertiary)}
|
|
7108
|
+
.dt-bar .copy-btn{opacity:1}
|
|
7109
|
+
.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}
|
|
7110
|
+
.tool-def{border:1px solid var(--border-subtle);border-radius:7px;margin-bottom:6px;background:var(--bg)}
|
|
7111
|
+
.tool-def>summary{display:flex;gap:10px;align-items:baseline;padding:8px 11px;cursor:pointer;font-size:11px}
|
|
7112
|
+
.tool-def>summary b{font:500 11px var(--mono);color:var(--network)}
|
|
7113
|
+
.tool-def>summary span{color:var(--text-tertiary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
7114
|
+
.tool-def>.dt-note,.tool-def>.jt-root{margin:0 11px 10px}
|
|
7115
|
+
.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}
|
|
7116
|
+
.sum-row:last-child{border-bottom:0}
|
|
7117
|
+
.sum-row .sum-msg{grid-column:1/-1;color:var(--text-secondary);font:10px var(--mono)}
|
|
7118
|
+
|
|
7119
|
+
/* Messages, as the model received them. */
|
|
7120
|
+
.tm{border:1px solid var(--border-subtle);border-radius:8px;background:var(--bg);margin-bottom:8px;overflow:hidden}
|
|
7121
|
+
.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)}
|
|
7122
|
+
.tm-role{font:9px var(--mono);text-transform:uppercase;letter-spacing:.1em;color:var(--text-secondary)}
|
|
7123
|
+
.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)}
|
|
7124
|
+
.tm.runtime{border-color:rgba(228,184,121,.2)}
|
|
7125
|
+
.tm.new{border-color:var(--accent-line)}
|
|
7126
|
+
.tm.missing{opacity:.6;border-style:dashed}
|
|
7127
|
+
.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}
|
|
7128
|
+
.tm-new.quiet{color:var(--text-tertiary);background:var(--bg-surface)}
|
|
7129
|
+
.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)}
|
|
7130
|
+
.tm-call,.tm-result{padding:8px 12px;border-top:1px solid var(--border-subtle)}
|
|
7131
|
+
.tm-call>span,.tm-result>span{display:block;font:10px var(--mono);color:var(--text-secondary);margin-bottom:6px}
|
|
7132
|
+
.tm-result.status-error>span{color:var(--danger)}
|
|
7133
|
+
.tm-note{font:10px/1.5 var(--mono);color:var(--text-tertiary);padding:6px 12px 8px;margin:0}
|
|
7134
|
+
.tm-media-row{padding:0 12px 8px}
|
|
7135
|
+
.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)}
|
|
7136
|
+
.tm-media .icon{width:11px;height:11px}
|
|
7137
|
+
.msg-earlier{margin-bottom:10px}
|
|
7138
|
+
.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}
|
|
7139
|
+
.msg-earlier[open]>summary{border-style:solid}
|
|
7140
|
+
|
|
7141
|
+
/* JSON trees */
|
|
7142
|
+
.jt-root{font:11px/1.6 var(--mono);color:var(--text-secondary);overflow-wrap:anywhere}
|
|
7143
|
+
.jt>summary{cursor:pointer;color:var(--text-tertiary)}
|
|
7144
|
+
.jt[open]>summary{color:var(--text-tertiary)}
|
|
7145
|
+
.jt-body{padding-left:14px;border-left:1px solid var(--border-subtle);margin-left:3px}
|
|
7146
|
+
.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}
|
|
7147
|
+
.jv-note{display:block;font-size:9px;color:var(--text-tertiary);text-transform:uppercase;letter-spacing:.08em;margin-bottom:2px}
|
|
7148
|
+
|
|
7149
|
+
/* Console */
|
|
7150
|
+
.con-list{flex:1;min-height:0;overflow:auto;font:11px/1.5 var(--mono)}
|
|
7151
|
+
.con-row{border-bottom:1px solid var(--border-subtle)}
|
|
7152
|
+
.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)}
|
|
7153
|
+
.con-line:hover{background:var(--accent-glow)}
|
|
7154
|
+
.con-time{color:var(--text-tertiary);font-variant-numeric:tabular-nums}
|
|
7155
|
+
.con-lvl{display:flex;padding-top:2px}.con-lvl .icon{width:12px;height:12px}
|
|
7156
|
+
.con-msg{white-space:pre-wrap;overflow-wrap:anywhere}
|
|
7157
|
+
.con-src{color:var(--text-tertiary);font-size:9px;padding-top:2px}
|
|
7158
|
+
.con-row.lvl-error{background:rgba(226,155,168,.06)}.con-row.lvl-error .con-line{color:var(--danger)}
|
|
7159
|
+
.con-row.lvl-warn{background:rgba(228,184,121,.06)}.con-row.lvl-warn .con-line{color:var(--warn)}
|
|
7160
|
+
.con-row.lvl-verbose .con-msg{color:var(--text-secondary)}
|
|
7161
|
+
.con-detail{display:none;padding:4px 12px 12px 96px}
|
|
7162
|
+
.con-row.open .con-detail{display:block}
|
|
7163
|
+
.con-row.open .con-line{background:var(--accent-glow)}
|
|
7164
|
+
.con-detail-head{display:flex;align-items:center;gap:12px;margin-bottom:6px;font-size:10px}
|
|
7165
|
+
.con-detail-head .copy-btn{opacity:1;margin-left:auto}
|
|
7166
|
+
.con-more{padding:10px 12px;margin:0}
|
|
7167
|
+
|
|
7168
|
+
/* Context */
|
|
7169
|
+
.ctx{flex:1;min-height:0;display:grid;grid-template-columns:220px minmax(0,1fr)}
|
|
7170
|
+
.ctx-tree{border-right:1px solid var(--border-subtle);overflow:auto;padding:6px 0 16px;background:rgba(8,11,10,.35)}
|
|
7171
|
+
.ctx-group{font:9px var(--mono);text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary);padding:12px 14px 5px}
|
|
7172
|
+
.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}
|
|
7173
|
+
.ctx-node:hover{color:var(--text-primary);background:var(--accent-glow)}
|
|
7174
|
+
.ctx-node.active{background:var(--accent-dim);color:var(--text-primary);box-shadow:inset 2px 0 0 var(--accent)}
|
|
7175
|
+
.ctx-node small{margin-left:auto;font:9px var(--mono);color:var(--text-tertiary)}
|
|
7176
|
+
.ctx-view{overflow:auto;padding:16px 18px 24px;min-height:0}
|
|
7177
|
+
.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)}
|
|
7178
|
+
|
|
7179
|
+
@media(max-width:1100px){.dt-hint{display:none}}
|
|
7180
|
+
@media(max-width:900px){
|
|
7181
|
+
.net-split.has-detail{grid-template-columns:1fr;grid-template-rows:minmax(160px,38%) minmax(0,1fr)}
|
|
7182
|
+
.net-detail{border-left:0;border-top:1px solid var(--border)}
|
|
7183
|
+
.c-init,.c-size,.c-type{display:none}
|
|
7184
|
+
.ctx{grid-template-columns:1fr;grid-template-rows:auto minmax(0,1fr)}
|
|
7185
|
+
.ctx-tree{display:flex;flex-wrap:nowrap;overflow-x:auto;padding:4px;border-right:0;border-bottom:1px solid var(--border-subtle)}
|
|
7186
|
+
.ctx-group{display:none}.ctx-node{width:auto;white-space:nowrap;padding:7px 10px}
|
|
7187
|
+
.con-detail{padding-left:12px}
|
|
7188
|
+
.dt-filter input{min-width:0;width:100%}.dt-filter{flex:1 1 200px}
|
|
7189
|
+
.dt-kv{grid-template-columns:1fr}
|
|
7190
|
+
}
|
|
5449
7191
|
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}
|
|
5450
7192
|
`;
|
|
5451
7193
|
|
|
@@ -5746,7 +7488,7 @@ ${current.content}
|
|
|
5746
7488
|
}
|
|
5747
7489
|
function openAiOutput(value) {
|
|
5748
7490
|
if (typeof value === "string") return value;
|
|
5749
|
-
if (value === void 0) return "";
|
|
7491
|
+
if (value === void 0 || value === null) return "";
|
|
5750
7492
|
return JSON.stringify(value);
|
|
5751
7493
|
}
|
|
5752
7494
|
function responseContentPart(value) {
|
|
@@ -6092,6 +7834,12 @@ var FoundryServer = class {
|
|
|
6092
7834
|
return;
|
|
6093
7835
|
}
|
|
6094
7836
|
const v1Approval = url.pathname.match(/^\/v1\/approvals\/([^/]+)$/);
|
|
7837
|
+
if (v1Approval && method === "GET") {
|
|
7838
|
+
const approval = await this.runtime.getApproval(decodeURIComponent(v1Approval[1]));
|
|
7839
|
+
if (!approval) throw new RequestError(404, "Foundry approval was not found.");
|
|
7840
|
+
json(response, 200, approval);
|
|
7841
|
+
return;
|
|
7842
|
+
}
|
|
6095
7843
|
if (v1Approval && method === "POST") {
|
|
6096
7844
|
json(response, 200, await this.runtime.resolveApproval(
|
|
6097
7845
|
decodeURIComponent(v1Approval[1]),
|
|
@@ -6130,18 +7878,65 @@ var FoundryServer = class {
|
|
|
6130
7878
|
json(response, 201, await this.runtime.createAgent(body.definitionId, {
|
|
6131
7879
|
...typeof body.id === "string" ? { id: body.id } : {},
|
|
6132
7880
|
...typeof body.workspaceId === "string" ? { workspaceId: body.workspaceId } : {},
|
|
7881
|
+
...typeof body.name === "string" ? { name: body.name } : {},
|
|
7882
|
+
...typeof body.description === "string" ? { description: body.description } : {},
|
|
6133
7883
|
...body.context && typeof body.context === "object" ? { context: body.context } : {},
|
|
6134
7884
|
...Array.isArray(body.installations) ? { installations: body.installations } : {},
|
|
6135
7885
|
...Array.isArray(body.playbooks) ? { playbooks: body.playbooks } : {}
|
|
6136
7886
|
}));
|
|
6137
7887
|
return;
|
|
6138
7888
|
}
|
|
7889
|
+
if (url.pathname === "/api/events" && method === "POST") {
|
|
7890
|
+
const body = await readJson(request);
|
|
7891
|
+
if (!body.target || typeof body.target.agentId !== "string" || typeof body.target.conversationId !== "string") throw new RequestError(400, "target.agentId and target.conversationId are required.");
|
|
7892
|
+
json(response, 202, await this.runtime.emitEvent(body.target, body.event, body.policy));
|
|
7893
|
+
return;
|
|
7894
|
+
}
|
|
7895
|
+
const workerRoute = url.pathname.match(/^\/api\/agent-instances\/([^/]+)\/subagents(?:\/([^/]+))?(?:\/(messages|data|archive|resume|purge))?$/);
|
|
7896
|
+
if (workerRoute) {
|
|
7897
|
+
const parent = decodeURIComponent(workerRoute[1]);
|
|
7898
|
+
const name = workerRoute[2] ? decodeURIComponent(workerRoute[2]) : void 0;
|
|
7899
|
+
const action = workerRoute[3];
|
|
7900
|
+
if (!name && method === "GET") {
|
|
7901
|
+
json(response, 200, await this.runtime.listSubagents(parent));
|
|
7902
|
+
return;
|
|
7903
|
+
}
|
|
7904
|
+
if (name && !action && method === "POST") {
|
|
7905
|
+
json(response, 200, await this.runtime.subagent(parent, name));
|
|
7906
|
+
return;
|
|
7907
|
+
}
|
|
7908
|
+
if (name && action === "data" && method === "GET") {
|
|
7909
|
+
json(response, 200, await this.runtime.subagentData(parent, name));
|
|
7910
|
+
return;
|
|
7911
|
+
}
|
|
7912
|
+
if (name && action === "messages" && method === "POST") {
|
|
7913
|
+
const body = await readJson(request);
|
|
7914
|
+
if (typeof body.message !== "string") throw new RequestError(400, "message is required.");
|
|
7915
|
+
json(response, 202, await this.runtime.messageSubagent(parent, name, body.message, body.delivery));
|
|
7916
|
+
return;
|
|
7917
|
+
}
|
|
7918
|
+
if (name && action === "archive" && method === "POST") {
|
|
7919
|
+
json(response, 200, await this.runtime.archiveSubagent(parent, name));
|
|
7920
|
+
return;
|
|
7921
|
+
}
|
|
7922
|
+
if (name && action === "resume" && method === "POST") {
|
|
7923
|
+
json(response, 200, await this.runtime.resumeSubagent(parent, name));
|
|
7924
|
+
return;
|
|
7925
|
+
}
|
|
7926
|
+
if (name && action === "purge" && method === "POST") {
|
|
7927
|
+
await this.runtime.purgeSubagent(parent, name);
|
|
7928
|
+
json(response, 200, { purged: true });
|
|
7929
|
+
return;
|
|
7930
|
+
}
|
|
7931
|
+
}
|
|
6139
7932
|
const instanceConfiguration = url.pathname.match(/^\/api\/agent-instances\/([^/]+)$/);
|
|
6140
7933
|
if (instanceConfiguration && method === "PATCH") {
|
|
6141
7934
|
const body = await readJson(request);
|
|
6142
7935
|
json(response, 200, await this.runtime.configureAgent(
|
|
6143
7936
|
decodeURIComponent(instanceConfiguration[1]),
|
|
6144
7937
|
{
|
|
7938
|
+
...typeof body.name === "string" ? { name: body.name } : {},
|
|
7939
|
+
...typeof body.description === "string" ? { description: body.description } : {},
|
|
6145
7940
|
...body.context && typeof body.context === "object" ? { context: body.context } : {},
|
|
6146
7941
|
...Array.isArray(body.installations) ? { installations: body.installations } : {},
|
|
6147
7942
|
...Array.isArray(body.playbooks) ? { playbooks: body.playbooks } : {}
|
|
@@ -6490,6 +8285,12 @@ var FoundryServer = class {
|
|
|
6490
8285
|
return;
|
|
6491
8286
|
}
|
|
6492
8287
|
const approvalMatch = url.pathname.match(/^\/api\/approvals\/([^/]+)$/);
|
|
8288
|
+
if (approvalMatch && method === "GET") {
|
|
8289
|
+
const approval = await this.runtime.getApproval(decodeURIComponent(approvalMatch[1]));
|
|
8290
|
+
if (!approval) throw new RequestError(404, "Foundry approval was not found.");
|
|
8291
|
+
json(response, 200, approval);
|
|
8292
|
+
return;
|
|
8293
|
+
}
|
|
6493
8294
|
if (approvalMatch && method === "POST") {
|
|
6494
8295
|
json(response, 200, await this.runtime.resolveApproval(
|
|
6495
8296
|
decodeURIComponent(approvalMatch[1]),
|
|
@@ -6560,7 +8361,9 @@ var FoundryServer = class {
|
|
|
6560
8361
|
json(
|
|
6561
8362
|
response,
|
|
6562
8363
|
200,
|
|
8364
|
+
// `after` lets a live view fetch only what it hasn't seen.
|
|
6563
8365
|
this.runtime.observability.list({
|
|
8366
|
+
...eventFilter(url),
|
|
6564
8367
|
runId: decodeURIComponent(eventsMatch[1]),
|
|
6565
8368
|
limit: 5e3
|
|
6566
8369
|
})
|