somora 2026.1004.4 → 2026.1007.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +27 -23
  2. package/config.example.yaml +27 -0
  3. package/docs/api.md +57 -9
  4. package/docs/cache-strategy.md +24 -5
  5. package/docs/compaction.md +45 -0
  6. package/docs/display.md +14 -6
  7. package/docs/files.md +54 -12
  8. package/docs/imagegen.md +10 -1
  9. package/docs/memory.md +28 -0
  10. package/docs/mobile.md +29 -1
  11. package/docs/models.md +44 -4
  12. package/docs/resources.md +22 -0
  13. package/docs/setup.md +35 -3
  14. package/docs/thinking.md +37 -9
  15. package/docs/web.md +14 -5
  16. package/package.json +2 -1
  17. package/src/attachments/store.ts +19 -1
  18. package/src/browser/session.ts +2 -2
  19. package/src/cli/auth.ts +22 -0
  20. package/src/cli/claude-bin.ts +48 -0
  21. package/src/cli/config.ts +47 -0
  22. package/src/cli/setup.ts +11 -7
  23. package/src/cli/somora.ts +6 -1
  24. package/src/cli/tui/api.ts +44 -2
  25. package/src/cli/tui/app.tsx +62 -8
  26. package/src/cli/tui/commands.ts +109 -12
  27. package/src/cli/tui/header.tsx +20 -0
  28. package/src/cli/tui/stream.ts +2 -0
  29. package/src/cli/tui/types.ts +10 -1
  30. package/src/compaction/summarize.ts +4 -0
  31. package/src/compaction/template.ts +15 -0
  32. package/src/compaction/types.ts +3 -0
  33. package/src/config/loader.ts +75 -10
  34. package/src/config/types.ts +40 -7
  35. package/src/engine/a2a.ts +1 -1
  36. package/src/engine/claude-cli.ts +136 -4
  37. package/src/engine/codex-cli.ts +74 -0
  38. package/src/engine/engine-meta-labels.ts +2 -0
  39. package/src/engine/openai-compatible.ts +142 -29
  40. package/src/engine/types.ts +7 -0
  41. package/src/imagegen/generate.ts +30 -5
  42. package/src/imagegen/types.ts +6 -0
  43. package/src/media/capabilities.ts +8 -0
  44. package/src/memory/inject.ts +66 -7
  45. package/src/multimodal/blocks.ts +14 -0
  46. package/src/multimodal/load.ts +21 -2
  47. package/src/multimodal/model-image.ts +127 -0
  48. package/src/server/index.ts +118 -39
  49. package/src/server/run-turn.ts +65 -16
  50. package/src/server/session-compact.ts +138 -0
  51. package/src/server/thinking-resolve.ts +30 -0
  52. package/src/ssh/exec.ts +55 -22
  53. package/src/storage/sessions.ts +40 -15
  54. package/src/tools/exec/tools.ts +3 -0
  55. package/src/tools/file/analyze.ts +46 -7
  56. package/src/tools/file/remote.ts +31 -10
  57. package/src/tools/file/tools.ts +86 -19
  58. package/src/tools/image/tools.ts +6 -0
  59. package/src/tools/registry.ts +14 -0
  60. package/src/types/events.ts +23 -2
  61. package/web/dist/assets/{index-Cl1xtY5g.js → index-40x__Izy.js} +96 -96
  62. package/web/dist/assets/index-40x__Izy.js.map +1 -0
  63. package/web/dist/assets/index-CZFgQRsq.css +32 -0
  64. package/web/dist/index.html +2 -2
  65. package/web-mobile/dist/assets/index-CxILeHfe.js +88 -0
  66. package/web-mobile/dist/assets/{index-BpsX8_mX.js.map → index-CxILeHfe.js.map} +1 -1
  67. package/web-mobile/dist/assets/{index-DZXivrMo.css → index-Cyr13VGR.css} +1 -1
  68. package/web-mobile/dist/index.html +2 -2
  69. package/web/dist/assets/index-Cl1xtY5g.js.map +0 -1
  70. package/web/dist/assets/index-D0q6NZer.css +0 -32
  71. package/web-mobile/dist/assets/index-BpsX8_mX.js +0 -88
@@ -41,7 +41,9 @@ import type { ModelCapability } from '../config/types.ts';
41
41
  import { withFromAgentHeader } from './a2a.ts';
42
42
  import type { AgentEngine, ResolvedAttachment, TurnInput } from './types.ts';
43
43
  import { buildOpenAiUserContent } from '../multimodal/user-content.ts';
