@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,500 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { lstat, realpath } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { terminateProcessTree } from "./process-tree.mjs";
|
|
8
|
+
import { AGENT_RUN_PROVIDER_EVENT, normalizeAgentInstance } from "./agent-run-protocol.mjs";
|
|
9
|
+
import { AgentRunRegistry, createAgentRunRecordId } from "./agent-run-registry.mjs";
|
|
10
|
+
|
|
11
|
+
const STRUCTURED_LAUNCHERS = new Set(["pi-rpc", "pi-json"]);
|
|
12
|
+
const SUBPROCESS_LAUNCHERS = new Set(["pi-rpc", "pi-json", "pi-print"]);
|
|
13
|
+
const DEFAULT_OUTPUT_BYTES = 256 * 1024;
|
|
14
|
+
|
|
15
|
+
function text(value, maximum = 240) {
|
|
16
|
+
if (typeof value !== "string") return undefined;
|
|
17
|
+
const trimmed = value.trim();
|
|
18
|
+
return trimmed ? trimmed.slice(0, maximum) : undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function modelName(model) {
|
|
22
|
+
if (!model || typeof model !== "object") return undefined;
|
|
23
|
+
const provider = text(model.provider, 100);
|
|
24
|
+
const id = text(model.id || model.modelId, 140);
|
|
25
|
+
return provider && id ? `${provider}/${id}` : id;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function usageFrom(value) {
|
|
29
|
+
if (!value || typeof value !== "object") return undefined;
|
|
30
|
+
const usage = value.usage && typeof value.usage === "object" ? value.usage : value;
|
|
31
|
+
const normalized = {};
|
|
32
|
+
for (const key of ["input", "output", "cacheRead", "cacheWrite", "total"]) {
|
|
33
|
+
if (Number.isFinite(usage[key]) && usage[key] >= 0) normalized[key] = Math.floor(usage[key]);
|
|
34
|
+
}
|
|
35
|
+
return Object.keys(normalized).length ? normalized : undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function boundedTail(previous, chunk, maximum) {
|
|
39
|
+
const combined = Buffer.concat([Buffer.from(previous), Buffer.from(chunk)]);
|
|
40
|
+
return combined.subarray(Math.max(0, combined.length - maximum));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function sessionActivity(event) {
|
|
44
|
+
switch (event?.type) {
|
|
45
|
+
case "tool_execution_start": return { activityState: "tool", currentTool: text(event.toolName, 120) };
|
|
46
|
+
case "tool_execution_update": return { activityState: "tool", currentTool: text(event.toolName, 120) };
|
|
47
|
+
case "tool_execution_end": return { activityState: "thinking", currentTool: undefined };
|
|
48
|
+
case "message_start":
|
|
49
|
+
case "message_update": return { activityState: "responding", currentTool: undefined };
|
|
50
|
+
case "agent_start":
|
|
51
|
+
case "turn_start": return { activityState: "thinking", currentTool: undefined };
|
|
52
|
+
case "agent_settled": return { activityState: "idle", currentTool: undefined };
|
|
53
|
+
default: return {};
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function sdkAgentEndStatus(event) {
|
|
58
|
+
if (event?.type !== "agent_end" || event.willRetry === true || !Array.isArray(event.messages)) return undefined;
|
|
59
|
+
const assistant = [...event.messages].reverse().find((message) => message?.role === "assistant");
|
|
60
|
+
if (assistant?.stopReason === "aborted") return "cancelled";
|
|
61
|
+
if (assistant?.stopReason === "error") return "failed";
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function normalizedSdkEvent(event, now) {
|
|
66
|
+
const type = text(event?.type, 80) || "event";
|
|
67
|
+
const output = { type, at: now };
|
|
68
|
+
if (type.startsWith("tool_execution_")) output.tool = text(event.toolName, 120);
|
|
69
|
+
if (type === "tool_execution_end") output.isError = event.isError === true;
|
|
70
|
+
const usage = usageFrom(event?.message || event?.result || event);
|
|
71
|
+
if (usage) output.usage = usage;
|
|
72
|
+
return output;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function sdkRecord(session, state, options, now) {
|
|
76
|
+
return normalizeAgentInstance({
|
|
77
|
+
version: 1,
|
|
78
|
+
instanceId: options.instanceId,
|
|
79
|
+
runId: options.runId,
|
|
80
|
+
parentInstanceId: options.parentInstanceId || null,
|
|
81
|
+
parentSessionId: options.parentSessionId || null,
|
|
82
|
+
launcher: options.launcher || "sdk",
|
|
83
|
+
provider: "webui-registry",
|
|
84
|
+
origin: options.origin || "createAgentSession",
|
|
85
|
+
name: options.name || session.sessionName,
|
|
86
|
+
status: state.status,
|
|
87
|
+
startedAt: state.startedAt,
|
|
88
|
+
updatedAt: state.updatedAt,
|
|
89
|
+
endedAt: state.endedAt,
|
|
90
|
+
model: modelName(session.model) || options.model,
|
|
91
|
+
thinking: text(session.thinkingLevel || options.thinking, 40),
|
|
92
|
+
activityState: state.activityState,
|
|
93
|
+
currentTool: state.currentTool,
|
|
94
|
+
capabilities: { open: true, refresh: true, cancel: false, steer: false },
|
|
95
|
+
outputRef: { kind: "registry-artifact", id: options.recordId },
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Track a caller-owned AgentSession. Disposing tracking never disposes the session itself. */
|
|
100
|
+
export function trackPiAgentSession(options = {}) {
|
|
101
|
+
const { session, registry } = options;
|
|
102
|
+
if (!session || typeof session.subscribe !== "function") throw new TypeError("session.subscribe is required");
|
|
103
|
+
if (!registry || typeof registry.writeRecord !== "function" || typeof registry.appendArtifactEvent !== "function") throw new TypeError("registry is required");
|
|
104
|
+
const producerId = text(options.producerId, 80) || "sdk";
|
|
105
|
+
const recordId = options.recordId || createAgentRunRecordId();
|
|
106
|
+
const now = typeof options.now === "function" ? options.now : Date.now;
|
|
107
|
+
const startedAt = now();
|
|
108
|
+
const ids = {
|
|
109
|
+
instanceId: options.instanceId || `${text(session.sessionId, 100) || "sdk"}:${randomUUID()}`,
|
|
110
|
+
runId: options.runId || randomUUID(),
|
|
111
|
+
recordId,
|
|
112
|
+
};
|
|
113
|
+
const settings = { ...options, ...ids };
|
|
114
|
+
const state = { status: session.isStreaming ? "running" : "queued", startedAt, updatedAt: startedAt, endedAt: null, activityState: session.isStreaming ? "thinking" : "idle", currentTool: undefined };
|
|
115
|
+
let closed = false;
|
|
116
|
+
let observationError;
|
|
117
|
+
let queue = Promise.resolve();
|
|
118
|
+
const write = (event, { artifact = true } = {}) => {
|
|
119
|
+
const record = sdkRecord(session, { ...state }, settings, now);
|
|
120
|
+
const artifactEvent = event && artifact ? normalizedSdkEvent(event, state.updatedAt) : null;
|
|
121
|
+
queue = queue.then(async () => {
|
|
122
|
+
await registry.writeRecord(producerId, record, { recordId });
|
|
123
|
+
if (artifactEvent) await registry.appendArtifactEvent(producerId, recordId, artifactEvent);
|
|
124
|
+
}).catch((error) => {
|
|
125
|
+
observationError ||= text(error?.message || String(error), 240) || "Registry observation failed";
|
|
126
|
+
});
|
|
127
|
+
return queue;
|
|
128
|
+
};
|
|
129
|
+
const unsubscribe = session.subscribe((event) => {
|
|
130
|
+
if (closed) return;
|
|
131
|
+
state.updatedAt = now();
|
|
132
|
+
Object.assign(state, sessionActivity(event));
|
|
133
|
+
if (event.type === "agent_start") { state.status = "running"; state.endedAt = null; }
|
|
134
|
+
const agentEndStatus = sdkAgentEndStatus(event);
|
|
135
|
+
if (agentEndStatus) { state.status = agentEndStatus; state.endedAt = state.updatedAt; }
|
|
136
|
+
if (event.type === "agent_settled") {
|
|
137
|
+
if (!["failed", "cancelled"].includes(state.status)) state.status = "done";
|
|
138
|
+
state.endedAt = state.updatedAt;
|
|
139
|
+
}
|
|
140
|
+
void write(event);
|
|
141
|
+
});
|
|
142
|
+
const heartbeatMs = Math.max(1_000, Number(options.heartbeatMs) || 10_000);
|
|
143
|
+
const heartbeat = setInterval(() => {
|
|
144
|
+
if (closed || state.status !== "running") return;
|
|
145
|
+
state.updatedAt = now();
|
|
146
|
+
void write(null, { artifact: false });
|
|
147
|
+
}, heartbeatMs);
|
|
148
|
+
heartbeat.unref?.();
|
|
149
|
+
const ready = write({ type: "tracking_started" });
|
|
150
|
+
|
|
151
|
+
return Object.freeze({
|
|
152
|
+
instanceId: ids.instanceId,
|
|
153
|
+
runId: ids.runId,
|
|
154
|
+
recordId,
|
|
155
|
+
ready,
|
|
156
|
+
flush: () => queue,
|
|
157
|
+
get observationError() { return observationError; },
|
|
158
|
+
async dispose({ status } = {}) {
|
|
159
|
+
if (closed) return queue;
|
|
160
|
+
closed = true;
|
|
161
|
+
clearInterval(heartbeat);
|
|
162
|
+
unsubscribe();
|
|
163
|
+
if (status) {
|
|
164
|
+
if (!["done", "failed", "cancelled"].includes(status)) throw new TypeError("dispose status must be done, failed, or cancelled");
|
|
165
|
+
state.status = status;
|
|
166
|
+
state.updatedAt = now();
|
|
167
|
+
state.endedAt = state.updatedAt;
|
|
168
|
+
await write({ type: "tracking_disposed", status });
|
|
169
|
+
}
|
|
170
|
+
return queue;
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function structuredEvent(lineValue, launcher, now) {
|
|
176
|
+
const value = lineValue && typeof lineValue === "object" ? lineValue : {};
|
|
177
|
+
const event = value.type === "event" && value.event && typeof value.event === "object" ? value.event : value;
|
|
178
|
+
const type = value.type === "response" ? "rpc_response" : text(event.type, 80) || "event";
|
|
179
|
+
const output = { type, at: now };
|
|
180
|
+
if (type.startsWith("tool_execution_")) output.tool = text(event.toolName, 120);
|
|
181
|
+
if (type === "tool_execution_end") output.isError = event.isError === true;
|
|
182
|
+
const usage = usageFrom(event.message || event.result || event);
|
|
183
|
+
if (usage) output.usage = usage;
|
|
184
|
+
if (launcher === "pi-rpc" && value.type === "response") output.status = value.success === false ? "failed" : "ok";
|
|
185
|
+
return output;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function processRecord(state, options) {
|
|
189
|
+
return normalizeAgentInstance({
|
|
190
|
+
version: 1,
|
|
191
|
+
instanceId: options.instanceId,
|
|
192
|
+
runId: options.runId,
|
|
193
|
+
parentInstanceId: options.parentInstanceId || null,
|
|
194
|
+
parentSessionId: options.parentSessionId || null,
|
|
195
|
+
launcher: options.launcher,
|
|
196
|
+
provider: "webui-registry",
|
|
197
|
+
origin: options.origin || "pi-subprocess",
|
|
198
|
+
name: options.name,
|
|
199
|
+
status: state.status,
|
|
200
|
+
startedAt: state.startedAt,
|
|
201
|
+
updatedAt: state.updatedAt,
|
|
202
|
+
endedAt: state.endedAt,
|
|
203
|
+
model: options.model,
|
|
204
|
+
thinking: options.thinking,
|
|
205
|
+
activityState: state.activityState,
|
|
206
|
+
currentTool: state.currentTool,
|
|
207
|
+
capabilities: { open: true, refresh: true, cancel: false, steer: false },
|
|
208
|
+
outputRef: { kind: options.launcher === "pi-rpc" ? "rpc-events" : options.launcher === "pi-json" ? "json-events" : "plain-log", id: options.recordId },
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Spawn and observe a declared Pi argv. The adapter owns only the returned child process. */
|
|
213
|
+
export function startObservedPiProcess(options = {}) {
|
|
214
|
+
if (!SUBPROCESS_LAUNCHERS.has(options.launcher)) throw new TypeError("launcher must be pi-rpc, pi-json, or pi-print");
|
|
215
|
+
if (typeof options.command !== "string" || !options.command) throw new TypeError("command is required");
|
|
216
|
+
if (!Array.isArray(options.argv) || options.argv.some((arg) => typeof arg !== "string")) throw new TypeError("argv must be a string array");
|
|
217
|
+
const registry = options.registry;
|
|
218
|
+
if (!registry || typeof registry.writeRecord !== "function") throw new TypeError("registry is required");
|
|
219
|
+
const spawnImpl = options.spawnImpl || spawn;
|
|
220
|
+
const now = typeof options.now === "function" ? options.now : Date.now;
|
|
221
|
+
const outputBytes = Math.max(1_024, Math.min(Number(options.outputBytes) || DEFAULT_OUTPUT_BYTES, 4 * 1024 * 1024));
|
|
222
|
+
const producerId = text(options.producerId, 80) || "pi-process";
|
|
223
|
+
const recordId = options.recordId || createAgentRunRecordId();
|
|
224
|
+
const normalized = {
|
|
225
|
+
...options,
|
|
226
|
+
instanceId: options.instanceId || randomUUID(),
|
|
227
|
+
runId: options.runId || randomUUID(),
|
|
228
|
+
recordId,
|
|
229
|
+
model: text(options.model, 240),
|
|
230
|
+
thinking: text(options.thinking, 40),
|
|
231
|
+
};
|
|
232
|
+
const state = { status: "running", startedAt: now(), updatedAt: now(), endedAt: null, activityState: "starting", currentTool: undefined };
|
|
233
|
+
let stdoutTail = Buffer.alloc(0);
|
|
234
|
+
let stderrTail = Buffer.alloc(0);
|
|
235
|
+
let framing = "";
|
|
236
|
+
let cancelled = false;
|
|
237
|
+
let observationError;
|
|
238
|
+
let queue = Promise.resolve();
|
|
239
|
+
const enqueue = (operation) => {
|
|
240
|
+
queue = queue.then(operation).catch((error) => { observationError ||= text(error?.message || String(error), 240) || "Registry observation failed"; });
|
|
241
|
+
return queue;
|
|
242
|
+
};
|
|
243
|
+
const append = (event) => enqueue(() => registry.appendArtifactEvent(producerId, recordId, event));
|
|
244
|
+
const writeRecord = () => enqueue(() => registry.writeRecord(producerId, processRecord(state, normalized), { recordId }));
|
|
245
|
+
const child = spawnImpl(options.command, [...options.argv], {
|
|
246
|
+
cwd: options.cwd || process.cwd(),
|
|
247
|
+
env: options.env || process.env,
|
|
248
|
+
stdio: [options.stdin || "ignore", "pipe", "pipe"],
|
|
249
|
+
shell: false,
|
|
250
|
+
windowsHide: true,
|
|
251
|
+
detached: process.platform !== "win32",
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
const processStructuredChunk = (chunk) => {
|
|
255
|
+
framing += String(chunk);
|
|
256
|
+
const lines = framing.split("\n");
|
|
257
|
+
framing = lines.pop() || "";
|
|
258
|
+
for (let line of lines) {
|
|
259
|
+
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
260
|
+
if (!line) continue;
|
|
261
|
+
if (Buffer.byteLength(line) > 64 * 1024) { void append({ type: "invalid_frame", at: now(), status: "oversized" }); continue; }
|
|
262
|
+
try {
|
|
263
|
+
const event = structuredEvent(JSON.parse(line), options.launcher, now());
|
|
264
|
+
if (event.tool) { state.activityState = "tool"; state.currentTool = event.tool; }
|
|
265
|
+
else if (event.type === "message_update") { state.activityState = "responding"; state.currentTool = undefined; }
|
|
266
|
+
state.updatedAt = event.at;
|
|
267
|
+
void append(event);
|
|
268
|
+
} catch { void append({ type: "invalid_frame", at: now(), status: "malformed" }); }
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
child.stdout?.on("data", (chunk) => {
|
|
273
|
+
state.updatedAt = now();
|
|
274
|
+
options.stdoutSink?.write?.(chunk);
|
|
275
|
+
if (STRUCTURED_LAUNCHERS.has(options.launcher)) processStructuredChunk(chunk);
|
|
276
|
+
else {
|
|
277
|
+
stdoutTail = boundedTail(stdoutTail, chunk, outputBytes);
|
|
278
|
+
void append({ type: "output", stream: "stdout", at: state.updatedAt, message: String(chunk).slice(-8_192) });
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
child.stderr?.on("data", (chunk) => {
|
|
282
|
+
state.updatedAt = now();
|
|
283
|
+
options.stderrSink?.write?.(chunk);
|
|
284
|
+
stderrTail = boundedTail(stderrTail, chunk, outputBytes);
|
|
285
|
+
void append({ type: "output", stream: "stderr", at: state.updatedAt, message: String(chunk).slice(-8_192) });
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
const ready = writeRecord().then(() => append({ type: "process_started", at: state.startedAt }));
|
|
289
|
+
const heartbeatMs = Math.max(1_000, Number(options.heartbeatMs) || 10_000);
|
|
290
|
+
const heartbeat = setInterval(() => {
|
|
291
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
292
|
+
state.updatedAt = now();
|
|
293
|
+
void writeRecord();
|
|
294
|
+
}, heartbeatMs);
|
|
295
|
+
heartbeat.unref?.();
|
|
296
|
+
const completion = new Promise((resolve) => {
|
|
297
|
+
let settled = false;
|
|
298
|
+
const finish = async (status, detail = {}) => {
|
|
299
|
+
if (settled) return;
|
|
300
|
+
settled = true;
|
|
301
|
+
clearInterval(heartbeat);
|
|
302
|
+
state.status = status;
|
|
303
|
+
state.updatedAt = now();
|
|
304
|
+
state.endedAt = state.updatedAt;
|
|
305
|
+
state.activityState = "idle";
|
|
306
|
+
state.currentTool = undefined;
|
|
307
|
+
if (framing && STRUCTURED_LAUNCHERS.has(options.launcher)) await append({ type: "invalid_frame", at: state.updatedAt, status: "unterminated" });
|
|
308
|
+
await append({ type: "process_exit", at: state.updatedAt, status, ...detail });
|
|
309
|
+
await writeRecord();
|
|
310
|
+
await queue;
|
|
311
|
+
resolve(Object.freeze({ status, ...detail, observationError, stdout: stdoutTail.toString("utf8"), stderr: stderrTail.toString("utf8") }));
|
|
312
|
+
};
|
|
313
|
+
child.once("error", (error) => { void finish(cancelled ? "cancelled" : "failed", { error: text(error?.message || String(error), 240) }); });
|
|
314
|
+
child.once("close", (code, signal) => { void finish(cancelled ? "cancelled" : code === 0 ? "done" : "failed", { code, signal: text(signal, 32) }); });
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
const cancel = (signal = "SIGTERM") => {
|
|
318
|
+
if (child.exitCode !== null || child.signalCode !== null) return false;
|
|
319
|
+
cancelled = true;
|
|
320
|
+
return terminateProcessTree(child, signal);
|
|
321
|
+
};
|
|
322
|
+
const abortHandler = () => cancel("SIGTERM");
|
|
323
|
+
if (options.signal) {
|
|
324
|
+
if (options.signal.aborted) abortHandler();
|
|
325
|
+
else options.signal.addEventListener("abort", abortHandler, { once: true });
|
|
326
|
+
completion.finally(() => options.signal.removeEventListener("abort", abortHandler));
|
|
327
|
+
}
|
|
328
|
+
return Object.freeze({ child, ready, completion, cancel, instanceId: normalized.instanceId, runId: normalized.runId, recordId });
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Track an SDK session inside an extension and emit canonical complete snapshots on Pi's process-local event bus. */
|
|
332
|
+
export function trackPiAgentSessionEventBus(options = {}) {
|
|
333
|
+
const { session } = options;
|
|
334
|
+
const emit = options.emit || options.events?.emit?.bind(options.events);
|
|
335
|
+
if (!session || typeof session.subscribe !== "function") throw new TypeError("session.subscribe is required");
|
|
336
|
+
if (typeof emit !== "function") throw new TypeError("emit or events.emit is required");
|
|
337
|
+
const now = typeof options.now === "function" ? options.now : Date.now;
|
|
338
|
+
const producerId = text(options.producerId, 80) || "sdk";
|
|
339
|
+
const ids = {
|
|
340
|
+
instanceId: options.instanceId || `${text(session.sessionId, 100) || "sdk"}:${randomUUID()}`,
|
|
341
|
+
runId: options.runId || randomUUID(),
|
|
342
|
+
recordId: options.recordId || createAgentRunRecordId(),
|
|
343
|
+
};
|
|
344
|
+
const settings = { ...options, ...ids };
|
|
345
|
+
const startedAt = now();
|
|
346
|
+
const state = { status: session.isStreaming ? "running" : "queued", startedAt, updatedAt: startedAt, endedAt: null, activityState: session.isStreaming ? "thinking" : "idle", currentTool: undefined };
|
|
347
|
+
let closed = false;
|
|
348
|
+
let observationError;
|
|
349
|
+
const publish = () => {
|
|
350
|
+
try {
|
|
351
|
+
const instance = sdkRecord(session, { ...state }, settings, now);
|
|
352
|
+
emit(AGENT_RUN_PROVIDER_EVENT, { version: 1, producerId, complete: true, instances: [instance], removals: [] });
|
|
353
|
+
} catch (error) {
|
|
354
|
+
observationError ||= text(error?.message || String(error), 240) || "Event-bus observation failed";
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
const unsubscribe = session.subscribe((event) => {
|
|
358
|
+
if (closed) return;
|
|
359
|
+
state.updatedAt = now();
|
|
360
|
+
Object.assign(state, sessionActivity(event));
|
|
361
|
+
if (event.type === "agent_start") { state.status = "running"; state.endedAt = null; }
|
|
362
|
+
const endStatus = sdkAgentEndStatus(event);
|
|
363
|
+
if (endStatus) { state.status = endStatus; state.endedAt = state.updatedAt; }
|
|
364
|
+
if (event.type === "agent_settled") { if (!["failed", "cancelled"].includes(state.status)) state.status = "done"; state.endedAt = state.updatedAt; }
|
|
365
|
+
publish();
|
|
366
|
+
});
|
|
367
|
+
const heartbeat = setInterval(() => { if (!closed && state.status === "running") { state.updatedAt = now(); publish(); } }, Math.max(1_000, Number(options.heartbeatMs) || 10_000));
|
|
368
|
+
heartbeat.unref?.();
|
|
369
|
+
publish();
|
|
370
|
+
return Object.freeze({
|
|
371
|
+
instanceId: ids.instanceId, runId: ids.runId,
|
|
372
|
+
get observationError() { return observationError; },
|
|
373
|
+
dispose({ status } = {}) {
|
|
374
|
+
if (closed) return;
|
|
375
|
+
closed = true;
|
|
376
|
+
clearInterval(heartbeat);
|
|
377
|
+
unsubscribe();
|
|
378
|
+
if (status) {
|
|
379
|
+
if (!["done", "failed", "cancelled"].includes(status)) throw new TypeError("dispose status must be done, failed, or cancelled");
|
|
380
|
+
state.status = status; state.updatedAt = now(); state.endedAt = state.updatedAt; publish();
|
|
381
|
+
}
|
|
382
|
+
},
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function inside(root, candidate) {
|
|
387
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
388
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async function canonicalFileWithin(file, roots) {
|
|
392
|
+
const info = await lstat(file).catch(() => null);
|
|
393
|
+
if (!info?.isFile() || info.isSymbolicLink()) return null;
|
|
394
|
+
const target = await realpath(file).catch(() => null);
|
|
395
|
+
if (!target) return null;
|
|
396
|
+
for (const root of roots) {
|
|
397
|
+
const canonicalRoot = await realpath(root).catch(() => null);
|
|
398
|
+
if (canonicalRoot && inside(canonicalRoot, target) && target !== canonicalRoot) return target;
|
|
399
|
+
}
|
|
400
|
+
return null;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** Resolve an explicit session ID or file strictly through configured Pi session roots. */
|
|
404
|
+
export async function resolveAttachSession(options = {}) {
|
|
405
|
+
const selector = text(options.session, 4_096);
|
|
406
|
+
if (!selector) throw new TypeError("session is required");
|
|
407
|
+
const sessionRoots = (options.sessionRoots || []).map((root) => path.resolve(root));
|
|
408
|
+
if (!sessionRoots.length) throw new TypeError("at least one configured session root is required");
|
|
409
|
+
const managerType = options.SessionManagerImpl || SessionManager;
|
|
410
|
+
let candidate = null;
|
|
411
|
+
if (path.isAbsolute(selector) || selector.includes("/") || selector.includes("\\")) {
|
|
412
|
+
candidate = path.resolve(selector);
|
|
413
|
+
} else {
|
|
414
|
+
const sessions = await managerType.listAll(options.sessionDir);
|
|
415
|
+
const matches = sessions.filter((item) => item?.id === selector);
|
|
416
|
+
if (matches.length !== 1) throw Object.assign(new Error(matches.length ? "Session ID is ambiguous" : "Session ID was not found"), { code: matches.length ? "ATTACH_SESSION_AMBIGUOUS" : "ATTACH_SESSION_NOT_FOUND" });
|
|
417
|
+
candidate = matches[0].path;
|
|
418
|
+
}
|
|
419
|
+
const canonical = await canonicalFileWithin(candidate, sessionRoots);
|
|
420
|
+
if (!canonical) throw Object.assign(new Error("Session must be a regular file inside a configured Pi session root"), { code: "ATTACH_SESSION_OUTSIDE_ROOT" });
|
|
421
|
+
const manager = managerType.open(canonical, options.sessionDir);
|
|
422
|
+
return Object.freeze({
|
|
423
|
+
sessionFile: canonical,
|
|
424
|
+
sessionId: manager.getSessionId(),
|
|
425
|
+
name: manager.getSessionName?.(),
|
|
426
|
+
model: manager.buildSessionContext?.().model || null,
|
|
427
|
+
thinking: manager.buildSessionContext?.().thinkingLevel,
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function parseCli(args) {
|
|
432
|
+
const command = args[0];
|
|
433
|
+
const options = {};
|
|
434
|
+
const rest = [];
|
|
435
|
+
let afterSeparator = false;
|
|
436
|
+
for (let index = 1; index < args.length; index += 1) {
|
|
437
|
+
const arg = args[index];
|
|
438
|
+
if (afterSeparator) { rest.push(arg); continue; }
|
|
439
|
+
if (arg === "--") { afterSeparator = true; continue; }
|
|
440
|
+
if (["--launcher", "--name", "--parent-session", "--session", "--session-dir", "--port", "--producer"].includes(arg)) {
|
|
441
|
+
if (!args[index + 1]) throw new Error(`${arg} requires a value`);
|
|
442
|
+
options[arg.slice(2)] = args[++index];
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
throw new Error(`Unknown agent option: ${arg}`);
|
|
446
|
+
}
|
|
447
|
+
return { command, options, rest };
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export async function runAgentCli(args, context = {}) {
|
|
451
|
+
const output = context.output || process.stdout;
|
|
452
|
+
const errorOutput = context.errorOutput || process.stderr;
|
|
453
|
+
if (!args.length || ["help", "--help", "-h"].includes(args[0])) {
|
|
454
|
+
output.write("Usage:\n pi-webui agent run --launcher <rpc|json|print> [options] -- <command> [args...]\n pi-webui agent attach --session <id-or-file> [options]\n");
|
|
455
|
+
return 0;
|
|
456
|
+
}
|
|
457
|
+
const parsed = parseCli(args);
|
|
458
|
+
const agentDir = context.agentDir || process.env.PI_CODING_AGENT_DIR || path.join(homedir(), ".pi", "agent");
|
|
459
|
+
const port = Number(parsed.options.port || process.env.PI_WEBUI_PORT || 31415);
|
|
460
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("--port/PI_WEBUI_PORT must be an integer between 1 and 65535");
|
|
461
|
+
const registry = context.registry || new AgentRunRegistry({ agentDir, port });
|
|
462
|
+
await registry.init();
|
|
463
|
+
const scopeId = registry.paths?.scopeId || "custom-registry";
|
|
464
|
+
output.write(`WebUI registration: port=${port} scope=${scopeId}\n`);
|
|
465
|
+
if (parsed.command === "run") {
|
|
466
|
+
const launcher = { rpc: "pi-rpc", json: "pi-json", print: "pi-print" }[parsed.options.launcher] || parsed.options.launcher;
|
|
467
|
+
if (!SUBPROCESS_LAUNCHERS.has(launcher)) throw new Error("--launcher must be rpc, json, or print");
|
|
468
|
+
if (!parsed.rest.length) throw new Error("A command is required after --");
|
|
469
|
+
const observed = startObservedPiProcess({
|
|
470
|
+
registry, launcher, producerId: parsed.options.producer || "pi-webui-cli", command: parsed.rest[0], argv: parsed.rest.slice(1),
|
|
471
|
+
name: parsed.options.name, parentSessionId: parsed.options["parent-session"], cwd: context.cwd || process.cwd(), env: context.env || process.env,
|
|
472
|
+
stdin: "inherit", stdoutSink: output, stderrSink: errorOutput,
|
|
473
|
+
});
|
|
474
|
+
const result = await observed.completion;
|
|
475
|
+
if (result.observationError) return 1;
|
|
476
|
+
return result.status === "done" ? 0 : result.status === "cancelled" ? 130 : 1;
|
|
477
|
+
}
|
|
478
|
+
if (parsed.command === "attach") {
|
|
479
|
+
if (parsed.rest.length) throw new Error("attach does not accept a command after --");
|
|
480
|
+
const sessionDir = parsed.options["session-dir"] ? path.resolve(parsed.options["session-dir"]) : undefined;
|
|
481
|
+
const sessionRoots = sessionDir ? [sessionDir] : [path.join(agentDir, "sessions")];
|
|
482
|
+
const attached = await resolveAttachSession({ session: parsed.options.session, sessionDir, sessionRoots, SessionManagerImpl: context.SessionManagerImpl });
|
|
483
|
+
const now = Date.now();
|
|
484
|
+
const recordId = createAgentRunRecordId();
|
|
485
|
+
const model = attached.model?.provider && attached.model?.modelId ? `${attached.model.provider}/${attached.model.modelId}` : undefined;
|
|
486
|
+
const record = normalizeAgentInstance({
|
|
487
|
+
version: 1, instanceId: `${attached.sessionId}:${randomUUID()}`, runId: randomUUID(), parentInstanceId: null,
|
|
488
|
+
parentSessionId: parsed.options["parent-session"] || null, launcher: "interactive", provider: "webui-registry", origin: "explicit-attach",
|
|
489
|
+
name: parsed.options.name || attached.name, status: "stale", startedAt: now, updatedAt: now, endedAt: null,
|
|
490
|
+
model, thinking: attached.thinking, activityState: "idle", capabilities: { open: true, refresh: true, cancel: false, steer: false },
|
|
491
|
+
outputRef: { kind: "session-jsonl", id: recordId },
|
|
492
|
+
});
|
|
493
|
+
await registry.writeRecord(parsed.options.producer || "pi-webui-attach", record, { recordId });
|
|
494
|
+
await registry.writeSessionLocator(parsed.options.producer || "pi-webui-attach", recordId, attached.sessionFile, { allowedRoots: sessionRoots });
|
|
495
|
+
output.write(`${record.instanceId}\n`);
|
|
496
|
+
return 0;
|
|
497
|
+
}
|
|
498
|
+
errorOutput.write(`Unknown pi-webui agent command: ${parsed.command || ""}\n`);
|
|
499
|
+
return 2;
|
|
500
|
+
}
|