@aragon-agent/cli 0.6.48 → 0.6.49

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 (70) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/agent/controller.d.ts +21 -0
  3. package/dist/agent/controller.js +35 -8
  4. package/dist/agent/governance-wiring.d.ts +2 -0
  5. package/dist/agent/governance-wiring.js +4 -0
  6. package/dist/app/App.d.ts +2 -4
  7. package/dist/app/App.js +207 -511
  8. package/dist/cli.js +2 -150
  9. package/dist/commands/catalog.d.ts +17 -0
  10. package/dist/commands/catalog.js +52 -0
  11. package/dist/commands/create-registry.d.ts +13 -0
  12. package/dist/commands/create-registry.js +19 -0
  13. package/dist/commands/governance-command.js +5 -1
  14. package/dist/commands/skills.js +18 -67
  15. package/dist/config/env.d.ts +2 -0
  16. package/dist/config/env.js +1 -1
  17. package/dist/fast/review-call.d.ts +6 -0
  18. package/dist/fast/review-call.js +10 -0
  19. package/dist/governance/engine/budget.d.ts +18 -6
  20. package/dist/governance/engine/budget.js +61 -19
  21. package/dist/governance/engine/engine-core.d.ts +8 -0
  22. package/dist/governance/engine/engine-core.js +29 -9
  23. package/dist/governance/engine/engine.d.ts +1 -0
  24. package/dist/governance/engine/engine.js +9 -10
  25. package/dist/governance/engine/inspector.js +4 -3
  26. package/dist/governance/engine/lifecycle.js +4 -2
  27. package/dist/governance/engine/report.js +7 -1
  28. package/dist/governance/engine/run-digest.js +2 -1
  29. package/dist/governance/engine/stage-runner.js +1 -1
  30. package/dist/governance/engine/submissions.d.ts +2 -0
  31. package/dist/governance/engine/submissions.js +22 -3
  32. package/dist/governance/engine/visibility.d.ts +10 -0
  33. package/dist/governance/engine/visibility.js +28 -0
  34. package/dist/governance/rules/settlement.d.ts +7 -0
  35. package/dist/governance/rules/settlement.js +24 -0
  36. package/dist/governance/tools/shared-tools.d.ts +2 -0
  37. package/dist/governance/tools/shared-tools.js +15 -1
  38. package/dist/governance/tools/submit-tools.js +14 -7
  39. package/dist/host/commands.d.ts +18 -0
  40. package/dist/host/commands.js +30 -0
  41. package/dist/host/controller-factory.d.ts +109 -0
  42. package/dist/host/controller-factory.js +159 -0
  43. package/dist/host/controller-feed.d.ts +122 -0
  44. package/dist/host/controller-feed.js +356 -0
  45. package/dist/host/index-build.d.ts +23 -0
  46. package/dist/host/index-build.js +35 -0
  47. package/dist/host/index.d.ts +21 -0
  48. package/dist/host/index.js +21 -0
  49. package/dist/host/interaction.d.ts +58 -0
  50. package/dist/host/interaction.js +165 -0
  51. package/dist/host/logging.d.ts +7 -0
  52. package/dist/host/logging.js +7 -0
  53. package/dist/host/prompts.d.ts +10 -0
  54. package/dist/host/prompts.js +9 -0
  55. package/dist/host/sessions.d.ts +87 -0
  56. package/dist/host/sessions.js +234 -0
  57. package/dist/host/settings.d.ts +104 -0
  58. package/dist/host/settings.js +235 -0
  59. package/dist/host/skills.d.ts +19 -0
  60. package/dist/host/skills.js +38 -0
  61. package/dist/skills/command-names.d.ts +19 -0
  62. package/dist/skills/command-names.js +28 -0
  63. package/dist/skills/invoke.d.ts +38 -0
  64. package/dist/skills/invoke.js +65 -0
  65. package/dist/team/overseer.d.ts +25 -1
  66. package/dist/team/overseer.js +38 -1
  67. package/dist/team/runtime.d.ts +2 -0
  68. package/dist/team/runtime.js +10 -7
  69. package/dist/team/subagent.js +2 -4
  70. package/package.json +3 -3
