pal-code 0.0.17 → 0.0.19

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
@@ -50,8 +50,8 @@ bun add -g pal-code
50
50
  pal
51
51
  ```
52
52
 
53
- On first launch, pal-code runs a short setup wizard. Pick a provider and paste an API
54
- key (or press Enter for a keyless provider like OpenCode Zen).
53
+ On first launch, pal-code runs a short setup wizard. Pick a provider (OpenCode Zen
54
+ included) and paste an API key.
55
55
 
56
56
  ## Features
57
57
 
@@ -60,8 +60,8 @@ key (or press Enter for a keyless provider like OpenCode Zen).
60
60
  - **Tool use** — read/write/edit files, run shell commands, grep/glob/ast-grep
61
61
  search, repo maps, `verify`, and `delegate` sub-agents.
62
62
  - **BYOK provider registry** with key-shape detection, live `/models` fetching,
63
- curated fallback model lists, and retry/backoff with quota-vs-rate-limit-aware
64
- fallback switching.
63
+ curated fallback model lists, and retry/backoff. Model rotation on failure is
64
+ opt-in (`/rotation`), with quota-vs-rate-limit-aware switching.
65
65
  - **Safety & context** — `.pal.json` ignore patterns, file-size limits, file
66
66
  snapshots for `/undo`, context compaction, and secret-redacting debug logs.
67
67
  - **Sessions** — SQLite-backed (`bun:sqlite`) with resume via `/sessions` or
@@ -96,11 +96,13 @@ MCP config is stored in `~/.pal/mcp.json` (user-level) or `./mcp.json` (project-
96
96
  API keys are resolved from (in order):
97
97
 
98
98
  1. Environment variables — `DEEPSEEK_API_KEY`, `GEMINI_API_KEY`,
99
- `OPENROUTER_API_KEY`, `ZEN_API_KEY`, `OPENAI_API_KEY`, `GROQ_API_KEY`,
99
+ `OPENROUTER_API_KEY`, `OPENCODE_API_KEY`, `OPENAI_API_KEY`, `GROQ_API_KEY`,
100
100
  `XAI_API_KEY`, `MISTRAL_API_KEY`.
101
101
  2. `~/.pal/config.json` — `{ "keys": { "<provider>": "<key>" } }`.
102
102
 
103
- Keyless providers are opted into by setting `"keyless": "<provider-id>"`.
103
+ Custom providers in `~/.pal/providers.json` can opt into keyless access with
104
+ `keyOptional: true`; set `"keyless": "<provider-id>"` to select one. A real key
105
+ saved for that provider always takes precedence and clears the keyless flag.
104
106
 
105
107
  Non-key settings can also live in `~/.pal/config.json` — for example
106
108
  `"model"`, `"systemPrompt"`, `"extensions"`, and `"contextLimit"`. A
@@ -130,6 +132,7 @@ All user data lives in `~/.pal/`:
130
132
  | `/model NAME` | Set a model directly |
131
133
  | `/key` | Set an API key interactively |
132
134
  | `/keys` | Show configured keys |
135
+ | `/rotation [on\|off]` | Toggle automatic model switching on failure |
133
136
  | `/sessions` / `/resume ID` | List / resume sessions |
134
137
  | `/snapshots` / `/undo [id]` | Restore a pre-edit file |
135
138
  | `/compact` | Compress conversation context |
package/SYSTEM.md CHANGED
@@ -89,8 +89,11 @@ runWithFallback → decides which model, retries, backoff (core)
89
89
  └─ runAgent → drives that model to completion (core)
90
90
  ```
91
91
 
92
- - **Same provider first** (same rate-limit pool), then other configured
93
- providers — the candidate list is built from each provider's live `/models`,
92
+ - **Rotation is opt-in** (`rotate`; `/rotation on`). By default the selected
93
+ model is retried and the turn reports the failure — it never switches models
94
+ silently.
95
+ - **When enabled** — same provider first (same rate-limit pool), then other
96
+ configured providers. Candidates come from each provider's live `/models`,
94
97
  never from invented names.
95
98
  - **Quota exhausted** → switch immediately (retrying only burns RPM).
96
99
  - **Rate limited** → exponential backoff, `maxRetries` attempts, then switch.
@@ -139,6 +142,18 @@ bun test # run the test suite
139
142
  bunx tsc --noEmit # typecheck
