@pricening/pi-web 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +8 -8
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found/page.js +1 -1
  14. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  15. package/.next/server/app/_not-found.html +1 -1
  16. package/.next/server/app/_not-found.rsc +5 -5
  17. package/.next/server/app/_not-found.segments/_full.segment.rsc +5 -5
  18. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +5 -5
  19. package/.next/server/app/_not-found.segments/_tree.segment.rsc +4 -4
  20. package/.next/server/app/api/app-update/route.js +1 -1
  21. package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
  22. package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
  23. package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
  24. package/.next/server/app/api/auth/providers/route.js +1 -1
  25. package/.next/server/app/api/files/[...path]/route.js +2 -2
  26. package/.next/server/app/api/git/diff/route.js +1 -1
  27. package/.next/server/app/api/mcp/route.js +1 -1
  28. package/.next/server/app/api/models/default/route.js +1 -1
  29. package/.next/server/app/api/models/default/route.js.nft.json +1 -1
  30. package/.next/server/app/api/models/enabled/route.js +1 -1
  31. package/.next/server/app/api/models/enabled/route.js.nft.json +1 -1
  32. package/.next/server/app/api/models/refresh/route.js +1 -1
  33. package/.next/server/app/api/models/route.js +1 -1
  34. package/.next/server/app/api/subagents/profiles/route.js +1 -1
  35. package/.next/server/app/index.html +1 -1
  36. package/.next/server/app/index.rsc +7 -7
  37. package/.next/server/app/index.segments/__PAGE__.segment.rsc +7 -7
  38. package/.next/server/app/index.segments/_full.segment.rsc +7 -7
  39. package/.next/server/app/index.segments/_tree.segment.rsc +4 -4
  40. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  41. package/.next/server/app/login.html +1 -1
  42. package/.next/server/app/login.rsc +6 -6
  43. package/.next/server/app/login.segments/_full.segment.rsc +6 -6
  44. package/.next/server/app/login.segments/_tree.segment.rsc +4 -4
  45. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +6 -6
  46. package/.next/server/app/page.js +21 -21
  47. package/.next/server/app/page_client-reference-manifest.js +1 -1
  48. package/.next/server/app-paths-manifest.json +8 -8
  49. package/.next/server/chunks/2243.js +1 -1
  50. package/.next/server/chunks/27.js +1 -0
  51. package/.next/server/chunks/3573.js +1 -1
  52. package/.next/server/chunks/3757.js +1 -1
  53. package/.next/server/chunks/4815.js +1 -1
  54. package/.next/server/chunks/5582.js +4 -4
  55. package/.next/server/chunks/6429.js +16 -5
  56. package/.next/server/middleware-build-manifest.js +1 -1
  57. package/.next/server/pages/404.html +1 -1
  58. package/.next/server/pages/500.html +1 -1
  59. package/.next/server/server-reference-manifest.json +1 -1
  60. package/.next/static/chunks/1278-efc45c56766dfb9e.js +1 -0
  61. package/.next/static/chunks/3298-67d510dd5eefea7b.js +7 -0
  62. package/.next/static/chunks/app/{layout-4fd82463c6a6ce72.js → layout-b443c6bf63e2119b.js} +1 -1
  63. package/.next/static/chunks/app/page-45e40373d5a8ac1a.js +284 -0
  64. package/.next/static/css/37802f9958c09c58.css +1 -0
  65. package/.next/static/css/{88714c00e109ce28.css → 9bcd6051db4f8890.css} +1 -1
  66. package/.next/static/css/{2da826216fd8066e.css → a4227f38b1abed42.css} +1 -1
  67. package/.next/trace +86 -86
  68. package/.next/trace-build +1 -1
  69. package/bin/pi-web.js +10 -0
  70. package/bin/rotate-preview-secrets.js +105 -0
  71. package/package.json +3 -2
  72. package/public/sw.js +20 -4
  73. package/public/sw.test.mjs +48 -4
  74. package/.next/server/chunks/436.js +0 -1
  75. package/.next/static/chunks/1278-ac53b38d14f1e9e0.js +0 -1
  76. package/.next/static/chunks/7005-327c123cad9d0daa.js +0 -7
  77. package/.next/static/chunks/app/page-2e7b8599b69a38be.js +0 -284
  78. package/.next/static/css/e8f3928dc00ee301.css +0 -1
  79. /package/.next/static/{jEYPBQZndLddtRZ1pDURx → KOelKxgKy8Fd8scUKNriY}/_buildManifest.js +0 -0
  80. /package/.next/static/{jEYPBQZndLddtRZ1pDURx → KOelKxgKy8Fd8scUKNriY}/_ssgManifest.js +0 -0
