@evandu/super-pi 0.1.187 → 0.1.188

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.
@@ -251,6 +251,52 @@ function textBodyReader() {
251
251
  finish: () => text + decoder.decode(),
252
252
  };
253
253
  }
254
+ /**
255
+ * THE READ SCOPE FOR A SESSION'S STATUS, WHICH IS DELIBERATELY WIDER THAN THE WRITE SCOPE.
256
+ *
257
+ * SEEING IS NOT ORDERING. A session in the same workspace may read another session's STATUS - is
258
+ * it running, is it stuck, how far has it got - without having any authority over it. The actions
259
+ * that spend somebody else's work - dispatch, stop, resume, report - stay bound to the tree edge,
260
+ * where the caller's DIRECT child is the only reachable session. Keeping the two apart is what
261
+ * lets a supervisor watch a whole project without being able to take it over.
262
+ *
263
+ * WHY IT IS A RULE AND NOT AN ACCIDENT. The rule was tightened once by accident: the read was put
264
+ * behind the same check as the write, so a session could not look at a peer it was supposed to be
265
+ * coordinating with, and the fix for "I cannot see my project" was to grant dispatch authority
266
+ * instead - which is how a supervisor ends up ordering everybody around. Reading and ordering are
267
+ * different powers and they get different boundaries.
268
+ *
269
+ * WHAT IS STILL BOUNDED: another session's FINAL OUTPUT. A status is a fact about the work; the
270
+ * output is the work itself, and reading somebody else's work is not supervision.
271
+ */
272
+ const verifyStatusReadScope = (options) => {
273
+ const { store, callerConversationId, targetConversationId } = options;
274
+ const caller = callerConversationId?.trim();
275
+ if (!caller)
276
+ return { ok: false, status: 403, error: "调用方会话为空,拒绝读取状态。" };
277
+ const callerConversation = store.conversation(caller);
278
+ if (!callerConversation?.workspaceId) {
279
+ return { ok: false, status: 403, error: `调用方会话 ${caller} 不存在或未关联有效工作区,拒绝读取状态。` };
280
+ }
281
+ const target = store.conversation(targetConversationId);
282
+ if (!target)
283
+ return { ok: false, status: 400, error: `找不到会话:${targetConversationId}` };
284
+ if (target.workspaceId !== callerConversation.workspaceId) {
285
+ return {
286
+ ok: false,
287
+ status: 403,
288
+ error: `调用方会话 ${caller} 所在工作区为 ${callerConversation.workspaceId},目标会话 ${targetConversationId} 所在工作区为 ${target.workspaceId},拒绝跨工作区读取状态。`,
289
+ };
290
+ }
291
+ if (options.includeOutput && target.parentConversationId !== caller) {
292
+ return {
293
+ ok: false,
294
+ status: 403,
295
+ error: `读取会话 ${targetConversationId} 的最终输出只限它的直接上级;同工作区内的状态读取不受此限制。`,
296
+ };
297
+ }
298
+ return { ok: true };
299
+ };
254
300
  /**
255
301
  * THE REQUEST BODY AS TEXT, DECODED ACROSS CHUNK BOUNDARIES.
256
302
  *
@@ -1856,7 +1902,15 @@ export function createHttpServer(options) {
1856
1902
  if (action === "status") {
1857
1903
  if (!body.conversationId)
1858
1904
  throw new Error("status requires conversationId");
1859
- const scope = verifyTargetScope(body.conversationId, "读取");
1905
+ // THE READ IS WIDER THAN THE WRITE, ON PURPOSE. Status is a fact about the work, not
1906
+ // authority over it: a session may look at any session in its own workspace, while only
1907
+ // its DIRECT child may be dispatched to, stopped or resumed. See `verifyStatusReadScope`.
1908
+ const scope = verifyStatusReadScope({
1909
+ store: context.store,
1910
+ callerConversationId,
1911
+ targetConversationId: body.conversationId,
1912
+ includeOutput: body.includeOutput,
1913
+ });
1860
1914
  if (!scope.ok) {
1861
1915
  json(scope.status, { error: scope.error });
1862
1916
  return;
@@ -2005,6 +2059,58 @@ export function createHttpServer(options) {
2005
2059
  json(200, { ...result, ok: true });
2006
2060
  return;
2007
2061
  }
2062
+ if (action === "reminder") {
2063
+ // THE REMINDER LIVES ON THE CALLING CONVERSATION. `callerConversationId` is the id the
2064
+ // capability above was verified against, so this is the session that asked for the timer
2065
+ // and the session the note comes back to - there is no way to aim a reminder at somebody
2066
+ // else's conversation, because the body does not get to choose the target.
2067
+ const reminders = context.sessionReminderService;
2068
+ if (!reminders) {
2069
+ json(503, { error: "提醒服务未就绪" });
2070
+ return;
2071
+ }
2072
+ const subaction = (body.subaction ?? "create").trim();
2073
+ if (subaction === "create") {
2074
+ const delaySeconds = Number(body.delaySeconds ?? body.seconds);
2075
+ if (!Number.isFinite(delaySeconds) || delaySeconds <= 0) {
2076
+ json(400, { error: "提醒需要正的秒数:请传 delaySeconds(或 seconds)。" });
2077
+ return;
2078
+ }
2079
+ const note = typeof body.note === "string" ? body.note.trim() : "";
2080
+ if (!note) {
2081
+ json(400, { error: "提醒内容不能为空:note 要写清楚提醒什么。" });
2082
+ return;
2083
+ }
2084
+ try {
2085
+ const created = reminders.createReminder({ conversationId: callerConversationId, delaySeconds, note });
2086
+ json(200, { ...created, ok: true });
2087
+ }
2088
+ catch (error) {
2089
+ json(400, { error: error instanceof Error ? error.message : "创建提醒失败" });
2090
+ }
2091
+ return;
2092
+ }
2093
+ if (subaction === "cancel") {
2094
+ const reminderId = typeof body.reminderId === "string" ? body.reminderId.trim() : "";
2095
+ if (!reminderId) {
2096
+ json(400, { error: "取消提醒需要 reminderId。" });
2097
+ return;
2098
+ }
2099
+ const result = reminders.cancelReminder(reminderId, callerConversationId);
2100
+ if (!result.ok) {
2101
+ json(404, { error: result.error ?? "找不到这条提醒。" });
2102
+ return;
2103
+ }
2104
+ json(200, { ok: true, cancelled: true, reminderId });
2105
+ return;
2106
+ }
2107
+ if (subaction === "list") {
2108
+ json(200, { ok: true, reminders: reminders.listReminders(callerConversationId) });
2109
+ return;
2110
+ }
2111
+ json(400, { error: `不支持的提醒操作:${subaction}` });
2112
+ return;
2113
+ }
2008
2114
  json(400, { error: `不支持的编排操作:${action}` });
2009
2115
  }
2010
2116
  catch (error) {
@@ -2131,12 +2237,13 @@ export function createHttpServer(options) {
2131
2237
  return;
2132
2238
  }
2133
2239
  const store = context.store;
2134
- // THE SAME SCOPE RULE AS THE POST ACTION: the target must be the caller's DIRECT child.
2135
- const scope = verifyDirectChildScope({
2240
+ // THE SAME READ SCOPE AS THE POST ACTION: status is visible across the caller's own
2241
+ // workspace, and only the direct-child rule governs who may be ordered around.
2242
+ const scope = verifyStatusReadScope({
2136
2243
  store,
2137
2244
  callerConversationId,
2138
2245
  targetConversationId: conversationId,
2139
- verb: "读取",
2246
+ includeOutput: url.searchParams.get("includeOutput") === "true",
2140
2247
  });
2141
2248
  if (!scope.ok) {
2142
2249
  response.writeHead(scope.status, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: scope.error }));
@@ -26,6 +26,7 @@ import { ConversationService } from "./application/conversation-service.js";
26
26
  import { ScheduledTaskService } from "./application/scheduled-task-service.js";
27
27
  import { SessionLedger } from "./session-ledger.js";
28
28
  import { SessionOrchestratorService } from "./application/session-orchestrator-service.js";
29
+ import { SessionReminderService } from "./application/session-reminder-service.js";
29
30
  import { ProjectService } from "./application/project-service.js";
30
31
  import { WorkspaceService } from "./application/workspace-service.js";
31
32
  import { CommandHandler } from "./command-handler.js";
@@ -309,6 +310,7 @@ runService.setExecService(execService);
309
310
  */