@@ -51,10 +51,11 @@ const TEST_DESCRIPTION = 'Submit your test report for ONE work package (call onc
51
51
  'skeletonRatio and skeletonEvidence from gov_scan. claims {kind, justification, against?} ' +
52
52
  'raises a claim the Inspector will rule on. A NOT ACCEPTED answer lists what to fix and ' +
53
53
  'costs nothing.';
54
- /** Run a normalizer, then forward the value to the engine exactly once on success. */
55
- function runSubmission(toolName, normalized, forward) {
56
- if (!normalized.ok)
57
- return textResult(formatNotAccepted(toolName, normalized.errors));
54
+ function runSubmission(call, normalized, forward) {
55
+ if (!normalized.ok) {
56
+ const text = formatNotAccepted(call.toolName, normalized.errors);
57
+ return textResult(call.engine.rejectInvalid(call.identity, call.params, text));
58
+ }
58
59
  return textResult(withNotes(forward(normalized.value), normalized.notes));
59
60
  }
60
61
  /** `gov_submit_work`: DEV (and the FIX developer). */
@@ -86,7 +87,9 @@ export function makeSubmitWorkTool(engine, identity) {
86
87
  required: ['wpId', 'summary'],
87
88
  },
88
89
  async execute(_id, params) {
89
- return runSubmission('gov_submit_work', normalizeWorkSubmission(params), (value) => engine.submitWork(identity, value));
90
+ const normalized = normalizeWorkSubmission(params);
91
+ const call = { engine, identity, toolName: 'gov_submit_work', params };
92
+ return runSubmission(call, normalized, (value) => engine.submitWork(identity, value));
90
93
  },
91
94
  };
92
95
  }
@@ -128,7 +131,9 @@ export function makeSubmitReviewTool(engine, identity) {
128
131
  required: ['wpId', 'verdict'],
129
132
  },
130
133
  async execute(_id, params) {
131
- return runSubmission('gov_submit_review', normalizeReviewSubmission(params), (value) => engine.submitReview(identity, value));
134
+ const normalized = normalizeReviewSubmission(params);
135
+ const call = { engine, identity, toolName: 'gov_submit_review', params };
136
+ return runSubmission(call, normalized, (value) => engine.submitReview(identity, value));
132
137
  },
133
138
  };
134
139
  }
@@ -165,7 +170,9 @@ export function makeSubmitTestTool(engine, identity) {
165
170
  required: ['wpId', 'verdict'],
166
171
  },
167
172
  async execute(_id, params) {
168
- return runSubmission('gov_submit_test', normalizeTestSubmission(params), (value) => engine.submitTest(identity, value));
173
+ const normalized = normalizeTestSubmission(params);
174
+ const call = { engine, identity, toolName: 'gov_submit_test', params };
175
+ return runSubmission(call, normalized, (value) => engine.submitTest(identity, value));
169
176
  },
170
177
  };
171
178
  }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The slash-command menu metadata the desktop composer shows.
