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/lib/oauth.js CHANGED
@@ -6,6 +6,7 @@ import { NodeOAuthClient } from '@atproto/oauth-client-node';
6
6
  import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
7
7
  import { join } from 'node:path';
8
8
  import { configDir, configPath } from './paths.js';
9
+ import { errorMessage } from './error-format.js';
9
10
 
10
11
  const requestLock = async (_name, fn) => await fn();
11
12
 
@@ -44,9 +45,13 @@ export function createStore() {
44
45
  export function createSessionStore() {
45
46
  const sessionFile = configPath('session.json');
46
47
  let data = {};
47
- try {
48
- data = JSON.parse(readFileSync(sessionFile, 'utf-8'));
49
- } catch {}
48
+ if (existsSync(sessionFile)) {
49
+ try {
50
+ data = JSON.parse(readFileSync(sessionFile, 'utf-8'));
51
+ } catch (err) {
52
+ console.warn(`warning: failed to read ${sessionFile}: ${errorMessage(err)}`);
53
+ }
54
+ }
50
55
  return {
51
56
  set: async (key, value) => {
52
57
  data[key] = value;
@@ -64,18 +69,22 @@ export function createSessionStore() {
64
69
 
65
70
  export function checkSession(did) {
66
71
  // Check project-local app-password session
72
+ const localPath = join(process.cwd(), '.vit', 'login.json');
67
73
  try {
68
- const localPath = join(process.cwd(), '.vit', 'login.json');
69
74
  if (existsSync(localPath)) {
70
75
  const local = JSON.parse(readFileSync(localPath, 'utf-8'));
71
76
  if (local.did === did && local.type === 'app-password' && local.session?.accessJwt) {
72
77
  return did;
73
78
  }
74
79
  }
75
- } catch {}
80
+ } catch (err) {
81
+ console.warn(`warning: failed to read ${localPath}: ${errorMessage(err)}`);
82
+ }
76
83
 
84
+ const sessionFile = configPath('session.json');
85
+ if (!existsSync(sessionFile)) return null;
77
86
  try {
78
- const raw = readFileSync(configPath('session.json'), 'utf-8');
87
+ const raw = readFileSync(sessionFile, 'utf-8');
79
88
  const data = JSON.parse(raw);
80
89
  const entry = data[did];
81
90
  if (!entry) return null;
@@ -89,7 +98,8 @@ export function checkSession(did) {
89
98
  const accessValid = tokenSet.expires_at && new Date(tokenSet.expires_at) > new Date();
90
99
  if (accessValid || tokenSet.refresh_token) return did;
91
100
  return null;
92
- } catch {
101
+ } catch (err) {
102
+ console.warn(`warning: failed to read ${sessionFile}: ${errorMessage(err)}`);
93
103
  return null;
94
104
  }
95
105
  }
@@ -108,8 +118,8 @@ export function createOAuthClient({ stateStore, sessionStore, redirectUri }) {
108
118
 
109
119
  export async function restoreAgent(did) {
110
120
  // Check project-local app-password session
121
+ const localPath = join(process.cwd(), '.vit', 'login.json');
111
122
  try {
112
- const localPath = join(process.cwd(), '.vit', 'login.json');
113
123
  if (existsSync(localPath)) {
114
124
  const local = JSON.parse(readFileSync(localPath, 'utf-8'));
115
125
  if (local.did === did && local.type === 'app-password' && local.session) {
@@ -118,19 +128,26 @@ export async function restoreAgent(did) {
118
128
  return { agent, session: { did: local.did, handle: local.handle } };
119
129
  }
120
130
  }
121
- } catch {}
131
+ } catch (err) {
132
+ console.warn(`warning: failed to read ${localPath}: ${errorMessage(err)}`);
133
+ }
122
134
 
123
135
  // Check global app-password session
136
+ const sessionFile = configPath('session.json');
124
137
  try {
125
- const raw = readFileSync(configPath('session.json'), 'utf-8');
126
- const data = JSON.parse(raw);
127
- const entry = data[did];
128
- if (entry?.type === 'app-password' && entry.session) {
129
- const agent = new AtpAgent({ service: entry.service || 'https://bsky.social' });
130
- await agent.resumeSession(entry.session);
131
- return { agent, session: { did, handle: entry.session.handle } };
138
+ if (existsSync(sessionFile)) {
139
+ const raw = readFileSync(sessionFile, 'utf-8');
140
+ const data = JSON.parse(raw);
141
+ const entry = data[did];
142
+ if (entry?.type === 'app-password' && entry.session) {
143
+ const agent = new AtpAgent({ service: entry.service || 'https://bsky.social' });
144
+ await agent.resumeSession(entry.session);
145
+ return { agent, session: { did, handle: entry.session.handle } };
146
+ }
132
147
  }
133
- } catch {}
148
+ } catch (err) {
149
+ console.warn(`warning: failed to read ${sessionFile}: ${errorMessage(err)}`);
150
+ }
134
151
 
135
152
  // Existing OAuth restore path
136
153
  const sessionStore = createSessionStore();
package/src/lib/pds.js CHANGED
@@ -1,9 +1,35 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Copyright (c) 2026 sol pbc
3
3
 
4
+ import { errorMessage } from './error-format.js';
5
+
4
6
  const PLC_DIRECTORY = 'https://plc.directory';
5
7
  const pdsCache = new Map();
6
8
 
9
+ function requestErrorMessage(method, url, err) {
10
+ const code = err?.cause?.code || err?.code;
11
+ if (code === 'ECONNREFUSED') return `could not connect to ${url} (refused)`;
12
+ if (code === 'ENOTFOUND') return `could not resolve ${url}`;
13
+ if (code === 'ETIMEDOUT' || code === 'UND_ERR_CONNECT_TIMEOUT') {
14
+ return `timed out connecting to ${url}`;
15
+ }
16
+ return `request to ${url} failed: ${errorMessage(err)}`;
17
+ }
18
+
19
+ async function fetchJson(method, url) {
20
+ const requestUrl = url.toString();
21
+ try {
22
+ const res = await fetch(url);
23
+ if (!res.ok) throw new Error(`${method} ${requestUrl} returned ${res.status}`);
24
+ return await res.json();
25
+ } catch (err) {
26
+ if (err instanceof Error && err.message.startsWith(`${method} ${requestUrl} returned `)) {
27
+ throw err;
28
+ }
29
+ throw new Error(requestErrorMessage(method, requestUrl, err), { cause: err });
30
+ }
31
+ }
32
+
7
33
  async function fetchDidDocument(did) {
8
34
  let url;
9
35
  if (did.startsWith('did:web:')) {
@@ -19,9 +45,7 @@ async function fetchDidDocument(did) {
19
45
  url = `${PLC_DIRECTORY}/${did}`;
20
46
  }
21
47
 
22
- const res = await fetch(url);
23
- if (!res.ok) throw new Error(`failed to resolve DID document for ${did}: ${res.status} ${res.statusText}`);
24
- return res.json();
48
+ return fetchJson('GET', url);
25
49
  }
26
50
 
27
51
  export async function resolvePds(did) {
@@ -42,9 +66,7 @@ export async function listRecordsFromPds(pdsUrl, repo, collection, limit) {
42
66
  url.searchParams.set('collection', collection);
43
67
  if (limit) url.searchParams.set('limit', String(limit));
44
68
  if (cursor) url.searchParams.set('cursor', cursor);
45
- const res = await fetch(url);
46
- if (!res.ok) throw new Error(`listRecords failed for ${repo}: ${res.status} ${res.statusText}`);
47
- const data = await res.json();
69
+ const data = await fetchJson('GET', url);
48
70
  records.push(...data.records);
49
71
  cursor = data.cursor;
50
72
  } while (cursor);
@@ -56,16 +78,15 @@ export async function resolveHandleFromDid(did) {
56
78
  const doc = await fetchDidDocument(did);
57
79
  const aka = doc.alsoKnownAs?.find(a => a.startsWith('at://'));
58
80
  return aka ? aka.replace('at://', '') : did;
59
- } catch {
81
+ } catch (err) {
82
+ console.warn(`warning: failed to resolve handle for ${did}: ${errorMessage(err)}`);
60
83
  return did;
61
84
  }
62
85
  }
63
86
 
64
87
  export async function resolveHandle(handle) {
65
88
  const url = `https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`;
66
- const res = await fetch(url);
67
- if (!res.ok) throw new Error(`could not resolve handle: ${handle}`);
68
- const data = await res.json();
89
+ const data = await fetchJson('GET', url);
69
90
  return data.did;
70
91
  }
71
92
 
@@ -0,0 +1,103 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 sol pbc
3
+
4
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, join } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const DEFAULT_SKILL_NAME = 'using-vit';
10
+ const SOURCE_MISSING_ERROR = 'source skill files missing or empty';
11
+
12
+ function defaultSourceDir() {
13
+ return join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'skills', 'vit');
14
+ }
15
+
16
+ function errorMessage(err) {
17
+ if (err instanceof Error) return err.message || String(err);
18
+ return String(err);
19
+ }
20
+
21
+ function readSkillName(sourceDir) {
22
+ try {
23
+ const content = readFileSync(join(sourceDir, 'SKILL.md'), 'utf-8');
24
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
25
+ if (!match) return DEFAULT_SKILL_NAME;
26
+ const nameMatch = match[1].match(/^name:\s*(.+)$/m);
27
+ return nameMatch ? nameMatch[1].trim() : DEFAULT_SKILL_NAME;
28
+ } catch {
29
+ return DEFAULT_SKILL_NAME;
30
+ }
31
+ }
32
+
33
+ function sourceExists(sourceDir) {
34
+ try {
35
+ return existsSync(sourceDir) && readdirSync(sourceDir).length > 0;
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ export function skillInstallReason(skillResult) {
42
+ if (skillResult.results.some(result => result.status === 'source-missing')) {
43
+ return 'source skill files missing';
44
+ }
45
+
46
+ const failed = skillResult.results.filter(result => result.status === 'failed');
47
+ if (failed.length > 0) {
48
+ return failed
49
+ .map(result => `${result.label} failed: ${result.error || 'unknown error'}`)
50
+ .join('; ');
51
+ }
52
+
53
+ return 'skill install failed';
54
+ }
55
+
56
+ // sourceDir exists only as a test seam; production callers pass nothing.
57
+ export function ensureSkill({ sourceDir = defaultSourceDir() } = {}) {
58
+ const name = readSkillName(sourceDir);
59
+ const home = homedir();
60
+ const targets = [
61
+ { label: 'claude', path: join(home, '.claude', 'skills', name) },
62
+ { label: 'agents', path: join(home, '.agents', 'skills', name) },
63
+ ];
64
+
65
+ if (!sourceExists(sourceDir)) {
66
+ return {
67
+ name,
68
+ source: null,
69
+ ok: false,
70
+ results: targets.map(target => ({
71
+ ...target,
72
+ status: 'source-missing',
73
+ error: SOURCE_MISSING_ERROR,
74
+ })),
75
+ };
76
+ }
77
+
78
+ const results = targets.map(target => {
79
+ try {
80
+ const existed = existsSync(join(target.path, 'SKILL.md'));
81
+ mkdirSync(target.path, { recursive: true });
82
+ cpSync(sourceDir, target.path, { recursive: true, force: true });
83
+ return {
84
+ ...target,
85
+ status: existed ? 'already-present' : 'created',
86
+ error: null,
87
+ };
88
+ } catch (err) {
89
+ return {
90
+ ...target,
91
+ status: 'failed',
92
+ error: errorMessage(err),
93
+ };
94
+ }
95
+ });
96
+
97
+ return {
98
+ name,
99
+ source: sourceDir,
100
+ ok: results.every(result => result.status === 'created' || result.status === 'already-present'),
101
+ results,
102
+ };
103
+ }
@@ -12,8 +12,8 @@ const ACCEPT_FILE = 'dangerous-accept';
12
12
  * Returns { accepted: true } or { accepted: false }.
13
13
  * No TTL — once set, it's permanent until deleted.
14
14
  */
15
- export function checkDangerousAccept() {
16
- const p = join(vitDir(), ACCEPT_FILE);
15
+ export function checkDangerousAccept(dir) {
16
+ const p = join(vitDir(dir), ACCEPT_FILE);
17
17
  if (!existsSync(p)) return { accepted: false };
18
18
  try {
19
19
  JSON.parse(readFileSync(p, 'utf-8'));
@@ -30,8 +30,8 @@ export function checkDangerousAccept() {
30
30
  * Bypass condition: dangerous-accept flag is active.
31
31
  * Caller checks trusted.jsonl before calling this.
32
32
  */
33
- export function shouldBypassVet() {
34
- const accept = checkDangerousAccept();
33
+ export function shouldBypassVet(dir) {
34
+ const accept = checkDangerousAccept(dir);
35
35
  if (accept.accepted) {
36
36
  return { bypass: true, reason: 'dangerous-accept' };
37
37
  }
@@ -3,23 +3,25 @@
3
3
 
4
4
  import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
+ import { errorMessage } from './error-format.js';
6
7
 
7
- export function vitDir() {
8
- return join(process.cwd(), '.vit');
8
+ export function vitDir(dir) {
9
+ return join(dir || process.cwd(), '.vit');
9
10
  }
10
11
 
11
- export function readProjectConfig() {
12
- const p = join(vitDir(), 'config.json');
12
+ export function readProjectConfig(dir) {
13
+ const p = join(vitDir(dir), 'config.json');
13
14
  if (!existsSync(p)) return {};
14
15
  try {
15
16
  return JSON.parse(readFileSync(p, 'utf-8'));
16
- } catch {
17
+ } catch (err) {
18
+ console.warn(`warning: failed to read ${p}: ${errorMessage(err)}`);
17
19
  return {};
18
20
  }
19
21
  }
20
22
 
21
- export function readBeaconSet() {
22
- const config = readProjectConfig();
23
+ export function readBeaconSet(dir) {
24
+ const config = readProjectConfig(dir);
23
25
  const set = new Set();
24
26
  if (config.beacon) set.add(config.beacon);
25
27
  if (config.secondaryBeacon) set.add(config.secondaryBeacon);
@@ -32,38 +34,47 @@ export function writeProjectConfig(obj, baseDir) {
32
34
  writeFileSync(join(dir, 'config.json'), JSON.stringify(obj, null, 2) + '\n');
33
35
  }
34
36
 
35
- export function appendLog(filename, record) {
36
- const dir = vitDir();
37
- mkdirSync(dir, { recursive: true });
38
- appendFileSync(join(dir, filename), JSON.stringify(record) + '\n');
37
+ export function appendLog(filename, record, dir) {
38
+ const d = vitDir(dir);
39
+ mkdirSync(d, { recursive: true });
40
+ appendFileSync(join(d, filename), JSON.stringify(record) + '\n');
39
41
  }
40
42
 
41
- export function readLog(filename) {
42
- const p = join(vitDir(), filename);
43
+ export function readLog(filename, dir) {
44
+ const p = join(vitDir(dir), filename);
43
45
  if (!existsSync(p)) return [];
44
46
  try {
45
47
  return readFileSync(p, 'utf-8')
46
48
  .split('\n')
47
49
  .filter(line => line.trim())
48
- .map(line => { try { return JSON.parse(line); } catch { return null; } })
50
+ .map((line, index) => {
51
+ try {
52
+ return JSON.parse(line);
53
+ } catch (err) {
54
+ console.warn(`warning: skipping malformed line ${index + 1} in ${p}: ${errorMessage(err)}`);
55
+ return null;
56
+ }
57
+ })
49
58
  .filter(Boolean);
50
- } catch {
59
+ } catch (err) {
60
+ console.warn(`warning: failed to read ${p}: ${errorMessage(err)}`);
51
61
  return [];
52
62
  }
53
63
  }
54
64
 
55
- export function readFollowing() {
56
- const p = join(vitDir(), 'following.json');
65
+ export function readFollowing(dir) {
66
+ const p = join(vitDir(dir), 'following.json');
57
67
  if (!existsSync(p)) return [];
58
68
  try {
59
69
  return JSON.parse(readFileSync(p, 'utf-8'));
60
- } catch {
70
+ } catch (err) {
71
+ console.warn(`warning: failed to read ${p}: ${errorMessage(err)}`);
61
72
  return [];
62
73
  }
63
74
  }
64
75
 
65
- export function writeFollowing(list) {
66
- const dir = vitDir();
67
- mkdirSync(dir, { recursive: true });
68
- writeFileSync(join(dir, 'following.json'), JSON.stringify(list, null, 2) + '\n');
76
+ export function writeFollowing(list, dir) {
77
+ const d = vitDir(dir);
78
+ mkdirSync(d, { recursive: true });
79
+ writeFileSync(join(d, 'following.json'), JSON.stringify(list, null, 2) + '\n');
69
80
  }
@@ -1,26 +1,12 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Copyright (c) 2026 sol pbc
3
3
 
4
- import { spawnSync } from 'node:child_process';
5
- import { dirname, join } from 'node:path';
6
- import { fileURLToPath } from 'node:url';
4
+ import { ensureSkill } from './lib/skill-install.js';
7
5
 
8
6
  try {
9
- const currentFile = fileURLToPath(import.meta.url);
10
- const currentDir = dirname(currentFile);
11
- const skillDir = join(currentDir, '..', 'skills', 'vit');
12
- const result = spawnSync(
13
- 'npx',
14
- ['skills', 'add', skillDir, '-g', '-a', 'claude-code', '-y'],
15
- {
16
- encoding: 'utf-8',
17
- stdio: ['pipe', 'pipe', 'pipe'],
18
- }
19
- );
20
-
21
- if (result.status === 0) {
22
- console.log('vit: skill installed (using-vit)');
23
- }
7
+ const r = ensureSkill();
8
+ if (r.ok) console.log('vit: using-vit skill installed');
24
9
  } catch {
25
- process.exit(0);
26
10
  }
11
+
12
+ process.exit(0);