context-doctor 0.34.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/pack.js CHANGED
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import { spawnSync } from "node:child_process";
17
17
  import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
18
+ import { homedir } from "node:os";
18
19
  import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
19
20
  import { estimateTokens, formatTokens } from "./tokens.js";
20
21
  import { EXTRACTABLE, extractText } from "./extract.js";
@@ -248,10 +249,16 @@ function select(sources, perSource, query, opts) {
248
249
  const chunks = perSource.flat();
249
250
  const pick = [];
250
251
  const missingIds = [];
252
+ const unfit = [];
251
253
  let used = 0;
252
- const take = (c) => {
253
- if (pick.includes(c) || used + c.tokens > budget)
254
+ const take = (c, requested) => {
255
+ if (pick.includes(c))
254
256
  return;
257
+ if (used + c.tokens > budget) {
258
+ if (!unfit.some((u) => u.id === c.id))
259
+ unfit.push({ id: c.id, tokens: c.tokens, requested });
260
+ return;
261
+ }
255
262
  pick.push(c);
256
263
  used += c.tokens;
257
264
  };
@@ -262,7 +269,7 @@ function select(sources, perSource, query, opts) {
262
269
  for (const id of opts.ids) {
263
270
  const c = byId.get(id);
264
271
  if (c)
265
- take(c);
272
+ take(c, true);
266
273
  else
267
274
  missingIds.push(id);
268
275
  }
@@ -271,7 +278,7 @@ function select(sources, perSource, query, opts) {
271
278
  if (mode === "outline")
272
279
  mode = "query";
273
280
  for (const c of [...chunks].filter((c) => c.score > 0).sort((a, b) => b.score - a.score))
274
- take(c);
281
+ take(c, false);
275
282
  }
276
283
  const order = new Map(chunks.map((c, i) => [c, i]));
277
284
  pick.sort((a, b) => order.get(a) - order.get(b));
@@ -284,6 +291,7 @@ function select(sources, perSource, query, opts) {
284
291
  selected: pick,
285
292
  chunks,
286
293
  missingIds,
294
+ unfit,
287
295
  sources: sources.map((s, i) => ({
288
296
  name: s.name,
289
297
  tokens: perSource[i].reduce((sum, c) => sum + c.tokens, 0),
@@ -317,6 +325,21 @@ export function renderPack(r, { outlineLimit = 60 } = {}) {
317
325
  out.push(`Unknown ids: ${r.missingIds.join(", ")}.`);
318
326
  if (r.semanticNote)
319
327
  out.push(`(${r.semanticNote})`);
328
+ const unfitRequested = (r.unfit ?? []).filter((u) => u.requested);
329
+ if (r.selected.length > 0 && unfitRequested.length > 0) {
330
+ out.push(`Did not fit the budget of ${formatTokens(r.budget)}: ${unfitRequested.map((u) => `${u.id} (~${formatTokens(u.tokens)})`).join(", ")}. Ask for it alone or with a larger budget (--max-tokens; MCP max_tokens).`);
331
+ }
332
+ if (r.selected.length === 0 && (r.unfit ?? []).length > 0) {
333
+ // Something matched (or was asked for by id); the budget is what stopped it.
334
+ // "Rephrase" would send the user after the wrong problem.
335
+ const best = r.unfit[0];
336
+ const chunk = r.chunks.find((c) => c.id === best.id);
337
+ out.push(`Nothing fit the budget of ${formatTokens(r.budget)} tokens: ${best.requested ? "the requested chunk" : "the best match"} ` +
338
+ `${best.id}${chunk?.heading ? ` (${chunk.heading})` : ""} is ~${formatTokens(best.tokens)} tokens. ` +
339
+ `Raise the budget to at least ${best.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`);
340
+ out.push(...outline(r.chunks, outlineLimit));
341
+ return out.join("\n");
342
+ }
320
343
  if (r.selected.length === 0) {
321
344
  out.push("No chunk matched. Choose from the outline by id, or rephrase with words the document would use.");
322
345
  out.push(...outline(r.chunks, outlineLimit));
@@ -359,18 +382,95 @@ function within(root, inner) {
359
382
  const rel = relative(root, inner);
360
383
  return rel === "" || (rel !== ".." && !rel.startsWith(".." + sep) && !isAbsolute(rel));
361
384
  }
385
+ /**
386
+ * Files that hold credentials by convention. Packing one puts its keys into a
387
+ * model's context (and, through MCP, into a transcript on disk): measured on
388
+ * a folder outside git, `pack .` returned an .env's API key and an .npmrc's
389
+ * token verbatim. They are skipped even when named outright or tracked by
390
+ * git; only the CLI's --include-secrets packs them.
391
+ */
392
+ const SECRET_NAMES = new Set([".npmrc", ".pypirc", ".netrc", "_netrc", ".git-credentials", ".pgpass", ".htpasswd"]);
393
+ const SECRET_EXT = new Set([".pem", ".key", ".p12", ".pfx", ".keystore", ".jks"]);
394
+ /** Why `path` looks like a secrets file, or undefined when it does not. */
395
+ export function secretFileReason(path) {
396
+ const name = basename(path);
397
+ const lower = name.toLowerCase();
398
+ if (lower === ".env" || lower.startsWith(".env."))
399
+ return "an .env file";
400
+ if (SECRET_NAMES.has(lower))
401
+ return `a credentials file (${name})`;
402
+ if (/^id_(rsa|dsa|ecdsa|ed25519)(_sk)?$/.test(lower) || (/^id_(rsa|dsa|ecdsa|ed25519)/.test(lower) && !lower.endsWith(".pub"))) {
403
+ return "a private SSH key";
404
+ }
405
+ if (SECRET_EXT.has(extname(lower)))
406
+ return `a key or certificate store (${extname(lower)})`;
407
+ const parts = path.split(/[\\/]+/);
408
+ if (lower === "credentials" && parts[parts.length - 2] === ".aws")
409
+ return "AWS credentials";
410
+ return undefined;
411
+ }
412
+ /**
413
+ * Folders that hold credentials whatever the files inside are called. A path
414
+ * in one is refused unless secrets are allowed (never over MCP).
415
+ */
416
+ function sensitiveDirs() {
417
+ const home = homedir();
418
+ const dirs = [
419
+ ...[".ssh", ".aws", ".gnupg", ".kube", ".docker", ".azure", join(".config", "gcloud"), join("Library", "Keychains"), ".password-store"].map((d) => join(home, d)),
420
+ "/etc/shadow", "/etc/gshadow", "/etc/sudoers", "/etc/master.passwd", "/etc/ssh",
421
+ ];
422
+ // Compared against real paths: /etc is /private/etc on macOS, and a home
423
+ // under /var/folders is really /private/var/folders.
424
+ const real = dirs.map((d) => {
425
+ try {
426
+ return realpathSync(d);
427
+ }
428
+ catch {
429
+ return d;
430
+ }
431
+ });
432
+ return [...new Set([...dirs, ...real])];
433
+ }
434
+ /** The denylisted folder `path` (a real path) sits in, if any. */
435
+ function inSensitiveDir(path, dirs) {
436
+ return dirs.find((d) => within(d, path));
437
+ }
438
+ /** A short reason for a filesystem error: EACCES reads as "permission denied", not a stack trace. */
439
+ function fsReason(e) {
440
+ const code = e?.code;
441
+ if (code === "ENOENT")
442
+ return "not found";
443
+ if (code === "EACCES" || code === "EPERM")
444
+ return "permission denied";
445
+ if (code === "ENOTDIR")
446
+ return "not a directory";
447
+ if (code === "EISDIR")
448
+ return "is a directory";
449
+ if (code === "ELOOP")
450
+ return "too many symlinks";
451
+ return code ? `unreadable (${code})` : `unreadable (${e?.message ?? e})`;
452
+ }
362
453
  /**
363
454
  * Read files and directories (recursively, skipping build and dependency
364
- * folders, binaries, and anything past the size limits) into sources.
365
- * `skipped` says what was left out and why, so nothing vanishes silently.
455
+ * folders, hidden entries, binaries, secrets files, and anything past the size
456
+ * limits) into sources. `skipped` says what was left out and why, so nothing
457
+ * vanishes silently.
366
458
  *
367
459
  * A path named here is read even through a symlink; a symlink met inside a
368
460
  * folder is not followed, as git does not follow one either. A link out of
369
461
  * the folder would pack files nobody named (a tracked link to /etc/hosts, or
370
462
  * to a secret beside the repo), a link to a parent loops, and what a link
371
463
  * inside points at is read under its own name (or left out by .gitignore).
464
+ *
465
+ * An unreadable entry (permission denied, a device, /dev/fd) is reported as
466
+ * skipped, never thrown: one locked file must not lose the rest of a folder.
372
467
  */
373
- export function readSources(paths, cwd = process.cwd()) {
468
+ export function readSources(paths, cwdOrOptions = process.cwd()) {
469
+ const options = typeof cwdOrOptions === "string" ? { cwd: cwdOrOptions } : cwdOrOptions;
470
+ const cwd = options.cwd ?? process.cwd();
471
+ const includeSecrets = options.includeSecrets === true;
472
+ const secretsHint = options.secretsHint ?? "";
473
+ const denied = includeSecrets ? [] : sensitiveDirs();
374
474
  const sources = [];
375
475
  const skipped = [];
376
476
  let bytes = 0;
@@ -379,6 +479,18 @@ export function readSources(paths, cwd = process.cwd()) {
379
479
  const seen = new Set();
380
480
  // Real location of the path being read: a link out of it is reported, not just dropped.
381
481
  let root = "";
482
+ // Hidden files and folders passed over in a walk outside git, per named folder.
483
+ let hidden = 0;
484
+ // Whether the folder being walked was listed by git (hidden tracked files are source there).
485
+ let insideGit = false;
486
+ const realOf = (p) => {
487
+ try {
488
+ return realpathSync(p);
489
+ }
490
+ catch {
491
+ return resolve(p);
492
+ }
493
+ };
382
494
  const visit = (p, top) => {
383
495
  if (sources.length >= PACK_LIMITS.files) {
384
496
  if (top || skipped.length < 20)
@@ -389,8 +501,8 @@ export function readSources(paths, cwd = process.cwd()) {
389
501
  try {
390
502
  st = top ? statSync(p) : lstatSync(p);
391
503
  }
392
- catch {
393
- skipped.push(`${p}: not found`);
504
+ catch (e) {
505
+ skipped.push(`${p}: ${fsReason(e)}`);
394
506
  return;
395
507
  }
396
508
  if (st.isSymbolicLink()) {
@@ -405,13 +517,29 @@ export function readSources(paths, cwd = process.cwd()) {
405
517
  skipped.push(`${p}: symlink pointing outside the folder (not followed)`);
406
518
  return;
407
519
  }
520
+ if (denied.length > 0) {
521
+ const dir = inSensitiveDir(realOf(p), denied);
522
+ if (dir) {
523
+ // Once per named path: a folder of keys is one refusal, not one per key.
524
+ if (top)
525
+ skipped.push(`${p}: refused, ${dir} holds credentials${secretsHint}`);
526
+ return;
527
+ }
528
+ }
408
529
  if (st.isDirectory()) {
409
- if (!top && (SKIP_DIRS.has(basename(p)) || basename(p).startsWith(".")))
530
+ const name = basename(p);
531
+ if (!top && SKIP_DIRS.has(name))
410
532
  return;
533
+ if (!top && name.startsWith(".")) {
534
+ hidden++;
535
+ return;
536
+ }
411
537
  // Inside a git repository the repository says what is source: tracked
412
538
  // files plus untracked ones not ignored, so .gitignore'd build output,
413
539
  // data dumps and secrets stay out. Elsewhere, walk with SKIP_DIRS.
414
540
  const listed = top ? gitFiles(p) : undefined;
541
+ if (top)
542
+ insideGit = listed !== undefined;
415
543
  if (listed) {
416
544
  // A folder named outright that git lists nothing in is still not read
417
545
  // (that is the .gitignore guarantee), but the user hears why.
@@ -422,19 +550,37 @@ export function readSources(paths, cwd = process.cwd()) {
422
550
  visit(join(p, f), false);
423
551
  return;
424
552
  }
425
- for (const e of readdirSync(p).sort())
553
+ let entries;
554
+ try {
555
+ entries = readdirSync(p).sort();
556
+ }
557
+ catch (e) {
558
+ skipped.push(`${p}: ${fsReason(e)}`);
559
+ return;
560
+ }
561
+ for (const e of entries)
426
562
  visit(join(p, e), false);
427
563
  return;
428
564
  }
429
- if (!st.isFile())
565
+ if (!st.isFile()) {
566
+ if (top)
567
+ skipped.push(`${p}: not a regular file`);
430
568
  return;
431
- let real;
432
- try {
433
- real = realpathSync(p);
434
569
  }
435
- catch {
436
- real = resolve(p);
570
+ if (!includeSecrets) {
571
+ const why = secretFileReason(p);
572
+ if (why) {
573
+ skipped.push(`${p}: ${why}, likely holding secrets; not packed${secretsHint}`);
574
+ return;
575
+ }
437
576
  }
577
+ // Outside git, a hidden file is passed over like a hidden folder (.DS_Store,
578
+ // editor state, tool configs with tokens in them). Named outright, it is read.
579
+ if (!top && basename(p).startsWith(".") && !insideGit) {
580
+ hidden++;
581
+ return;
582
+ }
583
+ const real = realOf(p);
438
584
  if (seen.has(real))
439
585
  return;
440
586
  if (st.size > PACK_LIMITS.fileBytes || bytes + st.size > PACK_LIMITS.totalBytes) {
@@ -454,7 +600,14 @@ export function readSources(paths, cwd = process.cwd()) {
454
600
  }
455
601
  return;
456
602
  }
457
- const buf = readFileSync(p);
603
+ let buf;
604
+ try {
605
+ buf = readFileSync(p);
606
+ }
607
+ catch (e) {
608
+ skipped.push(`${p}: ${fsReason(e)}`);
609
+ return;
610
+ }
458
611
  if (buf.subarray(0, 8000).includes(0)) {
459
612
  if (top)
460
613
  skipped.push(`${p}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);
@@ -469,13 +622,12 @@ export function readSources(paths, cwd = process.cwd()) {
469
622
  skipped.push(`${p}: not found`);
470
623
  continue;
471
624
  }
472
- try {
473
- root = realpathSync(p);
474
- }
475
- catch {
476
- root = resolve(p);
477
- }
625
+ root = realOf(p);
626
+ hidden = 0;
627
+ insideGit = false;
478
628
  visit(p, true);
629
+ if (hidden > 0)
630
+ skipped.push(`${p}: ${hidden} hidden file(s) or folder(s) not read (name one to pack it)`);
479
631
  }
480
632
  return { sources, skipped };
481
633
  }
package/dist/parse.d.ts CHANGED
@@ -6,6 +6,8 @@
6
6
  * - Anthropic format: { system?, messages: [{ role, content: string | Block[] }] }
7
7
  * where Block = { type: "text" | "tool_use" | "tool_result" | "image", ... }
8
8
  * - Bare message array: [{ role, content }, ...]
9
+ * - Gemini (generateContent): { systemInstruction?, contents: [{ role, parts }] }
10
+ * - OpenAI Responses: { instructions?, input: string | Item[] }
9
11
  * - Raw text: treated as a single user message (last-resort fallback)
10
12
  */
11
13
  export type MessageKind = "system" | "user" | "assistant" | "tool_call" | "tool_result" | "image" | "other";
@@ -33,7 +35,7 @@ export interface NormalizedMessage {
33
35
  export interface NormalizedConversation {
34
36
  messages: NormalizedMessage[];
35
37
  /** Format detected, for reporting. */
36
- sourceFormat: "openai" | "anthropic" | "array" | "text";
38
+ sourceFormat: "openai" | "anthropic" | "array" | "text" | "gemini" | "responses";
37
39
  /** The request's own `model` field, when it has one. Picks the tokenizer ratios. */
38
40
  model?: string;
39
41
  /**
package/dist/parse.js CHANGED
@@ -6,11 +6,17 @@
6
6
  * - Anthropic format: { system?, messages: [{ role, content: string | Block[] }] }
7
7
  * where Block = { type: "text" | "tool_use" | "tool_result" | "image", ... }
8
8
  * - Bare message array: [{ role, content }, ...]
9
+ * - Gemini (generateContent): { systemInstruction?, contents: [{ role, parts }] }
10
+ * - OpenAI Responses: { instructions?, input: string | Item[] }
9
11
  * - Raw text: treated as a single user message (last-resort fallback)
10
12
  */
11
13
  function flattenContent(content) {
12
14
  if (typeof content === "string")
13
15
  return { text: content, hasBinary: false };
16
+ // OpenAI sends `content: null` on an assistant message that only calls
17
+ // tools. It is no text, not the two-character string `""`.
18
+ if (content == null)
19
+ return { text: "", hasBinary: false };
14
20
  if (!Array.isArray(content))
15
21
  return { text: JSON.stringify(content ?? ""), hasBinary: false };
16
22
  let text = "";
@@ -27,6 +33,9 @@ function flattenContent(content) {
27
33
  const b = block;
28
34
  switch (b.type) {
29
35
  case "text":
36
+ // OpenAI Responses' text parts.
37
+ case "input_text":
38
+ case "output_text":
30
39
  text += b.text ?? "";
31
40
  break;
32
41
  case "tool_use": {
@@ -119,7 +128,7 @@ function rawText(input, parseError) {
119
128
  const parseWarning = input.trim() === ""
120
129
  ? "Input is empty — nothing to profile."
121
130
  : parseError && (head === "{" || head === "[")
122
- ? `Input starts like JSON but does not parse (${parseError.message}). Profiling it as raw text, which is almost certainly not what you want.`
131
+ ? `Input starts like JSON but does not parse (${parseError.message}), so it is not a conversation file.`
123
132
  : undefined;
124
133
  return {
125
134
  sourceFormat: "text",
@@ -129,7 +138,93 @@ function rawText(input, parseError) {
129
138
  messages: input.trim() === "" ? [] : [{ index: 0, role: "user", kind: "user", text: input, hasBinary: false }],
130
139
  };
131
140
  }
141
+ /** A Gemini part: text, an attachment, or a function call or response. */
142
+ function geminiPart(part) {
143
+ if (typeof part === "string")
144
+ return { text: part, hasBinary: false };
145
+ if (!part || typeof part !== "object")
146
+ return { text: "", hasBinary: false };
147
+ const p = part;
148
+ if (typeof p.text === "string")
149
+ return { text: p.text, hasBinary: false };
150
+ if (p.inlineData || p.fileData)
151
+ return { text: "[file]", hasBinary: true };
152
+ if (p.functionCall) {
153
+ const call = `[tool call: ${p.functionCall.name}] ${JSON.stringify(p.functionCall.args ?? {})}`;
154
+ return { text: call, hasBinary: false, kind: "tool_call", toolName: p.functionCall.name, call };
155
+ }
156
+ if (p.functionResponse) {
157
+ const r = p.functionResponse.response;
158
+ const out = typeof r?.output === "string" ? r.output : typeof r?.content === "string" ? r.content : JSON.stringify(r ?? {});
159
+ return { text: out, hasBinary: false, kind: "tool_result", toolName: p.functionResponse.name };
160
+ }
161
+ if (p.executableCode)
162
+ return { text: String(p.executableCode.code ?? ""), hasBinary: false };
163
+ if (p.codeExecutionResult)
164
+ return { text: String(p.codeExecutionResult.output ?? ""), hasBinary: false };
165
+ return { text: JSON.stringify(p), hasBinary: false };
166
+ }
167
+ function geminiMessage(raw, index) {
168
+ const c = raw && typeof raw === "object" ? raw : {};
169
+ const role = c.role === "model" ? "assistant" : String(c.role ?? "user");
170
+ const parts = Array.isArray(c.parts) ? c.parts : [];
171
+ let text = "";
172
+ let hasBinary = false;
173
+ let kind;
174
+ let toolName;
175
+ let toolCallText = "";
176
+ for (const part of parts) {
177
+ const f = geminiPart(part);
178
+ text += (text && f.text ? "\n" : "") + f.text;
179
+ hasBinary ||= f.hasBinary;
180
+ if (f.kind)
181
+ kind = f.kind;
182
+ toolName ??= f.toolName;
183
+ if (f.call)
184
+ toolCallText += f.call;
185
+ }
186
+ const fallback = ["system", "user", "assistant"].includes(role) ? role : "other";
187
+ return { index, role, kind: kind ?? fallback, text, toolName, toolCallText: toolCallText || undefined, hasBinary };
188
+ }
189
+ /** One OpenAI Responses input item: a message, a function or shell call, its output, or reasoning. */
190
+ function responsesItem(raw, index) {
191
+ if (typeof raw === "string")
192
+ return { index, role: "user", kind: "user", text: raw, hasBinary: false };
193
+ const it = raw && typeof raw === "object" ? raw : {};
194
+ const type = it.type;
195
+ if (type === "function_call" || type === "custom_tool_call" || type === "local_shell_call") {
196
+ const name = it.name ?? (type === "local_shell_call" ? "local_shell" : undefined);
197
+ const args = typeof it.arguments === "string" ? it.arguments : JSON.stringify(it.input ?? it.action ?? {});
198
+ const call = `[tool call: ${name}] ${args}`;
199
+ return { index, role: "assistant", kind: "tool_call", text: call, toolName: name, toolCallText: call, hasBinary: false };
200
+ }
201
+ if (type === "function_call_output" || type === "custom_tool_call_output" || type === "local_shell_call_output") {
202
+ const out = it.output;
203
+ const flat = typeof out === "string" ? { text: out, hasBinary: false } : flattenContent(out);
204
+ return { index, role: "tool", kind: "tool_result", text: flat.text, hasBinary: flat.hasBinary };
205
+ }
206
+ if (type === "reasoning") {
207
+ const summary = Array.isArray(it.summary) ? it.summary.map((p) => p?.text ?? "").join("\n") : "";
208
+ return { index, role: "assistant", kind: "assistant", text: summary, hasBinary: false };
209
+ }
210
+ return normalizeMessage(it, index);
211
+ }
132
212
  export function parseConversation(input) {
213
+ // Library callers sometimes hand over the object itself, or nothing at all;
214
+ // a stack trace from inside JSON.parse helps neither.
215
+ if (typeof input !== "string") {
216
+ if (input !== null && typeof input === "object") {
217
+ try {
218
+ input = JSON.stringify(input);
219
+ }
220
+ catch {
221
+ return rawText("");
222
+ }
223
+ }
224
+ else {
225
+ input = input === undefined || input === null ? "" : String(input);
226
+ }
227
+ }
133
228
  let data;
134
229
  try {
135
230
  data = JSON.parse(input);
@@ -142,7 +237,11 @@ export function parseConversation(input) {
142
237
  if (data === null || typeof data !== "object")
143
238
  return rawText(input);
144
239
  if (Array.isArray(data)) {
145
- const looksLikeMessages = data.length === 0 || data.some((m) => m && typeof m === "object" && "role" in m);
240
+ const looksLikeMessages = data.length === 0 || data.some((m) => m && typeof m === "object" && ("role" in m || "parts" in m));
241
+ // A bare Gemini `contents` array: role/parts entries.
242
+ if (data.length > 0 && data.every((m) => m && typeof m === "object" && Array.isArray(m.parts))) {
243
+ return { sourceFormat: "gemini", messages: data.map((m, i) => geminiMessage(m, i)) };
244
+ }
146
245
  return {
147
246
  sourceFormat: "array",
148
247
  parseWarning: looksLikeMessages ? undefined : "This is a JSON array, but no element has a `role` field — it does not look like a conversation.",
@@ -150,6 +249,28 @@ export function parseConversation(input) {
150
249
  };
151
250
  }
152
251
  const obj = data;
252
+ const model = typeof obj.model === "string" && obj.model ? obj.model : undefined;
253
+ // Gemini generateContent: `contents` of role/parts, the system prompt in `systemInstruction`.
254
+ if (obj.messages == null && Array.isArray(obj.contents)) {
255
+ const messages = [];
256
+ const sys = (obj.systemInstruction ?? obj.system_instruction);
257
+ if (sys != null) {
258
+ const m = typeof sys === "string" ? { text: sys, hasBinary: false } : geminiMessage(sys, -1);
259
+ messages.push({ index: -1, role: "system", kind: "system", text: m.text, hasBinary: m.hasBinary });
260
+ }
261
+ messages.push(...obj.contents.map((c, i) => geminiMessage(c, i)));
262
+ return { sourceFormat: "gemini", messages, model };
263
+ }
264
+ // OpenAI Responses: `input` (a string or a list of items), the system prompt in `instructions`.
265
+ if (obj.messages == null && (typeof obj.input === "string" || Array.isArray(obj.input))) {
266
+ const messages = [];
267
+ if (typeof obj.instructions === "string" && obj.instructions) {
268
+ messages.push({ index: -1, role: "system", kind: "system", text: obj.instructions, hasBinary: false });
269
+ }
270
+ const items = typeof obj.input === "string" ? [obj.input] : obj.input;
271
+ messages.push(...items.map((it, i) => responsesItem(it, i)));
272
+ return { sourceFormat: "responses", messages, model };
273
+ }
153
274
  const rawField = obj.messages;
154
275
  const rawMessages = Array.isArray(rawField)
155
276
  ? rawField
@@ -170,6 +291,5 @@ export function parseConversation(input) {
170
291
  : messages.length === 0
171
292
  ? "This JSON has no `messages` array (and no `system`) — it does not look like a conversation. Expected {\"messages\":[{\"role\":…,\"content\":…}]}."
172
293
  : undefined;
173
- const model = typeof obj.model === "string" && obj.model ? obj.model : undefined;
174
294
  return { sourceFormat: isAnthropic ? "anthropic" : "openai", parseWarning, messages, model };
175
295
  }
package/dist/pricing.js CHANGED
@@ -56,6 +56,14 @@ const PRICING = [
56
56
  [/gpt-4o|gpt-4\.1/i, { inputPerM: 2.5, outputPerM: 10, cacheReadPerM: 1.25 }],
57
57
  [/gpt-4-turbo/i, { inputPerM: 10, outputPerM: 30, cacheReadPerM: 10 }],
58
58
  [/o[13](-|$)/i, { inputPerM: 2, outputPerM: 8, cacheReadPerM: 1 }],
59
+ // Gemini 3, paid tier (ai.google.dev/gemini-api/docs/pricing, Oct 2026). 3.6/3.8 Flash
60
+ // double from 2027-01-01; 3.1 Pro bills prompts over 200k at $4/$18/$0.40, a tier
61
+ // this per-token table does not model.
62
+ [/gemini-3[.\d]*-flash-lite/i, rate(0.3, 2.5, 0.03)],
63
+ [/gemini-3\.1-flash-lite/i, rate(0.25, 1.5, 0.025)],
64
+ [/gemini-3-flash/i, rate(0.5, 3, 0.05)],
65
+ [/gemini-3[.\d]*-flash/i, rate(0.75, 3.75, 0.075)],
66
+ [/gemini-3[.\d]*-pro/i, rate(2, 12, 0.2)],
59
67
  [/gemini.*flash/i, { inputPerM: 0.1, outputPerM: 0.4, cacheReadPerM: 0.025 }],
60
68
  [/gemini.*pro/i, { inputPerM: 1.25, outputPerM: 5, cacheReadPerM: 0.31 }],
61
69
  ];
package/dist/profile.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * tokens go, plus a list of actionable findings ("what's eating my window").
4
4
  */
5
5
  import { createHash } from "node:crypto";
6
- import { contextWindowFor, estimateTokens, MESSAGE_OVERHEAD_TOKENS, providerFor } from "./tokens.js";
6
+ import { contextWindowFor, estimateTokens, formatTokens, MESSAGE_OVERHEAD_TOKENS, providerFor } from "./tokens.js";
7
7
  import { estimatedTtftSeconds, inputCostUsd, pricingFor } from "./pricing.js";
8
8
  import { hasBase64Blob } from "./blob.js";
9
9
  import { calibrationFor } from "./calibration.js";
@@ -39,10 +39,15 @@ function unionSavings(findings, totalTokens) {
39
39
  unscoped += f.estSavings;
40
40
  continue;
41
41
  }
42
- const target = f.messages[f.messages.length - 1];
43
- perMessage.set(target, Math.max(perMessage.get(target) ?? 0, f.estSavings));
42
+ // A cluster of similar messages saves on every copy after the first;
43
+ // spread its claim over them, so each competes with that message's
44
+ // other findings rather than one message holding the whole cluster.
45
+ const targets = f.id === "near_duplicate" && f.messages.length > 2 ? f.messages.slice(1) : [f.messages[f.messages.length - 1]];
46
+ const share = f.estSavings / targets.length;
47
+ for (const target of targets)
48
+ perMessage.set(target, Math.max(perMessage.get(target) ?? 0, share));
44
49
  }
45
- const scoped = [...perMessage.values()].reduce((a, b) => a + b, 0);
50
+ const scoped = Math.round([...perMessage.values()].reduce((a, b) => a + b, 0));
46
51
  // Whole-conversation findings can only claim tokens no message-scoped
47
52
  // finding already claimed.
48
53
  const headroom = Math.max(0, totalTokens - scoped);
@@ -152,7 +157,7 @@ export function profileConversation(conv, model) {
152
157
  // With no model at all, Anthropic's request format still says whose
153
158
  // tokenizer counts it. Only the ratios use this; pricing and the window
154
159
  // stay unknown rather than guessed.
155
- const tokenizerModel = model ?? (conv.sourceFormat === "anthropic" ? "claude" : undefined);
160
+ const tokenizerModel = model ?? (conv.sourceFormat === "anthropic" ? "claude" : conv.sourceFormat === "gemini" ? "gemini" : undefined);
156
161
  // Learned from the user's own exact counts, if they ever fetched any.
157
162
  const calibration = calibrationFor(tokenizerModel);
158
163
  const perMessage = conv.messages.map((m) => ({
@@ -233,6 +238,18 @@ export function profileConversation(conv, model) {
233
238
  // runtime, never results.
234
239
  const sizes = shingleSets.map((set) => set.size);
235
240
  const exactDup = new Set(findings.filter((f) => f.id === "duplicate_content").flatMap((f) => f.messages));
241
+ // Similar messages are clustered, not reported per pair: 40 variants of
242
+ // one text are 780 pairs, and a finding per pair reported 781 findings
243
+ // and "868k more recoverable" on a 58k context. One finding per cluster,
244
+ // its saving counted once per message that could become a reference.
245
+ const parent = candidates.map((_, i) => i);
246
+ const root = (i) => {
247
+ while (parent[i] !== i)
248
+ i = parent[i] = parent[parent[i]];
249
+ return i;
250
+ };
251
+ // Per candidate: its most similar partner, which its saving is measured against.
252
+ const best = candidates.map(() => ({ sim: 0, partnerTokens: 0 }));
236
253
  for (let i = 0; i < candidates.length; i++) {
237
254
  for (let j = i + 1; j < candidates.length; j++) {
238
255
  const a = candidates[i];
@@ -244,20 +261,46 @@ export function profileConversation(conv, model) {
244
261
  if (large === 0 || small / large < SIMILARITY_THRESHOLD)
245
262
  continue; // cannot clear the bar
246
263
  const sim = jaccard(shingleSets[i], shingleSets[j]);
247
- if (sim >= SIMILARITY_THRESHOLD) {
248
- const smaller = Math.min(a.tokens, b.tokens);
249
- const [first, second] = a.msg.index <= b.msg.index ? [a, b] : [b, a];
250
- findings.push({
251
- id: "near_duplicate",
252
- severity: "warn",
253
- estSavings: Math.round(smaller * sim * 0.9),
254
- message: `Messages #${first.msg.index} and #${second.msg.index} are ~${Math.round(sim * 100)}% similar (~${smaller} tokens repeated with different framing).`,
255
- suggestion: "Replace the later copy with a short reference to the first — repeats survive even when the surrounding words differ.",
256
- messages: [first.msg.index, second.msg.index],
257
- });
258
- }
264
+ if (sim < SIMILARITY_THRESHOLD)
265
+ continue;
266
+ parent[root(i)] = root(j);
267
+ if (sim > best[i].sim)
268
+ best[i] = { sim, partnerTokens: b.tokens };
269
+ if (sim > best[j].sim)
270
+ best[j] = { sim, partnerTokens: a.tokens };
259
271
  }
260
272
  }
273
+ const clusters = new Map();
274
+ candidates.forEach((_, i) => {
275
+ if (best[i].sim === 0)
276
+ return;
277
+ const r = root(i);
278
+ clusters.set(r, [...(clusters.get(r) ?? []), i]);
279
+ });
280
+ for (const members of clusters.values()) {
281
+ if (members.length < 2)
282
+ continue;
283
+ members.sort((x, y) => candidates[x].msg.index - candidates[y].msg.index);
284
+ // The earliest copy stays; every later one could become a reference to it.
285
+ const later = members.slice(1);
286
+ const saving = later.reduce((n, i) => n + Math.round(Math.min(candidates[i].tokens, best[i].partnerTokens) * best[i].sim * 0.9), 0);
287
+ const sims = members.map((i) => best[i].sim);
288
+ const lo = Math.round(Math.min(...sims) * 100);
289
+ const hi = Math.round(Math.max(...sims) * 100);
290
+ const indexes = members.map((i) => candidates[i].msg.index);
291
+ const pct = lo === hi ? `~${hi}%` : `${lo}-${hi}%`;
292
+ const repeated = later.reduce((n, i) => n + candidates[i].tokens, 0);
293
+ findings.push({
294
+ id: "near_duplicate",
295
+ severity: "warn",
296
+ estSavings: saving,
297
+ message: members.length === 2
298
+ ? `Messages #${indexes[0]} and #${indexes[1]} are ${pct} similar (~${Math.min(candidates[members[0]].tokens, candidates[members[1]].tokens)} tokens repeated with different framing).`
299
+ : `${members.length} messages are ${pct} similar to each other (${indexes.slice(0, 6).map((n) => `#${n}`).join(", ")}${indexes.length > 6 ? ", …" : ""}): ~${formatTokens(repeated)} tokens in the ${later.length} later copies repeat the first with different framing.`,
300
+ suggestion: "Replace the later copies with a short reference to the first — repeats survive even when the surrounding words differ.",
301
+ messages: indexes,
302
+ });
303
+ }
261
304
  }
262
305
  // -- Repeated identical tool calls ------------------------------------------
263
306
  const callSeen = new Map();
package/dist/proxy.d.ts CHANGED
@@ -55,9 +55,17 @@ export interface ProxyOptions extends OptimizeOptions {
55
55
  * CONTEXT_DOCTOR_CACHE_KEY=0 or 1 overrides.
56
56
  */
57
57
  promptCacheKey?: boolean;
58
+ /**
59
+ * Largest request body accepted, in bytes (default 100 MB). The body is
60
+ * held in memory to be read as JSON; past this a request gets 413 rather
61
+ * than taking the proxy (and every agent behind it) down.
62
+ */
63
+ maxBodyBytes?: number;
58
64
  }
65
+ /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
66
+ export declare const DEFAULT_MAX_BODY_BYTES: number;
59
67
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
60
- export declare const PROXY_VERSION = "0.34.0";
68
+ export declare const PROXY_VERSION = "0.35.0";
61
69
  /**
62
70
  * Remove a leading `/t/<token>` from a request path, or return undefined when
63
71
  * the prefix is absent or the token differs. The comparison is constant time