pi-hot 0.0.0-stage → 0.4.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.
@@ -0,0 +1,841 @@
1
+ /**
2
+ * HoT: Pi adapter. A thin shell around src/core. One command:
3
+ * /hot [what to do] pick a session (Claude Code, Codex, Pi), then say what you want about its recent chat. Empty labels the paragraphs
4
+ * of the latest answer; "highlight ..." colors phrases; "explain the code that ..." finds and colors that code;
5
+ * anything else is answered freely. The session is remembered, and plain text you type then goes to HoT
6
+ * (start with "!" to talk to Pi's own agent; "/hot off" / "/hot on").
7
+ * "/hot pick" switches, "/hot here ..." uses this Pi session, Alt+T opens the prompt box.
8
+ * "/hot add" / "drop" / "solo" / "all ..." read several sessions at once.
9
+ * "/hot skills" (let Claude Code and Codex send requests), "/hot plain [phrase]", "/hot terms" / "know <term>" / "forget <term|all>", "/hot auto [now]".
10
+ * Alt+A (Mac: Option+A) rewrite the selected text without its jargon.
11
+ * Inbox: other agents drop requests into ~/.hot/inbox (see bin/hot-send.mjs); this extension picks them up and shows the result here.
12
+ * Env: HOT_MODEL="provider/id" picks a cheaper model; HOT_DEBUG=1 writes a debug log to /tmp/hot.log.
13
+ */
14
+ import { execSync } from "node:child_process";
15
+ import * as fs from "node:fs";
16
+ import * as os from "node:os";
17
+ import * as path from "node:path";
18
+ import type { UserMessage } from "@earendil-works/pi-ai";
19
+ import { type ExtensionAPI, type ExtensionContext, getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
20
+ import { CURSOR_MARKER, type Focusable, matchesKey, Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
21
+ import { highlightText, plainSentence, sentenceRange, runFreeform, runMulti, tagText, wantsHighlight, wantsTag } from "../../core/actions.ts";
22
+ import { addTerms, forgetTerm, loadMemory, saveMemory } from "../../core/memory.ts";
23
+ import { annotateShots, itemsFromGroups, itemsFromTags } from "../../core/annotate.ts";
24
+ import { type CodeResult, explainLine, findCode, touchedFiles, wantsCode } from "../../core/code.ts";
25
+ import { installSkills } from "../../core/skills.ts";
26
+ import { readSteps } from "../../core/steps.ts";
27
+ import { beforeRequest, lastAssistant, listSessions, readMessages } from "../../core/transcripts.ts";
28
+ import type { Complete, Msg, Session, Shot, Source, Step } from "../../core/types.ts";
29
+ import { type CardData, clearSwap, type CodeCardData, codeCard, noteOf, setNote, type HighlightCardData, highlightCard, setSwap, swapsOf, tagCard, type TextCardData, textCard } from "./render.ts";
30
+
31
+ function log(msg: string) {
32
+ if (process.env.HOT_DEBUG !== "1") return;
33
+ try {
34
+ fs.appendFileSync("/tmp/hot.log", `${new Date().toISOString()} ${msg}\n`);
35
+ } catch {}
36
+ }
37
+
38
+ // ---------- remembered session ----------
39
+
40
+ const STATE_FILE = path.join(os.homedir(), ".hot", "state.json");
41
+ const INBOX = path.join(os.homedir(), ".hot", "inbox");
42
+ const PI_FILE = path.join(os.homedir(), ".hot", "pi.json");
43
+
44
+ interface State {
45
+ session?: Session;
46
+ /** More sessions read together with `session` ("/hot add"). */
47
+ extras: Session[];
48
+ listening: boolean;
49
+ }
50
+
51
+ const MAX_GROUP = 5;
52
+
53
+ function loadState(): State {
54
+ try {
55
+ const o = JSON.parse(fs.readFileSync(STATE_FILE, "utf8"));
56
+ const session = o?.session as Session | undefined;
57
+ const extras = (Array.isArray(o?.extras) ? o.extras : []).filter((x: Session) => x?.path && fs.existsSync(x.path)) as Session[];
58
+ return { session: session && fs.existsSync(session.path) ? session : undefined, extras: session ? extras : [], listening: o?.listening !== false };
59
+ } catch {
60
+ return { extras: [], listening: true };
61
+ }
62
+ }
63
+
64
+ function saveState(st: State) {
65
+ try {
66
+ fs.mkdirSync(path.dirname(STATE_FILE), { recursive: true });
67
+ fs.writeFileSync(STATE_FILE, JSON.stringify(st));
68
+ } catch {}
69
+ }
70
+
71
+ // ---------- model access ----------
72
+
73
+ function pickModel(ctx: ExtensionContext) {
74
+ const spec = process.env.HOT_MODEL;
75
+ if (spec?.includes("/")) {
76
+ const [provider, ...rest] = spec.split("/");
77
+ const found = (ctx.modelRegistry as any).find?.(provider, rest.join("/"));
78
+ if (found) return found;
79
+ }
80
+ return ctx.model;
81
+ }
82
+
83
+ /** Pi's current model accepts pictures (its model list says so). */
84
+ const hasVision = (ctx: ExtensionContext) => !!(pickModel(ctx) as any)?.input?.includes?.("image");
85
+
86
+ const userMsg = (text: string): UserMessage => ({ role: "user", content: [{ type: "text", text }], timestamp: Date.now() });
87
+
88
+ function completer(ctx: ExtensionContext): Complete {
89
+ return async (system, user, signal, images) => {
90
+ const model = pickModel(ctx);
91
+ if (!model) throw new Error("No model selected");
92
+ const msg: any = userMsg(user);
93
+ for (const img of images ?? []) msg.content.push({ type: "image", data: img.data, mimeType: img.mime });
94
+ const res = await ctx.modelRegistry.complete(model, { systemPrompt: system, messages: [msg] }, { signal });
95
+ const outText = res.content
96
+ .filter((c: any) => c.type === "text")
97
+ .map((c: any) => c.text)
98
+ .join("\n");
99
+ return outText;
100
+ };
101
+ }
102
+
103
+ function ownLastAssistantText(ctx: ExtensionContext): string | undefined {
104
+ const branch = ctx.sessionManager.getBranch();
105
+ for (let i = branch.length - 1; i >= 0; i--) {
106
+ const e: any = branch[i];
107
+ if (e.type === "message" && e.message?.role === "assistant") {
108
+ const text = (e.message.content ?? []).filter((c: any) => c.type === "text").map((c: any) => c.text).join("\n");
109
+ if (text.trim()) return text;
110
+ }
111
+ }
112
+ return undefined;
113
+ }
114
+
115
+ // ---------- session + answer picker ----------
116
+
117
+ interface Row {
118
+ s: Session;
119
+ snippet: string;
120
+ }
121
+ interface Picked {
122
+ session: Session;
123
+ /** Set in multi mode: every ticked session. */
124
+ sessions?: Session[];
125
+ instruction: string;
126
+ }
127
+
128
+ function age(ms: number): string {
129
+ const m = Math.max(0, Math.round((Date.now() - ms) / 60000));
130
+ if (m < 60) return `${m}m ago`;
131
+ if (m < 60 * 48) return `${Math.round(m / 60)}h ago`;
132
+ return `${Math.round(m / 1440)}d ago`;
133
+ }
134
+
135
+ const oneLine = (s: string) => s.replace(/\s+/g, " ").trim();
136
+
137
+ class Picker implements Focusable {
138
+ focused = false;
139
+ private step: "session" | "prompt" = "session";
140
+ private sel = 0;
141
+ private filter = "";
142
+ private chosen?: Session;
143
+ private text = "";
144
+ private cursor = 0;
145
+ private ticked = new Map<string, Session>();
146
+
147
+ /** askPrompt=false when the instruction already came from the command line. */
148
+ constructor(
149
+ private tui: { requestRender(): void },
150
+ private theme: Theme,
151
+ private done: (r: Picked | undefined) => void,
152
+ private rows: Row[],
153
+ private askPrompt: boolean,
154
+ private preset: string,
155
+ startAt?: Session,
156
+ private multi = false,
157
+ ) {
158
+ if (startAt) {
159
+ this.chosen = startAt;
160
+ this.step = "prompt";
161
+ }
162
+ }
163
+
164
+ private visibleRows(): Row[] {
165
+ const f = this.filter.toLowerCase();
166
+ return f ? this.rows.filter((r) => `${r.s.agent} ${r.s.cwd} ${r.snippet}`.toLowerCase().includes(f)) : this.rows;
167
+ }
168
+
169
+ handleInput(data: string): void {
170
+ const printable = data.length >= 1 && !data.startsWith("\x1b") && data.charCodeAt(0) >= 32;
171
+ if (matchesKey(data, "escape")) {
172
+ if (this.step === "prompt") this.step = "session";
173
+ else return this.done(undefined);
174
+ } else if (this.step === "session") {
175
+ if (matchesKey(data, "up")) this.sel = Math.max(0, this.sel - 1);
176
+ else if (matchesKey(data, "down")) this.sel = Math.min(Math.max(0, this.visibleRows().length - 1), this.sel + 1);
177
+ else if (this.multi && data === " ") {
178
+ const row = this.visibleRows()[this.sel];
179
+ if (row) this.ticked.has(row.s.path) ? this.ticked.delete(row.s.path) : this.ticked.set(row.s.path, row.s);
180
+ } else if (matchesKey(data, "return")) {
181
+ const row = this.visibleRows()[this.sel];
182
+ if (this.multi) {
183
+ const all = this.ticked.size ? [...this.ticked.values()] : row ? [row.s] : [];
184
+ if (all.length) return this.done({ session: all[0]!, sessions: all, instruction: "" });
185
+ } else if (row) {
186
+ this.chosen = row.s;
187
+ if (!this.askPrompt) return this.done({ session: row.s, instruction: this.preset });
188
+ this.step = "prompt";
189
+ }
190
+ } else if (matchesKey(data, "backspace")) {
191
+ this.filter = this.filter.slice(0, -1);
192
+ this.sel = 0;
193
+ } else if (printable) {
194
+ this.filter += data;
195
+ this.sel = 0;
196
+ }
197
+ } else {
198
+ if (matchesKey(data, "return")) return this.done({ session: this.chosen!, instruction: this.text.trim() });
199
+ if (matchesKey(data, "backspace")) {
200
+ if (this.cursor > 0) {
201
+ this.text = this.text.slice(0, this.cursor - 1) + this.text.slice(this.cursor);
202
+ this.cursor--;
203
+ }
204
+ } else if (matchesKey(data, "left")) this.cursor = Math.max(0, this.cursor - 1);
205
+ else if (matchesKey(data, "right")) this.cursor = Math.min(this.text.length, this.cursor + 1);
206
+ else if (printable) {
207
+ this.text = this.text.slice(0, this.cursor) + data + this.text.slice(this.cursor);
208
+ this.cursor += data.length;
209
+ }
210
+ }
211
+ this.tui.requestRender();
212
+ }
213
+
214
+ invalidate(): void {}
215
+
216
+ render(width: number): string[] {
217
+ const t = this.theme as any;
218
+ const inner = Math.max(20, width - 4);
219
+ const lines: string[] = [];
220
+ if (this.step === "session") {
221
+ lines.push(
222
+ t.bold(this.multi ? " HoT · add sessions " : " HoT · pick a session ") +
223
+ t.fg("dim", this.multi ? " ↑↓ move · Space tick · Enter add · Esc close" : " ↑↓ move · type to filter · Enter select · Esc close"),
224
+ );
225
+ lines.push(`${t.fg("accent", "filter ›")} ${this.filter}${this.focused ? CURSOR_MARKER : ""}`);
226
+ lines.push("");
227
+ const rows = this.visibleRows();
228
+ if (!rows.length) lines.push(t.fg("dim", " no sessions match"));
229
+ const start = Math.max(0, Math.min(this.sel - 5, rows.length - 12));
230
+ rows.slice(start, start + 12).forEach((r, i) => {
231
+ const live = Date.now() - r.s.mtimeMs < 10 * 60000 ? t.fg("success", "●") : t.fg("dim", "○");
232
+ const box = this.multi ? (this.ticked.has(r.s.path) ? "[x] " : "[ ] ") : "";
233
+ const text = `${box}${live} ${r.s.agent.padEnd(6)} ${path.basename(r.s.cwd).slice(0, 18).padEnd(18)} ${age(r.s.mtimeMs).padEnd(8)} ${r.snippet}`;
234
+ lines.push(start + i === this.sel ? t.bg("selectedBg", t.bold(`▸ ${text}`)) : ` ${text}`);
235
+ });
236
+ } else {
237
+ const s = this.chosen!;
238
+ lines.push(t.bold(` HoT · ${s.agent} · ${path.basename(s.cwd)} `) + t.fg("dim", " Enter run · Esc switch session"));
239
+ lines.push(t.fg("dim", " What should I do with its recent chat? e.g. “explain the latest answer”, “rewrite it more naturally”, “translate to Vietnamese”."));
240
+ lines.push(t.fg("dim", " Empty = label the paragraphs of the latest answer."));
241
+ lines.push("");
242
+ const at = this.text[this.cursor] ?? " ";
243
+ const cur = this.focused ? `${CURSOR_MARKER}\x1b[7m${at}\x1b[27m` : at;
244
+ lines.push(t.fg("accent", "› ") + this.text.slice(0, this.cursor) + cur + this.text.slice(this.cursor + 1));
245
+ }
246
+ const box = (x: string) => `│ ${truncateToWidth(x, inner, "")}${" ".repeat(Math.max(0, inner - visibleWidth(x)))} │`;
247
+ return [t.fg("accent", `┌${"─".repeat(width - 2)}┐`), ...lines.map(box), t.fg("accent", `└${"─".repeat(width - 2)}┘`)];
248
+ }
249
+ }
250
+
251
+ // ---------- clipboard ----------
252
+
253
+ function readClipboard(): string {
254
+ for (const c of ["pbpaste", "wl-paste -n", "xclip -selection clipboard -o"]) {
255
+ try {
256
+ const out = execSync(c, { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] });
257
+ if (out.trim()) return out.trim();
258
+ } catch {}
259
+ }
260
+ return "";
261
+ }
262
+
263
+ // ---------- extension ----------
264
+
265
+ /** The tool had other names before ("taki", then "tax"): keep what it remembered. */
266
+ function migrate() {
267
+ const now = path.join(os.homedir(), ".hot");
268
+ for (const name of [".tax", ".taki"]) {
269
+ const old = path.join(os.homedir(), name);
270
+ try {
271
+ if (!fs.existsSync(now) && fs.existsSync(old)) fs.renameSync(old, now);
272
+ } catch {}
273
+ }
274
+ }
275
+
276
+ export default function (pi: ExtensionAPI) {
277
+ migrate();
278
+ let auto = true;
279
+ let lastTagged = "";
280
+ let lastCtx: ExtensionContext | undefined;
281
+ let watcher: fs.FSWatcher | undefined;
282
+ let draining: Promise<void> = Promise.resolve();
283
+ const initial = loadState();
284
+ let sticky: Session | undefined = initial.session;
285
+ let extras: Session[] = initial.extras;
286
+ let listening = initial.listening;
287
+ // Plain typing goes to HoT only after /hot was used in this Pi, so a Pi opened for something else is left alone.
288
+ let engaged = false;
289
+ const capturing = () => listening && engaged;
290
+ /** The Pi that takes requests from other agents: the one /hot was last used in. */
291
+ const owner = (): number | undefined => {
292
+ try {
293
+ const pid = Number(JSON.parse(fs.readFileSync(PI_FILE, "utf8")).pid);
294
+ process.kill(pid, 0);
295
+ return pid;
296
+ } catch {
297
+ return undefined;
298
+ }
299
+ };
300
+ const claim = () => {
301
+ engaged = true;
302
+ try {
303
+ fs.mkdirSync(INBOX, { recursive: true });
304
+ fs.writeFileSync(PI_FILE, JSON.stringify({ pid: process.pid, pane: process.env.HERDR_PANE_ID ?? null, startedAt: Date.now() }));
305
+ } catch {}
306
+ };
307
+ const persist = () => saveState({ session: sticky, extras, listening });
308
+ const group = (): Session[] => (sticky ? [sticky, ...extras] : []);
309
+ const mem = loadMemory();
310
+ const learn = (terms: string[]) => {
311
+ if (terms.length) addTerms(mem, terms);
312
+ saveMemory(mem);
313
+ };
314
+
315
+ type Badge = { kind: "none" } | { kind: "ready" } | { kind: "working"; what: string } | { kind: "error"; msg: string };
316
+
317
+ /** A colored state badge above the editor: which session /hot is bound to and what it is doing. */
318
+ const setBadge = (ctx: ExtensionContext, b: Badge) => {
319
+ if (!ctx.hasUI) return;
320
+ const g = group();
321
+ const where = g.length > 1 ? `${g.length} sessions: ${g.map((x) => path.basename(x.cwd)).join(", ")}`.slice(0, 70) : sticky ? `${sticky.agent} · ${path.basename(sticky.cwd)}` : "";
322
+ ctx.ui.setStatus("HoT", undefined);
323
+ ctx.ui.setWidget("HoT", (_tui, theme) => {
324
+ const t = theme as any;
325
+ const pill = (bg: string, fg: string, text: string) => t.bg(bg, t.fg(fg, t.bold(` ${text} `)));
326
+ const head = pill("toolPendingBg", "accent", "HOT");
327
+ let line: string;
328
+ if (b.kind === "working") line = `${head} ${pill("toolPendingBg", "warning", `◌ ${b.what.toUpperCase()}`)} ${t.fg("muted", where)}`;
329
+ else if (b.kind === "error") line = `${head} ${pill("toolErrorBg", "error", "✗ ERROR")} ${t.fg("muted", b.msg.slice(0, 80))}`;
330
+ else if (b.kind === "none" || !sticky) line = `${head} ${pill("toolPendingBg", "muted", "○ NO SESSION")} ${t.fg("dim", "/hot <what to do> to pick one")}`;
331
+ else if (capturing()) line = `${head} ${pill("toolSuccessBg", "success", "● LISTENING")} ${t.fg("muted", where)} ${t.fg("dim", "· type to ask about it · ! = normal Pi · /hot off · /hot pick · /hot add")}`;
332
+ else line = `${head} ${pill("toolPendingBg", "warning", "◐ PAUSED")} ${t.fg("muted", where)} ${t.fg("dim", "· typing goes to Pi · /hot on to listen · /hot <what to do>")}`;
333
+ return new Text(line, 1, 0);
334
+ });
335
+ };
336
+
337
+ const showSticky = (ctx: ExtensionContext) => setBadge(ctx, sticky ? { kind: "ready" } : { kind: "none" });
338
+
339
+ let lastHl: HighlightCardData | undefined;
340
+ let plainBusy = false;
341
+ /** A phrase was clicked (or picked): its sentence is shown again in place, rewritten without it. Picking it again puts the original back. */
342
+ async function plainFlow(ctx: ExtensionContext | undefined, plain: string, offset: number, term: string) {
343
+ if (!ctx || plainBusy) return;
344
+ const [a, b] = sentenceRange(plain, offset);
345
+ if (swapsOf(plain).some((x) => x.start === a)) return clearSwap(plain, a);
346
+ const original = plain.slice(a, b);
347
+ setSwap(plain, { start: a, end: b, original, text: original, state: "busy", note: "" });
348
+ plainBusy = true;
349
+ try {
350
+ const r = await withBusy(ctx, "plain", () => plainSentence(completer(ctx), plain, term, original));
351
+ if (!r.rewrite) setSwap(plain, { start: a, end: b, original, text: `${original} ⚠ cannot say it without "${term}": ${r.note}`, state: "cannot", note: r.note });
352
+ else if (r.same) setSwap(plain, { start: a, end: b, original, text: r.rewrite, state: "same", note: r.note });
353
+ else setSwap(plain, { start: a, end: b, original, text: `${r.rewrite} ⚠ meaning may differ: ${r.note}`, state: "differs", note: r.note });
354
+ } catch (e: any) {
355
+ clearSwap(plain, a);
356
+ ctx.ui.notify(`plain failed: ${String(e?.message ?? e)}`, "error");
357
+ } finally {
358
+ plainBusy = false;
359
+ }
360
+ }
361
+
362
+ /** Show WORKING while fn runs, then READY again (or ERROR). */
363
+ async function withBusy<T>(ctx: ExtensionContext, what: string, fn: () => Promise<T>): Promise<T> {
364
+ setBadge(ctx, { kind: "working", what });
365
+ try {
366
+ const r = await fn();
367
+ showSticky(ctx);
368
+ return r;
369
+ } catch (e: any) {
370
+ setBadge(ctx, { kind: "error", msg: String(e?.message ?? e) });
371
+ throw e;
372
+ }
373
+ }
374
+
375
+ pi.on("session_start", async (_e, ctx) => {
376
+ lastCtx = ctx;
377
+ showSticky(ctx);
378
+ startInbox(ctx);
379
+ });
380
+ pi.on("session_shutdown", async () => stopInbox());
381
+
382
+ // entry ids keep the old "taki-" prefix so cards saved in earlier sessions still render
383
+ pi.registerEntryRenderer<CardData>("taki-card", (entry, _opts, theme) => tagCard(entry.data, theme));
384
+ pi.registerEntryRenderer<HighlightCardData>("taki-highlight", (entry, _opts, theme) => highlightCard(entry.data, theme, (term, start, plain) => void plainFlow(lastCtx, plain, start, term)));
385
+ pi.registerEntryRenderer<CodeCardData>("taki-code", (entry, _opts, theme) => codeCard(entry.data, theme, (code, line, instruction) => void lineFlow(lastCtx, code, line, instruction)));
386
+ pi.registerEntryRenderer<TextCardData>("taki-text", (entry, _opts, theme) => textCard(entry.data, theme, getMarkdownTheme()));
387
+
388
+ async function tagAndAppend(ctx: ExtensionContext, text: string, source?: Source, session?: Session) {
389
+ let steps: Step[] = [];
390
+ try {
391
+ steps = session ? readSteps(session) : [];
392
+ } catch {}
393
+ // pictures are sent only if the model accepts images, and drawn only if the terminal could show them
394
+ const vision = hasVision(ctx);
395
+ const { tags, terms } = await withBusy(ctx, "tagging", () => tagText(completer(ctx), text, { steps, glossary: mem.glossary, vision }));
396
+ log(`tagged ${tags.length} tags (text ${text.length} chars, ${steps.length} steps, ${steps.filter((s) => s.image).length} images, vision=${vision})`);
397
+ if (tags.length) {
398
+ let shots: Shot[] = [];
399
+ try {
400
+ shots = annotateShots(itemsFromTags(tags), steps);
401
+ } catch (e: any) {
402
+ log(`annotate failed: ${e?.message ?? e}`);
403
+ }
404
+ learn(terms);
405
+ pi.appendEntry<CardData>("taki-card", { tags, source, shots });
406
+ }
407
+ return tags.length;
408
+ }
409
+
410
+ pi.on("agent_settled", async (_event, ctx) => {
411
+ const text = ownLastAssistantText(ctx);
412
+ log(`agent_settled auto=${auto} hasUI=${ctx.hasUI} textLen=${text?.length ?? -1} same=${text === lastTagged}`);
413
+ if (!auto || !ctx.hasUI || !text || text === lastTagged || text.length < 300) return;
414
+ lastTagged = text;
415
+ try {
416
+ await tagAndAppend(ctx, text);
417
+ } catch (e: any) {
418
+ log(`auto tag failed: ${e?.message ?? e}`);
419
+ }
420
+ });
421
+
422
+ /** This Pi session as messages, so "/hot here ..." works without reading a file. */
423
+ function ownMessages(ctx: ExtensionContext): Msg[] {
424
+ const out: Msg[] = [];
425
+ for (const e of ctx.sessionManager.getBranch() as any[]) {
426
+ const role = e.type === "message" ? e.message?.role : undefined;
427
+ if (role !== "user" && role !== "assistant") continue;
428
+ const c = e.message.content;
429
+ const text = typeof c === "string" ? c : (c ?? []).filter((b: any) => b.type === "text").map((b: any) => b.text).join("\n");
430
+ if (text.trim()) out.push({ role, text });
431
+ }
432
+ return out;
433
+ }
434
+
435
+ /** "Explain the code that makes X": show that code, its lines colored by purpose. */
436
+ async function codeFlow(ctx: ExtensionContext, instruction: string, session?: Session) {
437
+ const cwd = session?.cwd ?? ctx.cwd;
438
+ ctx.ui.notify(`Looking for the code in ${path.basename(cwd)}…`, "info");
439
+ try {
440
+ const touched = session ? touchedFiles(session) : [];
441
+ const { result, looked } = await withBusy(ctx, "reading code", () => findCode(completer(ctx), instruction, cwd, touched));
442
+ const source = session ? sourceOf(session, readMessages(session)) : undefined;
443
+ log(`code: ${touched.length} edited files, looked at ${looked.join(", ")}, found=${!!result}`);
444
+ if (result) pi.appendEntry<CodeCardData>("taki-code", { instruction, code: result, source });
445
+ else pi.appendEntry<TextCardData>("taki-text", { action: instruction, text: looked.length ? `I could not find that code. Files I looked at: ${looked.join(", ")}` : "I found no source files to look at in that project folder.", source });
446
+ } catch (e: any) {
447
+ ctx.ui.notify(`Failed: ${e?.message ?? e}`, "error");
448
+ }
449
+ }
450
+
451
+ let lineBusy = false;
452
+ /** A code line was clicked: explain it under the line; clicking again removes the explanation. */
453
+ async function lineFlow(ctx: ExtensionContext | undefined, code: CodeResult, line: number, instruction: string) {
454
+ if (!ctx || lineBusy) return;
455
+ if (noteOf(code, line)) return setNote(code, line, undefined);
456
+ lineBusy = true;
457
+ setNote(code, line, "…");
458
+ try {
459
+ const text = await withBusy(ctx, "plain", () => explainLine(completer(ctx), code, line, instruction));
460
+ setNote(code, line, text || undefined);
461
+ } catch (e: any) {
462
+ setNote(code, line, undefined);
463
+ ctx.ui.notify(`explain failed: ${String(e?.message ?? e)}`, "error");
464
+ } finally {
465
+ lineBusy = false;
466
+ }
467
+ }
468
+
469
+ /** Run one request: tag the latest answer, or do what the instruction says with the recent chat. */
470
+ async function run(ctx: ExtensionContext, msgs: Msg[], instruction: string, session?: Session, fromAgent = false) {
471
+ lastCtx = ctx;
472
+ if (wantsCode(instruction)) return codeFlow(ctx, instruction, session);
473
+ const source = session ? sourceOf(session, msgs) : undefined;
474
+ const lastText = [...msgs].reverse().find((m) => m.role === "assistant")?.text;
475
+ if (!lastText) return ctx.ui.notify("No assistant message in that session", "error");
476
+ ctx.ui.notify(wantsTag(instruction) ? "Tagging…" : `${instruction.slice(0, 40)}…`, "info");
477
+ try {
478
+ if (wantsTag(instruction)) {
479
+ if (!(await tagAndAppend(ctx, lastText, source, fromAgent ? undefined : session))) ctx.ui.notify("Nothing worth tagging (too short?)", "info");
480
+ } else if (wantsHighlight(instruction)) {
481
+ let steps: Step[] = [];
482
+ try {
483
+ steps = session && !fromAgent ? readSteps(session) : [];
484
+ } catch {}
485
+ const h = await withBusy(ctx, "highlight", () =>
486
+ highlightText(completer(ctx), lastText, instruction, { memory: mem, sessionId: session?.id ?? "local", steps, vision: hasVision(ctx) }),
487
+ );
488
+ saveMemory(mem);
489
+ let shots: Shot[] = [];
490
+ try {
491
+ shots = annotateShots(itemsFromGroups(h.groups), steps);
492
+ } catch (e: any) {
493
+ log(`annotate failed: ${e?.message ?? e}`);
494
+ }
495
+ if (h.groups.length) {
496
+ lastHl = { instruction, plain: h.plain, groups: h.groups, spans: h.spans, source, shots };
497
+ pi.appendEntry<HighlightCardData>("taki-highlight", lastHl);
498
+ }
499
+ else ctx.ui.notify("Nothing to highlight for that request", "info");
500
+ } else {
501
+ const ans = await withBusy(ctx, instruction.slice(0, 24) || "working", () => runFreeform(completer(ctx), msgs, instruction, { glossary: mem.glossary }));
502
+ if (ans.text) {
503
+ learn(ans.terms);
504
+ pi.appendEntry<TextCardData>("taki-text", { action: instruction, text: ans.text, source });
505
+ }
506
+ else ctx.ui.notify("Empty result", "error");
507
+ }
508
+ } catch (e: any) {
509
+ ctx.ui.notify(`Failed: ${e?.message ?? e}`, "error");
510
+ }
511
+ }
512
+
513
+ /** One request over every session in the group. */
514
+ async function runGroup(ctx: ExtensionContext, instruction: string) {
515
+ lastCtx = ctx;
516
+ const all = group().filter((x) => fs.existsSync(x.path));
517
+ const parts = all.map((x) => ({ s: x, label: `${x.agent} · ${path.basename(x.cwd)}`, msgs: readMessages(x) })).filter((p) => p.msgs.length);
518
+ if (!parts.length) return ctx.ui.notify("No messages in the selected sessions", "error");
519
+ ctx.ui.notify(`${parts.length} sessions: ${instruction.slice(0, 40) || "summarize"}…`, "info");
520
+ try {
521
+ const ans = await withBusy(ctx, `${parts.length} sessions`, () => runMulti(completer(ctx), parts, instruction, { glossary: mem.glossary }));
522
+ if (!ans.text) return ctx.ui.notify("Empty result", "error");
523
+ learn(ans.terms);
524
+ const label = `${parts.length} sessions: ${parts.map((p) => path.basename(p.s.cwd)).join(", ")}`;
525
+ pi.appendEntry<TextCardData>("taki-text", { action: instruction || "summarize", text: ans.text, source: { agent: parts[0]!.s.agent, cwd: parts[0]!.s.cwd, id: "", snippet: "", label } });
526
+ } catch (e: any) {
527
+ ctx.ui.notify(`Failed: ${e?.message ?? e}`, "error");
528
+ }
529
+ }
530
+
531
+ /** Plain text or "/hot all": the whole group when several sessions are set, otherwise the one session. */
532
+ async function ask(ctx: ExtensionContext, instruction: string) {
533
+ if (!sticky) return;
534
+ if (extras.length && !wantsCode(instruction)) return runGroup(ctx, instruction);
535
+ const msgs = readMessages(sticky);
536
+ return run(ctx, msgs, instruction, sticky);
537
+ }
538
+
539
+ const rowsFor = (list: Session[]): Row[] => list.map((x) => ({ s: x, snippet: oneLine(lastAssistant(x)?.text ?? "").slice(0, 80) }));
540
+
541
+ async function addFlow(ctx: ExtensionContext) {
542
+ const have = new Set(group().map((x) => x.path));
543
+ const rows = rowsFor(listSessions({ limit: 20 }).filter((x) => !have.has(x.path)));
544
+ if (!rows.length) return ctx.ui.notify("No other sessions found", "info");
545
+ const picked = await ctx.ui.custom<Picked | undefined>((tui, theme, _kb, done) => new Picker(tui, theme, done, rows, false, "", undefined, true), {
546
+ overlay: true,
547
+ overlayOptions: { width: "90%", maxHeight: "70%", anchor: "center" },
548
+ });
549
+ if (!picked) return;
550
+ for (const x of picked.sessions ?? [picked.session]) {
551
+ if (group().length >= MAX_GROUP) {
552
+ ctx.ui.notify(`At most ${MAX_GROUP} sessions at once`, "info");
553
+ break;
554
+ }
555
+ if (!sticky) sticky = x;
556
+ else extras.push(x);
557
+ }
558
+ persist();
559
+ showSticky(ctx);
560
+ ctx.ui.notify(`Reading ${group().length} session${group().length > 1 ? "s" : ""}. Ask anything, or /hot drop to remove one.`, "info");
561
+ }
562
+
563
+ async function dropFlow(ctx: ExtensionContext) {
564
+ if (!group().length) return ctx.ui.notify("No sessions set", "info");
565
+ const picked = await ctx.ui.custom<Picked | undefined>((tui, theme, _kb, done) => new Picker(tui, theme, done, rowsFor(group()), false, "", undefined, false), {
566
+ overlay: true,
567
+ overlayOptions: { width: "90%", maxHeight: "70%", anchor: "center" },
568
+ });
569
+ if (!picked) return;
570
+ if (sticky?.path === picked.session.path) sticky = extras.shift();
571
+ else extras = extras.filter((x) => x.path !== picked.session.path);
572
+ persist();
573
+ showSticky(ctx);
574
+ }
575
+
576
+ const sourceOf = (s: Session, msgs: Msg[]): Source => {
577
+ const last = [...msgs].reverse().find((m) => m.role === "assistant");
578
+ return { agent: s.agent, cwd: s.cwd, id: s.id, snippet: oneLine(last?.text ?? "").slice(0, 80) };
579
+ };
580
+
581
+ /** Pick (or reuse) a session and an instruction, then run. */
582
+ async function tagFlow(ctx: ExtensionContext, instruction: string, forcePick: boolean) {
583
+ // the remembered session still exists? (it may have been deleted)
584
+ if (sticky && !fs.existsSync(sticky.path)) sticky = undefined;
585
+ const reuse = sticky && !forcePick;
586
+ let session = reuse ? sticky : undefined;
587
+ if (!reuse || !instruction) {
588
+ const rows: Row[] = listSessions({ limit: 15 }).map((s) => ({ s, snippet: oneLine(lastAssistant(s)?.text ?? "").slice(0, 80) }));
589
+ if (!rows.length) return ctx.ui.notify("No sessions found", "error");
590
+ const picked = await ctx.ui.custom<Picked | undefined>(
591
+ (tui, theme, _kb, done) => new Picker(tui, theme, done, rows, !instruction, instruction, reuse ? sticky : undefined),
592
+ { overlay: true, overlayOptions: { width: "90%", maxHeight: "70%", anchor: "center" } },
593
+ );
594
+ if (!picked) return;
595
+ session = picked.session;
596
+ instruction = picked.instruction;
597
+ }
598
+ if (!session) return;
599
+ if (!sticky || sticky.path !== session.path) {
600
+ sticky = session;
601
+ persist();
602
+ showSticky(ctx);
603
+ }
604
+ const msgs = readMessages(session);
605
+ await run(ctx, msgs, instruction, session);
606
+ }
607
+
608
+ pi.registerCommand("hot", {
609
+ description: 'Say what to do with a session\'s recent chat. Remembers the session; "/hot pick" switches, "/hot here" uses this one',
610
+ handler: async (args, ctx) => {
611
+ claim();
612
+ showSticky(ctx);
613
+ let instruction = args.trim();
614
+ // automatic tags on Pi's own answers: "/hot auto" switches them, "/hot auto now" tags the last one
615
+ if (/^auto$/i.test(instruction)) {
616
+ auto = !auto;
617
+ return ctx.ui.notify(`Automatic tags ${auto ? "on" : "off"}`, "info");
618
+ }
619
+ if (/^auto now$/i.test(instruction)) {
620
+ const text = ownLastAssistantText(ctx);
621
+ if (!text) return ctx.ui.notify("No assistant message yet", "error");
622
+ ctx.ui.notify("Tagging…", "info");
623
+ try {
624
+ lastTagged = text;
625
+ if (!(await tagAndAppend(ctx, text))) ctx.ui.notify("Nothing worth tagging (too short?)", "info");
626
+ } catch (e: any) {
627
+ ctx.ui.notify(`Tagging failed: ${e?.message ?? e}`, "error");
628
+ }
629
+ return;
630
+ }
631
+ if (/^skills$/i.test(instruction)) {
632
+ try {
633
+ return ctx.ui.notify(`${installSkills().join(" · ")}. Start a new agent session to use it.`, "info");
634
+ } catch (e: any) {
635
+ return ctx.ui.notify(`Could not install the skill: ${e?.message ?? e}`, "error");
636
+ }
637
+ }
638
+ if (/^here\b/i.test(instruction)) {
639
+ instruction = instruction.replace(/^here\b\s*/i, "");
640
+ return run(ctx, ownMessages(ctx), instruction);
641
+ }
642
+ if (/^(on|off)$/i.test(instruction)) {
643
+ listening = instruction.toLowerCase() === "on";
644
+ persist();
645
+ showSticky(ctx);
646
+ return ctx.ui.notify(listening ? "HoT is listening: plain text asks about the remembered session" : "HoT paused: plain text goes to Pi", "info");
647
+ }
648
+ if (/^add$/i.test(instruction)) return addFlow(ctx);
649
+ if (/^drop$/i.test(instruction)) return dropFlow(ctx);
650
+ if (/^solo$/i.test(instruction)) {
651
+ extras = [];
652
+ persist();
653
+ showSticky(ctx);
654
+ return ctx.ui.notify("Back to one session", "info");
655
+ }
656
+ if (/^all\b/i.test(instruction)) {
657
+ if (!sticky) return ctx.ui.notify("No session yet: /hot add", "error");
658
+ return runGroup(ctx, instruction.replace(/^all\b\s*/i, ""));
659
+ }
660
+ const plainCmd = instruction.match(/^plain\b\s*(.*)$/i);
661
+ if (plainCmd) {
662
+ if (!lastHl) return ctx.ui.notify("Highlight something first, then /hot plain", "error");
663
+ const terms = [...new Set(lastHl.spans.map((sp) => lastHl!.plain.slice(sp.start, sp.end)))];
664
+ const want = plainCmd[1]!.trim();
665
+ const term = terms.find((t) => t.toLowerCase() === want.toLowerCase()) ?? (want ? terms.find((t) => t.toLowerCase().includes(want.toLowerCase())) : undefined) ?? (want ? undefined : await ctx.ui.select("Which phrase, without it?", terms));
666
+ if (!term) return want ? ctx.ui.notify(`"${want}" is not highlighted. Highlighted: ${terms.join(", ")}`, "error") : undefined;
667
+ const sp = lastHl.spans.find((x) => lastHl!.plain.slice(x.start, x.end) === term)!;
668
+ return plainFlow(ctx, lastHl.plain, sp.start, term);
669
+ }
670
+ if (/^terms$/i.test(instruction)) return ctx.ui.notify(mem.glossary.length ? `Already explained: ${mem.glossary.join(", ")}` : "No terms explained yet", "info");
671
+ const know = instruction.match(/^know\s+(.+)/i);
672
+ if (know) {
673
+ addTerms(mem, know[1]!.split(/[,|]/));
674
+ saveMemory(mem);
675
+ return ctx.ui.notify("Marked as known", "info");
676
+ }
677
+ const forget = instruction.match(/^forget\s+(.+)/i);
678
+ if (forget) {
679
+ const n = forgetTerm(mem, forget[1]!);
680
+ saveMemory(mem);
681
+ return ctx.ui.notify(n ? `Forgot ${n} term${n > 1 ? "s" : ""}: it will be explained again` : "That term was not in the list", "info");
682
+ }
683
+ const pick = /^(pick|switch)\b/i.test(instruction);
684
+ if (pick) instruction = instruction.replace(/^(pick|switch)\b\s*/i, "");
685
+ await tagFlow(ctx, instruction, pick);
686
+ },
687
+ });
688
+
689
+ pi.on("input", async (event, ctx) => {
690
+ if (!capturing() || !sticky || !ctx.hasUI || event.source !== "interactive" || event.streamingBehavior) return { action: "continue" as const };
691
+ const text = event.text.trim();
692
+ if (!text || text.startsWith("/")) return { action: "continue" as const };
693
+ if (text.startsWith("!")) return { action: "transform" as const, text: text.replace(/^!\s*/, "") };
694
+ if (!fs.existsSync(sticky.path)) {
695
+ sticky = undefined;
696
+ persist();
697
+ showSticky(ctx);
698
+ return { action: "continue" as const };
699
+ }
700
+ void ask(ctx, text);
701
+ return { action: "handled" as const };
702
+ });
703
+
704
+ // ---------- inbox: requests from other agents (Claude Code skill, Codex...) ----------
705
+
706
+ function drain() {
707
+ draining = draining
708
+ .then(async () => {
709
+ const takenBy = owner();
710
+ if (takenBy && takenBy !== process.pid) return;
711
+ let names: string[] = [];
712
+ try {
713
+ names = fs.readdirSync(INBOX).filter((f) => f.endsWith(".json")).sort();
714
+ } catch {}
715
+ for (const n of names) {
716
+ const fp = path.join(INBOX, n);
717
+ let req: any;
718
+ try {
719
+ req = JSON.parse(fs.readFileSync(fp, "utf8"));
720
+ } catch {}
721
+ try {
722
+ fs.unlinkSync(fp);
723
+ } catch {}
724
+ const ctx = lastCtx;
725
+ if (!req || !ctx) continue;
726
+ const session = req.session as Session | undefined;
727
+ if (!session || !fs.existsSync(session.path)) {
728
+ ctx.ui.notify("HoT: request has no valid session", "error");
729
+ continue;
730
+ }
731
+ engaged = true;
732
+ sticky = session;
733
+ extras = extras.filter((x) => x.path !== session.path);
734
+ persist();
735
+ showSticky(ctx);
736
+ const instruction = String(req.instruction ?? "").trim();
737
+ ctx.ui.notify(`HoT ← ${session.agent}: ${instruction.slice(0, 60) || "tag"}`, "info");
738
+ log(`inbox request from ${session.agent}: ${instruction.slice(0, 80)}`);
739
+ // the agent's latest turn is the one that sent this request: read the chat as it was before it.
740
+ // Tool evidence is skipped, since the latest turn would only show the send command.
741
+ const msgs = beforeRequest(readMessages(session), Number(req.createdAt) || undefined);
742
+ await run(ctx, msgs, instruction, session, true);
743
+ }
744
+ })
745
+ .catch((e) => log(`inbox error: ${e?.message ?? e}`));
746
+ }
747
+
748
+ function startInbox(ctx: ExtensionContext) {
749
+ if (!ctx.hasUI || watcher) return;
750
+ try {
751
+ fs.mkdirSync(INBOX, { recursive: true });
752
+ if (!owner()) fs.writeFileSync(PI_FILE, JSON.stringify({ pid: process.pid, pane: process.env.HERDR_PANE_ID ?? null, startedAt: Date.now() }));
753
+ watcher = fs.watch(INBOX, () => drain());
754
+ drain(); // anything that arrived while Pi was not running
755
+ } catch (e: any) {
756
+ log(`inbox start failed: ${e?.message ?? e}`);
757
+ }
758
+ }
759
+
760
+ function stopInbox() {
761
+ watcher?.close();
762
+ watcher = undefined;
763
+ try {
764
+ if (owner() === process.pid) fs.unlinkSync(PI_FILE);
765
+ } catch {}
766
+ }
767
+
768
+ pi.registerShortcut("alt+t", {
769
+ description: "HoT: say what to do with the remembered session's recent chat",
770
+ handler: async (ctx) => (claim(), tagFlow(ctx, "", false)),
771
+ });
772
+
773
+ /**
774
+ * Rewrite any selected passage without its jargon. When the passage is inside the latest highlight card it is replaced right there
775
+ * (click it to undo); text from anywhere else cannot be edited in place (Pi owns its chat), so the result is added as a card.
776
+ */
777
+ async function rewriteSelection(ctx: ExtensionContext, selected: string) {
778
+ let selection = selected;
779
+ if (plainBusy) return;
780
+ const hl = lastHl;
781
+ // the selection may have line breaks where Pi wrapped the text, so match word by word
782
+ const words = selection.split(/\s+/).filter(Boolean).map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
783
+ const found = hl && words.length ? new RegExp(words.join("\\s+")).exec(hl.plain) : null;
784
+ const at = found ? found.index : -1;
785
+ if (found) selection = found[0];
786
+ const context = hl && at >= 0 ? hl.plain : (ownLastAssistantText(ctx) ?? lastTagged ?? "");
787
+ const ALL = "every jargon or technical term";
788
+ plainBusy = true;
789
+ try {
790
+ if (hl && at >= 0) {
791
+ const end = at + selection.length;
792
+ for (const x of swapsOf(hl.plain)) if (x.start < end && x.end > at) clearSwap(hl.plain, x.start);
793
+ setSwap(hl.plain, { start: at, end, original: selection, text: selection, state: "busy", note: "" });
794
+ try {
795
+ const r = await withBusy(ctx, "plain", () => plainSentence(completer(ctx), context, ALL, selection));
796
+ const kept = { start: at, end, original: selection };
797
+ if (!r.rewrite) setSwap(hl.plain, { ...kept, text: `${selection} ⚠ cannot rewrite it: ${r.note}`, state: "cannot", note: r.note });
798
+ else if (r.same) setSwap(hl.plain, { ...kept, text: r.rewrite, state: "same", note: r.note });
799
+ else setSwap(hl.plain, { ...kept, text: `${r.rewrite} ⚠ meaning may differ: ${r.note}`, state: "differs", note: r.note });
800
+ } catch (e: any) {
801
+ clearSwap(hl.plain, at);
802
+ throw e;
803
+ }
804
+ return;
805
+ }
806
+ const r = await withBusy(ctx, "plain", () => plainSentence(completer(ctx), context, ALL, selection));
807
+ const verdict = !r.rewrite ? `⚠ cannot rewrite it: ${r.note}` : r.same ? "✓ same meaning" : `⚠ meaning may differ: ${r.note}`;
808
+ pi.appendEntry<TextCardData>("taki-text", { action: "plain: selected text", text: [`> ${selection}`, "", r.rewrite || "_(no plain version)_", "", verdict].join("\n") });
809
+ } catch (e: any) {
810
+ ctx.ui.notify(`plain failed: ${String(e?.message ?? e)}`, "error");
811
+ } finally {
812
+ plainBusy = false;
813
+ }
814
+ }
815
+
816
+ // Select any text with the mouse (Pi copies it to the clipboard on release), then press alt+a to ask about it.
817
+ // Extensions do not see mouse events (Pi handles them first), so there is no automatic hint after selecting.
818
+ pi.registerShortcut("alt+a", {
819
+ description: "HoT: rewrite the text you just selected (or copied) without its jargon. On a Mac: Option+A",
820
+ handler: async (ctx) => {
821
+ const selection = readClipboard();
822
+ if (!selection) return ctx.ui.notify("Select some text with the mouse first", "info");
823
+ await rewriteSelection(ctx, selection);
824
+ },
825
+ });
826
+ // On a Mac, Option+A types "å" instead of sending Alt, unless the terminal is set to "Option as Meta". Treat that "å" as the shortcut,
827
+ // but only when the input box is empty, so typing an å inside a sentence still works.
828
+ let unwatchKeys: (() => void) | undefined;
829
+ pi.on("session_start", async (_e, ctx) => {
830
+ unwatchKeys?.();
831
+ if (process.platform !== "darwin") return;
832
+ unwatchKeys = ctx.ui.onTerminalInput((data) => {
833
+ if (data !== "å" || ctx.ui.getEditorText().trim()) return undefined;
834
+ const selection = readClipboard();
835
+ if (!selection) return undefined;
836
+ void rewriteSelection(ctx, selection);
837
+ return { consume: true };
838
+ });
839
+ });
840
+ pi.on("session_shutdown", async () => unwatchKeys?.());
841
+ }