44
- import { resolveAttachmentByHash } from '../attachments/store.ts';
44
+ import { resolveAttachmentForModel } from '../attachments/store.ts';
45
+ import { DEFAULT_MAX_IMAGE_EDGE } from '../multimodal/model-image.ts';
46
+ import { withoutMemoryBlock } from '../memory/inject.ts';
45
47
  import { openAiReasoningState, withReasoningRetry } from './reasoning-retry.ts';
46
48
  import { formatSampling, isSamplingParamError, samplingBody } from './sampling.ts';
47
49
  import { insideOpenThink, splitInlineThink } from './inline-think.ts';
@@ -304,6 +306,31 @@ export function stripScaffold(text: string): string {
304
306
  .trim();
305
307
  }
306
308
 
309
+ /**
310
+ * Turns recorded before the round text was stored: the closing message
311
+ * holds every round's text, joined by the blank lines that stood where
312
+ * the calls were. When the number of pieces is exactly one per tool
313
+ * round plus the closing reply, give each round its piece back; any
314
+ * other shape stays as it was (better unsplit than misattributed).
315
+ */
316
+ /** The text after the last run of blank lines that stood where tool
317
+ * calls were; null when the text has no such gap. */
318
+ export function lastRoundPiece(text: string): string | null {
319
+ const parts = text.split(/\n{4,}/);
320
+ if (parts.length < 2) return null;
321
+ const last = parts[parts.length - 1]!.trim();
322
+ return last || null;
323
+ }
324
+
325
+ export function splitLegacyRoundText(text: string, toolRounds: number): { leads: string[]; final: string } | null {
326
+ const parts = text.split(/\n{4,}/);
327
+ if (parts.length !== toolRounds + 1) return null;
328
+ const leads = parts.slice(0, toolRounds).map((p) => p.trim());
329
+ const final = parts[toolRounds]!.trim();
330
+ if (!final) return null;
331
+ return { leads, final };
332
+ }
333
+
307
334
  // Exported for the history-rebuild regression tests
308
335
  // (./tool-trace.test.mts) — the shape of what we hand a stateless
309
336
  // backend is load-bearing enough to assert on directly.
