pal-code 0.0.11 → 0.0.13
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 +5 -0
- package/package.json +3 -2
- package/packages/cli/src/commands/config-export.ts +99 -0
- package/packages/cli/src/commands/config-io.ts +264 -0
- package/packages/cli/src/commands/ext-registry.ts +83 -0
- package/packages/cli/src/commands/ext.ts +137 -7
- package/packages/cli/src/commands/portable.ts +295 -0
- package/packages/cli/src/commands/update-check.ts +180 -0
- package/packages/cli/src/commands/update.ts +185 -0
- package/packages/cli/src/commands.ts +30 -15
- package/packages/cli/src/components/assistant-body.ts +88 -0
- package/packages/cli/src/components/render-history.ts +5 -4
- package/packages/cli/src/components/run-view.ts +7 -6
- package/packages/cli/src/config.ts +28 -2
- package/packages/cli/src/index.ts +247 -40
- package/packages/cli/src/state.ts +26 -0
- package/packages/cli/src/turn.ts +29 -22
- package/packages/cli/src/utils/code-block.ts +123 -0
- package/packages/cli/src/utils/format.ts +25 -3
- package/packages/cli/src/utils/osc52.ts +55 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Daily-cached startup version check for pal-code.
|
|
3
|
+
*
|
|
4
|
+
* Cache: ~/.pal/update-check.json — {lastCheck, latest?, critical?, notified[]}
|
|
5
|
+
* The startup path is synchronous and pure: it renders whatever the cache says.
|
|
6
|
+
* refreshUpdateCheck() runs fire-and-forget and only writes on a successful
|
|
7
|
+
* fetch, so offline/corporate/mid-task sessions are never disturbed.
|
|
8
|
+
*
|
|
9
|
+
* Severity comes from npm's explicit `critical` dist-tag — 0.0.x semver cannot
|
|
10
|
+
* signal it — and nothing here ever forces an update:
|
|
11
|
+
* - dim hint when `latest` is ahead (once per version, via `notified`)
|
|
12
|
+
* - yellow banner when `critical` is ahead (every launch until local catches up)
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import {mkdirSync, readFileSync, writeFileSync} from 'node:fs';
|
|
16
|
+
import {homedir} from 'node:os';
|
|
17
|
+
import {dirname, join} from 'node:path';
|
|
18
|
+
|
|
19
|
+
const NPM_REGISTRY_URL = 'https://registry.npmjs.org';
|
|
20
|
+
const PAL_PACKAGE = 'pal-code';
|
|
21
|
+
const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
|
22
|
+
|
|
23
|
+
export const UPDATE_CHECK_CACHE_PATH = join(homedir(), '.pal', 'update-check.json');
|
|
24
|
+
|
|
25
|
+
export interface UpdateCheckCache {
|
|
26
|
+
lastCheck: number;
|
|
27
|
+
latest?: string;
|
|
28
|
+
critical?: string;
|
|
29
|
+
notified: string[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface DistTags {
|
|
33
|
+
latest?: string;
|
|
34
|
+
critical?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface StartupNotice {
|
|
38
|
+
/** Dim one-liner to show once for this exact `latest` version, or null. */
|
|
39
|
+
hint: string | null;
|
|
40
|
+
/** Yellow banner shown every launch while `critical` is ahead, or null. */
|
|
41
|
+
banner: string | null;
|
|
42
|
+
/** `notified` with the announced hint version appended (unchanged when no hint). */
|
|
43
|
+
notified: string[];
|
|
44
|
+
/** True when `notified` gained an entry and the cache should be rewritten. */
|
|
45
|
+
changed: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** True when `candidate` is strictly newer than `reference` (numeric dot segments). */
|
|
49
|
+
export function isNewer(candidate: string, reference: string): boolean {
|
|
50
|
+
const a = candidate.split('.');
|
|
51
|
+
const b = reference.split('.');
|
|
52
|
+
const len = Math.max(a.length, b.length);
|
|
53
|
+
for (let i = 0; i < len; i++) {
|
|
54
|
+
const x = segment(a[i]);
|
|
55
|
+
const y = segment(b[i]);
|
|
56
|
+
if (x !== y) return x > y;
|
|
57
|
+
}
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Missing segments count as 0; non-numeric garbage degrades to 0 rather than NaN. */
|
|
62
|
+
function segment(part: string | undefined): number {
|
|
63
|
+
if (part === undefined) return 0;
|
|
64
|
+
const n = Number.parseInt(part, 10);
|
|
65
|
+
return Number.isNaN(n) ? 0 : n;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Tolerant parse — corrupt/partial cache files degrade to an empty cache. */
|
|
69
|
+
export function parseUpdateCache(raw: string): UpdateCheckCache {
|
|
70
|
+
let data: unknown;
|
|
71
|
+
try {
|
|
72
|
+
data = JSON.parse(raw);
|
|
73
|
+
} catch {
|
|
74
|
+
return {lastCheck: 0, notified: []};
|
|
75
|
+
}
|
|
76
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
|
|
77
|
+
return {lastCheck: 0, notified: []};
|
|
78
|
+
}
|
|
79
|
+
const record = data as Record<string, unknown>;
|
|
80
|
+
const lastCheck =
|
|
81
|
+
typeof record.lastCheck === 'number' && Number.isFinite(record.lastCheck)
|
|
82
|
+
? record.lastCheck
|
|
83
|
+
: 0;
|
|
84
|
+
const cache: UpdateCheckCache = {lastCheck, notified: []};
|
|
85
|
+
if (typeof record.latest === 'string') cache.latest = record.latest;
|
|
86
|
+
if (typeof record.critical === 'string') cache.critical = record.critical;
|
|
87
|
+
if (Array.isArray(record.notified)) {
|
|
88
|
+
cache.notified = record.notified.filter((entry): entry is string => typeof entry === 'string');
|
|
89
|
+
}
|
|
90
|
+
return cache;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Never throws — a missing or unreadable cache just means "check fresh". */
|
|
94
|
+
export function loadUpdateCache(path: string = UPDATE_CHECK_CACHE_PATH): UpdateCheckCache {
|
|
95
|
+
try {
|
|
96
|
+
return parseUpdateCache(readFileSync(path, 'utf-8'));
|
|
97
|
+
} catch {
|
|
98
|
+
return {lastCheck: 0, notified: []};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Never throws — a read-only home skips persisting instead of breaking startup. */
|
|
103
|
+
export function saveUpdateCache(
|
|
104
|
+
cache: UpdateCheckCache,
|
|
105
|
+
path: string = UPDATE_CHECK_CACHE_PATH,
|
|
106
|
+
): void {
|
|
107
|
+
try {
|
|
108
|
+
mkdirSync(dirname(path), {recursive: true});
|
|
109
|
+
writeFileSync(path, `${JSON.stringify(cache, null, 2)}\n`, 'utf-8');
|
|
110
|
+
} catch {
|
|
111
|
+
// Best-effort persistence; the next launch re-derives whatever is missing.
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Pure startup decision — what the transcript shows this launch.
|
|
117
|
+
* The hint is gated by `notified` (once per version, ever); the critical banner
|
|
118
|
+
* is not gated at all, so it repaints every startup until local >= critical.
|
|
119
|
+
*/
|
|
120
|
+
export function planStartupNotice(cache: UpdateCheckCache, localVersion: string): StartupNotice {
|
|
121
|
+
const {latest, critical} = cache;
|
|
122
|
+
let notified = cache.notified;
|
|
123
|
+
let hint: string | null = null;
|
|
124
|
+
|
|
125
|
+
if (latest && isNewer(latest, localVersion) && !notified.includes(latest)) {
|
|
126
|
+
hint = `pal-code ${latest} available — run: pal update`;
|
|
127
|
+
notified = [...notified, latest];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const banner =
|
|
131
|
+
critical && isNewer(critical, localVersion)
|
|
132
|
+
? `pal-code ${critical} critical update available — run: pal update`
|
|
133
|
+
: null;
|
|
134
|
+
|
|
135
|
+
return {hint, banner, notified, changed: notified.length !== cache.notified.length};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Read a package's `dist-tags` from the npm registry.
|
|
140
|
+
* 404/offline/malformed → null (never throws), mirroring ext.ts lookupNpmPackage.
|
|
141
|
+
*/
|
|
142
|
+
export async function fetchDistTags(pkg: string): Promise<DistTags | null> {
|
|
143
|
+
try {
|
|
144
|
+
const res = await fetch(`${NPM_REGISTRY_URL}/${pkg.replaceAll('/', '%2F')}`);
|
|
145
|
+
if (!res.ok) return null;
|
|
146
|
+
const data: unknown = await res.json();
|
|
147
|
+
if (typeof data !== 'object' || data === null) return null;
|
|
148
|
+
const tags = (data as Record<string, unknown>)['dist-tags'];
|
|
149
|
+
if (typeof tags !== 'object' || tags === null) return null;
|
|
150
|
+
const record = tags as Record<string, unknown>;
|
|
151
|
+
const distTags: DistTags = {};
|
|
152
|
+
if (typeof record.latest === 'string') distTags.latest = record.latest;
|
|
153
|
+
if (typeof record.critical === 'string') distTags.critical = record.critical;
|
|
154
|
+
return distTags.latest || distTags.critical ? distTags : null;
|
|
155
|
+
} catch {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Fire-and-forget refresh — at most one registry hit per 24h, and only ever
|
|
162
|
+
* written on success, so a failed check retries on the next launch. Never rejects.
|
|
163
|
+
*/
|
|
164
|
+
export async function refreshUpdateCheck(
|
|
165
|
+
cachePath: string = UPDATE_CHECK_CACHE_PATH,
|
|
166
|
+
now: number = Date.now(),
|
|
167
|
+
): Promise<void> {
|
|
168
|
+
try {
|
|
169
|
+
const cache = loadUpdateCache(cachePath);
|
|
170
|
+
if (now - cache.lastCheck < UPDATE_CHECK_INTERVAL_MS) return;
|
|
171
|
+
const tags = await fetchDistTags(PAL_PACKAGE);
|
|
172
|
+
if (!tags) return;
|
|
173
|
+
saveUpdateCache(
|
|
174
|
+
{lastCheck: now, latest: tags.latest, critical: tags.critical, notified: cache.notified},
|
|
175
|
+
cachePath,
|
|
176
|
+
);
|
|
177
|
+
} catch {
|
|
178
|
+
// Startup must stay silent — any failure simply means "retry next launch".
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pal update` / `pal upgrade` — refresh pal-code itself and its extensions.
|
|
3
|
+
*
|
|
4
|
+
* Self-update is install-method aware (see detectInstallMethod): npm-global
|
|
5
|
+
* runs `npm i -g pal-code@latest`, bun-global runs `bun add -g pal-code@latest`,
|
|
6
|
+
* a dev checkout is never mutated (git-pull instructions instead), and an
|
|
7
|
+
* unknown install exits non-zero with both suggestions.
|
|
8
|
+
*
|
|
9
|
+
* Extension updates read the same config list /ext uses, compare each installed
|
|
10
|
+
* package against npm's `latest` dist-tag, and `bun update` the outdated ones —
|
|
11
|
+
* offline/404 lookups skip quietly, mirroring commands/ext.ts. Nothing here
|
|
12
|
+
* ever force-updates: the user asked, so we report and exit like ext.ts does.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import {execSync} from 'node:child_process';
|
|
16
|
+
import {existsSync, readFileSync} from 'node:fs';
|
|
17
|
+
import {dirname, join} from 'node:path';
|
|
18
|
+
import {readPalConfig} from '@pal-code/core';
|
|
19
|
+
|
|
20
|
+
import {EXTENSIONS_DIR, type ExtCommandResult} from './ext.js';
|
|
21
|
+
import {fetchDistTags, isNewer} from './update-check.js';
|
|
22
|
+
|
|
23
|
+
/** How the running copy of pal-code was installed. */
|
|
24
|
+
export type InstallMethod = 'npm-global' | 'bun-global' | 'dev' | 'unknown';
|
|
25
|
+
|
|
26
|
+
export interface InstallMethodHints {
|
|
27
|
+
/** Path hints, compared normalized (backslashes folded, lowercased). */
|
|
28
|
+
paths: readonly string[];
|
|
29
|
+
/** True when version.json and .git both sit near the package root (dev checkout). */
|
|
30
|
+
devCheckout: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface SectionResult {
|
|
34
|
+
ok: boolean;
|
|
35
|
+
lines: string[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
type SelfUpdateAction =
|
|
39
|
+
| {kind: 'run'; command: string; success: string}
|
|
40
|
+
| {kind: 'note'; line: string}
|
|
41
|
+
| {kind: 'manual'; lines: string[]};
|
|
42
|
+
|
|
43
|
+
/** Compile-time exhaustive map — a new InstallMethod variant fails tsc until handled. */
|
|
44
|
+
const SELF_UPDATE_ACTIONS: Record<InstallMethod, SelfUpdateAction> = {
|
|
45
|
+
'npm-global': {
|
|
46
|
+
kind: 'run',
|
|
47
|
+
command: 'npm i -g pal-code@latest',
|
|
48
|
+
success: 'Updated pal-code (npm i -g pal-code@latest).',
|
|
49
|
+
},
|
|
50
|
+
'bun-global': {
|
|
51
|
+
kind: 'run',
|
|
52
|
+
command: 'bun add -g pal-code@latest',
|
|
53
|
+
success: 'Updated pal-code (bun add -g pal-code@latest).',
|
|
54
|
+
},
|
|
55
|
+
dev: {kind: 'note', line: 'Development checkout — run: git pull && bun install'},
|
|
56
|
+
unknown: {
|
|
57
|
+
kind: 'manual',
|
|
58
|
+
lines: [
|
|
59
|
+
'Could not determine how pal was installed. Run one of:',
|
|
60
|
+
' npm i -g pal-code@latest',
|
|
61
|
+
' bun add -g pal-code@latest',
|
|
62
|
+
],
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Classify the install from path hints alone (pure — unit-testable).
|
|
68
|
+
* Order matters: bun-global paths also contain `node_modules/pal-code`, so the
|
|
69
|
+
* `.bun/install/global` marker wins first; the `node_modules/pal-code` marker
|
|
70
|
+
* also matches platform packages (`pal-code-win32-x64`) of compiled binaries.
|
|
71
|
+
*/
|
|
72
|
+
export function detectInstallMethod(hints: InstallMethodHints): InstallMethod {
|
|
73
|
+
const paths = hints.paths.map((p) => p.replaceAll('\\', '/').toLowerCase());
|
|
74
|
+
if (paths.some((p) => p.includes('/.bun/install/global'))) return 'bun-global';
|
|
75
|
+
if (paths.some((p) => p.includes('node_modules/pal-code'))) return 'npm-global';
|
|
76
|
+
if (hints.devCheckout) return 'dev';
|
|
77
|
+
return 'unknown';
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Walk up from `startDir` for a directory holding BOTH version.json and .git. */
|
|
81
|
+
function isDevCheckout(startDir: string): boolean {
|
|
82
|
+
let dir = startDir;
|
|
83
|
+
for (let i = 0; i < 12; i++) {
|
|
84
|
+
if (existsSync(join(dir, 'version.json')) && existsSync(join(dir, '.git'))) return true;
|
|
85
|
+
const parent = dirname(dir);
|
|
86
|
+
if (parent === dir) break;
|
|
87
|
+
dir = parent;
|
|
88
|
+
}
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function collectInstallHints(): InstallMethodHints {
|
|
93
|
+
return {
|
|
94
|
+
paths: [process.execPath, import.meta.dir],
|
|
95
|
+
// Compiled binaries live in dist/ (dev) or <prefix>/node_modules/... (global),
|
|
96
|
+
// so probe both the module dir and the executable's directory.
|
|
97
|
+
devCheckout: isDevCheckout(import.meta.dir) || isDevCheckout(dirname(process.execPath)),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function applySelfUpdate(method: InstallMethod): SectionResult {
|
|
102
|
+
const action = SELF_UPDATE_ACTIONS[method];
|
|
103
|
+
if (action.kind === 'run') {
|
|
104
|
+
try {
|
|
105
|
+
execSync(action.command, {stdio: 'inherit'});
|
|
106
|
+
return {ok: true, lines: [action.success]};
|
|
107
|
+
} catch (err) {
|
|
108
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
109
|
+
return {ok: false, lines: [`Self-update failed: ${msg}`]};
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (action.kind === 'manual') {
|
|
113
|
+
return {ok: false, lines: action.lines};
|
|
114
|
+
}
|
|
115
|
+
return {ok: true, lines: [action.line]};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Installed on-disk version, or null when absent/unreadable (→ skip). */
|
|
119
|
+
function installedVersion(pkg: string): string | null {
|
|
120
|
+
const manifest = join(EXTENSIONS_DIR, 'node_modules', pkg, 'package.json');
|
|
121
|
+
if (!existsSync(manifest)) return null;
|
|
122
|
+
try {
|
|
123
|
+
const data: unknown = JSON.parse(readFileSync(manifest, 'utf-8'));
|
|
124
|
+
if (typeof data === 'object' && data !== null) {
|
|
125
|
+
const version = (data as {version?: unknown}).version;
|
|
126
|
+
if (typeof version === 'string' && version.length > 0) return version;
|
|
127
|
+
}
|
|
128
|
+
} catch {
|
|
129
|
+
return null; // unreadable/corrupt manifest — treat as not installed
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Compare every configured extension against npm `latest`; bun-update outdated. */
|
|
135
|
+
async function updateExtensions(): Promise<SectionResult> {
|
|
136
|
+
const config = readPalConfig();
|
|
137
|
+
const extensions = Array.isArray(config.extensions) ? (config.extensions as string[]) : [];
|
|
138
|
+
if (extensions.length === 0) return {ok: true, lines: []};
|
|
139
|
+
|
|
140
|
+
const updated: string[] = [];
|
|
141
|
+
const failed: string[] = [];
|
|
142
|
+
let upToDate = 0;
|
|
143
|
+
let skipped = 0;
|
|
144
|
+
|
|
145
|
+
for (const pkg of extensions) {
|
|
146
|
+
const current = installedVersion(pkg);
|
|
147
|
+
if (current === null) continue; // configured but not installed — skip
|
|
148
|
+
const tags = await fetchDistTags(pkg);
|
|
149
|
+
if (!tags?.latest) {
|
|
150
|
+
skipped += 1; // offline or absent from npm — tolerant skip
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (!isNewer(tags.latest, current)) {
|
|
154
|
+
upToDate += 1;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
execSync(`bun update ${pkg}`, {cwd: EXTENSIONS_DIR, stdio: 'pipe'});
|
|
159
|
+
updated.push(` ${pkg} ${current} → ${tags.latest}`);
|
|
160
|
+
} catch (err) {
|
|
161
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
162
|
+
failed.push(` ${pkg}: update failed — ${msg}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const lines: string[] = ['', 'Extensions:'];
|
|
167
|
+
if (updated.length > 0) lines.push(...updated);
|
|
168
|
+
else if (failed.length === 0 && skipped === 0 && upToDate > 0) lines.push(' all up to date.');
|
|
169
|
+
if (failed.length > 0) lines.push(...failed);
|
|
170
|
+
if (skipped > 0) lines.push(` ${skipped} skipped — npm registry unreachable.`);
|
|
171
|
+
if (updated.length === 0 && failed.length === 0 && upToDate === 0 && skipped === 0) {
|
|
172
|
+
lines.push(' nothing installed to check.');
|
|
173
|
+
}
|
|
174
|
+
return {ok: failed.length === 0, lines};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** `pal update` / `pal upgrade` entry point — argv fast-exit, runs before the TUI. */
|
|
178
|
+
export async function palUpdate(): Promise<ExtCommandResult> {
|
|
179
|
+
const selfUpdate = applySelfUpdate(detectInstallMethod(collectInstallHints()));
|
|
180
|
+
const extensions = await updateExtensions();
|
|
181
|
+
return {
|
|
182
|
+
ok: selfUpdate.ok && extensions.ok,
|
|
183
|
+
message: [...selfUpdate.lines, ...extensions.lines].join('\n'),
|
|
184
|
+
};
|
|
185
|
+
}
|