pi-repl-py 0.6.0 → 0.6.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-repl-py",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "type": "module",
5
5
  "description": "A pi extension with a single tool: execute, running a TypeScript host with a persistent Python (ipykernel) evaluator and a user-configurable toolbox of functions.",
6
6
  "keywords": [
@@ -162,6 +162,15 @@ export class EngineManager {
162
162
  env: this.options.env,
163
163
  timeoutMs,
164
164
  });
165
+ // --- an unexpected kernel death must not survive the next execute: drop the dying
166
+ // --- instance and clear the boot cache so start() rebuilds it on the next cell. ---
167
+ const current = this.kernel;
168
+ current.setOnUnexpectedExit(() => {
169
+ if (this.kernel !== current) return;
170
+ this.kernel = undefined;
171
+ this.startPromise = undefined;
172
+ this.lastNamespaceNames = undefined;
173
+ });
165
174
  } catch (error) {
166
175
  if (this.state === "starting") this.state = "idle";
167
176
  liveEngines.delete(this);
@@ -215,6 +224,13 @@ export class EngineManager {
215
224
  throw new Error("Engine has been shut down");
216
225
  }
217
226
  await this.start();
227
+ // --- the kernel may have died after the boot promise resolved but before the async
228
+ // --- exit event surfaced it; drop the zombie and rebuild so the next cell runs. ---
229
+ if (this.kernel && !this.kernel.isRunning) {
230
+ this.kernel = undefined;
231
+ this.startPromise = undefined;
232
+ await this.start();
233
+ }
218
234
  if (this.isShutdown()) {
219
235
  throw new Error("Engine has been shut down");
220
236
  }
@@ -19,6 +19,7 @@ import {
19
19
  import { ZmtpSocket } from "./zmtp.js";
20
20
 
21
21
  const KERNEL_READY_TIMEOUT_MS = 30_000;
22
+ const SILENCE_KILL_GRACE_MS = 2000;
22
23
  const DEFAULT_MAX_OUTPUT_CHARS = 1_000_000;
23
24
 
24
25
  export interface KernelOptions {
@@ -169,8 +170,13 @@ export class KernelClient {
169
170
  private ready = false;
170
171
  /** Serializes all kernel ops: one execute at a time, snapshots between cells. */
171
172
  private queue: Promise<unknown> = Promise.resolve();
172
- private onUnexpectedExit?: () => void;
173
+ private _onUnexpectedExit?: () => void;
174
+ /** Engine hook: an unexpected kernel death (not a deliberate kill) should drop the instance. */
175
+ setOnUnexpectedExit(fn: () => void): void {
176
+ this._onUnexpectedExit = fn;
177
+ }
173
178
  private watchdog?: ReturnType<typeof setInterval>;
179
+ private silenceKillTimer?: ReturnType<typeof setTimeout>;
174
180
  private pendingReplies = new Map<
175
181
  string,
176
182
  { resolve(m: ParsedMessage): void; timer?: ReturnType<typeof setTimeout> }
@@ -223,9 +229,18 @@ export class KernelClient {
223
229
  kc.child = child;
224
230
  kc.connectionFilePath = connPath;
225
231
  child.on("exit", () => {
226
- // --- a dead kernel settles the running cell; the engine rebuilds ---
232
+ // --- a dead kernel settles the running cell; the engine rebuilds. clear child/ready
233
+ // --- so isRunning reflects death and the engine never resumes a zombie process. ---
227
234
  kc.settleActive(new Error("kernel process exited"));
228
- kc.onUnexpectedExit?.();
235
+ kc.child = undefined;
236
+ kc.ready = false;
237
+ kc.shell?.close();
238
+ kc.control?.close();
239
+ kc.iopub?.close();
240
+ kc.shell = undefined;
241
+ kc.control = undefined;
242
+ kc.iopub = undefined;
243
+ kc._onUnexpectedExit?.();
229
244
  });
230
245
 
231
246
  try {
@@ -494,6 +509,12 @@ export class KernelClient {
494
509
  if (quiet >= this.timeoutMs && !active.settled) {
495
510
  active.timedOut = true;
496
511
  this.interrupt();
512
+ // --- the interrupt is a real KeyboardInterrupt, but a cell that swallows/ignores
513
+ // --- it never replies; escalate to a kill so the queue is freed, mirroring index.ts. ---
514
+ this.silenceKillTimer ??= setTimeout(() => {
515
+ if (!active.settled) this.kill();
516
+ }, SILENCE_KILL_GRACE_MS);
517
+ this.silenceKillTimer.unref?.();
497
518
  }
498
519
  },
499
520
  Math.min(250, this.timeoutMs),
@@ -506,6 +527,10 @@ export class KernelClient {
506
527
  clearInterval(this.watchdog);
507
528
  this.watchdog = undefined;
508
529
  }
530
+ if (this.silenceKillTimer) {
531
+ clearTimeout(this.silenceKillTimer);
532
+ this.silenceKillTimer = undefined;
533
+ }
509
534
  }
510
535
 
511
536
  /** Genuine KeyboardInterrupt via control-channel interrupt_request; the kernel survives. */
@@ -41,6 +41,6 @@ export function buildHelpersMap(dir?: string): string[] {
41
41
  return loadHelperEntries(dir).map((t) =>
42
42
  t.description
43
43
  ? `- ${t.description.replace(/\n/g, "\n ")}`
44
- : `- ${t.name} (no description inspect it with print(${t.name}.__doc__))`,
44
+ : `- ${t.name} (no description, inspect it with print(${t.name}.__doc__))`,
45
45
  );
46
46
  }
@@ -1,9 +1,4 @@
1
- // --- prompt: the execute tool's model-facing contract (pure, no pi/helper dep) ---
2
- //
3
- // Verbatim clauses from CodeAct (arXiv 2402.01030) and RLM (arXiv 2512.24601)
4
- // are trimmed to what pi-repl actually has — no sub-LLMs, no recursion, no
5
- // context variable — and the rest is stripped for lean context. Less prose,
6
- // more signal; the machine reads every line every turn.
1
+ // --- execute tool: the model-facing contract + workspace doctrine (pure, no pi/helper dep) ---
7
2
 
8
3
  export const executeToolDescription =
9
4
  "Execute Python cells in a persistent ipython kernel; state survives across cells and turns, replacing " +
@@ -17,36 +12,27 @@ export const executePromptSnippet =
17
12
  export function buildPromptGuidelines(preloaded: string[]): string[] {
18
13
  return [
19
14
  "## Your only workspace",
20
- "You are an engineer in a persistent Python REPL. `execute` is the only callable surface it replaces read, bash, edit, write, and search. What you define (variables, functions, imports) survives across cells and turns. The work is proven by the result each cell returns, and by nothing else.",
21
- "",
22
- "## Get up to speed first",
23
- "Orient before you act: `%pwd`, glance at the namespace, read any state or progress file, skim recent history. A few tokens, it buys a right first move. Work from what you confirmed, not assumptions.",
15
+ "You are an engineer in a persistent Python REPL. `execute` is the only callable surface, it replaces read, bash, edit, write, and search. What you define (variables, functions, imports) survives across cells and turns, so define any function once and call it in later cells. The work is proven by the result each cell returns, and by nothing else.",
24
16
  "",
25
17
  "## Reason, then say, then stop",
26
- "Reason as much as the task needs, but reason inside the cell and keep the reasoning out of the transcript: do it in variables and filters, then return only the outcome. Every printed value is expensive — it enters the context now and stays, costing later tokens every time — so print only what the next decision consumes. A bare final expression auto-prints, so assign instead. Concise reasoning still works length you cut is reward you don't lose, because the evidence is the returned result, not the words around it.",
18
+ "Reason inside the cell, not the transcript: do the thinking in variables and filters, return only the outcome. End on an assignment, a bare expression auto-prints. Keep the reasoning you need, drop the rest, the returned result is the evidence of the work, not the words around it.",
27
19
  "",
28
20
  "## The environment answers you",
29
- "The cell's output is the ground truth what actually ran, what errored, what came back. Trust it over any narrative: if a cell already proved it, point at that. When you're unsure what a fetch contains, read a slice, don't guess and don't dump it whole to 'check'.",
21
+ "The cell's output is the ground truth, what actually ran, what errored, what came back. Trust it over any narrative: if a cell already proved it, point at that. When you're unsure what a fetch contains, read a slice, don't guess and don't dump it whole to 'check'.",
30
22
  "",
31
23
  "## Gather, slice, decide",
32
- "Fetch into a variable, never into the transcript. Search results, reads, command output, file contents assign. A bare expression prints, so end those cells on the assignment. Then advance on a bounded slice: print only the fragment that decides the next step, hold the rest in the variable, peel into the pieces you need without re-fetching, and when the reasoning lands, print the conclusion.",
24
+ "Fetch into a variable, never into the transcript. Search results, reads, command output, file contents, assign. A bare expression prints, so end those cells on the assignment. Then advance on a bounded slice: print only the fragment that decides the next step, hold the rest in the variable, peel into the pieces you need without re-fetching, and when the reasoning lands, print the conclusion.",
33
25
  "",
34
- "Reading whole is fine when the task needs all of it hold it and reason on it; the point isn't to never read fully, it's to not re-fetch the same big thing twice.",
26
+ "Reading whole is fine when the task needs all of it, hold it and reason on it; the point isn't to never read fully, it's to not re-fetch the same big thing twice.",
35
27
  "",
36
28
  "## Output format",
37
- "In reply text: the conclusion and the handful of results that prove it the slice you acted on, the returned value, a one-line takeaway. Do not transcribe the run, restate every variable, or narrate what the cell already showed.",
38
- "",
39
- "## Worked example",
40
- "Gather and slice — two cells, thin transcript:\n cell 1: doc = open('notes.txt').read()\n cell 2: print(doc.splitlines()[:5])\nThe whole file lands in doc (nothing printed); the second cell prints only the first five lines, the rest stays in doc for later.",
41
- "",
42
- "## Compose and reuse",
43
- "Compose filesystem, shell, search, transforms, checks, edits in ordinary Python in one cell, and end on the value the next step consumes. A step seen twice becomes a function you call once — proven work, reused. Revise on new observations; probe a few lines before building, then let the result name the next.",
29
+ "In reply text: the conclusion and the handful of results that prove it, the slice you acted on, the returned value, a one-line takeaway. Do not transcribe the run, restate every variable, or narrate what the cell already showed.",
44
30
  "",
45
31
  "## Edits and repo discipline",
46
- "Surgical old-text/new-text: read the region, fix an exact unique anchor that appears once, replace, verify. Many small edits over one big rewrite a parse error can strand an anchor; after an error, read the file back from disk first. Make the smallest valid change, preserve conventions, never invent files, APIs, conventions, or test results. Prune generated dirs when walking trees.",
32
+ "Surgical old-text/new-text: read the region, fix an exact unique anchor that appears once, replace, verify. Many small edits over one big rewrite, a parse error can strand an anchor; after an error, read the file back from disk first. Make the smallest valid change, preserve conventions, never invent files, APIs, conventions, or test results. Prune generated dirs when walking trees. Pass a `timeout` to any `subprocess.run(...)`, a silent cell must die, not hang.",
47
33
  "",
48
- "## Shell & search",
49
- "Always pass a `timeout` to `subprocess.run(...)` a silent cell must die, not hang. Capture output in a variable and read a slice, not the whole stdout. Use `rg`/`grep`/`find` for deep searches, not Python loops.",
34
+ "## Print is expensive",
35
+ "Print small, exact slices, bounded to what the decision actually needs. Keep the whole in a variable and print only on demand. Never dump a whole list, stream, or file, bloat floods context past usefulness. Prefer quality over quantity.",
50
36
  "",
51
37
  ...(preloaded.length
52
38
  ? [
@@ -58,9 +44,9 @@ export function buildPromptGuidelines(preloaded: string[]): string[] {
58
44
  ]
59
45
  : []),
60
46
  "## Environment & rescue",
61
- "The evaluator runs in a project-local venv, not the system Python. Do not install a project's dependencies into the evaluator; run external projects through their own interface. If output begins with `<repl_engine_reset>`, the kernel rebuilt re-verify a revived variable before reusing it.",
47
+ "The evaluator runs in a project-local venv, not the system Python. Do not install a project's dependencies into the evaluator; run external projects through their own interface. If output begins with `<repl_engine_reset>`, the kernel rebuilt, re-verify a revived variable before reusing it.",
62
48
  "",
63
- "## When a rule doesn't cover it",
64
- "If something isn't spelled out, keep working rather than asking: hold it in the workspace, prove it with a returned result, and keep the transcript to what you act on. Make the sensible default and correct it from the result.",
49
+ "## These rules are the surface",
50
+ "The rules above are the surface of how this workspace works, not the whole of it. Internalize their intent, apply it to cases they don't mention, and follow them diligently.",
65
51
  ];
66
52
  }
@@ -39,7 +39,7 @@ export interface RenderDeps {
39
39
  }
40
40
 
41
41
  const OUTPUT_INDENT = " ";
42
- const SPINNER_FRAMES = ["", "", "", ""];
42
+ const SPINNER_FRAMES = [">..", ".>.", "..>", ".>."];
43
43
 
44
44
  export function formatDuration(durationMs: number | undefined): string | undefined {
45
45
  if (durationMs === undefined) return undefined;
@@ -105,13 +105,68 @@ function marker(state: ExecuteRenderState, deps: RenderDeps): string {
105
105
  return deps.fg("success", "✓");
106
106
  case "running": {
107
107
  const now = deps.now?.() ?? Date.now();
108
- return deps.fg("accent", SPINNER_FRAMES[Math.floor(now / 160) % SPINNER_FRAMES.length]);
108
+ return deps.fg("accent", SPINNER_FRAMES[Math.floor(now / 120) % SPINNER_FRAMES.length]);
109
109
  }
110
110
  default:
111
111
  return deps.fg("muted", "◇");
112
112
  }
113
113
  }
114
114
 
115
+ /**
116
+ * highlight.js python emits no scope for plain identifiers, so they arrive as raw (uncolored)
117
+ * text mixed with SGR-colored tokens and bare punctuation. Re-color only whole identifier runs
118
+ * that sit outside any colored span, leaving keywords, strings, numbers, and other already
119
+ * colored tokens untouched.
120
+ */
121
+ function colorBareIdentifiers(line: string, paint: (id: string) => string): string {
122
+ if (!line.includes("\x1b") && !/[a-zA-Z_]/.test(line)) return line;
123
+ const out: string[] = [];
124
+ let pending = "";
125
+ let colored = false;
126
+ const pushRaw = (s: string) => {
127
+ let last = 0;
128
+ for (const m of s.matchAll(/[a-zA-Z_][a-zA-Z0-9_]*/g)) {
129
+ const index = m.index ?? 0;
130
+ out.push(s.slice(last, index), paint(m[0]));
131
+ last = index + m[0].length;
132
+ }
133
+ out.push(s.slice(last));
134
+ };
135
+ let i = 0;
136
+ const isFgColor = (seq: string) => /\x1b\[(?:38|9?[0-7])/.test(seq);
137
+ while (i < line.length) {
138
+ if (line[i] === "\x1b") {
139
+ const end = line.indexOf("m", i) + 1;
140
+ const seq = line.slice(i, end);
141
+ if (isFgColor(seq)) {
142
+ if (pending) {
143
+ pushRaw(pending);
144
+ pending = "";
145
+ }
146
+ out.push(seq);
147
+ colored = true;
148
+ } else if (seq.includes("39") || seq.includes("0m")) {
149
+ if (colored) {
150
+ out.push(seq);
151
+ colored = false;
152
+ } else {
153
+ pending += seq;
154
+ }
155
+ } else {
156
+ pending += seq;
157
+ }
158
+ i = end;
159
+ continue;
160
+ }
161
+ // only raw (uncolored) text may be repainted; colored tokens pass through untouched
162
+ if (colored) out.push(line[i]);
163
+ else pending += line[i];
164
+ i++;
165
+ }
166
+ if (pending) pushRaw(pending);
167
+ return out.join("");
168
+ }
169
+
115
170
  function highlightLines(code: string, deps: RenderDeps): string[] {
116
171
  if (!code) return [];
117
172
  return deps.highlight(code);
@@ -211,14 +266,15 @@ function addWrapped(
211
266
  text: string,
212
267
  width: number,
213
268
  deps: RenderDeps,
214
- options: { sanitize?: boolean } = {},
269
+ options: { sanitize?: boolean; indentAfter?: number } = {},
215
270
  ): void {
216
271
  const safe = options.sanitize === false ? text : sanitizeTuiOutput(text);
217
272
  const available = Math.max(1, width - 1 - deps.visibleWidth(prefix));
218
273
  const wrapped = deps.wrapTextWithAnsi(safe, available);
219
274
  for (const [index, line] of (wrapped.length > 0 ? wrapped : [""]).entries()) {
220
275
  const linePrefix = index === 0 ? prefix : " ".repeat(deps.visibleWidth(prefix));
221
- lines.push(deps.truncateToWidth(` ${linePrefix}${closeOpenSgr(line)}`, width, ""));
276
+ const continuationIndent = index > 0 && options.indentAfter ? " ".repeat(options.indentAfter) : "";
277
+ lines.push(deps.truncateToWidth(` ${linePrefix}${continuationIndent}${closeOpenSgr(line)}`, width, ""));
222
278
  }
223
279
  }
224
280
 
@@ -229,8 +285,13 @@ function renderCode(state: ExecuteRenderState, lines: string[], width: number, d
229
285
  const highlighted = highlightLines(code, deps);
230
286
  for (const [index, rawLine] of code.split("\n").entries()) {
231
287
  const prefix = index === 0 ? deps.fg("dim", "› ") : deps.fg("dim", " ");
232
- // --- code is already highlighted; don't strip its ANSI ---
233
- addWrapped(lines, prefix, highlighted[index] ?? rawLine, width, deps, { sanitize: false });
288
+ const paint = (id: string) => deps.fg("syntaxVariable", id);
289
+ const hlLine = colorBareIdentifiers(highlighted[index] ?? rawLine, paint);
290
+ const indent = /^[ \t]*/.exec(rawLine)?.[0] ?? "";
291
+ addWrapped(lines, prefix, hlLine, width, deps, {
292
+ sanitize: false,
293
+ indentAfter: deps.visibleWidth(indent),
294
+ });
234
295
  }
235
296
  return true;
236
297
  }
@@ -43,7 +43,7 @@ function renderVersion(state: ExecuteRenderState): string {
43
43
  state.executionStarted,
44
44
  state.hasResult,
45
45
  // --- fold the animation frame in while running so the spinner still turns ---
46
- statusKind(state) === "running" ? Math.floor(Date.now() / 160) % 4 : -1,
46
+ statusKind(state) === "running" ? Math.floor(Date.now() / 120) % 4 : -1,
47
47
  ].join("|");
48
48
  }
49
49