pal-code 0.0.21 → 0.0.23

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/README.md CHANGED
@@ -57,12 +57,45 @@ pal
57
57
  On first launch, pal-code runs a short setup wizard. Pick a provider (OpenCode Zen
58
58
  included) and paste an API key.
59
59
 
60
+ ### Headless
61
+
62
+ For scripts and CI, the same agent loop runs without the TUI:
63
+
64
+ ```bash
65
+ pal -p "explain what src/index.ts does" # one-shot, prints the answer
66
+ pal -p "fix the failing test" --yes # allow ask-gated tools
67
+ pal -p "summarise the diff" --json # machine-readable result
68
+ pal --mode rpc # NDJSON over stdio, long-lived
69
+ ```
70
+
71
+ `-p`/`--print`/`--prompt` take the task; `--model` and `--agent` select the
72
+ model and role. Nothing is written to the TUI, so this is safe to pipe.
73
+
74
+ Headless **fails closed**: with no human present, any tool call that would
75
+ normally prompt for approval is refused. `--yes` permits `ask`-gated calls but
76
+ never overrides an explicit `deny`, and dangerous shell commands are always
77
+ refused. Exit code is 130 on SIGINT.
78
+
79
+ In RPC mode pal emits a `ready` frame, then one `prompt_result` per prompt. Send
80
+ one JSON object per line: `{"type":"prompt","text":"..."}` to run a turn,
81
+ `{"type":"abort"}` to cancel, `{"type":"reset"}` to clear history. Malformed
82
+ JSON and unknown commands produce an `error` frame rather than ending the session.
83
+
60
84
  ## Features
61
85
 
62
86
  - **TUI** built on `@earendil-works/pi-tui` with streaming markdown, a model
63
87
  picker, session selector, and a live status line (tokens, cache-hit %, cost).
64
88
  - **Tool use** — read/write/edit files, run shell commands, grep/glob/ast-grep
65
89
  search, repo maps, `verify`, and `delegate` sub-agents.
90
+ - **Edits that recover from formatting drift** — an exact match is always tried
91
+ first and a non-unique `old_string` is always refused rather than applied to
92
+ the wrong site. When the match fails anyway, the model gets something usable:
93
+ a non-unique match reports each occurrence as `line: preview`, and a
94
+ multi-line miss whose only difference is indentation is matched by structure
95
+ with the original indentation restored. Re-wrapped blocks fall through to the
96
+ ast-grep `pattern`/`rewrite` path.
97
+ - **Structured delegation** — `delegate` accepts an optional `schema`, so a
98
+ child returns JSON you can parse instead of prose you have to read.
66
99
  - **BYOK provider registry** with key-shape detection, live `/models` fetching,
67
100
  curated fallback model lists, and retry/backoff. Model rotation on failure is
68
101
  opt-in (`/rotation`), with quota-vs-rate-limit-aware switching.
@@ -84,6 +117,63 @@ pal add @pal-code/agents # Multi-agent orchestration (delegate, explore
84
117
 
85
118
  Extensions are installed to `~/.pal/extensions/` and persist across sessions.
86
119
 
