vit 0.4.0 → 0.5.0

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/src/cmd/inbox.js CHANGED
@@ -5,6 +5,7 @@ import { DEFAULT_EXPLORE_URL } from '../lib/constants.js';
5
5
  import { readBeaconSet } from '../lib/vit-dir.js';
6
6
  import { brand } from '../lib/brand.js';
7
7
  import { jsonOk, jsonError } from '../lib/json-output.js';
8
+ import { errorMessage, formatError } from '../lib/error-format.js';
8
9
 
9
10
  function timeAgo(isoString) {
10
11
  const seconds = Math.floor((Date.now() - new Date(isoString).getTime()) / 1000);
@@ -67,7 +68,7 @@ export default function register(program) {
67
68
  if (!res.ok) throw new Error(`explore API returned ${res.status}`);
68
69
  data = await res.json();
69
70
  } catch (err) {
70
- const msg = err instanceof Error ? err.message : String(err);
71
+ const msg = errorMessage(err);
71
72
  const finalMsg = msg.startsWith('explore API returned ')
72
73
  ? msg
73
74
  : unavailableMessage(baseUrl);
@@ -119,12 +120,11 @@ export default function register(program) {
119
120
  console.log(`tip: 'vit vouch <ref> --kind want' to signal demand`);
120
121
  console.log(` 'vit ship --recap <ref>' to ship an implementation`);
121
122
  } catch (err) {
122
- const msg = err instanceof Error ? err.message : String(err);
123
123
  if (opts.json) {
124
- jsonError(msg);
124
+ jsonError(err);
125
125
  return;
126
126
  }
127
- console.error(msg);
127
+ console.error(formatError(err, { verbose: false }));
128
128
  process.exitCode = 1;
129
129
  }
130
130
  });
package/src/cmd/init.js CHANGED
@@ -9,6 +9,7 @@ import { vitDir, readProjectConfig, writeProjectConfig } from '../lib/vit-dir.js
9
9
  import { requireAgent } from '../lib/agent.js';
10
10
  import { mark, name, DOT_VIT_README } from '../lib/brand.js';
11
11
  import { jsonOk, jsonError } from '../lib/json-output.js';
12
+ import { errorMessage, formatError } from '../lib/error-format.js';
12
13
 
13
14
  export default function register(program) {
14
15
  program
@@ -80,7 +81,8 @@ export default function register(program) {
80
81
  if (hasVitDir) {
81
82
  console.log(`hint: run: ${name} init --beacon <canonical-git-url>`);
82
83
  } else {
83
- console.log(`hint: run ${name} init from inside a git repository.`);
84
+ console.log(`hint: navigate to a git repository and run '${name} init' there.`);
85
+ console.log(` to start fresh: git init && git remote add origin <your-repo-url>`);
84
86
  }
85
87
  return;
86
88
  }
@@ -97,7 +99,8 @@ export default function register(program) {
97
99
  .trim()
98
100
  .split('\n')
99
101
  .filter(Boolean);
100
- } catch {
102
+ } catch (err) {
103
+ console.warn(`warning: failed to list git remotes: ${errorMessage(err)}`);
101
104
  remoteNames = [];
102
105
  }
103
106
  if (verbose) vlog(`[verbose] remotes detected: ${remoteNames.length > 0 ? remoteNames.join(', ') : 'none'}`);
@@ -110,7 +113,9 @@ export default function register(program) {
110
113
  stdio: ['pipe', 'pipe', 'pipe'],
111
114
  }).trim();
112
115
  if (url) remotes.push({ name, url });
113
- } catch {}
116
+ } catch (err) {
117
+ console.warn(`warning: failed to read git remote ${name} url: ${errorMessage(err)}`);
118
+ }
114
119
  }
