github-router 0.3.339 → 0.3.340
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/dist/aic-statusline-settings-Chf-IT45.js +137 -0
- package/dist/aic-statusline-settings-Chf-IT45.js.map +1 -0
- package/dist/{attribution-settings-DpDZcVka.js → attribution-settings-BTfKm-RU.js} +4 -4
- package/dist/{attribution-settings-DpDZcVka.js.map → attribution-settings-BTfKm-RU.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{claude-D0SUYfyr.js → claude-DUpp7B4X.js} +11 -141
- package/dist/claude-DUpp7B4X.js.map +1 -0
- package/dist/{codex-CzV-I2h3.js → codex-Xn1xsoOw.js} +4 -4
- package/dist/{codex-CzV-I2h3.js.map → codex-Xn1xsoOw.js.map} +1 -1
- package/dist/engine-DvGukHty.js +2 -0
- package/dist/{gate-discovery-BKjq0x66.js → gate-discovery-BIBgN6mA.js} +2 -2
- package/dist/{gate-discovery-BKjq0x66.js.map → gate-discovery-BIBgN6mA.js.map} +1 -1
- package/dist/{internal-stop-hook-DV7o7chW.js → internal-stop-hook-Dyn0fRpZ.js} +2 -2
- package/dist/{internal-stop-hook-DV7o7chW.js.map → internal-stop-hook-Dyn0fRpZ.js.map} +1 -1
- package/dist/main.js +6 -5
- package/dist/main.js.map +1 -1
- package/dist/{peer-mcp-personas-CmR3f7nO.js → peer-mcp-personas-Dt0VRKYz.js} +20 -13
- package/dist/{peer-mcp-personas-CmR3f7nO.js.map → peer-mcp-personas-Dt0VRKYz.js.map} +1 -1
- package/dist/pi-DwfSuefC.js +1175 -0
- package/dist/pi-DwfSuefC.js.map +1 -0
- package/dist/{provision-CxulCZpS.js → provision-D_aHUCXt.js} +11 -2
- package/dist/provision-D_aHUCXt.js.map +1 -0
- package/dist/{serve-DVq-m7p5.js → serve-DWL5kmB_.js} +5 -5
- package/dist/{serve-DVq-m7p5.js.map → serve-DWL5kmB_.js.map} +1 -1
- package/dist/{server-setup-Df9BxQ-V.js → server-setup-UWugox0I.js} +84 -52
- package/dist/server-setup-UWugox0I.js.map +1 -0
- package/dist/{start-C4wi5ccP.js → start-4OTehsYq.js} +3 -3
- package/dist/{start-C4wi5ccP.js.map → start-4OTehsYq.js.map} +1 -1
- package/package.json +1 -1
- package/dist/claude-D0SUYfyr.js.map +0 -1
- package/dist/engine-vxnquZvh.js +0 -2
- package/dist/provision-CxulCZpS.js.map +0 -1
- package/dist/server-setup-Df9BxQ-V.js.map +0 -1
|
@@ -0,0 +1,1175 @@
|
|
|
1
|
+
import { I as withInstallLock, N as warmTreeSitterPool } from "./service-backend-7SPDLUB9.js";
|
|
2
|
+
import { t as state } from "./state-CVp30CBF.js";
|
|
3
|
+
import { c as runCommandVoid, o as resolveExecutable, s as runCommandCapture } from "./exec-MCU1H-KZ.js";
|
|
4
|
+
import { E as formatBalancedPrerequisiteFailure, I as validateCheapestProfilePrerequisites, M as resolveLaunchProfile, N as validateBalancedProfilePrerequisites, a as setupAndServe, c as startKeepAwake, f as enableFileLogging, i as parseSharedArgs, j as profileDescriptor, k as formatCheapestPrerequisiteFailure, l as stopKeepAwake, o as sharedServerArgs, r as getPiLaunchEnvVars, z as runSelfUpdate } from "./server-setup-UWugox0I.js";
|
|
5
|
+
import { a as BALANCED_PROFILE_NATIVE_EFFORTS, c as BALANCED_PROFILE_ORACLE_MODEL, r as BALANCED_PROFILE_MODELS, s as BALANCED_PROFILE_ORACLE_EFFORT } from "./balanced-profile-contract-C6AgFJNp.js";
|
|
6
|
+
import { D as toolbeltEnabled, Gt as registerLaunch, In as CHEAPEST_PROFILE_NATIVE_EFFORTS, Kt as unregisterLaunch, Mn as CHEAPEST_PROFILE_ADVISOR_EFFORT, Nn as CHEAPEST_PROFILE_ADVISOR_MODEL, Pn as CHEAPEST_PROFILE_MODELS, Rn as CHEAPEST_PROFILE_ORACLE_EFFORT, an as provisionAndIndexColbert, ft as browserToolsEnabled, in as colbertDegradedWarning, nn as provisionBrowserAssets, zn as CHEAPEST_PROFILE_ORACLE_MODEL } from "./peer-mcp-personas-Dt0VRKYz.js";
|
|
7
|
+
import { r as resolveSelfInvocation } from "./self-invocation-DIUyoRgL.js";
|
|
8
|
+
import { i as launchChild, t as provisionToolbelt } from "./provision-D_aHUCXt.js";
|
|
9
|
+
import { d as sweepStaleAicLedgerFiles, t as aicLedgerPath } from "./aic-ledger-D4fmThbS.js";
|
|
10
|
+
import { i as injectAicStatusLineIntoSettingsFile, n as AIC_USER_STATUSLINE_ENV, r as buildAicStatusHookCommand, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-Chf-IT45.js";
|
|
11
|
+
import { defineCommand } from "citty";
|
|
12
|
+
import consola from "consola";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import { randomBytes } from "node:crypto";
|
|
15
|
+
import fs from "node:fs/promises";
|
|
16
|
+
import os from "node:os";
|
|
17
|
+
import process$1 from "node:process";
|
|
18
|
+
//#region src/lib/pi-version-check.ts
|
|
19
|
+
const PI_NPM_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
20
|
+
/** Minimum Pi version the `pi` launcher supports. */
|
|
21
|
+
const PI_MIN_VERSION = "0.80.10";
|
|
22
|
+
const THROTTLE_HOURS = 1;
|
|
23
|
+
const NPM_VIEW_TIMEOUT_MS = 5e3;
|
|
24
|
+
const PI_VERSION_TIMEOUT_MS = 3e3;
|
|
25
|
+
const NPM_INSTALL_TIMEOUT_MS = 3e5;
|
|
26
|
+
/** Path to the throttle cache. Created on demand. Separate file from the Claude check. */
|
|
27
|
+
function cacheFilePath() {
|
|
28
|
+
return path.join(os.homedir(), ".local", "share", "github-router", "last-pi-update-check");
|
|
29
|
+
}
|
|
30
|
+
async function readCache() {
|
|
31
|
+
try {
|
|
32
|
+
const raw = await fs.readFile(cacheFilePath(), "utf8");
|
|
33
|
+
const parsed = JSON.parse(raw);
|
|
34
|
+
if (typeof parsed.checkedAt !== "string" || parsed.installedVersion !== null && typeof parsed.installedVersion !== "string" || parsed.latestVersion !== null && typeof parsed.latestVersion !== "string") return null;
|
|
35
|
+
return parsed;
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async function writeCache(cache) {
|
|
41
|
+
try {
|
|
42
|
+
await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true });
|
|
43
|
+
await fs.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 384 });
|
|
44
|
+
} catch (err) {
|
|
45
|
+
consola.debug("Failed to write pi version-check cache:", err);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function shouldCheckNow(cache) {
|
|
49
|
+
if (!cache) return true;
|
|
50
|
+
const lastCheck = new Date(cache.checkedAt).getTime();
|
|
51
|
+
if (Number.isNaN(lastCheck)) return true;
|
|
52
|
+
return (Date.now() - lastCheck) / 1e3 / 3600 >= THROTTLE_HOURS;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Read the installed `pi` version. Returns null if pi is not on PATH
|
|
56
|
+
* or the version probe fails.
|
|
57
|
+
*
|
|
58
|
+
* Windows-safe: `pi` may be a `.cmd` shim; resolved to an absolute path
|
|
59
|
+
* (excluding the cwd) before invocation via the shared exec helper.
|
|
60
|
+
*/
|
|
61
|
+
async function getInstalledPiVersion() {
|
|
62
|
+
const piPath = resolveExecutable("pi");
|
|
63
|
+
if (!piPath) return null;
|
|
64
|
+
try {
|
|
65
|
+
const { stdout, code } = await runCommandCapture([piPath, "--version"], { timeoutMs: PI_VERSION_TIMEOUT_MS });
|
|
66
|
+
if (code !== 0) return null;
|
|
67
|
+
const match = stdout.match(/(\d+\.\d+\.\d+)/);
|
|
68
|
+
return match ? match[1] : null;
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** Fetch the latest Pi version from npm. Null on network/npm failure. */
|
|
74
|
+
async function getLatestPiVersion() {
|
|
75
|
+
const npmPath = resolveExecutable("npm");
|
|
76
|
+
if (!npmPath) return null;
|
|
77
|
+
try {
|
|
78
|
+
const { stdout, code } = await runCommandCapture([
|
|
79
|
+
npmPath,
|
|
80
|
+
"view",
|
|
81
|
+
PI_NPM_PACKAGE,
|
|
82
|
+
"version",
|
|
83
|
+
"--silent"
|
|
84
|
+
], { timeoutMs: NPM_VIEW_TIMEOUT_MS });
|
|
85
|
+
if (code !== 0) return null;
|
|
86
|
+
const v = stdout.trim();
|
|
87
|
+
return /^\d+\.\d+\.\d+/.test(v) ? v : null;
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Compare two semver-shaped strings (leading X.Y.Z only). True when
|
|
94
|
+
* `latest` is strictly higher than `installed`.
|
|
95
|
+
*/
|
|
96
|
+
function isPiNewer(installed, latest) {
|
|
97
|
+
if (!installed || !latest) return false;
|
|
98
|
+
const a = installed.split(".").map((n) => parseInt(n, 10));
|
|
99
|
+
const b = latest.split(".").map((n) => parseInt(n, 10));
|
|
100
|
+
for (let i = 0; i < 3; i++) {
|
|
101
|
+
const av = a[i] ?? 0;
|
|
102
|
+
const bv = b[i] ?? 0;
|
|
103
|
+
if (av < bv) return true;
|
|
104
|
+
if (av > bv) return false;
|
|
105
|
+
}
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
/** True when `version` satisfies the minimum Pi floor (>= PI_MIN_VERSION). */
|
|
109
|
+
function meetsPiMinVersion(version) {
|
|
110
|
+
if (!version) return false;
|
|
111
|
+
return !isPiNewer(version, PI_MIN_VERSION);
|
|
112
|
+
}
|
|
113
|
+
/** Run a version check (subject to throttle). Side-effect: updates the cache. */
|
|
114
|
+
async function checkPiVersion(opts = {}) {
|
|
115
|
+
if (opts.noCheck) return {
|
|
116
|
+
installed: false,
|
|
117
|
+
installedVersion: null,
|
|
118
|
+
latestVersion: null,
|
|
119
|
+
needsUpdate: false,
|
|
120
|
+
needsMinUpgrade: false,
|
|
121
|
+
skipped: true,
|
|
122
|
+
skipReason: "disabled"
|
|
123
|
+
};
|
|
124
|
+
const cache = await readCache();
|
|
125
|
+
if (!opts.force && !shouldCheckNow(cache)) {
|
|
126
|
+
const installedVersion = cache?.installedVersion ?? null;
|
|
127
|
+
const latestVersion = cache?.latestVersion ?? null;
|
|
128
|
+
return {
|
|
129
|
+
installed: installedVersion !== null,
|
|
130
|
+
installedVersion,
|
|
131
|
+
latestVersion,
|
|
132
|
+
needsUpdate: isPiNewer(installedVersion, latestVersion),
|
|
133
|
+
needsMinUpgrade: !meetsPiMinVersion(installedVersion),
|
|
134
|
+
skipped: true,
|
|
135
|
+
skipReason: "throttled"
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
const installedVersion = await getInstalledPiVersion();
|
|
139
|
+
if (installedVersion === null) return {
|
|
140
|
+
installed: false,
|
|
141
|
+
installedVersion: null,
|
|
142
|
+
latestVersion: null,
|
|
143
|
+
needsUpdate: false,
|
|
144
|
+
needsMinUpgrade: true,
|
|
145
|
+
skipped: true,
|
|
146
|
+
skipReason: "no-pi"
|
|
147
|
+
};
|
|
148
|
+
const latestVersion = await getLatestPiVersion();
|
|
149
|
+
await writeCache({
|
|
150
|
+
checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
151
|
+
installedVersion,
|
|
152
|
+
latestVersion
|
|
153
|
+
});
|
|
154
|
+
if (latestVersion === null) return {
|
|
155
|
+
installed: true,
|
|
156
|
+
installedVersion,
|
|
157
|
+
latestVersion: null,
|
|
158
|
+
needsUpdate: false,
|
|
159
|
+
needsMinUpgrade: !meetsPiMinVersion(installedVersion),
|
|
160
|
+
skipped: true,
|
|
161
|
+
skipReason: "no-npm"
|
|
162
|
+
};
|
|
163
|
+
return {
|
|
164
|
+
installed: true,
|
|
165
|
+
installedVersion,
|
|
166
|
+
latestVersion,
|
|
167
|
+
needsUpdate: isPiNewer(installedVersion, latestVersion),
|
|
168
|
+
needsMinUpgrade: !meetsPiMinVersion(installedVersion),
|
|
169
|
+
skipped: false
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Install (or upgrade) Pi from npm under the cross-process install lock.
|
|
174
|
+
* Best-effort: throws on failure; callers fall back to the installed
|
|
175
|
+
* version with a visible warning rather than stranding the launch.
|
|
176
|
+
*/
|
|
177
|
+
async function updatePi(version) {
|
|
178
|
+
const npmPath = resolveExecutable("npm");
|
|
179
|
+
if (!npmPath) throw new Error("npm not found on PATH; cannot install Pi automatically");
|
|
180
|
+
await withInstallLock("pi-install.lock", async () => {
|
|
181
|
+
consola.info(`Installing ${PI_NPM_PACKAGE}@${version}...`);
|
|
182
|
+
await runCommandVoid([
|
|
183
|
+
npmPath,
|
|
184
|
+
"install",
|
|
185
|
+
"-g",
|
|
186
|
+
`${PI_NPM_PACKAGE}@${version}`
|
|
187
|
+
], { timeoutMs: NPM_INSTALL_TIMEOUT_MS });
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
//#endregion
|
|
191
|
+
//#region src/lib/pi-tier-windows.ts
|
|
192
|
+
/**
|
|
193
|
+
* Copilot Default-tier (cheap) input-token thresholds per model.
|
|
194
|
+
*
|
|
195
|
+
* Sourced from https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing
|
|
196
|
+
* (per 1M tokens; tiers key on per-request INPUT tokens):
|
|
197
|
+
* - gpt-6-luna: Default ≤ 272K ($0.10 in) vs Long > 272K ($0.20 in)
|
|
198
|
+
* - gpt-6-sol: Default ≤ 272K ($2.00 in) vs Long > 272K ($4.00 in)
|
|
199
|
+
* - grok-4.6: Default ≤ 200K ($2.00 in) vs Long > 200K ($4.00 in)
|
|
200
|
+
*
|
|
201
|
+
* The live catalog carries no tier data (flat `billing.token_prices` +
|
|
202
|
+
* single `limits.*` only), so this table is hardcoded by exact model id —
|
|
203
|
+
* same precedent as `FALLBACK_TOKEN_PRICES`. Anything not listed here
|
|
204
|
+
* runs at the 200K default window. LAST_VERIFIED 2026-09-24: refresh the
|
|
205
|
+
* values (and the drift expectations below) when the billing doc changes.
|
|
206
|
+
*/
|
|
207
|
+
const PI_TIER_THRESHOLDS = Object.freeze({
|
|
208
|
+
"gpt-6-luna": 272e3,
|
|
209
|
+
"gpt-6-sol": 272e3,
|
|
210
|
+
"grok-4.6": 2e5
|
|
211
|
+
});
|
|
212
|
+
/** Pinned Default-tier threshold for a model id, or the 200K fallback. */
|
|
213
|
+
function piTierThresholdFor(modelId) {
|
|
214
|
+
return PI_TIER_THRESHOLDS[modelId] ?? 2e5;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Effective Pi `contextWindow` for a model: its cheap-tier threshold,
|
|
218
|
+
* defensively capped at the catalog-advertised total window so a stale
|
|
219
|
+
* table can never budget above what Copilot serves.
|
|
220
|
+
*/
|
|
221
|
+
function piContextWindowFor(modelId, advertisedMaxContextTokens) {
|
|
222
|
+
const threshold = piTierThresholdFor(modelId);
|
|
223
|
+
if (typeof advertisedMaxContextTokens === "number" && Number.isFinite(advertisedMaxContextTokens) && advertisedMaxContextTokens > 0) return Math.min(threshold, Math.floor(advertisedMaxContextTokens));
|
|
224
|
+
return threshold;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Expected Default-tier input prices in CATALOG normalized units
|
|
228
|
+
* (`price/1e9*1e6/batch`, same as `livePricesFor`), NOT billing-doc USD.
|
|
229
|
+
* Empirically catalog units = USD × 100 (live luna 10/50 vs $0.10/$1.20,
|
|
230
|
+
* sol 200/1000 vs $2/$10, opus-5.5 400/2000 vs $4/$20 — all ×100).
|
|
231
|
+
* grok-4.6's 200 is inferred the same way (doc $2.00 × 100); if live
|
|
232
|
+
* disagrees the warning fires, which is the guard working, not failing.
|
|
233
|
+
*/
|
|
234
|
+
const EXPECTED_DEFAULT_INPUT_PER_1M = Object.freeze({
|
|
235
|
+
"gpt-6-luna": 10,
|
|
236
|
+
"gpt-6-sol": 200,
|
|
237
|
+
"grok-4.6": 200
|
|
238
|
+
});
|
|
239
|
+
/**
|
|
240
|
+
* Warn loudly when live catalog input prices disagree with the pinned
|
|
241
|
+
* tier table's implied Default rates — the table (or the billing doc)
|
|
242
|
+
* drifted and needs a refresh. Warn-only; never blocks a launch.
|
|
243
|
+
* Pure over caller-supplied rows so it is unit-testable.
|
|
244
|
+
*/
|
|
245
|
+
function tierPriceDriftWarnings(rows) {
|
|
246
|
+
const warnings = [];
|
|
247
|
+
for (const row of rows) {
|
|
248
|
+
const expected = EXPECTED_DEFAULT_INPUT_PER_1M[row.id];
|
|
249
|
+
if (expected === void 0) continue;
|
|
250
|
+
if (row.inputPer1M === void 0) continue;
|
|
251
|
+
if (Math.abs(row.inputPer1M - expected) > 1e-9) warnings.push(`Copilot catalog prices for "${row.id}" (${row.inputPer1M}/1M input, catalog units) disagree with the pinned Pi tier table (${expected}/1M Default). Refresh PI_TIER_THRESHOLDS in src/lib/pi-tier-windows.ts.`);
|
|
252
|
+
}
|
|
253
|
+
return warnings;
|
|
254
|
+
}
|
|
255
|
+
/** Emit drift warnings to stderr (launch-time seam). */
|
|
256
|
+
function warnOnTierPriceDrift(rows) {
|
|
257
|
+
for (const warning of tierPriceDriftWarnings(rows)) consola.warn(warning);
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Normalize live catalog input prices to per-1M rows for the drift guard.
|
|
261
|
+
* Same validation as `livePricesFor` (batch must be a positive safe
|
|
262
|
+
* integer, prices finite and non-negative); anything else yields
|
|
263
|
+
* `undefined` (unknown — skipped, never treated as drift).
|
|
264
|
+
*/
|
|
265
|
+
function liveInputPer1M(models) {
|
|
266
|
+
return (models ?? []).map((m) => {
|
|
267
|
+
const prices = m.billing?.token_prices;
|
|
268
|
+
const batch = prices?.batch_size;
|
|
269
|
+
const input = prices?.input_price;
|
|
270
|
+
const valid = typeof batch === "number" && Number.isSafeInteger(batch) && batch > 0 && typeof input === "number" && Number.isFinite(input) && input >= 0;
|
|
271
|
+
return {
|
|
272
|
+
id: m.id,
|
|
273
|
+
inputPer1M: valid ? input / 1e9 * 1e6 / batch : void 0
|
|
274
|
+
};
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
/** One-call launch seam: normalize the live catalog and warn on drift. */
|
|
278
|
+
function warnOnTierPriceDriftForModels(models) {
|
|
279
|
+
warnOnTierPriceDrift(liveInputPer1M(models));
|
|
280
|
+
}
|
|
281
|
+
//#endregion
|
|
282
|
+
//#region src/lib/pi-paths.ts
|
|
283
|
+
function appDir() {
|
|
284
|
+
return path.join(os.homedir(), ".local", "share", "github-router");
|
|
285
|
+
}
|
|
286
|
+
/** Where the user's real Pi agent dir lives (`PI_CODING_AGENT_DIR` wins). */
|
|
287
|
+
function userPiAgentDir() {
|
|
288
|
+
const override = (process.env.PI_CODING_AGENT_DIR ?? "").trim();
|
|
289
|
+
if (override.length > 0) return override;
|
|
290
|
+
return path.join(os.homedir(), ".pi", "agent");
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Per-launch suffix for the Pi mirror. Lazily generated once per process
|
|
294
|
+
* so every path getter in this module agrees on the directory.
|
|
295
|
+
*/
|
|
296
|
+
let launchSuffix;
|
|
297
|
+
function perLaunchSuffix() {
|
|
298
|
+
launchSuffix ??= `pi-agent-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
299
|
+
return launchSuffix;
|
|
300
|
+
}
|
|
301
|
+
/** Router-owned, per-launch Pi agent dir for the spawned `pi` child. */
|
|
302
|
+
function piMirrorDir() {
|
|
303
|
+
return path.join(appDir(), "pi-mirrors", perLaunchSuffix());
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Provision the per-launch Pi mirror: snapshot-copy the user's real Pi
|
|
307
|
+
* agent dir (settings, models, skills, prompts, extensions the user owns)
|
|
308
|
+
* so the spawned `pi` starts from the user's own setup, then let the
|
|
309
|
+
* launcher overlay the mode's generated files on top.
|
|
310
|
+
*
|
|
311
|
+
* Copy failures of individual user files are debug-logged and skipped —
|
|
312
|
+
* a corrupt user file must not strand the launch. Throws only when the
|
|
313
|
+
* mirror directory itself cannot be created.
|
|
314
|
+
*/
|
|
315
|
+
async function ensurePiAgentMirror() {
|
|
316
|
+
const mirror = piMirrorDir();
|
|
317
|
+
await fs.mkdir(mirror, { recursive: true });
|
|
318
|
+
const source = userPiAgentDir();
|
|
319
|
+
let entries;
|
|
320
|
+
try {
|
|
321
|
+
entries = await fs.readdir(source);
|
|
322
|
+
} catch {
|
|
323
|
+
return mirror;
|
|
324
|
+
}
|
|
325
|
+
const SKIP = /* @__PURE__ */ new Set([
|
|
326
|
+
"auth.json",
|
|
327
|
+
"sessions",
|
|
328
|
+
"models-store.json"
|
|
329
|
+
]);
|
|
330
|
+
await Promise.all(entries.filter((e) => !SKIP.has(e)).map(async (entry) => {
|
|
331
|
+
try {
|
|
332
|
+
await fs.cp(path.join(source, entry), path.join(mirror, entry), { recursive: true });
|
|
333
|
+
} catch (err) {
|
|
334
|
+
consola.debug(`Pi mirror: skipping ${entry}:`, err);
|
|
335
|
+
}
|
|
336
|
+
}));
|
|
337
|
+
return mirror;
|
|
338
|
+
}
|
|
339
|
+
/** Remove THIS launch's Pi mirror on shutdown. Best-effort, never throws. */
|
|
340
|
+
async function removeOwnPiAgentMirror() {
|
|
341
|
+
try {
|
|
342
|
+
await fs.rm(piMirrorDir(), {
|
|
343
|
+
recursive: true,
|
|
344
|
+
force: true
|
|
345
|
+
});
|
|
346
|
+
} catch (err) {
|
|
347
|
+
consola.debug("Pi mirror cleanup failed:", err);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Sweep stale Pi mirrors left behind by crashed launches (dirs whose PID
|
|
352
|
+
* no longer exists, or older than 24h). Best-effort, never throws.
|
|
353
|
+
*/
|
|
354
|
+
async function sweepStalePiAgentMirrors() {
|
|
355
|
+
const root = path.join(appDir(), "pi-mirrors");
|
|
356
|
+
let entries;
|
|
357
|
+
try {
|
|
358
|
+
entries = await fs.readdir(root);
|
|
359
|
+
} catch {
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
await Promise.all(entries.map(async (entry) => {
|
|
363
|
+
const dir = path.join(root, entry);
|
|
364
|
+
try {
|
|
365
|
+
const stat = await fs.stat(dir);
|
|
366
|
+
const ageMs = Date.now() - stat.mtimeMs;
|
|
367
|
+
const pidMatch = /^pi-agent-(\d+)-[0-9a-f]+$/.exec(entry);
|
|
368
|
+
let dead = ageMs > 864e5;
|
|
369
|
+
if (pidMatch && !dead) {
|
|
370
|
+
const pid = Number.parseInt(pidMatch[1], 10);
|
|
371
|
+
try {
|
|
372
|
+
process.kill(pid, 0);
|
|
373
|
+
} catch {
|
|
374
|
+
dead = true;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
if (dead) await fs.rm(dir, {
|
|
378
|
+
recursive: true,
|
|
379
|
+
force: true
|
|
380
|
+
});
|
|
381
|
+
} catch (err) {
|
|
382
|
+
consola.debug(`Pi mirror sweep: skipping ${entry}:`, err);
|
|
383
|
+
}
|
|
384
|
+
}));
|
|
385
|
+
}
|
|
386
|
+
//#endregion
|
|
387
|
+
//#region src/lib/pi-models-settings.ts
|
|
388
|
+
/** Provider key used in models.json and agent `provider/model` references. */
|
|
389
|
+
const PI_PROVIDER_NAME = "gh-router";
|
|
390
|
+
const PI_MIN_VERSION_NOTE = "Requires Pi >= 0.80.10 and Node >= 22.19.";
|
|
391
|
+
function piLeadModel(profileId) {
|
|
392
|
+
return profileId === "cheapest" ? CHEAPEST_PROFILE_MODELS.lead : BALANCED_PROFILE_MODELS.lead;
|
|
393
|
+
}
|
|
394
|
+
function piLeadThinking(profileId) {
|
|
395
|
+
return profileId === "cheapest" ? "max" : "medium";
|
|
396
|
+
}
|
|
397
|
+
function piOracleModel(profileId) {
|
|
398
|
+
return profileId === "cheapest" ? CHEAPEST_PROFILE_ORACLE_MODEL : BALANCED_PROFILE_ORACLE_MODEL;
|
|
399
|
+
}
|
|
400
|
+
function piOracleThinking(profileId) {
|
|
401
|
+
return profileId === "cheapest" ? CHEAPEST_PROFILE_ORACLE_EFFORT : BALANCED_PROFILE_ORACLE_EFFORT;
|
|
402
|
+
}
|
|
403
|
+
/** Cheapest-only advisor. Balanced is advisor-free by design: undefined. */
|
|
404
|
+
function piAdvisorModel(profileId) {
|
|
405
|
+
if (profileId !== "cheapest") return void 0;
|
|
406
|
+
return {
|
|
407
|
+
model: CHEAPEST_PROFILE_ADVISOR_MODEL,
|
|
408
|
+
thinking: CHEAPEST_PROFILE_ADVISOR_EFFORT
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
function piNativeRoles(profileId) {
|
|
412
|
+
if (profileId === "cheapest") return [
|
|
413
|
+
{
|
|
414
|
+
name: "Explore",
|
|
415
|
+
model: CHEAPEST_PROFILE_MODELS.explore,
|
|
416
|
+
thinking: CHEAPEST_PROFILE_NATIVE_EFFORTS.Explore,
|
|
417
|
+
readOnly: true
|
|
418
|
+
},
|
|
419
|
+
{
|
|
420
|
+
name: "General-Purpose",
|
|
421
|
+
model: CHEAPEST_PROFILE_MODELS["General-Purpose"],
|
|
422
|
+
thinking: CHEAPEST_PROFILE_NATIVE_EFFORTS["General-Purpose"],
|
|
423
|
+
readOnly: false
|
|
424
|
+
},
|
|
425
|
+
{
|
|
426
|
+
name: "reviewer",
|
|
427
|
+
model: CHEAPEST_PROFILE_MODELS.reviewer,
|
|
428
|
+
thinking: CHEAPEST_PROFILE_NATIVE_EFFORTS.reviewer,
|
|
429
|
+
readOnly: true
|
|
430
|
+
}
|
|
431
|
+
];
|
|
432
|
+
return [
|
|
433
|
+
{
|
|
434
|
+
name: "Explore",
|
|
435
|
+
model: BALANCED_PROFILE_MODELS.explore,
|
|
436
|
+
thinking: BALANCED_PROFILE_NATIVE_EFFORTS.Explore,
|
|
437
|
+
readOnly: true
|
|
438
|
+
},
|
|
439
|
+
{
|
|
440
|
+
name: "General-Purpose",
|
|
441
|
+
model: BALANCED_PROFILE_MODELS["General-Purpose"],
|
|
442
|
+
thinking: BALANCED_PROFILE_NATIVE_EFFORTS["General-Purpose"],
|
|
443
|
+
readOnly: false
|
|
444
|
+
},
|
|
445
|
+
{
|
|
446
|
+
name: "reviewer",
|
|
447
|
+
model: BALANCED_PROFILE_MODELS.reviewer,
|
|
448
|
+
thinking: BALANCED_PROFILE_NATIVE_EFFORTS.reviewer,
|
|
449
|
+
readOnly: true
|
|
450
|
+
}
|
|
451
|
+
];
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Every model id Pi must see for this profile. Peerless launches
|
|
455
|
+
* (`peers: false`) register the lead only — no peer or native-role model
|
|
456
|
+
* is consumed, so none is exposed to the picker or budgeted.
|
|
457
|
+
*/
|
|
458
|
+
function piProfileModelIds(profileId, opts = {}) {
|
|
459
|
+
const ids = /* @__PURE__ */ new Set([piLeadModel(profileId)]);
|
|
460
|
+
if (opts.peers !== false) {
|
|
461
|
+
ids.add(piOracleModel(profileId));
|
|
462
|
+
for (const r of piNativeRoles(profileId)) ids.add(r.model);
|
|
463
|
+
const advisor = piAdvisorModel(profileId);
|
|
464
|
+
if (advisor) ids.add(advisor.model);
|
|
465
|
+
}
|
|
466
|
+
return [...ids];
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Fallback per-request output cap when the catalog carries no
|
|
470
|
+
* max_output_tokens. Matches the documented Luna/Grok 128K ceiling;
|
|
471
|
+
* the live catalog always wins. Never below the proxy's 16-token floor.
|
|
472
|
+
*/
|
|
473
|
+
const PI_MAX_TOKENS_FALLBACK = 128e3;
|
|
474
|
+
/**
|
|
475
|
+
* Per-1M USD cost for a models.json row, or undefined when unknown.
|
|
476
|
+
*
|
|
477
|
+
* ALL-OR-NOTHING (verified live): Pi silently rejects the entire
|
|
478
|
+
* provider when any of the four figures is missing, surfacing only as
|
|
479
|
+
* `Unknown provider`. A missing figure therefore omits `cost`
|
|
480
|
+
* entirely — guessing zero would under-report real spend, and a
|
|
481
|
+
* partial object breaks the launch.
|
|
482
|
+
*/
|
|
483
|
+
function piUsdCostFor(prices) {
|
|
484
|
+
const batch = prices?.batch_size;
|
|
485
|
+
const usdPer1M = (v) => typeof batch === "number" && Number.isSafeInteger(batch) && batch > 0 && typeof v === "number" && Number.isFinite(v) && v >= 0 ? v / 1e9 * 1e6 / batch / 100 : void 0;
|
|
486
|
+
const input = usdPer1M(prices?.input_price);
|
|
487
|
+
const output = usdPer1M(prices?.output_price);
|
|
488
|
+
const cacheRead = usdPer1M(prices?.cache_read_price ?? prices?.cache_price);
|
|
489
|
+
const cacheWrite = usdPer1M(prices?.cache_write_price);
|
|
490
|
+
if (input === void 0 || output === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
|
|
491
|
+
return {
|
|
492
|
+
input,
|
|
493
|
+
output,
|
|
494
|
+
cacheRead,
|
|
495
|
+
cacheWrite
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Build the `models.json` provider entry pointing Pi at the running
|
|
500
|
+
* proxy as an ordinary OpenAI-compatible endpoint (the documented
|
|
501
|
+
* Ollama/vLLM pattern — no provider-override extension needed).
|
|
502
|
+
*
|
|
503
|
+
* The provider speaks `openai-responses`: every roster model is
|
|
504
|
+
* Responses-only on Copilot, and Pi POSTs `{baseUrl}/responses` for
|
|
505
|
+
* that API — i.e. our `/v1/responses`, the Codex-proven path. Sending
|
|
506
|
+
* these models to `/v1/chat/completions` is a Copilot 400 (observed).
|
|
507
|
+
*
|
|
508
|
+
* Every row is BARE (no `[1m]`) with its cheap-tier window from
|
|
509
|
+
* `piContextWindowFor` (272K Luna/Sol, 200K Grok/unknown): Pi budgets
|
|
510
|
+
* `contextWindow` per model, so each role gets its cheapest tier and
|
|
511
|
+
* Long-tier (2x) pricing is structurally unreachable.
|
|
512
|
+
*/
|
|
513
|
+
function buildPiModelsJson(opts) {
|
|
514
|
+
const baseUrl = `${opts.serverUrl.replace(/\/+$/, "")}/v1`;
|
|
515
|
+
const providerApi = opts.api ?? "openai-responses";
|
|
516
|
+
return { providers: { [PI_PROVIDER_NAME]: {
|
|
517
|
+
baseUrl,
|
|
518
|
+
api: providerApi,
|
|
519
|
+
apiKey: "dummy",
|
|
520
|
+
authHeader: true,
|
|
521
|
+
models: piProfileModelIds(opts.profileId, { peers: opts.peers }).map((id) => {
|
|
522
|
+
const entry = opts.catalog?.find((m) => m.id === id);
|
|
523
|
+
const out = entry?.maxOutputTokens;
|
|
524
|
+
const maxTokens = typeof out === "number" && Number.isFinite(out) && out >= 16 ? Math.floor(out) : PI_MAX_TOKENS_FALLBACK;
|
|
525
|
+
const override = opts.apiOverrides?.[id];
|
|
526
|
+
return {
|
|
527
|
+
id,
|
|
528
|
+
name: id,
|
|
529
|
+
reasoning: true,
|
|
530
|
+
input: ["text"],
|
|
531
|
+
contextWindow: piContextWindowFor(id, entry?.maxContextTokens),
|
|
532
|
+
maxTokens,
|
|
533
|
+
...entry?.cost ? { cost: entry.cost } : {},
|
|
534
|
+
...override && override !== providerApi ? { api: override } : {}
|
|
535
|
+
};
|
|
536
|
+
})
|
|
537
|
+
} } };
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Derive Pi compaction budgets from live catalog `max_prompt_tokens`
|
|
541
|
+
* ceilings AND each model's cheap-tier window — the Pi-native analogue
|
|
542
|
+
* of `deriveAutoCompactWindowTokens`. Pi triggers at
|
|
543
|
+
* `contextWindow − reserveTokens` per active model; the trigger must sit
|
|
544
|
+
* below BOTH the tier price cliff and Copilot's acceptance ceiling:
|
|
545
|
+
* reserve(id) = window(id) − floor(min(prompt, window) × 0.85),
|
|
546
|
+
* clamped to [16384, 100000]. keepRecentTokens stays 20000.
|
|
547
|
+
* The global reserve is the max over models (every model's trigger is
|
|
548
|
+
* safe); overrides carry each model's own value. Unknown catalog (no
|
|
549
|
+
* prompt metadata) → Pi built-in defaults so a missing signal can never
|
|
550
|
+
* disable compaction.
|
|
551
|
+
*/
|
|
552
|
+
function derivePiCompactionSettings(catalog, modelIds) {
|
|
553
|
+
const FALLBACK = {
|
|
554
|
+
enabled: true,
|
|
555
|
+
reserveTokens: 16384,
|
|
556
|
+
keepRecentTokens: 2e4,
|
|
557
|
+
modelOverrides: {}
|
|
558
|
+
};
|
|
559
|
+
if (!catalog || catalog.length === 0) return FALLBACK;
|
|
560
|
+
const perModel = /* @__PURE__ */ new Map();
|
|
561
|
+
for (const id of modelIds) {
|
|
562
|
+
const entry = catalog.find((m) => m.id === id);
|
|
563
|
+
const window = piContextWindowFor(id, entry?.maxContextTokens);
|
|
564
|
+
const prompt = entry?.maxPromptTokens ?? 0;
|
|
565
|
+
const ceiling = Number.isFinite(prompt) && prompt > 0 ? Math.min(prompt, window) : window;
|
|
566
|
+
perModel.set(id, Math.min(1e5, Math.max(16384, window - Math.floor(ceiling * .85))));
|
|
567
|
+
}
|
|
568
|
+
if (perModel.size === 0) return FALLBACK;
|
|
569
|
+
const global = Math.max(...perModel.values());
|
|
570
|
+
const modelOverrides = {};
|
|
571
|
+
for (const [id, reserve] of perModel) modelOverrides[`${PI_PROVIDER_NAME}/${id}`] = {
|
|
572
|
+
reserveTokens: reserve,
|
|
573
|
+
keepRecentTokens: 2e4
|
|
574
|
+
};
|
|
575
|
+
return {
|
|
576
|
+
enabled: true,
|
|
577
|
+
reserveTokens: global,
|
|
578
|
+
keepRecentTokens: 2e4,
|
|
579
|
+
modelOverrides
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Build the per-launch `settings.json`. Additive over the snapshotted
|
|
584
|
+
* user settings (the launcher merges lists it owns): narrow model
|
|
585
|
+
* scope, fixed thinking, limited toolset, derived compaction, and the
|
|
586
|
+
* mode's package slice. Never disables retry/transport hardening.
|
|
587
|
+
*
|
|
588
|
+
* `pi-subagents` rides `peersEnabled` and loads extensions ONLY
|
|
589
|
+
* (skills/prompts filtered out — the mode's own skills/prompts cover
|
|
590
|
+
* the roster, so the third-party sets never reach Ctrl+O).
|
|
591
|
+
* `pi-statusline` is extension-only by manifest and always present.
|
|
592
|
+
*/
|
|
593
|
+
function buildPiSettingsJson(opts) {
|
|
594
|
+
const peers = opts.peers !== false;
|
|
595
|
+
const modelIds = piProfileModelIds(opts.profileId, { peers });
|
|
596
|
+
return {
|
|
597
|
+
defaultProvider: PI_PROVIDER_NAME,
|
|
598
|
+
defaultModel: piLeadModel(opts.profileId),
|
|
599
|
+
defaultThinkingLevel: piLeadThinking(opts.profileId),
|
|
600
|
+
enabledModels: modelIds.map((id) => `${PI_PROVIDER_NAME}/${id}`),
|
|
601
|
+
defaultTools: [
|
|
602
|
+
"read",
|
|
603
|
+
"bash",
|
|
604
|
+
"edit",
|
|
605
|
+
"write",
|
|
606
|
+
"grep",
|
|
607
|
+
"find",
|
|
608
|
+
"ls"
|
|
609
|
+
],
|
|
610
|
+
compaction: derivePiCompactionSettings(opts.catalog, modelIds),
|
|
611
|
+
retry: {
|
|
612
|
+
enabled: true,
|
|
613
|
+
maxRetries: 3
|
|
614
|
+
},
|
|
615
|
+
packages: [
|
|
616
|
+
...peers ? [{
|
|
617
|
+
source: "npm:pi-subagents",
|
|
618
|
+
skills: [],
|
|
619
|
+
prompts: []
|
|
620
|
+
}] : [],
|
|
621
|
+
"npm:pi-statusline",
|
|
622
|
+
"local:gh-router-pi"
|
|
623
|
+
]
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
function agentFileName(name) {
|
|
627
|
+
return `${name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}.md`;
|
|
628
|
+
}
|
|
629
|
+
function roleDescription(profileId, role) {
|
|
630
|
+
const oracleNote = "For risky decisions, ask the oracle subagent for a second opinion before acting.";
|
|
631
|
+
if (role.name === "Explore") return `Fast read-only recon: locate code, answer evidence questions, return compressed context. ${oracleNote}`;
|
|
632
|
+
if (role.name === "General-Purpose") return profileId === "balanced" ? `General implementation and follow-through on scoped tasks. May hand the result to reviewer only when the change alters behavior. ${oracleNote}` : `General implementation and follow-through on scoped tasks. May hand the result to reviewer for assessment. ${oracleNote}`;
|
|
633
|
+
return profileId === "balanced" ? "Behavior-changing review only: assess a change, narrow scope with search first, delegate targeted discovery to Explore rather than sweeping the repo." : "Code review and assessment, including reproducing and root-causing a failure.";
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Build `.md` agent definitions for the mode's native roster, in the
|
|
637
|
+
* OpenCode/pi-subagents-lite frontmatter format Pi delegation tools
|
|
638
|
+
* consume (`name/description/tools/model/thinking/max_turns`, plus
|
|
639
|
+
* `allowedAgents` where the delegation graph has an edge). Bodies are
|
|
640
|
+
* short execution contracts; workflow prose lives in skills so agent
|
|
641
|
+
* files stay small enough to inline cheaply.
|
|
642
|
+
*/
|
|
643
|
+
function buildPiAgentFiles(profileId) {
|
|
644
|
+
const files = {};
|
|
645
|
+
for (const role of piNativeRoles(profileId)) {
|
|
646
|
+
const tools = role.name === "General-Purpose" ? "[read, bash, edit, write, grep, find, ls]" : "[read, grep, find, ls]";
|
|
647
|
+
const lines = [
|
|
648
|
+
"---",
|
|
649
|
+
`name: ${role.name}`,
|
|
650
|
+
`description: ${roleDescription(profileId, role)}`,
|
|
651
|
+
`tools: ${tools}`,
|
|
652
|
+
`model: ${PI_PROVIDER_NAME}/${role.model}`,
|
|
653
|
+
`thinking: ${role.thinking}`,
|
|
654
|
+
"max_turns: 80"
|
|
655
|
+
];
|
|
656
|
+
if (profileId === "balanced" && role.name === "reviewer") lines.push("allowedAgents: [Explore]");
|
|
657
|
+
if (role.name === "General-Purpose") lines.push("allowedAgents: [reviewer]");
|
|
658
|
+
lines.push("---", "");
|
|
659
|
+
if (role.name === "Explore") lines.push("You are a read-only scout. Never modify files. Search first, read second,", "return the smallest sufficient evidence: file paths, line spans, and short quotes.");
|
|
660
|
+
else if (role.name === "reviewer") lines.push("You review a change that already exists. Reproduce failures before diagnosing.", "Report findings with file:line references; do not rewrite code outside small,", "clearly-marked suggestions.");
|
|
661
|
+
else lines.push("You implement the scoped task and verify it (run the relevant tests).", "Hand behavior-changing results to reviewer when asked; otherwise summarize", "the diff and how it was verified.");
|
|
662
|
+
files[`agents/${agentFileName(role.name)}`] = `${lines.join("\n")}\n`;
|
|
663
|
+
}
|
|
664
|
+
const oracle = [
|
|
665
|
+
"---",
|
|
666
|
+
"name: oracle",
|
|
667
|
+
`description: Second opinion before acting. Challenges assumptions without editing. Use when the decision itself feels risky.`,
|
|
668
|
+
"tools: [read, grep, find, ls]",
|
|
669
|
+
`model: ${PI_PROVIDER_NAME}/${piOracleModel(profileId)}`,
|
|
670
|
+
`thinking: ${piOracleThinking(profileId)}`,
|
|
671
|
+
"max_turns: 40",
|
|
672
|
+
"---",
|
|
673
|
+
"",
|
|
674
|
+
"You are an oracle: a second set of eyes. You see only the task context",
|
|
675
|
+
"you are given — you have no repo memory beyond what you read now.",
|
|
676
|
+
"Challenge assumptions, name what is missing, recommend; never execute."
|
|
677
|
+
].join("\n");
|
|
678
|
+
files[`agents/${agentFileName("oracle")}`] = `${oracle}\n`;
|
|
679
|
+
const advisor = piAdvisorModel(profileId);
|
|
680
|
+
if (advisor) {
|
|
681
|
+
const body = [
|
|
682
|
+
"---",
|
|
683
|
+
"name: advisor",
|
|
684
|
+
`description: Advisory plan review for the lead: review the final plan before it is presented. Never executes.`,
|
|
685
|
+
"tools: [read, grep, find, ls]",
|
|
686
|
+
`model: ${PI_PROVIDER_NAME}/${advisor.model}`,
|
|
687
|
+
`thinking: ${advisor.thinking}`,
|
|
688
|
+
"max_turns: 40",
|
|
689
|
+
"---",
|
|
690
|
+
"",
|
|
691
|
+
"You review the lead's final plan and give advisory feedback only.",
|
|
692
|
+
"Confirm or challenge approach, scope, and verification steps.",
|
|
693
|
+
"You never implement, and your verdict never substitutes for verification."
|
|
694
|
+
].join("\n");
|
|
695
|
+
files[`agents/${agentFileName("advisor")}`] = `${body}\n`;
|
|
696
|
+
}
|
|
697
|
+
return files;
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* Short operating digest appended to APPEND_SYSTEM.md (prompt-cache-stable).
|
|
701
|
+
* Mode identity — always injected. Peer consult sentences drop out under
|
|
702
|
+
* `peers: false` so the digest never names tools that don't exist.
|
|
703
|
+
*/
|
|
704
|
+
function buildPiAppendSystem(profileId, opts = {}) {
|
|
705
|
+
const peers = opts.peers !== false;
|
|
706
|
+
const advisor = peers ? piAdvisorModel(profileId) : void 0;
|
|
707
|
+
const lines = [
|
|
708
|
+
`# gh-router ${profileId} mode`,
|
|
709
|
+
"",
|
|
710
|
+
`- Lead owns planning directly; there is no Plan subagent.`
|
|
711
|
+
];
|
|
712
|
+
if (peers) lines.push(`- Delegate FREELY to Explore for discovery and General-Purpose for scoped work.`, profileId === "balanced" ? `- Send work to reviewer ONLY when the change alters behavior.` : `- Send finished work to reviewer for assessment.`, `- Ask oracle for a second opinion when the decision itself feels risky.`, advisor ? `- Review the final plan with advisor (advisory) before presenting it.` : `- There is no advisor in this mode: oracle is the only consultant.`, `- Verify, don't vote: consultant verdicts never substitute for running the tests.`);
|
|
713
|
+
else lines.push(`- Peerless launch: no subagents or consultants in this session; plan, implement, and verify directly.`);
|
|
714
|
+
lines.push("", `(${PI_MIN_VERSION_NOTE})`, "");
|
|
715
|
+
return lines.join("\n");
|
|
716
|
+
}
|
|
717
|
+
//#endregion
|
|
718
|
+
//#region src/lib/pi-extension.ts
|
|
719
|
+
/**
|
|
720
|
+
* The gh-router Pi extension source, generated per launch into the
|
|
721
|
+
* isolated mirror (`extensions/gh-router-pi/index.ts`).
|
|
722
|
+
*
|
|
723
|
+
* Design (Pi-cooperative): executable seams only — oracle/advisor
|
|
724
|
+
* consult, semantic search, and browser dispatch all POST JSON-RPC
|
|
725
|
+
* `tools/call` to the running proxy's `/mcp/<group>` with the
|
|
726
|
+
* per-launch nonce (the same `GH_ROUTER_HOOK_MCP_URL/NONCE` channel the
|
|
727
|
+
* Claude hooks use), then return the text. No custom provider, no
|
|
728
|
+
* compaction replacement: `session_before_compact` only routes the
|
|
729
|
+
* summary model and always falls back to Pi native on failure.
|
|
730
|
+
*/
|
|
731
|
+
function buildPiExtensionSource(opts) {
|
|
732
|
+
const peers = opts.peers !== false;
|
|
733
|
+
const advisor = peers ? piAdvisorModel(opts.profileId) : void 0;
|
|
734
|
+
const oracleModel = piOracleModel(opts.profileId);
|
|
735
|
+
const oracleThinking = piOracleThinking(opts.profileId);
|
|
736
|
+
const lines = [];
|
|
737
|
+
lines.push(`// gh-router-pi extension (${opts.profileId} mode). Generated per launch; do not edit.`, `// Executable seams only. Workflow guidance lives in skills/, not here.`, `import { Type } from "typebox";`, ``, ...peers ? [
|
|
738
|
+
`const OracleParams = Type.Object({`,
|
|
739
|
+
` decision: Type.String({ description: "The risky decision to get a second opinion on" }),`,
|
|
740
|
+
` options: Type.Optional(Type.String({ description: "Options considered" })),`,
|
|
741
|
+
` context: Type.String({ description: "Missing-context gaps and background the cold-start oracle needs" }),`,
|
|
742
|
+
`});`
|
|
743
|
+
] : [], ...advisor ? [
|
|
744
|
+
`const AdvisorParams = Type.Object({`,
|
|
745
|
+
` plan: Type.String({ description: "The final plan to review (advisory)" }),`,
|
|
746
|
+
` context: Type.Optional(Type.String({ description: "Background context" })),`,
|
|
747
|
+
`});`
|
|
748
|
+
] : [], `const CodeSearchParams = Type.Object({`, ` query: Type.String({ description: "What to find" }),`, ` mode: Type.Optional(Type.String({ description: "semantic (default), lexical, exact, regex, or ast" })),`, ` limit: Type.Optional(Type.Number({ description: "Max results" })),`, `});`, `const BrowserParams = Type.Object({`, ` url: Type.Optional(Type.String({ description: "URL to act on" })),`, ` intent: Type.Optional(Type.String({ description: "What to do on the page" })),`, `});`, `async function toolText(promise) {`, ` const text = await promise;`, ` return { content: [{ type: "text", text }], details: undefined };`, `}`, `const MCP_URL = (process.env.GH_ROUTER_HOOK_MCP_URL ?? "").replace(/\\/+$/, "");`, `const MCP_NONCE = process.env.GH_ROUTER_HOOK_NONCE ?? "";`, ...peers ? [`const ORACLE_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${oracleModel}`)};`, `const ORACLE_THINKING = ${JSON.stringify(oracleThinking)};`] : [], ...advisor ? [`const ADVISOR_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${advisor.model}`)};`, `const ADVISOR_THINKING = ${JSON.stringify(advisor.thinking)};`] : [], `const LEAD_MODEL = ${JSON.stringify(`${PI_PROVIDER_NAME}/${piLeadModel(opts.profileId)}`)};`, `const LEAD_THINKING = ${JSON.stringify(piLeadThinking(opts.profileId))};`, ``, `async function callMcp(group, tool, args, signal) {`, ` const res = await fetch(MCP_URL + "/mcp/" + group, {`, ` method: "POST",`, ` headers: { "content-type": "application/json", accept: "application/json", authorization: "Bearer " + MCP_NONCE },`, ` body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } }),`, ` signal,`, ` });`, ` if (!res.ok) throw new Error("mcp " + group + "/" + tool + " -> HTTP " + res.status);`, ` const body = await res.json();`, ` if (body.error) return "Error: " + body.error.message;`, ` const content = body.result && body.result.content;`, ` if (!Array.isArray(content)) return "";`, ` return content.map((c) => c.text || "").join("\\n");`, `}`, ``, `export default function (pi) {`, ...peers ? [
|
|
749
|
+
` pi.registerTool({`,
|
|
750
|
+
` name: "oracle",`,
|
|
751
|
+
` label: "Oracle",`,
|
|
752
|
+
` description: "Second opinion before acting on a risky decision. Advisory only: challenges assumptions, never edits. Pass decision, options, and context.",`,
|
|
753
|
+
` parameters: OracleParams,`,
|
|
754
|
+
` async execute(_toolCallId, params, signal) {`,
|
|
755
|
+
` return await toolText(callMcp("peers", "oracle", { decision: params.decision, options: params.options || "", context: params.context, model: ORACLE_MODEL, thinking: ORACLE_THINKING }, signal));`,
|
|
756
|
+
` },`,
|
|
757
|
+
` });`
|
|
758
|
+
] : []);
|
|
759
|
+
if (advisor) lines.push(` pi.registerTool({`, ` name: "advisor",`, ` label: "Advisor",`, ` description: "Advisory plan review for the lead: review the final plan before presenting it. Never executes.",`, ` parameters: AdvisorParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("peers", "oracle", { decision: "Review this plan (advisory)", options: params.plan, context: params.context || "", model: ADVISOR_MODEL, thinking: ADVISOR_THINKING }, signal));`, ` },`, ` });`);
|
|
760
|
+
if (opts.searchEnabled) lines.push(` pi.registerTool({`, ` name: "code_search",`, ` label: "Code search",`, ` description: "Semantic-first code search over the workspace index (falls back to lexical with a label). Use for finding code by meaning.",`, ` parameters: CodeSearchParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("search", "code", { query: params.query, mode: params.mode || "semantic", limit: params.limit || 15 }, signal));`, ` },`, ` });`);
|
|
761
|
+
if (opts.browseEnabled) lines.push(` const BROWSER_TOOLS = ["browser_open_tab", "browser_navigate", "browser_screenshot", "browser_act", "browser_observe", "browser_extract"];`, ` for (const wireName of BROWSER_TOOLS) {`, ` pi.registerTool({`, ` name: wireName,`, ` description: "Browser control (" + wireName + "). Returns install_required with setup steps when the extension is not loaded.",`, ` parameters: BrowserParams,`, ` async execute(_toolCallId, params, signal) {`, ` return await toolText(callMcp("browser", wireName, { url: params.url || "", intent: params.intent || "" }, signal));`, ` },`, ` });`, ` }`);
|
|
762
|
+
lines.push(` // Route compaction summaries to the mode's cheap capable model;`, ` // ALWAYS fall back to Pi native (return undefined) on any failure.`, ` pi.on("session_before_compact", async (event) => {`, ` try {`, ` const preparation = event.preparation;`, ` if (!preparation || !Array.isArray(preparation.messagesToSummarize)) return undefined;`, ` return undefined; // v1: observe only; native pipeline stays authoritative.`, ` } catch {`, ` return undefined;`, ` }`, ` });`, `}`, ``);
|
|
763
|
+
return `${lines.join("\n")}\n`;
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* Workflow guidance as skills (progressive disclosure, not tools).
|
|
767
|
+
* Ownership mirrors the Claude launcher: peer consult prose rides
|
|
768
|
+
* `--peers`, semantic-search prose rides `--search`, and the
|
|
769
|
+
* delegation/review pipeline rides `--swe`. A bare launch emits NO
|
|
770
|
+
* skills at all.
|
|
771
|
+
*/
|
|
772
|
+
function buildPiSkills(opts) {
|
|
773
|
+
const peers = opts.peers !== false;
|
|
774
|
+
const skills = [];
|
|
775
|
+
if (peers) skills.push({
|
|
776
|
+
dir: "gh-oracle",
|
|
777
|
+
content: [
|
|
778
|
+
"---",
|
|
779
|
+
"name: gh-oracle",
|
|
780
|
+
"description: Consult the oracle for a second opinion on risky decisions. Use when the decision itself feels risky.",
|
|
781
|
+
"---",
|
|
782
|
+
"",
|
|
783
|
+
"# Oracle consult",
|
|
784
|
+
"",
|
|
785
|
+
"Call the `oracle` tool with the decision, the options considered, and the",
|
|
786
|
+
"missing-context gaps. The oracle is cold-start: it sees only what you pass.",
|
|
787
|
+
"Its verdict is advisory — verify with tests and code, never substitute votes",
|
|
788
|
+
"for verification."
|
|
789
|
+
].join("\n")
|
|
790
|
+
});
|
|
791
|
+
if (opts.search === true) skills.push({
|
|
792
|
+
dir: "gh-search-first",
|
|
793
|
+
content: [
|
|
794
|
+
"---",
|
|
795
|
+
"name: gh-search-first",
|
|
796
|
+
"description: Search the workspace semantically before reading broadly. Use when locating code by meaning.",
|
|
797
|
+
"---",
|
|
798
|
+
"",
|
|
799
|
+
"# Search first",
|
|
800
|
+
"",
|
|
801
|
+
"Use `code_search` (semantic by default) before broad reads. The response",
|
|
802
|
+
"labels its `source`: `semantic`, `lexical`, or `lexical-fallback` — a",
|
|
803
|
+
"fallback is never silent, so retry narrower on fallback rather than",
|
|
804
|
+
"assuming full coverage."
|
|
805
|
+
].join("\n")
|
|
806
|
+
});
|
|
807
|
+
if (opts.swe === true) {
|
|
808
|
+
skills.push({
|
|
809
|
+
dir: "gh-delegate",
|
|
810
|
+
content: [
|
|
811
|
+
"---",
|
|
812
|
+
"name: gh-delegate",
|
|
813
|
+
"description: Delegate scoped work to subagents with isolated context. Use for recon, implementation, and review loops.",
|
|
814
|
+
"---",
|
|
815
|
+
"",
|
|
816
|
+
"# Delegate",
|
|
817
|
+
"",
|
|
818
|
+
"Recommended loop: scout (Explore) before you understand the code, worker",
|
|
819
|
+
"(General-Purpose) to implement, fresh reviewers to check, worker to apply",
|
|
820
|
+
"feedback. Keep delegated tasks scoped with file:line evidence on return.",
|
|
821
|
+
opts.profileId === "balanced" ? "Send work to reviewer ONLY when the change alters behavior." : "Send finished work to reviewer for assessment."
|
|
822
|
+
].join("\n")
|
|
823
|
+
});
|
|
824
|
+
if (peers && piAdvisorModel(opts.profileId)) skills.push({
|
|
825
|
+
dir: "gh-advisor",
|
|
826
|
+
content: [
|
|
827
|
+
"---",
|
|
828
|
+
"name: gh-advisor",
|
|
829
|
+
"description: Advisory review of the final plan before presenting it. Use when the lead has a plan ready.",
|
|
830
|
+
"---",
|
|
831
|
+
"",
|
|
832
|
+
"# Advisor review",
|
|
833
|
+
"",
|
|
834
|
+
"The lead plans directly (there is no Plan subagent). Review the final plan",
|
|
835
|
+
"with the `advisor` tool before presenting it. Advisory only: it never",
|
|
836
|
+
"executes and never overrides verification."
|
|
837
|
+
].join("\n")
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
return skills;
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Saved workflow shortcuts as prompt templates (`/name`). The review
|
|
844
|
+
* pipeline is SWE-pipeline surface: only `--swe` emits prompts, so a
|
|
845
|
+
* bare launch advertises none.
|
|
846
|
+
*/
|
|
847
|
+
function buildPiPrompts(opts) {
|
|
848
|
+
if (opts.swe !== true) return [];
|
|
849
|
+
const prompts = [{
|
|
850
|
+
name: "review",
|
|
851
|
+
content: [
|
|
852
|
+
"---",
|
|
853
|
+
"description: Review the current changes with the reviewer subagent",
|
|
854
|
+
"argument-hint: \"[focus]\"",
|
|
855
|
+
"---",
|
|
856
|
+
"Have the reviewer subagent review the current changes. Focus on ${1:-correctness, tests, and simplicity}."
|
|
857
|
+
].join("\n")
|
|
858
|
+
}, {
|
|
859
|
+
name: "parallel-review",
|
|
860
|
+
content: [
|
|
861
|
+
"---",
|
|
862
|
+
"description: Run parallel reviewer passes over the change",
|
|
863
|
+
"argument-hint: \"[focus]\"",
|
|
864
|
+
"---",
|
|
865
|
+
"Run parallel reviewers: one for correctness, one for tests, one for unnecessary complexity. Focus: ${1:-the current diff}."
|
|
866
|
+
].join("\n")
|
|
867
|
+
}];
|
|
868
|
+
if (piAdvisorModel(opts.profileId)) prompts.push({
|
|
869
|
+
name: "plan-review",
|
|
870
|
+
content: [
|
|
871
|
+
"---",
|
|
872
|
+
"description: Advisory review of the current plan before presenting",
|
|
873
|
+
"argument-hint: \"[plan]\"",
|
|
874
|
+
"---",
|
|
875
|
+
"Review the final plan with the advisor tool (advisory) before presenting it: ${1:-the current plan}."
|
|
876
|
+
].join("\n")
|
|
877
|
+
});
|
|
878
|
+
return prompts;
|
|
879
|
+
}
|
|
880
|
+
//#endregion
|
|
881
|
+
//#region src/pi.ts
|
|
882
|
+
const piArgs = {
|
|
883
|
+
...sharedServerArgs,
|
|
884
|
+
model: {
|
|
885
|
+
alias: "m",
|
|
886
|
+
type: "string",
|
|
887
|
+
description: "Pi launch profile: cheapest (Luna-led, cheapest tier) or balanced (Sol-led, most-complex-tasks tier). Only these two aliases are supported for `github-router pi`."
|
|
888
|
+
},
|
|
889
|
+
"update-check": {
|
|
890
|
+
type: "boolean",
|
|
891
|
+
default: true,
|
|
892
|
+
description: "Check the npm registry for a newer Pi release on launch (throttled hourly). Set to false (--no-update-check) to skip (offline/CI)."
|
|
893
|
+
},
|
|
894
|
+
"auto-update": {
|
|
895
|
+
type: "boolean",
|
|
896
|
+
default: true,
|
|
897
|
+
description: "Install the latest Pi on launch when stale (default). Set to false (--no-auto-update) to warn only."
|
|
898
|
+
},
|
|
899
|
+
swe: {
|
|
900
|
+
type: "boolean",
|
|
901
|
+
default: false,
|
|
902
|
+
description: "Enable the SWE pipeline surface: delegation/review skills (gh-delegate, cheapest-only gh-advisor) and the review prompt shortcuts (/review, /parallel-review, cheapest-only /plan-review). Off by default; a bare launch advertises no skills or prompts."
|
|
903
|
+
},
|
|
904
|
+
peers: {
|
|
905
|
+
type: "boolean",
|
|
906
|
+
default: true,
|
|
907
|
+
description: "Wire the peer/subagent floor: native agent files, the oracle tool (plus cheapest-only advisor), the gh-oracle skill, and the pi-subagents package. Set to false (--no-peers) for a lead-only session; prereqs then validate the lead model only."
|
|
908
|
+
}
|
|
909
|
+
};
|
|
910
|
+
/**
|
|
911
|
+
* Forward child args: every raw token that is NOT one of github-router's
|
|
912
|
+
* own declared flags (or that flag's consumed value); everything after a
|
|
913
|
+
* literal `--` flows verbatim. Local copy of the claude.ts walk so this
|
|
914
|
+
* module doesn't import the Claude launch graph.
|
|
915
|
+
*/
|
|
916
|
+
function collectPiPassthroughArgs(rawArgs, argsDef) {
|
|
917
|
+
const known = /* @__PURE__ */ new Set();
|
|
918
|
+
const stringTyped = /* @__PURE__ */ new Set();
|
|
919
|
+
for (const [name, def] of Object.entries(argsDef)) {
|
|
920
|
+
const rawAlias = "alias" in def ? def.alias : void 0;
|
|
921
|
+
const aliases = rawAlias === void 0 ? [] : Array.isArray(rawAlias) ? rawAlias : [rawAlias];
|
|
922
|
+
for (const n of [name, ...aliases]) {
|
|
923
|
+
known.add(n);
|
|
924
|
+
if (def.type === "string") stringTyped.add(n);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
const forwarded = [];
|
|
928
|
+
for (let i = 0; i < rawArgs.length; i++) {
|
|
929
|
+
const tok = rawArgs[i];
|
|
930
|
+
if (tok === "--") {
|
|
931
|
+
forwarded.push(...rawArgs.slice(i + 1));
|
|
932
|
+
break;
|
|
933
|
+
}
|
|
934
|
+
if (tok === "-" || !tok.startsWith("-")) {
|
|
935
|
+
forwarded.push(tok);
|
|
936
|
+
continue;
|
|
937
|
+
}
|
|
938
|
+
const doubleDash = tok.startsWith("--");
|
|
939
|
+
const afterDashes = tok.slice(doubleDash ? 2 : 1);
|
|
940
|
+
const eq = afterDashes.indexOf("=");
|
|
941
|
+
const rawName = eq >= 0 ? afterDashes.slice(0, eq) : afterDashes;
|
|
942
|
+
const hasInlineValue = eq >= 0;
|
|
943
|
+
const negated = doubleDash && rawName.startsWith("no-");
|
|
944
|
+
const baseName = negated ? rawName.slice(3) : rawName;
|
|
945
|
+
if (!(known.has(rawName) || negated && known.has(baseName))) {
|
|
946
|
+
forwarded.push(tok);
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
if (!negated && !hasInlineValue && stringTyped.has(rawName) && i + 1 < rawArgs.length && rawArgs[i + 1] !== "--" && !rawArgs[i + 1].startsWith("-")) i++;
|
|
950
|
+
}
|
|
951
|
+
return forwarded;
|
|
952
|
+
}
|
|
953
|
+
async function writeJsonFile(file, value) {
|
|
954
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
955
|
+
await fs.writeFile(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
|
|
956
|
+
}
|
|
957
|
+
async function writeTextFile(file, content) {
|
|
958
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
959
|
+
await fs.writeFile(file, content, { mode: 384 });
|
|
960
|
+
}
|
|
961
|
+
const pi = defineCommand({
|
|
962
|
+
meta: {
|
|
963
|
+
name: "pi",
|
|
964
|
+
description: "Start the proxy server and launch the Pi coding agent (cheapest/balanced)"
|
|
965
|
+
},
|
|
966
|
+
args: piArgs,
|
|
967
|
+
async run({ args, rawArgs }) {
|
|
968
|
+
const headless = rawArgs.includes("--print") || rawArgs.includes("--mode");
|
|
969
|
+
if (!process$1.stdout.isTTY && !headless) {
|
|
970
|
+
consola.error("The pi subcommand requires a TTY (interactive terminal), or use --print/--mode for headless runs.");
|
|
971
|
+
process$1.exit(1);
|
|
972
|
+
}
|
|
973
|
+
const parsed = parseSharedArgs(args);
|
|
974
|
+
const launchProfileId = resolveLaunchProfile(args.model);
|
|
975
|
+
if (launchProfileId !== "cheapest" && launchProfileId !== "balanced") {
|
|
976
|
+
process$1.stderr.write(`github-router pi supports only -m cheapest and -m balanced (got ${JSON.stringify(args.model ?? "")}). Run plain \`github-router pi -m cheapest\` or \`github-router pi -m balanced\`.\n`);
|
|
977
|
+
process$1.exit(1);
|
|
978
|
+
}
|
|
979
|
+
const profileId = launchProfileId;
|
|
980
|
+
let server;
|
|
981
|
+
let serverUrl;
|
|
982
|
+
try {
|
|
983
|
+
const result = await setupAndServe({
|
|
984
|
+
...parsed,
|
|
985
|
+
port: parsed.port,
|
|
986
|
+
silent: true
|
|
987
|
+
});
|
|
988
|
+
server = result.server;
|
|
989
|
+
serverUrl = result.serverUrl;
|
|
990
|
+
} catch (error) {
|
|
991
|
+
consola.error("Failed to start server:", error instanceof Error ? error.message : error);
|
|
992
|
+
process$1.exit(1);
|
|
993
|
+
}
|
|
994
|
+
runSelfUpdate({ selfUpdate: args["self-update"] !== false });
|
|
995
|
+
const updateCheck = args["update-check"] !== false;
|
|
996
|
+
const autoUpdate = args["auto-update"] !== false;
|
|
997
|
+
if (updateCheck) try {
|
|
998
|
+
const check = await checkPiVersion();
|
|
999
|
+
if (!check.installed) try {
|
|
1000
|
+
await updatePi("latest");
|
|
1001
|
+
if (!(await checkPiVersion({ force: true })).installed) throw new Error("install did not place pi on PATH");
|
|
1002
|
+
} catch (err) {
|
|
1003
|
+
consola.error(`Pi is not installed and automatic install failed (${err instanceof Error ? err.message : String(err)}). Install it with \`npm install -g @earendil-works/pi-coding-agent\`, then retry.`);
|
|
1004
|
+
process$1.exit(1);
|
|
1005
|
+
}
|
|
1006
|
+
else if (check.needsMinUpgrade) if (autoUpdate && check.latestVersion) try {
|
|
1007
|
+
await updatePi(check.latestVersion);
|
|
1008
|
+
} catch (err) {
|
|
1009
|
+
consola.error(`Installed Pi v${check.installedVersion} is below the supported floor and auto-upgrade failed. Upgrade manually: \`npm install -g @earendil-works/pi-coding-agent@latest\`.`);
|
|
1010
|
+
process$1.exit(1);
|
|
1011
|
+
}
|
|
1012
|
+
else {
|
|
1013
|
+
consola.error(`Installed Pi v${check.installedVersion} is below the supported floor. Upgrade: \`npm install -g @earendil-works/pi-coding-agent@latest\`.`);
|
|
1014
|
+
process$1.exit(1);
|
|
1015
|
+
}
|
|
1016
|
+
else if (check.needsUpdate && check.latestVersion) if (autoUpdate) try {
|
|
1017
|
+
await updatePi(check.latestVersion);
|
|
1018
|
+
} catch (err) {
|
|
1019
|
+
consola.warn(`Auto-update of Pi to ${check.latestVersion} failed (${err instanceof Error ? err.message : String(err)}); continuing with installed v${check.installedVersion}.`);
|
|
1020
|
+
}
|
|
1021
|
+
else consola.warn(`Pi v${check.installedVersion} is installed; v${check.latestVersion} is available. Run with --auto-update (the default) to install on launch.`);
|
|
1022
|
+
} catch (err) {
|
|
1023
|
+
consola.debug("Pi version check failed:", err);
|
|
1024
|
+
}
|
|
1025
|
+
const peersEnabled = args["peers"] !== false;
|
|
1026
|
+
const sweEnabled = args["swe"] === true;
|
|
1027
|
+
const prereqCheck = profileId === "cheapest" ? validateCheapestProfilePrerequisites(state.models, { peers: peersEnabled }) : validateBalancedProfilePrerequisites(state.models, { peers: peersEnabled });
|
|
1028
|
+
if (!prereqCheck.ok) {
|
|
1029
|
+
const message = profileId === "cheapest" ? formatCheapestPrerequisiteFailure(prereqCheck.missing) : formatBalancedPrerequisiteFailure(prereqCheck.missing);
|
|
1030
|
+
consola.error(message);
|
|
1031
|
+
process$1.stderr.write(`${message}\n`);
|
|
1032
|
+
process$1.exit(1);
|
|
1033
|
+
}
|
|
1034
|
+
let mirror;
|
|
1035
|
+
try {
|
|
1036
|
+
mirror = await ensurePiAgentMirror();
|
|
1037
|
+
await sweepStalePiAgentMirrors();
|
|
1038
|
+
} catch (err) {
|
|
1039
|
+
consola.error(`Failed to provision Pi config mirror: ${err instanceof Error ? err.message : String(err)}.`);
|
|
1040
|
+
process$1.exit(1);
|
|
1041
|
+
}
|
|
1042
|
+
enableFileLogging();
|
|
1043
|
+
try {
|
|
1044
|
+
const searchEnabled = parsed.searchEnabled || process$1.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
|
|
1045
|
+
const browseEnabled = browserToolsEnabled();
|
|
1046
|
+
const catalog = state.models?.data.map((m) => {
|
|
1047
|
+
const cost = piUsdCostFor(m.billing?.token_prices);
|
|
1048
|
+
return {
|
|
1049
|
+
id: m.id,
|
|
1050
|
+
maxContextTokens: m.capabilities?.limits?.max_context_window_tokens ?? 0,
|
|
1051
|
+
maxPromptTokens: m.capabilities?.limits?.max_prompt_tokens ?? 0,
|
|
1052
|
+
maxOutputTokens: m.capabilities?.limits?.max_output_tokens ?? 0,
|
|
1053
|
+
efforts: m.capabilities?.supports?.reasoning_effort ?? [],
|
|
1054
|
+
endpoints: m.supported_endpoints ?? [],
|
|
1055
|
+
...cost ? { cost } : {}
|
|
1056
|
+
};
|
|
1057
|
+
});
|
|
1058
|
+
await writeJsonFile(path.join(mirror, "models.json"), buildPiModelsJson({
|
|
1059
|
+
serverUrl,
|
|
1060
|
+
profileId,
|
|
1061
|
+
catalog,
|
|
1062
|
+
peers: peersEnabled
|
|
1063
|
+
}));
|
|
1064
|
+
const settingsPath = path.join(mirror, "settings.json");
|
|
1065
|
+
let userSettings = {};
|
|
1066
|
+
try {
|
|
1067
|
+
const raw = await fs.readFile(settingsPath, "utf8");
|
|
1068
|
+
const parsedSettings = JSON.parse(raw);
|
|
1069
|
+
if (parsedSettings && typeof parsedSettings === "object") userSettings = parsedSettings;
|
|
1070
|
+
} catch {
|
|
1071
|
+
userSettings = {};
|
|
1072
|
+
}
|
|
1073
|
+
await writeJsonFile(settingsPath, {
|
|
1074
|
+
...userSettings,
|
|
1075
|
+
...buildPiSettingsJson({
|
|
1076
|
+
profileId,
|
|
1077
|
+
searchEnabled,
|
|
1078
|
+
browseEnabled,
|
|
1079
|
+
catalog,
|
|
1080
|
+
peers: peersEnabled
|
|
1081
|
+
})
|
|
1082
|
+
});
|
|
1083
|
+
await writeTextFile(path.join(mirror, "extensions", "gh-router-pi", "index.ts"), buildPiExtensionSource({
|
|
1084
|
+
profileId,
|
|
1085
|
+
searchEnabled,
|
|
1086
|
+
browseEnabled,
|
|
1087
|
+
peers: peersEnabled
|
|
1088
|
+
}));
|
|
1089
|
+
if (peersEnabled) {
|
|
1090
|
+
const agentFiles = buildPiAgentFiles(profileId);
|
|
1091
|
+
for (const [rel, content] of Object.entries(agentFiles)) await writeTextFile(path.join(mirror, rel), content);
|
|
1092
|
+
}
|
|
1093
|
+
for (const skill of buildPiSkills({
|
|
1094
|
+
profileId,
|
|
1095
|
+
peers: peersEnabled,
|
|
1096
|
+
swe: sweEnabled,
|
|
1097
|
+
search: searchEnabled
|
|
1098
|
+
})) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
|
|
1099
|
+
for (const prompt of buildPiPrompts({
|
|
1100
|
+
profileId,
|
|
1101
|
+
swe: sweEnabled
|
|
1102
|
+
})) await writeTextFile(path.join(mirror, "prompts", `${prompt.name}.md`), prompt.content);
|
|
1103
|
+
await writeTextFile(path.join(mirror, "APPEND_SYSTEM.md"), buildPiAppendSystem(profileId, { peers: peersEnabled }));
|
|
1104
|
+
} catch (err) {
|
|
1105
|
+
consola.error(`Failed to write Pi launch files: ${err instanceof Error ? err.message : String(err)}.`);
|
|
1106
|
+
process$1.exit(1);
|
|
1107
|
+
}
|
|
1108
|
+
try {
|
|
1109
|
+
warnOnTierPriceDriftForModels(state.models?.data);
|
|
1110
|
+
} catch (err) {
|
|
1111
|
+
consola.debug("Pi tier drift check skipped:", err);
|
|
1112
|
+
}
|
|
1113
|
+
let aicLedgerEnv;
|
|
1114
|
+
let aicUserStatuslineEnv;
|
|
1115
|
+
if (process$1.env.GH_ROUTER_DISABLE_AIC_STATUSLINE !== "1") try {
|
|
1116
|
+
sweepStaleAicLedgerFiles();
|
|
1117
|
+
const selfInvocation = await resolveSelfInvocation();
|
|
1118
|
+
const statusCommand = buildAicStatusHookCommand(selfInvocation);
|
|
1119
|
+
const injected = await injectAicStatusLineIntoSettingsFile(path.join(mirror, "settings.json"), statusCommand, { routerWins: true });
|
|
1120
|
+
if (injected.written) {
|
|
1121
|
+
aicLedgerEnv = aicLedgerPath();
|
|
1122
|
+
if (injected.mode === "wrapped" && injected.userCommand) aicUserStatuslineEnv = injected.userCommand;
|
|
1123
|
+
if (injected.mode === "forced") consola.info(`Pinned status line installed natively for ${profileId}; a pre-existing statusLine was backed up in this launch's isolated settings and will not run.`);
|
|
1124
|
+
}
|
|
1125
|
+
} catch (err) {
|
|
1126
|
+
consola.warn(`AIC status line skipped: ${err instanceof Error ? err.message : String(err)}.`);
|
|
1127
|
+
}
|
|
1128
|
+
if (toolbeltEnabled()) provisionToolbelt().catch((err) => consola.debug("Toolbelt provisioning failed:", err));
|
|
1129
|
+
provisionAndIndexColbert();
|
|
1130
|
+
colbertDegradedWarning(void 0, { logsToFile: true }).then((warning) => {
|
|
1131
|
+
if (warning) process$1.stderr.write(`${warning}\n`);
|
|
1132
|
+
}).catch(() => {});
|
|
1133
|
+
warmTreeSitterPool();
|
|
1134
|
+
startKeepAwake();
|
|
1135
|
+
if (browserToolsEnabled()) provisionBrowserAssets().catch((err) => consola.debug("Browser extension provisioning failed:", err));
|
|
1136
|
+
const descriptor = profileDescriptor(profileId);
|
|
1137
|
+
const nonce = randomBytes(32).toString("hex");
|
|
1138
|
+
const secret = randomBytes(32).toString("hex");
|
|
1139
|
+
const entry = registerLaunch({
|
|
1140
|
+
profileId,
|
|
1141
|
+
nonce,
|
|
1142
|
+
secret,
|
|
1143
|
+
allowedGroups: peersEnabled ? descriptor.allowedGroups : new Set([...descriptor.allowedGroups ?? []].filter((g) => g !== "peers")),
|
|
1144
|
+
allowedPersonas: peersEnabled ? descriptor.personaAllowlist : /* @__PURE__ */ new Set()
|
|
1145
|
+
});
|
|
1146
|
+
const extraArgs = collectPiPassthroughArgs(rawArgs, piArgs);
|
|
1147
|
+
const lead = piLeadModel(profileId);
|
|
1148
|
+
const modelIds = piProfileModelIds(profileId, { peers: peersEnabled });
|
|
1149
|
+
const surface = [`peers=${peersEnabled ? "on" : "off"}`, `swe=${sweEnabled ? "on" : "off"}`].join(" ");
|
|
1150
|
+
process$1.stderr.write(`Server ready on ${serverUrl}, launching Pi (${profileId} lead ${lead}, models ${modelIds.length}, ${surface})...\n`);
|
|
1151
|
+
const { disposeBluebirdClients } = await import("./bluebird-client-bn9Yv6Cb.js");
|
|
1152
|
+
launchChild({
|
|
1153
|
+
kind: "pi",
|
|
1154
|
+
envVars: {
|
|
1155
|
+
...getPiLaunchEnvVars(mirror),
|
|
1156
|
+
GH_ROUTER_HOOK_MCP_URL: serverUrl,
|
|
1157
|
+
GH_ROUTER_HOOK_NONCE: nonce,
|
|
1158
|
+
...aicLedgerEnv ? { [AIC_LEDGER_ENV]: aicLedgerEnv } : {},
|
|
1159
|
+
...aicUserStatuslineEnv ? { [AIC_USER_STATUSLINE_ENV]: aicUserStatuslineEnv } : {}
|
|
1160
|
+
},
|
|
1161
|
+
extraArgs,
|
|
1162
|
+
model: lead,
|
|
1163
|
+
serverUrl
|
|
1164
|
+
}, server, { onShutdown: async () => {
|
|
1165
|
+
unregisterLaunch(entry.launchId);
|
|
1166
|
+
await stopKeepAwake();
|
|
1167
|
+
await disposeBluebirdClients();
|
|
1168
|
+
await removeOwnPiAgentMirror();
|
|
1169
|
+
} });
|
|
1170
|
+
}
|
|
1171
|
+
});
|
|
1172
|
+
//#endregion
|
|
1173
|
+
export { pi };
|
|
1174
|
+
|
|
1175
|
+
//# sourceMappingURL=pi-DwfSuefC.js.map
|