@aragon-agent/cli 0.6.51 → 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
@@ -37,14 +37,17 @@
37
37
  * key present? - names the missing provider.
38
38
  * on - arm only; the next message dispatches.
39
39
  *
40
- * EVERY `armForcedTeam()` / `disarmForcedTeam()` CALL SITE BELOW IS FOLLOWED BY A
41
- * `ctx.notify` / `ctx.toast` IN THE SAME BRANCH (P1-6 / AC-28), because arming
42
- * itself produces no `AgentEvent` and therefore no render: without the notice the
43
- * `Team 4` chip would wait for an unrelated state change before appearing.
40
+ * `on` AND `off` GO THROUGH THE ONE SHARED ENTRY, `controller.setTeamMode()`
41
+ * (team-mode-toggle-keys D-5), the same call Ctrl+T and the desktop chip make, so a
42
+ * turn in flight defers the change instead of being refused and the wording is the
43
+ * shared `teamModeToast`. The status-bar switch repaints from the controller's
44
+ * subscription, so these notices are for the user to READ, no longer what makes the
45
+ * screen refresh (the old P1-6 contract).
44
46
  */
45
47
  import { buildForcedDirective } from '../team/forced-dispatch.js';
46
- import { DEFAULT_FORCED_COUNT, forcedCardNote, planForced, planNotice, readTeamIntent, } from '../team/forced-mode.js';
48
+ import { forcedCardNote, planForced, planNotice, readTeamIntent, } from '../team/forced-mode.js';
47
49
  import { subagentModelSummary } from '@aragon-agent/tui/ui/overlays/model-profile-state';
50
+ import { teamModeToast, } from '@aragon-agent/tui/model/team/team-mode';
48
51
  /**
49
52
  * The subagent model line, phrased by the same authority the settings root row
50
53
  * uses (`subagentModelSummary`), fed the six inputs only this layer can gather.
@@ -80,16 +83,15 @@ function reportStatus(ctx) {
80
83
  const forced = ctx.controller.getForcedTeam();
81
84
  const registered = ctx.controller.isTeamRegistered();
82
85
  const lines = [
83
- forced
84
- ? `Forced team mode: on, ${forced.count} subagents per turn.`
85
- : 'Forced team mode: off.',
86
+ forcedLine(ctx, forced),
86
87
  registered
87
88
  ? `Team: ${ctx.controller.isTeamEnabled() ? 'on' : 'off'}; `
88
89
  + `${team.maxSubagents} per dispatch, ${team.maxConcurrent} at once; `
89
90
  + `supervisor ${team.overseer ? 'on' : 'off'}.`
90
91
  : 'Team: off for this session (started with --no-team); /team cannot dispatch.',
91
92
  `Subagent model: ${modelLine(ctx)}`,
92
- 'Usage: /team <brief> arms it and starts now; /team off leaves it.',
93
+ 'Usage: /team <brief> arms it and starts now; /team on [n] | off switches it. '
94
+ + `Keys: Ctrl+T toggles, Ctrl+Up / Ctrl+Down sets the count (1-${team.maxSubagents}).`,
93
95
  'Settings > Team has the persistent switches (mode, width, supervisor).',
94
96
  ];
95
97
  // DISCLOSED, NEVER REFUSED (§5.1 third degraded form): plan mode narrows what a
@@ -99,6 +101,22 @@ function reportStatus(ctx) {
99
101
  }
100
102
  ctx.notify('info', lines.join('\n'));
101
103
  }
104
+ /**
105
+ * The first status line: the armed state, plus a change that is waiting for the turn to end.
106
+ *
107
+ * READS THE SWITCH'S VIEW WHEN THE CONTROLLER HAS ONE and falls back to the armed state when
108
+ * it does not (a hand-written double), so the line never claims more than the controller said.
109
+ */
110
+ function forcedLine(ctx, forced) {
111
+ const base = forced
112
+ ? `Forced team mode: on, ${forced.count} subagents per turn.`
113
+ : 'Forced team mode: off.';
114
+ const pending = ctx.controller.getTeamMode?.().pending;
115
+ if (!pending)
116
+ return base;
117
+ const change = pending.on ? `on, ${pending.count} subagents` : 'off';
118
+ return `${base} Pending: ${change} when this turn ends.`;
119
+ }
102
120
  /**
103
121
  * Guard 5's sentence. The provider is named because "no API key" alone leaves the
104
122
  * user guessing which of their configured providers is the empty one.
@@ -173,31 +191,53 @@ function reportParseError(ctx, intent) {
173
191
  ctx.notify('warn', '/team <brief> - describe the work; add -n <count> to fix the fan-out.');
174
192
  }
175
193
  /**
176
- * `/team off`: disarm the session, and say plainly that the CAPABILITY was not
177
- * touched.
194
+ * Say what a `setTeamMode()` call did, in the shared wording.
195
+ *
196
+ * `unregistered` keeps the command's own, more specific sentence: it names the flag AND the
197
+ * way out ("restart without --no-team"), which the one-line shared refusal text does not.
198
+ */
199
+ function reportTeamModeOutcome(ctx, req, outcome) {
200
+ if (!outcome.ok && outcome.refusal === 'unregistered') {
201
+ ctx.notify('warn', 'Team mode is off for this session (started with --no-team). '
202
+ + 'Restart without --no-team to use /team.');
203
+ return;
204
+ }
205
+ const toast = teamModeToast(outcome, {
206
+ request: req.kind,
207
+ firstOnThisSession: false,
208
+ max: ctx.controller.getTeamConfig().maxSubagents,
209
+ command: true,
210
+ });
211
+ if (toast)
212
+ ctx.notify(toast.level, toast.text);
213
+ }
214
+ /**
215
+ * `/team off`: leave the mode, and say plainly that the CAPABILITY was not touched.
178
216
  *
179
217
  * THE SECOND HALF OF THE SENTENCE IS THE POINT (D-2 / D-11): with the switch
180
218
  * moved to settings, "off" can only ever mean "this conversation stops being
181
219
  * forced". A user who reads it as "team mode is now disabled everywhere" would
182
220
  * next find `/team` still working tomorrow, and no test would describe that as a
183
221
  * defect because no single surface would be wrong.
222
+ *
223
+ * NO GUARDS, and a turn in flight is not a refusal: the change is deferred to the end of
224
+ * the turn like Ctrl+T's (D-12 / L-3). Idempotent: leaving a mode that is not on says so.
184
225
  */