115
120
  if (verbose && remotes.length > 0) {
116
121
  vlog(`[verbose] remote urls: ${remotes.map(r => `${r.name}=${r.url}`).join(' ')}`);
@@ -230,12 +235,11 @@ export default function register(program) {
230
235
  console.log(`${mark} secondary beacon: ${merged.secondaryBeacon}`);
231
236
  }
232
237
  } catch (err) {
233
- const msg = err instanceof Error ? err.message : String(err);
234
238
  if (opts.json) {
235
- jsonError(msg);
239
+ jsonError(err);
236
240
  return;
237
241
  }
238
- console.error(msg);
242
+ console.error(formatError(err, { verbose: opts.verbose }));
239
243
  process.exitCode = 1;
240
244
  }
241
245
  });
package/src/cmd/learn.js CHANGED
@@ -16,6 +16,7 @@ import { mark, name } from '../lib/brand.js';
16
16
  import { resolvePds, resolveHandle, listRecordsFromPds, batchQuery } from '../lib/pds.js';
17
17
  import { loadConfig } from '../lib/config.js';
18
18
  import { jsonOk, jsonError } from '../lib/json-output.js';
19
+ import { errorMessage, formatError } from '../lib/error-format.js';
19
20
 
20
21
  async function installSkill({ match, skillName, isGlobal, opts, ref }) {
21
22
  const { verbose } = opts;
@@ -53,11 +54,12 @@ async function installSkill({ match, skillName, isGlobal, opts, ref }) {
53
54
  }
54
55
  }
55
56
 
56
- const addArgs = ['skills', 'add', tempDir, '-a', 'claude-code', '-y'];
57
+ const addArgs = ['--yes', 'skills', 'add', tempDir, '-a', 'claude-code', '-y'];
57
58
  if (isGlobal) addArgs.push('-g');
58
59
  const addResult = spawnSync('npx', addArgs, {
59
60
  encoding: 'utf-8',
60
61
  stdio: ['pipe', 'pipe', 'pipe'],
62
+ env: { ...process.env, CI: 'true' },
61
63
  });
62
64
  if (addResult.status !== 0) {
63
65
  const errText = (addResult.stderr || addResult.stdout || '').trim();
@@ -65,7 +67,11 @@ async function installSkill({ match, skillName, isGlobal, opts, ref }) {
65
67
  }
66
68
  if (verbose) vlog('[verbose] installed via npx skills add');
67
69
  } finally {
68
- try { rmSync(tempDir, { recursive: true, force: true }); } catch {}
70
+ try {
71
+ rmSync(tempDir, { recursive: true, force: true });
72
+ } catch (err) {
73
+ console.warn(`warning: failed to remove temporary directory ${tempDir}: ${errorMessage(err)}`);
74
+ }
69
75
  }
70
76
 
71
77
  const installDir = isGlobal
@@ -404,12 +410,11 @@ Examples:
404
410
 
405
411
  await installSkill({ match, skillName, isGlobal: !!opts.user, opts, ref });
406
412
  } catch (err) {
407
- const msg = err instanceof Error ? err.message : String(err);
408
413
  if (opts.json) {
409
- jsonError(msg);
414
+ jsonError(err);
410
415
  return;
411
416
  }
412
- console.error(msg);
417
+ console.error(formatError(err, { verbose: opts.verbose }));
413
418
  process.exitCode = 1;
414
419
  }
415
420
  });
package/src/cmd/link.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import { existsSync, mkdirSync, symlinkSync, unlinkSync, readlinkSync, writeFileSync } from 'node:fs';
5
5
  import { join, resolve } from 'node:path';
6
6
  import { mark, name } from '../lib/brand.js';
7
+ import { formatError } from '../lib/error-format.js';
7
8
 
8
9
  export default function register(program) {
9
10
  program
@@ -68,7 +69,7 @@ export default function register(program) {
68
69
  console.log(`${mark} PATH: ok`);
69
70
  }
70
71
  } catch (err) {
71
- console.error(err instanceof Error ? err.message : String(err));
72
+ console.error(formatError(err, { verbose: false }));
72
73
  process.exitCode = 1;
73
74
  }
74
75
  });