120
+ ## Structured delegation
121
+
122
+ `delegate` normally returns the child's final answer as free text. Pass a
123
+ `schema` and it returns JSON instead:
124
+
125
+ ```json
126
+ {
127
+ "task": "Audit packages/core for unhandled promise rejections",
128
+ "agent": "explore",
129
+ "schema": {
130
+ "type": "object",
131
+ "required": ["findings"],
132
+ "properties": {
133
+ "findings": {
134
+ "type": "array",
135
+ "items": {
136
+ "type": "object",
137
+ "required": ["path", "line", "severity"],
138
+ "properties": {
139
+ "path": {"type": "string"},
140
+ "line": {"type": "number"},
141
+ "severity": {"type": "string", "enum": ["low", "high"]}
142
+ }
143
+ }
144
+ }
145
+ }
146
+ }
147
+ }
148
+ ```
149
+
150
+ The child is told about the schema up front, its answer is parsed (markdown
151
+ fences and trailing prose are tolerated), and the result is re-serialised as
152
+ clean JSON. If the answer does not match, the child gets exactly one repair
153
+ round naming what was wrong; if it still fails you get a plain string saying
154
+ which paths were wrong plus the child's last answer, rather than a silent
155
+ prose summary. `delegate_parallel` takes a `schema` per task, and one failing
156
+ task does not abort the batch.
157
+
158
+ **Supported schema subset.** Deliberately small and hand-written, so pal needs
159
+ no validator dependency:
160
+
161
+ | Keyword | Notes |
162
+ | --- | --- |
163
+ | `type` | `object`, `array`, `string`, `number`, `integer`, `boolean`, `null`; an array of these means "any of" |
164
+ | `properties` | recursed into named members |
165
+ | `required` | every named key must be present |
166
+ | `items` | recursed into every array element |
167
+ | `enum` | the value must deep-equal one of the listed values |
168
+
169
+ Anything else — `oneOf`/`anyOf`/`allOf`, `$ref`, `additionalProperties`,
170
+ `pattern`, `format`, numeric ranges, `patternProperties` — is **ignored, not
171
+ enforced**. Unsupported keywords cannot reject a correct answer; they simply
172
+ add no constraint. If you need one, validate the returned JSON yourself.
173
+
174
+ Omitting `schema` changes nothing: the child's answer comes back verbatim,
175
+ exactly as in earlier versions.
176
+
87
177
  ## MCP (Model Context Protocol)
88
178
 
89
179
  Add MCP servers for external tool integrations:
@@ -113,6 +203,47 @@ Non-key settings can also live in `~/.pal/config.json` — for example
113
203
  `contextLimit` set here is overridden by the `CONTEXT_LIMIT` env var, and
114
204
  invalid values are ignored in favour of the defaults.
115
205
 
206
+ ### Post-edit diagnostics
207
+
208
+ After a successful `edit`/`write`, pal checks the file and feeds one compact
209
+ line back to the model on its next round: `✓ edit ok`, or
210
+ `✗ src/a.ts:12 - <message>`. Failures are silently skipped, so a missing checker
211
+ never breaks an edit.
212
+
213
+ Two checkers exist, and the second is opt-in:
214
+
215
+ | Checker | Covers | Enabled by |
216
+ |---|---|---|
217
+ | biome + incremental `tsc` | JS/TS/JSON/CSS | default (`"diagnostics": "auto"`) |
218
+ | Language server (LSP) | Python, Go, Rust | `PAL_LSP=1` |
219
+
220
+ The LSP path is off by default because it spawns a language server against your
221
+ workspace — a bigger commitment than the JS/TS path, which only shells out to
222
+ tools the project already has. Turn it on with:
223
+
224
+ ```bash
225
+ PAL_LSP=1 pal
226
+ ```
227
+
228
+ Servers are used only if they are already on your `PATH` — pal never installs
229
+ anything. Install whichever you need: `pyright-langserver` (Python), `gopls`
230
+ (Go), `rust-analyzer` (Rust). If the binary is missing, the language server
231
+ fails to start, publishes nothing, or exceeds the time budget, pal falls back
232
+ silently and the edit proceeds.
233
+
234
+ Two deliberate limits:
235
+
236
+ - **`typescript-language-server` is not used.** biome + tsc already cover TS
237
+ better, and adding a server would displace them. LSP exists for languages
238
+ that currently get no post-edit feedback at all.
239
+ - **Cold starts can exceed the budget.** The default `budgetMs` is 2000, and a
240
+ language server touching a large project for the first time can take longer,
241
+ in which case that edit simply gets no diagnostic. This is a silent skip, not
242
+ an error.
243
+
244
+ `"diagnostics": "off"` disables both paths; `"diagnostics": "verify-only"` shows
245
+ the result to you but keeps it out of the model's context.
246
+
116
247
  ### Data storage
117
248
 
118
249
  All user data lives in `~/.pal/`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pal-code",
3
- "version": "0.0.21",
3
+ "version": "0.0.23",
4
4
  "description": "A terminal coding agent with BYOK, tool use, and extensions",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -66,7 +66,7 @@
66
66
  "gemini"
67
67
  ],
