@narumitw/pi-inline 0.4.0 β†’ 0.6.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @narumitw/pi-inline
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 502e95d: Preview local text files outside the workspace by hovering over Markdown links in fullscreen mode. The `externalPreviewRoots` setting is now ignored, including empty lists that previously disabled external previews. External images, symbolic links, and `node_modules` are still excluded. Hover previews stay on screen and are not sent to the model or stored in the session.
8
+
9
+ ## 0.5.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 41c08ba: Open the settings menu with `/inline`. `/inline-markup` remains a compatibility alias. Turn the system prompt hint on or off, or edit its text. After saving a change, choose whether to reload now or apply it in a later session. The default hint and session-only Wikilinks behavior are unchanged.
14
+
3
15
  ## 0.4.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -8,8 +8,9 @@ Style badges and preview local file citations in Pi's terminal transcript withou
8
8
  ## ✨ Features
9
9
 
10
10
  - Display decorative badges, linked badges, and local Markdown links in user and assistant messages.
11
- - Hover over a file link in fullscreen mode to preview a workspace image or text file, or text in an approved external directory.
11
+ - Hover over a file link in fullscreen mode to preview local text files, including files outside the workspace, or workspace images.
12
12
  - Turn on filename lookup for wikilinks in the current session.
13
+ - Edit or turn off the system prompt hint for badges and file citations.
13
14
 
14
15
  ## πŸ“¦ Install
15
16
 
@@ -41,21 +42,37 @@ for a project install.
41
42
 
42
43
  If you load the old checkout path, replace it with `./packages/pi-inline`.
43
44
  Remove any explicit entry for the former `.pi/extensions/pi-inline-markup/`
44
- extension. Do not load both copies. The `/inline-markup` command is unchanged.
45
+ extension. Do not load both copies. Use `/inline` to open the settings menu.
46
+ `/inline-markup` still opens the same menu.
45
47
 
46
48
  ## πŸš€ Quick start
47
49
 
48
50
  Start Pi in a directory with a `README.md` file. Send a message containing
49
51
  `[README](./README.md)` to see a file icon next to the label. In fullscreen mode,
50
- hover over the link to preview the file. If Pi detects Kitty graphics support,
51
- hover over an image link such as `[Cat Photo](./cat.png)` to see the image.
52
+ hover over the link to preview the file. Absolute and relative paths outside the
53
+ workspace also work for text previews without any setup. If Pi detects Kitty
54
+ graphics support, hover over a workspace image link such as
55
+ `[Cat Photo](./cat.png)` to see the image.
52
56
 
53
57
  ## πŸ’¬ Commands
54
58
 
55
- Run `/inline-markup` with no arguments in the terminal UI. Select **On** or **Off**
56
- to toggle wikilinks immediately, or press Escape to leave the value unchanged.
57
- Wikilinks start off in each new session and after `/reload`. Turning them off
58
- stops file indexing and closes any open preview.
59
+ Run `/inline` with no arguments in the terminal UI. `/inline-markup` is a
60
+ compatibility alias.
61
+
62
+ - **Wikilinks** changes filename lookup immediately for the current session.
63
+ It starts Off in each new session and after `/reload`. Turning it Off stops
64
+ file indexing and closes any open preview.
65
+ - **Prompt Hint** turns system prompt guidance On or Off. Turning it Off keeps
66
+ the saved text.
67
+ - **Edit Prompt Hint…** opens a multiline editor with the saved text, even if
68
+ the hint is Off.
69
+
70
+ After a prompt hint change is saved, Pi asks whether to reload. Choose No to
71
+ keep the saved change without applying it to the current session. Apply it later
72
+ with `/reload` or by starting another session. Cancelling an edit or submitting
73
+ an unchanged value does not save or ask for reload. While a save is pending,
74
+ Escape does not close the menu, but Ctrl+C closes it immediately. If the save
75
+ still goes through, Pi tells you to run `/reload`.
59
76
 
60
77
  ## πŸ”— Link and badge syntax
61
78
 
@@ -90,39 +107,35 @@ and refreshes five seconds after each scan.
90
107
 
91
108
  ## βš™οΈ Settings
92
109
 