310
311
  const scheduledTaskService = new ScheduledTaskService(store, runService, conversationService, broadcaster);
311
312
  const sessionLedger = new SessionLedger();
313
+ const sessionReminderService = new SessionReminderService(runService, store);
312
314
  const sessionOrchestratorService = new SessionOrchestratorService(store, conversationService, runService, sessionLedger, broadcaster, undefined, uploadsDir);
313
315
  /**
314
316
  * THE PROJECT SERVICE IS TOLD HOW TO ASK WHAT AN AGENT IS.
@@ -345,6 +347,7 @@ const serverContext = {
345
347
  providerService,
346
348
  scheduledTaskService,
347
349
  sessionLedger,
350
+ sessionReminderService,
348
351
  sessionOrchestratorService,
349
352
  projectService,
350
353
  execService,
@@ -0,0 +1,14 @@
1
+ /**
2
+ * JSONC COMMENTS, STRIPPED THE WAY PI STRIPS THEM.
3
+ *
4
+ * Pi reads `models.json` and `models-store.json` with comments allowed, so a person may well have
5
+ * written comments in them - and Super Pi has to be able to READ those files to merge into them and
6
+ * to learn what a model really costs in context. A naive strip would corrupt a string that contains
7
+ * `//` (a base URL with a path, an api key with a slash), so this walks the text and tracks whether
8
+ * it is inside a string.
9
+ *
10
+ * IT LIVES HERE, NOT IN `providers.ts`, because two unrelated modules need it: the provider registry
11
+ * reads `models.json`, and the model store reads `models-store.json`. Keeping it in one place is
12
+ * what makes "reuse it, do not write a second one" true rather than aspirational.
13
+ */
14
+ export declare function stripJsonComments(text: string): string;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * JSONC COMMENTS, STRIPPED THE WAY PI STRIPS THEM.
3
+ *
4
+ * Pi reads `models.json` and `models-store.json` with comments allowed, so a person may well have
5
+ * written comments in them - and Super Pi has to be able to READ those files to merge into them and
6
+ * to learn what a model really costs in context. A naive strip would corrupt a string that contains
7
+ * `//` (a base URL with a path, an api key with a slash), so this walks the text and tracks whether
8
+ * it is inside a string.
9
+ *
10
+ * IT LIVES HERE, NOT IN `providers.ts`, because two unrelated modules need it: the provider registry
11
+ * reads `models.json`, and the model store reads `models-store.json`. Keeping it in one place is
12
+ * what makes "reuse it, do not write a second one" true rather than aspirational.
13
+ */
14
+ export function stripJsonComments(text) {
15
+ let out = "";
16
+ let inString = false;
17
+ let inLineComment = false;
18
+ let inBlockComment = false;
19
+ for (let index = 0; index < text.length; index++) {
20
+ const char = text[index];
21
+ const next = text[index + 1];
22
+ if (inLineComment) {
23
+ if (char === "\n") {
24
+ inLineComment = false;
25
+ out += char;
26
+ }
27
+ else
28
+ out += " ";
29
+ continue;
30
+ }
31
+ if (inBlockComment) {
32
+ if (char === "*" && next === "/") {
33
+ inBlockComment = false;
34
+ out += " ";
35
+ index++;
36
+ }
37
+ else
38
+ out += char === "\n" ? "\n" : " ";
39
+ continue;
40
+ }
41
+ if (inString) {
42
+ out += char;
43
+ if (char === "\\" && next !== undefined) {
44
+ out += next;
45
+ index++;
46
+ }
47
+ else if (char === "\"")
48
+ inString = false;
49
+ continue;
50
+ }
51
+ if (char === "\"") {
52
+ inString = true;
53
+ out += char;
54
+ continue;
55
+ }
56
+ if (char === "/" && next === "/") {
57
+ inLineComment = true;
58
+ out += " ";
59
+ index++;
60
+ continue;
61
+ }
62
+ if (char === "/" && next === "*") {
63
+ inBlockComment = true;
64
+ out += " ";
65
+ index++;
66
+ continue;
67
+ }
68
+ out += char;
69
+ }
70
+ return out;
71
+ }
@@ -1,3 +1,11 @@
1
+ import { type ModelStore } from "./models-store.js";
2
+ /**
3
+ * THE DEFAULTS SUPER PI STAMPS WHEN IT DISCOVERS A MODEL. `providers.ts` writes these into
4
+ * `models.json` for every model the provider did not describe, and they are NOT a person's decision
5
+ * - they are a placeholder. The store's real number must outrank them.
6
+ */
7
+ export declare const SUPER_PI_DEFAULT_CONTEXT_WINDOW = 128000;
8
+ export declare const SUPER_PI_DEFAULT_MAX_TOKENS = 16384;
1
9
  /** One model's declared window, as the person's file states it. */
