@firstpick/pi-package-webui 0.9.1 → 0.9.3
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 +31 -9
- package/bin/pi-webui-launcher.mjs +23 -12
- package/bin/pi-webui.mjs +729 -93
- package/index.ts +266 -1
- package/lib/agent-run-adapters.mjs +500 -0
- package/lib/agent-run-protocol.mjs +262 -0
- package/lib/agent-run-registry.mjs +339 -0
- package/lib/git-workflow-preferences.mjs +18 -28
- package/lib/intercom-conversations.mjs +491 -0
- package/lib/intercom-transcript-filter.mjs +99 -0
- package/lib/resource-selection.mjs +140 -0
- package/lib/trust-boundaries.mjs +2 -0
- package/lib/ui-layout-settings.mjs +172 -28
- package/lib/update/package-layout.mjs +50 -0
- package/lib/update/plan.mjs +11 -0
- package/package.json +2 -2
- package/public/app.js +2276 -419
- package/public/index.html +142 -72
- package/public/service-worker.js +2 -1
- package/public/stream-output-controller.mjs +15 -0
- package/public/styles.css +764 -92
- package/public/syntax-highlight.mjs +622 -0
- package/tests/agent-run-adapters.test.mjs +217 -0
- package/tests/agent-run-launcher.test.mjs +41 -0
- package/tests/agent-run-protocol.test.mjs +82 -0
- package/tests/agent-run-registry.test.mjs +102 -0
- package/tests/boot-failure-diagnostics.test.mjs +3 -3
- package/tests/browser/control-deck-side-panels.spec.mjs +354 -0
- package/tests/browser/controls-layout.spec.mjs +122 -0
- package/tests/browser/file-tree-git-ignored.spec.mjs +113 -0
- package/tests/browser/interaction-continuity.spec.mjs +161 -0
- package/tests/browser/intercom-conversation-viewer.spec.mjs +355 -0
- package/tests/browser/mobile-foundation.spec.mjs +26 -0
- package/tests/browser/model-search-focus.spec.mjs +96 -0
- package/tests/browser/optimistic-prompt.spec.mjs +22 -0
- package/tests/browser/persistent-ui-layout.spec.mjs +285 -66
- package/tests/browser/resource-profiles.spec.mjs +200 -0
- package/tests/browser/subagent-observability.spec.mjs +116 -0
- package/tests/codex-fast-mode-static.test.mjs +7 -6
- package/tests/common-options-submenus-interaction-static.test.mjs +2 -0
- package/tests/common-options-submenus-markup-static.test.mjs +1 -0
- package/tests/component-update-api-static.test.mjs +2 -1
- package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
- package/tests/composer-skill-tag-layout.test.mjs +32 -2
- package/tests/control-deck-component-updates-static.test.mjs +6 -0
- package/tests/control-deck-side-panels-static.test.mjs +68 -0
- package/tests/controls-layout-static.test.mjs +22 -0
- package/tests/fast-mode-client-static.test.mjs +2 -2
- package/tests/feature-decision-output-popup-static.test.mjs +2 -2
- package/tests/feature-system-prompt-optional-feature-static.test.mjs +5 -5
- package/tests/file-tree-git-ignored-static.test.mjs +152 -0
- package/tests/file-tree-search-layout-static.test.mjs +2 -1
- package/tests/file-viewer-image-static.test.mjs +69 -0
- package/tests/fixtures/fake-pi.mjs +147 -12
- package/tests/foreground-transcript-catch-up-static.test.mjs +1 -1
- package/tests/git-panel-file-preview-static.test.mjs +5 -5
- package/tests/git-panel-live-updates-static.test.mjs +3 -3
- package/tests/git-workflow-preferences.test.mjs +55 -6
- package/tests/http-endpoints-harness.test.mjs +295 -14
- package/tests/intercom-conversation-viewer-static.test.mjs +105 -0
- package/tests/intercom-conversations-http.test.mjs +252 -0
- package/tests/intercom-conversations.test.mjs +374 -0
- package/tests/intercom-main-transcript-suppression-static.test.mjs +52 -0
- package/tests/intercom-tag-layout-static.test.mjs +46 -0
- package/tests/intercom-transcript-filter.test.mjs +98 -0
- package/tests/main-output-loading-static.test.mjs +59 -0
- package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
- package/tests/mobile-compact-layout.test.mjs +2 -3
- package/tests/mobile-continuity-tablet-static.test.mjs +6 -6
- package/tests/mobile-foundation-static.test.mjs +3 -3
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +76 -42
- package/tests/native-parity.test.mjs +8 -7
- package/tests/open-issue-wizard-static.test.mjs +2 -2
- package/tests/optional-feature-migration-frontend.test.mjs +5 -5
- package/tests/optional-feature-resource-setup-static.test.mjs +29 -0
- package/tests/persistent-ui-layout-static.test.mjs +13 -13
- package/tests/questionnaire-dialog.test.mjs +3 -3
- package/tests/remote-auth-settings-harness.test.mjs +1 -1
- package/tests/resource-defaults-helper.test.mjs +60 -6
- package/tests/resource-selection.test.mjs +114 -0
- package/tests/resource-tui-extension.test.mjs +23 -0
- package/tests/session-sampling-ui-static.test.mjs +3 -3
- package/tests/side-panel-context-menu-static.test.mjs +1 -1
- package/tests/side-panel-resize-static.test.mjs +26 -16
- package/tests/side-panel-section-height-removal-static.test.mjs +4 -4
- package/tests/side-panel-section-reorder-static.test.mjs +16 -70
- package/tests/stream-output-controller.test.mjs +8 -0
- package/tests/stream-output-isolation-static.test.mjs +2 -2
- package/tests/streaming-ui-coupling.test.mjs +5 -0
- package/tests/subagent-gate-visibility.test.mjs +2 -1
- package/tests/subagent-launch-slots.test.mjs +1 -1
- package/tests/subagent-observability-static.test.mjs +32 -0
- package/tests/subagent-reliability-integration.test.mjs +183 -0
- package/tests/subagent-workflow-section-static.test.mjs +67 -0
- package/tests/subagents-helper.test.mjs +548 -5
- package/tests/syntax-highlight.test.mjs +235 -0
- package/tests/syntax-highlighting-static.test.mjs +84 -0
- package/tests/terminal-tabs-resize-static.test.mjs +35 -0
- package/tests/theme-customizer-static.test.mjs +5 -5
- package/tests/thinking-format-parser.test.mjs +64 -0
- package/tests/ui-layout-settings.test.mjs +104 -32
- package/tests/update-api-harness.test.mjs +24 -10
- package/tests/update-package-layout.test.mjs +38 -0
- package/tests/update-plan.test.mjs +11 -1
- package/tests/webui-settings-locking.test.mjs +33 -3
- package/webui-rpc-helper.mjs +700 -89
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
4
|
+
const TERMINAL_STATUSES = new Set(["done", "failed", "cancelled"]);
|
|
5
|
+
const CANONICAL_ID_KEEP_BYTES = 120;
|
|
6
|
+
|
|
7
|
+
export const AGENT_RUN_PROTOCOL_VERSION = 1;
|
|
8
|
+
export const AGENT_RUN_PROVIDER_EVENT = "firstpick:webui-agent-runs:v1";
|
|
9
|
+
export const AGENT_RUN_LIMITS = Object.freeze({
|
|
10
|
+
id: 160,
|
|
11
|
+
providerId: 80,
|
|
12
|
+
label: 240,
|
|
13
|
+
model: 240,
|
|
14
|
+
thinking: 40,
|
|
15
|
+
tool: 120,
|
|
16
|
+
instancesPerSnapshot: 512,
|
|
17
|
+
});
|
|
18
|
+
export const AGENT_RUN_LAUNCHERS = Object.freeze([
|
|
19
|
+
"sdk", "pi-rpc", "pi-json", "pi-print", "interactive", "tmux",
|
|
20
|
+
"pi-subagents", "schedule", "gate", "workflow", "custom",
|
|
21
|
+
]);
|
|
22
|
+
export const AGENT_RUN_PROVIDERS = Object.freeze([
|
|
23
|
+
"pi-subagents", "workflow-run", "webui-registry", "webui-helper",
|
|
24
|
+
]);
|
|
25
|
+
export const AGENT_RUN_STATUSES = Object.freeze([
|
|
26
|
+
"queued", "running", "stale", "done", "failed", "cancelled", "lost",
|
|
27
|
+
]);
|
|
28
|
+
export const AGENT_RUN_OUTPUT_KINDS = Object.freeze([
|
|
29
|
+
"helper", "session-jsonl", "rpc-events", "json-events", "plain-log", "registry-artifact", "none",
|
|
30
|
+
]);
|
|
31
|
+
|
|
32
|
+
const LAUNCHERS = new Set(AGENT_RUN_LAUNCHERS);
|
|
33
|
+
const STATUSES = new Set(AGENT_RUN_STATUSES);
|
|
34
|
+
const OUTPUT_KINDS = new Set(AGENT_RUN_OUTPUT_KINDS);
|
|
35
|
+
|
|
36
|
+
/** Stable projection shared by helper/server code; safe IDs up to the common keep threshold remain unchanged. */
|
|
37
|
+
export function canonicalAgentRunId(value, fallback = "agent") {
|
|
38
|
+
const raw = String(value ?? "").trim();
|
|
39
|
+
const safeFallback = ID_PATTERN.test(String(fallback)) ? String(fallback) : "agent";
|
|
40
|
+
if (!raw) return safeFallback;
|
|
41
|
+
if (Buffer.byteLength(raw, "utf8") <= CANONICAL_ID_KEEP_BYTES && ID_PATTERN.test(raw)) return raw;
|
|
42
|
+
const digest = createHash("sha256").update(raw).digest("hex").slice(0, 16);
|
|
43
|
+
const sanitized = raw.replace(/[^A-Za-z0-9._:-]/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 100);
|
|
44
|
+
return `${sanitized || safeFallback}-${digest}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function issue(field, message) {
|
|
48
|
+
const error = new TypeError(`${field} ${message}`);
|
|
49
|
+
error.code = "AGENT_RUN_INVALID";
|
|
50
|
+
error.field = field;
|
|
51
|
+
return error;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function plainObject(value, field) {
|
|
55
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw issue(field, "must be an object");
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function boundedText(value, field, maximum, { required = false, id = false } = {}) {
|
|
60
|
+
if (value === undefined || value === null || value === "") {
|
|
61
|
+
if (required) throw issue(field, "is required");
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
if (typeof value !== "string") throw issue(field, "must be a string");
|
|
65
|
+
const text = value.trim();
|
|
66
|
+
if (!text && required) throw issue(field, "is required");
|
|
67
|
+
if (!text) return undefined;
|
|
68
|
+
if (Buffer.byteLength(text, "utf8") > maximum) throw issue(field, `exceeds ${maximum} bytes`);
|
|
69
|
+
if (/[\u0000-\u001f\u007f]/u.test(text)) throw issue(field, "contains control characters");
|
|
70
|
+
if (id && !ID_PATTERN.test(text)) throw issue(field, "must be an opaque safe identifier");
|
|
71
|
+
return text;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function timestamp(value, field, { required = false } = {}) {
|
|
75
|
+
if (value === undefined || value === null) {
|
|
76
|
+
if (required) throw issue(field, "is required");
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
if (!Number.isSafeInteger(value) || value < 0) throw issue(field, "must be a non-negative integer timestamp");
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function normalizeCapabilities(value) {
|
|
84
|
+
const input = value === undefined ? {} : plainObject(value, "capabilities");
|
|
85
|
+
const output = {};
|
|
86
|
+
for (const key of ["open", "refresh", "cancel", "steer"]) {
|
|
87
|
+
if (input[key] !== undefined && typeof input[key] !== "boolean") throw issue(`capabilities.${key}`, "must be boolean");
|
|
88
|
+
output[key] = input[key] === true;
|
|
89
|
+
}
|
|
90
|
+
return Object.freeze(output);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function normalizeOutputRef(value) {
|
|
94
|
+
if (value === undefined || value === null) return Object.freeze({ kind: "none" });
|
|
95
|
+
const input = plainObject(value, "outputRef");
|
|
96
|
+
if (!OUTPUT_KINDS.has(input.kind)) throw issue("outputRef.kind", "is unsupported");
|
|
97
|
+
if (input.kind === "none") return Object.freeze({ kind: "none" });
|
|
98
|
+
const id = boundedText(input.id, "outputRef.id", AGENT_RUN_LIMITS.id, { required: true, id: true });
|
|
99
|
+
return Object.freeze({ kind: input.kind, id });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Validate and copy one canonical agent instance. Unknown fields are not retained. */
|
|
103
|
+
export function normalizeAgentInstance(value) {
|
|
104
|
+
const input = plainObject(value, "instance");
|
|
105
|
+
if (input.version !== AGENT_RUN_PROTOCOL_VERSION) throw issue("version", `must equal ${AGENT_RUN_PROTOCOL_VERSION}`);
|
|
106
|
+
const launcher = boundedText(input.launcher, "launcher", 32, { required: true });
|
|
107
|
+
if (!LAUNCHERS.has(launcher)) throw issue("launcher", "is unsupported");
|
|
108
|
+
const status = boundedText(input.status, "status", 32, { required: true });
|
|
109
|
+
if (!STATUSES.has(status)) throw issue("status", "is unsupported");
|
|
110
|
+
const startedAt = timestamp(input.startedAt, "startedAt", { required: true });
|
|
111
|
+
const updatedAt = timestamp(input.updatedAt, "updatedAt", { required: true });
|
|
112
|
+
const endedAt = timestamp(input.endedAt, "endedAt");
|
|
113
|
+
if (updatedAt < startedAt) throw issue("updatedAt", "must not precede startedAt");
|
|
114
|
+
if (endedAt !== null && endedAt < startedAt) throw issue("endedAt", "must not precede startedAt");
|
|
115
|
+
if (TERMINAL_STATUSES.has(status) && endedAt === null) throw issue("endedAt", "is required for a terminal status");
|
|
116
|
+
if (!TERMINAL_STATUSES.has(status) && endedAt !== null) throw issue("endedAt", "is only valid for a terminal status");
|
|
117
|
+
|
|
118
|
+
return Object.freeze({
|
|
119
|
+
version: AGENT_RUN_PROTOCOL_VERSION,
|
|
120
|
+
instanceId: boundedText(input.instanceId, "instanceId", AGENT_RUN_LIMITS.id, { required: true, id: true }),
|
|
121
|
+
runId: boundedText(input.runId, "runId", AGENT_RUN_LIMITS.id, { required: true, id: true }),
|
|
122
|
+
parentInstanceId: boundedText(input.parentInstanceId, "parentInstanceId", AGENT_RUN_LIMITS.id, { id: true }) ?? null,
|
|
123
|
+
parentSessionId: boundedText(input.parentSessionId, "parentSessionId", AGENT_RUN_LIMITS.id, { id: true }) ?? null,
|
|
124
|
+
launcher,
|
|
125
|
+
provider: boundedText(input.provider, "provider", AGENT_RUN_LIMITS.providerId, { required: true, id: true }),
|
|
126
|
+
origin: boundedText(input.origin, "origin", AGENT_RUN_LIMITS.label),
|
|
127
|
+
name: boundedText(input.name, "name", AGENT_RUN_LIMITS.label),
|
|
128
|
+
status,
|
|
129
|
+
startedAt,
|
|
130
|
+
updatedAt,
|
|
131
|
+
endedAt,
|
|
132
|
+
model: boundedText(input.model, "model", AGENT_RUN_LIMITS.model),
|
|
133
|
+
thinking: boundedText(input.thinking, "thinking", AGENT_RUN_LIMITS.thinking),
|
|
134
|
+
activityState: boundedText(input.activityState, "activityState", 40, { id: true }),
|
|
135
|
+
currentTool: boundedText(input.currentTool, "currentTool", AGENT_RUN_LIMITS.tool),
|
|
136
|
+
capabilities: normalizeCapabilities(input.capabilities),
|
|
137
|
+
outputRef: normalizeOutputRef(input.outputRef),
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function normalizeProviderSnapshot(value) {
|
|
142
|
+
const input = plainObject(value, "snapshot");
|
|
143
|
+
if (input.version !== AGENT_RUN_PROTOCOL_VERSION) throw issue("snapshot.version", `must equal ${AGENT_RUN_PROTOCOL_VERSION}`);
|
|
144
|
+
const producerId = boundedText(input.producerId, "producerId", AGENT_RUN_LIMITS.providerId, { required: true, id: true });
|
|
145
|
+
if (typeof input.complete !== "boolean") throw issue("snapshot.complete", "must be boolean");
|
|
146
|
+
if (!Array.isArray(input.instances)) throw issue("snapshot.instances", "must be an array");
|
|
147
|
+
if (input.instances.length > AGENT_RUN_LIMITS.instancesPerSnapshot) throw issue("snapshot.instances", `exceeds ${AGENT_RUN_LIMITS.instancesPerSnapshot} entries`);
|
|
148
|
+
const seen = new Set();
|
|
149
|
+
const instances = input.instances.map((item) => {
|
|
150
|
+
const instance = normalizeAgentInstance(item);
|
|
151
|
+
const key = agentInstanceKey(instance);
|
|
152
|
+
if (seen.has(key)) throw issue("snapshot.instances", `contains duplicate ${instance.instanceId}`);
|
|
153
|
+
seen.add(key);
|
|
154
|
+
return instance;
|
|
155
|
+
});
|
|
156
|
+
const removals = input.removals === undefined ? [] : input.removals;
|
|
157
|
+
if (!Array.isArray(removals) || removals.length > AGENT_RUN_LIMITS.instancesPerSnapshot) throw issue("snapshot.removals", "must be a bounded array");
|
|
158
|
+
return Object.freeze({
|
|
159
|
+
version: AGENT_RUN_PROTOCOL_VERSION,
|
|
160
|
+
producerId,
|
|
161
|
+
complete: input.complete,
|
|
162
|
+
instances: Object.freeze(instances),
|
|
163
|
+
removals: Object.freeze(removals.map((id) => boundedText(id, "snapshot.removals[]", AGENT_RUN_LIMITS.id, { required: true, id: true }))),
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function agentInstanceKey(instance) {
|
|
168
|
+
return `${instance.parentSessionId || "external"}\0${instance.instanceId}`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const OUTPUT_PRIORITY = Object.freeze({ none: 0, "plain-log": 1, "registry-artifact": 2, "rpc-events": 3, "json-events": 3, helper: 4, "session-jsonl": 5 });
|
|
172
|
+
|
|
173
|
+
/** Merge duplicate evidence without allowing weak, newer observations to erase stronger fields. */
|
|
174
|
+
export function mergeAgentInstances(previousValue, nextValue, { lifecycleOwner = false, capabilityOwner = false } = {}) {
|
|
175
|
+
const previous = normalizeAgentInstance(previousValue);
|
|
176
|
+
const next = normalizeAgentInstance(nextValue);
|
|
177
|
+
if (agentInstanceKey(previous) !== agentInstanceKey(next)) throw issue("instanceId", "does not identify the same parent-scoped instance");
|
|
178
|
+
const nextIsNewer = next.updatedAt >= previous.updatedAt;
|
|
179
|
+
const previousTerminal = TERMINAL_STATUSES.has(previous.status);
|
|
180
|
+
const nextTerminal = TERMINAL_STATUSES.has(next.status);
|
|
181
|
+
let status = previous.status;
|
|
182
|
+
let endedAt = previous.endedAt;
|
|
183
|
+
if ((!previousTerminal && nextTerminal) || (lifecycleOwner && nextIsNewer) || (!previousTerminal && nextIsNewer)) {
|
|
184
|
+
status = next.status;
|
|
185
|
+
endedAt = next.endedAt;
|
|
186
|
+
}
|
|
187
|
+
const outputRef = (OUTPUT_PRIORITY[next.outputRef.kind] > OUTPUT_PRIORITY[previous.outputRef.kind]
|
|
188
|
+
|| (OUTPUT_PRIORITY[next.outputRef.kind] === OUTPUT_PRIORITY[previous.outputRef.kind] && nextIsNewer)) ? next.outputRef : previous.outputRef;
|
|
189
|
+
const choose = (field) => nextIsNewer && next[field] !== undefined ? next[field] : previous[field] ?? next[field];
|
|
190
|
+
return normalizeAgentInstance({
|
|
191
|
+
...previous,
|
|
192
|
+
launcher: previous.launcher === "custom" && next.launcher !== "custom" ? next.launcher : previous.launcher,
|
|
193
|
+
provider: previous.provider,
|
|
194
|
+
origin: choose("origin"), name: choose("name"), model: choose("model"), thinking: choose("thinking"),
|
|
195
|
+
activityState: choose("activityState"), currentTool: choose("currentTool"),
|
|
196
|
+
status, endedAt, startedAt: Math.min(previous.startedAt, next.startedAt), updatedAt: Math.max(previous.updatedAt, next.updatedAt),
|
|
197
|
+
capabilities: capabilityOwner ? next.capabilities : previous.capabilities,
|
|
198
|
+
outputRef,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Producer-aware in-memory index. Identity upgrades are explicit: a stronger ID
|
|
204
|
+
* may replace a provisional ID, but names, models, PIDs, and timestamps never merge rows.
|
|
205
|
+
*/
|
|
206
|
+
export class AgentRunIndex {
|
|
207
|
+
#rows = new Map();
|
|
208
|
+
#producerKeys = new Map();
|
|
209
|
+
#aliases = new Map();
|
|
210
|
+
|
|
211
|
+
upsert(value, { producerId, previousInstanceId, lifecycleOwner = false, capabilityOwner = false } = {}) {
|
|
212
|
+
const producer = boundedText(producerId || value?.provider, "producerId", AGENT_RUN_LIMITS.providerId, { required: true, id: true });
|
|
213
|
+
const instance = normalizeAgentInstance(value);
|
|
214
|
+
let key = agentInstanceKey(instance);
|
|
215
|
+
if (previousInstanceId) {
|
|
216
|
+
const previousId = boundedText(previousInstanceId, "previousInstanceId", AGENT_RUN_LIMITS.id, { required: true, id: true });
|
|
217
|
+
const oldKey = `${instance.parentSessionId || "external"}\0${previousId}`;
|
|
218
|
+
const resolvedOldKey = this.#aliases.get(oldKey) || oldKey;
|
|
219
|
+
if (resolvedOldKey !== key && this.#rows.has(resolvedOldKey)) {
|
|
220
|
+
const old = this.#rows.get(resolvedOldKey);
|
|
221
|
+
this.#rows.delete(resolvedOldKey);
|
|
222
|
+
this.#aliases.set(oldKey, key);
|
|
223
|
+
for (const keys of this.#producerKeys.values()) if (keys.delete(resolvedOldKey)) keys.add(key);
|
|
224
|
+
this.#rows.set(key, normalizeAgentInstance({ ...old, ...instance, instanceId: instance.instanceId }));
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const existing = this.#rows.get(key);
|
|
228
|
+
this.#rows.set(key, existing ? mergeAgentInstances(existing, instance, { lifecycleOwner, capabilityOwner }) : instance);
|
|
229
|
+
if (!this.#producerKeys.has(producer)) this.#producerKeys.set(producer, new Set());
|
|
230
|
+
this.#producerKeys.get(producer).add(key);
|
|
231
|
+
return this.#rows.get(key);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
ingestSnapshot(value, options = {}) {
|
|
235
|
+
const snapshot = normalizeProviderSnapshot(value);
|
|
236
|
+
const previous = new Set(this.#producerKeys.get(snapshot.producerId) || []);
|
|
237
|
+
const current = new Set();
|
|
238
|
+
for (const instance of snapshot.instances) {
|
|
239
|
+
const merged = this.upsert(instance, { producerId: snapshot.producerId, ...options });
|
|
240
|
+
current.add(agentInstanceKey(merged));
|
|
241
|
+
}
|
|
242
|
+
for (const id of snapshot.removals) {
|
|
243
|
+
const prefix = `\0${id}`;
|
|
244
|
+
for (const key of previous) if (key.endsWith(prefix)) this.#removeProducerKey(snapshot.producerId, key);
|
|
245
|
+
}
|
|
246
|
+
if (snapshot.complete) for (const key of previous) if (!current.has(key)) this.#removeProducerKey(snapshot.producerId, key);
|
|
247
|
+
return this.values();
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
#removeProducerKey(producerId, key) {
|
|
251
|
+
this.#producerKeys.get(producerId)?.delete(key);
|
|
252
|
+
const stillOwned = [...this.#producerKeys.values()].some((keys) => keys.has(key));
|
|
253
|
+
if (!stillOwned) this.#rows.delete(key);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
values() { return [...this.#rows.values()].sort((a, b) => a.startedAt - b.startedAt || a.instanceId.localeCompare(b.instanceId)); }
|
|
257
|
+
get size() { return this.#rows.size; }
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function isTerminalAgentStatus(status) {
|
|
261
|
+
return TERMINAL_STATUSES.has(status);
|
|
262
|
+
}
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { chmod, lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
AGENT_RUN_LIMITS,
|
|
7
|
+
isTerminalAgentStatus,
|
|
8
|
+
normalizeAgentInstance,
|
|
9
|
+
} from "./agent-run-protocol.mjs";
|
|
10
|
+
|
|
11
|
+
const DIRECTORY_MODE = 0o700;
|
|
12
|
+
const FILE_MODE = 0o600;
|
|
13
|
+
const RECORD_MAX_BYTES = 64 * 1024;
|
|
14
|
+
const EVENT_LINE_MAX_BYTES = 16 * 1024;
|
|
15
|
+
const DEFAULT_EVENT_MAX_BYTES = 256 * 1024;
|
|
16
|
+
const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
17
|
+
|
|
18
|
+
function fail(code, message) {
|
|
19
|
+
return Object.assign(new Error(message), { code });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function safeId(value, field, maximum = AGENT_RUN_LIMITS.id) {
|
|
23
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
24
|
+
if (!text || Buffer.byteLength(text) > maximum || !SAFE_ID.test(text)) throw fail("AGENT_RUN_UNSAFE_ID", `${field} must be an opaque safe identifier`);
|
|
25
|
+
return text;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function inside(root, candidate) {
|
|
29
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
30
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function ensurePrivateDirectory(directory) {
|
|
34
|
+
await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
|
|
35
|
+
const info = await lstat(directory);
|
|
36
|
+
if (!info.isDirectory() || info.isSymbolicLink()) throw fail("AGENT_RUN_REGISTRY_SYMLINK", "Agent-run registry directory must not be a symlink");
|
|
37
|
+
if (process.platform !== "win32") await chmod(directory, DIRECTORY_MODE);
|
|
38
|
+
return realpath(directory);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function safeRegularFile(file, canonicalRoot, maximum) {
|
|
42
|
+
const info = await lstat(file).catch(() => null);
|
|
43
|
+
if (!info || !info.isFile() || info.isSymbolicLink() || info.size > maximum) return null;
|
|
44
|
+
const canonical = await realpath(file).catch(() => null);
|
|
45
|
+
if (!canonical || !inside(canonicalRoot, canonical)) return null;
|
|
46
|
+
return { info, canonical };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function agentRunScopeId(agentDir, port) {
|
|
50
|
+
if (!agentDir || typeof agentDir !== "string") throw new TypeError("agentDir is required");
|
|
51
|
+
const numericPort = Number(port);
|
|
52
|
+
if (!Number.isInteger(numericPort) || numericPort < 1 || numericPort > 65535) throw new TypeError("port must be an integer between 1 and 65535");
|
|
53
|
+
// Deliberately identical to rpc-supervisor-state.mjs scopeDigest semantics.
|
|
54
|
+
return createHash("sha256").update(`${path.resolve(agentDir)}\0${numericPort}`).digest("hex");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function defaultAgentRunStateHome(environment = process.env) {
|
|
58
|
+
return path.resolve(environment.XDG_STATE_HOME || path.join(homedir(), ".local", "state"));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function agentRunRegistryPaths({ agentDir, port, stateHome, scopeId } = {}) {
|
|
62
|
+
const stateRoot = path.resolve(stateHome || defaultAgentRunStateHome());
|
|
63
|
+
const scope = scopeId ? safeId(scopeId, "scopeId") : agentRunScopeId(agentDir, port);
|
|
64
|
+
const webuiRoot = path.join(stateRoot, "pi-webui");
|
|
65
|
+
const registryBase = path.join(webuiRoot, "agent-runs");
|
|
66
|
+
return Object.freeze({ stateRoot, webuiRoot, registryBase, scopeId: scope, root: path.join(registryBase, scope) });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function createAgentRunRecordId() {
|
|
70
|
+
return randomUUID();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function ageAgentRun(instanceValue, now = Date.now(), { staleAfterMs = 30_000, lostAfterMs = 120_000 } = {}) {
|
|
74
|
+
const instance = normalizeAgentInstance(instanceValue);
|
|
75
|
+
if (isTerminalAgentStatus(instance.status) || !["running", "stale"].includes(instance.status)) return instance;
|
|
76
|
+
const elapsed = Math.max(0, now - instance.updatedAt);
|
|
77
|
+
const status = elapsed >= lostAfterMs ? "lost" : elapsed >= staleAfterMs ? "stale" : "running";
|
|
78
|
+
if (status === instance.status) return instance;
|
|
79
|
+
return normalizeAgentInstance({ ...instance, status, endedAt: null });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function boundedUtf8(value, maximum) {
|
|
83
|
+
const encoded = Buffer.from(value, "utf8");
|
|
84
|
+
return encoded.length <= maximum ? value : encoded.subarray(0, maximum).toString("utf8");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function normalizeArtifactEvent(value, now = Date.now()) {
|
|
88
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw fail("AGENT_RUN_EVENT_INVALID", "Artifact event must be an object");
|
|
89
|
+
const type = safeId(String(value.type || "event"), "event.type", 80);
|
|
90
|
+
const event = { type, at: Number.isSafeInteger(value.at) && value.at >= 0 ? value.at : now };
|
|
91
|
+
for (const [key, maximum] of [["stream", 16], ["tool", 120], ["status", 40], ["message", 8_192]]) {
|
|
92
|
+
if (value[key] === undefined) continue;
|
|
93
|
+
if (typeof value[key] !== "string") throw fail("AGENT_RUN_EVENT_INVALID", `event.${key} must be a string`);
|
|
94
|
+
const normalized = boundedUtf8(value[key], maximum);
|
|
95
|
+
if (key !== "message" && /[\u0000-\u001f\u007f]/u.test(normalized)) throw fail("AGENT_RUN_EVENT_INVALID", `event.${key} contains control characters`);
|
|
96
|
+
event[key] = normalized;
|
|
97
|
+
}
|
|
98
|
+
if (value.isError !== undefined) event.isError = value.isError === true;
|
|
99
|
+
if (value.usage && typeof value.usage === "object" && !Array.isArray(value.usage)) {
|
|
100
|
+
const usage = {};
|
|
101
|
+
for (const key of ["input", "output", "cacheRead", "cacheWrite", "total"]) {
|
|
102
|
+
if (Number.isFinite(value.usage[key]) && value.usage[key] >= 0) usage[key] = Math.floor(value.usage[key]);
|
|
103
|
+
}
|
|
104
|
+
if (Object.keys(usage).length) event.usage = usage;
|
|
105
|
+
}
|
|
106
|
+
const encoded = `${JSON.stringify(event)}\n`;
|
|
107
|
+
if (Buffer.byteLength(encoded) > EVENT_LINE_MAX_BYTES) throw fail("AGENT_RUN_EVENT_TOO_LARGE", `Artifact event exceeds ${EVENT_LINE_MAX_BYTES} bytes`);
|
|
108
|
+
return { event: Object.freeze(event), encoded };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export class AgentRunRegistry {
|
|
112
|
+
constructor(options = {}) {
|
|
113
|
+
this.paths = agentRunRegistryPaths(options);
|
|
114
|
+
this.eventMaxBytes = Math.max(EVENT_LINE_MAX_BYTES, Math.min(Number(options.eventMaxBytes) || DEFAULT_EVENT_MAX_BYTES, 4 * 1024 * 1024));
|
|
115
|
+
this.staleAfterMs = Number(options.staleAfterMs) || 30_000;
|
|
116
|
+
this.lostAfterMs = Number(options.lostAfterMs) || 120_000;
|
|
117
|
+
this.finishedRetentionMs = Number(options.finishedRetentionMs) || 24 * 60 * 60_000;
|
|
118
|
+
this.now = typeof options.now === "function" ? options.now : Date.now;
|
|
119
|
+
this.canonicalRoot = null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async init() {
|
|
123
|
+
const canonicalState = await ensurePrivateDirectory(this.paths.stateRoot);
|
|
124
|
+
const canonicalWebui = await ensurePrivateDirectory(this.paths.webuiRoot);
|
|
125
|
+
const canonicalBase = await ensurePrivateDirectory(this.paths.registryBase);
|
|
126
|
+
const canonicalRoot = await ensurePrivateDirectory(this.paths.root);
|
|
127
|
+
if (!inside(canonicalState, canonicalWebui) || !inside(canonicalState, canonicalBase) || !inside(canonicalState, canonicalRoot)) {
|
|
128
|
+
throw fail("AGENT_RUN_REGISTRY_ESCAPE", "Agent-run registry resolves outside the configured private state root");
|
|
129
|
+
}
|
|
130
|
+
this.canonicalRoot = canonicalRoot;
|
|
131
|
+
return this;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async #producerDirectory(producerId, { create = true } = {}) {
|
|
135
|
+
if (!this.canonicalRoot) await this.init();
|
|
136
|
+
const producer = safeId(producerId, "producerId", AGENT_RUN_LIMITS.providerId);
|
|
137
|
+
const directory = path.join(this.paths.root, producer);
|
|
138
|
+
if (create) {
|
|
139
|
+
const canonical = await ensurePrivateDirectory(directory);
|
|
140
|
+
if (!inside(this.canonicalRoot, canonical)) throw fail("AGENT_RUN_REGISTRY_ESCAPE", "Producer directory escapes the registry root");
|
|
141
|
+
return { producer, directory, canonical };
|
|
142
|
+
}
|
|
143
|
+
const info = await lstat(directory).catch(() => null);
|
|
144
|
+
if (!info?.isDirectory() || info.isSymbolicLink()) return null;
|
|
145
|
+
const canonical = await realpath(directory).catch(() => null);
|
|
146
|
+
return canonical && inside(this.canonicalRoot, canonical) ? { producer, directory, canonical } : null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async writeRecord(producerId, instanceValue, { recordId } = {}) {
|
|
150
|
+
const producer = await this.#producerDirectory(producerId);
|
|
151
|
+
const id = safeId(recordId || createAgentRunRecordId(), "recordId");
|
|
152
|
+
let instance = normalizeAgentInstance(instanceValue);
|
|
153
|
+
if (instance.provider !== "webui-registry") throw fail("AGENT_RUN_PROVIDER_INVALID", "Cross-process registry records must use provider webui-registry");
|
|
154
|
+
if (instance.outputRef.kind !== "none" && instance.outputRef.id !== id) {
|
|
155
|
+
throw fail("AGENT_RUN_OUTPUT_ID_INVALID", "Registry outputRef.id must equal its opaque record ID");
|
|
156
|
+
}
|
|
157
|
+
const file = path.join(producer.directory, `${id}.json`);
|
|
158
|
+
const temporary = path.join(producer.directory, `.${id}.${process.pid}.${randomUUID()}.tmp`);
|
|
159
|
+
const encoded = `${JSON.stringify(instance)}\n`;
|
|
160
|
+
if (Buffer.byteLength(encoded) > RECORD_MAX_BYTES) throw fail("AGENT_RUN_RECORD_TOO_LARGE", `Record exceeds ${RECORD_MAX_BYTES} bytes`);
|
|
161
|
+
await writeFile(temporary, encoded, { encoding: "utf8", mode: FILE_MODE, flag: "wx" });
|
|
162
|
+
if (process.platform !== "win32") await chmod(temporary, FILE_MODE);
|
|
163
|
+
try {
|
|
164
|
+
await rename(temporary, file);
|
|
165
|
+
if (process.platform !== "win32") await chmod(file, FILE_MODE);
|
|
166
|
+
} finally {
|
|
167
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
168
|
+
}
|
|
169
|
+
return Object.freeze({ producerId: producer.producer, recordId: id, instance });
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async writeSessionLocator(producerId, recordId, sessionFile, { allowedRoots = [] } = {}) {
|
|
173
|
+
const producer = await this.#producerDirectory(producerId);
|
|
174
|
+
const id = safeId(recordId, "recordId");
|
|
175
|
+
const roots = [];
|
|
176
|
+
for (const root of allowedRoots) {
|
|
177
|
+
const canonical = await realpath(path.resolve(root)).catch(() => null);
|
|
178
|
+
if (canonical) roots.push(canonical);
|
|
179
|
+
}
|
|
180
|
+
if (!roots.length) throw fail("AGENT_RUN_SESSION_ROOT_REQUIRED", "A configured Pi session root is required");
|
|
181
|
+
const info = await lstat(sessionFile).catch(() => null);
|
|
182
|
+
const canonicalSession = info?.isFile() && !info.isSymbolicLink() ? await realpath(sessionFile).catch(() => null) : null;
|
|
183
|
+
if (!canonicalSession || !roots.some((root) => inside(root, canonicalSession) && root !== canonicalSession)) {
|
|
184
|
+
throw fail("AGENT_RUN_SESSION_ESCAPE", "Session locator must resolve inside a configured Pi session root");
|
|
185
|
+
}
|
|
186
|
+
const file = path.join(producer.directory, `${id}.session-locator`);
|
|
187
|
+
const temporary = path.join(producer.directory, `.${id}.${process.pid}.${randomUUID()}.locator.tmp`);
|
|
188
|
+
await writeFile(temporary, `${JSON.stringify({ version: 1, sessionFile: canonicalSession })}\n`, { encoding: "utf8", mode: FILE_MODE, flag: "wx" });
|
|
189
|
+
if (process.platform !== "win32") await chmod(temporary, FILE_MODE);
|
|
190
|
+
try {
|
|
191
|
+
await rename(temporary, file);
|
|
192
|
+
if (process.platform !== "win32") await chmod(file, FILE_MODE);
|
|
193
|
+
} finally {
|
|
194
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
195
|
+
}
|
|
196
|
+
return Object.freeze({ id, sessionFile: canonicalSession });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async resolveSessionLocator(outputId, { allowedRoots = [] } = {}) {
|
|
200
|
+
const id = safeId(outputId, "outputId");
|
|
201
|
+
const snapshot = await this.readRecords();
|
|
202
|
+
const owner = snapshot.artifacts.get(id);
|
|
203
|
+
if (!owner || owner.kind !== "session-jsonl") return null;
|
|
204
|
+
const producer = await this.#producerDirectory(owner.producerId, { create: false });
|
|
205
|
+
if (!producer) return null;
|
|
206
|
+
const locatorFile = path.join(producer.directory, `${id}.session-locator`);
|
|
207
|
+
const safe = await safeRegularFile(locatorFile, producer.canonical, RECORD_MAX_BYTES);
|
|
208
|
+
if (!safe) return null;
|
|
209
|
+
let locator;
|
|
210
|
+
try { locator = JSON.parse(await readFile(safe.canonical, "utf8")); } catch { return null; }
|
|
211
|
+
if (locator?.version !== 1 || typeof locator.sessionFile !== "string") return null;
|
|
212
|
+
const canonicalSession = await realpath(locator.sessionFile).catch(() => null);
|
|
213
|
+
const info = canonicalSession ? await lstat(canonicalSession).catch(() => null) : null;
|
|
214
|
+
if (!info?.isFile() || info.isSymbolicLink()) return null;
|
|
215
|
+
const roots = await Promise.all(allowedRoots.map((root) => realpath(path.resolve(root)).catch(() => null)));
|
|
216
|
+
if (!roots.some((root) => root && inside(root, canonicalSession) && root !== canonicalSession)) return null;
|
|
217
|
+
return Object.freeze({ id, kind: owner.kind, sessionFile: canonicalSession });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async appendArtifactEvent(producerId, recordId, eventValue) {
|
|
221
|
+
const producer = await this.#producerDirectory(producerId);
|
|
222
|
+
const id = safeId(recordId, "recordId");
|
|
223
|
+
const { event, encoded } = normalizeArtifactEvent(eventValue, this.now());
|
|
224
|
+
const file = path.join(producer.directory, `${id}.events.jsonl`);
|
|
225
|
+
let existing = "";
|
|
226
|
+
const safe = await safeRegularFile(file, producer.canonical, this.eventMaxBytes).catch(() => null);
|
|
227
|
+
if (safe) existing = await readFile(safe.canonical, "utf8");
|
|
228
|
+
const lines = `${existing}${encoded}`.split("\n").filter(Boolean);
|
|
229
|
+
let bytes = 0;
|
|
230
|
+
const kept = [];
|
|
231
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
232
|
+
const line = `${lines[index]}\n`;
|
|
233
|
+
const size = Buffer.byteLength(line);
|
|
234
|
+
if (size > EVENT_LINE_MAX_BYTES) continue;
|
|
235
|
+
if (bytes + size > this.eventMaxBytes) break;
|
|
236
|
+
bytes += size;
|
|
237
|
+
kept.push(line);
|
|
238
|
+
}
|
|
239
|
+
kept.reverse();
|
|
240
|
+
const temporary = path.join(producer.directory, `.${id}.${process.pid}.${randomUUID()}.events.tmp`);
|
|
241
|
+
await writeFile(temporary, kept.join(""), { encoding: "utf8", mode: FILE_MODE, flag: "wx" });
|
|
242
|
+
if (process.platform !== "win32") await chmod(temporary, FILE_MODE);
|
|
243
|
+
try {
|
|
244
|
+
await rename(temporary, file);
|
|
245
|
+
if (process.platform !== "win32") await chmod(file, FILE_MODE);
|
|
246
|
+
} finally {
|
|
247
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
248
|
+
}
|
|
249
|
+
return event;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async readRecords({ now = this.now(), maxRecords = 2_048 } = {}) {
|
|
253
|
+
if (!this.canonicalRoot) await this.init();
|
|
254
|
+
const records = [];
|
|
255
|
+
const diagnostics = [];
|
|
256
|
+
const artifacts = new Map();
|
|
257
|
+
let omitted = 0;
|
|
258
|
+
const producers = await readdir(this.paths.root, { withFileTypes: true }).catch((error) => {
|
|
259
|
+
if (error?.code === "ENOENT") return [];
|
|
260
|
+
throw error;
|
|
261
|
+
});
|
|
262
|
+
for (const entry of producers) {
|
|
263
|
+
if (!entry.isDirectory() || entry.isSymbolicLink() || !SAFE_ID.test(entry.name)) {
|
|
264
|
+
diagnostics.push({ code: "ignored-producer", producerId: SAFE_ID.test(entry.name) ? entry.name : undefined });
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
const producer = await this.#producerDirectory(entry.name, { create: false });
|
|
268
|
+
if (!producer) { diagnostics.push({ code: "unsafe-producer", producerId: entry.name }); continue; }
|
|
269
|
+
const entries = await readdir(producer.directory, { withFileTypes: true }).catch(() => []);
|
|
270
|
+
for (const fileEntry of entries) {
|
|
271
|
+
if (!fileEntry.name.endsWith(".json") || fileEntry.name.endsWith(".events.jsonl")) continue;
|
|
272
|
+
if (records.length >= maxRecords) { omitted += 1; continue; }
|
|
273
|
+
const recordId = fileEntry.name.slice(0, -5);
|
|
274
|
+
if (!SAFE_ID.test(recordId) || fileEntry.isSymbolicLink()) { diagnostics.push({ code: "unsafe-record", producerId: entry.name }); continue; }
|
|
275
|
+
const file = path.join(producer.directory, fileEntry.name);
|
|
276
|
+
const safe = await safeRegularFile(file, producer.canonical, RECORD_MAX_BYTES).catch(() => null);
|
|
277
|
+
if (!safe) { diagnostics.push({ code: "unsafe-or-oversized-record", producerId: entry.name, recordId }); continue; }
|
|
278
|
+
try {
|
|
279
|
+
const parsed = JSON.parse(await readFile(safe.canonical, "utf8"));
|
|
280
|
+
const instance = ageAgentRun(normalizeAgentInstance(parsed), now, { staleAfterMs: this.staleAfterMs, lostAfterMs: this.lostAfterMs });
|
|
281
|
+
if (instance.provider !== "webui-registry") throw new Error("provider is not webui-registry");
|
|
282
|
+
if (instance.outputRef.kind !== "none") {
|
|
283
|
+
if (instance.outputRef.id !== recordId) throw new Error("output ID does not match record ID");
|
|
284
|
+
artifacts.set(recordId, { producerId: entry.name, recordId, kind: instance.outputRef.kind });
|
|
285
|
+
}
|
|
286
|
+
records.push(Object.freeze({ producerId: entry.name, recordId, instance }));
|
|
287
|
+
} catch {
|
|
288
|
+
diagnostics.push({ code: "invalid-record", producerId: entry.name, recordId });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return Object.freeze({ records: Object.freeze(records), diagnostics: Object.freeze(diagnostics.slice(0, 128)), omitted, artifacts });
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async readArtifact(outputId, { maxBytes = this.eventMaxBytes } = {}) {
|
|
296
|
+
const id = safeId(outputId, "outputId");
|
|
297
|
+
const snapshot = await this.readRecords();
|
|
298
|
+
const owner = snapshot.artifacts.get(id);
|
|
299
|
+
if (!owner) return null;
|
|
300
|
+
const producer = await this.#producerDirectory(owner.producerId, { create: false });
|
|
301
|
+
if (!producer) return null;
|
|
302
|
+
const file = path.join(producer.directory, `${id}.events.jsonl`);
|
|
303
|
+
const safe = await safeRegularFile(file, producer.canonical, Math.min(maxBytes, this.eventMaxBytes));
|
|
304
|
+
if (!safe) return null;
|
|
305
|
+
const text = await readFile(safe.canonical, "utf8");
|
|
306
|
+
const events = [];
|
|
307
|
+
for (const line of text.split("\n")) {
|
|
308
|
+
if (!line) continue;
|
|
309
|
+
if (Buffer.byteLength(line) > EVENT_LINE_MAX_BYTES) continue;
|
|
310
|
+
try { events.push(JSON.parse(line)); } catch {}
|
|
311
|
+
}
|
|
312
|
+
return Object.freeze({ id, kind: owner.kind, events: Object.freeze(events), bytes: Buffer.byteLength(text) });
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async prune({ now = this.now(), retentionMs = this.finishedRetentionMs } = {}) {
|
|
316
|
+
const snapshot = await this.readRecords({ now });
|
|
317
|
+
let removed = 0;
|
|
318
|
+
for (const record of snapshot.records) {
|
|
319
|
+
if (!isTerminalAgentStatus(record.instance.status)) continue;
|
|
320
|
+
const terminalAt = record.instance.endedAt ?? record.instance.updatedAt;
|
|
321
|
+
if (now - terminalAt < retentionMs) continue;
|
|
322
|
+
const producer = await this.#producerDirectory(record.producerId, { create: false });
|
|
323
|
+
if (!producer) continue;
|
|
324
|
+
await Promise.all([
|
|
325
|
+
rm(path.join(producer.directory, `${record.recordId}.json`), { force: true }),
|
|
326
|
+
rm(path.join(producer.directory, `${record.recordId}.events.jsonl`), { force: true }),
|
|
327
|
+
rm(path.join(producer.directory, `${record.recordId}.session-locator`), { force: true }),
|
|
328
|
+
]);
|
|
329
|
+
removed += 1;
|
|
330
|
+
}
|
|
331
|
+
return removed;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export const AGENT_RUN_REGISTRY_LIMITS = Object.freeze({
|
|
336
|
+
recordBytes: RECORD_MAX_BYTES,
|
|
337
|
+
eventLineBytes: EVENT_LINE_MAX_BYTES,
|
|
338
|
+
defaultEventBytes: DEFAULT_EVENT_MAX_BYTES,
|
|
339
|
+
});
|