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
@@ -0,0 +1,127 @@
1
+ // Every image that goes to a model passes through here first: a tool
2
+ // result (file_read, image_generate's review, an external MCP tool), a
3
+ // chat attachment (also the screenshot button), and an attachment
4
+ // replayed from the history. Images whose longer side exceeds
5
+ // `attachments.maxImageEdge` are scaled down to it.
6
+ //
7
+ // Why: the large providers scale big images down themselves, so the
8
+ // extra pixels buy nothing there, but they still travel with every
9
+ // request that carries the history. A session with a dozen 6 MB
10
+ // screenshots ended up with Bad Request answers from one provider, and
11
+ // local models pay for every pixel in context.
12
+ //
13
+ // The file on disk is never changed. Text stays readable: a 4K or
14
+ // Retina screenshot is scaled by about half, which brings its text to
15
+ // the size it has on an ordinary screen.
16
+
17
+ import { createHash } from 'node:crypto';
18
+ import { existsSync } from 'node:fs';
19
+ import { readFile, stat, writeFile } from 'node:fs/promises';
20
+ import { readDimensions } from './dimensions.ts';
21
+ import { logger } from '../server/logger.ts';
22
+
23
+ export const DEFAULT_MAX_IMAGE_EDGE = 2048;
24
+ /** With scaling on, the largest source image somora reads or accepts as
25
+ * an upload. `attachments.maxImageBytes` then applies to what is sent. */
26
+ export const IMAGE_SOURCE_BYTES = 50 * 1024 * 1024;
27
+
28
+ /** The read/upload limit for a source image under this config. */
29
+ export function imageSourceCap(att: { maxImageBytes: number; maxImageEdge?: number }): number {
30
+ return (att.maxImageEdge ?? DEFAULT_MAX_IMAGE_EDGE) > 0 ? Math.max(att.maxImageBytes, IMAGE_SOURCE_BYTES) : att.maxImageBytes;
31
+ }
32
+
33
+ export interface FittedImage {
34
+ bytes: Buffer;
35
+ mimeType: string;
36
+ /** True when the image was scaled down. */
37
+ resized: boolean;
38
+ /** Dimensions before and after, when they are known. */
39
+ from?: { width: number; height: number };
40
+ to?: { width: number; height: number };
41
+ }
42
+
43
+ type SharpFactory = (input: Buffer, options?: Record<string, unknown>) => {
44
+ rotate(): ReturnType<SharpFactory>;
45
+ resize(options: Record<string, unknown>): ReturnType<SharpFactory>;
46
+ png(options?: Record<string, unknown>): ReturnType<SharpFactory>;
47
+ jpeg(options?: Record<string, unknown>): ReturnType<SharpFactory>;
48
+ webp(options?: Record<string, unknown>): ReturnType<SharpFactory>;
49
+ toBuffer(options: { resolveWithObject: true }): Promise<{ data: Buffer; info: { width: number; height: number } }>;
50
+ };
51
+
52
+ let sharpPromise: Promise<SharpFactory | null> | undefined;
53
+ async function loadSharp(): Promise<SharpFactory | null> {
54
+ sharpPromise ??= import('sharp')
55
+ .then((m) => (m.default ?? m) as unknown as SharpFactory)
56
+ .catch(() => null);
57
+ return sharpPromise;
58
+ }
59
+
60
+ /** Scale an image down so its longer side is at most `maxEdge` pixels.
61
+ * `maxEdge` 0 (or less) switches it off. An image that already fits,
62
+ * a format we cannot read, or a missing image library returns the
63
+ * input unchanged — scaling is an optimisation, never a reason to fail. */
64
+ export async function fitImageForModel(bytes: Buffer, mimeType: string, maxEdge: number): Promise<FittedImage> {
65
+ const unchanged: FittedImage = { bytes, mimeType, resized: false };
66
+ if (!(maxEdge > 0)) return unchanged;
67
+ const dims = readDimensions(bytes);
68
+ if (dims && Math.max(dims.width, dims.height) <= maxEdge) return { ...unchanged, from: dims, to: dims };
69
+ const sharp = await loadSharp();
70
+ if (!sharp) return unchanged;
71
+ try {
72
+ // A GIF becomes its first frame as PNG: models read single frames.
73
+ const outMime = mimeType === 'image/jpeg' || mimeType === 'image/webp' ? mimeType : 'image/png';
74
+ let pipeline = sharp(bytes, { animated: false, limitInputPixels: 268_402_689 })
75
+ .rotate()
76
+ .resize({ width: maxEdge, height: maxEdge, fit: 'inside', withoutEnlargement: true });
77
+ pipeline =
78
+ outMime === 'image/jpeg'
79
+ ? pipeline.jpeg({ quality: 88, mozjpeg: true })
80
+ : outMime === 'image/webp'
81
+ ? pipeline.webp({ quality: 88 })
82
+ : pipeline.png({ compressionLevel: 8 });
83
+ const { data, info } = await pipeline.toBuffer({ resolveWithObject: true });
84
+ logger.info({
85
+ msg: 'image.scaled_for_model',
86
+ from: dims ? `${dims.width}x${dims.height}` : undefined,
87
+ to: `${info.width}x${info.height}`,
88
+ bytesBefore: bytes.length,
89
+ bytesAfter: data.length,
90
+ maxEdge,
91
+ });
92
+ return {
93
+ bytes: data,
94
+ mimeType: outMime,
95
+ resized: true,
96
+ ...(dims ? { from: dims } : {}),
97
+ to: { width: info.width, height: info.height },
98
+ };
99
+ } catch {
100
+ return unchanged;
101
+ }
102
+ }
103
+
104
+ /** For an image file that is sent by path (chat attachments; Codex takes
105
+ * file paths): the path of a scaled copy next to it, made once and
106
+ * reused on every later turn that replays the attachment. Returns the
107
+ * original path when nothing needs scaling. */
108
+ export async function fitImageFileForModel(
109
+ path: string,
110
+ mimeType: string,
111
+ maxEdge: number,
112
+ ): Promise<{ path: string; mimeType: string; size: number; resized: boolean }> {
113
+ const original = async () => ({ path, mimeType, size: (await stat(path)).size, resized: false });
114
+ if (!(maxEdge > 0)) return original();
115
+ const bytes = await readFile(path);
116
+ const dims = readDimensions(bytes);
117
+ if (dims && Math.max(dims.width, dims.height) <= maxEdge) return original();
118
+ const key = createHash('sha256').update(bytes).digest('hex').slice(0, 16);
119
+ const ext = mimeType === 'image/jpeg' ? 'jpg' : mimeType === 'image/webp' ? 'webp' : 'png';
120
+ const outMime = ext === 'jpg' ? 'image/jpeg' : ext === 'webp' ? 'image/webp' : 'image/png';
121
+ const cached = `${path}.model-${maxEdge}-${key}.${ext}`;
122
+ if (existsSync(cached)) return { path: cached, mimeType: outMime, size: (await stat(cached)).size, resized: true };
123
+ const fitted = await fitImageForModel(bytes, mimeType, maxEdge);
124
+ if (!fitted.resized) return original();
125
+ await writeFile(cached, fitted.bytes);
126
+ return { path: cached, mimeType: fitted.mimeType, size: fitted.bytes.length, resized: true };
127
+ }
@@ -29,7 +29,8 @@ import {
29
29
  } from 'node:os';