@@ -317,6 +344,11 @@ export async function buildMessages(
317
344
  * reintroduce the bug this parameter exists to prevent — replaying
318
345
  * image blocks at a model that cannot accept them. */
319
346
  caps: readonly ModelCapability[],
347
+ /** attachments.maxImageEdge: replayed images go out scaled, like the
348
+ * turn they were first sent in. */
349
+ maxImageEdge: number = DEFAULT_MAX_IMAGE_EDGE,
350
+ /** Turns before this ts lose their memory block in the replay. */
351
+ memoryDropBefore = 0,
320
352
  ): Promise<ChatMessage[]> {
321
353
  // The latest compaction summary is appended to the ONE leading system
322
354
  // message instead of travelling as a second `system` entry. Strict
@@ -373,34 +405,51 @@ export async function buildMessages(
373
405
  // because sessions recorded during that window carry fabricated ones.
374
406
  //
375
407
  // Full investigation: private/toolcall-investigation.md.
376
- const pendingCalls: Array<{ id: string; name: string; args: string }> = [];
408
+ // One assistant message per ROUND, as the model produced them: the
409
+ // text it wrote in that reply plus its calls, then the results. Merging
410
+ // a whole turn's calls into one message and appending all the text
411
+ // after the last result taught the model that tool work looks like
412
+ // narrated text with gaps — measured 2026-10-06 on a Qwen session that
413
+ // started answering "skill loaded, file written" without calling a
414
+ // single tool, in exactly that shape.
415
+ type Round = { calls: Array<{ id: string; name: string; args: string }>; lead?: string };
416
+ const pendingRounds: Round[] = [];
377
417
  const pendingResults = new Map<string, string>();
378
-
379
- /** Emit the collected tool activity of one turn, ahead of that turn's
380
- * assistant text. Calls without a matching result are dropped: an
381
- * assistant `tool_calls` entry whose result never arrives is a hard
382
- * 400 on most backends, and a crashed turn can leave exactly that. */
418
+ /** A result arrived since the last call: the next call opens a new round. */
419
+ let roundClosed = true;
420
+
421
+ /** Emit the collected tool activity of one turn, round by round, ahead
422
+ * of that turn's closing text. Calls without a matching result are
423
+ * dropped: an assistant `tool_calls` entry whose result never arrives
424
+ * is a hard 400 on most backends, and a crashed turn can leave
425
+ * exactly that. */
383
426
  const flushToolTurn = () => {
384
- if (pendingCalls.length === 0) return;
385
- const paired = pendingCalls.filter((c) => pendingResults.has(c.id));
386
- pendingCalls.length = 0;
387
- if (paired.length === 0) { pendingResults.clear(); return; }
427
+ if (pendingRounds.length === 0) return;
428
+ const rounds = pendingRounds.splice(0);
429
+ roundClosed = true;
388
430
  flush(); // close any open text message first — ordering is load-bearing
389
- messages.push({
390
- role: 'assistant',
391
- content: null,
392
- tool_calls: paired.map((c) => ({
393
- id: c.id,
394
- type: 'function' as const,
395
- function: { name: c.name, arguments: c.args || '{}' },
396
- })),
397
- } as unknown as ChatMessage);
398
- for (const c of paired) {
431
+ for (const r of rounds) {
432
+ const paired = r.calls.filter((c) => pendingResults.has(c.id));
433
+ if (paired.length === 0) {
434
+ if (r.lead) messages.push({ role: 'assistant', content: r.lead });
435
+ continue;
436
+ }
399
437
  messages.push({
400
- role: 'tool',
401
- tool_call_id: c.id,
402
- content: pendingResults.get(c.id)!,
438
+ role: 'assistant',
439
+ content: r.lead || null,
440
+ tool_calls: paired.map((c) => ({
441
+ id: c.id,
442
+ type: 'function' as const,
443
+ function: { name: c.name, arguments: c.args || '{}' },
444
+ })),
403
445
  } as unknown as ChatMessage);
446
+ for (const c of paired) {
447
+ messages.push({
448
+ role: 'tool',
449
+ tool_call_id: c.id,
450
+ content: pendingResults.get(c.id)!,
451
+ } as unknown as ChatMessage);
452
+ }
404
453
  }
405
454
  pendingResults.clear();
406
455
  };
@@ -426,7 +475,12 @@ export async function buildMessages(
426
475
  // openai-compatible backends. Engines with stateful resumed
427
476
  // sessions (claude-cli/codex-cli) don't reconstruct full
428
477
  // history so they ignore this code path.
429
- const composed = ev.ephemeral ? `${ev.ephemeral}\n\n${headed}` : headed;
478
+ // Dropped after a pause (memoryDropBefore): the turn keeps its
479
+ // framing, only the recalled notes go — the cache they protected
480
+ // has expired, and stale recall in every replayed turn costs
481
+ // context and measurably suppresses tool calls.
482
+ const eph = ev.ephemeral && ev.ts < memoryDropBefore ? withoutMemoryBlock(ev.ephemeral) : ev.ephemeral;
483
+ const composed = eph ? `${eph}\n\n${headed}` : headed;
430
484
  // Phase Y.B — when this past turn carried attachments, it must
431
485
  // become its own array-content message (can't be collapsed with
432
486
  // siblings). Resolve refs from disk and build the content parts;
@@ -437,7 +491,7 @@ export async function buildMessages(
437
491
  const resolved: ResolvedAttachment[] = [];
438
492
  for (const a of ev.attachments) {
439
493
  try {
440
- const r = await resolveAttachmentByHash({ hash: a.hash, expectedMime: a.mime });
494
+ const r = await resolveAttachmentForModel({ hash: a.hash, expectedMime: a.mime, maxImageEdge });
441
495
  resolved.push({
442
496
  hash: a.hash,
443
497
  path: r.path,
@@ -490,6 +544,41 @@ export async function buildMessages(
490
544
  pendingRole = 'user';
491
545
  pendingText = pendingText ? `${pendingText}\n\n${composed}` : composed;
492
546
  } else if (ev.kind === 'assistant_message') {
547
+ // The closing text of a turn with tool rounds: only the last
548
+ // reply's own text belongs here. New records carry it as `final`
549
+ // (earlier rounds' text sits on their calls); older ones get it
550
+ // split back out where possible (splitLegacyRoundText).
551
+ let closing = ev.text;
552
+ if (pendingRounds.length === 0) {
553
+ // A reply without any tool call that still shows the blank-line
554
+ // gaps where calls would be is a narrated imitation of tool work
555
+ // ("skill loaded … file written …" — nothing was run). Replaying
556
+ // it teaches the model to keep doing that; only its last piece
557
+ // goes back in. On the session where it happened this took the
558
+ // next turn from 4/8 to 9/10 with real calls (2026-10-06).
559
+ const last = lastRoundPiece(ev.text);
560
+ if (last !== null) closing = last;
561
+ } else {
562
+ if (ev.final !== undefined) closing = ev.final;
563
+ else if (!pendingRounds.some((r) => r.lead)) {
564
+ const split = splitLegacyRoundText(ev.text, pendingRounds.length);
565
+ if (split) {
566
+ split.leads.forEach((lead, i) => {
567
+ if (lead) pendingRounds[i]!.lead = sanitizeAssistantText(lead).text;
568
+ });
569
+ closing = split.final;
570
+ } else {
571
+ // Pieces that cannot be matched to their rounds: keep the
572
+ // closing reply only. The interim "loading the skill… —
573
+ // file written…" lines, replayed after the work, are what the
574
+ // model learned to imitate instead of calling tools; with
575
+ // them gone, the same session went from 69 % to 12/12 turns
576
+ // with real calls (2026-10-06).
577
+ const last = lastRoundPiece(ev.text);
578
+ if (last !== null) closing = last;
579
+ }
580
+ }
581
+ }
493
582
  // This turn's tool activity happened BEFORE the model's closing
494
583
  // text, so it goes out first.
495
584
  flushToolTurn();
@@ -497,17 +586,25 @@ export async function buildMessages(
497
586
  // block sat in the assistant role contain models' own fabricated
498
587
  // <somora-tool-log> blocks. Strip them on the way back in so a
499
588
  // poisoned session heals instead of compounding.
500
- const cleaned = sanitizeAssistantText(ev.text).text;
589
+ const cleaned = sanitizeAssistantText(closing).text;
590
+ if (!cleaned) continue;
501
591
  if (pendingRole !== 'assistant') flush();
502
592
  pendingRole = 'assistant';
503
593
  pendingText = pendingText ? `${pendingText}\n\n${cleaned}` : cleaned;
504
594
  } else if (ev.kind === 'tool_call') {
505
- pendingCalls.push({
595
+ if (roundClosed || pendingRounds.length === 0) {
596
+ pendingRounds.push({ calls: [] });
597
+ roundClosed = false;
598
+ }
599
+ const round = pendingRounds[pendingRounds.length - 1]!;
600
+ if (ev.lead && !round.lead) round.lead = sanitizeAssistantText(ev.lead).text;
601
+ round.calls.push({
506
602
  id: ev.callId,
507
603
  name: ev.tool,
508
604
  args: JSON.stringify(ev.input ?? {}),
509
605
  });
510
606
  } else if (ev.kind === 'tool_result') {
607
+ roundClosed = true;
511
608
  const payload = ev.error !== undefined ? { error: ev.error } : (ev.output ?? null);
512
609
  let text: string;
513
610
  try {
@@ -831,6 +928,8 @@ export const openAiCompatibleEngine: AgentEngine = {
831
928
  compactions,
832
929
  pdfMode,
833
930
  resolvedModel.model.capabilities,
931
+ input.maxImageEdge,
932
+ input.memoryDropBefore ?? 0,
834
933
  );
835
934
  const estTokens = estimateTokens(messages);
836
935
  const ctxRatio = estTokens / resolvedModel.model.contextWindow;
@@ -861,6 +960,10 @@ export const openAiCompatibleEngine: AgentEngine = {
861
960
  // monotonically — matches how claude-cli's SDK presents
862
961
  // tool-using turns to us (one final assistant_message at the end).
863
962
  let cumulative = '';
963
+ /** Text of the latest round, and how many rounds ran tools — for
964
+ * the `final` field of the closing assistant_message. */
965
+ let lastRoundContent = '';
966
+ let toolRoundsRun = 0;
864
967
  // Reasoning text across rounds of this turn — see roundThinking.
865
968
  let turnThinking = '';
866
969
  /** Rounds whose request was sent — the reactive context retry is only
@@ -1515,6 +1618,7 @@ export const openAiCompatibleEngine: AgentEngine = {
1515
1618
  if (roundContent) {
1516
1619
  cumulative = cumulative ? `${cumulative}\n\n${roundContent}` : roundContent;
1517
1620
  }
1621
+ lastRoundContent = roundContent;
1518
1622
  if (roundThinking) {
1519
1623
  turnThinking = turnThinking ? `${turnThinking}\n\n${roundThinking}` : roundThinking;
1520
1624
  roundThinking = '';
@@ -1526,6 +1630,7 @@ export const openAiCompatibleEngine: AgentEngine = {
1526
1630
  if (effectiveSignal.aborted) throw new DOMException('Aborted', 'AbortError');
1527
1631
 
1528
1632
  lastRoundHadTools = roundToolCalls.size > 0;
1633
+ if (lastRoundHadTools) toolRoundsRun++;
1529
1634
  if (roundToolCalls.size === 0) {
1530
1635
  // Nothing visible and nothing to run, but the model was
1531
1636
  // thinking: the output cap ended the response inside the
@@ -1726,6 +1831,7 @@ export const openAiCompatibleEngine: AgentEngine = {
1726
1831
  // shouldn't request them. Bail with a clear error.
1727
1832
  throw new Error('model requested tool_calls but no tool registry was passed to the engine');
1728
1833
  }
1834
+ let leadPending = roundContent;
1729
1835
  for (const { call, args: parsedArgs, fault, why } of calls) {
1730
1836
  yield {
1731
1837
  kind: 'tool_call',
@@ -1736,7 +1842,11 @@ export const openAiCompatibleEngine: AgentEngine = {
1736
1842
  // The fragment is kept HERE, in the session record, because it
1737
1843
  // is the evidence of what went wrong. It never reaches the wire.
1738
1844
  input: parsedArgs,
1845
+ // What the model said in this reply, stored once per round so
1846
+ // a rebuilt history keeps it next to its calls.
1847
+ ...(leadPending ? { lead: leadPending } : {}),
1739
1848
  };
1849
+ leadPending = '';
1740
1850
  if (fault) {
1741
1851
  // Not run: with half its arguments the call would either fail
1742
1852
  // in a confusing way or, worse, do something partial. The two
@@ -2190,7 +2300,10 @@ export const openAiCompatibleEngine: AgentEngine = {
2190
2300
  yield { kind: 'thinking_message', ts: ts(), engine: ENGINE, text: turnThinking };
2191
2301
  turnThinking = '';
2192
2302
  }
2193
- yield { kind: 'assistant_message', ts: ts(), engine: ENGINE, text: cumulative };
2303
+ // After tool rounds, the last reply's own text — the earlier
2304
+ // rounds' text travels on their tool_call events.
2305
+ const final = toolRoundsRun > 0 && lastRoundContent && cumulative.endsWith(lastRoundContent) ? lastRoundContent : undefined;
2306
+ yield { kind: 'assistant_message', ts: ts(), engine: ENGINE, text: cumulative, ...(final !== undefined ? { final } : {}) };
2194
2307
  } else if (round >= maxRounds) {
2195
2308
  // Loop ended at the cap and the force-summary path didn't
2196
2309
  // populate cumulative either — synthesize a marker so the
@@ -260,6 +260,13 @@ export interface TurnInput {
260
260
  * (openai-compatible) reconstruct the full content array per turn.
261
261
  */
262
262
  attachments?: ResolvedAttachment[];
263
+ /** attachments.maxImageEdge — engines that replay past attachments
264
+ * from disk scale them the same way. */
265
+ maxImageEdge?: number;
266
+ /** openai-compatible: past turns before this ts are replayed without
267
+ * their memory block (dropped after a pause, see
268
+ * providers.<name>.dropMemoryBlocksAfterIdleMinutes). */
269
+ memoryDropBefore?: number;
263
270
  }
264
271
 
265
272
  export interface AgentEngine {
@@ -94,6 +94,35 @@ export class ImageGenError extends Error {
94
94
  }
95
95
  }
96
96
 
97
+ /** Why the image came back in another size than asked for. Edit models
98
+ * commonly take their canvas from the first reference image and use
99
+ * `size` only as a pixel budget; when the result has that reference's
100
+ * shape, say so instead of guessing at caps and rounding — the guess
101
+ * sent an agent hunting for a model bug (2026-10-05). */
102
+ export function sizeSubstitutionNote(
103
+ requested: { width: number; height: number },
104
+ got: { width: number; height: number },
105
+ firstReference: { width: number; height: number } | null,
106
+ referenceCount: number,
107
+ ): string {
108
+ const head = `Requested ${requested.width}x${requested.height} but the image came back ${got.width}x${got.height}.`;
109
+ const ratio = (d: { width: number; height: number }) => d.width / d.height;
110
+ if (firstReference && Math.abs(ratio(got) / ratio(firstReference) - 1) < 0.03) {
111
+ return (
112
+ `${head} It has the shape of the first reference image (${firstReference.width}x${firstReference.height}): ` +
113
+ 'this edit model takes its canvas from reference image 1, and size only sets the pixel budget. ' +
114
+ `For a ${requested.width}x${requested.height} result, pass a first reference with that aspect ratio.`
115
+ );
116
+ }
117
+ if (referenceCount > 0) {
118
+ return (
119
+ `${head} Reference images were passed — edit models often take the shape of the first reference; ` +
120
+ "check the model's endpoint_note in image_models. Otherwise the endpoint capped or rounded the size."
121
+ );
122
+ }
123
+ return `${head} The endpoint substituted a size — it may cap dimensions or round to sizes it supports.`;
124
+ }
125
+
97
126
  function ensureEnabled(config: Config): void {
98
127
  if (!config.imageGen?.enabled) {
99
128
  throw new ImageGenError(
@@ -531,11 +560,7 @@ async function generateOnce(
531
560
  const firstDims = readDimensions(decoded[0]!.bytes);
532
561
  if (requested && firstDims &&
533
562
  (requested.width !== firstDims.width || requested.height !== firstDims.height)) {
534
- warnings.push(
535
- `Requested ${requested.width}x${requested.height} but the image came back ` +
536
- `${firstDims.width}x${firstDims.height}. The endpoint substituted a size — ` +
537
- `it may cap dimensions or round to sizes it supports.`,
538
- );
563
+ warnings.push(sizeSubstitutionNote(requested, firstDims, references[0] ? readDimensions(references[0].bytes) : null, references.length));
539
564
  logger.info({
540
565
  msg: 'imagegen.size_substituted',
541
566
  model: entry.name,
@@ -106,6 +106,12 @@ export interface ModelCapabilities {
106
106
  * something to show and `analyze_file` something to read.
107
107
  */
108
108
  variants?: string[];
109
+ /** The endpoint's own words about the model and its parameters — the
110
+ * catalog's `note` and `supported_parameters.<field>.note`. Passed to
111
+ * the agent as they are: they explain behaviour somora cannot know,
112
+ * such as an edit model taking its shape from the first reference. */
113
+ endpointNote?: string;
114
+ paramNotes?: Record<string, string>;
109
115
  }
110
116
 
111
117
  /** Does this model accept `field`? Unknown counts as yes — see the note
@@ -67,6 +67,7 @@ interface ParamSpec {
67
67
  also_accepts?: unknown;
68
68
  min?: unknown;
69
69
  max?: unknown;
70
+ note?: unknown;
70
71
  }
71
72
 
72
73
  function supportedParameters(raw: Record<string, unknown>): Record<string, ParamSpec> | null {
@@ -284,7 +285,14 @@ export async function resolveCapabilities(
284
285
  if (hint) recommended[field] = hint;
285
286
  }
286
287
  const sizeAlsoAccepts = asStringArray(params?.size?.also_accepts);
288
+ const endpointNote = typeof row.raw.note === 'string' && row.raw.note.trim() ? row.raw.note.trim().slice(0, 1500) : undefined;
289
+ const paramNotes: Record<string, string> = {};
290
+ for (const [field, spec] of Object.entries(params ?? {})) {
291
+ if (typeof spec?.note === 'string' && spec.note.trim()) paramNotes[field] = spec.note.trim().slice(0, 500);
292
+ }
287
293
  return {
294
+ ...(endpointNote ? { endpointNote } : {}),
295
+ ...(Object.keys(paramNotes).length > 0 ? { paramNotes } : {}),
288
296
  known: true,
289
297
  source: 'catalog',
290
298
  values,
@@ -41,8 +41,57 @@ type AutoInjectCfg = {
41
41
  historyWeightEmpty: number;
42
42
  historyTurnChars: number;
43
43
  shortQueryBm25Weight: number | null;
44
+ skipRepeats?: boolean;
44
45
  };
45
46
 
47
+ /** How a hit is shown in the block: the first 600 characters. */
48
+ function snippetOf(text: string): string {
49
+ return text.length > 600 ? text.slice(0, 600).trimEnd() + '…' : text;
50
+ }
51
+
52
+ /** Identity of an injected note section: where it is from and what was
53
+ * shown. The same section shown again is a repeat; another section of
54
+ * the same note is not. */
55
+ export function memoryHitKey(source: string, slug: string, snippet: string): string {
56
+ snippet = snippet.trimEnd();
57
+ let h = 0;
58
+ for (let i = 0; i < snippet.length; i++) h = (Math.imul(h, 31) + snippet.charCodeAt(i)) | 0;
59
+ return `${source}/${slug}#${(h >>> 0).toString(36)}`;
60
+ }
61
+
62
+ const BLOCK_RE = /<memory-context>[\s\S]*?<\/memory-context>/g;
63
+ const HIT_HEAD = /^### \[([a-z]+)\/(.+?) · score=[0-9.]+\]$/;
64
+
65
+ /**
66
+ * The note sections already in front of the model: parsed from the
67
+ * memory blocks stored with this session's user messages after `sinceTs`
68
+ * (the last compaction, or the point where old blocks were dropped).
69
+ */
70
+ export function injectedKeysInHistory(history: NormalizedEvent[], sinceTs: number): Set<string> {
71
+ const keys = new Set<string>();
72
+ for (const ev of history) {
73
+ if (ev.kind !== 'user_message' || ev.ts <= sinceTs) continue;
74
+ const eph = (ev as { ephemeral?: string }).ephemeral;
75
+ if (!eph || !eph.includes('<memory-context>')) continue;
76
+ for (const block of eph.match(BLOCK_RE) ?? []) {
77
+ const body = block.replace(/\n?<\/memory-context>$/, '');
78
+ for (const part of body.split(/\n(?=### \[)/)) {
79
+ const nl = part.indexOf('\n');
80
+ if (nl < 0) continue;
81
+ const head = HIT_HEAD.exec(part.slice(0, nl));
82
+ if (head) keys.add(memoryHitKey(head[1]!, head[2]!, part.slice(nl + 1)));
83
+ }
84
+ }
85
+ }
86
+ return keys;
87
+ }
88
+
89
+ /** Remove the memory block(s) from a stored ephemeral text, keeping the
90
+ * rest (turn framing, review block). '' when nothing else is left. */
91
+ export function withoutMemoryBlock(ephemeral: string): string {
92
+ return ephemeral.replace(BLOCK_RE, '').replace(/\n{3,}/g, '\n\n').trim();
93
+ }
94
+
46
95
  export interface InjectResult {
47
96
  /**
48
97
  * `<memory-context>` block ready to be inlined as ephemeral per-turn
@@ -60,10 +109,13 @@ export async function injectMemoryContext(args: {
60
109
  history: NormalizedEvent[];
61
110
  userMessage: string;
62
111
  cfg: AutoInjectCfg;
63
- }): Promise<InjectResult> {
112
+ /** Note sections the model still has in context (skipRepeats). */
113
+ alreadyInContext?: Set<string>;
114
+ }): Promise<InjectResult & { skippedRepeats: number }> {
115
+ const skip = args.cfg.skipRepeats !== false ? args.alreadyInContext : undefined;
64
116
  const query = args.userMessage;
65
117
  if (!query.trim()) {
66
- return { ephemeralContext: undefined, injectedCount: 0, hits: [] };
118
+ return { ephemeralContext: undefined, injectedCount: 0, hits: [], skippedRepeats: 0 };
67
119
  }
68
120
  const context = buildRecallContext(args.history, args.cfg.queryTurns, args.cfg.historyTurnChars);
69
121
  const contextWeight = historyWeightFor(query, args.cfg);
@@ -75,24 +127,31 @@ export async function injectMemoryContext(args: {
75
127
  const shortBm25 = terms > 0 && terms <= 2 && args.cfg.shortQueryBm25Weight !== null
76
128
  ? args.cfg.shortQueryBm25Weight
77
129
  : undefined;
78
- const hits = await args.mgr.search(query, {
79
- limit: args.cfg.maxResults,
130
+ // Ask for a few more when repeats will be left out, so their places go
131
+ // to the next hits instead of shrinking the block.
132
+ const extra = skip && skip.size > 0 ? Math.min(skip.size, 10) : 0;
133
+ const found = await args.mgr.search(query, {
134
+ limit: args.cfg.maxResults + extra,
80
135
  minScore: args.cfg.minScore,
81
136
  ...(context ? { context, contextWeight, alsoQueryAlone } : {}),
82
137
  ...(shortBm25 !== undefined ? { bm25Weight: shortBm25 } : {}),
83
138
  });
84
139
 
140
+ const fresh = skip ? found.filter((h) => !skip.has(memoryHitKey(h.source, h.slug, snippetOf(h.text)))) : found;
141
+ const skippedRepeats = found.length - fresh.length;
142
+ const hits = fresh.slice(0, args.cfg.maxResults);
85
143
  if (hits.length === 0) {
86
- return { ephemeralContext: undefined, injectedCount: 0, hits: [] };
144
+ return { ephemeralContext: undefined, injectedCount: 0, hits: [], skippedRepeats };
87
145
  }
88
146
  const block = formatMemoryBlock(hits, args.cfg.maxTokens);
89
147
  if (!block) {
90
- return { ephemeralContext: undefined, injectedCount: 0, hits };
148
+ return { ephemeralContext: undefined, injectedCount: 0, hits, skippedRepeats };
91
149
  }
92
150
  return {
93
151
  ephemeralContext: block,
94
152
  injectedCount: hits.length,
95
153
  hits,
154
+ skippedRepeats,
96
155
  };
97
156
  }
98
157
 
@@ -180,7 +239,7 @@ function formatMemoryBlock(hits: Hit[], maxTokens: number): string {
180
239
  used += '## Relevant hits for this turn\n\n'.length;
181
240
  for (const h of hits) {
182
241
  const ref = `[${h.source}/${h.slug} · score=${h.score.toFixed(2)}]`;
183
- const snippet = h.text.length > 600 ? h.text.slice(0, 600).trimEnd() + '…' : h.text;
242
+ const snippet = snippetOf(h.text);
184
243
  const block = `### ${ref}\n${snippet}`;
185
244
  const cost = block.length + 2;
186
245
  if (used + cost > maxChars && kept > 0) break;
@@ -94,6 +94,20 @@ export function toOpenAiContent(att: LoadedAttachment, prompt?: string) {
94
94
  return [{ type: 'text' as const, text: userText }];
95
95
  }
96
96
 
97
+ /** A PDF for a worker that sees images but cannot read PDFs: its pages
98
+ * as PNG images, the way file_read and chat attachments hand PDFs to
99
+ * such models. `note` says when only the first pages are included. */
100
+ export function pdfPagesToOpenAiContent(pagesBase64: string[], prompt: string | undefined, note?: string) {
101
+ const userText = (prompt ?? defaultPromptFor('pdf')) + (note ? `\n\n${note}` : '');
102
+ return [
103
+ { type: 'text' as const, text: userText },
104
+ ...pagesBase64.map((data) => ({
105
+ type: 'image_url' as const,
106
+ image_url: { url: `data:image/png;base64,${data}` },
107
+ })),
108
+ ];
109
+ }
110
+
97
111
  function defaultPromptFor(kind: DetectedKind): string {
98
112
  if (kind === 'image') return 'Describe this image in detail.';
99
113
  if (kind === 'pdf') return 'Summarize this document in detail.';
@@ -13,6 +13,7 @@
13
13
 
14
14
  import { readFile, stat } from 'node:fs/promises';
15
15
  import { detectMimeFromPath, type DetectedMime } from './mime.ts';
16
+ import { fitImageForModel, imageSourceCap } from './model-image.ts';
16
17
 
17
18
  export interface LoadedAttachment {
18
19
  /** Absolute path that was read (caller-provided). */
@@ -33,6 +34,11 @@ export interface LoadOptions {
33
34
  /** Max bytes for text files (so file_read does not OOM on a 1 GB log).
34
35
  * Default 1 MB; use file_read's existing line/offset paging for bigger. */
35
36
  maxTextBytes?: number;
37
+ /** Scale images down to this longest side before they are returned
38
+ * (attachments.maxImageEdge). 0 = as they are. When set, a source
39
+ * image may be up to IMAGE_SOURCE_BYTES; maxImageBytes applies to
40
+ * the scaled result. */
41
+ maxImageEdge?: number;
36
42
  }
37
43
 
38
44
  const DEFAULT_MAX_IMAGE = 5 * 1024 * 1024;
@@ -44,6 +50,8 @@ export async function loadAttachment(
44
50
  options: LoadOptions = {},
45
51
  ): Promise<LoadedAttachment> {
46
52
  const maxImage = options.maxImageBytes ?? DEFAULT_MAX_IMAGE;
53
+ const maxEdge = options.maxImageEdge ?? 0;
54
+ const maxImageSource = imageSourceCap({ maxImageBytes: maxImage, maxImageEdge: maxEdge });
47
55
  const maxPdf = options.maxPdfBytes ?? DEFAULT_MAX_PDF;
48
56
  const maxText = options.maxTextBytes ?? DEFAULT_MAX_TEXT;
49
57
 
@@ -53,7 +61,7 @@ export async function loadAttachment(
53
61
  }
54
62
  // Cheap pre-check before we even sniff bytes — if the file is bigger
55
63
  // than the largest cap we'd ever apply, reject without reading.
56
- const absoluteMax = Math.max(maxImage, maxPdf, maxText);
64
+ const absoluteMax = Math.max(maxImageSource, maxPdf, maxText);
57
65
  if (s.size > absoluteMax) {
58
66
  throw new Error(
59
67
  `multimodal: '${path}' is ${s.size} bytes, exceeds the largest configured cap (${absoluteMax})`,
@@ -65,7 +73,7 @@ export async function loadAttachment(
65
73
  // Per-kind size enforcement. We DO this before the full read so a
66
74
  // mid-sized text file (5 MB) doesn't pass image validation just
67
75
  // because the absolute-max ceiling is bigger.
68
- if (mime.kind === 'image' && s.size > maxImage) {
76
+ if (mime.kind === 'image' && s.size > maxImageSource) {
69
77
  throw new Error(
70
78
  `multimodal: image '${path}' is ${s.size} bytes, exceeds image cap ${maxImage} ` +
71
79
  `(raise config.attachments.maxImageBytes, or downscale first — ` +
@@ -82,5 +90,16 @@ export async function loadAttachment(
82
90
  }
83
91
 
84
92
  const bytes = await readFile(path);
93
+ if (mime.kind === 'image') {
94
+ const fitted = await fitImageForModel(bytes, mime.mimeType, maxEdge);
95
+ if (fitted.bytes.length > maxImage) {
96
+ throw new Error(
97
+ `multimodal: image '${path}' is ${fitted.bytes.length} bytes${fitted.resized ? ' after scaling' : ''}, exceeds image cap ${maxImage} ` +
98
+ `(raise config.attachments.maxImageBytes, or lower attachments.maxImageEdge)`,
99
+ );
100
+ }
101
+ const fittedMime = fitted.mimeType === mime.mimeType ? mime : { ...mime, mimeType: fitted.mimeType };
102
+ return { path, bytes: fitted.bytes, mime: fittedMime, size: fitted.bytes.length };
103
+ }
85
104
  return { path, bytes, mime, size: bytes.length };
86
105
  }