@blackbelt-technology/pi-agent-dashboard 0.6.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -38
- package/docs/architecture.md +148 -2
- package/package.json +6 -4
- package/packages/extension/package.json +4 -3
- package/packages/extension/src/AGENTS.md +1 -0
- package/packages/extension/src/__tests__/bridge-resume-disconnect.test.ts +333 -0
- package/packages/extension/src/__tests__/openspec-cli-shim.test.ts +145 -0
- package/packages/extension/src/__tests__/provider-register-native-models.test.ts +182 -0
- package/packages/extension/src/__tests__/provider-register-thinking-levels.test.ts +54 -1
- package/packages/extension/src/__tests__/single-derivation-guard.test.ts +39 -0
- package/packages/extension/src/bridge-context.ts +21 -0
- package/packages/extension/src/bridge.ts +41 -6
- package/packages/extension/src/openspec-cli-shim.ts +173 -0
- package/packages/extension/src/openspec-cli-shim.ts.AGENTS.md +7 -0
- package/packages/extension/src/provider-register.ts +180 -17
- package/packages/extension/src/provider-register.ts.AGENTS.md +1 -1
- package/packages/extension/src/session-sync.ts +9 -4
- package/packages/server/package.json +8 -8
- package/packages/server/src/__tests__/decorate-goals-spend.test.ts +79 -0
- package/packages/server/src/__tests__/embed-lifecycle-boot-smoke.test.ts +44 -0
- package/packages/server/src/__tests__/goal-routes.test.ts +62 -7
- package/packages/server/src/__tests__/goal-supervisor.test.ts +4 -4
- package/packages/server/src/__tests__/headless-pid-registry.test.ts +7 -3
- package/packages/server/src/__tests__/memory-event-store.test.ts +369 -13
- package/packages/server/src/__tests__/models-introspection-thinking-map.test.ts +67 -0
- package/packages/server/src/__tests__/pi-changelog-routes.test.ts +9 -2
- package/packages/server/src/__tests__/recovery-offer.test.ts +42 -7
- package/packages/server/src/__tests__/recovery-reattach-retraction.test.ts +188 -0
- package/packages/server/src/__tests__/session-tags-persistence.test.ts +29 -0
- package/packages/server/src/browser-handlers/AGENTS.md +1 -1
- package/packages/server/src/browser-handlers/__tests__/session-meta-handler.test.ts +98 -1
- package/packages/server/src/browser-handlers/handler-context.ts +24 -13
- package/packages/server/src/browser-handlers/session-action-handler.ts +12 -1
- package/packages/server/src/browser-handlers/session-meta-handler.ts +29 -0
- package/packages/server/src/embed-lifecycle/AGENTS.md +17 -0
- package/packages/server/src/embed-lifecycle/__tests__/caps.test.ts +129 -0
- package/packages/server/src/embed-lifecycle/__tests__/embed-lifecycle-controller.test.ts +84 -0
- package/packages/server/src/embed-lifecycle/__tests__/identity-key.test.ts +73 -0
- package/packages/server/src/embed-lifecycle/__tests__/idle-reaper.test.ts +173 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-config.test.ts +26 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-event-capture.test.ts +32 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-marker-persistence.test.ts +106 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-metrics.test.ts +39 -0
- package/packages/server/src/embed-lifecycle/__tests__/liveness-probe.test.ts +77 -0
- package/packages/server/src/embed-lifecycle/__tests__/quiescence.test.ts +175 -0
- package/packages/server/src/embed-lifecycle/__tests__/reclamation-soak.test.ts +77 -0
- package/packages/server/src/embed-lifecycle/__tests__/session-lifecycle-policy.test.ts +38 -0
- package/packages/server/src/embed-lifecycle/__tests__/visitor-session-registry.test.ts +140 -0
- package/packages/server/src/embed-lifecycle/caps.ts +88 -0
- package/packages/server/src/embed-lifecycle/cwd-allowlist.ts +50 -0
- package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +90 -0
- package/packages/server/src/embed-lifecycle/identity-key.ts +73 -0
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +161 -0
- package/packages/server/src/embed-lifecycle/lifecycle-event-capture.ts +30 -0
- package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +70 -0
- package/packages/server/src/embed-lifecycle/liveness-probe.ts +123 -0
- package/packages/server/src/embed-lifecycle/quiescence.ts +159 -0
- package/packages/server/src/embed-lifecycle/session-lifecycle-policy.ts +31 -0
- package/packages/server/src/embed-lifecycle/visitor-session-registry.ts +178 -0
- package/packages/server/src/event-wiring.ts +20 -0
- package/packages/server/src/event-wiring.ts.AGENTS.md +1 -0
- package/packages/server/src/goal/AGENTS.md +1 -0
- package/packages/server/src/goal/decorate-goals-spend.ts +47 -0
- package/packages/server/src/goal/goal-supervisor.ts +5 -3
- package/packages/server/src/model-proxy/AGENTS.md +2 -2
- package/packages/server/src/model-proxy/__tests__/internal-registry-native-merge.test.ts +155 -0
- package/packages/server/src/model-proxy/__tests__/read-native-models.test.ts +92 -0
- package/packages/server/src/model-proxy/internal-registry.ts +49 -23
- package/packages/server/src/model-proxy/registry-singleton.ts +15 -9
- package/packages/server/src/pairing/browser-gateway.ts +40 -11
- package/packages/server/src/pairing/browser-gateway.ts.AGENTS.md +1 -1
- package/packages/server/src/persistence/memory-event-store.ts +369 -23
- package/packages/server/src/persistence/memory-event-store.ts.AGENTS.md +1 -1
- package/packages/server/src/routes/AGENTS.md +2 -2
- package/packages/server/src/routes/goal-routes.ts +14 -9
- package/packages/server/src/routes/models-introspection-routes.ts +10 -0
- package/packages/server/src/routes/system-routes.ts +16 -1
- package/packages/server/src/server.ts +216 -65
- package/packages/server/src/server.ts.AGENTS.md +1 -1
- package/packages/server/src/session/memory-session-manager.ts +4 -0
- package/packages/server/src/session/session-scanner.ts +9 -0
- package/packages/server/src/session/session-to-meta.ts +6 -0
- package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -4
- package/packages/shared/package.json +1 -1
- package/packages/shared/src/AGENTS.md +5 -3
- package/packages/shared/src/__tests__/models-json-reader.test.ts +100 -0
- package/packages/shared/src/__tests__/nightly-workflow-contract.test.ts +125 -0
- package/packages/shared/src/__tests__/openspec-poller-1.6.0-compat.test.ts +112 -0
- package/packages/shared/src/__tests__/pnpm-migration-contract.test.ts +177 -0
- package/packages/shared/src/__tests__/publish-workflow-contract.test.ts +6 -3
- package/packages/shared/src/browser-protocol.ts +22 -0
- package/packages/shared/src/config.ts +70 -0
- package/packages/shared/src/dashboard-plugin/AGENTS.md +1 -1
- package/packages/shared/src/dashboard-plugin/slot-props.ts +9 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +19 -0
- package/packages/shared/src/models-json-reader.ts +98 -0
- package/packages/shared/src/platform/AGENTS.md +1 -1
- package/packages/shared/src/platform/paths.ts +12 -0
- package/packages/shared/src/session-meta.ts +9 -0
- package/packages/shared/src/types.ts +52 -1
- package/docs/AGENTS.md +0 -47
- package/packages/extension/AGENTS.md +0 -7
- package/packages/server/AGENTS.md +0 -7
- package/packages/shared/AGENTS.md +0 -7
- package/scripts/AGENTS.md +0 -38
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Idempotent, server-owned session acquire keyed by a visitor identity (D5, D6).
|
|
3
|
+
*
|
|
4
|
+
* `acquire(req)` runs the ladder: (a) reuse an existing live session for the
|
|
5
|
+
* key; (b) resume the key's most recent resumable ended session; (c) validate
|
|
6
|
+
* the cwd allowlist and spawn exactly one. Concurrent acquires for one key
|
|
7
|
+
* COALESCE onto a single in-flight promise that resolves only when the
|
|
8
|
+
* spawned/resumed session's `session_register` arrives (via `resolveByCwd`) —
|
|
9
|
+
* closing the spawn→register window so a second acquire never starts a second
|
|
10
|
+
* `pi` (E8, E9). The registry OWNS `identityKey → current live sessionId` and
|
|
11
|
+
* re-points it across resume's fresh-sessionId renumber (E10); browser
|
|
12
|
+
* `localStorage` is a stale-tolerant hint only (E7).
|
|
13
|
+
*
|
|
14
|
+
* The in-flight promise carries a bounded register timeout: a spawn that never
|
|
15
|
+
* registers rejects the coalesced result and clears the entry so waiters never
|
|
16
|
+
* hang (X2).
|
|
17
|
+
*
|
|
18
|
+
* See OpenSpec change: add-embed-session-lifecycle.
|
|
19
|
+
*/
|
|
20
|
+
import type { EmbedLifecycleConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
21
|
+
import { composeIdentityKey, type IdentityKeyParts } from "./identity-key.js";
|
|
22
|
+
|
|
23
|
+
export interface AcquireRequest extends IdentityKeyParts {}
|
|
24
|
+
|
|
25
|
+
export type AcquireReason = "live" | "resumed" | "spawned";
|
|
26
|
+
|
|
27
|
+
export interface AcquireResult {
|
|
28
|
+
sessionId: string;
|
|
29
|
+
reason: AcquireReason;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface RegistryDeps {
|
|
33
|
+
config: () => EmbedLifecycleConfig;
|
|
34
|
+
/** Canonicalize a cwd (realpath + case-normalize) — shared with the wiring. */
|
|
35
|
+
canonicalizeCwd: (cwd: string) => string;
|
|
36
|
+
/** Validate the requested cwd against the server-side allowlist (D11). */
|
|
37
|
+
isCwdAllowed: (cwd: string) => boolean;
|
|
38
|
+
/** Is this sessionId a currently live session? */
|
|
39
|
+
isSessionLive: (sessionId: string) => boolean;
|
|
40
|
+
/** Is this sessionId an ended-but-resumable session (policy permitting)? */
|
|
41
|
+
isSessionResumable: (sessionId: string) => boolean;
|
|
42
|
+
/** Fire a spawn for the request; `resolveByCwd` completes it on register. */
|
|
43
|
+
spawn: (req: AcquireRequest, key: string) => void;
|
|
44
|
+
/** Fire a resume of `sessionId`; `resolveByCwd` completes it on register. */
|
|
45
|
+
resume: (sessionId: string, req: AcquireRequest, key: string) => void;
|
|
46
|
+
/**
|
|
47
|
+
* Caps admission gate (Section 5). Resolves when a slot is available
|
|
48
|
+
* (possibly after reclaiming an idle session); throws `CapacityError` when
|
|
49
|
+
* every candidate is busy. Default: no-op (caps disabled).
|
|
50
|
+
*/
|
|
51
|
+
admit?: (key: string) => Promise<void>;
|
|
52
|
+
/** Reuse observability: hit (reused live) vs miss (spawn/resume). */
|
|
53
|
+
onReuse?: (hit: boolean) => void;
|
|
54
|
+
now?: () => number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface InFlight {
|
|
58
|
+
key: string;
|
|
59
|
+
canonicalCwd: string;
|
|
60
|
+
promise: Promise<AcquireResult>;
|
|
61
|
+
resolve: (r: AcquireResult) => void;
|
|
62
|
+
reject: (e: Error) => void;
|
|
63
|
+
/** Set once the caps gate resolves + the spawn/resume fires (register-window). */
|
|
64
|
+
timer: ReturnType<typeof setTimeout> | undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface VisitorSessionRegistry {
|
|
68
|
+
acquire: (req: AcquireRequest) => Promise<AcquireResult>;
|
|
69
|
+
/** Wiring hook: a session registered in `canonicalCwd` with `sessionId`. */
|
|
70
|
+
resolveByCwd: (canonicalCwd: string, sessionId: string) => void;
|
|
71
|
+
/** Current live sessionId the registry maps a key to, if any. */
|
|
72
|
+
mappedSessionId: (key: string) => string | undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function createVisitorSessionRegistry(deps: RegistryDeps): VisitorSessionRegistry {
|
|
76
|
+
const keyToSessionId = new Map<string, string>();
|
|
77
|
+
const inFlight = new Map<string, InFlight>();
|
|
78
|
+
const admit = deps.admit ?? (async () => {});
|
|
79
|
+
|
|
80
|
+
function keyFor(req: AcquireRequest): string {
|
|
81
|
+
return composeIdentityKey(req.visitorId, deps.canonicalizeCwd(req.cwd), req.agentIdentity);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function beginInFlight(
|
|
85
|
+
key: string,
|
|
86
|
+
canonicalCwd: string,
|
|
87
|
+
reason: Exclude<AcquireReason, "live">,
|
|
88
|
+
fire: () => void,
|
|
89
|
+
): Promise<AcquireResult> {
|
|
90
|
+
let resolve!: (r: AcquireResult) => void;
|
|
91
|
+
let reject!: (e: Error) => void;
|
|
92
|
+
const promise = new Promise<AcquireResult>((res, rej) => {
|
|
93
|
+
resolve = res;
|
|
94
|
+
reject = rej;
|
|
95
|
+
});
|
|
96
|
+
const timeoutMs = deps.config().registerTimeoutSeconds * 1000;
|
|
97
|
+
const entry: InFlight = {
|
|
98
|
+
key,
|
|
99
|
+
canonicalCwd,
|
|
100
|
+
promise: promise.then((r) => ({ ...r, reason })),
|
|
101
|
+
resolve,
|
|
102
|
+
reject,
|
|
103
|
+
timer: undefined,
|
|
104
|
+
};
|
|
105
|
+
// Register the in-flight entry SYNCHRONOUSLY (before the caps-admission
|
|
106
|
+
// await) so a truly-concurrent acquire coalesces onto it and the register
|
|
107
|
+
// callback can find it. The caps gate + the actual spawn/resume then run
|
|
108
|
+
// asynchronously; a capacity rejection clears the entry and rejects.
|
|
109
|
+
inFlight.set(key, entry);
|
|
110
|
+
admit(key)
|
|
111
|
+
.then(() => {
|
|
112
|
+
// Start the register-timeout clock only once the spawn/resume actually
|
|
113
|
+
// FIRES — the caps-admission gate may await a ~2 s graceful reclaim, and
|
|
114
|
+
// that must not eat into the register window (else a slow reclaim spuriously
|
|
115
|
+
// times out the acquire).
|
|
116
|
+
entry.timer = setTimeout(() => {
|
|
117
|
+
inFlight.delete(key);
|
|
118
|
+
reject(new Error(`acquire register timeout for ${key}`));
|
|
119
|
+
}, timeoutMs);
|
|
120
|
+
entry.timer.unref?.();
|
|
121
|
+
fire();
|
|
122
|
+
})
|
|
123
|
+
.catch((e: Error) => {
|
|
124
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
125
|
+
inFlight.delete(key);
|
|
126
|
+
reject(e);
|
|
127
|
+
});
|
|
128
|
+
return entry.promise;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function acquire(req: AcquireRequest): Promise<AcquireResult> {
|
|
132
|
+
const key = keyFor(req);
|
|
133
|
+
|
|
134
|
+
// (0) Coalesce onto an in-flight spawn/resume for the same key (E8, E9).
|
|
135
|
+
const pending = inFlight.get(key);
|
|
136
|
+
if (pending) return pending.promise;
|
|
137
|
+
|
|
138
|
+
// (a) Reuse an existing live session (E6, E7, E11).
|
|
139
|
+
const mapped = keyToSessionId.get(key);
|
|
140
|
+
if (mapped && deps.isSessionLive(mapped)) {
|
|
141
|
+
deps.onReuse?.(true);
|
|
142
|
+
return Promise.resolve({ sessionId: mapped, reason: "live" });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
deps.onReuse?.(false);
|
|
146
|
+
const canonicalCwd = deps.canonicalizeCwd(req.cwd);
|
|
147
|
+
|
|
148
|
+
// (b) Resume the key's most recent resumable ended session (E10, E13).
|
|
149
|
+
if (mapped && deps.isSessionResumable(mapped)) {
|
|
150
|
+
return beginInFlight(key, canonicalCwd, "resumed", () => deps.resume(mapped, req, key));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// (c) Spawn exactly one — after the allowlist check (X1).
|
|
154
|
+
if (!deps.isCwdAllowed(req.cwd)) {
|
|
155
|
+
return Promise.reject(new Error(`cwd not allowed: ${req.cwd}`));
|
|
156
|
+
}
|
|
157
|
+
return beginInFlight(key, canonicalCwd, "spawned", () => deps.spawn(req, key));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function resolveByCwd(canonicalCwd: string, sessionId: string): void {
|
|
161
|
+
// Resolve the oldest in-flight acquire whose canonical cwd matches (Map
|
|
162
|
+
// iteration is insertion order = FIFO).
|
|
163
|
+
for (const entry of inFlight.values()) {
|
|
164
|
+
if (entry.canonicalCwd !== canonicalCwd) continue;
|
|
165
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
166
|
+
inFlight.delete(entry.key);
|
|
167
|
+
keyToSessionId.set(entry.key, sessionId); // own the mapping / re-point (E10)
|
|
168
|
+
entry.resolve({ sessionId, reason: "spawned" });
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
acquire,
|
|
175
|
+
resolveByCwd,
|
|
176
|
+
mappedSessionId: (key) => keyToSessionId.get(key),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
@@ -13,6 +13,7 @@ import { createCanvasAccumulator } from "./canvas/canvas-accumulator.js";
|
|
|
13
13
|
import { readEffectiveCanvasTypes } from "./canvas/canvas-settings.js";
|
|
14
14
|
import { decideDashboardSource } from "./lifecycle/dashboard-source-decision.js";
|
|
15
15
|
import type { DirectoryService } from "./directory-service.js";
|
|
16
|
+
import { captureLifecycleTimestamp } from "./embed-lifecycle/lifecycle-event-capture.js";
|
|
16
17
|
import { extractSessionUpdates, isActivityEvent, isUnreadTrigger } from "./session/event-status-extraction.js";
|
|
17
18
|
import { composeWorktreePayload } from "./git-worktree/git-worktree-compose.js";
|
|
18
19
|
import { keeperOptsFromSpawnResult } from "./spawn-process/headless-pid-registry.js";
|
|
@@ -366,9 +367,14 @@ export function wireEvents(deps: EventWiringDeps): void {
|
|
|
366
367
|
if (pendingAutomationRunRegistry) {
|
|
367
368
|
const stamp = pendingAutomationRunRegistry.consume(cwd);
|
|
368
369
|
if (stamp) {
|
|
370
|
+
// Automation/flow-triggered spawns are machine-fronted → mark them
|
|
371
|
+
// `ephemeral` so the lifecycle reaper/caps have real producers. Human
|
|
372
|
+
// dashboard/TUI spawns never reach this arm, so they stay durable.
|
|
373
|
+
// See change: add-embed-session-lifecycle.
|
|
369
374
|
sessionManager.update(sessionId, {
|
|
370
375
|
kind: "automation",
|
|
371
376
|
automationRun: stamp,
|
|
377
|
+
lifecyclePolicy: "ephemeral",
|
|
372
378
|
});
|
|
373
379
|
const session = sessionManager.get(sessionId);
|
|
374
380
|
if (session?.sessionFile) {
|
|
@@ -376,6 +382,7 @@ export function wireEvents(deps: EventWiringDeps): void {
|
|
|
376
382
|
mergeSessionMeta(session.sessionFile, {
|
|
377
383
|
kind: "automation",
|
|
378
384
|
automationRun: stamp,
|
|
385
|
+
lifecyclePolicy: "ephemeral",
|
|
379
386
|
});
|
|
380
387
|
} catch (err) {
|
|
381
388
|
console.warn(
|
|
@@ -387,6 +394,7 @@ export function wireEvents(deps: EventWiringDeps): void {
|
|
|
387
394
|
browserGateway.broadcastSessionUpdated(sessionId, {
|
|
388
395
|
kind: "automation",
|
|
389
396
|
automationRun: stamp,
|
|
397
|
+
lifecyclePolicy: "ephemeral",
|
|
390
398
|
});
|
|
391
399
|
}
|
|
392
400
|
}
|
|
@@ -703,6 +711,18 @@ export function wireEvents(deps: EventWiringDeps): void {
|
|
|
703
711
|
}
|
|
704
712
|
}
|
|
705
713
|
|
|
714
|
+
// Capture the lifecycle run-boundary timestamps (`agent_start` →
|
|
715
|
+
// lastRunStartedAt, bridge-normalized `agent_settled` → lastSettledAt) so
|
|
716
|
+
// the disabled-by-default reaper's quiescence gate can read a version-
|
|
717
|
+
// agnostic "at rest" signal instead of an inferred `status` (D3). Passive:
|
|
718
|
+
// feeds only the reaper; no runtime behavior change when the feature is
|
|
719
|
+
// off. Skipped during replay so historical events do not reclassify a
|
|
720
|
+
// live session. See change: add-embed-session-lifecycle.
|
|
721
|
+
if (!replayingSessions.has(sessionId)) {
|
|
722
|
+
const lifecycleTs = captureLifecycleTimestamp(msg.event.eventType, Date.now());
|
|
723
|
+
if (lifecycleTs) sessionManager.update(sessionId, lifecycleTs);
|
|
724
|
+
}
|
|
725
|
+
|
|
706
726
|
// Auto-canvas accumulation (change: auto-canvas). Mirrors the replay +
|
|
707
727
|
// queue_state guards internally; drives eager/settle/reset off the same
|
|
708
728
|
// forwarded tool-event stream `detectOpenSpecActivity` reads. cwd comes
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
# event-wiring.ts — index
|
|
2
2
|
|
|
3
3
|
Wires pi-gateway events → browser-gateway + session manager. Exports `wireEvents`, `EventWiringDeps`. Handles `event_forward` (store insert, broadcast, status/unread/activity/OpenSpec/stats extraction, gated `completedFirst`/`questionFirst` reordering, throttled `lastActivityAt`), `session_register` (replay mode, skip-wipe dedup via eventCount, three-tier headless link token→pid→cwd-FIFO, `decideDashboardSource` stamp, ghost cleanup, spawn-correlation, worktree/automation/initial-prompt arms (initial-prompt arm dispatches first `send_prompt`; see change: project-init-skill-and-profiles), goal-driver link via `linkGoalDriver` (PRIMARY: `headlessPidRegistry.getGoalId(sessionId)` token path AFTER `linkByToken`; FALLBACK: legacy goal cwd-FIFO; `replaceDriver` + clears OUTGOING driver's `goalId` for C2e; clears `inFlightSpawn`), `maybeRekeyOrder`, `isGitRepo` stamp + `.meta.json` persist), `replay_complete`, `queue_update`, `prompt_received`, `flows_list` debounce, `git_info_update` (`composeWorktreePayload`, `isGitRepo` refresh + persist). `onUnregister` fans session death to plugins via `dispatchPluginSessionEnded` (EventWiringDeps). See changes: finalize-automation-run-on-session-death, gate-session-worktree-button-on-git, add-goal-session-supervisor. On live events: `empty_actionable_surface` → `console.log(buildEmptyActionableLogLine)` (server.log, non-error); `agent_end` with terminal error → `console.error(buildModelErrorLogLine)` via `extractModelTurnError` (redacted). See change: fix-gemini-subagent-silent-tool-schema-failure. `git_info_update` merges `gitStatus` when present (omitted on inconclusive probe leaves last value). `git_commit_draft_result` → `commitDraftRelay.resolve`; `commitDraftRelay` dep added. See change: add-session-uncommitted-indicator-and-commit.
|
|
4
|
+
On live events also captures lifecycle run-boundaries via `captureLifecycleTimestamp` (`agent_start`->`lastRunStartedAt`, normalized `agent_settled`->`lastSettledAt`; skipped in replay) feeding the disabled-by-default embed-lifecycle reaper; automation-run arm stamps `lifecyclePolicy:"ephemeral"` (mem+meta+broadcast). See change: add-embed-session-lifecycle.
|
|
@@ -4,6 +4,7 @@ Files in this directory. One row per source file. See change: fold-oversized-age
|
|
|
4
4
|
|
|
5
5
|
| File | Purpose |
|
|
6
6
|
|------|---------|
|
|
7
|
+
| `decorate-goals-spend.ts` | `decorateGoalsWithSpend(goals,sessions)` PURE choke point: returns new `{...g, totalSpendUsd}` (Σ guarded `sessions.get(sid)?.cost`, throw/undefined→0) — never mutates input (cache-alias safe). `SpendSessionLookup` = minimal `get(id):{cost?}` surface. Applied at every goal-record emission (routes + `goals_update` broadcast). Read-time only, never persisted. See change: fix-goal-detail-turns-and-spend. |
|
|
7
8
|
| `goal-budget-guard.ts` | `decideBudgetHalt(snapshot,budget)` pure. Returns `{halt:true,command:"/goal pause"}` when active loop… → see `goal-budget-guard.ts.AGENTS.md` |
|
|
8
9
|
| `goal-session-primer.ts` | Kickoff `/goal` loop for goal-linked sessions. Exports `buildGoalPrimerCommands` (`/goal <objective>` or `[]`… → see `goal-session-primer.ts.AGENTS.md` |
|
|
9
10
|
| `goal-status-projector.ts` | `createGoalStatusProjector({store,lookupSession,warn?})`. Peer `goal_status` consumer beside the accumulator. → see `goal-status-projector.ts.AGENTS.md` |
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* decorate-goals-spend — the single server-side choke point that joins each
|
|
3
|
+
* `GoalRecord` with its total USD spend (`Σ DashboardSession.cost` over the
|
|
4
|
+
* goal's `sessionIds`) at read time.
|
|
5
|
+
*
|
|
6
|
+
* PURE by contract: returns NEW record objects (`{ ...g, totalSpendUsd }`) and
|
|
7
|
+
* NEVER mutates an input in place. This purity is load-bearing, not stylistic —
|
|
8
|
+
* `goal-store.ts` create/update/link/unlink return a `result` reference that is
|
|
9
|
+
* ALSO the object stored in the write-through cache, so an in-place
|
|
10
|
+
* `g.totalSpendUsd = …` would be persisted to `<folderHash>.json` on the next
|
|
11
|
+
* write. A pure map can never touch the cache.
|
|
12
|
+
*
|
|
13
|
+
* Robust: a session that does not resolve, has no `cost`, or whose lookup throws
|
|
14
|
+
* contributes `0` — one bad id never propagates a 5xx to the list/broadcast.
|
|
15
|
+
*
|
|
16
|
+
* `totalSpendUsd` is server-derived at read time, never persisted, never
|
|
17
|
+
* bridge-sent — same convention as the server-joined `groupId`.
|
|
18
|
+
*
|
|
19
|
+
* See change: fix-goal-detail-turns-and-spend.
|
|
20
|
+
*/
|
|
21
|
+
import type { GoalRecord } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
22
|
+
|
|
23
|
+
/** Minimal read surface this helper needs from the SessionManager. */
|
|
24
|
+
export interface SpendSessionLookup {
|
|
25
|
+
get(sessionId: string): { cost?: number } | undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Sum the guarded per-session cost over a goal's linked sessions. */
|
|
29
|
+
function sumSpend(sessionIds: readonly string[], sessions: SpendSessionLookup): number {
|
|
30
|
+
let total = 0;
|
|
31
|
+
for (const sid of sessionIds) {
|
|
32
|
+
try {
|
|
33
|
+
total += sessions.get(sid)?.cost ?? 0;
|
|
34
|
+
} catch {
|
|
35
|
+
// Unresolvable / throwing lookup contributes 0 — never propagates.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return total;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Return new `GoalRecord` objects each carrying a read-time `totalSpendUsd`.
|
|
43
|
+
* Input records are never mutated.
|
|
44
|
+
*/
|
|
45
|
+
export function decorateGoalsWithSpend(goals: GoalRecord[], sessions: SpendSessionLookup): GoalRecord[] {
|
|
46
|
+
return goals.map((g) => ({ ...g, totalSpendUsd: sumSpend(g.sessionIds, sessions) }));
|
|
47
|
+
}
|
|
@@ -85,7 +85,7 @@ export interface GoalSupervisorDeps {
|
|
|
85
85
|
* it — `/goal` control is only reliable in dashboard-spawned headless). */
|
|
86
86
|
headlessAvailable?: () => boolean;
|
|
87
87
|
now?: () => number;
|
|
88
|
-
setTimer?: (fn: () => void
|
|
88
|
+
setTimer?: (fn: () => void | Promise<void>, ms: number) => ReturnType<typeof setTimeout>;
|
|
89
89
|
clearTimer?: (t: ReturnType<typeof setTimeout>) => void;
|
|
90
90
|
log?: (msg: string, meta?: Record<string, unknown>) => void;
|
|
91
91
|
}
|
|
@@ -275,8 +275,10 @@ export function createGoalSupervisor(deps: GoalSupervisorDeps): GoalSupervisor {
|
|
|
275
275
|
const timer = setTimer(() => {
|
|
276
276
|
timers.delete(goal.id);
|
|
277
277
|
// performSpawn is generation-guarded + lock-serialized; catch so a store
|
|
278
|
-
// I/O failure can't become an unhandled rejection.
|
|
279
|
-
|
|
278
|
+
// I/O failure can't become an unhandled rejection. Return the promise so a
|
|
279
|
+
// fake timer (tests) can deterministically await the spawn instead of
|
|
280
|
+
// racing a fixed settle delay; real setTimeout ignores the return value.
|
|
281
|
+
return withGoalLock(goal.id, () =>
|
|
280
282
|
performSpawn(goal.id, goal.cwd, reason, sessionFile, generationAtSchedule),
|
|
281
283
|
).catch((err) => log("[goal-supervisor] performSpawn failed", { goalId: goal.id, err: String(err) }));
|
|
282
284
|
}, backoff);
|
|
@@ -10,9 +10,9 @@ Files in this directory. One row per source file.
|
|
|
10
10
|
| `failed-auth-backoff.ts` | Per-source-IP exponential backoff for failed proxy auth. Class `FailedAuthBackoff`: `record(ip)` doubles delay from 10ms cap 10s, `reset(ip)` on success, `getDelayMs(ip)` peeks. In-memory only. |
|
|
11
11
|
| `custom-provider-discovery.ts` | Server-side custom-provider discovery (Approach C). Exports `discoverProviderModels(name, entry)` + `discoverAllCustomProviders(providers)`: for each `providers.json#providers` entry resolves apiKey (`resolveProbeApiKey`) + lists `/v1/models` (`listProviderModelIds`), returns `CustomModelEntry[]` carrying provider `baseUrl`/`api` + api-typed fallback capability floors. Never throws (unreachable provider → []). NO models.json. See change: add-agent-role-model-tools. |
|
|
12
12
|
| `internal-auth-storage.ts` | Server-resident auth storage `InternalAuthStorage`. Reads `~/.pi/agent/auth.json` via `provider-auth-storage.ts`, returns API key + headers per model. Constructor takes optional `customProviderCreds` resolver — custom-provider api_key creds (from providers.json, not auth.json) fall back here so custom-provider models route (change: add-agent-role-model-tools). For OAuth credentials, `ensureFreshOAuth` refreshes tokens 30s before expiry (provider-specific `getOAuthProvider` then generic `refreshOAuthToken` fallback), serializes concurrent refreshes per provider in `refreshLocks`, persists via `writeCredential`. `OAUTH_PROVIDER_MAP` maps anthropic/openai-codex/github-copilot. |
|
|
13
|
-
| `internal-registry.ts` | Server-resident model registry `InternalRegistry`. Composes pi-ai built-in providers with custom-provider models discovered from `providers.json` (`discover()` — fills the former no-op loop via `deps.discoverCustomProviders`, cached) + any user-authored `models.json`, filters to authed models via `canRouteModel` (api_key routes all; oauth routes only `oauthCompatible !== false`). `refresh()` re-runs discovery. Exports `getAvailable`, `find`, `firstAvailable(preferred[])` (walk ordered fqids, first available in registry; skips bare labels; null on empty/none), `getApiKeyAndHeaders`, `refresh`, `discover`, `getAll`, `getAllAnnotated` (excludedReason: no-credential/oauth-incompatible). `getAllModels()`
|
|
13
|
+
| `internal-registry.ts` | Server-resident model registry `InternalRegistry`. Composes pi-ai built-in providers with custom-provider models discovered from `providers.json` (`discover()` — fills the former no-op loop via `deps.discoverCustomProviders`, cached) + any user-authored `models.json`, filters to authed models via `canRouteModel` (api_key routes all; oauth routes only `oauthCompatible !== false`). `refresh()` re-runs discovery. Exports `getAvailable`, `find`, `firstAvailable(preferred[])` (walk ordered fqids, first available in registry; skips bare labels; null on empty/none), `getApiKeyAndHeaders`, `refresh`, `discover`, `getAll`, `getAllAnnotated` (excludedReason: no-credential/oauth-incompatible). `getAllModels()` field-level OUTER JOINs custom models per `provider/id`: routing (`baseUrl`/`api`/`oauthCompatible`) from discovery, capabilities (`contextWindow`/`maxTokens`/`reasoning`/`thinkingLevelMap`/`compat`/`input`/`cost`) from native `models.json` and WIN on overlap; native-only surfaces (routing from `providers.json`); discovered-only keeps floors; `oauthCompatible` NEVER from native. Then dedups by fqid keeping first (built-in → merged-custom) so a custom entry under a built-in name never overrides the built-in. `compat` carried on the model for `streamSimple` routing, never emitted by `toRow`. Types `PiAiModule`, `CustomProviderEntry`, `CustomModelEntry` (gains `thinkingLevelMap?`/`compat?`), `InternalRegistryDeps` (+ optional `discoverCustomProviders`). See change: add-agent-role-model-tools, fix-and-prefer-model-proxy-resolution, honor-native-models-json-metadata. |
|
|
14
14
|
| `oauth-compat.ts` | OAuth-incompatible model override table. Exports `OAUTH_INCOMPATIBLE: Record<provider, ReadonlySet<modelId>>` + `isOauthIncompatible(provider, id)` (unknown provider/id → false; case-sensitive). Flags legacy Anthropic snapshots (`claude-3.x` dated ids) unreachable over OAuth. `internal-registry.ts` sets `oauthCompatible = !isOauthIncompatible(...)` on built-in models. Hand-maintained; review when provider ships new model. See change: filter-oauth-incompatible-models. |
|
|
15
15
|
| `recursion-guard.ts` | Recursion guard preventing custom providers pointing back at dashboard. `collectDashboardOrigins(port, opts)` enumerates localhost + LAN IPs + optional tunnel/mDNS hostnames. `isSelfPointing(baseUrl, origins)` normalizes URL host:port and checks against origin list. |
|
|
16
|
-
| `registry-singleton.ts` | Singleton accessor for `InternalRegistry`. `getModelRegistry()` lazily resolves pi-ai via `getDefaultRegistry().resolveModule`, loads oauth subpath, constructs `InternalAuthStorage` + `InternalRegistry` with disk readers for `~/.pi/agent/providers.json` and `~/.pi/agent/models.json
|
|
16
|
+
| `registry-singleton.ts` | Singleton accessor for `InternalRegistry`. `getModelRegistry()` lazily resolves pi-ai via `getDefaultRegistry().resolveModule`, loads oauth subpath, constructs `InternalAuthStorage` + `InternalRegistry` with disk readers for `~/.pi/agent/providers.json` and `~/.pi/agent/models.json` (exported `readModels()` routes through shared `flattenModelsJson` — native nested + legacy shapes; `console.warn` on parse failure), wires `discoverCustomProviders: discoverAllCustomProviders` + fires initial `discover()`. `readAugmentedAuth` merges auth.json with synthetic custom-provider api_key creds (`readCustomProviderCreds`) so discovered custom models pass `getAvailable`'s auth filter. Also exports `refreshModelRegistry`, `disposeModelRegistry`, `getStreamSimpleFn`, `getModelProxyStatus` (ready/degraded). See change: add-agent-role-model-tools. |
|
|
17
17
|
| `request-log.ts` | Optional JSONL request logger `logRequest(entry)` to `~/.pi/dashboard/model-proxy.jsonl`. Logs metadata only (no bodies, no keys): `RequestLogEntry` carries ts, requestId, apiKeyId, model, format, status, durationMs, tokens, error. Rotates at 50MB to dated suffix. Best-effort, never throws. |
|
|
18
18
|
| `streamer.ts` | Wrapper `streamCompletion(opts, piAiStreamSimple, registryOverride?)` around pi-ai `streamSimple`. Resolves API key + headers from registry (`getModelRegistry` default), assembles context (messages/systemPrompt/tools) + options (apiKey/headers/maxTokens/temperature/signal), returns `AsyncIterable` of pi-ai StreamEvents. Types `StreamCompletionOpts`, `RegistryLike`. |
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* getAllModels field-level outer join: discovery = routing authority, native
|
|
3
|
+
* models.json = capabilities (win); native-only surfaces (outer join);
|
|
4
|
+
* discovered-only keeps fallback floors; built-in wins over a custom entry
|
|
5
|
+
* under a built-in name; oauthCompatible never taken from native.
|
|
6
|
+
*
|
|
7
|
+
* See change: honor-native-models-json-metadata (test-plan E4/E5/E6/E7/E8, §5).
|
|
8
|
+
*/
|
|
9
|
+
import { describe, expect, it } from "vitest";
|
|
10
|
+
import {
|
|
11
|
+
type CustomModelEntry,
|
|
12
|
+
type CustomProviderEntry,
|
|
13
|
+
InternalRegistry,
|
|
14
|
+
type InternalRegistryDeps,
|
|
15
|
+
type PiAiModule,
|
|
16
|
+
} from "../internal-registry.js";
|
|
17
|
+
|
|
18
|
+
function makePiAi(builtins: Record<string, any[]>): PiAiModule {
|
|
19
|
+
return {
|
|
20
|
+
registerBuiltInApiProviders: () => {},
|
|
21
|
+
getProviders: () => Object.keys(builtins),
|
|
22
|
+
getModels: (provider: string) => builtins[provider] ?? [],
|
|
23
|
+
getModel: () => null,
|
|
24
|
+
registerApiProvider: () => {},
|
|
25
|
+
unregisterApiProviders: () => {},
|
|
26
|
+
streamSimple: async function* () {},
|
|
27
|
+
} as unknown as PiAiModule;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function buildRegistry(opts: {
|
|
31
|
+
builtins?: Record<string, any[]>;
|
|
32
|
+
providers?: Record<string, CustomProviderEntry>;
|
|
33
|
+
discovered?: CustomModelEntry[];
|
|
34
|
+
native?: CustomModelEntry[];
|
|
35
|
+
}): Promise<InternalRegistry> {
|
|
36
|
+
const deps: InternalRegistryDeps = {
|
|
37
|
+
readProviders: () => opts.providers ?? {},
|
|
38
|
+
readModels: () => opts.native ?? [],
|
|
39
|
+
readAuth: () => ({}),
|
|
40
|
+
discoverCustomProviders: async () => opts.discovered ?? [],
|
|
41
|
+
};
|
|
42
|
+
const reg = new InternalRegistry(makePiAi(opts.builtins ?? {}), {} as any, deps);
|
|
43
|
+
await reg.discover();
|
|
44
|
+
return reg;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function pick(reg: InternalRegistry, provider: string, id: string): any {
|
|
48
|
+
return reg.getAll().find((m) => m.provider === provider && m.id === id);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const NATIVE_MAP = { minimal: null, xhigh: "xhigh", max: "max" };
|
|
52
|
+
|
|
53
|
+
describe("getAllModels — native wins over discovery fallback (E4)", () => {
|
|
54
|
+
it("merges: capabilities from native, routing from discovery", async () => {
|
|
55
|
+
const reg = await buildRegistry({
|
|
56
|
+
providers: { newapi: { baseUrl: "https://cfg.example/v1", apiKey: "k" } },
|
|
57
|
+
discovered: [
|
|
58
|
+
{
|
|
59
|
+
provider: "newapi",
|
|
60
|
+
id: "glm-5.2",
|
|
61
|
+
baseUrl: "https://disc.example/v1",
|
|
62
|
+
api: "openai-completions",
|
|
63
|
+
contextWindow: 128000,
|
|
64
|
+
maxTokens: 16384,
|
|
65
|
+
reasoning: false,
|
|
66
|
+
input: ["text"],
|
|
67
|
+
cost: { input: 0, output: 0 },
|
|
68
|
+
oauthCompatible: true,
|
|
69
|
+
},
|
|
70
|
+
],
|
|
71
|
+
native: [
|
|
72
|
+
{
|
|
73
|
+
provider: "newapi",
|
|
74
|
+
id: "glm-5.2",
|
|
75
|
+
contextWindow: 200000,
|
|
76
|
+
maxTokens: 65536,
|
|
77
|
+
reasoning: true,
|
|
78
|
+
thinkingLevelMap: NATIVE_MAP,
|
|
79
|
+
compat: { thinkingFormat: "deepseek" },
|
|
80
|
+
input: ["text", "image"],
|
|
81
|
+
cost: { input: 3, output: 15 },
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
});
|
|
85
|
+
const m = pick(reg, "newapi", "glm-5.2");
|
|
86
|
+
// Capabilities from native
|
|
87
|
+
expect(m.contextWindow).toBe(200000);
|
|
88
|
+
expect(m.maxTokens).toBe(65536);
|
|
89
|
+
expect(m.reasoning).toBe(true);
|
|
90
|
+
expect(m.thinkingLevelMap).toEqual(NATIVE_MAP);
|
|
91
|
+
expect(m.compat).toEqual({ thinkingFormat: "deepseek" });
|
|
92
|
+
expect(m.input).toEqual(["text", "image"]);
|
|
93
|
+
expect(m.cost).toEqual({ input: 3, output: 15 });
|
|
94
|
+
// Routing from discovery
|
|
95
|
+
expect(m.baseUrl).toBe("https://disc.example/v1");
|
|
96
|
+
expect(m.api).toBe("openai-completions");
|
|
97
|
+
expect(m.oauthCompatible).toBe(true);
|
|
98
|
+
// exactly one entry
|
|
99
|
+
expect(reg.getAll().filter((x) => x.provider === "newapi" && x.id === "glm-5.2")).toHaveLength(1);
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
describe("getAllModels — native-only entry survives a discovery outage (E5)", () => {
|
|
104
|
+
it("surfaces the native entry with routing from providers.json", async () => {
|
|
105
|
+
const reg = await buildRegistry({
|
|
106
|
+
providers: { newapi: { baseUrl: "https://cfg.example/v1", apiKey: "k", api: "openai-completions" } },
|
|
107
|
+
discovered: [], // /v1/models unavailable
|
|
108
|
+
native: [{ provider: "newapi", id: "glm-5.2", contextWindow: 200000, reasoning: true }],
|
|
109
|
+
});
|
|
110
|
+
const m = pick(reg, "newapi", "glm-5.2");
|
|
111
|
+
expect(m).toBeDefined();
|
|
112
|
+
expect(m.contextWindow).toBe(200000);
|
|
113
|
+
expect(m.baseUrl).toBe("https://cfg.example/v1");
|
|
114
|
+
expect(m.api).toBe("openai-completions");
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
describe("getAllModels — discovered-only keeps fallback floors (E6)", () => {
|
|
119
|
+
it("a discovered model with no native entry retains its floors", async () => {
|
|
120
|
+
const reg = await buildRegistry({
|
|
121
|
+
discovered: [{ provider: "newapi", id: "other-model", baseUrl: "https://disc.example/v1" }],
|
|
122
|
+
native: [],
|
|
123
|
+
});
|
|
124
|
+
const m = pick(reg, "newapi", "other-model");
|
|
125
|
+
expect(m.contextWindow).toBe(128000);
|
|
126
|
+
expect(m.maxTokens).toBe(8192);
|
|
127
|
+
expect(m.reasoning).toBe(false);
|
|
128
|
+
expect(m.input).toEqual(["text"]);
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
describe("getAllModels — built-in wins over a custom entry under a built-in name (E7)", () => {
|
|
133
|
+
it("keeps the built-in model; the custom models.json entry does not override", async () => {
|
|
134
|
+
const reg = await buildRegistry({
|
|
135
|
+
builtins: { anthropic: [{ id: "claude-x", provider: "anthropic", __src: "builtin", contextWindow: 200000 }] },
|
|
136
|
+
native: [{ provider: "anthropic", id: "claude-x", contextWindow: 999, __src: "custom" } as any],
|
|
137
|
+
});
|
|
138
|
+
const matches = reg.getAll().filter((m) => m.provider === "anthropic" && m.id === "claude-x");
|
|
139
|
+
expect(matches).toHaveLength(1);
|
|
140
|
+
expect(matches[0].__src).toBe("builtin");
|
|
141
|
+
expect(matches[0].contextWindow).toBe(200000);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
describe("getAllModels — oauthCompatible never taken from native (E8)", () => {
|
|
146
|
+
it("a native entry without oauthCompatible does not flip a discovered false to true", async () => {
|
|
147
|
+
const reg = await buildRegistry({
|
|
148
|
+
discovered: [{ provider: "newapi", id: "glm-5.2", baseUrl: "https://disc/v1", oauthCompatible: false }],
|
|
149
|
+
native: [{ provider: "newapi", id: "glm-5.2", contextWindow: 200000 }],
|
|
150
|
+
});
|
|
151
|
+
const m = pick(reg, "newapi", "glm-5.2");
|
|
152
|
+
expect(m.oauthCompatible).toBe(false);
|
|
153
|
+
expect(m.contextWindow).toBe(200000); // native caps still merged
|
|
154
|
+
});
|
|
155
|
+
});
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `readModels()` reads the native nested `providers.<p>.models[]` format (via
|
|
3
|
+
* the shared reader), keeps legacy shapes, is defensive per-provider, and
|
|
4
|
+
* console.warns on a JSON syntax error.
|
|
5
|
+
*
|
|
6
|
+
* See change: honor-native-models-json-metadata (test-plan E1/E3/X1, tasks §4).
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
12
|
+
import { readModels } from "../registry-singleton.js";
|
|
13
|
+
|
|
14
|
+
const MODELS_PATH = join(homedir(), ".pi", "agent", "models.json");
|
|
15
|
+
|
|
16
|
+
function writeModelsJson(text: string): void {
|
|
17
|
+
mkdirSync(join(homedir(), ".pi", "agent"), { recursive: true });
|
|
18
|
+
writeFileSync(MODELS_PATH, text, "utf-8");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
afterEach(() => {
|
|
22
|
+
if (existsSync(MODELS_PATH)) rmSync(MODELS_PATH);
|
|
23
|
+
vi.restoreAllMocks();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe("readModels — native nested format", () => {
|
|
27
|
+
it("flattens providers.<p>.models[] stamped with the parent provider (E1)", () => {
|
|
28
|
+
writeModelsJson(
|
|
29
|
+
JSON.stringify({
|
|
30
|
+
providers: {
|
|
31
|
+
newapi: {
|
|
32
|
+
models: [
|
|
33
|
+
{
|
|
34
|
+
id: "glm-5.2",
|
|
35
|
+
contextWindow: 200000,
|
|
36
|
+
maxTokens: 65536,
|
|
37
|
+
reasoning: true,
|
|
38
|
+
thinkingLevelMap: { max: "max" },
|
|
39
|
+
compat: { thinkingFormat: "deepseek" },
|
|
40
|
+
},
|
|
41
|
+
],
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
}),
|
|
45
|
+
);
|
|
46
|
+
const out = readModels();
|
|
47
|
+
expect(out).toHaveLength(1);
|
|
48
|
+
expect(out[0]).toMatchObject({
|
|
49
|
+
provider: "newapi",
|
|
50
|
+
id: "glm-5.2",
|
|
51
|
+
contextWindow: 200000,
|
|
52
|
+
maxTokens: 65536,
|
|
53
|
+
reasoning: true,
|
|
54
|
+
thinkingLevelMap: { max: "max" },
|
|
55
|
+
compat: { thinkingFormat: "deepseek" },
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("nested native entry wins over a legacy top-level entry on collision (E3)", () => {
|
|
60
|
+
writeModelsJson(
|
|
61
|
+
JSON.stringify({
|
|
62
|
+
models: [{ provider: "newapi", id: "glm-5.2", maxTokens: 8192 }],
|
|
63
|
+
providers: { newapi: { models: [{ id: "glm-5.2", maxTokens: 65536 }] } },
|
|
64
|
+
}),
|
|
65
|
+
);
|
|
66
|
+
const out = readModels();
|
|
67
|
+
expect(out).toHaveLength(1);
|
|
68
|
+
expect(out[0].maxTokens).toBe(65536);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("a malformed provider block contributes nothing but does not throw (X1)", () => {
|
|
72
|
+
writeModelsJson(
|
|
73
|
+
JSON.stringify({
|
|
74
|
+
providers: { bad: { models: "nope" }, good: { models: [{ id: "m1" }] } },
|
|
75
|
+
}),
|
|
76
|
+
);
|
|
77
|
+
expect(readModels()).toEqual([{ provider: "good", id: "m1" }]);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it("a syntactically invalid file returns [] and console.warns (X1)", () => {
|
|
81
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
82
|
+
writeModelsJson("{ not json");
|
|
83
|
+
expect(readModels()).toEqual([]);
|
|
84
|
+
expect(warn).toHaveBeenCalledOnce();
|
|
85
|
+
expect(warn.mock.calls[0][0]).toMatch(/models\.json parse failed/);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("returns [] when the file is absent", () => {
|
|
89
|
+
if (existsSync(MODELS_PATH)) rmSync(MODELS_PATH);
|
|
90
|
+
expect(readModels()).toEqual([]);
|
|
91
|
+
});
|
|
92
|
+
});
|