@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
package/dist/cli.js CHANGED
@@ -1,18 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
- /**
4
- * Bin entry (spec §3.1 / §5.1). Parses argv, resolves layered config, and
5
- * branches:
6
- * --help/--version → commander prints & exits
7
- * config / models subcommand → utility & exit
8
- * -p/--print or piped stdin → one-shot headless run
9
- * else → render the interactive Ink TUI
10
- *
11
- * The shebang is prepended post-build by scripts/prepend-shebang.mjs.
12
- */
13
- import { readFileSync } from 'node:fs';
14
- import { dirname, join } from 'node:path';
15
- import { fileURLToPath } from 'node:url';
16
3
  import process from 'node:process';
17
4
  import '../runtime/insecure-tls-warning.cjs';
18
5
  // Must precede every other dependency that imports Ink: CI detection is cached.
@@ -32,7 +19,6 @@ import { getLogger } from './logging/logger.js';
32
19
  import { runLogsCommand } from './logging/cli-commands.js';
33
20
  import { ADAPTER_PROVIDERS, clampDensity, clampTheme, clampThinkingLevel, clampHumanTimeout, clampSkillsIntegrity, clampSkillsToolPolicy, clampContextWindow, clampMaxRenderInterval, clampScrollMode, clampScrollResumeMs, clampTranscriptRetain, clampTranscriptWindow, coercePositiveInt, isAdapterProvider, isAutoToken, parseMaxTokensInput, RETIRED_CONFIG_KEYS, DEFAULT_MAX_RENDER_INTERVAL_MS, DEFAULT_MAX_TOKENS, DEFAULT_PLAN_HUMAN_TIMEOUT_MS, DEFAULT_SCROLL_MODE, DEFAULT_SCROLL_RESUME_MS, DEFAULT_SKILLS_CONFIG, DEFAULT_TRANSCRIPT_RETAIN, DEFAULT_TRANSCRIPT_WINDOW, } from '@aragon-agent/tui/model/config/schema';
34
21
  import { makeGetApiKey } from './config/load.js';
35
- import { AgentController, DENY_ALL_APPROVAL } from './agent/controller.js';
36
22
  import { runSkillsCommand } from './skills/cli-commands.js';
37
23
  import { runHeadless } from './agent/headless.js';
38
24
  // The four `register*Command` entry points of cli-integration-surface §3.1. The
@@ -43,8 +29,8 @@ import { registerExecCommand } from './exec/cli-commands.js';
43
29
  import { registerSessionsCommand } from './session/cli-commands.js';
44
30
  import { registerDoctorCommand, registerInfoCommand } from './diagnostics/cli-commands.js';
45
31
  import { App } from './app/App.js';
32
+ import { createSessionWriter, makeController, readCliVersion, } from './host/controller-factory.js';
46
33
  import { readSessionView, publishSessionView } from './app/session-bridge.js';
47
- import { SessionCheckpointWriter } from './session/checkpoint.js';
48
34
  import { resolveStartupSession, rotateToChildOf } from './session/startup-session.js';
49
35
  import { createBranchLauncher } from './session/branch-launch.js';
50
36
  import { EMPTY_USAGE_TOTAL } from '@aragon-agent/tui/model/agent/reducer';
@@ -71,7 +57,6 @@ import { resolveTuiCapabilities } from '@aragon-agent/tui/ui/capabilities';
71
57
  import { pickGlyphs } from '@aragon-agent/tui/ui/glyphs';
72
58
  import { getTheme } from '@aragon-agent/tui/ui/theme';
73
59
  import { createSelectionController, } from '@aragon-agent/tui/ui/selection/selection-controller';
74
- import { DENY_ALL_HUMAN_INPUT } from '@aragon-agent/tui/model/tools/human-input';
75
60
  // A VALUE import, and the one deliberate exception to the paragraph above
76
61
  // (cli-auto-update-hardening P2-7). `boot/guard.js` statically pulls
77
62
  // `update/state.js`, so `aragon -p` now EVALUATES that module - it is pure at
@@ -84,17 +69,7 @@ import { markBootHealthy } from './boot/guard.js';
84
69
  // ---------------------------------------------------------------------------
85
70
  // Version (read from the shipped package.json next to dist/)
86
71
  // ---------------------------------------------------------------------------
