pal-code 0.0.16 → 0.0.18

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.
Files changed (40) hide show
  1. package/README.md +9 -6
  2. package/SYSTEM.md +17 -2
  3. package/package.json +10 -5
  4. package/packages/cli/src/agent-panel.ts +1 -1
  5. package/packages/cli/src/agent-ui.ts +66 -0
  6. package/packages/cli/src/commands/ext-registry.ts +7 -0
  7. package/packages/cli/src/commands.ts +32 -102
  8. package/packages/cli/src/components/assistant-body.ts +4 -3
  9. package/packages/cli/src/components/message-box.ts +2 -2
  10. package/packages/cli/src/components/permission-prompt.ts +3 -3
  11. package/packages/cli/src/components/render-history.ts +13 -12
  12. package/packages/cli/src/components/run-view.ts +109 -33
  13. package/packages/cli/src/components/sidebar.ts +81 -14
  14. package/packages/cli/src/components/status-line.ts +3 -3
  15. package/packages/cli/src/config.ts +6 -129
  16. package/packages/cli/src/index.ts +194 -69
  17. package/packages/cli/src/overlays/key-input.ts +142 -121
  18. package/packages/cli/src/overlays/model-picker.ts +19 -56
  19. package/packages/cli/src/overlays/select.ts +102 -0
  20. package/packages/cli/src/overlays/session-picker.ts +14 -40
  21. package/packages/cli/src/overlays/wizard.ts +107 -42
  22. package/packages/cli/src/prompt/select.ts +181 -0
  23. package/packages/cli/src/slash-commands.ts +105 -0
  24. package/packages/cli/src/state.ts +32 -74
  25. package/packages/cli/src/theme.ts +13 -1
  26. package/packages/cli/src/themes/github-dark.ts +14 -3
  27. package/packages/cli/src/themes/types.ts +26 -2
  28. package/packages/cli/src/themes/vanilla-pi.ts +23 -9
  29. package/packages/cli/src/tui/components/text.ts +102 -0
  30. package/packages/cli/src/tui/render/code-block.ts +325 -0
  31. package/packages/cli/src/{utils → tui/render}/format.ts +31 -24
  32. package/packages/cli/src/{utils → tui/render}/highlight.ts +94 -2
  33. package/packages/cli/src/tui/render/markdown.ts +529 -0
  34. package/packages/cli/src/tui/surface/index.ts +9 -0
  35. package/packages/cli/src/tui/{paint-panel.ts → surface/paint-panel.ts} +1 -1
  36. package/packages/cli/src/tui/theme-types.ts +59 -0
  37. package/packages/cli/src/tui/tty-width.ts +20 -0
  38. package/packages/cli/src/tui/types.ts +53 -0
  39. package/packages/cli/src/turn.ts +0 -292
  40. package/packages/cli/src/utils/code-block.ts +0 -200
@@ -7,11 +7,12 @@
7
7
  * `finish()` collapses it to a one-line summary; `expand()` re-inflates it.
8
8
  */
9
9
 
10
- import {Container, Text} from '@earendil-works/pi-tui';
11
- import type {TUI} from '@earendil-works/pi-tui';
10
+ import {Text} from '../tui/components/text.js';
11
+ import {Container} from '@earendil-works/pi-tui';
12
+ import type {Component, TUI} from '@earendil-works/pi-tui';
12
13
 
13
- import {c} from '../theme.js';
14
- import {truncate} from '../utils/format.js';
14
+ import {c, surface} from '../theme.js';
15
+ import {truncate, displayWidth} from '../tui/render/format.js';
15
16
  import {AssistantBody} from './assistant-body.js';
16
17
  // ═══════════════════════════════════════════════════════════════════════════════
17
18
  // Live run view — one mutable block per turn instead of an append-only log
@@ -19,6 +20,39 @@ import {AssistantBody} from './assistant-body.js';
19
20
 
20
21
  const SPIN_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
21
22
 