30
30
  import { resolve as resolvePath } from 'node:path';
31
31
  import { WebSocketServer } from 'ws';
32
- import { applyClaudeCliSdkEnv, applyCodexCliEnv, configPath, loadConfig, primeFreshConfig } from '../config/loader.ts';
32
+ import { resolveThinking, VALID_THINKING_LEVELS } from './thinking-resolve.ts';
33
+ import { applyClaudeCliSdkEnv, applyCodexCliEnv, configPath, currentConfigProblem, getFreshConfig, loadConfig, primeFreshConfig } from '../config/loader.ts';
33
34
  import { diffConfigSections, restartRequiredFor, RESTART_REQUIRED_SECTIONS } from '../config/reload.ts';
34
35
  import { spawn as spawnChild, spawnSync as spawnSyncChild } from 'node:child_process';
35
36
  import { mkdir as mkdirFs, rename as renameFs, stat as statFile, writeFile as writeFileFs } from 'node:fs/promises';
@@ -195,6 +196,7 @@ import {
195
196
  listSessionWaiters,
196
197
  getSessionLockStatus,
197
198
  } from './session-queue.ts';
199
+ import { compactSessionByHand, manualCompactionText } from './session-compact.ts';
198
200
  import { findWaitCycle, registerWait } from './ask-wait-graph.ts';