package/src/cmd/login.js CHANGED
@@ -11,6 +11,16 @@ import { loadConfig, saveConfig } from '../lib/config.js';
11
11
  import { createOAuthClient, createSessionStore, createStore, checkSession } from '../lib/oauth.js';
12
12
  import { configDir, configPath } from '../lib/paths.js';
13
13
  import { vitDir } from '../lib/vit-dir.js';
14
+ import { errorMessage, formatError } from '../lib/error-format.js';
15
+ import { mark } from '../lib/brand.js';
16
+ import { ensureSkill, skillInstallReason } from '../lib/skill-install.js';
17
+
18
+ export const LOGIN_COMMON_ISSUES_FOOTER = `Common issues:
19
+ - make sure the handle is correct and resolves on Bluesky
20
+ - open the printed URL in your browser, approve vit, and wait for the callback to finish
21
+ - if you're on a remote machine, rerun with 'vit login <handle> --remote' and paste the full callback URL
22
+ - if you used an app password, create a fresh Bluesky app password and try again
23
+ - check your DNS, firewall, or VPN settings if vit cannot reach Bluesky`;
14
24
 
15
25
  function ensureGitignore(dir, entry) {
16
26
  const gitignorePath = join(dir, '.gitignore');
@@ -21,6 +31,51 @@ function ensureGitignore(dir, entry) {
21
31
  }
22
32
  }
23
33
 
34
+ export function cancelLogin({
35
+ server,
36
+ rl,
37
+ timer,
38
+ clearTimer = clearTimeout,
39
+ stderr = console.error,
40
+ exit = process.exit,
41
+ footer = LOGIN_COMMON_ISSUES_FOOTER,
42
+ }) {
43
+ try {
44
+ if (server?.listening) server.close();
45
+ } catch {
46
+ // Ignore cleanup failures during cancellation.
47
+ }
48
+ try {
49
+ rl?.close();
50
+ } catch {
51
+ // Ignore cleanup failures during cancellation.
52
+ }
53
+ try {
54
+ if (timer) clearTimer(timer);
55
+ } catch {
56
+ // Ignore cleanup failures during cancellation.
57
+ }
58
+ stderr('\nLogin cancelled.');
59
+ stderr(footer);
60
+ exit(130);
61
+ }
62
+
63
+ export function printLoginFailure(err, { verbose = false, includeFooter = false } = {}) {
64
+ console.error(formatError(err, { verbose }));
65
+ if (includeFooter) {
66
+ console.error(LOGIN_COMMON_ISSUES_FOOTER);
67
+ }
68
+ }
69
+
70
+ function printSkillReadiness(skillResult) {
71
+ if (skillResult.ok) {
72
+ console.log(`${mark} skill: ready (using-vit)`);
73
+ return;
74
+ }
75
+
76
+ console.log(`${mark} skill: install failed — ${skillInstallReason(skillResult)}; check write permissions on ~/.claude and ~/.agents, or reinstall vit`);
77
+ }
78
+
24
79
  export default function register(program) {
25
80
  program
26
81
  .command('login')
@@ -36,6 +91,8 @@ export default function register(program) {
36
91
  const { verbose, force, remote, browser, appPassword, local: localLogin } = opts;
37
92
  const isRemote = remote || !!(process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.SSH_CLIENT);
38
93
  handle = handle.replace(/^@/, '');
94
+ const skillResult = ensureSkill();
95
+ printSkillReadiness(skillResult);
39
96
 
40
97
  if (localLogin) {
41
98
  const dir = vitDir();
@@ -60,7 +117,9 @@ export default function register(program) {
60
117
  return;
61
118
  }
62
119
  }
63
- } catch {}
120
+ } catch (err) {
121
+ console.warn(`warning: failed to read ${localPath}: ${errorMessage(err)}`);
122
+ }
64
123
  }
