@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,64 @@
1
+ /**
2
+ * Registers the `weave` provider with the per-process header policy.
3
+ *
4
+ * Re-registered on each `session_start` (and once at load) so the right knob
5
+ * headers are always live and the provider survives `/reload`. We register a
6
+ * new provider named "weave" rather than overriding the built-in "anthropic"
7
+ * provider — overriding "anthropic" would hijack the Claude OAuth token.
8
+ */
9
+
10
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
11
+ import {
12
+ getRole,
13
+ getRouterBaseUrl,
14
+ isSubagent,
15
+ PROVIDER_NAME,
16
+ providerHeaders,
17
+ resolveRouterKey,
18
+ WEAVE_MODELS,
19
+ } from "./config.js";
20
+
21
+ export interface ContextWindowOverride {
22
+ modelId: string;
23
+ contextWindow: number;
24
+ }
25
+
26
+ function modelsForContextWindow(override?: ContextWindowOverride): typeof WEAVE_MODELS {
27
+ if (!override) return WEAVE_MODELS;
28
+ return WEAVE_MODELS.map((model) =>
29
+ model.id === override.modelId ? { ...model, contextWindow: override.contextWindow } : model,
30
+ );
31
+ }
32
+
33
+ /** Register the Weave provider, optionally using the router-confirmed active context window. */
34
+ export function registerWeave(pi: ExtensionAPI, contextWindowOverride?: ContextWindowOverride): void {
35
+ const key = resolveRouterKey();
36
+ const role = getRole();
37
+
38
+ if (!key) {
39
+ // The main loop can still run off the installer-written models.json
40
+ // provider. A subagent MUST apply the speed/cheap knobs, so a missing
41
+ // key there is fatal rather than silently routing on quality knobs.
42
+ if (isSubagent()) {
43
+ throw new Error(
44
+ "Weave Router: no router key found (set WEAVE_ROUTER_KEY or write ~/.pi/agent/.weave_router_key).",
45
+ );
46
+ }
47
+ return;
48
+ }
49
+
50
+ pi.registerProvider(PROVIDER_NAME, {
51
+ name: "Weave Router",
52
+ // Root URL, no /v1: the anthropic-messages provider uses @anthropic-ai/sdk,
53
+ // which appends /v1/messages to baseUrl. A /v1 here yields /v1/v1/messages.
54
+ baseUrl: getRouterBaseUrl(),
55
+ // Planted to satisfy pi's "is auth configured" check. The router ignores
56
+ // it (auth runs off X-Weave-Router-Key); authHeader:false keeps
57
+ // Authorization free for BYOK.
58
+ apiKey: key,
59
+ api: "anthropic-messages",
60
+ authHeader: false,
61
+ headers: providerHeaders(role, key),
62
+ models: modelsForContextWindow(contextWindowOverride),
63
+ });
64
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Route attribution, session savings, and the interactive Loom presentation.
3
+ *
4
+ * The selected Pi model is only the comparison baseline. The router's response
5
+ * headers are authoritative for the model that actually served each response.
6
+ * We pair those headers with Pi's finalized turn usage, persist an audit entry,
7
+ * and rebuild the reachable total whenever a session resumes or changes branch.
8
+ */
9
+
10
+ import type { AssistantMessage } from "@mariozechner/pi-ai";
11
+ import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
12
+ import {
13
+ isSubagent,
14
+ ROUTED_MODEL_HEADER,
15
+ ROUTED_MODEL_STDERR_PREFIX,
16
+ ROUTED_CONTEXT_WINDOW_HEADER,
17
+ ROUTED_PROVIDER_HEADER,
18
+ ROUTER_DECISION_HEADER,
19
+ PROVIDER_NAME,
20
+ } from "./config.js";
21
+ import { parseRoutedContextWindow } from "./context-window.js";
22
+ import { forcedModelFromBranch } from "./force-model.js";
23
+ import { registerWeave } from "./provider.js";
24
+ import {
25
+ aggregateSavings,
26
+ createSavingsEntry,
27
+ isSavingsEntryData,
28
+ normalizeModelId,
29
+ SAVINGS_ENTRY_TYPE,
30
+ type RouteDecision,
31
+ type SavingsAggregate,
32
+ type SavingsEntryData,
33
+ } from "./savings.js";
34
+ import { clearLoomUi, installLoomUi, updateRouterStatus } from "./ui.js";
35
+
36
+ interface PendingRoute {
37
+ requestedModel?: string;
38
+ routedModel: string;
39
+ provider?: string;
40
+ decision?: string;
41
+ }
42
+
43
+ function savingsFromBranch(ctx: ExtensionContext): { entries: SavingsEntryData[]; aggregate: SavingsAggregate } {
44
+ const entries: SavingsEntryData[] = [];
45
+ for (const entry of ctx.sessionManager.getBranch()) {
46
+ if (entry.type !== "custom" || entry.customType !== SAVINGS_ENTRY_TYPE || !isSavingsEntryData(entry.data)) continue;
47
+ entries.push(entry.data);
48
+ }
49
+ return { entries, aggregate: aggregateSavings(entries) };
50
+ }
51
+
52
+ function messageUsage(message: AssistantMessage) {
53
+ return {
54
+ input: message.usage.input,
55
+ output: message.usage.output,
56
+ cacheRead: message.usage.cacheRead,
57
+ cacheWrite: message.usage.cacheWrite,
58
+ };
59
+ }
60
+
61
+ export function registerRoutedModel(pi: ExtensionAPI): void {
62
+ let pendingRoutes: PendingRoute[] = [];
63
+ let entries: SavingsEntryData[] = [];
64
+ let savings = aggregateSavings(entries);
65
+ let requestedModel: string | undefined;
66
+ let routedModel: string | undefined;
67
+ let forcedModel: string | undefined;
68
+ let lastNotifiedModel: string | undefined;
69
+
70
+ const refresh = (ctx: ExtensionContext) => {
71
+ if (isSubagent()) return;
72
+ updateRouterStatus(ctx, { requestedModel, routedModel, forcedModel, savings });
73
+ };
74
+
75
+ const restore = (ctx: ExtensionContext) => {
76
+ const restored = savingsFromBranch(ctx);
77
+ entries = restored.entries;
78
+ savings = restored.aggregate;
79
+ const lastEntry = restored.aggregate.lastEntry;
80
+ requestedModel = ctx.model?.id ?? lastEntry?.requestedModel;
81
+ routedModel =
82
+ lastEntry && requestedModel && normalizeModelId(requestedModel) === lastEntry.requestedModel
83
+ ? lastEntry.routedModel
84
+ : undefined;
85
+ forcedModel = forcedModelFromBranch(ctx.sessionManager.getBranch());
86
+ pendingRoutes = [];
87
+ lastNotifiedModel = undefined;
88
+ };
89
+
90
+ pi.on("session_start", (_event, ctx: ExtensionContext) => {
91
+ restore(ctx);
92
+ if (!isSubagent()) installLoomUi(ctx);
93
+ refresh(ctx);
94
+ });
95
+
96
+ pi.on("model_select", (event, ctx: ExtensionContext) => {
97
+ // A new requested model has not yet received a router-confirmed window.
98
+ // Restore the conservative virtual-model default until its first response.
99
+ registerWeave(pi);
100
+ if (isSubagent()) return;
101
+ requestedModel = event.model.id;
102
+ routedModel = undefined;
103
+ refresh(ctx);
104
+ });
105
+
106
+ pi.on("after_provider_response", (event, ctx: ExtensionContext) => {
107
+ if (event.status < 200 || event.status >= 300) return;
108
+ const model = event.headers?.[ROUTED_MODEL_HEADER];
109
+ if (!model) return;
110
+ const contextWindow = parseRoutedContextWindow(event.headers?.[ROUTED_CONTEXT_WINDOW_HEADER]);
111
+ if (contextWindow && ctx.model?.provider === PROVIDER_NAME) {
112
+ registerWeave(pi, { modelId: ctx.model.id, contextWindow });
113
+ }
114
+ const route: PendingRoute = {
115
+ ...(ctx.model?.id ? { requestedModel: ctx.model.id } : {}),
116
+ routedModel: normalizeModelId(model),
117
+ ...(event.headers[ROUTED_PROVIDER_HEADER] ? { provider: event.headers[ROUTED_PROVIDER_HEADER] } : {}),
118
+ ...(event.headers[ROUTER_DECISION_HEADER] ? { decision: event.headers[ROUTER_DECISION_HEADER] } : {}),
119
+ };
120
+ if (!isSubagent()) pendingRoutes.push(route);
121
+
122
+ if (!ctx.hasUI || isSubagent()) {
123
+ if (route.routedModel !== lastNotifiedModel) {
124
+ process.stderr.write(`${ROUTED_MODEL_STDERR_PREFIX} ${route.routedModel}\n`);
125
+ lastNotifiedModel = route.routedModel;
126
+ }
127
+ return;
128
+ }
129
+
130
+ requestedModel = route.requestedModel ?? requestedModel;
131
+ routedModel = route.routedModel;
132
+ refresh(ctx);
133
+ if (route.routedModel !== lastNotifiedModel) {
134
+ ctx.ui.notify(`Weave Router routed to ${route.routedModel}`, "info");
135
+ lastNotifiedModel = route.routedModel;
136
+ }
137
+ });
138
+
139
+ pi.on("turn_end", (event, ctx: ExtensionContext) => {
140
+ if (isSubagent() || event.message.role !== "assistant") return;
141
+ const restoredForcedModel = forcedModelFromBranch(ctx.sessionManager.getBranch());
142
+ if (restoredForcedModel !== forcedModel) {
143
+ forcedModel = restoredForcedModel;
144
+ // Force-model directives take effect between responses, before the next
145
+ // served-window header can arrive. Fall back to the conservative value.
146
+ registerWeave(pi);
147
+ refresh(ctx);
148
+ }
149
+ const pending = pendingRoutes.shift();
150
+ if (!pending) return;
151
+ const message = event.message as AssistantMessage;
152
+ const selected = pending.requestedModel || message.model || ctx.model?.id;
153
+ if (!selected) return;
154
+ const decision: RouteDecision = {
155
+ requestedModel: selected,
156
+ routedModel: pending.routedModel,
157
+ ...(pending.provider ? { provider: pending.provider } : {}),
158
+ ...(pending.decision ? { decision: pending.decision } : {}),
159
+ };
160
+ const entry = createSavingsEntry(decision, messageUsage(message));
161
+ entries.push(entry);
162
+ savings = aggregateSavings(entries);
163
+ requestedModel = entry.requestedModel;
164
+ routedModel = entry.routedModel;
165
+ pi.appendEntry(SAVINGS_ENTRY_TYPE, entry);
166
+ refresh(ctx);
167
+ });
168
+
169
+ pi.on("session_tree", (_event, ctx: ExtensionContext) => {
170
+ // A branch can have been served by another pinned model. Do not carry that
171
+ // window into the first request on the newly selected branch.
172
+ registerWeave(pi);
173
+ if (isSubagent()) return;
174
+ restore(ctx);
175
+ refresh(ctx);
176
+ });
177
+
178
+ pi.on("session_shutdown", (_event, ctx: ExtensionContext) => {
179
+ pendingRoutes = [];
180
+ if (!isSubagent()) clearLoomUi(ctx);
181
+ });
182
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Last-resort guard against a handful of catastrophic, effectively
3
+ * irreversible shell commands. pi already confirms normal tool calls; this
4
+ * matters most in non-interactive subagents where there is no human to
5
+ * confirm. It blocks ONLY the obviously-destructive forms below — it is a
6
+ * backstop, not a sandbox. Disable with WEAVE_NO_SAFETY=1.
7
+ */
8
+
9
+ import { type ExtensionAPI, type ExtensionContext, isToolCallEventType, type ToolCallEvent } from "@mariozechner/pi-coding-agent";
10
+
11
+ interface Rule {
12
+ test: (cmd: string) => boolean;
13
+ reason: string;
14
+ }
15
+
16
+ const hasRecursive = (c: string) => /(?:\s|^)-\w*r/i.test(c) || /--recursive\b/.test(c);
17
+ const hasForce = (c: string) => /(?:\s|^)-\w*f/i.test(c) || /--force\b/.test(c);
18
+ const targetsRoot = (c: string) =>
19
+ /--no-preserve-root\b/.test(c) || /(?:\s|^)(?:\/|~|\$HOME|\/\*)(?:\s|$)/.test(c);
20
+
21
+ const RULES: Rule[] = [
22
+ {
23
+ test: (c) => /\brm\b/.test(c) && hasRecursive(c) && hasForce(c) && targetsRoot(c),
24
+ reason: "recursive force-remove of a root/home path",
25
+ },
26
+ {
27
+ test: (c) => /\bmkfs(\.\w+)?\b/.test(c),
28
+ reason: "filesystem format (mkfs)",
29
+ },
30
+ {
31
+ test: (c) => /\bdd\b[^\n]*\bof=\/dev\//.test(c),
32
+ reason: "dd writing directly to a device",
33
+ },
34
+ {
35
+ test: (c) => />\s*\/dev\/(?:sd|nvme|disk|hd|mapper)/.test(c),
36
+ reason: "redirect overwriting a raw block device",
37
+ },
38
+ {
39
+ test: (c) => /:\s*\(\s*\)\s*\{[^}]*\|[^}]*&[^}]*\}\s*;\s*:/.test(c),
40
+ reason: "fork bomb",
41
+ },
42
+ {
43
+ test: (c) =>
44
+ /\bgit\s+push\b/.test(c) &&
45
+ (/(?:--force(?!-with-lease)|\s-f\b)/.test(c) || /\+(?:main|master)\b/.test(c)) &&
46
+ /\b(?:main|master)\b/.test(c),
47
+ reason: "force-push to main/master",
48
+ },
49
+ ];
50
+
51
+ function catastrophicReason(command: string): string | undefined {
52
+ const cmd = command.trim();
53
+ for (const rule of RULES) {
54
+ if (rule.test(cmd)) return rule.reason;
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ export function registerSafety(pi: ExtensionAPI): void {
60
+ pi.on("tool_call", (event: ToolCallEvent, _ctx: ExtensionContext) => {
61
+ if (!isToolCallEventType("bash", event)) return undefined;
62
+ const reason = catastrophicReason(event.input.command ?? "");
63
+ if (!reason) return undefined;
64
+ return { block: true, reason: `Weave safety: blocked ${reason}. Set WEAVE_NO_SAFETY=1 to override.` };
65
+ });
66
+ }
@@ -0,0 +1,191 @@
1
+ import { MODEL_PRICING, PRICING_VERSION } from "./pricing.generated.js";
2
+
3
+ export const SAVINGS_ENTRY_TYPE = "weave-router-savings-v1";
4
+
5
+ export interface TokenUsage {
6
+ input: number;
7
+ output: number;
8
+ cacheRead: number;
9
+ cacheWrite: number;
10
+ }
11
+
12
+ export interface RouteDecision {
13
+ requestedModel: string;
14
+ routedModel: string;
15
+ provider?: string;
16
+ decision?: string;
17
+ }
18
+
19
+ export interface SavingsEntryData {
20
+ version: 1;
21
+ pricingVersion: string;
22
+ requestedModel: string;
23
+ routedModel: string;
24
+ provider?: string;
25
+ decision?: string;
26
+ usage: TokenUsage;
27
+ requestedCostUsd?: number;
28
+ routedCostUsd?: number;
29
+ savingsUsd?: number;
30
+ priced: boolean;
31
+ unpricedModels: string[];
32
+ }
33
+
34
+ export interface SavingsAggregate {
35
+ totalSavingsUsd: number;
36
+ pricedResponses: number;
37
+ unpricedResponses: number;
38
+ lastEntry?: SavingsEntryData;
39
+ }
40
+
41
+ function finiteNonNegative(value: number): number | undefined {
42
+ return Number.isFinite(value) && value >= 0 ? value : undefined;
43
+ }
44
+
45
+ export function normalizeModelId(model: string): string {
46
+ return model.trim().replace(/^weave\//, "").replace(/\[[^\]]*\]$/, "").replace(/-[0-9]{8}$/, "");
47
+ }
48
+
49
+ function normalizedUsage(usage: TokenUsage): TokenUsage | undefined {
50
+ const input = finiteNonNegative(usage.input);
51
+ const output = finiteNonNegative(usage.output);
52
+ const cacheRead = finiteNonNegative(usage.cacheRead);
53
+ const cacheWrite = finiteNonNegative(usage.cacheWrite);
54
+ if (input === undefined || output === undefined || cacheRead === undefined || cacheWrite === undefined) {
55
+ return undefined;
56
+ }
57
+ return { input, output, cacheRead, cacheWrite };
58
+ }
59
+
60
+ function modelCostUsd(model: string, usage: TokenUsage): number | undefined {
61
+ const price = MODEL_PRICING[normalizeModelId(model)];
62
+ if (!price) return undefined;
63
+ const inputTokens = usage.input + 1.25 * usage.cacheWrite + price.cacheReadMultiplier * usage.cacheRead;
64
+ return (inputTokens * price.inputUsdPerMillion + usage.output * price.outputUsdPerMillion) / 1_000_000;
65
+ }
66
+
67
+ export function createSavingsEntry(decision: RouteDecision, rawUsage: TokenUsage): SavingsEntryData {
68
+ const requestedModel = normalizeModelId(decision.requestedModel);
69
+ const routedModel = normalizeModelId(decision.routedModel);
70
+ const usage = normalizedUsage(rawUsage);
71
+ const base: SavingsEntryData = {
72
+ version: 1,
73
+ pricingVersion: PRICING_VERSION,
74
+ requestedModel,
75
+ routedModel,
76
+ ...(decision.provider ? { provider: decision.provider } : {}),
77
+ ...(decision.decision ? { decision: decision.decision } : {}),
78
+ usage: usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
79
+ priced: false,
80
+ unpricedModels: [],
81
+ };
82
+
83
+ if (!usage || !requestedModel || !routedModel) return base;
84
+
85
+ // An unchanged route has an exact zero delta even if the catalog does not
86
+ // know the model. Avoid calling a no-op response "unpriced" when no price
87
+ // comparison is necessary.
88
+ if (requestedModel === routedModel) {
89
+ const cost = modelCostUsd(requestedModel, usage);
90
+ return {
91
+ ...base,
92
+ ...(cost === undefined ? {} : { requestedCostUsd: cost, routedCostUsd: cost }),
93
+ savingsUsd: 0,
94
+ priced: true,
95
+ };
96
+ }
97
+
98
+ const requestedCostUsd = modelCostUsd(requestedModel, usage);
99
+ const routedCostUsd = modelCostUsd(routedModel, usage);
100
+ if (requestedCostUsd === undefined || routedCostUsd === undefined) {
101
+ const unpricedModels = [
102
+ ...(requestedCostUsd === undefined ? [requestedModel] : []),
103
+ ...(routedCostUsd === undefined ? [routedModel] : []),
104
+ ];
105
+ return { ...base, unpricedModels };
106
+ }
107
+
108
+ return {
109
+ ...base,
110
+ requestedCostUsd,
111
+ routedCostUsd,
112
+ savingsUsd: requestedCostUsd - routedCostUsd,
113
+ priced: true,
114
+ };
115
+ }
116
+
117
+ function isRecord(value: unknown): value is Record<string, unknown> {
118
+ return typeof value === "object" && value !== null;
119
+ }
120
+
121
+ function isTokenUsage(value: unknown): value is TokenUsage {
122
+ if (!isRecord(value)) return false;
123
+ return [value.input, value.output, value.cacheRead, value.cacheWrite].every(
124
+ (token) => typeof token === "number" && Number.isFinite(token) && token >= 0,
125
+ );
126
+ }
127
+
128
+ export function isSavingsEntryData(value: unknown): value is SavingsEntryData {
129
+ if (!isRecord(value)) return false;
130
+ return (
131
+ value.version === 1 &&
132
+ typeof value.pricingVersion === "string" &&
133
+ typeof value.requestedModel === "string" &&
134
+ typeof value.routedModel === "string" &&
135
+ isTokenUsage(value.usage) &&
136
+ typeof value.priced === "boolean" &&
137
+ (value.provider === undefined || typeof value.provider === "string") &&
138
+ (value.decision === undefined || typeof value.decision === "string") &&
139
+ (value.requestedCostUsd === undefined ||
140
+ (typeof value.requestedCostUsd === "number" && Number.isFinite(value.requestedCostUsd))) &&
141
+ (value.routedCostUsd === undefined ||
142
+ (typeof value.routedCostUsd === "number" && Number.isFinite(value.routedCostUsd))) &&
143
+ Array.isArray(value.unpricedModels) &&
144
+ value.unpricedModels.every((model) => typeof model === "string") &&
145
+ (value.savingsUsd === undefined || (typeof value.savingsUsd === "number" && Number.isFinite(value.savingsUsd)))
146
+ );
147
+ }
148
+
149
+ export function aggregateSavings(entries: Iterable<SavingsEntryData>): SavingsAggregate {
150
+ let totalSavingsUsd = 0;
151
+ let pricedResponses = 0;
152
+ let unpricedResponses = 0;
153
+ let lastEntry: SavingsEntryData | undefined;
154
+ for (const entry of entries) {
155
+ lastEntry = entry;
156
+ if (entry.priced && entry.savingsUsd !== undefined) {
157
+ totalSavingsUsd += entry.savingsUsd;
158
+ pricedResponses++;
159
+ } else {
160
+ unpricedResponses++;
161
+ }
162
+ }
163
+ return {
164
+ totalSavingsUsd,
165
+ pricedResponses,
166
+ unpricedResponses,
167
+ ...(lastEntry ? { lastEntry } : {}),
168
+ };
169
+ }
170
+
171
+ export function formatMoney(amount: number): string {
172
+ const absolute = Math.abs(amount);
173
+ if (absolute > 0 && absolute < 0.005) return "<$0.01";
174
+ return `$${absolute.toFixed(2)}`;
175
+ }
176
+
177
+ export function formatSavings(aggregate: SavingsAggregate): string {
178
+ let clause: string;
179
+ if (aggregate.pricedResponses === 0) {
180
+ clause = "saved —";
181
+ } else if (aggregate.totalSavingsUsd < 0) {
182
+ clause = `extra ${formatMoney(aggregate.totalSavingsUsd)}`;
183
+ } else {
184
+ clause = `saved ${formatMoney(aggregate.totalSavingsUsd)}`;
185
+ }
186
+ if (aggregate.unpricedResponses > 0) {
187
+ const suffix = aggregate.unpricedResponses === 1 ? "1 unpriced" : `${aggregate.unpricedResponses} unpriced`;
188
+ return `${clause} · ${suffix}`;
189
+ }
190
+ return clause;
191
+ }
@@ -0,0 +1,91 @@
1
+ import type { ExtensionContext, Theme } from "@mariozechner/pi-coding-agent";
2
+ import type { TUI } from "@mariozechner/pi-tui";
3
+ import type { SavingsAggregate } from "./savings.js";
4
+ import { formatSavings } from "./savings.js";
5
+ import { WoolyComponent } from "./wooly.js";
6
+
7
+ const STATUS_KEY = "weave-router";
8
+ const WOOLY_WIDGET_KEY = "weave-wooly";
9
+ const BRAND_OPEN = "\x1b[38;2;255;108;71m";
10
+ const BRAND_CLOSE = "\x1b[39m";
11
+
12
+ const WEAVE_WORDMARK = ["╦ ╦╔═╗╔═╗╦ ╦╔═╗", "║║║║╣ ╠═╣╚╗╔╝║╣ ", "╚╩╝╚═╝╩ ╩ ╚╝ ╚═╝"] as const;
13
+ const LOOM_WORDMARK = [
14
+ "██╗ ███████╗ ███████╗ ███╗ ███╗",
15
+ "██║ ██╔═══██╗██╔═══██╗████╗ ████║",
16
+ "██║ ██║ ██║██║ ██║██╔████╔██║",
17
+ "██║ ██║ ██║██║ ██║██║╚██╔╝██║",
18
+ "██████╗╚██████╔╝╚██████╔╝██║ ╚═╝ ██║",
19
+ "╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝",
20
+ ] as const;
21
+
22
+ export interface RouterUiSnapshot {
23
+ requestedModel?: string;
24
+ routedModel?: string;
25
+ forcedModel?: string;
26
+ savings: SavingsAggregate;
27
+ }
28
+
29
+ type LegacyCompatibleExtensionContext = ExtensionContext & { mode?: string };
30
+
31
+ function isTuiContext(ctx: ExtensionContext): boolean {
32
+ const mode = (ctx as LegacyCompatibleExtensionContext).mode;
33
+ // Pi 0.74.2 supports headers and widgets but predates ctx.mode. In that
34
+ // release hasUI is true only for the interactive TUI, so it is the safe
35
+ // compatibility signal. Newer Pi releases expose mode and take precedence.
36
+ return mode === "tui" || (mode === undefined && ctx.hasUI);
37
+ }
38
+
39
+ function brand(text: string): string {
40
+ return `${BRAND_OPEN}${text}${BRAND_CLOSE}`;
41
+ }
42
+
43
+ function headerLines(theme: Theme, width: number): string[] {
44
+ const weave = WEAVE_WORDMARK.map((line) => theme.bold(brand(line)));
45
+ if (width < 44) {
46
+ return ["", ...weave, theme.bold("LOOM"), theme.fg("dim", "Weave Router · Loom for Pi"), ""];
47
+ }
48
+ return [
49
+ "",
50
+ ...weave,
51
+ ...LOOM_WORDMARK.map((line) => theme.bold(line)),
52
+ theme.bold("Weave Router · Loom for Pi"),
53
+ "",
54
+ ];
55
+ }
56
+
57
+ export function installLoomUi(ctx: ExtensionContext): void {
58
+ if (!isTuiContext(ctx)) return;
59
+ ctx.ui.setTitle("Loom · Weave Router");
60
+ ctx.ui.setHeader((_tui: TUI, theme: Theme) => ({
61
+ invalidate() {},
62
+ render(width: number): string[] {
63
+ return headerLines(theme, width);
64
+ },
65
+ }));
66
+ ctx.ui.setWidget(WOOLY_WIDGET_KEY, (tui: TUI) => new WoolyComponent(tui), { placement: "belowEditor" });
67
+ }
68
+
69
+ export function clearLoomUi(ctx: ExtensionContext): void {
70
+ if (!ctx.hasUI) return;
71
+ ctx.ui.setStatus(STATUS_KEY, undefined);
72
+ if (isTuiContext(ctx)) {
73
+ ctx.ui.setWidget(WOOLY_WIDGET_KEY, undefined);
74
+ ctx.ui.setHeader(undefined);
75
+ }
76
+ }
77
+
78
+ export function updateRouterStatus(ctx: ExtensionContext, snapshot: RouterUiSnapshot): void {
79
+ if (!ctx.hasUI) return;
80
+ const { requestedModel, routedModel, forcedModel, savings } = snapshot;
81
+ let route: string;
82
+ if (routedModel && requestedModel) route = `${routedModel} ← ${requestedModel}`;
83
+ else if (routedModel) route = routedModel;
84
+ else if (requestedModel) route = `${requestedModel} · awaiting route`;
85
+ else route = "automatic routing";
86
+
87
+ const tui = isTuiContext(ctx);
88
+ const label = tui ? ctx.ui.theme.bold(brand("WEAVE ROUTER")) : "WEAVE ROUTER";
89
+ const detail = forcedModel ? `${forcedModel} [forced]` : `${route} · ${formatSavings(savings)}`;
90
+ ctx.ui.setStatus(STATUS_KEY, `${label} — ${tui ? ctx.ui.theme.fg("dim", detail) : detail}`);
91
+ }