@aragon-agent/cli 0.6.48 → 0.6.50

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 (72) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1 -0
  3. package/dist/agent/controller.d.ts +21 -0
  4. package/dist/agent/controller.js +35 -8
  5. package/dist/agent/governance-wiring.d.ts +2 -0
  6. package/dist/agent/governance-wiring.js +4 -0
  7. package/dist/app/App.d.ts +2 -4
  8. package/dist/app/App.js +279 -522
  9. package/dist/cli.js +8 -150
  10. package/dist/commands/catalog.d.ts +17 -0
  11. package/dist/commands/catalog.js +52 -0
  12. package/dist/commands/create-registry.d.ts +13 -0
  13. package/dist/commands/create-registry.js +19 -0
  14. package/dist/commands/governance-command.js +5 -1
  15. package/dist/commands/skills.js +18 -67
  16. package/dist/config/env.d.ts +2 -0
  17. package/dist/config/env.js +11 -1
  18. package/dist/config/load.js +4 -0
  19. package/dist/fast/review-call.d.ts +6 -0
  20. package/dist/fast/review-call.js +10 -0
  21. package/dist/governance/engine/budget.d.ts +18 -6
  22. package/dist/governance/engine/budget.js +61 -19
  23. package/dist/governance/engine/engine-core.d.ts +10 -0
  24. package/dist/governance/engine/engine-core.js +56 -9
  25. package/dist/governance/engine/engine.d.ts +1 -0
  26. package/dist/governance/engine/engine.js +9 -10
  27. package/dist/governance/engine/inspector.js +4 -3
  28. package/dist/governance/engine/lifecycle.js +4 -2
  29. package/dist/governance/engine/report.js +7 -1
  30. package/dist/governance/engine/run-digest.js +2 -1
  31. package/dist/governance/engine/stage-runner.js +1 -1
  32. package/dist/governance/engine/submissions.d.ts +2 -0
  33. package/dist/governance/engine/submissions.js +22 -3
  34. package/dist/governance/engine/visibility.d.ts +10 -0
  35. package/dist/governance/engine/visibility.js +28 -0
  36. package/dist/governance/rules/settlement.d.ts +7 -0
  37. package/dist/governance/rules/settlement.js +24 -0
  38. package/dist/governance/tools/shared-tools.d.ts +2 -0
  39. package/dist/governance/tools/shared-tools.js +15 -1
  40. package/dist/governance/tools/submit-tools.js +14 -7
  41. package/dist/host/commands.d.ts +18 -0
  42. package/dist/host/commands.js +30 -0
  43. package/dist/host/controller-factory.d.ts +109 -0
  44. package/dist/host/controller-factory.js +159 -0
  45. package/dist/host/controller-feed.d.ts +122 -0
  46. package/dist/host/controller-feed.js +356 -0
  47. package/dist/host/index-build.d.ts +23 -0
  48. package/dist/host/index-build.js +35 -0
  49. package/dist/host/index.d.ts +21 -0
  50. package/dist/host/index.js +21 -0
  51. package/dist/host/interaction.d.ts +58 -0
  52. package/dist/host/interaction.js +165 -0
  53. package/dist/host/logging.d.ts +7 -0
  54. package/dist/host/logging.js +7 -0
  55. package/dist/host/prompts.d.ts +10 -0
  56. package/dist/host/prompts.js +9 -0
  57. package/dist/host/sessions.d.ts +87 -0
  58. package/dist/host/sessions.js +234 -0
  59. package/dist/host/settings.d.ts +104 -0
  60. package/dist/host/settings.js +235 -0
  61. package/dist/host/skills.d.ts +19 -0
  62. package/dist/host/skills.js +38 -0
  63. package/dist/skills/command-names.d.ts +19 -0
  64. package/dist/skills/command-names.js +28 -0
  65. package/dist/skills/invoke.d.ts +38 -0
  66. package/dist/skills/invoke.js +65 -0
  67. package/dist/team/overseer.d.ts +25 -1
  68. package/dist/team/overseer.js +38 -1
  69. package/dist/team/runtime.d.ts +2 -0
  70. package/dist/team/runtime.js +10 -7
  71. package/dist/team/subagent.js +6 -4
  72. package/package.json +3 -3
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Config facade for hosts that own no controller (the Electron main process).
3
+ *
4
+ * EVERY WRITE GOES THROUGH THE SAME FUNCTIONS THE TUI USES (`commitModelSettings` for the
5
+ * compare-and-swap, `mergePersistedConfig` for clamping), so a desktop write and a terminal
6
+ * write can interleave on one `config.json` without losing an update. Nothing here holds a
7
+ * controller and nothing here writes to stdout.
8
+ *
9
+ * KEYS NEVER LEAVE THIS MODULE IN THE CLEAR except through {@link revealApiKey}: the view
10
+ * carries `{ present, tail, source }` per provider and per profile.
11
+ */
12
+ import { getProviderRegistry, LLMError } from '@aragon-agent/core';
13
+ import { getConfigPath } from '../config/app-paths.js';
14
+ import { PROVIDER_ENV_KEYS } from '../config/env.js';
15
+ import { adaptLegacyConnectionPatch, commitModelSettings, ModelProfileConfigError, readModelSettingsDisk, } from '../config/model-profile-store.js';
16
+ import { mergePersistedConfig } from '../config/store.js';
17
+ import { DEFAULT_CONFIG } from '@aragon-agent/tui/model/config/schema';
18
+ import { registerProfileSecrets } from '@aragon-agent/tui/model/logging/secret-registry';
19
+ /**
20
+ * Keys the terminal owns and a GUI neither shows nor edits (spec A.4 "shared-keep").
21
+ * They are preserved byte-for-byte by {@link patchConfig}; this list only feeds the
22
+ * settings page's "N terminal-only settings are kept" line.
23
+ */
24
+ export const TERMINAL_ONLY_KEYS = [
25
+ 'scrollMode', 'syncOutput', 'diffRender', 'renderGovernor', 'maxRenderIntervalMs', 'mouse',
26
+ 'mouseSelect', 'paste', 'keyboardEnhancement', 'scrollResumeMs', 'exitTranscript',
27
+ 'transcriptWindow',
28
+ ];
29
+ function maskKey(value, source) {
30
+ const key = typeof value === 'string' ? value.trim() : '';
31
+ if (key.length === 0)
32
+ return { present: false, tail: '', source: 'none' };
33
+ return { present: true, tail: key.length > 8 ? key.slice(-4) : '', source };
34
+ }
35
+ function envKeyFor(provider) {
36
+ for (const name of PROVIDER_ENV_KEYS[provider] ?? []) {
37
+ const value = process.env[name];
38
+ if (value && value.trim().length > 0)
39
+ return value.trim();
40
+ }
41
+ return undefined;
42
+ }
43
+ function maskApiKeys(stored) {
44
+ const out = {};
45
+ const providers = new Set([...Object.keys(PROVIDER_ENV_KEYS), ...Object.keys(stored ?? {})]);
46
+ for (const provider of providers) {
47
+ const fromFile = stored?.[provider];
48
+ out[provider] = fromFile?.trim()
49
+ ? maskKey(fromFile, 'file')
50
+ : maskKey(envKeyFor(provider), 'env');
51
+ }
52
+ return out;
53
+ }
54
+ function maskProfiles(profiles) {
55
+ if (!profiles)
56
+ return null;
57
+ return {
58
+ ...profiles,
59
+ entries: profiles.entries.map(({ apiKey, ...rest }) => ({ ...rest, key: maskKey(apiKey, 'file') })),
60
+ };
61
+ }
62
+ /** Project a normalized config into the masked shape a renderer may see. */
63
+ export function toConfigView(config) {
64
+ const { apiKeys, modelProfiles, ...rest } = config;
65
+ return { ...rest, apiKeys: maskApiKeys(apiKeys), modelProfiles: maskProfiles(modelProfiles) };
66
+ }
67
+ /** Read the config file, never throwing and never resetting a damaged file. */
68
+ export function readConfigView() {
69
+ const disk = readModelSettingsDisk();
70
+ // The normalized config spreads the raw file, so unknown keys survive into it; "unknown" is
71
+ // therefore measured against the defaults, which enumerate every key this build understands.
72
+ const knownTop = new Set(Object.keys(DEFAULT_CONFIG));
73
+ const unknownKeys = Object.keys(disk.parsed ?? {}).filter((key) => !knownTop.has(key));
74
+ const base = {
75
+ revision: disk.revision,
76
+ path: getConfigPath(),
77
+ unknownKeys,
78
+ terminalOnlyKeys: TERMINAL_ONLY_KEYS.filter((key) => disk.parsed && key in disk.parsed),
79
+ };
80
+ if (!disk.ok)
81
+ return { ...base, ok: false, view: null, ...(disk.error ? { error: disk.error } : {}) };
82
+ return { ...base, ok: true, view: toConfigView(disk.config) };
83
+ }
84
+ function sameJson(left, right) {
85
+ return JSON.stringify(left) === JSON.stringify(right);
86
+ }
87
+ /**
88
+ * Apply `patch` to the file that is on disk NOW, behind a revision check.
89
+ *
90
+ * FIDELITY RULE: the write starts from the RAW parsed file, not from the normalized object.
91
+ * Only top-level keys whose normalized value actually changed are overwritten, so a key a
92
+ * newer terminal build wrote (or one this build does not know) survives, and a patch that
93
+ * touches `theme` produces a diff of exactly `theme` (AC-14).
94
+ */
95
+ export function patchConfig(input) {
96
+ const disk = readModelSettingsDisk();
97
+ if (!disk.ok)
98
+ return { ok: false, code: 'read_failed', revision: disk.revision };
99
+ if (disk.revision !== input.baseRevision) {
100
+ return { ok: false, code: 'conflict', revision: disk.revision };
101
+ }
102
+ let adapted;
103
+ try {
104
+ adapted = adaptLegacyConnectionPatch({ current: disk.config, patch: input.patch });
105
+ }
106
+ catch (error) {
107
+ if (error instanceof ModelProfileConfigError) {
108
+ return { ok: false, code: error.code, revision: disk.revision };
109
+ }
110
+ throw error;
111
+ }
112
+ const after = mergePersistedConfig(disk.config, adapted);
113
+ const before = disk.config;
114
+ const raw = { ...(disk.parsed ?? {}) };
115
+ const changedKeys = [];
116
+ for (const key of Object.keys(after)) {
117
+ if (sameJson(after[key], before[key]))
118
+ continue;
119
+ raw[key] = after[key];
120
+ changedKeys.push(key);
121
+ }
122
+ if (changedKeys.length === 0)
123
+ return { ok: true, revision: disk.revision, changedKeys };
124
+ const result = commitModelSettings({
125
+ candidate: raw,
126
+ diskRevision: input.baseRevision,
127
+ });
128
+ const next = readModelSettingsDisk();
129
+ if (!result.ok)
130
+ return { ok: false, code: result.code ?? 'invalid', revision: next.revision };
131
+ return { ok: true, revision: next.revision, changedKeys };
132
+ }
133
+ /** The ONE path that returns a stored key in the clear; the caller audits it. */
134
+ export function revealApiKey(provider, profileId) {
135
+ const disk = readModelSettingsDisk();
136
+ if (!disk.ok)
137
+ return null;
138
+ if (profileId) {
139
+ return disk.config.modelProfiles?.entries.find((entry) => entry.id === profileId)?.apiKey ?? null;
140
+ }
141
+ const stored = disk.config.apiKeys[provider];
142
+ return stored?.trim() ? stored : envKeyFor(provider) ?? null;
143
+ }
144
+ /** Register every stored secret with the log redactor. Call at boot and on `config.changed`. */
145
+ export function registerConfigSecrets() {
146
+ const disk = readModelSettingsDisk();
147
+ if (disk.parsed)
148
+ registerProfileSecrets(disk.parsed);
149
+ }
150
+ const CONNECTION_TIMEOUT_MS = 20_000;
151
+ function resolveDraftKey(draft) {
152
+ if (draft.apiKey?.trim())
153
+ return draft.apiKey.trim();
154
+ return revealApiKey(draft.provider, draft.profileId);
155
+ }
156
+ function classifyFailure(error) {
157
+ if (!(error instanceof LLMError)) {
158
+ return { ok: false, stage: 'stream', detail: 'The connection test failed unexpectedly.' };
159
+ }
160
+ switch (error.errorType) {
161
+ case 'auth_error':
162
+ return { ok: false, stage: 'auth', detail: 'The provider rejected the API key (HTTP 401/403). Check the key.' };
163
+ case 'network_error':
164
+ return { ok: false, stage: 'network', detail: 'Could not reach the endpoint. Check the base URL, network and proxy.' };
165
+ case 'timeout':
166
+ return { ok: false, stage: 'network', detail: 'The endpoint did not answer in time. Check the network or proxy.' };
167
+ case 'rate_limit':
168
+ return { ok: true, stage: 'ok', detail: 'Connected (the provider is rate limiting; the key is valid).' };
169
+ case 'invalid_request':
170
+ return { ok: false, stage: 'model', detail: 'The endpoint rejected the request. Check the model name and base URL.' };
171
+ default:
172
+ return { ok: false, stage: 'stream', detail: `The provider returned an error (${error.errorType}).` };
173
+ }
174
+ }
175
+ /** One tiny streamed request, classified by stage. Aborts after 20 s. */
176
+ export async function testConnection(draft, signal) {
177
+ const key = resolveDraftKey(draft);
178
+ if (!key)
179
+ return { ok: false, stage: 'config', detail: 'No API key is set for this provider.' };
180
+ if (!draft.model.trim())
181
+ return { ok: false, stage: 'config', detail: 'Choose a model first.' };
182
+ const provider = getProviderRegistry().get(draft.provider);
183
+ if (!provider)
184
+ return { ok: false, stage: 'config', detail: `Unknown provider "${draft.provider}".` };
185
+ const timeout = AbortSignal.timeout(CONNECTION_TIMEOUT_MS);
186
+ const merged = signal ? AbortSignal.any([signal, timeout]) : timeout;
187
+ const startedAt = Date.now();
188
+ try {
189
+ const stream = provider.stream({
190
+ model: draft.model,
191
+ messages: [{ role: 'user', content: 'Reply with the single word: ok' }],
192
+ apiKey: key,
193
+ ...(draft.baseUrl ? { baseUrl: draft.baseUrl } : {}),
194
+ maxTokens: 16,
195
+ signal: merged,
196
+ });
197
+ for await (const event of stream) {
198
+ if (event.type === 'error')
199
+ return classifyFailure(event.error);
200
+ if (event.type === 'done')
201
+ break;
202
+ }
203
+ if (merged.aborted)
204
+ return { ok: false, stage: 'network', detail: 'The connection test timed out.' };
205
+ return { ok: true, stage: 'ok', detail: 'Connected.', latencyMs: Date.now() - startedAt };
206
+ }
207
+ catch (error) {
208
+ if (merged.aborted)
209
+ return { ok: false, stage: 'network', detail: 'The connection test timed out.' };
210
+ return classifyFailure(error);
211
+ }
212
+ }
213
+ /** List the models a draft can reach. Never throws; an unreachable endpoint yields `[]`. */
214
+ export async function discoverModels(draft, signal) {
215
+ const key = resolveDraftKey({ ...draft, model: '' });
216
+ if (!key)
217
+ return [];
218
+ const provider = getProviderRegistry().get(draft.provider);
219
+ if (!provider)
220
+ return [];
221
+ try {
222
+ return await provider.listModels(key, draft.baseUrl ?? undefined, signal);
223
+ }
224
+ catch {
225
+ return [];
226
+ }
227
+ }
228
+ // Redaction and diagnostics a GUI host needs next to its logs: the same redactor the terminal's
229
+ // logger uses, the live secret list it consults, and the doctor report.
230
+ export { redactText } from '../logging/redact.js';
231
+ export { getSecrets } from '@aragon-agent/tui/model/logging/secret-registry';
232
+ export { runDoctorChecks } from '../diagnostics/doctor.js';
233
+ // Where the home root and the config files are. A host verifies `getHomeRoot()` against the
234
+ // value its parent passed, because `ARAGON_HOME` is read once when `app-paths` first loads.
235
+ export { getConfigBackupPath, getConfigPath as getConfigFilePath, getHomeRoot, getLogsDir, isHomeOverridden, } from '../config/app-paths.js';
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The installed-skills listing for the desktop Skills page. Read-only: it never installs,
3
+ * updates or approves anything, and it persists nothing (`persist` is a no-op).
4
+ *
5
+ * Skills are user-level and project-level state, NOT session state, so the desktop must be able
6
+ * to ask without a live session. {@link listInstalledSkills} builds a throwaway service for that;
7
+ * {@link describeSkills} projects an already-running session's service.
8
+ */
9
+ import type { SkillRecord, SkillScope } from '@aragon-agent/core';
10
+ export interface SkillInfo {
11
+ name: string;
12
+ source: SkillScope;
13
+ description: string;
14
+ /** False when the user disabled it or it failed validation. */
15
+ enabled: boolean;
16
+ invalid: boolean;
17
+ }
18
+ export declare function describeSkills(records: readonly SkillRecord[]): SkillInfo[];
19
+ export declare function listInstalledSkills(cwd: string): SkillInfo[];
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The installed-skills listing for the desktop Skills page. Read-only: it never installs,
3
+ * updates or approves anything, and it persists nothing (`persist` is a no-op).
4
+ *
5
+ * Skills are user-level and project-level state, NOT session state, so the desktop must be able
6
+ * to ask without a live session. {@link listInstalledSkills} builds a throwaway service for that;
7
+ * {@link describeSkills} projects an already-running session's service.
8
+ */
9
+ import { loadConfig } from '../config/load.js';
10
+ import { createNodeSkillHost } from '../skills/node-host.js';
11
+ import { SkillService } from '../skills/service.js';
12
+ import { shortSkillDescription } from '../skills/command-names.js';
13
+ const SORT_ORDER = { project: 0, user: 1, env: 2, bundled: 3 };
14
+ export function describeSkills(records) {
15
+ return records
16
+ .map((record) => ({
17
+ name: record.name,
18
+ source: record.scope,
19
+ description: shortSkillDescription(record.description, 200),
20
+ enabled: !record.disabled && !record.invalid,
21
+ invalid: record.invalid,
22
+ }))
23
+ .sort((a, b) => SORT_ORDER[a.source] - SORT_ORDER[b.source] || a.name.localeCompare(b.name));
24
+ }
25
+ export function listInstalledSkills(cwd) {
26
+ const config = loadConfig({ cwd });
27
+ const service = new SkillService({
28
+ host: createNodeSkillHost(),
29
+ getCwd: () => config.cwd,
30
+ config: config.skills,
31
+ runtime: { forcedSkills: [], approveAll: false },
32
+ // Fail closed: a listing must never be the thing that approves a project's skills.
33
+ approval: { canPrompt: () => false, request: async () => false },
34
+ notify: () => undefined,
35
+ persist: () => undefined,
36
+ });
37
+ return describeSkills(service.discover().records);
38
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Which slash-command names a skill gets. Pure, so both the terminal registry and the desktop
3
+ * host's menu metadata (which may not import the Ink-reaching `commands/skills.ts`) use the SAME rule.
4
+ *
5
+ * CONFLICT RULE (D6 / P1-2): the namespaced `skill:<name>` form is ALWAYS present - documentation
6
+ * and scripts need a stable handle - while the bare `<name>` is only taken when nothing else owns it.
7
+ */
8
+ import type { SkillRecord } from '@aragon-agent/core';
9
+ /** The `/skills` management command's menu text, shared by the registry and the host metadata. */
10
+ export declare const SKILLS_COMMAND_DESCRIPTION = "List and manage skills";
11
+ /** A skill that can be invoked as a command at all. */
12
+ export declare function isInvocableSkill(record: SkillRecord): boolean;
13
+ /**
14
+ * `isTaken` MUST be a probe that sees aliases (`CommandRegistry.get`), never one over the primary
15
+ * names: `quit` is an alias of `exit`, and a skill named `quit` must not take it over.
16
+ */
17
+ export declare function skillCommandNames(record: SkillRecord, isTaken: (name: string) => boolean): string[];
18
+ /** One-line description, collapsed whitespace, truncated; the same text the `/` menu shows. */
19
+ export declare function shortSkillDescription(description: string, max?: number, ellipsis?: string): string;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Which slash-command names a skill gets. Pure, so both the terminal registry and the desktop
3
+ * host's menu metadata (which may not import the Ink-reaching `commands/skills.ts`) use the SAME rule.
4
+ *
5
+ * CONFLICT RULE (D6 / P1-2): the namespaced `skill:<name>` form is ALWAYS present - documentation
6
+ * and scripts need a stable handle - while the bare `<name>` is only taken when nothing else owns it.
7
+ */
8
+ /** The `/skills` management command's menu text, shared by the registry and the host metadata. */
9
+ export const SKILLS_COMMAND_DESCRIPTION = 'List and manage skills';
10
+ /** A skill that can be invoked as a command at all. */
11
+ export function isInvocableSkill(record) {
12
+ return !record.disabled && !record.invalid && record.frontmatter.activation !== 'manual';
13
+ }
14
+ /**
15
+ * `isTaken` MUST be a probe that sees aliases (`CommandRegistry.get`), never one over the primary
16
+ * names: `quit` is an alias of `exit`, and a skill named `quit` must not take it over.
17
+ */
18
+ export function skillCommandNames(record, isTaken) {
19
+ const names = [`skill:${record.name}`];
20
+ if (!isTaken(record.name))
21
+ names.push(record.name);
22
+ return names;
23
+ }
24
+ /** One-line description, collapsed whitespace, truncated; the same text the `/` menu shows. */
25
+ export function shortSkillDescription(description, max = 60, ellipsis = '...') {
26
+ const one = description.replace(/\s+/g, ' ').trim();
27
+ return one.length > max ? `${one.slice(0, max - ellipsis.length)}${ellipsis}` : one;
28
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Running a skill as a user turn, without a terminal: the part of the `/skill:<name>` command that
3
+ * is not about the terminal. Shared by the slash command (`commands/skills.ts`) and the desktop
4
+ * host's "build the project index" action, so the two cannot start a skill in different ways.
5
+ *
6
+ * The sequence is load the body, ACTIVATE, QUEUE the tool frame, render the message. Queue, do not
7
+ * enter (D-G2): the message returned here becomes the user turn that OPENS the next run, and
8
+ * `controller.prompt()` clears the frame on its way in - entering it here would leave the one turn
9
+ * the user asked this skill to run as the only unconstrained one.
10
+ *
11
+ * No Ink, no TTY (layering gate L9).
12
+ */
13
+ import { type SkillRecord } from '@aragon-agent/core';
14
+ import type { InvocationCardInput } from '@aragon-agent/tui/model/agent/invocation-card';
15
+ import type { SkillService } from './service.js';
16
+ /**
17
+ * The card's raw material for one skill run (tui-invocation-cards section 3.3). The
18
+ * command line always uses the namespaced `/skill:<name>` form - the stable handle -
19
+ * even when the user typed the bare name. Ctrl+I's machine-written sentence is NOT the
20
+ * user's input (RV-3): the card says `ctrl+i` and shows no input row.
21
+ */
22
+ export declare function skillCardInput(record: SkillRecord, args: string, sent: {
23
+ kb: number;
24
+ files: number;
25
+ policy: boolean;
26
+ }): InvocationCardInput;
27
+ export type PreparedSkillInvocation = {
28
+ ok: true;
29
+ message: string;
30
+ kb: number;
31
+ files: number;
32
+ policy: boolean;
33
+ card: InvocationCardInput;
34
+ } | {
35
+ ok: false;
36
+ error: string;
37
+ };
38
+ export declare function prepareSkillInvocation(record: SkillRecord, args: string, service: SkillService, listToolNames: () => string[]): PreparedSkillInvocation;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Running a skill as a user turn, without a terminal: the part of the `/skill:<name>` command that
3
+ * is not about the terminal. Shared by the slash command (`commands/skills.ts`) and the desktop
4
+ * host's "build the project index" action, so the two cannot start a skill in different ways.
5
+ *
6
+ * The sequence is load the body, ACTIVATE, QUEUE the tool frame, render the message. Queue, do not
7
+ * enter (D-G2): the message returned here becomes the user turn that OPENS the next run, and
8
+ * `controller.prompt()` clears the frame on its way in - entering it here would leave the one turn
9
+ * the user asked this skill to run as the only unconstrained one.
10
+ *
11
+ * No Ink, no TTY (layering gate L9).
12
+ */
13
+ import { renderSkillInvocation } from '@aragon-agent/core';
14
+ import { INDEX_SKILL_NAME, isIndexBuildArgs } from '../commands/index-build.js';
15
+ import { currentPlatform } from './node-host.js';
16
+ /**
17
+ * The card's raw material for one skill run (tui-invocation-cards section 3.3). The
18
+ * command line always uses the namespaced `/skill:<name>` form - the stable handle -
19
+ * even when the user typed the bare name. Ctrl+I's machine-written sentence is NOT the
20
+ * user's input (RV-3): the card says `ctrl+i` and shows no input row.
21
+ */
22
+ export function skillCardInput(record, args, sent) {
23
+ const machine = record.name === INDEX_SKILL_NAME && isIndexBuildArgs(args);
24
+ const version = record.frontmatter.version;
25
+ const facts = [
26
+ ...(machine ? ['ctrl+i'] : []),
27
+ ...(version ? [`v${version}`] : []),
28
+ record.scope,
29
+ `${sent.kb} KB`,
30
+ ...(sent.files > 0 ? [`${sent.files} files`] : []),
31
+ ...(sent.policy ? ['tool ceiling'] : []),
32
+ ];
33
+ const typed = machine ? '' : args;
34
+ return {
35
+ variant: 'skill',
36
+ name: record.name,
37
+ commandLine: typed === '' ? `/skill:${record.name}` : `/skill:${record.name} ${typed}`,
38
+ input: typed,
39
+ facts,
40
+ };
41
+ }
42
+ export function prepareSkillInvocation(record, args, service, listToolNames) {
43
+ let loaded;
44
+ try {
45
+ loaded = service.loadBody(record.name);
46
+ }
47
+ catch (err) {
48
+ return { ok: false, error: `Could not load skill "${record.name}": ${err.message}` };
49
+ }
50
+ const hydrated = { ...record, body: loaded.body, files: loaded.files };
51
+ service.getRegistry().activate(record.name);
52
+ service.queueFrame(record.name);
53
+ const policy = service.pendingToolPolicyView(listToolNames);
54
+ const message = renderSkillInvocation(hydrated, args, {
55
+ // The same knob as the tool path, at last (GG3 / FG3).
56
+ bodyMaxBytes: service.bodyMaxBytes(),
57
+ platform: currentPlatform(),
58
+ ...(policy ? { policy } : {}),
59
+ });
60
+ // The SUBMITTED size, not the file's. Reporting 480 KB while sending 30 KB
61
+ // is how a user concludes the truncation marker is a rendering glitch.
62
+ const kb = Math.max(1, Math.round(Buffer.byteLength(message, 'utf-8') / 1024));
63
+ const sent = { kb, files: loaded.files.length, policy: !!policy };
64
+ return { ok: true, message, ...sent, card: skillCardInput(record, args, sent) };
65
+ }
@@ -208,10 +208,26 @@ export interface OverseerInspectRequest {
208
208
  trigger: 'silence' | 'clock' | 'turncap' | 'postmortem';
209
209
  childAlive: boolean;
210
210
  }
211
+ /**
212
+ * What the session has already REPORTED of the provider's cumulative spend. The provider is
213
+ * built once per controller while a `TeamOverseer` is built per dispatch, so the "reported so
214
+ * far" cursor has to outlive the dispatch: owned by the runtime, shared by every overseer it
215
+ * builds. A construction-time baseline would permanently lose a fire-and-forget inspection
216
+ * that settles after its dispatch's outcome was read.
217
+ */
218
+ export interface OverseerUsageCursor {
219
+ reported: TokenUsage;
220
+ }
221
+ export declare function createOverseerUsageCursor(): OverseerUsageCursor;
211
222
  export interface TeamOverseerOptions {
212
223
  /** The dispatch's start, so memory entries read as "N s in". */
213
224
  startedAt: number;
214
225
  now?: () => number;
226
+ /**
227
+ * Shared across the dispatches of one runtime. Absent (a standalone overseer) means
228
+ * `takeUsage()` returns the provider's cumulative figure, as `usage()` does.
229
+ */
230
+ usageCursor?: OverseerUsageCursor;
215
231
  }
216
232
  export declare const OVERSEER_DEFAULT_NEXT_CHECK_MS: 300000;
217
233
  /**
@@ -259,7 +275,15 @@ export declare class TeamOverseer {
259
275
  noteReplacement(label: string): void;
260
276
  /** Called by the runtime when it APPLIES an abandon, not when it merely reads one. */
261
277
  noteAbandon(label: string): void;
262
- /** The provider's own accumulated inspection spend (D-7), zero when unreadable. */
278
+ /**
279
+ * The spend not yet reported to any dispatch outcome (D-7), advancing the shared cursor.
280
+ * The provider's figure is session-cumulative; reporting it as-is per dispatch counted
281
+ * dispatch 1's spend again in dispatch 2. A late inspection lands in the next window, so
282
+ * the sum over dispatches always equals the provider total. Zero when unreadable (the
283
+ * cursor then stays put and the next window picks the spend up).
284
+ */
285
+ takeUsage(): TokenUsage;
286
+ /** The provider's own accumulated (session-cumulative) spend, zero when unreadable. Read-only. */
263
287
  usage(): TokenUsage;
264
288
  /** Provider invocations, including ones that failed softly (D-7). */
265
289
  calls(): number;
@@ -424,6 +424,21 @@ export function createFastOverseerProvider(deps) {
424
424
  usage: () => ({ ...totalUsage }),
425
425
  };
426
426
  }
427
+ export function createOverseerUsageCursor() {
428
+ return { reported: { ...NO_USAGE } };
429
+ }
430
+ /** `total - reported`, clamped at zero; a cache field appears only when non-zero. */
431
+ function usageSince(total, reported) {
432
+ const gap = (a, b) => Math.max(0, (a ?? 0) - (b ?? 0));
433
+ const cacheRead = gap(total.cacheReadTokens, reported.cacheReadTokens);
434
+ const cacheWrite = gap(total.cacheWriteTokens, reported.cacheWriteTokens);
435
+ return {
436
+ inputTokens: gap(total.inputTokens, reported.inputTokens),
437
+ outputTokens: gap(total.outputTokens, reported.outputTokens),
438
+ ...(cacheRead > 0 ? { cacheReadTokens: cacheRead } : {}),
439
+ ...(cacheWrite > 0 ? { cacheWriteTokens: cacheWrite } : {}),
440
+ };
441
+ }
427
442
  export const OVERSEER_DEFAULT_NEXT_CHECK_MS = TEAM_LIMITS.overseerDefaultCheckMs;
428
443
  /**
429
444
  * Per-dispatch supervisor state: memory, budgets and the single-flight guard.
@@ -499,7 +514,29 @@ export class TeamOverseer {
499
514
  noteAbandon(label) {
500
515
  this.abandons.set(label, (this.abandons.get(label) ?? 0) + 1);
501
516
  }
502
- /** The provider's own accumulated inspection spend (D-7), zero when unreadable. */
517
+ /**
518
+ * The spend not yet reported to any dispatch outcome (D-7), advancing the shared cursor.
519
+ * The provider's figure is session-cumulative; reporting it as-is per dispatch counted
520
+ * dispatch 1's spend again in dispatch 2. A late inspection lands in the next window, so
521
+ * the sum over dispatches always equals the provider total. Zero when unreadable (the
522
+ * cursor then stays put and the next window picks the spend up).
523
+ */
524
+ takeUsage() {
525
+ let total;
526
+ try {
527
+ total = this.provider.usage();
528
+ }
529
+ catch {
530
+ return { ...NO_USAGE };
531
+ }
532
+ const cursor = this.options.usageCursor;
533
+ if (cursor === undefined)
534
+ return total;
535
+ const delta = usageSince(total, cursor.reported);
536
+ cursor.reported = { ...total };
537
+ return delta;
538
+ }
539
+ /** The provider's own accumulated (session-cumulative) spend, zero when unreadable. Read-only. */
503
540
  usage() {
504
541
  try {
505
542
  return this.provider.usage();
@@ -143,6 +143,8 @@ export declare class TeamRuntime {
143
143
  * back to the legacy hard abort. `active()` is re-read every tick.
144
144
  */
145
145
  private overseer;
146
+ /** Session-lifetime: how much of the cumulative supervisor spend outcomes already carried. */
147
+ private readonly overseerUsageCursor;
146
148
  /** The per-child silence windows, same lifetime as `overseer`. */
147
149
  private supervision;
148
150
  /** The cadence ladder (subagent-overseer-v2 D-2), same lifetime. */
@@ -28,10 +28,11 @@
28
28
  * pre-feature behaviour.
29
29
  */
30
30
  import { TeamBus } from './bus.js';
31
+ import { accumulateUsage } from '../fast/review-call.js';
31
32
  import { settledRun } from './settled.js';
32
33
  import { appendTimeline, withSettleEntry } from '@aragon-agent/tui/model/team/timeline';
33
34
  import { TEAM_AGGREGATE_LABEL, TEAM_LIMITS } from '@aragon-agent/tui/model/team/limits';
34
- import { TeamOverseer, buildReplacementPrompt, nextOverseerLadderStepMs, resolveOverseerFirstCheckMs, } from './overseer.js';
35
+ import { TeamOverseer, createOverseerUsageCursor, buildReplacementPrompt, nextOverseerLadderStepMs, resolveOverseerFirstCheckMs, } from './overseer.js';
35
36
  import { shouldRetryColdStart } from './retry.js';
36
37
  import { createSubagent, defaultSubagentFactory, } from './subagent.js';
37
38
  /**
@@ -327,6 +328,8 @@ export class TeamRuntime {
327
328
  * back to the legacy hard abort. `active()` is re-read every tick.
328
329
  */
329
330
  overseer = null;
331
+ /** Session-lifetime: how much of the cumulative supervisor spend outcomes already carried. */
332
+ overseerUsageCursor = createOverseerUsageCursor();
330
333
  /** The per-child silence windows, same lifetime as `overseer`. */
331
334
  supervision = null;
332
335
  /** The cadence ladder (subagent-overseer-v2 D-2), same lifetime. */
@@ -411,7 +414,10 @@ export class TeamRuntime {
411
414
  const supervised = this.deps.overseer !== undefined && team.overseer;
412
415
  this.overseer =
413
416
  supervised && this.deps.overseer !== undefined
414
- ? new TeamOverseer(this.deps.overseer, { startedAt })
417
+ ? new TeamOverseer(this.deps.overseer, {
418
+ startedAt,
419
+ usageCursor: this.overseerUsageCursor,
420
+ })
415
421
  : null;
416
422
  this.supervision =
417
423
  this.overseer !== null
@@ -616,7 +622,7 @@ export class TeamRuntime {
616
622
  // CAPTURED BEFORE THE FIELD IS NULLED: the outcome carries what the
617
623
  // supervisor spent (D-7) and whether any tick ran unassisted (D-10),
618
624
  // both read off the per-dispatch state being torn down here.
619
- const overseerUsage = this.overseer?.usage();
625
+ const overseerUsage = this.overseer?.takeUsage();
620
626
  const overseerCalls = this.overseer?.calls();
621
627
  const overseerDegraded = this.overseerDegraded;
622
628
  const overseerDegradedTicks = this.overseerDegradedTicks;
@@ -624,10 +630,7 @@ export class TeamRuntime {
624
630
  // ONE TOTAL, AT THE LEAD'S TABLE. Every child runs the lead's own model
625
631
  // (main-agent parity), so there is exactly one tier to sum and one price to
626
632
  // sum it at; a split would be two answers to one question.
627
- const usage = handles.reduce((acc, h) => ({
628
- inputTokens: acc.inputTokens + h.run.usage.inputTokens,
629
- outputTokens: acc.outputTokens + h.run.usage.outputTokens,
630
- }), { inputTokens: 0, outputTokens: 0 });
633
+ const usage = handles.reduce((acc, h) => accumulateUsage(acc, h.run.usage), { inputTokens: 0, outputTokens: 0 });
631
634
  const outcome = {
632
635
  dispatchId,
633
636
  // THE DISPATCH EXIT'S STRIP (tui-subagent-panel §4.5.4). `settledRun` drops the
@@ -20,6 +20,7 @@ import { describeToolActivity, pickActivityArgs, sanitizeActivity } from '@arago
20
20
  import { TEAM_LIMITS, TEAM_SUBAGENT_TOOL_NAMES } from '@aragon-agent/tui/model/team/limits';
21
21
  import { appendTimeline } from '@aragon-agent/tui/model/team/timeline';
22
22
  import { isRetryableStreamError } from './retry.js';
23
+ import { accumulateUsage } from '../fast/review-call.js';
23
24
  import { resolveSubagentKey, resolveSubagentModel } from '@aragon-agent/tui/model/team/model';
24
25
  import { makeTeamSend, makeTeamWait, withMailboxTail } from './comm-tools.js';
25
26
  import { buildSubagentBlock } from './prompt.js';
@@ -432,10 +433,7 @@ export function createSubagent(spec, deps, hooks) {
432
433
  // A completed turn means whatever it retried, it recovered (§6.10). The
433
434
  // row goes back to reporting its phase.
434
435
  run.retry = undefined;
435
- run.usage = {
436
- inputTokens: run.usage.inputTokens + event.usage.inputTokens,
437
- outputTokens: run.usage.outputTokens + event.usage.outputTokens,
438
- };
436
+ run.usage = accumulateUsage(run.usage, event.usage);
439
437
  hooks.onUsage(spec.label, event.usage);
440
438
  // W1's delta needs the history LENGTH the measurement covered, and the
441
439
  // port carries no turn hook. `turn_end` is emitted BEFORE the assistant
@@ -526,6 +524,10 @@ export function createSubagent(spec, deps, hooks) {
526
524
  ok: event.isError !== true,
527
525
  ...(startedAt !== undefined ? { ms: Math.max(0, endedAt - startedAt) } : {}),
528
526
  text: describeToolActivity(event.toolName, run.activityArgs, true),
527
+ // READ BEFORE `run.activityArgs = undefined` below (that clear must never move
528
+ // above this call): the board re-words the line from these two.
529
+ tool: event.toolName,
530
+ ...(run.activityArgs !== undefined ? { args: run.activityArgs } : {}),
529
531
  });
530
532
  run.phase = 'thinking';
531
533
  textTail = '';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aragon-agent/cli",
3
- "version": "0.6.48",
3
+ "version": "0.6.50",
4
4
  "description": "AragonAgent CLI — a Claude-Code / Codex-style interactive terminal UI (TUI) on top of the @aragon-agent/core engine. Installable and runnable via npm / npx.",
5
5
  "license": "MIT",
6
6
  "author": "AragonAgent contributors",
@@ -58,8 +58,8 @@
58
58
  "prepublishOnly": "npm run build"
59
59
  },
60
60
  "dependencies": {
61
- "@aragon-agent/core": "^0.2.60",
62
- "@aragon-agent/tui": "0.0.1",
61
+ "@aragon-agent/core": "^0.2.62",
62
+ "@aragon-agent/tui": "0.0.3",
63
63
  "commander": "^12.1.0",
64
64
  "dotenv": "^16.6.1",
65
65
  "env-paths": "^3.0.0",