@weave-os/router 0.2.14

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.
Files changed (69) hide show
  1. package/LICENSE +90 -0
  2. package/README.md +172 -0
  3. package/bin.js +68 -0
  4. package/cc-statusline.sh +951 -0
  5. package/codex-skills/disable-routing/SKILL.md +22 -0
  6. package/codex-skills/fm/SKILL.md +15 -0
  7. package/codex-skills/fm/scripts/emit.sh +8 -0
  8. package/codex-skills/force-model/SKILL.md +15 -0
  9. package/codex-skills/force-model/scripts/emit.sh +9 -0
  10. package/codex-skills/rf/SKILL.md +15 -0
  11. package/codex-skills/rf/scripts/emit.sh +7 -0
  12. package/codex-skills/router-feedback/SKILL.md +15 -0
  13. package/codex-skills/router-feedback/scripts/emit.sh +9 -0
  14. package/codex-skills/router-models/SKILL.md +51 -0
  15. package/codex-skills/router-off/SKILL.md +22 -0
  16. package/codex-skills/router-on/SKILL.md +22 -0
  17. package/codex-skills/router-status/SKILL.md +19 -0
  18. package/codex-skills/ufm/SKILL.md +14 -0
  19. package/codex-skills/ufm/scripts/emit.sh +3 -0
  20. package/codex-skills/unforce-model/SKILL.md +14 -0
  21. package/codex-skills/unforce-model/scripts/emit.sh +4 -0
  22. package/codex-status.sh +378 -0
  23. package/commands/beta.md +5 -0
  24. package/commands/fm.md +6 -0
  25. package/commands/force-model.md +6 -0
  26. package/commands/models.md +46 -0
  27. package/commands/rf.md +6 -0
  28. package/commands/router-feedback.md +6 -0
  29. package/commands/router-models.md +46 -0
  30. package/commands/router-off.md +10 -0
  31. package/commands/router-on.md +10 -0
  32. package/commands/router-session.md +15 -0
  33. package/commands/router-status.md +10 -0
  34. package/commands/ufm.md +5 -0
  35. package/commands/unforce-model.md +5 -0
  36. package/directives.tsv +13 -0
  37. package/install.sh +5092 -0
  38. package/opencode-weave/README.md +78 -0
  39. package/opencode-weave/package.json +18 -0
  40. package/opencode-weave/src/index.ts +655 -0
  41. package/package.json +79 -0
  42. package/pi-router/README.md +123 -0
  43. package/pi-router/package.json +25 -0
  44. package/pi-router/skills/install-lsps/SKILL.md +75 -0
  45. package/pi-router/skills/lsp-guide/SKILL.md +63 -0
  46. package/pi-router/src/beta.ts +21 -0
  47. package/pi-router/src/compaction.ts +188 -0
  48. package/pi-router/src/config.ts +293 -0
  49. package/pi-router/src/context-window.ts +12 -0
  50. package/pi-router/src/dispatch.ts +377 -0
  51. package/pi-router/src/force-model.ts +126 -0
  52. package/pi-router/src/index.ts +62 -0
  53. package/pi-router/src/lsp-broker.ts +255 -0
  54. package/pi-router/src/lsp-client.ts +435 -0
  55. package/pi-router/src/lsp-format.ts +230 -0
  56. package/pi-router/src/lsp-install.ts +215 -0
  57. package/pi-router/src/lsp-protocol.ts +128 -0
  58. package/pi-router/src/lsp-servers.ts +361 -0
  59. package/pi-router/src/lsp.ts +529 -0
  60. package/pi-router/src/metadata.ts +32 -0
  61. package/pi-router/src/pricing.generated.ts +91 -0
  62. package/pi-router/src/provider.ts +64 -0
  63. package/pi-router/src/routed-model.ts +182 -0
  64. package/pi-router/src/safety.ts +66 -0
  65. package/pi-router/src/savings.ts +191 -0
  66. package/pi-router/src/ui.ts +91 -0
  67. package/pi-router/src/wooly.ts +408 -0
  68. package/registry.sh +102 -0
  69. package/uninstall.sh +788 -0
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Environment, routing-knob presets, identity, and the static per-process
3
+ * header policy shared by every part of the extension.
4
+ *
5
+ * The whole design hinges on one pi constraint: `before_provider_request` can
6
+ * mutate the request body but cannot set HTTP headers (headers bind when the
7
+ * Anthropic client is created, before the hook runs). So routing-knob headers
8
+ * are *static per provider config*, i.e. static per process. Subagents are
9
+ * separate processes, which is exactly why "quality for the main loop, speed
10
+ * for subagents" maps cleanly onto process identity (`WEAVE_PI_SUBAGENT`).
11
+ */
12
+
13
+ import { execFileSync } from "node:child_process";
14
+ import * as fs from "node:fs";
15
+ import * as os from "node:os";
16
+ import * as path from "node:path";
17
+ import type { ProviderModelConfig } from "@mariozechner/pi-coding-agent";
18
+
19
+ /** Provider name. NOT "anthropic" — overriding the built-in provider hijacks the Claude OAuth token. */
20
+ export const PROVIDER_NAME = "weave";
21
+
22
+ export type Role = "main" | "subagent";
23
+
24
+ /** Children spawned by the dispatch tool run with WEAVE_PI_SUBAGENT=1. */
25
+ export function isSubagent(): boolean {
26
+ return process.env.WEAVE_PI_SUBAGENT === "1";
27
+ }
28
+
29
+ export function getRole(): Role {
30
+ return isSubagent() ? "subagent" : "main";
31
+ }
32
+
33
+ function numEnv(name: string, fallback: number): number {
34
+ const raw = process.env[name];
35
+ if (raw === undefined || raw.trim() === "") return fallback;
36
+ const n = Number(raw);
37
+ return Number.isFinite(n) ? n : fallback;
38
+ }
39
+
40
+ // ---------- router endpoint ----------
41
+
42
+ /**
43
+ * Router base URL — the ROOT, with no /v1 and no trailing slash. pi's
44
+ * anthropic-messages provider uses @anthropic-ai/sdk, which appends /v1/messages
45
+ * to this; a trailing /v1 would produce /v1/v1/messages and 404. Order:
46
+ * WEAVE_ROUTER_URL env (children inherit it), then the installer-written
47
+ * models.json baseUrl (so the extension always agrees with however the user
48
+ * installed — hosted, --local, or custom), then the local default. Without the
49
+ * models.json fallback, a hosted install with no env var would be silently
50
+ * re-pointed at localhost. The /v1 strip on the models.json value keeps installs
51
+ * written by an older installer (which appended /v1) working after an update.
52
+ */
53
+ export function getRouterBaseUrl(): string {
54
+ const env = process.env.WEAVE_ROUTER_URL?.trim();
55
+ if (env) return env.replace(/\/v1\/?$/, "").replace(/\/+$/, "");
56
+ const fromModels = readWeaveProvider().baseUrl?.trim();
57
+ if (fromModels) return fromModels.replace(/\/v1\/?$/, "").replace(/\/+$/, "");
58
+ return "http://localhost:8080";
59
+ }
60
+
61
+ // ---------- router key resolution ----------
62
+
63
+ /** Agent config dir, honoring PI_CODING_AGENT_DIR (set for project-scope installs). */
64
+ function getAgentDir(): string {
65
+ const env = process.env.PI_CODING_AGENT_DIR?.trim();
66
+ if (env) return env.startsWith("~/") ? path.join(os.homedir(), env.slice(2)) : env;
67
+ return path.join(os.homedir(), ".pi", "agent");
68
+ }
69
+
70
+ export function getKeyFilePath(): string {
71
+ return process.env.WEAVE_ROUTER_KEY_FILE?.trim() || path.join(getAgentDir(), ".weave_router_key");
72
+ }
73
+
74
+ /** Persisted LSP preferences (per-language "don't offer again" dismissals). */
75
+ export function getLspPrefsPath(): string {
76
+ return path.join(getAgentDir(), ".weave_lsp.json");
77
+ }
78
+
79
+ interface WeaveProviderConfig {
80
+ baseUrl?: string;
81
+ apiKey?: string;
82
+ }
83
+
84
+ let cachedWeaveProvider: WeaveProviderConfig | undefined;
85
+
86
+ /** Read the installer-written `weave` provider block from models.json (cached). */
87
+ function readWeaveProvider(): WeaveProviderConfig {
88
+ if (cachedWeaveProvider) return cachedWeaveProvider;
89
+ let result: WeaveProviderConfig = {};
90
+ try {
91
+ const raw = fs.readFileSync(path.join(getAgentDir(), "models.json"), "utf-8");
92
+ const parsed = JSON.parse(raw) as { providers?: { weave?: WeaveProviderConfig } };
93
+ result = parsed.providers?.weave ?? {};
94
+ } catch {
95
+ /* no models.json — fall through to env/defaults */
96
+ }
97
+ // Cache only a successful, non-empty read. An empty result (file missing or no
98
+ // weave block yet) must not be cached forever — a later install/write should be
99
+ // picked up on the next call.
100
+ if (result.baseUrl || result.apiKey) cachedWeaveProvider = result;
101
+ return result;
102
+ }
103
+
104
+ /** Router key from WEAVE_ROUTER_KEY, else the installer-written key file, else models.json. */
105
+ export function resolveRouterKey(): string | undefined {
106
+ const envKey = process.env.WEAVE_ROUTER_KEY?.trim();
107
+ if (envKey) return envKey;
108
+ try {
109
+ const contents = fs.readFileSync(getKeyFilePath(), "utf-8").trim();
110
+ if (contents) return contents;
111
+ } catch {
112
+ /* no key file — fall through */
113
+ }
114
+ return readWeaveProvider().apiKey?.trim() || undefined;
115
+ }
116
+
117
+ // ---------- identity ----------
118
+
119
+ export interface Identity {
120
+ email?: string;
121
+ name?: string;
122
+ }
123
+
124
+ function gitConfig(key: string): string | undefined {
125
+ try {
126
+ const out = execFileSync("git", ["config", "--get", key], {
127
+ encoding: "utf-8",
128
+ stdio: ["ignore", "pipe", "ignore"],
129
+ }).trim();
130
+ return out || undefined;
131
+ } catch {
132
+ return undefined;
133
+ }
134
+ }
135
+
136
+ let cachedIdentity: Identity | undefined;
137
+
138
+ /** Resolve user identity the same way the installer does: env overrides, then git config. */
139
+ export function resolveIdentity(): Identity {
140
+ if (cachedIdentity) return cachedIdentity;
141
+ const email = process.env.WEAVE_USER_EMAIL?.trim() || gitConfig("user.email");
142
+ const name = process.env.WEAVE_USER_NAME?.trim() || gitConfig("user.name");
143
+ cachedIdentity = { email: email || undefined, name: name || undefined };
144
+ return cachedIdentity;
145
+ }
146
+
147
+ // ---------- routing-knob presets ----------
148
+
149
+ export interface Knobs {
150
+ alpha: number;
151
+ speedWeight: number;
152
+ outputCostRatio: number;
153
+ expectedOutputTokens: number;
154
+ }
155
+
156
+ // Validated against the scorer: alpha + speedWeight <= 1.
157
+ // main: 0.80 + 0.05 = 0.85 (quality-biased; first turn pins a high tier)
158
+ // subagent: 0.25 + 0.45 = 0.70 (speed + cheap fan-out, isolated session)
159
+ // compaction: 0.05 + 0.55 = 0.60 (cheapest — summarization is throwaway)
160
+ const MAIN_LOOP_KNOBS: Knobs = { alpha: 0.8, speedWeight: 0.05, outputCostRatio: 0.5, expectedOutputTokens: 3000 };
161
+ const FAST_CHEAP_KNOBS: Knobs = { alpha: 0.25, speedWeight: 0.45, outputCostRatio: 2.0, expectedOutputTokens: 1500 };
162
+ const COMPACTION_KNOBS: Knobs = { alpha: 0.05, speedWeight: 0.55, outputCostRatio: 3.0, expectedOutputTokens: 1000 };
163
+
164
+ /** Knobs for this process, with per-knob env overrides applied on top of the role preset. */
165
+ export function knobsForRole(role: Role): Knobs {
166
+ const base = role === "subagent" ? FAST_CHEAP_KNOBS : MAIN_LOOP_KNOBS;
167
+ return {
168
+ alpha: numEnv("WEAVE_ROUTING_ALPHA", base.alpha),
169
+ speedWeight: numEnv("WEAVE_ROUTING_SPEED_WEIGHT", base.speedWeight),
170
+ outputCostRatio: numEnv("WEAVE_ROUTING_OUTPUT_COST_RATIO", base.outputCostRatio),
171
+ expectedOutputTokens: numEnv("WEAVE_ROUTING_EXPECTED_OUTPUT_TOKENS", base.expectedOutputTokens),
172
+ };
173
+ }
174
+
175
+ export function compactionKnobs(): Knobs {
176
+ return { ...COMPACTION_KNOBS };
177
+ }
178
+
179
+ // ---------- header builders ----------
180
+
181
+ const KNOB_HEADER = {
182
+ alpha: "x-weave-routing-alpha",
183
+ speedWeight: "x-weave-routing-speed-weight",
184
+ outputCostRatio: "x-weave-routing-output-cost-ratio",
185
+ expectedOutputTokens: "x-weave-routing-expected-output-tokens",
186
+ } as const;
187
+
188
+ export function knobHeaders(k: Knobs): Record<string, string> {
189
+ return {
190
+ [KNOB_HEADER.alpha]: String(k.alpha),
191
+ [KNOB_HEADER.speedWeight]: String(k.speedWeight),
192
+ [KNOB_HEADER.outputCostRatio]: String(k.outputCostRatio),
193
+ [KNOB_HEADER.expectedOutputTokens]: String(k.expectedOutputTokens),
194
+ };
195
+ }
196
+
197
+ /** Identity + auth headers. The router authenticates off X-Weave-Router-Key (authHeader stays false). */
198
+ export function identityHeaders(role: Role, key: string): Record<string, string> {
199
+ const id = resolveIdentity();
200
+ const headers: Record<string, string> = {
201
+ "X-Weave-Router-Key": key,
202
+ "X-App": role === "subagent" ? "pi-subagent" : "pi",
203
+ };
204
+ if (id.email) headers["X-Weave-User-Email"] = id.email;
205
+ if (id.name) headers["X-Weave-User-Name"] = id.name;
206
+ return headers;
207
+ }
208
+
209
+ /** The full static header set for this process's `weave` provider. */
210
+ export function providerHeaders(role: Role, key: string): Record<string, string> {
211
+ return {
212
+ ...identityHeaders(role, key),
213
+ ...knobHeaders(knobsForRole(role)),
214
+ // pi surfaces the routed model in its status bar (from x-router-model), so
215
+ // opt out of the router's in-band "✦ Weave Router → …" badge — it arrives as
216
+ // a separate text block that hides the answer in pi's renderer. (router #263)
217
+ "X-Weave-Routing-Marker": "off",
218
+ };
219
+ }
220
+
221
+ // ---------- model list ----------
222
+
223
+ // Carried as a shared constant rather than relying on registerProvider preserving
224
+ // an omitted `models` list, so the extension is self-sufficient: a freshly
225
+ // dispatched child (and a `pi -e` smoke test with no models.json) can still
226
+ // resolve `weave/<model>`. The list mirrors the installer's headline models;
227
+ // the router re-routes every request regardless, so this is a UX/label surface.
228
+ // The context windows mirror the router's catalog for these models (see
229
+ // internal/router/catalog) so the footer and auto-compaction budget reflect
230
+ // what the router actually serves; per-request reroutes can still land on a
231
+ // different window, which the served-window header reports on the response.
232
+ export const WEAVE_MODELS: ProviderModelConfig[] = [
233
+ model("claude-opus-4-8", "Claude Opus 4.8 (via Weave Router)", 64000, 1_000_000),
234
+ model("claude-opus-4-7", "Claude Opus 4.7 (via Weave Router)", 64000, 1_000_000),
235
+ model("claude-sonnet-4-6", "Claude Sonnet 4.6 (via Weave Router)", 64000, 1_000_000),
236
+ model("claude-haiku-4-5", "Claude Haiku 4.5 (via Weave Router)", 32000, 200_000),
237
+ model("grok-4.6", "Grok 4.6 (via Weave Router)", 131072, 500_000),
238
+ model("qwen/qwen3.8-max", "Qwen 3.8 Max (via Weave Router)", 131072, 1_000_000),
239
+ ];
240
+
241
+ function model(id: string, name: string, maxTokens: number, contextWindow: number = 200000): ProviderModelConfig {
242
+ return {
243
+ id,
244
+ name,
245
+ reasoning: true,
246
+ input: ["text", "image"],
247
+ // Real cost is decided by the router per request and is unknown client-side.
248
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
249
+ contextWindow,
250
+ maxTokens,
251
+ };
252
+ }
253
+
254
+ // ---------- dispatch / misc tunables ----------
255
+
256
+ export const ROUTED_MODEL_HEADER = (process.env.WEAVE_ROUTED_MODEL_HEADER || "x-router-model").toLowerCase();
257
+ export const ROUTED_PROVIDER_HEADER = "x-router-provider";
258
+ export const ROUTER_DECISION_HEADER = "x-router-decision";
259
+ /** Context window (tokens) of the model that actually served the routed response. */
260
+ export const ROUTED_CONTEXT_WINDOW_HEADER = "x-router-context-window";
261
+ /** Marker a headless child prints to stderr so the parent dispatch can read its routed model. */
262
+ export const ROUTED_MODEL_STDERR_PREFIX = "weave-routed-model:";
263
+
264
+ export const SUBAGENT_MODEL = process.env.WEAVE_PI_SUBAGENT_MODEL?.trim() || "claude-sonnet-4-6";
265
+ export const DISPATCH_CONCURRENCY = Math.max(1, numEnv("WEAVE_PI_DISPATCH_CONCURRENCY", 4));
266
+ export const MAX_SUBAGENTS = 8;
267
+ export const SUBAGENT_TIMEOUT_MS = Math.max(1000, numEnv("WEAVE_PI_SUBAGENT_TIMEOUT_MS", 600000));
268
+ export const DEFAULT_READONLY_TOOLS = ["read", "grep", "find", "ls"];
269
+
270
+ // ---------- LSP tunables ----------
271
+
272
+ /** Idle window before an unused language server is shut down. */
273
+ export const LSP_IDLE_MS = Math.max(10_000, numEnv("WEAVE_PI_LSP_IDLE_MS", 300_000));
274
+ export const LSP_REQUEST_TIMEOUT_MS = Math.max(1000, numEnv("WEAVE_PI_LSP_REQUEST_TIMEOUT_MS", 15_000));
275
+ /** Budget for `initialize` and the first query, which race the server's initial indexing pass. */
276
+ export const LSP_WARMUP_TIMEOUT_MS = Math.max(5000, numEnv("WEAVE_PI_LSP_WARMUP_TIMEOUT_MS", 60_000));
277
+ export const LSP_DIAGNOSTICS_WAIT_MS = Math.max(500, numEnv("WEAVE_PI_LSP_DIAGNOSTICS_WAIT_MS", 3000));
278
+ export const LSP_MAX_SERVERS = Math.max(1, numEnv("WEAVE_PI_LSP_MAX_SERVERS", 4));
279
+ export const LSP_MAX_REFERENCES = Math.max(1, numEnv("WEAVE_PI_LSP_MAX_REFERENCES", 100));
280
+
281
+ // Set by dispatch on children so a subagent reaches the parent's warm server
282
+ // pool over a local socket instead of cold-starting its own gopls. Internal:
283
+ // never set these yourself.
284
+ export const LSP_BROKER_ENV = "WEAVE_PI_LSP_BROKER";
285
+ export const LSP_BROKER_TOKEN_ENV = "WEAVE_PI_LSP_BROKER_TOKEN";
286
+
287
+ // Tools that let a subagent mutate the filesystem or run arbitrary commands.
288
+ // dispatch strips these from model-requested per-task `tools` (and downgrades
289
+ // readOnly:false's "all tools") unless WEAVE_PI_ALLOW_SUBAGENT_TOOLS=1, so a
290
+ // prompt-injected main loop can't silently escalate a read-only fan-out into
291
+ // writes/exec. The catastrophic-command gate in safety.ts is a separate, narrower
292
+ // backstop; this is the capability gate.
293
+ export const DANGEROUS_SUBAGENT_TOOLS = new Set(["bash", "edit", "write", "patch", "multiedit", "apply_patch"]);
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Router-served context-window parsing shared by the model registry and
3
+ * compaction guard. The response header is the source of truth for the model
4
+ * that actually served a routed request.
5
+ */
6
+
7
+ /** Parse a router context-window header without accepting fractional or unsafe values. */
8
+ export function parseRoutedContextWindow(value: string | undefined): number | undefined {
9
+ if (!value || !/^[1-9]\d*$/.test(value)) return undefined;
10
+ const contextWindow = Number(value);
11
+ return Number.isSafeInteger(contextWindow) ? contextWindow : undefined;
12
+ }
@@ -0,0 +1,377 @@
1
+ /**
2
+ * `dispatch` — parallel, context-isolated subagents.
3
+ *
4
+ * pi has no native subagents. The canonical pattern (examples/extensions/
5
+ * subagent) is to spawn a fresh `pi --print --mode json --no-session` process
6
+ * per task: true context isolation, reuses pi's own agent loop, and an
7
+ * independent router session. We layer Weave routing on top by loading this
8
+ * same extension in each child (`-e <self>`) with WEAVE_PI_SUBAGENT=1, so the
9
+ * child registers the `weave` provider with the speed/cheap knobs and a
10
+ * "subagent:" session id. Only the final assistant text comes back to the
11
+ * parent — intermediate tool output stays in the child, keeping the main
12
+ * context tiny.
13
+ */
14
+
15
+ import { spawn } from "node:child_process";
16
+ import { randomUUID } from "node:crypto";
17
+ import * as fs from "node:fs";
18
+ import * as path from "node:path";
19
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
20
+ import type { Message } from "@mariozechner/pi-ai";
21
+ import { Text } from "@mariozechner/pi-tui";
22
+ import { Type } from "typebox";
23
+ import {
24
+ DANGEROUS_SUBAGENT_TOOLS,
25
+ DEFAULT_READONLY_TOOLS,
26
+ DISPATCH_CONCURRENCY,
27
+ getRouterBaseUrl,
28
+ LSP_BROKER_ENV,
29
+ LSP_BROKER_TOKEN_ENV,
30
+ MAX_SUBAGENTS,
31
+ PROVIDER_NAME,
32
+ resolveIdentity,
33
+ resolveRouterKey,
34
+ ROUTED_MODEL_STDERR_PREFIX,
35
+ SUBAGENT_MODEL,
36
+ SUBAGENT_TIMEOUT_MS,
37
+ } from "./config.js";
38
+
39
+ /**
40
+ * The slice of the LSP subsystem dispatch depends on: hand me the env a child
41
+ * needs to reach a warm server pool. Declared here, by the consumer, so
42
+ * dispatch and lsp stay unaware of each other and index.ts does the wiring.
43
+ */
44
+ export interface SubagentEnvProvider {
45
+ ensure(): Promise<Record<string, string>>;
46
+ }
47
+
48
+ const SIGKILL_GRACE_MS = 5000;
49
+
50
+ const TaskItem = Type.Object({
51
+ prompt: Type.String({ description: "The full instruction for this subagent." }),
52
+ tools: Type.Optional(
53
+ Type.Array(Type.String(), {
54
+ description: "Tool names this subagent may use (e.g. read, grep). Overrides readOnly for this task. Dangerous tools (bash, write, edit) are ignored unless WEAVE_PI_ALLOW_SUBAGENT_TOOLS=1.",
55
+ }),
56
+ ),
57
+ cwd: Type.Optional(Type.String({ description: "Working directory for this subagent. Defaults to the parent cwd." })),
58
+ });
59
+
60
+ const DispatchParams = Type.Object({
61
+ tasks: Type.Array(TaskItem, {
62
+ minItems: 1,
63
+ maxItems: MAX_SUBAGENTS,
64
+ description: "Tasks to run as parallel, context-isolated subagents.",
65
+ }),
66
+ readOnly: Type.Optional(
67
+ Type.Boolean({
68
+ default: true,
69
+ description: "When true (default), subagents get read-only tools (read, grep, find, ls). Per-task `tools` overrides this. Without WEAVE_PI_ALLOW_SUBAGENT_TOOLS=1, readOnly:false still yields read-only tools (no silent bash/write).",
70
+ }),
71
+ ),
72
+ });
73
+
74
+ interface ChildResult {
75
+ index: number;
76
+ finalText: string;
77
+ routedModel?: string;
78
+ exitCode: number;
79
+ error?: string;
80
+ }
81
+
82
+ /** Resolve how to launch a nested pi (node/bun script, compiled binary, or `pi` on PATH). */
83
+ function getPiInvocation(args: string[]): { command: string; args: string[] } {
84
+ const currentScript = process.argv[1];
85
+ const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
86
+ if (currentScript && !isBunVirtualScript && fs.existsSync(currentScript)) {
87
+ return { command: process.execPath, args: [currentScript, ...args] };
88
+ }
89
+ const execName = path.basename(process.execPath).toLowerCase();
90
+ const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName);
91
+ if (!isGenericRuntime) return { command: process.execPath, args };
92
+ return { command: "pi", args };
93
+ }
94
+
95
+ async function mapWithConcurrencyLimit<TIn, TOut>(
96
+ items: TIn[],
97
+ concurrency: number,
98
+ fn: (item: TIn, index: number) => Promise<TOut>,
99
+ ): Promise<TOut[]> {
100
+ if (items.length === 0) return [];
101
+ const limit = Math.max(1, Math.min(concurrency, items.length));
102
+ const results: TOut[] = new Array(items.length);
103
+ let nextIndex = 0;
104
+ const workers = new Array(limit).fill(null).map(async () => {
105
+ while (true) {
106
+ const current = nextIndex++;
107
+ if (current >= items.length) return;
108
+ results[current] = await fn(items[current], current);
109
+ }
110
+ });
111
+ await Promise.all(workers);
112
+ return results;
113
+ }
114
+
115
+ /** Full text of the child's last assistant message (all text blocks joined). */
116
+ function finalAssistantText(messages: Message[]): string {
117
+ for (let i = messages.length - 1; i >= 0; i--) {
118
+ const msg = messages[i];
119
+ if (msg.role !== "assistant") continue;
120
+ const texts: string[] = [];
121
+ for (const part of msg.content ?? []) {
122
+ if (part.type === "text") texts.push(part.text);
123
+ }
124
+ if (texts.length > 0) return texts.join("");
125
+ }
126
+ return "";
127
+ }
128
+
129
+ function runChild(
130
+ selfPath: string,
131
+ task: { prompt: string; tools?: string[]; cwd?: string },
132
+ readOnly: boolean,
133
+ defaultCwd: string,
134
+ key: string,
135
+ signal: AbortSignal | undefined,
136
+ index: number,
137
+ lspEnv: Record<string, string> | undefined,
138
+ ): Promise<ChildResult> {
139
+ const args = ["--print", "--mode", "json", "--no-session", "-e", selfPath, "--model", `${PROVIDER_NAME}/${SUBAGENT_MODEL}`];
140
+
141
+ // Secure-by-default tool gating. Task input is model-influenced, so without an
142
+ // explicit opt-in we never hand a child write/exec tools: model-requested
143
+ // `tools` are stripped of dangerous entries, and readOnly:false's "all tools"
144
+ // is downgraded to read-only. WEAVE_PI_ALLOW_SUBAGENT_TOOLS=1 restores full
145
+ // flexibility. Stops a prompt-injected main loop from escalating a read-only
146
+ // fan-out into arbitrary command/file execution under the user's identity.
147
+ const allowDangerousTools = process.env.WEAVE_PI_ALLOW_SUBAGENT_TOOLS === "1";
148
+ let tools: string[] | undefined;
149
+ if (task.tools && task.tools.length > 0) {
150
+ tools = task.tools;
151
+ } else if (readOnly || !allowDangerousTools) {
152
+ tools = DEFAULT_READONLY_TOOLS;
153
+ } else {
154
+ tools = undefined; // readOnly:false + opt-in => full toolset
155
+ }
156
+ if (tools && !allowDangerousTools) {
157
+ // Trim first: pi's `--tools` parser trims each entry, so " bash" would slip
158
+ // past a non-trimmed check here and then get re-enabled downstream.
159
+ tools = tools.map((t) => t.trim()).filter((t) => t !== "" && !DANGEROUS_SUBAGENT_TOOLS.has(t.toLowerCase()));
160
+ if (tools.length === 0) tools = DEFAULT_READONLY_TOOLS;
161
+ }
162
+ // All five lsp operations are read-only, so granting it does not widen the
163
+ // capability gate above. Only offered when the parent actually has a broker
164
+ // listening; otherwise the child's tool list is exactly what it is today.
165
+ if (tools && lspEnv && !tools.includes("lsp")) tools = [...tools, "lsp"];
166
+ if (tools) args.push("--tools", tools.join(","));
167
+ args.push(task.prompt);
168
+
169
+ const identity = resolveIdentity();
170
+ const env: NodeJS.ProcessEnv = {
171
+ ...process.env,
172
+ ...lspEnv,
173
+ WEAVE_PI_SUBAGENT: "1",
174
+ WEAVE_PI_SUBAGENT_ID: randomUUID(),
175
+ WEAVE_ROUTER_KEY: key,
176
+ WEAVE_ROUTER_URL: getRouterBaseUrl(),
177
+ };
178
+ // Don't let the main loop's per-knob routing overrides leak into children:
179
+ // knobsForRole prefers env values over the role preset, which would route
180
+ // subagents on the main loop's quality knobs instead of the speed/cheap ones.
181
+ delete env.WEAVE_ROUTING_ALPHA;
182
+ delete env.WEAVE_ROUTING_SPEED_WEIGHT;
183
+ delete env.WEAVE_ROUTING_OUTPUT_COST_RATIO;
184
+ delete env.WEAVE_ROUTING_EXPECTED_OUTPUT_TOKENS;
185
+ // With no broker there must be no broker env at all, so a child never tries
186
+ // to dial a socket that isn't there.
187
+ if (!lspEnv) {
188
+ delete env[LSP_BROKER_ENV];
189
+ delete env[LSP_BROKER_TOKEN_ENV];
190
+ }
191
+ if (identity.email) env.WEAVE_USER_EMAIL = identity.email;
192
+ if (identity.name) env.WEAVE_USER_NAME = identity.name;
193
+
194
+ const result: ChildResult = { index, finalText: "", exitCode: 0 };
195
+ const messages: Message[] = [];
196
+
197
+ return new Promise<ChildResult>((resolve) => {
198
+ const invocation = getPiInvocation(args);
199
+ const proc = spawn(invocation.command, invocation.args, {
200
+ cwd: task.cwd ?? defaultCwd,
201
+ shell: false,
202
+ stdio: ["ignore", "pipe", "pipe"],
203
+ env,
204
+ });
205
+
206
+ let stdoutBuf = "";
207
+ let stderrBuf = "";
208
+ let settled = false;
209
+ let timedOut = false;
210
+
211
+ const processLine = (line: string) => {
212
+ if (!line.trim()) return;
213
+ let event: { type?: string; message?: Message };
214
+ try {
215
+ event = JSON.parse(line);
216
+ } catch {
217
+ return;
218
+ }
219
+ if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
220
+ messages.push(event.message);
221
+ }
222
+ };
223
+
224
+ proc.stdout.on("data", (data) => {
225
+ stdoutBuf += data.toString();
226
+ const lines = stdoutBuf.split("\n");
227
+ stdoutBuf = lines.pop() ?? "";
228
+ for (const line of lines) processLine(line);
229
+ });
230
+ proc.stderr.on("data", (data) => {
231
+ stderrBuf += data.toString();
232
+ });
233
+
234
+ const timer = setTimeout(() => {
235
+ timedOut = true;
236
+ proc.kill("SIGTERM");
237
+ // proc.killed flips true the instant SIGTERM is *sent*, so escalate based
238
+ // on whether the process actually exited (settled), not proc.killed.
239
+ setTimeout(() => {
240
+ if (!settled) proc.kill("SIGKILL");
241
+ }, SIGKILL_GRACE_MS);
242
+ }, SUBAGENT_TIMEOUT_MS);
243
+
244
+ const onAbort = () => {
245
+ proc.kill("SIGTERM");
246
+ setTimeout(() => {
247
+ if (!settled) proc.kill("SIGKILL");
248
+ }, SIGKILL_GRACE_MS);
249
+ };
250
+ if (signal) {
251
+ if (signal.aborted) onAbort();
252
+ else signal.addEventListener("abort", onAbort, { once: true });
253
+ }
254
+
255
+ const settle = (exitCode: number) => {
256
+ if (settled) return;
257
+ settled = true;
258
+ clearTimeout(timer);
259
+ signal?.removeEventListener("abort", onAbort);
260
+ result.exitCode = exitCode;
261
+ // resolve() must always run — a parse error here would otherwise strand
262
+ // this promise and block the whole dispatch via mapWithConcurrencyLimit.
263
+ try {
264
+ if (stdoutBuf.trim()) processLine(stdoutBuf);
265
+ result.finalText = finalAssistantText(messages);
266
+ result.routedModel = lastRoutedModel(stderrBuf);
267
+ if (exitCode !== 0 && !result.finalText) {
268
+ result.error = timedOut
269
+ ? `timed out after ${Math.round(SUBAGENT_TIMEOUT_MS / 1000)}s`
270
+ : signal?.aborted
271
+ ? "aborted"
272
+ : lastStderrLine(stderrBuf) || `exited with code ${exitCode}`;
273
+ }
274
+ } catch (err) {
275
+ if (!result.error) result.error = `failed to read subagent output: ${(err as Error).message}`;
276
+ }
277
+ resolve(result);
278
+ };
279
+
280
+ // A null exit code means the child was killed by a signal (timeout / abort /
281
+ // crash) — settle as failure (1), not success (0), so a killed subagent with
282
+ // no output can't be counted as succeeded.
283
+ proc.on("close", (code) => settle(code ?? 1));
284
+ proc.on("error", (err) => {
285
+ stderrBuf += `${err.message}\n`;
286
+ settle(1);
287
+ });
288
+ });
289
+ }
290
+
291
+ function lastRoutedModel(stderr: string): string | undefined {
292
+ let found: string | undefined;
293
+ for (const line of stderr.split("\n")) {
294
+ const idx = line.indexOf(ROUTED_MODEL_STDERR_PREFIX);
295
+ if (idx !== -1) found = line.slice(idx + ROUTED_MODEL_STDERR_PREFIX.length).trim();
296
+ }
297
+ return found || undefined;
298
+ }
299
+
300
+ function lastStderrLine(stderr: string): string {
301
+ const lines = stderr
302
+ .split("\n")
303
+ .map((l) => l.trim())
304
+ .filter(Boolean);
305
+ return lines.length > 0 ? lines[lines.length - 1] : "";
306
+ }
307
+
308
+ export function registerDispatch(pi: ExtensionAPI, selfPath: string, lspBroker?: SubagentEnvProvider): void {
309
+ pi.registerTool({
310
+ name: "dispatch",
311
+ label: "Dispatch",
312
+ description: [
313
+ "Run tasks as parallel, context-isolated subagents (separate pi processes).",
314
+ "Each subagent has its own context window and routes through the Weave Router on speed/cheap knobs;",
315
+ "only its final answer returns here, so intermediate work never bloats this context.",
316
+ "Subagents are read-only by default (read, grep, find, ls); pass per-task `tools` to widen.",
317
+ "Use for fan-out investigation/search across independent questions.",
318
+ ].join(" "),
319
+ parameters: DispatchParams,
320
+ executionMode: "parallel",
321
+
322
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
323
+ const key = resolveRouterKey();
324
+ if (!key) {
325
+ return {
326
+ content: [
327
+ { type: "text", text: "Weave Router dispatch unavailable: no router key (set WEAVE_ROUTER_KEY or run the --pi installer)." },
328
+ ],
329
+ details: { results: [] as ChildResult[] },
330
+ isError: true,
331
+ };
332
+ }
333
+
334
+ // Start the broker before fan-out so N children share the parent's warm
335
+ // language servers instead of each cold-starting its own. A broker that
336
+ // will not start is not fatal: children just run without the lsp tool.
337
+ let lspEnv: Record<string, string> | undefined;
338
+ try {
339
+ lspEnv = await lspBroker?.ensure();
340
+ } catch {
341
+ lspEnv = undefined;
342
+ }
343
+
344
+ const readOnly = params.readOnly ?? true;
345
+ const results = await mapWithConcurrencyLimit(params.tasks, DISPATCH_CONCURRENCY, (task, index) =>
346
+ runChild(selfPath, task, readOnly, ctx.cwd, key, signal, index, lspEnv),
347
+ );
348
+
349
+ const succeeded = results.filter((r) => r.exitCode === 0 && !r.error).length;
350
+ const blocks = results.map((r) => {
351
+ const tags = [r.routedModel ? `routed: ${r.routedModel}` : null, r.exitCode === 0 && !r.error ? null : "FAILED"]
352
+ .filter(Boolean)
353
+ .join(" · ");
354
+ const header = `## Subagent ${r.index + 1}${tags ? ` (${tags})` : ""}`;
355
+ const body = r.error ? `Error: ${r.error}` : r.finalText || "(no output)";
356
+ return `${header}\n${body}`;
357
+ });
358
+
359
+ return {
360
+ content: [{ type: "text", text: `${succeeded}/${results.length} subagents succeeded\n\n${blocks.join("\n\n")}` }],
361
+ details: { results },
362
+ isError: succeeded === 0,
363
+ };
364
+ },
365
+
366
+ renderCall(args, theme) {
367
+ const tasks = args.tasks ?? [];
368
+ let text = `${theme.fg("toolTitle", theme.bold("dispatch "))}${theme.fg("accent", `${tasks.length} subagent${tasks.length === 1 ? "" : "s"}`)}`;
369
+ for (const t of tasks.slice(0, 3)) {
370
+ const preview = t.prompt.length > 60 ? `${t.prompt.slice(0, 60)}...` : t.prompt;
371
+ text += `\n ${theme.fg("dim", preview)}`;
372
+ }
373
+ if (tasks.length > 3) text += `\n ${theme.fg("muted", `… +${tasks.length - 3} more`)}`;
374
+ return new Text(text, 0, 0);
375
+ },
376
+ });
377
+ }