claude-second-brain 1.1.0 → 1.2.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/README.md +68 -30
- package/bin/agents.js +320 -0
- package/bin/create.js +665 -95
- package/package.json +2 -2
- package/template/AGENTS.md +9 -0
- package/template/README.md +21 -15
package/bin/create.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { cp, rename, access, readFile, writeFile, mkdir, rm } from "fs/promises"
|
|
3
|
-
import { readFileSync } from "fs"
|
|
3
|
+
import { readFileSync, readdirSync } from "fs"
|
|
4
4
|
import { join, dirname } from "path"
|
|
5
5
|
import { fileURLToPath } from "url"
|
|
6
|
-
import { spawnSync } from "child_process"
|
|
6
|
+
import { spawn, spawnSync } from "child_process"
|
|
7
7
|
import { homedir } from "os"
|
|
8
8
|
import * as p from "@clack/prompts"
|
|
9
9
|
import pc from "picocolors"
|
|
10
|
+
import {
|
|
11
|
+
AGENTS, AGENT_IDS, CANONICAL_GLOBAL_DIR, detectAgents,
|
|
12
|
+
installProjectSkills, linkGlobalSkill, parseAgentFlags, resolveAgents, writeCanonicalSkill,
|
|
13
|
+
} from "./agents.js"
|
|
10
14
|
|
|
11
15
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
12
16
|
const TEMPLATE = join(__dirname, "../template")
|
|
@@ -39,6 +43,62 @@ function tailForError({ stdout, stderr }, lines = 10) {
|
|
|
39
43
|
return trimmed.split("\n").slice(-lines).join("\n")
|
|
40
44
|
}
|
|
41
45
|
|
|
46
|
+
// Async variant for long-running steps: doesn't block the event loop, so the
|
|
47
|
+
// spinner keeps animating. `onLine` receives each non-empty output line.
|
|
48
|
+
function runAsync(cmd, cwd, { onLine } = {}) {
|
|
49
|
+
return new Promise(resolve => {
|
|
50
|
+
let stdout = ""
|
|
51
|
+
let stderr = ""
|
|
52
|
+
let child
|
|
53
|
+
try {
|
|
54
|
+
child = spawn(cmd[0], cmd.slice(1), { cwd, stdio: ["ignore", "pipe", "pipe"] })
|
|
55
|
+
} catch (err) {
|
|
56
|
+
resolve({ ok: false, stdout, stderr: err.message })
|
|
57
|
+
return
|
|
58
|
+
}
|
|
59
|
+
const feed = chunk => {
|
|
60
|
+
if (!onLine) return
|
|
61
|
+
for (const line of chunk.split(/\r?\n|\r/)) {
|
|
62
|
+
const clean = stripAnsi(line).trim()
|
|
63
|
+
if (clean) onLine(clean)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
child.stdout.on("data", d => { const t = d.toString(); stdout += t; feed(t) })
|
|
67
|
+
child.stderr.on("data", d => { const t = d.toString(); stderr += t; feed(t) })
|
|
68
|
+
child.on("error", err => resolve({ ok: false, stdout, stderr: stderr + err.message }))
|
|
69
|
+
child.on("close", code => resolve({ ok: code === 0, stdout, stderr }))
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Run a long step under the spinner, showing elapsed time and the latest
|
|
74
|
+
// line of output so it's obvious the CLI isn't stuck.
|
|
75
|
+
async function runStep(spin, label, cmd, cwd) {
|
|
76
|
+
const started = Date.now()
|
|
77
|
+
let last = ""
|
|
78
|
+
const render = () => {
|
|
79
|
+
const secs = Math.round((Date.now() - started) / 1000)
|
|
80
|
+
const detail = last ? ` ${pc.dim(truncate(last, 60))}` : ""
|
|
81
|
+
spin.message(`${label} ${pc.dim(`(${secs}s)`)}${detail}`)
|
|
82
|
+
}
|
|
83
|
+
spin.start(label)
|
|
84
|
+
const timer = setInterval(render, 1000)
|
|
85
|
+
try {
|
|
86
|
+
const res = await runAsync(cmd, cwd, { onLine: l => { last = l } })
|
|
87
|
+
return { ...res, seconds: Math.round((Date.now() - started) / 1000) }
|
|
88
|
+
} finally {
|
|
89
|
+
clearInterval(timer)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Use the pnpm already on PATH when it's recent enough (the CLI itself runs on
|
|
94
|
+
// Node >= 22), so a fresh scaffold doesn't download node + pnpm through mise.
|
|
95
|
+
function systemPnpmUsable() {
|
|
96
|
+
const r = spawnSync("pnpm", ["--version"], { stdio: "pipe", encoding: "utf8" })
|
|
97
|
+
if (r.status !== 0) return false
|
|
98
|
+
const major = parseInt((r.stdout || "").trim().split(".")[0], 10)
|
|
99
|
+
return major >= 10 && parseInt(process.versions.node.split(".")[0], 10) >= 22
|
|
100
|
+
}
|
|
101
|
+
|
|
42
102
|
// Interactive commands (e.g. gh auth login) — must inherit stdio; call outside spinner
|
|
43
103
|
function runInteractive(cmd, cwd) {
|
|
44
104
|
const result = spawnSync(cmd[0], cmd.slice(1), { cwd, stdio: "inherit" })
|
|
@@ -87,6 +147,24 @@ function extractBearerToken(stdout) {
|
|
|
87
147
|
return candidates[0] || null
|
|
88
148
|
}
|
|
89
149
|
|
|
150
|
+
// Spinner wrapper: clack redraws the spinner line in place, which breaks into
|
|
151
|
+
// one new line per frame if the message wraps past the terminal width. Clamp
|
|
152
|
+
// every start/message to a single line that fits.
|
|
153
|
+
function fitLine(msg) {
|
|
154
|
+
const max = Math.max(20, (process.stdout.columns || 80) - 6)
|
|
155
|
+
const oneLine = String(msg).replace(/\s*\n\s*/g, " ")
|
|
156
|
+
const plain = stripAnsi(oneLine)
|
|
157
|
+
return plain.length > max ? plain.slice(0, max - 1) + "…" : oneLine
|
|
158
|
+
}
|
|
159
|
+
function makeSpinner() {
|
|
160
|
+
const spin = p.spinner()
|
|
161
|
+
return {
|
|
162
|
+
start: msg => spin.start(fitLine(msg)),
|
|
163
|
+
message: msg => spin.message(fitLine(msg)),
|
|
164
|
+
stop: (msg, code) => spin.stop(msg, code),
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
90
168
|
function truncate(s, n = 80) {
|
|
91
169
|
if (!s) return ""
|
|
92
170
|
return s.length > n ? s.slice(0, n) + "…" : s
|
|
@@ -95,6 +173,111 @@ function truncate(s, n = 80) {
|
|
|
95
173
|
// End-to-end Cloudflare Artifacts setup: auth, create repo, set remote, push.
|
|
96
174
|
// Every failure logs the exact step, exit codes, stderr, and HTTP bodies so the
|
|
97
175
|
// user can see where in the flow the break happened.
|
|
176
|
+
// Artifacts REST API: https://developers.cloudflare.com/artifacts/api/rest-api/
|
|
177
|
+
// Routes are account-scoped under the standard Cloudflare v4 API. (The
|
|
178
|
+
// artifacts.cloudflare.net/v1/api host from the beta announcement rejects
|
|
179
|
+
// wrangler OAuth tokens with 403 / code 10002.)
|
|
180
|
+
// Icons for the git-remote picker. Terminals can't draw SVG inside a prompt
|
|
181
|
+
// that redraws on every keypress, so the real logos come from Nerd Font
|
|
182
|
+
// glyphs: Ghostty, WezTerm and kitty bundle them, so they're on by default
|
|
183
|
+
// there. Anywhere else (iTerm2, Terminal.app, …) we fall back to emoji unless
|
|
184
|
+
// CSB_ICONS=nerd says a Nerd Font is installed. CSB_ICONS=emoji|none override.
|
|
185
|
+
function iconStyle() {
|
|
186
|
+
const forced = process.env.CSB_ICONS?.trim().toLowerCase()
|
|
187
|
+
if (forced === "nerd" || forced === "emoji" || forced === "none") return forced
|
|
188
|
+
const term = process.env.TERM_PROGRAM?.toLowerCase() || ""
|
|
189
|
+
if (term === "ghostty" || term === "wezterm" || process.env.KITTY_WINDOW_ID || process.env.TERM === "xterm-kitty") return "nerd"
|
|
190
|
+
return "emoji"
|
|
191
|
+
}
|
|
192
|
+
const CF_ORANGE = (s) => (pc.isColorSupported ? `\x1b[38;2;243;128;32m${s}\x1b[39m` : s)
|
|
193
|
+
const REMOTE_ICONS = {
|
|
194
|
+
// nf-fa-github, nf-fa-cloud (filled, in Cloudflare orange — the
|
|
195
|
+
// nf-dev-cloudflare glyph renders tiny), nf-oct-file_directory.
|
|
196
|
+
// Each entry includes its trailing gap: Nerd glyphs are drawn ~1.5 cells
|
|
197
|
+
// wide so one space reads right; emoji are 2 cells and want two.
|
|
198
|
+
nerd: { github: "\uf09b ", cloudflare: CF_ORANGE("\uf0c2") + " ", none: "\uf413 " },
|
|
199
|
+
emoji: { github: "🐙 ", cloudflare: "⛅ ", none: "📁 " },
|
|
200
|
+
none: { github: "", cloudflare: "", none: "" },
|
|
201
|
+
}[iconStyle()]
|
|
202
|
+
|
|
203
|
+
const CF_API = "https://api.cloudflare.com/client/v4"
|
|
204
|
+
function artifactsBase(accountId, namespace) {
|
|
205
|
+
return `${CF_API}/accounts/${accountId}/artifacts/namespaces/${namespace}`
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
209
|
+
|
|
210
|
+
function cfErrorCodes(rawBody) {
|
|
211
|
+
try { return (JSON.parse(rawBody)?.errors || []).map((e) => e?.code) } catch { return [] }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function isNamespaceInactive(res, rawBody) {
|
|
215
|
+
return res.status === 404 && (cfErrorCodes(rawBody).includes(10200) || /namespace is not active/i.test(rawBody))
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Make sure an Artifacts namespace exists and is usable. Creates it when
|
|
219
|
+
// missing; tolerates "already exists" and 409 (activation / deletion in
|
|
220
|
+
// progress) by polling until it settles. Returns { ok, error? }.
|
|
221
|
+
async function ensureArtifactsNamespace({ accountId, namespace, token }) {
|
|
222
|
+
const url = `${CF_API}/accounts/${accountId}/artifacts/namespaces`
|
|
223
|
+
const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }
|
|
224
|
+
let lastError = "unknown error"
|
|
225
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
226
|
+
let res, body = ""
|
|
227
|
+
try {
|
|
228
|
+
res = await fetch(url, { method: "POST", headers, body: JSON.stringify({ namespace }) })
|
|
229
|
+
body = await res.text()
|
|
230
|
+
} catch (err) {
|
|
231
|
+
return { ok: false, error: `network error: ${err.message}` }
|
|
232
|
+
}
|
|
233
|
+
if (res.ok) return { ok: true, created: true }
|
|
234
|
+
let msg = "unknown error"
|
|
235
|
+
try { msg = JSON.parse(body)?.errors?.[0]?.message || msg } catch {}
|
|
236
|
+
lastError = `HTTP ${res.status}: ${msg}`
|
|
237
|
+
if (res.status === 401 || res.status === 403) return { ok: false, error: lastError }
|
|
238
|
+
// Already exists → fine, the repo-create retry loop handles activation lag.
|
|
239
|
+
if (/already exists/i.test(msg)) return { ok: true, created: false }
|
|
240
|
+
// 409 = activation or deletion in progress; anything else, back off and retry.
|
|
241
|
+
await sleep(Math.min(1000 * 2 ** attempt, 8000))
|
|
242
|
+
}
|
|
243
|
+
return { ok: false, error: lastError }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Account ID from a repo remote like https://<ACCOUNT_ID>.artifacts.cloudflare.net/git/<ns>/<repo>.git
|
|
247
|
+
function accountIdFromRemote(url) {
|
|
248
|
+
const m = (url || "").match(/^https?:\/\/([0-9a-f]{32})\.artifacts\.cloudflare\.net\//i)
|
|
249
|
+
return m ? m[1] : null
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Resolve the Cloudflare account to create the repo in:
|
|
253
|
+
// CLOUDFLARE_ACCOUNT_ID, else the token's only account, else ask.
|
|
254
|
+
async function resolveCloudflareAccountId(token, { interactive = false } = {}) {
|
|
255
|
+
const fromEnv = process.env.CLOUDFLARE_ACCOUNT_ID?.trim()
|
|
256
|
+
if (fromEnv) return { id: fromEnv }
|
|
257
|
+
let data
|
|
258
|
+
try {
|
|
259
|
+
const res = await fetch(`${CF_API}/accounts?per_page=50`, { headers: { Authorization: `Bearer ${token}` } })
|
|
260
|
+
data = await res.json()
|
|
261
|
+
if (!res.ok || !data?.success) {
|
|
262
|
+
return { error: `listing accounts failed (HTTP ${res.status}): ${data?.errors?.[0]?.message || "unknown error"}` }
|
|
263
|
+
}
|
|
264
|
+
} catch (err) {
|
|
265
|
+
return { error: `listing accounts failed: ${err.message}` }
|
|
266
|
+
}
|
|
267
|
+
const accounts = data.result || []
|
|
268
|
+
if (accounts.length === 0) return { error: "this token can't see any Cloudflare accounts" }
|
|
269
|
+
if (accounts.length === 1) return { id: accounts[0].id, name: accounts[0].name }
|
|
270
|
+
if (!interactive) {
|
|
271
|
+
return { error: `token can access ${accounts.length} accounts — set CLOUDFLARE_ACCOUNT_ID to pick one` }
|
|
272
|
+
}
|
|
273
|
+
const picked = await p.select({
|
|
274
|
+
message: "Which Cloudflare account?",
|
|
275
|
+
options: accounts.map(a => ({ value: a.id, label: a.name, hint: a.id })),
|
|
276
|
+
})
|
|
277
|
+
if (p.isCancel(picked)) return { error: "no account selected" }
|
|
278
|
+
return { id: picked, name: accounts.find(a => a.id === picked)?.name }
|
|
279
|
+
}
|
|
280
|
+
|
|
98
281
|
async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
|
|
99
282
|
// Honor an existing API token as a shortcut — skip wrangler entirely.
|
|
100
283
|
let cfApiToken = process.env.CLOUDFLARE_API_TOKEN
|
|
@@ -174,13 +357,17 @@ async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
|
|
|
174
357
|
|
|
175
358
|
p.log.info(`Using token from ${tokenSource} (length ${cfApiToken.length}, prefix ${cfApiToken.slice(0, 8)}…)`)
|
|
176
359
|
|
|
177
|
-
const
|
|
178
|
-
|
|
360
|
+
const account = await resolveCloudflareAccountId(cfApiToken, { interactive: Boolean(process.stdin.isTTY) })
|
|
361
|
+
if (!account.id) {
|
|
362
|
+
p.log.warn(`Could not determine your Cloudflare account: ${account.error}`)
|
|
363
|
+
return null
|
|
364
|
+
}
|
|
365
|
+
const baseUrl = artifactsBase(account.id, namespace)
|
|
366
|
+
p.log.info(`Artifacts API: ${pc.dim(baseUrl)}`)
|
|
367
|
+
spin.start(`Creating Cloudflare Artifact ${pc.dim(repoName)}`)
|
|
179
368
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
try {
|
|
183
|
-
res = await fetch(`${baseUrl}/repos`, {
|
|
369
|
+
const createRepo = async () => {
|
|
370
|
+
const r = await fetch(`${baseUrl}/repos`, {
|
|
184
371
|
method: "POST",
|
|
185
372
|
headers: {
|
|
186
373
|
"Authorization": `Bearer ${cfApiToken}`,
|
|
@@ -188,7 +375,38 @@ async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
|
|
|
188
375
|
},
|
|
189
376
|
body: JSON.stringify({ name: repoName, default_branch: "main" }),
|
|
190
377
|
})
|
|
191
|
-
rawBody
|
|
378
|
+
return { res: r, rawBody: await r.text() }
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
let res
|
|
382
|
+
let rawBody = ""
|
|
383
|
+
try {
|
|
384
|
+
;({ res, rawBody } = await createRepo())
|
|
385
|
+
// A namespace that was deleted (or is still being deleted) answers
|
|
386
|
+
// 404 / code 10200 "Namespace is not active". Recreate it, wait for it
|
|
387
|
+
// to become active, and retry the repo create.
|
|
388
|
+
if (isNamespaceInactive(res, rawBody)) {
|
|
389
|
+
spin.message(`Namespace ${pc.dim(namespace)} is not active — creating it`)
|
|
390
|
+
const ns = await ensureArtifactsNamespace({ accountId: account.id, namespace, token: cfApiToken })
|
|
391
|
+
if (!ns.ok) {
|
|
392
|
+
spin.stop(`Could not activate Artifacts namespace "${namespace}": ${ns.error}`, 1)
|
|
393
|
+
p.log.warn([
|
|
394
|
+
"To fix:",
|
|
395
|
+
` • wait a minute and run ${pc.cyan("csb")} again (a just-deleted namespace can take a moment to clear), or`,
|
|
396
|
+
` • pick a different namespace when prompted, or`,
|
|
397
|
+
` • create it in the Cloudflare dashboard (Artifacts → Namespaces → Create "${namespace}")`,
|
|
398
|
+
].join("\n"))
|
|
399
|
+
return null
|
|
400
|
+
}
|
|
401
|
+
spin.stop(`Cloudflare namespace ${ns.created ? "created" : "reactivated"}: ${namespace}`)
|
|
402
|
+
spin.start(`Creating Cloudflare Artifact ${pc.dim(repoName)}`)
|
|
403
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
404
|
+
spin.message(`Creating Cloudflare Artifact ${pc.dim(repoName)}`)
|
|
405
|
+
;({ res, rawBody } = await createRepo())
|
|
406
|
+
if (!isNamespaceInactive(res, rawBody)) break
|
|
407
|
+
await sleep(Math.min(1000 * 2 ** attempt, 8000))
|
|
408
|
+
}
|
|
409
|
+
}
|
|
192
410
|
} catch (err) {
|
|
193
411
|
spin.stop(`Network error calling Artifacts API: ${err.message}`, 1)
|
|
194
412
|
return null
|
|
@@ -207,6 +425,14 @@ async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
|
|
|
207
425
|
const errMsg = createData?.errors?.[0]?.message || createData?.message || "unknown error"
|
|
208
426
|
spin.stop(`Artifacts API failed (HTTP ${res.status}): ${errMsg}`, 1)
|
|
209
427
|
p.log.warn(`full response: ${truncate(rawBody, 400)}`)
|
|
428
|
+
if (res.status === 401 || res.status === 403) {
|
|
429
|
+
p.log.warn([
|
|
430
|
+
"Check that:",
|
|
431
|
+
` • Artifacts is enabled for account ${account.name ? `"${account.name}" ` : ""}(${account.id}) — it needs the Workers Paid plan`,
|
|
432
|
+
" • your token has Artifacts > Edit (API token) or the artifacts:write scope (wrangler login)",
|
|
433
|
+
" • CLOUDFLARE_ACCOUNT_ID points at the right account, if you set it",
|
|
434
|
+
].join("\n"))
|
|
435
|
+
}
|
|
210
436
|
return null
|
|
211
437
|
}
|
|
212
438
|
|
|
@@ -236,12 +462,12 @@ async function setupCloudflareRemote({ targetDir, repoName, namespace, spin }) {
|
|
|
236
462
|
const stdout = pushResult.stdout?.toString().trim()
|
|
237
463
|
if (stderr) p.log.warn(`git stderr: ${truncate(stderr, 400)}`)
|
|
238
464
|
if (stdout) p.log.warn(`git stdout: ${truncate(stdout, 400)}`)
|
|
239
|
-
return { repoToken, remote }
|
|
465
|
+
return { repoToken, remote, accountId: account.id, pushed: false }
|
|
240
466
|
}
|
|
241
467
|
|
|
242
468
|
spin.stop(`Cloudflare Artifact created: ${pc.cyan(repoName)}`)
|
|
243
469
|
p.log.info(`Remote: ${pc.dim(remote)}`)
|
|
244
|
-
return { repoToken, remote }
|
|
470
|
+
return { repoToken, remote, accountId: account.id, pushed: true }
|
|
245
471
|
}
|
|
246
472
|
|
|
247
473
|
function parseGithubRepo(url) {
|
|
@@ -252,10 +478,11 @@ function parseGithubRepo(url) {
|
|
|
252
478
|
|
|
253
479
|
function parseCloudflareArtifact(url) {
|
|
254
480
|
if (!url || !/artifacts\.cloudflare/.test(url)) return null
|
|
481
|
+
const accountId = accountIdFromRemote(url)
|
|
255
482
|
const explicit = url.match(/namespaces\/([^/]+)\/repos\/([^/.]+)/)
|
|
256
|
-
if (explicit) return { namespace: explicit[1], repo: explicit[2] }
|
|
483
|
+
if (explicit) return { namespace: explicit[1], repo: explicit[2], accountId }
|
|
257
484
|
const parts = url.replace(/\.git$/, "").split("/").filter(Boolean)
|
|
258
|
-
if (parts.length >= 2) return { namespace: parts[parts.length - 2], repo: parts[parts.length - 1] }
|
|
485
|
+
if (parts.length >= 2) return { namespace: parts[parts.length - 2], repo: parts[parts.length - 1], accountId }
|
|
259
486
|
return null
|
|
260
487
|
}
|
|
261
488
|
|
|
@@ -281,11 +508,16 @@ function deleteGithubRepo(slug) {
|
|
|
281
508
|
return { ok: true }
|
|
282
509
|
}
|
|
283
510
|
|
|
284
|
-
async function deleteCloudflareArtifact({ namespace, repo }) {
|
|
511
|
+
async function deleteCloudflareArtifact({ namespace, repo, accountId }) {
|
|
285
512
|
const auth = await resolveCloudflareToken()
|
|
286
513
|
if (!auth) return { ok: false, error: "no Cloudflare API token (set CLOUDFLARE_API_TOKEN or run `wrangler login`)" }
|
|
514
|
+
if (!accountId) {
|
|
515
|
+
const account = await resolveCloudflareAccountId(auth.token, { interactive: Boolean(process.stdin.isTTY) })
|
|
516
|
+
if (!account.id) return { ok: false, error: account.error }
|
|
517
|
+
accountId = account.id
|
|
518
|
+
}
|
|
287
519
|
try {
|
|
288
|
-
const res = await fetch(
|
|
520
|
+
const res = await fetch(`${artifactsBase(accountId, namespace)}/repos/${repo}`, {
|
|
289
521
|
method: "DELETE",
|
|
290
522
|
headers: { Authorization: `Bearer ${auth.token}` },
|
|
291
523
|
})
|
|
@@ -300,6 +532,11 @@ async function deleteCloudflareArtifact({ namespace, repo }) {
|
|
|
300
532
|
}
|
|
301
533
|
|
|
302
534
|
const GLOBAL_SKILLS = ["brain-ingest", "brain-search", "brain-refresh"]
|
|
535
|
+
// Vault-local skills: every template skill that isn't global.
|
|
536
|
+
const LOCAL_SKILLS = readdirSync(join(TEMPLATE, ".claude", "skills"), { withFileTypes: true })
|
|
537
|
+
.filter(d => d.isDirectory() && !GLOBAL_SKILLS.includes(d.name))
|
|
538
|
+
.map(d => d.name)
|
|
539
|
+
const CANONICAL_PROJECT_DIR_LABEL = ".agents/skills (project) and ~/.agents/skills (global)"
|
|
303
540
|
|
|
304
541
|
async function readSkillVersion(skillDir) {
|
|
305
542
|
try {
|
|
@@ -310,6 +547,14 @@ async function readSkillVersion(skillDir) {
|
|
|
310
547
|
}
|
|
311
548
|
}
|
|
312
549
|
|
|
550
|
+
// Installed version of a global skill: the canonical ~/.agents/skills copy,
|
|
551
|
+
// falling back to a legacy ~/.claude/skills copy from releases before
|
|
552
|
+
// multi-agent install.
|
|
553
|
+
async function readInstalledGlobalVersion(name) {
|
|
554
|
+
return (await readSkillVersion(join(CANONICAL_GLOBAL_DIR, name)))
|
|
555
|
+
|| (await readSkillVersion(join(homedir(), ".claude", "skills", name)))
|
|
556
|
+
}
|
|
557
|
+
|
|
313
558
|
// Decide whether to (re)install each global skill. Returns a map name→"install"|"skip".
|
|
314
559
|
// Interactive mismatch prompts once per run with update-all / skip-all / ask-per-skill.
|
|
315
560
|
async function planGlobalSkillInstall({ isInteractive }) {
|
|
@@ -317,12 +562,13 @@ async function planGlobalSkillInstall({ isInteractive }) {
|
|
|
317
562
|
const mismatches = []
|
|
318
563
|
|
|
319
564
|
for (const name of GLOBAL_SKILLS) {
|
|
320
|
-
const
|
|
321
|
-
const
|
|
565
|
+
const installed = await readInstalledGlobalVersion(name)
|
|
566
|
+
const hasCanonical = await readSkillVersion(join(CANONICAL_GLOBAL_DIR, name))
|
|
322
567
|
if (!installed) {
|
|
323
568
|
decisions[name] = "install"
|
|
324
569
|
} else if (installed === version) {
|
|
325
|
-
|
|
570
|
+
// Same version but only a legacy copy exists: migrate to the canonical dir.
|
|
571
|
+
decisions[name] = hasCanonical ? "skip" : "install"
|
|
326
572
|
} else {
|
|
327
573
|
mismatches.push({ name, installed })
|
|
328
574
|
}
|
|
@@ -366,40 +612,230 @@ async function planGlobalSkillInstall({ isInteractive }) {
|
|
|
366
612
|
return decisions
|
|
367
613
|
}
|
|
368
614
|
|
|
369
|
-
|
|
370
|
-
|
|
615
|
+
// Install the global skills for each selected agent, the way `npx skills` does:
|
|
616
|
+
// one real copy in ~/.agents/skills/<name>, then a symlink (or copy, with
|
|
617
|
+
// --copy or when symlinks fail) in every agent's own global skills dir.
|
|
618
|
+
// Universal agents (Codex, Cursor, Copilot, …) read ~/.agents/skills directly.
|
|
619
|
+
async function installGlobalSkills({ isInteractive, agents, copy = false }) {
|
|
371
620
|
const decisions = await planGlobalSkillInstall({ isInteractive })
|
|
372
621
|
|
|
373
622
|
const installed = []
|
|
374
623
|
const skipped = []
|
|
375
624
|
const sameVersion = []
|
|
625
|
+
const links = []
|
|
376
626
|
|
|
377
|
-
|
|
378
|
-
const destDir = join(globalSkillsDir, name)
|
|
627
|
+
for (const name of GLOBAL_SKILLS) {
|
|
379
628
|
const decision = decisions[name]
|
|
629
|
+
const canonical = join(CANONICAL_GLOBAL_DIR, name)
|
|
380
630
|
|
|
381
631
|
if (decision === "skip") {
|
|
382
632
|
// Differentiate "already at this version" from "user declined update" for logging.
|
|
383
|
-
const current = await
|
|
633
|
+
const current = await readInstalledGlobalVersion(name)
|
|
384
634
|
if (current === version) sameVersion.push(name)
|
|
385
635
|
else skipped.push(name)
|
|
386
|
-
|
|
636
|
+
// A declined update with only a legacy copy: leave everything untouched.
|
|
637
|
+
if (!(await readSkillVersion(canonical))) continue
|
|
638
|
+
} else {
|
|
639
|
+
const content = await readFile(join(TEMPLATE, ".claude/skills", name, "SKILL.md"), "utf8")
|
|
640
|
+
await writeCanonicalSkill(name, {
|
|
641
|
+
"SKILL.md": content,
|
|
642
|
+
".csb-version": JSON.stringify({ version, installed: new Date().toISOString() }, null, 2) + "\n",
|
|
643
|
+
})
|
|
644
|
+
installed.push(name)
|
|
387
645
|
}
|
|
388
646
|
|
|
389
|
-
|
|
390
|
-
|
|
647
|
+
// (Re)link for every selected agent — idempotent, so newly added agents
|
|
648
|
+
// pick up skills even when the canonical copy is already current.
|
|
649
|
+
for (const id of agents) {
|
|
650
|
+
links.push({ name, ...(await linkGlobalSkill(id, name, { copy })) })
|
|
651
|
+
}
|
|
652
|
+
}
|
|
391
653
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
)
|
|
399
|
-
|
|
400
|
-
|
|
654
|
+
return { installed, skipped, sameVersion, links }
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function summarizeAgentInstall(agents, links, toDisplayPath) {
|
|
658
|
+
return agents.map(id => {
|
|
659
|
+
const own = links.filter(l => l.agent === id)
|
|
660
|
+
const mode = own.some(l => l.mode === "copy") ? "copy"
|
|
661
|
+
: own.some(l => l.mode === "symlink") ? "symlink" : "canonical"
|
|
662
|
+
const where = mode === "canonical"
|
|
663
|
+
? toDisplayPath(CANONICAL_GLOBAL_DIR)
|
|
664
|
+
: toDisplayPath(dirname(own[0]?.path || ""))
|
|
665
|
+
return ` ${AGENTS[id].displayName.padEnd(15)} ${pc.dim(`${where}${mode === "canonical" ? "" : ` (${mode})`}`)}`
|
|
666
|
+
}).join("\n")
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// "Next steps" lines for the agents the user picked: how to open each one in
|
|
670
|
+
// the vault. Agents without a CLI get an "open this folder in …" hint.
|
|
671
|
+
function agentLaunchSteps(agents) {
|
|
672
|
+
const lines = agents.map(id => {
|
|
673
|
+
const { launch, displayName } = AGENTS[id]
|
|
674
|
+
return launch?.cmd
|
|
675
|
+
? `${pc.cyan(launch.cmd.padEnd(16))} open ${displayName} and start ingesting sources`
|
|
676
|
+
: `${pc.dim("# ")}open this folder in ${launch?.app || displayName}${displayName !== launch?.app && launch?.app ? ` (${displayName})` : ""}`
|
|
677
|
+
})
|
|
678
|
+
return lines.length ? lines : [`${pc.cyan("claude".padEnd(16))} open Claude Code and start ingesting sources`]
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// Mint a repo-scoped Artifacts git token and store it as an http.extraHeader
|
|
682
|
+
// for that remote in the brain's .git/config (local only, never committed),
|
|
683
|
+
// so plain `git push` / `git pull` work until it expires.
|
|
684
|
+
// Artifacts git tokens: minimum 60s, maximum 1 year (API limit). We default
|
|
685
|
+
// to 90 days so a brain keeps syncing for a season without renewing.
|
|
686
|
+
const GIT_TOKEN_TTL_DEFAULT = 90 * 86400
|
|
687
|
+
const GIT_TOKEN_TTL_MAX = 365 * 86400
|
|
688
|
+
|
|
689
|
+
// "90d", "12h", "30m", "1y", or plain seconds → seconds.
|
|
690
|
+
function parseTtl(v) {
|
|
691
|
+
const m = String(v ?? "").trim().match(/^(\d+)\s*([smhdwy]?)$/i)
|
|
692
|
+
if (!m) return NaN
|
|
693
|
+
const mult = { "": 1, s: 1, m: 60, h: 3600, d: 86400, w: 604800, y: 31536000 }[m[2].toLowerCase()]
|
|
694
|
+
return parseInt(m[1], 10) * mult
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
function formatTtl(secs) {
|
|
698
|
+
if (secs % 31536000 === 0) return `${secs / 31536000} year${secs === 31536000 ? "" : "s"}`
|
|
699
|
+
if (secs % 86400 === 0) return `${secs / 86400} day${secs === 86400 ? "" : "s"}`
|
|
700
|
+
if (secs % 3600 === 0) return `${secs / 3600}h`
|
|
701
|
+
return `${Math.round(secs / 60)} min`
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
async function mintArtifactsGitToken({ remote, cwd, ttl = GIT_TOKEN_TTL_DEFAULT, scope = "write", interactive = false }) {
|
|
705
|
+
const parsed = parseCloudflareArtifact(remote)
|
|
706
|
+
if (!parsed) return { ok: false, error: `not a Cloudflare Artifacts remote: ${remote || "(none)"}` }
|
|
707
|
+
const auth = await resolveCloudflareToken()
|
|
708
|
+
if (!auth) return { ok: false, error: "no Cloudflare credentials — run `wrangler login` or set CLOUDFLARE_API_TOKEN" }
|
|
709
|
+
let accountId = parsed.accountId
|
|
710
|
+
if (!accountId) {
|
|
711
|
+
const account = await resolveCloudflareAccountId(auth.token, { interactive })
|
|
712
|
+
if (!account.id) return { ok: false, error: account.error }
|
|
713
|
+
accountId = account.id
|
|
714
|
+
}
|
|
715
|
+
let data
|
|
716
|
+
try {
|
|
717
|
+
const res = await fetch(`${artifactsBase(accountId, parsed.namespace)}/tokens`, {
|
|
718
|
+
method: "POST",
|
|
719
|
+
headers: { Authorization: `Bearer ${auth.token}`, "Content-Type": "application/json" },
|
|
720
|
+
body: JSON.stringify({ repo: parsed.repo, scope, ttl }),
|
|
721
|
+
})
|
|
722
|
+
data = await res.json().catch(() => ({}))
|
|
723
|
+
if (!res.ok || !data?.success) {
|
|
724
|
+
return { ok: false, error: `Artifacts API (HTTP ${res.status}): ${data?.errors?.[0]?.message || "unknown error"}` }
|
|
725
|
+
}
|
|
726
|
+
} catch (err) {
|
|
727
|
+
return { ok: false, error: err.message }
|
|
728
|
+
}
|
|
729
|
+
const token = data.result?.plaintext || data.result?.token
|
|
730
|
+
if (!token) return { ok: false, error: "Artifacts API response had no token" }
|
|
731
|
+
const expiresAt = data.result?.expires_at || null
|
|
732
|
+
if (cwd) setGitAuthHeader(cwd, remote, token)
|
|
733
|
+
return { ok: true, token, expiresAt, ...parsed, accountId }
|
|
734
|
+
}
|
|
401
735
|
|
|
402
|
-
|
|
736
|
+
function setGitAuthHeader(cwd, remote, token) {
|
|
737
|
+
const key = `http.${remote}.extraHeader`
|
|
738
|
+
spawnSync("git", ["config", "--local", "--unset-all", key], { cwd, stdio: "pipe" })
|
|
739
|
+
const r = spawnSync("git", ["config", "--local", "--add", key, `Authorization: Bearer ${token}`], { cwd, stdio: "pipe" })
|
|
740
|
+
return r.status === 0
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// `csb git-token [--brain <name>] [--ttl <duration>] [--read] [--print]`
|
|
744
|
+
async function cmdGitToken(args) {
|
|
745
|
+
let brainName = null
|
|
746
|
+
let ttl = GIT_TOKEN_TTL_DEFAULT
|
|
747
|
+
let scope = "write"
|
|
748
|
+
let printOnly = false
|
|
749
|
+
for (let i = 0; i < args.length; i++) {
|
|
750
|
+
const a = args[i]
|
|
751
|
+
if (a === "--brain") brainName = args[++i]
|
|
752
|
+
else if (a === "--ttl") ttl = parseTtl(args[++i])
|
|
753
|
+
else if (a.startsWith("--ttl=")) ttl = parseTtl(a.slice(6))
|
|
754
|
+
else if (a === "--read") scope = "read"
|
|
755
|
+
else if (a === "--print") printOnly = true
|
|
756
|
+
else if (!a.startsWith("-") && !brainName) brainName = a
|
|
757
|
+
else throw new Error(`Unknown option: ${a}. Run \`csb git-token --help\`.`)
|
|
758
|
+
}
|
|
759
|
+
if (!Number.isFinite(ttl) || ttl < 60 || ttl > GIT_TOKEN_TTL_MAX) {
|
|
760
|
+
throw new Error("--ttl must be between 60s and 1 year, e.g. 3600, 12h, 90d, 1y")
|
|
761
|
+
}
|
|
762
|
+
const brain = await resolveBrain(brainName)
|
|
763
|
+
let remote = brain.git_remote
|
|
764
|
+
if (!remote) {
|
|
765
|
+
const r = spawnSync("git", ["remote", "get-url", "origin"], { cwd: brain.path, stdio: "pipe", encoding: "utf8" })
|
|
766
|
+
remote = r.status === 0 ? r.stdout.trim() : ""
|
|
767
|
+
}
|
|
768
|
+
const result = await mintArtifactsGitToken({
|
|
769
|
+
remote, cwd: printOnly ? null : brain.path, ttl, scope, interactive: Boolean(process.stdin.isTTY),
|
|
770
|
+
})
|
|
771
|
+
if (!result.ok) throw new Error(`Could not mint a git token for "${brain.name}": ${result.error}`)
|
|
772
|
+
if (printOnly) {
|
|
773
|
+
process.stdout.write(result.token + "\n")
|
|
774
|
+
return
|
|
775
|
+
}
|
|
776
|
+
const until = result.expiresAt ? new Date(result.expiresAt).toLocaleString() : `${formatTtl(ttl)} from now`
|
|
777
|
+
console.log(`${pc.green("✓")} ${scope} token for ${pc.cyan(`${result.namespace}/${result.repo}`)} saved to ${pc.dim(`${brain.path}/.git/config`)} — git push/pull work until ${until}.`)
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function globalSkillSummary({ installed, skipped }) {
|
|
781
|
+
return [
|
|
782
|
+
installed.length > 0 ? `installed ${installed.length}` : null,
|
|
783
|
+
skipped.length > 0 ? `kept ${skipped.length}` : null,
|
|
784
|
+
].filter(Boolean).join(", ") || "already up to date"
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
// `csb skills [--agent <ids>] [--copy] [--brain <name>] [--list]`
|
|
788
|
+
// Install / update the global skills for more agents without creating a brain,
|
|
789
|
+
// and copy the vault-local skills into the brain for agents that need them.
|
|
790
|
+
async function cmdSkills(args) {
|
|
791
|
+
const { agents: explicit, copy, rest } = parseAgentFlags(args)
|
|
792
|
+
const toDisplayPath = p => p && p.startsWith(homedir()) ? "~" + p.slice(homedir().length) : p
|
|
793
|
+
|
|
794
|
+
if (rest.includes("--list") || rest[0] === "ls" || rest[0] === "list") {
|
|
795
|
+
const detected = detectAgents()
|
|
796
|
+
const lines = AGENT_IDS.map(id => {
|
|
797
|
+
const a = AGENTS[id]
|
|
798
|
+
const global = a.globalSkillsDir ? toDisplayPath(a.globalSkillsDir) : `${toDisplayPath(CANONICAL_GLOBAL_DIR)} (shared)`
|
|
799
|
+
const mark = detected.includes(id) ? pc.green("●") : pc.dim("○")
|
|
800
|
+
return `${mark} ${id.padEnd(15)} ${pc.dim(`project: ${a.skillsDir.padEnd(17)} global: ${global}`)}`
|
|
801
|
+
})
|
|
802
|
+
console.log(lines.join("\n"))
|
|
803
|
+
console.log(pc.dim(`\n● detected on this machine. Universal agents read ${CANONICAL_PROJECT_DIR_LABEL} directly.`))
|
|
804
|
+
return
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
let brainName = null
|
|
808
|
+
for (let i = 0; i < rest.length; i++) {
|
|
809
|
+
if (rest[i] === "--brain") brainName = rest[++i]
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
const isInteractive = Boolean(process.stdin.isTTY)
|
|
813
|
+
p.intro(`${pc.bgCyan(pc.black(" csb skills "))} v${version}`)
|
|
814
|
+
const agents = await resolveAgents({ explicit, isInteractive, prompts: p })
|
|
815
|
+
if (!agents) { p.cancel("Cancelled."); process.exit(0) }
|
|
816
|
+
|
|
817
|
+
const spin = makeSpinner()
|
|
818
|
+
spin.start("Installing global skills")
|
|
819
|
+
const result = await installGlobalSkills({ isInteractive, agents, copy })
|
|
820
|
+
spin.stop(`Global skills ${globalSkillSummary(result)}`)
|
|
821
|
+
p.log.message(summarizeAgentInstall(agents, result.links, toDisplayPath))
|
|
822
|
+
|
|
823
|
+
let brain = null
|
|
824
|
+
try { brain = await resolveBrain(brainName) } catch (err) {
|
|
825
|
+
if (brainName) throw err
|
|
826
|
+
}
|
|
827
|
+
if (brain) {
|
|
828
|
+
try {
|
|
829
|
+
await access(join(brain.path, ".claude", "skills"))
|
|
830
|
+
const dirs = await installProjectSkills(brain.path, join(brain.path, ".claude", "skills"), LOCAL_SKILLS, agents)
|
|
831
|
+
if (dirs.length > 0) {
|
|
832
|
+
p.log.step(`Vault skills for ${pc.cyan(brain.name)} copied to ${dirs.map(d => pc.dim(d)).join(", ")} — commit them in the vault to sync.`)
|
|
833
|
+
}
|
|
834
|
+
} catch {
|
|
835
|
+
p.log.warn(`No .claude/skills in ${toDisplayPath(brain.path)} — skipped vault skills.`)
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
p.outro("done")
|
|
403
839
|
}
|
|
404
840
|
|
|
405
841
|
function parseConfig(content) {
|
|
@@ -456,9 +892,20 @@ function printHelp(topic = "top") {
|
|
|
456
892
|
` ${c("csb path [qmd|config|root]")} print a path (default: root)`,
|
|
457
893
|
` ${c("csb qmd [--brain N] <qmd args…>")} run qmd against the resolved brain`,
|
|
458
894
|
` ${c("csb exec [--brain N] -- <cmd…>")} run a command inside the resolved brain`,
|
|
895
|
+
` ${c("csb skills [--agent <ids>]")} install/update skills for more agents`,
|
|
896
|
+
` ${c("csb git-token [<name>]")} renew a Cloudflare Artifacts git token`,
|
|
459
897
|
` ${c("csb doctor")} verify your setup and suggest fixes`,
|
|
460
898
|
` ${c("csb help [<command>]")} show help for a command`,
|
|
461
899
|
"",
|
|
900
|
+
"Create options:",
|
|
901
|
+
` ${c("--agent, -a <ids>")} agents to install skills for (comma-separated, or \`all\`; env: CSB_AGENTS)`,
|
|
902
|
+
` ${c("--copy")} copy skills into each agent dir instead of symlinking`,
|
|
903
|
+
"",
|
|
904
|
+
"Environment:",
|
|
905
|
+
` ${c("CSB_USE_MISE=1")} always fetch node + pnpm with mise, even if pnpm 10+ is installed`,
|
|
906
|
+
` ${c("CSB_ICONS=nerd|emoji|none")} icons in the git-remote picker`,
|
|
907
|
+
` ${c("CLOUDFLARE_API_TOKEN")}, ${c("CLOUDFLARE_ACCOUNT_ID")} Cloudflare Artifacts credentials / account`,
|
|
908
|
+
"",
|
|
462
909
|
"Examples:",
|
|
463
910
|
` ${c('csb qmd query -c wiki "distributed systems"')}`,
|
|
464
911
|
` ${c("csb path qmd")}`,
|
|
@@ -539,11 +986,49 @@ function printHelp(topic = "top") {
|
|
|
539
986
|
"Prints each registered brain with its path, creation date, and remote.",
|
|
540
987
|
"The default brain is shown in bold with a `*` marker.",
|
|
541
988
|
].join("\n")),
|
|
989
|
+
skills: () => console.log([
|
|
990
|
+
`${pc.bold("csb skills")} — install or update the wiki skills for any agent`,
|
|
991
|
+
"",
|
|
992
|
+
"Usage:",
|
|
993
|
+
` ${c("csb skills [--agent <ids>] [--copy] [--brain <name>]")}`,
|
|
994
|
+
` ${c("csb skills --list")} list supported agents and their skills dirs`,
|
|
995
|
+
"",
|
|
996
|
+
"Global skills (brain-ingest, brain-search, brain-refresh) are written once to",
|
|
997
|
+
`${pc.dim("~/.agents/skills/<name>")} and symlinked into each agent's own global skills dir`,
|
|
998
|
+
`(e.g. ${pc.dim("~/.claude/skills")}). Codex, Cursor, Copilot, Gemini CLI, OpenCode, Amp and Cline`,
|
|
999
|
+
`read ${pc.dim("~/.agents/skills")} directly. Vault-local skills (lint, brain-rebuild) are copied`,
|
|
1000
|
+
"into the default brain's per-agent skills dir (e.g. .agents/skills).",
|
|
1001
|
+
"",
|
|
1002
|
+
"Options:",
|
|
1003
|
+
` ${c("--agent, -a <ids>")} agents to install for, comma-separated, or \`all\``,
|
|
1004
|
+
` ${pc.dim(`(default: claude-code + detected; env: CSB_AGENTS)`)}`,
|
|
1005
|
+
` ${c("--copy")} copy instead of symlink`,
|
|
1006
|
+
` ${c("--brain <name>")} brain whose vault-local skills to update (default brain otherwise)`,
|
|
1007
|
+
"",
|
|
1008
|
+
`Agents: ${pc.dim(AGENT_IDS.join(", "))}`,
|
|
1009
|
+
].join("\n")),
|
|
1010
|
+
"git-token": () => console.log([
|
|
1011
|
+
`${pc.bold("csb git-token")} — renew the git token for a Cloudflare Artifacts brain`,
|
|
1012
|
+
"",
|
|
1013
|
+
"Usage:",
|
|
1014
|
+
` ${c("csb git-token [<name>] [--ttl <duration>] [--read] [--print]")}`,
|
|
1015
|
+
"",
|
|
1016
|
+
"Artifacts git tokens expire (90 days by default, 1 year max). This mints a new one with",
|
|
1017
|
+
"your wrangler login (or CLOUDFLARE_API_TOKEN) and stores it as an http.extraHeader",
|
|
1018
|
+
"for the brain's remote in its .git/config, so plain `git push` / `git pull` work.",
|
|
1019
|
+
"",
|
|
1020
|
+
"Options:",
|
|
1021
|
+
` ${c("--brain <name>")} brain to renew (default: the default brain; also positional)`,
|
|
1022
|
+
` ${c("--ttl <duration>")} token lifetime: seconds or 12h / 90d / 1y (default 90d, max 1y)`,
|
|
1023
|
+
` ${c("--read")} read-only token instead of write`,
|
|
1024
|
+
` ${c("--print")} print the token instead of saving it to .git/config`,
|
|
1025
|
+
].join("\n")),
|
|
542
1026
|
doctor: () => console.log([
|
|
543
1027
|
`${pc.bold("csb doctor")} — verify your setup and suggest fixes`,
|
|
544
1028
|
"",
|
|
545
1029
|
"Checks required and optional tools (gh, mise, pnpm, wrangler),",
|
|
546
|
-
"the central config, each registered brain's path
|
|
1030
|
+
"the central config, each registered brain's path and qmd index, and whether",
|
|
1031
|
+
"the global skills in ~/.agents/skills match this release.",
|
|
547
1032
|
"Prints a `Fix:` hint under each failing check.",
|
|
548
1033
|
].join("\n")),
|
|
549
1034
|
}
|
|
@@ -713,7 +1198,9 @@ async function cmdDoctor() {
|
|
|
713
1198
|
}
|
|
714
1199
|
lines.push(commandExists("mise")
|
|
715
1200
|
? ok("mise installed")
|
|
716
|
-
: (
|
|
1201
|
+
: systemPnpmUsable()
|
|
1202
|
+
? ok("mise not installed — using system node + pnpm instead")
|
|
1203
|
+
: (failures++, fail("neither mise nor pnpm >= 10 installed — one is required for scaffolded vaults", "npm install -g pnpm | npm install -g @jdxcode/mise")))
|
|
717
1204
|
lines.push(commandExists("wrangler") || commandExists("npx")
|
|
718
1205
|
? ok(commandExists("wrangler") ? "wrangler installed" : "wrangler available via npx (optional — for Cloudflare Artifacts)")
|
|
719
1206
|
: (warnings++, warn("wrangler not installed — required only for Cloudflare Artifacts remotes", "npm install -g wrangler")))
|
|
@@ -775,6 +1262,26 @@ async function cmdDoctor() {
|
|
|
775
1262
|
}
|
|
776
1263
|
}
|
|
777
1264
|
|
|
1265
|
+
// Global skills
|
|
1266
|
+
lines.push("")
|
|
1267
|
+
lines.push(pc.bold("Skills"))
|
|
1268
|
+
for (const name of GLOBAL_SKILLS) {
|
|
1269
|
+
const canonical = join(CANONICAL_GLOBAL_DIR, name)
|
|
1270
|
+
const v = await readSkillVersion(canonical)
|
|
1271
|
+
if (!v) {
|
|
1272
|
+
const legacy = await readSkillVersion(join(homedir(), ".claude", "skills", name))
|
|
1273
|
+
warnings++
|
|
1274
|
+
lines.push(legacy
|
|
1275
|
+
? warn(`${name} only in ~/.claude/skills (v${legacy}) — other agents can't see it`, "csb skills")
|
|
1276
|
+
: warn(`${name} not installed in ${toDisplayPath(CANONICAL_GLOBAL_DIR)}`, "csb skills"))
|
|
1277
|
+
} else if (v !== version) {
|
|
1278
|
+
warnings++
|
|
1279
|
+
lines.push(warn(`${name} is v${v} (this release is v${version})`, "csb skills"))
|
|
1280
|
+
} else {
|
|
1281
|
+
lines.push(ok(`${name} v${v} ${pc.dim(toDisplayPath(canonical))}`))
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
|
|
778
1285
|
p.note(lines.join("\n"), "Checks")
|
|
779
1286
|
|
|
780
1287
|
if (failures > 0) {
|
|
@@ -910,7 +1417,7 @@ async function removeBrain(names, { yes = false, remoteMode = "ask" } = {}) {
|
|
|
910
1417
|
}
|
|
911
1418
|
}
|
|
912
1419
|
|
|
913
|
-
const spin =
|
|
1420
|
+
const spin = makeSpinner()
|
|
914
1421
|
|
|
915
1422
|
for (const target of targets) {
|
|
916
1423
|
spin.start(`Deleting ${toDisplayPath(target.path)}`)
|
|
@@ -943,7 +1450,7 @@ async function removeBrain(names, { yes = false, remoteMode = "ask" } = {}) {
|
|
|
943
1450
|
spin.stop(`Removed Cloudflare Artifact ${pc.dim(`${decision.namespace}/${decision.repo}`)}`)
|
|
944
1451
|
} else {
|
|
945
1452
|
spin.stop(`Failed to delete Cloudflare Artifact for ${name}: ${result.error}`, 1)
|
|
946
|
-
p.log.warn(`Delete it manually:\n ${pc.cyan(`TOKEN=$(wrangler auth token)`)}\n ${pc.cyan(`curl -X DELETE https://
|
|
1453
|
+
p.log.warn(`Delete it manually:\n ${pc.cyan(`TOKEN=$(wrangler auth token)`)}\n ${pc.cyan(`curl -X DELETE https://api.cloudflare.com/client/v4/accounts/${decision.accountId || "<ACCOUNT_ID>"}/artifacts/namespaces/${decision.namespace}/repos/${decision.repo} \\`)}\n ${pc.cyan(` -H "Authorization: Bearer $TOKEN"`)}`)
|
|
947
1454
|
}
|
|
948
1455
|
}
|
|
949
1456
|
}
|
|
@@ -1016,7 +1523,7 @@ async function writeConfig(brainName, brainPath, qmdPath, gitRemote) {
|
|
|
1016
1523
|
await writeFile(CSB_CONFIG, [header, ...otherBrains, entry].join("\n").trimEnd() + "\n", "utf8")
|
|
1017
1524
|
}
|
|
1018
1525
|
|
|
1019
|
-
async function createBrain(initialName) {
|
|
1526
|
+
async function createBrain(initialName, { agents: explicitAgents = null, copy = false } = {}) {
|
|
1020
1527
|
const isInteractive = Boolean(process.stdin.isTTY)
|
|
1021
1528
|
|
|
1022
1529
|
p.intro(`${pc.bgCyan(pc.black(" claude-second-brain "))} v${version}`)
|
|
@@ -1044,9 +1551,9 @@ async function createBrain(initialName) {
|
|
|
1044
1551
|
const provider = await p.select({
|
|
1045
1552
|
message: "Where to host the Git remote?",
|
|
1046
1553
|
options: [
|
|
1047
|
-
{ value: "github", label:
|
|
1048
|
-
{ value: "cloudflare", label:
|
|
1049
|
-
{ value: "none", label:
|
|
1554
|
+
{ value: "github", label: `${REMOTE_ICONS.github}GitHub`, hint: "private repo via gh · default" },
|
|
1555
|
+
{ value: "cloudflare", label: `${REMOTE_ICONS.cloudflare}Cloudflare Artifacts`, hint: "git remote via wrangler" },
|
|
1556
|
+
{ value: "none", label: `${REMOTE_ICONS.none}Skip — I'll add a remote later`, hint: "local git only" },
|
|
1050
1557
|
],
|
|
1051
1558
|
initialValue: "github",
|
|
1052
1559
|
})
|
|
@@ -1074,6 +1581,23 @@ async function createBrain(initialName) {
|
|
|
1074
1581
|
}
|
|
1075
1582
|
}
|
|
1076
1583
|
|
|
1584
|
+
// Ask every question before the slow steps, so setup can run unattended.
|
|
1585
|
+
let doQmdSetup = true
|
|
1586
|
+
if (isInteractive) {
|
|
1587
|
+
const ok = await p.confirm({
|
|
1588
|
+
message: "Register qmd collections after install? (wiki + raw-sources)",
|
|
1589
|
+
initialValue: true,
|
|
1590
|
+
})
|
|
1591
|
+
if (p.isCancel(ok)) { p.cancel("Setup cancelled."); process.exit(0) }
|
|
1592
|
+
doQmdSetup = ok
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
const agents = await resolveAgents({ explicit: explicitAgents, isInteractive, prompts: p })
|
|
1596
|
+
if (!agents) { p.cancel("Setup cancelled."); process.exit(0) }
|
|
1597
|
+
if (!isInteractive || explicitAgents) {
|
|
1598
|
+
p.log.step(`Install skills for which agents?\n${pc.dim(agents.map(id => AGENTS[id].displayName).join(", "))}`)
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1077
1601
|
await mkdir(CSB_ROOT, { recursive: true })
|
|
1078
1602
|
const targetDir = join(CSB_ROOT, targetName)
|
|
1079
1603
|
|
|
@@ -1107,44 +1631,43 @@ async function createBrain(initialName) {
|
|
|
1107
1631
|
await patchVault(targetDir, targetName)
|
|
1108
1632
|
spin.stop("README patched")
|
|
1109
1633
|
|
|
1110
|
-
//
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
else spin.stop("Failed to install mise — run: npm install -g @jdxcode/mise", 1)
|
|
1116
|
-
}
|
|
1634
|
+
// Toolchain: reuse a system pnpm (>= 10) when there is one; otherwise let
|
|
1635
|
+
// mise install node + pnpm from the vault's mise.toml.
|
|
1636
|
+
const useSystemPnpm = process.env.CSB_USE_MISE !== "1" && systemPnpmUsable()
|
|
1637
|
+
const pnpmCmd = useSystemPnpm ? ["pnpm"] : ["mise", "exec", "--", "pnpm"]
|
|
1638
|
+
const fmt = secs => pc.dim(`(${secs}s)`)
|
|
1117
1639
|
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1640
|
+
if (useSystemPnpm) {
|
|
1641
|
+
p.log.step(`Using system node ${process.versions.node} + pnpm ${pc.dim("(set CSB_USE_MISE=1 to use mise instead)")}`)
|
|
1642
|
+
} else {
|
|
1643
|
+
if (!commandExists("mise")) {
|
|
1644
|
+
const r = await runStep(spin, "Installing mise", ["npm", "install", "-g", "@jdxcode/mise"])
|
|
1645
|
+
if (r.ok) spin.stop(`mise installed ${fmt(r.seconds)}`)
|
|
1646
|
+
else spin.stop("Failed to install mise — run: npm install -g @jdxcode/mise", 1)
|
|
1647
|
+
}
|
|
1648
|
+
run(["mise", "trust"], targetDir)
|
|
1649
|
+
const r = await runStep(spin, "Installing node + pnpm via mise", ["mise", "install"], targetDir)
|
|
1650
|
+
if (r.ok) spin.stop(`node + pnpm installed ${fmt(r.seconds)}`)
|
|
1651
|
+
else spin.stop("mise install failed — run it manually inside your vault", 1)
|
|
1652
|
+
}
|
|
1124
1653
|
|
|
1125
1654
|
// Install vault dependencies via pnpm
|
|
1126
|
-
spin
|
|
1127
|
-
const pnpmOk =
|
|
1128
|
-
if (pnpmOk) spin.stop(
|
|
1129
|
-
else
|
|
1655
|
+
const install = await runStep(spin, "Installing vault dependencies", [...pnpmCmd, "install", "--prefer-offline"], targetDir)
|
|
1656
|
+
const pnpmOk = install.ok
|
|
1657
|
+
if (pnpmOk) spin.stop(`dependencies installed ${fmt(install.seconds)}`)
|
|
1658
|
+
else {
|
|
1659
|
+
spin.stop("pnpm install failed — run it manually inside your vault", 1)
|
|
1660
|
+
const tail = tailForError(install)
|
|
1661
|
+
if (tail) p.log.warn(`pnpm install output:\n${tail}`)
|
|
1662
|
+
}
|
|
1130
1663
|
|
|
1131
1664
|
// Register qmd collections + contexts. Skip reindex — first reindex downloads
|
|
1132
1665
|
// ~2GB of GGUF models; user runs it explicitly when ready.
|
|
1133
1666
|
if (pnpmOk) {
|
|
1134
|
-
let doQmdSetup = true
|
|
1135
|
-
if (isInteractive) {
|
|
1136
|
-
const ok = await p.confirm({
|
|
1137
|
-
message: "Register qmd collections now? (wiki + raw-sources)",
|
|
1138
|
-
initialValue: true,
|
|
1139
|
-
})
|
|
1140
|
-
if (p.isCancel(ok)) { p.cancel("Setup cancelled."); process.exit(0) }
|
|
1141
|
-
doQmdSetup = ok
|
|
1142
|
-
}
|
|
1143
1667
|
if (doQmdSetup) {
|
|
1144
|
-
spin
|
|
1145
|
-
const qmdRes = runCapture(["mise", "exec", "--", "pnpm", "qmd:setup"], targetDir)
|
|
1668
|
+
const qmdRes = await runStep(spin, "Registering qmd collections (wiki, raw-sources)", [...pnpmCmd, "qmd:setup"], targetDir)
|
|
1146
1669
|
if (qmdRes.ok) {
|
|
1147
|
-
spin.stop(
|
|
1670
|
+
spin.stop(`qmd collections registered ${fmt(qmdRes.seconds)}`)
|
|
1148
1671
|
} else {
|
|
1149
1672
|
spin.stop("pnpm qmd:setup failed — run it manually inside your vault", 1)
|
|
1150
1673
|
const tail = tailForError(qmdRes)
|
|
@@ -1155,16 +1678,17 @@ async function createBrain(initialName) {
|
|
|
1155
1678
|
}
|
|
1156
1679
|
}
|
|
1157
1680
|
|
|
1681
|
+
// Vault-local skills for agents that don't read .claude/skills
|
|
1682
|
+
const projectDirs = await installProjectSkills(targetDir, join(targetDir, ".claude", "skills"), LOCAL_SKILLS, agents)
|
|
1683
|
+
if (projectDirs.length > 0) {
|
|
1684
|
+
p.log.step(`Vault skills copied to ${projectDirs.map(d => pc.dim(d)).join(", ")}`)
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1158
1687
|
// Install global skills (version-aware — prompts to update when versions differ)
|
|
1159
|
-
spin.start("Installing global
|
|
1160
|
-
const skillResult = await installGlobalSkills({ isInteractive })
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
const summary = [
|
|
1164
|
-
installedCount > 0 ? `installed ${installedCount}` : null,
|
|
1165
|
-
skippedCount > 0 ? `kept ${skippedCount}` : null,
|
|
1166
|
-
].filter(Boolean).join(", ") || "already up to date"
|
|
1167
|
-
spin.stop(`Global skills ${summary} → ${pc.dim(toDisplayPath(join(homedir(), ".claude", "skills")))}`)
|
|
1688
|
+
spin.start("Installing global skills")
|
|
1689
|
+
const skillResult = await installGlobalSkills({ isInteractive, agents, copy })
|
|
1690
|
+
spin.stop(`Global skills ${globalSkillSummary(skillResult)}`)
|
|
1691
|
+
p.log.message(summarizeAgentInstall(agents, skillResult.links, toDisplayPath))
|
|
1168
1692
|
|
|
1169
1693
|
// Git init
|
|
1170
1694
|
spin.start("Initializing git repo")
|
|
@@ -1177,10 +1701,15 @@ async function createBrain(initialName) {
|
|
|
1177
1701
|
spin.stop("git init failed — run it manually inside your vault", 1)
|
|
1178
1702
|
}
|
|
1179
1703
|
|
|
1704
|
+
// Remote setup outcome, surfaced in Next steps / outro instead of a silent
|
|
1705
|
+
// success-looking finish. null = no remote requested.
|
|
1706
|
+
let remoteProblem = null
|
|
1707
|
+
|
|
1180
1708
|
// GitHub repo (optional)
|
|
1181
1709
|
if (remoteProvider === "github") {
|
|
1182
1710
|
if (!commandExists("gh")) {
|
|
1183
1711
|
p.log.warn(`gh CLI not found — install from https://cli.github.com, then run:\n gh repo create ${repoName} --private --source=. --remote=origin --push`)
|
|
1712
|
+
remoteProblem = "GitHub repo not created (gh CLI not found)"
|
|
1184
1713
|
} else {
|
|
1185
1714
|
const authCheck = spawnSync("gh", ["auth", "status"], { stdio: "pipe" })
|
|
1186
1715
|
let loggedIn = authCheck.status === 0
|
|
@@ -1200,7 +1729,10 @@ async function createBrain(initialName) {
|
|
|
1200
1729
|
spin.stop(`GitHub repo created (private): ${pc.cyan(repoName)}`)
|
|
1201
1730
|
} else {
|
|
1202
1731
|
spin.stop(`gh repo create failed — run: gh repo create ${repoName} --private --source=. --remote=origin --push`, 1)
|
|
1732
|
+
remoteProblem = "GitHub repo not created (gh repo create failed)"
|
|
1203
1733
|
}
|
|
1734
|
+
} else {
|
|
1735
|
+
remoteProblem = "GitHub repo not created (not logged in to gh)"
|
|
1204
1736
|
}
|
|
1205
1737
|
}
|
|
1206
1738
|
}
|
|
@@ -1212,12 +1744,24 @@ async function createBrain(initialName) {
|
|
|
1212
1744
|
return r.status === 0 ? r.stdout.toString().trim() : ""
|
|
1213
1745
|
})()
|
|
1214
1746
|
: ""
|
|
1747
|
+
let cfAccountId = null
|
|
1215
1748
|
if (remoteProvider === "cloudflare") {
|
|
1216
1749
|
const result = await setupCloudflareRemote({ targetDir, repoName, namespace: cfNamespace, spin })
|
|
1217
|
-
if (result?.repoToken) {
|
|
1218
|
-
p.log.warn(`Save your Artifacts repo token — it expires and you'll need to mint a new one:\n ${result.repoToken}`)
|
|
1219
|
-
}
|
|
1220
1750
|
gitRemote = result?.remote || ""
|
|
1751
|
+
cfAccountId = result?.accountId || null
|
|
1752
|
+
if (result?.remote && result?.repoToken) {
|
|
1753
|
+
// The create response carries a 24h token; swap it for a long-lived one.
|
|
1754
|
+
setGitAuthHeader(targetDir, result.remote, result.repoToken)
|
|
1755
|
+
const long = await mintArtifactsGitToken({ remote: result.remote, cwd: targetDir, interactive: false })
|
|
1756
|
+
if (long.ok) {
|
|
1757
|
+
const until = long.expiresAt ? ` (until ${new Date(long.expiresAt).toLocaleDateString()})` : ""
|
|
1758
|
+
p.log.info(`Git token saved to the vault's .git/config — push/pull work for ${formatTtl(GIT_TOKEN_TTL_DEFAULT)}${until}; renew with ${pc.cyan("csb git-token")}`)
|
|
1759
|
+
} else {
|
|
1760
|
+
p.log.warn(`Could not mint a ${formatTtl(GIT_TOKEN_TTL_DEFAULT)} git token (${long.error}); using the 24h one. Run ${pc.cyan("csb git-token")} to get a longer one.`)
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
if (!result) remoteProblem = "Cloudflare Artifact not created (see the error above)"
|
|
1764
|
+
else if (!result.pushed) remoteProblem = "Cloudflare Artifact created, but the initial push failed (see the error above)"
|
|
1221
1765
|
}
|
|
1222
1766
|
|
|
1223
1767
|
// Write central config
|
|
@@ -1227,14 +1771,20 @@ async function createBrain(initialName) {
|
|
|
1227
1771
|
|
|
1228
1772
|
// Next steps
|
|
1229
1773
|
const brainDisplayPath = toDisplayPath(targetDir)
|
|
1230
|
-
const remoteSteps =
|
|
1774
|
+
const remoteSteps = remoteProblem
|
|
1231
1775
|
? [
|
|
1232
|
-
`${pc.
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1776
|
+
`${pc.yellow("⚠")} ${pc.yellow(remoteProblem)}`,
|
|
1777
|
+
...(remoteProvider === "github"
|
|
1778
|
+
? [`${pc.cyan(`gh repo create ${repoName} --private --source=. --remote=origin --push`)} retry`]
|
|
1779
|
+
: [
|
|
1780
|
+
`${pc.dim("# fix the error above, then delete this brain and re-run, or add any git remote:")}`,
|
|
1781
|
+
`${pc.cyan(`csb rm ${targetName} && csb ${targetName}`)}`,
|
|
1782
|
+
]),
|
|
1783
|
+
`${pc.cyan("git remote add origin <url> && git push -u origin main")} any other remote`,
|
|
1784
|
+
]
|
|
1785
|
+
: remoteProvider === "cloudflare"
|
|
1786
|
+
? [
|
|
1787
|
+
`${pc.cyan(`csb git-token${targetName ? ` ${targetName}` : ""}`)} ${pc.dim("# renew the git push/pull token (expires in 90 days)")}`,
|
|
1238
1788
|
]
|
|
1239
1789
|
: remoteProvider === "none"
|
|
1240
1790
|
? [
|
|
@@ -1246,12 +1796,17 @@ async function createBrain(initialName) {
|
|
|
1246
1796
|
const nextSteps = [
|
|
1247
1797
|
`${pc.cyan(`cd ${brainDisplayPath}`)}`,
|
|
1248
1798
|
`${pc.cyan("pnpm qmd:reindex")} ${pc.dim("# first run downloads ~2GB of embedding models")}`,
|
|
1249
|
-
|
|
1799
|
+
...agentLaunchSteps(agents),
|
|
1250
1800
|
...remoteSteps,
|
|
1251
1801
|
].join("\n")
|
|
1252
1802
|
|
|
1253
1803
|
p.note(nextSteps, "Next steps")
|
|
1254
|
-
|
|
1804
|
+
if (remoteProblem) {
|
|
1805
|
+
p.outro(pc.yellow(`Brain created, but the git remote isn't set up: ${remoteProblem}.`))
|
|
1806
|
+
process.exitCode = 1
|
|
1807
|
+
} else {
|
|
1808
|
+
p.outro("Happy knowledge building!")
|
|
1809
|
+
}
|
|
1255
1810
|
}
|
|
1256
1811
|
|
|
1257
1812
|
const SUBCOMMANDS = new Set([
|
|
@@ -1263,6 +1818,8 @@ const SUBCOMMANDS = new Set([
|
|
|
1263
1818
|
"exec",
|
|
1264
1819
|
"use", "default", "switch",
|
|
1265
1820
|
"doctor",
|
|
1821
|
+
"skills",
|
|
1822
|
+
"git-token",
|
|
1266
1823
|
])
|
|
1267
1824
|
|
|
1268
1825
|
async function main() {
|
|
@@ -1314,11 +1871,24 @@ async function main() {
|
|
|
1314
1871
|
await cmdUse(rest)
|
|
1315
1872
|
return
|
|
1316
1873
|
}
|
|
1874
|
+
if (cmd === "git-token") {
|
|
1875
|
+
await cmdGitToken(rest)
|
|
1876
|
+
return
|
|
1877
|
+
}
|
|
1317
1878
|
if (cmd === "doctor") {
|
|
1318
1879
|
await cmdDoctor()
|
|
1319
1880
|
return
|
|
1320
1881
|
}
|
|
1321
|
-
|
|
1882
|
+
if (cmd === "skills") {
|
|
1883
|
+
await cmdSkills(rest)
|
|
1884
|
+
return
|
|
1885
|
+
}
|
|
1886
|
+
// `csb [<name>] [--agent <ids>] [--copy]`
|
|
1887
|
+
const createArgs = cmd === undefined ? rest : [cmd, ...rest]
|
|
1888
|
+
const { agents, copy, rest: positional } = parseAgentFlags(createArgs)
|
|
1889
|
+
const unknownFlag = positional.find(a => a.startsWith("-"))
|
|
1890
|
+
if (unknownFlag) throw new Error(`Unknown option: ${unknownFlag}. Run \`csb help\`.`)
|
|
1891
|
+
await createBrain(positional[0], { agents, copy })
|
|
1322
1892
|
}
|
|
1323
1893
|
|
|
1324
1894
|
main().catch(err => {
|