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,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
+ }
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) {
@@ -215,7 +215,7 @@ export async function findLiveSessionsBySlug(agent: string, slug: string): Promi
215
215
  if (isEnoent(err)) return [];
216
216
  throw err;
217
217
  }
218
- const re = new RegExp(`^\\d{8}-\\d{6}_${slug.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:-\\d+)?$`);
218
+ const re = new RegExp(`^(?:\\d{8}-\\d{6}_)+${slug.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:-\\d+)?$`);
219
219
  const out: string[] = [];
220
220
  for (const f of entries.sort()) {
221
221
  if (!f.endsWith('.jsonl')) continue;
@@ -223,7 +223,7 @@ export async function findLiveSessionsBySlug(agent: string, slug: string): Promi
223
223
  if (!re.test(id)) continue;
224
224
  const meta = await sessionMetaStore.get(agent, id);
225
225
  if (metaIsArchived(id, meta)) continue;
226
- if ((meta.slug ?? id.replace(/^\d{8}-\d{6}_/, '')) !== slug) continue;
226
+ if ((meta.slug ?? id.replace(/^(?:\d{8}-\d{6}_)+/, '')) !== slug) continue;
227
227
  out.push(id);
228
228
  }
229
229
  return out;
@@ -402,7 +402,19 @@ export interface SessionSummary {
402
402
  * writing it forward), or the id ends in `-archive` (legacy /reset output
403
403
  * before the explicit flag — backward-compat detect). */
404
404
  function metaIsArchived(id: string, meta: SessionMeta): boolean {
405
- return meta.archived === true || id.endsWith('-archive');
405
+ return isSessionArchived(id, meta);
406
+ }
407
+
408
+ /** A reset archive's id: `<ts>_<name>-archive`, or `-archive-N` when two
409
+ * resets landed in the same second. */
410
+ const RESET_ARCHIVE_ID = /-archive(?:-\d+)?$/;
411
+
412
+ /** Archived = flagged, or a reset archive by its id — unless the session
413
+ * was restored, which writes `archived: false` explicitly. */
414
+ export function isSessionArchived(id: string, meta: SessionMeta): boolean {
415
+ if (meta.archived === true) return true;
416
+ if (meta.archived === false) return false;
417
+ return RESET_ARCHIVE_ID.test(id);
406
418
  }
407
419
 
408
420
  interface CachedStats {
@@ -498,7 +510,9 @@ export async function listSessions(
498
510
  const summaries: SessionSummary[] = [];
499
511
  for (const id of ids) {
500
512
  const isMain = id === 'main';
501
- const slug = isMain ? 'main' : (id.match(/^\d{8}-\d{6}_(.+)$/)?.[1] ?? id);
513
+ // A reset archive of a named session has two timestamps
514
+ // (`<reset>_<created>_trip-archive`); its name is `trip-archive`.
515
+ const slug = isMain ? 'main' : (id.match(/^(?:\d{8}-\d{6}_)+(.+)$/)?.[1] ?? id);
502
516
  const meta = await sessionMetaStore.get(agent, id);
503
517
  const isArchived = metaIsArchived(id, meta);
504
518
  if (isArchived && !includeArchived) continue;
@@ -587,16 +601,27 @@ export async function archiveSession(
587
601
  }));
588
602
  }
589
603
 
