@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
@@ -0,0 +1,221 @@
1
+ /**
2
+ * TeamModeWiring - the stateful half of the team mode switch (team-mode-toggle-keys 3.4).
3
+ *
4
+ * ASCII ONLY (`agent/` is inside the glyph scanner's scope).
5
+ *
6
+ * The controller is far over the repo's size limit, so the switch's state and rules live
7
+ * here and the controller only forwards, the same shape as `GovernanceWiring`. The DECISIONS
8
+ * are not here either: `planTeamMode` (tui/model/team/team-mode.ts) is a pure function the
9
+ * 28-row truth table pins. This class holds the three things a pure function cannot:
10
+ * `armed`, `lastCount`, `pending`, and the subscription that tells a surface to repaint.
11
+ *
12
+ * TWO LAYERS KEEP THE INVARIANT `armed => registered && enabled && count <= max` (I-4):
13
+ *
14
+ * - a READ-SIDE derivation, `effectiveForced`, is the only way anything reads the armed
15
+ * state. The system prompt composer feeds it the `config` ARGUMENT, so a prompt that is
16
+ * pre-built for a settings snapshot is already right before that snapshot is applied;
17
+ * - a WRITE-SIDE `reconcile()` that `rebuildSystemPrompt()` runs first, so the stored state
18
+ * catches up and "off, then on again" does not resurrect a mode the user lost.
19
+ *
20
+ * `config.team` has TWO runtime writers (`setTeamConfig`, and the settings snapshot apply
21
+ * that bypasses it). `rebuildSystemPrompt()` is the one place both pass through, which is
22
+ * why the reconcile lives behind it rather than behind `setTeamConfig`.
23
+ */
24
+ import { clampTeamCount, planTeamMode, } from '@aragon-agent/tui/model/team/team-mode';
25
+ /**
26
+ * The armed state as the prompt and the status bar may see it.
27
+ *
28
+ * `null` when the session cannot honour it (tool not registered, capability off in
29
+ * Settings), and a count narrowed to the CURRENT ceiling otherwise. Returns the stored
30
+ * object itself when nothing needs narrowing, so identity-based callers stay stable.
31
+ */
32
+ export function effectiveForced(raw, team, registered) {
33
+ if (!raw || !registered || team.enabled === false)
34
+ return null;
35
+ const ceiling = Math.max(1, team.maxSubagents);
36
+ return raw.count <= ceiling ? raw : { count: ceiling };
37
+ }
38
+ export class TeamModeWiring {
39
+ deps;
40
+ armed = null;
41
+ lastCount;
42
+ pending = null;
43
+ view = null;
44
+ lastEmitted = null;
45
+ listeners = new Set();
46
+ constructor(deps) {
47
+ this.deps = deps;
48
+ this.lastCount = clampTeamCount(deps.defaultCount, deps.getTeamConfig().maxSubagents);
49
+ }
50
+ /**
51
+ * Take the baseline view. Called once the controller is fully built, so the first change
52
+ * after construction is a real change rather than "the baseline appeared".
53
+ */
54
+ prime() {
55
+ this.view = this.computeView();
56
+ this.lastEmitted = JSON.stringify(this.view);
57
+ }
58
+ /** The stored value, un-narrowed. Only the prompt composer and `reconcile` read it. */
59
+ rawForced() {
60
+ return this.armed === null ? null : { count: this.armed };
61
+ }
62
+ /** The armed state the session actually honours (I-4, read side). */
63
+ getForced() {
64
+ return effectiveForced(this.rawForced(), this.deps.getTeamConfig(), this.deps.isRegistered());
65
+ }
66
+ /** The cached view: recomputed on rebuild and on pending changes, never during render. */
67
+ getView() {
68
+ if (this.view === null)
69
+ this.prime();
70
+ return this.view;
71
+ }
72
+ /** Plan and carry out one request. The outcome tells the caller what to say. */
73
+ request(req) {
74
+ const plan = planTeamMode(this.state(), req);
75
+ this.execute(plan.action);
76
+ return plan.outcome;
77
+ }
78
+ /**
79
+ * Arm with `count`, narrowed to `[1, team.maxSubagents]`. Returns the count adopted.
80
+ *
81
+ * A DIRECT WRITE, so it clears `pending` (I-14): `/team <brief>` arms and then submits, and
82
+ * a stale pending change must not be applied by the submit's safety net one line later.
83
+ */
84
+ arm(count) {
85
+ const adopted = clampTeamCount(count, this.deps.getTeamConfig().maxSubagents);
86
+ this.armed = adopted;
87
+ this.lastCount = adopted;
88
+ this.pending = null;
89
+ this.deps.rebuildPrompt();
90
+ return adopted;
91
+ }
92
+ /** Disarm. IDEMPOTENT: disarming an unarmed session with nothing pending rewrites nothing. */
93
+ disarm() {
94
+ const hadPending = this.pending !== null;
95
+ if (this.armed === null && !hadPending)
96
+ return;
97
+ const wasArmed = this.armed !== null;
98
+ this.armed = null;
99
+ this.pending = null;
100
+ if (wasArmed) {
101
+ this.deps.rebuildPrompt();
102
+ return;
103
+ }
104
+ // Only a pending change disappeared: the prompt is unchanged, the view is not.
105
+ this.emitIfChanged();
106
+ }
107
+ /**
108
+ * Land the pending change. Re-plans from the TARGET with `running: false` rather than
109
+ * replaying the stored action: while it waited, the capability, the ceiling or the GOVERN
110
+ * gate may have moved, and only a fresh plan gets `enableCapability` and the refusals right.
111
+ *
112
+ * `null` = nothing was pending, or it had already become a no-op. A refusal is returned so
113
+ * the caller can say the change was dropped.
114
+ */
115
+ applyPending() {
116
+ const target = this.pending;
117
+ if (!target)
118
+ return null;
119
+ const req = target.on ? { kind: 'on', count: target.count } : { kind: 'off' };
120
+ const plan = planTeamMode({ ...this.state(), running: false, pending: null }, req);
121
+ this.pending = null;
122
+ this.execute(plan.action);
123
+ // Cheap and idempotent: covers the branches that did not rebuild the prompt.
124
+ this.emitIfChanged();
125
+ if (!plan.outcome.ok)
126
+ return plan.outcome;
127
+ return plan.outcome.effect === 'unchanged' ? null : plan.outcome;
128
+ }
129
+ /**
130
+ * Bring the STORED state in line with the live configuration (I-4, write side).
131
+ *
132
+ * Runs first in `rebuildSystemPrompt()`. It only touches stored state, never the prompt
133
+ * string: when a settings snapshot supplied a pre-built prompt, that prompt was derived
134
+ * through `effectiveForced` and already agrees with what this solidifies.
135
+ */
136
+ reconcile() {
137
+ const team = this.deps.getTeamConfig();
138
+ if (!this.deps.isRegistered() || team.enabled === false) {
139
+ this.armed = null;
140
+ this.pending = null;
141
+ return;
142
+ }
143
+ const max = Math.max(1, team.maxSubagents);
144
+ if (this.armed !== null)
145
+ this.armed = Math.min(this.armed, max);
146
+ if (this.pending)
147
+ this.pending = { ...this.pending, count: Math.min(this.pending.count, max) };
148
+ this.lastCount = Math.min(this.lastCount, max);
149
+ }
150
+ subscribe(listener) {
151
+ this.listeners.add(listener);
152
+ return () => { this.listeners.delete(listener); };
153
+ }
154
+ /**
155
+ * Recompute the view and tell subscribers if it differs from the last one they were told.
156
+ * Called at the END of `rebuildSystemPrompt()` and when `pending` moves, and nowhere else
157
+ * (I-5): one funnel, so a surface never needs "did every call site remember to notify".
158
+ */
159
+ emitIfChanged() {
160
+ this.view = this.computeView();
161
+ const key = JSON.stringify(this.view);
162
+ if (key === this.lastEmitted)
163
+ return;
164
+ this.lastEmitted = key;
165
+ for (const listener of [...this.listeners]) {
166
+ try {
167
+ listener();
168
+ }
169
+ catch { /* a repaint hook must not break a mode change */ }
170
+ }
171
+ }
172
+ state() {
173
+ const team = this.deps.getTeamConfig();
174
+ return {
175
+ registered: this.deps.isRegistered(),
176
+ capability: team.enabled,
177
+ blocked: this.deps.isBlocked(),
178
+ armed: this.armed,
179
+ lastCount: this.lastCount,
180
+ pending: this.pending,
181
+ running: this.deps.isBusy(),
182
+ max: team.maxSubagents,
183
+ };
184
+ }
185
+ execute(action) {
186
+ switch (action.type) {
187
+ case 'none':
188
+ return;
189
+ case 'arm':
190
+ if (action.enableCapability)
191
+ this.deps.enableCapability();
192
+ this.arm(action.count);
193
+ return;
194
+ case 'disarm':
195
+ this.disarm();
196
+ return;
197
+ case 'defer':
198
+ // NO prompt rebuild: a turn is in flight, and rewriting the prompt mid-turn is exactly
199
+ // what deferring avoids (I-8).
200
+ this.pending = action.target;
201
+ this.emitIfChanged();
202
+ return;
203
+ }
204
+ }
205
+ computeView() {
206
+ const team = this.deps.getTeamConfig();
207
+ const registered = this.deps.isRegistered();
208
+ const forced = this.getForced();
209
+ const blocked = this.deps.isBlocked();
210
+ return {
211
+ available: registered,
212
+ on: forced !== null,
213
+ paused: forced !== null && blocked,
214
+ count: clampTeamCount(forced?.count ?? this.lastCount, team.maxSubagents),
215
+ min: 1,
216
+ max: Math.max(1, team.maxSubagents),
217
+ pending: this.pending,
218
+ capability: team.enabled,
219
+ };
220
+ }
221
+ }
package/dist/app/App.js CHANGED
@@ -59,7 +59,9 @@ import { advanceBudget, decideFollowThrough, emptyBudget, } from '@aragon-agent/
59
59
  // THE THIRD LAYER OF FORCED TEAM MODE (team-command-forced-dispatch §3.7): the
