@aragon-agent/cli 0.6.50 → 0.6.52

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
@@ -5,7 +5,11 @@ import { randomUUID } from 'node:crypto';
5
5
  import { join } from 'node:path';
6
6
  import { verifyCompactionIdentity } from '../compaction/memory-identity.js';
7
7
  import { COMPACTION_LIMITS } from '@aragon-agent/tui/model/compaction/limits';
8
- import { Agent, initProviders, ModelRegistry, } from '@aragon-agent/core';
8
+ import { resolveImageSupport } from './image-support.js';
9
+ import { countAllImages, countHistoryImages, makeImageProjection, projectImagesForModel, } from './image-history.js';
10
+ import { buildImageInputBlock } from './image-input-prompt.js';
11
+ import { isImageCapabilityRefusal } from '@aragon-agent/tui/model/agent/image-refusal';
12
+ import { Agent, IMAGE_TOKEN_ESTIMATE, initProviders, ModelRegistry, } from '@aragon-agent/core';
9
13
  import { clampCompactionConfig, clampFastConfig, clampRetryConfig, clampTeamConfig, clampTodoConfig, isAdapterProvider, toRetryPolicy, } from '@aragon-agent/tui/model/config/schema';
10
14
  import { resolveModelProfileState } from '@aragon-agent/tui/model/config/model-profile-resolution';
11
15
  import { makeGetApiKey } from '../config/load.js';
@@ -24,6 +28,8 @@ import { buildTeamBlock } from '../team/prompt.js';
24
28
  // THE THIRD LAYER's prompt half (team-command-forced-dispatch §3.6): spliced
25
29
  // after `<team_mode>` and before the subagent block, only while armed.
26
30
  import { buildForcedTeamBlock } from '../team/forced-prompt.js';
31
+ import { DEFAULT_FORCED_COUNT } from '../team/forced-mode.js';
32
+ import { TeamModeWiring, effectiveForced } from './team-mode-wiring.js';
27
33
  import { buildFastBlock } from '../fast/prompt.js';
28
34
  import { ProcSupervisor } from '../proc/supervisor.js';
29
35
  import { buildBackgroundJobsBlock, buildBackgroundServicesBlock } from '../proc/prompt.js';