23
+ /** Fixed columns for the elapsed and name cells so rows align at EN width. */
24
+ const ELAPSED_W = 7;
25
+ const NAME_W = 12;
26
+
27
+ /**
28
+ * Align one tool row as columns `icon │ elapsed │ name │ args…`:
29
+ * ` ⠹ 12.40s Bash npm test → preview`.
30
+ * The name cell is padded with plain spaces so its text starts at the same
31
+ * visible column on every row (measured with `displayWidth`, never
32
+ * `String.length`); a running row leaves the elapsed cell blank so the
33
+ * columns never shift when a tool finishes.
34
+ */
35
+ /** Elapsed label for the thinking phase: `657ms` under a second, `1.2s` above. */
36
+ function formatDuration(ms: number): string {
37
+ const n = Math.max(0, Math.round(ms));
38
+ return n < 1000 ? `${n}ms` : `${(n / 1000).toFixed(1)}s`;
39
+ }
40
+
41
+ /** One paint definition for thought blocks — live stream and resume repaint share it. */
42
+ export function formatThinkingBlock(thinking: string, ms: number): string {
43
+ return `\n${c.dim}${c.bright_black}${thinking}${c.reset}\n${c.yellow}Thought · ${formatDuration(ms)}${c.reset}\n`;
44
+ }
45
+
46
+ export function toolRowText(icon: string, elapsed: string, name: string, args: string): string {
47
+ const elapsedCell = `${surface.runView.elapsed}${elapsed.padStart(ELAPSED_W)}${c.reset}`;
48
+ const nameTrunc = truncate(name, NAME_W);
49
+ const nameCell = `${surface.runView.row}${nameTrunc}${c.reset}${' '.repeat(
50
+ Math.max(0, NAME_W - displayWidth(nameTrunc)),
51
+ )}`;
52
+ const argsPart = args ? ` ${args}` : '';
53
+ return ` ${icon} ${elapsedCell} ${nameCell}${argsPart}`;
54
+ }
55
+
22
56
  interface RunRow {
23
57
  name: string;
24
58
  argsSummary: string;
@@ -40,10 +74,11 @@ export class RunView {
40
74
  private readonly rowIds: string[] = [];
41
75
  private readonly rowTexts: Text[] = [];
42
76
  private summaryText: Text | null = null;
43
- /** All streaming answer blocks from every round — only the last is active. */
44
- private responses: AssistantBody[] = [];
45
77
  private response: AssistantBody | null = null;
46
- /** True after finish() re-parented responses to `this.parent`. */
78
+ /** Container children archived by finish(), in creation order (header
79
+ excluded) — tool rows stay interleaved with thinking and answers. */
80
+ private archived: Component[] = [];
81
+ /** True after finish() re-parented activity to `this.parent`. */
47
82
  private reParented = false;
48
83
  private roundNo = 0;
49
84
  private maxRounds = 0;
@@ -53,6 +88,10 @@ export class RunView {
53
88
  collapsed = false;
54
89
 
55
90
  private streamBuffer = '';
91
+ private thinkingBuffer = '';
92
+ private thinkingText: Text | null = null;
93
+ private thinkingStartedAt: number | null = null;
94
+ private thinkingFrozenMs: number | null = null;
56
95
 
57
96
  constructor(
58
97
  private readonly parent: Container,
@@ -73,11 +112,38 @@ export class RunView {
73
112
 
74
113
  /** Append streamed assistant text to this round's answer block. */
75
114
  streamText(chunk: string): void {
115
+ if (this.thinkingText && this.thinkingFrozenMs === null) {
116
+ this.thinkingFrozenMs = Date.now() - (this.thinkingStartedAt ?? Date.now());
117
+ this.renderThinking();
118
+ }
76
119
  this.streamBuffer += chunk;
77
120
  this.responseBlock().setText(this.streamBuffer);
78
121
  this.tui.requestRender();
79
122
  }
80
123
 
124
+ /**
125
+ * Append streamed model thinking, rendered dimmed above the answer.
126
+ * Thinking arrives before text, so the lazily created block naturally
127
+ * lands above the response block; on collapse it is archived with the
128
+ * answers instead of vanishing with the activity.
129
+ */
130
+ streamThinking(chunk: string): void {
131
+ this.thinkingBuffer += chunk;
132
+ if (this.thinkingStartedAt === null) this.thinkingStartedAt = Date.now();
133
+ if (!this.thinkingText) {
134
+ this.thinkingText = new Text('', 1, 0);
135
+ this.container.addChild(this.thinkingText);
136
+ }
137
+ this.renderThinking();
138
+ this.tui.requestRender();
139
+ }
140
+
141
+ private renderThinking(): void {
142
+ if (!this.thinkingText) return;
143
+ const ms = this.thinkingFrozenMs ?? Date.now() - (this.thinkingStartedAt ?? Date.now());
144
+ this.thinkingText.setText(formatThinkingBlock(this.thinkingBuffer, ms));
145
+ }
146
+
81
147
  private renderHeader(): void {
82
148
  const active = !this.collapsed;
83
149
  const mark = active
@@ -85,13 +151,13 @@ export class RunView {
85
151
  : `${c.cyan}▸${c.reset}`;
86
152
  const secs = ((Date.now() - this.startedAt) / 1000).toFixed(1);
87
153
  const roundPart = this.maxRounds
88
- ? ` ${c.dim}· ${this.roundNo}/${this.maxRounds}${c.reset}`
154
+ ? ` ${surface.runView.border}· ${this.roundNo}/${this.maxRounds}${c.reset}`
89
155
  : '';
90
156
  const toolPart = this.rows.length
91
- ? ` ${c.dim}· ${this.rows.length} tool${this.rows.length === 1 ? '' : 's'}${c.reset}`
157
+ ? ` ${surface.runView.border}· ${this.rows.length} tool${this.rows.length === 1 ? '' : 's'}${c.reset}`
92
158
  : '';
93
159
  this.header.setText(
94
- `${mark} ${c.bold}Run${c.reset} ${c.dim}${this.model} · ${secs}s${c.reset}${roundPart}${toolPart}`,
160
+ `${mark} ${c.bold}Run${c.reset} ${surface.runView.border}${this.model} · ${secs}s${c.reset}${roundPart}${toolPart}`,
95
161
  );
96
162
  }
97
163
 
@@ -105,10 +171,14 @@ export class RunView {
105
171
  : r.status === 'ok'
106
172
  ? `${c.green}✓${c.reset}`
107
173
  : `${c.red}✗${c.reset}`;
108
- const ms =
109
- r.status === 'running' ? '' : ` ${c.dim}${(r.elapsedMs / 1000).toFixed(2)}s${c.reset}`;
110
- const tail = r.preview ? ` ${c.dim}→ ${r.preview}${c.reset}` : '';
111
- t.setText(` ${icon} ${r.name}${c.dim}(${r.argsSummary})${c.reset}${ms}${tail}`);
174
+ const elapsed = r.status === 'running' ? '' : `${(r.elapsedMs / 1000).toFixed(2)}s`;
175
+ const args = r.argsSummary
176
+ ? `${surface.runView.border}(${r.argsSummary})${c.reset}`
177
+ : '';
178
+ const tail = r.preview
179
+ ? ` ${surface.runView.preview}→ ${r.preview}${c.reset}`
180
+ : '';
181
+ t.setText(`${toolRowText(icon, elapsed, r.name, args)}${tail}`);
112
182
  }
113
183
 
114
184
  private tick(): void {
@@ -126,6 +196,10 @@ export class RunView {
126
196
  // Archive the previous round's response so finish() can preserve it.
127
197
  this.response = null;
128
198
  this.streamBuffer = '';
199
+ this.thinkingBuffer = '';
200
+ this.thinkingText = null;
201
+ this.thinkingStartedAt = null;
202
+ this.thinkingFrozenMs = null;
129
203
  if (!this.timer) this.timer = setInterval(() => this.tick(), 120);
130
204
  this.renderHeader();
131
205
  this.tui.requestRender();
@@ -135,7 +209,6 @@ export class RunView {
135
209
  responseBlock(): AssistantBody {
136
210
  if (!this.response) {
137
211
  this.response = new AssistantBody('');
138
- this.responses.push(this.response);
139
212
  this.container.addChild(this.response);
140
213
  }
141
214
  return this.response;
@@ -195,18 +268,25 @@ export class RunView {
195
268
 
196
269
  /** Collapse: drop the activity, keep ALL answers, leave a one-line summary. */
197
270
  finish(keepAnswer: boolean): void {
271
+ if (this.thinkingText && this.thinkingFrozenMs === null) {
272
+ this.thinkingFrozenMs = Date.now() - (this.thinkingStartedAt ?? Date.now());
273
+ this.renderThinking();
274
+ }
198
275
  if (this.timer) {
199
276
  clearInterval(this.timer);
200
277
  this.timer = null;
201
278
  }
202
279
  this.parent.removeChild(this.container);
203
280
  this.parent.addChild(this.summary());
204
- if (keepAnswer && this.responses.length > 0) {
205
- // Re-parent every round's answer block so multi-round turns don't lose
206
- // earlier assistant prose. They are kept in creation order (round 1, 2, …).
207
- for (const resp of this.responses) {
208
- this.container.removeChild(resp);
209
- this.parent.addChild(resp);
281
+ if (keepAnswer) {
282
+ // Archive every activity child EXCEPT the header, in container
283
+ // (creation) order — tool rows stay interleaved with thinking and
284
+ // answers instead of pooling behind the summary.
285
+ for (const kid of [...this.container.children]) {
286
+ if (kid === this.header) continue;
287
+ this.container.removeChild(kid);
288
+ this.parent.addChild(kid);
289
+ this.archived.push(kid);
210
290
  }
211
291
  this.reParented = true;
212
292
  }
@@ -223,7 +303,7 @@ export class RunView {
223
303
  bits.push(`${tools} tool${tools === 1 ? '' : 's'}${failed ? `, ${failed} failed` : ''}`);
224
304
  bits.push('ctrl+o to expand');
225
305
  if (!this.summaryText) this.summaryText = new Text('', 1, 0);
226
- this.summaryText.setText(` ${c.dim}${bits.join(' · ')}${c.reset}`);
306
+ this.summaryText.setText(` ${surface.runView.summary}${bits.join(' · ')}${c.reset}`);
227
307
  return this.summaryText;
228
308
  }
229
309
 
@@ -235,21 +315,17 @@ export class RunView {
235
315
  this.parent.removeChild(this.summaryText);
236
316
  this.summaryText = null;
237
317
  }
238
- // Re-insert the activity *before* the answers so the order reads
239
- // activity → answers, not summary → answers → activity.
240
- //
241
- // Only responses that were re-parented by finish() live in `this.parent`;
242
- // finish(false) left them inside `this.container`, so skip those to avoid
243
- // removeChild throwing for a non-child.
318
+ // Pull the archived activity back into the container in its original
319
+ // order; the header never left, so plain re-append restores the layout.
320
+ // Then re-insert the container where the summary stood.
244
321
  if (this.reParented) {
245
- for (const resp of this.responses) {
246
- this.parent.removeChild(resp);
322
+ for (const kid of this.archived) {
323
+ this.parent.removeChild(kid);
324
+ this.container.addChild(kid);
247
325
  }
326
+ this.archived = [];
248
327
  }
249
328
  this.parent.addChild(this.container);
250
- for (const resp of this.responses) {
251
- this.parent.addChild(resp);
252
- }
253
329
  this.reParented = false;
254
330
  this.collapsed = false;
255
331
  this.tui.requestRender();
@@ -6,13 +6,14 @@
6
6
  * pinned while the main column scrolls underneath.
7
7
  */
8
8
 
9
- import {Text} from '@earendil-works/pi-tui';
10
- import type {Component} from '@earendil-works/pi-tui';
9
+ import {Text} from '../tui/components/text.js';
10
+ import type {Component} from '../tui/types.js';
11
11
 
12
12
  import {c, surface} from '../theme.js';
13
- import {paintPanel} from '../tui/paint-panel.js';
13
+ import {paintPanel} from '../tui/surface/paint-panel.js';
14
+ import {truncateToWidth} from '../tui/tty-width.js';
14
15
  import {formatTokens, formatCost, formatCacheHit} from '../utils/cost.js';
15
- import {truncate} from '../utils/format.js';
16
+ import {truncate, displayWidth} from '../tui/render/format.js';
16
17
  import {state} from '../state.js';
17
18
 
18
19
  export interface SidebarStats {
@@ -21,6 +22,10 @@ export interface SidebarStats {
21
22
  cachedTokens: number;
22
23
  cost: number;
23
24
  contextPct: number;
25
+ /** Estimated tokens of the CURRENT conversation (the compaction measure). */
26
+ ctxTokens: number;
27
+ /** Configured context window — shown next to ctxTokens so the limit is explicit. */
28
+ contextLimit: number;
24
29
  priced: boolean;
25
30
  }
26
31
 
@@ -39,14 +44,27 @@ function todoIcon(status: string): string {
39
44
  }
40
45
  }
41
46
 
47
+ /** Time-based placeholder shown while a session has no generated title yet. */
48
+ export function timeGreeting(now = new Date()): string {
49
+ const h = now.getHours();
50
+ if (h < 5) return 'Good night';
51
+ if (h < 12) return 'Good morning';
52
+ if (h < 18) return 'Good afternoon';
53
+ return 'Good evening';
54
+ }
55
+
42
56
  export class Sidebar implements Component {
43
57
  private readonly body = new Text('', 1, 0);
58
+ /** Must match SIDEBAR_WIDTH — the overlay width passed to showOverlay in index.ts. */
59
+ private w = 34;
44
60
  private stats: SidebarStats = {
45
61
  inputTokens: 0,
46
62
  outputTokens: 0,
47
63
  cachedTokens: 0,
48
64
  cost: 0,
49
65
  contextPct: 0,
66
+ ctxTokens: 0,
67
+ contextLimit: 0,
50
68
  priced: false,
51
69
  };
52
70
 
@@ -57,21 +75,58 @@ export class Sidebar implements Component {
57
75
 
58
76
  refresh(): void {
59
77
  const s = this.stats;
78
+ const w = this.w;
60
79
 
61
- // Must match the overlay width passed to tui.showOverlay() in index.ts.
62
- const w = 30;
63
-
64
- // The same symbols the old status bar used — one stat per line, left-aligned.
65
80
  const lines: string[] = [];
66
81
  if (state.sessionTitle) {
67
82
  lines.push(`${surface.sidebar.title}${truncate(state.sessionTitle, w - 4)}${c.reset}`, '');
83
+ } else {
84
+ lines.push(`${surface.sidebar.dim}${timeGreeting()}${c.reset}`, '');
68
85
  }
86
+ // Boxed stats table: header inside the top border, one separator under it,
87
+ // glyph+word labels in a fixed left column, values left-aligned right after
88
+ // the label column, dim annotations trailing the value. No per-row rules —
89
+ // four short rows read fine without them.
90
+ const inner = w - 4; // columns between the side walls (body budget is w-2)
91
+ const wall = (ch: string): string => `${surface.sidebar.border}${ch}${c.reset}`;
92
+ const dashes = (n: number): string => `${surface.sidebar.border}${'─'.repeat(n)}${c.reset}`;
93
+ const cell = (body: string): string => {
94
+ const pad = Math.max(0, inner - 2 - displayWidth(body));
95
+ return `${wall('│')} ${body}${' '.repeat(pad)} ${wall('│')}`;
96
+ };
97
+ const LABEL_W = 9; // widest label ('◔ context')
98
+ const row = (label: string, value: string, dimSuffix = ''): string => {
99
+ const budget = inner - 2; // walls + one space each side
100
+ // Long values (≥10M tokens) would overflow the box: drop the dim
101
+ // annotation first, then hard-truncate — the border must stay whole.
102
+ let suffix = dimSuffix;
103
+ if (displayWidth(label) + 1 + displayWidth(value) + displayWidth(suffix) > budget) {
104
+ suffix = '';
105
+ }
106
+ let body = `${label.padEnd(LABEL_W)} ${value}`;
107
+ if (displayWidth(body) + displayWidth(suffix) > budget) {
108
+ body = truncateToWidth(body, budget, '');
109
+ suffix = '';
110
+ }
111
+ const dim = suffix ? `${c.dim}${suffix}${c.reset}` : '';
112
+ return cell(`${body}${dim}`);
113
+ };
114
+ const cacheSuffix =
115
+ s.inputTokens > 0 && s.cachedTokens > 0
116
+ ? ` ${formatCacheHit(s.cachedTokens, s.inputTokens)}`
117
+ : '';
69
118
  lines.push(
70
- `${surface.sidebar.itemAccent}Info${c.reset}`,
71
- `↑${formatTokens(s.inputTokens)}${s.inputTokens > 0 && s.cachedTokens > 0 ? ` ${c.dim}${formatCacheHit(s.cachedTokens, s.inputTokens)}${c.reset}` : ''}`,
72
- `↓${formatTokens(s.outputTokens)}`,
73
- `${formatCost(s.cost)}${s.priced ? '' : `${c.dim} (unpriced)${c.reset}`}`,
74
- `${s.contextPct}%`,
119
+ `${wall('┌')} ${surface.sidebar.itemAccent}Info${c.reset} ${dashes(inner - 6)}${wall('┐')}`,
120
+ `${wall('├')}${dashes(inner)}${wall('┤')}`,
121
+ row('↑ input', formatTokens(s.inputTokens), cacheSuffix),
122
+ row('↓ output', formatTokens(s.outputTokens)),
123
+ row('$ cost', formatCost(s.cost), s.priced ? '' : ' (unpriced)'),
124
+ row(
125
+ '◔ context',
126
+ `${formatTokens(s.ctxTokens)}${s.contextLimit ? `/${formatTokens(s.contextLimit)}` : ''}`,
127
+ ` (${s.contextPct}%)`,
128
+ ),
129
+ `${wall('└')}${dashes(inner)}${wall('┘')}`,
75
130
  '',
76
131
  );
77
132
 
@@ -82,7 +137,13 @@ export class Sidebar implements Component {
82
137
  } else {
83
138
  const sorted = [...state.extensions].sort((a, b) => a.name.localeCompare(b.name));
84
139
  for (const ext of sorted) {
85
- const dot = ext.active ? `${surface.sidebar.item}●${c.reset}` : `${c.red}●${c.reset}`;
140
+ // Grey for "loaded but inert" (no key) — a deliberate state, not an
141
+ // error. Red is reserved for an extension that actually broke.
142
+ const dot = ext.active
143
+ ? `${surface.sidebar.item}●${c.reset}`
144
+ : ext.status === 'failed'
145
+ ? `${c.red}●${c.reset}`
146
+ : `${c.dim}○${c.reset}`;
86
147
  lines.push(`${dot} ${truncate(ext.name, w - 5)}`);
87
148
  }
88
149
  }
@@ -128,6 +189,12 @@ export class Sidebar implements Component {
128
189
  }
129
190
 
130
191
  render(width: number): string[] {
192
+ // Keep the layout in sync with the width the compositor actually renders
193
+ // at (tests and narrower overlays pass a different width than SIDEBAR_WIDTH).
194
+ if (width !== this.w) {
195
+ this.w = width;
196
+ this.refresh();
197
+ }
131
198
  // Panel fill behind every row — single choke point; bg '' (vanilla)
132
199
  // passes through byte-identical. Status line and editor rows paint no
133
200
  // panel: their GitHub bg is the canvas #0d1117 itself, so they sit
@@ -1,11 +1,11 @@
1
1
  /**
2
- * StatusLine — a single-line pi-tui component whose text can be replaced.
2
+ * StatusLine — a single-line component whose text can be replaced.
3
3
  *
4
4
  * Rendering-only: `main()` owns what the text says.
5
5
  */
6
6
 
7
- import {truncateToWidth} from '@earendil-works/pi-tui';
8
- import type {Component} from '@earendil-works/pi-tui';
7
+ import {truncateToWidth} from '../tui/tty-width.js';
8
+ import type {Component} from '../tui/types.js';
9
9
 
10
10
  export class StatusLine implements Component {
11
11
  private _text: string;
@@ -1,133 +1,10 @@
1
1
  /**
2
- * CLI configuration.
2
+ * CLI config facade.
3
3
  *
4
- * Values come from environment variables, then `~/.pal/config.json`, then
5
- * built-in defaults. Invalid values are reported and ignored rather than
6
- * silently producing NaN (which previously flowed into retry backoff and the
7
- * context limit).
4
+ * The config shape, defaults, env parsing and permission cache live in
5
+ * `@pal-code/core`; this module only re-exports them so existing CLI imports
6
+ * keep working.
8
7
  */
9
8
 
10
- import {readPalConfig, loadPermissionConfig} from '@pal-code/core';
11
- import type {PermissionConfig} from '@pal-code/core';
12
-
13
- export interface Config {
14
- model: string;
15
- systemPrompt: string;
16
- maxToolRounds: number;
17
- maxRetries: number;
18
- retryBaseMs: number;
19
- contextLimit: number;
20
- reasoningEffort: 'low' | 'medium' | 'high';
21
- /** Extension package names to load (default: ['@pal-code/web-search']). */
22
- extensions: string[];
23
- }
24
-
25
- const DEFAULT_SYSTEM_PROMPT = [
26
- "pal — a terminal coding agent working in the user's project.",
27
- 'TOOLS: Never guess about files — read them. Batch independent tool calls in one response.',
28
- 'PLAN: For any task needing more than ~2 steps, call `todo` first with the full list and update it as you progress. Keep exactly one item in_progress.',
29
- 'VERIFY: After editing code, run `verify` to confirm nothing broke.',
30
- "DON'T LOOP: Never repeat a tool call with identical arguments — it cannot give a different result. If something fails twice, change approach or report the blocker.",
31
- 'STOP: Once every todo item is done and the request is satisfied, stop calling tools and reply. Do not re-read files you already have.',
32
- 'DELEGATE: For broad multi-file exploration, use `delegate` to keep your own context small.',
33
- 'Windows shell: the bash tool ALREADY runs inside cmd.exe. Write native commands directly (`dir`, `type`, `findstr`, `where`) and NEVER prefix them with `cmd /c`. Unix commands (`ls`, `cat`, `grep`, `head`, `rm`) do not exist here. Keep commands to a single line without `&&` chains when possible. Be concise; show code only when asked.',
34
- ].join('\n');
35
-
36
- const EFFORTS = ['low', 'medium', 'high'] as const;
37
-
38
- /** Parse a non-negative integer env var, warning and falling back when invalid. */
39
- function intEnv(name: string, fallback: number, min = 0): number {
40
- const raw = process.env[name]?.trim();
41
- if (!raw) return fallback;
42
- if (!/^\d+$/.test(raw)) {
43
- console.error(`pal: ignoring invalid ${name}=${JSON.stringify(raw)} — using ${fallback}`);
44
- return fallback;
45
- }
46
- const n = Number.parseInt(raw, 10);
47
- if (n < min) {
48
- console.error(`pal: ${name}=${n} is below the minimum ${min} — using ${fallback}`);
49
- return fallback;
50
- }
51
- return n;
52
- }
53
-
54
- function effortEnv(): 'low' | 'medium' | 'high' {
55
- const raw = process.env.REASONING_EFFORT;
56
- if (raw === undefined || raw === '') return 'medium';
57
- if ((EFFORTS as readonly string[]).includes(raw)) return raw as (typeof EFFORTS)[number];
58
- console.error(`pal: ignoring invalid REASONING_EFFORT=${JSON.stringify(raw)} — using medium`);
59
- return 'medium';
60
- }
61
-
62
- function strEnv(name: string, fallback: string): string {
63
- const raw = process.env[name];
64
- return raw && raw.trim() ? raw : fallback;
65
- }
66
-
67
- /**
68
- * Read a positive integer out of a config file value.
69
- *
70
- * Returns undefined for anything that isn't a finite number at or above `min`,
71
- * so a typo in `~/.pal/config.json` falls through to the default rather than
72
- * poisoning the context limit with NaN (which would disable compaction).
73
- */
74
- function intConfig(value: unknown, label: string, min = 1000): number | undefined {
75
- if (typeof value !== 'number' || !Number.isFinite(value) || value < min) {
76
- if (value !== undefined) {
77
- console.error(
78
- `pal: ignoring invalid ${label}=${JSON.stringify(value)} in config.json — must be a number >= ${min}`,
79
- );
80
- }
81
- return undefined;
82
- }
83
- return Math.floor(value);
84
- }
85
-
86
- export function loadConfig(): Config {
87
- const saved = readPalConfig();
88
- const savedModel =
89
- typeof saved.model === 'string' && saved.model.trim() ? saved.model : undefined;
90
- const savedPrompt =
91
- typeof saved.systemPrompt === 'string' && saved.systemPrompt.trim()
92
- ? saved.systemPrompt
93
- : undefined;
94
-
95
- // Extensions: use saved list or default to the shipped set.
96
- const savedExtensions = Array.isArray(saved.extensions) ? saved.extensions : undefined;
97
- const extensions = savedExtensions ?? [
98
- '@pal-code/web-search',
99
- '@pal-code/agents',
100
- '@pal-code/mcp',
101
- ];
102
-
103
- // Context limit: env wins, then config.json, then the built-in default.
104
- const savedContextLimit = intConfig(saved.contextLimit, 'contextLimit');
105
-
106
- return {
107
- model: strEnv('MODEL', strEnv('PAL_MODEL', savedModel ?? 'deepseek/deepseek-chat')),
108
- systemPrompt: strEnv('SYSTEM_PROMPT', savedPrompt ?? DEFAULT_SYSTEM_PROMPT),
109
- maxToolRounds: intEnv('MAX_TOOL_ROUNDS', 100, 1),
110
- maxRetries: intEnv('MAX_RETRIES', 1, 0),
111
- retryBaseMs: intEnv('RETRY_BASE_MS', 2000, 0),
112
- contextLimit: intEnv('CONTEXT_LIMIT', savedContextLimit ?? 100_000, 1000),
113
- reasoningEffort: effortEnv(),
114
- extensions,
115
- };
116
- }
117
-
118
- // ── Permissions ──────────────────────────────────────────────────────────────
119
-
120
- let _cachedPermissions: PermissionConfig | null = null;
121
-
122
- /** Load and cache the merged permission config. Clears cache on /reload. */
123
- export function loadPermissions(): PermissionConfig {
124
- if (!_cachedPermissions) {
125
- _cachedPermissions = loadPermissionConfig();
126
- }
127
- return _cachedPermissions;
128
- }
129
-
130
- /** Clear permission cache (for /reload or testing). */
131
- export function clearPermissionsCache(): void {
132
- _cachedPermissions = null;
133
- }
9
+ export {loadConfig, loadPermissions, clearPermissionsCache} from '@pal-code/core';
10
+ export type {Config} from '@pal-code/core';