@unscientificjszhai/howto 1.0.0-alpha.3 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.CN.md +37 -5
  2. package/README.md +37 -5
  3. package/THIRD_PARTY_NOTICES.md +18 -0
  4. package/dist/ai/command-schema.js +2 -0
  5. package/dist/ai/errors.js +7 -23
  6. package/dist/ai/gemini.js +67 -27
  7. package/dist/ai/openai.js +35 -27
  8. package/dist/cli.js +12 -1
  9. package/dist/config-file.js +97 -51
  10. package/dist/config.js +7 -6
  11. package/dist/errors.js +17 -16
  12. package/dist/execute.js +12 -25
  13. package/dist/index.js +85 -97
  14. package/dist/init/InitializationApp.js +175 -32
  15. package/dist/init/index.js +35 -33
  16. package/dist/init/state.js +46 -23
  17. package/dist/prompt.js +5 -2
  18. package/dist/safety/dangerous-command.js +262 -93
  19. package/dist/shell/command-analysis.js +373 -0
  20. package/dist/terminal-text.js +33 -0
  21. package/dist/ui/App.js +84 -41
  22. package/dist/ui/ConfirmView.js +166 -61
  23. package/dist/ui/InteractiveSessionProvider.js +19 -0
  24. package/dist/ui/ResolvePlaceholdersView.js +131 -72
  25. package/dist/ui/SelectCommandView.js +73 -23
  26. package/dist/ui/SelectedCommandDisplay.js +11 -9
  27. package/dist/ui/interactive-session.js +407 -0
  28. package/dist/ui/paste-framing.js +105 -0
  29. package/dist/ui/placeholder-logic.js +109 -8
  30. package/dist/ui/resize-safe-output.js +73 -0
  31. package/dist/ui/run-interactive-command.js +55 -0
  32. package/dist/ui/single-line-preview.js +28 -0
  33. package/dist/ui/text-input.js +53 -0
  34. package/dist/ui/use-keyboard-input.js +12 -0
  35. package/dist/ui/use-paste-aware-input.js +7 -0
  36. package/dist/user-visible-error.js +19 -0
  37. package/dist/validation/ai-response.js +11 -4
  38. package/dist/validation/command-tool.js +25 -127
  39. package/dist/validation/generated-commands.js +8 -0
  40. package/dist/version.js +38 -0
  41. package/package.json +21 -16
@@ -1,19 +1,41 @@
1
- import React, { useState } from "react";
2
- import { Box, Text, useInput } from "ink";
1
+ import React, { useRef, useState } from "react";
2
+ import { Box, Text } from "ink";
3
+ import { getUserVisibleErrorMessage } from "../errors.js";
4
+ import { usePhysicalStdoutRows } from "../ui/resize-safe-output.js";
5
+ import { toSingleLinePreview } from "../ui/single-line-preview.js";
6
+ import { useInteractiveSession } from "../ui/InteractiveSessionProvider.js";
7
+ import { usePasteAwareInput } from "../ui/use-paste-aware-input.js";
3
8
  import { applyInitializationInput, createInitialInitializationState, getProviderOptions, } from "./state.js";