199
201
  import { getTurnOrigin } from './turn-origin.ts';
200
202
  import { readPersonaFiles, writePersonaFile } from '../persona/files.ts';
@@ -424,21 +426,6 @@ function resolveEffectiveModel(
424
426
  return resolveAnyRef(config, ref);
425
427
  }
426
428
 
427
- // Resolve effective thinking depth: per-session override beats persona
428
- // default. Returns undefined if neither set — engines treat that as
429
- // "use whatever the model defaults to".
430
- const VALID_THINKING_LEVELS = new Set<ThinkingLevel>(['off', 'low', 'medium', 'high']);
431
- function resolveEffectiveThinking(
432
- persona: Persona,
433
- sessionMeta: Record<string, unknown>,
434
- ): ThinkingLevel | undefined {
435
- const override = sessionMeta.thinkingOverride;
436
- if (typeof override === 'string' && VALID_THINKING_LEVELS.has(override as ThinkingLevel)) {
437
- return override as ThinkingLevel;
438
- }
439
- return persona.thinking;
440
- }
441
-
442
429
  // Runs the primary engine. If the primary fails before yielding any
443
430
  // assistant content (delta or message), AND the persona has a fallback
444
431
  // configured, transparently switches to the fallback and resumes the turn
@@ -491,6 +478,9 @@ async function configFileMtime(): Promise<number> {
491
478
  try {
492
479
  config = await loadConfig();
493
480
  configLoadedMtimeMs = await configFileMtime();
481
+ // The boot config is the first "last valid" one: a broken edit later
482
+ // falls back to it instead of failing every turn.
483
+ primeFreshConfig(config, configLoadedMtimeMs);
494
484
  configureModelAvailability(config.fallback.retryUnavailableMinutes);
495
485
  } catch (err) {
496
486
  // pino's worker transport can swallow the error during fast crash; print
@@ -557,12 +547,14 @@ startClaudeCredentialSyncWatcher();
557
547
  worker: ref,
558
548
  });
559
549
  }
560
- if (requirePdf && !m.model.capabilities.includes('pdf')) {
550
+ // A worker without `pdf` still reads a PDF as page images, so only
551
+ // one that has neither can do nothing with a PDF.
552
+ if (requirePdf && !m.model.capabilities.includes('pdf') && !m.model.capabilities.includes('image')) {
561
553
  logger.warn({
562
554
  msg: 'vision.worker.no_pdf_capability',
563
555
  label,
564
556
  worker: ref,
565
- hint: 'set config.vision.pdfWorker to a pdf-capable model, or analyze_file on PDFs will error',
557
+ hint: "reads neither PDFs nor images — analyze_file passes it over for PDFs; give it 'pdf' or 'image', or remove it",
566
558
  });
567
559
  }
568
560
  };
