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
@@ -10,12 +10,16 @@ export interface BuildSummaryPromptInput {
10
10
  pairs: ReplayPair[];
11
11
  /** Optional: prior summary that this compaction should subsume. */
12
12
  priorSummary?: string;
13
+ /** Optional: what a person who compacted by hand asked the summary to
14
+ * keep (`/compact keep every path and open question`). */
15
+ focus?: string;
13
16
  }
14
17
 
15
18
  export function buildSummaryPrompt({
16
19
  systemPrompt,
17
20
  pairs,
18
21
  priorSummary,
22
+ focus,
19
23
  }: BuildSummaryPromptInput): { system: string; user: string } {
20
24
  const system = [
21
25
  'You write a structured summary of an ongoing conversation for an',
@@ -84,6 +88,17 @@ export function buildSummaryPrompt({
84
88
  }
85
89
  userParts.push('</conversation-to-summarize>');
86
90
  userParts.push('');
91
+ if (focus) {
92
+ userParts.push(
93
+ '<focus>',
94
+ focus,
95
+ '</focus>',
96
+ 'The user compacted this conversation by hand and asked the summary',
97
+ 'to pay particular attention to the focus above. Keep everything it',
98
+ 'names, verbatim where the history allows.',
99
+ '',
100
+ );
101
+ }
87
102
  userParts.push('Write the seven sections now.');
88
103
 
89
104
  return { system, user: userParts.join('\n') };
@@ -20,6 +20,9 @@ export interface Compaction {
20
20
  tokensBefore?: number;
21
21
  /** Output-token count of the summary itself. */
22
22
  tokensAfter?: number;
23
+ /** Set when a person asked for it (`/compact`); absent for the
24
+ * automatic compaction before a turn. */
25
+ trigger?: 'manual';
23
26
  }
24
27
 
25
28
  export interface CompactionConfig {
@@ -156,6 +156,37 @@ providers:
156
156
  # system: false
157
157
  `;
158
158
 
159
+ /** One schema problem: the dotted path and what is wrong. */
160
+ export interface ConfigIssue {
161
+ path: string;
162
+ message: string;
163
+ }
164
+
165
+ /** Validate config.yaml text exactly as the server does at start and on
166
+ * reload: YAML syntax, the schema, unique model aliases. Never throws. */
167
+ export function validateConfigText(raw: string): { ok: true; config: Config } | { ok: false; issues: ConfigIssue[] } {
168
+ let parsed: unknown;
169
+ try {
170
+ parsed = parseYaml(raw);
171
+ } catch (err) {
172
+ return { ok: false, issues: [{ path: '(yaml)', message: (err as Error).message.split('\n')[0] ?? String(err) }] };
173
+ }
174
+ const result = ConfigSchema.safeParse(parsed);
175
+ if (!result.success) {
176
+ return { ok: false, issues: result.error.issues.map((i) => ({ path: i.path.join('.') || '(root)', message: i.message })) };
177
+ }
178
+ try {
179
+ assertUniqueAliases(result.data);
180
+ } catch (err) {
181
+ return { ok: false, issues: [{ path: 'providers', message: (err as Error).message }] };
182
+ }
183
+ return { ok: true, config: result.data };
184
+ }
185
+
186
+ export function formatConfigIssues(issues: ConfigIssue[]): string {
187
+ return issues.map((i) => ` - ${i.path}: ${i.message}`).join('\n');
188
+ }
189
+
159
190
  export async function loadConfig(): Promise<Config> {
160
191
  await mkdir(SOMORA_HOME, { recursive: true });
161
192
  let raw: string;
@@ -166,16 +197,11 @@ export async function loadConfig(): Promise<Config> {
166
197
  await writeFile(CONFIG_PATH, DEFAULT_CONFIG, 'utf8');
167
198
  raw = DEFAULT_CONFIG;
168
199
  }
169
- const parsed = parseYaml(raw);
170
- const result = ConfigSchema.safeParse(parsed);
171
- if (!result.success) {
172
- const issues = result.error.issues
173
- .map((i) => ` - ${i.path.join('.') || '(root)'}: ${i.message}`)
174
- .join('\n');
175
- throw new Error(`config.yaml is invalid (${CONFIG_PATH}):\n${issues}`);
200
+ const checked = validateConfigText(raw);
201
+ if (!checked.ok) {
202
+ throw new Error(`config.yaml is invalid (${CONFIG_PATH}):\n${formatConfigIssues(checked.issues)}`);
176
203
  }
177
- assertUniqueAliases(result.data);
178
- return result.data;
204
+ return checked.config;
179
205
  }
180
206
 
181
207
  // Lazy hot-reload cache for config.yaml. Tools that legitimately need
@@ -201,11 +227,27 @@ export async function loadConfig(): Promise<Config> {
201
227
  let cachedFreshConfig: Config | null = null;
202
228
  let cachedFreshMtimeMs = 0;
203
229
 
230
+ /** The file on disk does not validate; the last valid config stays in
231
+ * use. `since` = when this version of the file was first seen. */
232
+ export interface ConfigProblem {
233
+ mtimeMs: number;
234
+ since: string;
235
+ message: string;
236
+ }
237
+ let configProblem: ConfigProblem | null = null;
238
+
239
+ /** Set while config.yaml on disk is invalid and the last valid version
240
+ * is in use; null once the file validates again. */
241
+ export function currentConfigProblem(): ConfigProblem | null {
242
+ return configProblem;
243
+ }
244
+
204
245
  /** After POST /config/reload: make getFreshConfig() hand out the same
205
246
  * object the server just switched to, instead of re-parsing once more. */
206
247
  export function primeFreshConfig(cfg: Config, mtimeMs: number): void {
207
248
  cachedFreshConfig = cfg;
208
249
  cachedFreshMtimeMs = mtimeMs;
250
+ configProblem = null;
209
251
  }
210
252
 
211
253
  export async function getFreshConfig(): Promise<Config> {
@@ -220,7 +262,30 @@ export async function getFreshConfig(): Promise<Config> {
220
262
  if (cachedFreshConfig && mtimeMs === cachedFreshMtimeMs) {
221
263
  return cachedFreshConfig;
222
264
  }
223
- const fresh = await loadConfig();
265
+ let fresh: Config;
266
+ try {
267
+ fresh = await loadConfig();
268
+ } catch (err) {
269
+ // A broken edit must not stop every turn of every agent: keep the
270
+ // last valid config, as POST /config/reload does, and say so once
271
+ // per version of the file. Without a last valid one (nothing loaded
272
+ // yet) there is nothing to fall back to.
273
+ if (!cachedFreshConfig) throw err;
274
+ if (configProblem?.mtimeMs !== mtimeMs) {
275
+ configProblem = { mtimeMs, since: new Date().toISOString(), message: (err as Error).message };
276
+ // Imported here, not at the top: the CLI loads this module too and
277
+ // must not start the server's log writer.
278
+ const { logger } = await import('../server/logger.ts');
279
+ logger.error({ msg: 'config.invalid_kept_last_good', err: (err as Error).message });
280
+ }
281
+ cachedFreshMtimeMs = mtimeMs;
282
+ return cachedFreshConfig;
283
+ }
284
+ if (configProblem) {
285
+ const { logger } = await import('../server/logger.ts');
286
+ logger.info({ msg: 'config.valid_again' });
287
+ }
288
+ configProblem = null;
224
289
  cachedFreshConfig = fresh;
225
290
  cachedFreshMtimeMs = mtimeMs;
226
291
  return fresh;
@@ -36,6 +36,12 @@ export type ThinkingLevel = z.infer<typeof ThinkingLevelSchema>;
36
36
  * `reasoning_effort`). See docs/thinking.md → Per-model vocabulary.
37
37
  */
38
38
  export const ModelReasoningSchema = z.object({
39
+ /** The thinking level this model runs with when neither the session
40
+ * (/thinking) nor the agent (`thinking:` in agent.yaml) sets one, in
41
+ * somora's words. Sent explicitly and shown as the model's default in
42
+ * every client. Unset = nothing is sent and the model decides — many
43
+ * reasoning models then think. Applies on every engine. */
44
+ default: z.enum(['off', 'low', 'medium', 'high']).optional(),
39
45
  /** Body shape. `reasoning_effort` (top-level, default), `reasoning`
40
46
  * (OpenRouter's nested `{ reasoning: { effort } }`), or
41
47
  * `chat_template_kwargs` (vLLM templates that only read kwargs). */
@@ -100,7 +106,8 @@ export const ModelSchema = z.object({
100
106
  * injected memory block).
101
107
  */
102
108
  maxTokens: z.number().int().positive().optional(),
103
- /** Reasoning vocabulary + wire shape for this model (openai-compatible only). */
109
+ /** Reasoning default for every engine; vocabulary + wire shape
110
+ * (`levels`, `param`) apply to openai-compatible, codex-cli, grok-cli. */
104
111
  reasoning: ModelReasoningSchema.optional(),
105
112
  /** Vendor-recommended sampling defaults for this model (openai-compatible
106
113
  * only). agent.yaml `sampling:` and the session override win per key. */
@@ -214,6 +221,16 @@ export const OpenAiCompatibleProviderSchema = z.object({
214
221
  * agent or session names.
215
222
  */
216
223
  sendUserTag: z.boolean().default(true).optional(),
224
+ /**
225
+ * The memory block of every past turn is replayed with the history so
226
+ * the provider's prompt cache keeps hitting. After a pause the cache
227
+ * has expired anyway — then the old blocks are dropped from the
228
+ * history, once, and the session continues without them. Minutes of
229
+ * silence that count as such a pause; 0 keeps them for good. Set it
230
+ * to the provider's cache lifetime: about 60 for a paid API, a few
231
+ * minutes for your own server.
232
+ */
233
+ dropMemoryBlocksAfterIdleMinutes: z.number().int().min(0).max(10080).default(60).optional(),
217
234
  });
218
235
 
219
236
  /** The one provider variant that carries baseUrl + apiKey. Named so
@@ -307,7 +324,14 @@ export const MemoryAutoInjectConfigSchema = z.object({
307
324
  * is the remainder. `null` = use `memory.hybrid` as for every query.
308
325
  */
309
326
  shortQueryBm25Weight: z.number().min(0).max(1).nullable().default(0.5),
310
- }).default({ queryTurns: 3, maxResults: 5, minScore: 0.35, maxTokens: 1500, historyWeight: 0.3, historyWeightShort: 0.55, historyWeightEmpty: 0.8, historyTurnChars: 800, shortQueryBm25Weight: 0.5 });
327
+ /**
328
+ * Leave out hits the model still has in front of it: a note section
329
+ * already injected in an earlier turn of this session that is still
330
+ * in the context (not compacted away, not dropped after a pause). Its
331
+ * place goes to the next hit. Off = every turn gets the full block.
332
+ */
333
+ skipRepeats: z.boolean().default(true),
334
+ }).default({ queryTurns: 3, maxResults: 5, minScore: 0.35, maxTokens: 1500, historyWeight: 0.3, historyWeightShort: 0.55, historyWeightEmpty: 0.8, historyTurnChars: 800, shortQueryBm25Weight: 0.5, skipRepeats: true });
311
335
 
312
336
  export const MemoryHybridConfigSchema = z.object({
313
337
  vectorWeight: z.number().min(0).max(1).default(0.7),
@@ -364,7 +388,7 @@ export const MemoryConfigSchema = z.object({
364
388
  }).default({
365
389
  embedding: { provider: 'local', model: 'all-MiniLM-L6-v2' },
366
390
  chunking: { targetTokens: 400, overlapTokens: 80 },
367
- autoInject: { queryTurns: 3, maxResults: 5, minScore: 0.35, maxTokens: 1500, historyWeight: 0.3, historyWeightShort: 0.55, historyWeightEmpty: 0.8, historyTurnChars: 800, shortQueryBm25Weight: 0.5 },
391
+ autoInject: { queryTurns: 3, maxResults: 5, minScore: 0.35, maxTokens: 1500, historyWeight: 0.3, historyWeightShort: 0.55, historyWeightEmpty: 0.8, historyTurnChars: 800, shortQueryBm25Weight: 0.5, skipRepeats: true },
368
392
  hybrid: { vectorWeight: 0.7, bm25Weight: 0.3, slugMatchBoost: 1.5, logDemotion: 0.5, pageSupport: 0.3, slugFullNameBoost: 1.5 },
369
393
  rescanMinutes: 10,
370
394
  });
@@ -972,14 +996,16 @@ const WorkerRefSchema = z.union([z.string().min(1), z.array(z.string().min(1)).m
972
996
  export const VisionConfigSchema = z
973
997
  .object({
974
998
  /** Worker(s) for image + PDF analysis, `<provider>/<modelId>` each.
975
- * A worker MUST have `image` capability; PDF use also requires
976
- * `pdf` (or set `pdfWorker` to a model that has it). Entries that
999
+ * A worker MUST have `image` capability. A PDF goes to a worker
1000
+ * with `pdf` as the document, to one with only `image` as page
1001
+ * images (first 20 pages). Entries that
977
1002
  * lack the needed capability are skipped, not fatal — the point of
978
1003
  * a chain is that it survives one entry being unusable. */
979
1004
  worker: WorkerRefSchema.optional(),
980
1005
  /** Override for PDF dispatch only. When unset, PDF uses `worker`.
981
- * Use case: a cheap image-only worker plus a separate PDF-capable
982
- * one for cost control. */
1006
+ * Use case: images to a cheap or local worker, PDFs to a model
1007
+ * that reads the document itself (its text, not only page
1008
+ * pictures) — better for long or text-heavy PDFs. */
983
1009
  pdfWorker: WorkerRefSchema.optional(),
984
1010
  /** Per-attempt budget. A worker that hasn't answered by then counts
985
1011
  * as down and the chain moves on. Generous by default because a
@@ -1975,8 +2001,15 @@ export const AttachmentsConfigSchema = z
1975
2001
  maxPdfBytes: z.number().int().positive().default(32 * 1024 * 1024),
1976
2002
  maxTextBytes: z.number().int().positive().default(1 * 1024 * 1024),
1977
2003
  maxPerTurn: z.number().int().positive().default(10),
2004
+ /** Longest side, in pixels, of an image sent to a model; larger
2005
+ * images are scaled down first (src/multimodal/model-image.ts).
2006
+ * 0 = send images as they are. With scaling on, a source image may
2007
+ * be up to IMAGE_SOURCE_BYTES before scaling; maxImageBytes then
2008
+ * applies to what is sent. */
2009
+ maxImageEdge: z.number().int().min(0).max(16384).default(2048),
1978
2010
  })
1979
2011
  .default({
2012
+ maxImageEdge: 2048,
1980
2013
  maxImageBytes: 5 * 1024 * 1024,
1981
2014
  maxPdfBytes: 32 * 1024 * 1024,
1982
2015
  maxTextBytes: 1 * 1024 * 1024,
package/src/engine/a2a.ts CHANGED
@@ -12,7 +12,7 @@ const HEADER_PREFIX = '[Message from agent ';
12
12
  /** Agent-facing slug of a session id: `20260906-172957_craftbox`
13
13
  * → `craftbox`, `main` stays `main`. Unknown shapes pass through. */
14
14
  export function sessionSlugOf(sessionId: string): string {
15
- const m = /^\d{8}-\d{6}_(.+)$/.exec(sessionId);
15
+ const m = /^(?:\d{8}-\d{6}_)+(.+)$/.exec(sessionId);
16
16
  return m ? m[1]! : sessionId;
17
17
  }
18
18
 
@@ -281,10 +281,19 @@ export const claudeCliEngine: AgentEngine = {
281
281
  // letterbox poll, and records waiting to be yielded from the loop.
282
282
  let steerInput: SteerableInput | undefined;
283
283
  let steerPoll: ReturnType<typeof setInterval> | undefined;
284
- // Messages handed to the SDK beyond the first, and results seen:
285
- // the input closes when results === 1 + pushedSteers.
284
+ // Steers the SDK has not answered yet. The SDK folds a message that
285
+ // arrives while a tool runs into its next request (right after the
286
+ // tool result) — the model answers it within the current leg, and
287
+ // no extra result follows. Only a message that arrives after the
288
+ // last tool result, while the final answer is written, gets a leg
289
+ // of its own. Counting every push as a leg left the turn waiting
290
+ // for a result that never came, until the idle watchdog ended it
291
+ // as an error (report 2026-10-04; probed against the SDK).
286
292
  let pushedSteers = 0;
293
+ let unansweredSteers = 0;
287
294
  let resultsSeen = 0;
295
+ let sawSuccessResult = false;
296
+ let closedAfterResult = false;
288
297
  const pendingSteerEvents: NormalizedEvent[] = [];
289
298
  if (signal) {
290
299
  if (signal.aborted) sdkAbortController.abort();
@@ -318,6 +327,27 @@ export const claudeCliEngine: AgentEngine = {
318
327
  if (idleTimer) clearTimeout(idleTimer);
319
328
  const threshold = pendingToolCalls > 0 ? TOOL_IDLE_TIMEOUT_MS : IDLE_TIMEOUT_MS;
320
329
  idleTimer = setTimeout(() => {
330
+ // After a successful result with no tool outstanding, silence
331
+ // means the SDK has nothing left to do — not a dead child. End
332
+ // the turn normally by closing the input; if the iterator still
333
+ // does not finish, the next firing aborts as usual.
334
+ if (sawSuccessResult && pendingToolCalls === 0 && !closedAfterResult && steerInput) {
335
+ closedAfterResult = true;
336
+ logger.warn({
337
+ msg: 'engine.steer_leg_never_started',
338
+ engine: ENGINE,
339
+ agent,
340
+ session,
341
+ turnId,
342
+ results: resultsSeen,
343
+ pushed_steers: pushedSteers,
344
+ unanswered_steers: unansweredSteers,
345
+ hint: 'the answer was complete; closing the input instead of failing the turn',
346
+ });
347
+ steerInput.close();
348
+ armIdleTimer();
349
+ return;
350
+ }
321
351
  watchdogFired = true;
322
352
  logger.error({
323
353
  msg: 'engine.watchdog_idle_timeout',
@@ -326,7 +356,10 @@ export const claudeCliEngine: AgentEngine = {
326
356
  session,
327
357
  idleMs: threshold,
328
358
  pendingToolCalls,
329
- hint: 'no SDK events received — likely underlying claude-cli child died silently after tool_use; aborting to surface as error',
359
+ hint:
360
+ pendingToolCalls > 0
361
+ ? 'no SDK events while a tool call was outstanding — the claude-cli child likely died; aborting to surface as error'
362
+ : 'no SDK events received — the claude-cli child likely died silently; aborting to surface as error',
330
363
  });
331
364
  sdkAbortController.abort();
332
365
  }, threshold);
@@ -395,6 +428,7 @@ export const claudeCliEngine: AgentEngine = {
395
428
  message: { role: 'user', content: steer.frame(m) },
396
429
  });
397
430
  pushedSteers += 1;
431
+ unansweredSteers += 1;
398
432
  }
399
433
  pendingSteerEvents.push({ kind: 'steer_applied', ts: Date.now(), engine: ENGINE, messages: msgs });
400
434
  }, 300);
@@ -596,6 +630,14 @@ export const claudeCliEngine: AgentEngine = {
596
630
  }
597
631
  } else if (msg.type === 'stream_event') {
598
632
  const ev = msg.event;
633
+ // A new request after a result: the SDK is answering the steers
634
+ // that came in while the final answer was written.
635
+ if (ev.type === 'message_start' && resultsSeen > 0) {
636
+ unansweredSteers = 0;
637
+ // The steer's answer continues the same bubble: keep it a
638
+ // paragraph of its own instead of gluing it to the last word.
639
+ if (cumulative && !cumulative.endsWith('\n\n')) cumulative += cumulative.endsWith('\n') ? '\n' : '\n\n';
640
+ }
599
641
  if (ev.type === 'content_block_delta' && ev.delta.type === 'text_delta') {
600
642
  cumulative += ev.delta.text;
601
643
  receivedTextViaStream = true;
@@ -648,6 +690,9 @@ export const claudeCliEngine: AgentEngine = {
648
690
  } else if (msg.type === 'user') {
649
691
  for (const block of msg.message.content) {
650
692
  if (typeof block === 'object' && 'type' in block && block.type === 'tool_result') {
693
+ // Every steer pushed so far rides along with this tool
694
+ // result into the next request — the model answers it there.
695
+ unansweredSteers = 0;
651
696
  // Tool finished — drop back toward the normal idle threshold
652
697
  // once no tools are outstanding (re-armed below at loop top).
653
698
  if (pendingToolCalls > 0) pendingToolCalls--;
@@ -689,7 +734,8 @@ export const claudeCliEngine: AgentEngine = {
689
734
  clearInterval(steerPoll);
690
735
  steerPoll = undefined;
691
736
  }
692
- if (resultsSeen >= 1 + pushedSteers) {
737
+ if (msg.subtype === 'success') sawSuccessResult = true;
738
+ if (unansweredSteers === 0) {
693
739
  steerInput?.close();
694
740
  } else {
695
741
  logger.info({
@@ -700,6 +746,7 @@ export const claudeCliEngine: AgentEngine = {
700
746
  turnId,
701
747
  results: resultsSeen,
702
748
  pushed_steers: pushedSteers,
749
+ unanswered_steers: unansweredSteers,
703
750
  });
704
751
  }
705
752
  if (msg.subtype === 'success') {
@@ -967,3 +1014,88 @@ export const claudeCliEngine: AgentEngine = {
967
1014
  }
968
1015
  },
969
1016
  };
1017
+
1018
+ /** Outcome of a compaction asked for by hand. */
1019
+ export interface ManualCompactionResult {
1020
+ status: 'compacted' | 'nothing_to_compact';
1021
+ tokensBefore?: number;
1022
+ tokensAfter?: number;
1023
+ /** Why nothing happened, in the engine's own words. */
1024
+ note?: string;
1025
+ }
1026
+
1027
+ /**
1028
+ * `/compact [focus]` on a claude-cli session: Claude Code compacts its
1029
+ * own session (the same as typing /compact in Claude Code), the focus
1030
+ * goes along as its custom instructions. Runs outside a turn; the
1031
+ * caller holds the session lock.
1032
+ */
1033
+ export async function compactClaudeSession(args: {
1034
+ agent: string;
1035
+ session: string;
1036
+ resolvedModel: TurnInput['resolvedModel'];
1037
+ systemPrompt: string;
1038
+ metaStore: TurnInput['metaStore'];
1039
+ focus?: string;
1040
+ timeoutMs?: number;
1041
+ }): Promise<ManualCompactionResult> {
1042
+ const { agent, session, resolvedModel, metaStore } = args;
1043
+ const meta = (await metaStore.get(agent, session)) as ClaudeCliMeta;
1044
+ // Nothing to compact when Claude never held this session, or when the
1045
+ // next turn rebuilds it anyway (MCP server renamed).
1046
+ if (!meta.sdkSessionId || meta.mcpServerName !== MCP_SERVER_NAME) {
1047
+ return { status: 'nothing_to_compact', note: 'Claude has no conversation for this session yet.' };
1048
+ }
1049
+ reconcileClaudeCredentials();
1050
+ const abort = new AbortController();
1051
+ const timer = setTimeout(() => abort.abort(), args.timeoutMs ?? 300_000);
1052
+ let sessionId = meta.sdkSessionId;
1053
+ let boundary: { pre_tokens?: number; post_tokens?: number } | undefined;
1054
+ let resultText = '';
1055
+ try {
1056
+ const stream = query({
1057
+ prompt: args.focus ? `/compact ${args.focus}` : '/compact',
1058
+ options: {
1059
+ model: resolvedModel.modelId,
1060
+ systemPrompt: args.systemPrompt,
1061
+ settingSources: [],
1062
+ tools: ['ToolSearch'],
1063
+ disallowedTools: KNOWN_ACCOUNT_TOOLS,
1064
+ mcpServers: {
1065
+ [MCP_SERVER_NAME]: somoraMemoryServerSpawn({
1066
+ agent,
1067
+ session,
1068
+ activeModelRef: `${resolvedModel.providerName}/${resolvedModel.modelId}`,
1069
+ }),
1070
+ },
1071
+ canUseTool: somoraToolGate,
1072
+ strictMcpConfig: true,
1073
+ abortController: abort,
1074
+ managedSettings: { autoMemoryEnabled: false },
1075
+ ...(CLAUDE_BIN ? { pathToClaudeCodeExecutable: CLAUDE_BIN } : {}),
1076
+ resume: meta.sdkSessionId,
1077
+ },
1078
+ });
1079
+ for await (const msg of stream as AsyncIterable<SDKMessage>) {
1080
+ const m = msg as { type: string; subtype?: string; session_id?: string; compact_metadata?: { pre_tokens?: number; post_tokens?: number }; result?: string };
1081
+ if (typeof m.session_id === 'string') sessionId = m.session_id;
1082
+ if (m.type === 'system' && m.subtype === 'compact_boundary') boundary = m.compact_metadata;
1083
+ if (m.type === 'result' && typeof m.result === 'string') resultText = m.result;
1084
+ }
1085
+ } finally {
1086
+ clearTimeout(timer);
1087
+ }
1088
+ if (sessionId !== meta.sdkSessionId) {
1089
+ await metaStore.update(agent, session, (fresh) => ({ ...fresh, sdkSessionId: sessionId }));
1090
+ }
1091
+ if (!boundary) {
1092
+ logger.info({ msg: 'engine.manual_compaction_skipped', engine: ENGINE, agent, session, result: resultText.slice(0, 200) });
1093
+ return { status: 'nothing_to_compact', note: resultText.trim() || 'Claude did not compact.' };
1094
+ }
1095
+ logger.info({ msg: 'engine.manual_compaction_done', engine: ENGINE, agent, session, tokensBefore: boundary.pre_tokens, tokensAfter: boundary.post_tokens });
1096
+ return {
1097
+ status: 'compacted',
1098
+ ...(typeof boundary.pre_tokens === 'number' ? { tokensBefore: boundary.pre_tokens } : {}),
1099
+ ...(typeof boundary.post_tokens === 'number' ? { tokensAfter: boundary.post_tokens } : {}),
1100
+ };
1101
+ }
@@ -1012,3 +1012,77 @@ export const codexCliEngine: AgentEngine = {
1012
1012
  }
1013
1013
  },
1014
1014
  };
1015
+
1016
+ /**
1017
+ * `/compact` on a codex-cli session: Codex compacts its own thread
1018
+ * (`thread/compact/start`), which runs as a short turn of its own.
1019
+ * Codex takes no instructions for it, so a focus is not passed on —
1020
+ * the caller says so. Runs outside a turn; the caller holds the
1021
+ * session lock.
1022
+ */
1023
+ export async function compactCodexThread(args: {
1024
+ agent: string;
1025
+ session: string;
1026
+ resolvedModel: TurnInput['resolvedModel'];
1027
+ metaStore: TurnInput['metaStore'];
1028
+ timeoutMs?: number;
1029
+ }): Promise<{ status: 'compacted' | 'nothing_to_compact'; tokensBefore?: number; note?: string }> {
1030
+ const { agent, session, metaStore } = args;
1031
+ const meta = (await metaStore.get(agent, session)) as CodexCliMeta;
1032
+ if (!meta.codexSessionId) {
1033
+ return { status: 'nothing_to_compact', note: 'Codex has no thread for this session yet.' };
1034
+ }
1035
+ const logCtx = { engine: ENGINE, agent, session };
1036
+ syncCodexAuth();
1037
+ const launch = resolveCodexLaunch();
1038
+ const workspace = join(somoraCodexHome(), 'workspace');
1039
+ mkdirSync(workspace, { recursive: true });
1040
+ let settle: ((how: 'done' | 'failed') => void) | null = null;
1041
+ const finished = new Promise<'done' | 'failed'>((resolve) => (settle = resolve));
1042
+ let compactedItem = false;
1043
+ // The compaction request's own input: the thread's size before.
1044
+ let tokensBefore: number | undefined;
1045
+ const client = await CodexAppServerClient.start({
1046
+ command: launch.command,
1047
+ args: codexAppServerArgv(launch),
1048
+ env: codexChildEnv(),
1049
+ cwd: workspace,
1050
+ logCtx,
1051
+ onServerRequest: async () => ({}),
1052
+ onNotification: (method, params) => {
1053
+ const p = params as { item?: { type?: string }; turn?: { status?: string }; tokenUsage?: { last?: { inputTokens?: number } } };
1054
+ if (method === 'item/completed' && p.item?.type === 'contextCompaction') compactedItem = true;
1055
+ if (method === 'thread/compacted') compactedItem = true;
1056
+ // Codex may report 0 here; a size of zero says nothing, so it is left out.
1057
+ if (method === 'thread/tokenUsage/updated' && (p.tokenUsage?.last?.inputTokens ?? 0) > 0) tokensBefore = p.tokenUsage!.last!.inputTokens;
1058
+ if (method === 'turn/completed') settle?.(p.turn?.status === 'completed' ? 'done' : 'failed');
1059
+ },
1060
+ });
1061
+ const timer = setTimeout(() => settle?.('failed'), args.timeoutMs ?? 300_000);
1062
+ try {
1063
+ await client.request(
1064
+ 'thread/resume',
1065
+ {
1066
+ threadId: meta.codexSessionId,
1067
+ excludeTurns: true,
1068
+ model: meta.codexRecordedModel ?? args.resolvedModel.modelId,
1069
+ cwd: workspace,
1070
+ approvalPolicy: 'never',
1071
+ sandbox: 'danger-full-access',
1072
+ personality: 'none',
1073
+ },
1074
+ { timeoutMs: 60_000 },
1075
+ );
1076
+ await client.request('thread/compact/start', { threadId: meta.codexSessionId }, { timeoutMs: 60_000 });
1077
+ const how = await finished;
1078
+ if (how !== 'done' || !compactedItem) {
1079
+ logger.warn({ msg: 'engine.manual_compaction_failed', ...logCtx, how, compactedItem });
1080
+ throw new Error('Codex did not finish the compaction.');
1081
+ }
1082
+ logger.info({ msg: 'engine.manual_compaction_done', ...logCtx, tokensBefore });
1083
+ return { status: 'compacted', ...(tokensBefore !== undefined ? { tokensBefore } : {}) };
1084
+ } finally {
1085
+ clearTimeout(timer);
1086
+ client.close();
1087
+ }
1088
+ }
@@ -67,6 +67,8 @@ export const ENGINE_META_LABELS: Record<string, Record<string, string>> = {
67
67
  somora: {
68
68
  // An agent switched (or cleared) this session's model.
69
69
  session_model: 'model switched',
70
+ // Someone compacted the session by hand (`/compact`), on any engine.
71
+ context_compacted: 'context compacted',
70
72
  },
71
73
  voice: {
72
74
  // The call moved to another agent. This is the only row a call