9
+ const RICH_LAYOUT_MIN_ROWS = 15;
4
10
  export const InitializationApp = ({ onSubmit, onComplete, onCancel, onError }) => {
11
+ const session = useInteractiveSession();
12
+ const rows = usePhysicalStdoutRows();
5
13
  const [state, setState] = useState(createInitialInitializationState);
14
+ const stateRef = useRef(state);
6
15
  const [submitStatus, setSubmitStatus] = useState("editing");
16
+ const submitStatusRef = useRef(submitStatus);
7
17
  const [errorMessage, setErrorMessage] = useState("");
8
- useInput((input, key) => {
9
- const update = applyInitializationInput(state, { input, key });
18
+ const frameRows = Math.max(0, rows - 1);
19
+ const handleInput = (event) => {
20
+ if (frameRows === 0) {
21
+ return;
22
+ }
23
+ if (submitStatusRef.current !== "editing") {
24
+ return;
25
+ }
26
+ const update = applyInitializationInput(stateRef.current, event);
27
+ stateRef.current = update.state;
10
28
  setState(update.state);
11
29
  if (update.cancelled) {
30
+ session.suspendViewInput();
31
+ submitStatusRef.current = "cancelled";
12
32
  setSubmitStatus("cancelled");
13
33
  onCancel();
14
34
  return;
15
35
  }
16
36
  if (update.completedValues !== undefined) {
37
+ session.suspendViewInput();
38
+ submitStatusRef.current = "saving";
17
39
  setSubmitStatus("saving");
18
40
  onSubmit(update.completedValues)
19
41
  .then((config) => {
@@ -21,33 +43,72 @@ export const InitializationApp = ({ onSubmit, onComplete, onCancel, onError }) =
21
43
  })
22
44
  .catch((error) => {
23
45
  const appError = normalizeError(error);
24
- setErrorMessage(appError.message);
46
+ setErrorMessage(getUserVisibleErrorMessage(appError));
47
+ submitStatusRef.current = "error";
25
48
  setSubmitStatus("error");
26
49
  onError(appError);
27
50
  });
28
51
  }
29
- }, { isActive: submitStatus === "editing" });
52
+ };
53
+ usePasteAwareInput({
54
+ onInput: (input, key) => {
55
+ handleInput({ type: "keyboard", input, key });
56
+ },
57
+ onPaste: (input) => {
58
+ handleInput({ type: "paste", input });
59
+ },
60
+ isInputActive: frameRows === 0 || submitStatus === "editing",
61
+ isPasteActive: frameRows > 0 && submitStatus === "editing",
62
+ });
63
+ let content;
30
64
  if (submitStatus === "saving") {
31
- return (React.createElement(Box, { flexDirection: "column", marginY: 1 },
32
- React.createElement(Text, { color: "green" }, "Saving howto configuration...")));
65
+ content = (React.createElement(InitializationStatusLine, { frameRows: frameRows, message: "Saving howto configuration...", color: "green" }));
66
+ }
67
+ else if (submitStatus === "error") {
68
+ content = (React.createElement(InitializationStatusLine, { frameRows: frameRows, message: `Error: ${errorMessage}`, color: "red" }));
33
69
  }
34
- if (submitStatus === "error") {
35
- return (React.createElement(Box, { flexDirection: "column", marginY: 1 },
36
- React.createElement(Text, { color: "red" },
37
- "Error: ",
38
- errorMessage)));
70
+ else if (submitStatus === "cancelled") {
71
+ content = (React.createElement(InitializationStatusLine, { frameRows: frameRows, message: "Initialization cancelled.", dimColor: true }));
39
72
  }
40
- if (submitStatus === "cancelled") {
41
- return (React.createElement(Box, { flexDirection: "column", marginY: 1 },
42
- React.createElement(Text, { dimColor: true }, "Initialization cancelled.")));
73
+ else if (state.step === "provider") {
74
+ content = React.createElement(ProviderStep, { selectedIndex: state.selectedIndex, frameRows: frameRows });
43
75
  }
44
- if (state.step === "provider") {
45
- return React.createElement(ProviderStep, { selectedIndex: state.selectedIndex });
76
+ else {
77
+ content = React.createElement(InputStep, { state: state, frameRows: frameRows });
46
78
  }
47
- return React.createElement(InputStep, { state: state });
79
+ return (React.createElement(Box, { display: frameRows > 0 ? "flex" : "none", flexDirection: "column", maxHeight: frameRows, overflowX: "hidden", overflowY: "hidden" }, content));
48
80
  };
49
- const ProviderStep = ({ selectedIndex }) => {
81
+ const ClippedLine = ({ children, color, dimColor = false, prefix, prefixWidth }) => (React.createElement(Box, { width: "100%", height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" }, prefix === undefined ? (React.createElement(Text, { color: color, dimColor: dimColor }, children)) : (React.createElement(React.Fragment, null,
82
+ React.createElement(Box, { width: prefixWidth, flexShrink: 0 },
83
+ React.createElement(Text, { color: color, dimColor: dimColor }, prefix)),
84
+ React.createElement(Box, { flexGrow: 1, flexShrink: 1, minWidth: 1, height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" },
85
+ React.createElement(Text, { color: color, dimColor: dimColor }, children))))));
86
+ const ProviderStep = ({ selectedIndex, frameRows, }) => {
50
87
  const providers = getProviderOptions();
88
+ const selectedProvider = selectedIndex === null ? undefined : providers[selectedIndex];
89
+ const providerSelectionLine = selectedProvider === "openai"
90
+ ? "> openai 2 gemini"
91
+ : selectedProvider === "gemini"
92
+ ? "1 openai > gemini"
93
+ : "1 openai 2 gemini";
94
+ if (frameRows < RICH_LAYOUT_MIN_ROWS) {
95
+ if (frameRows === 1) {
96
+ const compactSelection = selectedProvider === "openai" ? "O" : selectedProvider === "gemini" ? "G" : "-";
97
+ return (React.createElement(Box, { height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" },
98
+ React.createElement(Text, null, `O/G:${compactSelection} UD Ent 1/2 Esc`)));
99
+ }
100
+ if (frameRows <= 3) {
101
+ return (React.createElement(Box, { flexDirection: "column", height: frameRows, maxHeight: frameRows, overflowX: "hidden", overflowY: "hidden" },
102
+ frameRows === 3 && React.createElement(Text, { color: "green" }, "? Choose provider"),
103
+ React.createElement(ClippedLine, null, providerSelectionLine),
104
+ React.createElement(Text, { dimColor: true }, "UD Enter 1/2 Esc")));
105
+ }
106
+ return (React.createElement(Box, { flexDirection: "column", maxHeight: 4, overflowX: "hidden", overflowY: "hidden" },
107
+ React.createElement(ClippedLine, null, "howto needs an AI provider before it can call AI."),
108
+ React.createElement(ClippedLine, { color: "green" }, "? Choose provider"),
109
+ React.createElement(ClippedLine, null, providerSelectionLine),
110
+ React.createElement(ClippedLine, { dimColor: true }, "UD Enter 1/2 Esc")));
111
+ }
51
112
  return (React.createElement(Box, { flexDirection: "column", marginY: 1 },
52
113
  React.createElement(Text, null, "howto needs an AI provider before it can call AI."),
53
114
  React.createElement(Box, { height: 1 },
@@ -65,27 +126,109 @@ const ProviderStep = ({ selectedIndex }) => {
65
126
  React.createElement(Box, { flexShrink: 0, marginTop: 1 },
66
127
  React.createElement(Text, { dimColor: true }, "Use Up/Down or 1/2 to choose, Enter to continue, Esc or Ctrl+C to cancel."))));
67
128
  };
68
- const InputStep = ({ state, }) => {
129
+ const InputStep = ({ state, frameRows }) => {
69
130
  const currentField = state.fields[state.fieldIndex];
131
+ const shortLabel = getShortFieldLabel(currentField);
132
+ if (frameRows < RICH_LAYOUT_MIN_ROWS) {
133
+ const fieldValue = getFieldValuePreview(currentField);
134
+ const fieldLine = `${shortLabel}: ${fieldValue}`;
135
+ const statusLine = state.errorMessage === undefined ? fieldLine : `! ${shortLabel} required`;
136
+ if (frameRows === 1) {
137
+ const compactField = state.errorMessage === undefined
138
+ ? `${shortLabel}:${getCompactFieldValuePreview(currentField)}`
139
+ : `!${shortLabel}:req`;
140
+ return (React.createElement(Box, { height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" },
141
+ React.createElement(Box, { flexGrow: 1, flexShrink: 1, minWidth: 1, height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" },
142
+ React.createElement(Text, null, compactField)),
143
+ React.createElement(Box, { flexShrink: 0 },
144
+ React.createElement(Text, { dimColor: true }, " Ent Esc ^C"))));
145
+ }
146
+ if (frameRows <= 3) {
147
+ return (React.createElement(Box, { flexDirection: "column", height: frameRows, maxHeight: frameRows, overflowX: "hidden", overflowY: "hidden" },
148
+ frameRows === 3 && (React.createElement(ClippedLine, { color: state.errorMessage === undefined ? "green" : "red" }, state.errorMessage === undefined ? `? Configure ${state.provider}` : statusLine)),
149
+ frameRows === 3 || state.errorMessage === undefined ? (React.createElement(ClippedLine, { prefix: `${shortLabel}:`, prefixWidth: shortLabel.length + 2 }, fieldValue)) : (React.createElement(ClippedLine, null, statusLine)),
150
+ React.createElement(Text, { dimColor: true }, "Ent next Esc back ^C")));
151
+ }
152
+ const defaultPreview = currentField.defaultValue !== undefined && currentField.value === ""
153
+ ? `Default: ${toSingleLinePreview(currentField.defaultValue)}`
154
+ : undefined;
155
+ const guidance = defaultPreview ?? getFullFieldGuidance(currentField);
156
+ return (React.createElement(Box, { flexDirection: "column", maxHeight: 4, overflowX: "hidden", overflowY: "hidden" },
157
+ React.createElement(ClippedLine, { color: state.errorMessage === undefined ? "green" : "red" }, state.errorMessage === undefined ? `? Configure ${state.provider}` : statusLine),
158
+ React.createElement(ClippedLine, { prefix: `${shortLabel}:`, prefixWidth: shortLabel.length + 2 }, fieldValue),
159
+ guidance !== undefined && React.createElement(ClippedLine, { dimColor: true }, guidance),
160
+ React.createElement(ClippedLine, { dimColor: true }, "Ent next Esc back ^C")));
161
+ }
70
162
  return (React.createElement(Box, { flexDirection: "column", marginY: 1 },
71
163
  React.createElement(Text, { color: "green" },
72
164
  "? Configure ",
73
165
  state.provider),
74
166
  React.createElement(Box, { flexDirection: "column", marginTop: 1 }, state.fields.map((field, index) => (React.createElement(FieldRow, { key: field.name, field: field, isActive: index === state.fieldIndex })))),
75
- currentField.defaultValue !== undefined && currentField.value === "" && (React.createElement(Text, { dimColor: true },
76
- "Default: ",
77
- currentField.defaultValue)),
78
- state.errorMessage !== undefined && React.createElement(Text, { color: "red" }, state.errorMessage),
167
+ getFullFieldGuidance(currentField) !== undefined && (React.createElement(ClippedLine, { dimColor: true }, getFullFieldGuidance(currentField))),
168
+ currentField.defaultValue !== undefined && currentField.value === "" && (React.createElement(ClippedLine, { dimColor: true, prefix: "Default:", prefixWidth: 9 }, toSingleLinePreview(currentField.defaultValue))),
169
+ state.errorMessage !== undefined && (React.createElement(ClippedLine, { color: "red" }, toSingleLinePreview(state.errorMessage))),
79
170
  React.createElement(Box, { flexShrink: 0, marginTop: 1 },
80
171
  React.createElement(Text, { dimColor: true }, "Press Enter for next value, Esc to go back, Ctrl+C to cancel."))));
81
172
  };
82
- const FieldRow = ({ field, isActive, }) => (React.createElement(Box, null,
83
- React.createElement(Text, { color: isActive ? "cyan" : undefined }, isActive ? "> " : " "),
84
- React.createElement(Text, null,
85
- field.label,
86
- ": "),
87
- React.createElement(Text, null, field.value),
88
- isActive && React.createElement(Text, { backgroundColor: "white" }, " ")));
173
+ const FieldRow = ({ field, isActive, }) => {
174
+ const shortLabel = getShortFieldLabel(field);
175
+ return (React.createElement(Box, { height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" },
176
+ React.createElement(Box, { width: 2, flexShrink: 0 },
177
+ React.createElement(Text, { color: isActive ? "cyan" : undefined }, isActive ? "> " : " ")),
178
+ React.createElement(Box, { width: shortLabel.length + 2, flexShrink: 0 },
179
+ React.createElement(Text, null,
180
+ shortLabel,
181
+ ":")),
182
+ React.createElement(Box, { flexShrink: 1, minWidth: 1, height: 1, maxHeight: 1, overflowX: "hidden", overflowY: "hidden" },
183
+ React.createElement(Text, null, toSingleLinePreview(field.value))),
184
+ isActive && (React.createElement(Box, { width: 1, flexShrink: 0 },
185
+ React.createElement(Text, { backgroundColor: "white" }, " ")))));
186
+ };
187
+ const InitializationStatusLine = ({ frameRows, message, color, dimColor = false }) => {
188
+ const status = (React.createElement(ClippedLine, { color: color, dimColor: dimColor }, toSingleLinePreview(message)));
189
+ if (frameRows < 4) {
190
+ return status;
191
+ }
192
+ return (React.createElement(Box, { flexDirection: "column", marginY: 1 }, status));
193
+ };
194
+ function getShortFieldLabel(field) {
195
+ switch (field.name) {
196
+ case "apiKey":
197
+ return "Key";
198
+ case "model":
199
+ return "Model";
200
+ case "openaiBaseUrl":
201
+ return "URL";
202
+ }
203
+ }
204
+ function getFullFieldGuidance(field) {
205
+ switch (field.name) {
206
+ case "apiKey":
207
+ return field.required ? "Required." : "Optional; empty allowed.";
208
+ case "model":
209
+ return undefined;
210
+ case "openaiBaseUrl":
211
+ return "Empty uses official OpenAI URL.";
212
+ }
213
+ }
214
+ function getFieldValuePreview(field) {
215
+ if (field.value !== "") {
216
+ return toSingleLinePreview(field.value);
217
+ }
218
+ if (field.defaultValue !== undefined) {
219
+ return toSingleLinePreview(field.defaultValue);
220
+ }
221
+ return field.required ? "<required>" : "<empty>";
222
+ }
223
+ function getCompactFieldValuePreview(field) {
224
+ if (field.value !== "") {
225
+ return toSingleLinePreview(field.value);
226
+ }
227
+ if (field.defaultValue !== undefined) {
228
+ return toSingleLinePreview(field.defaultValue);
229
+ }
230
+ return field.required ? "req" : "-";
231
+ }
89
232
  function normalizeError(error) {
90
233
  if (error instanceof Error) {
91
234
  return error;
@@ -1,37 +1,30 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import React from "react";
11
2
  import { render } from "ink";
12
3
  import { loadConfig } from "../config.js";
13
4
  import { getConfigFilePath, writeUserConfigFile } from "../config-file.js";
5
+ import { InteractiveSessionProvider } from "../ui/InteractiveSessionProvider.js";
14
6
  import { InteractionCancelledError } from "../ui/tty.js";
15
7
  import { InitializationApp } from "./InitializationApp.js";
16
- export function initializeConfig(_a) {
17
- return __awaiter(this, arguments, void 0, function* ({ cliOptions, env, input, output, }) {
18
- return yield new Promise((resolve, reject) => {
19
- let settled = false;
20
- const settle = (result) => {
21
- if (settled) {
22
- return;
23
- }
24
- settled = true;
25
- instance.clear();
26
- instance.unmount();
27
- void instance.waitUntilExit().then(result, result);
28
- };
29
- const instance = render(React.createElement(InitializationApp, { onSubmit: (values) => __awaiter(this, void 0, void 0, function* () {
30
- const fileConfig = createFileConfig(values);
31
- const configFilePath = getConfigFilePath(env);
32
- yield writeUserConfigFile(fileConfig, configFilePath);
33
- return loadConfig(cliOptions, env, fileConfig);
34
- }), onComplete: (config) => {
8
+ export async function initializeConfig({ cliOptions, env, session, }) {
9
+ return await new Promise((resolve, reject) => {
10
+ let settled = false;
11
+ let unsubscribe = () => { };
12
+ const settle = (result) => {
13
+ if (settled) {
14
+ return;
15
+ }
16
+ settled = true;
17
+ session.suspendViewInput();
18
+ unsubscribe();
19
+ const exitPromise = instance.waitUntilExit();
20
+ instance.clear();
21
+ instance.unmount();
22
+ void exitPromise.then(result, result);
23
+ };
24
+ const instance = render(React.createElement(InteractiveSessionProvider, { session: session },
25
+ React.createElement(InitializationApp, { onSubmit: async (values) => {
26
+ return validateAndPersistInitializationConfig(values, cliOptions, env);
27
+ }, onComplete: (config) => {
35
28
  settle(() => {
36
29
  resolve(config);
37
30
  });
@@ -43,14 +36,23 @@ export function initializeConfig(_a) {
43
36
  settle(() => {
44
37
  reject(error);
45
38
  });
46
- } }), {
47
- stdin: input,
48
- stdout: output,
49
- exitOnCtrlC: false,
50
- });
39
+ } })), {
40
+ stdin: session.input,
41
+ stdout: session.output,
42
+ exitOnCtrlC: false,
43
+ // 会话已确认 TTY,避免 CI 环境关闭 Ink 的实时渲染。
44
+ interactive: true,
51
45
  });
46
+ unsubscribe = session.subscribeFailure((error) => settle(() => reject(error)));
52
47
  });
53
48
  }
49
+ export async function validateAndPersistInitializationConfig(values, cliOptions, env) {
50
+ const fileConfig = createFileConfig(values);
51
+ const config = loadConfig(cliOptions, env, fileConfig);
52
+ const configFilePath = getConfigFilePath(env);
53
+ await writeUserConfigFile(fileConfig, configFilePath);
54
+ return config;
55
+ }
54
56
  export function clearInitializationOutput(output, rows) {
55
57
  if (output.isTTY) {
56
58
  output.write(erasePreviousTerminalRows(rows));
@@ -1,4 +1,6 @@
1
1
  import { DEFAULT_GEMINI_MODEL, DEFAULT_OPENAI_MODEL } from "../config.js";
2
+ import { hasUnsafeTerminalControlCharacters } from "../terminal-text.js";
3
+ import { deleteLastGrapheme, isTextInputEvent } from "../ui/text-input.js";
2
4
  const PROVIDERS = ["openai", "gemini"];
3
5
  export function createInitialInitializationState() {
4
6
  return {
@@ -10,6 +12,14 @@ export function getProviderOptions() {
10
12
  return PROVIDERS;
11
13
  }
12
14
  export function applyInitializationInput(state, event) {
15
+ if (event.type === "paste") {
16
+ if (state.step !== "input" || hasUnsafeTerminalControlCharacters(event.input)) {
17
+ return { state };
18
+ }
19
+ return updateCurrentField(state, (value) => value + event.input);
20
+ }
21
+ if (event.key.eventType === "release")
22
+ return { state };
13
23
  if (event.key.ctrl && event.input === "c") {
14
24
  return { state, cancelled: true };
15
25
  }
@@ -22,7 +32,9 @@ function applyProviderInput(state, event) {
22
32
  if (event.key.escape) {
23
33
  return { state, cancelled: true };
24
34
  }
25
- const numericSelection = getNumericProviderSelection(event.input);
35
+ const numericSelection = isTextInputEvent(event.input, event.key)
36
+ ? getNumericProviderSelection(event.input)
37
+ : null;
26
38
  if (numericSelection !== null) {
27
39
  return {
28
40
  state: createInputState(PROVIDERS[numericSelection]),
@@ -30,14 +42,20 @@ function applyProviderInput(state, event) {
30
42
  }
31
43
  if (event.key.upArrow) {
32
44
  return {
33
- state: Object.assign(Object.assign({}, state), { selectedIndex: state.selectedIndex === null
45
+ state: {
46
+ ...state,
47
+ selectedIndex: state.selectedIndex === null
34
48
  ? PROVIDERS.length - 1
35
- : (state.selectedIndex - 1 + PROVIDERS.length) % PROVIDERS.length }),
49
+ : (state.selectedIndex - 1 + PROVIDERS.length) % PROVIDERS.length,
50
+ },
36
51
  };
37
52
  }
38
53
  if (event.key.downArrow) {
39
54
  return {
40
- state: Object.assign(Object.assign({}, state), { selectedIndex: state.selectedIndex === null ? 0 : (state.selectedIndex + 1) % PROVIDERS.length }),
55
+ state: {
56
+ ...state,
57
+ selectedIndex: state.selectedIndex === null ? 0 : (state.selectedIndex + 1) % PROVIDERS.length,
58
+ },
41
59
  };
42
60
  }
43
61
  if (event.key.return && state.selectedIndex !== null) {
@@ -64,7 +82,10 @@ function applyFieldInput(state, event) {
64
82
  const validationError = validateCurrentField(state);
65
83
  if (validationError !== undefined) {
66
84
  return {
67
- state: Object.assign(Object.assign({}, state), { errorMessage: validationError }),
85
+ state: {
86
+ ...state,
87
+ errorMessage: validationError,
88
+ },
68
89
  };
69
90
  }
70
91
  if (state.fieldIndex === state.fields.length - 1) {
@@ -74,26 +95,21 @@ function applyFieldInput(state, event) {
74
95
  };
75
96
  }
76
97
  return {
77
- state: Object.assign(Object.assign({}, state), { fieldIndex: state.fieldIndex + 1, errorMessage: undefined }),
98
+ state: {
99
+ ...state,
100
+ fieldIndex: state.fieldIndex + 1,
101
+ errorMessage: undefined,
102
+ },
78
103
  };
79
104
  }
80
105
  if (event.key.backspace || event.key.delete) {
81
- return updateCurrentField(state, (value) => value.slice(0, -1));
106
+ return updateCurrentField(state, deleteLastGrapheme);
82
107
  }
83
- if (event.input !== "" && !hasControlKey(event)) {
108
+ if (isTextInputEvent(event.input, event.key)) {
84
109
  return updateCurrentField(state, (value) => value + event.input);
85
110
  }
86
111
  return { state };
87
112
  }
88
- function hasControlKey(event) {
89
- return (event.key.upArrow ||
90
- event.key.downArrow ||
91
- event.key.return ||
92
- event.key.escape ||
93
- event.key.ctrl ||
94
- event.key.backspace ||
95
- event.key.delete);
96
- }
97
113
  function createInputState(provider) {
98
114
  return {
99
115
  step: "input",
@@ -140,8 +156,16 @@ function createInputState(provider) {
140
156
  }
141
157
  function updateCurrentField(state, updateValue) {
142
158
  return {
143
- state: Object.assign(Object.assign({}, state), { fields: state.fields.map((field, index) => index === state.fieldIndex
144
- ? Object.assign(Object.assign({}, field), { value: updateValue(field.value) }) : field), errorMessage: undefined }),
159
+ state: {
160
+ ...state,
161
+ fields: state.fields.map((field, index) => index === state.fieldIndex
162
+ ? {
163
+ ...field,
164
+ value: updateValue(field.value),
165
+ }
166
+ : field),
167
+ errorMessage: undefined,
168
+ },
145
169
  };
146
170
  }
147
171
  function validateCurrentField(state) {
@@ -152,20 +176,19 @@ function validateCurrentField(state) {
152
176
  return undefined;
153
177
  }
154
178
  function createInitializationValues(state) {
155
- var _a, _b, _c;
156
179
  const fieldValues = new Map(state.fields.map((field) => [field.name, field.value]));
157
- const modelValue = (_a = fieldValues.get("model")) === null || _a === void 0 ? void 0 : _a.trim();
180
+ const modelValue = fieldValues.get("model")?.trim();
158
181
  if (state.provider === "gemini") {
159
182
  return {
160
183
  provider: "gemini",
161
- apiKey: (_b = fieldValues.get("apiKey")) !== null && _b !== void 0 ? _b : "",
184
+ apiKey: fieldValues.get("apiKey") ?? "",
162
185
  model: modelValue === "" || modelValue === undefined ? DEFAULT_GEMINI_MODEL : modelValue,
163
186
  };
164
187
  }
165
188
  const baseUrl = fieldValues.get("openaiBaseUrl");
166
189
  return {
167
190
  provider: "openai",
168
- apiKey: (_c = fieldValues.get("apiKey")) !== null && _c !== void 0 ? _c : "",
191
+ apiKey: fieldValues.get("apiKey") ?? "",
169
192
  model: modelValue === "" || modelValue === undefined ? DEFAULT_OPENAI_MODEL : modelValue,
170
193
  openaiBaseUrl: baseUrl === undefined || baseUrl.trim() === "" ? undefined : baseUrl,
171
194
  };
package/dist/prompt.js CHANGED
@@ -17,10 +17,13 @@ The JSON object must match this schema:
17
17
  }
18
18
  The commands array must contain 1 to 3 items. Do not return more than 3 candidate commands.
19
19
  Detect the primary natural language of the user's question. Return title, description, and placeholders[].description in that language. Keep placeholder name values English-compatible ASCII using only letters, numbers, underscores, or hyphens.
20
- Use placeholders in commands only as {{name}}, and declare every placeholder in the placeholders array. User may provide argument. If the user's intent is clear, try to use the provided arguments as parameters in the generated commands instead of placeholders. If the intent is unclear, do not fill them.`;
20
+ Do not include terminal control characters in string fields. CR and LF are the only allowed control characters.
21
+ Use placeholders in commands only as {{name}}, and declare every placeholder in the placeholders array. Each placeholder name must be declared exactly once per candidate; multiple references to the same name share one input value. User may provide argument. If the user's intent is clear, try to use the provided arguments as parameters in the generated commands instead of placeholders. If the intent is unclear, do not fill them.`;
21
22
  export const STRUCTURED_OUTPUT_CONTRACT = `Return only the JSON object requested by the response schema. Do not include a natural-language body, markdown, or code fences.
23
+ The commands array must contain 1 to 3 items. Do not return more than 3 candidate commands.
22
24
  Detect the primary natural language of the user's question. Return title, description, and placeholders[].description in that language. Keep placeholder name values English-compatible ASCII using only letters, numbers, underscores, or hyphens.
23
- Use placeholders in commands only as {{name}}, and declare every placeholder in the placeholders array. User may provide argument. If the user's intent is clear, try to use the provided arguments as parameters in the generated commands instead of placeholders. If the intent is unclear, do not fill them.`;
25
+ Do not include terminal control characters in string fields. CR and LF are the only allowed control characters.
26
+ Use placeholders in commands only as {{name}}, and declare every placeholder in the placeholders array. Each placeholder name must be declared exactly once per candidate; multiple references to the same name share one input value. User may provide argument. If the user's intent is clear, try to use the provided arguments as parameters in the generated commands instead of placeholders. If the intent is unclear, do not fill them.`;
24
27
  export const SAFETY_CONSTRAINTS = `Prefer read-only, reversible, and low-risk commands.
25
28
  When a task could involve deletion, overwrite, privilege escalation, network download, or executing downloaded content, prefer a safer alternative or inspection command when possible.
26
29
  Do not include safety metadata or claim that a command is safe; the local CLI will perform its own validation and dangerous-command checks.`;