185
226
  function leaveForcedMode(ctx) {
186
- if (!ctx.controller.getForcedTeam()) {
187
- // IDEMPOTENT, and it says so rather than reporting a change it did not make.
188
- ctx.notify('info', 'Forced team mode was not on.');
189
- return;
190
- }
191
- ctx.controller.disarmForcedTeam();
192
- ctx.notify('info', 'Forced team mode off. Team capability unchanged (Settings > Team).');
227
+ const req = { kind: 'off' };
228
+ reportTeamModeOutcome(ctx, req, ctx.controller.setTeamMode(req));
193
229
  }
194
- /** `/team on`: arm with the default count and stop there - no turn is submitted. */
195
- function enterForcedMode(ctx) {
196
- if (!passGuards(ctx, ctx.controller.getTeamConfig()))
197
- return;
198
- const adopted = ctx.controller.armForcedTeam(DEFAULT_FORCED_COUNT);
199
- ctx.notify('info', `Forced team mode on: ${adopted} subagents per turn. `
200
- + 'Your next message dispatches.');
230
+ /**
231
+ * `/team on [n]`: arm with the default (or the given) count and stop there - no turn is
232
+ * submitted.
233
+ *
234
+ * The three guards that protect SUBMITTING a turn (busy, running, key) do not apply: nothing
235
+ * is submitted. The capability is still switched on for this session when Settings had it
236
+ * off, by the shared entry, and nothing is persisted (I-4).
237
+ */
238
+ function enterForcedMode(ctx, count) {
239
+ const req = count === undefined ? { kind: 'on' } : { kind: 'on', count };
240
+ reportTeamModeOutcome(ctx, req, ctx.controller.setTeamMode(req));
201
241
  }
202
242
  /**
203
243
  * The card's raw material for `/team <brief>` (tui-invocation-cards section 3.3). The
@@ -272,7 +312,7 @@ export function runTeamCommand(ctx) {
272
312
  return;
273
313
  }
274
314
  if (intent.kind === 'on') {
275
- enterForcedMode(ctx);
315
+ enterForcedMode(ctx, intent.count);
276
316
  return;
277
317
  }
278
318
  if (intent.kind === 'error') {
@@ -290,7 +330,7 @@ export function registerTeamCommand(registry) {
290
330
  registry.register({
291
331
  name: 'team',
292
332
  rendersInvocationCard: teamRendersInvocationCard,
293
- description: 'Force team mode and start now: /team <brief>; /team [on|off|status]',
333
+ description: 'Force team mode and start now: /team <brief>; /team [on [n]|off|status]',
294
334
  run: (ctx) => { runTeamCommand(ctx); },
295
335
  });
296
336
  }
@@ -22,6 +22,7 @@ import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync }
22
22
  import { join } from 'node:path';
23
23
  import { getCompactionArchiveDir } from '../config/app-paths.js';
24
24
  import { getLogger } from '../logging/logger.js';
25
+ import { stripToolImagePixels } from '../agent/image-history.js';
25
26
  import { COMPACTION_BLOCK_VERSION, COMPACTION_LIMITS } from '@aragon-agent/tui/model/compaction/limits';
26
27
  const FILE_PREFIX = 'compaction-';
27
28
  const FILE_SUFFIX = '.json';
@@ -130,7 +131,11 @@ export function writeArchive(input) {
130
131
  ...(input.summary !== undefined ? { summary: input.summary } : {}),
131
132
  ...(input.tailRelief ? { tailRelief: input.tailRelief } : {}),
132
133
  clipped: false,
133
- dropped: input.dropped,
134
+ // agent-image-reading: the archive is the SECOND place messages reach the disk. A tool
135
+ // picture is re-fetchable, so it is archived as its label and a note; verbatim pixels
136
+ // would both leak the image and, at 8 MB, make `serializeArchive` halve away the TEXT
137
+ // the archive exists to keep. (ASCII only: this directory is in the glyph scan.)
138
+ dropped: [...stripToolImagePixels(input.dropped)],
134
139
  };
135
140
  writeFileSync(path, serializeArchive(doc, COMPACTION_LIMITS.archiveMaxBytes), 'utf8');
136
141
  }
@@ -163,6 +163,11 @@ export class Compactor {
163
163
  this.phase(state, 'digesting');
164
164
  const input = prepareMemoryInput({ messages: state.messages, cutIndex: plan.cutIndex,
165
165
  ...(this.identity ? { identity: this.identity } : {}) });
166
+ if (input.imagesDemoted > 0) {
167
+ this.log.info('images_demoted', { count: input.imagesDemoted });
168
+ this.deps.notify('info', `${input.imagesDemoted} image(s) were moved out of the model's context by compaction; `
169
+ + 'they remain visible in the transcript.');
170
+ }
166
171
  const selected = this.selectInput(input, instructions);
167
172
  state.elided = selected.digest.omitted;
168
173
  this.checkMinimumCandidate(input, selected.digest, state, ctx.systemPrompt);
@@ -15,11 +15,32 @@ export interface PreparedMemoryInput {
15
15
  tail: Message[];
16
16
  cutIndex: number;
17
17
  legacySummary?: string;
18
+ /** Labelled images (anchor included) replaced by text so the history stays compactable. */
19
+ imagesDemoted: number;
18
20
  }
