@blackbelt-technology/pi-dashboard-extension 0.5.0 → 0.5.1
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/package.json +11 -3
- package/src/__tests__/ask-user-tool.test.ts +1 -1
- package/src/__tests__/command-handler.test.ts +68 -0
- package/src/__tests__/enrich-model-metadata.test.ts +1 -1
- package/src/__tests__/no-tui-multiselect-arm-regression.test.ts +1 -1
- package/src/__tests__/provider-register-reload.test.ts +74 -0
- package/src/__tests__/retry-tracker.test.ts +147 -0
- package/src/__tests__/session-sync.test.ts +72 -0
- package/src/__tests__/usage-limit-orderer.test.ts +105 -0
- package/src/ask-user-tool.ts +1 -1
- package/src/bridge-context.ts +1 -1
- package/src/bridge.ts +59 -3
- package/src/command-handler.ts +59 -2
- package/src/flow-event-wiring.ts +1 -1
- package/src/multiselect-list.ts +1 -1
- package/src/pi-env.d.ts +16 -9
- package/src/provider-register.ts +16 -9
- package/src/retry-tracker.ts +123 -0
- package/src/session-sync.ts +10 -1
- package/src/usage-limit-orderer.ts +76 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blackbelt-technology/pi-dashboard-extension",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "Pi bridge extension for pi-dashboard",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -24,15 +24,23 @@
|
|
|
24
24
|
".pi/skills/pi-dashboard/"
|
|
25
25
|
],
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@blackbelt-technology/pi-dashboard-shared": "^0.5.
|
|
27
|
+
"@blackbelt-technology/pi-dashboard-shared": "^0.5.1",
|
|
28
28
|
"ws": "^8.18.0"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
32
|
+
"@earendil-works/pi-tui": "*",
|
|
31
33
|
"@mariozechner/pi-coding-agent": "*",
|
|
32
34
|
"@mariozechner/pi-tui": "*",
|
|
33
35
|
"typebox": "*"
|
|
34
36
|
},
|
|
35
37
|
"peerDependenciesMeta": {
|
|
38
|
+
"@earendil-works/pi-coding-agent": {
|
|
39
|
+
"optional": true
|
|
40
|
+
},
|
|
41
|
+
"@earendil-works/pi-tui": {
|
|
42
|
+
"optional": true
|
|
43
|
+
},
|
|
36
44
|
"@mariozechner/pi-coding-agent": {
|
|
37
45
|
"optional": true
|
|
38
46
|
},
|
|
@@ -41,7 +49,7 @@
|
|
|
41
49
|
}
|
|
42
50
|
},
|
|
43
51
|
"devDependencies": {
|
|
44
|
-
"@
|
|
52
|
+
"@earendil-works/pi-tui": "*",
|
|
45
53
|
"@types/ws": "^8.18.1",
|
|
46
54
|
"typebox": "^1.1.33"
|
|
47
55
|
}
|
|
@@ -201,6 +201,74 @@ describe("CommandHandler", () => {
|
|
|
201
201
|
await handler.handle({ type: "abort", sessionId: "s1" } as ServerToExtensionMessage);
|
|
202
202
|
});
|
|
203
203
|
|
|
204
|
+
it("abort schedules persistent-abort retries until isIdle returns true", async () => {
|
|
205
|
+
// See change: fix-provider-retry-infinite-loop.
|
|
206
|
+
vi.useFakeTimers();
|
|
207
|
+
const pi = createMockPi();
|
|
208
|
+
const abort = vi.fn();
|
|
209
|
+
let idleAfter = 3; // become idle after 3 polls
|
|
210
|
+
const isIdle = vi.fn(() => --idleAfter <= 0);
|
|
211
|
+
const handler = createCommandHandler(pi as any, "s1", { abort, isIdle, eventSink: vi.fn() });
|
|
212
|
+
|
|
213
|
+
await handler.handle({ type: "abort", sessionId: "s1" } as ServerToExtensionMessage);
|
|
214
|
+
expect(abort).toHaveBeenCalledOnce();
|
|
215
|
+
|
|
216
|
+
// Advance through the persistent-abort schedule. Each 200ms tick
|
|
217
|
+
// checks isIdle first, then calls abort if not idle.
|
|
218
|
+
vi.advanceTimersByTime(200); // tick 1: idleAfter 3→2, abort
|
|
219
|
+
vi.advanceTimersByTime(200); // tick 2: idleAfter 2→1, abort
|
|
220
|
+
vi.advanceTimersByTime(200); // tick 3: idleAfter 1→0, isIdle true, no abort, scheduler stops
|
|
221
|
+
vi.advanceTimersByTime(1000); // no more aborts
|
|
222
|
+
|
|
223
|
+
expect(abort.mock.calls.length).toBe(3); // initial + 2 retries
|
|
224
|
+
vi.useRealTimers();
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
it("persistent-abort scheduler stops after 2 seconds even if never idle", async () => {
|
|
228
|
+
vi.useFakeTimers();
|
|
229
|
+
const pi = createMockPi();
|
|
230
|
+
const abort = vi.fn();
|
|
231
|
+
const isIdle = vi.fn(() => false); // never idle
|
|
232
|
+
const handler = createCommandHandler(pi as any, "s1", { abort, isIdle, eventSink: vi.fn() });
|
|
233
|
+
|
|
234
|
+
await handler.handle({ type: "abort", sessionId: "s1" } as ServerToExtensionMessage);
|
|
235
|
+
|
|
236
|
+
vi.advanceTimersByTime(2500); // safely past 2s cap
|
|
237
|
+
// initial + ~10 retries (2000ms / 200ms)
|
|
238
|
+
const calls = abort.mock.calls.length;
|
|
239
|
+
expect(calls).toBeGreaterThanOrEqual(10);
|
|
240
|
+
expect(calls).toBeLessThanOrEqual(11);
|
|
241
|
+
|
|
242
|
+
// Past cap, no more calls
|
|
243
|
+
const before = abort.mock.calls.length;
|
|
244
|
+
vi.advanceTimersByTime(1000);
|
|
245
|
+
expect(abort.mock.calls.length).toBe(before);
|
|
246
|
+
vi.useRealTimers();
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it("abort synthesizes auto_retry_end event after invoking abort callback (provider-retry-state)", async () => {
|
|
250
|
+
// See change: fix-provider-retry-infinite-loop.
|
|
251
|
+
const pi = createMockPi();
|
|
252
|
+
const calls: Array<{ name: string; arg?: unknown }> = [];
|
|
253
|
+
const abort = vi.fn(() => calls.push({ name: "abort" }));
|
|
254
|
+
const eventSink = vi.fn((m: unknown) => calls.push({ name: "eventSink", arg: m }));
|
|
255
|
+
const handler = createCommandHandler(pi as any, "s1", { abort, eventSink });
|
|
256
|
+
|
|
257
|
+
await handler.handle({ type: "abort", sessionId: "s1" } as ServerToExtensionMessage);
|
|
258
|
+
|
|
259
|
+
expect(abort).toHaveBeenCalledOnce();
|
|
260
|
+
expect(eventSink).toHaveBeenCalledOnce();
|
|
261
|
+
// Order: abort() first, then synthesized event
|
|
262
|
+
expect(calls[0]!.name).toBe("abort");
|
|
263
|
+
expect(calls[1]!.name).toBe("eventSink");
|
|
264
|
+
const evt = (calls[1]!.arg as any);
|
|
265
|
+
expect(evt.type).toBe("event_forward");
|
|
266
|
+
expect(evt.sessionId).toBe("s1");
|
|
267
|
+
expect(evt.event.eventType).toBe("auto_retry_end");
|
|
268
|
+
expect(evt.event.data).toEqual({ success: false, attempt: -1, finalError: "Aborted by user" });
|
|
269
|
+
expect(typeof evt.event.timestamp).toBe("number");
|
|
270
|
+
});
|
|
271
|
+
|
|
204
272
|
it("should handle request_commands message", async () => {
|
|
205
273
|
const pi = createMockPi();
|
|
206
274
|
const handler = createCommandHandler(pi as any, "s1");
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* defaults when the probe has no match.
|
|
6
6
|
*
|
|
7
7
|
* The helper takes an optional `probe` parameter so unit tests can supply a
|
|
8
|
-
* fake catalog without needing `@
|
|
8
|
+
* fake catalog without needing `@earendil-works/pi-ai` installed — in
|
|
9
9
|
* production, registerEntry() injects `modelRegistry.find` as the probe.
|
|
10
10
|
*
|
|
11
11
|
* Spec: openspec/changes/enrich-custom-provider-model-metadata/specs/provider-auth-bridge/spec.md
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* pi 0.70's RPC mode (the only mode dashboard headless sessions run
|
|
12
12
|
* under) defines `ExtensionUIContext.custom` as an unconditional no-op
|
|
13
13
|
* (`async custom() { return undefined; }`, see
|
|
14
|
-
* `~/.nvm/.../@
|
|
14
|
+
* `~/.nvm/.../@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-mode.js`
|
|
15
15
|
* lines 150-153). Awaiting that primitive resolves to `undefined`
|
|
16
16
|
* synchronously, and the TUI arm's `bus.respond({ cancelled: true,
|
|
17
17
|
* source: "tui" })` triggers the PromptBus's first-response-wins
|
|
@@ -367,6 +367,80 @@ describe("reloadProviders", () => {
|
|
|
367
367
|
expect(opus.input).toEqual(["text", "image"]);
|
|
368
368
|
});
|
|
369
369
|
|
|
370
|
+
// ── custom-flag race regression (see change: fix-custom-provider-flag-race) ──
|
|
371
|
+
// The bridge's first `providers_list` push fires from `session_start`
|
|
372
|
+
// shortly after `activate()` kicked off async `registerEntry()` calls.
|
|
373
|
+
// The catalogue's `custom: true` flag MUST be set on that first push,
|
|
374
|
+
// even when each provider's `/v1/models` endpoint hasn't responded yet —
|
|
375
|
+
// otherwise custom providers from `~/.pi/agent/providers.json` leak into
|
|
376
|
+
// Settings → Provider Authentication → API Keys (where they don't belong;
|
|
377
|
+
// the LLM Providers section already manages them).
|
|
378
|
+
|
|
379
|
+
it("custom flag is set on first providers_list push, before discoverModels resolves (regression)", async () => {
|
|
380
|
+
const mod = await importFresh();
|
|
381
|
+
const { pi } = makeMockPi();
|
|
382
|
+
|
|
383
|
+
// Capture event handlers so we can fire model_select to set modelRegistryRef.
|
|
384
|
+
const handlers = new Map<string, (event: any, ctx: any) => Promise<void> | void>();
|
|
385
|
+
pi.on = vi.fn((event: string, handler: any) => { handlers.set(event, handler); });
|
|
386
|
+
|
|
387
|
+
// Stub fetch with a never-resolving promise — simulates a slow or
|
|
388
|
+
// unreachable /v1/models endpoint. The fix's correctness does NOT depend
|
|
389
|
+
// on this resolving; the synchronous `lastRegistered.set` runs before the
|
|
390
|
+
// await.
|
|
391
|
+
let resolveFetch: ((value: Response) => void) | null = null;
|
|
392
|
+
globalThis.fetch = vi.fn(
|
|
393
|
+
() => new Promise<Response>((r) => { resolveFetch = r; }),
|
|
394
|
+
) as any;
|
|
395
|
+
|
|
396
|
+
// Two custom providers. With the fix, both end up in lastRegistered
|
|
397
|
+
// synchronously when activate() iterates them.
|
|
398
|
+
writeProvidersJson(tmpHome, {
|
|
399
|
+
proxy: { baseUrl: "https://example.com/v1", apiKey: "sk-test", api: "openai-completions" },
|
|
400
|
+
"your-llmproxy": { baseUrl: "https://example2.com/v1", apiKey: "sk-test", api: "openai-completions" },
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
// activate() fires registerEntry async (.catch(() => {})). The synchronous
|
|
404
|
+
// body runs to the first await before yielding.
|
|
405
|
+
mod.activate(pi);
|
|
406
|
+
|
|
407
|
+
// Capture modelRegistry via a model_select event — buildProviderCatalogue()
|
|
408
|
+
// returns [] when modelRegistryRef is null. We use model_select rather
|
|
409
|
+
// than session_start because session_start would re-register every entry
|
|
410
|
+
// (also stalling on the never-resolving fetch).
|
|
411
|
+
const fakeRegistry = {
|
|
412
|
+
find: () => null,
|
|
413
|
+
getAll: () => [
|
|
414
|
+
{ provider: "proxy", id: "some-model" },
|
|
415
|
+
{ provider: "your-llmproxy", id: "some-model" },
|
|
416
|
+
{ provider: "deepseek", id: "deepseek-chat" },
|
|
417
|
+
],
|
|
418
|
+
getProviderDisplayName: (id: string) => id,
|
|
419
|
+
authStorage: {
|
|
420
|
+
getOAuthProviders: () => [],
|
|
421
|
+
getAuthStatus: () => ({ configured: false }),
|
|
422
|
+
get: () => undefined,
|
|
423
|
+
},
|
|
424
|
+
};
|
|
425
|
+
const modelSelectHandler = handlers.get("model_select");
|
|
426
|
+
expect(modelSelectHandler).toBeDefined();
|
|
427
|
+
await modelSelectHandler!({}, { modelRegistry: fakeRegistry, model: undefined });
|
|
428
|
+
|
|
429
|
+
// Build the catalogue while discovery is still in flight. With the fix,
|
|
430
|
+
// both custom providers are flagged custom: true. Without it, lastRegistered
|
|
431
|
+
// is still empty (the post-await `lastRegistered.set` never runs because
|
|
432
|
+
// fetch never resolves) and the flags are missing.
|
|
433
|
+
const cat = mod.buildProviderCatalogue();
|
|
434
|
+
|
|
435
|
+
expect(cat.find((c) => c.id === "proxy")?.custom).toBe(true);
|
|
436
|
+
expect(cat.find((c) => c.id === "your-llmproxy")?.custom).toBe(true);
|
|
437
|
+
// Built-in pi-ai providers must remain unflagged.
|
|
438
|
+
expect(cat.find((c) => c.id === "deepseek")?.custom).toBeUndefined();
|
|
439
|
+
|
|
440
|
+
// Cleanup: settle the dangling fetches so the test process doesn't leak.
|
|
441
|
+
if (resolveFetch) (resolveFetch as (value: Response) => void)(new Response(JSON.stringify({ data: [] }), { status: 200 }));
|
|
442
|
+
});
|
|
443
|
+
|
|
370
444
|
it("discovered unknown model falls back to api-appropriate defaults (openai-completions → 128k)", async () => {
|
|
371
445
|
const mod = await importFresh();
|
|
372
446
|
const { pi, registerProvider } = makeMockPi();
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { RetryTracker, RETRYABLE_PATTERN } from "../retry-tracker.js";
|
|
3
|
+
|
|
4
|
+
describe("RetryTracker", () => {
|
|
5
|
+
it("synthesizes auto_retry_start on retryable assistant error", () => {
|
|
6
|
+
const t = new RetryTracker();
|
|
7
|
+
const ev = t.observeMessageEnd("s1", {
|
|
8
|
+
role: "assistant",
|
|
9
|
+
stopReason: "error",
|
|
10
|
+
errorMessage: "rate limit exceeded",
|
|
11
|
+
});
|
|
12
|
+
expect(ev).not.toBeNull();
|
|
13
|
+
expect(ev!.eventType).toBe("auto_retry_start");
|
|
14
|
+
expect(ev!.data).toEqual({
|
|
15
|
+
attempt: 1,
|
|
16
|
+
maxAttempts: -1,
|
|
17
|
+
delayMs: -1,
|
|
18
|
+
errorMessage: "rate limit exceeded",
|
|
19
|
+
});
|
|
20
|
+
expect(t.isRetrying("s1")).toBe(true);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it("does not synthesize for non-retryable error (e.g. context overflow)", () => {
|
|
24
|
+
const t = new RetryTracker();
|
|
25
|
+
const ev = t.observeMessageEnd("s1", {
|
|
26
|
+
role: "assistant",
|
|
27
|
+
stopReason: "error",
|
|
28
|
+
errorMessage: "prompt is too long: 300000 tokens > 200000 maximum",
|
|
29
|
+
});
|
|
30
|
+
expect(ev).toBeNull();
|
|
31
|
+
expect(t.isRetrying("s1")).toBe(false);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("does not synthesize for non-assistant messages", () => {
|
|
35
|
+
const t = new RetryTracker();
|
|
36
|
+
expect(t.observeMessageEnd("s1", { role: "user" })).toBeNull();
|
|
37
|
+
expect(t.observeMessageEnd("s1", { role: "toolResult", stopReason: "error" })).toBeNull();
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("does not synthesize for missing or empty errorMessage", () => {
|
|
41
|
+
const t = new RetryTracker();
|
|
42
|
+
expect(t.observeMessageEnd("s1", { role: "assistant", stopReason: "error" })).toBeNull();
|
|
43
|
+
expect(
|
|
44
|
+
t.observeMessageEnd("s1", { role: "assistant", stopReason: "error", errorMessage: "" }),
|
|
45
|
+
).toBeNull();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("increments attempt counter across multiple retryable errors", () => {
|
|
49
|
+
const t = new RetryTracker();
|
|
50
|
+
const a = t.observeMessageEnd("s1", { role: "assistant", stopReason: "error", errorMessage: "429" });
|
|
51
|
+
const b = t.observeMessageEnd("s1", { role: "assistant", stopReason: "error", errorMessage: "429" });
|
|
52
|
+
const c = t.observeMessageEnd("s1", { role: "assistant", stopReason: "error", errorMessage: "429" });
|
|
53
|
+
expect((a!.data as any).attempt).toBe(1);
|
|
54
|
+
expect((b!.data as any).attempt).toBe(2);
|
|
55
|
+
expect((c!.data as any).attempt).toBe(3);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("synthesizes auto_retry_end success on successful assistant message_end after retry", () => {
|
|
59
|
+
const t = new RetryTracker();
|
|
60
|
+
t.observeMessageEnd("s1", { role: "assistant", stopReason: "error", errorMessage: "429" });
|
|
61
|
+
const ev = t.observeMessageEnd("s1", { role: "assistant", stopReason: "end_turn" });
|
|
62
|
+
expect(ev).not.toBeNull();
|
|
63
|
+
expect(ev!.eventType).toBe("auto_retry_end");
|
|
64
|
+
expect(ev!.data).toEqual({ success: true, attempt: 1 });
|
|
65
|
+
expect(t.isRetrying("s1")).toBe(false);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("does not synthesize auto_retry_end when no retry was tracked", () => {
|
|
69
|
+
const t = new RetryTracker();
|
|
70
|
+
expect(t.observeMessageEnd("s1", { role: "assistant", stopReason: "end_turn" })).toBeNull();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("synthesizes auto_retry_end failure on agent_end with terminal error", () => {
|
|
74
|
+
const t = new RetryTracker();
|
|
75
|
+
t.observeMessageEnd("s1", { role: "assistant", stopReason: "error", errorMessage: "rate limit" });
|
|
76
|
+
t.observeMessageEnd("s1", { role: "assistant", stopReason: "error", errorMessage: "rate limit" });
|
|
77
|
+
const ev = t.observeAgentEnd("s1", {
|
|
78
|
+
messages: [{ role: "assistant", stopReason: "error", errorMessage: "Rate limit exceeded permanently" }],
|
|
79
|
+
});
|
|
80
|
+
expect(ev).not.toBeNull();
|
|
81
|
+
expect(ev!.eventType).toBe("auto_retry_end");
|
|
82
|
+
expect(ev!.data).toEqual({
|
|
83
|
+
success: false,
|
|
84
|
+
attempt: 2,
|
|
85
|
+
finalError: "Rate limit exceeded permanently",
|
|
86
|
+
});
|
|
87
|
+
expect(t.isRetrying("s1")).toBe(false);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("synthesizes auto_retry_end success on agent_end with non-error terminal message", () => {
|
|
91
|
+
const t = new RetryTracker();
|
|
92
|
+
t.observeMessageEnd("s1", { role: "assistant", stopReason: "error", errorMessage: "429" });
|
|
93
|
+
const ev = t.observeAgentEnd("s1", {
|
|
94
|
+
messages: [{ role: "assistant", stopReason: "end_turn" }],
|
|
95
|
+
});
|
|
96
|
+
expect(ev).not.toBeNull();
|
|
97
|
+
expect((ev!.data as any).success).toBe(true);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("agent_end without prior retry returns null", () => {
|
|
101
|
+
const t = new RetryTracker();
|
|
102
|
+
expect(t.observeAgentEnd("s1", { messages: [] })).toBeNull();
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("noteAbort clears tracker so subsequent agent_end does not double-emit", () => {
|
|
106
|
+
const t = new RetryTracker();
|
|
107
|
+
t.observeMessageEnd("s1", { role: "assistant", stopReason: "error", errorMessage: "429" });
|
|
108
|
+
t.noteAbort("s1");
|
|
109
|
+
expect(t.isRetrying("s1")).toBe(false);
|
|
110
|
+
expect(t.observeAgentEnd("s1", { messages: [] })).toBeNull();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("scopes retry state per-session", () => {
|
|
114
|
+
const t = new RetryTracker();
|
|
115
|
+
t.observeMessageEnd("s1", { role: "assistant", stopReason: "error", errorMessage: "429" });
|
|
116
|
+
expect(t.isRetrying("s1")).toBe(true);
|
|
117
|
+
expect(t.isRetrying("s2")).toBe(false);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it.each([
|
|
121
|
+
"rate limit exceeded",
|
|
122
|
+
"Rate Limit hit",
|
|
123
|
+
"overloaded_error",
|
|
124
|
+
"too many requests",
|
|
125
|
+
"HTTP 429",
|
|
126
|
+
"HTTP 500 Internal Server Error",
|
|
127
|
+
"service unavailable",
|
|
128
|
+
"fetch failed",
|
|
129
|
+
"socket hang up",
|
|
130
|
+
"connection refused",
|
|
131
|
+
"connection lost",
|
|
132
|
+
"request timed out",
|
|
133
|
+
"terminated",
|
|
134
|
+
"retry delay exceeded",
|
|
135
|
+
])("RETRYABLE_PATTERN matches: %s", (msg) => {
|
|
136
|
+
expect(RETRYABLE_PATTERN.test(msg)).toBe(true);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it.each([
|
|
140
|
+
"prompt is too long: 300000 tokens > 200000 maximum",
|
|
141
|
+
"tool execution failed",
|
|
142
|
+
"invalid input",
|
|
143
|
+
"",
|
|
144
|
+
])("RETRYABLE_PATTERN does NOT match: %s", (msg) => {
|
|
145
|
+
expect(RETRYABLE_PATTERN.test(msg)).toBe(false);
|
|
146
|
+
});
|
|
147
|
+
});
|
|
@@ -133,3 +133,75 @@ describe("handleSessionChange", () => {
|
|
|
133
133
|
expect(registerMsg.registerReason).toBe("spawn");
|
|
134
134
|
});
|
|
135
135
|
});
|
|
136
|
+
|
|
137
|
+
// See change: spawn-correlation-token — bridge token inclusion contract.
|
|
138
|
+
describe("sendStateSync: spawnToken from env", () => {
|
|
139
|
+
const ENV_VAR = "PI_DASHBOARD_SPAWN_TOKEN";
|
|
140
|
+
|
|
141
|
+
function withEnvVar<T>(value: string | undefined, fn: () => T): T {
|
|
142
|
+
const prior = process.env[ENV_VAR];
|
|
143
|
+
if (value === undefined) delete process.env[ENV_VAR];
|
|
144
|
+
else process.env[ENV_VAR] = value;
|
|
145
|
+
try {
|
|
146
|
+
return fn();
|
|
147
|
+
} finally {
|
|
148
|
+
if (prior === undefined) delete process.env[ENV_VAR];
|
|
149
|
+
else process.env[ENV_VAR] = prior;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
it("first register includes spawnToken from env", () => {
|
|
154
|
+
withEnvVar("tok_first", () => {
|
|
155
|
+
const bc = createMockBridgeContext({ hasRegisteredOnce: false } as any);
|
|
156
|
+
sendStateSync(bc, () => []);
|
|
157
|
+
const sent = (bc as any)._sent;
|
|
158
|
+
const registerMsg = sent.find((m: any) => m.type === "session_register");
|
|
159
|
+
expect(registerMsg.spawnToken).toBe("tok_first");
|
|
160
|
+
expect(registerMsg.registerReason).toBe("spawn");
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("reattach register omits spawnToken (even when env still set)", () => {
|
|
165
|
+
withEnvVar("tok_first", () => {
|
|
166
|
+
const bc = createMockBridgeContext({ hasRegisteredOnce: true } as any);
|
|
167
|
+
sendStateSync(bc, () => []);
|
|
168
|
+
const sent = (bc as any)._sent;
|
|
169
|
+
const registerMsg = sent.find((m: any) => m.type === "session_register");
|
|
170
|
+
expect(registerMsg.spawnToken).toBeUndefined();
|
|
171
|
+
expect(registerMsg.registerReason).toBe("reattach");
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it("first register without env var omits spawnToken", () => {
|
|
176
|
+
withEnvVar(undefined, () => {
|
|
177
|
+
const bc = createMockBridgeContext({ hasRegisteredOnce: false } as any);
|
|
178
|
+
sendStateSync(bc, () => []);
|
|
179
|
+
const sent = (bc as any)._sent;
|
|
180
|
+
const registerMsg = sent.find((m: any) => m.type === "session_register");
|
|
181
|
+
expect(registerMsg.spawnToken).toBeUndefined();
|
|
182
|
+
expect(registerMsg.registerReason).toBe("spawn");
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it("handleSessionChange register omits spawnToken (in-process new/fork/resume)", () => {
|
|
187
|
+
withEnvVar("tok_first", () => {
|
|
188
|
+
const bc = createMockBridgeContext({ hasRegisteredOnce: true } as any);
|
|
189
|
+
const ctx = {
|
|
190
|
+
cwd: "/proj",
|
|
191
|
+
sessionManager: {
|
|
192
|
+
getSessionId: () => "sess-fork",
|
|
193
|
+
getSessionFile: () => "/path/new.json",
|
|
194
|
+
getSessionDir: () => "/path",
|
|
195
|
+
getBranch: () => [],
|
|
196
|
+
getEntries: () => [],
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
handleSessionChange(bc, ctx as any, () => []);
|
|
200
|
+
const sent = (bc as any)._sent;
|
|
201
|
+
const registerMsg = sent.find((m: any) => m.type === "session_register" && m.sessionId === "sess-fork");
|
|
202
|
+
expect(registerMsg).toBeDefined();
|
|
203
|
+
expect(registerMsg.spawnToken).toBeUndefined();
|
|
204
|
+
expect(registerMsg.registerReason).toBe("spawn");
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
});
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { UsageLimitOrderer, USAGE_LIMIT_PATTERN } from "../usage-limit-orderer.js";
|
|
3
|
+
|
|
4
|
+
describe("UsageLimitOrderer", () => {
|
|
5
|
+
it("returns null when no retry was pending", () => {
|
|
6
|
+
const o = new UsageLimitOrderer();
|
|
7
|
+
const result = o.maybeSynthesize("s1", {
|
|
8
|
+
messages: [{ role: "assistant", stopReason: "error", errorMessage: "usage_limit_reached" }],
|
|
9
|
+
});
|
|
10
|
+
expect(result).toBeNull();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it("returns null when retry was pending but error is not a usage-limit", () => {
|
|
14
|
+
const o = new UsageLimitOrderer();
|
|
15
|
+
o.noteRetryStart("s1");
|
|
16
|
+
const result = o.maybeSynthesize("s1", {
|
|
17
|
+
messages: [{ role: "assistant", stopReason: "error", errorMessage: "tool execution failed" }],
|
|
18
|
+
});
|
|
19
|
+
expect(result).toBeNull();
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("returns null on a non-error agent_end even with pending retry", () => {
|
|
23
|
+
const o = new UsageLimitOrderer();
|
|
24
|
+
o.noteRetryStart("s1");
|
|
25
|
+
const result = o.maybeSynthesize("s1", {
|
|
26
|
+
messages: [{ role: "assistant", stopReason: "end_turn" }],
|
|
27
|
+
});
|
|
28
|
+
expect(result).toBeNull();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("synthesizes auto_retry_end on usage_limit_reached when retry was pending", () => {
|
|
32
|
+
const o = new UsageLimitOrderer();
|
|
33
|
+
o.noteRetryStart("s1");
|
|
34
|
+
const result = o.maybeSynthesize("s1", {
|
|
35
|
+
messages: [{ role: "assistant", stopReason: "error", errorMessage: "usage_limit_reached: 5000 RPM" }],
|
|
36
|
+
});
|
|
37
|
+
expect(result).not.toBeNull();
|
|
38
|
+
expect(result!.eventType).toBe("auto_retry_end");
|
|
39
|
+
expect(result!.data).toEqual({ success: false, attempt: -1, finalError: "usage_limit_reached: 5000 RPM" });
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it.each([
|
|
43
|
+
"usage_limit_reached",
|
|
44
|
+
"usage_not_included",
|
|
45
|
+
"quota_exceeded",
|
|
46
|
+
"monthly limit reached for free tier",
|
|
47
|
+
"hourly limit hit",
|
|
48
|
+
"Your quota will reset after 18h31m10s",
|
|
49
|
+
])("matches usage-limit variant: %s", (msg) => {
|
|
50
|
+
expect(USAGE_LIMIT_PATTERN.test(msg)).toBe(true);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it.each([
|
|
54
|
+
"rate limit exceeded",
|
|
55
|
+
"overloaded_error",
|
|
56
|
+
"tool execution failed",
|
|
57
|
+
"fetch failed",
|
|
58
|
+
"",
|
|
59
|
+
])("does not match non-usage-limit variant: %s", (msg) => {
|
|
60
|
+
expect(USAGE_LIMIT_PATTERN.test(msg)).toBe(false);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("clears pending after agent_end (no double-synthesis on subsequent agent_end)", () => {
|
|
64
|
+
const o = new UsageLimitOrderer();
|
|
65
|
+
o.noteRetryStart("s1");
|
|
66
|
+
const first = o.maybeSynthesize("s1", {
|
|
67
|
+
messages: [{ role: "assistant", stopReason: "error", errorMessage: "usage_limit_reached" }],
|
|
68
|
+
});
|
|
69
|
+
expect(first).not.toBeNull();
|
|
70
|
+
// Same payload again — pending was cleared, so no synthesis.
|
|
71
|
+
const second = o.maybeSynthesize("s1", {
|
|
72
|
+
messages: [{ role: "assistant", stopReason: "error", errorMessage: "usage_limit_reached" }],
|
|
73
|
+
});
|
|
74
|
+
expect(second).toBeNull();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("noteRetryEnd clears pending so subsequent agent_end does not synthesize", () => {
|
|
78
|
+
const o = new UsageLimitOrderer();
|
|
79
|
+
o.noteRetryStart("s1");
|
|
80
|
+
o.noteRetryEnd("s1");
|
|
81
|
+
expect(o.hasPending("s1")).toBe(false);
|
|
82
|
+
const result = o.maybeSynthesize("s1", {
|
|
83
|
+
messages: [{ role: "assistant", stopReason: "error", errorMessage: "usage_limit_reached" }],
|
|
84
|
+
});
|
|
85
|
+
expect(result).toBeNull();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("scopes pending state per-session", () => {
|
|
89
|
+
const o = new UsageLimitOrderer();
|
|
90
|
+
o.noteRetryStart("s1");
|
|
91
|
+
expect(o.hasPending("s2")).toBe(false);
|
|
92
|
+
const result = o.maybeSynthesize("s2", {
|
|
93
|
+
messages: [{ role: "assistant", stopReason: "error", errorMessage: "usage_limit_reached" }],
|
|
94
|
+
});
|
|
95
|
+
expect(result).toBeNull();
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("returns null on missing or empty messages array", () => {
|
|
99
|
+
const o = new UsageLimitOrderer();
|
|
100
|
+
o.noteRetryStart("s1");
|
|
101
|
+
expect(o.maybeSynthesize("s1", {})).toBeNull();
|
|
102
|
+
o.noteRetryStart("s1");
|
|
103
|
+
expect(o.maybeSynthesize("s1", { messages: [] })).toBeNull();
|
|
104
|
+
});
|
|
105
|
+
});
|
package/src/ask-user-tool.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* static tool-name conflicts with other extensions (e.g. pi-flows) that also
|
|
6
6
|
* register ask_user. Runtime registration bypasses detectExtensionConflicts.
|
|
7
7
|
*/
|
|
8
|
-
import type { ExtensionAPI } from "@
|
|
8
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
9
9
|
import { Type } from "typebox";
|
|
10
10
|
import { polyfillMultiselect } from "./multiselect-polyfill.js";
|
|
11
11
|
|
package/src/bridge-context.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Shared mutable state for bridge modules.
|
|
3
3
|
* Avoids passing 14+ closure variables to every extracted function.
|
|
4
4
|
*/
|
|
5
|
-
import type { ExtensionAPI } from "@
|
|
5
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
6
6
|
import type { ConnectionManager } from "./connection.js";
|
|
7
7
|
|
|
8
8
|
export interface BridgeContext {
|
package/src/bridge.ts
CHANGED
|
@@ -4,12 +4,14 @@
|
|
|
4
4
|
* Global extension that connects to the dashboard server,
|
|
5
5
|
* forwards all pi events, and relays commands back.
|
|
6
6
|
*/
|
|
7
|
-
import type { ExtensionAPI } from "@
|
|
8
|
-
import { Loader } from "@
|
|
7
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { Loader } from "@earendil-works/pi-tui";
|
|
9
9
|
import { ConnectionManager } from "./connection.js";
|
|
10
10
|
import { detectSessionSource } from "./source-detector.js";
|
|
11
11
|
import { mapEventToProtocol } from "./event-forwarder.js";
|
|
12
12
|
import { createCommandHandler } from "./command-handler.js";
|
|
13
|
+
import { RetryTracker } from "./retry-tracker.js";
|
|
14
|
+
import { UsageLimitOrderer } from "./usage-limit-orderer.js";
|
|
13
15
|
import fs from "node:fs";
|
|
14
16
|
import os from "node:os";
|
|
15
17
|
import path from "node:path";
|
|
@@ -191,6 +193,22 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
191
193
|
let hasRegisteredOnce = false; // see change: reattach-move-to-front
|
|
192
194
|
let promptBus: PromptBus | undefined;
|
|
193
195
|
|
|
196
|
+
// Provider-retry synthesis trackers. pi's ExtensionAPI does not expose
|
|
197
|
+
// `auto_retry_*` events, so the bridge synthesizes them from observed
|
|
198
|
+
// `message_end` / `agent_end` events. See change: fix-provider-retry-infinite-loop.
|
|
199
|
+
const retryTracker = new RetryTracker();
|
|
200
|
+
const usageLimitOrderer = new UsageLimitOrderer();
|
|
201
|
+
|
|
202
|
+
/** Forward a synthesized auto_retry_* event using the standard event_forward shape. */
|
|
203
|
+
const sendSyntheticRetryEvent = (eventType: string, data: Record<string, unknown>): void => {
|
|
204
|
+
if (!isActive() || !sessionReady) return;
|
|
205
|
+
connection.send({
|
|
206
|
+
type: "event_forward",
|
|
207
|
+
sessionId,
|
|
208
|
+
event: { eventType, timestamp: Date.now(), data },
|
|
209
|
+
});
|
|
210
|
+
};
|
|
211
|
+
|
|
194
212
|
// ── Per-message entry id tracking (for fix-per-message-fork) ──
|
|
195
213
|
// Pi 0.69+ awaits extension handlers BEFORE sessionManager.appendMessage runs,
|
|
196
214
|
// which means getLeafId() at emit time returns the previous leaf, not the
|
|
@@ -648,6 +666,14 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
648
666
|
if (cachedCtx?.abort) {
|
|
649
667
|
cachedCtx.abort();
|
|
650
668
|
}
|
|
669
|
+
// Clear retry-synthesis trackers — the user-initiated abort path
|
|
670
|
+
// already synthesizes its own auto_retry_end via command-handler.
|
|
671
|
+
// See change: fix-provider-retry-infinite-loop.
|
|
672
|
+
retryTracker.noteAbort(sessionId);
|
|
673
|
+
usageLimitOrderer.noteRetryEnd(sessionId);
|
|
674
|
+
},
|
|
675
|
+
isIdle: () => {
|
|
676
|
+
try { return cachedCtx?.isIdle?.() ?? false; } catch { return false; }
|
|
651
677
|
},
|
|
652
678
|
eventSink: (msg) => connection.send(msg),
|
|
653
679
|
compact: (opts) => {
|
|
@@ -802,7 +828,25 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
802
828
|
if (!sessionReady) return;
|
|
803
829
|
// Track agent streaming state (survives reconnect/reload)
|
|
804
830
|
if (eventType === "agent_start") getBridgeState().isAgentStreaming = true;
|
|
805
|
-
if (eventType === "agent_end")
|
|
831
|
+
if (eventType === "agent_end") {
|
|
832
|
+
getBridgeState().isAgentStreaming = false;
|
|
833
|
+
// Provider-retry synthesis: forward auto_retry_end BEFORE agent_end
|
|
834
|
+
// when retries were in flight, so the dashboard's retry banner
|
|
835
|
+
// clears before the error banner appears. The usage-limit orderer
|
|
836
|
+
// takes precedence (it carries the actual error string); the retry
|
|
837
|
+
// tracker handles the non-usage-limit case. See change:
|
|
838
|
+
// fix-provider-retry-infinite-loop.
|
|
839
|
+
const orderedSynth = usageLimitOrderer.maybeSynthesize(sessionId, (event as any));
|
|
840
|
+
if (orderedSynth) {
|
|
841
|
+
sendSyntheticRetryEvent(orderedSynth.eventType, orderedSynth.data);
|
|
842
|
+
retryTracker.noteAbort(sessionId); // clear tracker; orderer's event is authoritative
|
|
843
|
+
} else {
|
|
844
|
+
const trackerSynth = retryTracker.observeAgentEnd(sessionId, event as any);
|
|
845
|
+
if (trackerSynth) {
|
|
846
|
+
sendSyntheticRetryEvent(trackerSynth.eventType, trackerSynth.data);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
}
|
|
806
850
|
// For model_select, enrich the event data with thinkingLevel
|
|
807
851
|
if (eventType === "model_select") {
|
|
808
852
|
const enriched = { ...event, thinkingLevel: (pi as any).getThinkingLevel?.() };
|
|
@@ -872,6 +916,18 @@ function initBridge(pi: ExtensionAPI) {
|
|
|
872
916
|
const enriched = { ...event, entryId, nonce };
|
|
873
917
|
const protoMsg = mapEventToProtocol(sessionId, enriched);
|
|
874
918
|
connection.send(protoMsg);
|
|
919
|
+
// After forwarding the original message_end, ask the retry tracker
|
|
920
|
+
// whether to synthesize an auto_retry_* event. See change:
|
|
921
|
+
// fix-provider-retry-infinite-loop.
|
|
922
|
+
const synthetic = retryTracker.observeMessageEnd(sessionId, messageRef as any);
|
|
923
|
+
if (synthetic) {
|
|
924
|
+
sendSyntheticRetryEvent(synthetic.eventType, synthetic.data);
|
|
925
|
+
if (synthetic.eventType === "auto_retry_start") {
|
|
926
|
+
usageLimitOrderer.noteRetryStart(sessionId);
|
|
927
|
+
} else {
|
|
928
|
+
usageLimitOrderer.noteRetryEnd(sessionId);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
875
931
|
}, 0);
|
|
876
932
|
return;
|
|
877
933
|
}
|
package/src/command-handler.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { readdirSync } from "node:fs";
|
|
5
5
|
import { join, relative } from "node:path";
|
|
6
|
-
import type { ExtensionAPI } from "@
|
|
6
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import type {
|
|
8
8
|
ServerToExtensionMessage,
|
|
9
9
|
ExtensionToServerMessage,
|
|
@@ -145,6 +145,11 @@ export function createCommandHandler(
|
|
|
145
145
|
getThinkingLevel?: () => string | undefined;
|
|
146
146
|
shutdown?: () => void;
|
|
147
147
|
abort?: () => void;
|
|
148
|
+
/**
|
|
149
|
+
* Probe agent idleness for the persistent-abort scheduler.
|
|
150
|
+
* See change: fix-provider-retry-infinite-loop.
|
|
151
|
+
*/
|
|
152
|
+
isIdle?: () => boolean;
|
|
148
153
|
getCwd?: () => string;
|
|
149
154
|
/** Callback to send events (e.g., bash_output, command_feedback) back to server */
|
|
150
155
|
eventSink?: (msg: ExtensionToServerMessage) => void;
|
|
@@ -161,6 +166,33 @@ export function createCommandHandler(
|
|
|
161
166
|
},
|
|
162
167
|
): CommandHandler {
|
|
163
168
|
const getSessionId = typeof sessionIdOrGetter === "function" ? sessionIdOrGetter : () => sessionIdOrGetter;
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Persistent-abort scheduler. Re-invokes `options.abort()` at 200ms
|
|
172
|
+
* intervals for up to 2 seconds, breaking early when `options.isIdle()`
|
|
173
|
+
* returns true. Closes the retry race window in pi-coding-agent.
|
|
174
|
+
* See change: fix-provider-retry-infinite-loop.
|
|
175
|
+
*/
|
|
176
|
+
const PERSISTENT_ABORT_INTERVAL_MS = 200;
|
|
177
|
+
const PERSISTENT_ABORT_MAX_MS = 2000;
|
|
178
|
+
function schedulePersistentAbort(opts: NonNullable<typeof options>): void {
|
|
179
|
+
if (!opts.abort) return;
|
|
180
|
+
const startedAt = Date.now();
|
|
181
|
+
const interval = setInterval(() => {
|
|
182
|
+
if (Date.now() - startedAt >= PERSISTENT_ABORT_MAX_MS) {
|
|
183
|
+
clearInterval(interval);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
try {
|
|
187
|
+
if (opts.isIdle?.()) {
|
|
188
|
+
clearInterval(interval);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
} catch { /* probe failure — keep trying */ }
|
|
192
|
+
try { opts.abort?.(); } catch { /* idempotent */ }
|
|
193
|
+
}, PERSISTENT_ABORT_INTERVAL_MS);
|
|
194
|
+
}
|
|
195
|
+
|
|
164
196
|
return {
|
|
165
197
|
async handle(msg: ServerToExtensionMessage): Promise<ExtensionToServerMessage | undefined> {
|
|
166
198
|
const sessionId = getSessionId();
|
|
@@ -292,6 +324,31 @@ export function createCommandHandler(
|
|
|
292
324
|
if (options?.abort) {
|
|
293
325
|
options.abort();
|
|
294
326
|
}
|
|
327
|
+
// Synthesize an immediate auto_retry_end so the dashboard clears
|
|
328
|
+
// any in-flight retry banner without waiting for pi's natural
|
|
329
|
+
// auto_retry_end (which is delayed by the abortable-sleep cancel
|
|
330
|
+
// window AND, on extension API, never reaches us at all — see
|
|
331
|
+
// https://github.com/badlogic/pi-mono/discussions/2073). The
|
|
332
|
+
// reducer no-ops auto_retry_end when retryState is undefined,
|
|
333
|
+
// so this is idempotent against later events.
|
|
334
|
+
if (options?.eventSink) {
|
|
335
|
+
options.eventSink({
|
|
336
|
+
type: "event_forward",
|
|
337
|
+
sessionId,
|
|
338
|
+
event: {
|
|
339
|
+
eventType: "auto_retry_end",
|
|
340
|
+
timestamp: Date.now(),
|
|
341
|
+
data: { success: false, attempt: -1, finalError: "Aborted by user" },
|
|
342
|
+
},
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
// Persistent-abort scheduler: pi-coding-agent's _retryAbortController
|
|
346
|
+
// is briefly `undefined` between sleep-end and the next
|
|
347
|
+
// agent.continue() call. An abort that arrives in that window is
|
|
348
|
+
// a no-op against the retry. Re-invoke abort every 200ms for up
|
|
349
|
+
// to 2s, breaking early when the agent is idle.
|
|
350
|
+
// See change: fix-provider-retry-infinite-loop.
|
|
351
|
+
if (options) schedulePersistentAbort(options);
|
|
295
352
|
return undefined;
|
|
296
353
|
|
|
297
354
|
case "request_commands": {
|
|
@@ -394,7 +451,7 @@ export function createCommandHandler(
|
|
|
394
451
|
case "list_sessions": {
|
|
395
452
|
try {
|
|
396
453
|
// Dynamic import to avoid hard dependency at module load
|
|
397
|
-
const { SessionManager } = await import("@
|
|
454
|
+
const { SessionManager } = await import("@earendil-works/pi-coding-agent") as any;
|
|
398
455
|
const cwd = msg.cwd || options?.getCwd?.() || process.cwd();
|
|
399
456
|
const sessionInfos = await SessionManager.list(cwd);
|
|
400
457
|
const sessions: PiSessionInfo[] = (sessionInfos || []).map((s: any) => ({
|
package/src/flow-event-wiring.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Flow event wiring: registers listeners for pi-flows events
|
|
3
3
|
* and forwards them as protocol messages to the dashboard server.
|
|
4
4
|
*/
|
|
5
|
-
import type { ExtensionAPI } from "@
|
|
5
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
6
6
|
import type { BridgeContext } from "./bridge-context.js";
|
|
7
7
|
import { filterHiddenCommands } from "./bridge-context.js";
|
|
8
8
|
import type { FlowInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
package/src/multiselect-list.ts
CHANGED
|
@@ -23,7 +23,7 @@ interface Item {
|
|
|
23
23
|
|
|
24
24
|
/**
|
|
25
25
|
* Minimal shape of pi-tui's `Component` interface — we avoid importing from
|
|
26
|
-
* `@
|
|
26
|
+
* `@earendil-works/pi-tui` directly so this module stays compile-friendly when
|
|
27
27
|
* that peer dep isn't present (e.g. in unit tests running via vitest without
|
|
28
28
|
* the full pi runtime).
|
|
29
29
|
*/
|
package/src/pi-env.d.ts
CHANGED
|
@@ -1,15 +1,8 @@
|
|
|
1
1
|
// Ambient declarations for pi runtime packages.
|
|
2
|
-
// The actual types are provided by whichever host
|
|
2
|
+
// The actual types are provided by whichever host loads this extension.
|
|
3
3
|
// tsconfig paths handles resolution when one of the packages is installed;
|
|
4
4
|
// these declarations serve as fallback when neither is available (e.g. CI, dev without pi).
|
|
5
|
-
declare module "@
|
|
6
|
-
export type ExtensionAPI = import("@oh-my-pi/pi-coding-agent").ExtensionAPI;
|
|
7
|
-
}
|
|
8
|
-
declare module "@mariozechner/pi-ai" {
|
|
9
|
-
export function StringEnum<T extends readonly string[]>(values: T, schema?: Record<string, unknown>): any;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
declare module "@oh-my-pi/pi-coding-agent" {
|
|
5
|
+
declare module "@earendil-works/pi-coding-agent" {
|
|
13
6
|
export interface ModelRegistry {
|
|
14
7
|
getAvailable(): Array<{ provider: string; id: string }>;
|
|
15
8
|
refresh(): void;
|
|
@@ -35,3 +28,17 @@ declare module "@oh-my-pi/pi-coding-agent" {
|
|
|
35
28
|
events: EventBus;
|
|
36
29
|
}
|
|
37
30
|
}
|
|
31
|
+
|
|
32
|
+
// Legacy fork — re-exports the same ExtensionAPI shape so existing installs still type-check.
|
|
33
|
+
declare module "@mariozechner/pi-coding-agent" {
|
|
34
|
+
export type ExtensionAPI = import("@earendil-works/pi-coding-agent").ExtensionAPI;
|
|
35
|
+
export type ModelRegistry = import("@earendil-works/pi-coding-agent").ModelRegistry;
|
|
36
|
+
export type EventBus = import("@earendil-works/pi-coding-agent").EventBus;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
declare module "@earendil-works/pi-ai" {
|
|
40
|
+
export function StringEnum<T extends readonly string[]>(values: T, schema?: Record<string, unknown>): any;
|
|
41
|
+
}
|
|
42
|
+
declare module "@mariozechner/pi-ai" {
|
|
43
|
+
export function StringEnum<T extends readonly string[]>(values: T, schema?: Record<string, unknown>): any;
|
|
44
|
+
}
|
package/src/provider-register.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* flow:resolve-model / flow:get-available-models
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import type { ExtensionAPI } from "@
|
|
14
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
15
15
|
import { existsSync, readFileSync } from "node:fs";
|
|
16
16
|
import { homedir } from "node:os";
|
|
17
17
|
import { join } from "node:path";
|
|
@@ -373,7 +373,7 @@ async function loadPiAi(): Promise<PiAiHelpers> {
|
|
|
373
373
|
if (_piAiLoadAttempted) return {};
|
|
374
374
|
_piAiLoadAttempted = true;
|
|
375
375
|
try {
|
|
376
|
-
const mod: any = await import("@
|
|
376
|
+
const mod: any = await import("@earendil-works/pi-ai");
|
|
377
377
|
_piAiModule = { findEnvKeys: mod.findEnvKeys, getEnvApiKey: mod.getEnvApiKey };
|
|
378
378
|
return _piAiModule;
|
|
379
379
|
} catch {
|
|
@@ -436,6 +436,20 @@ function getModelRegistry(): any {
|
|
|
436
436
|
// -- Provider registration (with auto-discovery) --------------------------
|
|
437
437
|
|
|
438
438
|
async function registerEntry(pi: ExtensionAPI, name: string, entry: ProviderEntry): Promise<number> {
|
|
439
|
+
// Record snapshot SYNCHRONOUSLY before awaiting discovery so the very
|
|
440
|
+
// first providers_list push (typically fired from `session_start`
|
|
441
|
+
// shortly after `activate()` kicked off async registerEntry calls) carries
|
|
442
|
+
// the correct `custom: true` flags. Otherwise a slow / unreachable
|
|
443
|
+
// /v1/models endpoint causes custom providers from
|
|
444
|
+
// `~/.pi/agent/providers.json` to leak into Settings → Provider
|
|
445
|
+
// Authentication → API Keys until the discovery probe resolves.
|
|
446
|
+
// See change: fix-custom-provider-flag-race.
|
|
447
|
+
lastRegistered.set(name, {
|
|
448
|
+
baseUrl: entry.baseUrl,
|
|
449
|
+
apiKey: entry.apiKey,
|
|
450
|
+
api: entry.api ?? "openai-completions",
|
|
451
|
+
});
|
|
452
|
+
|
|
439
453
|
const discovered = await discoverModels(entry.baseUrl, entry.apiKey);
|
|
440
454
|
|
|
441
455
|
// Metadata (contextWindow, maxTokens, reasoning, cost, input) is resolved
|
|
@@ -464,13 +478,6 @@ async function registerEntry(pi: ExtensionAPI, name: string, entry: ProviderEntr
|
|
|
464
478
|
models,
|
|
465
479
|
});
|
|
466
480
|
|
|
467
|
-
// Record snapshot so reloadProviders can detect subsequent changes.
|
|
468
|
-
lastRegistered.set(name, {
|
|
469
|
-
baseUrl: entry.baseUrl,
|
|
470
|
-
apiKey: entry.apiKey,
|
|
471
|
-
api: entry.api ?? "openai-completions",
|
|
472
|
-
});
|
|
473
|
-
|
|
474
481
|
// Notify bridge directly (same package — no cross-package event needed)
|
|
475
482
|
onProvidersChanged?.();
|
|
476
483
|
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RetryTracker — synthesizes `auto_retry_start` / `auto_retry_end` events from
|
|
3
|
+
* observed pi events.
|
|
4
|
+
*
|
|
5
|
+
* Background: pi's ExtensionAPI does NOT expose `auto_retry_*` events to
|
|
6
|
+
* extensions (verified against pi 0.70/0.73 — see
|
|
7
|
+
* https://github.com/badlogic/pi-mono/discussions/2073). They fire only via
|
|
8
|
+
* `AgentSession._emit → _eventListeners` which only the embedded SDK can
|
|
9
|
+
* subscribe to.
|
|
10
|
+
*
|
|
11
|
+
* Workaround: pi-coding-agent's `_handleRetryableError` fires `message_end`
|
|
12
|
+
* for the failed assistant message BEFORE entering its retry sleep. The
|
|
13
|
+
* bridge sees that `message_end` via `pi.on("message_end")`. By matching
|
|
14
|
+
* the same regex pi-coding-agent uses internally, we can detect that a
|
|
15
|
+
* retry is about to happen and emit our own `auto_retry_start` to the
|
|
16
|
+
* dashboard. When the next non-error `message_end` or `agent_end` arrives,
|
|
17
|
+
* we emit `auto_retry_end`.
|
|
18
|
+
*
|
|
19
|
+
* `delayMs` and `maxAttempts` are unknowable from observed events (pi's
|
|
20
|
+
* settings are not exposed); we send sentinel `-1` for both. The
|
|
21
|
+
* RetryBanner renders an indeterminate "retrying…" UI in that case.
|
|
22
|
+
*
|
|
23
|
+
* See change: fix-provider-retry-infinite-loop.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Regex copied verbatim from pi-coding-agent `agent-session.js`
|
|
28
|
+
* `_isRetryableError`. If pi adds new retryable categories, this regex
|
|
29
|
+
* goes stale — but the failure mode is "tracker silently misses some
|
|
30
|
+
* retries", never "tracker breaks". Sync at major pi version bumps.
|
|
31
|
+
*/
|
|
32
|
+
export const RETRYABLE_PATTERN =
|
|
33
|
+
/overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|http2 request did not get a response|timed? out|timeout|terminated|retry delay/i;
|
|
34
|
+
|
|
35
|
+
export interface SyntheticRetryEvent {
|
|
36
|
+
eventType: "auto_retry_start" | "auto_retry_end";
|
|
37
|
+
data: Record<string, unknown>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Minimal shape we pluck from a `message_end` event. */
|
|
41
|
+
export interface ObservedAssistantMessage {
|
|
42
|
+
role?: string;
|
|
43
|
+
stopReason?: string;
|
|
44
|
+
errorMessage?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class RetryTracker {
|
|
48
|
+
/** sessionId → 1-based attempt counter for the current retry chain. */
|
|
49
|
+
private attempt = new Map<string, number>();
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Process a `message_end` event. Returns a synthetic event the bridge
|
|
53
|
+
* should ALSO forward (after the original message_end), or null.
|
|
54
|
+
*/
|
|
55
|
+
observeMessageEnd(
|
|
56
|
+
sessionId: string,
|
|
57
|
+
message: ObservedAssistantMessage | undefined | null,
|
|
58
|
+
): SyntheticRetryEvent | null {
|
|
59
|
+
if (!message || message.role !== "assistant") return null;
|
|
60
|
+
|
|
61
|
+
if (message.stopReason === "error") {
|
|
62
|
+
const err = typeof message.errorMessage === "string" ? message.errorMessage : "";
|
|
63
|
+
if (!err || !RETRYABLE_PATTERN.test(err)) return null;
|
|
64
|
+
const next = (this.attempt.get(sessionId) ?? 0) + 1;
|
|
65
|
+
this.attempt.set(sessionId, next);
|
|
66
|
+
return {
|
|
67
|
+
eventType: "auto_retry_start",
|
|
68
|
+
data: { attempt: next, maxAttempts: -1, delayMs: -1, errorMessage: err },
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Non-error assistant message — clears any in-flight retry chain.
|
|
73
|
+
if (this.attempt.has(sessionId)) {
|
|
74
|
+
const last = this.attempt.get(sessionId) ?? 0;
|
|
75
|
+
this.attempt.delete(sessionId);
|
|
76
|
+
return { eventType: "auto_retry_end", data: { success: true, attempt: last } };
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Process an `agent_end` event. Returns a synthetic event the bridge
|
|
83
|
+
* should forward BEFORE the original agent_end, or null.
|
|
84
|
+
*
|
|
85
|
+
* Always clears any in-flight retry tracking (terminal turn boundary).
|
|
86
|
+
*/
|
|
87
|
+
observeAgentEnd(
|
|
88
|
+
sessionId: string,
|
|
89
|
+
agentEndData: { messages?: unknown } | undefined | null,
|
|
90
|
+
): SyntheticRetryEvent | null {
|
|
91
|
+
const wasRetrying = this.attempt.has(sessionId);
|
|
92
|
+
const last = this.attempt.get(sessionId) ?? -1;
|
|
93
|
+
this.attempt.delete(sessionId);
|
|
94
|
+
if (!wasRetrying) return null;
|
|
95
|
+
|
|
96
|
+
// Inspect terminal message for error context.
|
|
97
|
+
const messages = agentEndData?.messages;
|
|
98
|
+
const lastMsg =
|
|
99
|
+
Array.isArray(messages) && messages.length > 0
|
|
100
|
+
? (messages[messages.length - 1] as ObservedAssistantMessage)
|
|
101
|
+
: undefined;
|
|
102
|
+
if (lastMsg?.stopReason === "error" && typeof lastMsg.errorMessage === "string") {
|
|
103
|
+
return {
|
|
104
|
+
eventType: "auto_retry_end",
|
|
105
|
+
data: { success: false, attempt: last, finalError: lastMsg.errorMessage },
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return { eventType: "auto_retry_end", data: { success: true, attempt: last } };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Notify the tracker of a user abort. Clears in-flight tracking so a
|
|
113
|
+
* subsequent agent_end does not double-emit auto_retry_end.
|
|
114
|
+
*/
|
|
115
|
+
noteAbort(sessionId: string): void {
|
|
116
|
+
this.attempt.delete(sessionId);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Test-only / bridge-coordination: is a retry currently in flight? */
|
|
120
|
+
isRetrying(sessionId: string): boolean {
|
|
121
|
+
return this.attempt.has(sessionId);
|
|
122
|
+
}
|
|
123
|
+
}
|
package/src/session-sync.ts
CHANGED
|
@@ -39,7 +39,15 @@ export function sendStateSync(
|
|
|
39
39
|
// dashboard restart) is a "reattach". Server applies the configured
|
|
40
40
|
// `reattachPlacement` policy on "reattach".
|
|
41
41
|
// See change: reattach-move-to-front.
|
|
42
|
-
const
|
|
42
|
+
const isFirstRegister = !bc.hasRegisteredOnce;
|
|
43
|
+
const registerReason: "spawn" | "reattach" = isFirstRegister ? "spawn" : "reattach";
|
|
44
|
+
|
|
45
|
+
// Include the spawn correlation token (server-minted UUID injected via
|
|
46
|
+
// env var at spawn time) ONLY on the first register. Subsequent
|
|
47
|
+
// registers (reattach after dashboard restart, in-process Ctrl+F fork)
|
|
48
|
+
// omit it because the sessionId is already known to the server.
|
|
49
|
+
// See change: spawn-correlation-token (Decision 3).
|
|
50
|
+
const spawnToken = isFirstRegister ? process.env.PI_DASHBOARD_SPAWN_TOKEN : undefined;
|
|
43
51
|
|
|
44
52
|
bc.connection.send({
|
|
45
53
|
type: "session_register",
|
|
@@ -55,6 +63,7 @@ export function sendStateSync(
|
|
|
55
63
|
eventCount,
|
|
56
64
|
pid: process.pid,
|
|
57
65
|
registerReason,
|
|
66
|
+
...(spawnToken ? { spawnToken } : {}),
|
|
58
67
|
});
|
|
59
68
|
|
|
60
69
|
bc.hasRegisteredOnce = true;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Usage-limit event orderer.
|
|
3
|
+
*
|
|
4
|
+
* Tracks per-session whether an `auto_retry_start` was forwarded without a
|
|
5
|
+
* matching `auto_retry_end`, and — when an `agent_end` arrives whose terminal
|
|
6
|
+
* assistant message has a usage-limit / quota errorMessage — synthesizes an
|
|
7
|
+
* `auto_retry_end { success: false }` to emit BEFORE the `agent_end`.
|
|
8
|
+
*
|
|
9
|
+
* Pure logic (no I/O). The bridge wires this into its forwarding pipeline.
|
|
10
|
+
*
|
|
11
|
+
* See change: fix-provider-retry-infinite-loop.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export const USAGE_LIMIT_PATTERN =
|
|
15
|
+
/usage[_ ]limit[_ ]reached|usage_not_included|quota[_ ]exceeded|monthly limit|hourly limit|reset after \d+[hms]/i;
|
|
16
|
+
|
|
17
|
+
export interface SyntheticEventEnvelope {
|
|
18
|
+
eventType: "auto_retry_end";
|
|
19
|
+
data: { success: false; attempt: -1; finalError: string };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class UsageLimitOrderer {
|
|
23
|
+
/** sessionId → true while a retry is in flight (no auto_retry_end seen yet). */
|
|
24
|
+
private pending = new Set<string>();
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Notify the orderer of an outbound `auto_retry_start` for sessionId.
|
|
28
|
+
*/
|
|
29
|
+
noteRetryStart(sessionId: string): void {
|
|
30
|
+
this.pending.add(sessionId);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Notify the orderer of an outbound `auto_retry_end` for sessionId.
|
|
35
|
+
* Subsequent `agent_end` events will not synthesize unless a new retry
|
|
36
|
+
* has been started.
|
|
37
|
+
*/
|
|
38
|
+
noteRetryEnd(sessionId: string): void {
|
|
39
|
+
this.pending.delete(sessionId);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Inspect an `agent_end` payload. If the terminal message has a
|
|
44
|
+
* usage-limit error AND we have an unmatched retry-start for this session,
|
|
45
|
+
* return the synthetic event the bridge should forward BEFORE the agent_end.
|
|
46
|
+
*
|
|
47
|
+
* Returns null when no synthesis is needed. Always clears the pending flag
|
|
48
|
+
* after a terminal agent_end (errored or not) so we don't double-synthesize.
|
|
49
|
+
*/
|
|
50
|
+
maybeSynthesize(
|
|
51
|
+
sessionId: string,
|
|
52
|
+
agentEndData: Record<string, unknown> | undefined,
|
|
53
|
+
): SyntheticEventEnvelope | null {
|
|
54
|
+
const wasPending = this.pending.has(sessionId);
|
|
55
|
+
// Always clear on agent_end: a terminal turn ends any retry tracking.
|
|
56
|
+
this.pending.delete(sessionId);
|
|
57
|
+
|
|
58
|
+
if (!wasPending || !agentEndData) return null;
|
|
59
|
+
const messages = agentEndData.messages;
|
|
60
|
+
if (!Array.isArray(messages) || messages.length === 0) return null;
|
|
61
|
+
const last = messages[messages.length - 1] as Record<string, unknown> | undefined;
|
|
62
|
+
if (!last || last.stopReason !== "error") return null;
|
|
63
|
+
const errorMessage = typeof last.errorMessage === "string" ? last.errorMessage : "";
|
|
64
|
+
if (!errorMessage || !USAGE_LIMIT_PATTERN.test(errorMessage)) return null;
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
eventType: "auto_retry_end",
|
|
68
|
+
data: { success: false, attempt: -1, finalError: errorMessage },
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Test-only: inspect pending state. */
|
|
73
|
+
hasPending(sessionId: string): boolean {
|
|
74
|
+
return this.pending.has(sessionId);
|
|
75
|
+
}
|
|
76
|
+
}
|