@hexdecimal16/nexo 0.4.4 → 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/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
  }
@@ -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,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hexdecimal16/nexo",
3
- "version": "0.4.4",
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,5 @@
1
1
  export { checkSetup, createNexo } from "./nexo.js";
2
+ export { parseSkillInvocation } from "../../skills/src/index.js";
2
3
  export { allowAllPrompter, nonInteractivePrompter } from "../../tools/src/index.js";
3
4
  export { createRuntime, openLogger } from "./runtime.js";
4
5
  export { NexoError } from "../../telemetry/src/index.js";
@@ -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
+ }