klui-code 0.1.7 → 0.1.8

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.
@@ -0,0 +1,193 @@
1
+ // When something new lands on the clipboard, a line above the composer says which keys paste it.
2
+ // Text and images paste differently: the terminal pastes text itself (cmd+v on macOS, ctrl+v in
3
+ // Windows Terminal and VS Code), but it can't send an image, so Klui reads images straight from the
4
+ // clipboard on Pi's paste key (ctrl+v on macOS, alt+v on Windows, where the terminal keeps ctrl+v).
5
+ // Pi's key pastes text too, so it's the advice wherever Klui doesn't know the terminal's own key.
6
+ //
7
+ // Klui looks at the clipboard when the terminal window gets focus back (fullscreen mode turns on
8
+ // the terminal's focus reports) and right after Klui copies something itself. A terminal that never
9
+ // reports focus gets a light check every couple of seconds instead.
10
+ import { createHash } from "node:crypto";
11
+ const hash = (data) => createHash("sha1").update(data).digest("hex");
12
+ /** A read that failed (Windows: another app has the clipboard open) makes the whole clipboard unknown. */
13
+ const FAILED = Symbol("failed");
14
+ const settle = (read) => read ? read().catch(() => FAILED) : Promise.resolve(undefined);
15
+ /**
16
+ * What's on the clipboard, in the order Pi's paste key takes it: files, then an image, then text.
17
+ * Undefined when the clipboard can't be read; null when it's empty.
18
+ */
19
+ export async function readClip(reader) {
20
+ // One after another: on Windows each read opens the clipboard, which locks it for other apps.
21
+ const files = await settle(reader.getFilePaths?.bind(reader));
22
+ const image = await settle(() => reader.getImage());
23
+ const text = await settle(() => reader.getText());
24
+ if (files === FAILED || image === FAILED || text === FAILED)
25
+ return undefined;
26
+ if (files === undefined && image === undefined && text === undefined)
27
+ return undefined;
28
+ if (files?.length)
29
+ return { kind: "files", files: files.length, signature: `files:${hash(files.join("\0"))}` };
30
+ // The text is part of it: the hint names its key too.
31
+ if (image?.length)
32
+ return { kind: "image", alsoText: !!text, signature: `image:${hash(image)}:${text ? hash(text) : ""}` };
33
+ if (text)
34
+ return { kind: "text", signature: `text:${hash(text)}` };
35
+ return null;
36
+ }
37
+ /**
38
+ * The key the terminal itself pastes text with, or Pi's paste key (`piKey`) where that's unknown.
39
+ * The old Windows console (conhost) hands ctrl+v to Klui instead of pasting, and Pi's key is alt+v.
40
+ */
41
+ export function textPasteKey(piKey, platform = process.platform, env = process.env) {
42
+ if (platform === "darwin")
43
+ return "cmd+v";
44
+ if (platform === "win32") {
45
+ if (env.WT_SESSION || env.TERM_PROGRAM === "vscode")
46
+ return "ctrl+v";
47
+ if (env.TERM_PROGRAM === "WezTerm")
48
+ return "ctrl+shift+v";
49
+ return piKey;
50
+ }
51
+ return "ctrl+shift+v";
52
+ }
53
+ /** The hint's words: what was copied, and which keys paste it. `imageKey` is Pi's paste key. */
54
+ export function hintParts(clip, imageKey, platform = process.platform, env = process.env) {
55
+ const textKey = textPasteKey(imageKey, platform, env);
56
+ if (clip.kind === "text")
57
+ return { what: "Text copied", keys: [{ key: textKey, does: "to paste" }] };
58
+ if (clip.kind === "files") {
59
+ return { what: clip.files === 1 ? "File copied" : `${clip.files} files copied`, keys: [{ key: imageKey, does: "to paste" }] };
60
+ }
61
+ if (!clip.alsoText || textKey === imageKey)
62
+ return { what: "Image copied", keys: [{ key: imageKey, does: "to paste" }] };
63
+ return { what: "Image copied", keys: [{ key: imageKey, does: "pastes the image" }, { key: textKey, does: "the text" }] };
64
+ }
65
+ const listeners = new Set();
66
+ export function clipboardEvent(event) {
67
+ for (const listener of listeners)
68
+ listener(event);
69
+ }
70
+ export function onClipboardEvent(listener) {
71
+ listeners.add(listener);
72
+ return () => listeners.delete(listener);
73
+ }
74
+ const RETRIES = 3;
75
+ /**
76
+ * Remembers what was on the clipboard and shows the hint when that changes. Whatever is on the
77
+ * clipboard when Klui starts is taken as already known, so no hint shows for it, and so is
78
+ * whatever is on it when something gets pasted.
79
+ */
80
+ export function createClipboardWatcher({ read, show, hide, pollMs = 2_000, showMs = 10_000, retryMs = 500 }) {
81
+ let last;
82
+ let known = false;
83
+ let stopped = false;
84
+ // Goes up on every paste, copy and focus. A read that started before the latest one is stale:
85
+ // it changes nothing, and the check that event started reads again.
86
+ let epoch = 0;
87
+ // After a paste, the first read that works records what was pasted without showing it, unless
88
+ // Klui copies something first.
89
+ let quiet = false;
90
+ let hideTimer;
91
+ let pollTimer;
92
+ let retryTimer;
93
+ let retries = 0;
94
+ // One read at a time. Checks asked for during a read share the one read after it.
95
+ let reading;
96
+ let next;
97
+ const clearHint = () => {
98
+ clearTimeout(hideTimer);
99
+ hideTimer = undefined;
100
+ hide();
101
+ };
102
+ /** False when the clipboard couldn't be read. */
103
+ const look = async () => {
104
+ const started = epoch;
105
+ const clip = await read().catch(() => undefined);
106
+ if (stopped || epoch !== started)
107
+ return true;
108
+ if (clip === undefined)
109
+ return false;
110
+ const silent = quiet;
111
+ quiet = false;
112
+ const signature = clip?.signature ?? null;
113
+ if (known && signature === last)
114
+ return true;
115
+ const first = !known;
116
+ known = true;
117
+ last = signature;
118
+ if (first || silent)
119
+ return true;
120
+ if (!clip) {
121
+ clearHint();
122
+ return true;
123
+ }
124
+ clearTimeout(hideTimer);
125
+ show(clip);
126
+ hideTimer = setTimeout(clearHint, showMs);
127
+ hideTimer.unref?.();
128
+ return true;
129
+ };
130
+ const check = () => {
131
+ if (stopped)
132
+ return Promise.resolve(true);
133
+ if (!reading) {
134
+ reading = look().finally(() => {
135
+ reading = undefined;
136
+ });
137
+ return reading;
138
+ }
139
+ next ??= reading.then(() => {
140
+ next = undefined;
141
+ return check();
142
+ });
143
+ return next;
144
+ };
145
+ /** Checks focus, a copy or a paste ask for get a few more tries when the clipboard is busy. */
146
+ const checkHard = () => {
147
+ retries = 0;
148
+ clearTimeout(retryTimer);
149
+ retryTimer = undefined;
150
+ const attempt = () => void check().then((ok) => {
151
+ if (ok || stopped || retries >= RETRIES)
152
+ return;
153
+ retries++;
154
+ retryTimer = setTimeout(() => {
155
+ retryTimer = undefined;
156
+ attempt();
157
+ }, retryMs);
158
+ retryTimer.unref?.();
159
+ });
160
+ attempt();
161
+ };
162
+ pollTimer = setInterval(() => void check(), pollMs);
163
+ pollTimer.unref?.();
164
+ void check();
165
+ return {
166
+ check,
167
+ handle(event) {
168
+ if (stopped)
169
+ return;
170
+ epoch++;
171
+ // Klui's own copy after a paste is something new. Focus keeps a paste's quiet read due: what
172
+ // was pasted can still be all that's there.
173
+ if (event === "pasted")
174
+ quiet = true;
175
+ else if (event === "copied")
176
+ quiet = false;
177
+ if (event === "pasted")
178
+ clearHint();
179
+ if (event === "focus" && pollTimer) {
180
+ // The terminal reports focus, so polling can stop.
181
+ clearInterval(pollTimer);
182
+ pollTimer = undefined;
183
+ }
184
+ checkHard();
185
+ },
186
+ stop() {
187
+ stopped = true;
188
+ clearInterval(pollTimer);
189
+ clearTimeout(hideTimer);
190
+ clearTimeout(retryTimer);
191
+ },
192
+ };
193
+ }
@@ -0,0 +1,51 @@
1
+ // The clipboard hint above the composer (see ../clipboard-hint.ts): "Image copied · ctrl+v to paste".
2
+ import { keyText } from "@earendil-works/pi-coding-agent";
3
+ import { getNativeClipboard, truncateToWidth } from "@earendil-works/pi-tui";
4
+ import { createClipboardWatcher, hintParts, onClipboardEvent, readClip } from "../clipboard-hint.js";
5
+ const WIDGET = "klui-clipboard";
6
+ const BRACKETED_PASTE = "\x1b[200~";
7
+ export function hintLine(clip, theme, width, platform = process.platform) {
8
+ const { what, keys } = hintParts(clip, keyText("app.clipboard.pasteImage") || "ctrl+v", platform);
9
+ const dot = theme.fg("dim", " · ");
10
+ const pasting = keys.map(({ key, does }) => `${theme.bold(theme.fg("accent", key))} ${theme.fg("muted", does)}`).join(dot);
11
+ return truncateToWidth(` ${theme.fg("muted", what)}${dot}${pasting}`, width);
12
+ }
13
+ export function registerClipboardHint(pi) {
14
+ let watcher;
15
+ let unsubscribe;
16
+ let unlisten;
17
+ const stop = () => {
18
+ watcher?.stop();
19
+ unsubscribe?.();
20
+ unlisten?.();
21
+ watcher = unsubscribe = unlisten = undefined;
22
+ };
23
+ pi.on("session_start", async (_event, ctx) => {
24
+ stop();
25
+ if (ctx.mode !== "tui")
26
+ return;
27
+ const clipboard = getNativeClipboard();
28
+ if (!clipboard)
29
+ return;
30
+ const { ui } = ctx;
31
+ watcher = createClipboardWatcher({
32
+ read: () => readClip(clipboard),
33
+ show: (clip) => ui.setWidget(WIDGET, (_tui, theme) => ({ render: (width) => [hintLine(clip, theme, width)], invalidate() { } })),
34
+ hide: () => ui.setWidget(WIDGET, undefined),
35
+ });
36
+ const current = watcher;
37
+ unsubscribe = onClipboardEvent((event) => current.handle(event));
38
+ // The terminal's own paste arrives as a bracketed paste.
39
+ unlisten = ui.onTerminalInput((data) => {
40
+ if (data.includes(BRACKETED_PASTE))
41
+ current.handle("pasted");
42
+ return undefined;
43
+ });
44
+ });
45
+ // Sending the message, or queueing it while Klui works, is using what was pasted.
46
+ pi.on("input", async () => {
47
+ watcher?.handle("pasted");
48
+ return { action: "continue" };
49
+ });
50
+ pi.on("session_shutdown", async () => stop());
51
+ }
@@ -1,9 +1,9 @@
1
1
  // A one-line footer under the editor, like Claude Code's: the permission mode on the left; the