93
- To allow external text previews, edit the user file `pi-inline.json` in Pi's agent
94
- directory (by default `~/.pi/agent/`):
95
-
96
- ```json
97
- {
98
- "externalPreviewRoots": ["/home/alex/.agents/plans"]
99
- }
110
+ Prompt hint settings use `pi-inline.json` in Pi's agent directory (by default
111
+ `~/.pi/agent/`). Project settings are ignored. Use a regular file, not a
112
+ symbolic link. If its content is invalid, repair it before saving through the
113
+ menu. Settings writes are ordered within one Pi process, not between processes.
114
+ Finish saving before editing the file by hand or from another Pi process.
115
+ The former `externalPreviewRoots` field is ignored and can be removed.
116
+
117
+ `promptHintEnabled` accepts a boolean and defaults to `true`. `promptHintText`
118
+ accepts a non-blank string, including multiple lines. Line endings are saved as
119
+ LF. Do not include terminal or bidirectional controls. Remove both keys and
120
+ reload to restore the default:
121
+
122
+ ```text
123
+ Use [[label]] for badges.
124
+ Use Markdown links with workspace-relative paths for file citations, for example [file](./path/to/file#L12-L20).
100
125
  ```
101
126
 
102
- A conversation link can trigger a file read inside an approved directory when
103
- you hover over it. Approve only narrow directories you control, not shared
104
- directories. Use existing absolute directories without symbolic links. Do not
105
- use globs, a filesystem root, your home directory, or a directory that contains
106
- your home directory.
107
-
108
- The default is `[]` and project settings are ignored. Invalid or unreadable
109
- settings leave external previews off. Use a regular file, not a symbolic link.
110
- Changes take effect on session start or
111
- `/reload`. To revoke access, remove the field or set it to `[]`, then run
112
- `/reload`. Link icons do not depend on this setting.
113
-
114
127
  ## πŸ”’ Security and privacy
115
128
 
116
- Hover can show hidden files, including files that contain secrets. Previews
117
- exclude `node_modules` and symbolic links. External previews are text-only.
118
- External PNG, JPEG, GIF, and WebP links can be opened but never start an image
119
- preview. The extension does not add preview contents to model context or
120
- stored messages.
129
+ Hovering over a local Markdown link can display a file Pi can read, even outside
130
+ the workspace. This includes hidden files and files that contain secrets. Avoid
131
+ hovering over untrusted links, especially when sharing your screen. Previews
132
+ exclude `node_modules` and symbolic links. External PNG, JPEG, GIF, and WebP
133
+ links can be opened but not previewed. The extension does not add preview
134
+ contents to model context or stored messages.
121
135
 
122
- In the terminal UI, the extension adds a fixed system prompt hint about badge
123
- labels and Markdown file citations. The hint uses a placeholder path and contains
124
- no extension name or workspace data. Updating the hint does not rewrite existing
125
- session history.
136
+ In the terminal UI, Pi sends the enabled prompt hint to the model provider and
137
+ can retain it in session history. Do not put secrets in the hint. Editing or
138
+ turning it off does not remove text from earlier requests or stored history.
126
139
 
127
140
  ## 🚧 Limitations
128
141
 
@@ -142,8 +155,8 @@ session history.
142
155
  ## πŸ—‚οΈ Package layout
143
156
 
144
157
  - `src/index.ts` forwards the extension factory to Pi. The rest of `src/` owns
145
- transcript rendering, hover previews, and the wikilink index.
146
- - `test/` covers rendering, session cleanup, file boundaries, and workspace lookups.
158
+ settings, transcript rendering, hover previews, and the wikilink index.
159
+ - `test/` covers settings, rendering, session cleanup, and preview boundaries.
147
160
 
148
161
  The package ships its TypeScript source and needs no build step.
149
162
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-inline",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Style inline badges and preview local file links in Pi's terminal UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,8 +33,8 @@
33
33
  "@earendil-works/pi-tui": "*"
34
34
  },
35
35
  "devDependencies": {
36
- "@earendil-works/pi-coding-agent": "1.5.0",
37
- "@earendil-works/pi-tui": "1.5.0",
36
+ "@earendil-works/pi-coding-agent": "1.6.0",
37
+ "@earendil-works/pi-tui": "1.6.0",
38
38
  "@types/node": "26.6.6",
39
39
  "typescript": "7.0.2"
40
40
  },
@@ -44,6 +44,9 @@
44
44
  "directory": "packages/pi-inline"
45
45
  },
46
46
  "dependencies": {
47
+ "@narumitw/pi-tui-kit": "^0.70.0",
48
+ "diff": "9.0.0",
49
+ "jsonc-parser": "3.3.1",
47
50
  "sharp": "0.35.5"
48
51
  }
49
52
  }
package/src/filelinks.ts CHANGED
@@ -21,12 +21,7 @@ export interface PreviewExcerpt {
21
21
  lineRange?: LineRange;
22
22
  }
23
23
 
24
- export interface ExternalPreviewRoot {
25
- path: string;
26
- identity: Pick<BigIntStats, "dev" | "ino">;
27
- }
28
-
29
- export function relativePreviewPath(root: string, path: string): string | undefined {
24
+ function relativePreviewPath(root: string, path: string): string | undefined {
30
25
  const local = relative(root, path);
31
26
  if (!local || isAbsolute(local) || local === ".." || local.startsWith(`..${sep}`)) return undefined;
32
27
  if (local.split(sep).includes("node_modules")) return undefined;
@@ -49,11 +44,6 @@ function localLinkPath(root: string, href: string): string | undefined {
49
44
  }
50
45
  }
51
46
 
52
- export function resolveLinkPath(root: string, href: string): string | undefined {
53
- const path = localLinkPath(root, href);
54
- return path && relativePreviewPath(root, path) ? path : undefined;
55
- }
56
-
57
47
  /** Classifies local links for display without checking whether a file exists. */
58
48
  export function classifyLinkPath(
59
49
  root: string,
@@ -98,44 +88,29 @@ function selectLines(
98
88
  };
99
89
  }
100
90
 
101
- function sameFile(a: ExternalPreviewRoot["identity"], b: ExternalPreviewRoot["identity"]): boolean {
91
+ function sameFile(a: BigIntStats, b: BigIntStats): boolean {
102
92
  return a.dev === b.dev && a.ino === b.ino;
103
93
  }
104
94
 
105
- async function isCurrentRoot(root: ExternalPreviewRoot, signal: AbortSignal): Promise<boolean> {
106
- if (signal.aborted || (await realpath(root.path)) !== root.path || signal.aborted) return false;
107
- const stat = await lstat(root.path, { bigint: true });
108
- return !signal.aborted && stat.isDirectory() && sameFile(stat, root.identity);
109
- }
110
-
111
95
  /** Opens a regular preview file without following symlinks. The caller owns the handle. */
112
- export async function openPreviewFile(root: string | ExternalPreviewRoot, path: string, signal: AbortSignal) {
96
+ export async function openPreviewFile(root: string, path: string, signal: AbortSignal) {
113
97
  try {
114
- const external = typeof root === "string" ? undefined : root;
115
- const rootPath = typeof root === "string" ? root : root.path;
116
- const local = relativePreviewPath(rootPath, path);
98
+ const local = relativePreviewPath(root, path);
117
99
  if (!local || signal.aborted) return undefined;
118
- if (external && !(await isCurrentRoot(external, signal))) return undefined;
119
- const directory = external ? rootPath : await realpath(rootPath);
100
+ const directory = await realpath(root);
120
101
  if (signal.aborted) return undefined;
121
102
  const candidate = resolve(directory, local);
122
103
  if ((await realpath(candidate)) !== candidate || signal.aborted) return undefined;
123
104
  const verified = await lstat(candidate, { bigint: true });
124
105
  if (!verified.isFile() || signal.aborted) return undefined;
125
- if (external && !(await isCurrentRoot(external, signal))) return undefined;
126
- if (signal.aborted) return undefined;
127
106
 
128
107
  const file = await open(candidate, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
129
108
  let keepOpen = false;
130
109
  try {
131
110
  if (signal.aborted) return undefined;
132
111
  const stat = await file.stat({ bigint: true });
133
- if (signal.aborted || !stat.isFile()) return undefined;
134
- // Do not read a different file if the target changed between lstat and open.
135
- if (external) {
136
- if (!sameFile(verified, stat) || !(await isCurrentRoot(external, signal)) || signal.aborted) return undefined;
137
- if ((await realpath(candidate)) !== candidate || signal.aborted) return undefined;
138
- }
112
+ if (signal.aborted || !stat.isFile() || !sameFile(verified, stat)) return undefined;
113
+ if ((await realpath(candidate)) !== candidate || signal.aborted) return undefined;
139
114
  keepOpen = true;
140
115
  return {
141
116
  file,
@@ -152,7 +127,7 @@ export async function openPreviewFile(root: string | ExternalPreviewRoot, path:
152
127
  }
153
128
 
154
129
  export async function readExcerpt(
155
- root: string | ExternalPreviewRoot,
130
+ root: string,
156
131
  path: string,
157
132
  signal: AbortSignal,
158
133
  lineRange?: LineRange,
@@ -1,4 +1,4 @@
1
- import { resolve } from "node:path";
1
+ import { parse, resolve } from "node:path";
2
2
  import type { Theme } from "@earendil-works/pi-coding-agent";
3
3
  import {
4
4
  type Component,
@@ -9,15 +9,7 @@ import {
9
9
  TuiAltScreen,
10
10
  } from "@earendil-works/pi-tui";
11
11
  import type { createExternalLinkMarker } from "./external-link-marker.js";
12
- import {
13
- classifyLinkPath,
14
- type ExternalPreviewRoot,
15
- parseLineRange,
16
- readExcerpt,
17
- relativePreviewPath,
18
- renderFilePreview,
19
- resolveLinkPath,
20
- } from "./filelinks.js";
12
+ import { classifyLinkPath, parseLineRange, readExcerpt, renderFilePreview } from "./filelinks.js";
21
13
  import { prepareImagePreview, previewImageMime } from "./image-preview.js";
22
14
  import {
23
15
  hoverLinkLine,
@@ -39,7 +31,7 @@ interface Point {
39
31
  interface Hover extends Point {
40
32
  href: string;
41
33
  path?: string;
42
- externalRoot?: ExternalPreviewRoot;
34
+ external: boolean;
43
35
  preview?: WikiPreview;
44
36
  controller: AbortController;
45
37
  }
@@ -49,10 +41,7 @@ export function createHoverPreview(
49
41
  theme: Theme,
50
42
  cwd: string,
51
43
  findWikiPreview: (href: string) => WikiPreview | undefined,
52
- external: {
53
- marker: ReturnType<typeof createExternalLinkMarker>;
54
- roots(): readonly ExternalPreviewRoot[];
55
- },
44
+ marker: ReturnType<typeof createExternalLinkMarker>,
56
45
  ): Component & { dismiss(): void; dispose(): void } {
57
46
  let hover: Hover | undefined;
58
47
  let timer: ReturnType<typeof setTimeout> | undefined;
@@ -73,17 +62,17 @@ export function createHoverPreview(
73
62
  return tui instanceof TuiAltScreen ? (tui.getScreenLines()[row] ?? "") : "";
74
63
  }
75
64
 
76
- function stillOnLink({ row, col, href, preview, externalRoot }: Hover): boolean {
65
+ function stillOnLink({ row, col, href, preview, external }: Hover): boolean {
77
66
  const line = screenLine(row);
78
67
  return (
79
68
  getOsc8LinkAtColumn(hoverLinkLine(line), col) === href &&
80
69
  findWikiPreview(href) === preview &&
81
- (!externalRoot || external.marker.matches(line, col, href))
70
+ (!external || marker.matches(line, col, href))
82
71
  );
83
72
  }
84
73
 
85
74
  async function show(target: Hover): Promise<void> {
86
- const { preview, path, controller, externalRoot } = target;
75
+ const { preview, path, controller, external } = target;
87
76
  if (hover !== target) return;
88
77
  if (
89
78
  !viewport ||
@@ -98,7 +87,7 @@ export function createHoverPreview(
98
87
  const { columns, rows } = tui.terminal;
99
88
  const below = rows - target.row - 1;
100
89
  const above = target.row;
101
- const imageMime = !externalRoot && !preview && path ? previewImageMime(path) : undefined;
90
+ const imageMime = !external && !preview && path ? previewImageMime(path) : undefined;
102
91
  const placeBelow = below >= above || (!imageMime && below >= MAX_HEIGHT);
103
92
  const availableRows = placeBelow ? below : above;
104
93
  const width = imageMime ? columns : Math.min(columns, preview ? 56 : 60);
@@ -124,7 +113,7 @@ export function createHoverPreview(
124
113
  } else {
125
114
  if (!path) return;
126
115
  const lineRange = preview ? undefined : parseLineRange(target.href);
127
- const excerpt = await readExcerpt(externalRoot ?? cwd, path, controller.signal, lineRange);
116
+ const excerpt = await readExcerpt(external ? parse(path).root : cwd, path, controller.signal, lineRange);
128
117
  if (!excerpt) return;
129
118
  draw = () =>
130
119
  preview
@@ -179,24 +168,20 @@ export function createHoverPreview(
179
168
  href === hover.href &&
180
169
  point.row === hover.row &&
181
170
  preview === hover.preview &&
182
- (!hover.externalRoot || external.marker.matches(line, point.col, href))
171
+ (!hover.external || marker.matches(line, point.col, href))
183
172
  ) {
184
173
  hover.col = point.col;
185
174
  return;
186
175
  }
187
176
  hide();
188
177
  if (!href || tui.hasOverlay()) return;
189
- let path = preview ? ("path" in preview ? preview.path : undefined) : resolveLinkPath(cwd, href);
190
- let externalRoot: ExternalPreviewRoot | undefined;
191
- if (!preview && !path) {
192
- const local = classifyLinkPath(cwd, href);
193
- if (local?.kind !== "external" || previewImageMime(local.path)) return;
194
- externalRoot = external.roots().find((root) => relativePreviewPath(root.path, local.path));
195
- if (!externalRoot || !external.marker.matches(line, point.col, href)) return;
196
- path = local.path;
197
- }
178
+ const local = preview ? undefined : classifyLinkPath(cwd, href);
179
+ if (!preview && !local) return;
180
+ const external = local?.kind === "external";
181
+ if (external && (previewImageMime(local.path) || !marker.matches(line, point.col, href))) return;
182
+ const path = preview && "path" in preview ? preview.path : local?.path;
198
183
 
199
- const target: Hover = { ...point, href, path, externalRoot, preview, controller: new AbortController() };
184
+ const target: Hover = { ...point, href, path, external, preview, controller: new AbortController() };
200
185
  hover = target;
201
186
  viewport = { columns: tui.terminal.columns, rows: tui.terminal.rows };
202
187
  timer = setTimeout(() => void show(target), HOVER_DELAY_MS);
@@ -1,11 +1,10 @@
1
- import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
2
2
  import type { TUI } from "@earendil-works/pi-tui";
3
3
  import { createExternalLinkMarker } from "./external-link-marker.js";
4
- import type { ExternalPreviewRoot } from "./filelinks.js";
5
4
  import { createHoverPreview } from "./hover-preview.js";
6
5
  import { renderInlineMarkup } from "./inline-markup.js";
7
- import { loadPreviewSettings } from "./preview-settings.js";
8
- import { INLINE_FORMATTING_PROMPT } from "./prompt.js";
6
+ import { loadPromptSettings, type PromptHintSettings, savePromptHint } from "./settings.js";
7
+ import { showInlineSettings } from "./settings-menu.js";
9
8
  import { createWikilinks } from "./wikilinks.js";
10
9
 
11
10
  const WIDGET_KEY = "pi-inline-markup.preview";
@@ -20,24 +19,38 @@ interface Session {
20
19
  dismissPreview(): void;
21
20
  wiki?: ReturnType<typeof createWikilinks>;
22
21
  menu?: AbortController;
22
+ prompt?: PromptHintSettings;
23
+ }
24
+
25
+ function setWikilinks(session: Session, enabled: boolean): void {
26
+ if (enabled === Boolean(session.wiki)) return;
27
+ session.dismissPreview();
28
+ if (enabled) {
29
+ session.wiki = createWikilinks(session.cwd, () => {
30
+ session.tui.invalidate();
31
+ session.tui.requestRender();
32
+ });
33
+ } else {
34
+ session.wiki?.dispose();
35
+ session.wiki = undefined;
36
+ }
37
+ session.tui.invalidate();
38
+ session.tui.requestRender();
23
39
  }
24
40
 
25
41
  export function inlineMarkupExtension(pi: ExtensionAPI): void {
26
42
  let session: Session | undefined;
43
+ const writes = new Set<Promise<boolean>>();
27
44
 
28
45
  pi.on("session_start", async (_event, { mode, cwd, ui, hasUI, sessionManager }) => {
29
46
  session?.clearWidget();
30
47
  if (mode !== "tui") return;
31
48
  const settings = new AbortController();
32
49
  const marker = createExternalLinkMarker();
33
- let roots: readonly ExternalPreviewRoot[] = [];
34
50
  ui.setWidget(
35
51
  WIDGET_KEY,
36
52
  (tui, theme) => {
37
- const preview = createHoverPreview(tui, theme, cwd, (href) => current.wiki?.findPreview(href), {
38
- marker,
39
- roots: () => roots,
40
- });
53
+ const preview = createHoverPreview(tui, theme, cwd, (href) => current.wiki?.findPreview(href), marker);
41
54
  const current: Session = {
42
55
  cwd,
43
56
  theme,
@@ -53,7 +66,6 @@ export function inlineMarkupExtension(pi: ExtensionAPI): void {
53
66
  dispose() {
54
67
  if (session === current) session = undefined;
55
68
  settings.abort();
56
- roots = [];
57
69
  current.menu?.abort();
58
70
  preview.dispose();
59
71
  current.wiki?.dispose();
@@ -71,54 +83,79 @@ export function inlineMarkupExtension(pi: ExtensionAPI): void {
71
83
  },
72
84
  { placement: "belowEditor" },
73
85
  );
74
- const snapshot = await loadPreviewSettings(settings.signal);
86
+ const snapshot = await loadPromptSettings(settings.signal);
75
87
  if (settings.signal.aborted || session?.marker !== marker) return;
76
- roots = snapshot.roots;
77
- if (snapshot.invalid && hasUI)
78
- ui.notify("pi-inline: Invalid or unreadable settings. External previews are off.", "warning");
88
+ session.prompt = snapshot.prompt;
89
+ if (snapshot.saveBlocked && hasUI) ui.notify("pi-inline: Invalid or unreadable settings were ignored.", "warning");
79
90
  });
80
91
 
81
- pi.on("session_shutdown", (_event, ctx) => {
82
- if (session && ctx.mode === "tui" && session.owner === ctx.sessionManager) session.clearWidget();
92
+ pi.on("session_shutdown", async (_event, ctx) => {
93
+ if (ctx.mode !== "tui") return;
94
+ if (session && session.owner === ctx.sessionManager) session.clearWidget();
95
+ // The host may already have disposed the widget. Wait for writes that reached publication.
96
+ await Promise.allSettled(writes);
83
97
  });
84
98
 
85
- pi.registerCommand("inline-markup", {
86
- description: "Turn wikilinks on or off for this session",
87
- async handler(args, ctx) {
88
- if (args.trim()) throw new Error("Usage: /inline-markup (no arguments)");
89
- if (ctx.mode !== "tui") throw new Error("/inline-markup is available only in the terminal UI.");
90
- const current = session;
91
- if (!current || current.menu) return;
92
- const menu = new AbortController();
93
- current.menu = menu;
99
+ async function handler(args: string, ctx: ExtensionCommandContext): Promise<void> {
100
+ if (args.trim()) throw new Error("Usage: /inline (no arguments)");
101
+ if (ctx.mode !== "tui") throw new Error("/inline is available only in the terminal UI.");
102
+ const current = session;
103
+ const active = current?.prompt;
104
+ if (!current || !active || current.owner !== ctx.sessionManager || current.menu) return;
105
+ const menu = new AbortController();
106
+ current.menu = menu;
107
+ const live = () => session === current && current.menu === menu && !menu.signal.aborted;
108
+ try {
109
+ const saved = await loadPromptSettings(menu.signal);
110
+ if (!live()) return;
111
+ const changed = await showInlineSettings(ctx, {
112
+ signal: menu.signal,
113
+ wikilinks: Boolean(current.wiki),
114
+ setWikilinks: (enabled) => {
115
+ if (live()) setWikilinks(current, enabled);
116
+ },
117
+ saved: saved.prompt,
118
+ active,
119
+ saveBlocked: Boolean(saved.saveBlocked),
120
+ async save(change, signal) {
121
+ if (!live() || signal.aborted) return false;
122
+ const pending = savePromptHint(saved.prompt, change, signal);
123
+ writes.add(pending);
124
+ try {
125
+ return await pending;
126
+ } finally {
127
+ writes.delete(pending);
128
+ }
129
+ },
130
+ });
131
+ if (!changed || !live()) return;
132
+ if (changed === "saved-after-cancel") {
133
+ ctx.ui.notify("The prompt hint was saved. Run /reload to apply it.", "info");
134
+ return;
135
+ }
136
+ const reload = await ctx.ui.confirm("Reload Pi now?", "The prompt hint setting was saved.", {
137
+ signal: menu.signal,
138
+ });
139
+ if (!reload || !live()) return;
94
140
  try {
95
- const choice = await ctx.ui.select(`Wikilinks: ${current.wiki ? "On" : "Off"} (this session)`, ["On", "Off"], {
96
- signal: menu.signal,
97
- });
98
- if (session !== current || menu.signal.aborted || (choice !== "On" && choice !== "Off")) return;
99
- if ((choice === "On") === Boolean(current.wiki)) return;
100
-
101
- current.dismissPreview();
102
- if (choice === "On") {
103
- current.wiki = createWikilinks(current.cwd, () => {
104
- current.tui.invalidate();
105
- current.tui.requestRender();
106
- });
107
- } else {
108
- current.wiki?.dispose();
109
- current.wiki = undefined;
110
- }
111
- current.tui.invalidate();
112
- current.tui.requestRender();
113
- } finally {
114
- current.menu = undefined;
141
+ await ctx.reload();
142
+ return;
143
+ } catch {
144
+ if (live())
145
+ ctx.ui.notify("The prompt hint was saved, but Pi could not reload. Run /reload to apply it.", "error");
115
146
  }
116
- },
117
- });
147
+ } finally {
148
+ if (current.menu === menu) current.menu = undefined;
149
+ menu.abort();
150
+ }
151
+ }
152
+
153
+ pi.registerCommand("inline", { description: "Configure inline markup and the prompt hint", handler });
154
+ pi.registerCommand("inline-markup", { description: "Open /inline (compatibility alias)", handler });
118
155
 
119
156
  pi.on("before_agent_start", (event, ctx) => {
120
- if (ctx.mode !== "tui" || !session) return;
121
- event.systemPromptOptions.sections.inline_formatting = INLINE_FORMATTING_PROMPT;
157
+ if (ctx.mode !== "tui" || !session || session.owner !== ctx.sessionManager || !session.prompt?.enabled) return;
158
+ event.systemPromptOptions.sections.inline_formatting = session.prompt.text;
122
159
  });
123
160
 
124
161
  // Pi 1.5.0 does not accept messageTypes registration options.
@@ -0,0 +1,241 @@
1
+ import type { KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ decodeKittyPrintable,
4
+ Editor,
5
+ type Keybinding,
6
+ matchesKey,
7
+ type TUI,
8
+ type TuiMouseEvent,
9
+ } from "@earendil-works/pi-tui";
10
+ import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit";
11
+ import { diffChars } from "diff";
12
+
13
+ const PASTE_START = "\x1b[200~";
14
+ const PASTE_END = "\x1b[201~";
15
+
16
+ // Pi handles these before newline and submit. This editor does not configure autocomplete.
17
+ const EDIT_ACTIONS_BEFORE_SUBMIT: readonly Keybinding[] = [
18
+ "tui.input.copy",
19
+ "tui.editor.undo",
20
+ "tui.input.tab",
21
+ "tui.editor.deleteToLineEnd",
22
+ "tui.editor.deleteToLineStart",
23
+ "tui.editor.deleteWordBackward",
24
+ "tui.editor.deleteWordForward",
25
+ "tui.editor.deleteCharBackward",
26
+ "tui.editor.deleteCharForward",
27
+ "tui.editor.yank",
28
+ "tui.editor.yankPop",
29
+ "tui.editor.historyPrevious",
30
+ "tui.editor.historyNext",
31
+ "tui.editor.cursorLineStart",
32
+ "tui.editor.cursorLineEnd",
33
+ "tui.editor.cursorWordLeft",
34
+ "tui.editor.cursorWordRight",
35
+ ];
36
+ const NAVIGATION_BEFORE_JUMP: readonly Keybinding[] = [
37
+ "tui.editor.cursorUp",
38
+ "tui.editor.cursorDown",
39
+ "tui.editor.cursorRight",
40
+ "tui.editor.cursorLeft",
41
+ "tui.editor.pageUp",
42
+ "tui.editor.pageDown",
43
+ ];
44
+
45
+ interface DraftActions {
46
+ back(): void;
47
+ cancel(): void;
48
+ save(readDraft: () => string): void;
49
+ }
50
+
51
+ export function createPromptHintEditor(
52
+ tui: TUI,
53
+ theme: Theme,
54
+ keybindings: KeybindingsManager,
55
+ initialText: string,
56
+ actions: DraftActions,
57
+ ) {
58
+ const muted = (text: string) => theme.fg("muted", text);
59
+ const editorTheme = {
60
+ borderColor: (text: string) => theme.fg("borderMuted", text),
61
+ selectList: {
62
+ selectedPrefix: (text: string) => theme.fg("accent", text),
63
+ selectedText: (text: string) => theme.fg("accent", text),
64
+ description: muted,
65
+ scrollInfo: muted,
66
+ noMatch: muted,
67
+ },
68
+ };
69
+ const editor = new Editor(tui, editorTheme);
70
+ editor.disableSubmit = true;
71
+ editor.setText(initialText);
72
+ const initialDraft = editor.getExpandedText();
73
+ let pasteBuffer: string | undefined;
74
+ let awaitingJumpTarget = false;
75
+ const displaySafe = () => sanitizeTerminalDocument(editor.getText()) === editor.getText();
76
+
77
+ function handleInput(data: string) {
78
+ const start = data.indexOf(PASTE_START);
79
+ if (start >= 0 && pasteBuffer === undefined) {
80
+ if (awaitingJumpTarget) {
81
+ // A bracketed paste cancels Pi's pending character jump.
82
+ editor.handleInput(PASTE_START + PASTE_END);
83
+ awaitingJumpTarget = false;
84
+ }
85
+ pasteBuffer = "";
86
+ data = data.slice(start + PASTE_START.length);
87
+ }
88
+ if (pasteBuffer !== undefined) {
89
+ const searchFrom = Math.max(0, pasteBuffer.length - PASTE_END.length + 1);
90
+ pasteBuffer += data;
91
+ const end = pasteBuffer.indexOf(PASTE_END, searchFrom);
92
+ if (end === -1) return;
93
+ // Decode and filter the paste like Pi does, but use an empty editor so Pi's
94
+ // large-paste marker cannot match literal text in the prompt draft.
95
+ const decoder = new Editor(tui, editorTheme);
96
+ decoder.handleInput(PASTE_START + pasteBuffer.slice(0, end) + PASTE_END);
97
+ let pasted = decoder.getExpandedText();
98
+ const { line, col } = editor.getCursor();
99
+ if (/^[/~.]/u.test(pasted) && /\w/u.test(editor.getLines()[line]?.charAt(col - 1) ?? "")) pasted = ` ${pasted}`;
100
+ editor.insertTextAtCursor(pasted);
101
+ const tail = pasteBuffer.slice(end + PASTE_END.length);
102
+ pasteBuffer = undefined;
103
+ if (tail) handleInput(tail);
104
+ return;
105
+ }
106
+ if (matchesKey(data, "ctrl+c")) {
107
+ actions.cancel();
108
+ return;
109
+ }
110
+ if (keybindings.matches(data, "tui.select.cancel")) {
111
+ actions.back();
112
+ return;
113
+ }
114
+
115
+ const jump =
116
+ keybindings.matches(data, "tui.editor.jumpForward") || keybindings.matches(data, "tui.editor.jumpBackward");
117
+ const wasAwaitingJumpTarget = awaitingJumpTarget;
118
+ awaitingJumpTarget = false;
119
+ if (wasAwaitingJumpTarget && (jump || isPrintableInput(data))) {
120
+ editor.handleInput(data);
121
+ return;
122
+ }
123
+ if (
124
+ EDIT_ACTIONS_BEFORE_SUBMIT.some((action) => keybindings.matches(data, action)) ||
125
+ matchesKey(data, "shift+backspace") ||
126
+ matchesKey(data, "shift+delete")
127
+ ) {
128
+ editor.handleInput(data);
129
+ return;
130
+ }
131
+
132
+ const submit = keybindings.matches(data, "tui.input.submit");
133
+ const newline =
134
+ keybindings.matches(data, "tui.input.newLine") ||
135
+ data.startsWith("\n") ||
136
+ data === "\x1b[13;2~" ||
137
+ (data.includes("\x1b") && data.includes("\r"));
138
+ if (!submit && !newline) {
139
+ awaitingJumpTarget = jump && !NAVIGATION_BEFORE_JUMP.some((action) => keybindings.matches(data, action));
140
+ editor.handleInput(data);
141
+ return;
142
+ }
143
+
144
+ const { line, col } = editor.getCursor();
145
+ const lines = editor.getLines();
146
+ const backslash = lines[line]?.charAt(col - 1) === "\\";
147
+ const fallbackSubmit =
148
+ newline &&
149
+ matchesKey(data, "enter") &&
150
+ backslash &&
151
+ keybindings.getKeys("tui.input.submit").some((key) => key === "shift+enter" || String(key) === "shift+return");
152
+ if (newline && !fallbackSubmit) {
153
+ editor.handleInput(data);
154
+ return;
155
+ }
156
+ if (!newline && backslash) {
157
+ // This native submit branch removes the backslash and inserts a newline.
158
+ editor.disableSubmit = false;
159
+ try {
160
+ editor.handleInput(data);
161
+ } finally {
162
+ editor.disableSubmit = true;
163
+ }
164
+ return;
165
+ }
166
+
167
+ if (wasAwaitingJumpTarget) editor.handleInput(PASTE_START + PASTE_END);
168
+ // Native submit clears Undo. Read the draft without submitting it to Pi.
169
+ const offset = fallbackSubmit ? lines.slice(0, line).reduce((sum, text) => sum + text.length + 1, col - 1) : -1;
170
+ const raw = editor.getExpandedText();
171
+ const draft = offset === -1 ? raw : raw.slice(0, offset) + raw.slice(offset + 1);
172
+ if (draft === initialDraft && initialDraft !== initialText) {
173
+ actions.back();
174
+ return;
175
+ }
176
+ actions.save(() => restoreUnchangedTabs(initialText, initialDraft, draft));
177
+ }
178
+
179
+ return {
180
+ get focused() {
181
+ return editor.focused;
182
+ },
183
+ set focused(value: boolean) {
184
+ editor.focused = value;
185
+ },
186
+ get pasting() {
187
+ return pasteBuffer !== undefined;
188
+ },
189
+ render: (width: number) =>
190
+ displaySafe()
191
+ ? editor.render(width)
192
+ : [theme.fg("warning", "Draft contains unsafe terminal text. Undo or edit it.")],
193
+ invalidate: () => editor.invalidate(),
194
+ handleInput,
195
+ handleMouse: (event: TuiMouseEvent) => (displaySafe() ? editor.handleMouse(event) : undefined),
196
+ };
197
+ }
198
+
199
+ function isPrintableInput(data: string): boolean {
200
+ if (data.charCodeAt(0) >= 32 || decodeKittyPrintable(data) !== undefined) return true;
201
+ // xterm modifyOtherKeys encodes unmodified or Shift-modified printable input as CSI 27;mod;code~.
202
+ const prefix = "\x1b[27;";
203
+ if (!data.startsWith(prefix)) return false;
204
+ const match = /^(\d+);(\d+)~$/u.exec(data.slice(prefix.length));
205
+ if (!match) return false;
206
+ const modifiers = (Number(match[1]) - 1) & ~(64 | 128);
207
+ const codePoint = Number(match[2]);
208
+ return (modifiers === 0 || modifiers === 1) && codePoint >= 32 && codePoint <= 0x10ffff;
209
+ }
210
+
211
+ function restoreUnchangedTabs(original: string, initialDraft: string, draft: string): string {
212
+ if (!original.includes("\t")) return draft;
213
+ const tabWidth = 4;
214
+ const tabs = Array.from(original.matchAll(/\t/gu), (match, index) => match.index + index * (tabWidth - 1));
215
+ const changes = diffChars(initialDraft, draft, { timeout: 200 });
216
+ if (!changes) throw new Error("This edit is too large to preserve tabs. Edit pi-inline.json directly.");
217
+
218
+ let sourceOffset = 0;
219
+ let tabIndex = 0;
220
+ const output: string[] = [];
221
+ for (const { added, removed, value } of changes) {
222
+ if (added) {
223
+ output.push(value);
224
+ continue;
225
+ }
226
+ const end = sourceOffset + value.length;
227
+ if (!removed) {
228
+ let from = 0;
229
+ for (; tabIndex < tabs.length && tabs[tabIndex] + tabWidth <= end; tabIndex++) {
230
+ const start = tabs[tabIndex] - sourceOffset;
231
+ if (start < 0) continue;
232
+ output.push(value.slice(from, start), "\t");
233
+ from = start + tabWidth;
234
+ }
235
+ output.push(value.slice(from));
236
+ }
237
+ while (tabIndex < tabs.length && tabs[tabIndex] < end) tabIndex++;
238
+ sourceOffset = end;
239
+ }
240
+ return output.join("");
241
+ }
@@ -0,0 +1,219 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import { type ExtensionCommandContext, getSettingsListTheme } from "@earendil-works/pi-coding-agent";
3
+ import { CURSOR_MARKER, matchesKey, type SettingItem, SettingsList, type TuiMouseEvent } from "@earendil-works/pi-tui";
4
+ import {
5
+ HorizontalRule,
6
+ renderBoundedFrameLayout,
7
+ runCustomInteraction,
8
+ sanitizeTerminalDocument,
9
+ } from "@narumitw/pi-tui-kit";
10
+ import { createPromptHintEditor } from "./prompt-hint-editor.js";
11
+ import type { PromptHintChange, PromptHintSettings } from "./settings.js";
12
+
13
+ interface InlineSettingsOptions {
14
+ signal: AbortSignal;
15
+ wikilinks: boolean;
16
+ setWikilinks(enabled: boolean): void;
17
+ saved: PromptHintSettings;
18
+ active: PromptHintSettings;
19
+ saveBlocked: boolean;
20
+ save(change: PromptHintChange, signal: AbortSignal): Promise<boolean>;
21
+ }
22
+
23
+ const VALUES = ["On", "Off"];
24
+
25
+ function onOff(enabled: boolean) {
26
+ return enabled ? "On" : "Off";
27
+ }
28
+
29
+ export async function showInlineSettings(
30
+ ctx: ExtensionCommandContext,
31
+ options: InlineSettingsOptions,
32
+ ): Promise<boolean | "saved-after-cancel"> {
33
+ let savedWhileClosing = false;
34
+ const result = await runCustomInteraction<boolean>(ctx, {
35
+ blocked: { kind: "question", message: "Edit Inline settings" },
36
+ signal: options.signal,
37
+ create({ tui, theme, keybindings, signal, complete }) {
38
+ const rule = new HorizontalRule({ ruleStyle: (text) => theme.fg("border", text) });
39
+ const cursor = stripVTControlCharacters(getSettingsListTheme().cursor);
40
+ const reloadPending =
41
+ options.saved.enabled !== options.active.enabled || options.saved.text !== options.active.text;
42
+ const promptValue = `${onOff(options.saved.enabled)}${reloadPending ? " (reload pending)" : ""}`;
43
+ let pending: Promise<void> | undefined;
44
+ let editor: ReturnType<typeof createPromptHintEditor> | undefined;
45
+ let focused = false;
46
+ let renderedWidth = 0;
47
+ let contentHeight = 0;
48
+ let mousePressed = false;
49
+ const mouseRows = new Map<number, number>();
50
+
51
+ function save(change: () => PromptHintChange, unchanged?: () => void) {
52
+ if (signal.aborted || pending || options.saveBlocked) return;
53
+ pending = Promise.resolve().then(async () => {
54
+ try {
55
+ if (signal.aborted) return;
56
+ const changed = await options.save(change(), signal);
57
+ if (signal.aborted) {
58
+ savedWhileClosing = changed;
59
+ return;
60
+ }
61
+ if (changed) complete(true);
62
+ else unchanged?.();
63
+ } catch (error) {
64
+ if (signal.aborted) return;
65
+ const detail = error instanceof Error ? sanitizeTerminalDocument(error.message).replace(/\n/gu, " ") : "";
66
+ ctx.ui.notify(detail || "Could not save the prompt hint.", "error");
67
+ } finally {
68
+ pending = undefined;
69
+ if (!signal.aborted) tui.requestRender();
70
+ }
71
+ });
72
+ }
73
+
74
+ const items: SettingItem[] = [
75
+ {
76
+ id: "wikilinks",
77
+ label: "Wikilinks",
78
+ currentValue: onOff(options.wikilinks),
79
+ values: VALUES,
80
+ description: "Resolve Wikilinks in this session.",
81
+ },
82
+ {
83
+ id: "promptHintEnabled",
84
+ label: "Prompt Hint",
85
+ currentValue: promptValue,
86
+ values: options.saveBlocked ? undefined : [promptValue, onOff(!options.saved.enabled)],
87
+ description: reloadPending
88
+ ? `The active hint is ${onOff(options.active.enabled)}. Reload to apply saved settings.`
89
+ : "Include the saved prompt hint in new sessions.",
90
+ },
91
+ {
92
+ id: "promptHintText",
93
+ label: "Edit Prompt Hint…",
94
+ currentValue: "",
95
+ description: "Edit the saved text, even when Prompt Hint is Off.",
96
+ submenu: options.saveBlocked
97
+ ? undefined
98
+ : (_value, finish) => {
99
+ const back = () => {
100
+ if (editor) editor.focused = false;
101
+ editor = undefined;
102
+ mousePressed = false;
103
+ mouseRows.clear();
104
+ finish();
105
+ };
106
+ editor = createPromptHintEditor(tui, theme, keybindings, options.saved.text, {
107
+ back,
108
+ cancel: () => complete(false),
109
+ save: (draft) => save(() => ({ key: "promptHintText", value: draft() }), back),
110
+ });
111
+ editor.focused = focused;
112
+ mouseRows.clear();
113
+ return editor;
114
+ },
115
+ },
116
+ ];
117
+ const list = new SettingsList(
118
+ items,
119
+ items.length,
120
+ {
121
+ label: (text, selected) => (selected ? theme.fg("accent", text) : text),
122
+ value: (text, selected) => theme.fg(selected ? "accent" : "muted", text),
123
+ description: (text) => theme.fg("muted", text),
124
+ cursor: theme.fg("accent", cursor),
125
+ hint: (text) => theme.fg("muted", text),
126
+ },
127
+ (id, value) => {
128
+ if (signal.aborted) return;
129
+ if (id === "wikilinks") options.setWikilinks(value === "On");
130
+ if (id === "promptHintEnabled") {
131
+ // Native SettingsList cycles first; keep the displayed value until a save succeeds.
132
+ list.updateValue(id, promptValue);
133
+ save(() => ({ key: id, value: value === "On" }));
134
+ }
135
+ },
136
+ () => complete(false),
137
+ );
138
+
139
+ return {
140
+ capturesViewportInput: true,
141
+ get focused() {
142
+ return focused;
143
+ },
144
+ set focused(value: boolean) {
145
+ focused = value;
146
+ if (editor) editor.focused = value;
147
+ },
148
+ render(width: number) {
149
+ renderedWidth = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0;
150
+ // The native list needs four cells for its row prefix and description layout.
151
+ // Drop its fixed Enter/Space/Esc hint; it does not reflect remapped bindings.
152
+ const content = editor ? editor.render(renderedWidth) : list.render(Math.max(4, renderedWidth)).slice(0, -2);
153
+ contentHeight = content.length;
154
+ const focusedRow = content.findIndex((line) =>
155
+ editor ? line.includes(CURSOR_MARKER) : stripVTControlCharacters(line).startsWith(cursor),
156
+ );
157
+ const terminalRows = Number.isFinite(tui.terminal.rows) ? Math.floor(tui.terminal.rows) : 24;
158
+ const status = pending
159
+ ? "Saving prompt hint…"
160
+ : options.saveBlocked
161
+ ? "Repair pi-inline.json before saving prompt settings."
162
+ : undefined;
163
+ const frame = renderBoundedFrameLayout({
164
+ width: renderedWidth,
165
+ maxRows: Math.max(1, terminalRows - 3),
166
+ rule: rule.render(renderedWidth)[0] ?? "",
167
+ title: [theme.fg("accent", theme.bold(editor ? "Edit Prompt Hint" : "Inline Settings"))],
168
+ context: status ? [theme.fg("muted", status)] : [],
169
+ content,
170
+ priorityRows: focusedRow < 0 ? [] : [focusedRow],
171
+ focusedRow,
172
+ });
173
+ mouseRows.clear();
174
+ for (const { frameIndex, contentIndex } of frame.contentRows) mouseRows.set(frameIndex, contentIndex);
175
+ return frame.lines;
176
+ },
177
+ invalidate() {
178
+ list.invalidate();
179
+ rule.invalidate();
180
+ mouseRows.clear();
181
+ mousePressed = false;
182
+ },
183
+ handleInput(data: string) {
184
+ if (signal.aborted) return;
185
+ mousePressed = false;
186
+ mouseRows.clear();
187
+ if (matchesKey(data, "ctrl+c") && !editor?.pasting) complete(false);
188
+ else if (!pending) list.handleInput(data);
189
+ if (!signal.aborted) tui.requestRender();
190
+ },
191
+ handleMouse(event: TuiMouseEvent) {
192
+ if (signal.aborted || pending) return;
193
+ const nativeRow = mouseRows.get(event.y);
194
+ if (nativeRow === undefined || event.x < 0 || event.x >= renderedWidth) {
195
+ mousePressed = false;
196
+ return;
197
+ }
198
+ const nativeEvent = { ...event, y: nativeRow, width: renderedWidth, height: contentHeight };
199
+ if (!editor && event.type === "click" && event.button === "left" && !mousePressed) {
200
+ // Clear a stale native press when a previous gesture ended outside the list.
201
+ list.handleMouse({ ...nativeEvent, type: "press" });
202
+ }
203
+ const result = list.handleMouse(nativeEvent);
204
+ if (event.type === "press" && event.button === "left") mousePressed = result?.handled === true;
205
+ if (event.type === "click" || event.type === "wheel") mousePressed = false;
206
+ if (result?.handled && result.render !== false && !signal.aborted) tui.requestRender();
207
+ return result;
208
+ },
209
+ dispose() {
210
+ if (editor) editor.focused = false;
211
+ mouseRows.clear();
212
+ },
213
+ waitForPending: () => pending ?? Promise.resolve(),
214
+ };
215
+ },
216
+ });
217
+ if (result.kind !== "completed") return false;
218
+ return savedWhileClosing ? "saved-after-cancel" : result.value;
219
+ }
@@ -0,0 +1,220 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { type BigIntStats, constants } from "node:fs";
3
+ import { lstat, mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
6
+ import { parseTree } from "jsonc-parser";
7
+ import { INLINE_FORMATTING_PROMPT } from "./prompt.js";
8
+
9
+ export type PromptHintSettings = { enabled: boolean; text: string };
10
+ export type PromptHintChange = { key: "promptHintEnabled"; value: boolean } | { key: "promptHintText"; value: string };
11
+
12
+ export const DEFAULT_PROMPT_HINT: PromptHintSettings = Object.freeze({ enabled: true, text: INLINE_FORMATTING_PROMPT });
13
+
14
+ type PromptSettings = { prompt: PromptHintSettings; saveBlocked?: true };
15
+ type SettingsDocument = Record<string, unknown>;
16
+
17
+ type DocumentSnapshot = { document: SettingsDocument; source?: string; stat?: BigIntStats };
18
+ const repair = "Settings cannot be saved. Repair the user pi-inline.json file and reopen the menu.";
19
+ const stale = "Settings changed. Reopen the menu before saving.";
20
+ const writeFailed = "Settings were not saved. Check file permissions and available disk space.";
21
+ const settingsTails = new Map<string, Promise<unknown>>();
22
+
23
+ function inSettingsQueue<T>(path: string, operation: () => Promise<T>): Promise<T> {
24
+ // Keep request order for the configured path even if Pi's realpath-based key changes
25
+ // when the file is created under a symlinked directory. Neither queue spans processes.
26
+ const result = (settingsTails.get(path) ?? Promise.resolve()).then(() => withFileMutationQueue(path, operation));
27
+ const tail = result.catch(() => undefined);
28
+ settingsTails.set(path, tail);
29
+ return result.finally(() => {
30
+ if (settingsTails.get(path) === tail) settingsTails.delete(path);
31
+ });
32
+ }
33
+
34
+ function settingsPath(): string {
35
+ return resolve(getAgentDir(), "pi-inline.json");
36
+ }
37
+
38
+ async function statFile(path: string): Promise<BigIntStats | undefined> {
39
+ return lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
40
+ if (error.code !== "ENOENT") throw error;
41
+ return undefined;
42
+ });
43
+ }
44
+
45
+ function sameFile(a: BigIntStats, b: BigIntStats): boolean {
46
+ return a.dev === b.dev && a.ino === b.ino;
47
+ }
48
+
49
+ async function readDocument(path: string, signal: AbortSignal): Promise<DocumentSnapshot> {
50
+ signal.throwIfAborted();
51
+ const stat = await statFile(path);
52
+ signal.throwIfAborted();
53
+ if (!stat) return { document: {} };
54
+ // Reject symlinks, streams and directories before reading from a verified handle.
55
+ if (!stat.isFile()) throw new Error(repair);
56
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
57
+ try {
58
+ signal.throwIfAborted();
59
+ const opened = await handle.stat({ bigint: true });
60
+ signal.throwIfAborted();
61
+ if (!opened.isFile() || !sameFile(stat, opened)) throw new Error(repair);
62
+ const bytes = await readFile(handle, { signal });
63
+ signal.throwIfAborted();
64
+ const source = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
65
+ const document: unknown = JSON.parse(source);
66
+ if (!document || typeof document !== "object" || Array.isArray(document)) throw new Error(repair);
67
+ return { document: document as SettingsDocument, source, stat };
68
+ } finally {
69
+ await handle.close();
70
+ }
71
+ }
72
+
73
+ function normalizePromptText(value: unknown): string | undefined {
74
+ if (typeof value !== "string") return undefined;
75
+ const text = value.replaceAll("\r\n", "\n");
76
+ if (!text.trim() || /(?![\n\t])[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u.test(text)) return undefined;
77
+ return text;
78
+ }
79
+
80
+ function readPromptHint(document: SettingsDocument): PromptHintSettings | undefined {
81
+ const enabled = Object.hasOwn(document, "promptHintEnabled")
82
+ ? document.promptHintEnabled
83
+ : DEFAULT_PROMPT_HINT.enabled;
84
+ const text = Object.hasOwn(document, "promptHintText")
85
+ ? normalizePromptText(document.promptHintText)
86
+ : DEFAULT_PROMPT_HINT.text;
87
+ return typeof enabled === "boolean" && text !== undefined ? { enabled, text } : undefined;
88
+ }
89
+
90
+ async function readSettings(signal: AbortSignal): Promise<SettingsDocument | undefined> {
91
+ if (signal.aborted) return undefined;
92
+ const path = settingsPath();
93
+ try {
94
+ const { document } = await inSettingsQueue(path, () => readDocument(path, signal));
95
+ return signal.aborted ? undefined : document;
96
+ } catch {
97
+ return undefined;
98
+ }
99
+ }
100
+
101
+ export async function loadPromptSettings(signal: AbortSignal): Promise<PromptSettings> {
102
+ const document = await readSettings(signal);
103
+ const defaults = { prompt: { ...DEFAULT_PROMPT_HINT } };
104
+ if (signal.aborted) return defaults;
105
+ const prompt = document && readPromptHint(document);
106
+ return prompt ? { prompt } : { ...defaults, saveBlocked: true };
107
+ }
108
+
109
+ function editPromptSetting(source: string | undefined, key: PromptHintChange["key"], value: boolean | string): string {
110
+ if (source === undefined) return `${JSON.stringify({ [key]: value }, null, 2)}\n`;
111
+
112
+ // The source already passed strict JSON validation. Edit the last matching property
113
+ // to agree with JSON.parse on duplicate keys, without reserializing other values.
114
+ const root = parseTree(source);
115
+ if (root?.type !== "object") throw new Error(repair);
116
+ const properties = root.children ?? [];
117
+ const property = properties.findLast(({ children }) => children?.[0]?.value === key);
118
+ const current = property?.children?.[1];
119
+ if (current) {
120
+ return source.slice(0, current.offset) + JSON.stringify(value) + source.slice(current.offset + current.length);
121
+ }
122
+
123
+ const last = properties.at(-1);
124
+ const offset = last ? last.offset + last.length : root.offset + 1;
125
+ return (
126
+ source.slice(0, offset) +
127
+ `${last ? "," : ""}\n ${JSON.stringify(key)}: ${JSON.stringify(value)}` +
128
+ source.slice(offset)
129
+ );
130
+ }
131
+
132
+ async function publishDocument(
133
+ path: string,
134
+ snapshot: DocumentSnapshot,
135
+ updated: string,
136
+ signal: AbortSignal,
137
+ ): Promise<boolean> {
138
+ const directory = dirname(path);
139
+ const temporary = join(directory, `.pi-inline-${randomUUID()}.tmp`);
140
+ let ownsTemporary = false;
141
+ try {
142
+ await mkdir(directory, { recursive: true, mode: 0o700 });
143
+ signal.throwIfAborted();
144
+ const handle = await open(temporary, "wx", 0o600);
145
+ ownsTemporary = true;
146
+ try {
147
+ signal.throwIfAborted();
148
+ await writeFile(handle, updated, { encoding: "utf8", signal });
149
+ signal.throwIfAborted();
150
+ await handle.sync();
151
+ } finally {
152
+ await handle.close();
153
+ }
154
+ signal.throwIfAborted();
155
+ const current = await statFile(path);
156
+ signal.throwIfAborted();
157
+ const previous = snapshot.stat;
158
+ if (
159
+ previous
160
+ ? !current?.isFile() ||
161
+ !sameFile(current, previous) ||
162
+ current.size !== previous.size ||
163
+ current.mtimeNs !== previous.mtimeNs ||
164
+ current.ctimeNs !== previous.ctimeNs
165
+ : current !== undefined
166
+ ) {
167
+ return false;
168
+ }
169
+ // Once rename starts, await it even if the caller is cancelled.
170
+ await rename(temporary, path);
171
+ ownsTemporary = false;
172
+ return true;
173
+ } finally {
174
+ if (ownsTemporary) await rm(temporary, { force: true }).catch(() => undefined);
175
+ }
176
+ }
177
+
178
+ export async function savePromptHint(
179
+ expected: PromptHintSettings,
180
+ change: PromptHintChange,
181
+ signal: AbortSignal,
182
+ ): Promise<boolean> {
183
+ if (signal.aborted) return false;
184
+ const { key } = change;
185
+ const enabled = key === "promptHintEnabled";
186
+ const value = key === "promptHintText" ? normalizePromptText(change.value) : change.value;
187
+ if (enabled) {
188
+ if (typeof value !== "boolean") throw new Error("Select On or Off for the prompt hint.");
189
+ } else if (key !== "promptHintText" || value === undefined) {
190
+ throw new Error("Enter a nonblank prompt hint without terminal or bidirectional controls.");
191
+ }
192
+ const baseline = enabled ? expected.enabled : expected.text;
193
+ const path = settingsPath();
194
+ let fail = repair;
195
+ try {
196
+ return await inSettingsQueue(path, async () => {
197
+ const snapshot = await readDocument(path, signal);
198
+ if (signal.aborted) return false;
199
+ const prompt = readPromptHint(snapshot.document);
200
+ if (!prompt) throw new Error();
201
+ const current = enabled ? prompt.enabled : prompt.text;
202
+ if (current !== baseline) {
203
+ fail = stale;
204
+ throw new Error();
205
+ }
206
+ if (value === current) return false;
207
+ const updated = editPromptSetting(snapshot.source, key, value);
208
+ fail = writeFailed;
209
+ const published = await publishDocument(path, snapshot, updated, signal);
210
+ if (!published) {
211
+ fail = stale;
212
+ throw new Error();
213
+ }
214
+ return published;
215
+ });
216
+ } catch {
217
+ if (signal.aborted) return false;
218
+ throw new Error(fail);
219
+ }
220
+ }
@@ -1,52 +0,0 @@
1
- import { lstat, readFile, realpath } from "node:fs/promises";
2
- import { homedir } from "node:os";
3
- import { isAbsolute, join, parse, resolve } from "node:path";
4
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
- import { type ExternalPreviewRoot, relativePreviewPath } from "./filelinks.js";
6
-
7
- type PreviewSettings = { roots: readonly ExternalPreviewRoot[]; invalid?: true };
8
-
9
- export async function loadPreviewSettings(signal: AbortSignal): Promise<PreviewSettings> {
10
- const defaults = { roots: [] };
11
- const invalid = { ...defaults, invalid: true } as const;
12
- try {
13
- const file = join(getAgentDir(), "pi-inline.json");
14
- // Settings are a regular user file, not a project file, symlink, or stream.
15
- const stat = await lstat(file).catch((error: NodeJS.ErrnoException) => {
16
- if (error.code !== "ENOENT") throw error;
17
- });
18
- if (!stat || signal.aborted) return defaults;
19
- if (!stat.isFile()) return invalid;
20
- const source = await readFile(file, { encoding: "utf8", signal });
21
- if (signal.aborted) return defaults;
22
- const document: unknown = JSON.parse(source);
23
- if (!document || typeof document !== "object" || Array.isArray(document)) return invalid;
24
- if (!("externalPreviewRoots" in document)) return defaults;
25
- const values = document.externalPreviewRoots;
26
- if (!Array.isArray(values)) return invalid;
27
- if (!values.length || signal.aborted) return defaults;
28
-
29
- const home = resolve(homedir());
30
- const realHome = await realpath(home).catch(() => home);
31
- const roots: ExternalPreviewRoot[] = [];
32
- for (const value of values) {
33
- if (signal.aborted) return defaults;
34
- if (
35
- typeof value !== "string" ||
36
- !isAbsolute(value) ||
37
- /[*?[\]{}\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u.test(value)
38
- ) {
39
- return invalid;
40
- }
41
- const path = resolve(value);
42
- if ([parse(path).root, home, realHome].includes(path) || relativePreviewPath(path, realHome)) return invalid;
43
- const identity = await lstat(path, { bigint: true });
44
- if (signal.aborted) return defaults;
45
- if (!identity.isDirectory() || (await realpath(path)) !== path) return invalid;
46
- roots.push({ path, identity });
47
- }
48
- return signal.aborted ? defaults : { roots };
49
- } catch {
50
- return signal.aborted ? defaults : invalid;
51
- }
52
- }