@codyn06/cboard 0.1.0 → 0.3.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 +5 -2
- package/dist/api.d.ts +36 -4
- package/dist/api.js +128 -51
- package/dist/cache.d.ts +28 -0
- package/dist/cache.js +101 -0
- package/dist/cboard.js +57 -3
- package/dist/cli.js +2 -1
- package/dist/docs.d.ts +39 -0
- package/dist/docs.js +244 -0
- package/dist/extract.js +23 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/issues.d.ts +44 -0
- package/dist/issues.js +139 -0
- package/dist/wake.d.ts +13 -0
- package/dist/wake.js +33 -0
- package/kit/cboard-connect.js +425 -46
- package/kit/cboard-kit/brief.js +144 -18
- package/kit/cboard-kit/config.js +38 -3
- package/kit/cboard-kit/connect-check.js +56 -13
- package/kit/cboard-kit/device.js +192 -0
- package/kit/cboard-kit/drift.js +55 -0
- package/kit/cboard-kit/headers.js +24 -3
- package/kit/cboard-kit/mcp.js +38 -3
- package/kit/cboard-kit/references.js +70 -0
- package/kit/cboard-kit/skill/SKILL.md +16 -0
- package/kit/cboard-kit/wait.js +45 -0
- package/package.json +1 -1
package/kit/cboard-kit/brief.js
CHANGED
|
@@ -7,11 +7,21 @@
|
|
|
7
7
|
// `status_update` node unless .cboard.json names a "statusNodeFile" holding a node id; the release
|
|
8
8
|
// lag line appears only when .cboard.json sets "releaseBranch".
|
|
9
9
|
import { execFileSync } from "node:child_process";
|
|
10
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
11
11
|
import { dirname, join, relative } from "node:path";
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
|
-
import { mcpCall } from "./mcp.js";
|
|
14
|
-
import {
|
|
13
|
+
import { describeWhoami, fetchWhoami, mcpCall } from "./mcp.js";
|
|
14
|
+
import { retryWake } from "./wait.js";
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_SYNC_COMMAND,
|
|
17
|
+
isMain,
|
|
18
|
+
locateRoot,
|
|
19
|
+
pinSyncCommand,
|
|
20
|
+
readToken,
|
|
21
|
+
resolveConfig,
|
|
22
|
+
} from "./config.js";
|
|
23
|
+
import { driftLine, latestVersion } from "./drift.js";
|
|
24
|
+
import { checkReference } from "./references.js";
|
|
15
25
|
|
|
16
26
|
const DEFAULT_MAX_BYTES = 3000;
|
|
17
27
|
const BODY_BYTES = 1000;
|
|
@@ -53,11 +63,14 @@ const LOCAL_SYNC = {
|
|
|
53
63
|
};
|
|
54
64
|
|
|
55
65
|
// Hook budget (.claude/settings.json: 60 s). releaseLag worst case: fetch 5 s + 4 local git calls
|
|
56
|
-
// at 1.5 s each = 11 s, run before the hosted wait
|
|
57
|
-
// the first
|
|
66
|
+
// at 1.5 s each = 11 s, run before the hosted wait. The wake-up wait (retry with backoff) is
|
|
67
|
+
// capped at 35 s, so the first call finishes by ~46 s; later calls are 5 s each once the service
|
|
68
|
+
// is awake. Past the wake budget the brief falls back to the cached one. The long (90 s) wait is
|
|
69
|
+
// for CLI commands, not hooks.
|
|
58
70
|
const FETCH_TIMEOUT_MS = 5000;
|
|
59
71
|
const GIT_TIMEOUT_MS = 1500;
|
|
60
|
-
const
|
|
72
|
+
const HOSTED_WAKE_MS = 35_000;
|
|
73
|
+
export const CACHE_FILE = ".cboard/brief-cache.json";
|
|
61
74
|
// The health line is optional: by then the service is awake, so never wait long for it.
|
|
62
75
|
const HEALTH_TIMEOUT_MS = 5000;
|
|
63
76
|
|
|
@@ -146,12 +159,12 @@ export function formatHealthLine(health) {
|
|
|
146
159
|
}
|
|
147
160
|
|
|
148
161
|
// Sync reads .cboard.json and the repo token file itself; only a local graph needs its address.
|
|
149
|
-
function syncLine(sync) {
|
|
150
|
-
const command = `${sync.command ?? DEFAULT_SYNC_COMMAND} sync`;
|
|
162
|
+
function syncLine(sync, kit) {
|
|
163
|
+
const command = `${pinSyncCommand(sync.command ?? DEFAULT_SYNC_COMMAND, kit)} sync`;
|
|
151
164
|
return sync.local ? `${command} --server ${sync.server}` : command;
|
|
152
165
|
}
|
|
153
166
|
|
|
154
|
-
function recommendations(project, freshness = {}, sync = LOCAL_SYNC, release = null) {
|
|
167
|
+
function recommendations(project, freshness = {}, sync = LOCAL_SYNC, release = null, kit) {
|
|
155
168
|
const out = [];
|
|
156
169
|
if (typeof release?.count === "number" && release.count > 0) {
|
|
157
170
|
out.push("- Hosted lacks unreleased fixes; do not assume merged PRs are live.");
|
|
@@ -164,12 +177,47 @@ function recommendations(project, freshness = {}, sync = LOCAL_SYNC, release = n
|
|
|
164
177
|
if (freshness.codeCommit && (freshness.codeCommitsBehind ?? 0) > 0) {
|
|
165
178
|
out.push(
|
|
166
179
|
`- Code nodes are at ${freshness.codeCommit.slice(0, 7)}, ${String(freshness.codeCommitsBehind)} commit(s) behind HEAD: ` +
|
|
167
|
-
`before code work run \`${syncLine(sync)}\`.`,
|
|
180
|
+
`before code work run \`${syncLine(sync, kit)}\`.`,
|
|
168
181
|
);
|
|
169
182
|
}
|
|
170
183
|
return out.length ? `Recommended graph updates:\n${out.join("\n")}` : "";
|
|
171
184
|
}
|
|
172
185
|
|
|
186
|
+
/** Short start steps for a project with no status node (#107). */
|
|
187
|
+
function emptyProjectSteps(goalNodeId, sync = LOCAL_SYNC) {
|
|
188
|
+
const goal = goalNodeId
|
|
189
|
+
? `Goal node ${goalNodeId}: link the first decisions to it with an \`answers\` edge.`
|
|
190
|
+
: `No goal node yet: ask the owner for a one-line goal, then run \`${sync.command ?? DEFAULT_SYNC_COMMAND} connect --goal "<text>"\`.`;
|
|
191
|
+
return [
|
|
192
|
+
"No status node found (no `status_update` nodes): this project is new.",
|
|
193
|
+
`1. ${goal}`,
|
|
194
|
+
"2. Create the first `status_update` node (status open) with `submit_contribution`, linked to the goal or first decision.",
|
|
195
|
+
].join("\n");
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function tokenLines(me) {
|
|
199
|
+
const info = describeWhoami(me);
|
|
200
|
+
const facts = `Token: ${info.scopes}${info.expires ? `; expires ${info.expires}` : ""}.`;
|
|
201
|
+
const mode = info.readOnly
|
|
202
|
+
? "This token is read-only: query the graph and report findings to the user; do not call submit_contribution."
|
|
203
|
+
: UPDATE_RULE;
|
|
204
|
+
return [facts, info.warning && `Warning: ${info.warning}.`, mode].filter(Boolean).join(" ");
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Reference projects: read-only; one line each (name, project title, read-only or the problem). */
|
|
208
|
+
function referenceLines(references) {
|
|
209
|
+
if (!references?.length) return "";
|
|
210
|
+
const rows = references.map((r) =>
|
|
211
|
+
r.ok
|
|
212
|
+
? `- ${r.name}: "${r.title}", ${r.readOnly === false ? "WRITE-CAPABLE token (use a graph:read token)" : "read-only"}`
|
|
213
|
+
: `- ${r.name}: ${r.message.replace(`reference ${r.name}: `, "")}`,
|
|
214
|
+
);
|
|
215
|
+
return [
|
|
216
|
+
"Reference projects (read-only): query them with the `cboard-ref-<name>` MCP tools; never call submit_contribution there.",
|
|
217
|
+
...rows,
|
|
218
|
+
].join("\n");
|
|
219
|
+
}
|
|
220
|
+
|
|
173
221
|
export function buildBrief({
|
|
174
222
|
releaseBranch,
|
|
175
223
|
project,
|
|
@@ -181,15 +229,21 @@ export function buildBrief({
|
|
|
181
229
|
release,
|
|
182
230
|
health,
|
|
183
231
|
kit,
|
|
232
|
+
goalNodeId,
|
|
233
|
+
latest,
|
|
234
|
+
whoami,
|
|
235
|
+
references,
|
|
184
236
|
maxBytes = DEFAULT_MAX_BYTES,
|
|
185
237
|
}) {
|
|
186
238
|
const head = [
|
|
187
239
|
`cboard graph brief${kit ? ` (kit ${kit})` : ""}: project "${project.title}" (${project.id}), revision ${String(revision)}.`,
|
|
188
240
|
...(release === undefined ? [] : [formatReleaseLag(release, releaseBranch)]),
|
|
189
241
|
RULE,
|
|
190
|
-
UPDATE_RULE,
|
|
191
|
-
recommendations(project, freshness, sync, release),
|
|
242
|
+
whoami ? tokenLines(whoami) : UPDATE_RULE,
|
|
243
|
+
recommendations(project, freshness, sync, release, kit),
|
|
244
|
+
driftLine(kit, latest),
|
|
192
245
|
formatHealthLine(health),
|
|
246
|
+
referenceLines(references),
|
|
193
247
|
]
|
|
194
248
|
.filter(Boolean)
|
|
195
249
|
.join("\n");
|
|
@@ -198,7 +252,7 @@ export function buildBrief({
|
|
|
198
252
|
`Status node ${status.id} [${status.status ?? "?"}]: ${status.title}`,
|
|
199
253
|
clip(String(status.body ?? ""), BODY_BYTES),
|
|
200
254
|
].join("\n")
|
|
201
|
-
:
|
|
255
|
+
: emptyProjectSteps(goalNodeId, sync);
|
|
202
256
|
const lines = (activity ?? [])
|
|
203
257
|
.slice(0, ACTIVITY_ITEMS)
|
|
204
258
|
.map((item) => `- r${String(item.revision)} ${item.contributionId} (${item.status})`);
|
|
@@ -240,6 +294,38 @@ export function gitRepo(cwd) {
|
|
|
240
294
|
};
|
|
241
295
|
}
|
|
242
296
|
|
|
297
|
+
function saveCachedBrief(file, brief) {
|
|
298
|
+
if (!file) return;
|
|
299
|
+
try {
|
|
300
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
301
|
+
writeFileSync(file, JSON.stringify({ savedAt: new Date().toISOString(), brief }));
|
|
302
|
+
} catch {
|
|
303
|
+
// A cache that cannot be written only costs the offline fallback.
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function formatAge(ms) {
|
|
308
|
+
const minutes = Math.max(0, Math.round(ms / 60_000));
|
|
309
|
+
if (minutes < 60) return `${String(minutes)} min`;
|
|
310
|
+
const hours = Math.round(minutes / 60);
|
|
311
|
+
return hours < 48 ? `${String(hours)} h` : `${String(Math.round(hours / 24))} days`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** The last good brief, marked stale with its age; null when there is none. */
|
|
315
|
+
function readCachedBrief(file) {
|
|
316
|
+
if (!file) return null;
|
|
317
|
+
try {
|
|
318
|
+
const { savedAt, brief } = JSON.parse(readFileSync(file, "utf8"));
|
|
319
|
+
if (typeof brief !== "string" || Number.isNaN(Date.parse(savedAt))) return null;
|
|
320
|
+
return (
|
|
321
|
+
`cboard graph brief is stale (saved ${formatAge(Date.now() - Date.parse(savedAt))} ago; ` +
|
|
322
|
+
`the hosted graph did not answer, so this may be out of date):\n${brief}`
|
|
323
|
+
);
|
|
324
|
+
} catch {
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
243
329
|
export async function runBrief({
|
|
244
330
|
api,
|
|
245
331
|
token,
|
|
@@ -253,6 +339,11 @@ export async function runBrief({
|
|
|
253
339
|
fixHint = "run `npm run graph:up`",
|
|
254
340
|
timeoutMs,
|
|
255
341
|
kit,
|
|
342
|
+
wake,
|
|
343
|
+
cacheFile,
|
|
344
|
+
goalNodeId,
|
|
345
|
+
latest,
|
|
346
|
+
references,
|
|
256
347
|
}) {
|
|
257
348
|
const call = (name, args, limitMs = timeoutMs) =>
|
|
258
349
|
mcpCall({
|
|
@@ -264,7 +355,13 @@ export async function runBrief({
|
|
|
264
355
|
...(limitMs ? { timeoutMs: limitMs } : {}),
|
|
265
356
|
});
|
|
266
357
|
try {
|
|
267
|
-
const projects =
|
|
358
|
+
const projects =
|
|
359
|
+
(
|
|
360
|
+
await retryWake(
|
|
361
|
+
(attemptMs) => call("list_projects", {}, wake?.budgetMs ? attemptMs : timeoutMs),
|
|
362
|
+
{ budgetMs: 0, ...wake },
|
|
363
|
+
)
|
|
364
|
+
).data ?? [];
|
|
268
365
|
// A configured project is never replaced by another one the token can see.
|
|
269
366
|
const project = projectId ? projects.find((p) => p.id === projectId) : projects[0];
|
|
270
367
|
if (!project) {
|
|
@@ -308,9 +405,22 @@ export async function runBrief({
|
|
|
308
405
|
const health = (
|
|
309
406
|
await call("graph_health", { project_id: project.id }, HEALTH_TIMEOUT_MS).catch(() => null)
|
|
310
407
|
)?.data;
|
|
311
|
-
|
|
408
|
+
const whoami = await fetchWhoami(() => call("whoami", {}, HEALTH_TIMEOUT_MS));
|
|
409
|
+
const checked = references?.length
|
|
410
|
+
? await Promise.all(
|
|
411
|
+
references.map((ref) =>
|
|
412
|
+
checkReference({ api }, ref, {
|
|
413
|
+
...(fetchImpl ? { fetchImpl } : {}),
|
|
414
|
+
timeoutMs: HEALTH_TIMEOUT_MS,
|
|
415
|
+
}),
|
|
416
|
+
),
|
|
417
|
+
)
|
|
418
|
+
: [];
|
|
419
|
+
const brief = buildBrief({
|
|
312
420
|
project,
|
|
421
|
+
references: checked,
|
|
313
422
|
health,
|
|
423
|
+
...(whoami ? { whoami } : {}),
|
|
314
424
|
revision: activity?.revision ?? status?.graphRevision ?? 0,
|
|
315
425
|
status,
|
|
316
426
|
activity: activity?.items ?? [],
|
|
@@ -318,15 +428,21 @@ export async function runBrief({
|
|
|
318
428
|
sync,
|
|
319
429
|
release,
|
|
320
430
|
...(kit ? { kit } : {}),
|
|
431
|
+
...(goalNodeId ? { goalNodeId } : {}),
|
|
432
|
+
...(latest ? { latest } : {}),
|
|
321
433
|
...(releaseBranch ? { releaseBranch } : {}),
|
|
322
434
|
});
|
|
435
|
+
saveCachedBrief(cacheFile, brief);
|
|
436
|
+
return brief;
|
|
323
437
|
} catch {
|
|
438
|
+
const stale = readCachedBrief(cacheFile);
|
|
439
|
+
if (stale) return stale;
|
|
324
440
|
return `cboard graph brief unavailable; ${fixHint}, then query the graph (\`query_graph\`) before planning.`;
|
|
325
441
|
}
|
|
326
442
|
}
|
|
327
443
|
|
|
328
444
|
/** The brief for the repository at `root`, from its .cboard.json; never throws. */
|
|
329
|
-
export async function briefForRoot({ root, env = process.env, fetchImpl, kitDir, fixHint }) {
|
|
445
|
+
export async function briefForRoot({ root, env = process.env, fetchImpl, kitDir, fixHint, wake }) {
|
|
330
446
|
let config;
|
|
331
447
|
try {
|
|
332
448
|
config = resolveConfig(env, root, { required: true });
|
|
@@ -350,6 +466,12 @@ export async function briefForRoot({ root, env = process.env, fetchImpl, kitDir,
|
|
|
350
466
|
// No generated package.json (cboard's own checkout): no kit version.
|
|
351
467
|
}
|
|
352
468
|
if (typeof kit !== "string") kit = undefined;
|
|
469
|
+
const latest = kit
|
|
470
|
+
? await latestVersion({
|
|
471
|
+
dir: kitDir ?? join(root, ".cboard"),
|
|
472
|
+
...(fetchImpl ? { fetchImpl } : {}),
|
|
473
|
+
})
|
|
474
|
+
: undefined;
|
|
353
475
|
const nodeFile = config.statusNodeFile;
|
|
354
476
|
const statusNodeId =
|
|
355
477
|
nodeFile && existsSync(nodeFile)
|
|
@@ -373,9 +495,13 @@ export async function briefForRoot({ root, env = process.env, fetchImpl, kitDir,
|
|
|
373
495
|
local: !config.hosted,
|
|
374
496
|
},
|
|
375
497
|
...(kit ? { kit } : {}),
|
|
498
|
+
...(config.goalNodeId ? { goalNodeId: config.goalNodeId } : {}),
|
|
499
|
+
...(config.references.length ? { references: config.references } : {}),
|
|
500
|
+
...(latest ? { latest } : {}),
|
|
376
501
|
fixHint: fixHint ?? `run \`node ${kitRel}/connect-check.js\``,
|
|
377
|
-
// The hosted service may need up to a minute to wake from idle.
|
|
378
|
-
|
|
502
|
+
// The hosted service may need up to a minute to wake from idle: wait within the hook budget.
|
|
503
|
+
wake: { budgetMs: config.hosted ? HOSTED_WAKE_MS : 0, ...wake },
|
|
504
|
+
cacheFile: join(root, CACHE_FILE),
|
|
379
505
|
});
|
|
380
506
|
}
|
|
381
507
|
|
package/kit/cboard-kit/config.js
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
// .cboard.json (tracked, never holds a token):
|
|
6
6
|
// { "server": "https://…", "projectId": "<uuid>", "tokenFile": ".cboard/token",
|
|
7
7
|
// "tokenEnv": "CBOARD_PAT" }
|
|
8
|
-
// Optional keys: "
|
|
8
|
+
// Optional keys: "references" ([{ "name", "projectId", "tokenFile" }]: other projects read through their
|
|
9
|
+
// own graph:read token, see `connect --reference`), "goalNodeId" (the project goal requirement node, written by `connect --goal`), "releaseBranch" (shows how far that branch lags main), "statusNodeFile" (a file
|
|
9
10
|
// holding the status node id to show) and "syncCommand" (how to run the cboard command).
|
|
10
11
|
// Environment overrides: CBOARD_GRAPH_URL (a 127.0.0.1/localhost URL selects the local dev graph),
|
|
11
12
|
// CBOARD_PROJECT_ID, and the token variable named by "tokenEnv" (default CBOARD_PAT).
|
|
@@ -20,11 +21,22 @@ export const DEFAULT_TOKEN_FILE = ".cboard/token";
|
|
|
20
21
|
export const DEFAULT_TOKEN_ENV = "CBOARD_PAT";
|
|
21
22
|
export const LOCAL_TOKEN_FILE = ".local/cboard.pat";
|
|
22
23
|
export const DEFAULT_SYNC_COMMAND = "npx @codyn06/cboard";
|
|
24
|
+
export const REFERENCE_NAME = /^[a-z0-9][a-z0-9-]{0,30}$/;
|
|
25
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
26
|
+
/** MCP server name and token file a reference name maps to. */
|
|
27
|
+
export const referenceServer = (name) => `cboard-ref-${name}`;
|
|
28
|
+
export const referenceTokenFile = (name) => `.cboard/ref-${name}.token`;
|
|
23
29
|
|
|
24
30
|
/** Old connect versions wrote a checkout path or `cboard-context` here; those no longer work. */
|
|
25
31
|
export const isStaleSyncCommand = (command) =>
|
|
26
32
|
typeof command === "string" && /<cboard-checkout>|cboard-context/.test(command);
|
|
27
33
|
|
|
34
|
+
/** The default command pinned to a kit version, so the printed sync matches the installed kit. */
|
|
35
|
+
export const pinSyncCommand = (command, version) =>
|
|
36
|
+
command === DEFAULT_SYNC_COMMAND && /^\d+\.\d+\.\d+/.test(String(version))
|
|
37
|
+
? `${DEFAULT_SYNC_COMMAND}@${String(version)}`
|
|
38
|
+
: command;
|
|
39
|
+
|
|
28
40
|
export class ConfigError extends Error {
|
|
29
41
|
constructor(message) {
|
|
30
42
|
super(message);
|
|
@@ -163,6 +175,22 @@ export function resolveConfig(env, root, options = {}) {
|
|
|
163
175
|
const syncCommand = str(file?.syncCommand);
|
|
164
176
|
if (statusNodeFile) validateRepoPath(root, statusNodeFile, "statusNodeFile");
|
|
165
177
|
const abs = (path) => join(root, path);
|
|
178
|
+
// Reference projects: read-only access to other projects, each with its own token file (never the
|
|
179
|
+
// main token, never $CBOARD_PAT).
|
|
180
|
+
const rawRefs = file?.references ?? [];
|
|
181
|
+
if (!Array.isArray(rawRefs)) throw new ConfigError(`${CONFIG_FILE}: references must be an array`);
|
|
182
|
+
const references = rawRefs.map((raw) => {
|
|
183
|
+
const name = str(raw?.name);
|
|
184
|
+
const refProject = str(raw?.projectId);
|
|
185
|
+
if (!name || !REFERENCE_NAME.test(name) || !refProject || !UUID_PATTERN.test(refProject)) {
|
|
186
|
+
throw new ConfigError(
|
|
187
|
+
`${CONFIG_FILE}: each reference needs a name (lowercase letters, digits, hyphens) and a project UUID`,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
const tokenFileRel = str(raw.tokenFile) ?? referenceTokenFile(name);
|
|
191
|
+
validateRepoPath(root, tokenFileRel, `references.${name}.tokenFile`);
|
|
192
|
+
return { name, projectId: refProject, tokenFile: abs(tokenFileRel), tokenFileRel };
|
|
193
|
+
});
|
|
166
194
|
return {
|
|
167
195
|
root,
|
|
168
196
|
configured: file !== null,
|
|
@@ -173,6 +201,8 @@ export function resolveConfig(env, root, options = {}) {
|
|
|
173
201
|
tokenFile: abs(tokenFile),
|
|
174
202
|
tokenFileRel: tokenFile,
|
|
175
203
|
releaseBranch: str(file?.releaseBranch),
|
|
204
|
+
goalNodeId: str(file?.goalNodeId),
|
|
205
|
+
references,
|
|
176
206
|
statusNodeFile: statusNodeFile ? abs(statusNodeFile) : undefined,
|
|
177
207
|
syncCommand:
|
|
178
208
|
syncCommand && !isStaleSyncCommand(syncCommand) ? syncCommand : DEFAULT_SYNC_COMMAND,
|
|
@@ -195,6 +225,11 @@ export function readToken(config, env) {
|
|
|
195
225
|
return fromFile || env.CBOARD_PAT?.trim() || "";
|
|
196
226
|
}
|
|
197
227
|
|
|
228
|
+
/** A reference's token: its own file only, so a reference can never borrow the main (writable) token. */
|
|
229
|
+
export function readReferenceToken(reference) {
|
|
230
|
+
return existsSync(reference.tokenFile) ? readFileSync(reference.tokenFile, "utf8").trim() : "";
|
|
231
|
+
}
|
|
232
|
+
|
|
198
233
|
/** The repo root for a kit script: from the working directory, else from the kit's own location. */
|
|
199
234
|
export function locateRoot(cwd, importMetaUrl) {
|
|
200
235
|
return findRoot(cwd) ?? findRoot(dirname(fileURLToPath(importMetaUrl))) ?? resolve(cwd);
|
|
@@ -208,8 +243,8 @@ export function isMain(importMetaUrl) {
|
|
|
208
243
|
/** How to get a token, for messages. */
|
|
209
244
|
export function tokenFix(config) {
|
|
210
245
|
return (
|
|
211
|
-
"create one in cboard (Agent tokens button in the project header
|
|
212
|
-
`graph:contribute, graph:context) and save it to ${config.tokenFileRel} (it takes precedence over $${DEFAULT_TOKEN_ENV}` +
|
|
246
|
+
"create one in cboard (Agent tokens button in the project header; members choose graph:read, " +
|
|
247
|
+
`graph:contribute, graph:context; viewers are read-only (graph:read only)) and save it to ${config.tokenFileRel} (it takes precedence over $${DEFAULT_TOKEN_ENV}` +
|
|
213
248
|
(config.tokenEnv === DEFAULT_TOKEN_ENV ? ")" : `; $${config.tokenEnv} overrides the file)`)
|
|
214
249
|
);
|
|
215
250
|
}
|
|
@@ -2,14 +2,17 @@
|
|
|
2
2
|
// SessionStart hook: checks that this repository can reach its cboard graph (token present and
|
|
3
3
|
// accepted, configured project visible). Never starts anything and never prints the token.
|
|
4
4
|
// Prints `cboard graph: CONNECTED …` or a fix hint on stderr; exits 1 when not connected.
|
|
5
|
-
import { McpError, mcpCall } from "./mcp.js";
|
|
5
|
+
import { McpError, describeWhoami, fetchWhoami, mcpCall } from "./mcp.js";
|
|
6
|
+
import { retryWake } from "./wait.js";
|
|
7
|
+
import { checkReference } from "./references.js";
|
|
6
8
|
import { ConfigError, isMain, locateRoot, readToken, resolveConfig, tokenFix } from "./config.js";
|
|
7
9
|
|
|
8
|
-
// The hosted service may need up to a minute to wake from idle
|
|
9
|
-
|
|
10
|
+
// The hosted service may need up to a minute to wake from idle; retry with backoff within this
|
|
11
|
+
// budget (the hook timeout is 120 s).
|
|
12
|
+
const HOSTED_WAKE_MS = 90_000;
|
|
10
13
|
|
|
11
14
|
/** @returns {Promise<{ code: number, message: string }>} */
|
|
12
|
-
export async function connectCheck(env, root, { fetchImpl, timeoutMs } = {}) {
|
|
15
|
+
export async function connectCheck(env, root, { fetchImpl, timeoutMs, wake } = {}) {
|
|
13
16
|
let config;
|
|
14
17
|
try {
|
|
15
18
|
config = resolveConfig(env, root, { required: true });
|
|
@@ -17,23 +20,48 @@ export async function connectCheck(env, root, { fetchImpl, timeoutMs } = {}) {
|
|
|
17
20
|
if (error instanceof ConfigError) return { code: 1, message: error.message };
|
|
18
21
|
throw error;
|
|
19
22
|
}
|
|
23
|
+
const main = await checkMain(config, env, { fetchImpl, timeoutMs, wake });
|
|
24
|
+
if (!config.references.length) return main;
|
|
25
|
+
const refs = await Promise.all(
|
|
26
|
+
config.references.map((ref) =>
|
|
27
|
+
checkReference(config, ref, { ...(fetchImpl ? { fetchImpl } : {}), timeoutMs }),
|
|
28
|
+
),
|
|
29
|
+
);
|
|
30
|
+
return {
|
|
31
|
+
code: main.code || (refs.some((r) => !r.ok) ? 1 : 0),
|
|
32
|
+
message: [main.message, ...refs.map((r) => r.message)].join("\n"),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function checkMain(config, env, { fetchImpl, timeoutMs, wake }) {
|
|
20
37
|
const token = readToken(config, env);
|
|
21
38
|
if (!token) return { code: 1, message: `token missing; ${tokenFix(config)}` };
|
|
22
39
|
let projects;
|
|
40
|
+
const budgetMs = wake?.budgetMs ?? (config.hosted ? HOSTED_WAKE_MS : 0);
|
|
23
41
|
try {
|
|
24
|
-
const listed = await
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
42
|
+
const listed = await retryWake(
|
|
43
|
+
(attemptMs) =>
|
|
44
|
+
mcpCall({
|
|
45
|
+
api: config.api,
|
|
46
|
+
token,
|
|
47
|
+
name: "list_projects",
|
|
48
|
+
timeoutMs: timeoutMs ?? (budgetMs ? attemptMs : 5000),
|
|
49
|
+
...(fetchImpl ? { fetchImpl } : {}),
|
|
50
|
+
}),
|
|
51
|
+
{ ...wake, budgetMs },
|
|
52
|
+
);
|
|
31
53
|
projects = Array.isArray(listed?.data) ? listed.data : [];
|
|
32
54
|
} catch (error) {
|
|
33
55
|
if (error instanceof McpError && error.kind === "unauthorized") {
|
|
34
56
|
return { code: 1, message: `token rejected; ${tokenFix(config)}` };
|
|
35
57
|
}
|
|
36
|
-
return {
|
|
58
|
+
return {
|
|
59
|
+
code: 1,
|
|
60
|
+
message:
|
|
61
|
+
budgetMs > 0
|
|
62
|
+
? `hosted service did not wake within ${String(Math.round(budgetMs / 1000))} s (${config.api}); retry in a minute, or check the service`
|
|
63
|
+
: `graph unreachable (${config.api}); retry, or check the service`,
|
|
64
|
+
};
|
|
37
65
|
}
|
|
38
66
|
if (config.projectId && !projects.some((p) => p.id === config.projectId)) {
|
|
39
67
|
return {
|
|
@@ -41,7 +69,22 @@ export async function connectCheck(env, root, { fetchImpl, timeoutMs } = {}) {
|
|
|
41
69
|
message: `connected to ${config.api}, but project ${config.projectId} is not visible to this token; ${tokenFix(config)}`,
|
|
42
70
|
};
|
|
43
71
|
}
|
|
44
|
-
|
|
72
|
+
// Optional: an older server lacks whoami; any failure keeps the plain message. One short try only.
|
|
73
|
+
const me = await fetchWhoami(() =>
|
|
74
|
+
mcpCall({
|
|
75
|
+
api: config.api,
|
|
76
|
+
token,
|
|
77
|
+
name: "whoami",
|
|
78
|
+
timeoutMs: timeoutMs ?? 5000,
|
|
79
|
+
...(fetchImpl ? { fetchImpl } : {}),
|
|
80
|
+
}),
|
|
81
|
+
);
|
|
82
|
+
const info = me ? describeWhoami(me) : null;
|
|
83
|
+
const head = info?.readOnly
|
|
84
|
+
? "CONNECTED (read-only): you can query, not contribute"
|
|
85
|
+
: "CONNECTED";
|
|
86
|
+
const tail = info?.warning ? `; ${info.warning}` : "";
|
|
87
|
+
return { code: 0, message: `${head} (${config.api}/mcp)${tail}` };
|
|
45
88
|
}
|
|
46
89
|
|
|
47
90
|
if (isMain(import.meta.url)) {
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/* global fetch, AbortSignal, process, setTimeout, console, Buffer, URL */
|
|
2
|
+
// Browser (device) login for `cboard connect`: the CLI asks the server for a code, the owner
|
|
3
|
+
// approves it in the browser and picks the project, and the token comes back encrypted to a key
|
|
4
|
+
// that never leaves this process ("cboard-device-v1": X25519 + HKDF-SHA256 + AES-256-GCM).
|
|
5
|
+
// Never logs or prints the token.
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import {
|
|
8
|
+
createDecipheriv,
|
|
9
|
+
createPublicKey,
|
|
10
|
+
diffieHellman,
|
|
11
|
+
generateKeyPairSync,
|
|
12
|
+
hkdfSync,
|
|
13
|
+
} from "node:crypto";
|
|
14
|
+
import { retryWake } from "./wait.js";
|
|
15
|
+
|
|
16
|
+
const SCHEME = "cboard-device-v1";
|
|
17
|
+
const UNSUPPORTED =
|
|
18
|
+
"this server does not support browser login; use --project <id> and a token (see docs/guides/using-cboard.md)";
|
|
19
|
+
|
|
20
|
+
export class DeviceError extends Error {
|
|
21
|
+
/** @param {string} message @param {boolean} [transient] network failure or 5xx: worth retrying */
|
|
22
|
+
constructor(message, transient = false) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "DeviceError";
|
|
25
|
+
this.transient = transient;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Decrypts `encrypted_token` (base64url of serverPub[32] | iv[12] | ciphertext | tag[16]). */
|
|
30
|
+
export function decryptToken(privateKey, encrypted) {
|
|
31
|
+
const raw = Buffer.from(String(encrypted), "base64url");
|
|
32
|
+
if (raw.length < 32 + 12 + 16 + 1) throw new DeviceError("the server sent a malformed token");
|
|
33
|
+
try {
|
|
34
|
+
const ephemeral = createPublicKey({
|
|
35
|
+
key: { kty: "OKP", crv: "X25519", x: raw.subarray(0, 32).toString("base64url") },
|
|
36
|
+
format: "jwk",
|
|
37
|
+
});
|
|
38
|
+
const shared = diffieHellman({ privateKey, publicKey: ephemeral });
|
|
39
|
+
const key = Buffer.from(hkdfSync("sha256", shared, Buffer.alloc(0), SCHEME, 32));
|
|
40
|
+
const decipher = createDecipheriv("aes-256-gcm", key, raw.subarray(32, 44));
|
|
41
|
+
decipher.setAAD(Buffer.from(SCHEME));
|
|
42
|
+
decipher.setAuthTag(raw.subarray(raw.length - 16));
|
|
43
|
+
return Buffer.concat([
|
|
44
|
+
decipher.update(raw.subarray(44, raw.length - 16)),
|
|
45
|
+
decipher.final(),
|
|
46
|
+
]).toString("utf8");
|
|
47
|
+
} catch {
|
|
48
|
+
throw new DeviceError("could not decrypt the token the server sent");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Best effort: open the URL in the default browser without a shell. Never throws. */
|
|
53
|
+
export function openBrowser(url) {
|
|
54
|
+
try {
|
|
55
|
+
const parsed = new URL(url);
|
|
56
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return;
|
|
57
|
+
const [command, args] =
|
|
58
|
+
process.platform === "win32"
|
|
59
|
+
? ["rundll32", ["url.dll,FileProtocolHandler", parsed.href]]
|
|
60
|
+
: process.platform === "darwin"
|
|
61
|
+
? ["open", [parsed.href]]
|
|
62
|
+
: ["xdg-open", [parsed.href]];
|
|
63
|
+
const child = spawn(command, args, { stdio: "ignore", detached: true, windowsHide: true });
|
|
64
|
+
child.on("error", () => undefined);
|
|
65
|
+
child.unref();
|
|
66
|
+
} catch {
|
|
67
|
+
// Printing the URL is the fallback.
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function post(fetchImpl, server, path, body) {
|
|
72
|
+
let res;
|
|
73
|
+
try {
|
|
74
|
+
res = await fetchImpl(`${server}${path}`, {
|
|
75
|
+
method: "POST",
|
|
76
|
+
signal: AbortSignal.timeout(30_000),
|
|
77
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
78
|
+
body: JSON.stringify(body),
|
|
79
|
+
});
|
|
80
|
+
} catch {
|
|
81
|
+
throw new DeviceError(`could not reach ${server}`, true);
|
|
82
|
+
}
|
|
83
|
+
if (res.status >= 500) throw new DeviceError(`${server} answered ${String(res.status)}`, true);
|
|
84
|
+
let json = null;
|
|
85
|
+
try {
|
|
86
|
+
json = await res.json();
|
|
87
|
+
} catch {
|
|
88
|
+
// Handled by status below.
|
|
89
|
+
}
|
|
90
|
+
return { status: res.status, ok: res.ok, json };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Runs the device flow against `server` (an origin) and returns the token and the chosen project.
|
|
97
|
+
* @param {{ server: string, fetchImpl?: typeof fetch, print?: (line: string) => void,
|
|
98
|
+
* open?: ((url: string) => void) | null, sleep?: (ms: number) => Promise<void>,
|
|
99
|
+
* now?: () => number, wakeBudgetMs?: number }} options `open: null` skips the browser.
|
|
100
|
+
* @returns {Promise<{ token: string, projectId: string, scopes: string[], expiresAt: string }>}
|
|
101
|
+
*/
|
|
102
|
+
export async function deviceLogin({
|
|
103
|
+
server,
|
|
104
|
+
fetchImpl = fetch,
|
|
105
|
+
print = console.log,
|
|
106
|
+
open = openBrowser,
|
|
107
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
108
|
+
now = Date.now,
|
|
109
|
+
wakeBudgetMs = 0,
|
|
110
|
+
}) {
|
|
111
|
+
const { publicKey, privateKey } = generateKeyPairSync("x25519");
|
|
112
|
+
const clientPublicKey = publicKey.export({ format: "jwk" }).x;
|
|
113
|
+
const started = await retryWake(
|
|
114
|
+
() => post(fetchImpl, server, "/v1/device/code", { client_public_key: clientPublicKey }),
|
|
115
|
+
{ budgetMs: wakeBudgetMs, onWake: (message) => print(`cboard: ${message}`), sleep, now },
|
|
116
|
+
);
|
|
117
|
+
if (started.status === 404) throw new DeviceError(UNSUPPORTED);
|
|
118
|
+
if (started.status === 429) {
|
|
119
|
+
throw new DeviceError("the server is rate limiting login requests; wait a minute and retry");
|
|
120
|
+
}
|
|
121
|
+
const grant = started.json;
|
|
122
|
+
if (
|
|
123
|
+
!started.ok ||
|
|
124
|
+
!isObject(grant) ||
|
|
125
|
+
typeof grant.device_code !== "string" ||
|
|
126
|
+
typeof grant.user_code !== "string" ||
|
|
127
|
+
typeof grant.verification_uri !== "string"
|
|
128
|
+
) {
|
|
129
|
+
throw new DeviceError(`the server did not start a login (status ${String(started.status)})`);
|
|
130
|
+
}
|
|
131
|
+
const deadline = now() + (Number(grant.expires_in) > 0 ? Number(grant.expires_in) : 600) * 1000;
|
|
132
|
+
let interval = Number(grant.interval) >= 0 ? Number(grant.interval) : 5;
|
|
133
|
+
const url =
|
|
134
|
+
typeof grant.verification_uri_complete === "string"
|
|
135
|
+
? grant.verification_uri_complete
|
|
136
|
+
: grant.verification_uri;
|
|
137
|
+
print(`Open ${url}`);
|
|
138
|
+
print(`and confirm the code ${grant.user_code} to connect this repository.`);
|
|
139
|
+
// Only open a page on the server we are talking to; a mismatched origin is printed, never launched.
|
|
140
|
+
let sameOrigin = false;
|
|
141
|
+
try {
|
|
142
|
+
sameOrigin = new URL(url).origin === new URL(server).origin;
|
|
143
|
+
} catch {
|
|
144
|
+
// an unparsable URL is not opened
|
|
145
|
+
}
|
|
146
|
+
if (open && sameOrigin) open(url);
|
|
147
|
+
print("Waiting for approval in the browser...");
|
|
148
|
+
|
|
149
|
+
for (;;) {
|
|
150
|
+
await sleep(interval * 1000);
|
|
151
|
+
if (now() >= deadline) throw new DeviceError("the login code expired; run connect again");
|
|
152
|
+
let polled;
|
|
153
|
+
try {
|
|
154
|
+
polled = await post(fetchImpl, server, "/v1/device/token", {
|
|
155
|
+
device_code: grant.device_code,
|
|
156
|
+
});
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (error instanceof DeviceError && error.transient) continue;
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
if (polled.status === 429) {
|
|
162
|
+
interval += 5;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
const body = polled.json;
|
|
166
|
+
if (polled.ok && isObject(body) && typeof body.encrypted_token === "string") {
|
|
167
|
+
const token = decryptToken(privateKey, body.encrypted_token);
|
|
168
|
+
if (!/^cbp_[A-Za-z0-9_-]+$/.test(token))
|
|
169
|
+
throw new DeviceError("the server returned a token in an unexpected format");
|
|
170
|
+
return {
|
|
171
|
+
token,
|
|
172
|
+
projectId: String(body.project_id),
|
|
173
|
+
scopes: Array.isArray(body.scopes) ? body.scopes : [],
|
|
174
|
+
expiresAt: String(body.expires_at ?? ""),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
const code = isObject(body) ? body.error : undefined;
|
|
178
|
+
if (code === "authorization_pending") {
|
|
179
|
+
if (Number(body.interval) >= 0) interval = Number(body.interval);
|
|
180
|
+
} else if (code === "slow_down") {
|
|
181
|
+
interval = Number(body.interval) >= 0 ? Number(body.interval) : interval + 5;
|
|
182
|
+
} else if (code === "expired_token") {
|
|
183
|
+
throw new DeviceError("the login code expired; run connect again");
|
|
184
|
+
} else if (code === "access_denied") {
|
|
185
|
+
throw new DeviceError("the login was denied in the browser");
|
|
186
|
+
} else {
|
|
187
|
+
throw new DeviceError(
|
|
188
|
+
`the login is no longer valid (${typeof code === "string" ? code : String(polled.status)}); run connect again`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|