@weave-os/router 0.2.19 → 0.2.20
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 +26 -18
- package/cc-statusline.sh +6 -1
- package/install.sh +314 -89
- package/opencode-weave/README.md +85 -13
- package/opencode-weave/package.json +4 -2
- package/opencode-weave/src/directives.ts +72 -0
- package/opencode-weave/src/index.ts +138 -28
- package/package.json +1 -1
- package/pi-router/README.md +69 -3
- package/pi-router/package.json +4 -4
- package/pi-router/src/compaction.ts +2 -2
- package/pi-router/src/escalation.ts +265 -0
- package/pi-router/src/index.ts +8 -4
- package/pi-router/src/ui.ts +14 -2
- package/uninstall.sh +147 -24
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { compact, VERSION, type ExtensionAPI, type ExtensionContext } from "@mariozechner/pi-coding-agent";
|
|
2
|
+
import { streamSimple } from "@mariozechner/pi-ai";
|
|
3
|
+
import { getRole, getRouterBaseUrl, isSubagent, PROVIDER_NAME, providerHeaders, resolveRouterKey, ROUTED_MODEL_HEADER } from "./config.js";
|
|
4
|
+
import { ROUTED_COMPACTION_CONTINUATION } from "./compaction.js";
|
|
5
|
+
|
|
6
|
+
type Complexity = "low" | "medium" | "high" | "maximum";
|
|
7
|
+
const COMPLEXITY_RANK: Record<Complexity, number> = { low: 0, medium: 1, high: 2, maximum: 3 };
|
|
8
|
+
// Below this, Pi's retained recent context can outweigh the history summarized.
|
|
9
|
+
const MIN_HANDOFF_TOKENS = 32_768;
|
|
10
|
+
const STATUS_KEY = "weave-handoff";
|
|
11
|
+
const ROUTE_ENTRY_TYPE = "weave-handoff-route";
|
|
12
|
+
const SESSION_ENTRY_TYPE = "weave-handoff-session";
|
|
13
|
+
|
|
14
|
+
interface RouteSelection {
|
|
15
|
+
token: string;
|
|
16
|
+
session_token: string;
|
|
17
|
+
summary_token?: string;
|
|
18
|
+
model: string;
|
|
19
|
+
provider: string;
|
|
20
|
+
complexity?: Complexity;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type PreparedRoute = RouteSelection | { bypass: true };
|
|
24
|
+
type HandoffStage = "waiting" | "compacting" | "ready";
|
|
25
|
+
|
|
26
|
+
interface PendingHandoff {
|
|
27
|
+
stage: HandoffStage;
|
|
28
|
+
route: RouteSelection;
|
|
29
|
+
sessionId: string;
|
|
30
|
+
modelId: string;
|
|
31
|
+
payload: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const HANDOFF_SUMMARY_INSTRUCTIONS = `Create a concise checkpoint for another model to continue this conversation. Do not execute tools or continue the task. Preserve the user's objective and constraints, decisions and reasoning, changed files and exact identifiers, test results, failures, unresolved questions, and remaining work. Distinguish verified facts from assumptions. Recent messages will also be retained; avoid repeating lengthy outputs. Return only the checkpoint, within 3000 tokens.`;
|
|
35
|
+
|
|
36
|
+
export function handoffSummaryPayload(original: Record<string, unknown>, generated: unknown, token: string, customInstructions?: string): Record<string, unknown> {
|
|
37
|
+
if (!Array.isArray(original.messages) || !isRecord(generated)) throw new Error("Invalid compaction payload");
|
|
38
|
+
return {
|
|
39
|
+
...original,
|
|
40
|
+
stream: generated.stream,
|
|
41
|
+
// Preserve the original system, tools, thinking settings and message
|
|
42
|
+
// prefix so the old model can reuse its cache when the provider permits.
|
|
43
|
+
messages: [...original.messages, { role: "user", content: HANDOFF_SUMMARY_INSTRUCTIONS + (customInstructions ? `\n\nAdditional focus: ${customInstructions}` : "") }],
|
|
44
|
+
weave_handoff: token,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
49
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function isComplexity(value: unknown): value is Complexity {
|
|
53
|
+
return typeof value === "string" && Object.hasOwn(COMPLEXITY_RANK, value);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function parsePreparedRoute(value: unknown): PreparedRoute {
|
|
57
|
+
if (!isRecord(value)) throw new Error("Invalid router handoff response");
|
|
58
|
+
if (value.bypass === true) return { bypass: true };
|
|
59
|
+
if (typeof value.token !== "string" || !value.token || typeof value.model !== "string" || !value.model ||
|
|
60
|
+
typeof value.session_token !== "string" || !value.session_token ||
|
|
61
|
+
typeof value.provider !== "string" || !value.provider ||
|
|
62
|
+
(value.summary_token !== undefined && typeof value.summary_token !== "string")) {
|
|
63
|
+
throw new Error("Invalid router handoff selection");
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
token: value.token, session_token: value.session_token, model: value.model, provider: value.provider,
|
|
67
|
+
summary_token: value.summary_token as string | undefined,
|
|
68
|
+
complexity: isComplexity(value.complexity) ? value.complexity : undefined,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function needsEscalationCompaction(previous: Pick<RouteSelection, "model" | "complexity"> | undefined, next: RouteSelection, tokens: number): boolean {
|
|
73
|
+
return previous?.complexity !== undefined && next.complexity !== undefined &&
|
|
74
|
+
previous.model !== next.model && COMPLEXITY_RANK[next.complexity] > COMPLEXITY_RANK[previous.complexity] &&
|
|
75
|
+
tokens >= MIN_HANDOFF_TOKENS && !!next.summary_token;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function registerEscalationCompaction(
|
|
79
|
+
pi: ExtensionAPI,
|
|
80
|
+
request: typeof fetch = fetch,
|
|
81
|
+
version: string = VERSION,
|
|
82
|
+
): () => boolean {
|
|
83
|
+
const [major, minor] = version.split(".").map(Number);
|
|
84
|
+
if (major === 0 && minor < 83) {
|
|
85
|
+
pi.on("session_start", (_event, ctx) => {
|
|
86
|
+
if (process.env.WEAVE_PI_ESCALATION_COMPACTION === "0") return;
|
|
87
|
+
const message = "Weave escalation compaction requires Pi 0.83 or newer. Upgrade Pi to enable it; routing will continue without escalation compaction.";
|
|
88
|
+
if (ctx.hasUI) ctx.ui.notify(message, "warning");
|
|
89
|
+
else process.stderr.write(`${message}\n`);
|
|
90
|
+
});
|
|
91
|
+
return () => false;
|
|
92
|
+
}
|
|
93
|
+
let pending: PendingHandoff | undefined;
|
|
94
|
+
let sessionToken: string | undefined;
|
|
95
|
+
let previous: Pick<RouteSelection, "model" | "complexity"> | undefined;
|
|
96
|
+
let dispatched: RouteSelection | undefined;
|
|
97
|
+
let generation = 0;
|
|
98
|
+
let finishContinuation: (() => void) | undefined;
|
|
99
|
+
|
|
100
|
+
const clear = () => {
|
|
101
|
+
generation++;
|
|
102
|
+
pending = undefined;
|
|
103
|
+
dispatched = undefined;
|
|
104
|
+
previous = undefined;
|
|
105
|
+
finishContinuation?.();
|
|
106
|
+
finishContinuation = undefined;
|
|
107
|
+
};
|
|
108
|
+
pi.on("session_shutdown", clear);
|
|
109
|
+
pi.on("model_select", clear);
|
|
110
|
+
const restore = (_event: unknown, ctx: ExtensionContext) => {
|
|
111
|
+
clear();
|
|
112
|
+
sessionToken = undefined;
|
|
113
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
114
|
+
if (entry.type === "custom" && entry.customType === SESSION_ENTRY_TYPE && isRecord(entry.data) &&
|
|
115
|
+
entry.data.sessionId === ctx.sessionManager.getSessionId() && typeof entry.data.token === "string") {
|
|
116
|
+
sessionToken = entry.data.token;
|
|
117
|
+
}
|
|
118
|
+
if (entry.type !== "custom" || entry.customType !== ROUTE_ENTRY_TYPE) continue;
|
|
119
|
+
previous = undefined;
|
|
120
|
+
if (isRecord(entry.data) &&
|
|
121
|
+
typeof entry.data.model === "string" && isComplexity(entry.data.complexity)) {
|
|
122
|
+
previous = { model: entry.data.model, complexity: entry.data.complexity };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
pi.on("session_start", restore);
|
|
127
|
+
pi.on("session_tree", restore);
|
|
128
|
+
pi.on("input", (event) => {
|
|
129
|
+
if (event.source !== "extension") {
|
|
130
|
+
generation++;
|
|
131
|
+
pending = undefined;
|
|
132
|
+
dispatched = undefined;
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
const fail = (ctx: ExtensionContext, error: unknown) => {
|
|
137
|
+
pending = undefined;
|
|
138
|
+
dispatched = undefined;
|
|
139
|
+
const message = `Weave handoff failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
140
|
+
if (ctx.hasUI) ctx.ui.notify(message, "error");
|
|
141
|
+
else process.stderr.write(`${message}\n`);
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
pi.on("before_provider_request", async (event, ctx) => {
|
|
145
|
+
if (process.env.WEAVE_PI_ESCALATION_COMPACTION === "0" || isSubagent() || ctx.model?.provider !== PROVIDER_NAME) return;
|
|
146
|
+
if (!isRecord(event.payload)) return;
|
|
147
|
+
let payload = sessionToken ? { ...event.payload, weave_session: sessionToken } : event.payload;
|
|
148
|
+
const requestGeneration = generation;
|
|
149
|
+
try {
|
|
150
|
+
if (pending?.stage === "ready") {
|
|
151
|
+
if (pending.sessionId !== ctx.sessionManager.getSessionId() || pending.modelId !== ctx.model.id) {
|
|
152
|
+
throw new Error("Session changed during compaction");
|
|
153
|
+
}
|
|
154
|
+
dispatched = pending.route;
|
|
155
|
+
pending = undefined;
|
|
156
|
+
return { ...payload, weave_handoff: dispatched.token };
|
|
157
|
+
}
|
|
158
|
+
if (pending) throw new Error("A compaction handoff is already in progress");
|
|
159
|
+
const key = resolveRouterKey();
|
|
160
|
+
if (!key) throw new Error("Router key is missing");
|
|
161
|
+
const signals = [AbortSignal.timeout(30_000)];
|
|
162
|
+
if (ctx.signal) signals.push(ctx.signal);
|
|
163
|
+
const response = await request(`${getRouterBaseUrl()}/v1/route/handoff`, {
|
|
164
|
+
method: "POST",
|
|
165
|
+
headers: { ...providerHeaders(getRole(), key), "content-type": "application/json" },
|
|
166
|
+
body: JSON.stringify(payload), signal: AbortSignal.any(signals),
|
|
167
|
+
});
|
|
168
|
+
if (!response.ok) throw new Error(`Route preparation returned HTTP ${response.status}; the router must support Pi handoffs`);
|
|
169
|
+
const prepared = parsePreparedRoute(await response.json());
|
|
170
|
+
if (requestGeneration !== generation || ctx.signal?.aborted) {
|
|
171
|
+
ctx.abort();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if ("bypass" in prepared) {
|
|
175
|
+
dispatched = undefined;
|
|
176
|
+
previous = undefined;
|
|
177
|
+
pi.appendEntry(ROUTE_ENTRY_TYPE, {});
|
|
178
|
+
return payload;
|
|
179
|
+
}
|
|
180
|
+
if (sessionToken !== prepared.session_token) {
|
|
181
|
+
sessionToken = prepared.session_token;
|
|
182
|
+
pi.appendEntry(SESSION_ENTRY_TYPE, { sessionId: ctx.sessionManager.getSessionId(), token: sessionToken });
|
|
183
|
+
}
|
|
184
|
+
payload = { ...payload, weave_session: sessionToken };
|
|
185
|
+
if (!needsEscalationCompaction(previous, prepared, ctx.getContextUsage()?.tokens ?? 0)) {
|
|
186
|
+
dispatched = prepared;
|
|
187
|
+
return { ...payload, weave_handoff: prepared.token };
|
|
188
|
+
}
|
|
189
|
+
pending = { stage: "waiting", route: prepared, sessionId: ctx.sessionManager.getSessionId(), modelId: ctx.model.id, payload: structuredClone(payload) };
|
|
190
|
+
// Awaiting compact/abort here deadlocks the active provider request. The
|
|
191
|
+
// aborted signal prevents dispatch; agent_settled owns compaction.
|
|
192
|
+
ctx.abort();
|
|
193
|
+
} catch (error) {
|
|
194
|
+
ctx.abort();
|
|
195
|
+
if (requestGeneration === generation) fail(ctx, error);
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
pi.on("after_provider_response", (event) => {
|
|
200
|
+
if (event.status >= 200 && event.status < 300 && dispatched) {
|
|
201
|
+
previous = event.headers[ROUTED_MODEL_HEADER] === dispatched.model ? dispatched : undefined;
|
|
202
|
+
pi.appendEntry(ROUTE_ENTRY_TYPE, previous ? { model: previous.model, complexity: previous.complexity } : {});
|
|
203
|
+
}
|
|
204
|
+
dispatched = undefined;
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
pi.on("agent_settled", async (_event, ctx) => {
|
|
208
|
+
if (pending?.stage !== "waiting") {
|
|
209
|
+
finishContinuation?.();
|
|
210
|
+
finishContinuation = undefined;
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const handoff = pending;
|
|
214
|
+
handoff.stage = "compacting";
|
|
215
|
+
// Pi is idle at agent_settled, so compact() can safely wait for abort.
|
|
216
|
+
// Keep this event pending through the continuation so print mode cannot
|
|
217
|
+
// dispose the runtime between the aborted request and its replacement.
|
|
218
|
+
await new Promise<void>((resolve) => {
|
|
219
|
+
if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, `compacting before handoff to ${handoff.route.model}...`);
|
|
220
|
+
ctx.compact({
|
|
221
|
+
onComplete: () => {
|
|
222
|
+
if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
223
|
+
if (pending !== handoff) { resolve(); return; }
|
|
224
|
+
handoff.stage = "ready";
|
|
225
|
+
finishContinuation = resolve;
|
|
226
|
+
pi.sendUserMessage(ROUTED_COMPACTION_CONTINUATION, ctx.isIdle() ? undefined : { deliverAs: "followUp" });
|
|
227
|
+
},
|
|
228
|
+
onError: (error) => {
|
|
229
|
+
if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
230
|
+
if (pending === handoff) fail(ctx, error);
|
|
231
|
+
resolve();
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
pi.on("session_before_compact", async (event, ctx) => {
|
|
238
|
+
// Let the pending handoff run at agent_settled rather than racing Pi's
|
|
239
|
+
// threshold compaction between agent_end and the settled event.
|
|
240
|
+
if (pending?.stage === "waiting") return { cancel: true };
|
|
241
|
+
if (pending?.stage !== "compacting") return;
|
|
242
|
+
const handoff = pending;
|
|
243
|
+
const key = resolveRouterKey();
|
|
244
|
+
if (!ctx.model || !key) return { cancel: true };
|
|
245
|
+
try {
|
|
246
|
+
const summary = await compact(
|
|
247
|
+
event.preparation, ctx.model, key, providerHeaders(getRole(), key), event.customInstructions, event.signal,
|
|
248
|
+
undefined,
|
|
249
|
+
(model, context, options) => streamSimple(model, context, {
|
|
250
|
+
...options,
|
|
251
|
+
onPayload: (payload) => handoffSummaryPayload(handoff.payload, payload, handoff.route.summary_token!, event.customInstructions),
|
|
252
|
+
}),
|
|
253
|
+
);
|
|
254
|
+
if (!summary.summary.trim()) throw new Error("The previous model returned an empty compaction summary");
|
|
255
|
+
if (pending !== handoff || event.signal.aborted) return { cancel: true };
|
|
256
|
+
return { compaction: summary };
|
|
257
|
+
} catch (error) {
|
|
258
|
+
// Pi catches extension errors and otherwise proceeds with its default
|
|
259
|
+
// summarizer. Explicit cancellation prevents a second paid summary.
|
|
260
|
+
if (pending === handoff) fail(ctx, error);
|
|
261
|
+
return { cancel: true };
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
return () => pending !== undefined;
|
|
265
|
+
}
|
package/pi-router/src/index.ts
CHANGED
|
@@ -1,15 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @weave-os/router — route the pi coding agent through the Weave Router.
|
|
3
3
|
*
|
|
4
|
-
* Wiring
|
|
5
|
-
* the installer):
|
|
4
|
+
* Wiring:
|
|
6
5
|
* - provider: register `weave` with per-process knob headers (quality on
|
|
7
6
|
* the main loop, speed/cheap in subagents).
|
|
8
7
|
* - metadata: stamp body.metadata.user_id for sticky sessions + subagent
|
|
9
8
|
* detection.
|
|
10
9
|
* - Loom UI: branded header, Wooly animation, actual route, and saved $.
|
|
11
10
|
* - safety: block catastrophic bash (unless WEAVE_NO_SAFETY=1).
|
|
12
|
-
* - compaction: protect long tool loops
|
|
11
|
+
* - compaction: protect long tool loops and compact before model escalation.
|
|
13
12
|
* - dispatch: parallel, context-isolated subagents — top-level process
|
|
14
13
|
* only (no grandchildren).
|
|
15
14
|
* - lsp: code intelligence (definition/references/hover/symbols/
|
|
@@ -25,6 +24,7 @@ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
|
25
24
|
import { registerBetaCommand } from "./beta.js";
|
|
26
25
|
import { isSubagent } from "./config.js";
|
|
27
26
|
import { registerCompaction } from "./compaction.js";
|
|
27
|
+
import { registerEscalationCompaction } from "./escalation.js";
|
|
28
28
|
import { registerDispatch } from "./dispatch.js";
|
|
29
29
|
import { registerForceModelCommands } from "./force-model.js";
|
|
30
30
|
import { registerLsp } from "./lsp.js";
|
|
@@ -32,6 +32,7 @@ import { registerMetadata } from "./metadata.js";
|
|
|
32
32
|
import { registerRoutedModel } from "./routed-model.js";
|
|
33
33
|
import { registerSafety } from "./safety.js";
|
|
34
34
|
import { registerWeave } from "./provider.js";
|
|
35
|
+
import { registerWooly } from "./ui.js";
|
|
35
36
|
|
|
36
37
|
const SELF_PATH = fileURLToPath(import.meta.url);
|
|
37
38
|
|
|
@@ -46,7 +47,10 @@ export default function (pi: ExtensionAPI): void {
|
|
|
46
47
|
registerBetaCommand(pi);
|
|
47
48
|
registerForceModelCommands(pi);
|
|
48
49
|
registerRoutedModel(pi);
|
|
49
|
-
|
|
50
|
+
if (!isSubagent()) registerWooly(pi);
|
|
51
|
+
let handoffPending = () => false;
|
|
52
|
+
registerCompaction(pi, undefined, () => handoffPending());
|
|
53
|
+
handoffPending = registerEscalationCompaction(pi);
|
|
50
54
|
|
|
51
55
|
if (process.env.WEAVE_NO_SAFETY !== "1") registerSafety(pi);
|
|
52
56
|
|
package/pi-router/src/ui.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ExtensionContext, Theme } from "@mariozechner/pi-coding-agent";
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext, Theme } from "@mariozechner/pi-coding-agent";
|
|
2
2
|
import type { TUI } from "@mariozechner/pi-tui";
|
|
3
3
|
import type { SavingsAggregate } from "./savings.js";
|
|
4
4
|
import { formatSavings } from "./savings.js";
|
|
@@ -63,7 +63,19 @@ export function installLoomUi(ctx: ExtensionContext): void {
|
|
|
63
63
|
return headerLines(theme, width);
|
|
64
64
|
},
|
|
65
65
|
}));
|
|
66
|
-
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function registerWooly(pi: ExtensionAPI): void {
|
|
69
|
+
let visible = false;
|
|
70
|
+
pi.registerCommand("wooly", {
|
|
71
|
+
description: "Show or hide Wooly for this session",
|
|
72
|
+
handler: async (_args, ctx) => {
|
|
73
|
+
if (!isTuiContext(ctx)) return;
|
|
74
|
+
visible = !visible;
|
|
75
|
+
ctx.ui.setWidget(WOOLY_WIDGET_KEY, visible ? (tui: TUI) => new WoolyComponent(tui) : undefined, { placement: "belowEditor" });
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
pi.on("session_shutdown", () => { visible = false; });
|
|
67
79
|
}
|
|
68
80
|
|
|
69
81
|
export function clearLoomUi(ctx: ExtensionContext): void {
|
package/uninstall.sh
CHANGED
|
@@ -27,6 +27,10 @@ set -euo pipefail
|
|
|
27
27
|
scope="user"
|
|
28
28
|
scope_explicit="false"
|
|
29
29
|
install_dir=""
|
|
30
|
+
script_dir=""
|
|
31
|
+
if [ -n "${BASH_SOURCE[0]:-}" ]; then
|
|
32
|
+
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd -P)" || script_dir=""
|
|
33
|
+
fi
|
|
30
34
|
|
|
31
35
|
# ---------- directive registry (embedded) ----------
|
|
32
36
|
#
|
|
@@ -141,6 +145,8 @@ EOF
|
|
|
141
145
|
|
|
142
146
|
target="claude"
|
|
143
147
|
|
|
148
|
+
CLAUDE_STATUSLINE_MARKER="# Claude Code statusline for the Weave Router."
|
|
149
|
+
|
|
144
150
|
err() { printf "\033[31merror:\033[0m %s\n" "$*" >&2; }
|
|
145
151
|
warn() { printf "\033[33mwarning:\033[0m %s\n" "$*" >&2; }
|
|
146
152
|
info() { printf "\033[36m==>\033[0m %s\n" "$*"; }
|
|
@@ -158,6 +164,64 @@ refuse_if_symlink() {
|
|
|
158
164
|
fi
|
|
159
165
|
}
|
|
160
166
|
|
|
167
|
+
# weave_command_router_owned accepts legacy marker-bearing wrappers and
|
|
168
|
+
# markerless wrappers written by current installers. Current wrappers carry a
|
|
169
|
+
# body copy in a sidecar so ownership survives standalone and piped uninstall.
|
|
170
|
+
weave_command_router_owned() {
|
|
171
|
+
local command_file="$1" command_name="$2" ownership_file ownership_header ownership_body
|
|
172
|
+
local source_file expected scope_args="" candidate
|
|
173
|
+
if grep -Fq "<!-- weave-router managed command: $command_name -->" "$command_file" 2>/dev/null; then
|
|
174
|
+
return 0
|
|
175
|
+
fi
|
|
176
|
+
|
|
177
|
+
ownership_file="$command_file.weave-router"
|
|
178
|
+
if [ -f "$ownership_file" ]; then
|
|
179
|
+
ownership_header="$(sed -n '1p' "$ownership_file" 2>/dev/null || true)"
|
|
180
|
+
ownership_body="$(sed '1d' "$ownership_file" 2>/dev/null || true)"
|
|
181
|
+
if [ "$ownership_header" = "weave-router managed command: $command_name" ] \
|
|
182
|
+
&& [ "$(cat "$command_file")" = "$ownership_body" ]; then
|
|
183
|
+
return 0
|
|
184
|
+
fi
|
|
185
|
+
fi
|
|
186
|
+
|
|
187
|
+
if [ -n "$install_dir" ]; then
|
|
188
|
+
scope_args=" --dir $(printf '%q' "$install_dir")"
|
|
189
|
+
elif [ "$scope" = "project" ]; then
|
|
190
|
+
scope_args=" --scope project"
|
|
191
|
+
fi
|
|
192
|
+
|
|
193
|
+
for candidate in \
|
|
194
|
+
"$script_dir/commands" \
|
|
195
|
+
"$script_dir/../commands"
|
|
196
|
+
do
|
|
197
|
+
source_file="$candidate/$command_name.md"
|
|
198
|
+
[ -f "$source_file" ] || continue
|
|
199
|
+
expected="$(cat "$source_file")"
|
|
200
|
+
expected="${expected//\{\{SCOPE\}\}/$scope_args}"
|
|
201
|
+
[ "$(cat "$command_file")" = "$expected" ] && return 0
|
|
202
|
+
done
|
|
203
|
+
return 1
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
# claude_statusline_router_owned reports whether a settings entry points at the
|
|
207
|
+
# router's statusline. Existing scripts prove ownership with the marker; when a
|
|
208
|
+
# script is missing, the adjacent ownership marker proves that the router wrote
|
|
209
|
+
# it and should remove it with the rest of the router config.
|
|
210
|
+
claude_statusline_router_owned() {
|
|
211
|
+
local settings_path="$1" expected_command="$2" script_path="$3" ownership_marker_path="$4" configured_command
|
|
212
|
+
[ -f "$settings_path" ] || return 1
|
|
213
|
+
configured_command="$(jq -r '.statusLine.command // empty' "$settings_path" 2>/dev/null || true)"
|
|
214
|
+
[ "$configured_command" = "$expected_command" ] || return 1
|
|
215
|
+
if [ -f "$script_path" ]; then
|
|
216
|
+
if grep -Fq "$CLAUDE_STATUSLINE_MARKER" "$script_path" 2>/dev/null; then
|
|
217
|
+
return 0
|
|
218
|
+
fi
|
|
219
|
+
[ -r "$script_path" ] && return 1
|
|
220
|
+
fi
|
|
221
|
+
[ -f "$ownership_marker_path" ] \
|
|
222
|
+
&& grep -Fq "$CLAUDE_STATUSLINE_MARKER" "$ownership_marker_path"
|
|
223
|
+
}
|
|
224
|
+
|
|
161
225
|
while [ $# -gt 0 ]; do
|
|
162
226
|
case "$1" in
|
|
163
227
|
--scope)
|
|
@@ -424,7 +488,13 @@ if [ "$target" = "opencode" ]; then
|
|
|
424
488
|
refuse_if_symlink "$opencode_dir"
|
|
425
489
|
fi
|
|
426
490
|
opencode_config_file="$opencode_dir/opencode.json"
|
|
491
|
+
opencode_parked="$opencode_dir/.weave-parked.json"
|
|
492
|
+
opencode_direct_model=""
|
|
427
493
|
refuse_if_symlink "$opencode_config_file"
|
|
494
|
+
if [ -f "$opencode_parked" ]; then
|
|
495
|
+
refuse_if_symlink "$opencode_parked"
|
|
496
|
+
opencode_direct_model="$(jq -r '.direct_model // empty' "$opencode_parked" 2>/dev/null || true)"
|
|
497
|
+
fi
|
|
428
498
|
|
|
429
499
|
# Canonicalize the plugin path exactly as install.sh did (`cd … && pwd`) so
|
|
430
500
|
# the `plugin` array entry matches on removal — a raw "$opencode_dir/…" string
|
|
@@ -437,19 +507,19 @@ if [ "$target" = "opencode" ]; then
|
|
|
437
507
|
if [ -f "$opencode_config_file" ]; then
|
|
438
508
|
# Strip every managed provider (`weave`, the login-only `weave-claude`, and
|
|
439
509
|
# the legacy `weave-codex` from pre-upgrade installs), the managed plugin
|
|
440
|
-
# entry from the `plugin` array, and
|
|
441
|
-
#
|
|
442
|
-
#
|
|
443
|
-
|
|
444
|
-
# unrelated keys are preserved.
|
|
445
|
-
cleaned="$(jq --arg plugin "$opencode_plugin" '
|
|
510
|
+
# entry from the `plugin` array, and restore the direct model parked during
|
|
511
|
+
# install. Other providers, direct models selected while routing was off,
|
|
512
|
+
# other plugins, and unrelated keys are preserved.
|
|
513
|
+
cleaned="$(jq --arg plugin "$opencode_plugin" --arg direct_model "$opencode_direct_model" '
|
|
446
514
|
(if .provider.weave then del(.provider.weave) else . end)
|
|
447
515
|
| (if .provider["weave-claude"] then del(.provider["weave-claude"]) else . end)
|
|
448
516
|
| (if .provider["weave-codex"] then del(.provider["weave-codex"]) else . end)
|
|
449
517
|
| (if (.provider // {}) == {} then del(.provider) else . end)
|
|
450
518
|
| (if (.plugin | type) == "array" then .plugin -= [$plugin] else . end)
|
|
451
519
|
| (if (.plugin | type) == "array" and (.plugin | length) == 0 then del(.plugin) else . end)
|
|
452
|
-
| (if (.model // "" | tostring | (startswith("weave/") or startswith("weave-claude/") or startswith("weave-codex/")))
|
|
520
|
+
| (if (.model // "" | tostring | (startswith("weave/") or startswith("weave-claude/") or startswith("weave-codex/")))
|
|
521
|
+
then (if $direct_model != "" then .model = $direct_model else del(.model) end)
|
|
522
|
+
else . end)
|
|
453
523
|
' "$opencode_config_file")"
|
|
454
524
|
printf '%s\n' "$cleaned" >"$opencode_config_file"
|
|
455
525
|
|
|
@@ -472,22 +542,24 @@ if [ "$target" = "opencode" ]; then
|
|
|
472
542
|
if [ -f "$opencode_plugin" ]; then
|
|
473
543
|
refuse_if_symlink "$opencode_plugin"
|
|
474
544
|
rm -f "$opencode_plugin"
|
|
545
|
+
opencode_directives="$(dirname "$opencode_plugin")/directives.ts"
|
|
546
|
+
if [ -f "$opencode_directives" ]; then
|
|
547
|
+
refuse_if_symlink "$opencode_directives"
|
|
548
|
+
rm -f "$opencode_directives"
|
|
549
|
+
fi
|
|
475
550
|
rmdir "$opencode_dir/.weave" 2>/dev/null || true
|
|
476
551
|
ok "Removed $opencode_plugin"
|
|
477
552
|
fi
|
|
478
553
|
|
|
479
|
-
# Drop the toggle parked sidecar
|
|
480
|
-
opencode_parked="$opencode_dir/.weave-parked.json"
|
|
554
|
+
# Drop the toggle parked sidecar after its prior model has been restored.
|
|
481
555
|
if [ -f "$opencode_parked" ]; then
|
|
482
556
|
refuse_if_symlink "$opencode_parked"
|
|
483
557
|
rm -f "$opencode_parked"
|
|
484
558
|
ok "Removed $opencode_parked"
|
|
485
559
|
fi
|
|
486
560
|
|
|
487
|
-
# Remove slash command wrapper files this installer owns.
|
|
488
|
-
#
|
|
489
|
-
# scope—including a user-style --dir install—uses the global XDG commands
|
|
490
|
-
# directory so opencode discovers the wrappers from any working directory.
|
|
561
|
+
# Remove slash command wrapper files this installer owns. Project and --dir
|
|
562
|
+
# installs keep commands beside their config; user scope uses global XDG.
|
|
491
563
|
remove_opencode_command_dir() {
|
|
492
564
|
local opencode_cmds_dir="$1" cmd cmd_file
|
|
493
565
|
if [ -d "$opencode_cmds_dir" ]; then
|
|
@@ -495,9 +567,10 @@ if [ "$target" = "opencode" ]; then
|
|
|
495
567
|
while IFS= read -r cmd; do
|
|
496
568
|
cmd_file="$opencode_cmds_dir/$cmd.md"
|
|
497
569
|
if [ -f "$cmd_file" ]; then
|
|
498
|
-
if
|
|
570
|
+
if weave_command_router_owned "$cmd_file" "$cmd"; then
|
|
499
571
|
refuse_if_symlink "$cmd_file"
|
|
500
|
-
|
|
572
|
+
refuse_if_symlink "$cmd_file.weave-router"
|
|
573
|
+
rm -f "$cmd_file" "$cmd_file.weave-router"
|
|
501
574
|
ok "Removed $cmd_file"
|
|
502
575
|
else
|
|
503
576
|
warn "Leaving user-owned opencode command at $cmd_file untouched."
|
|
@@ -510,7 +583,7 @@ EOF
|
|
|
510
583
|
fi
|
|
511
584
|
}
|
|
512
585
|
|
|
513
|
-
if [ "$scope" = "project" ]; then
|
|
586
|
+
if [ "$scope" = "project" ] || [ -n "$install_dir" ]; then
|
|
514
587
|
opencode_commands_dir="$opencode_dir/.opencode/commands"
|
|
515
588
|
else
|
|
516
589
|
opencode_commands_dir="${XDG_CONFIG_HOME:-$HOME/.config}/opencode/commands"
|
|
@@ -826,19 +899,25 @@ if [ -n "$install_dir" ]; then
|
|
|
826
899
|
# uses .claude/. Match the installer's scope-dependent statusline placement.
|
|
827
900
|
if [ "$scope" = "project" ]; then
|
|
828
901
|
statusline_file="$install_dir/.claude/cc-statusline.sh"
|
|
902
|
+
statusline_command="$statusline_file"
|
|
829
903
|
else
|
|
830
904
|
statusline_file="$install_dir/.weave/cc-statusline.sh"
|
|
905
|
+
statusline_command="$statusline_file"
|
|
831
906
|
fi
|
|
907
|
+
statusline_ownership_file="$statusline_file.weave-router"
|
|
832
908
|
# Symlink containment: --dir paths come from a user-supplied directory that may
|
|
833
909
|
# be hostile. The later `>` redirect on settings_file and `rm -f` on the
|
|
834
910
|
# statusline script would otherwise follow links out of the directory.
|
|
835
911
|
refuse_if_symlink "$install_dir/.claude"
|
|
836
912
|
refuse_if_symlink "$settings_file"
|
|
837
913
|
refuse_if_symlink "$statusline_file"
|
|
914
|
+
refuse_if_symlink "$statusline_ownership_file"
|
|
838
915
|
elif [ "$scope" = "user" ]; then
|
|
839
916
|
settings_file="$HOME/.claude/settings.json"
|
|
840
917
|
local_settings_file=""
|
|
841
918
|
statusline_file="$HOME/.weave/cc-statusline.sh"
|
|
919
|
+
statusline_command="$statusline_file"
|
|
920
|
+
statusline_ownership_file="$statusline_file.weave-router"
|
|
842
921
|
else
|
|
843
922
|
# Project scope without --dir: mirror install.sh — directory prompt only when
|
|
844
923
|
# scope_explicit is false (interactive install path); explicit --scope project
|
|
@@ -874,6 +953,8 @@ else
|
|
|
874
953
|
settings_file="$settings_base/.claude/settings.json"
|
|
875
954
|
local_settings_file="$settings_base/.claude/settings.local.json"
|
|
876
955
|
statusline_file="$settings_base/.claude/cc-statusline.sh"
|
|
956
|
+
statusline_command="\${CLAUDE_PROJECT_DIR}/.claude/cc-statusline.sh"
|
|
957
|
+
statusline_ownership_file="$statusline_file.weave-router"
|
|
877
958
|
# Symlink containment: paths come from a git repo or user-supplied directory
|
|
878
959
|
# that may be hostile. The later `>` redirect on settings_file and `rm -f` on
|
|
879
960
|
# the scripts would otherwise follow links out of the repo.
|
|
@@ -881,6 +962,34 @@ else
|
|
|
881
962
|
refuse_if_symlink "$settings_file"
|
|
882
963
|
refuse_if_symlink "$local_settings_file"
|
|
883
964
|
refuse_if_symlink "$statusline_file"
|
|
965
|
+
refuse_if_symlink "$statusline_ownership_file"
|
|
966
|
+
fi
|
|
967
|
+
|
|
968
|
+
statusline_file_owned="false"
|
|
969
|
+
statusline_setting_owned="false"
|
|
970
|
+
context_state_file="$(dirname "$settings_file")/.weave-context-window.json"
|
|
971
|
+
if [ -f "$context_state_file" ]; then
|
|
972
|
+
refuse_if_symlink "$context_state_file"
|
|
973
|
+
context_settings_file="${local_settings_file:-$settings_file}"
|
|
974
|
+
if [ -f "$context_settings_file" ]; then
|
|
975
|
+
cleaned="$(jq --slurpfile state "$context_state_file" '
|
|
976
|
+
$state[0] as $s |
|
|
977
|
+
if .model == $s.managed then
|
|
978
|
+
if $s.had_model then .model = $s.original else del(.model) end
|
|
979
|
+
else . end
|
|
980
|
+
' "$context_settings_file")"
|
|
981
|
+
printf '%s\n' "$cleaned" >"$context_settings_file"
|
|
982
|
+
fi
|
|
983
|
+
rm -f "$context_state_file"
|
|
984
|
+
ok "Restored the previous Claude Code model setting (or kept a newer user selection)."
|
|
985
|
+
fi
|
|
986
|
+
if [ -f "$statusline_file" ] && grep -Fq "$CLAUDE_STATUSLINE_MARKER" "$statusline_file"; then
|
|
987
|
+
statusline_file_owned="true"
|
|
988
|
+
fi
|
|
989
|
+
if claude_statusline_router_owned \
|
|
990
|
+
"$settings_file" "$statusline_command" "$statusline_file" "$statusline_ownership_file"; then
|
|
991
|
+
statusline_setting_owned="true"
|
|
992
|
+
statusline_file_owned="true"
|
|
884
993
|
fi
|
|
885
994
|
|
|
886
995
|
if [ -f "$settings_file" ]; then
|
|
@@ -888,13 +997,12 @@ if [ -f "$settings_file" ]; then
|
|
|
888
997
|
# delete `statusLine` / `apiKeyHelper` when they point at scripts this
|
|
889
998
|
# installer used in older versions. Otherwise an unrelated user-configured
|
|
890
999
|
# statusLine or apiKeyHelper would be silently clobbered.
|
|
891
|
-
cleaned="$(jq '
|
|
1000
|
+
cleaned="$(jq --arg statusline_setting_owned "$statusline_setting_owned" '
|
|
892
1001
|
if .env then
|
|
893
1002
|
.env |= (del(.ANTHROPIC_BASE_URL, .ANTHROPIC_AUTH_TOKEN, .ANTHROPIC_CUSTOM_HEADERS, .ENABLE_TOOL_SEARCH))
|
|
894
1003
|
| (if (.env | length) == 0 then del(.env) else . end)
|
|
895
1004
|
else . end
|
|
896
|
-
| (if
|
|
897
|
-
then del(.statusLine) else . end)
|
|
1005
|
+
| (if $statusline_setting_owned == "true" then del(.statusLine) else . end)
|
|
898
1006
|
| (if (.apiKeyHelper // "" | tostring | endswith("weave-key.sh"))
|
|
899
1007
|
then del(.apiKeyHelper) else . end)
|
|
900
1008
|
| (if ((.attribution.commit == "Co-Authored-By: Weave Router <router@workweave.ai>"
|
|
@@ -932,9 +1040,23 @@ if [ -f "$parked_file" ]; then
|
|
|
932
1040
|
ok "Removed $parked_file"
|
|
933
1041
|
fi
|
|
934
1042
|
|
|
935
|
-
if [
|
|
936
|
-
|
|
937
|
-
|
|
1043
|
+
if [ "$statusline_file_owned" = "true" ]; then
|
|
1044
|
+
# The installer now leaves an existing statusline alone. A user may already
|
|
1045
|
+
# have a script at the router's conventional filename, so remove this file
|
|
1046
|
+
# only when its content or ownership marker identifies it as our managed
|
|
1047
|
+
# statusline. The marker must also be removed when the script is already
|
|
1048
|
+
# missing; otherwise a later install could mistake the stale marker for
|
|
1049
|
+
# ownership and overwrite a user-owned statusline.
|
|
1050
|
+
if [ -f "$statusline_file" ]; then
|
|
1051
|
+
rm -f "$statusline_file"
|
|
1052
|
+
ok "Removed $statusline_file"
|
|
1053
|
+
fi
|
|
1054
|
+
if [ -f "$statusline_ownership_file" ]; then
|
|
1055
|
+
rm -f "$statusline_ownership_file"
|
|
1056
|
+
ok "Removed $statusline_ownership_file"
|
|
1057
|
+
fi
|
|
1058
|
+
elif [ -f "$statusline_file" ]; then
|
|
1059
|
+
warn "Leaving user-owned statusline at $statusline_file untouched."
|
|
938
1060
|
fi
|
|
939
1061
|
|
|
940
1062
|
# Remove only the slash command files this installer owns; leave any other
|
|
@@ -947,8 +1069,9 @@ if [ -d "$commands_dir" ]; then
|
|
|
947
1069
|
cmd_file="$commands_dir/$cmd.md"
|
|
948
1070
|
if [ -f "$cmd_file" ]; then
|
|
949
1071
|
refuse_if_symlink "$cmd_file"
|
|
950
|
-
if
|
|
951
|
-
|
|
1072
|
+
if weave_command_router_owned "$cmd_file" "$cmd"; then
|
|
1073
|
+
refuse_if_symlink "$cmd_file.weave-router"
|
|
1074
|
+
rm -f "$cmd_file" "$cmd_file.weave-router"
|
|
952
1075
|
ok "Removed $cmd_file"
|
|
953
1076
|
else
|
|
954
1077
|
warn "Leaving user-owned Claude command at $cmd_file untouched."
|