65
124
  } else {
66
125
  const existing = loadConfig();
@@ -91,7 +150,13 @@ export default function register(program) {
91
150
  } else {
92
151
  const sessionFile = configPath('session.json');
93
152
  let data = {};
94
- try { data = JSON.parse(readFileSync(sessionFile, 'utf-8')); } catch {}
153
+ if (existsSync(sessionFile)) {
154
+ try {
155
+ data = JSON.parse(readFileSync(sessionFile, 'utf-8'));
156
+ } catch (err) {
157
+ console.warn(`warning: failed to read ${sessionFile}: ${errorMessage(err)}`);
158
+ }
159
+ }
95
160
  data[did] = { type: 'app-password', service: 'https://bsky.social', session };
96
161
  mkdirSync(configDir, { recursive: true });
97
162
  writeFileSync(sessionFile, JSON.stringify(data, null, 2) + '\n');
@@ -102,7 +167,7 @@ export default function register(program) {
102
167
 
103
168
  console.log(`Logged in as ${did}`);
104
169
  } catch (err) {
105
- console.error(err instanceof Error ? err.message : String(err));
170
+ printLoginFailure(err, { verbose: opts.verbose, includeFooter: true });
106
171
  process.exitCode = 1;
107
172
  }
108
173
  return;
@@ -111,6 +176,8 @@ export default function register(program) {
111
176
  let server;
112
177
  let timeout;
113
178
  let rl;
179
+ let loginStage = 'preflight';
180
+ let onSigint = () => {};
114
181
 
115
182
  try {
116
183
  let resolveCallback;
@@ -139,6 +206,12 @@ export default function register(program) {
139
206
  res.end('Not found');
140
207
  });
141
208
 
209
+ onSigint = () => {
210
+ process.off('SIGINT', onSigint);
211
+ cancelLogin({ server, rl, timer: timeout });
212
+ };
213
+ process.once('SIGINT', onSigint);
214
+
142
215
  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
143
216
  const port = server.address().port;
144
217
 
@@ -156,6 +229,7 @@ export default function register(program) {
156
229
  const sessionStore = createSessionStore();
157
230
  const client = createOAuthClient({ stateStore, sessionStore, redirectUri });
158
231
 
232
+ loginStage = 'authorize';
159
233
  const authUrl = await client.authorize(handle, {
160
234
  scope: 'atproto transition:generic',
161
235
  });
@@ -182,6 +256,7 @@ export default function register(program) {
182
256
  console.log(`Open this URL in your browser:\n ${authUrl.toString()}\n`);
183
257
  }
184
258
 
259
+ loginStage = 'callback';
185
260
  if (isRemote) {
186
261
  rl = createInterface({ input: process.stdin, output: process.stdout });
187
262
  rl.question('Paste the callback URL from your browser: ', (line) => {
@@ -229,6 +304,7 @@ export default function register(program) {
229
304
  }
230
305
 
231
306
  console.log('Exchanging token...');
307
+ loginStage = 'token';
232
308
  const { session } = await client.callback(params);
233
309
 
234
310
  if (verbose) {
@@ -247,9 +323,13 @@ export default function register(program) {
247
323
  }
248
324
  console.log(`Logged in as ${session.did}`);
249
325
  } catch (err) {
250
- console.error(err instanceof Error ? err.message : String(err));
326
+ printLoginFailure(err, {
327
+ verbose: opts.verbose,
328
+ includeFooter: loginStage !== 'preflight',
329
+ });
251
330
  process.exitCode = 1;
252
331
  } finally {
332
+ process.removeListener('SIGINT', onSigint);
253
333
  if (timeout) {
254
334
  clearTimeout(timeout);
255
335
  }
package/src/cmd/remix.js CHANGED
@@ -12,6 +12,7 @@ import { brand, name } from '../lib/brand.js';
12
12
  import { resolvePds, listRecordsFromPds, batchQuery } from '../lib/pds.js';
13
13
  import { loadConfig } from '../lib/config.js';
14
14
  import { jsonOk, jsonError } from '../lib/json-output.js';
15
+ import { formatError } from '../lib/error-format.js';
15
16
 
16
17
  export default function register(program) {
17
18
  program
@@ -173,12 +174,11 @@ export default function register(program) {
173
174
  console.log('');
174
175
  console.log(text);
175
176
  } catch (err) {
176
- const msg = err instanceof Error ? err.message : String(err);
177
177
  if (opts.json) {
178
- jsonError(msg);
178
+ jsonError(err);
179
179
  return;
180
180
  }
181
- console.error(msg);
181
+ console.error(formatError(err, { verbose: opts.verbose }));
182
182
  process.exitCode = 1;
183
183
  }
184
184
  });
package/src/cmd/scan.js CHANGED
@@ -7,6 +7,7 @@ import { resolveHandleFromDid } from '../lib/pds.js';
7
7
  import { brand } from '../lib/brand.js';
8
8
  import { jsonOk, jsonError } from '../lib/json-output.js';
9
9
  import { readBeaconSet } from '../lib/vit-dir.js';
10
+ import { formatError } from '../lib/error-format.js';
10
11
 
11
12
  export default function register(program) {
12
13
  program
@@ -91,7 +92,12 @@ export default function register(program) {
91
92
 
92
93
  ws.onmessage = (event) => {
93
94
  let msg;
94
- try { msg = JSON.parse(event.data); } catch { return; }
95
+ try {
96
+ msg = JSON.parse(event.data);
97
+ } catch {
98
+ console.warn('warning: failed to parse Jetstream event as JSON; skipping');
99
+ return;
100
+ }
95
101
 
96
102
  if (msg.kind !== 'commit' || msg.commit?.operation !== 'create') return;
97
103
 
@@ -197,12 +203,11 @@ export default function register(program) {
197
203
  console.log(` ${parts.join(' ')}`);
198
204
  }
199
205
  } catch (err) {
200
- const msg = err instanceof Error ? err.message : String(err);
201
206
  if (opts.json) {
202
- jsonError(msg);
207
+ jsonError(err);
203
208
  return;
204
209
  }
205
- console.error(msg);
210
+ console.error(formatError(err, { verbose: opts.verbose }));
206
211
  process.exitCode = 1;
207
212
  }
208
213
  });
package/src/cmd/ship.js CHANGED
@@ -16,6 +16,7 @@ import { resolvePds, listRecordsFromPds, batchQuery } from '../lib/pds.js';
16
16
  import { jsonOk, jsonError } from '../lib/json-output.js';
17
17
  import { toBeacon } from '../lib/beacon.js';
18
18
  import { hashTo3Words } from '../lib/cap-ref.js';
19
+ import { formatError } from '../lib/error-format.js';
19
20
 
20
21
  const STOP_WORDS = new Set([
21
22
  'a', 'an', 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
@@ -664,12 +665,11 @@ export default function register(program) {
664
665
  await shipCap(opts);
665
666
  }
666
667
  } catch (err) {
667
- const msg = err instanceof Error ? err.message : String(err);
668
668
  if (opts.json) {
669
- jsonError(msg);
669
+ jsonError(err);
670
670
  return;
671
671
  }
672
- console.error(msg);
672
+ console.error(formatError(err, { verbose: opts.verbose }));
673
673
  process.exitCode = 1;
674
674
  }
675
675
  })
package/src/cmd/skim.js CHANGED
@@ -10,6 +10,8 @@ import { resolveRef } from '../lib/cap-ref.js';
10
10
  import { skillRefFromName } from '../lib/skill-ref.js';
11
11
  import { name } from '../lib/brand.js';
12
12
  import { resolvePds, listRecordsFromPds, batchQuery } from '../lib/pds.js';
13
+ import { jsonError } from '../lib/json-output.js';
14
+ import { formatError } from '../lib/error-format.js';
13
15
 
14
16
  export default function register(program) {
15
17
  program
@@ -208,7 +210,11 @@ export default function register(program) {
208
210
  }
209
211
  }
210
212
  } catch (err) {
211
- console.error(err instanceof Error ? err.message : String(err));
213
+ if (opts.json) {
214
+ jsonError(err);
215
+ return;
216
+ }
217
+ console.error(formatError(err, { verbose: opts.verbose }));
212
218
  process.exitCode = 1;
213
219
  }
214
220
  });
package/src/cmd/vet.js CHANGED
@@ -17,6 +17,7 @@ import { resolvePds, listRecordsFromPds, batchQuery } from '../lib/pds.js';
17
17
  import { loadConfig } from '../lib/config.js';
18
18
  import { jsonOk, jsonError } from '../lib/json-output.js';
19
19
  import { sandboxArgs } from '../lib/sandbox.js';
20
+ import { formatError } from '../lib/error-format.js';
20
21
 
21
22
  const execFileAsync = promisify(execFile);
22
23
 
@@ -629,12 +630,11 @@ export default function register(program) {
629
630
  console.log(` vit vet ${ref} --trust`);
630
631
  }
631
632
  } catch (err) {
632
- const msg = err instanceof Error ? err.message : String(err);
633
633
  if (opts.json) {
634
- jsonError(msg);
634
+ jsonError(err);
635
635
  return;
636
636
  }
637
- console.error(msg);
637
+ console.error(formatError(err, { verbose: opts.verbose }));
638
638
  process.exitCode = 1;
639
639
  }
640
640
  });