140
143
  ```
141
144
 
145
+ ### List selection
146
+
147
+ Any flow that asks the user to pick from a list uses a filterable arrow-key
148
+ selector, never a numbered text prompt:
149
+
150
+ - Inside the TUI: `packages/cli/src/overlays/select.ts` (`showSelectOverlay`,
151
+ built on pi-tui's `SelectList`).
152
+ - Before the TUI exists: `packages/cli/src/prompt/select.ts` (`promptSelect`,
153
+ raw stdin + ANSI, no pi-tui).
154
+
155
+ Piped/non-TTY runs fall back to numbered input.
156
+
142
157
  ## See also
143
158
 
144
159
  - [`README.md`](./README.md) — what pal is, install, commands
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pal-code",
3
- "version": "0.0.17",
3
+ "version": "0.0.19",
4
4
  "description": "A terminal coding agent with BYOK, tool use, and extensions",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -31,7 +31,7 @@
31
31
  "dev": "cd packages/cli && bun src/index.ts",
32
32
  "test": "bun test",
33
33
  "eval": "bun run evals/run.ts",
34
- "typecheck": "bunx tsc --noEmit",
34
+ "typecheck": "bunx tsc --noEmit && bun run --cwd packages/ui web:typecheck",
35
35
  "lint": "biome check .",
36
36
  "lint:fix": "biome check --write .",
37
37
  "format": "biome format --write .",
@@ -42,11 +42,14 @@
42
42
  "build:linux-x64": "bun build --compile packages/cli/src/index.ts --target=bun-linux-x64 --outfile dist/pal-linux-x64",
43
43
  "build:linux-arm64": "bun build --compile packages/cli/src/index.ts --target=bun-linux-arm64 --outfile dist/pal-linux-arm64",
44
44
  "build:windows-x64": "bun build --compile packages/cli/src/index.ts --target=bun-windows-x64 --outfile dist/pal-windows-x64.exe",
45
- "publish:all": "npm run publish:core && npm publish && npm run publish:web-search && npm run publish:agents && npm run publish:mcp",
45
+ "publish:all": "npm run publish:core && npm publish && npm run publish:web-search && npm run publish:agents && npm run publish:mcp && npm run publish:jev && npm run publish:memory && npm run publish:workflow",
46
46
  "publish:core": "cd packages/core && npm publish",
47
47
  "publish:web-search": "cd packages/web-search && npm publish",
48
48
  "publish:agents": "cd packages/agents && npm publish",
49
49
  "publish:mcp": "cd packages/mcp && npm publish",
50
+ "publish:jev": "cd packages/jev && npm publish",
51
+ "publish:memory": "cd packages/memory && npm publish",
52
+ "publish:workflow": "cd packages/workflow && npm publish",
50
53
  "prepublishOnly": "node scripts/sync-version.js"
51
54
  },
52
55
  "keywords": [
@@ -62,8 +65,10 @@
62
65
  "gemini"
63
66
  ],
64
67
  "dependencies": {
65
- "@pal-code/core": "0.0.17",
66
- "@earendil-works/pi-tui": "^0.85.1"
68
+ "@pal-code/core": "0.0.19",
69
+ "@earendil-works/pi-tui": "^0.85.1",
70
+ "get-east-asian-width": "1.6.0",
71
+ "marked": "^18.1.3"
67
72
  },
68
73
  "devDependencies": {
69
74
  "@biomejs/biome": "^2.5.13",
@@ -0,0 +1,66 @@
1
+ /**
2
+ * TUI adapter for core's `AgentUi` port. This is the only place the turn
3
+ * orchestrator touches RunView and the sidebar-facing app state.
4
+ */
5
+
6
+ import type {AgentUi, Approval} from '@pal-code/core';
7
+ import type {Container, TUI} from '@earendil-works/pi-tui';
8
+
9
+ import {RunView} from './components/run-view.js';
10
+ import {state} from './state.js';
11
+ import {checkToolPermission} from './utils/permissions.js';
12
+
13
+ export function createTuiAgentUi(tui: TUI, container: Container): AgentUi {
14
+ let run: RunView | null = null;
15
+
16
+ return {
17
+ startRun(model) {
18
+ run = new RunView(container, tui, model);
19
+ state.activeRun = run;
20
+ },
21
+ setModel(model) {
22
+ run?.setModel(model);
23
+ },
24
+ beginRound(round, max) {
25
+ run?.beginRound(round, max);
26
+ },
27
+ text(delta) {
28
+ run?.streamText(delta);
29
+ },
30
+ thinking(delta) {
31
+ run?.streamThinking(delta);
32
+ },
33
+ toolStart(id, name, argsSummary) {
34
+ run?.addTool(id, name, argsSummary);
35
+ },
36
+ toolEnd(id, ok, content) {
37
+ run?.endTool(id, ok, content);
38
+ },
39
+ notice(text) {
40
+ run?.notice(text);
41
+ },
42
+ aborted() {
43
+ run?.aborted();
44
+ },
45
+ extensions(extensions) {
46
+ state.extensions = extensions;
47
+ },
48
+ mcpServers(servers) {
49
+ state.mcpServers = servers;
50
+ },
51
+ primary(name) {
52
+ state.currentAgentRole = name;
53
+ },
54
+ ready() {
55
+ state.refreshSidebar();
56
+ state.refreshStatusLine();
57
+ state.refreshRoleIndicator();
58
+ },
59
+ };
60
+ }
61
+
62
+ /** Route core's approval request through the TUI permission gate. */
63
+ export const approveTool: Approval = async (toolName, args) => {
64
+ const decision = await checkToolPermission(toolName, args);
65
+ return decision.allowed ? 'allow' : 'deny';
66
+ };
@@ -40,6 +40,25 @@ export const REGISTRY: ExtRegistryEntry[] = [
40
40
  package: '@pal-code/mcp',
41
41
  tags: ['mcp', 'model context protocol', 'server', 'bridge', 'integrations'],
42
42
  },
43
+ {
44
+ name: 'Memory',
45
+ description:
46
+ 'Repo knowledge the agent reads before re-exploring: schemas, playbooks, past runs',
47
+ package: '@pal-code/memory',
48
+ tags: ['memory', 'knowledge', 'schema', 'playbook', 'context', 'notes', 'handoff'],
49
+ },
50
+ {
51
+ name: 'Jev',
52
+ description: 'Calibrated yes/no, choice and rubric judgments over OpenCode Zen',
53
+ package: '@pal-code/jev',
54
+ tags: ['jev', 'judgment', 'decision', 'classify', 'score', 'calibration', 'zen'],
55
+ },
56
+ {
57
+ name: 'Workflow',
58
+ description: 'Task continuity: work folders, a durable backlog, session guardrails',
59
+ package: '@pal-code/workflow',
60
+ tags: ['workflow', 'work', 'backlog', 'handoff', 'todo', 'continuity', 'session'],
61
+ },
43
62
  ];
44
63
 
45
64
  /** ANSI codes used when rendering the browse list (omit for plain text). */
@@ -12,9 +12,9 @@
12
12
 
13
13
  import {homedir} from 'node:os';
14
14
  import {join} from 'node:path';
15
- import {existsSync, mkdirSync, writeFileSync} from 'node:fs';
15
+ import {existsSync, mkdirSync, readdirSync, writeFileSync} from 'node:fs';
16
16
  import {execSync} from 'node:child_process';
17
- import {readPalConfig, saveSetting} from '@pal-code/core';
17
+ import {DEFAULT_EXTENSIONS, readPalConfig, saveSetting} from '@pal-code/core';
18
18
 
19
19
  import {formatBrowse} from './ext-registry.js';
20
20
 
@@ -37,9 +37,19 @@ function ensureExtensionsDir(): void {
37
37
  }
38
38
  }
39
39
 
40
- function getExtensions(): string[] {
40
+ /**
41
+ * The configured extension list, defaulting to the shipped set.
42
+ *
43
+ * Must not fall back to `[]`: `extAdd` pushes onto whatever this returns and
44
+ * saves it, so an empty default would replace the whole shipped set with the
45
+ * single package being added. One `pal add jev` would silently disable
46
+ * web-search, agents, mcp, memory and workflow — the user would see a list of
47
+ * one and assume the rest were never installed.
48
+ */
49
+ export function getExtensions(): string[] {
41
50
  const config = readPalConfig();
42
- return Array.isArray(config.extensions) ? (config.extensions as string[]) : [];
51
+ if (Array.isArray(config.extensions)) return config.extensions as string[];
52
+ return [...DEFAULT_EXTENSIONS];
43
53
  }
44
54
 
45
55
  export interface ExtCommandResult {
@@ -154,11 +164,79 @@ async function lookupNpmPackage(pkg: string): Promise<'found' | 'missing' | 'unk
154
164
  }
155
165
  }
156
166
 
167
+ /**
168
+ * Package names physically present in `~/.pal/extensions/node_modules`.
169
+ *
170
+ * `/ext list` needs this because the loaded-extension list only ever contains
171
+ * packages pal was *asked* to load (the defaults plus `config.json`). A package
172
+ * installed with `bun add` by hand, or one that dropped out of the config, is
173
+ * invisible there — which reads to the user as "my install vanished".
174
+ *
175
+ * Best-effort and never throws: a missing directory means nothing is installed.
176
+ */
177
+ export function listInstalledExtensions(root: string = EXTENSIONS_DIR): string[] {
178
+ const modulesDir = join(root, 'node_modules');
179
+ if (!existsSync(modulesDir)) return [];
180
+
181
+ const names: string[] = [];
182
+ try {
183
+ for (const entry of readdirSync(modulesDir, {withFileTypes: true})) {
184
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
185
+
186
+ // A scope directory holds the real packages one level down.
187
+ if (entry.name.startsWith('@')) {
188
+ for (const inner of readdirSync(join(modulesDir, entry.name), {withFileTypes: true})) {
189
+ if (inner.isDirectory() && !inner.name.startsWith('.')) {
190
+ names.push(`${entry.name}/${inner.name}`);
191
+ }
192
+ }
193
+ continue;
194
+ }
195
+
196
+ names.push(entry.name);
197
+ }
198
+ } catch {
199
+ return names;
200
+ }
201
+
202
+ return names.sort();
203
+ }
204
+
205
+ /** npm package for an extension name, e.g. `jev` → `@pal-code/jev`. */
206
+ function scopedGuess(name: string): string {
207
+ return `@pal-code/${name}`;
208
+ }
209
+
210
+ /**
211
+ * Suggest the `@pal-code/*` package for a bare name, when one exists.
212
+ *
213
+ * Returns undefined when the name is already scoped, or when no scoped
214
+ * counterpart is published. Exported so the guard can be tested without
215
+ * running a real install.
216
+ */
217
+ export async function suggestScopedPackage(pkg: string): Promise<string | undefined> {
218
+ if (pkg.startsWith('@')) return undefined;
219
+ const scoped = scopedGuess(pkg);
220
+ return (await lookupNpmPackage(scoped)) === 'found' ? scoped : undefined;
221
+ }
222
+
157
223
  export async function extAdd(pkg: string): Promise<ExtCommandResult> {
158
224
  if (!NPM_NAME_RE.test(pkg)) {
159
225
  return {ok: false, message: `Invalid package name: ${pkg}`};
160
226
  }
161
227
 
228
+ // A bare name is almost never a pal extension, and the collision is silent:
229
+ // `jev` exists on npm as an unrelated 2021 stub, so `pal add jev` would
230
+ // install that and report a confusing red "failed". If the scoped package
231
+ // exists, point at it instead of installing the wrong thing.
232
+ const scoped = await suggestScopedPackage(pkg);
233
+ if (scoped) {
234
+ return {
235
+ ok: false,
236
+ message: `"${pkg}" is not a pal extension — did you mean "${scoped}"?`,
237
+ };
238
+ }
239
+
162
240
  // Validate against npm before installing; on registry/network failure fall
163
241
  // through to `bun add` so offline installs still work (bun will 404 itself).
164
242
  const lookup = await lookupNpmPackage(pkg);
@@ -11,20 +11,40 @@ import type {TUI, Container} from '@earendil-works/pi-tui';
11
11
  import {c} from './theme.js';
12
12
  import {formatTokens, formatCost} from './utils/cost.js';
13
13
  import {isDebugEnabled} from '@pal-code/core';
14
+ import {visibleCommands} from './slash-commands.js';
14
15
 
15
16
  export function cmdHelp(container: Container, tui: TUI): void {
17
+ const commands = visibleCommands(isDebugEnabled());
18
+ const labels = commands.map((cmd) => `/${cmd.name}${cmd.usage ? ` ${cmd.usage}` : ''}`);
19
+ const labelWidth = Math.max(...labels.map((label) => label.length)) + 2;
20
+ const detailWidth =
21
+ Math.max(
22
+ 0,
23
+ ...commands.flatMap((cmd) =>
24
+ (cmd.details ?? []).map((detail) => `/${cmd.name} ${detail.usage}`.length),
25
+ ),
26
+ ) + 2;
27
+
16
28
  container.addChild(new Text('', 0, 0));
17
29
  container.addChild(new Text(` ${c.bold}Available commands:${c.reset}`, 1, 0));
18
- container.addChild(new Text(` ${c.cyan}/help${c.reset} Show this help message`, 1, 0));
19
- container.addChild(new Text(` ${c.cyan}/exit${c.reset} Save session and quit`, 1, 0));
20
- container.addChild(new Text(` ${c.cyan}/new${c.reset} Start a new session`, 1, 0));
21
- container.addChild(new Text(` ${c.cyan}/sessions${c.reset} List recent sessions`, 1, 0));
22
- container.addChild(
23
- new Text(` ${c.cyan}/undo${c.reset} Restore the file from your last edit`, 1, 0),
24
- );
25
- container.addChild(
26
- new Text(` ${c.cyan}/snapshots${c.reset} List recent file snapshots`, 1, 0),
27
- );
30
+ for (const [i, cmd] of commands.entries()) {
31
+ container.addChild(
32
+ new Text(` ${c.cyan}${labels[i].padEnd(labelWidth)}${c.reset}${cmd.description}`, 1, 0),
33
+ );
34
+ for (const detail of cmd.details ?? []) {
35
+ const prefix = `/${cmd.name} ${detail.usage}`;
36
+ container.addChild(
37
+ new Text(
38
+ ` ${c.cyan}${prefix.padEnd(detailWidth)}${c.reset}${detail.description}`,
39
+ 1,
40
+ 0,
41
+ ),
42
+ );
43
+ }
44
+ }
45
+
46
+ container.addChild(new Text('', 0, 0));
47
+ container.addChild(new Text(` ${c.bold}Keys:${c.reset}`, 1, 0));
28
48
  container.addChild(
29
49
  new Text(` ${c.cyan}ctrl+b${c.reset} Toggle background agent panel`, 1, 0),
30
50
  );
@@ -32,97 +52,7 @@ export function cmdHelp(container: Container, tui: TUI): void {
32
52
  container.addChild(
33
53
  new Text(` ${c.cyan}esc${c.reset} Interrupt the running turn`, 1, 0),
34
54
  );
35
- container.addChild(new Text(` ${c.cyan}/resume ID${c.reset} Load a previous session`, 1, 0));
36
- container.addChild(
37
- new Text(` ${c.cyan}/cost${c.reset} Show token usage and estimated cost`, 1, 0),
38
- );
39
- container.addChild(
40
- new Text(
41
- ` ${c.cyan}/model${c.reset} Open model selector (arrow keys + type to filter)`,
42
- 1,
43
- 0,
44
- ),
45
- );
46
- container.addChild(new Text(` ${c.cyan}/model NAME${c.reset} Set model directly`, 1, 0));
47
- container.addChild(
48
- new Text(` ${c.cyan}/key${c.reset} Set API key interactively`, 1, 0),
49
- );
50
- container.addChild(
51
- new Text(
52
- ` ${c.cyan}/export${c.reset} [file] Export config to JSON (secrets excluded)`,
53
- 1,
54
- 0,
55
- ),
56
- );
57
- container.addChild(
58
- new Text(` ${c.cyan}/import${c.reset} <file> Merge an export (local API keys kept)`, 1, 0),
59
- );
60
- container.addChild(
61
- new Text(` ${c.cyan}/roles${c.reset} List agent roles (agents extension)`, 1, 0),
62
- );
63
- container.addChild(
64
- new Text(
65
- ` ${c.cyan}/plan${c.reset} [task] Enter read-only plan mode (Tab also cycles)`,
66
- 1,
67
- 0,
68
- ),
69
- );
70
- container.addChild(
71
- new Text(` ${c.cyan}/execute${c.reset} Leave plan mode and implement`, 1, 0),
72
- );
73
- container.addChild(
74
- new Text(` ${c.cyan}/ext add${c.reset} <pkg> Install an extension from npm`, 1, 0),
75
- );
76
- container.addChild(
77
- new Text(` ${c.cyan}/ext remove${c.reset} <pkg> Remove an extension`, 1, 0),
78
- );
79
- container.addChild(
80
- new Text(
81
- ` ${c.cyan}/ext search${c.reset} <q> Search the npm registry for extensions`,
82
- 1,
83
- 0,
84
- ),
85
- );
86
- container.addChild(
87
- new Text(` ${c.cyan}/ext list${c.reset} List loaded extensions`, 1, 0),
88
- );
89
- container.addChild(
90
- new Text(` ${c.cyan}/ext browse${c.reset} Browse curated extensions`, 1, 0),
91
- );
92
- container.addChild(
93
- new Text(` ${c.cyan}/mcp add${c.reset} <name> <cmd> [args] Add a local MCP server`, 1, 0),
94
- );
95
- container.addChild(
96
- new Text(` ${c.cyan}/mcp add-remote${c.reset} <name> <url> Add a remote MCP server`, 1, 0),
97
- );
98
- container.addChild(
99
- new Text(` ${c.cyan}/mcp remove${c.reset} <name> Remove an MCP server`, 1, 0),
100
- );
101
- container.addChild(new Text(` ${c.cyan}/mcp list${c.reset} List MCP servers`, 1, 0));
102
- container.addChild(
103
- new Text(` ${c.cyan}/mcp browse${c.reset} Browse curated MCP servers`, 1, 0),
104
- );
105
- container.addChild(
106
- new Text(` ${c.cyan}/mcp search${c.reset} <q> Search curated MCP servers`, 1, 0),
107
- );
108
- container.addChild(
109
- new Text(` ${c.cyan}/permission${c.reset} Show permission rules and whitelist`, 1, 0),
110
- );
111
- container.addChild(
112
- new Text(
113
- ` ${c.cyan}/copy${c.reset} [code] Copy last reply (or code block) to clipboard`,
114
- 1,
115
- 0,
116
- ),
117
- );
118
- if (isDebugEnabled()) {
119
- container.addChild(
120
- new Text(` ${c.cyan}/reload${c.reset} Hot-reload extensions (dev)`, 1, 0),
121
- );
122
- container.addChild(
123
- new Text(` ${c.cyan}/restart${c.reset} Restart pal (saves session first)`, 1, 0),
124
- );
125
- }
55
+
126
56
  container.addChild(new Text('', 0, 0));
127
57
  container.addChild(new Text(` ${c.bold}Scroll transcript:${c.reset}`, 1, 0));
128
58
  container.addChild(
@@ -13,7 +13,8 @@
13
13
  * through `setHovered`/`setSuccess`, never sampled from input devices.
14
14
  */
15
15
 
16
- import {Markdown, type Component} from '@earendil-works/pi-tui';
16
+ import {Markdown} from '../tui/render/markdown.js';
17
+ import type {Component} from '../tui/types.js';
17
18
 
18
19
  import {markdownTheme} from '../theme.js';
19
20
  import {
@@ -6,7 +6,7 @@
6
6
  * messages instead of leaving them at their submit-time width.
7
7
  */
8
8
 
9
- import type {Component} from '@earendil-works/pi-tui';
9
+ import type {Component} from '../tui/types.js';
10
10
 
11
11
  import {userMessageBox} from '../tui/render/format.js';
12
12
  import type {AgentRole} from '../state.js';
@@ -7,7 +7,7 @@
7
7
  */
8
8
 
9
9
  import {Text} from '../tui/components/text.js';
10
- import type {Component} from '@earendil-works/pi-tui';
10
+ import type {Component} from '../tui/types.js';
11
11
 
12
12
  import {c, surface} from '../theme.js';
13
13
  import {paintPanel} from '../tui/surface/paint-panel.js';
@@ -137,7 +137,13 @@ export class Sidebar implements Component {
137
137
  } else {
138
138
  const sorted = [...state.extensions].sort((a, b) => a.name.localeCompare(b.name));
139
139
  for (const ext of sorted) {
140
- 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}`;
141
147
  lines.push(`${dot} ${truncate(ext.name, w - 5)}`);
142
148
  }
143
149
  }
@@ -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 ?? 200_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';