package/.next/trace-build CHANGED
@@ -1 +1 @@
1
- [{"name":"run-webpack","duration":32992883,"timestamp":243886707,"id":14,"parentId":1,"tags":{},"startTime":1791012535555,"traceId":"fa2ebbcd7f6f6f23"},{"name":"run-typescript","duration":16340146,"timestamp":276892358,"id":8674,"parentId":1,"tags":{},"startTime":1791012568561,"traceId":"fa2ebbcd7f6f6f23"},{"name":"static-check","duration":2268547,"timestamp":293296808,"id":8677,"parentId":1,"tags":{},"startTime":1791012584966,"traceId":"fa2ebbcd7f6f6f23"},{"name":"static-generation","duration":6516695,"timestamp":295698251,"id":8823,"parentId":1,"tags":{},"startTime":1791012587367,"traceId":"fa2ebbcd7f6f6f23"},{"name":"collect-build-traces","duration":46913652,"timestamp":295567889,"id":8820,"parentId":1,"tags":{},"startTime":1791012587237,"traceId":"fa2ebbcd7f6f6f23"},{"name":"telemetry-flush","duration":53,"timestamp":342485709,"id":8832,"parentId":1,"tags":{},"startTime":1791012634154,"traceId":"fa2ebbcd7f6f6f23"},{"name":"next-build","duration":98764903,"timestamp":243720871,"id":1,"tags":{"buildMode":"default","version":"16.3.6","bundler":"webpack","has-custom-webpack-config":"true","use-build-worker":"false"},"startTime":1791012535390,"traceId":"fa2ebbcd7f6f6f23"}]
1
+ [{"name":"run-webpack","duration":32736761,"timestamp":497180145,"id":14,"parentId":1,"tags":{},"startTime":1791467784319,"traceId":"7336969604d80775"},{"name":"run-typescript","duration":16652663,"timestamp":529925319,"id":8720,"parentId":1,"tags":{},"startTime":1791467817065,"traceId":"7336969604d80775"},{"name":"static-check","duration":2349787,"timestamp":546633957,"id":8723,"parentId":1,"tags":{},"startTime":1791467833773,"traceId":"7336969604d80775"},{"name":"static-generation","duration":6525913,"timestamp":549139890,"id":8869,"parentId":1,"tags":{},"startTime":1791467836279,"traceId":"7336969604d80775"},{"name":"collect-build-traces","duration":46348616,"timestamp":548986500,"id":8866,"parentId":1,"tags":{},"startTime":1791467836126,"traceId":"7336969604d80775"},{"name":"telemetry-flush","duration":60,"timestamp":595339262,"id":8878,"parentId":1,"tags":{},"startTime":1791467882479,"traceId":"7336969604d80775"},{"name":"next-build","duration":98339910,"timestamp":496999423,"id":1,"tags":{"buildMode":"default","version":"16.3.6","bundler":"webpack","has-custom-webpack-config":"true","use-build-worker":"false"},"startTime":1791467784139,"traceId":"7336969604d80775"}]
package/bin/pi-web.js CHANGED
@@ -21,6 +21,8 @@ const { getHelpText, parseLaunchOptions } = require("./pi-web-options");
21
21
  const { getNextNodeArgs } = require("./pi-web-node-args");
22
22
  // eslint-disable-next-line @typescript-eslint/no-require-imports
23
23
  const { wireChildProcessLifecycle } = require("./process-lifecycle");
24
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
25
+ const { rotatePreviewSecrets, getRotationWarning } = require("./rotate-preview-secrets");
24
26
 
25
27
  let launchOptions;