87
- function readVersion() {
88
- try {
89
- const here = dirname(fileURLToPath(import.meta.url));
90
- const pkg = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf-8'));
91
- return pkg.version ?? '0.0.0';
92
- }
93
- catch {
94
- return '0.0.0';
95
- }
96
- }
97
- const VERSION = readVersion();
72
+ const VERSION = readCliVersion();
98
73
  /**
99
74
  * `--scroll-mode` is the one flag validated at parse time (tui-native-terminal-scroll
100
75
  * §6.1): a typo must be an exit-2 sentence, not a silent fallback to the default.
@@ -249,95 +224,6 @@ function toFlags(opts) {
249
224
  // ---------------------------------------------------------------------------
250
225
  // Modes
251
226
  // ---------------------------------------------------------------------------
252
- /**
253
- * Build the controller for a mode.
254
- *
255
- * TWO DIFFERENT APPROVAL CHANNELS, AND THEY MUST NOT BE CONFLATED:
256
- *
257
- * `confirm` — the `--confirm` gate for mutating tools. Its `handler === null`
258
- * fallback is `Promise.resolve(true)`, which is fine because that
259
- * path is opt-in and only reachable with the TUI mounted.
260
- *
261
- * `approval` — the skill-install gate. It PROBES for a human first and denies
262
- * when there is none (D17 / §8.3.1). Passing the `confirm`
263
- * closure here instead would inherit the auto-approve fallback
264
- * and make `requireApproval: true` a no-op under `-p`, silently.
265
- *
266
- * `interactive: false` (the headless path) gets the deny-all gate, so a model
267
- * calling `skill_install` in `-p` mode is refused with an actionable message
268
- * instead of writing to disk unattended.
269
- */
270
- function makeController(flags, opts = { interactive: true }) {
271
- const config = loadConfig(flags, { interactive: opts.interactive });
272
- // The authoritative log level lands here (§4.4.5). `installLogging()` only
273
- // resolved a bootstrap level — it ran before commander and before `.env` were
274
- // readable — and without this hand-off the fully resolved one never applies.
275
- getLogger().reconfigure(config.log);
276
- // Headless controllers never expose the task panel.
277
- const todoPanelCapable = opts.interactive;
278
- const confirmBridge = { handler: null };
279
- // `cancelPending` is replaced by the App's own implementation on mount; this
280
- // no-op keeps the object total so nothing has to null-check it.
281
- const humanInputBridge = { handler: null, cancelPending: () => { } };
282
- const controller = new AgentController(config, {
283
- version: VERSION,
284
- todoPanelCapable,
285
- confirm: (req) => confirmBridge.handler ? confirmBridge.handler(req) : Promise.resolve(true),
286
- // THE TWO CAN NEVER BOTH BE PRESENT: `interactive: false` is the only path
287
- // that supplies a bridge gate, and the interactive branch is the only one that
288
- // reads the overlay bridge. `??` keeps `-p`'s deny-all default byte-identical.
289
- approval: opts.approval ??
290
- (opts.interactive
291
- ? {
292
- // Read live on every call: the App's effect cleanup nulls the handler
293
- // on unmount, and a cached `true` would keep the gate open after the
294
- // human channel is gone.
295
- canPrompt: () => confirmBridge.handler !== null,
296
- request: (req) => confirmBridge.handler ? confirmBridge.handler(req) : Promise.resolve(false),
297
- }
298
- : DENY_ALL_APPROVAL),
299
- notify: (level, text) => {
300
- if (!opts.interactive)
301
- process.stderr.write(`[skills] ${level}: ${text}\n`);
302
- },
303
- // A THIRD approval channel, and it must not be conflated with the other two.
304
- // `confirm` auto-approves when unattached and `approval` denies; neither can
305
- // render a question wizard or a plan card. Headless gets the fail-closed
306
- // gate, whose STATIC `neverPrompts` is also what stops `createPlanTools`
307
- // registering two tools the model could never use there.
308
- humanInput: opts.humanInput ??
309
- (opts.interactive
310
- ? {
311
- // Live probe, never cached - same contract as `approval` above.
312
- canPrompt: () => humanInputBridge.handler !== null,
313
- request: (req, signal) => humanInputBridge.handler
314
- ? humanInputBridge.handler(req, signal)
315
- : Promise.resolve(null),
316
- }
317
- : DENY_ALL_HUMAN_INPUT),
318
- ...(opts.permission ? { permission: opts.permission } : {}),
319
- ...(opts.appendSystemPrompt ? { appendSystemPrompt: opts.appendSystemPrompt } : {}),
320
- // SPREAD, never `toolGate: opts.toolGate`: with no gate the deps bag has no
321
- // such key, `createBuiltinTools` never enters its mapping branch, and the tool
322
- // array stays provably identical outside bridge mode (I-1).
323
- ...(opts.toolGate ? { toolGate: opts.toolGate } : {}),
324
- ...(opts.toolGateForChild ? { toolGateForChild: opts.toolGateForChild } : {}),
325
- ...(opts.decisionBudgetMs !== undefined ? { decisionBudgetMs: opts.decisionBudgetMs } : {}),
326
- // THE R3 PAIR, AND THIS LINE IS THE DIFFERENCE BETWEEN A WORKING FEATURE AND A DEAD
327
- // ONE (headless-request-scope-and-typed-result section 2.6 rows 11/17). This factory
328
- // takes `deps` as a bag and FORWARDS ONLY WHAT IS NAMED HERE, so a new dep that is
329
- // not spread below is dropped in silence: every unit test that stubs the factory
330
- // keeps passing while the real binary never registers the tool. That is the D-12
331
- // defect this project has already paid for once, which is why both keys are spread
332
- // conditionally and adjacent to each other.
333
- ...(opts.resultTool ? { resultTool: opts.resultTool } : {}),
334
- ...(opts.structuredResultBlock
335
- ? { structuredResultBlock: opts.structuredResultBlock }
336
- : {}),
337
- ...(opts.hookRunner ? { hookRunner: opts.hookRunner } : {}),
338
- });
339
- return { controller, confirmBridge, humanInputBridge };
340
- }
341
227
  /**
342
228
  * The controller factory `aragon exec` runs on.
343
229
  *
@@ -1357,40 +1243,6 @@ async function runInteractive(flags, extras = {}) {
1357
1243
  })
1358
1244
  .catch(failInteractive);
1359
1245
  }
1360
- /**
1361
- * Build the checkpoint writer for one process (D-2 / D-21).
1362
- *
1363
- * ONE CONSTRUCTION SITE FOR TWO PATHS. The TUI and `-p` differ in exactly one
1364
- * thing - where `readView` gets its transcript - and in nothing else: the same
1365
- * `meta` fields, the same live model, the same todos, the same cwd. Writing the
1366
- * eight deps twice is how `meta.turns` would come to mean two things, which is
1367
- * the drift class D-9 exists to prevent for `applyRestoredSession`.
1368
- */
1369
- function createSessionWriter(input) {
1370
- const { controller } = input;
1371
- return new SessionCheckpointWriter({
1372
- readView: input.readView,
1373
- readHistory: () => controller.getSessionSnapshot(),
1374
- readTodos: () => controller.getTodoSnapshot()?.items ?? [],
1375
- // The verdicts travel with the plan; read from the STORE, not from the render
1376
- // projection, so a checkpoint taken while the capability is off still saves them.
1377
- readAcceptance: () => controller.getAcceptanceItems(),
1378
- // READ AT WRITE TIME: `/model` rebuilds the config, and a checkpoint that
1379
- // recorded the model from launch would name the wrong one after a switch.
1380
- readModel: () => {
1381
- const live = controller.getConfig();
1382
- return {
1383
- providerId: live.provider,
1384
- modelId: live.model,
1385
- ...(live.baseUrl ? { baseUrl: live.baseUrl } : {}),
1386
- };
1387
- },
1388
- readCwd: () => controller.getCwd(),
1389
- version: VERSION,
1390
- readParentId: input.readParentId,
1391
- startPinned: input.startPinned,
1392
- });
1393
- }
1394
1246
  async function runOneShot(flags, prompt, quiet) {
1395
1247
  // THE SAME RESOLUTION THE TUI USES (D-9 / D-21). A `-p` run has no Ink, no
1396
1248
  // `/session` and no `agent_end` subscription, so `--resume` here is one read
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The built-in slash commands as PURE DATA: name, aliases, description.
3
+ *
4
+ * Why a table next to the registry instead of reading the registry: the registry's
5
+ * registration path reaches Ink-layer modules (`tui/ui/*`), and the desktop host closure
6
+ * (layering rule L9) may not. The table is what `host/commands.ts` serves to the composer menu.
7
+ *
8
+ * It cannot drift silently: `__tests__/command-catalog.test.ts` builds the real registry through
9
+ * `createCommandRegistry` and fails on any difference in names, aliases or descriptions. Add a
10
+ * command to the registry and that test names the missing row.
11
+ */
12
+ export interface CatalogCommand {
13
+ readonly name: string;
14
+ readonly aliases: readonly string[];
15
+ readonly description: string;
16
+ }
17
+ export declare const BUILTIN_COMMAND_CATALOG: readonly CatalogCommand[];
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The built-in slash commands as PURE DATA: name, aliases, description.
3
+ *
4
+ * Why a table next to the registry instead of reading the registry: the registry's
5
+ * registration path reaches Ink-layer modules (`tui/ui/*`), and the desktop host closure
6
+ * (layering rule L9) may not. The table is what `host/commands.ts` serves to the composer menu.
7
+ *
8
+ * It cannot drift silently: `__tests__/command-catalog.test.ts` builds the real registry through
9
+ * `createCommandRegistry` and fails on any difference in names, aliases or descriptions. Add a
10
+ * command to the registry and that test names the missing row.
11
+ */
12
+ export const BUILTIN_COMMAND_CATALOG = [
13
+ { name: 'help', aliases: [], description: 'Show keybindings and commands' },
14
+ { name: 'model', aliases: [], description: 'Open the model picker' },
15
+ { name: 'settings', aliases: [], description: 'Open the settings screen' },
16
+ { name: 'thinking', aliases: [], description: 'Set the thinking level' },
17
+ { name: 'max-tokens', aliases: [], description: 'Show or set the output token cap (<n> | auto | default)' },
18
+ { name: 'theme', aliases: [], description: 'Switch the color theme (auto|warm|cool|light)' },
19
+ { name: 'plan', aliases: [], description: 'Toggle plan mode (on | off | status)' },
20
+ { name: 'fast', aliases: [], description: 'Fast model tier: status | on | off | model <id> | provider <id> | same | review <n|off> | budget <n>' },
21
+ { name: 'update', aliases: [], description: 'Auto-update: status | now | skip | off' },
22
+ { name: 'todo', aliases: [], description: 'Todo planning: status | on | off | panel on|off | follow <mode> | acceptance [on|off|reset] | clear | continue' },
23
+ { name: 'retry', aliases: [], description: 'API retry: show | on | off | max <n>' },
24
+ { name: 'compact', aliases: [], description: 'Context compaction: status | on | off | threshold <n> | keep <n> | <instructions>' },
25
+ { name: 'context', aliases: [], description: 'Show context occupancy, the window it is measured against, and session spend' },
26
+ { name: 'expand', aliases: [], description: 'Expand / collapse a recent tool card (default: last)' },
27
+ { name: 'tools', aliases: [], description: 'List active tools' },
28
+ { name: 'clear', aliases: [], description: 'Start a new conversation; "/clear screen" only clears the screen' },
29
+ { name: 'reset', aliases: [], description: 'Alias of /clear' },
30
+ { name: 'cwd', aliases: [], description: 'Show or change the tool working directory' },
31
+ { name: 'save', aliases: [], description: 'Save the session to JSON' },
32
+ { name: 'resume', aliases: [], description: 'Load a saved session' },
33
+ { name: 'session', aliases: [], description: 'Show this session id and file; "/session copy" copies the resume command' },
34
+ { name: 'branch', aliases: [], description: 'Open a new terminal on this session (Ctrl+L); the branch gets its own id' },
35
+ { name: 'copy', aliases: [], description: 'Copy the last answer to the clipboard' },
36
+ { name: 'mouse', aliases: [], description: 'Release the mouse to the terminal, or take it back' },
37
+ { name: 'terminal-setup', aliases: [], description: 'How Shift+Enter sends a newline in your terminal' },
38
+ { name: 'logs', aliases: [], description: 'Show where this session is being logged' },
39
+ { name: 'reload', aliases: [], description: 'Re-read config.json (after editing it in another window)' },
40
+ { name: 'perf', aliases: [], description: 'Render statistics (/perf reset clears the caches and the governor)' },
41
+ { name: 'bg', aliases: [], description: 'Background jobs: list | logs <id> [n] | stop <id|all> | status' },
42
+ { name: 'exit', aliases: ['quit'], description: 'Exit' },
43
+ { name: 'queue', aliases: [], description: '\u67e5\u770b\u5f85\u5904\u7406\u6d88\u606f\u5168\u6587' },
44
+ { name: 'kit', aliases: [], description: 'Agent kits: status, list, use for this session' },
45
+ { name: 'prompts', aliases: [], description: 'Quick prompt library: pick, list, add, edit, remove, reorder' },
46
+ { name: 'agents', aliases: [], description: 'Open the subagent board: every child, its facts and its timeline' },
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]' },
49
+ { name: 'gov', aliases: [], description: 'Governed multi-agent team: /gov help' },
50
+ { name: 'keys', aliases: [], description: 'List every keyboard shortcut (opens the drawer)' },
51
+ { name: 'task', aliases: [], description: 'Show the header task summary (/task refresh regenerates it)' },
52
+ ];
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The ONE place the slash-command set is assembled, shared by the terminal App and the
3
+ * desktop host's menu metadata (`host/commands.ts`). Two hand-kept copies of this list is
4
+ * how a menu and a dispatcher drift apart without anybody noticing.
5
+ */
6
+ import { CommandRegistry } from './registry.js';
7
+ import type { SkillService } from '../skills/service.js';
8
+ export interface CommandRegistryOptions {
9
+ /** Present only when skills are enabled; absent registers no skill commands at all. */
10
+ skills?: SkillService;
11
+ version: string;
12
+ }
13
+ export declare function createCommandRegistry(options: CommandRegistryOptions): CommandRegistry;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The ONE place the slash-command set is assembled, shared by the terminal App and the
3
+ * desktop host's menu metadata (`host/commands.ts`). Two hand-kept copies of this list is
4
+ * how a menu and a dispatcher drift apart without anybody noticing.
5
+ */
6
+ import { registerBuiltinCommands } from './builtins.js';
7
+ import { CommandRegistry } from './registry.js';
8
+ import { makeSkillsCommand, registerSkillCommands } from './skills.js';
9
+ export function createCommandRegistry(options) {
10
+ const registry = new CommandRegistry();
11
+ // Order matters: built-ins first, so `registerSkillCommands` sees them when it probes
12
+ // for name conflicts and a skill can never displace `/exit` (D6).
13
+ registerBuiltinCommands(registry);
14
+ if (options.skills) {
15
+ registry.register(makeSkillsCommand(options.skills, options.version));
16
+ registerSkillCommands(registry, options.skills);
17
+ }
18
+ return registry;
19
+ }
@@ -227,7 +227,11 @@ export function parseBudgetTokens(raw) {
227
227
  if (!match)
228
228
  return Number.NaN;
229
229
  const scale = match[2] === 'm' ? 1_000_000 : match[2] === 'k' ? 1_000 : 1;
230
- return Math.floor(Number(match[1]) * scale);
230
+ const value = Number(match[1]) * scale;
231
+ // 0 means "no budget"; a positive amount that rounds down to 0 must not silently become it.
232
+ if (value > 0 && Math.floor(value) === 0)
233
+ return Number.NaN;
234
+ return Math.floor(value);
231
235
  }