@@ -203,15 +209,20 @@ export class AgentController {
203
209
  */
204
210
  governance;
205
211
  // -----------------------------------------------------------------------
206
- // Forced team mode (team-command-forced-dispatch §3.5 / D-4).
212
+ // Forced team mode (team-command-forced-dispatch §3.5 / D-4), now the team mode SWITCH
213
+ // (team-mode-toggle-keys).
207
214
  //
208
- // SESSION STATE, NEVER PERSISTED: `null` means "not armed". `/team <brief>`
209
- // and `/team on` set it, `/team off` clears it, and the process exiting is the
210
- // third way it ends. It is not a `config.json` key on purpose — a persisted
211
- // "always force a fan-out" would be inherited by `aragon exec` and by every
215
+ // SESSION STATE, NEVER PERSISTED: not armed is the constructor's value. `/team <brief>`,
216
+ // `/team on`, Ctrl+T and the desktop chip arm it, `/team off` / Ctrl+T clear it, and the
217
+ // process exiting is the third way it ends. It is not a `config.json` key on purpose — a
218
+ // persisted "always force a fan-out" would be inherited by `aragon exec` and by every
212
219
  // launch after one experiment, at four children a turn (D-4 / AC-24).
220
+ //
221
+ // The state, the pending change and the subscription live in `TeamModeWiring`; this class
222
+ // forwards. Built in the constructor, after `teamRegistered` and the governance wiring it
223
+ // reads.
213
224
  // -----------------------------------------------------------------------
214
- forcedTeam = null;
225
+ teamMode;
215
226
  // -----------------------------------------------------------------------
216
227
  // Todo planning (todo-plan-execution §3.6a) — THE SAME TWO FLAGS, FOR THE
217
228
  // SAME REASON.
@@ -372,6 +383,21 @@ export class AgentController {
372
383
  abortRequested = false;
373
384
  /** Only exact acceptance receipts release user messages from reviewer protection. */
374
385
  pendingUserSteering = new Map();
386
+ imageOverride;
387
+ /**
388
+ * The single switch for agent-image-reading (D-17). `ARAGON_TOOL_IMAGES=0` turns off EVERY
389
+ * producer and helper together: the `read_file` image port, the `<image_input>` block, the
390
+ * tool-picture window, the refusal learning, and the subagents' `imageSupportFor` (a second
391
+ * producer: a half-off switch would still hand pictures to a child). Read once, so the
392
+ * answer cannot change between the tool array and the prompt that describes it.
393
+ */
394
+ toolImagesEnabled = process.env.ARAGON_TOOL_IMAGES !== '0';
395
+ /**
396
+ * What the CURRENT prompt's `<image_input>` block was written for: the model and the support
397
+ * answer together (`provider/model:support`). The block names the model, so a switch between
398
+ * two vision models changes its text even though the answer stays `yes`.
399
+ */
400
+ promptImageKey;
375
401
  /** Session changes must not make a delayed receipt match a new message. */
376
402
  steeringPrefix = randomUUID();
377
403
  steeringSequence = 0;
@@ -487,6 +513,17 @@ export class AgentController {
487
513
  this.governance.setGovernOn(true);
488
514
  this.effectiveMode = initialPosture === 'plan_govern' ? 'plan' : 'build';
489
515
  }
516
+ // AFTER the governance wiring and the launch posture: `isBlocked` reads both. The
517
+ // baseline view is taken at the end of construction (`prime`), not here.
518
+ this.teamMode = new TeamModeWiring({
519
+ getTeamConfig: () => this.config.team,
520
+ isRegistered: () => this.teamRegistered,
521
+ isBlocked: () => this.teamBlocksDropped(),
522
+ isBusy: () => this.isRunning() || this.isCompactionBusy(),
523
+ enableCapability: () => this.setTeamEnabled(true),
524
+ rebuildPrompt: () => this.rebuildSystemPrompt(),
525
+ defaultCount: DEFAULT_FORCED_COUNT,
526
+ });
490
527
  this.teamRuntime = this.teamRegistered
491
528
  ? new TeamRuntime({
492
529
  getConfig: () => this.config,
@@ -580,6 +617,19 @@ export class AgentController {
580
617
  extraPolicyExempt: this.governance.childPolicyExempt(),
581
618
  }
582
619
  : {}),
620
+ // THE THIRD HALF OF THE SWITCH (agent-image-reading RV-P1-3): present ONLY with the
621
+ // feature on. A child reads pictures with the child's OWN model, so the lead's
622
+ // answer is no use to it. Providing this unconditionally would let
623
+ // `ARAGON_TOOL_IMAGES=0` stop the lead and leave every dispatched child reading.
624
+ ...(this.toolImagesEnabled
625
+ ? {
626
+ imageSupportFor: (ref) => this.resolveImageSupportFor({
627
+ provider: ref.providerId,
628
+ model: ref.modelId,
629
+ ...(ref.baseUrl !== undefined ? { baseUrl: ref.baseUrl } : {}),
630
+ }).support,
631
+ }
632
+ : {}),
583
633
  })
584
634
  : null;
585
635
  // ABOVE `createBuiltinTools`, and the ordering is load-bearing for the
@@ -637,6 +687,17 @@ export class AgentController {
637
687
  this.jobRelay.attach((listener) => this.procs.subscribe(listener));
638
688
  this.tools = createBuiltinTools({
639
689
  getCwd: () => this.cwd,
690
+ // `read_file` can show a picture; the answer is read from the controller on every call
691
+ // because the model can change mid-session (agent-image-reading D-2). No key at all with
692
+ // the feature off, so the tool is the pre-feature one.
693
+ ...(this.toolImagesEnabled
694
+ ? {
695
+ images: {
696
+ support: () => this.getImageSupport().support,
697
+ modelLabel: () => `${this.config.provider}/${this.config.model}`,
698
+ },
699
+ }
700
+ : {}),
640
701
  // OWNED HERE, NOT IN `cli.tsx` (D-18): `createBuiltinTools` is called from
641
702
  // this constructor and from `team/subagent.ts`, never from `cli.tsx`, so
642
703
  // this is the one place a recorder can be bound to the toolset that will
@@ -906,6 +967,8 @@ export class AgentController {
906
967
  meter: this.contextMeter,
907
968
  })
908
969
  : null;
970
+ // The block in the prompt composed just below is written for exactly this answer.
971
+ this.promptImageKey = this.currentImageKey();
909
972
  this.agent = new Agent({
910
973
  systemPrompt: this.composeSystemPrompt(),
911
974
  model,
@@ -923,6 +986,13 @@ export class AgentController {
923
986
  // provable by construction rather than by inspection. `createBuiltinTools`
924
987
  // above spreads `permission` for the identical reason (P1-2 / AC-28).
925
988
  ...(this.compaction ? { contextManager: this.compaction.manager() } : {}),
989
+ // D-20: when the CURRENT model cannot read images, history images are shown to the
990
+ // provider as their label text. Resolved per request (the model can change), and it
991
+ // returns the same array when there is nothing to change.
992
+ // agent-image-reading D-9: with the feature on it also windows old TOOL pictures.
993
+ projectMessages: this.toolImagesEnabled
994
+ ? makeImageProjection(() => this.getImageSupport().support)
995
+ : (messages) => this.getImageSupport().support === 'no' ? projectImagesForModel(messages) : messages,
926
996
  timeouts: {
927
997
  // Timeout invariant (R1): idle ≥ tool so long tool runs are not killed.
928
998
  toolTimeout: config.toolTimeoutMs,
@@ -1033,6 +1103,9 @@ export class AgentController {
1033
1103
  this.agent.subscribe((event) => {
1034
1104
  if (event.type === 'agent_start')
1035
1105
  this.abortRequested = false;
1106
+ if (event.type === 'message_update' && event.streamEvent.type === 'error') {
1107
+ this.learnImageRefusal(event.streamEvent.error);
1108
+ }
1036
1109
  if (event.type === 'steering_accepted') {
1037
1110
  for (const id of event.ids)
1038
1111
  this.pendingUserSteering.delete(id);
@@ -1078,6 +1151,8 @@ export class AgentController {
1078
1151
  this.maybeReportSkillTriage();
1079
1152
  }
1080
1153
  });
1154
+ // The switch's baseline view, taken once everything it reads exists (team-mode-toggle-keys).
1155
+ this.teamMode.prime();
1081
1156
  if (this.fast) {
1082
1157
  this.rebuildSystemPrompt();
1083
1158
  }
@@ -1142,7 +1217,12 @@ export class AgentController {
1142
1217
  const posture = this.getPosture();
1143
1218
  const governBlock = this.governance.orchestratorBlock(posture, config);
1144
1219
  const governAddendum = this.governance.planAddendum(posture, config);
1145
- const dropTeamBlocks = governBlock !== '' && this.effectiveMode === 'build';
1220
+ const dropTeamBlocks = this.teamBlocksDropped(config, governBlock);
1221
+ // The armed state as THIS config would honour it, never `this.config`: a settings save
1222
+ // pre-builds the prompt before it is applied, and a block written for the outgoing
1223
+ // configuration would tell the model to dispatch with a capability the user just turned
1224
+ // off (team-mode-toggle-keys RV-P0-1; same discipline as `imageInputBlock` below).
1225
+ const forced = effectiveForced(this.teamMode.rawForced(), config.team, this.teamRegistered);
1146
1226
  return buildSystemPrompt({
1147
1227
  cwd: this.cwd,
1148
1228
  tools: this.tools,
@@ -1160,7 +1240,7 @@ export class AgentController {
1160
1240
  // Advertising in either case would describe a capability the model does not
1161
1241
  // have. Read through the field rather than `this.isTeamEnabled()` so the
1162
1242
  // sentence and the code agree, as the two flags always have here (P1-4).
1163
- teamBlock: this.teamRegistered && this.config.team.enabled && !dropTeamBlocks
1243
+ teamBlock: this.teamRegistered && config.team.enabled && !dropTeamBlocks
1164
1244
  ? buildTeamBlock({
1165
1245
  maxSubagents: config.team.maxSubagents,
1166
1246
  maxConcurrent: config.team.maxConcurrent,
@@ -1173,9 +1253,9 @@ export class AgentController {
1173
1253
  // session can never be told to use a tool the prompt above it does not
1174
1254
  // mention. Empty everywhere else, which is what keeps I-2 (byte-identical
1175
1255
  // prompt) true for every session that never types `/team`.
1176
- forcedTeamBlock: this.forcedTeam && this.teamRegistered && this.config.team.enabled && !dropTeamBlocks
1256
+ forcedTeamBlock: forced && !dropTeamBlocks
1177
1257
  ? buildForcedTeamBlock({
1178
- count: this.forcedTeam.count,
1258
+ count: forced.count,
1179
1259
  planMode: this.effectiveMode === 'plan',
1180
1260
  })
1181
1261
  : '',
@@ -1213,6 +1293,15 @@ export class AgentController {
1213
1293
  // tools that make its promises achievable are registered. With the flag off
1214
1294
  // the prompt is byte-identical to the pre-feature text (I-3).
1215
1295
  jobsBlock: this.jobsRegistered ? buildBackgroundJobsBlock() : '',
1296
+ // FROM THE `config` ARGUMENT, never `this.config` (agent-image-reading F-9): a model
1297
+ // switch pre-builds the prompt for the INCOMING model before it is committed, and a
1298
+ // block written for the outgoing one would tell the new model the wrong thing.
1299
+ imageInputBlock: this.toolImagesEnabled
1300
+ ? buildImageInputBlock({
1301
+ support: this.resolveImageSupportFor(config).support,
1302
+ model: `${config.provider}/${config.model}`,
1303
+ })
1304
+ : '',
1216
1305
  // FROM THE FIELD, so the block survives every rebuild for the reason the field's
1217
1306
  // own comment records. Empty everywhere but `aragon exec --result-schema`, and
1218
1307
  // `buildSystemPrompt` splices it conditionally - so every existing prompt is
@@ -1224,11 +1313,47 @@ export class AgentController {
1224
1313
  appendSystemPrompt: this.appendSystemPrompt,
1225
1314
  });
1226
1315
  }
1316
+ /**
1317
+ * Whether GOVERN is dropping the team blocks (`task` is refused there, and advertising it
1318
+ * would describe a refused capability). ONE predicate for the prompt composer and for the
1319
+ * team switch's `paused` state, so the status bar and the prompt cannot disagree.
1320
+ *
1321
+ * `governBlock` lets the composer pass the block it already built for the prompt instead
1322
+ * of building the Orchestrator text a second time.
1323
+ */
1324
+ teamBlocksDropped(config = this.config, governBlock = this.governance.orchestratorBlock(this.getPosture(), config)) {
1325
+ return governBlock !== '' && this.effectiveMode === 'build';
1326
+ }
1227
1327
  rebuildSystemPrompt() {
1328
+ // FIRST: bring the stored team-mode state in line with the configuration that is now
1329
+ // live. This is the one place the two writers of `config.team` (`setTeamConfig` and the
1330
+ // settings snapshot apply) both pass through (team-mode-toggle-keys I-4).
1331
+ this.teamMode.reconcile();
1228
1332
  const prompt = this.preparedSystemPrompt ?? this.composeSystemPrompt();
1229
1333
  if (prompt !== this.agent.state.systemPrompt)
1230
1334
  this.idleCompaction?.abort();
1231
1335
  this.agent.setSystemPrompt(prompt);
1336
+ this.promptImageKey = this.currentImageKey();
1337
+ // LAST: every change to what the switch shows passes through here, so one notification
1338
+ // point replaces "each call site remembers to notify" (D-7).
1339
+ this.teamMode.emitIfChanged();
1340
+ }
1341
+ currentImageKey() {
1342
+ if (!this.toolImagesEnabled)
1343
+ return undefined;
1344
+ return `${this.config.provider}/${this.config.model}:${this.getImageSupport().support}`;
1345
+ }
1346
+ /**
1347
+ * Rewrite the prompt only when what the `<image_input>` block says has actually changed (a
1348
+ * model switch, a user override, or model discovery turning `unknown` into a fact). Every
1349
+ * rewrite breaks the provider's prompt cache from the system prompt on, so an unchanged
1350
+ * answer costs nothing.
1351
+ */
1352
+ syncImageInputBlock() {
1353
+ if (!this.toolImagesEnabled)
1354
+ return;
1355
+ if (this.currentImageKey() !== this.promptImageKey)
1356
+ this.rebuildSystemPrompt();
1232
1357
  }
1233
1358
  /** Re-render the prompt from the current skill set and tell the UI. */
1234
1359
  refreshSkills() {
@@ -1337,6 +1462,12 @@ export class AgentController {
1337
1462
  throw new Error('The previous run is still stopping.');
1338
1463
  if (this.isCompactionBusy())
1339
1464
  return this.compactionBusyOutcome();
1465
+ // A team-mode change asked for during the last turn lands before this message is built
1466
+ // when `agent_end` never reached the host (force-stop, /clear, crash recovery: the
1467
+ // generation guard drops that event). Here the engine is idle and this request has
1468
+ // survived the cancellation check, so neither a superseded `prompt()` nor a live turn
1469
+ // can apply it early (team-mode-toggle-keys RV-P1-3).
1470
+ this.teamMode.applyPending();
1340
1471
  return await this.startPrompt(text, options, request);
1341
1472
  }
1342
1473
  catch (err) {
@@ -1382,7 +1513,7 @@ export class AgentController {
1382
1513
  // from the previous run - a notice `fast` wiped, or one the model never saw
1383
1514
  // because it answered and stopped - is delivered here (RV-P1-7).
1384
1515
  this.flushPendingNotices();
1385
- await this.agent.prompt(text);
1516
+ await this.agent.prompt(options.parts ? { role: 'user', content: options.parts, timestamp: Date.now() } : text);
1386
1517
  return { status: 'finished' };
1387
1518
  }
1388
1519
  /**
@@ -1579,10 +1710,10 @@ export class AgentController {
1579
1710
  this.enqueueSteering(text, true);
1580
1711
  }
1581
1712
  /** Return the opaque ID used by the view to match Core's acceptance receipt. */
1582
- queueUserMessage(text) {
1583
- return this.enqueueSteering(text, true);
1713
+ queueUserMessage(text, parts) {
1714
+ return this.enqueueSteering(text, true, parts);
1584
1715
  }
1585
- enqueueSteering(text, user) {
1716
+ enqueueSteering(text, user, parts) {
1586
1717
  // Both reviewer and user guidance can activate queued skill frames.
1587
1718
  if (this.skillsEnabled && this.isRunning())
1588
1719
  this.skills.absorbPendingFrames();
@@ -1590,7 +1721,11 @@ export class AgentController {
1590
1721
  if (id !== undefined)
1591
1722
  this.pendingUserSteering.set(id, text);
1592
1723
  try {
1593
- this.agent.steer(text, id);
1724
+ // The legacy two-argument call is kept verbatim when there are no parts.
1725
+ if (parts)
1726
+ this.agent.steer(text, id, parts);
1727
+ else
1728
+ this.agent.steer(text, id);
1594
1729
  }
1595
1730
  catch (error) {
1596
1731
  if (id !== undefined)
@@ -2063,26 +2198,42 @@ export class AgentController {
2063
2198
  * does not silently widen back to four.
2064
2199
  */
2065
2200
  armForcedTeam(count) {
2066
- const ceiling = Math.max(1, this.config.team.maxSubagents);
2067
- const adopted = Math.max(1, Math.min(Math.floor(count), ceiling));
2068
- this.forcedTeam = { count: adopted };
2069
- // RE-RENDER: the `<forced_team_mode>` block has to be in the very next
2070
- // request, and `rebuildSystemPrompt()` is the live path that does it (it is
2071
- // also why the command body prints a notice: this produces no AgentEvent, so
2072
- // without one React would not repaint the `Team N` chip - P1-6).
2073
- this.rebuildSystemPrompt();
2074
- return adopted;
2201
+ // RE-RENDER: the `<forced_team_mode>` block has to be in the very next request, and the
2202
+ // wiring rebuilds the prompt (which also notifies subscribers, so the status switch
2203
+ // repaints without a notice).
2204
+ return this.teamMode.arm(count);
2075
2205
  }
2076
2206
  /** Disarm. IDEMPOTENT: disarming an unarmed session rewrites nothing. */
2077
2207
  disarmForcedTeam() {
2078
- if (!this.forcedTeam)
2079
- return;
2080
- this.forcedTeam = null;
2081
- this.rebuildSystemPrompt();
2208
+ this.teamMode.disarm();
2082
2209
  }
2083
- /** The armed state, read at render time by the chip and by `/team`'s status. */
2210
+ /**
2211
+ * The armed state the session honours, read at render time by `/team`'s status.
2212
+ *
2213
+ * DERIVED (team-mode-toggle-keys I-4): `null` whenever the tool is not registered or the
2214
+ * capability is off, and narrowed to the current `maxSubagents`.
2215
+ */
2084
2216
  getForcedTeam() {
2085
- return this.forcedTeam;
2217
+ return this.teamMode.getForced();
2218
+ }
2219
+ /** The team mode switch as every surface renders it. Cached; cheap to call per render. */
2220
+ getTeamMode() {
2221
+ return this.teamMode.getView();
2222
+ }
2223
+ /**
2224
+ * The ONE write entry for the team mode switch: Ctrl+T, Ctrl+Up/Down, `/team on|off` and
2225
+ * the desktop chip all call this. A turn in flight defers the change to its end.
2226
+ */
2227
+ setTeamMode(req) {
2228
+ return this.teamMode.request(req);
2229
+ }
2230
+ /** Land a deferred change at `agent_end`. `null` = nothing was pending. */
2231
+ applyPendingTeamMode() {
2232
+ return this.teamMode.applyPending();
2233
+ }
2234
+ /** Tell `listener` whenever the switch's view changes. Returns the unsubscribe. */
2235
+ subscribeTeamMode(listener) {
2236
+ return this.teamMode.subscribe(listener);
2086
2237
  }
2087
2238
  getTeamConfig() {
2088
2239
  return this.config.team;
@@ -2447,6 +2598,9 @@ export class AgentController {
2447
2598
  this.config = { ...this.config, provider, model, baseUrl };
2448
2599
  this.config.modelProfileState = resolveModelProfileState(this.config);
2449
2600
  this.agent.setModel({ providerId: provider, modelId: model, ...(baseUrl ? { baseUrl } : {}) });
2601
+ // This path does not rebuild the prompt on its own (only a live fast tier does, below),
2602
+ // so without this the `<image_input>` block would keep describing the OUTGOING model.
2603
+ this.syncImageInputBlock();
2450
2604
  // NOT NEUTRAL TO THE FAST TIER even when the user never touched a `fast.*`
2451
2605
  // key (§3.9 / RV-3): `fast.provider: ''` and `fast.baseUrl: ''` INHERIT from
2452
2606
  // exactly these three fields. Switching the main provider can therefore turn
@@ -2754,6 +2908,71 @@ export class AgentController {
2754
2908
  getModelRegistry() {
2755
2909
  return this.modelRegistry;
2756
2910
  }
2911
+ /**
2912
+ * Whether the ACTIVE model can read images (desktop-attachments-and-tool-voice §3.6).
2913
+ * Read live on every call: the model can change mid-session.
2914
+ */
2915
+ getImageSupport() {
2916
+ return { ...this.resolveImageSupportFor(this.config), tokenEstimate: IMAGE_TOKEN_ESTIMATE };
2917
+ }
2918
+ /**
2919
+ * The same answer for ANY model, not just the active one: the user's override first (it only
2920
+ * applies to the model it was set for), then the tables. A model switch is transactional and
2921
+ * pre-builds the system prompt for the incoming config, and a subagent may run a different
2922
+ * model from the lead, so neither can ask the single-model question above.
2923
+ */
2924
+ resolveImageSupportFor(cfg) {
2925
+ const user = this.imageOverride;
2926
+ if (user && user.key === `${cfg.provider}/${cfg.model}`) {
2927
+ return { support: user.value === 'on' ? 'yes' : 'no', source: 'override' };
2928
+ }
2929
+ return resolveImageSupport({
2930
+ providerId: cfg.provider,
2931
+ modelId: cfg.model,
2932
+ catalog: this.modelRegistry.findCatalogModel(cfg.provider, cfg.model),
2933
+ discovered: this.modelRegistry.getDiscoveredModel(cfg.provider, cfg.model, cfg.baseUrl),
2934
+ });
2935
+ }
2936
+ /**
2937
+ * The user's word on whether ONE model (`provider/model`) reads images. It only applies while
2938
+ * that model is active, and it is what makes request-time projection correct for a model the
2939
+ * tables do not know. `null` clears it. Session-scoped: the desktop re-sends it on attach.
2940
+ */
2941
+ setImageSupportOverride(key, value) {
2942
+ this.imageOverride = value === null ? undefined : { key, value };
2943
+ this.syncImageInputBlock();
2944
+ }
2945
+ /**
2946
+ * D-12: a model of unconfirmed image support that the provider refuses a picture for is, for
2947
+ * the rest of the session, a model that cannot read pictures. Without this, trying (which
2948
+ * `unknown` allows) would lock a text-only model out of the conversation: every later
2949
+ * request would carry the same picture and fail the same way.
2950
+ *
2951
+ * Conservative on purpose, and silent when any condition fails: it acts on the error TEXT
2952
+ * (a token-count mention is classed as context overflow by the transport), never overrides
2953
+ * the user's own word, ignores size and format complaints (the model may read other
2954
+ * pictures fine), and needs a picture in the history to have been the cause. It does not
2955
+ * retry: the next send simply works, and the desktop has its own recovery for the same error.
2956
+ */
2957
+ learnImageRefusal(error) {
2958
+ if (!this.toolImagesEnabled || !isImageCapabilityRefusal(error.message))
2959
+ return;
2960
+ const current = this.getImageSupport();
2961
+ if (current.support === 'no' || current.source === 'override')
2962
+ return;
2963
+ if (countAllImages(this.agent.state.messages) === 0)
2964
+ return;
2965
+ const key = `${this.config.provider}/${this.config.model}`;
2966
+ this.imageOverride = { key, value: 'off' };
2967
+ this.syncImageInputBlock();
2968
+ getLogger().info('agent', 'image_refusal_learned', { key });
2969
+ this.notifyHostFn?.('warn', `The provider rejected a request that contained images (${key}). Images are now replaced by `
2970
+ + 'text notes for this model until the session ends. Send your message again to continue.');
2971
+ }
2972
+ /** Image parts currently held by history (budget input; counts base64 chars, never decodes). */
2973
+ getImageUsageInHistory() {
2974
+ return countHistoryImages(this.agent.state.messages);
2975
+ }
2757
2976
  /** Resolve `ModelInfo` for the active model, falling back to a runtime model. */
2758
2977
  getModelInfo() {
2759
2978
  return this.getModelInfoFor({
@@ -2802,6 +3021,8 @@ export class AgentController {
2802
3021
  if (this.disposed || generation !== this.modelMetadataGeneration)
2803
3022
  return;
2804
3023
  this.contextMeter.onWindowChanged();
3024
+ // Discovery may have turned `unknown` into a fact, which the prompt should now state.
3025
+ this.syncImageInputBlock();
2805
3026
  }
2806
3027
  catch {
2807
3028
  // Offline or unsupported discovery leaves catalog/unknown metadata intact.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Image parts that live in conversation history (desktop-attachments-and-tool-voice §3.6, §3.12;
3
+ * agent-image-reading §3.7-§3.9).
4
+ *
5
+ * `projectImagesForModel` is the request-time view used when the CURRENT model cannot read
6
+ * images: it never edits history, and it returns the SAME array when there is nothing to
7
+ * change, so a text-only session sends byte-identical requests. `countHistoryImages` feeds the
8
+ * per-session image budget. The host-built label text (`[image1: shot.png ...]`, or the
9
+ * `[read_file image: ...]` label of a tool picture) is the only thing that makes an image
10
+ * attributable, so every projection keeps it and only swaps the pixels.
11
+ *
12
+ * Two kinds of picture are NOT treated alike, on purpose. A picture the user pasted may be
13
+ * unrecoverable, so only host-labelled ones are ever replaced. A picture a TOOL returned can
14
+ * always be fetched again by re-running the tool, so it is unconditionally replaceable:
15
+ * `demoteToolImages` is the single implementation behind the request window, compaction and
16
+ * both disk writers (session file and compaction archive).
17
+ * Agent-facing text: English, ASCII.
18
+ */
19
+ import type { Message } from '@aragon-agent/core';
20
+ import type { ImageSupport } from './image-support.js';
21
+ /** The label the desktop host writes in front of every inline image. */
22
+ export declare const IMAGE_LABEL_RE: RegExp;
23
+ /**
24
+ * The label `read_file` writes in front of every picture it returns. The recognising grammar
25
+ * lives HERE, with the consumers that must find it again (projection, window, compaction,
26
+ * persistence), not in the producing tool: a lifecycle module must not depend on a module
27
+ * that drags in `node:fs`. The producer imports this and a test checks the round trip.
28
+ */
29
+ export declare const TOOL_IMAGE_LABEL_RE: RegExp;
30
+ export type DemoteReason = 'dropped' | 'not_saved';
31
+ export declare const TOOL_IMAGE_DROPPED_SUFFIX = " - pixels dropped from context; call read_file on the path to view it again";
32
+ export declare const TOOL_IMAGE_NOT_SAVED_SUFFIX = " - pixels not saved with the session; call read_file on the path to view it again";
33
+ /**
34
+ * The request window for tool pictures. Stateless, so the same history prefix projects the
35
+ * same way on every request; `step` quantises how many are dropped so that the oldest picture
36
+ * is swapped out once per four reads, not once per read (every swap rewrites the middle of
37
+ * the conversation and invalidates the provider's prompt cache from that point on).
38
+ */
39
+ export declare const TOOL_IMAGE_WINDOW: {
40
+ readonly maxImages: 8;
41
+ readonly maxBase64Chars: number;
42
+ readonly step: 4;
43
+ };
44
+ /**
45
+ * User-message and tool-result images become their label text; everything else is untouched.
46
+ * A user picture is matched against the desktop label, a tool picture against the
47
+ * `read_file` label; an unlabelled picture of either kind becomes the generic placeholder.
48
+ */
49
+ export declare function projectImagesForModel(messages: readonly Message[]): readonly Message[];
50
+ export interface ImageUsage {
51
+ /** Base64 characters held by image parts in user messages. */
52
+ bytes: number;
53
+ /** User messages that carry at least one image part. */
54
+ messages: number;
55
+ /** Image parts in total. */
56
+ images: number;
57
+ }
58
+ export declare function countHistoryImages(messages: readonly Message[]): ImageUsage;
59
+ /** Image parts in user messages AND tool results: what a provider would be sent. */
60
+ export declare function countAllImages(messages: readonly Message[]): number;
61
+ /**
62
+ * Every picture of a tool result becomes its label plus a note saying why the pixels are gone
63
+ * and how to get them back. Returns the SAME message when there is nothing to change.
64
+ *
65
+ * `labelledOnly` restricts that to pictures directly behind a `read_file` label. Compaction
66
+ * uses it: a picture nobody labelled has no attribution to keep, so the old protection
67
+ * (never summarise an unattributed picture away) still applies to it. The window, the session
68
+ * file and the archive demote unlabelled pictures too.
69
+ */
70
+ export declare function demoteToolImages(message: Message, reason: DemoteReason, options?: {
71
+ labelledOnly?: boolean;
72
+ }): {
73
+ message: Message;
74
+ demoted: number;
75
+ };
76
+ /**
77
+ * How many of the OLDEST pictures to drop. `sizes` are base64 lengths, oldest first. The
78
+ * answer is 0, a multiple of `step`, or all of them; adding a picture never lowers it.
79
+ */
80
+ export declare function planToolImageWindow(sizes: readonly number[]): number;
81
+ /**
82
+ * Request-time view that keeps at most `TOOL_IMAGE_WINDOW` tool pictures, newest first, by
83
+ * turning the oldest into text. Only tool results are touched; user pictures keep their own
84
+ * budget. Returns the SAME array when nothing needs dropping.
85
+ */
86
+ export declare function windowToolImages(messages: readonly Message[]): readonly Message[];
87
+ /** What a session file or compaction archive may hold: no tool pixels, same array if none. */
88
+ export declare function stripToolImagePixels(messages: readonly Message[]): readonly Message[];
89
+ /**
90
+ * The `projectMessages` hook for an agent: pictures vanish for a model that cannot read them,
91
+ * and tool pictures are windowed for one that can.
92
+ */
93
+ export declare function makeImageProjection(getSupport: () => ImageSupport): (messages: readonly Message[]) => readonly Message[];