2
- // model, context used and event credits on the right.
2
+ // model, context used and connection status on the right.
3
3
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
4
  import { PROVIDER } from "../paths.js";
5
5
  import { modeLabel } from "./permissions.js";
6
- import { creditsLabel, modelLabel, state, subscribe } from "./state.js";
6
+ import { modelLabel, state, subscribe } from "./state.js";
7
7
  export function createFooter(pi, ctx, tui, theme, footerData) {
8
8
  const unsubscribe = subscribe(() => tui.requestRender());
9
9
  return {
@@ -12,18 +12,15 @@ export function createFooter(pi, ctx, tui, theme, footerData) {
12
12
  const think = ctx.model?.reasoning && level && level !== "off" ? ` · ${level}` : "";
13
13
  const usage = ctx.getContextUsage();
14
14
  const statuses = [...footerData.getExtensionStatuses().values()].filter(Boolean);
15
- // Event credits only pay for the event's models.
15
+ // Connection status only applies to the event's models.
16
16
  const eventModel = state.model?.provider === PROVIDER;
17
- const credits = eventModel ? creditsLabel(true) : undefined;
18
17
  const status = !eventModel
19
18
  ? undefined
20
19
  : state.connection.kind === "connecting"
21
20
  ? theme.fg("dim", "connecting…")
22
21
  : state.connection.kind !== "ready"
23
22
  ? theme.fg(state.connection.kind === "closed" ? "warning" : "error", `● ${state.connection.message}`)
24
- : credits
25
- ? theme.fg("success", credits)
26
- : undefined;
23
+ : undefined;
27
24
  const tail = (full) => {
28
25
  const right = [modelLabel() + (full ? think : "")];
29
26
  if (full && usage?.percent != null)
@@ -12,6 +12,7 @@ import { recordUsage } from "../usage.js";
12
12
  import { agentProgress, registerAgents, SUBAGENT_ENV, subagentTokensSoFar } from "./agents.js";
13
13
  import { registerBrowser } from "./browser.js";
14
14
  import { registerChecks } from "./checks.js";
15
+ import { registerClipboardHint } from "./clipboard.js";
15
16
  import { registerCommands } from "./commands.js";
16
17
  import { createFooter } from "./footer.js";
17
18
  import { createHeader } from "./header.js";
@@ -221,6 +222,8 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
221
222
  pi.on("model_select", async (event) => {
222
223
  update({ model: { provider: event.model.provider, id: event.model.id, name: event.model.name } });
223
224
  });
225
+ // Before Klui's own input handler, which decides what the message carries.
226
+ registerClipboardHint(pi);
224
227
  // Pasted image chips and dropped image files go along with the message as images.
225
228
  pi.on("input", async (event, ctx) => {
226
229
  const images = collectImages(event.text);
@@ -3,6 +3,7 @@
3
3
  // if a Pi update moves things around.
4
4
  import { Spacer, TruncatedText, TuiAltScreen } from "@earendil-works/pi-tui";
5
5
  import { PROVIDER_ISSUE, serviceOf } from "./fallback.js";
6
+ import { clipboardEvent } from "./clipboard-hint.js";
6
7
  import { chipFor, isClipboardImageFile } from "./images.js";
7
8
  import { PROVIDER } from "./paths.js";
8
9
  import { scrollFrame } from "./scroll.js";
@@ -13,7 +14,7 @@ export async function patchPi(config, machineOutput = false) {
13
14
  brandOutput();
14
15
  scrollWithTerminal();
15
16
  clearAfterCopy();
16
- for (const patch of [() => sellerModelIds(config), retryProviderIssues, removeLlama, hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips, quietImageNotes])
17
+ for (const patch of [() => sellerModelIds(config), retryProviderIssues, removeLlama, hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips, quietImageNotes, clipboardEvents])
17
18
  await patch().catch(() => { });
18
19
  }
19
20
  /**
@@ -382,6 +383,51 @@ async function pasteImageChips() {
382
383
  editor.insertTextAtCursor = insert;
383
384
  else
384
385
  delete editor.insertTextAtCursor;
386
+ clipboardEvent("pasted");
385
387
  }
386
388
  };
387
389
  }
390
+ /**
391
+ * Tells the clipboard hint (clipboard-hint.ts) when the terminal window gets focus back and when
392
+ * Klui copies something itself. Pi's fullscreen mode turns on focus reports and swallows them.
393
+ */
394
+ async function clipboardEvents() {
395
+ const alt = TuiAltScreen.prototype;
396
+ const viewportInput = alt.handleViewportInput;
397
+ if (typeof viewportInput === "function") {
398
+ alt.handleViewportInput = function (data) {
399
+ if (data === "\x1b[I")
400
+ clipboardEvent("focus");
401
+ return viewportInput.call(this, data);
402
+ };
403
+ }
404
+ // Every Pi copy confirms with "Copied!" or "Copied … to clipboard", and only once it's copied.
405
+ const copied = (message) => typeof message === "string" && message.startsWith("Copied") && clipboardEvent("copied");
406
+ const flash = alt.flash;
407
+ if (typeof flash === "function") {
408
+ alt.flash = function (message, durationMs) {
409
+ flash.call(this, message, durationMs);
410
+ copied(message);
411
+ };
412
+ }
413
+ const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
414
+ // Right-click pastes text straight into the composer, past the terminal input listeners.
415
+ const rightClick = InteractiveMode.prototype.handleRightClickPaste;
416
+ if (typeof rightClick === "function") {
417
+ InteractiveMode.prototype.handleRightClickPaste = async function () {
418
+ try {
419
+ await rightClick.call(this);
420
+ }
421
+ finally {
422
+ clipboardEvent("pasted");
423
+ }
424
+ };
425
+ }
426
+ const status = InteractiveMode.prototype.showStatus;
427
+ if (typeof status !== "function")
428
+ return;
429
+ InteractiveMode.prototype.showStatus = function (message) {
430
+ status.call(this, message);
431
+ copied(message);
432
+ };
433
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "klui-code",
9
- "version": "0.1.7",
9
+ "version": "0.1.8",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@earendil-works/chord": "1.1.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "Klui Code: a pixel-cute coding agent for your terminal, built on Pi and running on Surplus and AntSeed.",
5
5
  "keywords": [
6
6
  "klui",