590
- /** Clear the archived flag. The id-suffix detection (`-archive`) still
591
- * fires for legacy reset-archives, so unarchiving one of those is a no-op
592
- * for visibility purposes — the suffix check overrides the meta flag.
593
- * We still clear the meta flag for consistency. */
594
- export async function unarchiveSession(agent: string, session: string): Promise<void> {
595
- await sessionMetaStore.update(agent, session, (current) => {
596
- const next = { ...current };
597
- delete next.archived;
598
- delete next.archivedAt;
599
- delete next.archiveReason;
600
- return next;
604
+ /** Bring a session back from the archive, as a normal session to work
605
+ * in. A reset archive is archived by its id (`…-archive`), so clearing a
606
+ * flag is not enough: it gets `archived: false`, which beats the id rule,
607
+ * and the name its id shows (`main-archive`, `trip-archive`) instead of
608
+ * the name of the session it was reset from — that name belongs to the
609
+ * fresh session. REM's read marker stays, so the archived part is not
610
+ * dreamed a second time. Returns the session's name and state after. */
611
+ export async function unarchiveSession(agent: string, session: string): Promise<{ slug: string; isArchived: boolean }> {
612
+ const resetArchive = RESET_ARCHIVE_ID.test(session);
613
+ const derivedSlug = session.match(/^(?:\d{8}-\d{6}_)+(.+)$/)?.[1] ?? session;
614
+ const next = await sessionMetaStore.update(agent, session, (current) => {
615
+ const out = { ...current };
616
+ delete out.archived;
617
+ delete out.archivedAt;
618
+ delete out.archiveReason;
619
+ if (resetArchive) {
620
+ out.archived = false;
621
+ out.slug = derivedSlug;
622
+ out.restoredAt = new Date().toISOString();
623
+ }
624
+ return out;
601
625
  });
626
+ return { slug: session === 'main' ? 'main' : derivedSlug, isArchived: isSessionArchived(session, next) };
602
627
  }
@@ -247,6 +247,9 @@ export const exec: ToolDefinition<z.infer<typeof ExecInput>, ExecResult> = {
247
247
  'Remote targets have NO assumed binaries beyond POSIX core (sh, ls, cat, cp, mv, find, …). ' +
248
248
  'jq, python, node, rg etc. may be missing — probe first with `which <bin>` or `command -v` ' +
249
249
  'before relying on them, or pipe a JSON post-processor through stdin on the local side. ' +
250
+ 'To leave something running on a remote target from a sync call, detach all three streams: ' +
251
+ '`nohup cmd </dev/null >/tmp/cmd.log 2>&1 &` — a bare `cmd &` keeps the call open, and it returns ' +
252
+ 'a few seconds after your command exits with a note; or use background:true. ' +
250
253
  '\n\n' +
251
254
  'Output: a sync result carries about 60 000 chars of stdout+stderr. Longer output comes back as ' +
252
255
  'the first and last part of each stream with the cut marked in the text and truncated:true — ' +
@@ -6,6 +6,8 @@
6
6
  //
7
7
  // Worker is configured globally in `config.vision.{worker, pdfWorker}`.
8
8
  // PDF dispatches use `pdfWorker` if set, else fall back to `worker`.
9
+ // A worker with `pdf` gets the document itself; one with only `image`
10
+ // gets the pages as images, like file_read hands PDFs to such models.
9
11
  // Both workers must be on `openai-compatible` engine in v1 (same
10
12
  // constraint as Dream-Mode) — Anthropic-direct support is future work.
11
13
  //
@@ -20,7 +22,8 @@ import { workerChain, resolveAnyRef, type Config, type ResolvedModel } from '../
20
22
  import { logger } from '../../server/logger.ts';
21
23
  import { loadAttachment, type LoadedAttachment } from '../../multimodal/load.ts';
22
24
  import { samplingBody } from '../../engine/sampling.ts';
23
- import { toOpenAiContent } from '../../multimodal/blocks.ts';
25
+ import { pdfPagesToOpenAiContent, toOpenAiContent } from '../../multimodal/blocks.ts';
26
+ import { renderPdfToPngs } from '../../multimodal/pdf-render.ts';
24
27
  import { checkReadAllowed, realpathSafeAncestor, resolveLocalPath } from './policy.ts';
25
28
  import type { ToolDefinition } from '../types.ts';
26
29
 
@@ -92,8 +95,8 @@ export const analyzeFile: ToolDefinition<z.infer<typeof AnalyzeInput>, AnalyzeOu
92
95
  'A described image is a second-hand account: quote what the worker reported, do not ' +
93
96
  'claim to have seen the file yourself.\n\n' +
94
97
  'Worker model is configured globally in `config.vision.worker` (and optional ' +
95
- '`config.vision.pdfWorker` override for PDFs). Returns an error if the file type is ' +
96
- 'unsupported. Image cap 5 MB, PDF cap 32 MB.',
98
+ '`config.vision.pdfWorker` override for PDFs). A worker that cannot read PDFs but sees ' +
99
+ 'images gets the first 20 pages as images. Returns an error if the file type is unsupported.',
97
100
  inputSchema: AnalyzeInput,
98
101
  jsonSchema: {
99
102
  type: 'object',
@@ -151,6 +154,7 @@ export const analyzeFile: ToolDefinition<z.infer<typeof AnalyzeInput>, AnalyzeOu
151
154
  maxImageBytes: ctx.config.attachments.maxImageBytes,
152
155
  maxPdfBytes: ctx.config.attachments.maxPdfBytes,
153
156
  maxTextBytes: ctx.config.attachments.maxTextBytes,
157
+ maxImageEdge: ctx.config.attachments.maxImageEdge,
154
158
  });
155
159
  } catch (err) {
156
160
  const e = err as NodeJS.ErrnoException;
@@ -237,8 +241,22 @@ export async function describeMedia(args: {
237
241
  `openai-compatible engine.`,
238
242
  );
239
243
  }
240
- const requiredCap = att.mime.kind === 'pdf' ? 'pdf' : 'image';
244
+ const isPdf = att.mime.kind === 'pdf';
241
245
  const content = toOpenAiContent(att, args.prompt);
246
+ // Rendered once, on the first worker that needs the pages.
247
+ let pages: { content: ReturnType<typeof pdfPagesToOpenAiContent>; count: number } | { error: string } | null = null;
248
+ const pageContent = async () => {
249
+ if (pages) return pages;
250
+ try {
251
+ const r = await renderPdfToPngs(att.path, { maxPages: PDF_PAGE_LIMIT, scale: 1.5 });
252
+ if (r.pages.length === 0) throw new Error('no renderable pages');
253
+ const note = r.truncated ? `[The PDF has ${r.totalPages} pages; only the first ${r.pages.length} are included.]` : undefined;
254
+ pages = { content: pdfPagesToOpenAiContent(r.pages, args.prompt, note), count: r.pages.length };
255
+ } catch (err) {
256
+ pages = { error: `could not render the PDF to pages: ${(err as Error).message}` };
257
+ }
258
+ return pages;
259
+ };
242
260
  const start = Date.now();
243
261
  const deadline = start + visionConfig.totalBudgetMs;
244
262
 
@@ -254,8 +272,12 @@ export async function describeMedia(args: {
254
272
  skipped.push(`${ref}: not a known model in config.yaml`);
255
273
  continue;
256
274
  }
257
- if (!worker.model.capabilities.includes(requiredCap)) {
258
- skipped.push(`${ref}: lacks '${requiredCap}' capability`);
275
+ const caps = worker.model.capabilities;
276
+ // A PDF goes as the document to a worker that reads PDFs, as page
277
+ // images to one that only sees images.
278
+ const pdfAs: 'document' | 'pages' | null = !isPdf ? null : caps.includes('pdf') ? 'document' : caps.includes('image') ? 'pages' : null;
279
+ if (isPdf ? pdfAs === null : !caps.includes('image')) {
280
+ skipped.push(`${ref}: lacks '${isPdf ? 'pdf' : 'image'}' capability${isPdf ? " and 'image' for the pages" : ''}`);
259
281
  continue;
260
282
  }
261
283
  const cooling = failedUntil.get(ref);
@@ -271,6 +293,17 @@ export async function describeMedia(args: {
271
293
  continue;
272
294
  }
273
295
  const attemptMs = Math.min(visionConfig.timeoutMs, remaining);
296
+ let messageContent: unknown = content;
297
+ let pageCount: number | undefined;
298
+ if (pdfAs === 'pages') {
299
+ const p = await pageContent();
300
+ if ('error' in p) {
301
+ skipped.push(`${ref}: ${p.error}`);
302
+ continue;
303
+ }
304
+ messageContent = p.content;
305
+ pageCount = p.count;
306
+ }
274
307
 
275
308
  attempts += 1;
276
309
  const label = `${worker.providerName}/${worker.modelId}`;
@@ -284,6 +317,8 @@ export async function describeMedia(args: {
284
317
  attempt: attempts,
285
318
  chainLength: chain.length,
286
319
  attemptMs,
320
+ ...(pdfAs ? { pdfAs } : {}),
321
+ ...(pageCount !== undefined ? { pages: pageCount } : {}),
287
322
  });
288
323
  try {
289
324
  const completion = await buildClient(worker).chat.completions.create(
@@ -291,7 +326,7 @@ export async function describeMedia(args: {
291
326
  model: worker.modelId,
292
327
  messages: [
293
328
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
294
- { role: 'user', content: content as any },
329
+ { role: 'user', content: messageContent as any },
295
330
  ],
296
331
  // A caption is not a chat answer. The worker model's own cap
297
332
  // is a chat cap (16k and up is normal), which lets a reasoning
@@ -367,6 +402,10 @@ export async function describeMedia(args: {
367
402
  );
368
403
  }
369
404
 
405
+ /** Pages of a PDF sent as images to a worker without `pdf`, same cap
406
+ * as file_read. */
407
+ const PDF_PAGE_LIMIT = 20;
408
+
370
409
  /** An aborted attempt, however the client dressed it up. */
371
410
  function isTimeout(err: unknown): boolean {
372
411
  const e = err as { name?: string; message?: string };
@@ -297,28 +297,49 @@ function sftpMkdirP(sftp: SFTPWrapper, path: string): Promise<void> {
297
297
  });
298
298
  }
299
299
 
300
- export async function remoteRead(args: {
300
+ /** Largest remote file file_read downloads (images and PDFs are scaled
301
+ * or rendered afterwards; text is paged). */
302
+ export const REMOTE_READ_MAX_BYTES = 64 * 1024 * 1024;
303
+
304
+ /** Download a remote file for file_read, after the same read policy the
305
+ * text path applies. Refuses files over REMOTE_READ_MAX_BYTES before
306
+ * transferring anything. */
307
+ export async function remoteFetch(args: {
301
308
  resourceName: string;
302
309
  resource: SshResource;
303
310
  path: string;
304
- offset?: number;
305
- limit?: number;
306
- }): Promise<ReadResult> {
311
+ }): Promise<{ remotePath: string; buf: Buffer }> {
307
312
  const client = await getConnection(args.resourceName, args.resource);
308
313
  const remotePath = await resolveRemotePath(args.path, args.resourceName, args.resource);
309
- // Read-blacklist against the REMOTE home — same protection localRead
310
- // applies, which the remote path skipped entirely before the
311
- // Juni-Audit 2026-06 fix (see checkRemoteReadAllowed).
312
314
  const remoteHome = await getResourceHome(args.resourceName, args.resource);
313
315
  const policy = checkRemoteReadAllowed(remotePath, remoteHome);
314
316
  if (!policy.ok) throw new Error(policy.reason);
315
- const buf = await withSftp(client, (sftp) => sftpReadFile(sftp, remotePath));
316
- const formatted = formatRead(buf.toString('utf8'), args.offset, args.limit);
317
+ const buf = await withSftp(client, async (sftp) => {
318
+ const st = await new Promise<Stats>((resolve, reject) =>
319
+ sftp.stat(remotePath, (err, s) =>
320
+ err
321
+ ? reject(/no such file/i.test(String(err.message)) ? new Error(`file_read: no such file: ${args.resourceName}:${remotePath}`) : err)
322
+ : resolve(s),
323
+ ),
324
+ );
325
+ if (st.size > REMOTE_READ_MAX_BYTES) {
326
+ throw new Error(
327
+ `file_read: ${remotePath} on ${args.resourceName} is ${st.size} bytes, more than file_read downloads (${REMOTE_READ_MAX_BYTES}). ` +
328
+ 'Narrow it on the remote first (head, tail, grep, ffmpeg for a frame) and read the result.',
329
+ );
330
+ }
331
+ return sftpReadFile(sftp, remotePath);
332
+ });
333
+ return { remotePath, buf };
334
+ }
335
+
336
+ /** A downloaded remote text file, shaped like localRead's result. */
337
+ export function remoteTextResult(remotePath: string, buf: Buffer, offset?: number, limit?: number): ReadResult {
317
338
  return {
318
339
  path: remotePath,
319
340
  workspace_relative: null, // remote workspace not tracked the same way
320
341
  bytes: buf.length,
321
- ...formatted,
342
+ ...formatRead(buf.toString('utf8'), offset, limit),
322
343
  };
323
344
  }
324
345