60
60
  // decision and its two strings live in a pure module, so `App` gains wiring and
61
61
  // no policy. Imported beside the todo decision it shares one timer with.
62
- import { decideForcedDispatch, FORCED_NUDGE_NOTICE } from '../team/dispatch-gate.js';
62
+ import { buildDispatchNudge, decideForcedDispatch, FORCED_NUDGE_NOTICE } from '../team/dispatch-gate.js';
63
+ import { teamToastTtlMs, useTeamMode } from './use-team-mode.js';
64
+ import { teamStatusFromView } from '@aragon-agent/tui/model/team/team-mode';
63
65
  import { FORCED_NUDGE_GRACE_MS } from '@aragon-agent/tui/model/team/limits';
64
66
  import { useTerminalSize } from '@aragon-agent/tui/ui/layout/useTerminalSize';
65
67
  import { useHeightStore } from '@aragon-agent/tui/ui/use-height-store';
@@ -604,6 +606,18 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
604
606
  drainCompactionQueue.current();
605
607
  });
606
608
  }, [controller]);
609
+ // THE TEAM MODE SWITCH (team-mode-toggle-keys): Ctrl+T, Ctrl+Up / Ctrl+Down and the
610
+ // deferred-change landing at `agent_end`. The view is read from the controller at render
611
+ // (never mirrored into `ViewState`); the agent subscription below never re-runs, so it
612
+ // reaches the hook through a ref assigned each render, like `submitRef`.
613
+ const teamKeys = useTeamMode({
614
+ controller,
615
+ pushToast: (level, text) => dispatch({ type: 'pushToast', level, text, ttlMs: teamToastTtlMs(level) }),
616
+ pushNotice: (level, text) => dispatch({ type: 'notice', level, text }),
617
+ canAct: () => !stateRef.current.overlay,
618
+ });
619
+ const teamKeysRef = useRef(teamKeys);
620
+ teamKeysRef.current = teamKeys;
607
621
  /**
608
622
  * Disarm an armed continuation. Idempotent; NEVER touches the budget — a
609
623
  * cancelled continuation was never issued, so it must not be charged (AC-18).
@@ -748,7 +762,14 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
748
762
  // by a whole turn and carry `errored` into the next one. It also keeps
749
763
  // `cancelFollowThrough()`'s callers at three: the gate reuses the timer
750
764
  // instead of adding a fourth canceller.
751
- const forced = controller.getForcedTeam();
765
+ // THE BASIS IS WHAT THE MODE WILL BE, not what it was when the turn began (I-9):
766
+ // a change asked for during this turn is still pending here, and nudging for a
767
+ // mode the user has already switched off - or for the old count - would start a
768
+ // forced turn they just cancelled. GOVERN drops the block, so `paused` is not armed.
769
+ const teamNow = controller.getTeamMode?.();
770
+ const teamBasis = teamNow ? (teamNow.pending ?? { on: teamNow.on, count: teamNow.count }) : null;
771
+ const forced = teamNow && teamBasis && teamBasis.on && !teamNow.paused
772
+ ? { count: teamBasis.count } : null;
752
773
  const gate = decideForcedDispatch({
753
774
  armed: forced !== null,
754
775
  count: forced?.count ?? 0,
@@ -824,9 +845,22 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
824
845
  followTimer.current = null;
825
846
  if (controller.isRunning() || controller.isCompactionBusy?.())
826
847
  return;
827
- submitRef.current(gate.message, { userInitiated: false, todoPolicy: 'continue' });
848
+ // THE THIRD RE-CHECK (I-13): the grace window is open to the user, and a
849
+ // Ctrl+T pressed in it takes effect at once because nothing is running. Read
850
+ // the mode NOW, not the value the decision was made on, and word the nudge with
851
+ // the count it has now.
852
+ const live = controller.getTeamMode?.();
853
+ if (!live || !live.on || live.paused)
854
+ return;
855
+ submitRef.current(buildDispatchNudge(live.count), {
856
+ userInitiated: false, todoPolicy: 'continue',
857
+ });
828
858
  }, FORCED_NUDGE_GRACE_MS);
829
859
  }
860
+ // A team-mode change asked for during the turn lands here, AFTER the gate above
861
+ // read its basis (I-9). The posture lands next: a pending GOVERN entry that
862
+ // arrives with it is reported by the same toast channel, not silently swallowed.
863
+ teamKeysRef.current.onTurnEnd();
830
864
  // A deferred `plan -> build` (or any posture change that waited for a governed
831
865
  // stage, governance-mode D-23) becomes real here and nowhere else (§3.2).
832
866
  const applied = controller.applyPendingPosture();
@@ -2523,6 +2557,15 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2523
2557
  applyPosture(nextPosture(postureNow.pending ?? postureNow.effective, controller.getPostureCycle()));
2524
2558
  return;
2525
2559
  }
2560
+ // Team mode: Ctrl+T switches it on/off, Ctrl+Up / Ctrl+Down sets how many subagents each
2561
+ // message fans out to (team-mode-toggle-keys D-1 / D-3). THREE CONSEQUENCES OF THIS SPOT
2562
+ // are deliberate: `tooSmall` already returned above (the keys are inert, like Ctrl+N and
2563
+ // Ctrl+R); an open overlay makes `canAct()` false (I-7) - unlike the old Ctrl+T branch,
2564
+ // which had no overlay guard; and the help/plan/queue overlays consume Ctrl+Up/Down in
2565
+ // their own paging block earlier, which is the intended precedence. `PromptInput` ignores
2566
+ // both keys so a draft's history and a popup's highlight never also move (I-6).
2567
+ if (teamKeys.handleKey(input, key))
2568
+ return;
2526
2569
  // Moved off Ctrl+L by D-1, because Ctrl+L is the branch key now.
2527
2570
  //
2528
2571
  // Ctrl+R, NOT Ctrl+Shift+L: legacy encodings deliver 0x0c for both, so a
@@ -2560,7 +2603,10 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2560
2603
  return;
2561
2604
  }
2562
2605
  }
2563
- if (key.ctrl && (input === 't' || input === 'T')) {
2606
+ // Alt+T, which used to be Ctrl+T (that key is the team switch now). Two byte forms: the
2607
+ // `meta` flag Ink sets after stripping the ESC, and the raw `ESC t` some stacks deliver
2608
+ // whole. `PromptInput` carries the matching guard, or the `t` would also be typed.
2609
+ if ((key.meta && !key.ctrl && input.toLowerCase() === 't') || input === '\x1bt') {
2564
2610
  const revealing = !stateRef.current.thinkingVisible;
2565
2611
  dispatch({ type: 'toggleThinking' });
2566
2612
  // Printed history never changes, so say what the toggle actually reaches.
@@ -2945,7 +2991,9 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2945
2991
  // THE DRAWER (tui-shortcut-drawer-and-task-summary D-4): it rides the SAME
2946
2992
  // overlay slot as `/help` and `/agents`, so it needs no new frame shape, no
2947
2993
  // second scroll authority and no geometry change in `ScrollViewport`.
2948
- overlay === 'shortcuts' ? (_jsx(ShortcutPanel, { isActive: !tooSmall, cols: viewCols, maxRows: overlayMaxRows, theme: theme, caps: caps, native: native, running: running, query: shortcutQuery, task: taskSectionFrom({
2994
+ overlay === 'shortcuts' ? (_jsx(ShortcutPanel, { isActive: !tooSmall, cols: viewCols, maxRows: overlayMaxRows, theme: theme, caps: caps, native: native, running: running,
2995
+ // Only the team-size row reads it: dim until team mode is on (team-mode-toggle-keys D-13).
2996
+ team: { available: teamKeys.view.available, on: teamKeys.view.on }, query: shortcutQuery, task: taskSectionFrom({
2949
2997
  view: state.taskSummary,
2950
2998
  pending: state.taskSummaryPending,
2951
2999
  enabled: cfg.taskSummary?.enabled !== false,
@@ -2972,7 +3020,7 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2972
3020
  // an untouched save writes a value the user never chose.
2973
3021
  //
2974
3022
  // FROM `ViewState`, NOT FROM `cfg`. `thinkingVisible` is session state
2975
- // that `Ctrl+T` also writes, and there is no controller setter to keep
3023
+ // that `Alt+T` also writes, and there is no controller setter to keep
2976
3024
  // `cfg` in step — so seeding from the config would show the LAUNCH
2977
3025
  // value under a transcript that has been toggled since, and an
2978
3026
  // untouched save would then quietly toggle it back.
@@ -3118,13 +3166,6 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3118
3166
  railRows: native ? (nativeBudget?.band.railRows ?? 0) : (fullscreenRailVisible ? railRows : 0),
3119
3167
  width: native ? (nativeBudget?.band.railCols ?? 0) : railWidth,
3120
3168
  });
3121
- // THE FORCED-MODE CHIP'S SOURCE (team-command-forced-dispatch §3.8 / D-9),
3122
- // read from the controller on every frame: `armForcedTeam()` writes no
3123
- // `ViewState`, so a mirror would have to be kept in step by hand - which is the
3124
- // double-truth this design deletes elsewhere. It is handed to `StatusBar`, which
3125
- // plans the primary row from its own props (a copy on `statusInput` above would
3126
- // be a field nothing renders).
3127
- const forcedTeam = controller.getForcedTeam();
3128
3169
  const statusInput = {
3129
3170
  columns: viewCols, phase: state.runPhase, pendingCount: state.pendingSteering.length,
3130
3171
  context: state.context, usageTotal: state.usageTotal, thinkingLevel: cfg.thinkingLevel,
@@ -3194,7 +3235,7 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3194
3235
  // partially stale. The window and its `known` flag now travel INSIDE
3195
3236
  // it, resolved by the meter - which is what makes the user's
3196
3237
  // `contextWindow` override reach the bar.
3197
- context: state.context, status: state.status, elapsedMs: elapsedMs, thinkingLevel: cfg.thinkingLevel, tokPerSec: tokPerSec, theme: theme, caps: caps, scrolledLines: scrolledLines, redrawNonce: redrawNonce, agentMode: state.posture, pendingAgentMode: state.pendingPosture, governance: state.governance, ...(forcedTeam ? { forcedTeam } : {}), ecoRung: governor.rung, ...(state.team
3238
+ context: state.context, status: state.status, elapsedMs: elapsedMs, thinkingLevel: cfg.thinkingLevel, tokPerSec: tokPerSec, theme: theme, caps: caps, scrolledLines: scrolledLines, redrawNonce: redrawNonce, agentMode: state.posture, pendingAgentMode: state.pendingPosture, governance: state.governance, ...(teamKeys.view.available ? { team: teamStatusFromView(teamKeys.view) } : {}), ecoRung: governor.rung, ...(state.team
3198
3239
  ? {
3199
3240
  // `rosterCounts`, NOT a fourth inline phase filter (A-1): the chip and
3200
3241
  // the roster header above it must never disagree.
@@ -0,0 +1,53 @@
1
+ /**
2
+ * `useTeamMode`: the terminal's half of the team mode switch (team-mode-toggle-keys 3.5.1).
3
+ *
4
+ * ASCII ONLY (`app/` is inside the glyph scanner's scope).
5
+ *
6
+ * `App.tsx` is far over the repo's size limit, so the key recognition, the toast policy and
7
+ * the subscription live here and `App` only wires the result in. The DECISIONS are not here:
8
+ * `planTeamMode` (pure) decides, `TeamModeWiring` (controller) carries out, and this hook is
9
+ * the thin adapter between a keystroke and one `controller.setTeamMode(request)`.
10
+ *
11
+ * EVERY CONTROLLER MEMBER IS OPTIONAL (D-17). Several App-level tests hand `App` a
12
+ * hand-written controller stub that implements only what they need; an unconditional call
13
+ * would throw `is not a function` at render. A controller without the members reads as "this
14
+ * session has no team switch": the view is unavailable, the keys do nothing and no toast
15
+ * appears, so those sessions render the bytes they always did (I-10).
16
+ */
17
+ import { type TeamModeRequest, type TeamModeView } from '@aragon-agent/tui/model/team/team-mode';
18
+ import type { AgentController } from '../agent/controller.js';
19
+ /** The slice of Ink's `Key` this hook reads; structural so tests need not import Ink. */
20
+ export interface TeamKeyLike {
21
+ ctrl: boolean;
22
+ meta: boolean;
23
+ shift: boolean;
24
+ upArrow: boolean;
25
+ downArrow: boolean;
26
+ }
27
+ export type TeamToastLevel = 'info' | 'warn';
28
+ export type TeamModeControllerPort = Partial<Pick<AgentController, 'getTeamMode' | 'setTeamMode' | 'applyPendingTeamMode' | 'subscribeTeamMode'>>;
29
+ export interface UseTeamModeArgs {
30
+ controller: TeamModeControllerPort;
31
+ /** App supplies the toast with the right ttl for the level (see `teamToastTtlMs`). */
32
+ pushToast(level: TeamToastLevel, text: string): void;
33
+ /**
34
+ * A full-width transcript line. Used once per session for the cost disclosure: a toast is
35
+ * clipped to 32 cells in the status row, and that sentence must not be clipped away.
36
+ */
37
+ pushNotice?(level: TeamToastLevel, text: string): void;
38
+ /** False while an overlay owns the keyboard (I-7). `tooSmall` is handled by the caller. */
39
+ canAct(): boolean;
40
+ }
41
+ export interface UseTeamMode {
42
+ view: TeamModeView;
43
+ request(req: TeamModeRequest): void;
44
+ /** True when the key was a team-mode key and has been consumed. */
45
+ handleKey(input: string, key: TeamKeyLike): boolean;
46
+ /** Call at `agent_end`: lands a change that was asked for during the turn. */
47
+ onTurnEnd(): void;
48
+ }
49
+ /** A held key repeats at roughly 30 Hz; the same limit message may appear once per window. */
50
+ export declare const TEAM_LIMIT_TOAST_COOLDOWN_MS = 1500;
51
+ /** How long each level stays on screen. Refusals are longer: they have to be read. */
52
+ export declare function teamToastTtlMs(level: TeamToastLevel): number;
53
+ export declare function useTeamMode(args: UseTeamModeArgs): UseTeamMode;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * `useTeamMode`: the terminal's half of the team mode switch (team-mode-toggle-keys 3.5.1).
3
+ *
4
+ * ASCII ONLY (`app/` is inside the glyph scanner's scope).
5
+ *
6
+ * `App.tsx` is far over the repo's size limit, so the key recognition, the toast policy and
7
+ * the subscription live here and `App` only wires the result in. The DECISIONS are not here:
8
+ * `planTeamMode` (pure) decides, `TeamModeWiring` (controller) carries out, and this hook is
9
+ * the thin adapter between a keystroke and one `controller.setTeamMode(request)`.
10
+ *
11
+ * EVERY CONTROLLER MEMBER IS OPTIONAL (D-17). Several App-level tests hand `App` a
12
+ * hand-written controller stub that implements only what they need; an unconditional call
13
+ * would throw `is not a function` at render. A controller without the members reads as "this
14
+ * session has no team switch": the view is unavailable, the keys do nothing and no toast
15
+ * appears, so those sessions render the bytes they always did (I-10).
16
+ */
17
+ import { useCallback, useEffect, useReducer, useRef } from 'react';
18
+ import { UNAVAILABLE_TEAM_VIEW, teamModeFirstOnNotice, teamModeToast, teamRefusalText, } from '@aragon-agent/tui/model/team/team-mode';
19
+ /** A held key repeats at roughly 30 Hz; the same limit message may appear once per window. */
20
+ export const TEAM_LIMIT_TOAST_COOLDOWN_MS = 1500;
21
+ /** How long each level stays on screen. Refusals are longer: they have to be read. */
22
+ export function teamToastTtlMs(level) {
23
+ return level === 'warn' ? 3500 : 1800;
24
+ }
25
+ /** Which cooldown bucket an outcome belongs to, or null when it is not a repeatable limit. */
26
+ function limitKindOf(req, outcome) {
27
+ if (req.kind !== 'step')
28
+ return null;
29
+ if (!outcome.ok)
30
+ return outcome.refusal === 'off' ? 'off' : null;
31
+ if (outcome.effect !== 'unchanged')
32
+ return null;
33
+ return outcome.clamped === 'min' ? 'min' : 'max';
34
+ }
35
+ export function useTeamMode(args) {
36
+ const { controller } = args;
37
+ const [, bump] = useReducer((n) => n + 1, 0);
38
+ const argsRef = useRef(args);
39
+ argsRef.current = args;
40
+ const lastLimitToast = useRef({ max: 0, min: 0, off: 0 });
41
+ const announcedOn = useRef(false);
42
+ // The view is read at render and never mirrored into App state: a mirror is a second copy
43
+ // that can disagree with the controller (the defect the switch's single source removes).
44
+ const view = controller.getTeamMode?.() ?? UNAVAILABLE_TEAM_VIEW;
45
+ useEffect(() => controller.subscribeTeamMode?.(() => bump()), [controller]);
46
+ const request = useCallback((req) => {
47
+ const live = argsRef.current.controller;
48
+ if (!live.setTeamMode)
49
+ return;
50
+ const outcome = live.setTeamMode(req);
51
+ const now = Date.now();
52
+ const limit = limitKindOf(req, outcome);
53
+ if (limit !== null) {
54
+ // Repeats of the SAME limit message inside the window are dropped, not queued.
55
+ if (now - lastLimitToast.current[limit] < TEAM_LIMIT_TOAST_COOLDOWN_MS)
56
+ return;
57
+ lastLimitToast.current[limit] = now;
58
+ }
59
+ const max = live.getTeamMode?.().max ?? 1;
60
+ const first = outcome.ok && outcome.effect === 'applied' && outcome.on
61
+ && !outcome.wasOn && !announcedOn.current;
62
+ const ctx = { request: req.kind, firstOnThisSession: first, max };
63
+ const toast = teamModeToast(outcome, ctx);
64
+ if (first)
65
+ announcedOn.current = true;
66
+ if (toast)
67
+ argsRef.current.pushToast(toast.level, toast.text);
68
+ const notice = teamModeFirstOnNotice(outcome, ctx);
69
+ if (notice)
70
+ argsRef.current.pushNotice?.('info', notice);
71
+ }, []);
72
+ const handleKey = useCallback((input, key) => {
73
+ if (!argsRef.current.canAct())
74
+ return false;
75
+ const port = argsRef.current.controller;
76
+ // A session with no team switch leaves both keys free for whoever else wants them.
77
+ if (!port.setTeamMode)
78
+ return false;
79
+ if (key.ctrl && !key.meta && input.toLowerCase() === 't') {
80
+ request({ kind: 'toggle' });
81
+ return true;
82
+ }
83
+ if (key.ctrl && !key.meta && !key.shift && (key.upArrow || key.downArrow)) {
84
+ request({ kind: 'step', delta: key.upArrow ? 1 : -1 });
85
+ return true;
86
+ }
87
+ return false;
88
+ }, [request]);
89
+ const onTurnEnd = useCallback(() => {
90
+ const outcome = argsRef.current.controller.applyPendingTeamMode?.();
91
+ if (!outcome)
92
+ return;
93
+ if (!outcome.ok) {
94
+ argsRef.current.pushToast('warn', `Team mode change was dropped: ${teamRefusalText(outcome.refusal)}`);
95
+ return;
96
+ }
97
+ const max = argsRef.current.controller.getTeamMode?.().max ?? 1;
98
+ const toast = teamModeToast(outcome, {
99
+ request: outcome.on ? 'on' : 'off',
100
+ firstOnThisSession: false,
101
+ max,
102
+ });
103
+ if (toast)
104
+ argsRef.current.pushToast(toast.level, toast.text);
105
+ }, []);
106
+ return { view, request, handleKey, onTurnEnd };
107
+ }
@@ -45,7 +45,7 @@ export const BUILTIN_COMMAND_CATALOG = [
45
45
  { name: 'prompts', aliases: [], description: 'Quick prompt library: pick, list, add, edit, remove, reorder' },
46
46
  { name: 'agents', aliases: [], description: 'Open the subagent board: every child, its facts and its timeline' },
47
47
  { name: 'subagent', aliases: [], description: 'Deprecated alias of /team - same arguments' },
48
- { name: 'team', aliases: [], description: 'Force team mode and start now: /team <brief>; /team [on|off|status]' },
48
+ { name: 'team', aliases: [], description: 'Force team mode and start now: /team <brief>; /team [on [n]|off|status]' },
49
49
  { name: 'gov', aliases: [], description: 'Governed multi-agent team: /gov help' },
50
50
  { name: 'keys', aliases: [], description: 'List every keyboard shortcut (opens the drawer)' },
51
51
  { name: 'task', aliases: [], description: 'Show the header task summary (/task refresh regenerates it)' },
@@ -37,10 +37,12 @@
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 type { CommandContext, CommandRegistry } from './registry.js';
46
48
  /**