pi-repl-py 0.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-repl-py",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
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": [
@@ -116,6 +116,8 @@ export class EngineManager {
116
116
  private startPromise?: Promise<void>;
117
117
  private executionQueue: Promise<unknown> = Promise.resolve();
118
118
  private snapshotTimer?: ReturnType<typeof setTimeout>;
119
+ /** Last-seen top-level namespace names; snapshots are gated on this set changing. */
120
+ private lastNamespaceNames?: string[];
119
121
  private pythonPath?: string;
120
122
 
121
123
  constructor(options: EngineOptions = {}) {
@@ -242,7 +244,7 @@ export class EngineManager {
242
244
  onStream: opts.onStream,
243
245
  maxOutputChars: maxChars,
244
246
  });
245
- if (r.status === "ok") this.scheduleSnapshot();
247
+ if (r.status === "ok") void this.scheduleSnapshotIfChanged();
246
248
  const status: ExecuteResult["status"] = opts.signal?.aborted ? "aborted" : r.status;
247
249
  // Channel cap (truncateWithMarker), then per-line cap; both append a marker so truncation is explicit.
248
250
  const finalize = (text: string, channelTruncated: boolean): string => {
@@ -313,6 +315,20 @@ export class EngineManager {
313
315
  }
314
316
  }
315
317
 
318
+ /** Snapshot only if the set of top-level names changed since the last snapshot. Names-only
319
+ * comparison is cheap (no pickling); a cell that reuses existing state skips the heavy dump. */
320
+ private async scheduleSnapshotIfChanged(): Promise<void> {
321
+ const config = this.options.snapshot;
322
+ if (!config) return;
323
+ const names = await this.listNamespaceNames();
324
+ if (names === null || names.length === 0) return;
325
+ const key = [...names].sort().join(",");
326
+ const prev = this.lastNamespaceNames ? [...this.lastNamespaceNames].sort().join(",") : undefined;
327
+ if (prev !== undefined && prev === key) return; // nothing changed
328
+ this.lastNamespaceNames = [...names].sort();
329
+ this.scheduleSnapshot();
330
+ }
331
+
316
332
  private scheduleSnapshot(): void {
317
333
  const config = this.options.snapshot;
318
334
  if (!config) return;
@@ -6,13 +6,9 @@
6
6
  // more signal; the machine reads every line every turn.
7
7
 
8
8
  export const executeToolDescription =
9
- "Execute Python cells in a persistent ipython kernel that stays alive across cells and turns, replacing " +
10
- "the default read, bash, edit, write, and search tools. Everything you define (variables, imports, and " +
11
- "helpers preloaded into the workspace namespace) survives for reuse in later cells. A cell returns its " +
12
- "final expression — bare final expressions are auto-printed, and output is trimmed at 1,000,000 " +
13
- "characters per cell / 4,096 per line. Treat these as facts about how the workspace reports, not as " +
14
- "limits to test: assign the values you want to keep so they stay in scope for later cells, and let a " +
15
- "cell's return value be the proof of its work rather than re-stating that work in prose.";
9
+ "Execute Python cells in a persistent ipython kernel; state survives across cells and turns, replacing " +
10
+ "the default read, bash, edit, write, and search tools. Let a cell's returned value prove the work, " +
11
+ "not prose restating it.";
16
12
 
17
13
  export const executePromptSnippet =
18
14
  "Execute Python cells in a persistent ipython kernel (replaces read, bash, edit, write, and search; state survives across cells and turns)";
@@ -21,39 +17,36 @@ export const executePromptSnippet =
21
17
  export function buildPromptGuidelines(preloaded: string[]): string[] {
22
18
  return [
23
19
  "## Your only workspace",
24
- "`execute` is your workspace: a persistent Python session that is the only callable surface. What you define variables, functions, data survives across cells and turns, and the work is proven by the results each cell returns.",
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.",
25
21
  "",
26
- "## Go deep in the cell; prove it by the result",
27
- "Depth, the cell, not the transcript. Do the heavy reasoning in variables and filters; a cell's worth is shown by what it returns as a result, not by restating that result in prose. Every printed value enters the context — and equating length with value is the trap — so let the code's result, not a recap paragraph, be the evidence.",
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.",
28
24
  "",
29
- "## The gather-filter-advance shape",
30
- "Leave raw data in the workspace. Search results, reads, command output, file contentswhatever you fetch land in variables, never in the transcript.",
25
+ "## 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.",
31
27
  "",
32
- "1. **Gather.** One cell assigns the whole: result = search(q), doc = load(path), out = run(...) — nothing printed, ends on the assignment.",
33
- "2. **Advance.** The next cell prints only the fragment that decides the next step titles only, a slice of content and you pick from that sliver.",
34
- "3. **Peel, don't re-fetch.** You already hold the whole; walk into the pieces you need without re-running it.",
35
- "4. **Emit, then drop.** When the reasoning lands, print the conclusion; the rest stays in the variable, or is overwritten when done.",
28
+ "## 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'.",
36
30
  "",
37
- "Each printed value is the one that changes the next cell; the transcript stays thin, the work dense in variables.",
31
+ "## 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.",
38
33
  "",
39
- "Windows, not bans: reading something whole is fine when the task genuinely needs all of it — do that, then keep reasoning on it. The point is not to never read fully; it is to read by window by default and hold the whole, so you never re-fetch the same big thing twice.",
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.",
40
35
  "",
41
- "## A cell is a small program",
42
- "Compose whatever the step needs filesystem, shell, search, transforms in one cell, and end it on the return value the next step consumes. The cell itself (what ran) carries the meaning; the transcript carries only that returned value.",
36
+ "## 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.",
43
38
  "",
44
- "Name what recurs: when the same operation shows up twice, give it a name once — a function in the namespace — and call it. A defined function is work already proven; every call is a new return-value result, and you never re-print the steps that made it.",
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.",
45
41
  "",
46
- "## Revise on observations",
47
- "Revise prior actions or emit new actions upon new observations.", // CodeAct core
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.",
48
44
  "",
49
- "## Probe, then build",
50
- "Inspect where you are a small slicebefore committing; then build one step and let its returned result name the next. The proof of each step is the cell's result, not a summary of it.",
45
+ "## 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.",
51
47
  "",
52
- "## File and search work",
53
- "Prefer a surgical old-text/new-text replacement over rewriting a file: read the region first, fix an exact unique anchor that appears once, replace exactly, then verify. Prefer many small verified edits over one big blind rewrite — a parse error mid-way can strand an anchor. Use complete writes only for new files or intentional full rewrites. After an edit errors or writes a partial result, read the file back from disk before reasoning about it. When walking directories, prune generated dirs and never print a raw tree.",
54
- "",
55
- "## Repository discipline",
56
- "Make the smallest valid change, preserve conventions, verify afterward, and never invent files, APIs, conventions, or test results.",
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.",
57
50
  "",
58
51
  ...(preloaded.length
59
52
  ? [
@@ -64,13 +57,10 @@ export function buildPromptGuidelines(preloaded: string[]): string[] {
64
57
  "",
65
58
  ]
66
59
  : []),
67
- "## Shell and search",
68
- "Always pass a `timeout` to `subprocess.run(...)` — a silent cell must die, not hang. Capture the result in a variable and read a slice, not dump the whole stdout into the transcript: use `rg`/`grep`/`find` for deep searches, not Python loops.",
69
- "",
70
60
  "## Environment & rescue",
71
- "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 was rebuilt — re-verify any revived variable before reusing it.",
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.",
72
62
  "",
73
- "## The operating principle above the manual",
74
- "The rules above are working forms of one principle: the work happens in the workspace — in cells and their results — and the transcript carries only what decides or concludes. When a case isn't spelled out, apply the principle over the example: wherever the work can live in the workspace instead of the transcript, keep it there, and let the returned result be the proof. The result is the certificate; the rest of the work stays out of the reply.",
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.",
75
65
  ];
76
66
  }