somora 2026.1001.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 (123) hide show
  1. package/README.md +31 -24
  2. package/config.example.yaml +37 -1
  3. package/docs/agents.md +714 -584
  4. package/docs/api.md +2327 -2546
  5. package/docs/browser.md +450 -265
  6. package/docs/builder.md +408 -282
  7. package/docs/cache-strategy.md +249 -301
  8. package/docs/compaction.md +378 -232
  9. package/docs/display.md +363 -130
  10. package/docs/dream-phases.md +598 -789
  11. package/docs/files.md +509 -333
  12. package/docs/imagegen.md +421 -302
  13. package/docs/images/somora-hero.png +0 -0
  14. package/docs/index.md +139 -174
  15. package/docs/lsp.md +142 -60
  16. package/docs/mcp.md +365 -273
  17. package/docs/memory.md +315 -356
  18. package/docs/mobile.md +283 -282
  19. package/docs/models.md +440 -197
  20. package/docs/projects.md +297 -316
  21. package/docs/realtime-voice.md +358 -234
  22. package/docs/resources.md +268 -176
  23. package/docs/sampling.md +141 -78
  24. package/docs/security.md +413 -169
  25. package/docs/sentinel.md +268 -208
  26. package/docs/setup.md +786 -1115
  27. package/docs/skills.md +415 -430
  28. package/docs/team.md +268 -143
  29. package/docs/thinking.md +415 -387
  30. package/docs/tmux.md +384 -334
  31. package/docs/tools.md +492 -109
  32. package/docs/videogen.md +319 -146
  33. package/docs/voice.md +335 -220
  34. package/docs/web.md +633 -835
  35. package/docs/wiki.md +442 -482
  36. package/package.json +2 -1
  37. package/src/attachments/store.ts +19 -1
  38. package/src/browser/session.ts +2 -2
  39. package/src/cli/auth.ts +22 -0
  40. package/src/cli/banner.ts +56 -0
  41. package/src/cli/claude-bin.ts +48 -0
  42. package/src/cli/config.ts +47 -0
  43. package/src/cli/server-call.ts +65 -0
  44. package/src/cli/setup.ts +26 -8
  45. package/src/cli/somora.ts +36 -4
  46. package/src/cli/team.ts +13 -6
  47. package/src/cli/tui/api.ts +44 -2
  48. package/src/cli/tui/app.tsx +77 -8
  49. package/src/cli/tui/commands.ts +111 -14
  50. package/src/cli/tui/header.tsx +20 -0
  51. package/src/cli/tui/stream.ts +3 -0
  52. package/src/cli/tui/turn-views.tsx +22 -0
  53. package/src/cli/tui/types.ts +14 -3
  54. package/src/compaction/summarize.ts +12 -3
  55. package/src/compaction/template.ts +15 -0
  56. package/src/compaction/types.ts +3 -0
  57. package/src/config/loader.ts +75 -10
  58. package/src/config/types.ts +59 -20
  59. package/src/dream/deep-llm.ts +83 -3
  60. package/src/dream/deep-runner.ts +8 -2
  61. package/src/dream/deep-worker.ts +1 -0
  62. package/src/dream/lucid-runner.ts +7 -3
  63. package/src/dream/lucid-types.ts +3 -0
  64. package/src/dream/rem-extract.ts +99 -69
  65. package/src/dream/worker-model.ts +31 -0
  66. package/src/engine/a2a.ts +1 -1
  67. package/src/engine/claude-cli.ts +136 -4
  68. package/src/engine/codex-cli.ts +74 -0
  69. package/src/engine/engine-meta-labels.ts +2 -0
  70. package/src/engine/openai-compatible.ts +142 -29
  71. package/src/engine/types.ts +7 -0
  72. package/src/imagegen/generate.ts +30 -5
  73. package/src/imagegen/types.ts +6 -0
  74. package/src/media/capabilities.ts +8 -0
  75. package/src/memory/inject.ts +66 -7
  76. package/src/multimodal/blocks.ts +14 -0
  77. package/src/multimodal/load.ts +21 -2
  78. package/src/multimodal/model-image.ts +127 -0
  79. package/src/persona/loader.ts +2 -2
  80. package/src/server/index.ts +275 -62
  81. package/src/server/restart-intent.ts +138 -0
  82. package/src/server/restart-reconcile.ts +6 -2
  83. package/src/server/run-turn.ts +66 -17
  84. package/src/server/session-compact.ts +138 -0
  85. package/src/server/thinking-resolve.ts +30 -0
  86. package/src/server/turn-origin-kind.ts +2 -2
  87. package/src/ssh/exec.ts +55 -22
  88. package/src/ssh/known-hosts.ts +17 -2
  89. package/src/ssh/pool.ts +7 -1
  90. package/src/storage/sessions.ts +40 -15
  91. package/src/tools/dream/tools.ts +2 -2
  92. package/src/tools/exec/tools.ts +19 -2
  93. package/src/tools/file/analyze.ts +46 -7
  94. package/src/tools/file/remote.ts +31 -10
  95. package/src/tools/file/tools.ts +86 -19
  96. package/src/tools/image/tools.ts +6 -0
  97. package/src/tools/registry.ts +14 -0
  98. package/src/types/events.ts +25 -4
  99. package/src/types/turn-origin.ts +6 -2
  100. package/web/dist/apple-touch-icon.png +0 -0
  101. package/web/dist/assets/{index-CrkkIfd9.js → index-40x__Izy.js} +168 -163
  102. package/web/dist/assets/index-40x__Izy.js.map +1 -0
  103. package/web/dist/assets/index-CZFgQRsq.css +32 -0
  104. package/web/dist/favicon-48.png +0 -0
  105. package/web/dist/favicon.ico +0 -0
  106. package/web/dist/favicon.svg +1 -8
  107. package/web/dist/index.html +6 -2
  108. package/web-mobile/dist/apple-touch-icon.png +0 -0
  109. package/web-mobile/dist/assets/index-CxILeHfe.js +88 -0
  110. package/web-mobile/dist/assets/index-CxILeHfe.js.map +1 -0
  111. package/web-mobile/dist/assets/index-Cyr13VGR.css +1 -0
  112. package/web-mobile/dist/favicon-48.png +0 -0
  113. package/web-mobile/dist/favicon.ico +0 -0
  114. package/web-mobile/dist/favicon.svg +1 -8
  115. package/web-mobile/dist/icon-192.png +0 -0
  116. package/web-mobile/dist/icon-512.png +0 -0
  117. package/web-mobile/dist/index.html +5 -3
  118. package/web-mobile/dist/manifest.webmanifest +2 -2
  119. package/web/dist/assets/index-BA5mmiV0.css +0 -32
  120. package/web/dist/assets/index-CrkkIfd9.js.map +0 -1
  121. package/web-mobile/dist/assets/index-BqKt7IMx.css +0 -1
  122. package/web-mobile/dist/assets/index-X_vRr6cd.js +0 -88
  123. package/web-mobile/dist/assets/index-X_vRr6cd.js.map +0 -1
