pi-dual-engine 0.0.0-stage → 0.2.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/README.md +103 -2
- package/biome.json +22 -0
- package/dist/index.js +1089 -0
- package/package.json +27 -4
- package/scripts/smoke.ts +141 -0
- package/src/assignment.ts +176 -0
- package/src/breaker.ts +33 -0
- package/src/config.ts +55 -0
- package/src/engine-pool.ts +163 -0
- package/src/families.ts +58 -0
- package/src/handles.ts +31 -0
- package/src/headroom-http.ts +58 -0
- package/src/index.ts +96 -0
- package/src/lifecycle.ts +145 -0
- package/src/locks.ts +93 -0
- package/src/probe.ts +154 -0
- package/src/providers.ts +71 -0
- package/src/retrieve.ts +65 -0
- package/src/session.ts +150 -0
- package/src/setup.ts +230 -0
- package/src/state.ts +49 -0
- package/src/status.ts +64 -0
- package/src/types.ts +47 -0
- package/test/assignment.test.ts +193 -0
- package/test/boot.ts +84 -0
- package/test/breaker.test.ts +92 -0
- package/test/coldstart.test.ts +133 -0
- package/test/defaults.test.ts +16 -0
- package/test/degradation.test.ts +69 -0
- package/test/factory.test.ts +158 -0
- package/test/fakes.ts +155 -0
- package/test/handles.test.ts +37 -0
- package/test/harness.ts +39 -0
- package/test/headroom-http.test.ts +99 -0
- package/test/lifecycle.test.ts +75 -0
- package/test/optin.test.ts +41 -0
- package/test/ownership.test.ts +160 -0
- package/test/probe.test.ts +195 -0
- package/test/providers.test.ts +156 -0
- package/test/retrieve.test.ts +137 -0
- package/test/windows-spawn.test.ts +93 -0
- package/tsconfig.json +17 -0
- package/wiki/01-getting-started.md +17 -0
- package/wiki/02-guides-and-workflows.md +22 -0
- package/wiki/03-architecture-and-internals.md +15 -0
- package/wiki/index.md +15 -0
package/src/retrieve.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { AgentToolResult, ExtensionToolContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { RETRIEVAL_TOOL_CANDIDATES, resolveRetrievalTool } from "./families.ts";
|
|
4
|
+
import { dispatchHandle } from "./handles.ts";
|
|
5
|
+
import type { EngineId } from "./types.ts";
|
|
6
|
+
|
|
7
|
+
export type EngineOutcome = {
|
|
8
|
+
readonly content: AgentToolResult<unknown>["content"];
|
|
9
|
+
readonly isError: boolean;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export type RetrieveDeps = {
|
|
13
|
+
/** Calls the engine's own retrieval tool. Never rejects for tool failures. */
|
|
14
|
+
readonly resolve: (engine: EngineId, handle: string, ctx: ExtensionToolContext) => Promise<EngineOutcome>;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const parameters = Type.Object({
|
|
18
|
+
handle: Type.String({
|
|
19
|
+
description: "Recovery handle from a compression marker: ccr_... or 12-24 lowercase hex.",
|
|
20
|
+
}),
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
function text(value: string): AgentToolResult<unknown> {
|
|
24
|
+
return { content: [{ type: "text", text: value }], details: undefined };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* One model-visible retrieval tool. It owns no store: it dispatches by handle shape and returns
|
|
29
|
+
* the owning engine's result unchanged.
|
|
30
|
+
*/
|
|
31
|
+
export function createRetrieveTool(deps: RetrieveDeps): ToolDefinition<typeof parameters> {
|
|
32
|
+
return {
|
|
33
|
+
name: "retrieve",
|
|
34
|
+
label: "Retrieve",
|
|
35
|
+
description:
|
|
36
|
+
"Restore an original compressed by Caveman or Headroom. Pass the recovery handle exactly as it appeared in the marker.",
|
|
37
|
+
parameters,
|
|
38
|
+
prepareLoadout: (loadout) => ({
|
|
39
|
+
hiddenDeclarations: Object.values(RETRIEVAL_TOOL_CANDIDATES)
|
|
40
|
+
.flat()
|
|
41
|
+
.filter((name) => loadout.registered.some((tool) => tool.name === name)),
|
|
42
|
+
}),
|
|
43
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
44
|
+
const target = dispatchHandle(params.handle);
|
|
45
|
+
if ("error" in target) {
|
|
46
|
+
const failure = text(target.error);
|
|
47
|
+
return { content: failure.content, details: undefined, isError: true };
|
|
48
|
+
}
|
|
49
|
+
const outcome = await deps.resolve(target.engine, target.handle, ctx);
|
|
50
|
+
return { content: outcome.content, details: undefined, isError: outcome.isError };
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Run the engine's own tool through the same validation, hooks and permission checks. */
|
|
56
|
+
export async function executeEngineTool(
|
|
57
|
+
ctx: ExtensionToolContext,
|
|
58
|
+
engine: EngineId,
|
|
59
|
+
handle: string,
|
|
60
|
+
): Promise<EngineOutcome> {
|
|
61
|
+
const callable = Array.isArray(ctx.tools) ? ctx.tools : [];
|
|
62
|
+
// Caveman's own retrieval tool takes `recovery_handle`; its schema rejects any other spelling.
|
|
63
|
+
const outcome = await ctx.executeTool(resolveRetrievalTool(engine, callable), { recovery_handle: handle });
|
|
64
|
+
return { content: outcome.result.content, isError: outcome.isError };
|
|
65
|
+
}
|
package/src/session.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { deriveAssignments, type AssignmentPlan, type ProviderGroup } from "./assignment.ts";
|
|
3
|
+
import { discoverEngines, startNeeded } from "./engine-pool.ts";
|
|
4
|
+
import { familyOf, hostOf } from "./families.ts";
|
|
5
|
+
import { stopOwned } from "./lifecycle.ts";
|
|
6
|
+
import { writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { planRegistrations, registerAll } from "./providers.ts";
|
|
9
|
+
import type { ModelExtras } from "./providers.ts";
|
|
10
|
+
import { type SessionDeps, type SessionState, groupChatModels } from "./state.ts";
|
|
11
|
+
import type { EngineId, EngineState } from "./types.ts";
|
|
12
|
+
|
|
13
|
+
const STATE_ORDER: readonly EngineId[] = ["caveman", "headroom"];
|
|
14
|
+
|
|
15
|
+
/** Image and classifier models are never compressed, but a provider registration must not drop them. */
|
|
16
|
+
function collectExtras(ctx: ExtensionContext): ModelExtras {
|
|
17
|
+
const extras = new Map<string, Record<string, unknown>[]>();
|
|
18
|
+
for (const type of ["image", "classifier"] as const) {
|
|
19
|
+
for (const model of ctx.modelRegistry.getModelsOfType(type)) {
|
|
20
|
+
const list = extras.get(model.provider) ?? [];
|
|
21
|
+
list.push(model as unknown as Record<string, unknown>);
|
|
22
|
+
extras.set(model.provider, list);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return extras;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Probe what runs, start only the engines a plan needs, then register every provider whose engine
|
|
30
|
+
* proved its identity. An unproven engine never receives a provider.
|
|
31
|
+
*/
|
|
32
|
+
export async function openSession(
|
|
33
|
+
api: ExtensionAPI,
|
|
34
|
+
ctx: ExtensionContext,
|
|
35
|
+
deps: SessionDeps,
|
|
36
|
+
): Promise<SessionState> {
|
|
37
|
+
const groups = await groupChatModels(ctx);
|
|
38
|
+
const extras = collectExtras(ctx);
|
|
39
|
+
const directModels = new Map<string, NonNullable<ExtensionContext["model"]>>();
|
|
40
|
+
for (const model of ctx.modelRegistry.getModelsOfType("chat")) {
|
|
41
|
+
if (!directModels.has(model.provider)) directModels.set(model.provider, model);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const discovered = await discoverEngines(groups, deps);
|
|
45
|
+
await startNeeded(groups, ctx.model?.provider, discovered, deps);
|
|
46
|
+
|
|
47
|
+
const derived = deriveAssignments(groups, discovered.engines, deps.overrides, { familyOf, hostOf });
|
|
48
|
+
for (const notice of derived.notices) deps.notify("warning", notice);
|
|
49
|
+
reportUncompressedResponses(groups, derived.plans, deps);
|
|
50
|
+
writeAssignmentReport(deps, groups, derived.plans, extras);
|
|
51
|
+
|
|
52
|
+
const ports = new Map<string, number>();
|
|
53
|
+
for (const [provider, state] of discovered.headroom) ports.set(provider, state.port);
|
|
54
|
+
registerAll(
|
|
55
|
+
api,
|
|
56
|
+
planRegistrations(
|
|
57
|
+
derived.plans.filter((plan) => plan.engine === "headroom" && ports.has(plan.provider)),
|
|
58
|
+
groups,
|
|
59
|
+
ports,
|
|
60
|
+
extras,
|
|
61
|
+
),
|
|
62
|
+
(message) => deps.notify("warning", message),
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
reportDegradation(deps, discovered.engines, discovered.failures);
|
|
66
|
+
return {
|
|
67
|
+
engines: discovered.engines,
|
|
68
|
+
ports,
|
|
69
|
+
directModels,
|
|
70
|
+
counters: new Map(discovered.engines.map((engine) => [engine.engine, { requests: 0, failures: 0 }])),
|
|
71
|
+
tripped: new Set<string>(),
|
|
72
|
+
failures: discovered.failures,
|
|
73
|
+
plans: [...derived.plans],
|
|
74
|
+
groups,
|
|
75
|
+
extras,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** One durable report the operator and the gates can read: every provider, its families and its engine. */
|
|
80
|
+
function writeAssignmentReport(
|
|
81
|
+
deps: SessionDeps,
|
|
82
|
+
groups: readonly ProviderGroup[],
|
|
83
|
+
plans: readonly AssignmentPlan[],
|
|
84
|
+
extras: ModelExtras,
|
|
85
|
+
): void {
|
|
86
|
+
const chat = groups.map((group) => {
|
|
87
|
+
const plan = plans.find((entry) => entry.provider === group.provider);
|
|
88
|
+
return {
|
|
89
|
+
provider: group.provider,
|
|
90
|
+
engine: plan?.engine ?? null,
|
|
91
|
+
families: plan?.families ?? [],
|
|
92
|
+
direct: plan?.direct ?? [...new Set(group.models.map((model) => model.api))],
|
|
93
|
+
};
|
|
94
|
+
});
|
|
95
|
+
const named = new Set(chat.map((entry) => entry.provider));
|
|
96
|
+
const chatless = [...extras.keys()].filter((provider) => !named.has(provider));
|
|
97
|
+
if (chatless.length > 0) {
|
|
98
|
+
deps.notify(
|
|
99
|
+
"info",
|
|
100
|
+
`Non-chat providers (${chatless.join(", ")}) are never routed through a compression engine.`,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
const report = {
|
|
104
|
+
providers: [
|
|
105
|
+
...chat,
|
|
106
|
+
...chatless.map((provider) => ({ provider, engine: null, families: [], direct: [] })),
|
|
107
|
+
],
|
|
108
|
+
};
|
|
109
|
+
try {
|
|
110
|
+
writeFileSync(join(deps.lifecycle.stateDir, "assignment.json"), JSON.stringify(report, null, 2), "utf8");
|
|
111
|
+
} catch {
|
|
112
|
+
deps.notify("warning", "Could not write the assignment report; the session continues.");
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function reportUncompressedResponses(
|
|
117
|
+
groups: readonly ProviderGroup[],
|
|
118
|
+
plans: readonly AssignmentPlan[],
|
|
119
|
+
deps: SessionDeps,
|
|
120
|
+
): void {
|
|
121
|
+
const responses = groups
|
|
122
|
+
.filter((group) => plans.some((plan) => plan.provider === group.provider && plan.engine === "headroom"))
|
|
123
|
+
.flatMap((group) =>
|
|
124
|
+
group.models
|
|
125
|
+
.filter((model) => /responses/i.test(model.api))
|
|
126
|
+
.map((model) => `${group.provider}/${model.id}`),
|
|
127
|
+
);
|
|
128
|
+
if (responses.length === 0) return;
|
|
129
|
+
deps.notify(
|
|
130
|
+
"info",
|
|
131
|
+
`OpenAI Responses models (${responses.join(", ")}) are not compressed by default: set HEADROOM_COMPRESS_PASSTHROUGH=1 for the Headroom process to opt in.`,
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function reportDegradation(
|
|
136
|
+
deps: SessionDeps,
|
|
137
|
+
engines: readonly EngineState[],
|
|
138
|
+
failures: Map<EngineId, string>,
|
|
139
|
+
): void {
|
|
140
|
+
for (const engine of STATE_ORDER) {
|
|
141
|
+
if (engines.some((candidate) => candidate.engine === engine)) continue;
|
|
142
|
+
const reason = failures.get(engine);
|
|
143
|
+
if (!reason) continue;
|
|
144
|
+
deps.notify("warning", `${engine} is unavailable (${reason}). The session continues without it.`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function closeSession(state: SessionState, deps: SessionDeps): void {
|
|
149
|
+
for (const engine of state.engines) stopOwned(engine, deps.lifecycle);
|
|
150
|
+
}
|
package/src/setup.ts
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { spawn as spawnProcess } from "node:child_process";
|
|
2
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, extname, isAbsolute, join, resolve } from "node:path";
|
|
5
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { loadConfig } from "./config.ts";
|
|
7
|
+
import { probeCaveman, probeHeadroom } from "./probe.ts";
|
|
8
|
+
import type { SessionDeps } from "./state.ts";
|
|
9
|
+
|
|
10
|
+
export const HEADROOM_MCP = "headroom";
|
|
11
|
+
|
|
12
|
+
type Notice = { readonly type: "info" | "warning" | "error"; readonly message: string };
|
|
13
|
+
|
|
14
|
+
export type DualEngineOptions = {
|
|
15
|
+
readonly stateDir?: string;
|
|
16
|
+
readonly cavemanHome?: string;
|
|
17
|
+
readonly agentDir?: string;
|
|
18
|
+
readonly deps?: Partial<SessionDeps>;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** pi versions without exposure metadata cannot hide declarations, so no single retrieve tool is offered. */
|
|
22
|
+
export function canHideDeclarations(pi: ExtensionAPI): boolean {
|
|
23
|
+
try {
|
|
24
|
+
return pi.getAllTools().some((tool) => typeof (tool as { exposure?: unknown }).exposure === "string");
|
|
25
|
+
} catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function resolvePaths(options: DualEngineOptions): {
|
|
31
|
+
stateDir: string;
|
|
32
|
+
cavemanHome: string;
|
|
33
|
+
agentDir: string;
|
|
34
|
+
} {
|
|
35
|
+
return {
|
|
36
|
+
stateDir:
|
|
37
|
+
options.stateDir ?? process.env.DUAL_ENGINE_HOME ?? join(homedir(), ".pi", "agent", "dual-engine"),
|
|
38
|
+
cavemanHome: options.cavemanHome ?? process.env.CAVEMAN_HOME ?? join(homedir(), ".caveman"),
|
|
39
|
+
agentDir: options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Windows npm shims (`.cmd`/`.bat`) cannot run via `CreateProcessW`; resolve them to a direct launch.
|
|
44
|
+
* Mirrors `@caveman-ai/cli` `portableInvocation`: Node shims exec through `process.execPath`, real
|
|
45
|
+
* binaries run directly, always with `shell: false` so no console window is allocated. */
|
|
46
|
+
const WINDOWS_SHIM_MAX_BYTES = 256 * 1024;
|
|
47
|
+
const WINDOWS_SHIM_MAX_DEPTH = 4;
|
|
48
|
+
|
|
49
|
+
function parseWindowsNestedShim(source: string): string | null {
|
|
50
|
+
const match = source.match(/"([^"\r\n]+\.(?:cmd|bat))"[ \t]+%\*/i);
|
|
51
|
+
return match?.[1] ?? null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function parseWindowsNodeShim(source: string): string | null {
|
|
55
|
+
const match = source.match(/["']?%_prog%["']?[ \t]+["']?%dp0%[\\/]([^"'\r\n]+)["']?[ \t]+%\*/i);
|
|
56
|
+
return match?.[1] ?? null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function parseWindowsExeShim(source: string): string | null {
|
|
60
|
+
const match = source.match(/["']?%dp0%[\\/]([^"'\r\n]+\.exe)["']?[ \t]+%\*/i);
|
|
61
|
+
return match?.[1] ?? null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function resolveWindowsNodeShim(executable: string, depth = 0, seen = new Set<string>()): string {
|
|
65
|
+
if (depth > WINDOWS_SHIM_MAX_DEPTH) throw new Error("Windows command shim nesting too deep");
|
|
66
|
+
const normalized = resolve(executable);
|
|
67
|
+
const key = normalized.toLowerCase();
|
|
68
|
+
if (seen.has(key)) throw new Error("Windows command shim cycle");
|
|
69
|
+
seen.add(key);
|
|
70
|
+
const stat = statSync(normalized);
|
|
71
|
+
if (!stat.isFile() || stat.size > WINDOWS_SHIM_MAX_BYTES) {
|
|
72
|
+
throw new Error(`cannot safely launch Windows command shim: ${normalized}`);
|
|
73
|
+
}
|
|
74
|
+
const source = readFileSync(normalized, "utf8");
|
|
75
|
+
const forwardsToBatch = /"[^"\r\n]+\.(?:cmd|bat)"[ \t]+%\*/i.test(source);
|
|
76
|
+
const jsTarget = forwardsToBatch ? null : parseWindowsNodeShim(source);
|
|
77
|
+
const nested = parseWindowsNestedShim(source);
|
|
78
|
+
const exeTarget = forwardsToBatch || jsTarget ? null : parseWindowsExeShim(source);
|
|
79
|
+
const child = jsTarget ?? nested ?? exeTarget;
|
|
80
|
+
if (!child) throw new Error(`cannot safely launch non-Node Windows command shim: ${normalized}`);
|
|
81
|
+
const target =
|
|
82
|
+
/^[A-Za-z]:[\\/]/.test(child) || isAbsolute(child)
|
|
83
|
+
? child
|
|
84
|
+
: resolve(dirname(normalized), ...child.split(/[\\/]+/));
|
|
85
|
+
if (!existsSync(target) || !statSync(target).isFile()) {
|
|
86
|
+
throw new Error(`Windows command shim target is missing: ${target}`);
|
|
87
|
+
}
|
|
88
|
+
if (jsTarget || (!nested && exeTarget)) return target;
|
|
89
|
+
return resolveWindowsNodeShim(target, depth + 1, seen);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function resolveWindowsCommand(command: string, env: NodeJS.ProcessEnv = process.env): string | undefined {
|
|
93
|
+
const pathExt = env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD";
|
|
94
|
+
const names = extname(command)
|
|
95
|
+
? [command]
|
|
96
|
+
: pathExt.split(";").map((ext) => command + (ext.startsWith(".") ? ext : `.${ext}`));
|
|
97
|
+
if (isAbsolute(command) || /[\\/]/.test(command)) {
|
|
98
|
+
for (const name of names) if (existsSync(name)) return name;
|
|
99
|
+
return existsSync(command) ? command : undefined;
|
|
100
|
+
}
|
|
101
|
+
for (const directory of (env.PATH ?? "").split(";")) {
|
|
102
|
+
if (!directory) continue;
|
|
103
|
+
for (const name of names) {
|
|
104
|
+
const candidate = join(directory, name);
|
|
105
|
+
if (existsSync(candidate)) return candidate;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function portableInvocation(
|
|
112
|
+
command: string,
|
|
113
|
+
args: readonly string[],
|
|
114
|
+
platform = process.platform,
|
|
115
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
116
|
+
): { command: string; args: string[] } {
|
|
117
|
+
if (platform !== "win32") return { command, args: [...args] };
|
|
118
|
+
const executable = resolveWindowsCommand(command, env) ?? command;
|
|
119
|
+
if (!/\.(?:cmd|bat)$/i.test(executable)) return { command: executable, args: [...args] };
|
|
120
|
+
try {
|
|
121
|
+
const target = resolveWindowsNodeShim(executable);
|
|
122
|
+
return /\.exe$/i.test(target)
|
|
123
|
+
? { command: target, args: [...args] }
|
|
124
|
+
: { command: process.execPath, args: [target, ...args] };
|
|
125
|
+
} catch {
|
|
126
|
+
return { command: executable, args: [...args] };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Fire-and-forget daemon launch; failures are contained so the probe/degrade path reports them. */
|
|
131
|
+
function spawnDaemon(command: string, args: readonly string[]): { pid: number | undefined } {
|
|
132
|
+
try {
|
|
133
|
+
const inv = portableInvocation(command, args);
|
|
134
|
+
const child = spawnProcess(inv.command, inv.args, {
|
|
135
|
+
stdio: "ignore",
|
|
136
|
+
detached: true,
|
|
137
|
+
shell: false,
|
|
138
|
+
windowsHide: true,
|
|
139
|
+
});
|
|
140
|
+
child.on("error", () => {});
|
|
141
|
+
child.unref();
|
|
142
|
+
return { pid: child.pid };
|
|
143
|
+
} catch {
|
|
144
|
+
return { pid: undefined };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Notices are collected until a session context exists, then flushed once. */
|
|
149
|
+
export function buildDeps(options: DualEngineOptions): {
|
|
150
|
+
deps: SessionDeps;
|
|
151
|
+
flush: (ctx: ExtensionContext) => void;
|
|
152
|
+
} {
|
|
153
|
+
const { stateDir, cavemanHome } = resolvePaths(options);
|
|
154
|
+
const { config } = loadConfig(stateDir);
|
|
155
|
+
const pending: Notice[] = [];
|
|
156
|
+
const seen = new Set<string>();
|
|
157
|
+
const notify = (type: Notice["type"], message: string): void => {
|
|
158
|
+
if (seen.has(message)) return;
|
|
159
|
+
seen.add(message);
|
|
160
|
+
pending.push({ type, message });
|
|
161
|
+
};
|
|
162
|
+
const base: SessionDeps = {
|
|
163
|
+
start: config.start,
|
|
164
|
+
overrides: config.assignment,
|
|
165
|
+
notify,
|
|
166
|
+
lifecycle: {
|
|
167
|
+
stateDir,
|
|
168
|
+
cavemanHome,
|
|
169
|
+
timeoutMs: config.timeoutMs,
|
|
170
|
+
spawn: (command, args) => {
|
|
171
|
+
// Detached so a launcher that forks a worker (headroom) still yields one killable group.
|
|
172
|
+
return spawnDaemon(command, args);
|
|
173
|
+
},
|
|
174
|
+
cavemanStop: () => {
|
|
175
|
+
spawnDaemon("caveman", ["stop"]);
|
|
176
|
+
},
|
|
177
|
+
// A spawned installer can exit before we stop it; ESRCH is normal, never fatal.
|
|
178
|
+
kill: (pid) => {
|
|
179
|
+
try {
|
|
180
|
+
process.kill(-pid);
|
|
181
|
+
} catch {
|
|
182
|
+
try {
|
|
183
|
+
process.kill(pid);
|
|
184
|
+
} catch {
|
|
185
|
+
// ESRCH: process already gone; nothing to stop.
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
now: () => Date.now(),
|
|
190
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
191
|
+
probeCaveman,
|
|
192
|
+
probeHeadroom,
|
|
193
|
+
},
|
|
194
|
+
};
|
|
195
|
+
return {
|
|
196
|
+
deps: { ...base, ...options.deps, notify: options.deps?.notify ?? notify },
|
|
197
|
+
flush: (ctx) => {
|
|
198
|
+
for (const entry of pending.splice(0)) ctx.ui.notify(entry.message, entry.type);
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function userDeclaresHeadroom(agentDir: string): string | undefined {
|
|
204
|
+
const mcpPath = join(agentDir, "mcp.json");
|
|
205
|
+
try {
|
|
206
|
+
const raw = JSON.parse(readFileSync(mcpPath, "utf8")) as { mcpServers?: Record<string, unknown> };
|
|
207
|
+
return raw.mcpServers?.[HEADROOM_MCP] ? mcpPath : undefined;
|
|
208
|
+
} catch {
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Register Headroom's MCP server for this session only; a user declaration of the same name wins. */
|
|
214
|
+
export function registerHeadroomMcp(
|
|
215
|
+
pi: ExtensionAPI,
|
|
216
|
+
ctx: ExtensionContext,
|
|
217
|
+
port: number,
|
|
218
|
+
agentDir: string,
|
|
219
|
+
): void {
|
|
220
|
+
const declared = userDeclaresHeadroom(agentDir);
|
|
221
|
+
if (declared) {
|
|
222
|
+
ctx.ui.notify(`${declared} declares "${HEADROOM_MCP}"; the user declaration takes precedence.`, "info");
|
|
223
|
+
}
|
|
224
|
+
pi.registerMcpServer(HEADROOM_MCP, {
|
|
225
|
+
command: "headroom",
|
|
226
|
+
args: ["mcp", "serve", "--proxy-url", `http://127.0.0.1:${port}`],
|
|
227
|
+
exposure: "codemode",
|
|
228
|
+
toolExposure: { headroom_retrieve: "codemode" },
|
|
229
|
+
});
|
|
230
|
+
}
|
package/src/state.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
|
+
import type { AssignmentPlan, ProviderGroup, ProviderModel } from "./assignment.ts";
|
|
4
|
+
import type { LifecycleDeps } from "./lifecycle.ts";
|
|
5
|
+
import type { ModelExtras } from "./providers.ts";
|
|
6
|
+
import type { EngineId, EngineState } from "./types.ts";
|
|
7
|
+
|
|
8
|
+
export type SessionState = {
|
|
9
|
+
readonly engines: EngineState[];
|
|
10
|
+
readonly ports: Map<string, number>;
|
|
11
|
+
readonly directModels: Map<string, Model<Api>>;
|
|
12
|
+
readonly counters: Map<string, { requests: number; failures: number }>;
|
|
13
|
+
readonly tripped: Set<string>;
|
|
14
|
+
readonly failures: Map<EngineId, string>;
|
|
15
|
+
readonly plans: AssignmentPlan[];
|
|
16
|
+
readonly groups: readonly ProviderGroup[];
|
|
17
|
+
readonly extras: ModelExtras;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export type SessionDeps = {
|
|
21
|
+
readonly lifecycle: LifecycleDeps;
|
|
22
|
+
readonly notify: (type: "info" | "warning" | "error", message: string) => void;
|
|
23
|
+
readonly start: { readonly caveman: boolean; readonly headroom: boolean };
|
|
24
|
+
readonly overrides: readonly { readonly provider: string; readonly engine: string }[];
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** Every usable chat model, grouped by the provider pi reports for it. Unusable providers never route. */
|
|
28
|
+
export async function groupChatModels(ctx: ExtensionContext): Promise<ProviderGroup[]> {
|
|
29
|
+
const grouped = new Map<string, ProviderModel[]>();
|
|
30
|
+
const models = await ctx.modelRegistry
|
|
31
|
+
.getAvailableOfType("chat")
|
|
32
|
+
.catch(() => ctx.modelRegistry.getModelsOfType("chat"));
|
|
33
|
+
for (const model of models) {
|
|
34
|
+
const list = grouped.get(model.provider) ?? [];
|
|
35
|
+
list.push({
|
|
36
|
+
id: model.id,
|
|
37
|
+
name: model.name,
|
|
38
|
+
api: model.api,
|
|
39
|
+
baseUrl: model.baseUrl,
|
|
40
|
+
reasoning: model.reasoning,
|
|
41
|
+
input: model.input,
|
|
42
|
+
cost: model.cost,
|
|
43
|
+
contextWindow: model.contextWindow,
|
|
44
|
+
maxTokens: model.maxTokens,
|
|
45
|
+
});
|
|
46
|
+
grouped.set(model.provider, list);
|
|
47
|
+
}
|
|
48
|
+
return [...grouped.entries()].map(([provider, models]) => ({ provider, models }));
|
|
49
|
+
}
|
package/src/status.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export type EngineCounters = { readonly requests: number; readonly failures: number };
|
|
2
|
+
|
|
3
|
+
export type EngineSection = {
|
|
4
|
+
readonly engine: string;
|
|
5
|
+
readonly port: number;
|
|
6
|
+
readonly mode: "started" | "adopted";
|
|
7
|
+
readonly upstreams: readonly string[];
|
|
8
|
+
readonly providers: readonly string[];
|
|
9
|
+
readonly requests: number;
|
|
10
|
+
readonly failures: number;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export type StatusReport = {
|
|
14
|
+
readonly sections: readonly EngineSection[];
|
|
15
|
+
/** Deliberately absent: the two measurement bases are not summable. */
|
|
16
|
+
readonly combined?: never;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type StatusInput = {
|
|
20
|
+
readonly engines: readonly {
|
|
21
|
+
readonly engine: string;
|
|
22
|
+
readonly port: number;
|
|
23
|
+
readonly owned: boolean;
|
|
24
|
+
readonly upstreams: readonly { readonly family: string; readonly host: string }[];
|
|
25
|
+
}[];
|
|
26
|
+
readonly assignments: readonly { readonly provider: string; readonly engine: string }[];
|
|
27
|
+
readonly counters: ReadonlyMap<string, EngineCounters>;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** Report each engine separately and label the source. Never a combined figure. */
|
|
31
|
+
export function buildStatus(input: StatusInput): StatusReport {
|
|
32
|
+
const sections = input.engines.map((engine) => {
|
|
33
|
+
const counters = input.counters.get(engine.engine) ?? { requests: 0, failures: 0 };
|
|
34
|
+
return {
|
|
35
|
+
engine: engine.engine,
|
|
36
|
+
port: engine.port,
|
|
37
|
+
mode: engine.owned ? ("started" as const) : ("adopted" as const),
|
|
38
|
+
upstreams: engine.upstreams.map((upstream) => `${upstream.family}@${upstream.host}`),
|
|
39
|
+
providers: input.assignments
|
|
40
|
+
.filter((entry) => entry.engine === engine.engine)
|
|
41
|
+
.map((entry) => entry.provider),
|
|
42
|
+
requests: counters.requests,
|
|
43
|
+
failures: counters.failures,
|
|
44
|
+
};
|
|
45
|
+
});
|
|
46
|
+
return { sections };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Human-readable status, one labeled block per engine. */
|
|
50
|
+
export function formatStatus(report: StatusReport): string {
|
|
51
|
+
if (report.sections.length === 0) return "dual-engine: no engine is active; every provider runs direct.";
|
|
52
|
+
return report.sections
|
|
53
|
+
.map((section) => {
|
|
54
|
+
const providers = section.providers.length > 0 ? section.providers.join(", ") : "none";
|
|
55
|
+
const upstreams = section.upstreams.length > 0 ? section.upstreams.join(", ") : "none";
|
|
56
|
+
return [
|
|
57
|
+
`${section.engine} (${section.mode}, port ${section.port})`,
|
|
58
|
+
` providers: ${providers}`,
|
|
59
|
+
` upstreams: ${upstreams}`,
|
|
60
|
+
` requests: ${section.requests} failures: ${section.failures}`,
|
|
61
|
+
].join("\n");
|
|
62
|
+
})
|
|
63
|
+
.join("\n");
|
|
64
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Wire families an engine can carry, and the engines that coordinate them. */
|
|
2
|
+
export type Family = "anthropic" | "openai" | "gemini";
|
|
3
|
+
|
|
4
|
+
export type EngineId = "caveman" | "headroom";
|
|
5
|
+
|
|
6
|
+
/** The engines in stable preference-independent order. */
|
|
7
|
+
export const ENGINE_IDS: readonly EngineId[] = ["headroom", "caveman"];
|
|
8
|
+
|
|
9
|
+
/** An upstream an engine proved it can reach: a family served at a host. */
|
|
10
|
+
export type Upstream = { readonly family: Family; readonly host: string };
|
|
11
|
+
|
|
12
|
+
/** A running engine this session may route through. */
|
|
13
|
+
export type EngineState = {
|
|
14
|
+
readonly engine: EngineId;
|
|
15
|
+
readonly port: number;
|
|
16
|
+
readonly upstreams: readonly Upstream[];
|
|
17
|
+
/** True only when this session started the process; adopted engines are never stopped. */
|
|
18
|
+
readonly owned: boolean;
|
|
19
|
+
/** Caveman's proxy is started by its own door, so its own teardown is what stops it. */
|
|
20
|
+
readonly shutdown?: "caveman";
|
|
21
|
+
/** The lock key this instance was recorded under: a provider for the wire engine, otherwise "main". */
|
|
22
|
+
readonly key?: string;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** A distinct (family, host) pair across one provider's models. */
|
|
26
|
+
export type ProviderFamily = { readonly family: Family; readonly host: string };
|
|
27
|
+
|
|
28
|
+
/** The engine that owns a provider, plus the families it cannot carry. */
|
|
29
|
+
export type Assignment = {
|
|
30
|
+
readonly provider: string;
|
|
31
|
+
readonly engine: EngineId;
|
|
32
|
+
readonly families: readonly Family[];
|
|
33
|
+
readonly direct: readonly Family[];
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** The extension's optional configuration. Absent configuration narrows nothing. */
|
|
37
|
+
export type CoordinatorConfig = {
|
|
38
|
+
readonly start: Record<EngineId, boolean>;
|
|
39
|
+
readonly assignment: readonly { readonly provider: string; readonly engine: string }[];
|
|
40
|
+
readonly timeoutMs: number;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export const DEFAULT_CONFIG: CoordinatorConfig = {
|
|
44
|
+
start: { caveman: true, headroom: true },
|
|
45
|
+
assignment: [],
|
|
46
|
+
timeoutMs: 30_000,
|
|
47
|
+
};
|