pi-pocket 0.28.2 → 0.29.0-beta.1

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 (45) hide show
  1. package/docs/architecture.md +5 -4
  2. package/docs/customizing.md +1 -1
  3. package/docs/extensions/linked-sessions.md +2 -0
  4. package/docs/extensions/policies/api-stability.md +1 -1
  5. package/docs/extensions/reference/api-versions.md +3 -0
  6. package/docs/extensions/reference/host.md +15 -1
  7. package/docs/extensions/reference/pocket.md +12 -1
  8. package/docs/extensions/reference/types.md +19 -1
  9. package/docs/extensions/tools.md +18 -0
  10. package/docs/features.md +5 -5
  11. package/docs/map.md +6 -4
  12. package/npm-shrinkwrap.json +2 -2
  13. package/package.json +1 -1
  14. package/src/server/app.ts +2 -7
  15. package/src/server/browser/cdp.ts +6 -0
  16. package/src/server/browser/identity.ts +55 -0
  17. package/src/server/browser/page.ts +12 -1
  18. package/src/server/browser.ts +1 -0
  19. package/src/server/commands.ts +26 -5
  20. package/src/server/config.ts +10 -0
  21. package/src/server/custom-providers.ts +298 -23
  22. package/src/server/docs.ts +10 -3
  23. package/src/server/extensions/agent-teams.ts +9 -1
  24. package/src/server/extensions/subagents.ts +51 -3
  25. package/src/server/host.ts +12 -3
  26. package/src/server/http/assets.ts +26 -3
  27. package/src/server/http/io.ts +11 -1
  28. package/src/server/http/link-routes.ts +4 -1
  29. package/src/server/http.ts +29 -3
  30. package/src/server/linked-sessions.ts +92 -9
  31. package/src/server/project-model.ts +17 -1
  32. package/types/pocket.d.ts +38 -4
  33. package/web/app.js +3 -2
  34. package/web/back.js +27 -6
  35. package/web/browser-panel.js +23 -12
  36. package/web/browser-paste.js +13 -0
  37. package/web/composer.js +7 -3
  38. package/web/extension-ui.js +17 -2
  39. package/web/index.html +2 -0
  40. package/web/running-board.js +38 -36
  41. package/web/sheets/custom-providers.js +420 -21
  42. package/web/sheets/memory.js +76 -40
  43. package/web/store.js +117 -22
  44. package/web/style.css +151 -11
  45. package/web/transcript.js +57 -11
@@ -2,6 +2,7 @@
2
2
  import { type ChildProcess, spawn } from "node:child_process";
3
3
  import { mkdirSync } from "node:fs";
4
4
  import type { Readable, Writable } from "node:stream";
5
+ import { brandName } from "./identity.ts";
5
6
 
6
7
  export class BrowserError extends Error {}
7
8
 
