@aragon-agent/cli 0.6.51 → 0.6.53

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 (48) hide show
  1. package/CHANGELOG.md +2800 -2723
  2. package/README.md +81 -6
  3. package/dist/agent/controller.d.ts +91 -5
  4. package/dist/agent/controller.js +252 -31
  5. package/dist/agent/image-history.d.ts +93 -0
  6. package/dist/agent/image-history.js +239 -0
  7. package/dist/agent/image-input-prompt.d.ts +17 -0
  8. package/dist/agent/image-input-prompt.js +56 -0
  9. package/dist/agent/image-support.d.ts +51 -0
  10. package/dist/agent/image-support.js +40 -0
  11. package/dist/agent/prompt-options.d.ts +18 -0
  12. package/dist/agent/system-prompt.d.ts +13 -0
  13. package/dist/agent/system-prompt.js +2 -0
  14. package/dist/agent/team-mode-wiring.d.ts +108 -0
  15. package/dist/agent/team-mode-wiring.js +221 -0
  16. package/dist/app/App.js +55 -14
  17. package/dist/app/use-team-mode.d.ts +53 -0
  18. package/dist/app/use-team-mode.js +107 -0
  19. package/dist/commands/catalog.js +1 -1
  20. package/dist/commands/team-command.d.ts +6 -4
  21. package/dist/commands/team-command.js +67 -27
  22. package/dist/compaction/archive.js +6 -1
  23. package/dist/compaction/compactor.js +5 -0
  24. package/dist/compaction/memory-input.d.ts +21 -0
  25. package/dist/compaction/memory-input.js +66 -3
  26. package/dist/governance/engine/engine.d.ts +8 -0
  27. package/dist/governance/engine/engine.js +11 -1
  28. package/dist/governance/store/atomic.d.ts +10 -0
  29. package/dist/governance/store/atomic.js +16 -8
  30. package/dist/governance/store/run-lock.d.ts +4 -0
  31. package/dist/governance/store/run-lock.js +4 -2
  32. package/dist/host/interaction.d.ts +6 -1
  33. package/dist/host/interaction.js +47 -8
  34. package/dist/session/persist.js +24 -2
  35. package/dist/session/validate-session.js +2 -2
  36. package/dist/team/forced-mode.d.ts +6 -2
  37. package/dist/team/forced-mode.js +11 -1
  38. package/dist/team/runtime.d.ts +6 -0
  39. package/dist/team/runtime.js +4 -0
  40. package/dist/team/subagent.d.ts +23 -2
  41. package/dist/team/subagent.js +44 -2
  42. package/dist/tools/fs-tools.d.ts +22 -0
  43. package/dist/tools/fs-tools.js +26 -3
  44. package/dist/tools/image-read.d.ts +69 -0
  45. package/dist/tools/image-read.js +183 -0
  46. package/dist/tools/index.d.ts +12 -0
  47. package/dist/tools/index.js +2 -0
  48. package/package.json +3 -3
@@ -10,9 +10,11 @@ import { dirname, isAbsolute, join, resolve } from 'node:path';
10
10
  import { getSessionsDir } from '../config/store.js';
11
11
  import { stripEphemeralRuns } from '../team/settled.js';
12
12
  import { sanitizeInvocationCard } from '@aragon-agent/tui/model/agent/invocation-card';
13
+ import { sanitizeAttachmentMetas } from '@aragon-agent/tui/model/agent/attachment-meta';
13
14
  import { validateSession } from './validate-session.js';
14
15
  import { validateCompactionIdentity, verifyCompactionIdentity, } from '../compaction/memory-identity.js';
15
16
  import { getLogger } from '../logging/logger.js';
17
+ import { stripToolImagePixels } from '../agent/image-history.js';
16
18
  const SESSION_VERSION = 1;
17
19
  /** Resolve a `/save` target: absolute/relative path, or a name in the data dir. */