package/src/cmd/vouch.js CHANGED
@@ -12,6 +12,7 @@ import { mark, name } from '../lib/brand.js';
12
12
  import { resolvePds, listRecordsFromPds, batchQuery } from '../lib/pds.js';
13
13
  import { loadConfig } from '../lib/config.js';
14
14
  import { jsonOk, jsonError } from '../lib/json-output.js';
15
+ import { formatError } from '../lib/error-format.js';
15
16
 
16
17
  export default function register(program) {
17
18
  program
@@ -302,12 +303,11 @@ export default function register(program) {
302
303
  }
303
304
  }
304
305
  } catch (err) {
305
- const msg = err instanceof Error ? err.message : String(err);
306
306
  if (opts.json) {
307
- jsonError(msg);
307
+ jsonError(err);
308
308
  return;
309
309
  }
310
- console.error(msg);
310
+ console.error(formatError(err, { verbose: opts.verbose }));
311
311
  process.exitCode = 1;
312
312
  }
313
313
  });
package/src/lib/config.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import { configDir, configPath } from './paths.js';
7
+ import { errorMessage } from './error-format.js';
7
8
 
8
9
  const vitJsonPath = configPath('vit.json');
9
10
 
@@ -11,7 +12,8 @@ export function loadConfig() {
11
12
  if (!existsSync(vitJsonPath)) return {};
12
13
  try {
13
14
  return JSON.parse(readFileSync(vitJsonPath, 'utf-8'));
14
- } catch {
15
+ } catch (err) {
16
+ console.warn(`warning: failed to read ${vitJsonPath}: ${errorMessage(err)}`);
15
17
  return {};
16
18
  }
17
19
  }