19
21
  export interface PrepareMemoryOptions {
20
22
  messages: readonly Message[];
21
23
  cutIndex: number;
22
24
  identity?: CompactionIdentity;
23
25
  }
26
+ /**
27
+ * desktop-attachments-and-tool-voice D-19. An image that the desktop labelled
28
+ * (`[image1: shot.png, 1568x882]` immediately before the part) is DEMOTABLE: when its message
29
+ * is about to be compacted away, the pixels are replaced by that label plus a removal note.
30
+ * The summariser cannot see images anyway, and without this one screenshot would make every
31
+ * later compaction fail (`protected_multimodal_tail` / `protected_memory_too_large`).
32
+ * Unlabelled images keep the old protection. Returns the same message when nothing changes.
33
+ * Kill switch: ARAGON_COMPACTION_DEMOTE_IMAGES=0.
34
+ *
35
+ * agent-image-reading D-10: a TOOL picture that carries the `read_file` label is demotable
36
+ * too. Unlike a pasted image it can be fetched again by re-running the tool, so no pixel is
37
+ * ever lost for good and the first `read_file` screenshot cannot make the history
38
+ * uncompactable. A tool picture with NO label keeps the old protection (see the issues section
39
+ * of the spec: `compaction-memory-input.test.ts` pins that behaviour).
40
+ */
41
+ export declare function demoteImages(message: Message): {
42
+ message: Message;
43
+ demoted: number;
44
+ };
24
45
  /** Prepare a snapshot without mutation; throws before payment when protection cannot fit. */
