@hexdecimal16/nexo 0.4.3 → 0.4.5

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.
package/README.md CHANGED
@@ -3,60 +3,60 @@
3
3
  [![npm version](https://img.shields.io/npm/v/@hexdecimal16/nexo)](https://www.npmjs.com/package/@hexdecimal16/nexo)
4
4
  [![test](https://github.com/hexdecimal16/nexo/actions/workflows/test.yml/badge.svg?event=push)](https://github.com/hexdecimal16/nexo/actions/workflows/test.yml)
5
5
 
6
- An AI agent engine that runs on your machine. It tracks what each run costs, scores the results, and keeps every run inspectable. Use it from the terminal, from a web run inspector, or from Node code.
6
+ nexo is an AI agent that runs on your machine. It tracks what each run costs, scores the results, and keeps every run inspectable. You can use it from the terminal, from a web run inspector, or from Node code.
7
7
 
8
8
  Requires Node 22.19 or newer.
9
9
 
10
10
  ## Install
11
11
 
12
- From npm:
13
-
14
12
  ```sh
15
13
  npm install -g @hexdecimal16/nexo
14
+ nexo init # pick two models (s1, s2), store their API keys, make one test call
16
15
  ```
17
16
 
18
- From source:
17
+ Running `nexo` for the first time also opens this setup. `nexo update` tells you when a newer version is out.
18
+
19
+ ## Everyday use
19
20
 
20
21
  ```sh
21
- git clone https://github.com/hexdecimal16/nexo.git
22
- cd nexo
23
- npm ci
24
- npm run nexo -- init
22
+ nexo # chat; type /settings to change anything
23
+ nexo run "summarize this folder" --budget 0.25 # one task, then exit
24
+ nexo ui # run inspector: traces, costs, scores
25
+ nexo cost --by day # what you spent
26
+ nexo doctor # check Node, config, keys and tools
25
27
  ```
26
28
 
27
- To install a `nexo` command globally from your checkout:
29
+ `nexo --help` lists every command. Data lives in `~/.nexo`. Set `NEXO_HOME` to move it.
28
30
 
29
- ```sh
30
- npm run build
31
- (cd dist && npm pack --pack-destination /tmp) && npm install -g /tmp/nexo-*.tgz
32
- ```
31
+ ## Settings and keys
33
32
 
34
- ## First run
33
+ Every option is in `/settings` inside a chat, or in `nexo settings` from the shell:
35
34
 
36
35
  ```sh
37
- nexo init # pick models, store API keys, make one small test call
38
- nexo doctor # check Node, config, keys and the data directory
39
- nexo # start a chat
40
- nexo run "summarize this folder" --budget 0.25
41
- nexo ui # open the run inspector (traces, costs, scores)
36
+ nexo settings keys # which keys are set and where from (never the values)
37
+ nexo settings set-key anthropic # hidden prompt, or pipe the key on stdin
38
+ nexo settings set budgets.perRunUsd 0.5
42
39
  ```
43
40
 
44
- For scripts, `nexo init --yes --s1 <provider/id> --s2 <provider/id>` runs without prompts and reads keys from the provider's environment variable. `nexo doctor --json` prints the checks for automation.
41
+ Keys are stored in `~/.nexo/credentials.json` (mode 600) and redacted from logs. A provider's environment variable, such as `ANTHROPIC_API_KEY`, takes precedence over the stored key.
45
42
 
46
- Data lives in `~/.nexo` (set `NEXO_HOME` to change it).
43
+ ## Optional tools
47
44
 
48
- ### Web search
45
+ **Web search.** Set a [Brave Search](https://api-dashboard.search.brave.com) or [Tavily](https://app.tavily.com) key and the agent gets a `web_search` tool. With both keys, it queries both and merges the results.
49
46
 
50
- The agent gets a `web_search` tool once a [Brave Search](https://api-dashboard.search.brave.com) or [Tavily](https://app.tavily.com) key is set. With both keys, it queries both in parallel and merges the results. Results found by both rank higher, and a provider that fails is skipped. The tool is allowed without a prompt (`tools.policy.web_search`), including in unattended runs.
47
+ ```sh
48
+ nexo settings set-key brave # or tavily
49
+ nexo search "node 22 release notes" # try it without a model
50
+ ```
51
+
52
+ **Browser control.** The agent can drive your own Chrome, with your signed-in sites, through [playwright-cli](https://github.com/microsoft/playwright-cli) and the Playwright Extension. It keeps page snapshots on disk and reads only the lines it needs, so browsing uses few tokens.
51
53
 
52
54
  ```sh
53
- nexo settings set-key brave # or tavily; hidden prompt, or pipe the key on stdin
54
- nexo settings keys # which keys are set, and from where
55
- nexo search "node 22 release notes" # try it without a model (--count <n>, --json)
56
- nexo settings set tools.webSearch.count 10
55
+ npm install -g @playwright/cli@latest
56
+ nexo settings set-key playwright-personal # paste the token from the Playwright Extension in that Chrome profile
57
57
  ```
58
58
 
59
- `BRAVE_API_KEY` and `TAVILY_API_KEY` work too, and they take precedence over the credentials file. In a chat, `/settings` lists both keys.
59
+ Add one key per Chrome profile, such as `playwright-work`. First-run setup and `/settings` offer the same step. The browser skill tells the agent to ask before sending, posting, buying or deleting anything. Its wrapper also blocks the commands that run arbitrary code in your pages.
60
60
 
61
61
  ## Use it from Node
62
62
 
@@ -72,21 +72,25 @@ try {
72
72
  }
73
73
  ```
74
74
 
75
- Keys can be passed in code without touching disk: `createNexo({ apiKeys: { anthropic: "…", brave: "…" } })`. `nexo.webSearch(query)` searches directly, without a model and at no model cost. `nexo.keys()`, `nexo.setKey()` and `nexo.removeKey()` manage stored keys.
76
-
77
- The SDK denies every tool approval by default, so a backend never waits on a person. Always pass `budgetUsd`. `checkSetup()` runs the doctor checks without starting the engine, which suits a start-up pre-flight.
75
+ - Pass keys in code without writing them to disk: `createNexo({ apiKeys: { anthropic: "…" } })`.
76
+ - `nexo.keys()`, `nexo.setKey()` and `nexo.removeKey()` manage stored keys. `nexo.webSearch(query)` searches without a model.
77
+ - The SDK denies every tool approval by default, so a backend never waits on a person. Pass `allowAll: true` to `createNexo` or `run` to auto-approve tool actions in sandboxed environments. Always pass `budgetUsd`.
78
+ - `checkSetup()` runs the doctor checks without starting the engine, for a start-up pre-flight.
78
79
 
79
80
  ## Security
80
81
 
81
- nexo tools run shell commands and edit files. Path confinement is not a sandbox. If you run nexo for other people, give each request its own workspace and use a container for real isolation.
82
+ nexo's tools run shell commands and edit files. Path confinement is not a sandbox. If you run nexo for other people, give each request its own workspace and use a container for real isolation.
82
83
 
83
84
  ## Develop
84
85
 
85
86
  ```sh
87
+ git clone https://github.com/hexdecimal16/nexo.git && cd nexo
88
+ npm ci
89
+ npm run nexo -- init # run from source
86
90
  npm run typecheck
87
91
  npm test
88
- npm run build # release build into dist/
89
- npm run bump -- minor
92
+ npm run build # release build into dist/
93
+ npm run bump -- patch # set one version on every package
90
94
  ```
91
95
 
92
96
  ## License
package/cli/src/common.js CHANGED
@@ -3,7 +3,7 @@ export const USAGE = `Usage:
3
3
  nexo start an interactive session (needs a terminal)
4
4
  nexo --resume [id] [--all] resume a session (a picker of this project's sessions when no id is given;
5
5
  --all lists every project)
6
- nexo [--workspace <dir>] [--model <s1|s2|provider/id>] [--effort <level>] options for a new session
6
+ nexo [--workspace <dir>] [--model <s1|s2|provider/id>] [--effort <level>] [--allow-all] options for a new session
7
7
  without --workspace each turn works in its own run folder (files carried over
8
8
  from the previous turn); --workspace . works in the current folder
9
9
  nexo sessions [--limit <n>]
@@ -17,7 +17,7 @@ export const USAGE = `Usage:
17
17
  nexo settings remove-key <provider> delete a key from the credentials file
18
18
  nexo settings keys key status of the model and web search providers (never the keys)
19
19
  nexo search <query...> [--count <n>] [--json] search the web with the configured Brave/Tavily keys
20
- nexo run <instruction...> [--skill <name>] [--model <s1|s2|provider/id>] [--effort <level>] [--workspace <dir>] [--budget <usd>] [--no-review]
20
+ nexo run <instruction...> [--skill <name>] [--model <s1|s2|provider/id>] [--effort <level>] [--workspace <dir>] [--budget <usd>] [--no-review] [--allow-all]
21
21
  nexo cost [--by model|tier|day|run|skill] [--since YYYY-MM-DD]
22
22
  nexo reindex
23
23
  nexo review-queue [--limit <n>] [--days <n>] recent runs without a verdict, worst first
@@ -53,7 +53,7 @@ export function parseInteractiveArgs(args) {
53
53
  else
54
54
  rest.push(arg);
55
55
  }
56
- const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { workspace: { type: "string" }, model: { type: "string" }, effort: { type: "string" }, all: { type: "boolean" } } });
56
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { workspace: { type: "string" }, model: { type: "string" }, effort: { type: "string" }, all: { type: "boolean" }, "allow-all": { type: "boolean" } } });
57
57
  if (values.all && !resume)
58
58
  throw usageError("--all applies to --resume only");
59
59
  if (positionals.length > 0)
@@ -63,7 +63,7 @@ export function parseInteractiveArgs(args) {
63
63
  if (resume && (values.workspace !== undefined || values.model !== undefined || values.effort !== undefined)) {
64
64
  throw usageError("--resume reopens a session as it was; --workspace, --model and --effort apply to new sessions only");
65
65
  }
66
- return { resume, workspace: values.workspace, model: values.model, effort: values.effort, all: values.all === true };
66
+ return { resume, workspace: values.workspace, model: values.model, effort: values.effort, all: values.all === true, allowAll: values["allow-all"] === true };
67
67
  }
68
68
  const PICKER_LIMIT = 50;
69
69
  /**
@@ -133,7 +133,13 @@ export async function interactiveCommand(args, io, options, stdio) {
133
133
  signal: options.signal,
134
134
  openSession: (prompter) => {
135
135
  const deps = buildDeps(prompter);
136
- return resumeId ? resumeSession(deps, resumeId) : createSession(deps, { cwd, workspace: parsed.workspace, model: parsed.model, effort: parsed.effort });
136
+ if (resumeId) {
137
+ const s = resumeSession(deps, resumeId);
138
+ if (parsed.allowAll)
139
+ s.setAllowAll(true);
140
+ return s;
141
+ }
142
+ return createSession(deps, { cwd, workspace: parsed.workspace, model: parsed.model, effort: parsed.effort, allowAll: parsed.allowAll });
137
143
  },
138
144
  resumeSession: (id, prompter) => resumeSession(buildDeps(prompter), id),
139
145
  });
package/cli/src/main.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { judgeFamilyWarnings } from "../../core/src/index.js";
3
3
  import { EFFORTS } from "../../router/src/index.js";
4
+ import { parseSkillInvocation } from "../../skills/src/index.js";
4
5
  import { costReport, ensureNexoDirs, openDb, reindex, resolveNexoPaths } from "../../store/src/index.js";
5
6
  import { NexoError, toErrorPayload } from "../../telemetry/src/index.js";
6
7
  import { nonInteractivePrompter } from "../../tools/src/index.js";
@@ -92,6 +93,7 @@ async function runCommand(args, io, options) {
92
93
  workspace: { type: "string" },
93
94
  budget: { type: "string" },
94
95
  "no-review": { type: "boolean" },
96
+ "allow-all": { type: "boolean" },
95
97
  },
96
98
  });
97
99
  const instruction = positionals.join(" ").trim();
@@ -134,16 +136,19 @@ async function runCommand(args, io, options) {
134
136
  });
135
137
  for (const warning of judgeFamilyWarnings(runtime.config))
136
138
  io.stderr.write(`warning: ${escapeControl(warning)}\n`);
139
+ // `nexo run "/impeccable init"` reads like `nexo run --skill impeccable init`, matching the TUI and SDK sessions.
140
+ const invoked = values.skill ? null : parseSkillInvocation(instruction, runtime.skills.skills.keys());
137
141
  let result;
138
142
  try {
139
143
  result = await runtime.engine.run({
140
- instruction,
141
- skill: values.skill,
144
+ instruction: invoked?.instruction ?? instruction,
145
+ skill: values.skill ?? invoked?.skill,
142
146
  model: values.model,
143
147
  effort: values.effort,
144
148
  workspace: values.workspace,
145
149
  projectDir: options.cwd ?? process.cwd(),
146
150
  budgetUsd,
151
+ allowAll: values["allow-all"] === true,
147
152
  }, options.signal);
148
153
  }
149
154
  finally {
@@ -1,4 +1,16 @@
1
1
  import { createInterface } from "node:readline/promises";
2
+ /** Model text on one terminal line: control characters become spaces. */
3
+ const clean = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ");
4
+ /** `2` or `1,3` picks options (numbers in range; one only for single-select); anything else is a typed answer. */
5
+ export function parseTtyAnswer(q, raw) {
6
+ if (/^\d+(\s*,\s*\d+)*$/.test(raw)) {
7
+ const picks = [...new Set(raw.split(",").map((s) => Number(s.trim())))];
8
+ if (picks.every((n) => n >= 1 && n <= q.options.length) && (q.multiSelect || picks.length === 1)) {
9
+ return { question: q.question, selected: q.options.filter((_, i) => picks.includes(i + 1)).map((o) => o.label) };
10
+ }
11
+ }
12
+ return { question: q.question, selected: [], text: raw };
13
+ }
2
14
  function isAbortError(error) {
3
15
  return error instanceof Error && error.name === "AbortError";
4
16
  }
@@ -36,6 +48,32 @@ export function createTtyPrompter(input, output, options = {}) {
36
48
  rl.close();
37
49
  }
38
50
  };
51
+ const askQuestions = async (request, signal) => {
52
+ if (signal?.aborted)
53
+ return null;
54
+ const rl = createInterface({ input, output });
55
+ try {
56
+ const answers = [];
57
+ for (const q of request.questions) {
58
+ const lines = [`${q.header ? `[${clean(q.header)}] ` : ""}${clean(q.question)}`];
59
+ q.options.forEach((o, i) => lines.push(` ${i + 1}. ${clean(o.label)}${o.description ? ` - ${clean(o.description)}` : ""}`));
60
+ lines.push(` ${q.multiSelect ? "Numbers separated by commas" : "A number"}, or type your own answer (empty skips all questions)`);
61
+ const raw = (await rl.question(`${lines.join("\n")}\n> `, { signal })).trim();
62
+ if (!raw)
63
+ return null;
64
+ answers.push(parseTtyAnswer(q, raw));
65
+ }
66
+ return { answers };
67
+ }
68
+ catch (error) {
69
+ if (isAbortError(error) && !signal?.aborted)
70
+ options.onInterrupt?.();
71
+ return null;
72
+ }
73
+ finally {
74
+ rl.close();
75
+ }
76
+ };
39
77
  return {
40
78
  interactive: Boolean(input.isTTY),
41
79
  approve(request, signal) {
@@ -43,5 +81,10 @@ export function createTtyPrompter(input, output, options = {}) {
43
81
  queue = turn.catch(() => undefined);
44
82
  return turn;
45
83
  },
84
+ ask(request, signal) {
85
+ const turn = queue.then(() => askQuestions(request, signal));
86
+ queue = turn.catch(() => undefined);
87
+ return turn;
88
+ },
46
89
  };
47
90
  }
@@ -186,7 +186,7 @@ export const DEFAULT_CONFIG = {
186
186
  instructions: [],
187
187
  skills: { dirs: ["$NEXO_HOME/skills", "./.nexo/skills"], pins: {} },
188
188
  tools: {
189
- policy: { read: "allow", write: "allow", edit: "allow", bash: "ask", web_fetch: "ask", web_search: "allow", load_skill: "allow", spawn: "allow" },
189
+ policy: { read: "allow", write: "allow", edit: "allow", bash: "ask", web_fetch: "ask", web_search: "allow", load_skill: "allow", spawn: "allow", ask_user: "allow" },
190
190
  rules: [],
191
191
  nonInteractiveAsk: "deny",
192
192
  autoApprove: "off",
@@ -4,7 +4,7 @@ import { createModelRegistry, DEFAULT_ROUTER_POLICY, ESCALATION_BLOCK_REASONS, e
4
4
  import { createLoadSkillTool, formatSkillIndex, parseSkillFile } from "../../../skills/src/index.js";
5
5
  import { createArtifactSet, enqueueLearnJob, getActiveArtifact, insertRun, isPidAlive, listPlaybookItems, listSpans, newId, recoverCrashedRuns, resolveSourcedArtifact, RunDir, sessionRunDirs, updateRun, } from "../../../store/src/index.js";
6
6
  import { NexoError, toErrorPayload } from "../../../telemetry/src/index.js";
7
- import { builtinToolDescriptions, createBuiltinTools, createChangeTracker, createPolicy, createWebSearchTool, FileLeases, SEARCH_PROVIDER_IDS, TOOL_OUTPUT_PREFIX, } from "../../../tools/src/index.js";
7
+ import { builtinToolDescriptions, createAskUserTool, createBuiltinTools, createChangeTracker, createPolicy, createWebSearchTool, FileLeases, SEARCH_PROVIDER_IDS, TOOL_OUTPUT_PREFIX, } from "../../../tools/src/index.js";
8
8
  import { realpathSync, statSync } from "node:fs";
9
9
  import { join } from "node:path";
10
10
  import { createApprovalClassifier } from "../approval/classifier.js";
@@ -157,6 +157,7 @@ export async function executeRun(env, input) {
157
157
  sessionRules: request.sessionRules ?? (() => []),
158
158
  ...(request.addSessionRule ? { addSessionRule: request.addSessionRule } : {}),
159
159
  auto: request.autoApprove ?? config.tools.autoApprove === "on",
160
+ allowAll: request.allowAll ?? false,
160
161
  userRequest: request.instruction,
161
162
  };
162
163
  // Resolve skill, model and workspace before creating anything on disk.
@@ -572,6 +573,10 @@ export async function executeRun(env, input) {
572
573
  });
573
574
  if (webSearchTool)
574
575
  baseTools.push(webSearchTool);
576
+ // ask_user only where someone can answer: a root run (not a rollout) whose prompter is interactive and implements ask.
577
+ // Headless, eval and optimize runs never see it, so they cannot block waiting on a person.
578
+ if (depth === 0 && !rollout && deps.prompter.interactive && deps.prompter.ask)
579
+ baseTools.push(createAskUserTool({ prompter: deps.prompter }));
575
580
  const toolCtx = {
576
581
  env,
577
582
  runId,
@@ -804,12 +809,13 @@ export async function executeRun(env, input) {
804
809
  sessionRules: approvals.sessionRules,
805
810
  ...(approvals.addSessionRule ? { addSessionRule: approvals.addSessionRule } : {}),
806
811
  ...(classifier ? { classify: (name, a, s) => classifier(name, a, toolCall.id, s) } : {}),
812
+ allowAll: approvals.allowAll,
807
813
  }
808
814
  : undefined);
809
815
  if (!auth.allowed)
810
816
  return { block: true, reason: toolErrorText(auth.error) };
811
817
  approvedBy.set(toolCall.id, auth.by);
812
- if (auth.by === "auto")
818
+ if (auth.by === "auto" || auth.by === "allow_all")
813
819
  deps.onEvent?.({ type: "approval", runId, depth, toolCallId: toolCall.id, toolName: toolCall.name, reason: deps.redact(auth.reason ?? "") });
814
820
  return undefined;
815
821
  },
@@ -2,6 +2,7 @@ import { realpathSync, statSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
  import { EFFORTS, isEffort, parseModelRef } from "../../../router/src/index.js";
4
4
  import { getSpent, latestSessionRunId, latestSessionRunWorkspace, deleteSessionRow, listSessionRows, maxSessionTurn, newId, recordFeedback, SessionDir, sessionRowFromJson, upsertSessionRow, } from "../../../store/src/index.js";
5
+ import { parseSkillInvocation } from "../../../skills/src/index.js";
5
6
  import { runBash, sameSessionRule } from "../../../tools/src/index.js";
6
7
  import { createRedactor, NexoError, toErrorPayload } from "../../../telemetry/src/index.js";
7
8
  import { checkAdmission, runBudgetLimit, sessionScope } from "../cost/admission.js";
@@ -96,6 +97,10 @@ export class Session {
96
97
  this.learner = new LearnWorker(this.env);
97
98
  this.save();
98
99
  }
100
+ /** The skills a turn can pin with `TurnOptions.skill`, as names and one-line descriptions. */
101
+ skills() {
102
+ return [...this.deps.skills.skills.values()].map((s) => ({ name: s.name, description: s.description }));
103
+ }
99
104
  get dirPath() {
100
105
  return this.dir.root;
101
106
  }
@@ -178,6 +183,14 @@ export class Session {
178
183
  this.state.autoApprove = on;
179
184
  this.save();
180
185
  }
186
+ /** Allow-all mode for this session: auto-approves all tool approval prompts without asking. */
187
+ get allowAll() {
188
+ return this.state.allowAll ?? false;
189
+ }
190
+ setAllowAll(on) {
191
+ this.state.allowAll = on;
192
+ this.save();
193
+ }
181
194
  get remainingUsd() {
182
195
  return Math.max(0, this.budgetUsd - this.state.costUsd);
183
196
  }
@@ -286,7 +299,10 @@ export class Session {
286
299
  const limit = runBudgetLimit(this.deps.db, config.budgets, this.env.now(), { run: config.budgets.perTurnShare * this.budgetUsd, session: remaining });
287
300
  const turnIndex = this.state.turns + 1;
288
301
  this.onEvent = options.onEvent;
289
- const sent = withShellNotes(this.state.pendingShell ?? [], instruction);
302
+ // `/impeccable init` pins the skill like `nexo run --skill`, so SDK sessions and the TUI read it the same way.
303
+ const invoked = options.skill ? null : parseSkillInvocation(instruction, this.deps.skills.skills.keys());
304
+ const skill = options.skill ?? invoked?.skill;
305
+ const sent = withShellNotes(this.state.pendingShell ?? [], invoked?.instruction ?? instruction);
290
306
  const workspace = this.state.workspace;
291
307
  const previous = workspace === null ? latestSessionRunWorkspace(this.deps.db, this.id) : undefined;
292
308
  const result = await executeRun(this.env, {
@@ -302,9 +318,11 @@ export class Session {
302
318
  ...(this.state.model ? { model: this.state.model } : {}),
303
319
  ...(this.continuesOnS2 ? { startOnS2: true } : {}),
304
320
  ...(this.effort ? { effort: this.effort } : {}),
321
+ ...(skill ? { skill } : {}),
305
322
  sessionRules: () => this.state.sessionRules ?? [],
306
323
  addSessionRule: (rule) => this.addSessionRule(rule),
307
324
  autoApprove: this.autoApprove,
325
+ allowAll: this.allowAll,
308
326
  onSteeringReady: (control) => {
309
327
  this.steerCtl = control;
310
328
  for (const text of this.steerPending.splice(0))
@@ -599,6 +617,7 @@ export function createSession(deps, options) {
599
617
  updatedAt: nowIso,
600
618
  lastRunId: null,
601
619
  context: null,
620
+ allowAll: options.allowAll ?? null,
602
621
  };
603
622
  const dir = SessionDir.create(deps.paths.sessions, id, deps.redact);
604
623
  const session = openSession(deps, dir, state, [], SessionLock.acquire(dir.root, id));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hexdecimal16/nexo",
3
- "version": "0.4.3",
3
+ "version": "0.4.5",
4
4
  "description": "nexo agent engine",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "repository": {
package/sdk/src/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export { checkSetup, createNexo } from "./nexo.js";
2
+ export { parseSkillInvocation } from "../../skills/src/index.js";
3
+ export { allowAllPrompter, nonInteractivePrompter } from "../../tools/src/index.js";
2
4
  export { createRuntime, openLogger } from "./runtime.js";
3
5
  export { NexoError } from "../../telemetry/src/index.js";
4
6
  export { trackRunTree } from "./run-tree.js";
package/sdk/src/nexo.js CHANGED
@@ -23,6 +23,7 @@ export function createNexo(options = {}) {
23
23
  const env = withHome(options);
24
24
  const cwd = options.cwd ?? process.cwd();
25
25
  const prompter = options.prompter ?? nonInteractivePrompter;
26
+ const allowAll = options.allowAll ?? false;
26
27
  const listeners = new Set();
27
28
  const runtime = createRuntime({
28
29
  env,
@@ -63,7 +64,7 @@ export function createNexo(options = {}) {
63
64
  if (onEvent)
64
65
  listeners.add(onEvent);
65
66
  try {
66
- return await runtime.engine.run(request, runOptions.signal);
67
+ return await runtime.engine.run(allowAll && request.allowAll === undefined ? { ...request, allowAll: true } : request, runOptions.signal);
67
68
  }
68
69
  finally {
69
70
  if (onEvent)
@@ -72,7 +73,7 @@ export function createNexo(options = {}) {
72
73
  },
73
74
  createSession(sessionOptions) {
74
75
  live();
75
- return createSession(sessionDeps(), sessionOptions);
76
+ return createSession(sessionDeps(), allowAll && sessionOptions.allowAll === undefined ? { ...sessionOptions, allowAll: true } : sessionOptions);
76
77
  },
77
78
  resumeSession(id) {
78
79
  live();
@@ -1,3 +1,4 @@
1
1
  export * from "./frontmatter.js";
2
+ export * from "./invocation.js";
2
3
  export * from "./load-skill-tool.js";
3
4
  export * from "./loader.js";
@@ -0,0 +1,18 @@
1
+ /** `/name` or `/skill:name`, then optional text; skill names follow the loader's rule (lowercase words joined by `-`). */
2
+ const INVOCATION = /^\/(skill:)?([a-z0-9]+(?:-[a-z0-9]+)*)(?:\s+([\s\S]*))?$/;
3
+ /**
4
+ * Reads `/impeccable init` as { skill: "impeccable", instruction: "init" } when `impeccable` is one of `names`.
5
+ * `/skill:<name>` always means the skill, so a skill whose name a front end's built-in command uses stays reachable.
6
+ * Returns null for any other text (plain messages, paths like `/tmp/x`, unknown names), which the caller handles as before.
7
+ * With no text after the name, the instruction asks the agent to run the skill.
8
+ */
9
+ export function parseSkillInvocation(text, names) {
10
+ const match = INVOCATION.exec(text.trim());
11
+ if (!match)
12
+ return null;
13
+ const name = match[2];
14
+ if (![...names].includes(name))
15
+ return null;
16
+ const args = (match[3] ?? "").trim();
17
+ return { skill: name, instruction: args || `Run the ${name} skill.` };
18
+ }
@@ -0,0 +1,56 @@
1
+ import { Type } from "typebox";
2
+ const OptionSchema = Type.Object({
3
+ label: Type.String({ minLength: 1, maxLength: 80, description: "Short answer text the user picks (1-5 words)" }),
4
+ description: Type.Optional(Type.String({ maxLength: 200, description: "What choosing this option means or implies" })),
5
+ });
6
+ const QuestionSchema = Type.Object({
7
+ question: Type.String({ minLength: 1, maxLength: 500, description: "The complete question, ending with a question mark" }),
8
+ header: Type.Optional(Type.String({ maxLength: 24, description: "Very short tag shown above the question, e.g. \"Scope\"" })),
9
+ options: Type.Array(OptionSchema, { minItems: 2, maxItems: 4, description: "2-4 distinct choices; the user can always type their own answer instead" }),
10
+ multiSelect: Type.Optional(Type.Boolean({ description: "True when the user may pick more than one option" })),
11
+ });
12
+ const AskUserParams = Type.Object({ questions: Type.Array(QuestionSchema, { minItems: 1, maxItems: 4 }) });
13
+ export const ASK_USER_DESCRIPTION = "Ask the user 1-4 multiple-choice questions and wait for the answers. Use it when a requirement is ambiguous or a decision is consequential and neither the instruction nor the workspace settles it (scope, target, trade-offs, design direction). Do not use it to ask permission for a tool call (approval prompts do that). The user can pick options or type their own answer. If they decline, proceed on your best judgment and state what you assumed.";
14
+ export const ASK_USER_DECLINED = "The user declined to answer. Proceed on your best judgment and state what you assumed.";
15
+ /** The answers as text for the model: one `Q:` / `A:` pair per question. */
16
+ export function formatQuestionAnswer(answer) {
17
+ return answer.answers
18
+ .map((a) => {
19
+ const parts = [...a.selected];
20
+ if (a.text)
21
+ parts.push(`(typed) ${a.text}`);
22
+ return `Q: ${a.question}\nA: ${parts.length > 0 ? parts.join(", ") : "(no answer)"}`;
23
+ })
24
+ .join("\n\n");
25
+ }
26
+ /** `ask_user`: structured questions answered through the prompter (TUI box, terminal prompt, or an SDK host's UI). */
27
+ export function createAskUserTool(options) {
28
+ return {
29
+ name: "ask_user",
30
+ label: "Ask user",
31
+ description: ASK_USER_DESCRIPTION,
32
+ parameters: AskUserParams,
33
+ execute: async (_toolCallId, params, signal) => {
34
+ const { prompter } = options;
35
+ if (!prompter.interactive || !prompter.ask) {
36
+ return {
37
+ content: [{ type: "text", text: "UNAVAILABLE: nobody can answer questions in this run. Proceed on your best judgment and state what you assumed." }],
38
+ details: { code: "UNAVAILABLE" },
39
+ isError: true,
40
+ };
41
+ }
42
+ const request = {
43
+ questions: params.questions.map((q) => ({
44
+ question: q.question,
45
+ ...(q.header ? { header: q.header } : {}),
46
+ options: q.options.map((o) => ({ label: o.label, ...(o.description ? { description: o.description } : {}) })),
47
+ multiSelect: q.multiSelect === true,
48
+ })),
49
+ };
50
+ const answer = await prompter.ask(request, signal);
51
+ if (!answer)
52
+ return { content: [{ type: "text", text: ASK_USER_DECLINED }], details: { declined: true } };
53
+ return { content: [{ type: "text", text: formatQuestionAnswer(answer) }], details: answer };
54
+ },
55
+ };
56
+ }
@@ -1,3 +1,4 @@
1
+ export * from "./ask-user.js";
1
2
  export * from "./builtin.js";
2
3
  export * from "./change-tracker.js";
3
4
  export * from "./confine.js";
@@ -2,6 +2,7 @@ import { NexoError } from "../../telemetry/src/index.js";
2
2
  import { isReadOnlyCommand } from "./read-only.js";
3
3
  import { describeSessionRule, matchesSessionRule, sessionRuleFor } from "./session-rules.js";
4
4
  export const nonInteractivePrompter = { interactive: false, approve: async () => "deny" };
5
+ export const allowAllPrompter = { interactive: true, approve: async () => "once" };
5
6
  /** The auto-allow reason for a bash command `isReadOnlyCommand` accepts; the approver is not called. */
6
7
  export const READ_ONLY_REASON = "read-only command";
7
8
  /** Shell metacharacters that chain or redirect commands; an allow rule never vouches for a command containing them. */
@@ -109,6 +110,8 @@ export function createPolicy(cfg) {
109
110
  const ruleMatches = () => (options.sessionRules?.() ?? []).some((rule) => matchesSessionRule(rule, toolName, args));
110
111
  if (ruleMatches())
111
112
  return { allowed: true, by: "session_rule" };
113
+ if (options.allowAll)
114
+ return { allowed: true, by: "allow_all", reason: "allow-all" };
112
115
  if (!prompter.interactive && cfg.nonInteractiveAsk === "allow")
113
116
  return { allowed: true, by: "config" };
114
117
  const aborted = () => ({
package/tui/src/app.js CHANGED
@@ -6,7 +6,7 @@ import { getSessionRow, reviewQueue, sessionNotFound } from "../../store/src/ind
6
6
  import { toErrorPayload } from "../../telemetry/src/index.js";
7
7
  import { describeSessionRule } from "../../tools/src/index.js";
8
8
  import { createApprovalPrompter } from "./approvals.js";
9
- import { helpText, parseSlashCommand, SLASH_COMMANDS } from "./commands.js";
9
+ import { helpText, isSkillCommand, parseSlashCommand, SLASH_COMMANDS, skillSlashCommands } from "./commands.js";
10
10
  import { Block, DynamicLine, QueuedList, SafeContainer, SafeMarkdown, SubagentLine, Ticker, ToolLine, ViewMode } from "./components.js";
11
11
  import { createSessionPickerScreen } from "./session-picker.js";
12
12
  import { SettingsScreen } from "./settings-screen.js";
@@ -187,7 +187,7 @@ class InteractiveApp {
187
187
  throw error;
188
188
  }
189
189
  this.refreshDefaults();
190
- this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider([...SLASH_COMMANDS], this.session.cwd));
190
+ this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider([...SLASH_COMMANDS, ...skillSlashCommands(this.session.skills())], this.session.cwd));
191
191
  this.renderHeader(this.session);
192
192
  this.showEditor();
193
193
  await this.exitRequested;
@@ -327,7 +327,7 @@ class InteractiveApp {
327
327
  const fraction = session.contextFraction;
328
328
  const ctx = fraction === null ? "ctx –" : `ctx ${Math.round(fraction * 100)}%`;
329
329
  const score = !this.running && this.lastScore ? [this.lastScore] : [];
330
- const parts = [escapeControl(model), escapeControl(effort), ...(session.autoApprove ? ["auto"] : []), `turn ${usd(turn)}`, ...score, `session ${usd(spent)}/${usd(session.budgetUsd)}`, ctx];
330
+ const parts = [escapeControl(model), escapeControl(effort), ...(session.allowAll ? ["allow-all"] : session.autoApprove ? ["auto"] : []), `turn ${usd(turn)}`, ...score, `session ${usd(spent)}/${usd(session.budgetUsd)}`, ctx];
331
331
  return style.gray(parts.join(" · ")) + (this.running ? style.cyan(" · running…") : "");
332
332
  }
333
333
  // Input
@@ -404,7 +404,8 @@ class InteractiveApp {
404
404
  return;
405
405
  this.editor.addToHistory(text);
406
406
  const command = parseSlashCommand(text);
407
- if (command) {
407
+ // `/<skill> …` is a turn (the session pins the skill), so it queues and runs like any message.
408
+ if (command && !isSkillCommand(command.name, this.session.skills())) {
408
409
  this.runCommand(command.name, command.args);
409
410
  return;
410
411
  }
@@ -414,7 +415,8 @@ class InteractiveApp {
414
415
  }
415
416
  if (this.running) {
416
417
  // Plain text goes into the running turn at its next step; `!` commands and anything typed during a command wait.
417
- const steered = !this.runningShell && !text.startsWith("!") && this.session.steer(text);
418
+ // A skill command waits for its own turn: steering would drop the skill pin.
419
+ const steered = !this.runningShell && !text.startsWith("!") && !text.startsWith("/") && this.session.steer(text);
418
420
  this.queued.push({ text, steered });
419
421
  this.say(`queued (${this.queued.length}) · ${steered ? "sent to the agent at its next step" : `sent when the ${this.runningShell ? "command" : "turn"} ends`}`);
420
422
  return;
@@ -697,7 +699,11 @@ class InteractiveApp {
697
699
  try {
698
700
  switch (name) {
699
701
  case "help":
700
- this.say(`${helpText()}\n\n${filesLine(session)}`);
702
+ {
703
+ const skills = skillSlashCommands(session.skills()).map((c) => `/${c.name}`);
704
+ const skillLine = skills.length > 0 ? `\n\nskills (/<name> [instruction] runs a turn with that skill): ${skills.join(" ")}` : "";
705
+ this.say(`${helpText()}${skillLine}\n\n${filesLine(session)}`);
706
+ }
701
707
  break;
702
708
  case "done":
703
709
  session.review("done");
@@ -746,6 +752,19 @@ class InteractiveApp {
746
752
  }
747
753
  break;
748
754
  }
755
+ case "allow-all": {
756
+ if (!args) {
757
+ this.say(`allow-all mode: ${session.allowAll ? "on" : "off"}`);
758
+ }
759
+ else if (args === "on" || args === "off") {
760
+ session.setAllowAll(args === "on");
761
+ this.say(`allow-all mode ${session.allowAll ? "on" : "off"} for this session`);
762
+ }
763
+ else {
764
+ this.sayError({ code: "INVALID_REQUEST", message: `Unknown /allow-all argument "${escapeControl(oneLine(args, 40))}"`, hint: "Use on or off" });
765
+ }
766
+ break;
767
+ }
749
768
  case "permissions": {
750
769
  if (!args) {
751
770
  const rules = session.sessionRules;
@@ -891,7 +910,7 @@ class InteractiveApp {
891
910
  this.liveModel = null;
892
911
  this.tools.clear();
893
912
  this.subagents.clear();
894
- this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider([...SLASH_COMMANDS], next.cwd));
913
+ this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider([...SLASH_COMMANDS, ...skillSlashCommands(next.skills())], next.cwd));
895
914
  this.chat.clear();
896
915
  this.renderHeader(next);
897
916
  this.tui.requestRender(true);
@@ -1,5 +1,6 @@
1
1
  import { Container, SelectList, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
2
2
  import { fitLines } from "./components.js";
3
+ import { QuestionBox } from "./questions.js";
3
4
  import { escapeControl } from "./text.js";
4
5
  import { selectListTheme, style } from "./theme.js";
5
6
  /** The question, the optional note, the Allow once / Always allow / Deny list and a key hint, in a bordered box. */
@@ -85,6 +86,24 @@ export function createApprovalPrompter(host, options = {}) {
85
86
  list.onSelect = (item) => finish(item.value);
86
87
  list.onCancel = () => finish("deny");
87
88
  });
89
+ const askQuestions = (request, signal) => new Promise((resolve) => {
90
+ if (signal?.aborted)
91
+ return resolve(null);
92
+ let settled = false;
93
+ let hide = () => { };
94
+ const finish = (answer) => {
95
+ if (settled)
96
+ return;
97
+ settled = true;
98
+ signal?.removeEventListener("abort", onAbort);
99
+ hide();
100
+ resolve(answer);
101
+ };
102
+ const onAbort = () => finish(null);
103
+ const box = new QuestionBox(request, finish, { guardUntil: now() + guardMs, now, clean: (text) => escapeControl(redact(text)) });
104
+ hide = host.show(box);
105
+ signal?.addEventListener("abort", onAbort, { once: true });
106
+ });
88
107
  return {
89
108
  interactive: true,
90
109
  approve(request, signal) {
@@ -92,5 +111,11 @@ export function createApprovalPrompter(host, options = {}) {
92
111
  queue = next.catch(() => undefined);
93
112
  return next;
94
113
  },
114
+ // Shares the approval queue, so a question box and an approval box never overlap.
115
+ ask(request, signal) {
116
+ const next = queue.then(() => askQuestions(request, signal));
117
+ queue = next.catch(() => undefined);
118
+ return next;
119
+ },
95
120
  };
96
121
  }
@@ -22,6 +22,7 @@ export const SLASH_COMMANDS = [
22
22
  { name: "model", description: "Set this session's model (default clears it)", argumentHint: "<s1|s2|provider/id|default>", getArgumentCompletions: items(["s1", "s2", "default"]) },
23
23
  { name: "effort", description: "Set this session's effort (default clears it)", argumentHint: "<level|default>", getArgumentCompletions: items([...EFFORTS, "default"]) },
24
24
  { name: "auto", description: "Auto mode for this session: an approver model allows in-scope actions", argumentHint: "[on|off|default]", getArgumentCompletions: items(["on", "off", "default"]) },
25
+ { name: "allow-all", description: "Allow-all mode for this session: auto-approves all tool prompts", argumentHint: "[on|off]", getArgumentCompletions: items(["on", "off"]) },
25
26
  { name: "permissions", description: "List this session's Always-allow rules", argumentHint: "[remove <n>|clear]", getArgumentCompletions: items(["remove", "clear"]) },
26
27
  { name: "compact", description: "Summarize older turns at the start of the next turn" },
27
28
  { name: "clear", description: "Start a new conversation in this session" },
@@ -30,6 +31,21 @@ export const SLASH_COMMANDS = [
30
31
  { name: "settings", description: "Open settings (models, keys, budgets, tool policy)" },
31
32
  { name: "exit", description: "Leave nexo (the session can be resumed)" },
32
33
  ];
34
+ /** True when `/name` should start a skill turn: `/skill:<name>` always, `/<name>` unless a built-in command has that name. */
35
+ export function isSkillCommand(name, skills) {
36
+ const bare = name.startsWith("skill:") ? name.slice("skill:".length) : name;
37
+ if (!skills.some((s) => s.name === bare))
38
+ return false;
39
+ return bare !== name || !SLASH_COMMANDS.some((c) => c.name === name);
40
+ }
41
+ /** Autocomplete entries for skills; a skill whose name a built-in uses is offered as `/skill:<name>`. */
42
+ export function skillSlashCommands(skills) {
43
+ return skills.map((s) => ({
44
+ name: SLASH_COMMANDS.some((c) => c.name === s.name) ? `skill:${s.name}` : s.name,
45
+ description: `skill · ${s.description.split("\n")[0]?.slice(0, 120) ?? ""}`,
46
+ argumentHint: "[instruction]",
47
+ }));
48
+ }
33
49
  export function helpText() {
34
50
  const width = Math.max(...SLASH_COMMANDS.map((c) => `/${c.name}${c.argumentHint ? ` ${c.argumentHint}` : ""}`.length));
35
51
  const lines = SLASH_COMMANDS.map((c) => `${`/${c.name}${c.argumentHint ? ` ${c.argumentHint}` : ""}`.padEnd(width)} ${c.description ?? ""}`);
@@ -0,0 +1,126 @@
1
+ import { Container, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
2
+ import { fitLines } from "./components.js";
3
+ import { style } from "./theme.js";
4
+ const UP = "\u001b[A";
5
+ const DOWN = "\u001b[B";
6
+ const ESC = "\u001b";
7
+ const OTHER_LABEL = "Type your own answer";
8
+ /**
9
+ * An `ask_user` box: one question at a time, ↑↓ to move, space to toggle (multi-select), enter to answer, and a
10
+ * "Type your own answer" row that opens a one-line text field. Esc declines the whole request.
11
+ */
12
+ export class QuestionBox extends Container {
13
+ index = 0;
14
+ cursor = 0;
15
+ picked = new Set();
16
+ typing = false;
17
+ draft = "";
18
+ answers = [];
19
+ request;
20
+ onDone;
21
+ options;
22
+ constructor(request, onDone, options) {
23
+ super();
24
+ this.request = request;
25
+ this.onDone = onDone;
26
+ this.options = options;
27
+ }
28
+ get question() {
29
+ return this.request.questions[this.index];
30
+ }
31
+ handleInput(data) {
32
+ if (this.options.now() < this.options.guardUntil)
33
+ return;
34
+ const q = this.question;
35
+ const other = q.options.length;
36
+ if (this.typing) {
37
+ if (data === "\r" || data === "\n") {
38
+ if (this.draft.trim())
39
+ this.commit([], this.draft.trim());
40
+ else
41
+ this.typing = false;
42
+ }
43
+ else if (data === ESC)
44
+ this.typing = false;
45
+ else if (data === "\x7f" || data === "\b")
46
+ this.draft = [...this.draft].slice(0, -1).join("");
47
+ else if (!data.includes(ESC))
48
+ this.draft += data.replace(/[\u0000-\u001f\u007f]/g, "");
49
+ return;
50
+ }
51
+ const rows = other + 1;
52
+ if (data === UP)
53
+ this.cursor = (this.cursor - 1 + rows) % rows;
54
+ else if (data === DOWN)
55
+ this.cursor = (this.cursor + 1) % rows;
56
+ else if (data === " " && q.multiSelect && this.cursor < other) {
57
+ if (this.picked.has(this.cursor))
58
+ this.picked.delete(this.cursor);
59
+ else
60
+ this.picked.add(this.cursor);
61
+ }
62
+ else if (data === "\r" || data === "\n") {
63
+ if (this.cursor === other) {
64
+ this.typing = true;
65
+ this.draft = "";
66
+ }
67
+ else if (q.multiSelect) {
68
+ if (this.picked.size === 0)
69
+ this.picked.add(this.cursor);
70
+ this.commit(q.options.filter((_, i) => this.picked.has(i)).map((o) => o.label));
71
+ }
72
+ else
73
+ this.commit([q.options[this.cursor].label]);
74
+ }
75
+ else if (data === ESC)
76
+ this.onDone(null);
77
+ }
78
+ commit(selected, text) {
79
+ this.answers.push({ question: this.question.question, selected, ...(text ? { text } : {}) });
80
+ this.index++;
81
+ this.cursor = 0;
82
+ this.picked = new Set();
83
+ this.typing = false;
84
+ this.draft = "";
85
+ if (this.index >= this.request.questions.length)
86
+ this.onDone({ answers: [...this.answers] });
87
+ }
88
+ render(width) {
89
+ if (this.index >= this.request.questions.length)
90
+ return [];
91
+ const inner = Math.max(1, width - 4);
92
+ const clean = this.options.clean;
93
+ const border = (s) => style.cyan(s);
94
+ const row = (s) => `${border("│")} ${truncateToWidth(s, inner, "…", true)} ${border("│")}`;
95
+ const q = this.question;
96
+ const total = this.request.questions.length;
97
+ const lines = [border(`╭${"─".repeat(inner + 2)}╮`)];
98
+ const title = `Question${total > 1 ? ` ${this.index + 1}/${total}` : ""}${q.header ? ` · ${clean(q.header)}` : ""}`;
99
+ lines.push(row(style.bold(style.cyan(title))));
100
+ for (const line of wrapTextWithAnsi(clean(q.question), inner))
101
+ lines.push(row(line));
102
+ lines.push(row(""));
103
+ q.options.forEach((o, i) => {
104
+ const mark = q.multiSelect ? (this.picked.has(i) ? "[x] " : "[ ] ") : "";
105
+ const here = this.cursor === i;
106
+ const label = `${here ? "→ " : " "}${mark}${clean(o.label)}`;
107
+ lines.push(row(here ? style.bold(label) : label));
108
+ if (o.description)
109
+ for (const line of wrapTextWithAnsi(clean(o.description), Math.max(1, inner - 4)))
110
+ lines.push(row(style.gray(` ${line}`)));
111
+ });
112
+ const onOther = this.cursor === q.options.length;
113
+ const otherLabel = `${onOther ? "→ " : " "}${OTHER_LABEL}`;
114
+ lines.push(row(onOther ? style.bold(otherLabel) : otherLabel));
115
+ if (this.typing)
116
+ lines.push(row(` › ${this.draft}▏`));
117
+ lines.push(row(""));
118
+ const hint = this.typing
119
+ ? "type your answer · enter send · esc back to the options"
120
+ : `↑↓ choose${q.multiSelect ? " · space toggle" : ""} · enter answer · esc skip all questions · ctrl-c stop the turn`;
121
+ for (const line of wrapTextWithAnsi(hint, inner))
122
+ lines.push(row(style.gray(line)));
123
+ lines.push(border(`╰${"─".repeat(inner + 2)}╯`));
124
+ return fitLines(lines, width);
125
+ }
126
+ }