@@ -26,13 +28,15 @@ export function saveConfig(obj) {
26
28
 
27
29
  export function requireDid(opts) {
28
30
  if (opts?.did) return opts.did;
31
+ const localLogin = join(process.cwd(), '.vit', 'login.json');
29
32
  try {
30
- const localLogin = join(process.cwd(), '.vit', 'login.json');
31
33
  if (existsSync(localLogin)) {
32
34
  const local = JSON.parse(readFileSync(localLogin, 'utf-8'));
33
35
  if (local.did) return local.did;
34
36
  }
35
- } catch {}
37
+ } catch (err) {
38
+ console.warn(`warning: failed to read ${localLogin}: ${errorMessage(err)}`);
39
+ }
36
40
  const did = loadConfig().did;
37
41
  if (!did) {
38
42
  console.error("no DID configured. run 'vit login <handle>' first or pass --did.");
@@ -0,0 +1,78 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 sol pbc
3
+
4
+ const MAX_CAUSES = 10;
5
+
6
+ function isObjectLike(value) {
7
+ return (typeof value === 'object' && value !== null) || typeof value === 'function';
8
+ }
9
+
10
+ export function errorMessage(value) {
11
+ if (value instanceof Error) return value.message || String(value);
12
+ if (isObjectLike(value) && typeof value.message === 'string') return value.message;
13
+ return String(value);
14
+ }
15
+
16
+ function stackLinesOf(value) {
17
+ if (!(value instanceof Error) || typeof value.stack !== 'string' || value.stack === '') return [];
18
+ return value.stack.split('\n').map(line => ` ${line}`);
19
+ }
20
+
21
+ function walkChain(err) {
22
+ if (!(err instanceof Error)) {
23
+ return [{ value: err, message: String(err), stackLines: [] }];
24
+ }
25
+
26
+ const levels = [];
27
+ const seen = new Set();
28
+ let current = err;
29
+ let causeCount = 0;
30
+
31
+ while (current !== undefined) {
32
+ if (isObjectLike(current)) {
33
+ if (seen.has(current)) break;
34
+ seen.add(current);
35
+ }
36
+
37
+ levels.push({
38
+ value: current,
39
+ message: errorMessage(current),
40
+ stackLines: stackLinesOf(current),
41
+ });
42
+
43
+ if (!isObjectLike(current) || !('cause' in current)) break;
44
+
45
+ const next = current.cause;
46
+ if (next === undefined) break;
47
+ if (causeCount >= MAX_CAUSES) break;
48
+
49
+ current = next;
50
+ causeCount += 1;
51
+ }
52
+
53
+ return levels;
54
+ }
55
+
56
+ export function collectCauses(err) {
57
+ if (!(err instanceof Error)) return [];
58
+ return walkChain(err).slice(1).map(level => level.message);
59
+ }
60
+
61
+ export function formatError(err, { hint, verbose = false } = {}) {
62
+ const levels = walkChain(err);
63
+ const lines = [];
64
+
65
+ for (let i = 0; i < levels.length; i += 1) {
66
+ const level = levels[i];
67
+ lines.push(i === 0 ? level.message : ` caused by: ${level.message}`);
68
+ if (verbose && level.stackLines.length > 0) {
69
+ lines.push(...level.stackLines);
70
+ }
71
+ }
72
+
73
+ if (typeof hint === 'string' && hint) {
74
+ lines.push(`hint: ${hint}`);
75
+ }
76
+
77
+ return lines.join('\n');
78
+ }
@@ -1,13 +1,38 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Copyright (c) 2026 sol pbc
3
3
 
4
+ import { collectCauses } from './error-format.js';
5
+
6
+ function errorMessage(input) {
7
+ if (input instanceof Error) return input.message || String(input);
8
+ return String(input);
9
+ }
10
+
4
11
  export function jsonOk(data) {
5
12
  console.log(JSON.stringify({ ok: true, ...data }, null, 2));
6
13
  }
7
14
 
8
- export function jsonError(error, hint) {
9
- const obj = { ok: false, error };
10
- if (hint) obj.hint = hint;
15
+ export function jsonError(input, hintArg) {
16
+ if (typeof input === 'string') {
17
+ const obj = { ok: false, error: input };
18
+ if (hintArg) obj.hint = hintArg;
19
+ console.log(JSON.stringify(obj, null, 2));
20
+ process.exitCode = 1;
21
+ return;
22
+ }
23
+
24
+ const obj = {
25
+ ok: false,
26
+ error: errorMessage(input),
27
+ };
28
+ const causes = collectCauses(input);
29
+ if (causes.length > 0) obj.causes = causes;
30
+
31
+ const resolvedHint = typeof hintArg === 'string'
32
+ ? hintArg
33
+ : (typeof input?.hint === 'string' ? input.hint : undefined);
34
+ if (resolvedHint) obj.hint = resolvedHint;
35
+
11
36
  console.log(JSON.stringify(obj, null, 2));
12
37
  process.exitCode = 1;
13
38
  }