@@ -178,6 +179,9 @@ export class Chromium {
178
179
  readonly #child: ChildProcess;
179
180
  readonly exited: Promise<void>;
180
181
  userAgent = "";
182
+ /** The browser's name and full version, for its client hints. */
183
+ brand = "Chromium";
184
+ version = "";
181
185
 
182
186
  private constructor(child: ChildProcess, connection: Connection) {
183
187
  this.#child = child;
@@ -249,6 +253,8 @@ export class Chromium {
249
253
  "HeadlessChrome/",
250
254
  "Chrome/",
251
255
  );
256
+ chromium.brand = brandName(String(version.product ?? ""), executable);
257
+ chromium.version = /\/([\d.]+)/.exec(String(version.product ?? ""))?.[1] ?? "";
252
258
  await connection.send("Target.setDiscoverTargets", { discover: true });
253
259
  } catch (error) {
254
260
  chromium.kill();
@@ -0,0 +1,55 @@
1
+ /** What the browser tells pages it is: the brands and versions in its client hints, the platform of this machine. */
2
+ import { arch, platform, release } from "node:os";
3
+ import { basename } from "node:path";
4
+
5
+ type Os = { platform: string; arch: string; release: string };
6
+
7
+ /** The name of the browser. `Browser.getVersion` says `Chrome` for Chromium and Brave too, so the executable tells them apart. */
8
+ export function brandName(product: string, executable: string): string {
9
+ const name = /^(?:Headless)?([A-Za-z]+)\//.exec(product)?.[1] ?? "Chrome";
10
+ const path = executable.toLowerCase();
11
+ const file = basename(path);
12
+
13
+ if (name.startsWith("Edg") || file.includes("edge")) {
14
+ return "Microsoft Edge";
15
+ }
16
+
17
+ if (path.includes("brave")) {
18
+ return "Brave";
19
+ }
20
+
21
+ return path.includes("chromium") || !file.includes("chrome") ? "Chromium" : "Google Chrome";
22
+ }
23
+
24
+ /** `Emulation.setUserAgentOverride`'s `userAgentMetadata` (client hints) for a version such as `155.0.8059.84`. */
25
+ export function clientHints(
26
+ brand: string,
27
+ version: string,
28
+ mobile: boolean,
29
+ os: Os = { platform: platform(), arch: arch(), release: release() },
30
+ ) {
31
+ const major = version.split(".")[0] ?? "0";
32
+ const named = brand === "Chromium" ? [] : [brand];
33
+ const list = (of: (version: string) => string) => [
34
+ { brand: "Not.A/Brand", version: of("8") },
35
+ { brand: "Chromium", version: of(major) },
36
+ ...named.map((name) => ({ brand: name, version: of(major) })),
37
+ ];
38
+ const desktop = {
39
+ linux: ["Linux", os.release.split("-")[0] ?? ""],
40
+ darwin: ["macOS", ""],
41
+ win32: ["Windows", os.release],
42
+ }[os.platform] ?? ["Linux", ""];
43
+
44
+ return {
45
+ brands: list((v) => v),
46
+ fullVersionList: list((v) => (v === major ? version : `${v}.0.0.0`)),
47
+ fullVersion: version,
48
+ platform: mobile ? "Android" : (desktop[0] as string),
49
+ platformVersion: mobile ? "14.0.0" : (desktop[1] as string),
50
+ architecture: mobile ? "" : os.arch === "arm64" ? "arm" : "x86",
51
+ model: mobile ? "Pixel 8" : "",
52
+ mobile,
53
+ bitness: mobile ? "" : "64",
54
+ };
55
+ }
@@ -3,6 +3,7 @@
3
3
  * and people do to it.
4
4
  */
5
5
  import { BrowserError, type Connection, type Json } from "./cdp.ts";
6
+ import { clientHints } from "./identity.ts";
6
7
  import { KEYS, keyEvents, parseKeys } from "./keys.ts";
7
8
  import {
8
9
  DESCRIBE_FUNCTION,
@@ -156,6 +157,7 @@ export class BrowserPage {
156
157
  readonly #target: string;
157
158
  readonly #context: string;
158
159
  readonly #baseAgent: string;
160
+ readonly #brand: { name: string; version: string } | undefined;
159
161
  readonly #changed: () => void;
160
162
  readonly #saved: (saved: Saved) => void;
161
163
  #frameId = "";
@@ -194,6 +196,8 @@ export class BrowserPage {
194
196
  target: string;
195
197
  context: string;
196
198
  userAgent: string;
199
+ /** The browser's name and full version: its client hints name them, as its user agent does. */
200
+ brand?: { name: string; version: string };
197
201
  viewport: Viewport;
198
202
  changed: () => void;
199
203
  saved: (saved: Saved) => void;
@@ -204,6 +208,7 @@ export class BrowserPage {
204
208
  this.#target = options.target;
205
209
  this.#context = options.context;
206
210
  this.#baseAgent = options.userAgent;
211
+ this.#brand = options.brand;
207
212
  this.#viewport = options.viewport;
208
213
  this.#changed = options.changed;
209
214
  this.#saved = options.saved;
@@ -988,7 +993,13 @@ export class BrowserPage {
988
993
  }),
989
994
  agent === ""
990
995
  ? Promise.resolve()
991
- : this.#send("Emulation.setUserAgentOverride", { userAgent: agent }),
996
+ : this.#send("Emulation.setUserAgentOverride", {
997
+ userAgent: agent,
998
+ userAgentMetadata:
999
+ this.#brand === undefined || this.#brand.version === ""
1000
+ ? undefined
1001
+ : clientHints(this.#brand.name, this.#brand.version, viewport.mobile),
1002
+ }),
992
1003
  ]);
993
1004
  }
994
1005
 
@@ -299,6 +299,7 @@ export class Browsers {
299
299
  target: targetId,
300
300
  context: browserContextId,
301
301
  userAgent: chromium.userAgent,
302
+ brand: { name: chromium.brand, version: chromium.version },
302
303
  viewport: viewportFrom(saved?.viewport) ??
303
304
  options.viewport ?? { ...VIEWPORTS.desktop },
304
305
  changed: () => this.#changed(conversationId),
@@ -69,7 +69,12 @@ import { mentionedPaths, viewFile } from "./files.ts";
69
69
  import { isThinkingLevel, THINKING_LEVELS } from "./models.ts";
70
70
  import { writePiSession } from "./pi-sessions.ts";
71
71
  import { snippet } from "./projection.ts";
72
- import { globalModelSettings, projectModelDefault } from "./project-model.ts";
72
+ import {
73
+ globalModelSettings,
74
+ piGlobalSettings,
75
+ projectModelDefault,
76
+ rememberedLevel,
77
+ } from "./project-model.ts";
73
78
  import { expandPromptTemplate, expandSkillCommand, unwrapSkill } from "./prompts.ts";
74
79
  import { clientKey, ownRequest, requestFor, requestPerson } from "./requests.ts";
75
80
  import {
@@ -646,9 +651,10 @@ export class Commands {
646
651
  * The model a new session starts with, always one a person chose: `prefer` (with its thinking level) when it is
647
652
  * signed in here, or else the owner's default, even when it is not signed in now: the session then shows that, and
648
653
  * its first message fails in sight, where another model would spend on what nobody chose for it. Without an owner's
649
- * default, ordinary sessions consult trusted project defaults in their final cwd, then the last picked model,
650
- * then Pi's global default. A no-cwd caller (imports and PiP itself) keeps the legacy default selection. Never
651
- * the first model there is: with none chosen, the session starts without a model, and someone picks one.
654
+ * default, ordinary sessions consult trusted project defaults in their final cwd, then the last picked model (at
655
+ * its level in Pi's `modelThinkingLevels`, when it has one), then Pi's global default. A no-cwd caller (imports and
656
+ * PiP itself) keeps the legacy default selection. Never the first model there is: with none chosen, the session
657
+ * starts without a model, and someone picks one.
652
658
  */
653
659
  #defaultModel(
654
660
  prefer?: {
@@ -704,7 +710,10 @@ export class Commands {
704
710
  : project !== undefined
705
711
  ? project.thinkingLevel
706
712
  : lastPicked !== undefined
707
- ? last?.thinkingLevel
713
+ ? ((cwd === undefined
714
+ ? undefined
715
+ : rememberedLevel(defaults, lastPicked.provider, lastPicked.id)) ??
716
+ last?.thinkingLevel)
708
717
  : cwd === undefined
709
718
  ? settings.getDefaultThinkingLevel()
710
719
  : global?.defaultThinkingLevel) ?? "off") as ModelThinkingLevel;
@@ -1985,7 +1994,19 @@ export class Commands {
1985
1994
  );
1986
1995
  }
1987
1996
 
1997
+ // A model picked with no level takes the level Pi's TUI keeps for it; PiP's panel keeps its own.
1998
+ const remembered =
1999
+ request.model === undefined ||
2000
+ request.thinkingLevel !== undefined ||
2001
+ request.pipPanel === true
2002
+ ? undefined
2003
+ : rememberedLevel(
2004
+ piGlobalSettings(app.defaultCwd),
2005
+ request.model.provider,
2006
+ request.model.modelId,
2007
+ );
1988
2008
  const wanted = (request.thinkingLevel ??
2009
+ remembered ??
1989
2010
  current?.thinkingLevel ??
1990
2011
  "off") as ModelThinkingLevel;
1991
2012
  const thinkingLevel = model === undefined ? wanted : clampThinkingLevel(model, wanted);
@@ -58,6 +58,16 @@ export interface User {
58
58
  avatar?: number;
59
59
  }
60
60
 
61
+ /** Who is signed in, as `hello` says it to a tab, and as the app page carries it (`serveApp`). */
62
+ export function helloUser(user: User) {
63
+ return {
64
+ id: user.id,
65
+ name: user.name,
66
+ role: user.role,
67
+ ...(user.sessions === undefined ? {} : { sessions: user.sessions.map(Number) }),
68
+ };
69
+ }
70
+
61
71
  /** An invite not yet used, kept by its code's sha256 (the code itself is only shown to whoever made it). */
62
72
  export interface StoredInvite {
63
73
  codeHash: string;
@@ -6,7 +6,9 @@
6
6
  *
7
7
  * Pi Pocket rewrites `models.json` only when it is plain JSON that Pi accepts: a file with comments or trailing commas
8
8
  * (which Pi reads) or one that Pi refuses is left alone, with a message, so a hand-made file never loses anything.
9
- * Fields it does not manage (headers, compat, a model's metadata) are kept as they are.
9
+ * Fields it does not manage (headers, compat, a model's other metadata) are kept as they are. Of a model's metadata, the
10
+ * form sets only image input (`input`), thinking (`reasoning` and `thinkingLevelMap`), its context window and maximum
11
+ * output (`contextWindow`, `maxTokens`), and its price (`cost`, whose hand-made `tiers` stay).
10
12
  */
11
13
  import {
12
14
  chmodSync,
@@ -37,8 +39,65 @@ const MAX_KEY = 4000;
37
39
  /** How long, and how much, an endpoint's model list may take. */
38
40
  const DISCOVER_MS = 10_000;
39
41
  const DISCOVER_BYTES = 5_000_000;
42
+ /** The most tokens a context window or output may have, and the most dollars per million tokens. */
43
+ const MAX_TOKENS = 1_000_000_000;
44
+ const MAX_PRICE = 1_000_000;
45
+
46
+ /** Pi's thinking levels, in order: a model's `thinkingLevelMap` names what each one sends. */
47
+ export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
48
+
49
+ export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
50
+
51
+ /** One level a model thinks at, and what it sends the endpoint for it; `off` may send nothing (`""`). */
52
+ export interface ThinkingTier {
53
+ level: ThinkingLevel;
54
+ value: string;
55
+ }
56
+
57
+ /**
58
+ * The levels a model gets when thinking is turned on: the ones Pi offers a reasoning model that has no map (off to
59
+ * high, not xhigh or max), each sending its own name; off sends nothing.
60
+ */
61
+ export const DEFAULT_TIERS: ThinkingTier[] = (
62
+ ["off", "minimal", "low", "medium", "high"] as const
63
+ ).map((level) => ({ level, value: level === "off" ? "" : level }));
64
+
65
+ const MAX_TIER_VALUE = 64;
66
+
67
+ /** A model's price in dollars per million tokens: Pi's `cost`, without its tiers. */
68
+ export interface ModelPrice {
69
+ input: number;
70
+ output: number;
71
+ cacheRead: number;
72
+ cacheWrite: number;
73
+ }
40
74
 
41
75
  export interface CustomModel {
76
+ id: string;
77
+ /** Its context window in tokens, or null for Pi's default. Left out of a change: as it was. */
78
+ contextWindow?: number | null;
79
+ /** The most tokens it writes in one answer, or null for Pi's default. Left out of a change: as it was. */
80
+ maxTokens?: number | null;
81
+ /** It sees images (`input` has `"image"`). Left out of a change: as it was. */
82
+ images?: boolean;
83
+ /** The levels it thinks at, or null when it does not think. Left out of a change: as it was. */
84
+ thinking?: ThinkingTier[] | null;
85
+ /** What it costs, or null when it costs nothing. Left out of a change: as it was. */
86
+ cost?: ModelPrice | null;
87
+ }
88
+
89
+ /** A model as the form sees it: what the endpoint says it can do, read back from `models.json`. */
90
+ export interface CustomModelInfo {
91
+ id: string;
92
+ images: boolean;
93
+ thinking: ThinkingTier[] | null;
94
+ contextWindow: number | null;
95
+ maxTokens: number | null;
96
+ cost: ModelPrice | null;
97
+ }
98
+
99
+ /** A model an endpoint lists, with its context window when it is a vLLM server (`max_model_len`). */
100
+ export interface ListedModel {
42
101
  id: string;
43
102
  contextWindow?: number;
44
103
  }
@@ -47,7 +106,7 @@ export interface CustomProvider {
47
106
  id: string;
48
107
  name: string;
49
108
  baseUrl: string;
50
- models: string[];
109
+ models: CustomModelInfo[];
51
110
  /** Where its key is: Pi's sign-ins, `models.json` (a hand-made entry), none (the placeholder), or nowhere. */
52
111
  key: "stored" | "file" | "none" | "missing";
53
112
  }
@@ -101,7 +160,7 @@ function baseUrlOf(value: unknown): string {
101
160
  return raw.replace(/\/+$/, "");
102
161
  }
103
162
 
104
- /** The models asked for: ids, each once, with a context window when the endpoint said one. */
163
+ /** The models asked for: ids, each once, with what the form says of each. */
105
164
  function modelsOf(value: unknown): CustomModel[] {
106
165
  if (!Array.isArray(value)) {
107
166
  throw new HttpError(400, "models must be a list.");
@@ -124,19 +183,225 @@ function modelsOf(value: unknown): CustomModel[] {
124
183
  );
125
184
  }
126
185
 
127
- const window = entry?.contextWindow;
186
+ const images = entry?.images;
187
+
188
+ if (images !== undefined && typeof images !== "boolean") {
189
+ throw new HttpError(400, `${id}: images must be true or false.`);
190
+ }
191
+
192
+ const window = tokensOf(id, entry?.contextWindow, "context window");
193
+ const most = tokensOf(id, entry?.maxTokens, "maximum output");
128
194
 
129
195
  seen.set(id, {
130
196
  id,
131
- ...(typeof window === "number" && Number.isFinite(window) && window > 0
132
- ? { contextWindow: Math.floor(window) }
133
- : {}),
197
+ ...(window === undefined ? {} : { contextWindow: window }),
198
+ ...(most === undefined ? {} : { maxTokens: most }),
199
+ ...(images === undefined ? {} : { images }),
200
+ ...(entry?.thinking === undefined ? {} : { thinking: tiersOf(id, entry.thinking) }),
201
+ ...(entry?.cost === undefined ? {} : { cost: priceOf(id, entry.cost) }),
134
202
  });
135
203
  }
136
204
 
137
205
  return [...seen.values()];
138
206
  }
139
207
 
208
+ /** A count of tokens as asked for: a whole number, null for Pi's default, or undefined to leave it as it is. */
209
+ function tokensOf(id: string, value: unknown, name: string): number | null | undefined {
210
+ if (value === undefined || value === null) {
211
+ return value;
212
+ }
213
+
214
+ if (
215
+ typeof value !== "number" ||
216
+ !Number.isSafeInteger(value) ||
217
+ value < 1 ||
218
+ value > MAX_TOKENS
219
+ ) {
220
+ throw new HttpError(
221
+ 400,
222
+ `${id}: the ${name} must be a whole number of tokens, from 1 to ${MAX_TOKENS.toLocaleString("en-US")}.`,
223
+ );
224
+ }
225
+
226
+ return value;
227
+ }
228
+
229
+ /** A price as asked for: dollars per million tokens, input and output given and the cache ones 0 when not; or null. */
230
+ export function priceOf(id: string, value: unknown): ModelPrice | null {
231
+ if (value === null) {
232
+ return null;
233
+ }
234
+
235
+ const given = (typeof value === "object" ? value : {}) as Json;
236
+
237
+ if (given.input === undefined || given.output === undefined) {
238
+ throw new HttpError(400, `${id}: a price needs its input and output dollars.`);
239
+ }
240
+
241
+ const rate = (field: keyof ModelPrice): number => {
242
+ const each = given[field] ?? 0;
243
+
244
+ if (typeof each !== "number" || !Number.isFinite(each) || each < 0 || each > MAX_PRICE) {
245
+ throw new HttpError(
246
+ 400,
247
+ `${id}: a price is dollars per million tokens, from 0 to ${MAX_PRICE.toLocaleString("en-US")}.`,
248
+ );
249
+ }
250
+
251
+ return each;
252
+ };
253
+
254
+ return {
255
+ input: rate("input"),
256
+ output: rate("output"),
257
+ cacheRead: rate("cacheRead"),
258
+ cacheWrite: rate("cacheWrite"),
259
+ };
260
+ }
261
+
262
+ /** A model entry's price as Pi reads it, without its tiers; null when it has none (Pi then counts it free). */
263
+ export function priceOfEntry(model: Json): ModelPrice | null {
264
+ const cost = model.cost as Json | null | undefined;
265
+
266
+ if (typeof cost?.input !== "number" || typeof cost.output !== "number") {
267
+ return null;
268
+ }
269
+
270
+ const rate = (value: unknown) => (typeof value === "number" ? value : 0);
271
+
272
+ return {
273
+ input: cost.input,
274
+ output: cost.output,
275
+ cacheRead: rate(cost.cacheRead),
276
+ cacheWrite: rate(cost.cacheWrite),
277
+ };
278
+ }
279
+
280
+ /** A model's thinking levels as asked for: null (it does not think), or each of Pi's levels at most once. */
281
+ export function tiersOf(id: string, value: unknown): ThinkingTier[] | null {
282
+ if (value === null) {
283
+ return null;
284
+ }
285
+
286
+ if (!Array.isArray(value) || value.length === 0) {
287
+ throw new HttpError(400, `${id}: give its thinking levels, or turn thinking off.`);
288
+ }
289
+
290
+ const tiers = new Map<ThinkingLevel, string>();
291
+
292
+ for (const each of value as (Json | null)[]) {
293
+ const level = each?.level;
294
+ const sent = typeof each?.value === "string" ? each.value.trim() : undefined;
295
+
296
+ if (!THINKING_LEVELS.includes(level as ThinkingLevel)) {
297
+ throw new HttpError(
298
+ 400,
299
+ `${id}: a thinking level is one of ${THINKING_LEVELS.join(", ")}.`,
300
+ );
301
+ }
302
+
303
+ if (tiers.has(level as ThinkingLevel)) {
304
+ throw new HttpError(400, `${id}: the level ${String(level)} is there twice.`);
305
+ }
306
+
307
+ if (
308
+ sent === undefined ||
309
+ sent.length > MAX_TIER_VALUE ||
310
+ (sent === "" && level !== "off")
311
+ ) {
312
+ throw new HttpError(
313
+ 400,
314
+ `${id}: the level ${String(level)} needs a value of 1 to ${String(MAX_TIER_VALUE)} characters.`,
315
+ );
316
+ }
317
+
318
+ tiers.set(level as ThinkingLevel, sent);
319
+ }
320
+
321
+ return THINKING_LEVELS.filter((level) => tiers.has(level)).map((level) => ({
322
+ level,
323
+ value: tiers.get(level)!,
324
+ }));
325
+ }
326
+
327
+ /**
328
+ * A model's thinking levels as Pi reads its entry: none without `reasoning`; else each level the map does not mark
329
+ * null, sending what the map says. A level the map leaves out sends its own name, as Pi does, except xhigh and max,
330
+ * which Pi then leaves out; and off, which sends nothing.
331
+ */
332
+ export function tiersOfEntry(model: Json): ThinkingTier[] | null {
333
+ if (model.reasoning !== true) {
334
+ return null;
335
+ }
336
+
337
+ const map = (
338
+ typeof model.thinkingLevelMap === "object" && model.thinkingLevelMap !== null
339
+ ? model.thinkingLevelMap
340
+ : {}
341
+ ) as Record<string, unknown>;
342
+
343
+ return THINKING_LEVELS.flatMap((level): ThinkingTier[] => {
344
+ const sent = map[level];
345
+
346
+ if (sent === null || (sent === undefined && (level === "xhigh" || level === "max"))) {
347
+ return [];
348
+ }
349
+
350
+ if (typeof sent === "string") {
351
+ return [{ level, value: sent }];
352
+ }
353
+
354
+ return [{ level, value: level === "off" ? "" : level }];
355
+ });
356
+ }
357
+
358
+ /**
359
+ * Sets what the form changes in a model's entry: image input, thinking, context window, maximum output, and price.
360
+ * Other fields stay as they are, and so do the price tiers of a hand-made price.
361
+ */
362
+ function applyForm(entry: Json, model: CustomModel): Json {
363
+ for (const field of ["contextWindow", "maxTokens"] as const) {
364
+ if (model[field] === null) {
365
+ delete entry[field];
366
+ } else if (model[field] !== undefined) {
367
+ entry[field] = model[field];
368
+ }
369
+ }
370
+
371
+ if (model.cost === null) {
372
+ delete entry.cost;
373
+ } else if (model.cost !== undefined) {
374
+ const tiers = (entry.cost as Json | null | undefined)?.tiers;
375
+
376
+ entry.cost = { ...model.cost, ...(Array.isArray(tiers) ? { tiers } : {}) };
377
+ }
378
+
379
+ if (model.images === true) {
380
+ entry.input = ["text", "image"];
381
+ } else if (model.images === false) {
382
+ delete entry.input;
383
+ }
384
+
385
+ if (model.thinking === null) {
386
+ delete entry.reasoning;
387
+ delete entry.thinkingLevelMap;
388
+ } else if (model.thinking !== undefined) {
389
+ const sent = new Map(model.thinking.map((tier) => [tier.level, tier.value]));
390
+
391
+ entry.reasoning = true;
392
+ // Every level named: null where it is not one of the model's. Off without a value sends nothing.
393
+ entry.thinkingLevelMap = Object.fromEntries(
394
+ THINKING_LEVELS.flatMap((level) => {
395
+ const value = sent.get(level);
396
+
397
+ return value === "" ? [] : [[level, value ?? null]];
398
+ }),
399
+ );
400
+ }
401
+
402
+ return entry;
403
+ }
404
+
140
405
  /** The text of models.json as it is now; undefined when there is none. */
141
406
  function rawModels(): string | undefined {
142
407
  try {
@@ -164,15 +429,18 @@ export function idFor(name: string, taken: (id: string) => boolean): string {
164
429
  return id;
165
430
  }
166
431
 
167
- /** The ids of an endpoint's models, from an OpenAI `/models` answer, with vLLM's context windows. */
168
- export function parseModelList(body: unknown): CustomModel[] {
432
+ /**
433
+ * The ids of an endpoint's models, from an OpenAI `/models` answer, with vLLM's context windows (`max_model_len`). Nothing
434
+ * else is read: model lists have no common way to say what a model can do or costs, so the form leaves that to the owner.
435
+ */
436
+ export function parseModelList(body: unknown): ListedModel[] {
169
437
  const list = (body as Json | null)?.data;
170
438
 
171
439
  if (!Array.isArray(list)) {
172
440
  throw new Error("The answer has no list of models.");
173
441
  }
174
442
 
175
- const models = new Map<string, CustomModel>();
443
+ const models = new Map<string, ListedModel>();
176
444
 
177
445
  for (const entry of list as (Json | null)[]) {
178
446
  const id = entry?.id;
@@ -181,7 +449,7 @@ export function parseModelList(body: unknown): CustomModel[] {
181
449
  if (typeof id === "string" && id !== "" && id.length <= MAX_ID) {
182
450
  models.set(id, {
183
451
  id,
184
- ...(typeof window === "number" && window >= 1
452
+ ...(typeof window === "number" && window >= 1 && window <= MAX_TOKENS
185
453
  ? { contextWindow: Math.floor(window) }
186
454
  : {}),
187
455
  });
@@ -221,9 +489,17 @@ export class CustomProviders {
221
489
  id,
222
490
  name: typeof entry.name === "string" ? entry.name : id,
223
491
  baseUrl: entry.baseUrl as string,
224
- models: (Array.isArray(entry.models) ? (entry.models as Json[]) : [])
225
- .map((model) => model?.id)
226
- .filter((model): model is string => typeof model === "string"),
492
+ models: (Array.isArray(entry.models) ? (entry.models as (Json | null)[]) : [])
493
+ .filter((model): model is Json => typeof model?.id === "string")
494
+ .map((model) => ({
495
+ id: model.id as string,
496
+ images: Array.isArray(model.input) && model.input.includes("image"),
497
+ thinking: tiersOfEntry(model),
498
+ contextWindow:
499
+ typeof model.contextWindow === "number" ? model.contextWindow : null,
500
+ maxTokens: typeof model.maxTokens === "number" ? model.maxTokens : null,
501
+ cost: priceOfEntry(model),
502
+ })),
227
503
  key: this.#keyOf(id, entry),
228
504
  }))
229
505
  .sort((a, b) => a.name.localeCompare(b.name));
@@ -316,9 +592,11 @@ export class CustomProviders {
316
592
  ]),
317
593
  );
318
594
 
319
- entry.models = modelsOf(input.models).map(
320
- (model) => before.get(model.id) ?? entryOf(model),
321
- );
595
+ entry.models = modelsOf(input.models).map((model) => {
596
+ const kept = before.get(model.id);
597
+
598
+ return kept === undefined ? entryOf(model) : applyForm({ ...kept }, model);
599
+ });
322
600
  }
323
601
 
324
602
  if (key === NO_KEY) {
@@ -380,7 +658,7 @@ export class CustomProviders {
380
658
  * Ask an endpoint for its models (`GET <baseUrl>/models`), with the key given, or else the saved endpoint's own.
381
659
  * The owner's to ask, so a local or private address is allowed: that is where such servers often are.
382
660
  */
383
- discover(input: { baseUrl?: unknown; apiKey?: unknown; id?: unknown }): Promise<CustomModel[]> {
661
+ discover(input: { baseUrl?: unknown; apiKey?: unknown; id?: unknown }): Promise<ListedModel[]> {
384
662
  // After any save in progress: a saved key is read with the address it belongs to.
385
663
  return this.#serial(() => this.#discover(input));
386
664
  }
@@ -389,7 +667,7 @@ export class CustomProviders {
389
667
  baseUrl?: unknown;
390
668
  apiKey?: unknown;
391
669
  id?: unknown;
392
- }): Promise<CustomModel[]> {
670
+ }): Promise<ListedModel[]> {
393
671
  const baseUrl = baseUrlOf(input.baseUrl);
394
672
  const headers = new Headers({ accept: "application/json" });
395
673
  let key =
@@ -682,10 +960,7 @@ async function refusal(path: string): Promise<string | undefined> {
682
960
  }
683
961
 
684
962
  function entryOf(model: CustomModel): Json {
685
- return {
686
- id: model.id,
687
- ...(model.contextWindow === undefined ? {} : { contextWindow: model.contextWindow }),
688
- };
963
+ return applyForm({ id: model.id }, model);
689
964
  }
690
965
 
691
966
  /** A response's text, refused past `max` bytes. */
@@ -37,6 +37,11 @@ export type SessionMeta = {
37
37
  forkedFrom?: { id: number; entryId?: number };
38
38
  /** The session that started this one (`linked-sessions.ts`): a link only, which gives no access and owns nothing. */
39
39
  linkedFrom?: { id: number };
40
+ /**
41
+ * False: this session, as a lead, takes no run-end answers from the sessions it started (`linked-sessions.ts`,
42
+ * `reports`), and a message from it asks the target to send its answer. Absent: it takes them.
43
+ */
44
+ linkedReports?: false;
40
45
  /** The most Pi may spend here, in dollars, subagents included. */
41
46
  budget?: number;
42
47
  /** The git worktree the session works in, when it has one of its own. */
@@ -148,11 +153,13 @@ export const LinkedSessionCallsDoc = defineDoc<{
148
153
  by?: string;
149
154
  at: number;
150
155
  /**
151
- * What a stop or an archive returned, so a repeat gives that and changes nothing again. `stopping`: the stop
152
- * has not finished.
156
+ * What a stop, an archive or a reports switch returned, so a repeat gives that and changes nothing again.
157
+ * `stopping`: the stop has not finished. A reports switch names its own session in `conversationId`.
153
158
  */
154
159
  result?:
155
- { busy: boolean; stopping?: boolean } | { archived: boolean; repeating: number };
160
+ | { busy: boolean; stopping?: boolean }
161
+ | { archived: boolean; repeating: number }
162
+ | { take: boolean };
156
163
  }
157
164
  >;
158
165
  }>({