@phren/cli 0.1.46 → 0.1.47

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.
@@ -1,3 +1,8 @@
1
1
  export declare function resolveProjectStorePath(phrenPath: string, project: string): string;
2
2
  export declare function parseMcpToggle(raw: string | undefined): boolean | undefined;
3
+ /**
4
+ * One-shot CLI wrapper around the shared launcher: exits non-zero when the
5
+ * editor will not start, which is right for a command and wrong inside the
6
+ * shell — hence the split.
7
+ */
3
8
  export declare function openInEditor(filePath: string): void;
@@ -1,8 +1,7 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
- import { execFileSync } from "child_process";
4
- import { errorMessage } from "../utils.js";
5
3
  import { logger } from "../logger.js";
4
+ import { openInEditor as launchEditor } from "../editor/launch.js";
6
5
  import { getNonPrimaryStores } from "../store-registry.js";
7
6
  export function resolveProjectStorePath(phrenPath, project) {
8
7
  try {
@@ -26,15 +25,16 @@ export function parseMcpToggle(raw) {
26
25
  return false;
27
26
  return undefined;
28
27
  }
28
+ /**
29
+ * One-shot CLI wrapper around the shared launcher: exits non-zero when the
30
+ * editor will not start, which is right for a command and wrong inside the
31
+ * shell — hence the split.
32
+ */
29
33
  export function openInEditor(filePath) {
30
- const editor = process.env.EDITOR || process.env.VISUAL || "nano";
31
- try {
32
- execFileSync(editor, [filePath], { stdio: "inherit" });
33
- }
34
- catch (err) {
35
- if ((process.env.PHREN_DEBUG))
36
- logger.debug("cli-namespaces", `openInEditor: ${errorMessage(err)}`);
37
- console.error(`Editor "${editor}" failed. Set $EDITOR to your preferred editor.`);
38
- process.exit(1);
39
- }
34
+ const result = launchEditor(filePath);
35
+ if (result.ok)
36
+ return;
37
+ logger.debug("cli-namespaces", `openInEditor: ${result.error ?? "failed"}`);
38
+ console.error(`Editor "${result.command}" failed. Set $EDITOR to your preferred editor.`);
39
+ process.exit(1);
40
40
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * A small modal text editor, as a pure state machine.
3
+ *
4
+ * `applyEditorKey(state, key) -> state` holds every behaviour, so the whole
5
+ * editor is testable without a terminal — the same shape `handleMenuKey` in
6
+ * shell/render-api.ts uses. Rendering and file IO live elsewhere.
7
+ *
8
+ * This is deliberately a subset of vim: the motions and edits reached for
9
+ * without thinking, and nothing else. An unrecognised key does nothing rather
10
+ * than approximating something. Anyone wanting the real thing presses `e`.
11
+ */
12
+ export type EditorMode = "normal" | "insert" | "command";
13
+ export interface Cursor {
14
+ line: number;
15
+ col: number;
16
+ }
17
+ export interface EditorState {
18
+ /** File being edited, and how to name it on the status line. */
19
+ path: string;
20
+ label: string;
21
+ lines: string[];
22
+ cursor: Cursor;
23
+ mode: EditorMode;
24
+ /** The `:` or `/` line being typed, including its leading character. */
25
+ command: string;
26
+ /** A half-finished multi-key command: "d", "y" or "g". */
27
+ pending: string;
28
+ /** Yanked or deleted lines, for p and P. */
29
+ register: string[];
30
+ undo: Array<{
31
+ lines: string[];
32
+ cursor: Cursor;
33
+ }>;
34
+ dirty: boolean;
35
+ /** Shown on the status line: an error, or a confirmation. */
36
+ message: string;
37
+ /** Last search, for n and N. */
38
+ search: string;
39
+ /** Set when the buffer should be written; the host clears it. */
40
+ wantSave: boolean;
41
+ /** Set when the editor should close; the host clears it. */
42
+ wantClose: boolean;
43
+ }
44
+ export declare function createEditorState(path: string, label: string, content: string): EditorState;
45
+ /** Text as it should be written: one trailing newline, always. */
46
+ export declare function editorText(state: EditorState): string;
47
+ /** One key, one new state. Never mutates its argument. */
48
+ export declare function applyEditorKey(state: EditorState, key: string): EditorState;
@@ -0,0 +1,312 @@
1
+ /**
2
+ * A small modal text editor, as a pure state machine.
3
+ *
4
+ * `applyEditorKey(state, key) -> state` holds every behaviour, so the whole
5
+ * editor is testable without a terminal — the same shape `handleMenuKey` in
6
+ * shell/render-api.ts uses. Rendering and file IO live elsewhere.
7
+ *
8
+ * This is deliberately a subset of vim: the motions and edits reached for
9
+ * without thinking, and nothing else. An unrecognised key does nothing rather
10
+ * than approximating something. Anyone wanting the real thing presses `e`.
11
+ */
12
+ const UNDO_DEPTH = 100;
13
+ export function createEditorState(path, label, content) {
14
+ // A trailing newline is a line terminator, not an empty last line.
15
+ const body = content.endsWith("\n") ? content.slice(0, -1) : content;
16
+ return {
17
+ path,
18
+ label,
19
+ lines: body.length ? body.split("\n") : [""],
20
+ cursor: { line: 0, col: 0 },
21
+ mode: "normal",
22
+ command: "",
23
+ pending: "",
24
+ register: [],
25
+ undo: [],
26
+ dirty: false,
27
+ message: "",
28
+ search: "",
29
+ wantSave: false,
30
+ wantClose: false,
31
+ };
32
+ }
33
+ /** Text as it should be written: one trailing newline, always. */
34
+ export function editorText(state) {
35
+ return `${state.lines.join("\n")}\n`;
36
+ }
37
+ const clamp = (v, lo, hi) => Math.max(lo, Math.min(v, hi));
38
+ /** In normal mode the cursor sits on a character, so it stops one before the end. */
39
+ function clampCursor(state, cursor, mode = state.mode) {
40
+ const line = clamp(cursor.line, 0, state.lines.length - 1);
41
+ const text = state.lines[line] ?? "";
42
+ const max = mode === "insert" ? text.length : Math.max(0, text.length - 1);
43
+ return { line, col: clamp(cursor.col, 0, max) };
44
+ }
45
+ function snapshot(state) {
46
+ return [...state.undo, { lines: [...state.lines], cursor: { ...state.cursor } }].slice(-UNDO_DEPTH);
47
+ }
48
+ /** Apply an edit: records undo, marks dirty, clears any half-typed command. */
49
+ function mutate(state, lines, cursor, message = "") {
50
+ const next = { ...state, undo: snapshot(state), lines, dirty: true, pending: "", message };
51
+ return { ...next, cursor: clampCursor(next, cursor) };
52
+ }
53
+ function move(state, cursor) {
54
+ return { ...state, cursor: clampCursor(state, cursor), pending: "" };
55
+ }
56
+ const WORD = /[A-Za-z0-9_]/;
57
+ /** Start of the next word, wrapping onto following lines. */
58
+ function nextWord(state) {
59
+ let { line, col } = state.cursor;
60
+ const text = () => state.lines[line] ?? "";
61
+ const inWord = WORD.test(text()[col] ?? "");
62
+ // Leave the current word, then any gap.
63
+ while (col < text().length && WORD.test(text()[col] ?? "") === inWord && (inWord || !WORD.test(text()[col] ?? ""))) {
64
+ col++;
65
+ if (col >= text().length)
66
+ break;
67
+ if (inWord && !WORD.test(text()[col] ?? ""))
68
+ break;
69
+ if (!inWord && WORD.test(text()[col] ?? ""))
70
+ break;
71
+ }
72
+ while (col < text().length && !WORD.test(text()[col] ?? ""))
73
+ col++;
74
+ while (col >= text().length && line < state.lines.length - 1) {
75
+ line++;
76
+ col = 0;
77
+ while (col < text().length && !WORD.test(text()[col] ?? ""))
78
+ col++;
79
+ if (col < text().length)
80
+ break;
81
+ }
82
+ return { line, col };
83
+ }
84
+ /** Start of the previous word, wrapping onto earlier lines. */
85
+ function prevWord(state) {
86
+ let { line, col } = state.cursor;
87
+ const text = () => state.lines[line] ?? "";
88
+ col--;
89
+ while (col < 0 && line > 0) {
90
+ line--;
91
+ col = Math.max(0, text().length - 1);
92
+ }
93
+ if (col < 0)
94
+ return { line: 0, col: 0 };
95
+ while (col > 0 && !WORD.test(text()[col] ?? ""))
96
+ col--;
97
+ while (col > 0 && WORD.test(text()[col - 1] ?? ""))
98
+ col--;
99
+ return { line, col: Math.max(0, col) };
100
+ }
101
+ /** First match at or after the cursor, wrapping to the top. */
102
+ function findNext(state, term, from, backwards = false) {
103
+ if (!term)
104
+ return null;
105
+ const total = state.lines.length;
106
+ const order = [];
107
+ for (let i = 0; i < total; i++) {
108
+ order.push(backwards ? (from.line - i + total * 2) % total : (from.line + i) % total);
109
+ }
110
+ for (const [step, line] of order.entries()) {
111
+ const text = state.lines[line] ?? "";
112
+ if (step === 0) {
113
+ const idx = backwards
114
+ ? text.lastIndexOf(term, Math.max(0, from.col - 1))
115
+ : text.indexOf(term, from.col + 1);
116
+ if (idx >= 0)
117
+ return { line, col: idx };
118
+ continue;
119
+ }
120
+ const idx = backwards ? text.lastIndexOf(term) : text.indexOf(term);
121
+ if (idx >= 0)
122
+ return { line, col: idx };
123
+ }
124
+ return null;
125
+ }
126
+ function runCommand(state) {
127
+ const raw = state.command;
128
+ const base = { ...state, mode: "normal", command: "", pending: "" };
129
+ if (raw.startsWith("/")) {
130
+ const term = raw.slice(1);
131
+ if (!term)
132
+ return base;
133
+ const hit = findNext({ ...base, search: term }, term, base.cursor);
134
+ if (!hit)
135
+ return { ...base, search: term, message: `not found: ${term}` };
136
+ return { ...base, search: term, cursor: clampCursor(base, hit), message: "" };
137
+ }
138
+ const cmd = raw.slice(1).trim();
139
+ switch (cmd) {
140
+ case "w":
141
+ return { ...base, wantSave: true };
142
+ case "wq":
143
+ case "x":
144
+ return { ...base, wantSave: true, wantClose: true };
145
+ case "q":
146
+ return base.dirty
147
+ ? { ...base, message: "unsaved changes — :w to write, :q! to discard" }
148
+ : { ...base, wantClose: true };
149
+ case "q!":
150
+ return { ...base, wantClose: true };
151
+ default:
152
+ return { ...base, message: cmd ? `not an editor command: ${cmd}` : "" };
153
+ }
154
+ }
155
+ /** One key, one new state. Never mutates its argument. */
156
+ export function applyEditorKey(state, key) {
157
+ const cleared = { ...state, message: "" };
158
+ return state.mode === "insert"
159
+ ? insertKey(cleared, key)
160
+ : state.mode === "command"
161
+ ? commandKey(cleared, key)
162
+ : normalKey(cleared, key);
163
+ }
164
+ function commandKey(state, key) {
165
+ if (key === "\x1b")
166
+ return { ...state, mode: "normal", command: "" };
167
+ if (key === "\r" || key === "\n")
168
+ return runCommand(state);
169
+ if (key === "\x7f" || key === "\x08") {
170
+ const next = state.command.slice(0, -1);
171
+ // Backspacing away the leading : or / leaves command mode entirely.
172
+ return next ? { ...state, command: next } : { ...state, mode: "normal", command: "" };
173
+ }
174
+ const cp = key.codePointAt(0);
175
+ if (key.length > 0 && cp !== undefined && cp >= 32 && cp !== 0x7f && !key.startsWith("\x1b")) {
176
+ return { ...state, command: state.command + key };
177
+ }
178
+ return state;
179
+ }
180
+ function insertKey(state, key) {
181
+ const { line, col } = state.cursor;
182
+ const text = state.lines[line] ?? "";
183
+ if (key === "\x1b") {
184
+ // vim steps left on leaving insert; the cursor sits on a character again.
185
+ const next = { ...state, mode: "normal" };
186
+ return { ...next, cursor: clampCursor(next, { line, col: col - 1 }, "normal") };
187
+ }
188
+ if (key === "\r" || key === "\n") {
189
+ const lines = [...state.lines];
190
+ lines.splice(line, 1, text.slice(0, col), text.slice(col));
191
+ return { ...mutate(state, lines, { line: line + 1, col: 0 }), mode: "insert" };
192
+ }
193
+ if (key === "\x7f" || key === "\x08") {
194
+ if (col > 0) {
195
+ const lines = [...state.lines];
196
+ lines[line] = text.slice(0, col - 1) + text.slice(col);
197
+ return { ...mutate(state, lines, { line, col: col - 1 }), mode: "insert" };
198
+ }
199
+ if (line === 0)
200
+ return state;
201
+ // At column zero, backspace joins this line onto the one above.
202
+ const previous = state.lines[line - 1] ?? "";
203
+ const lines = [...state.lines];
204
+ lines.splice(line - 1, 2, previous + text);
205
+ return { ...mutate(state, lines, { line: line - 1, col: previous.length }), mode: "insert" };
206
+ }
207
+ if (key === "\t") {
208
+ const lines = [...state.lines];
209
+ lines[line] = `${text.slice(0, col)} ${text.slice(col)}`;
210
+ return { ...mutate(state, lines, { line, col: col + 2 }), mode: "insert" };
211
+ }
212
+ const cp = key.codePointAt(0);
213
+ if (cp === undefined || cp < 32 || cp === 0x7f || key.startsWith("\x1b"))
214
+ return state;
215
+ const lines = [...state.lines];
216
+ lines[line] = text.slice(0, col) + key + text.slice(col);
217
+ return { ...mutate(state, lines, { line, col: col + key.length }), mode: "insert" };
218
+ }
219
+ function normalKey(state, key) {
220
+ const { line, col } = state.cursor;
221
+ const text = state.lines[line] ?? "";
222
+ // Half-finished commands: dd, yy, gg.
223
+ if (state.pending) {
224
+ const pending = state.pending;
225
+ const cleared = { ...state, pending: "" };
226
+ if (pending === "d" && key === "d") {
227
+ const lines = [...state.lines];
228
+ const [cut] = lines.splice(line, 1);
229
+ if (!lines.length)
230
+ lines.push("");
231
+ return { ...mutate(cleared, lines, { line, col: 0 }), register: [cut ?? ""] };
232
+ }
233
+ if (pending === "y" && key === "y") {
234
+ return { ...cleared, register: [text], message: "1 line yanked" };
235
+ }
236
+ if (pending === "g" && key === "g")
237
+ return move(cleared, { line: 0, col: 0 });
238
+ return cleared;
239
+ }
240
+ switch (key) {
241
+ // ── Motion
242
+ case "h":
243
+ case "\x1b[D": return move(state, { line, col: col - 1 });
244
+ case "l":
245
+ case "\x1b[C": return move(state, { line, col: col + 1 });
246
+ case "j":
247
+ case "\x1b[B": return move(state, { line: line + 1, col });
248
+ case "k":
249
+ case "\x1b[A": return move(state, { line: line - 1, col });
250
+ case "0":
251
+ case "\x1b[H": return move(state, { line, col: 0 });
252
+ case "$":
253
+ case "\x1b[F": return move(state, { line, col: text.length });
254
+ case "w": return move(state, nextWord(state));
255
+ case "b": return move(state, prevWord(state));
256
+ case "G": return move(state, { line: state.lines.length - 1, col: 0 });
257
+ case "g":
258
+ case "d":
259
+ case "y": return { ...state, pending: key };
260
+ // ── Entering insert
261
+ case "i": return { ...state, mode: "insert" };
262
+ case "a": return { ...state, mode: "insert", cursor: clampCursor(state, { line, col: col + 1 }, "insert") };
263
+ case "I": return { ...state, mode: "insert", cursor: { line, col: 0 } };
264
+ case "A": return { ...state, mode: "insert", cursor: { line, col: text.length } };
265
+ case "o": {
266
+ const lines = [...state.lines];
267
+ lines.splice(line + 1, 0, "");
268
+ return { ...mutate(state, lines, { line: line + 1, col: 0 }), mode: "insert" };
269
+ }
270
+ case "O": {
271
+ const lines = [...state.lines];
272
+ lines.splice(line, 0, "");
273
+ return { ...mutate(state, lines, { line, col: 0 }), mode: "insert" };
274
+ }
275
+ // ── Edits
276
+ case "x": {
277
+ if (!text.length)
278
+ return state;
279
+ const lines = [...state.lines];
280
+ lines[line] = text.slice(0, col) + text.slice(col + 1);
281
+ return mutate(state, lines, { line, col });
282
+ }
283
+ case "p":
284
+ case "P": {
285
+ if (!state.register.length)
286
+ return state;
287
+ const at = key === "p" ? line + 1 : line;
288
+ const lines = [...state.lines];
289
+ lines.splice(at, 0, ...state.register);
290
+ return mutate(state, lines, { line: at, col: 0 });
291
+ }
292
+ case "u": {
293
+ const previous = state.undo[state.undo.length - 1];
294
+ if (!previous)
295
+ return { ...state, message: "nothing to undo" };
296
+ const next = { ...state, lines: previous.lines, undo: state.undo.slice(0, -1), dirty: true };
297
+ return { ...next, cursor: clampCursor(next, previous.cursor) };
298
+ }
299
+ // ── Search and commands
300
+ case "/": return { ...state, mode: "command", command: "/" };
301
+ case ":": return { ...state, mode: "command", command: ":" };
302
+ case "n":
303
+ case "N": {
304
+ if (!state.search)
305
+ return { ...state, message: "no search — press / first" };
306
+ const hit = findNext(state, state.search, state.cursor, key === "N");
307
+ return hit ? move(state, hit) : { ...state, message: `not found: ${state.search}` };
308
+ }
309
+ default:
310
+ return state;
311
+ }
312
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Hand a file to the user's own editor.
3
+ *
4
+ * `$EDITOR` is a command line, not a binary path. Plenty of people set it to
5
+ * something carrying arguments — `code --wait`, `nvim -u NONE`, and on this
6
+ * machine `omarchy-launch-editor --inline` — so passing it straight to
7
+ * `execFileSync` looks for a binary with spaces in its name and fails with
8
+ * ENOENT. Git treats `core.editor` as a command line for the same reason, and
9
+ * so do we: split it, append the path, run the first word.
10
+ *
11
+ * Splitting rather than `shell: true` keeps a file path from ever being
12
+ * interpreted by a shell.
13
+ */
14
+ export interface EditorCommand {
15
+ command: string;
16
+ args: string[];
17
+ }
18
+ /**
19
+ * Split a command line into a command and its arguments, honouring single and
20
+ * double quotes so a quoted path with spaces survives. Backslash escapes are
21
+ * deliberately not handled: `$EDITOR` values that need them are vanishingly
22
+ * rare, and guessing wrong is worse than not trying.
23
+ */
24
+ export declare function splitCommandLine(raw: string): string[];
25
+ /** The editor to use, from `$EDITOR`, then `$VISUAL`, then a sensible default. */
26
+ export declare function resolveEditorCommand(env?: NodeJS.ProcessEnv): EditorCommand | null;
27
+ export interface EditorResult {
28
+ ok: boolean;
29
+ /** The command that ran, for messages. */
30
+ command: string;
31
+ error?: string;
32
+ }
33
+ /**
34
+ * Run the editor on `filePath` and wait for it to exit. The child inherits the
35
+ * terminal, so the caller must have released it first.
36
+ *
37
+ * Returns a result rather than throwing or exiting: inside the shell an editor
38
+ * that will not start is a message on the status line, not the end of the
39
+ * session.
40
+ */
41
+ export declare function openInEditor(filePath: string, env?: NodeJS.ProcessEnv): EditorResult;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Hand a file to the user's own editor.
3
+ *
4
+ * `$EDITOR` is a command line, not a binary path. Plenty of people set it to
5
+ * something carrying arguments — `code --wait`, `nvim -u NONE`, and on this
6
+ * machine `omarchy-launch-editor --inline` — so passing it straight to
7
+ * `execFileSync` looks for a binary with spaces in its name and fails with
8
+ * ENOENT. Git treats `core.editor` as a command line for the same reason, and
9
+ * so do we: split it, append the path, run the first word.
10
+ *
11
+ * Splitting rather than `shell: true` keeps a file path from ever being
12
+ * interpreted by a shell.
13
+ */
14
+ import { execFileSync } from "child_process";
15
+ import { resolveExecCommand } from "../utils-helpers.js";
16
+ import { errorMessage } from "../utils.js";
17
+ import { debugLog } from "../shared.js";
18
+ /**
19
+ * Split a command line into a command and its arguments, honouring single and
20
+ * double quotes so a quoted path with spaces survives. Backslash escapes are
21
+ * deliberately not handled: `$EDITOR` values that need them are vanishingly
22
+ * rare, and guessing wrong is worse than not trying.
23
+ */
24
+ export function splitCommandLine(raw) {
25
+ const parts = [];
26
+ let current = "";
27
+ let quote = null;
28
+ let has = false;
29
+ for (const ch of raw) {
30
+ if (quote) {
31
+ if (ch === quote)
32
+ quote = null;
33
+ else
34
+ current += ch;
35
+ continue;
36
+ }
37
+ if (ch === '"' || ch === "'") {
38
+ quote = ch;
39
+ has = true;
40
+ continue;
41
+ }
42
+ if (/\s/.test(ch)) {
43
+ if (has || current) {
44
+ parts.push(current);
45
+ current = "";
46
+ has = false;
47
+ }
48
+ continue;
49
+ }
50
+ current += ch;
51
+ }
52
+ if (has || current)
53
+ parts.push(current);
54
+ return parts;
55
+ }
56
+ /** The editor to use, from `$EDITOR`, then `$VISUAL`, then a sensible default. */
57
+ export function resolveEditorCommand(env = process.env) {
58
+ const raw = (env.EDITOR || env.VISUAL || "").trim();
59
+ const parts = raw ? splitCommandLine(raw) : [];
60
+ if (!parts.length) {
61
+ // Nothing configured. `vi` is the one editor POSIX requires to exist.
62
+ return { command: "vi", args: [] };
63
+ }
64
+ const [command, ...args] = parts;
65
+ return command ? { command, args } : null;
66
+ }
67
+ /**
68
+ * Run the editor on `filePath` and wait for it to exit. The child inherits the
69
+ * terminal, so the caller must have released it first.
70
+ *
71
+ * Returns a result rather than throwing or exiting: inside the shell an editor
72
+ * that will not start is a message on the status line, not the end of the
73
+ * session.
74
+ */
75
+ export function openInEditor(filePath, env = process.env) {
76
+ const editor = resolveEditorCommand(env);
77
+ if (!editor)
78
+ return { ok: false, command: "", error: "No editor configured. Set $EDITOR." };
79
+ const resolved = resolveExecCommand(editor.command);
80
+ try {
81
+ execFileSync(resolved.command, [...editor.args, filePath], {
82
+ stdio: "inherit",
83
+ shell: resolved.shell,
84
+ });
85
+ return { ok: true, command: editor.command };
86
+ }
87
+ catch (err) {
88
+ const error = errorMessage(err);
89
+ debugLog(`openInEditor: ${editor.command}: ${error}`);
90
+ return { ok: false, command: editor.command, error };
91
+ }
92
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Write an edited file back into the store.
3
+ *
4
+ * The store is git-backed and other tools read it, so a save is not a bare
5
+ * writeFileSync: it refuses to clobber a symlink, checks that a skill is still
6
+ * loadable before replacing a working one, and lands atomically.
7
+ */
8
+ export type EditKind = "skill" | "claude";
9
+ export interface SaveResult {
10
+ ok: boolean;
11
+ error?: string;
12
+ /** True when a skill's frontmatter changed, so the manifests need rebuilding. */
13
+ frontmatterChanged?: boolean;
14
+ }
15
+ export declare function saveEditedFile(filePath: string, content: string, kind: EditKind): SaveResult;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Write an edited file back into the store.
3
+ *
4
+ * The store is git-backed and other tools read it, so a save is not a bare
5
+ * writeFileSync: it refuses to clobber a symlink, checks that a skill is still
6
+ * loadable before replacing a working one, and lands atomically.
7
+ */
8
+ import * as fs from "fs";
9
+ import { atomicWriteText } from "../phren-paths.js";
10
+ import { validateSkillFrontmatter, parseSkillFrontmatter } from "../link/skills.js";
11
+ import { errorMessage } from "../utils.js";
12
+ /**
13
+ * The registry never lists a symlink as a skill — it skips them — so a link
14
+ * here means we are pointed at one of the mirrors in ~/.claude/skills or
15
+ * ~/.copilot/skills. Writing atomically through one would replace the link
16
+ * with a regular file and silently detach the mirror from the store, so refuse
17
+ * rather than quietly break it. Matches the guard the write_skill MCP tool has.
18
+ */
19
+ function symlinkRefusal(filePath) {
20
+ try {
21
+ if (fs.existsSync(filePath) && fs.lstatSync(filePath).isSymbolicLink()) {
22
+ return "Refusing to write through a symlinked path — edit the file in the store instead.";
23
+ }
24
+ }
25
+ catch {
26
+ // An unreadable path fails later, with a better message, at write time.
27
+ }
28
+ return null;
29
+ }
30
+ /** Compare the fields the skill manifests bake in, so a re-sync only runs when needed. */
31
+ function frontmatterDiffers(before, after) {
32
+ const key = (raw) => {
33
+ const { frontmatter } = parseSkillFrontmatter(raw);
34
+ if (!frontmatter)
35
+ return "";
36
+ const fm = frontmatter;
37
+ return JSON.stringify([fm.name, fm.description, fm.command, fm.aliases]);
38
+ };
39
+ return key(before) !== key(after);
40
+ }
41
+ export function saveEditedFile(filePath, content, kind) {
42
+ const refusal = symlinkRefusal(filePath);
43
+ if (refusal)
44
+ return { ok: false, error: refusal };
45
+ let previous = "";
46
+ try {
47
+ previous = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8") : "";
48
+ }
49
+ catch {
50
+ previous = "";
51
+ }
52
+ if (kind === "skill") {
53
+ // A skill with broken frontmatter loads as nameless and description-less,
54
+ // so it is better to refuse than to leave one behind.
55
+ const check = validateSkillFrontmatter(content, filePath);
56
+ if (!check.valid) {
57
+ return { ok: false, error: check.errors[0] ?? "invalid skill frontmatter" };
58
+ }
59
+ }
60
+ try {
61
+ atomicWriteText(filePath, content);
62
+ }
63
+ catch (err) {
64
+ return { ok: false, error: errorMessage(err) };
65
+ }
66
+ return {
67
+ ok: true,
68
+ frontmatterChanged: kind === "skill" && frontmatterDiffers(previous, content),
69
+ };
70
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Drawing for the shell's modal editor.
3
+ *
4
+ * The frame is painted whole on every key, so there is no real terminal cursor
5
+ * to move: the character under the cursor is drawn inverted instead.
6
+ */
7
+ import type { EditorState } from "../editor/buffer.js";
8
+ export declare function renderEditor(state: EditorState, width: number, height: number): string[];