3
+ *
4
+ * The built-in rows come from `commands/catalog.ts` (pure data, guarded against drift by
5
+ * `command-catalog.test.ts`, which compares it with the registry the terminal really builds):
6
+ * the registration path itself reaches Ink-layer modules, which the host closure may not (L9).
7
+ * Skill commands are derived with the SAME naming rule the registry uses (`skills/command-names`).
8
+ */
9
+ import type { SkillService } from '../skills/service.js';
10
+ export interface SlashCommandMeta {
11
+ name: string;
12
+ aliases: string[];
13
+ /** The registry's own text (may be in any language); the renderer prefers its dictionary. */
14
+ description: string;
15
+ }
16
+ export declare function listSlashCommands(options?: {
17
+ skills?: SkillService;
18
+ }): SlashCommandMeta[];
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The slash-command menu metadata the desktop composer shows.
3
+ *
4
+ * The built-in rows come from `commands/catalog.ts` (pure data, guarded against drift by
5
+ * `command-catalog.test.ts`, which compares it with the registry the terminal really builds):
6
+ * the registration path itself reaches Ink-layer modules, which the host closure may not (L9).
7
+ * Skill commands are derived with the SAME naming rule the registry uses (`skills/command-names`).
8
+ */
9
+ import { BUILTIN_COMMAND_CATALOG } from '../commands/catalog.js';
10
+ import { isInvocableSkill, shortSkillDescription, SKILLS_COMMAND_DESCRIPTION, skillCommandNames, } from '../skills/command-names.js';
11
+ export function listSlashCommands(options = {}) {
12
+ const commands = BUILTIN_COMMAND_CATALOG.map((c) => ({
13
+ name: c.name, aliases: [...c.aliases], description: c.description,
14
+ }));
15
+ if (!options.skills)
16
+ return commands;
17
+ const taken = new Set(commands.flatMap((c) => [c.name, ...c.aliases]));
18
+ commands.push({ name: 'skills', aliases: [], description: SKILLS_COMMAND_DESCRIPTION });
19
+ taken.add('skills');
20
+ for (const record of options.skills.list()) {
21
+ if (!isInvocableSkill(record))
22
+ continue;
23
+ const description = shortSkillDescription(record.description);
24
+ for (const name of skillCommandNames(record, (candidate) => taken.has(candidate))) {
25
+ taken.add(name);
26
+ commands.push({ name, aliases: [], description });
27
+ }
28
+ }
29
+ return commands;
30
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Controller + checkpoint-writer construction shared by every front end.
3
+ *
4
+ * MOVED, NOT REWRITTEN (desktop-electron-app Phase 0). `makeController` and
5
+ * `createSessionWriter` used to be private to `cli.tsx`; the Electron desktop host builds
6
+ * the same controller, so the ONE definition now lives here. The comments below are the
7
+ * originals - they record decisions (two approval channels, the R3 spread pair) that must
8
+ * not be re-derived by whoever copies this next.
9
+ *
10
+ * NO INK, NO TTY: this module is in the import closure of `host/index.ts`, which the
11
+ * layering gate (L9) keeps free of `ink` / `react` / `tui/ui/**`.
12
+ */
13
+ import type { AgentTool } from '@aragon-agent/core';
14
+ import type { HumanInputGate } from '@aragon-agent/tui/model/tools/human-input';
15
+ import { type HumanInputBridge } from '@aragon-agent/tui/model/tools/human-input';
16
+ import { AgentController } from '../agent/controller.js';
17
+ import { type CliFlags } from '../config/load.js';
18
+ import type { ToolPermission } from '../exec/permission.js';
19
+ import type { ToolHookRunner } from '../exec/hooks/tool-wrapper.js';
20
+ import type { ApprovalGate } from '../skills/service.js';
21
+ import { SessionCheckpointWriter, type LiveSessionView } from '../session/checkpoint.js';
22
+ import type { ToolGate } from '../tools/tool-gate.js';
23
+ import type { ConfirmRequest } from '../tools/index.js';
24
+ /** Re-exported so a host can name the controller type without a deep import. */
25
+ export type { AgentController };
26
+ /** The `--confirm` gate's late-bound handler. `null` until a human channel attaches. */
27
+ export interface ConfirmBridge {
28
+ handler: ((req: ConfirmRequest) => Promise<boolean>) | null;
29
+ }
30
+ /**
31
+ * The shipped package version, read from the `package.json` next to `dist/`.
32
+ * `src/host/` and `dist/host/` sit at the same depth, so one relative hop serves both.
33
+ */
34
+ export declare function readCliVersion(): string;
35
+ /**
36
+ * Build the controller for a mode.
37
+ *
38
+ * TWO DIFFERENT APPROVAL CHANNELS, AND THEY MUST NOT BE CONFLATED:
39
+ *
40
+ * `confirm` - the `--confirm` gate for mutating tools. Its `handler === null`
41
+ * fallback is `Promise.resolve(true)`, which is fine because that
42
+ * path is opt-in and only reachable with the TUI mounted.
43
+ *
44
+ * `approval` - the skill-install gate. It PROBES for a human first and denies
45
+ * when there is none (D17 / section 8.3.1). Passing the `confirm`
46
+ * closure here instead would inherit the auto-approve fallback
47
+ * and make `requireApproval: true` a no-op under `-p`, silently.
48
+ *
49
+ * `interactive: false` (the headless path) gets the deny-all gate, so a model
50
+ * calling `skill_install` in `-p` mode is refused with an actionable message
51
+ * instead of writing to disk unattended.
52
+ */
53
+ export declare function makeController(flags: CliFlags, opts?: {
54
+ interactive: boolean;
55
+ /**
56
+ * `aragon exec`'s tool policy (cli-integration-surface section 4.2). Spread into
57
+ * `ControllerDeps` so every other caller builds today's deps object exactly,
58
+ * which is what keeps the tool array provably unchanged for the TUI and `-p`.
59
+ */
60
+ permission?: ToolPermission;
61
+ /** `aragon exec --append-system-prompt` text. */
62
+ appendSystemPrompt?: string;
63
+ /**
64
+ * The bridge's three gates and its decision budget (headless-host-bridge
65
+ * section 2.6, step 6). ABSENT FOR EVERY OTHER CALLER - `runOneShot`, the TUI
66
+ * and every subcommand pass nothing - so the deny-all defaults below stay
67
+ * exactly what they are for them.
68
+ */
69
+ toolGate?: ToolGate;
70
+ toolGateForChild?: (label: string) => ToolGate;
71
+ approval?: ApprovalGate;
72
+ humanInput?: HumanInputGate;
73
+ decisionBudgetMs?: number;
74
+ /**
75
+ * `submit_result` and its prompt block (headless-request-scope-and-typed-result
76
+ * section 2.6 rows 11 and 17), or absent.
77
+ *
78
+ * BOTH OR NEITHER ARRIVES: `exec/index.ts` builds the tool and the block together
79
+ * from the same preflighted schema, and neither exists without `--result-schema`.
80
+ */
81
+ resultTool?: AgentTool;
82
+ structuredResultBlock?: string;
83
+ /**
84
+ * The caller's lifecycle hooks (headless-threads-and-lifecycle-hooks section 2.4.9).
85
+ * Absent for every caller except a bridge run's `makeExecController`.
86
+ */
87
+ hookRunner?: ToolHookRunner;
88
+ }): {
89
+ controller: AgentController;
90
+ confirmBridge: ConfirmBridge;
91
+ humanInputBridge: HumanInputBridge;
92
+ };
93
+ /** The second parameter of {@link makeController}. */
94
+ export type ControllerFactoryOptions = NonNullable<Parameters<typeof makeController>[1]>;
95
+ /**
96
+ * Build the checkpoint writer for one process (D-2 / D-21).
97
+ *
98
+ * ONE CONSTRUCTION SITE FOR TWO PATHS. The TUI and `-p` differ in exactly one
99
+ * thing - where `readView` gets its transcript - and in nothing else: the same
100
+ * `meta` fields, the same live model, the same todos, the same cwd. Writing the
101
+ * eight deps twice is how `meta.turns` would come to mean two things, which is
102
+ * the drift class D-9 exists to prevent for `applyRestoredSession`.
103
+ */
104
+ export declare function createSessionWriter(input: {
105
+ controller: AgentController;
106
+ readView: () => LiveSessionView | undefined;
107
+ readParentId: () => string | undefined;
108
+ startPinned: boolean;
109
+ }): SessionCheckpointWriter;
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Controller + checkpoint-writer construction shared by every front end.
3
+ *
4
+ * MOVED, NOT REWRITTEN (desktop-electron-app Phase 0). `makeController` and
5
+ * `createSessionWriter` used to be private to `cli.tsx`; the Electron desktop host builds
6
+ * the same controller, so the ONE definition now lives here. The comments below are the
7
+ * originals - they record decisions (two approval channels, the R3 spread pair) that must
8
+ * not be re-derived by whoever copies this next.
9
+ *
10
+ * NO INK, NO TTY: this module is in the import closure of `host/index.ts`, which the
11
+ * layering gate (L9) keeps free of `ink` / `react` / `tui/ui/**`.
12
+ */
13
+ import { readFileSync } from 'node:fs';
14
+ import { dirname, join } from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ import process from 'node:process';
17
+ import { DENY_ALL_HUMAN_INPUT } from '@aragon-agent/tui/model/tools/human-input';
18
+ import { AgentController, DENY_ALL_APPROVAL } from '../agent/controller.js';
19
+ import { loadConfig } from '../config/load.js';
20
+ import { getLogger } from '../logging/logger.js';
21
+ import { SessionCheckpointWriter } from '../session/checkpoint.js';
22
+ /**
23
+ * The shipped package version, read from the `package.json` next to `dist/`.
24
+ * `src/host/` and `dist/host/` sit at the same depth, so one relative hop serves both.
25
+ */
26
+ export function readCliVersion() {
27
+ try {
28
+ const here = dirname(fileURLToPath(import.meta.url));
29
+ const pkg = JSON.parse(readFileSync(join(here, '..', '..', 'package.json'), 'utf-8'));
30
+ return pkg.version ?? '0.0.0';
31
+ }
32
+ catch {
33
+ return '0.0.0';
34
+ }
35
+ }
36
+ const VERSION = readCliVersion();
37
+ /**
38
+ * Build the controller for a mode.
39
+ *
40
+ * TWO DIFFERENT APPROVAL CHANNELS, AND THEY MUST NOT BE CONFLATED:
41
+ *
42
+ * `confirm` - the `--confirm` gate for mutating tools. Its `handler === null`
43
+ * fallback is `Promise.resolve(true)`, which is fine because that
44
+ * path is opt-in and only reachable with the TUI mounted.
45
+ *
46
+ * `approval` - the skill-install gate. It PROBES for a human first and denies
47
+ * when there is none (D17 / section 8.3.1). Passing the `confirm`
48
+ * closure here instead would inherit the auto-approve fallback
49
+ * and make `requireApproval: true` a no-op under `-p`, silently.
50
+ *
51
+ * `interactive: false` (the headless path) gets the deny-all gate, so a model
52
+ * calling `skill_install` in `-p` mode is refused with an actionable message
53
+ * instead of writing to disk unattended.
54
+ */
55
+ export function makeController(flags, opts = { interactive: true }) {
56
+ const config = loadConfig(flags, { interactive: opts.interactive });
57
+ // The authoritative log level lands here (section 4.4.5). `installLogging()` only
58
+ // resolved a bootstrap level - it ran before commander and before `.env` were
59
+ // readable - and without this hand-off the fully resolved one never applies.
60
+ getLogger().reconfigure(config.log);
61
+ // Headless controllers never expose the task panel.
62
+ const todoPanelCapable = opts.interactive;
63
+ const confirmBridge = { handler: null };
64
+ // `cancelPending` is replaced by the App's own implementation on mount; this
65
+ // no-op keeps the object total so nothing has to null-check it.
66
+ const humanInputBridge = { handler: null, cancelPending: () => { } };
67
+ const controller = new AgentController(config, {
68
+ version: VERSION,
69
+ todoPanelCapable,
70
+ confirm: (req) => confirmBridge.handler ? confirmBridge.handler(req) : Promise.resolve(true),
71
+ // THE TWO CAN NEVER BOTH BE PRESENT: `interactive: false` is the only path
72
+ // that supplies a bridge gate, and the interactive branch is the only one that
73
+ // reads the overlay bridge. `??` keeps `-p`'s deny-all default byte-identical.
74
+ approval: opts.approval ??
75
+ (opts.interactive
76
+ ? {
77
+ // Read live on every call: the App's effect cleanup nulls the handler
78
+ // on unmount, and a cached `true` would keep the gate open after the
79
+ // human channel is gone.
80
+ canPrompt: () => confirmBridge.handler !== null,
81
+ request: (req) => confirmBridge.handler ? confirmBridge.handler(req) : Promise.resolve(false),
82
+ }
83
+ : DENY_ALL_APPROVAL),
84
+ notify: (level, text) => {
85
+ if (!opts.interactive)
86
+ process.stderr.write(`[skills] ${level}: ${text}\n`);
87
+ },
88
+ // A THIRD approval channel, and it must not be conflated with the other two.
89
+ // `confirm` auto-approves when unattached and `approval` denies; neither can
90
+ // render a question wizard or a plan card. Headless gets the fail-closed
91
+ // gate, whose STATIC `neverPrompts` is also what stops `createPlanTools`
92
+ // registering two tools the model could never use there.
93
+ humanInput: opts.humanInput ??
94
+ (opts.interactive
95
+ ? {
96
+ // Live probe, never cached - same contract as `approval` above.
97
+ canPrompt: () => humanInputBridge.handler !== null,
98
+ request: (req, signal) => humanInputBridge.handler
99
+ ? humanInputBridge.handler(req, signal)
100
+ : Promise.resolve(null),
101
+ }
102
+ : DENY_ALL_HUMAN_INPUT),
103
+ ...(opts.permission ? { permission: opts.permission } : {}),
104
+ ...(opts.appendSystemPrompt ? { appendSystemPrompt: opts.appendSystemPrompt } : {}),
105
+ // SPREAD, never `toolGate: opts.toolGate`: with no gate the deps bag has no
106
+ // such key, `createBuiltinTools` never enters its mapping branch, and the tool
107
+ // array stays provably identical outside bridge mode (I-1).
108
+ ...(opts.toolGate ? { toolGate: opts.toolGate } : {}),
109
+ ...(opts.toolGateForChild ? { toolGateForChild: opts.toolGateForChild } : {}),
110
+ ...(opts.decisionBudgetMs !== undefined ? { decisionBudgetMs: opts.decisionBudgetMs } : {}),
111
+ // THE R3 PAIR, AND THIS LINE IS THE DIFFERENCE BETWEEN A WORKING FEATURE AND A DEAD
112
+ // ONE (headless-request-scope-and-typed-result section 2.6 rows 11/17). This factory
113
+ // takes `deps` as a bag and FORWARDS ONLY WHAT IS NAMED HERE, so a new dep that is
114
+ // not spread below is dropped in silence: every unit test that stubs the factory
115
+ // keeps passing while the real binary never registers the tool. That is the D-12
116
+ // defect this project has already paid for once, which is why both keys are spread
117
+ // conditionally and adjacent to each other.
118
+ ...(opts.resultTool ? { resultTool: opts.resultTool } : {}),
119
+ ...(opts.structuredResultBlock
120
+ ? { structuredResultBlock: opts.structuredResultBlock }
121
+ : {}),
122
+ ...(opts.hookRunner ? { hookRunner: opts.hookRunner } : {}),
123
+ });
124
+ return { controller, confirmBridge, humanInputBridge };
125
+ }
126
+ /**
127
+ * Build the checkpoint writer for one process (D-2 / D-21).
128
+ *
129
+ * ONE CONSTRUCTION SITE FOR TWO PATHS. The TUI and `-p` differ in exactly one
130
+ * thing - where `readView` gets its transcript - and in nothing else: the same
131
+ * `meta` fields, the same live model, the same todos, the same cwd. Writing the
132
+ * eight deps twice is how `meta.turns` would come to mean two things, which is
133
+ * the drift class D-9 exists to prevent for `applyRestoredSession`.
134
+ */
135
+ export function createSessionWriter(input) {
136
+ const { controller } = input;
137
+ return new SessionCheckpointWriter({
138
+ readView: input.readView,
139
+ readHistory: () => controller.getSessionSnapshot(),
140
+ readTodos: () => controller.getTodoSnapshot()?.items ?? [],
141
+ // The verdicts travel with the plan; read from the STORE, not from the render
142
+ // projection, so a checkpoint taken while the capability is off still saves them.
143
+ readAcceptance: () => controller.getAcceptanceItems(),
144
+ // READ AT WRITE TIME: `/model` rebuilds the config, and a checkpoint that
145
+ // recorded the model from launch would name the wrong one after a switch.
146
+ readModel: () => {
147
+ const live = controller.getConfig();
148
+ return {
149
+ providerId: live.provider,
150
+ modelId: live.model,
151
+ ...(live.baseUrl ? { baseUrl: live.baseUrl } : {}),
152
+ };
153
+ },
154
+ readCwd: () => controller.getCwd(),
155
+ version: VERSION,
156
+ readParentId: input.readParentId,
157
+ startPinned: input.startPinned,
158
+ });
159
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Controller event -> `ViewAction` feed, independent of any UI framework.
3
+ *
4
+ * MOVED OUT OF `App.tsx`, NOT REWRITTEN (desktop-electron-app Phase 0). The terminal and the
5
+ * desktop host must turn the same engine events into the same view actions, or one of them
6
+ * silently renders a different conversation. Each `attach*Channel` below is the body of one
7
+ * former `useEffect` in `App.tsx`, with its original comments, and `App.tsx` now calls it.
8
+ *
9
+ * WHAT STAYS IN APP: follow-through, the forced-dispatch gate, interrupt gestures, run
10
+ * metrics and the human-request overlay are TUI interaction policy, not mapping. They plug
11
+ * in through {@link AgentChannelHooks} at the exact points the inline code used to run.
12
+ *
13
+ * NO INK, NO TTY, NO REACT (layering gate L9).
14
+ */
15
+ import type { AgentEvent } from '@aragon-agent/core';
16
+ import type { AgentController } from '../agent/controller.js';
17
+ import { type PatchSource, type ViewAction } from '@aragon-agent/tui/model/agent/reducer';
18
+ import type { ServiceSnapshot } from '@aragon-agent/tui/model/proc/types';
19
+ export type FeedDispatch = (action: ViewAction) => void;
20
+ export type Unsubscribe = () => void;
21
+ /**
22
+ * The streaming coalescer. Text / thinking / tool-output deltas arrive at pipe speed and
23
+ * are buffered then merged; everything else is dispatched immediately (the callers decide
24
+ * which is which). `intervalMs` is read AT ARM TIME so a governor that retunes the interval
25
+ * moves the next flush, not only the next mount.
26
+ */
27
+ export declare class ActionCoalescer {
28
+ private readonly dispatch;
29
+ private readonly intervalMs;
30
+ private pending;
31
+ private timer;
32
+ constructor(dispatch: FeedDispatch, intervalMs: () => number);
33
+ /** Buffer one action and arm the flush timer if it is not already armed. */
34
+ push(action: ViewAction): void;
35
+ /** Merge and dispatch everything buffered. Safe to call when empty. */
36
+ flush(): void;
37
+ }
38
+ /** Where the TUI's interaction policy hangs off the main agent channel. */
39
+ export interface AgentChannelHooks {
40
+ /** Every NON-STALE event, before it is reduced (run metrics, phase flags). */
41
+ beforeEvent?(event: AgentEvent): void;
42
+ /** Every produced action, before it is buffered or dispatched. */
43
+ onAction?(action: ViewAction): void;
44
+ /** After an `agent_end`'s actions were dispatched (follow-through, pending posture). */
45
+ afterAgentEnd?(): void;
46
+ }
47
+ /**
48
+ * The main run stream: generation guard, reduce, coalesce.
49
+ *
50
+ * THE GENERATION GUARD (I-7 / P1-7): `forceStop()` bumps the controller's generation, and
51
+ * everything the engine emits while it unwinds belongs to the run the user abandoned.
52
+ * `generation` is a LOCAL `let`, RE-READ on every event rather than captured once, so a
53
+ * force-stop makes stale events inert WITHOUT making the next run's events inert too.
54
+ */
55
+ export declare function attachAgentChannel(controller: AgentController, deps: {
56
+ dispatch: FeedDispatch;
57
+ coalescer: ActionCoalescer;
58
+ patchSource: PatchSource;
59
+ hooks?: AgentChannelHooks;
60
+ }): Unsubscribe;
61
+ /** Background services. `onService` lets the TUI keep its own id -> snapshot map. */
62
+ export declare function attachProcChannel(controller: AgentController, dispatch: FeedDispatch, onService?: (service: ServiceSnapshot) => void): Unsubscribe;
63
+ /**
64
+ * Team-mode event stream (team-subagents). A SEPARATE SUBSCRIPTION: `TeamEvent` is
65
+ * deliberately not a member of core's `AgentEvent`. Not routed through the coalescer -
66
+ * `agent_update` is already coalesced at the source at 120 ms per child.
67
+ */
68
+ export declare function attachTeamChannel(controller: AgentController, dispatch: FeedDispatch): Unsubscribe;
69
+ /**
70
+ * Governance event stream. CLI-LOCAL for the reason the team one is: `GovernanceEvent` is
71
+ * not a member of `AgentEvent`. Folds snapshots into the view, appends the four settlement
72
+ * cards (charter, phase, escalation, final) and clears the live snapshot when the run ends.
73
+ */
74
+ export declare function attachGovernanceChannel(controller: AgentController, dispatch: FeedDispatch): Unsubscribe;
75
+ /**
76
+ * Todo event stream. NOT through the coalescer: a `todo_write` is one deliberate act per
77
+ * step, and delaying the one surface the user watches a long task through is backwards.
78
+ */
79
+ export declare function attachTodosChannel(controller: AgentController, dispatch: FeedDispatch): Unsubscribe;
80
+ /**
81
+ * Fast-tier event stream. `subscribeFast` returns a no-op unsubscribe when the tier was off
82
+ * at construction, so this can subscribe unconditionally. Seeds the chip from the tier
83
+ * resolved at construction so a fast-enabled session shows it on the first frame.
84
+ */
85
+ export declare function attachFastChannel(controller: AgentController, dispatch: FeedDispatch): Unsubscribe;
86
+ /**
87
+ * Context occupancy: THE SOLE DISPATCHER OF `contextUsage`. The gauge used to be written
88
+ * from three reducer branches fed by two upstreams, which is what let a stale snapshot
89
+ * bounce the bar back to the pre-compaction figure one statement after a compaction
90
+ * correctly dropped it. One writer makes that unrepresentable. Seeded on attach so a
91
+ * resumed session shows a real occupancy on frame 1.
92
+ */
93
+ export declare function attachContextUsageChannel(controller: AgentController, dispatch: FeedDispatch): Unsubscribe;
94
+ /** Where the TUI's run clock hangs off compaction (a manual compaction has no agent run). */
95
+ export interface CompactionChannelHooks {
96
+ /** Before `compactionStart` is dispatched. */
97
+ onStart?(): void;
98
+ /** Before `compactionEnd` is dispatched. */
99
+ onEnd?(): void;
100
+ }
101
+ /**
102
+ * Compaction event stream: THE SOLE DISPATCHER OF THE FIVE COMPACTION ACTIONS. One
103
+ * compaction arriving through two channels is two transcript cards and a doubled
104
+ * `tokensReclaimed`. Priced at the SUMMARIZER's model, which may be neither the lead's nor
105
+ * the fast tier's, so the ref is asked for rather than assumed.
106
+ */
107
+ export declare function attachCompactionChannel(controller: AgentController, dispatch: FeedDispatch, hooks?: CompactionChannelHooks): Unsubscribe;
108
+ /**
109
+ * Live tool output: a STREAM at pipe speed, so it goes THROUGH THE COALESCER (it pushes and
110
+ * arms the timer itself - there is no "buffered path for every other action" to fall into).
111
+ * `Date.now()` is read here, in the listener, which is what keeps `viewReducer` pure.
112
+ */
113
+ export declare function attachToolOutputChannel(controller: AgentController, coalescer: ActionCoalescer): Unsubscribe;
114
+ /**
115
+ * The long wait's live view. Through the coalescer, like the tool tail: two updates landing
116
+ * in one frame should commit once. `begin` and `update` are the same action; `end` needs
117
+ * none (`toolExecEnd` and every idle path clear the view). OPTIONAL CALL: a duck-typed
118
+ * controller predates this channel and has nothing to subscribe to.
119
+ */
120
+ export declare function attachWaitChannel(controller: AgentController, coalescer: ActionCoalescer): Unsubscribe | undefined;
121
+ /** The CLI-local diff side channel: `reduceEvent` TAKES a patch, the store is consume-once. */
122
+ export declare function makePatchSource(controller: AgentController): PatchSource;