@@ -1663,7 +1655,14 @@ app.get('/version', (c) => {
1663
1655
  // are reported so the client can say "restart needed".
1664
1656
  app.get('/config/status', async (c) => {
1665
1657
  const mtimeMs = await configFileMtime();
1658
+ // Re-checks the file (cheap when unchanged) so a broken edit shows up
1659
+ // here even before the next turn.
1660
+ await getFreshConfig().catch(() => undefined);
1661
+ const problem = currentConfigProblem();
1666
1662
  return c.json({
1663
+ // Set while config.yaml does not validate: the last valid version
1664
+ // keeps running. `since` = when this broken version was first seen.
1665
+ invalid: problem ? { since: problem.since, message: problem.message } : null,
1667
1666
  path: configPath(),
1668
1667
  loadedAt: configLoadedAt,
1669
1668
  changedOnDisk: mtimeMs > configLoadedMtimeMs,
@@ -1937,18 +1936,15 @@ app.put('/agents/:agent/persona/:file', async (c) => {
1937
1936
  return c.json({ ok: true, hash: r.hash, backup: r.backup, chars: body.content.length });
1938
1937
  });
1939
1938
 
1940
- // The system prompt exactly as the next turn on `session` would send it,
1941
- // split into its parts, plus the tool schemas the agent can see (they
1942
- // travel on the API tool channel, not in this text — but they cost
1943
- // context all the same). Read-only: the wiki snapshot is not persisted.
1944
- app.get('/agents/:agent/prompt-preview', async (c) => {
1945
- const agent = c.req.param('agent');
1946
- const persona = await loadPersona(agent);
1947
- if (!persona) return c.json({ error: `agent '${agent}' not found` }, 404);
1948
- const sessionRef = c.req.query('session') || 'main';
1949
- const session = await resolveSessionId(agent, sessionRef);
1950
- if (!session) return c.json({ error: `session '${sessionRef}' not found` }, 404);
1951
- const sessionMeta = await sessionMetaStore.get(agent, session);
1939
+ // The system prompt and tool list the NEXT turn of a session would send.
1940
+ // Read-only: the wiki snapshot is not persisted. Shared by the prompt
1941
+ // preview and the manual compaction (which summarises against it).
1942
+ async function nextTurnPrompt(
1943
+ agent: string,
1944
+ session: string,
1945
+ persona: NonNullable<Awaited<ReturnType<typeof loadPersona>>>,
1946
+ sessionMeta: Awaited<ReturnType<typeof sessionMetaStore.get>>,
1947
+ ) {
1952
1948
  // The preview has to answer with the tools the NEXT TURN would send,
1953
1949
  // so it needs the same active model that turn resolves. Without it a
1954
1950
  // capability-gated tool shows up here and then is not offered — the
@@ -1970,10 +1966,6 @@ app.get('/agents/:agent/prompt-preview', async (c) => {
1970
1966
  const available = (await tools.listAvailable(toolCtx)).filter(
1971
1967
  (t) => isToolAllowed(t.name, t.toolset, persona.toolGating) && builderSessionAllows(previewBuilderState, t.name),
1972
1968
  );
1973
- const toolSchemaChars = available.reduce(
1974
- (n, t) => n + JSON.stringify({ name: t.name, description: t.description, parameters: t.jsonSchema }).length,
1975
- 0,
1976
- );
1977
1969
  const assembled = await assembleSystemPrompt({
1978
1970
  agent,
1979
1971
  session,
@@ -1985,6 +1977,26 @@ app.get('/agents/:agent/prompt-preview', async (c) => {
1985
1977
  toolNames: available.map((t) => t.name),
1986
1978
  persistWikiSnapshot: false,
1987
1979
  });
1980
+ return { assembled, available };
1981
+ }
1982
+
1983
+ // The system prompt exactly as the next turn on `session` would send it,
1984
+ // split into its parts, plus the tool schemas the agent can see (they
1985
+ // travel on the API tool channel, not in this text — but they cost
1986
+ // context all the same). Read-only: the wiki snapshot is not persisted.
1987
+ app.get('/agents/:agent/prompt-preview', async (c) => {
1988
+ const agent = c.req.param('agent');
1989
+ const persona = await loadPersona(agent);
1990
+ if (!persona) return c.json({ error: `agent '${agent}' not found` }, 404);
1991
+ const sessionRef = c.req.query('session') || 'main';
1992
+ const session = await resolveSessionId(agent, sessionRef);
1993
+ if (!session) return c.json({ error: `session '${sessionRef}' not found` }, 404);
1994
+ const sessionMeta = await sessionMetaStore.get(agent, session);
1995
+ const { assembled, available } = await nextTurnPrompt(agent, session, persona, sessionMeta);
1996
+ const toolSchemaChars = available.reduce(
1997
+ (n, t) => n + JSON.stringify({ name: t.name, description: t.description, parameters: t.jsonSchema }).length,
1998
+ 0,
1999
+ );
1988
2000
  return c.json({
1989
2001
  agent,
1990
2002
  session,
@@ -2431,9 +2443,12 @@ app.post('/agents/:agent/sessions/:session/unarchive', async (c) => {
2431
2443
  const session = await resolveSessionId(agent, sessionRef);
2432
2444
  if (!session) return c.json({ error: `session '${sessionRef}' not found` }, 404);
2433
2445
  try {
2434
- await unarchiveSession(agent, session);
2435
- logger.info({ msg: 'session.unarchive', agent, session });
2436
- return c.json({ archived: false, agent, session });
2446
+ const after = await unarchiveSession(agent, session);
2447
+ logger.info({ msg: 'session.unarchive', agent, session, slug: after.slug, archived: after.isArchived });
2448
+ // The state after the call, computed the way the session list does —
2449
+ // never a success that did not happen.
2450
+ if (after.isArchived) return c.json({ error: `session '${session}' is still archived`, archived: true, agent, session }, 409);
2451
+ return c.json({ archived: false, agent, session, slug: after.slug });
2437
2452
  } catch (err) {
2438
2453
  return c.json({ error: (err as Error).message }, 400);
2439
2454
  }
@@ -2545,6 +2560,65 @@ app.put('/agents/:agent/sessions/:session/model', async (c) => {
2545
2560
  return c.json({ agent, session, model: body.model, resolved: `${resolved.providerName}/${resolved.modelId}` });
2546
2561
  });
2547
2562
 
2563
+ // Compact a session by hand (`/compact [focus]`). Refused while a turn
2564
+ // runs; while it works it holds the session's lock, so a message sent
2565
+ // meanwhile waits behind it like behind any turn.
2566
+ app.post('/agents/:agent/sessions/:session/compact', async (c) => {
2567
+ const agent = c.req.param('agent');
2568
+ const persona = await loadPersona(agent);
2569
+ if (!persona) return c.json({ error: `agent '${agent}' not found` }, 404);
2570
+ const sessionRef = c.req.param('session');
2571
+ const session = await resolveSessionId(agent, sessionRef);
2572
+ if (!session) return c.json({ error: `session '${sessionRef}' not found` }, 404);
2573
+ const body = (await c.req.json().catch(() => ({}))) as { instructions?: unknown };
2574
+ const focus = typeof body.instructions === 'string' ? body.instructions.trim().slice(0, 2000) : '';
2575
+ if (getSessionLockStatus(agent, session).busy) {
2576
+ return c.json({ error: 'This session is busy (a turn or a compaction is running). Compact after it has finished.', busy: true }, 409);
2577
+ }
2578
+ const sessionMeta = await sessionMetaStore.get(agent, session);
2579
+ const resolvedModel = resolveEffectiveModel(config, persona, sessionMeta);
2580
+ if (!resolvedModel) return c.json({ error: `the session's model cannot be resolved from config.yaml` }, 400);
2581
+ const release = await acquireSessionLock(agent, session, { priority: 'user', turnId: `compact-${Date.now()}` });
2582
+ const started = Date.now();
2583
+ try {
2584
+ const outcome = await compactSessionByHand(
2585
+ {
2586
+ config,
2587
+ metaStore: sessionMetaStore,
2588
+ getHistory,
2589
+ systemPrompt: async () => (await nextTurnPrompt(agent, session, persona, sessionMeta)).assembled.text,
2590
+ },
2591
+ { agent, session, resolvedModel, ...(focus ? { focus } : {}) },
2592
+ );
2593
+ logger.info({ msg: 'session.compacted_by_hand', agent, session, engine: outcome.engine, status: outcome.status, ms: Date.now() - started, focus: Boolean(focus), ...(outcome.status === 'compacted' ? { tokensBefore: outcome.tokensBefore, tokensAfter: outcome.tokensAfter } : {}) });
2594
+ if (outcome.status === 'compacted') {
2595
+ const ev = {
2596
+ kind: 'engine_meta',
2597
+ ts: Date.now(),
2598
+ engine: 'somora',
2599
+ itemType: 'context_compacted',
2600
+ payload: {
2601
+ text: manualCompactionText(outcome, focus || undefined),
2602
+ manual: true,
2603
+ engine: outcome.engine,
2604
+ ...(outcome.tokensBefore !== undefined ? { tokensBefore: outcome.tokensBefore } : {}),
2605
+ ...(outcome.tokensAfter !== undefined ? { tokensAfter: outcome.tokensAfter } : {}),
2606
+ ...(focus ? { focus } : {}),
2607
+ },
2608
+ } as NormalizedEvent;
2609
+ await appendEvent(agent, session, ev);
2610
+ const sse = serializeSessionEvent(ev);
2611
+ if (sse) await publish(agent, session, sse);
2612
+ }
2613
+ return c.json({ agent, session, ...outcome }, outcome.status === 'unsupported' ? 400 : 200);
2614
+ } catch (err) {
2615
+ logger.warn({ msg: 'session.compact_failed', agent, session, err: (err as Error).message });
2616
+ return c.json({ error: `Compaction failed: ${(err as Error).message}` }, 502);
2617
+ } finally {
2618
+ release();
2619
+ }
2620
+ });
2621
+
2548
2622
  // Reset a session: archive current jsonl + meta, fresh-start the
2549
2623
  // session id. The archived copy is resume-able under a timestamped
2550
2624
  // name. Used primarily for the magic `main` session, which can't be
@@ -2655,7 +2729,8 @@ app.get('/agents/:agent/sessions/:session/thinking', async (c) => {
2655
2729
  VALID_THINKING_LEVELS.has(meta.thinkingOverride as ThinkingLevel)
2656
2730
  ? (meta.thinkingOverride as ThinkingLevel)
2657
2731
  : null;
2658
- const effective = resolveEffectiveThinking(persona, meta) ?? null;
2732
+ const thinking = resolveThinking(persona, meta, resolved?.model);
2733
+ const effective = thinking.level ?? null;
2659
2734
  // Wire value the engine sends for this level (per-model
2660
2735
  // `reasoning.levels`); null when identical to the level or not applicable.
2661
2736
  // openai-compatible: the reasoning_effort body value. codex-cli: the
@@ -2676,7 +2751,11 @@ app.get('/agents/:agent/sessions/:session/thinking', async (c) => {
2676
2751
  effective,
2677
2752
  override,
2678
2753
  personaDefault: persona.thinking ?? null,
2679
- source: override ? 'session-override' : effective ? 'persona-default' : 'engine-default',
2754
+ // The active model's `reasoning.default`, if it has one.
2755
+ modelDefault: resolved?.model.reasoning?.default ?? null,
2756
+ // session-override | persona-default | model-default | engine-default
2757
+ // (nothing set: nothing is sent, the model decides — not "off").
2758
+ source: thinking.source,
2680
2759
  modelSupportsReasoning,
2681
2760
  wire: wireValue !== null && wireValue !== effective ? wireValue : null,
2682
2761
  });
@@ -53,14 +53,14 @@ import { claimWorkdir, describeClaim, noteToolCall, workdirClaimedBy } from './b
53
53
  import { originKind, type TurnOrigin } from './turn-origin-kind.ts';
54
54
  import { assembleSystemPrompt } from './prompt-assembly.ts';
55
55
  import type { ResolvedAttachment } from '../engine/types.ts';
56
- import { resolveAttachmentByHash } from '../attachments/store.ts';
56
+ import { resolveAttachmentForModel } from '../attachments/store.ts';
57
57
  import { listRecords as listMediaRecords, readRecord as readMediaRecord } from '../media/records.ts';
58
58
  import {
59
59
  buildReviewLoopBlock,
60
60
  refreshLoopActivity,
61
61
  resetWikiCallCounter,
62
62
  } from '../dream/loop-state.ts';
63
- import { injectMemoryContext } from '../memory/inject.ts';
63
+ import { injectMemoryContext, injectedKeysInHistory } from '../memory/inject.ts';
64
64
  import { getMemoryManager } from '../memory/registry.ts';
65
65
  import { logger } from './logger.ts';
66
66
  import { loadPersona, type Persona } from '../persona/loader.ts';
@@ -74,8 +74,21 @@ import type { NormalizedEvent, SseEvent } from '../types/events.ts';
74
74
  import { resolveOpenAiReasoning } from '../engine/thinking-params.ts';
75
75
  import { mergeSampling } from '../engine/sampling.ts';
76
76
  import { SOMORA_HOME_DIR } from './logger.ts';
77
+ import { currentConfigProblem, getFreshConfig } from '../config/loader.ts';
78
+ import { resolveThinking } from './thinking-resolve.ts';
79
+
80
+ /** `agent::session` → mtime of the broken config.yaml it was told about. */
81
+ const configProblemNoticed = new Map<string, number>();
82
+
83
+ /** The note an agent gets while config.yaml does not validate. */
84
+ export function configProblemNotice(message: string): string {
85
+ return (
86
+ '[system: config] ~/.somora/config.yaml does not validate, so somora keeps running on the last valid version. ' +
87
+ 'Changes since then are not in effect. Fix the file (check it with `somora config check`):\n' +
88
+ message.replace(/^config\.yaml is invalid \([^)]*\):\n/, '')
89
+ );
90
+ }
77
91
 
78
- const VALID_THINKING_LEVELS = new Set<ThinkingLevel>(['off', 'low', 'medium', 'high']);
79
92
 
80
93
  // Injected into the system prompt when the agent has tools and
81
94
  // `agentLoop.toolUsageReminder` is on. Kept short and constant — it has
@@ -140,17 +153,6 @@ function pickToolIdleTimeoutForEngine(
140
153
  }
141
154
  }
142
155
 
143
- function resolveEffectiveThinking(
144
- persona: Persona,
145
- sessionMeta: Record<string, unknown>,
146
- ): ThinkingLevel | undefined {
147
- const override = sessionMeta.thinkingOverride;
148
- if (typeof override === 'string' && VALID_THINKING_LEVELS.has(override as ThinkingLevel)) {
149
- return override as ThinkingLevel;
150
- }
151
- return persona.thinking;
152
- }
153
-
154
156
  /** Sampling: model default < agent.yaml < session override, per key. */
155
157
  export function resolveEffectiveSampling(
156
158
  model: { sampling?: SamplingConfig },
@@ -516,6 +518,8 @@ export async function runChatTurn(args: RunChatTurnArgs): Promise<ChatTurnResult
516
518
  // codex-cli) ignore this field — they inline the block once into
517
519
  // the outgoing message and the provider remembers everything.
518
520
  const historyBeforeTurn = await getHistory(agent, session);
521
+ /** openai-compatible: memory blocks of turns before this ts are left out of the replay. */
522
+ let memoryDropBefore = 0;
519
523
 
520
524
  // Self-heal: if the previous turn died mid-flight (engine subprocess
521
525
  // crash after tool_use but before tool_result), the JSONL tail will
@@ -541,6 +545,28 @@ export async function runChatTurn(args: RunChatTurnArgs): Promise<ChatTurnResult
541
545
  });
542
546
  }
543
547
 
548
+ // Which past memory blocks are still in front of the model: none
549
+ // before the last compaction, and — on an openai-compatible provider
550
+ // that drops them after a pause — none before the drop point. A pause
551
+ // longer than the provider's cache lifetime moves the drop point to
552
+ // now: the cache is gone anyway, so dropping costs nothing.
553
+ const memoryContextSince = await (async (): Promise<number> => {
554
+ let since = 0;
555
+ const compactions = (sessionMeta as { compactions?: Array<{ throughTs: number }> }).compactions;
556
+ for (const c of compactions ?? []) if (typeof c.throughTs === 'number' && c.throughTs > since) since = c.throughTs;
557
+ if (resolvedModel.provider.engine !== 'openai-compatible') return since;
558
+ const idleMin = (resolvedModel.provider as { dropMemoryBlocksAfterIdleMinutes?: number }).dropMemoryBlocksAfterIdleMinutes ?? 60;
559
+ let dropBefore = typeof sessionMeta.memoryDropBefore === 'number' ? sessionMeta.memoryDropBefore : 0;
560
+ const last = historyBeforeTurn.length > 0 ? historyBeforeTurn[historyBeforeTurn.length - 1]!.ts : 0;
561
+ if (idleMin > 0 && last > 0 && Date.now() - last > idleMin * 60_000) {
562
+ dropBefore = Date.now();
563
+ await deps.sessionMetaStore.update(agent, session, (m) => ({ ...m, memoryDropBefore: dropBefore }));
564
+ logger.info({ msg: 'memory.blocks_dropped_after_pause', turnId, agent, session, idleMinutes: Math.round((Date.now() - last) / 60_000), setting: idleMin });
565
+ }
566
+ memoryDropBefore = dropBefore;
567
+ return Math.max(since, dropBefore);
568
+ })();
569
+
544
570
  let ephemeralContext: string | undefined;
545
571
  let memoryHits: Array<{ source: string; slug: string; score: number }> = [];
546
572
  let memoryInjectedCount = 0;
@@ -561,6 +587,7 @@ export async function runChatTurn(args: RunChatTurnArgs): Promise<ChatTurnResult
561
587
  history: historyBeforeTurn,
562
588
  userMessage: text,
563
589
  cfg: deps.config.memory.autoInject,
590
+ alreadyInContext: injectedKeysInHistory(historyBeforeTurn, memoryContextSince),
564
591
  });
565
592
  ephemeralContext = inject.ephemeralContext;
566
593
  memoryInjectedCount = inject.injectedCount;
@@ -574,7 +601,10 @@ export async function runChatTurn(args: RunChatTurnArgs): Promise<ChatTurnResult
574
601
  count: inject.injectedCount,
575
602
  slugs: inject.hits.map((h) => `${h.source}/${h.slug}`),
576
603
  topScore: inject.hits[0]?.score,
604
+ ...(inject.skippedRepeats > 0 ? { skippedRepeats: inject.skippedRepeats } : {}),
577
605
  });
606
+ } else if (inject.skippedRepeats > 0) {
607
+ logger.info({ msg: 'memory.inject_all_repeats', turnId, agent, session, skippedRepeats: inject.skippedRepeats });
578
608
  }
579
609
  } catch (err) {
580
610
  logger.warn({ msg: 'memory.inject_failed', turnId, agent, err: (err as Error).message });
@@ -586,6 +616,22 @@ export async function runChatTurn(args: RunChatTurnArgs): Promise<ChatTurnResult
586
616
  ephemeralContext = ephemeralContext ? `${turnPrefix}\n\n${ephemeralContext}` : turnPrefix;
587
617
  }
588
618
 
619
+ // config.yaml on disk does not validate: the last valid version keeps
620
+ // running (getFreshConfig). Tell the agent once per session and broken
621
+ // version — it is often the one who just edited the file and can fix it.
622
+ try {
623
+ await getFreshConfig();
624
+ const problem = currentConfigProblem();
625
+ const key = `${agent}::${session}`;
626
+ if (problem && configProblemNoticed.get(key) !== problem.mtimeMs) {
627
+ configProblemNoticed.set(key, problem.mtimeMs);
628
+ const notice = configProblemNotice(problem.message);
629
+ ephemeralContext = ephemeralContext ? `${notice}\n\n${ephemeralContext}` : notice;
630
+ }
631
+ } catch {
632
+ /* no valid config at all — the turn fails elsewhere with the reason */
633
+ }
634
+
589
635
  // Loop-holder gets the active Lucid review block prepended to the
590
636
  // ephemeral context. Refreshed on every turn so the user can see
591
637
  // that the agent stays on topic until dream_review({action:'end'}).
@@ -622,7 +668,7 @@ export async function runChatTurn(args: RunChatTurnArgs): Promise<ChatTurnResult
622
668
  );
623
669
  }
624
670
  for (const a of attachments) {
625
- const r = await resolveAttachmentByHash({ hash: a.hash, expectedMime: a.mime });
671
+ const r = await resolveAttachmentForModel({ hash: a.hash, expectedMime: a.mime, maxImageEdge: deps.config.attachments.maxImageEdge });
626
672
  resolvedAttachments.push({
627
673
  hash: a.hash,
628
674
  path: r.path,
@@ -661,6 +707,7 @@ export async function runChatTurn(args: RunChatTurnArgs): Promise<ChatTurnResult
661
707
  maxImageBytes: deps.config.attachments.maxImageBytes,
662
708
  maxPdfBytes: deps.config.attachments.maxPdfBytes,
663
709
  maxTextBytes: deps.config.attachments.maxTextBytes,
710
+ maxImageEdge: deps.config.attachments.maxImageEdge,
664
711
  });
665
712
  described = await describeMedia({
666
713
  att,
@@ -776,7 +823,7 @@ export async function runChatTurn(args: RunChatTurnArgs): Promise<ChatTurnResult
776
823
  deps.onActivity(agent);
777
824
 
778
825
  const modelSupportsReasoning = resolvedModel.model.capabilities.includes('reasoning');
779
- const effectiveThinking = resolveEffectiveThinking(persona, sessionMeta);
826
+ const effectiveThinking = resolveThinking(persona, sessionMeta, resolvedModel.model).level;
780
827
  const effectiveSampling = resolveEffectiveSampling(resolvedModel.model, persona, sessionMeta);
781
828
  // What the openai-compatible engine will actually put on the wire for
782
829
  // this level (per-model `reasoning.levels`). Only sent to clients when
@@ -1007,6 +1054,8 @@ export async function runChatTurn(args: RunChatTurnArgs): Promise<ChatTurnResult
1007
1054
  captureThinking: deps.config.thinkingContent.capture,
1008
1055
  ...(signal ? { signal } : {}),
1009
1056
  ...(resolvedAttachments.length > 0 ? { attachments: resolvedAttachments } : {}),
1057
+ maxImageEdge: deps.config.attachments.maxImageEdge,
1058
+ ...(memoryDropBefore > 0 ? { memoryDropBefore } : {}),
1010
1059
  },
1011
1060
  });
1012
1061