pi-legible 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jordan Coeyman
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ # pi-legible
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Your coding agent shows you what it is about to run. You should be able to read it.
4
+
5
+ <a href="https://raw.githubusercontent.com/acoyfellow/pi-legible/main/docs/demo.mp4"><img src="https://raw.githubusercontent.com/acoyfellow/pi-legible/main/docs/demo.gif" alt="Two pi sessions running the same task side by side, without and with pi-legible"></a>
6
+
7
+ <table>
8
+ <tr><th>Without</th><th>With</th></tr>
9
+ <tr>
10
+ <td valign="top"><img src="https://raw.githubusercontent.com/acoyfellow/pi-legible/main/docs/without.png" alt="Without pi-legible: one long shell line, cramped Python and SQL"></td>
11
+ <td valign="top"><img src="https://raw.githubusercontent.com/acoyfellow/pi-legible/main/docs/with.png" alt="With pi-legible: one shell step per line, formatted Python and SQL"></td>
12
+ </tr>
13
+ </table>
14
+
15
+ This [pi](https://pi.dev) extension makes the code in your transcript legible:
16
+
17
+ 1. **Shell calls** show one step per line.
18
+ 2. **Code blocks** in replies are run through a real formatter.
19
+ 3. **`codemode` scripts** are formatted as JavaScript.
20
+ 4. **The model is asked** to write legible code in the first place.
21
+
22
+ Only the display changes. What runs is exactly what the model wrote.
23
+
24
+ ## Install
25
+
26
+ ```sh
27
+ pi install git:github.com/acoyfellow/pi-legible
28
+ ```
29
+
30
+ Then `/reload` or start a new session.
31
+
32
+ ## Languages
33
+
34
+ | Fence tag | Formatter |
35
+ |---|---|
36
+ | `sh`, `bash`, `zsh`, `shell` | built-in splitter: top-level `;` `&&` `\|\|` `\|` |
37
+ | `ts`, `js`, `tsx`, `jsx` | [Biome](https://biomejs.dev) |
38
+ | `py`, `python` | [Ruff](https://docs.astral.sh/ruff/) |
39
+ | `go` | gofmt |
40
+ | `sql` | sqlformat |
41
+ | `yaml`, `yml` | yamlfmt |
42
+ | `json` | `JSON.stringify` |
43
+
44
+ The formatters are WebAssembly builds from [wasm-fmt](https://github.com/wasm-fmt), about 4 MB in total. No binaries, no network.
45
+
46
+ ## Safety
47
+
48
+ - If a formatter fails, or its output does not keep the same tokens, the code is shown exactly as written.
49
+ - Inputs over 20 KB are not formatted.
50
+ - Streaming messages are formatted only when they finish.
51
+ - The shell splitter never splits inside quotes, `$( )`, `( )`, `{ }` or heredoc bodies.
52
+
53
+ ## The writing rule
54
+
55
+ It appends a short rule to the system prompt: one shell step per line, a script file for more than three steps or any loop, no long inline Python or jq, name long paths once, tag code blocks with their language.
56
+
57
+ ## What it does not do
58
+
59
+ - It does not change what runs.
60
+ - It does not format untagged code blocks or languages not in the table.
61
+ - It does not format inline `code` spans.
62
+
63
+ ## Related
64
+
65
+ [pi-code-previews](https://github.com/mattleong/pi-code-previews) adds syntax highlighting to all built-in tools but keeps commands on one line. Both register tool renderers; the one loaded later draws `bash` calls.
66
+
67
+ ## Develop
68
+
69
+ ```sh
70
+ npm install
71
+ bun test
72
+ ```
73
+
74
+ ## Screenshots
75
+
76
+ The README images are real pi sessions in [cmux](https://cmux.com), rebuilt with:
77
+
78
+ ```sh
79
+ sh demo/shoot.sh before <window> <workspace>
80
+ sh demo/shoot.sh after <window> <workspace>
81
+ ```
82
+
83
+ MIT
@@ -0,0 +1,95 @@
1
+ import * as biome from "@wasm-fmt/biome_fmt";
2
+ import * as go from "@wasm-fmt/gofmt";
3
+ import * as ruff from "@wasm-fmt/ruff_fmt";
4
+ import * as sql from "@wasm-fmt/sql_fmt";
5
+ import * as yaml from "@wasm-fmt/yamlfmt";
6
+ import { formatCommand } from "./shell";
7
+
8
+ export type Language = "shell" | "typescript" | "javascript" | "tsx" | "jsx" | "json" | "python" | "go" | "sql" | "yaml";
9
+
10
+ type Formatter = (code: string, width: number) => string;
11
+
12
+ const DEFAULT_WIDTH = 100;
13
+ const MIN_WIDTH = 20;
14
+
15
+ function spaces(width: number) {
16
+ return { indentStyle: "space", indentWidth: 2, lineWidth: width } as const;
17
+ }
18
+ const MAX_INPUT = 20_000;
19
+
20
+ const ALIASES: Record<string, Language> = {
21
+ sh: "shell", bash: "shell", zsh: "shell", shell: "shell", console: "shell",
22
+ ts: "typescript", typescript: "typescript", mts: "typescript", cts: "typescript",
23
+ js: "javascript", javascript: "javascript", mjs: "javascript", cjs: "javascript",
24
+ tsx: "tsx", jsx: "jsx",
25
+ json: "json", jsonc: "json",
26
+ py: "python", python: "python",
27
+ go: "go", golang: "go",
28
+ sql: "sql",
29
+ yml: "yaml", yaml: "yaml",
30
+ };
31
+
32
+ const EXTENSIONS: Record<string, string> = { typescript: "a.ts", javascript: "a.js", tsx: "a.tsx", jsx: "a.jsx", json: "a.json" };
33
+
34
+ function biomeFormat(language: Language): Formatter {
35
+ return (code, width) => biome.format(code, EXTENSIONS[language], spaces(width));
36
+ }
37
+
38
+ function scriptBody(language: Language): Formatter {
39
+ const wrapperName = "__legible_body__";
40
+ return (code, width) => {
41
+ const wrapped = `async function ${wrapperName}() {\n${code}\n}\n`;
42
+ const formatted = biome.format(wrapped, EXTENSIONS[language], spaces(width + 2)).trimEnd().split("\n");
43
+ if (formatted[0] !== `async function ${wrapperName}() {` || formatted.at(-1) !== "}") throw new Error("unwrapped");
44
+ return formatted.slice(1, -1).map((line) => line.replace(/^ {2}/, "")).join("\n");
45
+ };
46
+ }
47
+
48
+ const FORMATTERS: Record<Language, Formatter> = {
49
+ shell: formatCommand,
50
+ typescript: biomeFormat("typescript"),
51
+ javascript: biomeFormat("javascript"),
52
+ tsx: biomeFormat("tsx"),
53
+ jsx: biomeFormat("jsx"),
54
+ json: (code) => JSON.stringify(JSON.parse(code), null, 2),
55
+ python: (code, width) => ruff.format(code, null, { indent_width: 4, line_width: width }),
56
+ go: (code) => go.format(code),
57
+ sql: (code) => sql.format(code, {}),
58
+ yaml: (code) => yaml.format(code, {}),
59
+ };
60
+
61
+ export function languageOf(tag: string | undefined): Language | null {
62
+ if (!tag) return null;
63
+ return ALIASES[tag.trim().toLowerCase().split(/[\s{]/)[0]] ?? null;
64
+ }
65
+
66
+ function clampWidth(width: number): number {
67
+ return Math.max(MIN_WIDTH, Math.min(DEFAULT_WIDTH, Math.floor(width)));
68
+ }
69
+
70
+ function sameTokens(before: string, after: string): boolean {
71
+ const squash = (text: string) => text.replace(/[\s;,()]/g, "").replace(/["'`]/g, "'");
72
+ return squash(before) === squash(after);
73
+ }
74
+
75
+ export function formatCode(code: string, language: Language | null, width = DEFAULT_WIDTH): string {
76
+ if (!language || code.length > MAX_INPUT || !code.trim()) return code;
77
+ try {
78
+ const formatted = FORMATTERS[language](code, clampWidth(width)).replace(/\n+$/, "");
79
+ if (!formatted.trim()) return code;
80
+ if (language !== "shell" && language !== "sql" && !sameTokens(code, formatted)) return code;
81
+ return formatted;
82
+ } catch {
83
+ return code;
84
+ }
85
+ }
86
+
87
+ export function formatScript(code: string, width = DEFAULT_WIDTH): string {
88
+ if (code.length > MAX_INPUT || !code.trim()) return code;
89
+ try {
90
+ const formatted = scriptBody("typescript")(code, clampWidth(width));
91
+ return sameTokens(code, formatted) ? formatted : code;
92
+ } catch {
93
+ return code;
94
+ }
95
+ }
@@ -0,0 +1,59 @@
1
+ import type { ExtensionAPI, ToolRenderers } from "@earendil-works/pi-coding-agent";
2
+ import { Text } from "@earendil-works/pi-tui";
3
+ import { formatCode, formatScript } from "./languages";
4
+ import { formatMarkdownCode } from "./markdown";
5
+
6
+ type CallFormatter = { readonly prompt: string; readonly field: string; readonly format: (code: string) => string };
7
+
8
+ const CALLS: Record<string, CallFormatter> = {
9
+ bash: { prompt: "$", field: "command", format: (code) => formatCode(code, "shell") },
10
+ powershell: { prompt: ">", field: "command", format: (code) => formatCode(code, "shell") },
11
+ codemode: { prompt: "js", field: "code", format: formatScript },
12
+ };
13
+
14
+ const CODE_BLOCK_INDENT = 4;
15
+
16
+ const WRITING_RULE = `
17
+ ## Legible code
18
+
19
+ The user reads every tool call and code block. Write code a human can scan:
20
+ - Shell: one step per line. Put each \`&&\` or \`|\` continuation on its own line. More than three steps, or any loop or branch: write a script file, then run it.
21
+ - No inline Python, jq or node over about five lines; write a file instead.
22
+ - Name things once: \`MODEL_DIR=...\` before use, not repeated long paths.
23
+ - Code blocks in replies: tag the language and use normal formatting, one statement per line.
24
+ `;
25
+
26
+ function argumentsSettled(context: { argsComplete?: boolean; executionStarted?: boolean; isPartial?: boolean }): boolean {
27
+ return Boolean(context.argsComplete || context.executionStarted || context.isPartial === false);
28
+ }
29
+
30
+ function legibleCall(next: ToolRenderers | undefined, call: CallFormatter): ToolRenderers {
31
+ return {
32
+ ...next,
33
+ renderCall(args, theme, context) {
34
+ const source = typeof args?.[call.field] === "string" ? (args[call.field] as string) : "";
35
+ if (!source || !argumentsSettled(context)) {
36
+ return next?.renderCall ? next.renderCall(args, theme, context) : new Text(source, 0, 0);
37
+ }
38
+ next?.renderCall?.(args, theme, { ...context, lastComponent: undefined });
39
+ const [first, ...rest] = call.format(source).split("\n");
40
+ const timeout = args?.timeout ? theme.fg("muted", ` (timeout ${args.timeout}s)`) : "";
41
+ const head = theme.fg("toolTitle", theme.bold(`${call.prompt} ${first}`));
42
+ const body = rest.map((line) => theme.fg("toolTitle", ` ${line}`)).join("\n");
43
+ const component = context.lastComponent instanceof Text ? context.lastComponent : new Text("", 0, 0);
44
+ component.setText(body ? `${head}\n${body}${timeout}` : `${head}${timeout}`);
45
+ return component;
46
+ },
47
+ };
48
+ }
49
+
50
+ export default function legible(pi: ExtensionAPI) {
51
+ pi.registerToolRenderer((toolName, next) => {
52
+ const call = CALLS[toolName];
53
+ return call ? legibleCall(next(), call) : next();
54
+ });
55
+
56
+ pi.registerMarkdownTransformer((markdown, context) => (context.isStreaming ? markdown : formatMarkdownCode(markdown, context.availableWidth - CODE_BLOCK_INDENT)));
57
+
58
+ pi.on("before_agent_start", async (event) => ({ systemPrompt: `${event.systemPrompt}\n${WRITING_RULE}` }));
59
+ }
@@ -0,0 +1,11 @@
1
+ import { formatCode, languageOf } from "./languages";
2
+
3
+ const FENCE = /^( {0,3})(`{3,}|~{3,})([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm;
4
+
5
+ export function formatMarkdownCode(markdown: string, width?: number): string {
6
+ if (!markdown.includes("```") && !markdown.includes("~~~")) return markdown;
7
+ return markdown.replace(FENCE, (whole, indent: string, fence: string, info: string, body: string) => {
8
+ const formatted = formatCode(body, languageOf(info), width);
9
+ return formatted === body ? whole : `${indent}${fence}${info}\n${formatted}\n${indent}${fence}`;
10
+ });
11
+ }
@@ -0,0 +1,112 @@
1
+ export type Piece = { readonly text: string; readonly joiner: string };
2
+
3
+ const JOINERS = ["&&", "||", ";", "|"] as const;
4
+ const WRAP_AT = 100;
5
+
6
+ function heredocDelimiter(command: string, index: number): string | null {
7
+ const match = /^<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(command.slice(index));
8
+ return match ? match[2] : null;
9
+ }
10
+
11
+ export function splitTopLevel(command: string): Piece[] {
12
+ const pieces: Piece[] = [];
13
+ let current = "";
14
+ let quote: "'" | '"' | "`" | null = null;
15
+ let depth = 0;
16
+ let index = 0;
17
+
18
+ const push = (joiner: string) => {
19
+ if (current.trim()) pieces.push({ text: current.trim(), joiner });
20
+ current = "";
21
+ };
22
+
23
+ while (index < command.length) {
24
+ const char = command[index];
25
+
26
+ if (quote) {
27
+ current += char;
28
+ if (char === "\\" && quote !== "'" && index + 1 < command.length) {
29
+ current += command[index + 1];
30
+ index += 2;
31
+ continue;
32
+ }
33
+ if (char === quote) quote = null;
34
+ index += 1;
35
+ continue;
36
+ }
37
+
38
+ if (char === "'" || char === '"' || char === "`") {
39
+ quote = char;
40
+ current += char;
41
+ index += 1;
42
+ continue;
43
+ }
44
+
45
+ if (char === "<" && command[index + 1] === "<" && command[index + 2] !== "<") {
46
+ const delimiter = heredocDelimiter(command, index);
47
+ const bodyEnd = delimiter ? command.indexOf(`\n${delimiter}`, index) : -1;
48
+ if (delimiter && bodyEnd !== -1) {
49
+ const end = bodyEnd + delimiter.length + 1;
50
+ current += command.slice(index, end);
51
+ index = end;
52
+ continue;
53
+ }
54
+ }
55
+
56
+ if (char === "(" || char === "{") depth += 1;
57
+ if ((char === ")" || char === "}") && depth > 0) depth -= 1;
58
+
59
+ if (depth === 0) {
60
+ if (char === "\n") {
61
+ push(";");
62
+ index += 1;
63
+ continue;
64
+ }
65
+ const joiner = JOINERS.find((candidate) => command.startsWith(candidate, index));
66
+ const isPipeOr = joiner === "|" && command[index + 1] === "|";
67
+ const isRedirectAmp = joiner === "|" && command[index - 1] === ">";
68
+ if (joiner && !isPipeOr && !isRedirectAmp && !(joiner === ";" && command[index + 1] === ";")) {
69
+ push(joiner);
70
+ index += joiner.length;
71
+ continue;
72
+ }
73
+ }
74
+
75
+ current += char;
76
+ index += 1;
77
+ }
78
+
79
+ push("");
80
+ return pieces;
81
+ }
82
+
83
+ function wrapLong(text: string, indent: string): string {
84
+ if (text.length <= WRAP_AT || text.includes("\n")) return text;
85
+ const words = text.split(/(?<=\S)\s+(?=-{1,2}[A-Za-z]|"|')/);
86
+ if (words.length < 2) return text;
87
+ const lines: string[] = [];
88
+ let line = "";
89
+ for (const word of words) {
90
+ if (line && line.length + word.length + 1 > WRAP_AT) {
91
+ lines.push(line);
92
+ line = word;
93
+ } else {
94
+ line = line ? `${line} ${word}` : word;
95
+ }
96
+ }
97
+ lines.push(line);
98
+ return lines.join(` \\\n${indent} `);
99
+ }
100
+
101
+ export function formatCommand(command: string): string {
102
+ const pieces = splitTopLevel(command);
103
+ if (pieces.length <= 1 && command.length <= WRAP_AT) return command;
104
+
105
+ const lines: string[] = [];
106
+ let indent = "";
107
+ for (const piece of pieces) {
108
+ lines.push(`${indent}${wrapLong(piece.text, indent)}${piece.joiner && piece.joiner !== ";" ? ` ${piece.joiner}` : ""}`);
109
+ indent = piece.joiner === "|" ? " " : piece.joiner === "&&" || piece.joiner === "||" ? " " : "";
110
+ }
111
+ return lines.join("\n");
112
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "pi-legible",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "Makes code in pi legible: shell one step per line, code blocks and codemode scripts formatted, and asks the model to write it that way.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Jordan Coeyman",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/acoyfellow/pi-legible.git"
11
+ },
12
+ "keywords": [
13
+ "pi-package",
14
+ "pi-extension",
15
+ "formatter",
16
+ "legibility",
17
+ "bash",
18
+ "markdown"
19
+ ],
20
+ "files": [
21
+ "extensions",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "pi": {
26
+ "extensions": [
27
+ "./extensions/legible.ts"
28
+ ]
29
+ },
30
+ "scripts": {
31
+ "test": "bun test"
32
+ },
33
+ "peerDependencies": {
34
+ "@earendil-works/pi-coding-agent": "*",
35
+ "@earendil-works/pi-tui": "*"
36
+ },
37
+ "dependencies": {
38
+ "@wasm-fmt/biome_fmt": "^0.2.10",
39
+ "@wasm-fmt/gofmt": "^0.7.3",
40
+ "@wasm-fmt/ruff_fmt": "^0.15.20",
41
+ "@wasm-fmt/sql_fmt": "^0.2.2",
42
+ "@wasm-fmt/yamlfmt": "^0.2.1"
43
+ }
44
+ }