@hexdecimal16/nexo 0.4.4 → 0.4.6

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/cli/src/common.js CHANGED
@@ -9,8 +9,9 @@ export const USAGE = `Usage:
9
9
  nexo sessions [--limit <n>]
10
10
  nexo --version print the installed version
11
11
  nexo settings open the settings screen (needs a terminal)
12
+ nexo settings list every editable setting by group, with its value and source
12
13
  nexo settings get <key>
13
- nexo settings set <key> <value> keys: models.s1|s2|judge|reflector|embedding, budgets.*, tools.policy.*, tools.webSearch.count, tools.autoApprove, tools.nonInteractiveAsk, models.approver, scoring.judge, learning.*, memory.*, optimize.minCases|patience|minJudgeKappa|noveltySimilarity|offspringAlpha|reflectionTier|maxCaseDrop, loop.maxToolCalls|repeatLimit
14
+ nexo settings set <key> <value> keys as shown by nexo settings list; auto mode: tools.autoApprove, tools.nonInteractiveAsk, models.approver
14
15
  nexo settings reset <key> remove it from the user config
15
16
  nexo settings set-key <provider> reads the key from a hidden prompt, or from stdin when piped; playwright-<profile> stores a Chrome profile's browser token
16
17
  (brave or tavily turns on the web_search tool)
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";
@@ -135,11 +136,13 @@ async function runCommand(args, io, options) {
135
136
  });
136
137
  for (const warning of judgeFamilyWarnings(runtime.config))
137
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());
138
141
  let result;
139
142
  try {
140
143
  result = await runtime.engine.run({
141
- instruction,
142
- skill: values.skill,
144
+ instruction: invoked?.instruction ?? instruction,
145
+ skill: values.skill ?? invoked?.skill,
143
146
  model: values.model,
144
147
  effort: values.effort,
145
148
  workspace: values.workspace,
@@ -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
  }
@@ -1,4 +1,4 @@
1
- import { createSettings, keyStatusLabel, nexoModels } from "../../core/src/index.js";
1
+ import { createSettings, keyStatusLabel, nexoModels, SETTING_GROUPS } from "../../core/src/index.js";
2
2
  import { ensureNexoDirs, resolveNexoPaths } from "../../store/src/index.js";
3
3
  import { NexoError, toErrorPayload } from "../../telemetry/src/index.js";
4
4
  import { EXIT_SIGINT, exitCodeFor, printError, usageError } from "./common.js";
@@ -90,7 +90,7 @@ export function readHiddenKey(stdin, stderr, provider, signal) {
90
90
  function show(view) {
91
91
  return view.value === null ? "unset" : String(view.value);
92
92
  }
93
- /** `nexo settings get|set|reset|set-key`: no TUI, for scripts. Invalid keys and values are usage errors (exit 2). */
93
+ /** `nexo settings list|get|set|reset|keys|set-key|remove-key`: no TUI, for scripts. Invalid keys and values are usage errors (exit 2). */
94
94
  export async function settingsCommand(args, io, options, stdio) {
95
95
  const [sub, ...rest] = args;
96
96
  const env = options.env ?? process.env;
@@ -131,6 +131,22 @@ export async function settingsCommand(args, io, options, stdio) {
131
131
  io.stderr.write(`note: ${view.notice}\n`);
132
132
  return 0;
133
133
  }
134
+ case "list": {
135
+ if (rest.length !== 0)
136
+ throw usageError("nexo settings list takes no arguments");
137
+ const views = build().settings();
138
+ for (const group of SETTING_GROUPS) {
139
+ const inGroup = views.filter((v) => v.group === group.id);
140
+ if (inGroup.length === 0)
141
+ continue;
142
+ io.stdout.write(`${group.label}\n`);
143
+ for (const view of inGroup) {
144
+ const source = view.source === "unset" ? "" : ` (${view.source})`;
145
+ io.stdout.write(` ${view.key} = ${show(view)}${source}\n`);
146
+ }
147
+ }
148
+ return 0;
149
+ }
134
150
  case "keys": {
135
151
  if (rest.length !== 0)
136
152
  throw usageError("nexo settings keys takes no arguments");
@@ -177,7 +193,7 @@ export async function settingsCommand(args, io, options, stdio) {
177
193
  return 0;
178
194
  }
179
195
  default:
180
- throw usageError(sub === undefined ? "nexo settings needs get, set, reset, keys, set-key or remove-key (or a terminal for the screen)" : `Unknown settings command "${sub}"`);
196
+ throw usageError(sub === undefined ? "nexo settings needs list, get, set, reset, keys, set-key or remove-key (or a terminal for the screen)" : `Unknown settings command "${sub}"`);
181
197
  }
182
198
  }
183
199
  catch (error) {
@@ -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";
@@ -573,6 +573,10 @@ export async function executeRun(env, input) {
573
573
  });
574
574
  if (webSearchTool)
575
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 }));
576
580
  const toolCtx = {
577
581
  env,
578
582
  runId,
@@ -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
  }
@@ -294,7 +299,10 @@ export class Session {
294
299
  const limit = runBudgetLimit(this.deps.db, config.budgets, this.env.now(), { run: config.budgets.perTurnShare * this.budgetUsd, session: remaining });
295
300
  const turnIndex = this.state.turns + 1;
296
301
  this.onEvent = options.onEvent;
297
- 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);
298
306
  const workspace = this.state.workspace;
299
307
  const previous = workspace === null ? latestSessionRunWorkspace(this.deps.db, this.id) : undefined;
300
308
  const result = await executeRun(this.env, {
@@ -310,6 +318,7 @@ export class Session {
310
318
  ...(this.state.model ? { model: this.state.model } : {}),
311
319
  ...(this.continuesOnS2 ? { startOnS2: true } : {}),
312
320
  ...(this.effort ? { effort: this.effort } : {}),
321
+ ...(skill ? { skill } : {}),
313
322
  sessionRules: () => this.state.sessionRules ?? [],
314
323
  addSessionRule: (rule) => this.addSessionRule(rule),
315
324
  autoApprove: this.autoApprove,
@@ -4,6 +4,36 @@ import { EFFORTS } from "../../../router/src/index.js";
4
4
  import { NexoError } from "../../../telemetry/src/index.js";
5
5
  import { configErrors, deepMerge, projectConfigPath, readConfigFile } from "../config/load.js";
6
6
  import { DEFAULT_CONFIG } from "../config/schema.js";
7
+ /** Setting groups in display order. */
8
+ export const SETTING_GROUPS = [
9
+ { id: "models", label: "Models" },
10
+ { id: "budgets", label: "Budgets" },
11
+ { id: "tools", label: "Tools & permissions" },
12
+ { id: "runs", label: "Runs & sessions" },
13
+ { id: "memory", label: "Memory & learning" },
14
+ { id: "scoring", label: "Scoring" },
15
+ { id: "optimize", label: "Optimization" },
16
+ ];
17
+ export function settingGroupLabel(id) {
18
+ return SETTING_GROUPS.find((g) => g.id === id)?.label ?? id;
19
+ }
20
+ function groupOf(key) {
21
+ if (key === "budgets.optimDefaultUsd" || key.startsWith("optimize."))
22
+ return "optimize";
23
+ if (key === "models.judge" || key.startsWith("scoring."))
24
+ return "scoring";
25
+ if (key.startsWith("models."))
26
+ return "models";
27
+ if (key.startsWith("budgets."))
28
+ return "budgets";
29
+ if (key.startsWith("tools."))
30
+ return "tools";
31
+ if (key.startsWith("memory.") || key.startsWith("learning."))
32
+ return "memory";
33
+ if (key.startsWith("session.") || key.startsWith("loop.") || key.startsWith("spawn."))
34
+ return "runs";
35
+ throw new Error(`No settings group for ${key}`);
36
+ }
7
37
  /** Values of `boolean` and `scorerToggle` settings as shown and picked. */
8
38
  export const ON_OFF = ["on", "off"];
9
39
  export const PROJECT_OVERRIDE_NOTICE = "overridden by project config";
@@ -19,8 +49,7 @@ const POLICY_DESCRIPTIONS = {
19
49
  load_skill: "load a skill's instructions",
20
50
  spawn: "start subagents",
21
51
  };
22
- /** Every setting the settings screen and `nexo settings` can edit, in display order. */
23
- export const EDITABLE_SETTINGS = [
52
+ const SETTING_LIST = [
24
53
  { key: "models.s1", label: "Model s1", description: "Default model for most work (provider/model-id)", type: { kind: "model" } },
25
54
  { key: "models.s2", label: "Model s2", description: "Stronger model the router escalates to (provider/model-id)", type: { kind: "model" } },
26
55
  { key: "models.s1.effort", label: "Effort s1", description: "Default reasoning effort for s1", type: { kind: "enum", values: EFFORTS } },
@@ -172,6 +201,11 @@ export const EDITABLE_SETTINGS = [
172
201
  type: { kind: "number", integer: false, min: 0, max: 10 },
173
202
  },
174
203
  ];
204
+ /** Every setting the settings screen and `nexo settings` can edit: group by group (SETTING_GROUPS), listed order within a group. */
205
+ export const EDITABLE_SETTINGS = (() => {
206
+ const grouped = SETTING_LIST.map((def) => ({ ...def, group: groupOf(def.key) }));
207
+ return SETTING_GROUPS.flatMap((g) => grouped.filter((def) => def.group === g.id));
208
+ })();
175
209
  function isPlainObject(value) {
176
210
  return typeof value === "object" && value !== null && !Array.isArray(value);
177
211
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hexdecimal16/nexo",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
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 { SETTING_GROUPS, settingGroupLabel } from "../../core/src/index.js";
3
+ export { parseSkillInvocation } from "../../skills/src/index.js";
2
4
  export { allowAllPrompter, nonInteractivePrompter } from "../../tools/src/index.js";
3
5
  export { createRuntime, openLogger } from "./runtime.js";
4
6
  export { NexoError } from "../../telemetry/src/index.js";
package/sdk/src/nexo.js CHANGED
@@ -110,6 +110,20 @@ export function createNexo(options = {}) {
110
110
  live();
111
111
  return runtime.settings.removeKey(provider);
112
112
  },
113
+ settings() {
114
+ return runtime.settings.settings();
115
+ },
116
+ getSetting(key) {
117
+ return runtime.settings.getSetting(key);
118
+ },
119
+ setSetting(key, value) {
120
+ live();
121
+ return runtime.settings.setSetting(key, value);
122
+ },
123
+ resetSetting(key) {
124
+ live();
125
+ return runtime.settings.resetSetting(key);
126
+ },
113
127
  async close() {
114
128
  if (closed)
115
129
  return;
@@ -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";
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;
@@ -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");
@@ -904,7 +910,7 @@ class InteractiveApp {
904
910
  this.liveModel = null;
905
911
  this.tools.clear();
906
912
  this.subagents.clear();
907
- this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider([...SLASH_COMMANDS], next.cwd));
913
+ this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider([...SLASH_COMMANDS, ...skillSlashCommands(next.skills())], next.cwd));
908
914
  this.chat.clear();
909
915
  this.renderHeader(next);
910
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
  }
@@ -31,6 +31,21 @@ export const SLASH_COMMANDS = [
31
31
  { name: "settings", description: "Open settings (models, keys, budgets, tool policy)" },
32
32
  { name: "exit", description: "Leave nexo (the session can be resumed)" },
33
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
+ }
34
49
  export function helpText() {
35
50
  const width = Math.max(...SLASH_COMMANDS.map((c) => `/${c.name}${c.argumentHint ? ` ${c.argumentHint}` : ""}`.length));
36
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
+ }
@@ -1,5 +1,5 @@
1
1
  import { Input, truncateToWidth } from "@earendil-works/pi-tui";
2
- import { keyStatusLabel, ON_OFF } from "../../core/src/index.js";
2
+ import { keyStatusLabel, ON_OFF, SETTING_GROUPS } from "../../core/src/index.js";
3
3
  import { toErrorPayload } from "../../telemetry/src/index.js";
4
4
  import { isSearchProvider, SEARCH_PROVIDERS } from "../../tools/src/index.js";
5
5
  import { fitLines, MaskedInput } from "./components.js";
@@ -8,6 +8,8 @@ import { escapeControl, formatError } from "./text.js";
8
8
  import { style } from "./theme.js";
9
9
  const RESET = "\u0000reset";
10
10
  const BACK = "\u0000back";
11
+ /** Value prefix of a group heading row in the menu; picking one does nothing. */
12
+ const GROUP = "\u0000group:";
11
13
  /** A single-line text entry (plain or masked). */
12
14
  class EntryView {
13
15
  title;
@@ -105,7 +107,15 @@ export class SettingsScreen {
105
107
  description: escapeControl(keyStatusLabel(k)),
106
108
  })),
107
109
  { value: "browser:add", label: "Add browser profile", description: "store a Chrome profile token from the Playwright Extension for the browser skill" },
108
- ...views.map((v) => ({ value: `set:${v.key}`, label: escapeControl(v.label), description: settingDescription(v) })),
110
+ ...SETTING_GROUPS.flatMap((group) => {
111
+ const inGroup = views.filter((v) => v.group === group.id);
112
+ if (inGroup.length === 0)
113
+ return [];
114
+ return [
115
+ { value: `${GROUP}${group.id}`, label: style.bold(`── ${group.label}`), description: "" },
116
+ ...inGroup.map((v) => ({ value: `set:${v.key}`, label: escapeControl(v.label), description: settingDescription(v) })),
117
+ ];
118
+ }),
109
119
  ];
110
120
  return new PickerView({
111
121
  title: "Settings",
@@ -114,6 +124,8 @@ export class SettingsScreen {
114
124
  hint: "type to filter · ↑↓ move · enter edit · esc close",
115
125
  onPick: (value) => {
116
126
  this.status = null;
127
+ if (value.startsWith(GROUP))
128
+ return;
117
129
  if (value === "browser:add")
118
130
  this.show(this.browserProfileView(() => this.backToMenu(), () => this.backToMenu()));
119
131
  else if (value.startsWith("key:"))