@firstpick/pi-package-webui 0.7.1 → 0.7.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 +7 -5
- package/bin/pi-webui.mjs +507 -66
- package/index.ts +4 -0
- package/lib/git-live-watcher.mjs +135 -0
- package/lib/git-message-artifacts.mjs +103 -0
- package/lib/process-tree.mjs +3 -1
- package/lib/subagent-gate.mjs +618 -0
- package/package.json +8 -6
- package/public/app.js +1261 -117
- package/public/index.html +25 -3
- package/public/styles.css +479 -4
- package/tests/app-runner-windows-conpty-harness.test.mjs +140 -0
- package/tests/danger-button-contrast-static.test.mjs +32 -0
- package/tests/fixtures/fake-pi.mjs +22 -4
- package/tests/footer-middle-truncation.test.mjs +118 -0
- package/tests/git-live-watcher.test.mjs +93 -0
- package/tests/git-message-artifacts.test.mjs +59 -0
- package/tests/git-panel-live-updates-static.test.mjs +54 -0
- package/tests/git-panel-render-stability-static.test.mjs +43 -0
- package/tests/guided-git-message-reliability-static.test.mjs +38 -0
- package/tests/http-endpoints-harness.test.mjs +103 -5
- package/tests/image-payload-hardening-harness.test.mjs +115 -0
- package/tests/mobile-static.test.mjs +74 -10
- package/tests/pi-footer-calibration-static.test.mjs +55 -0
- package/tests/runtime-error-visibility.test.mjs +63 -0
- package/tests/side-panel-context-menu-static.test.mjs +74 -0
- package/tests/subagent-gate.test.mjs +300 -0
- package/tests/subagents-helper.test.mjs +34 -3
- package/webui-rpc-helper.mjs +165 -11
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
|
|
4
|
+
export const SUBAGENT_GATE_UPDATE_EVENT = "webui:subagent-gate:v1:update";
|
|
5
|
+
export const SUBAGENT_GATE_PROTOCOL_VERSION = 1;
|
|
6
|
+
|
|
7
|
+
const SUBAGENT_RPC_VERSION = 1;
|
|
8
|
+
const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
|
|
9
|
+
const SUBAGENT_RPC_REPLY_PREFIX = "subagents:rpc:v1:reply:";
|
|
10
|
+
const SUBAGENT_ASYNC_COMPLETE_EVENT = "subagent:async-complete";
|
|
11
|
+
const DEFAULT_MAX_ATTEMPTS = 2;
|
|
12
|
+
const DEFAULT_GATE_TIMEOUT_MS = 30 * 60 * 1000;
|
|
13
|
+
const RPC_TIMEOUT_MS = 10_000;
|
|
14
|
+
const COMPLETION_CACHE_LIMIT = 128;
|
|
15
|
+
const COMPLETION_CACHE_TTL_MS = 10 * 60 * 1000;
|
|
16
|
+
const GATE_ATTEMPT_LIMIT = 100;
|
|
17
|
+
|
|
18
|
+
const RetrySafety = Type.String({
|
|
19
|
+
enum: ["read-only", "may-write"],
|
|
20
|
+
description: "Post-launch retry safety. Defaults to may-write; only read-only tasks may retry automatically after a child starts.",
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const GateTask = Type.Object({
|
|
24
|
+
agent: Type.String({ minLength: 1 }),
|
|
25
|
+
task: Type.String({ minLength: 1 }),
|
|
26
|
+
label: Type.Optional(Type.String()),
|
|
27
|
+
phase: Type.Optional(Type.String()),
|
|
28
|
+
model: Type.Optional(Type.String()),
|
|
29
|
+
fallbackModels: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { maxItems: 8 })),
|
|
30
|
+
context: Type.Optional(Type.String({ enum: ["fresh", "fork"] })),
|
|
31
|
+
cwd: Type.Optional(Type.String()),
|
|
32
|
+
skill: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "array", items: { type: "string" } }, { type: "boolean" }] })),
|
|
33
|
+
output: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "boolean" }] })),
|
|
34
|
+
outputMode: Type.Optional(Type.String({ enum: ["inline", "file-only"] })),
|
|
35
|
+
acceptance: Type.Optional(Type.Any()),
|
|
36
|
+
retrySafety: Type.Optional(RetrySafety),
|
|
37
|
+
}, { additionalProperties: false });
|
|
38
|
+
|
|
39
|
+
export const SubagentGateParams = Type.Object({
|
|
40
|
+
tasks: Type.Array(GateTask, { minItems: 1, maxItems: 20 }),
|
|
41
|
+
requiredSuccesses: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "Successful task slots required. Defaults to all tasks." })),
|
|
42
|
+
maxAttemptsPerTask: Type.Optional(Type.Integer({ minimum: 1, maximum: 5, description: "Total attempts per task slot, including the first. Defaults to 2." })),
|
|
43
|
+
requireDistinctProviders: Type.Optional(Type.Boolean({ description: "Count at most one successful task per provider family." })),
|
|
44
|
+
excludedProviders: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { maxItems: 12 })),
|
|
45
|
+
concurrency: Type.Optional(Type.Integer({ minimum: 1, maximum: 8 })),
|
|
46
|
+
attemptTimeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: 2 * 60 * 60 * 1000 })),
|
|
47
|
+
gateTimeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: 2 * 60 * 60 * 1000 })),
|
|
48
|
+
}, { additionalProperties: false });
|
|
49
|
+
|
|
50
|
+
function text(value, maxLength = 1000) {
|
|
51
|
+
const normalized = String(value ?? "").trim();
|
|
52
|
+
return normalized ? normalized.slice(0, maxLength) : "";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function uniqueStrings(values) {
|
|
56
|
+
const seen = new Set();
|
|
57
|
+
const result = [];
|
|
58
|
+
for (const value of values) {
|
|
59
|
+
const normalized = text(value, 240);
|
|
60
|
+
if (!normalized || seen.has(normalized)) continue;
|
|
61
|
+
seen.add(normalized);
|
|
62
|
+
result.push(normalized);
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function providerFromModel(model) {
|
|
68
|
+
const normalized = text(model, 240);
|
|
69
|
+
const slash = normalized.indexOf("/");
|
|
70
|
+
return (slash > 0 ? normalized.slice(0, slash) : normalized).toLowerCase();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function completionChild(result = {}) {
|
|
74
|
+
const children = Array.isArray(result.results) ? result.results : [];
|
|
75
|
+
return children.length === 1 ? children[0] || {} : {};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function completionOutput(result = {}) {
|
|
79
|
+
const child = completionChild(result);
|
|
80
|
+
return text(child.output || child.summary || result.summary || result.output, 50_000);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function completionModel(result = {}, requestedModel) {
|
|
84
|
+
const child = completionChild(result);
|
|
85
|
+
return text(child.model || result.model || requestedModel, 240);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function completionAcceptanceRejected(result = {}) {
|
|
89
|
+
const child = completionChild(result);
|
|
90
|
+
return child?.acceptance?.status === "rejected" || result?.acceptance?.status === "rejected";
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const TRANSIENT_PROVIDER_PATTERN = /(?:rate\s*limit|too many requests|\b429\b|quota|billing|credit|auth(?:entication)?|unauthori[sz]ed|forbidden|api key|token expired|invalid key|provider.*unavailable|model.*(?:unavailable|disabled|not found|load|fail|error)|unknown model|overloaded|service unavailable|temporar(?:ily)? unavailable|connection refused|fetch failed|network error|socket hang up|stream ended without finish_reason|upstream|cold.?start|\b50[234]\b)/i;
|
|
94
|
+
const DETERMINISTIC_CONFIGURATION_PATTERN = /(?:unknown agent|invalid (?:request|params|model scope)|out of scope|skills? not found|tool.+unavailable|missing required|must not have additional properties|does not exist)/i;
|
|
95
|
+
|
|
96
|
+
export function classifySubagentFailure(input = {}) {
|
|
97
|
+
const result = input.result || {};
|
|
98
|
+
const child = completionChild(result);
|
|
99
|
+
const error = text(input.error || child.error || result.error || result.summary, 4000);
|
|
100
|
+
const state = text(child.state || child.status || result.state, 80).toLowerCase();
|
|
101
|
+
const output = completionOutput(result);
|
|
102
|
+
|
|
103
|
+
if (input.phase === "spawn") {
|
|
104
|
+
if (input.code === "invalid_request" || input.code === "invalid_params" || DETERMINISTIC_CONFIGURATION_PATTERN.test(error)) {
|
|
105
|
+
return { kind: "configuration", retryable: false, reason: error || "Invalid subagent launch configuration." };
|
|
106
|
+
}
|
|
107
|
+
return { kind: "pre-launch", retryable: true, reason: error || "Subagent launch failed before a child run was created." };
|
|
108
|
+
}
|
|
109
|
+
if (result.stopped === true || child.stopped === true || state === "stopped") {
|
|
110
|
+
return { kind: "stopped", retryable: false, reason: error || "Subagent was stopped." };
|
|
111
|
+
}
|
|
112
|
+
if (result.interrupted === true || child.interrupted === true || state === "paused" || state === "interrupted") {
|
|
113
|
+
return { kind: "interrupted", retryable: false, reason: error || "Subagent was interrupted." };
|
|
114
|
+
}
|
|
115
|
+
if (result.timedOut === true || child.timedOut === true || /timed? out|timeout/i.test(error)) {
|
|
116
|
+
return { kind: "timeout", retryable: true, reason: error || "Subagent timed out." };
|
|
117
|
+
}
|
|
118
|
+
if (result.protocolError || child.protocolError) {
|
|
119
|
+
return { kind: "protocol", retryable: true, reason: error || "Subagent protocol failed." };
|
|
120
|
+
}
|
|
121
|
+
if (completionAcceptanceRejected(result)) {
|
|
122
|
+
return { kind: "acceptance", retryable: true, reason: error || "Subagent output failed acceptance." };
|
|
123
|
+
}
|
|
124
|
+
if (DETERMINISTIC_CONFIGURATION_PATTERN.test(error)) {
|
|
125
|
+
return { kind: "configuration", retryable: false, reason: error };
|
|
126
|
+
}
|
|
127
|
+
if (TRANSIENT_PROVIDER_PATTERN.test(error)) {
|
|
128
|
+
return { kind: "transient-provider", retryable: true, reason: error };
|
|
129
|
+
}
|
|
130
|
+
if (!output || output === "(no output)") {
|
|
131
|
+
return { kind: "empty-output", retryable: true, reason: error || "Subagent produced no usable output." };
|
|
132
|
+
}
|
|
133
|
+
return { kind: "task-failure", retryable: false, reason: error || "Subagent task failed." };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function isSuccessfulCompletion(result = {}) {
|
|
137
|
+
const child = completionChild(result);
|
|
138
|
+
const state = text(result.state, 80).toLowerCase();
|
|
139
|
+
const childSucceeded = typeof child.success === "boolean" ? child.success : undefined;
|
|
140
|
+
const success = result.success === true || (result.success === undefined && childSucceeded === true) || state === "complete" || state === "completed";
|
|
141
|
+
return success && childSucceeded !== false && !completionAcceptanceRejected(result) && Boolean(completionOutput(result)) && completionOutput(result) !== "(no output)";
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function attemptSnapshot(attempt) {
|
|
145
|
+
return {
|
|
146
|
+
id: attempt.id,
|
|
147
|
+
taskIndex: attempt.taskIndex,
|
|
148
|
+
attempt: attempt.attempt,
|
|
149
|
+
maxAttempts: attempt.maxAttempts,
|
|
150
|
+
agent: text(attempt.agent, 160),
|
|
151
|
+
label: text(attempt.label, 200) || undefined,
|
|
152
|
+
phase: text(attempt.phase, 120) || undefined,
|
|
153
|
+
retrySafety: attempt.retrySafety,
|
|
154
|
+
runId: text(attempt.runId, 160) || undefined,
|
|
155
|
+
retryOf: text(attempt.retryOf, 160) || undefined,
|
|
156
|
+
model: text(attempt.model, 240) || undefined,
|
|
157
|
+
provider: text(attempt.provider, 80) || undefined,
|
|
158
|
+
status: attempt.status,
|
|
159
|
+
failureKind: text(attempt.failureKind, 80) || undefined,
|
|
160
|
+
error: text(attempt.error, 1000) || undefined,
|
|
161
|
+
startedAt: attempt.startedAt,
|
|
162
|
+
endedAt: attempt.endedAt,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function gateSnapshot(gate) {
|
|
167
|
+
return {
|
|
168
|
+
version: SUBAGENT_GATE_PROTOCOL_VERSION,
|
|
169
|
+
id: gate.id,
|
|
170
|
+
status: gate.status,
|
|
171
|
+
requiredSuccesses: gate.requiredSuccesses,
|
|
172
|
+
qualifyingSuccesses: gate.qualifyingSuccesses,
|
|
173
|
+
requireDistinctProviders: gate.requireDistinctProviders,
|
|
174
|
+
startedAt: gate.startedAt,
|
|
175
|
+
updatedAt: gate.updatedAt,
|
|
176
|
+
endedAt: gate.endedAt,
|
|
177
|
+
attempts: gate.attempts.slice(-GATE_ATTEMPT_LIMIT).map(attemptSnapshot),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function rpcRequest(pi, method, params, { signal, timeoutMs = RPC_TIMEOUT_MS, preserveReplyOnAbort = false } = {}) {
|
|
182
|
+
const requestId = randomUUID();
|
|
183
|
+
return new Promise((resolve, reject) => {
|
|
184
|
+
let unsubscribe;
|
|
185
|
+
let settled = false;
|
|
186
|
+
const finish = (error, value) => {
|
|
187
|
+
if (settled) return;
|
|
188
|
+
settled = true;
|
|
189
|
+
clearTimeout(timeout);
|
|
190
|
+
signal?.removeEventListener("abort", abort);
|
|
191
|
+
if (typeof unsubscribe === "function") unsubscribe();
|
|
192
|
+
if (error) reject(error);
|
|
193
|
+
else resolve(value);
|
|
194
|
+
};
|
|
195
|
+
const abort = () => {
|
|
196
|
+
if (!preserveReplyOnAbort) finish(Object.assign(new Error("Subagent gate cancelled."), { name: "AbortError" }));
|
|
197
|
+
};
|
|
198
|
+
const timeout = setTimeout(() => finish(Object.assign(new Error(`pi-subagents RPC ${method} timed out.`), { code: "rpc_timeout" })), timeoutMs);
|
|
199
|
+
timeout.unref?.();
|
|
200
|
+
unsubscribe = pi.events.on(`${SUBAGENT_RPC_REPLY_PREFIX}${requestId}`, (reply) => {
|
|
201
|
+
if (reply?.success === false) {
|
|
202
|
+
finish(Object.assign(new Error(reply.error?.message || `pi-subagents RPC ${method} failed.`), { code: reply.error?.code || "execution_failed" }));
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
finish(null, reply?.data || {});
|
|
206
|
+
});
|
|
207
|
+
if (signal?.aborted) {
|
|
208
|
+
finish(Object.assign(new Error("Subagent gate cancelled."), { name: "AbortError" }));
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
212
|
+
try {
|
|
213
|
+
pi.events.emit(SUBAGENT_RPC_REQUEST_EVENT, {
|
|
214
|
+
version: SUBAGENT_RPC_VERSION,
|
|
215
|
+
requestId,
|
|
216
|
+
method,
|
|
217
|
+
params,
|
|
218
|
+
source: { extension: "@firstpick/pi-package-webui", feature: "subagent_gate" },
|
|
219
|
+
});
|
|
220
|
+
} catch (error) {
|
|
221
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function createCompletionRegistry(pi) {
|
|
227
|
+
const completed = new Map();
|
|
228
|
+
const waiters = new Map();
|
|
229
|
+
const prune = () => {
|
|
230
|
+
const cutoff = Date.now() - COMPLETION_CACHE_TTL_MS;
|
|
231
|
+
for (const [runId, entry] of completed) if (entry.receivedAt < cutoff) completed.delete(runId);
|
|
232
|
+
while (completed.size > COMPLETION_CACHE_LIMIT) completed.delete(completed.keys().next().value);
|
|
233
|
+
};
|
|
234
|
+
const unsubscribe = pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, (value) => {
|
|
235
|
+
const runId = text(value?.runId || value?.id, 160);
|
|
236
|
+
if (!runId) return;
|
|
237
|
+
const waiter = waiters.get(runId);
|
|
238
|
+
if (waiter) {
|
|
239
|
+
waiters.delete(runId);
|
|
240
|
+
waiter.resolve(value || {});
|
|
241
|
+
} else {
|
|
242
|
+
completed.set(runId, { value: value || {}, receivedAt: Date.now() });
|
|
243
|
+
prune();
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
return {
|
|
247
|
+
wait(runId, signal) {
|
|
248
|
+
const cached = completed.get(runId);
|
|
249
|
+
if (cached) {
|
|
250
|
+
completed.delete(runId);
|
|
251
|
+
return Promise.resolve(cached.value);
|
|
252
|
+
}
|
|
253
|
+
return new Promise((resolve, reject) => {
|
|
254
|
+
const abort = () => {
|
|
255
|
+
waiters.delete(runId);
|
|
256
|
+
reject(Object.assign(new Error("Subagent gate cancelled."), { name: "AbortError" }));
|
|
257
|
+
};
|
|
258
|
+
waiters.set(runId, {
|
|
259
|
+
resolve: (value) => {
|
|
260
|
+
signal?.removeEventListener("abort", abort);
|
|
261
|
+
resolve(value);
|
|
262
|
+
},
|
|
263
|
+
});
|
|
264
|
+
if (signal?.aborted) abort();
|
|
265
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
266
|
+
});
|
|
267
|
+
},
|
|
268
|
+
dispose() {
|
|
269
|
+
if (typeof unsubscribe === "function") unsubscribe();
|
|
270
|
+
for (const waiter of waiters.values()) waiter.resolve({ success: false, state: "stopped", summary: "Subagent gate extension disposed." });
|
|
271
|
+
waiters.clear();
|
|
272
|
+
completed.clear();
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function mapConcurrent(items, limit, fn) {
|
|
278
|
+
const results = new Array(items.length);
|
|
279
|
+
let next = 0;
|
|
280
|
+
async function worker() {
|
|
281
|
+
while (next < items.length) {
|
|
282
|
+
const index = next++;
|
|
283
|
+
results[index] = await fn(items[index], index);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
await Promise.all(Array.from({ length: Math.min(Math.max(1, limit), items.length) }, worker));
|
|
287
|
+
return results;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function modelForAttempt(task, attemptIndex, successfulProviders, requireDistinctProviders, excludedProviders) {
|
|
291
|
+
const declaredCandidates = uniqueStrings([task.model, ...(task.fallbackModels || [])]);
|
|
292
|
+
if (!declaredCandidates.length) return { model: undefined, exhausted: false };
|
|
293
|
+
const candidates = declaredCandidates.filter((candidate) => !excludedProviders.has(providerFromModel(candidate)));
|
|
294
|
+
const available = requireDistinctProviders
|
|
295
|
+
? candidates.filter((candidate) => !successfulProviders.has(providerFromModel(candidate)))
|
|
296
|
+
: candidates;
|
|
297
|
+
if (!available.length) return { model: undefined, exhausted: true };
|
|
298
|
+
return { model: available[Math.min(attemptIndex, available.length - 1)], exhausted: false };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function spawnParams(task, model, attemptTimeoutMs) {
|
|
302
|
+
return {
|
|
303
|
+
agent: task.agent,
|
|
304
|
+
task: task.task,
|
|
305
|
+
...(model ? { model } : {}),
|
|
306
|
+
...(task.context ? { context: task.context } : {}),
|
|
307
|
+
...(task.cwd ? { cwd: task.cwd } : {}),
|
|
308
|
+
...(task.skill !== undefined ? { skill: task.skill } : {}),
|
|
309
|
+
...(task.output !== undefined ? { output: task.output } : {}),
|
|
310
|
+
...(task.outputMode ? { outputMode: task.outputMode } : {}),
|
|
311
|
+
...(task.acceptance !== undefined ? { acceptance: task.acceptance } : {}),
|
|
312
|
+
...(attemptTimeoutMs ? { timeoutMs: attemptTimeoutMs } : {}),
|
|
313
|
+
async: true,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function formatGateResult(gate, slotResults) {
|
|
318
|
+
const lines = [
|
|
319
|
+
`Subagent gate ${gate.status}: ${gate.qualifyingSuccesses}/${gate.requiredSuccesses} qualifying successes.`,
|
|
320
|
+
`Attempts: ${gate.attempts.length}.`,
|
|
321
|
+
];
|
|
322
|
+
const failures = gate.attempts.filter((attempt) => attempt.status === "failed" || attempt.status === "not-qualifying" || attempt.status === "cancelled");
|
|
323
|
+
if (failures.length) lines.push(`Failures: ${failures.map((attempt) => `${attempt.agent}#${attempt.attempt} ${attempt.failureKind || "failed"}`).join(", ")}.`);
|
|
324
|
+
return {
|
|
325
|
+
content: [{ type: "text", text: lines.join("\n") }],
|
|
326
|
+
...(gate.status === "satisfied" ? {} : { isError: true }),
|
|
327
|
+
details: {
|
|
328
|
+
mode: "gate",
|
|
329
|
+
gate: gateSnapshot(gate),
|
|
330
|
+
results: slotResults.filter((slot) => slot && !slot.skipped).map((slot) => ({
|
|
331
|
+
taskIndex: slot.taskIndex,
|
|
332
|
+
agent: slot.agent,
|
|
333
|
+
success: slot.success,
|
|
334
|
+
output: slot.output,
|
|
335
|
+
model: slot.model,
|
|
336
|
+
provider: slot.provider,
|
|
337
|
+
runId: slot.runId,
|
|
338
|
+
error: slot.error,
|
|
339
|
+
})),
|
|
340
|
+
exhaustedSlots: slotResults.filter((slot) => slot && slot.success === false && !slot.skipped).map((slot) => slot.taskIndex),
|
|
341
|
+
skippedSlots: slotResults.filter((slot) => slot?.skipped).map((slot) => slot.taskIndex),
|
|
342
|
+
residualFailures: gate.attempts.filter((attempt) => attempt.status === "failed" || attempt.status === "not-qualifying" || attempt.status === "cancelled").map((attempt) => ({
|
|
343
|
+
taskIndex: attempt.taskIndex,
|
|
344
|
+
attempt: attempt.attempt,
|
|
345
|
+
kind: attempt.failureKind,
|
|
346
|
+
error: attempt.error,
|
|
347
|
+
})),
|
|
348
|
+
},
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export function registerSubagentGate(pi) {
|
|
353
|
+
const completionRegistry = createCompletionRegistry(pi);
|
|
354
|
+
const activeGates = new Map();
|
|
355
|
+
|
|
356
|
+
const emitGate = (gate) => {
|
|
357
|
+
gate.updatedAt = Date.now();
|
|
358
|
+
pi.events.emit(SUBAGENT_GATE_UPDATE_EVENT, gateSnapshot(gate));
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
const tool = {
|
|
362
|
+
name: "subagent_gate",
|
|
363
|
+
label: "Subagent Gate",
|
|
364
|
+
description: "Launch generic subagent task slots through pi-subagents RPC v1, require a success quorum, and perform bounded failure-aware retries. Post-launch retries require retrySafety='read-only'; may-write is the safe default.",
|
|
365
|
+
promptSnippet: "Run subagent tasks with bounded retries and a required success quorum",
|
|
366
|
+
promptGuidelines: [
|
|
367
|
+
"Use subagent_gate instead of raw subagent calls when a delegated result must be retried safely or a success quorum must be enforced.",
|
|
368
|
+
"Set each subagent_gate task retrySafety to read-only only when rerunning it cannot duplicate file mutations or external side effects; omission defaults to may-write.",
|
|
369
|
+
],
|
|
370
|
+
parameters: SubagentGateParams,
|
|
371
|
+
async execute(_toolCallId, params, signal, onUpdate) {
|
|
372
|
+
const requiredSuccesses = params.requiredSuccesses ?? params.tasks.length;
|
|
373
|
+
if (requiredSuccesses > params.tasks.length) throw new Error("requiredSuccesses cannot exceed the number of task slots.");
|
|
374
|
+
const maxAttempts = params.maxAttemptsPerTask ?? DEFAULT_MAX_ATTEMPTS;
|
|
375
|
+
const gateTimeoutMs = params.gateTimeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
|
|
376
|
+
const excludedProviders = new Set((params.excludedProviders || []).map((provider) => text(provider, 80).toLowerCase()).filter(Boolean));
|
|
377
|
+
const gate = {
|
|
378
|
+
id: randomUUID(),
|
|
379
|
+
status: "running",
|
|
380
|
+
requiredSuccesses,
|
|
381
|
+
qualifyingSuccesses: 0,
|
|
382
|
+
requireDistinctProviders: params.requireDistinctProviders === true,
|
|
383
|
+
startedAt: Date.now(),
|
|
384
|
+
updatedAt: Date.now(),
|
|
385
|
+
attempts: [],
|
|
386
|
+
};
|
|
387
|
+
activeGates.set(gate.id, gate);
|
|
388
|
+
emitGate(gate);
|
|
389
|
+
|
|
390
|
+
const controller = new AbortController();
|
|
391
|
+
let gateDeadlineReached = false;
|
|
392
|
+
const abort = () => controller.abort();
|
|
393
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
394
|
+
const timeout = setTimeout(() => {
|
|
395
|
+
gateDeadlineReached = true;
|
|
396
|
+
controller.abort();
|
|
397
|
+
}, gateTimeoutMs);
|
|
398
|
+
const activeRunIds = new Set();
|
|
399
|
+
const successfulProviders = new Set();
|
|
400
|
+
const slotResults = new Array(params.tasks.length);
|
|
401
|
+
|
|
402
|
+
const publishProgress = () => {
|
|
403
|
+
emitGate(gate);
|
|
404
|
+
onUpdate?.({
|
|
405
|
+
content: [{ type: "text", text: `Subagent gate running: ${gate.qualifyingSuccesses}/${gate.requiredSuccesses} qualifying successes across ${gate.attempts.length} attempts.` }],
|
|
406
|
+
details: { mode: "gate", gate: gateSnapshot(gate), results: [] },
|
|
407
|
+
});
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
const cancelAttempt = (attempt) => {
|
|
411
|
+
attempt.status = "cancelled";
|
|
412
|
+
attempt.failureKind = gateDeadlineReached ? "timeout" : "cancelled";
|
|
413
|
+
attempt.error = gateDeadlineReached ? "Subagent gate deadline reached." : "Subagent gate cancelled.";
|
|
414
|
+
attempt.endedAt = Date.now();
|
|
415
|
+
publishProgress();
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
const runSlot = async (task, taskIndex) => {
|
|
419
|
+
let previousRunId;
|
|
420
|
+
for (let attemptIndex = 0; attemptIndex < maxAttempts; attemptIndex++) {
|
|
421
|
+
if (controller.signal.aborted) break;
|
|
422
|
+
if (gate.qualifyingSuccesses >= gate.requiredSuccesses) {
|
|
423
|
+
const skipped = { taskIndex, agent: task.agent, success: false, skipped: true };
|
|
424
|
+
slotResults[taskIndex] = skipped;
|
|
425
|
+
return skipped;
|
|
426
|
+
}
|
|
427
|
+
const selection = modelForAttempt(task, attemptIndex, successfulProviders, gate.requireDistinctProviders, excludedProviders);
|
|
428
|
+
const model = selection.model;
|
|
429
|
+
const attempt = {
|
|
430
|
+
id: `${gate.id}:${taskIndex}:${attemptIndex + 1}`,
|
|
431
|
+
taskIndex,
|
|
432
|
+
attempt: attemptIndex + 1,
|
|
433
|
+
maxAttempts,
|
|
434
|
+
agent: task.agent,
|
|
435
|
+
label: task.label,
|
|
436
|
+
phase: task.phase,
|
|
437
|
+
retrySafety: task.retrySafety || "may-write",
|
|
438
|
+
retryOf: previousRunId,
|
|
439
|
+
model,
|
|
440
|
+
provider: providerFromModel(model),
|
|
441
|
+
status: "launching",
|
|
442
|
+
startedAt: Date.now(),
|
|
443
|
+
};
|
|
444
|
+
gate.attempts.push(attempt);
|
|
445
|
+
publishProgress();
|
|
446
|
+
|
|
447
|
+
if (selection.exhausted) {
|
|
448
|
+
attempt.status = "failed";
|
|
449
|
+
attempt.failureKind = "provider-exhausted";
|
|
450
|
+
attempt.error = "No declared model candidate can satisfy the gate's provider constraints.";
|
|
451
|
+
attempt.endedAt = Date.now();
|
|
452
|
+
slotResults[taskIndex] = { taskIndex, agent: task.agent, success: false, error: attempt.error };
|
|
453
|
+
publishProgress();
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
let spawn;
|
|
458
|
+
try {
|
|
459
|
+
spawn = await rpcRequest(pi, "spawn", spawnParams(task, model, params.attemptTimeoutMs), { signal: controller.signal, preserveReplyOnAbort: true });
|
|
460
|
+
} catch (error) {
|
|
461
|
+
if (controller.signal.aborted || error?.name === "AbortError") {
|
|
462
|
+
cancelAttempt(attempt);
|
|
463
|
+
break;
|
|
464
|
+
}
|
|
465
|
+
const classified = classifySubagentFailure({ phase: "spawn", code: error?.code, error: error?.message || error });
|
|
466
|
+
attempt.status = "failed";
|
|
467
|
+
attempt.failureKind = classified.kind;
|
|
468
|
+
attempt.error = classified.reason;
|
|
469
|
+
attempt.endedAt = Date.now();
|
|
470
|
+
publishProgress();
|
|
471
|
+
if (!classified.retryable || attemptIndex + 1 >= maxAttempts) {
|
|
472
|
+
slotResults[taskIndex] = { taskIndex, agent: task.agent, success: false, error: classified.reason };
|
|
473
|
+
break;
|
|
474
|
+
}
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const runId = text(spawn?.details?.asyncId || spawn?.details?.runId, 160);
|
|
479
|
+
if (!runId) {
|
|
480
|
+
if (controller.signal.aborted) {
|
|
481
|
+
cancelAttempt(attempt);
|
|
482
|
+
break;
|
|
483
|
+
}
|
|
484
|
+
const reason = "pi-subagents RPC spawn succeeded without an async run id; child creation is ambiguous.";
|
|
485
|
+
attempt.status = "failed";
|
|
486
|
+
attempt.failureKind = "protocol-ambiguous";
|
|
487
|
+
attempt.error = reason;
|
|
488
|
+
attempt.endedAt = Date.now();
|
|
489
|
+
publishProgress();
|
|
490
|
+
if (attempt.retrySafety !== "read-only" || attemptIndex + 1 >= maxAttempts) {
|
|
491
|
+
slotResults[taskIndex] = { taskIndex, agent: task.agent, success: false, error: reason };
|
|
492
|
+
break;
|
|
493
|
+
}
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
attempt.runId = runId;
|
|
498
|
+
previousRunId = runId;
|
|
499
|
+
activeRunIds.add(runId);
|
|
500
|
+
if (controller.signal.aborted) {
|
|
501
|
+
cancelAttempt(attempt);
|
|
502
|
+
break;
|
|
503
|
+
}
|
|
504
|
+
attempt.status = "running";
|
|
505
|
+
publishProgress();
|
|
506
|
+
|
|
507
|
+
let completion;
|
|
508
|
+
let completionSettled = false;
|
|
509
|
+
try {
|
|
510
|
+
completion = await completionRegistry.wait(runId, controller.signal);
|
|
511
|
+
completionSettled = true;
|
|
512
|
+
} catch (error) {
|
|
513
|
+
if (error?.name === "AbortError") {
|
|
514
|
+
cancelAttempt(attempt);
|
|
515
|
+
break;
|
|
516
|
+
}
|
|
517
|
+
completion = { success: false, state: "failed", summary: error?.message || String(error) };
|
|
518
|
+
completionSettled = true;
|
|
519
|
+
} finally {
|
|
520
|
+
if (completionSettled) activeRunIds.delete(runId);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const effectiveModel = completionModel(completion, model);
|
|
524
|
+
const provider = providerFromModel(effectiveModel);
|
|
525
|
+
attempt.model = effectiveModel || model;
|
|
526
|
+
attempt.provider = provider || attempt.provider;
|
|
527
|
+
attempt.endedAt = Date.now();
|
|
528
|
+
|
|
529
|
+
if (isSuccessfulCompletion(completion)) {
|
|
530
|
+
if (excludedProviders.has(provider)) {
|
|
531
|
+
attempt.status = "not-qualifying";
|
|
532
|
+
attempt.failureKind = "excluded-provider";
|
|
533
|
+
attempt.error = `Provider ${provider || "unknown"} is excluded by this gate.`;
|
|
534
|
+
} else if (gate.requireDistinctProviders && !provider) {
|
|
535
|
+
attempt.status = "not-qualifying";
|
|
536
|
+
attempt.failureKind = "provider-unknown";
|
|
537
|
+
attempt.error = "The effective provider is unknown, so provider diversity cannot be verified.";
|
|
538
|
+
} else if (gate.requireDistinctProviders && successfulProviders.has(provider)) {
|
|
539
|
+
attempt.status = "not-qualifying";
|
|
540
|
+
attempt.failureKind = "provider-diversity";
|
|
541
|
+
attempt.error = `Provider ${provider} already supplied a qualifying success.`;
|
|
542
|
+
} else {
|
|
543
|
+
attempt.status = "succeeded";
|
|
544
|
+
if (provider) successfulProviders.add(provider);
|
|
545
|
+
gate.qualifyingSuccesses += 1;
|
|
546
|
+
slotResults[taskIndex] = {
|
|
547
|
+
taskIndex,
|
|
548
|
+
agent: task.agent,
|
|
549
|
+
success: true,
|
|
550
|
+
output: completionOutput(completion),
|
|
551
|
+
model: effectiveModel || model,
|
|
552
|
+
provider,
|
|
553
|
+
runId,
|
|
554
|
+
};
|
|
555
|
+
publishProgress();
|
|
556
|
+
return slotResults[taskIndex];
|
|
557
|
+
}
|
|
558
|
+
} else {
|
|
559
|
+
const classified = classifySubagentFailure({ phase: "completion", result: completion });
|
|
560
|
+
attempt.status = "failed";
|
|
561
|
+
attempt.failureKind = classified.kind;
|
|
562
|
+
attempt.error = classified.reason;
|
|
563
|
+
}
|
|
564
|
+
publishProgress();
|
|
565
|
+
|
|
566
|
+
const postLaunchRetrySafe = attempt.retrySafety === "read-only";
|
|
567
|
+
const retryableFailure = attempt.failureKind === "provider-diversity" || attempt.failureKind === "provider-unknown" || attempt.failureKind === "excluded-provider"
|
|
568
|
+
? postLaunchRetrySafe
|
|
569
|
+
: postLaunchRetrySafe && classifySubagentFailure({ phase: "completion", result: completion }).retryable;
|
|
570
|
+
if (!retryableFailure || attemptIndex + 1 >= maxAttempts) {
|
|
571
|
+
slotResults[taskIndex] = {
|
|
572
|
+
taskIndex,
|
|
573
|
+
agent: task.agent,
|
|
574
|
+
success: false,
|
|
575
|
+
model: effectiveModel || model,
|
|
576
|
+
provider,
|
|
577
|
+
runId,
|
|
578
|
+
error: attempt.error,
|
|
579
|
+
};
|
|
580
|
+
break;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return slotResults[taskIndex];
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
try {
|
|
587
|
+
await mapConcurrent(params.tasks, params.concurrency ?? Math.min(4, params.tasks.length), runSlot);
|
|
588
|
+
gate.status = gate.qualifyingSuccesses >= gate.requiredSuccesses ? "satisfied" : gateDeadlineReached ? "failed" : controller.signal.aborted ? "cancelled" : "failed";
|
|
589
|
+
} finally {
|
|
590
|
+
clearTimeout(timeout);
|
|
591
|
+
signal?.removeEventListener("abort", abort);
|
|
592
|
+
if (controller.signal.aborted && activeRunIds.size) {
|
|
593
|
+
await Promise.allSettled([...activeRunIds].map((runId) => rpcRequest(pi, "stop", { id: runId }, { timeoutMs: RPC_TIMEOUT_MS })));
|
|
594
|
+
}
|
|
595
|
+
gate.endedAt = Date.now();
|
|
596
|
+
emitGate(gate);
|
|
597
|
+
activeGates.delete(gate.id);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const result = formatGateResult(gate, slotResults);
|
|
601
|
+
if (gate.status !== "satisfied") {
|
|
602
|
+
const error = new Error(result.content[0].text);
|
|
603
|
+
error.name = "SubagentGateError";
|
|
604
|
+
error.details = result.details;
|
|
605
|
+
throw error;
|
|
606
|
+
}
|
|
607
|
+
return result;
|
|
608
|
+
},
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
pi.registerTool(tool);
|
|
612
|
+
return {
|
|
613
|
+
dispose() {
|
|
614
|
+
completionRegistry.dispose();
|
|
615
|
+
activeGates.clear();
|
|
616
|
+
},
|
|
617
|
+
};
|
|
618
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@firstpick/pi-package-webui",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.3",
|
|
4
4
|
"description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://github.com/Firstp1ck/npm-packages/tree/main/pi-package-webui#readme",
|
|
@@ -51,13 +51,14 @@
|
|
|
51
51
|
"pi-webui": "./bin/pi-webui.mjs"
|
|
52
52
|
},
|
|
53
53
|
"scripts": {
|
|
54
|
-
"check": "node --check public/app.js && node --check public/voice-conversation.mjs && node --check public/aur-review-payload.mjs && node --check public/guided-git-command-state.mjs && node --check public/guided-git-review-state.mjs && node --check bin/pi-webui.mjs && node --check webui-rpc-helper.mjs && node --check lib/trust-boundaries.mjs && node --check lib/native-command-adapter.mjs && node --check lib/session-actions.mjs && node --check lib/auth-actions.mjs && node --check lib/temp-artifacts.mjs && node tests/run-all.mjs",
|
|
54
|
+
"check": "node --check public/app.js && node --check public/voice-conversation.mjs && node --check public/aur-review-payload.mjs && node --check public/guided-git-command-state.mjs && node --check public/guided-git-review-state.mjs && node --check bin/pi-webui.mjs && node --check webui-rpc-helper.mjs && node --check lib/git-live-watcher.mjs && node --check lib/git-message-artifacts.mjs && node --check lib/trust-boundaries.mjs && node --check lib/native-command-adapter.mjs && node --check lib/session-actions.mjs && node --check lib/auth-actions.mjs && node --check lib/temp-artifacts.mjs && node tests/run-all.mjs",
|
|
55
55
|
"test": "node tests/run-all.mjs"
|
|
56
56
|
},
|
|
57
57
|
"dependencies": {
|
|
58
|
-
"@earendil-works/pi-coding-agent": "^0.
|
|
58
|
+
"@earendil-works/pi-coding-agent": "^0.81.1",
|
|
59
59
|
"@firstpick/pi-utils": "^0.2.4",
|
|
60
|
-
"mermaid": "^11.15.0"
|
|
60
|
+
"mermaid": "^11.15.0",
|
|
61
|
+
"typebox": "^1.3.6"
|
|
61
62
|
},
|
|
62
63
|
"optionalDependencies": {
|
|
63
64
|
"@firstpick/pi-extension-bang-command-autocomplete": "^0.2.1",
|
|
@@ -73,8 +74,9 @@
|
|
|
73
74
|
"@firstpick/pi-extension-tools": "^0.1.6",
|
|
74
75
|
"@firstpick/pi-extension-workflows": "^0.1.4",
|
|
75
76
|
"@firstpick/pi-package-remote-webui": "^0.1.6",
|
|
76
|
-
"@firstpick/pi-prompts-git-pr": "^0.1.
|
|
77
|
-
"@firstpick/pi-themes-bundle": "^0.1.4"
|
|
77
|
+
"@firstpick/pi-prompts-git-pr": "^0.1.4",
|
|
78
|
+
"@firstpick/pi-themes-bundle": "^0.1.4",
|
|
79
|
+
"node-pty": "^1.1.0"
|
|
78
80
|
},
|
|
79
81
|
"files": [
|
|
80
82
|
"index.ts",
|