@@ -0,0 +1,138 @@
1
+ // A restart an agent asked for, kept across the restart.
2
+ //
3
+ // An agent that restarts somora from inside its own turn (a deploy, a
4
+ // config change, `somora update`) used to kill that turn: the server
5
+ // died mid-tool-call, nothing recorded the outcome, and afterwards the
6
+ // person had to tell the agent to look again (report 2026-09-13, four
7
+ // cut turns in two days on one installation).
8
+ //
9
+ // Two layers:
10
+ // 1. Requested: `somora server restart` / `somora update` called from an
11
+ // agent's shell — or POST /server/restart with agent + session — do
12
+ // not restart at once. The request is written here, the restart
13
+ // waits until that turn has ended, and after boot the session is
14
+ // woken with what happened.
15
+ // 2. Detected: a turn cut by a restart it visibly caused itself (a raw
16
+ // `systemctl restart somora` in its tool calls) is woken as well.
17
+ // A session is resumed at most twice in ten minutes — an agent that
18
+ // answers the wake by restarting again must not loop.
19
+
20
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
21
+ import { homedir } from 'node:os';
22
+ import { dirname, join } from 'node:path';
23
+
24
+ export interface RestartIntent {
25
+ agent: string;
26
+ session: string;
27
+ requestedAt: number;
28
+ fromVersion: string;
29
+ reason?: string;
30
+ }
31
+
32
+ const home = (): string => process.env.SOMORA_HOME ?? join(homedir(), '.somora');
33
+ export const intentPath = (): string => join(home(), 'restart-intent.json');
34
+ const historyPath = (): string => join(home(), 'restart-resume.json');
35
+
36
+ function writeJson(path: string, value: unknown): void {
37
+ mkdirSync(dirname(path), { recursive: true });
38
+ const tmp = `${path}.tmp`;
39
+ writeFileSync(tmp, JSON.stringify(value, null, 2));
40
+ renameSync(tmp, path);
41
+ }
42
+
43
+ export function writeRestartIntent(intent: RestartIntent): void {
44
+ writeJson(intentPath(), intent);
45
+ }
46
+
47
+ export function readRestartIntent(): RestartIntent | null {
48
+ try {
49
+ const j = JSON.parse(readFileSync(intentPath(), 'utf8')) as Partial<RestartIntent>;
50
+ if (typeof j.agent !== 'string' || typeof j.session !== 'string' || typeof j.requestedAt !== 'number') return null;
51
+ return { agent: j.agent, session: j.session, requestedAt: j.requestedAt, fromVersion: typeof j.fromVersion === 'string' ? j.fromVersion : '?', ...(typeof j.reason === 'string' ? { reason: j.reason } : {}) };
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ export function clearRestartIntent(): void {
58
+ rmSync(intentPath(), { force: true });
59
+ }
60
+
61
+ /** A shell command that restarts this somora: its own CLI, or the
62
+ * service manager aimed at the somora unit. A heuristic — wrappers and
63
+ * scripts escape it, which is why the requested path exists. */
64
+ export function looksLikeSelfRestart(command: string): boolean {
65
+ const c = command.toLowerCase();
66
+ if (/\bsomora\s+(server\s+restart|update)\b/.test(c)) return true;
67
+ if (/\bsystemctl\b[^|;&\n]*\b(restart|try-restart|reload-or-restart)\b[^|;&\n]*\bsomora/.test(c)) return true;
68
+ if (/\blaunchctl\b[^|;&\n]*\b(kickstart|bootout|stop|unload)\b[^|;&\n]*somora/.test(c)) return true;
69
+ if (/\bpm2\b[^|;&\n]*\b(restart|reload)\b[^|;&\n]*\bsomora/.test(c)) return true;
70
+ return false;
71
+ }
72
+
73
+ /** Does any tool call of a turn restart somora? `rows` are the turn's
74
+ * stored events (exec `command`, tmux `keys`/`command`/`text`). */
75
+ export function turnRestartedServer(rows: ReadonlyArray<Record<string, unknown>>): boolean {
76
+ for (const r of rows) {
77
+ if (r.kind !== 'tool_call') continue;
78
+ const input = r.input as Record<string, unknown> | undefined;
79
+ if (!input) continue;
80
+ for (const key of ['command', 'cmd', 'keys', 'text', 'script']) {
81
+ const v = input[key];
82
+ if (typeof v === 'string' && looksLikeSelfRestart(v)) return true;
83
+ if (Array.isArray(v) && looksLikeSelfRestart(v.filter((x) => typeof x === 'string').join(' '))) return true;
84
+ }
85
+ }
86
+ return false;
87
+ }
88
+
89
+ const RESUME_WINDOW_MS = 10 * 60 * 1000;
90
+ const RESUME_MAX = 2;
91
+
92
+ /** May this session be woken after a restart? Records the wake when it
93
+ * may. False once it was woken twice in ten minutes. */
94
+ export function allowResume(agent: string, session: string, now: number = Date.now()): boolean {
95
+ let history: Record<string, number[]> = {};
96
+ try {
97
+ history = JSON.parse(readFileSync(historyPath(), 'utf8')) as Record<string, number[]>;
98
+ } catch {
99
+ /* first time */
100
+ }
101
+ const key = `${agent}/${session}`;
102
+ const fresh: Record<string, number[]> = {};
103
+ for (const [k, list] of Object.entries(history)) {
104
+ const kept = (Array.isArray(list) ? list : []).filter((t) => typeof t === 'number' && now - t < RESUME_WINDOW_MS);
105
+ if (kept.length) fresh[k] = kept;
106
+ }
107
+ const mine = fresh[key] ?? [];
108
+ if (mine.length >= RESUME_MAX) {
109
+ writeJson(historyPath(), fresh);
110
+ return false;
111
+ }
112
+ fresh[key] = [...mine, now];
113
+ writeJson(historyPath(), fresh);
114
+ return true;
115
+ }
116
+
117
+ function seconds(ms: number): string {
118
+ return `${Math.max(1, Math.round(ms / 1000))} s`;
119
+ }
120
+
121
+ /** Wake text after a requested restart. */
122
+ export function requestedResumeText(intent: RestartIntent, nowVersion: string, now: number = Date.now()): string {
123
+ const version = intent.fromVersion === nowVersion ? `somora ${nowVersion}` : `somora ${intent.fromVersion} → ${nowVersion}`;
124
+ return (
125
+ `[system: restart] The server restart you requested is done: ${version}, back after ${seconds(now - intent.requestedAt)}` +
126
+ (intent.reason ? ` (${intent.reason})` : '') +
127
+ '. Your turn before it ended normally. Check that what you restarted for is in place, then continue with what you were doing — do not restart again unless something is actually wrong.'
128
+ );
129
+ }
130
+
131
+ /** Wake text for a turn that was cut by a restart it caused itself. */
132
+ export function detectedResumeText(nowVersion: string): string {
133
+ return (
134
+ `[system: restart] Your previous turn was cut off by a server restart that it started itself; the server is back (somora ${nowVersion}). ` +
135
+ 'The command that restarted it did run — do NOT run it again. The instruction above still stands: check the current state, then continue from there. ' +
136
+ 'Next time restart with `somora server restart` (or `somora update`) from your shell: it waits until your turn has ended and wakes you afterwards.'
137
+ );
138
+ }
@@ -18,6 +18,7 @@ import { join } from 'node:path';
18
18
  import { appendEvent } from '../storage/sessions.ts';
19
19
  import type { NormalizedEvent } from '../types/events.ts';
20
20
  import { logger } from './logger.ts';
21
+ import { turnRestartedServer } from './restart-intent.ts';
21
22
 
22
23
  export const RESTART_NOTE = '[somora] This turn was interrupted by a server restart; the work it was doing stopped here.';
23
24
  const TAIL_BYTES = 128 * 1024;
@@ -33,6 +34,8 @@ export interface InterruptedTurn {
33
34
  callId?: string;
34
35
  /** The parent of a helper turn, when this was one. */
35
36
  parent?: { agent: string; session: string };
37
+ /** A tool call of the cut turn restarted somora (restart-intent.ts). */
38
+ selfRestart?: boolean;
36
39
  }
37
40
 
38
41
  async function readTail(path: string): Promise<Record<string, unknown>[]> {
@@ -76,6 +79,7 @@ export function openTurnOf(rows: Record<string, unknown>[]): Omit<InterruptedTur
76
79
  turnId: typeof start.turnId === 'string' ? start.turnId : `t-${start.ts}`,
77
80
  startedAt: typeof start.ts === 'number' ? start.ts : Date.now(),
78
81
  };
82
+ if (turnRestartedServer(rows.slice(startIdx + 1))) t.selfRestart = true;
79
83
  for (let i = startIdx - 1; i >= 0; i--) {
80
84
  const r = rows[i]!;
81
85
  if (r.kind !== 'user_message') continue;
@@ -128,12 +132,12 @@ export async function reconcileInterruptedTurns(agents: readonly string[]): Prom
128
132
  /** The wake text for an asker whose question died with the restart. */
129
133
  export function restartWakeText(t: InterruptedTurn): string {
130
134
  return (
131
- `[agent answer] The question you sent to ${t.agent} (session '${t.session}') was cut off by a server restart before an answer came` +
135
+ `[system: restart] The question you sent to ${t.agent} (session '${t.session}') was cut off by a server restart before an answer came` +
132
136
  (t.callId ? ` (call_id "${t.callId}")` : '') +
133
137
  '. It will not be answered on its own — send it again if you still need it.'
134
138
  );
135
139
  }
136
140
 
137
141
  export function restartParentWakeText(t: InterruptedTurn): string {
138
- return `[subagent attention] The helper in ${t.agent}'s session '${t.session}' was cut off by a server restart before it finished; there is no result. Start it again if you still need it.`;
142
+ return `[system: restart] The helper in ${t.agent}'s session '${t.session}' was cut off by a server restart before it finished; there is no result. Start it again if you still need it.`;
139
143
  }
@@ -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 },
@@ -190,7 +192,7 @@ export interface RunChatTurnArgs {
190
192
  * the message as a centered system divider rather than a normal
191
193
  * user-bubble. Mutually exclusive with fromAgent. Derived from
192
194
  * `origin` when a caller goes through startTurn. */
193
- fromSystem?: 'sentinel' | 'tmux' | 'subagent' | 'job' | 'browser' | 'voice' | 'a2a';
195
+ fromSystem?: 'sentinel' | 'tmux' | 'subagent' | 'job' | 'browser' | 'voice' | 'a2a' | 'system';
194
196
  /** Where this turn came from, as one value (src/types/turn-origin.ts).
195
197
  * Persisted additively on user_message and the SSE event; the
196
198
  * legacy fields above stay what old sessions, clients and engines
@@ -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
 
@@ -0,0 +1,138 @@
1
+ // Compacting a session by hand (`/compact [focus]`, POST
2
+ // /agents/:agent/sessions/:session/compact). The automatic compaction
3
+ // runs before a turn when the context fills up; this one runs when a
4
+ // person asks, outside any turn, on the engine of the session's model:
5
+ //
6
+ // openai-compatible somora summarises (the same compaction as the
7
+ // automatic one), the focus goes into the prompt
8
+ // claude-cli Claude Code compacts its own session, the focus
9
+ // goes along as its instructions
10
+ // codex-cli Codex compacts its own thread; it takes no
11
+ // instructions, so a focus is reported as unused
12
+ // anything else not available
13
+ //
14
+ // The session file is never shortened; REM keeps reading all of it.
15
+
16
+ import type { Config, ResolvedModel } from '../config/types.ts';
17
+ import { listAllModels } from '../config/types.ts';
18
+ import { resolveCompactionConfig, type Compaction } from '../compaction/index.ts';
19
+ import { runCompaction } from '../compaction/summarize.ts';
20
+ import type { SessionMetaStore } from '../engine/types.ts';
21
+ import { compactClaudeSession } from '../engine/claude-cli.ts';
22
+ import { compactCodexThread } from '../engine/codex-cli.ts';
23
+ import type { NormalizedEvent } from '../types/events.ts';
24
+
25
+ export type ManualCompactionOutcome =
26
+ | { status: 'compacted'; engine: string; tokensBefore?: number; tokensAfter?: number; note?: string }
27
+ | { status: 'nothing_to_compact'; engine: string; note: string }
28
+ | { status: 'unsupported'; engine: string; note: string };
29
+
30
+ export interface ManualCompactionDeps {
31
+ config: Config;
32
+ metaStore: SessionMetaStore;
33
+ getHistory: (agent: string, session: string) => Promise<NormalizedEvent[]>;
34
+ /** The system prompt the next turn would send; only read when needed. */
35
+ systemPrompt: () => Promise<string>;
36
+ /** Test seams. */
37
+ engines?: {
38
+ runCompaction?: typeof runCompaction;
39
+ claude?: typeof compactClaudeSession;
40
+ codex?: typeof compactCodexThread;
41
+ };
42
+ }
43
+
44
+ export async function compactSessionByHand(
45
+ deps: ManualCompactionDeps,
46
+ args: { agent: string; session: string; resolvedModel: ResolvedModel; focus?: string },
47
+ ): Promise<ManualCompactionOutcome> {
48
+ const { agent, session, resolvedModel } = args;
49
+ const focus = args.focus?.trim() || undefined;
50
+ const engine = resolvedModel.provider.engine;
51
+
52
+ if (engine === 'openai-compatible') {
53
+ const meta = (await deps.metaStore.get(agent, session)) as { compactions?: Compaction[] };
54
+ const compaction = await (deps.engines?.runCompaction ?? runCompaction)({
55
+ systemPrompt: await deps.systemPrompt(),
56
+ history: await deps.getHistory(agent, session),
57
+ resolvedModel,
58
+ availableModels: listAllModels(deps.config),
59
+ compactions: meta.compactions,
60
+ config: resolveCompactionConfig(deps.config),
61
+ manual: focus ? { focus } : {},
62
+ });
63
+ if (!compaction) {
64
+ return {
65
+ status: 'nothing_to_compact',
66
+ engine,
67
+ note: 'Too little conversation to compact yet: the last exchanges are always kept as they are.',
68
+ };
69
+ }
70
+ await deps.metaStore.update(agent, session, (fresh) => ({
71
+ ...fresh,
72
+ compactions: [...(((fresh as { compactions?: Compaction[] }).compactions) ?? []), compaction],
73
+ }));
74
+ return {
75
+ status: 'compacted',
76
+ engine,
77
+ ...(compaction.tokensBefore !== undefined ? { tokensBefore: compaction.tokensBefore } : {}),
78
+ ...(compaction.tokensAfter !== undefined ? { tokensAfter: compaction.tokensAfter } : {}),
79
+ };
80
+ }
81
+
82
+ if (engine === 'claude-cli') {
83
+ const r = await (deps.engines?.claude ?? compactClaudeSession)({
84
+ agent,
85
+ session,
86
+ resolvedModel,
87
+ systemPrompt: await deps.systemPrompt(),
88
+ metaStore: deps.metaStore,
89
+ ...(focus ? { focus } : {}),
90
+ });
91
+ return r.status === 'compacted'
92
+ ? { status: 'compacted', engine, ...pickTokens(r) }
93
+ : { status: 'nothing_to_compact', engine, note: r.note ?? 'Claude did not compact.' };
94
+ }
95
+
96
+ if (engine === 'codex-cli') {
97
+ const r = await (deps.engines?.codex ?? compactCodexThread)({
98
+ agent,
99
+ session,
100
+ resolvedModel,
101
+ metaStore: deps.metaStore,
102
+ });
103
+ if (r.status !== 'compacted') {
104
+ return { status: 'nothing_to_compact', engine, note: r.note ?? 'Codex did not compact.' };
105
+ }
106
+ return {
107
+ status: 'compacted',
108
+ engine,
109
+ ...pickTokens(r),
110
+ ...(focus ? { note: 'Codex compacts by its own rules and takes no instructions: the focus was not used.' } : {}),
111
+ };
112
+ }
113
+
114
+ return { status: 'unsupported', engine, note: `Compacting by hand is not available on the ${engine} engine.` };
115
+ }
116
+
117
+ function pickTokens(r: { tokensBefore?: number; tokensAfter?: number }): { tokensBefore?: number; tokensAfter?: number } {
118
+ return {
119
+ ...(typeof r.tokensBefore === 'number' && r.tokensBefore > 0 ? { tokensBefore: r.tokensBefore } : {}),
120
+ ...(typeof r.tokensAfter === 'number' && r.tokensAfter > 0 ? { tokensAfter: r.tokensAfter } : {}),
121
+ };
122
+ }
123
+
124
+ /** The chat row: what happened, in one line every client can show. */
125
+ export function manualCompactionText(o: Extract<ManualCompactionOutcome, { status: 'compacted' }>, focus?: string): string {
126
+ const size =
127
+ o.tokensBefore !== undefined && o.tokensAfter !== undefined
128
+ ? ` (${formatTokens(o.tokensBefore)} → ${formatTokens(o.tokensAfter)} tokens)`
129
+ : o.tokensBefore !== undefined
130
+ ? ` (was ${formatTokens(o.tokensBefore)} tokens)`
131
+ : '';
132
+ const by = o.engine === 'openai-compatible' ? 'somora summarised the earlier conversation' : `${o.engine === 'claude-cli' ? 'Claude' : 'Codex'} compacted its session`;
133
+ return `Compacted by hand: ${by}${size}.${focus && !o.note ? ` Focus: ${focus}` : ''}${o.note ? ` ${o.note}` : ''}`;
134
+ }
135
+
136
+ function formatTokens(n: number): string {
137
+ return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);
138
+ }
@@ -0,0 +1,30 @@
1
+ // The thinking level a turn runs with, and where it comes from. One
2
+ // resolver for the turn and for the route the clients read, so what a
3
+ // client shows is what the model gets.
4
+ //
5
+ // session override (/thinking) > agent.yaml `thinking:` >
6
+ // the model's `reasoning.default` in config.yaml > none
7
+ //
8
+ // "none" sends nothing, and the model does what it does by default —
9
+ // many reasoning models think. Clients show that as "model decides",
10
+ // never as "off".
11
+ import type { Model, ThinkingLevel } from '../config/types.ts';
12
+
13
+ export const VALID_THINKING_LEVELS = new Set<ThinkingLevel>(['off', 'low', 'medium', 'high']);
14
+
15
+ export type ThinkingSource = 'session-override' | 'persona-default' | 'model-default' | 'engine-default';
16
+
17
+ export function resolveThinking(
18
+ persona: { thinking?: ThinkingLevel },
19
+ sessionMeta: Record<string, unknown>,
20
+ model?: Pick<Model, 'reasoning'>,
21
+ ): { level: ThinkingLevel | undefined; source: ThinkingSource } {
22
+ const override = sessionMeta.thinkingOverride;
23
+ if (typeof override === 'string' && VALID_THINKING_LEVELS.has(override as ThinkingLevel)) {
24
+ return { level: override as ThinkingLevel, source: 'session-override' };
25
+ }
26
+ if (persona.thinking) return { level: persona.thinking, source: 'persona-default' };
27
+ const modelDefault = model?.reasoning?.default;
28
+ if (modelDefault) return { level: modelDefault, source: 'model-default' };
29
+ return { level: undefined, source: 'engine-default' };
30
+ }
@@ -6,7 +6,7 @@ import type { TurnOrigin } from '../types/turn-origin.ts';
6
6
 
7
7
  export type { TurnOrigin, TurnOriginKind, TurnOriginRef } from '../types/turn-origin.ts';
8
8
 
9
- export type FromSystem = 'sentinel' | 'tmux' | 'subagent' | 'job' | 'browser' | 'voice' | 'a2a';
9
+ export type FromSystem = 'sentinel' | 'tmux' | 'subagent' | 'job' | 'browser' | 'voice' | 'a2a' | 'system';
10
10
 
11
11
  export interface LegacyOriginFields {
12
12
  fromAgent?: string;
@@ -25,7 +25,7 @@ export interface LegacyOriginFields {
25
25
  * agent → from_agent, from_session (when known), agent_ask_call_id (when known)
26
26
  * subagent → subagentDepth only (a brief is neutral, never labelled — Juni-Audit 2026-07)
27
27
  * sentinel/tmux/browser/voice → from_system = kind
28
- * wake → from_system = about ('a2a' | 'subagent' | 'job'), subagentDepth when carried
28
+ * wake → from_system = about ('a2a' | 'subagent' | 'job' | 'system'), subagentDepth when carried
29
29
  */
30
30
  export function originToLegacy(origin: TurnOrigin): LegacyOriginFields {
31
31
  switch (origin.kind) {
package/src/ssh/exec.ts CHANGED
@@ -9,6 +9,9 @@
9
9
  import type { Client } from 'ssh2';
10
10
 
11
11
  const DEFAULT_MAX_OUTPUT_BYTES = 256 * 1024;
12
+ /** After the remote shell exited: how long to wait for the channel to
13
+ * close before concluding a background process holds it open. */
14
+ export const HELD_OPEN_GRACE_MS = 3_000;
12
15
 
13
16
  export interface RemoteExecResult {
14
17
  stdout: string;
@@ -67,16 +70,48 @@ export async function remoteExec(
67
70
  const stderrChunks: Buffer[] = [];
68
71
  let totalBytes = 0;
69
72
  let truncated = false;
70
- let timedOut = false;
71
- const timer = setTimeout(() => {
72
- timedOut = true;
73
- try {
74
- stream.signal('KILL');
75
- stream.end();
76
- } catch {
77
- /* best-effort */
73
+ let done = false;
74
+ let exitCode: number | null = null;
75
+ let exitSignal: string | null = null;
76
+ let afterExitTimer: NodeJS.Timeout | undefined;
77
+
78
+ // One way out, whichever comes first: the channel closes (normal
79
+ // end), the deadline passes, or the command exited but a process
80
+ // it left in the background still holds stdout/stderr open — the
81
+ // channel would then stay open until that process ends.
82
+ const finish = (how: 'closed' | 'timeout' | 'held-open', code: number | null, signal: string | null): void => {
83
+ if (done) return;
84
+ done = true;
85
+ clearTimeout(timer);
86
+ if (afterExitTimer) clearTimeout(afterExitTimer);
87
+ if (how !== 'closed') {
88
+ try {
89
+ if (how === 'timeout') stream.signal('KILL');
90
+ stream.close();
91
+ } catch {
92
+ /* best-effort */
93
+ }
94
+ }
95
+ const ms = Date.now() - start;
96
+ const result: RemoteExecResult = {
97
+ stdout: Buffer.concat(stdoutChunks).toString('utf8'),
98
+ stderr: Buffer.concat(stderrChunks).toString('utf8'),
99
+ code: how === 'timeout' ? null : code,
100
+ signal: how === 'timeout' ? 'TIMEOUT' : signal,
101
+ truncated,
102
+ ms,
103
+ };
104
+ if (how === 'timeout') {
105
+ result.stderr = `${result.stderr}\n[somora] command exceeded ${timeoutMs}ms — stopped and the channel closed after ${ms}ms. Processes it started in the background on the remote may still be running.`;
106
+ } else if (how === 'held-open') {
107
+ result.stderr =
108
+ `${result.stderr}\n[somora] the command exited (code ${code ?? 'none'}), but a process it left in the background still held its output open — returned without waiting. ` +
109
+ 'That process keeps running. To detach cleanly: `nohup cmd </dev/null >/tmp/cmd.log 2>&1 &`, or use background: true.';
78
110
  }
79
- }, timeoutMs);
111
+ resolve(result);
112
+ };
113
+
114
+ const timer = setTimeout(() => finish('timeout', null, null), timeoutMs);
80
115
 
81
116
  const onData = (data: Buffer, sink: Buffer[]): void => {
82
117
  if (truncated) return;
@@ -99,20 +134,18 @@ export async function remoteExec(
99
134
  if (stream.stderr) {
100
135
  stream.stderr.on('data', (d: Buffer) => onData(d, stderrChunks));
101
136
  }
137
+ // The remote shell reports its exit status before the channel
138
+ // closes. Normally 'close' follows at once; if it does not within
139
+ // a few seconds, something the command left in the background
140
+ // still holds the output open, and waiting would block until it
141
+ // ends (or the connection idles out).
142
+ stream.on('exit', (code: number | null, signal?: string | null) => {
143
+ exitCode = code;
144
+ exitSignal = signal ?? null;
145
+ afterExitTimer = setTimeout(() => finish('held-open', exitCode, exitSignal), HELD_OPEN_GRACE_MS);
146
+ });
102
147
  stream.on('close', (code: number | null, signal: string | null) => {
103
- clearTimeout(timer);
104
- const result: RemoteExecResult = {
105
- stdout: Buffer.concat(stdoutChunks).toString('utf8'),
106
- stderr: Buffer.concat(stderrChunks).toString('utf8'),
107
- code: timedOut ? null : code,
108
- signal: timedOut ? 'TIMEOUT' : signal,
109
- truncated,
110
- ms: Date.now() - start,
111
- };
112
- if (timedOut) {
113
- result.stderr = `${result.stderr}\n[somora] command exceeded ${timeoutMs}ms — killed`;
114
- }
115
- resolve(result);
148
+ finish('closed', code ?? exitCode, signal ?? exitSignal);
116
149
  });
117
150
  };
118
151
  if (execOpts) {