2
10
  export type DeclaredWindow = {
3
11
  provider: string;
@@ -44,3 +52,29 @@ export declare function effectiveContextWindow(declared: Map<string, number>, pr
44
52
  * simply "Super Pi has no opinion about this model's window" - which is where it started.
45
53
  */
46
54
  export declare function readDeclaredWindows(agentDir: string): Map<string, number>;
55
+ /** The windows the catalogue (`models-store.json`) declares, keyed the same way as `declared`. */
56
+ export declare function storeWindows(store: ModelStore): Map<string, number>;
57
+ /**
58
+ * Read the catalogue's declared windows, alongside the person's.
59
+ *
60
+ * The catalogue is the truth the provider self-reports; it is re-read only when the file changes.
61
+ */
62
+ export declare function readStoreWindows(agentDir: string): ModelStore;
63
+ /**
64
+ * THE WINDOW A MODEL REALLY GETS, arbitrated across the three sources that each claim to know it.
65
+ *
66
+ * PRECEDENCE, HIGHEST FIRST:
67
+ *
68
+ * 1. A NON-DEFAULT value in the person's `models.json` — somebody typed it, so it is a decision.
69
+ * (This is the original rule, unchanged.)
70
+ * 2. The CATALOGUE (`models-store.json`) — the provider's self-report. This is the truth for a
71
+ * model Super Pi only knows from its own default. `MiniMax-M3` is the case in point: the
72
+ * catalogue says 1,000,000 while every `models.json` entry Super Pi wrote says the default
73
+ * 128,000.
74
+ * 3. The `reported` value the model object already carries, then nothing (`undefined`).
75
+ *
76
+ * THE OLD "SAME MODEL TAKE THE SMALLEST" RULE IS GONE. It was written for a catalogue that lies
77
+ * big; on this machine the catalogue is right and the stamped default is what was too small, so
78
+ * taking the smallest is exactly how a million-token model ended up believing it had 128,000.
79
+ */
80
+ export declare function arbitrateContextWindow(declared: Map<string, number>, store: ModelStore, provider: string, modelId: string, reported?: number): number | undefined;
@@ -32,6 +32,14 @@
32
32
  */
33
33
  import { readFileSync } from "node:fs";
34
34
  import { join } from "node:path";
35
+ import { readModelStore, storeWindowFor } from "./models-store.js";
36
+ /**
37
+ * THE DEFAULTS SUPER PI STAMPS WHEN IT DISCOVERS A MODEL. `providers.ts` writes these into
38
+ * `models.json` for every model the provider did not describe, and they are NOT a person's decision
39
+ * - they are a placeholder. The store's real number must outrank them.
40
+ */
41
+ export const SUPER_PI_DEFAULT_CONTEXT_WINDOW = 128000;
42
+ export const SUPER_PI_DEFAULT_MAX_TOKENS = 16384;
35
43
  /**
36
44
  * The windows the person's `models.json` declares, keyed by `provider/modelId`.
37
45
  *
@@ -119,3 +127,71 @@ export function readDeclaredWindows(agentDir) {
119
127
  return new Map();
120
128
  }
121
129
  }
130
+ /** The windows the catalogue (`models-store.json`) declares, keyed the same way as `declared`. */
131
+ export function storeWindows(store) {
132
+ const out = new Map();
133
+ for (const [key, entry] of store.byProviderModel) {
134
+ if (entry.contextWindow !== undefined)
135
+ out.set(key, entry.contextWindow);
136
+ }
137
+ return out;
138
+ }
139
+ /**
140
+ * Read the catalogue's declared windows, alongside the person's.
141
+ *
142
+ * The catalogue is the truth the provider self-reports; it is re-read only when the file changes.
143
+ */
144
+ export function readStoreWindows(agentDir) {
145
+ return readModelStore(agentDir);
146
+ }
147
+ /**
148
+ * Is a `models.json` window a PERSON's decision, or just Super Pi's own default stamped at import?
149
+ *
150
+ * Only a number somebody actually typed is authoritative. The value Super Pi writes when the
151
+ * provider said nothing (128000 / 16384) is a placeholder, and a placeholder never outranks the
152
+ * catalogue's real figure.
153
+ */
154
+ function isDeliberateWindow(window) {
155
+ return window !== undefined && window !== SUPER_PI_DEFAULT_CONTEXT_WINDOW;
156
+ }
157
+ /**
158
+ * THE WINDOW A MODEL REALLY GETS, arbitrated across the three sources that each claim to know it.
159
+ *
160
+ * PRECEDENCE, HIGHEST FIRST:
161
+ *
162
+ * 1. A NON-DEFAULT value in the person's `models.json` — somebody typed it, so it is a decision.
163
+ * (This is the original rule, unchanged.)
164
+ * 2. The CATALOGUE (`models-store.json`) — the provider's self-report. This is the truth for a
165
+ * model Super Pi only knows from its own default. `MiniMax-M3` is the case in point: the
166
+ * catalogue says 1,000,000 while every `models.json` entry Super Pi wrote says the default
167
+ * 128,000.
168
+ * 3. The `reported` value the model object already carries, then nothing (`undefined`).
169
+ *
170
+ * THE OLD "SAME MODEL TAKE THE SMALLEST" RULE IS GONE. It was written for a catalogue that lies
171
+ * big; on this machine the catalogue is right and the stamped default is what was too small, so
172
+ * taking the smallest is exactly how a million-token model ended up believing it had 128,000.
173
+ */
174
+ export function arbitrateContextWindow(declared, store, provider, modelId, reported) {
175
+ const exact = declared.get(`${provider}/${modelId}`);
176
+ if (isDeliberateWindow(exact))
177
+ return exact;
178
+ // A deliberate cross-provider declaration still wins over the catalogue.
179
+ let deliberate;
180
+ for (const [key, window] of declared) {
181
+ const slash = key.indexOf("/");
182
+ if (slash < 0 || key.slice(slash + 1) !== modelId)
183
+ continue;
184
+ if (!isDeliberateWindow(window))
185
+ continue;
186
+ if (deliberate === undefined || window > deliberate)
187
+ deliberate = window;
188
+ }
189
+ if (deliberate !== undefined)
190
+ return deliberate;
191
+ const storeEntry = storeWindowFor(store, modelId, provider);
192
+ if (storeEntry?.contextWindow !== undefined)
193
+ return storeEntry.contextWindow;
194
+ if (isDeliberateWindow(reported))
195
+ return reported;
196
+ return exact ?? deliberate ?? storeEntry?.contextWindow ?? reported;
197
+ }
@@ -0,0 +1,36 @@
1
+ /** What the catalogue says about one model. Either number may be absent. */
2
+ export type StoreEntry = {
3
+ contextWindow?: number;
4
+ maxTokens?: number;
5
+ };
6
+ /**
7
+ * The catalogue, indexed twice.
8
+ *
9
+ * `byProviderModel` is keyed `provider/modelId` and `byModel` is keyed by the model id alone. The
10
+ * second index exists because a model id belongs to the MODEL, not to the endpoint: the catalogue
11
+ * declares `MiniMax-M3` under both `minimax` and `minimax-cn`, and a session may run under either
12
+ * provider id, or under a provider id the user made up.
13
+ */
14
+ export type ModelStore = {
15
+ byModel: Map<string, StoreEntry>;
16
+ byProviderModel: Map<string, StoreEntry>;
17
+ };
18
+ /** The file Pi writes the catalogue into, next to the file it writes providers into. */
19
+ export declare function modelStorePath(agentDir: string): string;
20
+ export declare function readModelStore(agentDir: string): ModelStore;
21
+ /**
22
+ * The catalogue as data.
23
+ *
24
+ * The shape Pi writes is `{ <provider id>: { models: [{ id, contextWindow, maxTokens }] } }`, and a
25
+ * shape with the providers nested one level deeper is read too - Pi has moved this file around
26
+ * before, and a catalogue in a slightly different shape is still a catalogue.
27
+ */
28
+ export declare function parseModelStore(raw: unknown): ModelStore;
29
+ /**
30
+ * What the catalogue says about one model.
31
+ *
32
+ * The provider-specific entry is preferred when the catalogue has one, because a provider may serve
33
+ * a model under a different limit than another provider does. The model-id entry is the fallback,
34
+ * and it is what makes the lookup work for a provider id the user invented.
35
+ */
36
+ export declare function storeWindowFor(store: ModelStore | undefined, modelId: string, providerId?: string): StoreEntry | undefined;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * THE CATALOGUE PI FETCHED, AND WHAT IT SAYS A MODEL REALLY HAS.
3
+ *
4
+ * WHAT THIS FILE IS. `~/.pi/agent/models-store.json` is Pi's own copy of every provider's model
5
+ * list, refreshed when Pi asks the provider what it serves. Each entry carries the two numbers
6
+ * that decide how a model actually behaves: `contextWindow` (how much conversation fits) and
7
+ * `maxTokens` (how much a SINGLE answer may be). Those are different things and they stay
8
+ * different here - the store keeps them apart, and so does everything that reads them.
9
+ *
10
+ * WHY IT IS THE TRUTH. Measured on this machine, the store says `MiniMax-M3` has a context window
11
+ * of 1,000,000 and a max output of 512,000, while `models.json` - the file Super Pi writes when it
12
+ * discovers that model - said 128,000 for every one of the provider's nine models. The provider was
13
+ * never asked; Super Pi stamped its own default and the stamp was later read back as if a person had
14
+ * typed it. The result: a model with a million tokens of room ran a session that believed it had a
15
+ * hundred and twenty-eight thousand, and a long task could not be finished.
16
+ *
17
+ * SO THE RULE IS: THE CATALOGUE IS THE TRUTH, AND A FILE SUPER PI WROTE IS NOT A DECISION. A number
18
+ * a person wrote down still wins over the catalogue (see `model-context-window.ts`), but Super Pi's
19
+ * own default is a placeholder, not an opinion, and a placeholder never outranks the truth.
20
+ *
21
+ * IT IS AN OPTIONAL FILE, SO IT IS READ WITHOUT EVER FAILING. A missing catalogue, a catalogue that
22
+ * is not JSON, a catalogue whose shape is not what we expect - all of them mean "Super Pi knows
23
+ * nothing about this model", never "Super Pi refuses to start".
24
+ */
25
+ import { readFileSync, statSync } from "node:fs";
26
+ import { join } from "node:path";
27
+ import { stripJsonComments } from "./json-comments.js";
28
+ /** A catalogue nobody could read. It knows nothing, and it says so without throwing. */
29
+ const EMPTY_STORE = { byModel: new Map(), byProviderModel: new Map() };
30
+ /** The file Pi writes the catalogue into, next to the file it writes providers into. */
31
+ export function modelStorePath(agentDir) {
32
+ return join(agentDir, "models-store.json");
33
+ }
34
+ /**
35
+ * The catalogue, read from disk.
36
+ *
37
+ * The file is re-read only when it actually changed: every session and every turn asks for it, and
38
+ * parsing thirty kilobytes of JSON per turn to learn the same thing is waste. The check is the
39
+ * file's modification time and size, so an edit by Pi is seen immediately.
40
+ */
41
+ const cache = new Map();
42
+ export function readModelStore(agentDir) {
43
+ const path = modelStorePath(agentDir);
44
+ try {
45
+ const stat = statSync(path);
46
+ const cached = cache.get(path);
47
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size)
48
+ return cached.store;
49
+ const store = parseModelStore(JSON.parse(stripJsonComments(readFileSync(path, "utf8"))));
50
+ cache.set(path, { mtimeMs: stat.mtimeMs, size: stat.size, store });
51
+ return store;
52
+ }
53
+ catch {
54
+ // NO CATALOGUE IS NOT A FAILURE. It is the state of every machine where Pi has not fetched one
55
+ // yet, and the answer is "Super Pi knows nothing about this model", not an exception.
56
+ return EMPTY_STORE;
57
+ }
58
+ }
59
+ /**
60
+ * The catalogue as data.
61
+ *
62
+ * The shape Pi writes is `{ <provider id>: { models: [{ id, contextWindow, maxTokens }] } }`, and a
63
+ * shape with the providers nested one level deeper is read too - Pi has moved this file around
64
+ * before, and a catalogue in a slightly different shape is still a catalogue.
65
+ */
66
+ export function parseModelStore(raw) {
67
+ const store = { byModel: new Map(), byProviderModel: new Map() };
68
+ collectProvider(raw, "", store, 0);
69
+ return store;
70
+ }
71
+ /** How deep the shape may nest before we call it something we do not understand. */
72
+ const MAX_NESTING = 4;
73
+ function collectProvider(entry, providerId, store, depth) {
74
+ if (!entry || typeof entry !== "object" || depth > MAX_NESTING)
75
+ return;
76
+ const record = entry;
77
+ const models = record.models;
78
+ if (Array.isArray(models)) {
79
+ for (const model of models)
80
+ collectModel(model, providerId, store);
81
+ return;
82
+ }
83
+ for (const [nestedId, nested] of Object.entries(record)) {
84
+ collectProvider(nested, nestedId, store, depth + 1);
85
+ }
86
+ }
87
+ function collectModel(model, providerId, store) {
88
+ if (!model || typeof model !== "object")
89
+ return;
90
+ const record = model;
91
+ const id = typeof record.id === "string" ? record.id.trim() : typeof record.name === "string" ? record.name.trim() : "";
92
+ if (!id)
93
+ return;
94
+ const entry = {};
95
+ if (typeof record.contextWindow === "number" && Number.isFinite(record.contextWindow) && record.contextWindow > 0) {
96
+ entry.contextWindow = record.contextWindow;
97
+ }
98
+ if (typeof record.maxTokens === "number" && Number.isFinite(record.maxTokens) && record.maxTokens > 0) {
99
+ entry.maxTokens = record.maxTokens;
100
+ }
101
+ if (entry.contextWindow === undefined && entry.maxTokens === undefined)
102
+ return;
103
+ const key = id.toLowerCase();
104
+ store.byProviderModel.set(`${providerId.toLowerCase()}/${key}`, entry);
105
+ const known = store.byModel.get(key);
106
+ // THE SAME MODEL UNDER TWO PROVIDERS. The catalogue says the same thing about it in both places,
107
+ // but when it does not, the larger window is the one the model actually has - a smaller duplicate
108
+ // is an older or narrower copy of the same truth, and taking it is how a million-token model
109
+ // ends up being treated as a hundred-and-twenty-eight-thousand-token one.
110
+ if (!known || (entry.contextWindow ?? 0) > (known.contextWindow ?? 0))
111
+ store.byModel.set(key, entry);
112
+ }
113
+ /**
114
+ * What the catalogue says about one model.
115
+ *
116
+ * The provider-specific entry is preferred when the catalogue has one, because a provider may serve
117
+ * a model under a different limit than another provider does. The model-id entry is the fallback,
118
+ * and it is what makes the lookup work for a provider id the user invented.
119
+ */
120
+ export function storeWindowFor(store, modelId, providerId) {
121
+ if (!store)
122
+ return undefined;
123
+ const key = modelId.trim().toLowerCase();
124
+ if (!key)
125
+ return undefined;
126
+ if (providerId) {
127
+ const scoped = store.byProviderModel.get(`${providerId.trim().toLowerCase()}/${key}`);
128
+ if (scoped)
129
+ return scoped;
130
+ }
131
+ return store.byModel.get(key);
132
+ }
@@ -27,7 +27,7 @@ import { existsSync, statSync } from "node:fs";
27
27
  import { open, readdir } from "node:fs/promises";
28
28
  import { StringDecoder } from "node:string_decoder";
29
29
  import { dirname, join, resolve } from "node:path";
30
- import { effectiveContextWindow, readDeclaredWindows } from "./model-context-window.js";
30
+ import { arbitrateContextWindow, readDeclaredWindows, readStoreWindows } from "./model-context-window.js";
31
31
  import { fileURLToPath, pathToFileURL } from "node:url";
32
32
  const traceSession = (conversationId, phase, startedAt, extra = "") => {
33
33
  if (process.env.SUPER_PI_TRACE_LATENCY !== "1")
@@ -336,12 +336,13 @@ export async function createPiSession(creation) {
336
336
  // So the person's file wins: a number somebody typed is a decision, and a number a catalogue
337
337
  // fetched is a claim. See `model-context-window.ts` for the whole reasoning.
338
338
  const declared = readDeclaredWindows(agentDir);
339
+ const catalogue = readStoreWindows(agentDir);
339
340
  live.resolveModel = (provider, modelId) => {
340
341
  const found = modelRuntime.getModel?.(provider, modelId);
341
342
  if (!found || typeof found !== "object")
342
343
  return undefined;
343
344
  const model = found;
344
- const window = effectiveContextWindow(declared, provider, modelId, model.contextWindow);
345
+ const window = arbitrateContextWindow(declared, catalogue, provider, modelId, model.contextWindow);
345
346
  // The model is handed to Pi WHOLE - it is what the agent runs on - so this is where the
346
347
  // corrected window has to be. A model Super Pi has no opinion about is handed over untouched.
347
348
  return window === undefined ? model : { ...model, contextWindow: window };
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
+ import { readModelStore, storeWindowFor } from "./models-store.js";
4
5
  /**
5
6
  * The API adapters Pi ships, as the ids a provider may name.
6
7
  *
@@ -811,8 +812,15 @@ export function parseRemoteModels(payload) {
811
812
  const lower = id.toLowerCase();
812
813
  const reasoning = /r1|reason|o1|o3|thinking|qwq|deepseek-r1/i.test(lower);
813
814
  const imageInput = /vision|vl|4o|gemini|claude-3|flash|pixtral/i.test(lower);
814
- const contextWindow = typeof rec.context_window === "number" ? rec.context_window : DEFAULT_CONTEXT_WINDOW;
815
- const maxTokens = reasoning ? 32768 : DEFAULT_MAX_TOKENS;
815
+ // THE CATALOGUE IS ASKED BEFORE THE DEFAULT IS GUESSED. A model the provider did not describe
816
+ // used to fall straight to the placeholder 128000/16384, and that stamp was later read back as
817
+ // if a person had chosen it - which is how MiniMax-M3 (a 1,000,000-token model) came to believe
818
+ // it had 128,000. Only a model with NO catalogue entry takes the default.
819
+ const catalogue = storeWindowFor(readModelStore(piAgentDir()), id);
820
+ const contextWindow = typeof rec.context_window === "number"
821
+ ? rec.context_window
822
+ : catalogue?.contextWindow ?? DEFAULT_CONTEXT_WINDOW;
823
+ const maxTokens = reasoning ? 32768 : catalogue?.maxTokens ?? DEFAULT_MAX_TOKENS;
816
824
  discovered.push({
817
825
  id,
818
826
  name: id,
@@ -24,7 +24,7 @@ import { LengthExceededError } from "./turn-failure.js";
24
24
  // paths recognise a delivery identically. Re-exported because they were part of this module's surface.
25
25
  export { describeDeliveredUserMessage, describePiQueue } from "./pi-session-events.js";
26
26
  import { createPiSession, createSdkCatalog, piSdkAvailable, resolveTranscriptFile, superPiExtensionPaths } from "./pi-session.js";
27
- import { TASK_CONVERSATION_ENV, PARENT_CONVERSATION_ENV, TASK_DEPTH_ENV, TASK_ENDPOINT_ENV, TASK_EXEC_ENDPOINT_ENV, TASK_ROSTER_ENV, TASK_TOOL_NAME, TODO_ENDPOINT_ENV, TODO_TOOL_NAME, PROJECT_TOOL_NAME, PROJECT_ENDPOINT_ENV, SCHEDULED_TASK_ENDPOINT_ENV, SCHEDULED_TASK_TOOL_NAME, WORKFLOW_ENDPOINT_ENV, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, ORCHESTRATOR_ENDPOINT_ENV, ORCHESTRATOR_WORKSPACE_ENV, SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME, rosterPayload, } from "./task-tool.js";
27
+ import { TASK_CONVERSATION_ENV, PARENT_CONVERSATION_ENV, TASK_DEPTH_ENV, TASK_ENDPOINT_ENV, TASK_EXEC_ENDPOINT_ENV, TASK_ROSTER_ENV, TASK_TOOL_NAME, TODO_ENDPOINT_ENV, TODO_TOOL_NAME, PROJECT_TOOL_NAME, PROJECT_ENDPOINT_ENV, SCHEDULED_TASK_ENDPOINT_ENV, SCHEDULED_TASK_TOOL_NAME, WORKFLOW_ENDPOINT_ENV, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, ORCHESTRATOR_ENDPOINT_ENV, ORCHESTRATOR_WORKSPACE_ENV, SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME, SESSION_REMINDER_TOOL_NAME, rosterPayload, } from "./task-tool.js";
28
28
  import { BLOCKING_UI_METHODS, EXTENSION_UI_METHODS, } from "./types.js";
29
29
  import { loadConversationImages } from "./upload.js";
30
30
  import { describeToolCall, describeToolCallArgs, describeToolCallInProgress, extractPartialResultText, extractToolResultText, readQuestionCall } from "./tool-calls.js";
@@ -1267,6 +1267,10 @@ export class PiRpcRuntime {
1267
1267
  names.push(PROJECT_TOOL_NAME);
1268
1268
  if (this.options.orchestratorEndpoint)
1269
1269
  names.push(SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME);
1270
+ // THE REMINDER TOOL IS A SESSION TOOL, SO IT IS NAMED WHERE THE OTHER SESSION TOOLS ARE
1271
+ // NAMED - on its own line, because the line above is a pinned list and this one belongs to it.
1272
+ if (this.options.orchestratorEndpoint)
1273
+ names.push(SESSION_REMINDER_TOOL_NAME);
1270
1274
  return names;
1271
1275
  }
1272
1276
  /**
@@ -1485,7 +1489,7 @@ export class PiRpcRuntime {
1485
1489
  // allowlist and naming a tool Pi has not registered would change the spawn line for every other
1486
1490
  // mode. The prompt asks for a bare JSON array and nothing else; if the model spends a turn on a
1487
1491
  // tool call anyway the reranker times out and falls back to the lexical order.
1488
- const agentArgs = memoryReview ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates", "--tools", "memory,skill_manage,session_search"] : knowledgeRerank ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates"] : await agentSpawnArgs(this.agents.promptDir, agent, { extraAllowedTools: [...(extensionArgs.length ? [TASK_TOOL_NAME, TODO_TOOL_NAME, PROJECT_TOOL_NAME, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, SCHEDULED_TASK_TOOL_NAME, "question", "tool_register", ...(this.options.orchestratorEndpoint ? [SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME] : [])] : []), ...(memoryEnabled ? ["memory", "skill_manage", "session_search"] : []), ...(knowledgeEnabled ? [KNOWLEDGE_TOOL_NAME, KNOWLEDGE_IMPORT_TOOL_NAME] : []), ...(documentsEnabled ? [DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME] : []), ...(webEnabled ? [WEB_SEARCH_TOOL_NAME, WEB_FETCH_TOOL_NAME] : []), ...(feishuEnabled ? [FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME] : [])] });
1492
+ const agentArgs = memoryReview ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates", "--tools", "memory,skill_manage,session_search"] : knowledgeRerank ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates"] : await agentSpawnArgs(this.agents.promptDir, agent, { extraAllowedTools: [...(extensionArgs.length ? [TASK_TOOL_NAME, TODO_TOOL_NAME, PROJECT_TOOL_NAME, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, SCHEDULED_TASK_TOOL_NAME, "question", "tool_register", ...(this.options.orchestratorEndpoint ? [SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME, SESSION_REMINDER_TOOL_NAME] : [])] : []), ...(memoryEnabled ? ["memory", "skill_manage", "session_search"] : []), ...(knowledgeEnabled ? [KNOWLEDGE_TOOL_NAME, KNOWLEDGE_IMPORT_TOOL_NAME] : []), ...(documentsEnabled ? [DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME] : []), ...(webEnabled ? [WEB_SEARCH_TOOL_NAME, WEB_FETCH_TOOL_NAME] : []), ...(feishuEnabled ? [FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME] : [])] });
1489
1493
  // Refused here, with the reason, rather than handed to the spawn: an ENOENT from `spawn` reads as
1490
1494
  // "the app is broken" and hides the one fact that matters, which is where it looked for Pi.
1491
1495
  if (!this.pi.found)
@@ -73,6 +73,7 @@ export interface ServerContext {
73
73
  scheduledTaskService?: import("./application/scheduled-task-service.js").ScheduledTaskService;
74
74
  sessionLedger?: import("./session-ledger.js").SessionLedger;
75
75
  sessionOrchestratorService?: import("./application/session-orchestrator-service.js").SessionOrchestratorService;
76
+ sessionReminderService?: import("./application/session-reminder-service.js").SessionReminderService;
76
77
  projectService?: import("./application/project-service.js").ProjectService;
77
78
  execService: ExecService;
78
79
  toolRegistry: ToolRegistry;