26
28
  try {
@@ -66,6 +68,14 @@ if (!fs.existsSync(nextDir)) {
66
68
  process.exit(1);
67
69
  }
68
70
 
71
+ // Replace the published preview-mode secrets with fresh random values so the
72
+ // previewModeId baked into the npm tarball cannot be used to skip the proxy
73
+ // (via the x-prerender-revalidate header). Must happen before `next start`.
74
+ const rotation = rotatePreviewSecrets(nextDir);
75
+ if (!rotation.ok) {
76
+ console.warn(getRotationWarning(rotation.reason));
77
+ }
78
+
69
79
  if (!loopbackHostnames.has(hostname)) {
70
80
  if (passwordEnabled) {
71
81
  console.warn(
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+
3
+ // The published npm tarball ships `.next/prerender-manifest.json`, whose
4
+ // `preview` block holds the build's preview-mode secrets. One of them,
5
+ // `previewModeId`, is the value Next compares against the `x-prerender-revalidate`
6
+ // request header: when they match, Next treats the request as an on-demand
7
+ // revalidation and skips middleware/proxy entirely (see next-server.js
8
+ // `runMiddleware`). Because the value is baked into every published version, an
9
+ // attacker who reads the tarball can send that header and bypass `proxy.ts` —
10
+ // the central password gate and the Host/Origin/Fetch-Metadata checks.
11
+ //
12
+ // `next start` reads these secrets only from this file (there is no runtime env
13
+ // override) and never regenerates them, so we rewrite the three preview secrets
14
+ // with fresh random values before launching Next. That makes the published
15
+ // values useless and unique per launch. Done at startup rather than in a
16
+ // postinstall hook so it runs on the guaranteed launch path and cannot be
17
+ // skipped with `--ignore-scripts`.
18
+
19
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
20
+ const crypto = require("crypto");
21
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
22
+ const fs = require("fs");
23
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
24
+ const path = require("path");
25
+
26
+ const PRERENDER_MANIFEST = "prerender-manifest.json";
27
+
28
+ function freshPreviewSecrets() {
29
+ return {
30
+ // Lengths mirror what Next generates at build time.
31
+ previewModeId: crypto.randomBytes(16).toString("hex"),
32
+ previewModeSigningKey: crypto.randomBytes(32).toString("hex"),
33
+ previewModeEncryptionKey: crypto.randomBytes(32).toString("hex"),
34
+ };
35
+ }
36
+
37
+ /**
38
+ * Rewrite the preview-mode secrets in `.next/prerender-manifest.json` with fresh
39
+ * random values. Never throws: returns a status the caller can surface so a
40
+ * read-only install (where the rewrite cannot happen) is visible rather than a
41
+ * silent bypass.
42
+ *
43
+ * @param {string} nextDir absolute path to the package's `.next` directory
44
+ * @returns {{ ok: boolean, reason?: string, error?: Error }}
45
+ */
46
+ function rotatePreviewSecrets(nextDir) {
47
+ const manifestPath = path.join(nextDir, PRERENDER_MANIFEST);
48
+
49
+ let manifest;
50
+ try {
51
+ manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
52
+ } catch (error) {
53
+ if (error && error.code === "ENOENT") {
54
+ return { ok: false, reason: "missing" };
55
+ }
56
+ return { ok: false, reason: "unreadable", error };
57
+ }
58
+
59
+ if (!manifest || typeof manifest !== "object" || typeof manifest.preview !== "object") {
60
+ return { ok: false, reason: "unexpected-shape" };
61
+ }
62
+
63
+ manifest.preview = { ...manifest.preview, ...freshPreviewSecrets() };
64
+
65
+ // Write to a sibling temp file and rename so a concurrent `next start` never
66
+ // reads a half-written manifest.
67
+ const tempPath = path.join(nextDir, `${PRERENDER_MANIFEST}.${process.pid}.tmp`);
68
+ try {
69
+ fs.writeFileSync(tempPath, JSON.stringify(manifest));
70
+ fs.renameSync(tempPath, manifestPath);
71
+ } catch (error) {
72
+ try {
73
+ fs.rmSync(tempPath, { force: true });
74
+ } catch {
75
+ // Best effort: leaving a stray temp file is harmless.
76
+ }
77
+ return { ok: false, reason: "unwritable", error };
78
+ }
79
+
80
+ return { ok: true };
81
+ }
82
+
83
+ function getRotationWarning(reason) {
84
+ const detail =
85
+ reason === "unwritable"
86
+ ? "the install directory is not writable"
87
+ : reason === "missing"
88
+ ? "its prerender manifest is missing"
89
+ : reason === "unreadable"
90
+ ? "its prerender manifest could not be read"
91
+ : "its prerender manifest has an unexpected format";
92
+ return [
93
+ `Warning: could not rotate pi-web's preview-mode secrets because ${detail}.`,
94
+ "This instance keeps the published preview id, so a client that knows it can",
95
+ "bypass the proxy's authentication and Host/Origin checks via the",
96
+ "x-prerender-revalidate header. Run from a writable install, or restrict",
97
+ "network access to this instance.",
98
+ ].join("\n");
99
+ }
100
+
101
+ module.exports = {
102
+ PRERENDER_MANIFEST,
103
+ rotatePreviewSecrets,
104
+ getRotationWarning,
105
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pricening/pi-web",
3
- "version": "0.10.0",
3
+ "version": "0.10.2",
4
4
  "description": "Web UI for the pi coding agent (fork of @agegr/pi-web with server-side pinned and archived projects)",
5
5
  "homepage": "https://github.com/PriceNing/pi-web#readme",
6
6
  "repository": {
@@ -17,7 +17,7 @@
17
17
  "forkedFrom": {
18
18
  "name": "@agegr/pi-web",
19
19
  "version": "0.10.0",
20
- "commit": "6fcd7d44981ab51a21d6cd6eb06d361d0e3d3068",
20
+ "commit": "86d94e2229f3d552a5b06ff7f79f9e4d09822937",
21
21
  "url": "https://github.com/agegr/pi-web"
22
22
  },
23
23
  "license": "MIT",
@@ -101,6 +101,7 @@
101
101
  "rehype-katex": "^7.0.1",
102
102
  "rehype-raw": "^7.0.0",
103
103
  "rehype-sanitize": "^6.0.0",
104
+ "remark-cjk-friendly": "^2.3.2",
104
105
  "remark-frontmatter": "^5.0.0",
105
106
  "remark-gfm": "^4.0.1",
106
107
  "remark-math": "^6.0.0",
package/public/sw.js CHANGED
@@ -64,7 +64,7 @@ self.addEventListener("fetch", (event) => {
64
64
  PRECACHE_URLS.includes(url.pathname);
65
65
 
66
66
  if (isStaticAsset) {
67
- event.respondWith(cacheFirst(request));
67
+ event.respondWith(cacheFirst(request, event));
68
68
  }
69
69
  });
70
70
 
@@ -151,14 +151,30 @@ async function fetchWithTimeout(request, timeoutMs) {
151
151
  }
152
152
  }
153
153
 
154
- async function cacheFirst(request) {
154
+ async function cacheFirst(request, event) {
155
155
  const cached = await caches.match(request);
156
156
  if (cached) return cached;
157
157
 
158
158
  const response = await fetchWithTimeout(request, ASSET_TIMEOUT_MS);
159
159
  if (response.ok && response.type === "basic") {
160
- const cache = await caches.open(STATIC_CACHE);
161
- await cache.put(request, response.clone());
160
+ // Deliberately NOT awaited before returning the response.
161
+ //
162
+ // The SW script URL is versioned (?v=<app version>), so every upgrade
163
+ // starts a fresh cache: the first load after an upgrade misses on every
164
+ // chunk and writes them all at once. Awaiting each write here held every
165
+ // response behind Cache Storage I/O, which stalled navigations past
166
+ // NAVIGATION_TIMEOUT_MS — the browser showed the offline page while the
167
+ // local server was perfectly healthy. waitUntil keeps this worker alive
168
+ // until the write finishes without blocking the response.
169
+ const copy = response.clone();
170
+ event.waitUntil(
171
+ caches
172
+ .open(STATIC_CACHE)
173
+ .then((cache) => cache.put(request, copy))
174
+ .catch(() => {
175
+ // A failed write only costs one network re-fetch next time.
176
+ }),
177
+ );
162
178
  }
163
179
  return response;
164
180
  }
@@ -157,13 +157,15 @@ function installOfflineStub() {
157
157
 
158
158
  function dispatchFetch(url, { mode = "cors", method = "GET" } = {}) {
159
159
  let pending;
160
+ const background = [];
160
161
  const request = new Request(url, { method });
161
162
  Object.defineProperty(request, "mode", { value: mode });
162
163
  listeners.get("fetch")({
163
164
  request,
164
165
  respondWith: (promise) => { pending = promise; },
166
+ waitUntil: (promise) => { background.push(promise); },
165
167
  });
166
- return pending;
168
+ return { pending, background };
167
169
  }
168
170
 
169
171
  /** fetch() that never settles until the signal it was handed is aborted. */
@@ -191,7 +193,7 @@ test("a stalled navigation falls back to offline.html", async () => {
191
193
 
192
194
  mock.timers.enable({ apis: ["setTimeout"] });
193
195
  try {
194
- const pending = dispatchFetch("https://pi.test/", { mode: "navigate" });
196
+ const { pending } = dispatchFetch("https://pi.test/", { mode: "navigate" });
195
197
  await flushMicrotasks();
196
198
  mock.timers.tick(8000);
197
199
  const response = await pending;
@@ -209,7 +211,7 @@ test("a stalled static asset request is bounded as well", async () => {
209
211
 
210
212
  mock.timers.enable({ apis: ["setTimeout"] });
211
213
  try {
212
- const pending = dispatchFetch("https://pi.test/_next/static/chunks/app.js");
214
+ const { pending } = dispatchFetch("https://pi.test/_next/static/chunks/app.js");
213
215
  // cacheFirst awaits the cache lookup before it reaches the network.
214
216
  await flushMicrotasks();
215
217
  mock.timers.tick(8000);
@@ -221,6 +223,47 @@ test("a stalled static asset request is bounded as well", async () => {
221
223
  }
222
224
  });
223
225
 
226
+ test("a cache miss responds before the cache write finishes", async () => {
227
+ let releaseWrite;
228
+ let writeStarted = false;
229
+ globalThis.caches = {
230
+ match: async () => undefined,
231
+ open: async () => ({
232
+ put: () => {
233
+ writeStarted = true;
234
+ return new Promise((resolve) => { releaseWrite = resolve; });
235
+ },
236
+ }),
237
+ };
238
+ // fetch() to a same-origin URL yields type "basic"; a constructed Response
239
+ // defaults to "default", which cacheFirst deliberately skips.
240
+ globalThis.fetch = async () => {
241
+ const response = new Response("chunk", {
242
+ status: 200,
243
+ headers: { "Content-Type": "text/javascript" },
244
+ });
245
+ Object.defineProperty(response, "type", { value: "basic" });
246
+ return response;
247
+ };
248
+
249
+ const { pending, background } = dispatchFetch("https://pi.test/_next/static/chunks/app.js");
250
+ const response = await pending;
251
+
252
+ // The regression this guards: the SW script URL is versioned, so a version
253
+ // bump leaves the cache cold and every chunk misses at once. Awaiting each
254
+ // write held the responses behind Cache Storage I/O, which pushed
255
+ // navigations past the offline-fallback budget even though the server was
256
+ // healthy. The response must never wait for the write.
257
+ assert.equal(await response.text(), "chunk");
258
+
259
+ await flushMicrotasks();
260
+ assert.equal(writeStarted, true, "the write must still happen");
261
+ assert.equal(background.length, 1, "the write must be kept alive with waitUntil");
262
+
263
+ releaseWrite();
264
+ await background[0];
265
+ });
266
+
224
267
  test("a response that arrives in time is not cut off mid-stream", async () => {
225
268
  installOfflineStub();
226
269
  let signal;
@@ -234,7 +277,8 @@ test("a response that arrives in time is not cut off mid-stream", async () => {
234
277
 
235
278
  mock.timers.enable({ apis: ["setTimeout"] });
236
279
  try {
237
- const response = await dispatchFetch("https://pi.test/", { mode: "navigate" });
280
+ const { pending } = dispatchFetch("https://pi.test/", { mode: "navigate" });
281
+ const response = await pending;
238
282
  // The budget only covers time to first byte: a long-lived body keeps
239
283
  // streaming past it (Next.js streams its SSR payload).
240
284
  mock.timers.tick(60000);
@@ -1 +0,0 @@
1
- "use strict";exports.id=436,exports.ids=[436],exports.modules={11881:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Bl:()=>o,PM:()=>q,d5:()=>s,h3:()=>p,lv:()=>k,qB:()=>n,vF:()=>r});var e=c(21820),f=c(33873),g=c(55831),h=c(75430),i=c(13888),j=a([g,h]);[g,h]=j.then?(await j)():j;let t=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function k(a){return`${a.provider}/${a.id}`}async function l(a,b){let c={getAvailable:async()=>b},d=[];for(let b of a){let a=[];try{({scopedModels:a}=await (0,h.resolveModelScopeWithDiagnostics)([b],c))}catch{a=[]}let e=a.find(a=>a.thinkingLevel)?.thinkingLevel;d.push({pattern:b,matched:a.map(a=>k(a.model)),...e?{pin:e}:{}})}return d}let u=["*","**"];async function m(a){let b=new Map;for(let c of a){let a=b.get(c.provider);a?a.add(k(c)):b.set(c.provider,new Set([k(c)]))}let c={};for(let[d,e]of b){let b=u.map(a=>`${d}/${a}`);for(let f of(await l(b,a)))if(f.matched.length===e.size&&f.matched.every(a=>e.has(a))){c[d]=f.pattern;break}}return c}async function n(a,b,c={}){return{patterns:a,availableRefs:b.map(k),resolutions:await l(a??[],b),...c.withProviderGlobs?{providerGlobs:await m(b)}:{}}}function o(a){let b=new Set([...(0,g.getBuiltinProviders)(),...a.getRegisteredProviderIds()]);return new Set(a.getProviders().map(a=>a.id).filter(a=>!b.has(a)))}function p({input:a,models:b,providerNames:c,customProviders:d,scope:e,settingsPath:f,modelError:g}){let h=(0,i.KL)(a),j=new Set(h.enabled),l=new Map;for(let a of b){let b=k(a),c=h.pins[b],d={id:a.id,name:a.name||a.id,ref:b,enabled:j.has(b),...c?{thinkingPin:c}:{}},e=l.get(a.provider);e?e.push(d):l.set(a.provider,[d])}let m=[...l.entries()].map(([a,b])=>(b.sort((a,b)=>t.compare(a.name,b.name)||t.compare(a.id,b.id)),{id:a,name:c.get(a)??a,kind:d.has(a)?"custom":"builtin",enabledCount:b.filter(a=>a.enabled).length,models:b}));return m.sort((a,b)=>t.compare(a.name,b.name)||t.compare(a.id,b.id)),{allEnabled:h.allEnabled,patterns:a.patterns??null,stalePatterns:h.stalePatterns,enabledTotal:h.enabled.length,availableTotal:a.availableRefs.length,providers:m,scope:e,settingsPath:f,editable:"global"===e,...g?{modelError:g}:{}}}function q(a){let b=(0,e.homedir)();if(!b||!a.startsWith(b))return a;let c=a.slice(b.length);return""===c||c.startsWith(f.sep)?`~${c}`:a}function r(a,{cwd:b,agentDir:c}){let d=a.getProjectSettings().enabledModels,e=void 0===d?"global":"project";return{patterns:a.getEnabledModels(),scope:e,path:q("project"===e?(0,f.join)(b,".pi","settings.json"):(0,f.join)(c,"settings.json"))}}async function s(a,b){let c=a.drainErrors().find(a=>"global"===a.scope);if(c)throw c.error;a.setEnabledModels(b),await a.flush();let d=a.drainErrors();if(d.length>0)throw d[0].error}d()}catch(a){d(a)}})},13888:(a,b,c)=>{function d(a){let b=a.indexOf("/");return b<0?a:a.slice(0,b)}function e(a){return a.map(a=>({pattern:a.pattern,matched:[...a.matched],...a.pin?{pin:a.pin}:{}}))}function f(a){let b=new Set,c=[];for(let d of a)for(let a of d.matched)b.has(a)||(b.add(a),c.push(a));return c}function g(a,b){return b?`${a}:${b}`:a}function h(a){let b=[];for(let c of a){let a=d(c);b.includes(a)||b.push(a)}return b}function i(a,b){return a.filter(a=>d(a)===b)}function j(a,b){let c=a.some(a=>0===a.matched.length),d=a.some(a=>a.pin),e=new Set(f(a));if(!b.availableRefs.every(a=>e.has(a))||c||d)return a.map(a=>a.pattern)}function k(a,b){return void 0===a||void 0===b?a===b:a.length===b.length&&a.every((a,c)=>a===b[c])}function l(a){let b=e(a.resolutions),c=f(b),d={};for(let a of b)if(a.pin)for(let b of a.matched)d[b]??=a.pin;let g=0===c.length;return{allEnabled:g,enabled:g?[...a.availableRefs]:c,pins:d,stalePatterns:b.filter(a=>0===a.matched.length).map(a=>a.pattern)}}function m(a,b,c){let d=new Set(a.availableRefs),l=[...new Set(b.filter(a=>d.has(a)))];if(0===l.length)return{ok:!0,patterns:a.patterns,changed:!1};let m=function(a){let b=e(a.resolutions);if(f(b).length>0)return b;for(let c of h(a.availableRefs)){let d=i(a.availableRefs,c),e=a.providerGlobs?.[c];if(e)b.push({pattern:e,matched:d});else for(let a of d)b.push({pattern:a,matched:[a]})}return b}(a);if(c){let a=new Set(f(m));for(let b of l)a.has(b)||(a.add(b),m.push({pattern:b,matched:[b]}))}else{let a=new Set(l),b=[];for(let c of m){if(!c.matched.some(b=>a.has(b))){b.push(c);continue}for(let d of c.matched.filter(b=>!a.has(b)))b.push({pattern:g(d,c.pin),matched:[d],...c.pin?{pin:c.pin}:{}})}if(0===f(b).length)return{ok:!1,reason:"last-model"};m=b}let n=j(function(a,b){let c=a;for(let a of h(b.availableRefs))c=function(a,b,c){let d=b.providerGlobs?.[c];if(!d)return a;let e=i(b.availableRefs,c);if(0===e.length)return a;let f=new Set(e),g=a.filter(a=>a.matched.some(a=>f.has(a)));if(g.some(a=>a.pin))return a;let h=new Set(g.flatMap(a=>a.matched.filter(a=>f.has(a))));if(e.some(a=>!h.has(a)))return a;let j=a=>a.matched.length>0&&a.matched.every(a=>f.has(a));if(a.filter(j).length<2)return a;let k=a.findIndex(j);if(k<0)return a;let l=new Set(g.filter(a=>!j(a)).flatMap(a=>a.matched));if(e.every(a=>l.has(a)))return a;let m={pattern:d,matched:e};return a.map((a,b)=>b===k?m:a).filter((a,b)=>b===k||!j(a))}(c,b,a);return c}(m,a),a);return{ok:!0,patterns:n,changed:!k(n,a.patterns)}}c.d(b,{KL:()=>l,Ld:()=>s,XW:()=>o,hi:()=>q,jo:()=>r,s2:()=>m,vf:()=>p});let n=new Set(["off","minimal","low","medium","high","xhigh","max"]);function o(a,b){if(!a)return a;let c=b.filter(a=>a.from&&a.to&&a.from!==a.to);return 0===c.length?a:a.map(a=>{for(let{from:b,to:d}of c){if(a===b)return d;if(!a.startsWith(`${b}:`))continue;let c=a.slice(b.length+1);if(n.has(c))return`${d}:${c}`}return a})}function p(a,b){if(!a)return a;let c=b.filter(a=>a.from&&a.to&&a.from!==a.to);return 0===c.length?a:a.map(a=>{let b=c.find(b=>a.startsWith(`${b.from}/`));return b?`${b.to}${a.slice(b.from.length)}`:a})}function q(a){let b=new Set(h(a.availableRefs)),c=[],f=!1;for(let h of e(a.resolutions)){let a=h.pattern.indexOf("/"),e=a>0?h.pattern.slice(0,a):"",i=b.has(e)?h.matched.filter(a=>d(a)===e):[];if(0===i.length||i.length===h.matched.length){c.push(h);continue}for(let a of(f=!0,i))c.push({pattern:g(a,h.pin),matched:[a],...h.pin?{pin:h.pin}:{}})}if(!f)return{ok:!0,patterns:a.patterns,changed:!1};let i=j(c,a);return{ok:!0,patterns:i,changed:!k(i,a.patterns)}}function r(a){let b=e(a.resolutions).filter(a=>a.matched.length>0);if(b.length===a.resolutions.length)return{ok:!0,patterns:a.patterns,changed:!1};let c=0===b.length?void 0:j(b,a);return{ok:!0,patterns:c,changed:!k(c,a.patterns)}}function s(a){return{ok:!0,patterns:void 0,changed:void 0!==a.patterns}}},19225:(a,b,c)=>{a.exports=c(44870)},28967:(a,b,c)=>{function d(){return globalThis.__piModelsCacheState||(globalThis.__piModelsCacheState={entries:new Map,inFlight:new Map,generation:0}),globalThis.__piModelsCacheState}function e(){let a=d();a.generation+=1,a.entries.clear(),a.inFlight.clear()}function f(a,b){return b?{...a,modelError:b}:a}function g(a){return{...a,modelError:"Model list is temporarily unavailable. Check your configuration and try again."}}function h(a,b){let c=d(),e=c.entries.get(a);if(e){if(e.expiresAt>Date.now())return Promise.resolve(e.data);c.entries.delete(a)}let f=c.inFlight.get(a);if(f)return f;let g=c.generation,h=Promise.resolve().then(b).then(b=>{if(c.generation===g&&c.inFlight.get(a)===h){let d=Date.now();for(let[a,b]of c.entries)b.expiresAt<=d&&c.entries.delete(a);for(;c.entries.size>=32;){let a=c.entries.keys().next().value;if(void 0===a)break;c.entries.delete(a)}c.entries.set(a,{data:b,expiresAt:d+6e4})}return b}).finally(()=>{c.inFlight.get(a)===h&&c.inFlight.delete(a)});return c.inFlight.set(a,h),h}c.d(b,{Fw:()=>g,Mx:()=>f,kn:()=>e,rC:()=>h})},80547:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{A$:()=>k,B7:()=>l,mc:()=>j,uK:()=>h.uK,wz:()=>e.wz});var e=c(25252),f=c(82536),g=c(40402),h=c(58864),i=a([g]);async function j(){let a=Date.now(),b=globalThis.__piAllowedRootsCache;if(b&&b.expiresAt>a)return b.roots;let c=await (0,g.dQ)(),d=new Set;for(let a of c)a.cwd&&d.add((0,e.Nw)(a.cwd)),a.projectRoot&&d.add((0,e.Nw)(a.projectRoot));for(let a of(0,e.HM)())d.add(a);return globalThis.__piAllowedRootsCache={roots:d,expiresAt:a+5e3},d}function k(a,b){return(0,f.o4)(a,b)}function l(a,b){return(0,f.xk)(a,b)}g=(i.then?(await i)():i)[0],d()}catch(a){d(a)}})},92280:(a,b,c)=>{Object.defineProperty(b,"I",{enumerable:!0,get:function(){return g}});let d=c(28208),e=c(47617),f=c(62018);async function g(a,b,c,g){if((0,d.isNodeNextResponse)(b)){var h;b.statusCode=c.status,b.statusMessage=c.statusText;let d=["set-cookie","www-authenticate","proxy-authenticate","vary"];null==(h=c.headers)||h.forEach((a,c)=>{if("x-middleware-set-cookie"!==c.toLowerCase())if("set-cookie"===c.toLowerCase())for(let d of(0,f.splitCookiesString)(a))b.appendHeader(c,d);else{let e=void 0!==b.getHeader(c);(d.includes(c.toLowerCase())||!e)&&b.appendHeader(c,a)}});let{originalResponse:i}=b;c.body&&"HEAD"!==a.method?await (0,e.pipeToNodeResponse)(c.body,i,g):i.end()}}}};