232
236
  function setBudget(ctx) {
233
237
  const raw = ctx.args.trim().split(/\s+/)[1];
@@ -4,19 +4,19 @@
4
4
  */
5
5
  import { mkdirSync, writeFileSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
- import { computeToolPolicy, rankCatalogRecords, renderSkillInvocation, } from '@aragon-agent/core';
7
+ import { computeToolPolicy, rankCatalogRecords, } from '@aragon-agent/core';
8
8
  import { resolveDeclaredTool } from '@aragon-agent/core/skills';
9
9
  import { installSkill, removeSkill, renderSkillMarkdown } from '../skills/installer.js';
10
10
  import { writableRootFor } from '../skills/installer.js';
11
11
  import { checkManifest } from '../skills/manifest.js';
12
+ import { isInvocableSkill, shortSkillDescription, SKILLS_COMMAND_DESCRIPTION, skillCommandNames, } from '../skills/command-names.js';
12
13
  import { updateAllSkills, updateSkill, isHardFailure } from '../skills/updater.js';
13
- import { currentPlatform } from '../skills/node-host.js';
14
14
  import { listUsage, resetUsage, getUsagePath } from '../skills/usage.js';
15
15
  import { SKILL_TRIAGE_LIMITS } from '../skills/triage.js';
16
16
  import { HOST_TOOL_NAMES, SKILL_TOOL_FLOOR } from '../tools/index.js';
17
17
  import { SKILLS_TOOL_POLICY_MODES, isSkillsToolPolicyMode } from '@aragon-agent/tui/model/config/schema';
18
18
  import { pickGlyphs } from '@aragon-agent/tui/ui/glyphs';
19
- import { INDEX_SKILL_NAME, isIndexBuildArgs } from './index-build.js';
19
+ import { prepareSkillInvocation } from '../skills/invoke.js';
20
20
  function marksFor(ctx) {
21
21
  const cfg = ctx.controller.getConfig();
22
22
  const glyphs = pickGlyphs({ colorLevel: cfg.colorLevel ?? 0, unicode: cfg.unicode ?? false });
@@ -38,8 +38,7 @@ function markFor(record, marks) {
38
38
  return marks.ok;
39
39
  }
40
40
  function shortDescription(record, max = 60, ellipsis = '...') {
41
- const one = record.description.replace(/\s+/g, ' ').trim();
42
- return one.length > max ? `${one.slice(0, max - ellipsis.length)}${ellipsis}` : one;
41
+ return shortSkillDescription(record.description, max, ellipsis);
43
42
  }
44
43
  function formatRow(record, marks, glyphs) {
45
44
  const shadow = record.shadowed.length > 0 ? ` ${marks.shadowed}shadowed by ${record.shadowed[0].scope}` : '';
@@ -643,7 +642,7 @@ function trustFromCommand(ctx, service, dir, untrust) {
643
642
  export function makeSkillsCommand(service, version) {
644
643
  return {
645
644
  name: 'skills',
646
- description: 'List and manage skills',
645
+ description: SKILLS_COMMAND_DESCRIPTION,
647
646
  run: (ctx) => runSkills(ctx, service, version),
648
647
  };
649
648
  }
@@ -663,82 +662,34 @@ export function makeSkillsCommand(service, version) {
663
662
  */
664
663
  export function registerSkillCommands(registry, service) {
665
664
  for (const record of service.list()) {
666
- if (record.disabled || record.invalid)
667
- continue;
668
- if (record.frontmatter.activation === 'manual')
665
+ if (!isInvocableSkill(record))
669
666
  continue;
670
667
  const command = makeSkillCommand(record, service);
671
- registry.register({ ...command, name: `skill:${record.name}` });
672
- if (registry.get(record.name) === undefined) {
673
- registry.register({ ...command, name: record.name });
674
- }
668
+ // The probe is evaluated against the registry AS IT STANDS, so registering the namespaced
669
+ // form first cannot make the bare name look taken.
670
+ const [namespaced, ...bare] = skillCommandNames(record, (name) => registry.get(name) !== undefined);
671
+ registry.register({ ...command, name: namespaced });
672
+ for (const name of bare)
673
+ registry.register({ ...command, name });
675
674
  }
676
675
  }
677
- /**
678
- * The card's raw material for one skill run (tui-invocation-cards section 3.3). The
679
- * command line always uses the namespaced `/skill:<name>` form - the stable handle -
680
- * even when the user typed the bare name. Ctrl+I's machine-written sentence is NOT the
681
- * user's input (RV-3): the card says `ctrl+i` and shows no input row.
682
- */
683
- function skillCardInput(record, args, sent) {
684
- const machine = record.name === INDEX_SKILL_NAME && isIndexBuildArgs(args);
685
- const version = record.frontmatter.version;
686
- const facts = [
687
- ...(machine ? ['ctrl+i'] : []),
688
- ...(version ? [`v${version}`] : []),
689
- record.scope,
690
- `${sent.kb} KB`,
691
- ...(sent.files > 0 ? [`${sent.files} files`] : []),
692
- ...(sent.policy ? ['tool ceiling'] : []),
693
- ];
694
- const typed = machine ? '' : args;
695
- return {
696
- variant: 'skill',
697
- name: record.name,
698
- commandLine: typed === '' ? `/skill:${record.name}` : `/skill:${record.name} ${typed}`,
699
- input: typed,
700
- facts,
701
- };
702
- }
703
676
  function makeSkillCommand(record, service) {
704
677
  return {
705
678
  name: record.name,
706
679
  description: shortDescription(record),
707
680
  rendersInvocationCard: () => true,
708
681
  run: (ctx) => {
709
- let loaded;
710
- try {
711
- loaded = service.loadBody(record.name);
712
- }
713
- catch (err) {
714
- ctx.notify('error', `Could not load skill "${record.name}": ${err.message}`);
682
+ const prepared = prepareSkillInvocation(record, ctx.args, service, () => ctx.controller.listTools().map((t) => t.name));
683
+ if (!prepared.ok) {
684
+ ctx.notify('error', prepared.error);
715
685
  return;
716
686
  }
717
- const hydrated = { ...record, body: loaded.body, files: loaded.files };
718
- service.getRegistry().activate(record.name);
719
- // QUEUE, do not enter (D-G2). `ctx.submit()` below turns into the user
720
- // message that OPENS the next turn, and `controller.prompt()` clears the
721
- // frame on its way in — so entering here would leave the one turn the user
722
- // explicitly asked this skill to run as the only unconstrained one.
723
- service.queueFrame(record.name);
724
- const policy = service.pendingToolPolicyView(() => ctx.controller.listTools().map((t) => t.name));
725
- const message = renderSkillInvocation(hydrated, ctx.args, {
726
- // The same knob as the tool path, at last (GG3 / FG3).
727
- bodyMaxBytes: service.bodyMaxBytes(),
728
- platform: currentPlatform(),
729
- ...(policy ? { policy } : {}),
730
- });
731
- // The SUBMITTED size, not the file's. Reporting 480 KB while sending 30 KB
732
- // is how a user concludes the truncation marker is a rendering glitch.
733
- const kb = Math.max(1, Math.round(Buffer.byteLength(message, 'utf-8') / 1024));
734
687
  if (ctx.invocationCards === false) {
735
- ctx.notify('info', `Skill "${record.name}" loaded (${kb} KB submitted, ${loaded.files.length} bundled files).`);
736
- ctx.submit(message);
688
+ ctx.notify('info', `Skill "${record.name}" loaded (${prepared.kb} KB submitted, ${prepared.files} bundled files).`);
689
+ ctx.submit(prepared.message);
737
690
  return;
738
691
  }
739
- ctx.submit(message, {
740
- invocation: skillCardInput(record, ctx.args, { kb, files: loaded.files.length, policy: !!policy }),
741
- });
692
+ ctx.submit(prepared.message, { invocation: prepared.card });
742
693
  },
743
694
  };
744
695
  }
@@ -43,6 +43,8 @@ import { type PersistedConfig } from '@aragon-agent/tui/model/config/schema';
43
43
  * process env wins — dotenv never overrides already-set variables).
44
44
  */
45
45
  export declare function loadDotenv(cwd: string): void;
46
+ /** Provider -> the env vars that may carry its key (first non-empty wins). */
47
+ export declare const PROVIDER_ENV_KEYS: Record<string, string[]>;
46
48
  export interface EnvConfig {
47
49
  /** Non-secret overrides sourced from ARAGON_* env vars. */
48
50
  partial: Partial<PersistedConfig>;
@@ -52,7 +52,7 @@ export function loadDotenv(cwd) {
52
52
  dotenv.config({ path: join(cwd, '.env') });
53
53
  }
54
54
  /** Provider -> the env vars that may carry its key (first non-empty wins). */
55
- const PROVIDER_ENV_KEYS = {
55
+ export const PROVIDER_ENV_KEYS = {
56
56
  anthropic: ['ANTHROPIC_API_KEY'],
57
57
  openai: ['OPENAI_API_KEY'],
58
58
  google: ['GOOGLE_API_KEY', 'GEMINI_API_KEY'],
@@ -48,6 +48,12 @@ export declare function usageOf(message: AssistantMessage | undefined): {
48
48
  usage: TokenUsage;
49
49
  missing: boolean;
50
50
  };
51
+ /**
52
+ * Sum two usages. Cache read/write tokens are real spend (Anthropic reports `input_tokens`
53
+ * EXCLUDING them), so they are carried; a cache field appears only when non-zero so a
54
+ * session without prompt caching keeps the two-field shape. `cost` is deliberately NOT
55
+ * summed: a partial sum would read as complete (price it from the totals instead).
56
+ */
51
57
  export declare function accumulateUsage(total: TokenUsage, next: TokenUsage): TokenUsage;
52
58
  export interface ReviewRequestParams {
53
59
  ref: ModelRef;
@@ -76,10 +76,20 @@ export function usageOf(message) {
76
76
  missing: usage === undefined,
77
77
  };
78
78
  }
79
+ /**
80
+ * Sum two usages. Cache read/write tokens are real spend (Anthropic reports `input_tokens`
81
+ * EXCLUDING them), so they are carried; a cache field appears only when non-zero so a
82
+ * session without prompt caching keeps the two-field shape. `cost` is deliberately NOT
83
+ * summed: a partial sum would read as complete (price it from the totals instead).
84
+ */
79
85
  export function accumulateUsage(total, next) {
86
+ const cacheRead = (total.cacheReadTokens ?? 0) + (next.cacheReadTokens ?? 0);
87
+ const cacheWrite = (total.cacheWriteTokens ?? 0) + (next.cacheWriteTokens ?? 0);
80
88
  return {
81
89
  inputTokens: total.inputTokens + next.inputTokens,
82
90
  outputTokens: total.outputTokens + next.outputTokens,
91
+ ...(cacheRead > 0 ? { cacheReadTokens: cacheRead } : {}),
92
+ ...(cacheWrite > 0 ? { cacheWriteTokens: cacheWrite } : {}),
83
93
  };
84
94
  }
85
95
  /**
@@ -5,9 +5,14 @@
5
5
  *
6
6
  * WHAT IS COUNTED. `run.usage` and `governance.budgetTokens` cover the governed TEAM's
7
7
  * spend only: every dispatch's `outcome.usage` plus `outcome.overseerUsage` (the
8
- * supervisor's fast-tier spend). The orchestrator's own turns are already in the
9
- * session total on the status bar, and labelling this figure "team tokens" everywhere
10
- * keeps a user from reading it as the session total.
8
+ * supervisor's fast-tier spend). The unit is input + cacheRead + cacheWrite + output (the
9
+ * same formula as the status bar's context occupancy): Anthropic reports `input_tokens`
10
+ * EXCLUDING cached tokens, and on a long cached run the cache traffic is most of the spend,
11
+ * so an input+output budget would not bound spend at all. This is a deliberate deviation
12
+ * from the literal wording of the spec (8.5), which was amended alongside. The
13
+ * orchestrator's own turns are already in the session total on the status bar, and
14
+ * labelling this figure "team tokens" everywhere keeps a user from reading it as the
15
+ * session total.
11
16
  *
12
17
  * COST IS NEVER FABRICATED. `costUsd` stays `null` until a price table is supplied; once
13
18
  * it is `null` it is only replaced by a number when a price arrives, and a run that had
@@ -30,10 +35,12 @@ export declare const EMPTY_RUN_USAGE: RunUsage;
30
35
  export declare function newRunUsage(): RunUsage;
31
36
  /**
32
37
  * Fold one dispatch into the run usage. Returns a NEW object. If any non-empty part of
33
- * the dispatch cannot be priced (`price` absent) the running cost becomes `null`.
38
+ * the dispatch cannot be priced the running cost becomes `null`. The children's usage is
39
+ * priced with `price`; the supervisor runs on the FAST tier and is priced with
40
+ * `overseerPrice` ONLY - never with the children's table (a wrong price reads as complete).
34
41
  */
35
- export declare function accumulateUsage(previous: RunUsage, outcome: DispatchUsage, price?: ModelCost): RunUsage;
36
- /** Total team tokens (input + output) - the budget's unit. */
42
+ export declare function accumulateUsage(previous: RunUsage, outcome: DispatchUsage, price?: ModelCost, overseerPrice?: ModelCost): RunUsage;
43
+ /** Total team tokens (input + cache read + cache write + output) - the budget's unit. */
37
44
  export declare function totalTokens(usage: RunUsage): number;
38
45
  export type BudgetLevel = 'ok' | 'warning' | 'exhausted' | 'unlimited';
39
46
  /** `budgetTokens <= 0` means unlimited. */
@@ -46,6 +53,11 @@ export declare function shouldStopNewStages(usage: RunUsage, budgetTokens: numbe
46
53
  export declare function formatTokens(count: number): string;
47
54
  /** "$0.42" or "pricing unknown". */
48
55
  export declare function formatCost(costUsd: number | null): string;
56
+ /**
57
+ * Whole-number percent of the budget used. It agrees with `budgetLevel`: "100%" only once the
58
+ * budget is exhausted (the 99.5% case used to print 100% while a new stage was still allowed).
59
+ */
60
+ export declare function budgetPercent(usage: RunUsage, budgetTokens: number): number;
49
61
  /** One line for digests and `gov_run status`. Always says "team tokens". */
50
62
  export declare function budgetLine(usage: RunUsage, budgetTokens: number): string;
51
63
  /** The `BUDGET WARNING` / refusal text, or null when nothing needs saying. */