18
20
  export function resolveSessionPath(nameOrPath, cwd) {
@@ -121,7 +123,11 @@ export function saveSession(filePath, data) {
121
123
  version: SESSION_VERSION,
122
124
  savedAt: Date.now(),
123
125
  model: data.model,
124
- messages: data.messages,
126
+ // agent-image-reading D-11: a tool picture is re-fetchable by re-running the tool, so the
127
+ // file keeps its label and a note, never the pixels (they would be re-written at every
128
+ // checkpoint, and a screenshot can hold secrets). User pictures are unchanged. This is
129
+ // the one place that sees `/save`, the checkpoint and the exit flush alike.
130
+ messages: [...stripToolImagePixels(data.messages)],
125
131
  ...(data.compactionIdentity ? { compactionIdentity: data.compactionIdentity } : {}),
126
132
  // THE EPHEMERAL-RUN GATE IS THE THIRD STRIP IN THIS CHAIN (tui-subagent-panel
127
133
  // §4.5.4 / RV-P0-1), and it is the only one that protects EVERY write path:
@@ -157,7 +163,7 @@ export function saveSession(filePath, data) {
157
163
  * never legitimately sees a stale-active entry — only the file does.
158
164
  */
159
165
  export function normalizeLoadedEntries(entries) {
160
- return entries.map((entry) => {
166
+ return entries.map(dropInvalidAttachments).map((entry) => {
161
167
  // A runtime-only wait view that reached disk anyway (an older or hand-edited
162
168
  // file) describes a wait that died with the session: drop it (I-9).
163
169
  if (entry.kind === 'tool' && (entry.wait !== undefined || entry.waitSeq !== undefined)) {
@@ -266,6 +272,22 @@ export function normalizeLoadedEntries(entries) {
266
272
  return entry;
267
273
  });
268
274
  }
275
+ /**
276
+ * desktop-attachments-and-tool-voice RV-11: `attachments` is declared but not validated
277
+ * by `validate-session` (one bad thumbnail must not fail the whole file), so the repair
278
+ * happens here, item by item. A corrupt item is dropped with a warning; the entry and the
279
+ * session survive.
280
+ */
281
+ function dropInvalidAttachments(entry) {
282
+ if ((entry.kind !== 'user' && entry.kind !== 'queued') || !('attachments' in entry))
283
+ return entry;
284
+ const { attachments: stored, ...plain } = entry;
285
+ const { metas, dropped } = sanitizeAttachmentMetas(stored);
286
+ if (dropped > 0) {
287
+ getLogger().warn('agent', 'dropped_invalid_attachment_records', { entryId: entry.id, dropped });
288
+ }
289
+ return metas ? { ...plain, attachments: metas } : plain;
290
+ }
269
291
  export function loadSession(filePath) {
270
292
  const raw = readFileSync(filePath, 'utf-8');
271
293
  const parsed = validateSession(JSON.parse(raw));
@@ -147,14 +147,14 @@ const subagent = shape({
147
147
  const ENTRY_FIELDS = {
148
148
  // `invocation` is declared for self-description only: `shape()` ignores undeclared
149
149
  // fields, and `normalizeLoadedEntries` repairs or drops a bad card (tui-invocation-cards).
150
- user: { text: string, invocation: optional(() => { }) },
150
+ user: { text: string, invocation: optional(() => { }), attachments: optional(() => { }) },
151
151
  // A GOVERNANCE CARD IS HISTORY, so it is validated LENIENTLY (governance-mode 10.4):
152
152
  // unknown fields are ignored (`shape` only reads the declared ones) and `card` is not
153
153
  // shape-checked here at all - `sanitizeGovernanceEntries` below repairs a card it can
154
154
  // and degrades one it cannot to a one-line notice, so a corrupt footnote never costs
155
155
  // the session. `at` is advisory.
156
156
  governance: { at: optional(number), card: () => { } },
157
- queued: { text: string, queueId: optional(nonempty), invocation: optional(() => { }) },
157
+ queued: { text: string, queueId: optional(nonempty), invocation: optional(() => { }), attachments: optional(() => { }) },
158
158
  notice: { text: string, level: enumeration('info', 'warn', 'error') },
159
159
  assistant: {
160
160
  text: string, thinking: optional(string), thinkingOpen: boolean, streaming: boolean,
@@ -16,7 +16,8 @@
16
16
  *
17
17
  * 1. CONTROL WORDS ARE WHOLE-ARGUMENT ONLY. `off the record` is a brief whose
18
18
  * first word happens to be `off`; treating it as "turn off, then take notes"
19
- * would delete a legitimate brief from the grammar.
19
+ * would delete a legitimate brief from the grammar. The one extension is
20
+ * `on <n>` (a count): the word plus a single positive integer.
20
21
  * 2. THE QUOTE ESCAPE HATCH IS CHECKED BEFORE THE CONTROL WORDS. `/team "off"`
21
22
  * asks for a fan-out on the brief `off`. Without this rule the three control
22
23
  * words would be permanently unavailable as briefs, and a user working on a
@@ -46,8 +47,11 @@ export type TeamIntent = {
46
47
  kind: 'status';
47
48
  } | {
48
49
  kind: 'off';
49
- } | {
50
+ }
51
+ /** `count` only for `/team on <n>` (team-mode-toggle-keys D-12); absent = keep the current one. */
52
+ | {
50
53
  kind: 'on';
54
+ count?: number;
51
55
  } | {
52
56
  kind: 'brief';
53
57
  args: SubagentCommandArgs;
@@ -16,7 +16,8 @@
16
16
  *
17
17
  * 1. CONTROL WORDS ARE WHOLE-ARGUMENT ONLY. `off the record` is a brief whose
18
18
  * first word happens to be `off`; treating it as "turn off, then take notes"
19
- * would delete a legitimate brief from the grammar.
19
+ * would delete a legitimate brief from the grammar. The one extension is
20
+ * `on <n>` (a count): the word plus a single positive integer.
20
21
  * 2. THE QUOTE ESCAPE HATCH IS CHECKED BEFORE THE CONTROL WORDS. `/team "off"`
21
22
  * asks for a fan-out on the brief `off`. Without this rule the three control
22
23
  * words would be permanently unavailable as briefs, and a user working on a
@@ -74,6 +75,15 @@ export function readTeamIntent(raw) {
74
75
  return { kind: 'error', error: parsed.error, token: parsed.token };
75
76
  return { kind: 'brief', args: parsed.args, quoted: true };
76
77
  }
78
+ // RULE 1b (team-mode-toggle-keys D-12): `on <n>` - a control word plus ONE positive integer,
79
+ // and nothing else. It is as narrow as rule 1 for the same reason: `on the record` and
80
+ // `on 6 7` are briefs, and so is `on 0` (a count of zero is not a count). Checked after the
81
+ // quote escape so `/team "on 6"` still asks for a fan-out on the brief `on 6`. The number is
82
+ // capped before it leaves this function: a 400-digit argument must clamp to the ceiling, not
83
+ // overflow to Infinity and clamp to one.
84
+ const onCount = /^on\s+([1-9][0-9]*)$/i.exec(trimmed);
85
+ if (onCount)
86
+ return { kind: 'on', count: Math.min(Number(onCount[1]), 1_000_000) };
77
87
  // RULE 1: whole-argument equality, compared case-insensitively.
78
88
  const word = trimmed.toLowerCase();
79
89
  if (CONTROL_WORDS.has(word))
@@ -106,6 +106,12 @@ export interface TeamRuntimeDeps {
106
106
  narrowToolsFor?: SubagentDeps['narrowToolsFor'];
107
107
  governanceRoleBlockFor?: SubagentDeps['governanceRoleBlockFor'];
108
108
  extraPolicyExempt?: SubagentDeps['extraPolicyExempt'];
109
+ /**
110
+ * Whether a model can read pictures, passed straight through to `SubagentDeps`
111
+ * (agent-image-reading D-15). ABSENT when the feature is off, which leaves every child built
112
+ * as before.
113
+ */
114
+ imageSupportFor?: SubagentDeps['imageSupportFor'];
109
115
  }
110
116
  export declare class TeamRuntime {
111
117
  private readonly deps;
@@ -527,6 +527,10 @@ export class TeamRuntime {
527
527
  ? { governanceRoleBlockFor: this.deps.governanceRoleBlockFor }
528
528
  : {}),
529
529
  ...(this.deps.extraPolicyExempt ? { extraPolicyExempt: this.deps.extraPolicyExempt } : {}),
530
+ // Site two of three for the image hook (the controller and `TeamRuntimeDeps` are the
531
+ // others): declared above and not forwarded here, it type-checks and every child keeps
532
+ // the pre-feature `read_file`, with no error anywhere.
533
+ ...(this.deps.imageSupportFor ? { imageSupportFor: this.deps.imageSupportFor } : {}),
530
534
  // Same conditional-spread rule: a dispatch without a supervisor builds
531
535
  // the exact pre-feature `SubagentDeps`, and the child's idle watchdog
532
536
  // keeps its un-lengthened ceiling (team-overseer §3.6).
@@ -11,9 +11,10 @@
11
11
  * omission has a reason that is a correctness boundary rather than caution.
12
12
  */
13
13
  import type { ModelRole } from '@aragon-agent/tui/model/config/model-profiles';
14
- import { type AgentConfig, type AgentEvent, type AgentTool, type Message, type ProviderRegistry, type SkillRegistry, type TokenUsage, type ToolPolicyDecision, type ToolPolicyVerdict } from '@aragon-agent/core';
14
+ import { type AgentConfig, type AgentEvent, type AgentTool, type Message, type ModelRef, type ProviderRegistry, type SkillRegistry, type TokenUsage, type ToolPolicyDecision, type ToolPolicyVerdict } from '@aragon-agent/core';
15
15
  import type { AgentMode } from '@aragon-agent/tui/model/agent/agent-mode';
16
16
  import type { ChildContextManagerProvider } from '../compaction/child.js';
17
+ import type { ImageSupport } from '../agent/image-support.js';
17
18
  import type { ToolGate } from '../tools/tool-gate.js';
18
19
  import type { CliConfig } from '@aragon-agent/tui/model/config/schema';
19
20
  import type { ToolPermission } from '../exec/permission.js';
@@ -161,6 +162,20 @@ export interface SubagentDeps {
161
162
  narrowToolsFor?: (spec: SubagentSpec, tools: AgentTool[]) => AgentTool[];
162
163
  governanceRoleBlockFor?: (spec: SubagentSpec) => string;
163
164
  extraPolicyExempt?: ReadonlySet<string>;
165
+ /**
166
+ * Whether a given model can read pictures (agent-image-reading D-15). A child may run a
167
+ * DIFFERENT model from the lead (`team.model: fast | profile`), and a fast tier is often
168
+ * text-only, so the lead's answer cannot stand in for the child's: this is asked about the
169
+ * child's own resolved model, for its `read_file`, its `<image_input>` block and its request
170
+ * projection alike.
171
+ *
172
+ * ABSENT unless the feature is on (the controller omits it under `ARAGON_TOOL_IMAGES=0`),
173
+ * and then a child is built exactly as before: the pre-feature `read_file`, no block, no
174
+ * projection. Three sites forward it, like every dep above: `TeamRuntimeDeps`, the
175
+ * `SubagentDeps` literal in `runtime.ts`, and the controller; declaring it in one and
176
+ * forgetting another type-checks and forwards nothing.
177
+ */
178
+ imageSupportFor?: (ref: ModelRef) => ImageSupport;
164
179
  }
165
180
  export interface SubagentHooks {
166
181
  /** Coalesced at the source (§5.2); phase transitions always pass. */
@@ -220,7 +235,13 @@ export interface SubagentHandle {
220
235
  * call without constructing an `Agent` or reaching a network — the tool set IS
221
236
  * the security boundary here, so it has to be directly checkable.
222
237
  */
223
- export declare function buildSubagentTools(spec: SubagentSpec, deps: SubagentDeps, getAgent: () => WatchdogPausable | null): AgentTool[];
238
+ export declare function buildSubagentTools(spec: SubagentSpec, deps: SubagentDeps, getAgent: () => WatchdogPausable | null,
239
+ /**
240
+ * The child's resolved model, read lazily because the tools are built BEFORE the model is
241
+ * resolved (the same holder shape as `getAgent`). OPTIONAL: callers that predate pictures
242
+ * pass three arguments and get the tools they always got.
243
+ */
244
+ getModel?: () => ModelRef | null): AgentTool[];
224
245
  /**
225
246
  * Construct a child and wire its instrumentation.
226
247
  *
@@ -13,6 +13,8 @@
13
13
  import { Agent, createSkillFindTool, } from '@aragon-agent/core';
14
14
  import { formatStreamError } from '@aragon-agent/tui/model/agent/reducer';
15
15
  import { buildSystemPrompt } from '../agent/system-prompt.js';
16
+ import { buildImageInputBlock } from '../agent/image-input-prompt.js';
17
+ import { makeImageProjection } from '../agent/image-history.js';
16
18
  import { buildFastBlock } from '../fast/prompt.js';
17
19
  import { createBuiltinTools, gatedToolTimeouts, } from '../tools/index.js';
18
20
  import { ledgerPathKey, normalizeLedgerPath } from './report.js';
@@ -64,7 +66,13 @@ function assistantText(message) {
64
66
  * call without constructing an `Agent` or reaching a network — the tool set IS
65
67
  * the security boundary here, so it has to be directly checkable.
66
68
  */
67
- export function buildSubagentTools(spec, deps, getAgent) {
69
+ export function buildSubagentTools(spec, deps, getAgent,
70
+ /**
71
+ * The child's resolved model, read lazily because the tools are built BEFORE the model is
72
+ * resolved (the same holder shape as `getAgent`). OPTIONAL: callers that predate pictures
73
+ * pass three arguments and get the tools they always got.
74
+ */
75
+ getModel) {
68
76
  // `team_wait`'s ceiling is the STRUCTURAL clamp when the child itself has no
69
77
  // wall clock (`subagentTimeoutMs: 0`): a peer wait must stay bounded even when
70
78
  // the child's run is not, or one forgotten wait would hold a slot forever.
@@ -79,9 +87,25 @@ export function buildSubagentTools(spec, deps, getAgent) {
79
87
  }),
80
88
  ];
81
89
  const extras = deps.extraToolsFor?.(spec) ?? [];
90
+ const imageSupportFor = deps.imageSupportFor;
82
91
  const built = createBuiltinTools({
83
92
  getCwd: deps.getCwd,
84
93
  confirmTools: deps.confirmTools,
94
+ // Only when BOTH halves exist; either missing and the child's `read_file` is the old one.
95
+ ...(imageSupportFor && getModel
96
+ ? {
97
+ images: {
98
+ support: () => {
99
+ const model = getModel();
100
+ return model ? imageSupportFor(model) : 'unknown';
101
+ },
102
+ modelLabel: () => {
103
+ const model = getModel();
104
+ return model ? `${model.providerId}/${model.modelId}` : 'the subagent model';
105
+ },
106
+ },
107
+ }
108
+ : {}),
85
109
  // THE CHILD ASKS THE CALLER TOO (section 2.3.7). Without this the approval
86
110
  // gate would hold for the lead and be bypassed by one `task` call - the hole
87
111
  // the `--deny-tool` pass-through above records, one feature later and with a
@@ -206,7 +230,9 @@ export function createSubagent(spec, deps, hooks) {
206
230
  // silently drop the watchdog pause (see `TeamWaitDeps.getAgent`).
207
231
  let agentRef = null;
208
232
  const getAgent = () => agentRef;
209
- const tools = buildSubagentTools(spec, deps, getAgent);
233
+ // The same lazy holder for the model: the tools below are built before it is resolved.
234
+ let modelRef = null;
235
+ const tools = buildSubagentTools(spec, deps, getAgent, () => modelRef);
210
236
  // WHICH MODEL A CHILD RUNS IS A USER SETTING, RESOLVED FROM THE
211
237
  // DISPATCH-TIME CONFIG through the one authority (subagent-model §3.4).
212
238
  // `team.model: 'main'` - the default - is the historical main-agent parity
@@ -223,6 +249,7 @@ export function createSubagent(spec, deps, hooks) {
223
249
  // number rather than to an HTTP 400.
224
250
  const resolution = resolveSubagentModel(deps.config, (id, role) => Boolean(deps.getApiKey(id, role)));
225
251
  const model = resolution.ref;
252
+ modelRef = model;
226
253
  // THE CHILD'S OWN KEY CLOSURE, PROFILE-AWARE (§3.3 / I-4). A bound profile's
227
254
  // dedicated key is visible ONLY inside this closure - never in env, config
228
255
  // `apiKeys` or a log line - while every other provider resolves through the
@@ -263,6 +290,15 @@ export function createSubagent(spec, deps, hooks) {
263
290
  peers: deps.bus.peersOf(spec.label),
264
291
  }),
265
292
  ...(fastBlock ? { fastBlock } : {}),
293
+ // The child's OWN model decides what it is told about pictures (agent-image-reading D-15).
294
+ ...(deps.imageSupportFor
295
+ ? {
296
+ imageInputBlock: buildImageInputBlock({
297
+ support: deps.imageSupportFor(model),
298
+ model: `${model.providerId}/${model.modelId}`,
299
+ }),
300
+ }
301
+ : {}),
266
302
  // The governed role block (governance-mode 6.1), after the subagent block. Spread
267
303
  // only when this child is a governed one, so every other child's prompt is unchanged.
268
304
  ...(spec.governance && deps.governanceRoleBlockFor
@@ -324,6 +360,12 @@ export function createSubagent(spec, deps, hooks) {
324
360
  // tests a field that is genuinely `undefined` rather than a property holding
325
361
  // one - the identical argument `AgentController` makes for the lead (AC-H10).
326
362
  ...(contextManager ? { contextManager } : {}),
363
+ // Same hook the lead has (D-9, D-15): a child with a text-only model never has pixels in
364
+ // its request, and a child with a vision model has its old tool pictures windowed. Spread
365
+ // only with the feature on, so the child's options bag is otherwise unchanged.
366
+ ...(deps.imageSupportFor
367
+ ? { projectMessages: makeImageProjection(() => deps.imageSupportFor(model)) }
368
+ : {}),
327
369
  });
328
370
  agentRef = agent;
329
371
  // PER-CHILD FAST REVIEW (main-agent parity). GATED ON THE PROVIDER'S OWN
@@ -7,6 +7,7 @@
7
7
  * tools do not re-implement them.
8
8
  */
9
9
  import { type AgentTool } from '@aragon-agent/core';
10
+ import { type ImageReadPort } from './image-read.js';
10
11
  import { type FilePatch } from '@aragon-agent/tui/model/tools/patch';
11
12
  import type { ProcSupervisorPort } from '@aragon-agent/tui/model/proc/types';
12
13
  export interface ToolDeps {
@@ -52,7 +53,28 @@ export interface ToolDeps {
52
53
  * pre-feature description string (I-2).
53
54
  */
54
55
  procs?: ProcSupervisorPort;
56
+ /**
57
+ * What `read_file` needs to show a picture (agent-image-reading D-2): the current model's
58
+ * image support, read afresh on every call, and its name for wording.
59
+ *
60
+ * THE TWO-INTERFACE RULE ABOVE APPLIES VERBATIM, a fourth time: adding the field HERE
61
+ * alone type-checks and forwards nothing, so `read_file` keeps answering every picture
62
+ * with "binary" and NOTHING ANYWHERE ERRORS. It must be added here AND forwarded in
63
+ * `tools/index.ts` (`images.forwarding` test).
64
+ *
65
+ * OPTIONAL: omitting it leaves `read_file` byte-identical to the pre-feature build - the
66
+ * same description, the same binary error, and no extra `stat`.
67
+ */
68
+ images?: ImageReadPort;
55
69
  }
70
+ /** The description when no image port is wired: byte-for-byte what it always was. */
71
+ export declare const READ_FILE_TEXT_ONLY_DESCRIPTION: string;
72
+ /**
73
+ * The description with the image port. Its FIRST LINE is the only thing the system prompt's
74
+ * tool list shows the model, which is why the capability is stated there, conditionally (it
75
+ * is true for a model that can see images and a promise a text-only model must not receive).
76
+ */
77
+ export declare const READ_FILE_IMAGE_DESCRIPTION: string;
56
78
  export declare function makeReadFile(deps: ToolDeps): AgentTool;
57
79
  export declare function makeWriteFile(deps: ToolDeps): AgentTool;
58
80
  export declare function makeEditFile(deps: ToolDeps): AgentTool;
@@ -10,6 +10,7 @@ import { promises as fs } from 'node:fs';
10
10
  import { isAbsolute, join, resolve, dirname } from 'node:path';
11
11
  import { defineTool, errorResult, textResult, } from '@aragon-agent/core';
12
12
  import { renderUnifiedDiff } from './diff.js';
13
+ import { binaryMessage, tryReadImage } from './image-read.js';
13
14
  import { PATCH_LIMITS, buildPatch } from '@aragon-agent/tui/model/tools/patch';
14
15
  function resolvePath(cwd, p) {
15
16
  return isAbsolute(p) ? p : resolve(cwd, p);
@@ -22,12 +23,24 @@ function looksBinary(buf) {
22
23
  // ---------------------------------------------------------------------------
23
24
  // read_file
24
25
  // ---------------------------------------------------------------------------
26
+ /** The description when no image port is wired: byte-for-byte what it always was. */
27
+ export const READ_FILE_TEXT_ONLY_DESCRIPTION = 'Read a UTF-8 text file and return its contents as numbered lines. ' +
28
+ 'Optionally read a window with `offset` (1-based start line) and `limit` (line count).';
29
+ /**
30
+ * The description with the image port. Its FIRST LINE is the only thing the system prompt's
31
+ * tool list shows the model, which is why the capability is stated there, conditionally (it
32
+ * is true for a model that can see images and a promise a text-only model must not receive).
33
+ */
34
+ export const READ_FILE_IMAGE_DESCRIPTION = [
35
+ 'Read a UTF-8 text file as numbered lines, or view an image file (PNG, JPEG, GIF, WebP) when the model can see images.',
36
+ 'For a text file, optionally read a window with `offset` (1-based start line) and `limit` (line count).',
37
+ 'For an image file the picture itself is returned so you can look at it; `offset` and `limit` do not apply. One image per call, at most 5 MB and 8000 px per side.',
38
+ ].join('\n');
25
39
  export function makeReadFile(deps) {
26
40
  return defineTool({
27
41
  name: 'read_file',
28
42
  label: 'Read File',
29
- description: 'Read a UTF-8 text file and return its contents as numbered lines. ' +
30
- 'Optionally read a window with `offset` (1-based start line) and `limit` (line count).',
43
+ description: deps.images ? READ_FILE_IMAGE_DESCRIPTION : READ_FILE_TEXT_ONLY_DESCRIPTION,
31
44
  parameters: {
32
45
  type: 'object',
33
46
  properties: {
@@ -41,9 +54,19 @@ export function makeReadFile(deps) {
41
54
  const params = rawParams;
42
55
  const target = resolvePath(deps.getCwd(), params.path);
43
56
  try {
57
+ if (deps.images) {
58
+ const picture = await tryReadImage({
59
+ target,
60
+ display: params.path,
61
+ port: deps.images,
62
+ windowIgnored: params.offset !== undefined || params.limit !== undefined,
63
+ });
64
+ if (picture)
65
+ return picture;
66
+ }
44
67
  const buf = await fs.readFile(target);
45
68
  if (looksBinary(buf)) {
46
- return errorResult(`File appears to be binary: ${params.path}`);
69
+ return errorResult(deps.images ? binaryMessage(buf, params.path) : `File appears to be binary: ${params.path}`);
47
70
  }
48
71
  const content = buf.toString('utf-8');
49
72
  const allLines = content.split('\n');
@@ -0,0 +1,69 @@
1
+ /**
2
+ * `read_file`'s picture branch (agent-image-reading §3.3).
3
+ *
4
+ * A model that can see images has always been able to receive one from a tool in the engine;
5
+ * `read_file` simply answered every image with "File appears to be binary". This module turns
6
+ * a PNG / JPEG / GIF / WebP path into `[label, image]` (plus an optional note), and turns every
7
+ * way that can go wrong into a message that tells the model what to do next.
8
+ *
9
+ * Order is semantics: the capability and the size are judged from `stat` and a 64-byte head,
10
+ * BEFORE the whole file is read, so a 2 GB file or a model that cannot see never costs the
11
+ * memory of reading it. Recognition is by magic bytes; the extension is only used to explain
12
+ * a file that looks like an image but is not one. Agent-facing text: English, ASCII.
13
+ */
14
+ import { type ToolResult } from '@aragon-agent/core';
15
+ import type { ImageMediaType } from '@aragon-agent/tui/model/agent/attachment-meta';
16
+ import { type ImageDimensions } from '@aragon-agent/tui/model/tools/image-bytes';
17
+ /** What `read_file` needs to know about the model, read afresh on every call. */
18
+ export interface ImageReadPort {
19
+ /** `unknown` means "try it": the provider's answer settles it (see the controller). */
20
+ support(): 'yes' | 'no' | 'unknown';
21
+ /** 'provider/model', used only for wording. */
22
+ modelLabel(): string;
23
+ }
24
+ export interface ReadImageInput {
25
+ /** Resolved absolute path. */
26
+ target: string;
27
+ /** The path as the model wrote it. */
28
+ display: string;
29
+ type: ImageMediaType;
30
+ /** Bytes on disk, from `stat`. */
31
+ size: number;
32
+ port: ImageReadPort;
33
+ /** `offset` / `limit` were passed for an image, where they mean nothing. */
34
+ windowIgnored: boolean;
35
+ }
36
+ /** `512 B`, `412 KB`, `3.2 MB`, `1.5 GB`. */
37
+ export declare function formatImageSize(bytes: number): string;
38
+ /**
39
+ * The text block in front of every picture: the anchor that survives when the pixels are later
40
+ * dropped, so the path is sanitised (a `]` or a newline would break `TOOL_IMAGE_LABEL_RE`).
41
+ */
42
+ export declare function toolImageLabel(i: {
43
+ display: string;
44
+ type: ImageMediaType;
45
+ dims: ImageDimensions | null;
46
+ bytes: number;
47
+ }): string;
48
+ /**
49
+ * Why a binary file cannot be shown as text: a recognised-but-unsupported format gets its name
50
+ * and a conversion command, a damaged image gets a plain diagnosis, anything else gets the
51
+ * message `read_file` always had. The caller wraps it in `errorResult`.
52
+ */
53
+ export declare function binaryMessage(buf: Uint8Array, display: string): string;
54
+ /**
55
+ * Show one picture. Judges capability and size before reading the file; strips EXIF / GPS /
56
+ * IPTC losslessly; measures the header. A failure the model can act on is an `errorResult`;
57
+ * an I/O error from the read itself propagates to `read_file`'s catch, which words it.
58
+ */
59
+ export declare function readImage(i: ReadImageInput): Promise<ToolResult>;
60
+ /**
61
+ * The picture result for `target`, or `null` when it is not a PNG / JPEG / GIF / WebP so
62
+ * `read_file` carries on exactly as before.
63
+ */
64
+ export declare function tryReadImage(i: {
65
+ target: string;
66
+ display: string;
67
+ port: ImageReadPort;
68
+ windowIgnored: boolean;
69
+ }): Promise<ToolResult | null>;
@@ -0,0 +1,183 @@
1
+ /**
2
+ * `read_file`'s picture branch (agent-image-reading §3.3).
3
+ *
4
+ * A model that can see images has always been able to receive one from a tool in the engine;
5
+ * `read_file` simply answered every image with "File appears to be binary". This module turns
6
+ * a PNG / JPEG / GIF / WebP path into `[label, image]` (plus an optional note), and turns every
7
+ * way that can go wrong into a message that tells the model what to do next.
8
+ *
9
+ * Order is semantics: the capability and the size are judged from `stat` and a 64-byte head,
10
+ * BEFORE the whole file is read, so a 2 GB file or a model that cannot see never costs the
11
+ * memory of reading it. Recognition is by magic bytes; the extension is only used to explain
12
+ * a file that looks like an image but is not one. Agent-facing text: English, ASCII.
13
+ */
14
+ import { promises as fs } from 'node:fs';
15
+ import { extname } from 'node:path';
16
+ import { errorResult, multiResult } from '@aragon-agent/core';
17
+ import { IMAGE_FILE_EXTENSIONS, IMAGE_READ_LIMITS, describeUnsupportedImage, readImageDimensions, sanitizeLabelText, sniffImageType, stripImageMetadata, } from '@aragon-agent/tui/model/tools/image-bytes';
18
+ import { getLogger } from '../logging/logger.js';
19
+ const TYPE_NAME = {
20
+ 'image/png': 'PNG',
21
+ 'image/jpeg': 'JPEG',
22
+ 'image/gif': 'GIF',
23
+ 'image/webp': 'WebP',
24
+ };
25
+ const LIMIT_MB = IMAGE_READ_LIMITS.maxBytes / (1024 * 1024);
26
+ const SHRINK_ADVICE = `Make a smaller copy (long edge about ${IMAGE_READ_LIMITS.advisoryEdgePx} px)`;
27
+ const MAGICK_RESIZE = `magick in.png -resize "${IMAGE_READ_LIMITS.advisoryEdgePx}x${IMAGE_READ_LIMITS.advisoryEdgePx}>" out.png`;
28
+ /** `512 B`, `412 KB`, `3.2 MB`, `1.5 GB`. */
29
+ export function formatImageSize(bytes) {
30
+ if (!Number.isFinite(bytes) || bytes < 0)
31
+ return '0 B';
32
+ if (bytes < 1024)
33
+ return `${bytes} B`;
34
+ if (bytes < 1024 * 1024)
35
+ return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;
36
+ if (bytes < 1024 * 1024 * 1024)
37
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
38
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
39
+ }
40
+ /**
41
+ * The text block in front of every picture: the anchor that survives when the pixels are later
42
+ * dropped, so the path is sanitised (a `]` or a newline would break `TOOL_IMAGE_LABEL_RE`).
43
+ */
44
+ export function toolImageLabel(i) {
45
+ const dims = i.dims ? ` ${i.dims.width}x${i.dims.height}` : '';
46
+ return `[read_file image: ${sanitizeLabelText(i.display)} - ${TYPE_NAME[i.type]}${dims}, ${formatImageSize(i.bytes)}]`;
47
+ }
48
+ // ---------------------------------------------------------------------------
49
+ // Messages (appendix A.2)
50
+ // ---------------------------------------------------------------------------
51
+ function noVisionMessage(i) {
52
+ return `Cannot show ${i.display} (${TYPE_NAME[i.type]}, ${formatImageSize(i.size)}): `
53
+ + `the current model (${i.port.modelLabel()}) cannot read images. `
54
+ + 'Do not call read_file on image files again with this model. '
55
+ + 'If the task depends on the picture, tell the user and ask them to switch to a model '
56
+ + 'that can see images; otherwise continue from the file name, metadata or OCR output.';
57
+ }
58
+ function tooLargeMessage(display, size) {
59
+ return `${display} is ${formatImageSize(size)}; read_file shows images up to ${LIMIT_MB} MB. `
60
+ + `${SHRINK_ADVICE} with a tool that is installed, then read the copy. `
61
+ + `ImageMagick: ${MAGICK_RESIZE}. `
62
+ + `macOS: sips -Z ${IMAGE_READ_LIMITS.advisoryEdgePx} in.png --out out.png. `
63
+ + `Python Pillow: Image.open(p).thumbnail((${IMAGE_READ_LIMITS.advisoryEdgePx}, ${IMAGE_READ_LIMITS.advisoryEdgePx})).`;
64
+ }
65
+ function tooManyPixelsMessage(display, dims) {
66
+ return `${display} is ${dims.width}x${dims.height} px; read_file shows images up to `
67
+ + `${IMAGE_READ_LIMITS.maxEdgePx} px per side. ${SHRINK_ADVICE} - for example ImageMagick: `
68
+ + `${MAGICK_RESIZE} - then read the copy.`;
69
+ }
70
+ /**
71
+ * Why a binary file cannot be shown as text: a recognised-but-unsupported format gets its name
72
+ * and a conversion command, a damaged image gets a plain diagnosis, anything else gets the
73
+ * message `read_file` always had. The caller wraps it in `errorResult`.
74
+ */
75
+ export function binaryMessage(buf, display) {
76
+ const kind = describeUnsupportedImage(buf);
77
+ if (kind) {
78
+ return `${display} is ${kind.label}; read_file can only show PNG, JPEG, GIF and WebP. ${kind.hint}`;
79
+ }
80
+ if (IMAGE_FILE_EXTENSIONS.has(extname(display).slice(1).toLowerCase())) {
81
+ return `${display} has an image extension but is not a valid PNG, JPEG, GIF or WebP file `
82
+ + '(damaged, truncated, or another format such as HEIC or BMP). Convert it to PNG or JPEG first.';
83
+ }
84
+ return `File appears to be binary: ${display}`;
85
+ }
86
+ // ---------------------------------------------------------------------------
87
+ // The five checks, each `ToolResult | null` (null = pass)
88
+ // ---------------------------------------------------------------------------
89
+ function checkSupport(i) {
90
+ return i.port.support() === 'no' ? errorResult(noVisionMessage(i)) : null;
91
+ }
92
+ function checkSize(i, size) {
93
+ return size > IMAGE_READ_LIMITS.maxBytes ? errorResult(tooLargeMessage(i.display, size)) : null;
94
+ }
95
+ function checkDimensions(i, dims) {
96
+ if (!dims)
97
+ return null; // unreadable header: omit the size, do not fail the read
98
+ return Math.max(dims.width, dims.height) > IMAGE_READ_LIMITS.maxEdgePx
99
+ ? errorResult(tooManyPixelsMessage(i.display, dims))
100
+ : null;
101
+ }
102
+ function buildNote(i, dims) {
103
+ const notes = [];
104
+ if (dims && Math.max(dims.width, dims.height) > IMAGE_READ_LIMITS.advisoryEdgePx) {
105
+ notes.push(`Note: the long edge is ${Math.max(dims.width, dims.height)} px; the provider may downscale it, so fine detail can be lost.`);
106
+ }
107
+ if (i.type === 'image/gif')
108
+ notes.push('Note: only the first frame of a GIF is visible.');
109
+ if (i.windowIgnored)
110
+ notes.push('Note: offset and limit were ignored because this is an image.');
111
+ return notes.join(' ');
112
+ }
113
+ function buildSuccess(i, bytes, dims) {
114
+ const data = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64');
115
+ const note = buildNote(i, dims);
116
+ return multiResult([
117
+ { type: 'text', text: toolImageLabel({ display: i.display, type: i.type, dims, bytes: i.size }) },
118
+ { type: 'image', mediaType: i.type, data },
119
+ ...(note ? [{ type: 'text', text: note }] : []),
120
+ ]);
121
+ }
122
+ /**
123
+ * Show one picture. Judges capability and size before reading the file; strips EXIF / GPS /
124
+ * IPTC losslessly; measures the header. A failure the model can act on is an `errorResult`;
125
+ * an I/O error from the read itself propagates to `read_file`'s catch, which words it.
126
+ */
127
+ export async function readImage(i) {
128
+ const early = checkSupport(i) ?? checkSize(i, i.size);
129
+ if (early)
130
+ return early;
131
+ const stripped = stripImageMetadata(await fs.readFile(i.target), i.type);
132
+ const dims = readImageDimensions(stripped, i.type);
133
+ const refused = checkSize(i, stripped.length) ?? checkDimensions(i, dims);
134
+ if (refused)
135
+ return refused;
136
+ getLogger().debug('tool', 'image_read', {
137
+ bytes: stripped.length,
138
+ width: dims?.width,
139
+ height: dims?.height,
140
+ support: i.port.support(),
141
+ });
142
+ return buildSuccess(i, stripped, dims);
143
+ }
144
+ // ---------------------------------------------------------------------------
145
+ // Entry point for read_file
146
+ // ---------------------------------------------------------------------------
147
+ /** `stat` + the first bytes, or `null` for anything that is not a readable regular file. */
148
+ async function readHead(target) {
149
+ try {
150
+ const stat = await fs.stat(target);
151
+ if (!stat.isFile())
152
+ return null;
153
+ const handle = await fs.open(target, 'r');
154
+ try {
155
+ const head = Buffer.alloc(Math.min(IMAGE_READ_LIMITS.headerBytes, stat.size));
156
+ const { bytesRead } = await handle.read(head, 0, head.length, 0);
157
+ return { bytes: head.subarray(0, bytesRead), size: stat.size };
158
+ }
159
+ finally {
160
+ await handle.close();
161
+ }
162
+ }
163
+ catch {
164
+ // Missing, unreadable, a directory: the text path below raises the same error it always did.
165
+ return null;
166
+ }
167
+ }
168
+ /**
169
+ * The picture result for `target`, or `null` when it is not a PNG / JPEG / GIF / WebP so
170
+ * `read_file` carries on exactly as before.
171
+ */
172
+ export async function tryReadImage(i) {
173
+ const head = await readHead(i.target);
174
+ if (!head)
175
+ return null;
176
+ const type = sniffImageType(head.bytes);
177
+ if (type)
178
+ return readImage({ ...i, type, size: head.size });
179
+ // A format we can name but not show (BMP, TIFF, ICO, HEIC, AVIF, PDF) is explained from its
180
+ // head alone: no need to read a large file, and a NUL-free PDF would otherwise be dumped
181
+ // as text.
182
+ return describeUnsupportedImage(head.bytes) ? errorResult(binaryMessage(head.bytes, i.display)) : null;
183
+ }