25
46
  export declare function prepareMemoryInput(options: PrepareMemoryOptions): PreparedMemoryInput;
@@ -5,10 +5,67 @@ import { parseCompactedBlock } from './summary-prompt.js';
5
5
  import { verifyCompactionIdentity } from './memory-identity.js';
6
6
  import { COMPACTION_LIMITS as LIMITS } from '@aragon-agent/tui/model/compaction/limits';
7
7
  import { buildDigest } from './digest.js';
8
+ import { IMAGE_LABEL_RE, demoteToolImages } from '../agent/image-history.js';
8
9
  function hasImage(message) {
9
10
  return message.role !== 'assistant' && Array.isArray(message.content)
10
11
  && message.content.some((part) => part.type === 'image');
11
12
  }
13
+ /**
14
+ * desktop-attachments-and-tool-voice D-19. An image that the desktop labelled
15
+ * (`[image1: shot.png, 1568x882]` immediately before the part) is DEMOTABLE: when its message
16
+ * is about to be compacted away, the pixels are replaced by that label plus a removal note.
17
+ * The summariser cannot see images anyway, and without this one screenshot would make every
18
+ * later compaction fail (`protected_multimodal_tail` / `protected_memory_too_large`).
19
+ * Unlabelled images keep the old protection. Returns the same message when nothing changes.
20
+ * Kill switch: ARAGON_COMPACTION_DEMOTE_IMAGES=0.
21
+ *
22
+ * agent-image-reading D-10: a TOOL picture that carries the `read_file` label is demotable
23
+ * too. Unlike a pasted image it can be fetched again by re-running the tool, so no pixel is
24
+ * ever lost for good and the first `read_file` screenshot cannot make the history
25
+ * uncompactable. A tool picture with NO label keeps the old protection (see the issues section
26
+ * of the spec: `compaction-memory-input.test.ts` pins that behaviour).
27
+ */
28
+ export function demoteImages(message) {
29
+ if (message.role === 'tool_result') {
30
+ return demoteToolImages(message, 'dropped', { labelledOnly: true });
31
+ }
32
+ if (message.role !== 'user' || !Array.isArray(message.content))
33
+ return { message, demoted: 0 };
34
+ const out = [];
35
+ let demoted = 0;
36
+ const parts = message.content;
37
+ for (const part of parts) {
38
+ const last = out[out.length - 1];
39
+ if (part.type === 'image' && last?.type === 'text' && IMAGE_LABEL_RE.test(last.text)) {
40
+ out[out.length - 1] = {
41
+ type: 'text',
42
+ text: last.text.replace(/\]$/, ' - removed from context by compaction]'),
43
+ };
44
+ demoted += 1;
45
+ }
46
+ else {
47
+ out.push(part);
48
+ }
49
+ }
50
+ return demoted ? { message: { ...message, content: out }, demoted } : { message, demoted: 0 };
51
+ }
52
+ function demotionEnabled() {
53
+ return process.env.ARAGON_COMPACTION_DEMOTE_IMAGES !== '0';
54
+ }
55
+ /** Copy of `messages` with labelled images demoted in every user message below `cutIndex`. */
56
+ function demoteBelowCut(messages, cutIndex) {
57
+ if (!demotionEnabled() || !messages.some(hasImage))
58
+ return { view: messages, demoted: 0 };
59
+ let total = 0;
60
+ const view = messages.map((message, index) => {
61
+ if (index >= cutIndex)
62
+ return message;
63
+ const result = demoteImages(message);
64
+ total += result.demoted;
65
+ return result.message;
66
+ });
67
+ return { view: total ? view : messages, demoted: total };
68
+ }
12
69
  function protectImages(messages, cutIndex, anchorIndex) {
13
70
  const imageIndex = messages.findIndex((message, index) => index < cutIndex && index !== anchorIndex && hasImage(message));
14
71
  if (imageIndex < 0)
@@ -55,8 +112,11 @@ function preflightBudget(input) {
55
112
  }
56
113
  /** Prepare a snapshot without mutation; throws before payment when protection cannot fit. */
57
114
  export function prepareMemoryInput(options) {
58
- const { messages, identity } = options;
59
- if (identity && !verifyCompactionIdentity(messages, identity)) {
115
+ const { identity } = options;
116
+ const demotion = demoteBelowCut(options.messages, options.cutIndex);
117
+ const messages = demotion.view;
118
+ // Identity is a property of the real history, never of the demoted view.
119
+ if (identity && !verifyCompactionIdentity(options.messages, identity)) {
60
120
  throw new MemoryError('invalid_prior_memory', '$.identity');
61
121
  }
62
122
  const parsed = identity ? parseCompactedBlock(messages[1]) : undefined;
@@ -96,8 +156,11 @@ export function prepareMemoryInput(options) {
96
156
  userMessages,
97
157
  head: messages.slice(headStartIndex, cutIndex),
98
158
  headStartIndex,
99
- tail: messages.slice(cutIndex),
159
+ // The tail always comes from the ORIGINAL history: demotion applies only to what is
160
+ // being compacted away, never to messages the model keeps.
161
+ tail: options.messages.slice(cutIndex),
100
162
  cutIndex,
163
+ imagesDemoted: demotion.demoted,
101
164
  legacySummary: prior?.legacySummary
102
165
  ?? (!identity ? legacyReference(messages.slice(0, cutIndex)) : undefined),
103
166
  };
@@ -20,6 +20,7 @@ import { EngineCore, type EngineDeps } from './engine-core.js';
20
20
  import { type PauseOutcome } from './pause.js';
21
21
  export declare class GovernanceEngine implements GovernanceEngineApi {
22
22
  private readonly core;
23
+ private releasing;
23
24
  constructor(deps: EngineDeps);
24
25
  /** Exposed for tests and the wiring's persistence helpers; not part of the tool surface. */
25
26
  get internals(): EngineCore;
@@ -47,6 +48,13 @@ export declare class GovernanceEngine implements GovernanceEngineApi {
47
48
  * the run resumable (D-12), exactly as an Esc does.
48
49
  */
49
50
  dispose(): void;
51
+ /**
52
+ * Settles once the lock release started by `dispose()` has finished on disk (never
53
+ * rejects). `dispose()` stays synchronous so quitting never waits on the filesystem; code
54
+ * that re-opens the same run in this process (tests, an in-process restart) awaits this
55
+ * first, otherwise its own lock acquisition races the old unlink.
56
+ */
57
+ whenReleased(): Promise<void>;
50
58
  rejectInvalid(identity: Identity, input: unknown, text: string): ToolText;
51
59
  submitWork(identity: Identity, input: unknown): ToolText;
52
60
  submitReview(identity: Identity, input: unknown): ToolText;
@@ -66,6 +66,7 @@ function renderForAccess(item, access, markdown) {
66
66
  }
67
67
  export class GovernanceEngine {
68
68
  core;
69
+ releasing = Promise.resolve();
69
70
  constructor(deps) {
70
71
  this.core = new EngineCore(deps);
71
72
  }
@@ -146,10 +147,19 @@ export class GovernanceEngine {
146
147
  this.core.abortStage();
147
148
  if (runId !== undefined) {
148
149
  this.core.deps.store.stopHeartbeat(runId);
149
- void this.core.deps.store.releaseLock(runId).catch(() => undefined);
150
+ this.releasing = this.core.deps.store.releaseLock(runId).catch(() => undefined);
150
151
  }
151
152
  this.core.dispose();
152
153
  }
154
+ /**
155
+ * Settles once the lock release started by `dispose()` has finished on disk (never
156
+ * rejects). `dispose()` stays synchronous so quitting never waits on the filesystem; code
157
+ * that re-opens the same run in this process (tests, an in-process restart) awaits this
158
+ * first, otherwise its own lock acquisition races the old unlink.
159
+ */
160
+ whenReleased() {
161
+ return this.releasing;
162
+ }
153
163
  // ---------------------------------------------------------------------------
154
164
  // Child entry points (synchronous: a tool call cannot wait on the disk)
155
165
  // ---------------------------------------------------------------------------
@@ -61,6 +61,16 @@ export interface AtomicOptions {
61
61
  }
62
62
  /** mkdir -p with the store's directory mode. */
63
63
  export declare function ensureDir(path: string, fs?: GovFs): Promise<void>;
64
+ /**
65
+ * Run one filesystem operation, retrying the transient Windows contention codes
66
+ * (EPERM / EBUSY / EACCES) at `RENAME_RETRY_DELAYS_MS`. Off Windows those codes are real
67
+ * permission problems, so nothing is retried and the first error is thrown at once.
68
+ *
69
+ * Covers two races with the same cause (a scanner or indexer briefly holding a handle):
70
+ * `rename` over a freshly written file, and an exclusive create (`wx`) of a file whose
71
+ * unlink is still pending, which Windows reports as EPERM instead of EEXIST or ENOENT.
72
+ */
73
+ export declare function retryOnWindowsContention<T>(operation: () => Promise<T>, options?: Pick<AtomicOptions, 'platform' | 'sleep'>): Promise<T>;
64
74
  /**
65
75
  * Replace `path` with `data` atomically. Creates the parent directory if missing.
66
76
  * On failure the temp file is removed (best effort) and the ORIGINAL error is thrown,
@@ -63,19 +63,29 @@ async function writeTempFile(fs, tempPath, data) {
63
63
  await handle.close();
64
64
  }
65
65
  }
66
- async function renameWithRetry(fs, from, to, options) {
67
- const delays = options.retry ? RENAME_RETRY_DELAYS_MS : [];
66
+ /**
67
+ * Run one filesystem operation, retrying the transient Windows contention codes
68
+ * (EPERM / EBUSY / EACCES) at `RENAME_RETRY_DELAYS_MS`. Off Windows those codes are real
69
+ * permission problems, so nothing is retried and the first error is thrown at once.
70
+ *
71
+ * Covers two races with the same cause (a scanner or indexer briefly holding a handle):
72
+ * `rename` over a freshly written file, and an exclusive create (`wx`) of a file whose
73
+ * unlink is still pending, which Windows reports as EPERM instead of EEXIST or ENOENT.
74
+ */
75
+ export async function retryOnWindowsContention(operation, options = {}) {
76
+ const platform = options.platform ?? process.platform;
77
+ const sleep = options.sleep ?? realSleep;
78
+ const delays = platform === 'win32' ? RENAME_RETRY_DELAYS_MS : [];
68
79
  for (let attempt = 0;; attempt++) {
69
80
  try {
70
- await fs.rename(from, to);
71
- return;
81
+ return await operation();
72
82
  }
73
83
  catch (error) {
74
84
  const code = errorCode(error);
75
85
  const canRetry = attempt < delays.length && code !== undefined && RETRYABLE_CODES.has(code);
76
86
  if (!canRetry)
77
87
  throw error;
78
- await options.sleep(delays[attempt]);
88
+ await sleep(delays[attempt]);
79
89
  }
80
90
  }
81
91
  }
@@ -86,13 +96,11 @@ async function renameWithRetry(fs, from, to, options) {
86
96
  */
87
97
  export async function atomicWriteFile(path, data, options = {}) {
88
98
  const fs = options.fs ?? nodeGovFs;
89
- const platform = options.platform ?? process.platform;
90
- const sleep = options.sleep ?? realSleep;
91
99
  await ensureDir(dirname(path), fs);
92
100
  const tempPath = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
93
101
  try {
94
102
  await writeTempFile(fs, tempPath, data);
95
- await renameWithRetry(fs, tempPath, path, { retry: platform === 'win32', sleep });
103
+ await retryOnWindowsContention(() => fs.rename(tempPath, path), options);
96
104
  }
97
105
  catch (error) {
98
106
  await fs.unlink(tempPath).catch(() => undefined);
@@ -28,6 +28,10 @@ export interface LockDeps {
28
28
  pid: number;
29
29
  isPidAlive: (pid: number) => boolean;
30
30
  staleMs: number;
31
+ /** Defaults to `process.platform`; injected so the Windows retry path is testable anywhere. */
32
+ platform?: NodeJS.Platform;
33
+ /** Defaults to a real timer; tests pass a recorder. */
34
+ sleep?: (ms: number) => Promise<void>;
31
35
  }
32
36
  export type AcquireResult = {
33
37
  ok: true;
@@ -16,7 +16,7 @@
16
16
  * cannot both win it. Two processes racing to take over a STALE lock can, so a takeover
17
17
  * re-reads the file after writing and yields if somebody else's pid is in it.
18
18
  */
19
- import { atomicWriteFile, nodeGovFs } from './atomic.js';
19
+ import { atomicWriteFile, nodeGovFs, retryOnWindowsContention, } from './atomic.js';
20
20
  /** `kill(pid, 0)`: ESRCH means gone, EPERM means alive but not ours. */
21
21
  export function defaultIsPidAlive(pid) {
22
22
  try {
@@ -73,7 +73,9 @@ async function tryExclusiveCreate(path, deps) {
73
73
  const fs = deps.fs ?? nodeGovFs;
74
74
  let handle;
75
75
  try {
76
- handle = await fs.open(path, 'wx', 0o600);
76
+ // A previous owner's release (unlink) may still be in flight. On Windows the file is then
77
+ // delete-pending and `wx` fails with EPERM rather than EEXIST; wait it out like `rename`.
78
+ handle = await retryOnWindowsContention(() => fs.open(path, 'wx', 0o600), deps);
77
79
  }
78
80
  catch (error) {
79
81
  if (error.code === 'EEXIST')
@@ -22,6 +22,8 @@ export interface SubmitOutcome {
22
22
  accepted: boolean;
23
23
  /** Present when `accepted` is false; a sentence the UI may show verbatim. */
24
24
  reason?: string;
25
+ /** Present only when an attachment-bearing message was queued behind a running turn. */
26
+ queueId?: string;
25
27
  }
26
28
  export interface InteractionPorts {
27
29
  controller: AgentController;
@@ -41,9 +43,12 @@ export declare class InteractionCoordinator {
41
43
  onAgentStart(): void;
42
44
  /**
43
45
  * `agent_end`: the run is over, so a deferred `plan -> build` (or any posture change that
44
- * waited for a governed stage) becomes real here and nowhere else.
46
+ * waited for a governed stage) and a deferred team-mode change become real here and nowhere
47
+ * else.
45
48
  */
46
49
  onAgentEnd(): void;
50
+ /** Land the team-mode change that was asked for during the turn, and say what happened. */
51
+ private landTeamMode;
47
52
  /** Send a message to the agent, bypassing slash parsing. */
48
53
  submit(message: string, opts?: SubmitMessageOptions): SubmitOutcome;
49
54
  /**
@@ -19,6 +19,7 @@ import { bumpSubmitCount } from '../config/ui-state.js';
19
19
  import { postureAppliedToast } from '../governance/copy.js';
20
20
  import { advanceInterruptGesture, cancelInterruptConfirmation, } from '@aragon-agent/tui/input/interrupt-gesture';
21
21
  import { splitPosture } from '@aragon-agent/tui/model/governance/posture';
22
+ import { teamModeToast, teamRefusalText } from '@aragon-agent/tui/model/team/team-mode';
22
23
  import { buildInvocationCard, invocationCardsEnabled } from '@aragon-agent/tui/model/agent/invocation-card';
23
24
  import { getSecrets } from '@aragon-agent/tui/model/logging/secret-registry';
24
25
  import { redactText } from '../logging/redact.js';
@@ -40,12 +41,18 @@ export class InteractionCoordinator {
40
41
  }
41
42
  /**
42
43
  * `agent_end`: the run is over, so a deferred `plan -> build` (or any posture change that
43
- * waited for a governed stage) becomes real here and nowhere else.
44
+ * waited for a governed stage) and a deferred team-mode change become real here and nowhere
45
+ * else.
44
46
  */
45
47
  onAgentEnd() {
46
48
  this.phaseValue = 'idle';
47
49
  this.gesture = { phase: 'ready' };
48
50
  const { controller, dispatch } = this.ports;
51
+ // BEFORE the posture, and not behind its early return: `applyPendingPosture()` answers
52
+ // `null` for almost every turn, and a team-mode change that waited for this turn would
53
+ // otherwise be skipped by the `if (!applied) return` below and sit pending until the next
54
+ // `prompt()` safety net (team-mode-toggle-keys R-10).
55
+ this.landTeamMode();
49
56
  const applied = controller.applyPendingPosture();
50
57
  if (!applied)
51
58
  return;
@@ -59,6 +66,24 @@ export class InteractionCoordinator {
59
66
  });
60
67
  dispatch({ type: 'pushToast', level: 'info', text: postureAppliedToast(applied.effective) });
61
68
  }
69
+ /** Land the team-mode change that was asked for during the turn, and say what happened. */
70
+ landTeamMode() {
71
+ const { controller, dispatch } = this.ports;
72
+ // Optional on purpose: a controller double or an older host has no team switch.
73
+ const outcome = controller.applyPendingTeamMode?.();
74
+ if (!outcome)
75
+ return;
76
+ const toast = outcome.ok
77
+ ? teamModeToast(outcome, {
78
+ request: outcome.on ? 'on' : 'off',
79
+ firstOnThisSession: false,
80
+ max: controller.getTeamMode?.().max ?? 1,
81
+ })
82
+ : { level: 'warn',
83
+ text: `Team mode change was dropped: ${teamRefusalText(outcome.refusal)}` };
84
+ if (toast)
85
+ dispatch({ type: 'pushToast', level: toast.level, text: toast.text });
86
+ }
62
87
  /** Send a message to the agent, bypassing slash parsing. */
63
88
  submit(message, opts = {}) {
64
89
  const { controller, dispatch, notify } = this.ports;
@@ -73,12 +98,23 @@ export class InteractionCoordinator {
73
98
  const card = opts.invocation && invocationCardsEnabled()
74
99
  ? buildInvocationCard(opts.invocation, (text) => redactText(text, getSecrets()))
75
100
  : undefined;
76
- const shown = card?.commandLine ?? message;
101
+ const attachments = opts.attachments;
102
+ // With attachments the bubble and the up-arrow history show the user's own words; `message`
103
+ // may also carry a host-built path block the user never typed.
104
+ const shown = card?.commandLine ?? attachments?.displayText ?? message;
105
+ const metas = attachments?.metas.length ? { attachments: attachments.metas } : {};
77
106
  if (this.phaseValue === 'running' || controller.isCompactionBusy?.()) {
78
107
  try {
79
- const queueId = controller.queueUserMessage(message);
80
- dispatch({ type: 'steerQueued', queueId, text: shown, ...(card ? { invocation: card } : {}) });
81
- return { accepted: true };
108
+ // Called with exactly the pre-feature arguments unless parts exist.
109
+ const queueId = attachments?.parts
110
+ ? controller.queueUserMessage(message, attachments.parts)
111
+ : controller.queueUserMessage(message);
112
+ dispatch({
113
+ type: 'steerQueued', queueId, text: shown, ...(card ? { invocation: card } : {}), ...metas,
114
+ });
115
+ // The receipt id is only surfaced for attachment-bearing messages (the host needs it to
116
+ // retain their bytes for withdrawal); plain messages keep the exact legacy outcome.
117
+ return attachments ? { accepted: true, queueId } : { accepted: true };
82
118
  }
83
119
  catch (error) {
84
120
  const reason = error instanceof Error ? error.message : String(error);
@@ -93,10 +129,10 @@ export class InteractionCoordinator {
93
129
  if (opts.userInitiated !== false) {
94
130
  // A card's payload must never reach the up-arrow history (the same gate as the terminal).
95
131
  if (!card)
96
- appendPrompt(message);
132
+ appendPrompt(attachments?.displayText ?? message);
97
133
  controller.setSubmitCount(bumpSubmitCount());
98
134
  }
99
- dispatch({ type: 'submit', text: shown, ...(card ? { invocation: card } : {}) });
135
+ dispatch({ type: 'submit', text: shown, ...(card ? { invocation: card } : {}), ...metas });
100
136
  const pre = controller.preflight();
101
137
  if (!pre.ok) {
102
138
  dispatch({ type: 'runError' });
@@ -106,7 +142,10 @@ export class InteractionCoordinator {
106
142
  return { accepted: true };
107
143
  }
108
144
  // Fire-and-forget: events drive the UI. prompt() never rejects.
109
- void controller.prompt(message, { todoPolicy: opts.todoPolicy ?? 'new-task' }).then((outcome) => {
145
+ void controller.prompt(message, {
146
+ todoPolicy: opts.todoPolicy ?? 'new-task',
147
+ ...(attachments?.parts ? { parts: attachments.parts } : {}),
148
+ }).then((outcome) => {
110
149
  if (this.disposed || sequence !== this.sequence)
111
150
  return;
112
151
  if (outcome?.status !== 'not-started')