pal-code 0.0.10 → 0.0.12

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.
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Portable config schema for `pal export` / `pal import` (config as code).
3
+ *
4
+ * This module owns the boundary: it parses untrusted export files into a typed
5
+ * document, and sanitizes local config into an exportable one. Key material is
6
+ * stripped here — nothing in this file may carry secrets across the boundary.
7
+ */
8
+
9
+ export const EXPORT_VERSION = 1;
10
+
11
+ export interface PortableProject {
12
+ ignore?: string[];
13
+ ignoreLargeFiles?: boolean;
14
+ maxFileSizeKB?: number;
15
+ readLineLimit?: number;
16
+ }
17
+
18
+ export interface PortableConfig {
19
+ version: number;
20
+ settings?: Record<string, unknown>;
21
+ providers?: Record<string, unknown>[];
22
+ hooks?: unknown;
23
+ agents?: unknown;
24
+ skills?: unknown;
25
+ project?: PortableProject;
26
+ }
27
+
28
+ /** Top-level config.json fields that are key material and must never leave the machine. */
29
+ const SECRET_SETTING_FIELDS = new Set([
30
+ 'keys',
31
+ 'apiKey',
32
+ 'geminiApiKey',
33
+ 'token',
34
+ 'secret',
35
+ 'accessToken',
36
+ 'refreshToken',
37
+ ]);
38
+
39
+ /** Provider fields that hold key material (or could). */
40
+ const SECRET_PROVIDER_FIELDS = new Set([
41
+ 'key',
42
+ 'auth',
43
+ 'authorization',
44
+ 'credentials',
45
+ 'password',
46
+ 'api_key',
47
+ 'access_token',
48
+ 'refresh_token',
49
+ 'client_secret',
50
+ ]);
51
+
52
+ /** Lower-cased union used for field-name checks and secret-value collection. */
53
+ const SECRET_FIELD_NAMES = new Set(
54
+ [...SECRET_SETTING_FIELDS, ...SECRET_PROVIDER_FIELDS].map((name) => name.toLowerCase()),
55
+ );
56
+
57
+ /** Header names whose values are redacted (Authorization, X-API-Key, ...). */
58
+ const SECRET_HEADER_RE = /auth|key|token|secret|bearer|password/i;
59
+
60
+ /** config.json fields whose types are checked on import; unknown fields pass through. */
61
+ const SETTING_TYPES: Record<string, 'string' | 'number' | 'boolean' | 'string[]' | 'object'> = {
62
+ model: 'string',
63
+ systemPrompt: 'string',
64
+ reasoningEffort: 'string',
65
+ contextLimit: 'number',
66
+ maxToolRounds: 'number',
67
+ maxRetries: 'number',
68
+ retryBaseMs: 'number',
69
+ keyless: 'string',
70
+ extensions: 'string[]',
71
+ hooks: 'object',
72
+ agents: 'object',
73
+ skills: 'object',
74
+ };
75
+
76
+ export const HOOKS_LIKE_FIELDS = ['hooks', 'agents', 'skills'] as const;
77
+
78
+ const HOOKS_LIKE_SET: ReadonlySet<string> = new Set<string>(HOOKS_LIKE_FIELDS);
79
+
80
+ export function isHooksLike(name: string): boolean {
81
+ return HOOKS_LIKE_SET.has(name);
82
+ }
83
+
84
+ export const PROJECT_FIELDS = [
85
+ 'ignore',
86
+ 'ignoreLargeFiles',
87
+ 'maxFileSizeKB',
88
+ 'readLineLimit',
89
+ ] as const;
90
+
91
+ export function isRecord(value: unknown): value is Record<string, unknown> {
92
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
93
+ }
94
+
95
+ /** True when a config field name denotes key material (case-insensitive). */
96
+ export function isSecretField(name: string): boolean {
97
+ return SECRET_FIELD_NAMES.has(name.toLowerCase());
98
+ }
99
+
100
+ /** Every string found under a secret-bearing field name (candidate secret values). */
101
+ export function collectSecretStrings(value: unknown, secretName: boolean): string[] {
102
+ if (typeof value === 'string') return secretName && value ? [value] : [];
103
+ if (Array.isArray(value)) return value.flatMap((v) => collectSecretStrings(v, secretName));
104
+ if (isRecord(value)) {
105
+ return Object.entries(value).flatMap(([k, v]) =>
106
+ collectSecretStrings(v, secretName || isSecretField(k)),
107
+ );
108
+ }
109
+ return [];
110
+ }
111
+
112
+ /**
113
+ * Deep-copy a JSON value, replacing every occurrence of a known secret string
114
+ * with "[redacted]". Short secrets only match on equality to avoid clobbering
115
+ * unrelated substrings.
116
+ */
117
+ export function scrubSecrets(value: string, secrets: string[]): string;
118
+ export function scrubSecrets(
119
+ value: Record<string, unknown>,
120
+ secrets: string[],
121
+ ): Record<string, unknown>;
122
+ export function scrubSecrets(value: unknown, secrets: string[]): unknown;
123
+ export function scrubSecrets(value: unknown, secrets: string[]): unknown {
124
+ if (typeof value === 'string') {
125
+ let out = value;
126
+ for (const secret of secrets) {
127
+ if (secret.length >= 6) {
128
+ if (out.includes(secret)) out = out.replaceAll(secret, '[redacted]');
129
+ } else if (out === secret) {
130
+ out = '[redacted]';
131
+ }
132
+ }
133
+ return out;
134
+ }
135
+ if (Array.isArray(value)) return value.map((v) => scrubSecrets(v, secrets));
136
+ if (isRecord(value)) {
137
+ const out: Record<string, unknown> = {};
138
+ for (const [k, v] of Object.entries(value)) out[k] = scrubSecrets(v, secrets);
139
+ return out;
140
+ }
141
+ return value;
142
+ }
143
+
144
+ /** Strip key-bearing fields and redact secret-looking header values from a provider entry. */
145
+ export function sanitizeProvider(entry: Record<string, unknown>): Record<string, unknown> {
146
+ const out: Record<string, unknown> = {};
147
+ for (const [k, v] of Object.entries(entry)) {
148
+ if (isSecretField(k)) continue;
149
+ if (k === 'headers' && isRecord(v)) {
150
+ const headers: Record<string, unknown> = {};
151
+ for (const [hk, hv] of Object.entries(v)) {
152
+ headers[hk] = SECRET_HEADER_RE.test(hk) ? '[redacted]' : hv;
153
+ }
154
+ out.headers = headers;
155
+ continue;
156
+ }
157
+ out[k] = v;
158
+ }
159
+ return out;
160
+ }
161
+
162
+ export type ParseResult = {ok: true; doc: PortableConfig} | {ok: false; message: string};
163
+
164
+ function typeOfValue(v: unknown): string {
165
+ if (Array.isArray(v)) return 'array';
166
+ if (v === null) return 'null';
167
+ return typeof v;
168
+ }
169
+
170
+ function validateSetting(name: string, value: unknown): string | null {
171
+ const expected = SETTING_TYPES[name];
172
+ if (!expected) return null;
173
+ const actual = typeOfValue(value);
174
+ const matches =
175
+ expected === 'string[]'
176
+ ? Array.isArray(value) && value.every((v) => typeof v === 'string')
177
+ : expected === 'object'
178
+ ? typeof value === 'object'
179
+ : actual === expected;
180
+ return matches ? null : `must be ${expected} (got ${actual})`;
181
+ }
182
+
183
+ function parseProject(
184
+ value: unknown,
185
+ ): {ok: true; project: PortableProject} | {ok: false; message: string} {
186
+ if (!isRecord(value)) return {ok: false, message: 'project must be an object'};
187
+ const project: PortableProject = {};
188
+ for (const field of PROJECT_FIELDS) {
189
+ const v = value[field];
190
+ if (v === undefined) continue;
191
+ const ok =
192
+ field === 'ignore'
193
+ ? Array.isArray(v) && v.every((x) => typeof x === 'string')
194
+ : field === 'ignoreLargeFiles'
195
+ ? typeof v === 'boolean'
196
+ : typeof v === 'number';
197
+ if (!ok) return {ok: false, message: `project.${field} has the wrong type`};
198
+ Object.assign(project, {[field]: v});
199
+ }
200
+ return {ok: true, project};
201
+ }
202
+
203
+ /** Parse untrusted export-file JSON into a typed document, or explain why not. */
204
+ export function parsePortableConfig(value: unknown): ParseResult {
205
+ if (!isRecord(value)) {
206
+ return {ok: false, message: 'not a pal export file (expected a JSON object)'};
207
+ }
208
+ if (value.version !== undefined) {
209
+ if (
210
+ typeof value.version !== 'number' ||
211
+ !Number.isInteger(value.version) ||
212
+ value.version < 1 ||
213
+ value.version > EXPORT_VERSION
214
+ ) {
215
+ return {
216
+ ok: false,
217
+ message: `unsupported export version ${JSON.stringify(value.version)} (expected 1..${EXPORT_VERSION})`,
218
+ };
219
+ }
220
+ }
221
+
222
+ const doc: PortableConfig = {version: EXPORT_VERSION};
223
+ let sections = 0;
224
+
225
+ if (value.settings !== undefined) {
226
+ if (!isRecord(value.settings)) return {ok: false, message: 'settings must be an object'};
227
+ for (const [k, v] of Object.entries(value.settings)) {
228
+ const err = validateSetting(k, v);
229
+ if (err) return {ok: false, message: `settings.${k} ${err}`};
230
+ }
231
+ doc.settings = value.settings;
232
+ sections++;
233
+ }
234
+
235
+ if (value.providers !== undefined) {
236
+ if (!Array.isArray(value.providers)) return {ok: false, message: 'providers must be an array'};
237
+ const providers: Record<string, unknown>[] = [];
238
+ for (const entry of value.providers) {
239
+ if (!isRecord(entry) || typeof entry.id !== 'string' || typeof entry.baseUrl !== 'string') {
240
+ return {ok: false, message: 'each provider needs string id and baseUrl'};
241
+ }
242
+ providers.push(entry);
243
+ }
244
+ doc.providers = providers;
245
+ sections++;
246
+ }
247
+
248
+ for (const field of HOOKS_LIKE_FIELDS) {
249
+ if (value[field] !== undefined) {
250
+ const err = validateSetting(field, value[field]);
251
+ if (err) return {ok: false, message: `${field} ${err}`};
252
+ doc[field] = value[field];
253
+ sections++;
254
+ }
255
+ }
256
+
257
+ if (value.project !== undefined) {
258
+ const parsed = parseProject(value.project);
259
+ if (!parsed.ok) return {ok: false, message: parsed.message};
260
+ doc.project = parsed.project;
261
+ sections++;
262
+ }
263
+
264
+ if (sections === 0) {
265
+ return {
266
+ ok: false,
267
+ message:
268
+ 'no pal config sections found (expected at least one of settings, providers, hooks, agents, skills, project)',
269
+ };
270
+ }
271
+ return {ok: true, doc};
272
+ }
273
+
274
+ export function jsonEqual(a: unknown, b: unknown): boolean {
275
+ if (a === b) return true;
276
+ if (Array.isArray(a) && Array.isArray(b)) {
277
+ return a.length === b.length && a.every((x, i) => jsonEqual(x, b[i]));
278
+ }
279
+ if (isRecord(a) && isRecord(b)) {
280
+ const aKeys = Object.keys(a);
281
+ const bKeys = Object.keys(b);
282
+ return (
283
+ aKeys.length === bKeys.length &&
284
+ aKeys.every((k) => Object.hasOwn(b, k) && jsonEqual(a[k], b[k]))
285
+ );
286
+ }
287
+ return false;
288
+ }
289
+
290
+ export function fmtValue(value: unknown): string {
291
+ if (value === undefined) return '(unset)';
292
+ const json = JSON.stringify(value);
293
+ if (json === undefined) return String(value);
294
+ return json.length <= 60 ? json : `${json.slice(0, 59)}…`;
295
+ }
@@ -17,9 +17,7 @@ export function cmdHelp(container: Container, tui: TUI): void {
17
17
  container.addChild(new Text(` ${c.bold}Available commands:${c.reset}`, 1, 0));
18
18
  container.addChild(new Text(` ${c.cyan}/help${c.reset} Show this help message`, 1, 0));
19
19
  container.addChild(new Text(` ${c.cyan}/exit${c.reset} Save session and quit`, 1, 0));
20
- container.addChild(
21
- new Text(` ${c.cyan}/new${c.reset} Start a new session`, 1, 0),
22
- );
20
+ container.addChild(new Text(` ${c.cyan}/new${c.reset} Start a new session`, 1, 0));
23
21
  container.addChild(new Text(` ${c.cyan}/sessions${c.reset} List recent sessions`, 1, 0));
24
22
  container.addChild(
25
23
  new Text(` ${c.cyan}/undo${c.reset} Restore the file from your last edit`, 1, 0),
@@ -49,6 +47,16 @@ export function cmdHelp(container: Container, tui: TUI): void {
49
47
  container.addChild(
50
48
  new Text(` ${c.cyan}/key${c.reset} Set API key interactively`, 1, 0),
51
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
+ );
52
60
  container.addChild(
53
61
  new Text(` ${c.cyan}/roles${c.reset} List agent roles (agents extension)`, 1, 0),
54
62
  );
@@ -63,34 +71,31 @@ export function cmdHelp(container: Container, tui: TUI): void {
63
71
  new Text(` ${c.cyan}/execute${c.reset} Leave plan mode and implement`, 1, 0),
64
72
  );
65
73
  container.addChild(
66
- new Text(` ${c.cyan}/ext add${c.reset} <pkg> Install an extension`, 1, 0),
74
+ new Text(` ${c.cyan}/ext add${c.reset} <pkg> Install an extension from npm`, 1, 0),
67
75
  );
68
76
  container.addChild(
69
77
  new Text(` ${c.cyan}/ext remove${c.reset} <pkg> Remove an extension`, 1, 0),
70
78
  );
71
- container.addChild(
72
- new Text(` ${c.cyan}/ext list${c.reset} List loaded extensions`, 1, 0),
73
- );
74
79
  container.addChild(
75
80
  new Text(
76
- ` ${c.cyan}/mcp add${c.reset} <name> <cmd> [args] Add a local MCP server`,
81
+ ` ${c.cyan}/ext search${c.reset} <q> Search the npm registry for extensions`,
77
82
  1,
78
83
  0,
79
84
  ),
80
85
  );
81
86
  container.addChild(
82
- new Text(
83
- ` ${c.cyan}/mcp add-remote${c.reset} <name> <url> Add a remote MCP server`,
84
- 1,
85
- 0,
86
- ),
87
+ new Text(` ${c.cyan}/ext list${c.reset} List loaded extensions`, 1, 0),
87
88
  );
88
89
  container.addChild(
89
- new Text(` ${c.cyan}/mcp remove${c.reset} <name> Remove an MCP server`, 1, 0),
90
+ new Text(` ${c.cyan}/mcp add${c.reset} <name> <cmd> [args] Add a local MCP server`, 1, 0),
90
91
  );
91
92
  container.addChild(
92
- new Text(` ${c.cyan}/mcp list${c.reset} List MCP servers`, 1, 0),
93
+ new Text(` ${c.cyan}/mcp add-remote${c.reset} <name> <url> Add a remote MCP server`, 1, 0),
94
+ );
95
+ container.addChild(
96
+ new Text(` ${c.cyan}/mcp remove${c.reset} <name> Remove an MCP server`, 1, 0),
93
97
  );
98
+ container.addChild(new Text(` ${c.cyan}/mcp list${c.reset} List MCP servers`, 1, 0));
94
99
  container.addChild(
95
100
  new Text(` ${c.cyan}/mcp browse${c.reset} Browse curated MCP servers`, 1, 0),
96
101
  );
@@ -64,6 +64,25 @@ function strEnv(name: string, fallback: string): string {
64
64
  return raw && raw.trim() ? raw : fallback;
65
65
  }
66
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
+
67
86
  export function loadConfig(): Config {
68
87
  const saved = readPalConfig();
69
88
  const savedModel =
@@ -75,7 +94,14 @@ export function loadConfig(): Config {
75
94
 
76
95
  // Extensions: use saved list or default to the shipped set.
77
96
  const savedExtensions = Array.isArray(saved.extensions) ? saved.extensions : undefined;
78
- const extensions = savedExtensions ?? ['@pal-code/web-search', '@pal-code/agents', '@pal-code/mcp'];
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');
79
105
 
80
106
  return {
81
107
  model: strEnv('MODEL', strEnv('PAL_MODEL', savedModel ?? 'deepseek/deepseek-chat')),
@@ -83,7 +109,7 @@ export function loadConfig(): Config {
83
109
  maxToolRounds: intEnv('MAX_TOOL_ROUNDS', 100, 1),
84
110
  maxRetries: intEnv('MAX_RETRIES', 1, 0),
85
111
  retryBaseMs: intEnv('RETRY_BASE_MS', 2000, 0),
86
- contextLimit: intEnv('CONTEXT_LIMIT', 100_000, 1000),
112
+ contextLimit: intEnv('CONTEXT_LIMIT', savedContextLimit ?? 100_000, 1000),
87
113
  reasoningEffort: effortEnv(),
88
114
  extensions,
89
115
  };