68
68
  "dependencies": {
69
- "@pal-code/core": "0.0.21",
69
+ "@pal-code/core": "0.0.23",
70
70
  "@earendil-works/pi-tui": "^0.85.1",
71
71
  "get-east-asian-width": "1.6.0",
72
72
  "marked": "^18.1.3"
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Plan → build approval gate.
3
+ *
4
+ * `exit_plan_mode` used to start an implementation turn *inside the planning
5
+ * turn itself*: the model called the tool and pal immediately began writing,
6
+ * while the transcript announced "your plan above is approved". Nothing had
7
+ * been approved — the model asked, and pal answered for the user.
8
+ *
9
+ * The gate here is deliberately a small, pure state machine so the interesting
10
+ * rules (which key wins, when a timeout is allowed to fire, the countdown text)
11
+ * are testable without a TUI, a provider, or a timer.
12
+ */
13
+
14
+ /** Default seconds before an unanswered prompt auto-approves. */
15
+ export const APPROVAL_TIMEOUT_SECONDS = 60;
16
+
17
+ /** The message handed to the implementation turn once a plan is approved. */
18
+ export const APPROVAL_PROMPT =
19
+ 'Your plan above is approved. Implement it now, following that plan. ' +
20
+ 'Do not enter plan mode again for this task — carry it through to completion. ' +
21
+ 'You are now in execution mode. Work through the plan by calling tools until it is ' +
22
+ 'fully implemented — never end a turn with prose describing what you will do next; ' +
23
+ 'a turn may only end in prose when everything is done or a genuine question for the user.';
24
+
25
+ /** Resolve the configured timeout, falling back to the default on junk. */
26
+ export function resolveApprovalTimeoutSeconds(value: unknown): number {
27
+ const n = typeof value === 'number' ? value : Number(value);
28
+ if (!Number.isFinite(n) || n <= 0) return APPROVAL_TIMEOUT_SECONDS;
29
+ return Math.floor(n);
30
+ }
31
+
32
+ /**
33
+ * The inline prompt, including the countdown.
34
+ *
35
+ * The countdown is part of the contract, not decoration: the prompt
36
+ * auto-approves, so the user has to be able to see that it is going to.
37
+ */
38
+ export function approvalPromptText(remainingSeconds: number): string {
39
+ const s = Math.max(0, Math.ceil(remainingSeconds));
40
+ return `Plan ready — implement? y / n (auto in ${s}s)`;
41
+ }
42
+
43
+ /** What the user's keypress means while the approval prompt is showing. */
44
+ export type ApprovalKeyDecision = 'approve' | 'reject' | 'ignore';
45
+
46
+ /**
47
+ * Classify a keypress against the pending approval prompt.
48
+ *
49
+ * Matched by key name rather than by importing pi-tui's key table, so the
50
+ * decision is unit-testable. Only `y`/`n` (and Esc, treated as "no") are
51
+ * meaningful; anything else must fall through to the editor untouched.
52
+ */
53
+ export function approvalKeyDecision(key: string): ApprovalKeyDecision {
54
+ switch (key.toLowerCase()) {
55
+ case 'y':
56
+ case 'enter':
57
+ return 'approve';
58
+ case 'n':
59
+ case 'escape':
60
+ case 'esc':
61
+ return 'reject';
62
+ default:
63
+ return 'ignore';
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Whether the timeout may fire right now.
69
+ *
70
+ * Both conditions matter. Still-pending means the user has not answered, so the
71
+ * timer must not approve a plan they are about to decline. Idle means no turn
72
+ * is live — `runTurn` is not re-entrant, so a timeout that fired mid-turn would
73
+ * either run two turns at once or be silently dropped.
74
+ */
75
+ export function shouldAutoApprove(input: {
76
+ pending: boolean;
77
+ idle: boolean;
78
+ remainingSeconds: number;
79
+ }): boolean {
80
+ return input.pending && input.idle && input.remainingSeconds <= 0;
81
+ }
82
+
83
+ /**
84
+ * Whether the settle path must fire an approval whose countdown already ran out.
85
+ *
86
+ * The timeout is *held* while a turn is live (`shouldAutoApprove` refuses a
87
+ * busy process), so a countdown that expires mid-turn reaches zero and then has
88
+ * nothing to act on. Without this re-check that approval is lost forever: the
89
+ * prompt sits on screen answering to nothing, and the plan is never
90
+ * implemented. The settle path calls this once the turn is over.
91
+ *
92
+ * Deliberately the same predicate as `shouldAutoApprove` with `idle` known to
93
+ * be true, so "the timer could not fire" and "the settle path catches up" can
94
+ * never disagree about what counts as expired.
95
+ */
96
+ export function shouldFireOnSettle(input: {pending: boolean; remainingSeconds: number}): boolean {
97
+ return input.pending && input.remainingSeconds <= 0;
98
+ }
99
+
100
+ /**
101
+ * Where the countdown goes after one tick.
102
+ *
103
+ * Returns `done` at zero so the caller fires the timeout exactly once and stops
104
+ * its interval. Never goes negative — a negative value would render as
105
+ * "(auto in -1s)" and read as a crash rather than a decision.
106
+ */
107
+ export function tickApproval(remainingSeconds: number): {
108
+ remainingSeconds: number;
109
+ done: boolean;
110
+ } {
111
+ const next = Math.max(0, remainingSeconds - 1);
112
+ return {remainingSeconds: next, done: next <= 0};
113
+ }
@@ -49,24 +49,42 @@ export function cmdHelp(container: Container, tui: TUI): void {
49
49
  new Text(` ${c.cyan}ctrl+b${c.reset} Toggle background agent panel`, 1, 0),
50
50
  );
51
51
  container.addChild(new Text(` ${c.cyan}ctrl+o${c.reset} Expand the last run`, 1, 0));
52
+ container.addChild(new Text(` ${c.cyan}esc${c.reset} Interrupt the running turn`, 1, 0));
52
53
  container.addChild(
53
- new Text(` ${c.cyan}esc${c.reset} Interrupt the running turn`, 1, 0),
54
+ new Text(` ${c.cyan}ctrl+c${c.reset} Copy the selection, or press twice to quit`, 1, 0),
54
55
  );
55
56
 
56
57
  container.addChild(new Text('', 0, 0));
57
58
  container.addChild(new Text(` ${c.bold}Scroll transcript:${c.reset}`, 1, 0));
58
59
  container.addChild(
59
60
  new Text(
60
- ` ${c.dim}Mouse wheel · PgUp/PgDn · ↑/↓ (while scrolled) · Home/End · Esc to exit${c.reset}`,
61
+ ` ${c.dim}Shift+↑/↓ · Shift+PgUp/PgDn · Shift+Home/End${c.reset}`,
61
62
  1,
62
63
  0,
63
64
  ),
64
65
  );
66
+ container.addChild(
67
+ new Text(` ${c.dim}Plain PgUp/PgDn and Ctrl+Home/Ctrl+End work too · Esc returns${c.reset}`, 1, 0),
68
+ );
65
69
  container.addChild(new Text('', 0, 0));
66
70
  container.addChild(new Text(` ${c.bold}Copy text:${c.reset}`, 1, 0));
67
71
  container.addChild(
68
72
  new Text(
69
- ` ${c.dim}Shift+drag to select (plain drag is captured by mouse scrolling)${c.reset}`,
73
+ ` ${c.dim}Drag to select, then Ctrl/Cmd+C to copy (Esc clears)${c.reset}`,
74
+ 1,
75
+ 0,
76
+ ),
77
+ );
78
+ container.addChild(
79
+ new Text(
80
+ ` ${c.dim}Double-click a word · drag past an edge to keep scrolling${c.reset}`,
81
+ 1,
82
+ 0,
83
+ ),
84
+ );
85
+ container.addChild(
86
+ new Text(
87
+ ` ${c.dim}Shift+drag for the terminal's selection · /copy or /copy code · click ⧉ on a code block${c.reset}`,
70
88
  1,
71
89
  0,
72
90
  ),
@@ -57,6 +57,20 @@ export class Sidebar implements Component {
57
57
  private readonly body = new Text('', 1, 0);
58
58
  /** Must match SIDEBAR_WIDTH — the overlay width passed to showOverlay in index.ts. */
59
59
  private w = 34;
60
+ /**
61
+ * Version shown in the sticky footer. Injected by `index.ts` (which owns the
62
+ * VERSION constant) rather than imported, so the sidebar never becomes a
63
+ * second source of truth for the release number.
64
+ */
65
+ private version = '';
66
+ /**
67
+ * Screen rows available to this overlay, set by `index.ts` from the same
68
+ * terminal height the layout uses. Needed because pi-tui paints an overlay's
69
+ * rows from the TOP of its bounding box with no bottom alignment, so the only
70
+ * way to pin a footer to the bottom is to pad the content to full height and
71
+ * let the last row land there.
72
+ */
73
+ private viewportRows = 0;
60
74
  private stats: SidebarStats = {
61
75
  inputTokens: 0,
62
76
  outputTokens: 0,
@@ -73,6 +87,26 @@ export class Sidebar implements Component {
73
87
  this.refresh();
74
88
  }
75
89
 
90
+ /** Set once at startup — the release version shown in the sticky footer. */
91
+ setVersion(version: string): void {
92
+ this.version = version;
93
+ this.refresh();
94
+ }
95
+
96
+ /**
97
+ * Tell the sidebar how many rows the terminal gives it.
98
+ *
99
+ * `rows` is the full terminal height. The main column renders at `columns -
100
+ * sidebarWidth`, so this overlay owns the right-hand columns for the entire
101
+ * screen height and cannot overlap the editor or status line — full height is
102
+ * therefore safe, and it is what puts the footer on the last screen row.
103
+ */
104
+ setViewportRows(rows: number): void {
105
+ if (rows === this.viewportRows) return;
106
+ this.viewportRows = rows;
107
+ this.refresh();
108
+ }
109
+
76
110
  refresh(): void {
77
111
  const s = this.stats;
78
112
  const w = this.w;
@@ -184,6 +218,18 @@ export class Sidebar implements Component {
184
218
  this.body.setText(lines.join('\n'));
185
219
  }
186
220
 
221
+ /**
222
+ * The sticky footer row: right-aligned `v<version>`.
223
+ *
224
+ * Right-aligned and last, so it reads as a corner label rather than another
225
+ * content block. Returns '' when no version was injected (tests, or a caller
226
+ * that has not wired it yet) so the footer never renders as a bare "v".
227
+ */
228
+ private footerLine(): string {
229
+ if (!this.version) return '';
230
+ return `${surface.sidebar.dim}v${this.version}${c.reset}`;
231
+ }
232
+
187
233
  invalidate(): void {
188
234
  this.body.invalidate();
189
235
  }
@@ -199,6 +245,31 @@ export class Sidebar implements Component {
199
245
  // passes through byte-identical. Status line and editor rows paint no
200
246
  // panel: their GitHub bg is the canvas #0d1117 itself, so they sit
201
247
  // flush on the canvas while the sidebar reads darker (#010409).
202
- return this.body.render(width).map((line) => paintPanel(surface.sidebar.bg, line, width));
248
+ const rows = this.body.render(width).map((line) => paintPanel(surface.sidebar.bg, line, width));
249
+
250
+ // ── Sticky footer ──
251
+ // pi-tui composites an overlay starting at the TOP of its bounding box and
252
+ // has no bottom alignment, so a footer can only be pinned by padding the
253
+ // content out to the full height and letting the last row be the footer.
254
+ // The padding is what keeps todo/extension growth from pushing the version
255
+ // up the screen: content grows into the gap, the footer never moves.
256
+ const footer = this.footerLine();
257
+ if (!footer || this.viewportRows <= 0) return rows;
258
+ // Full height, deliberately: the main column renders at `columns -
259
+ // sidebarWidth`, so this overlay owns the right-hand columns for the whole
260
+ // screen and never overlaps the editor or the status line. Rendering all
261
+ // `rows` puts the footer on the last screen row — the same row as the model
262
+ // name in the status line — which is what "bottom right" means here.
263
+ const usable = Math.max(1, this.viewportRows);
264
+ const out = rows.slice(0, Math.max(1, usable - 1));
265
+ while (out.length < usable - 1) out.push(paintPanel(surface.sidebar.bg, '', width));
266
+ out.push(paintPanel(surface.sidebar.bg, this.alignRight(footer, width), width));
267
+ return out;
268
+ }
269
+
270
+ /** Right-align a styled line so it ends flush at the right edge of `width`. */
271
+ private alignRight(line: string, width: number): string {
272
+ const pad = Math.max(0, width - displayWidth(line));
273
+ return `${' '.repeat(pad)}${line}`;
203
274
  }
204
275
  }