claude-code-session-manager 0.143.0 → 0.144.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 +3 -1
- package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
- package/dist/assets/{History-DTttbvPb.js → History-C3E6y_7t.js} +2 -2
- package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
- package/dist/assets/{Panel-B_D4Bg7L.js → Panel-CnfWs46Z.js} +1 -1
- package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
- package/dist/assets/Scheduler-D8un7N3B.js +16 -0
- package/dist/assets/{SkillReferenceGraph-D1b2aiol.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
- package/dist/assets/{Skills-cfV7sgk6.js → Skills-Bg5O2Hyn.js} +23 -23
- package/dist/assets/{TiptapBody-DVXtEIVy.js → TiptapBody-BdzoBmqu.js} +27 -27
- package/dist/assets/{Toggle-CYajnSdx.js → Toggle-Dt5K1OXt.js} +1 -1
- package/dist/assets/{VoiceButton-DJ4gGRuE.js → VoiceButton-CTLyRgdF.js} +1 -1
- package/dist/assets/{historyTotals-D3MoHY2U.js → historyTotals-B2_KWBga.js} +1 -1
- package/dist/assets/{index-CdTppjKR.js → index-446b69rr.js} +698 -697
- package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +439 -436
- package/package.json +4 -2
- package/plugins/session-manager-dev/skills/develop/SKILL.md +14 -13
- package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
- package/scripts/README.md +1 -1
- package/scripts/scheduler-mcp-server.cjs +77 -0
- package/src/main/adminRouteRegistry.cjs +6 -0
- package/src/main/agentLibrary.cjs +60 -11
- package/src/main/agentsIpc.cjs +19 -0
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +109 -0
- package/src/main/health.cjs +59 -17
- package/src/main/index.cjs +4 -0
- package/src/main/ipcSchemas.cjs +50 -1
- package/src/main/lib/claude/agentArmory.cjs +128 -0
- package/src/main/lib/claude/agentModelResolve.cjs +3 -2
- package/src/main/lib/claude/agentSnapshot.cjs +24 -3
- package/src/main/lib/claude/builtinTools.cjs +110 -0
- package/src/main/lib/claude/environmentProfiles.cjs +1 -1
- package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
- package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
- package/src/main/lib/claude/personaToolScope.cjs +77 -6
- package/src/main/lib/epic/epicDepsSync.cjs +66 -0
- package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
- package/src/main/lib/epic/epicSettle.cjs +48 -4
- package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
- package/src/main/lib/epic/epicValidationHook.cjs +9 -1
- package/src/main/lib/epic/planReviewInput.cjs +123 -0
- package/src/main/lib/epic/restorableSessions.cjs +1 -0
- package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
- package/src/main/lib/externalContract.cjs +12 -0
- package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
- package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +24 -3
- package/src/main/lib/feedback-remote/pendingReplies.cjs +8 -4
- package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
- package/src/main/lib/feedback-remote/replyClaims.cjs +15 -6
- package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
- package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
- package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
- package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
- package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
- package/src/main/lib/git/gitWorktree.cjs +1 -1
- package/src/main/lib/git/worktreeDeps.cjs +9 -3
- package/src/main/lib/mcpToolCatalog.cjs +43 -5
- package/src/main/lib/mcpToolsProbe.cjs +19 -2
- package/src/main/lib/packs/packCatalog.cjs +98 -5
- package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
- package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
- package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
- package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
- package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
- package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +94 -0
- package/src/main/lib/prd/prdCreate.cjs +48 -5
- package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
- package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
- package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
- package/src/main/lib/process/peerChatSession.cjs +165 -0
- package/src/main/lib/project-pages/videoScriptPress.cjs +6 -0
- package/src/main/lib/project-pages/videoScriptRunRoute.cjs +24 -4
- package/src/main/lib/promptSessionSchema.cjs +2 -0
- package/src/main/lib/scheduler/baselineGate.cjs +31 -2
- package/src/main/lib/scheduler/planRecordHarvest.cjs +104 -12
- package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
- package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
- package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
- package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
- package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
- package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +12 -2
- package/src/main/lib/tasks/memoryConsolidation.cjs +109 -37
- package/src/main/lib/tasks/taskAdminRoutes.cjs +26 -14
- package/src/main/lib/tasks/taskRun.cjs +3 -1
- package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
- package/src/main/projectPages.cjs +22 -14
- package/src/main/pty.cjs +3 -0
- package/src/main/runVerify.cjs +3 -2
- package/src/main/scheduler/planReviewHold.cjs +140 -0
- package/src/main/scheduler/prdParser.cjs +1 -0
- package/src/main/scheduler/reviewLadder.cjs +2 -0
- package/src/main/scheduler/utilizationHold.cjs +7 -2
- package/src/main/scheduler.cjs +532 -78
- package/src/main/seedAgentPersonas.cjs +11 -6
- package/src/main/seedStatus.cjs +1 -1
- package/src/main/templates/PRD_AUTHORING.md +16 -1
- package/src/main/webRemote.cjs +47 -7
- package/src/preload/api.d.ts +71 -1
- package/src/preload/apiSurface.json +28 -0
- package/src/preload/index.cjs +9 -0
- package/src/seed/agents/architect.md +28 -43
- package/src/seed/agents/dev-lead.md +3 -1
- package/src/seed/agents/md-network-curator.md +27 -0
- package/src/seed/agents/plan-reviewer.md +47 -0
- package/src/seed/agents/validator.md +2 -1
- package/dist/assets/AppSettings-BO4jDVGO.js +0 -2
- package/dist/assets/HomeClaudeConfig-DADP5bfn.js +0 -3
- package/dist/assets/ProjectClaudeConfig-DPnDJKcr.js +0 -26
- package/dist/assets/Scheduler-CNLjn90m.js +0 -16
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* servicePairLocalRoutes.cjs — POST /admin/services/pair-local (start) and
|
|
4
|
+
* POST /admin/services/pair-local/confirm on the token-guarded loopback admin
|
|
5
|
+
* transport, so a same-machine agent can pair a service with no window step.
|
|
6
|
+
* Auth is the transport's job (401 before the handler runs).
|
|
7
|
+
*/
|
|
8
|
+
'use strict';
|
|
9
|
+
|
|
10
|
+
const { z } = require('zod');
|
|
11
|
+
|
|
12
|
+
/** @param {string} error */
|
|
13
|
+
function statusOf(error) {
|
|
14
|
+
if (error === 'web_remote_off' || error === 'no_paired_device') return 409;
|
|
15
|
+
if (error === 'not_local_pairing' || error === 'no_pending_service') return 404;
|
|
16
|
+
if (error === 'sas_mismatch') return 403;
|
|
17
|
+
return 400;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {{ registerRoute: (method: string, path: string, handler: (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => Promise<void>) => void }} adminHttp
|
|
22
|
+
* @param {{ webRemote?: any }} [opts]
|
|
23
|
+
*/
|
|
24
|
+
function registerAdminRoute(adminHttp, { webRemote } = {}) {
|
|
25
|
+
const { readBody, sendJson } = require('./localAdminHttp.cjs');
|
|
26
|
+
const { SERVICE_TOOL_NAMES } = require('./servicePairings.cjs');
|
|
27
|
+
const wr = () => webRemote || require('../../webRemote.cjs');
|
|
28
|
+
const path = require('node:path');
|
|
29
|
+
|
|
30
|
+
const startSchema = z.object({
|
|
31
|
+
name: z.string().min(1).max(80),
|
|
32
|
+
homeCwd: z.string().min(1).refine((p) => path.isAbsolute(p), 'homeCwd must be an absolute path'),
|
|
33
|
+
tools: z.array(z.enum(/** @type {[string, ...string[]]} */ (SERVICE_TOOL_NAMES))).min(1),
|
|
34
|
+
projectRoot: z.string().min(1).optional(),
|
|
35
|
+
}).strict();
|
|
36
|
+
const confirmSchema = z.object({
|
|
37
|
+
pairingId: z.string().min(1),
|
|
38
|
+
sas: z.string().regex(/^\d{6}$/),
|
|
39
|
+
}).strict();
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @template {z.ZodTypeAny} S
|
|
43
|
+
* @param {import('node:http').IncomingMessage} req @param {import('node:http').ServerResponse} res @param {S} schema
|
|
44
|
+
* @returns {Promise<z.infer<S> | null>}
|
|
45
|
+
*/
|
|
46
|
+
async function parse(req, res, schema) {
|
|
47
|
+
const raw = await readBody(req);
|
|
48
|
+
let json;
|
|
49
|
+
try {
|
|
50
|
+
json = raw ? JSON.parse(raw) : {};
|
|
51
|
+
} catch {
|
|
52
|
+
sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
const r = schema.safeParse(json);
|
|
56
|
+
if (!r.success) {
|
|
57
|
+
const i = r.error.issues[0];
|
|
58
|
+
sendJson(res, 400, { ok: false, error: `${(i.path || []).join('.') || 'body'}: ${i.message}` });
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
return r.data;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
adminHttp.registerRoute('POST', '/admin/services/pair-local', async (req, res) => {
|
|
65
|
+
const b = await parse(req, res, startSchema);
|
|
66
|
+
if (!b) return;
|
|
67
|
+
const r = await wr().servicePairStartLocal({ name: b.name, homeCwd: b.homeCwd, scope: b.tools, projectRoot: b.projectRoot });
|
|
68
|
+
if (!r || !r.ok) {
|
|
69
|
+
const error = (r && r.error) || 'pairing failed';
|
|
70
|
+
sendJson(res, statusOf(error), { ok: false, error });
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const { code, pairingId, codeExpiresAt, deviceId } = r;
|
|
74
|
+
sendJson(res, 200, { ok: true, code, pairingId, codeExpiresAt, deviceId });
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
adminHttp.registerRoute('POST', '/admin/services/pair-local/confirm', async (req, res) => {
|
|
78
|
+
const b = await parse(req, res, confirmSchema);
|
|
79
|
+
if (!b) return;
|
|
80
|
+
const r = await wr().confirmServiceSasLocal(b.pairingId, b.sas);
|
|
81
|
+
if (!r || !r.ok) {
|
|
82
|
+
const error = (r && r.error) || 'confirm failed';
|
|
83
|
+
sendJson(res, statusOf(error), { ok: false, error });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const { pubKey: _omit, ...service } = r.service || {};
|
|
87
|
+
sendJson(res, 200, { ok: true, service });
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
module.exports = { registerAdminRoute };
|
|
@@ -7,13 +7,16 @@
|
|
|
7
7
|
* File (default ~/.claude/session-manager/remote-services.json, mode 0600):
|
|
8
8
|
* { version: 1, pending: [...], services: [...] }
|
|
9
9
|
*
|
|
10
|
-
* - pending: { pairingId, name, homeCwd, scope, createdAt, expiresAt } — a
|
|
10
|
+
* - pending: { pairingId, name, homeCwd, scope, projectRoot, createdAt, expiresAt } — a
|
|
11
11
|
* pairing the owner started; lives 10 minutes (the relay code itself lasts 5).
|
|
12
|
-
* - services: { serviceId, name, homeCwd, scope, pubKey, relayClientId,
|
|
12
|
+
* - services: { serviceId, name, homeCwd, scope, projectRoot, pubKey, relayClientId,
|
|
13
13
|
* pairedAt, lastSeenAt, opened: [{ cwd, epicId, externalRef?, at }] } — a
|
|
14
14
|
* confirmed service with its pinned P-256 public key and the ledger of Epics
|
|
15
15
|
* it opened (newest 1000), each keyed by project + id: an Epic id matches
|
|
16
16
|
* only in the project the service opened it in.
|
|
17
|
+
* - projectRoot: the owner-approved projects folder project_create creates
|
|
18
|
+
* into — required when scope grants project_create, null otherwise (and for
|
|
19
|
+
* a record saved before the field existed).
|
|
17
20
|
*
|
|
18
21
|
* State is read once from disk (missing/corrupt = empty) and kept in memory;
|
|
19
22
|
* every mutation is written atomically, serialized through one queue. Reads
|
|
@@ -40,6 +43,7 @@ const SERVICE_TOOL_NAMES = Object.freeze([
|
|
|
40
43
|
'macro_run',
|
|
41
44
|
'epic_get',
|
|
42
45
|
'events_read',
|
|
46
|
+
'project_create',
|
|
43
47
|
]);
|
|
44
48
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
45
49
|
|
|
@@ -62,6 +66,15 @@ function validateHomeCwd(homeCwd) {
|
|
|
62
66
|
return homeCwd;
|
|
63
67
|
}
|
|
64
68
|
|
|
69
|
+
/** Required (absolute, no NUL, resolved) when the scope grants project_create; null otherwise. */
|
|
70
|
+
function validateProjectRoot(projectRoot, scope) {
|
|
71
|
+
if (!scope.includes('project_create')) return null;
|
|
72
|
+
if (typeof projectRoot !== 'string' || projectRoot.length === 0 || !path.isAbsolute(projectRoot) || projectRoot.includes('\0')) {
|
|
73
|
+
throw new Error('projectRoot must be an absolute path when scope includes project_create');
|
|
74
|
+
}
|
|
75
|
+
return path.resolve(projectRoot);
|
|
76
|
+
}
|
|
77
|
+
|
|
65
78
|
function validateScope(scope) {
|
|
66
79
|
if (!Array.isArray(scope) || scope.length === 0) throw new Error('scope must be a non-empty list of tool names');
|
|
67
80
|
for (const t of scope) {
|
|
@@ -107,31 +120,52 @@ function validateExternalRef(externalRef) {
|
|
|
107
120
|
return externalRef;
|
|
108
121
|
}
|
|
109
122
|
|
|
123
|
+
const PAIRED_VIA = ['window', 'local'];
|
|
124
|
+
|
|
110
125
|
function publicService(s) {
|
|
111
126
|
return {
|
|
112
127
|
serviceId: s.serviceId,
|
|
113
128
|
name: s.name,
|
|
114
129
|
homeCwd: s.homeCwd,
|
|
115
130
|
scope: [...s.scope],
|
|
131
|
+
projectRoot: typeof s.projectRoot === 'string' ? s.projectRoot : null,
|
|
116
132
|
pubKey: s.pubKey,
|
|
117
133
|
relayClientId: s.relayClientId,
|
|
118
134
|
pairedAt: s.pairedAt,
|
|
119
135
|
lastSeenAt: s.lastSeenAt,
|
|
136
|
+
pairedVia: s.pairedVia === 'local' ? 'local' : 'window',
|
|
120
137
|
};
|
|
121
138
|
}
|
|
122
139
|
|
|
123
140
|
function publicPending(p) {
|
|
124
|
-
return {
|
|
141
|
+
return {
|
|
142
|
+
pairingId: p.pairingId,
|
|
143
|
+
name: p.name,
|
|
144
|
+
homeCwd: p.homeCwd,
|
|
145
|
+
scope: [...p.scope],
|
|
146
|
+
projectRoot: typeof p.projectRoot === 'string' ? p.projectRoot : null,
|
|
147
|
+
createdAt: p.createdAt,
|
|
148
|
+
expiresAt: p.expiresAt,
|
|
149
|
+
pairedVia: p.pairedVia === 'local' ? 'local' : 'window',
|
|
150
|
+
};
|
|
125
151
|
}
|
|
126
152
|
|
|
127
153
|
function normalizeLoaded(raw) {
|
|
128
154
|
const empty = { version: STORE_VERSION, pending: [], services: [] };
|
|
129
155
|
if (!raw || typeof raw !== 'object') return empty;
|
|
130
|
-
const
|
|
156
|
+
const rootOf = (x) => (typeof x.projectRoot === 'string' && x.projectRoot !== '' ? x.projectRoot : null);
|
|
157
|
+
const pending = Array.isArray(raw.pending)
|
|
158
|
+
? raw.pending.filter((p) => p && typeof p.pairingId === 'string').map((p) => ({ ...p, projectRoot: rootOf(p) }))
|
|
159
|
+
: [];
|
|
131
160
|
const services = Array.isArray(raw.services)
|
|
132
161
|
? raw.services
|
|
133
162
|
.filter((s) => s && typeof s.serviceId === 'string' && typeof s.pubKey === 'string')
|
|
134
|
-
.map((s) => ({
|
|
163
|
+
.map((s) => ({
|
|
164
|
+
...s,
|
|
165
|
+
scope: Array.isArray(s.scope) ? s.scope : [],
|
|
166
|
+
projectRoot: rootOf(s),
|
|
167
|
+
opened: Array.isArray(s.opened) ? s.opened : [],
|
|
168
|
+
}))
|
|
135
169
|
: [];
|
|
136
170
|
return { version: STORE_VERSION, pending, services };
|
|
137
171
|
}
|
|
@@ -173,15 +207,19 @@ function createServicePairings({ filePath, now } = {}) {
|
|
|
173
207
|
}
|
|
174
208
|
|
|
175
209
|
return {
|
|
176
|
-
createPending({ name, homeCwd, scope } = /** @type {any} */ ({})) {
|
|
210
|
+
createPending({ name, homeCwd, scope, projectRoot, pairedVia = 'window' } = /** @type {any} */ ({})) {
|
|
177
211
|
let entry;
|
|
178
212
|
try {
|
|
179
213
|
const t = clock();
|
|
214
|
+
if (!PAIRED_VIA.includes(pairedVia)) throw new Error(`pairedVia must be one of: ${PAIRED_VIA.join(', ')}`);
|
|
215
|
+
const grants = validateScope(scope);
|
|
180
216
|
entry = {
|
|
181
217
|
pairingId: crypto.randomUUID(),
|
|
182
218
|
name: validateName(name),
|
|
183
219
|
homeCwd: validateHomeCwd(homeCwd),
|
|
184
|
-
scope:
|
|
220
|
+
scope: grants,
|
|
221
|
+
projectRoot: validateProjectRoot(projectRoot, grants),
|
|
222
|
+
pairedVia,
|
|
185
223
|
createdAt: t,
|
|
186
224
|
expiresAt: t + PENDING_TTL_MS,
|
|
187
225
|
};
|
|
@@ -226,10 +264,12 @@ function createServicePairings({ filePath, now } = {}) {
|
|
|
226
264
|
name: p.name,
|
|
227
265
|
homeCwd: p.homeCwd,
|
|
228
266
|
scope: [...p.scope],
|
|
267
|
+
projectRoot: typeof p.projectRoot === 'string' ? p.projectRoot : null,
|
|
229
268
|
pubKey: key,
|
|
230
269
|
relayClientId: relayId,
|
|
231
270
|
pairedAt: t,
|
|
232
271
|
lastSeenAt: t,
|
|
272
|
+
pairedVia: p.pairedVia === 'local' ? 'local' : 'window',
|
|
233
273
|
opened: [],
|
|
234
274
|
};
|
|
235
275
|
s.services.push(svc);
|
|
@@ -41,6 +41,7 @@ const USAGE = [
|
|
|
41
41
|
'usage:',
|
|
42
42
|
' claude-code-session-manager service pair --code <code> --name <name> --state-dir <dir> [--device <prefix>] [--timeout <seconds>]',
|
|
43
43
|
' claude-code-session-manager service mcp --state-dir <dir>',
|
|
44
|
+
' claude-code-session-manager service pair-local --state-dir <dir> --name <name> --home <cwd> --tools a,b,c [--project-root <dir>] [--timeout <seconds>]',
|
|
44
45
|
].join('\n');
|
|
45
46
|
|
|
46
47
|
/** Parses `--key value` / `--key=value` pairs. Returns { flags } or { error }. */
|
|
@@ -132,6 +133,100 @@ async function runPair(args, { stdout, stderr, clientFactory }) {
|
|
|
132
133
|
}
|
|
133
134
|
}
|
|
134
135
|
|
|
136
|
+
const NOT_RUNNING_MSG = 'session manager is not running (no admin-api.json)';
|
|
137
|
+
|
|
138
|
+
function errText(err) { return err && err.message ? err.message : String(err); }
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Pairs a same-machine service through the loopback admin API, no window step.
|
|
142
|
+
* @param {{ stateDir: string, name: string, homeCwd: string, tools: string[], projectRoot?: string, timeoutS?: number, fetchImpl?: Function, clientFactory?: Function, adminApiPath?: string }} opts
|
|
143
|
+
* @returns {Promise<{ ok: true, service: any } | { ok: false, error: string }>}
|
|
144
|
+
*/
|
|
145
|
+
async function pairLocal(opts) {
|
|
146
|
+
const { stateDir, name, homeCwd, tools, projectRoot, timeoutS = DEFAULT_PAIR_TIMEOUT_S } = opts || {};
|
|
147
|
+
const fetchImpl = (opts && opts.fetchImpl) || globalThis.fetch;
|
|
148
|
+
const clientFactory = (opts && opts.clientFactory) || defaultClientFactory;
|
|
149
|
+
let admin;
|
|
150
|
+
try {
|
|
151
|
+
const adminApiPath = (opts && opts.adminApiPath) || require('../scheduler/schedulerPaths.cjs').adminTokenPath();
|
|
152
|
+
admin = require('../util/atomicFs.cjs').readJsonOrSync(adminApiPath, null);
|
|
153
|
+
} catch { return { ok: false, error: NOT_RUNNING_MSG }; }
|
|
154
|
+
if (!admin || !admin.port || !admin.token) return { ok: false, error: NOT_RUNNING_MSG };
|
|
155
|
+
const base = `http://127.0.0.1:${admin.port}/admin/services/pair-local`;
|
|
156
|
+
|
|
157
|
+
const post = async (url, body) => {
|
|
158
|
+
let res;
|
|
159
|
+
try {
|
|
160
|
+
res = await fetchImpl(url, {
|
|
161
|
+
method: 'POST',
|
|
162
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${admin.token}` },
|
|
163
|
+
body: JSON.stringify(body),
|
|
164
|
+
});
|
|
165
|
+
} catch (err) { return { ok: false, error: `admin api unreachable: ${errText(err)}` }; }
|
|
166
|
+
let json = null;
|
|
167
|
+
try { json = await res.json(); } catch { /* non-JSON */ }
|
|
168
|
+
if (!res.ok || !json || json.ok === false) return { ok: false, error: (json && json.error) || `admin api HTTP ${res.status}` };
|
|
169
|
+
return json;
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
let client;
|
|
173
|
+
let timer = null;
|
|
174
|
+
try {
|
|
175
|
+
const startBody = { name, homeCwd, tools };
|
|
176
|
+
if (projectRoot) startBody.projectRoot = projectRoot;
|
|
177
|
+
const started = await post(base, startBody);
|
|
178
|
+
if (!started.ok) return { ok: false, error: started.error };
|
|
179
|
+
|
|
180
|
+
let rejectConfirm;
|
|
181
|
+
const confirmFailed = new Promise((_, rej) => { rejectConfirm = rej; });
|
|
182
|
+
confirmFailed.catch(() => {});
|
|
183
|
+
let confirmP = null;
|
|
184
|
+
const onSas = (sas) => {
|
|
185
|
+
if (confirmP || !sas) return;
|
|
186
|
+
confirmP = post(`${base}/confirm`, { pairingId: started.pairingId, sas: String(sas).replace(/\D/g, '') });
|
|
187
|
+
confirmP.then((r) => { if (!r.ok) rejectConfirm(new Error(r.error)); });
|
|
188
|
+
};
|
|
189
|
+
client = clientFactory({ stateDir, onSas });
|
|
190
|
+
await client.pair({ code: started.code, name });
|
|
191
|
+
const timeout = new Promise((_, reject) => {
|
|
192
|
+
timer = setTimeout(() => reject(new Error(`timed out after ${timeoutS} s waiting for pairing to confirm`)), timeoutS * 1000);
|
|
193
|
+
});
|
|
194
|
+
const res = await Promise.race([client.connect(), confirmFailed, timeout]);
|
|
195
|
+
if (res && res.sas) onSas(res.sas);
|
|
196
|
+
const confirmed = confirmP ? await confirmP : { ok: false, error: 'no SAS was derived' };
|
|
197
|
+
if (!confirmed.ok) return { ok: false, error: confirmed.error };
|
|
198
|
+
return { ok: true, service: confirmed.service };
|
|
199
|
+
} catch (err) {
|
|
200
|
+
return { ok: false, error: errText(err) };
|
|
201
|
+
} finally {
|
|
202
|
+
clearTimeout(timer);
|
|
203
|
+
try { if (client) client.close(); } catch { /* best-effort */ }
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function runPairLocal(args, { stdout, stderr, clientFactory, fetchImpl, adminApiPath }) {
|
|
208
|
+
const parsed = parseFlags(args, ['state-dir', 'name', 'home', 'tools', 'project-root', 'timeout']);
|
|
209
|
+
if (parsed.error) { line(stderr, `${parsed.error}\n${USAGE}`); return EXIT_USAGE; }
|
|
210
|
+
const { flags } = parsed;
|
|
211
|
+
for (const k of ['state-dir', 'name', 'home', 'tools']) {
|
|
212
|
+
if (!flags[k]) { line(stderr, `missing --${k}\n${USAGE}`); return EXIT_USAGE; }
|
|
213
|
+
}
|
|
214
|
+
const tools = flags.tools.split(',').map((t) => t.trim()).filter(Boolean);
|
|
215
|
+
if (!tools.length) { line(stderr, `missing --tools\n${USAGE}`); return EXIT_USAGE; }
|
|
216
|
+
let timeoutS = DEFAULT_PAIR_TIMEOUT_S;
|
|
217
|
+
if (flags.timeout !== undefined) {
|
|
218
|
+
timeoutS = Number(flags.timeout);
|
|
219
|
+
if (!Number.isFinite(timeoutS) || timeoutS <= 0) { line(stderr, `--timeout must be a positive number of seconds\n${USAGE}`); return EXIT_USAGE; }
|
|
220
|
+
}
|
|
221
|
+
const r = await pairLocal({
|
|
222
|
+
stateDir: flags['state-dir'], name: flags.name, homeCwd: flags.home, tools,
|
|
223
|
+
projectRoot: flags['project-root'], timeoutS, clientFactory, fetchImpl, adminApiPath,
|
|
224
|
+
});
|
|
225
|
+
if (!r.ok) { line(stderr, `service pair-local: ${r.error}`); return EXIT_FAIL; }
|
|
226
|
+
line(stdout, `Paired locally: ${flags.name}`);
|
|
227
|
+
return EXIT_OK;
|
|
228
|
+
}
|
|
229
|
+
|
|
135
230
|
function runMcp(args, { stdin, stdout, stderr, clientFactory }) {
|
|
136
231
|
const parsed = parseFlags(args, ['state-dir']);
|
|
137
232
|
if (parsed.error) { line(stderr, `${parsed.error}\n${USAGE}`); return Promise.resolve(EXIT_USAGE); }
|
|
@@ -279,12 +374,15 @@ async function runServiceCli(argv, io = {}) {
|
|
|
279
374
|
stdout: io.stdout || process.stdout,
|
|
280
375
|
stderr: io.stderr || process.stderr,
|
|
281
376
|
clientFactory: io.clientFactory || defaultClientFactory,
|
|
377
|
+
fetchImpl: io.fetchImpl,
|
|
378
|
+
adminApiPath: io.adminApiPath,
|
|
282
379
|
};
|
|
283
380
|
const [sub, ...rest] = Array.isArray(argv) ? argv : [];
|
|
284
381
|
if (sub === 'pair') return runPair(rest, deps);
|
|
382
|
+
if (sub === 'pair-local') return runPairLocal(rest, deps);
|
|
285
383
|
if (sub === 'mcp') return runMcp(rest, deps);
|
|
286
384
|
line(deps.stderr, sub ? `unknown service subcommand: ${sub}\n${USAGE}` : USAGE);
|
|
287
385
|
return EXIT_USAGE;
|
|
288
386
|
}
|
|
289
387
|
|
|
290
|
-
module.exports = { runServiceCli, USAGE, CONFIRM_HINT, REVOKED_MSG, EXIT_OK, EXIT_FAIL, EXIT_USAGE, EXIT_REVOKED };
|
|
388
|
+
module.exports = { runServiceCli, pairLocal, USAGE, CONFIRM_HINT, REVOKED_MSG, EXIT_OK, EXIT_FAIL, EXIT_USAGE, EXIT_REVOKED };
|
|
@@ -984,7 +984,7 @@ async function createWorktree({ kind, cwd, key, fromRef }) {
|
|
|
984
984
|
// since (and drop links main lost). Best-effort — never fails the reuse.
|
|
985
985
|
try {
|
|
986
986
|
const sync = await require('./worktreeDeps.cjs').syncNodeModulesLinks({ mainCwd: cwd, worktreeCwd: epicDir });
|
|
987
|
-
if (sync && (sync.added || sync.removed)) console.log(`[gitWorktree] synced dep links: +${sync.added} -${sync.removed} -> ${epicDir}`);
|
|
987
|
+
if (sync && (sync.added || sync.removed || sync.kept)) console.log(`[gitWorktree] synced dep links: +${sync.added} -${sync.removed} kept=${sync.kept} -> ${epicDir}`);
|
|
988
988
|
} catch (err) {
|
|
989
989
|
console.warn(`[gitWorktree] dep link sync failed for ${epicDir}: ${(err && err.message) || err}`);
|
|
990
990
|
}
|
|
@@ -374,7 +374,8 @@ async function linkDependencyDirs({ mainCwd, worktreeCwd, names = DEFAULT_DEP_DI
|
|
|
374
374
|
|
|
375
375
|
/**
|
|
376
376
|
* Refresh one worktree node_modules (`rel`) against the main checkout's: link entries main
|
|
377
|
-
* gained since the snapshot, unlink worktree links whose target
|
|
377
|
+
* gained since the snapshot, unlink dangling worktree links whose target lay inside main's
|
|
378
|
+
* `rel` (others are kept, counted in `counts.kept`). Skips unless the
|
|
378
379
|
* worktree folder is a real directory (a whole-folder symlink is left alone). Reads main
|
|
379
380
|
* only. Never throws.
|
|
380
381
|
*/
|
|
@@ -385,10 +386,13 @@ function syncModulesDir(mainCwd, worktreeCwd, rel, counts) {
|
|
|
385
386
|
if (st.isSymbolicLink() || !st.isDirectory()) return;
|
|
386
387
|
const src = path.join(mainCwd, rel);
|
|
387
388
|
if (isDir(src)) counts.added += linkMissingModulesEntries(src, dest, false);
|
|
389
|
+
const ownPrefix = path.resolve(src) + path.sep; // trailing sep: main/node_modules-x is not inside
|
|
388
390
|
for (const name of fs.readdirSync(dest)) {
|
|
389
391
|
const link = path.join(dest, name);
|
|
390
392
|
try {
|
|
391
393
|
if (!fs.lstatSync(link).isSymbolicLink() || fs.existsSync(link)) continue;
|
|
394
|
+
const target = path.resolve(dest, fs.readlinkSync(link));
|
|
395
|
+
if (!target.startsWith(ownPrefix)) { counts.kept++; continue; } // not linker-made: leave it
|
|
392
396
|
fs.unlinkSync(link); // removes the dangling link itself, never a target
|
|
393
397
|
counts.removed++;
|
|
394
398
|
} catch { /* best-effort per entry */ }
|
|
@@ -402,10 +406,12 @@ function syncModulesDir(mainCwd, worktreeCwd, rel, counts) {
|
|
|
402
406
|
* considers). pnpm projects are skipped (their worktree node_modules is a real install).
|
|
403
407
|
* No-op under SM_WORKTREE_DEP_LINK_DISABLE=1. Never throws.
|
|
404
408
|
* @param {{ mainCwd: string, worktreeCwd: string }} opts
|
|
405
|
-
*
|
|
409
|
+
* Only dangling links into the main checkout's matching node_modules (the linker's own) are
|
|
410
|
+
* removed; any other dangling link (e.g. a workspace package mid-build) is kept and counted.
|
|
411
|
+
* @returns {Promise<{ added: number, removed: number, kept: number }>}
|
|
406
412
|
*/
|
|
407
413
|
async function syncNodeModulesLinks({ mainCwd, worktreeCwd }) {
|
|
408
|
-
const counts = { added: 0, removed: 0 };
|
|
414
|
+
const counts = { added: 0, removed: 0, kept: 0 };
|
|
409
415
|
try {
|
|
410
416
|
if (process.env.SM_WORKTREE_DEP_LINK_DISABLE === '1') return counts;
|
|
411
417
|
if (!mainCwd || !worktreeCwd || isPnpmProject(mainCwd)) return counts;
|
|
@@ -190,6 +190,24 @@ const MCP_TOOL_CATALOG = [
|
|
|
190
190
|
},
|
|
191
191
|
notes: 'See /develop.',
|
|
192
192
|
},
|
|
193
|
+
{
|
|
194
|
+
name: 'scheduler_release_plan',
|
|
195
|
+
group: 'scheduler',
|
|
196
|
+
purpose: 'Release a plan held for independent review via the session-manager app admin API (POST /admin/scheduler/release-plan). '
|
|
197
|
+
+ 'Records the accepted finding count and one non-empty reason per rejected finding, then lets the plan\'s PRDs dispatch. '
|
|
198
|
+
+ 'A second call returns alreadyReleased. With rereview: true it instead asks for ONE more review after a block '
|
|
199
|
+
+ '(allowed only when the latest review has a block decision and the plan is at round 1; at most once per plan).',
|
|
200
|
+
summary: 'Release a reviewed plan, or request its single re-review.',
|
|
201
|
+
whenToUse: 'Use after reading the plan review: call once with accepted (count) and rejected [{ finding, reason }], or with rereview: true after a block.',
|
|
202
|
+
whenNotToUse: 'Not callable from inside a headless scheduled job (same refusal as scheduler_create_prds). Do not use to edit PRDs or to request a second re-review.',
|
|
203
|
+
exampleArgs: {
|
|
204
|
+
epicId: 'abc123',
|
|
205
|
+
validateSlug: 'validate-my-plan',
|
|
206
|
+
accepted: 2,
|
|
207
|
+
rejected: [{ finding: 'prd-3: add a failure-path test', reason: 'covered by the gate in prd-2' }],
|
|
208
|
+
},
|
|
209
|
+
notes: null,
|
|
210
|
+
},
|
|
193
211
|
{
|
|
194
212
|
name: 'scheduler_list_prds',
|
|
195
213
|
group: 'scheduler',
|
|
@@ -401,6 +419,25 @@ const MCP_TOOL_CATALOG = [
|
|
|
401
419
|
+ 'or release. A done reply that names a Session Manager version must carry release.commits (or it is '
|
|
402
420
|
+ 'refused): write `{version}`, never hand-type a version.',
|
|
403
421
|
},
|
|
422
|
+
{
|
|
423
|
+
name: 'service_pair_local',
|
|
424
|
+
group: 'feedback',
|
|
425
|
+
purpose: 'Pair a service that runs on THIS machine with Session Manager in one call, with no window step: '
|
|
426
|
+
+ 'the same pairing as `service pair-local`, through the loopback admin API. Returns the paired service (never its key).',
|
|
427
|
+
summary: 'Pair a same-machine service with Session Manager, no window step.',
|
|
428
|
+
whenToUse: 'Use when the human asked you to pair a service running on this same machine (for example Kiln). '
|
|
429
|
+
+ 'Give the absolute stateDir the service keeps its pairing in, a name, its homeCwd, and the tools it may call.',
|
|
430
|
+
whenNotToUse: 'Do not use for a service on another machine (that needs the window pairing). Web remote must be on or the '
|
|
431
|
+
+ 'call is refused. Refused inside a scheduled job and outside a Session Manager chat or terminal session. '
|
|
432
|
+
+ 'The pairing can be revoked in App Settings → Web remote.',
|
|
433
|
+
exampleArgs: {
|
|
434
|
+
stateDir: '/home/bilko/.local/state/kiln',
|
|
435
|
+
name: 'Kiln',
|
|
436
|
+
homeCwd: '/home/bilko/Projects/kiln',
|
|
437
|
+
tools: ['feedback_list_projects', 'feedback_open_session'],
|
|
438
|
+
},
|
|
439
|
+
notes: 'Result: { ok: true, service } or an error with the route\'s refusal text. Report only what was paired; the human revokes it in App Settings → Web remote.',
|
|
440
|
+
},
|
|
404
441
|
{
|
|
405
442
|
name: 'project_home_write',
|
|
406
443
|
group: 'project-home',
|
|
@@ -899,12 +936,12 @@ const MCP_TOOL_CATALOG = [
|
|
|
899
936
|
purpose: "Read-only list of one project's open Epics (sessions) via the session-manager app's admin API "
|
|
900
937
|
+ '(GET /admin/epics) — the same outside-facing records a script gets: each Epic\'s epicId, title, '
|
|
901
938
|
+ 'outside-facing state and PRD progress. Optionally filter by `state`. Results are paginated (default limit 50, '
|
|
902
|
-
+ 'max 200) — check `hasMore`/`total` before assuming you received every Epic; page further with `offset`.'
|
|
939
|
+
+ 'max 200) — check `hasMore`/`total` before assuming you received every Epic; page further with `offset`. '
|
|
940
|
+
+ 'Each record\'s source.startedBy is absent/null when a person pressed New Epic; otherwise a script started it, with its caller and fromEpicId.',
|
|
903
941
|
summary: 'List the open sessions of one project and what state each is in.',
|
|
904
942
|
whenToUse: 'Use to survey which Epics a project has open and which need input, review or approval, before '
|
|
905
943
|
+ 'reading one in full with epic_get.',
|
|
906
|
-
whenNotToUse: 'Do not use this to create, approve or change an Epic — it is read-only
|
|
907
|
-
+ 'ever created by a human pressing New Epic. Do not use it for PRD status; use scheduler_list_prds.',
|
|
944
|
+
whenNotToUse: 'Do not use this to create, approve or change an Epic — it is read-only. Do not use it for PRD status; use scheduler_list_prds.',
|
|
908
945
|
exampleArgs: { cwd: '/home/bilko/Projects/session-manager', state: 'needs_input' },
|
|
909
946
|
notes: 'A partial page carries a `note` naming how many Epics were returned out of `total`.',
|
|
910
947
|
},
|
|
@@ -913,7 +950,8 @@ const MCP_TOOL_CATALOG = [
|
|
|
913
950
|
group: 'epics',
|
|
914
951
|
purpose: "Read-only fetch of one Epic's outside-facing record via the session-manager app's admin API "
|
|
915
952
|
+ '(GET /admin/epic), looked up in project `cwd` by exactly one of `id` (the Epic id) or `externalRef` '
|
|
916
|
-
+ '(the reference it was opened with). Returns `{ ok: true, epic }`, or `{ ok: false, error: "not found" }`.'
|
|
953
|
+
+ '(the reference it was opened with). Returns `{ ok: true, epic }`, or `{ ok: false, error: "not found" }`. '
|
|
954
|
+
+ 'epic.source.startedBy is absent/null when a person pressed New Epic; otherwise a script started it, with its caller and fromEpicId.',
|
|
917
955
|
summary: 'Read one session by its id or by the outside reference it was opened with.',
|
|
918
956
|
whenToUse: 'Use after epic_list, or when you already hold an Epic id or external reference, to read that '
|
|
919
957
|
+ "one Epic's state and progress.",
|
|
@@ -1189,7 +1227,7 @@ const MCP_RECIPES = [
|
|
|
1189
1227
|
+ 'curl -s -X POST "http://127.0.0.1:$(jq -r .port ~/.claude/session-manager/admin-api.json)/admin/project-home/videos/run" '
|
|
1190
1228
|
+ '-H "Authorization: Bearer $(jq -r .token ~/.claude/session-manager/admin-api.json)" -H \'Content-Type: application/json\' '
|
|
1191
1229
|
+ '-d \'{"cwd":"/abs/project","kind":"Blog post","target":"https://example.com/blog/hello","externalRef":"hello"}\'. '
|
|
1192
|
-
+ 'Optional keys: length, style, character, voiceId, focus, reviewFirst. Success is { ok, entryId, epicId, slug, stage }; the same externalRef again answers { ok, existing: true, entryId, epicId } instead of a second run.',
|
|
1230
|
+
+ 'Optional keys: length, style, character, voiceId, focus, reviewFirst, and caller { pipeline, runId, step, attempt } (recorded on the Epic as source.startedBy.caller), e.g. "caller":{"pipeline":"blog-videos","runId":"run-42","step":"render","attempt":1}; a press from an SM chat records that chat\'s Epic automatically (fromEpicId). Success is { ok, entryId, epicId, slug, stage }; the same externalRef again answers { ok, existing: true, entryId, epicId } instead of a second run.',
|
|
1193
1231
|
'Read the outcome with GET /admin/project-home/videos/status?cwd=<encoded>&id=<entryId> (same bearer token): state is queued, running, awaiting_review, saved (files.index/meta/mp4/poster, absolute paths), season-complete or failed (reason).',
|
|
1194
1232
|
'409 already_building means a Demo Video job for this project is already pending or running — retry later; never loop tightly.',
|
|
1195
1233
|
'With Review first (reviewFirst: true) the run stops at awaiting_review: only the human approves or asks for changes in Project Home > Video, then the final video builds. A script just keeps reading the status.',
|
|
@@ -825,7 +825,24 @@ async function checkConfiguredMcpServer(request, options) {
|
|
|
825
825
|
const { home, check = checkMcpServer, timeoutMs, clientVersion } = options || {};
|
|
826
826
|
const target = await resolveMcpServerConfig(request, { home });
|
|
827
827
|
if (!target) return { ok: false, status: 'failed', error: 'server not found', checkedAt: Date.now() };
|
|
828
|
-
|
|
828
|
+
const result = await check(target.server, { timeoutMs, clientVersion, cwd: target.cwd });
|
|
829
|
+
const { source, name } = request;
|
|
830
|
+
if (typeof name === 'string' && typeof source === 'string') lastProbes.set(`${source}\u0000${name}`, { scope: source, name, result });
|
|
831
|
+
return result;
|
|
829
832
|
}
|
|
830
833
|
|
|
831
|
-
|
|
834
|
+
/** Last checkConfiguredMcpServer result per (scope, name), this process only. */
|
|
835
|
+
const lastProbes = new Map();
|
|
836
|
+
|
|
837
|
+
/** @returns {object | null} the last result for the server, or null if never checked. */
|
|
838
|
+
function lastProbe(scope, name) {
|
|
839
|
+
const hit = lastProbes.get(`${scope}\u0000${name}`);
|
|
840
|
+
return hit ? hit.result : null;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** @param {string} scope @returns {{ name: string, scope: string }[]} servers with a stored result in the scope. */
|
|
844
|
+
function probedServers(scope) {
|
|
845
|
+
return [...lastProbes.values()].filter((e) => e.scope === scope).map((e) => ({ name: e.name, scope: e.scope }));
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
module.exports = { checkMcpServer, resolveMcpServerConfig, checkConfiguredMcpServer, lastProbe, probedServers };
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* a malformed pack becomes an `{ dir, error }` entry, never a crash. No caching.
|
|
12
12
|
*/
|
|
13
13
|
const fs = require('fs');
|
|
14
|
+
const os = require('os');
|
|
14
15
|
const path = require('path');
|
|
15
16
|
const { z } = require('zod');
|
|
16
17
|
|
|
@@ -28,7 +29,8 @@ const PackManifestSchema = z.object({
|
|
|
28
29
|
/**
|
|
29
30
|
* @typedef {{ platform?: 'darwin'|'linux'|'win32' }} PackRequires
|
|
30
31
|
* @typedef {{ id: string, label: string, description: string, dir: string,
|
|
31
|
-
* pluginName: string, laws: string, requires: PackRequires
|
|
32
|
+
* pluginName: string, laws: string, requires: PackRequires, source: 'shipped'|'plugin',
|
|
33
|
+
* skills: string[] }} Pack
|
|
32
34
|
* @typedef {{ dir: string, error: string }} PackError
|
|
33
35
|
*/
|
|
34
36
|
|
|
@@ -75,15 +77,106 @@ function readPack(dir) {
|
|
|
75
77
|
pluginName,
|
|
76
78
|
laws,
|
|
77
79
|
requires: m.requires ? { ...m.requires } : {},
|
|
80
|
+
source: 'shipped',
|
|
81
|
+
skills: listSkillsIn(path.join(dir, 'skills'), pluginName),
|
|
78
82
|
};
|
|
79
83
|
}
|
|
80
84
|
|
|
85
|
+
/** Folder names under `skillsDir` holding a SKILL.md; prefixed `<prefix>:` when given. Never throws.
|
|
86
|
+
* @param {string} skillsDir @param {string} [prefix] @returns {string[]} */
|
|
87
|
+
function listSkillsIn(skillsDir, prefix) {
|
|
88
|
+
try {
|
|
89
|
+
return fs.readdirSync(skillsDir, { withFileTypes: true })
|
|
90
|
+
.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && fs.existsSync(path.join(skillsDir, e.name, 'SKILL.md')))
|
|
91
|
+
.map((e) => (prefix ? `${prefix}:${e.name}` : e.name))
|
|
92
|
+
.sort();
|
|
93
|
+
} catch { return []; }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Loose ~/.claude/skills folders: visible but not equippable (not in a pack).
|
|
97
|
+
* @param {{ home?: string }} [opts] @returns {string[]} */
|
|
98
|
+
function listUnpackedSkills({ home = os.homedir() } = {}) {
|
|
99
|
+
return listSkillsIn(path.join(home, '.claude', 'skills'));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @param {string} dir @param {string} id @returns {Pack} */
|
|
103
|
+
function readPluginPack(dir, id) {
|
|
104
|
+
const plugin = readJson(path.join(dir, '.claude-plugin', 'plugin.json'), '.claude-plugin/plugin.json');
|
|
105
|
+
if (!plugin || typeof plugin !== 'object' || Array.isArray(plugin)) throw new Error('.claude-plugin/plugin.json must be an object');
|
|
106
|
+
const pluginName = typeof plugin.name === 'string' && plugin.name ? plugin.name : id;
|
|
107
|
+
return {
|
|
108
|
+
id,
|
|
109
|
+
label: id,
|
|
110
|
+
description: typeof plugin.description === 'string' ? plugin.description : '',
|
|
111
|
+
dir,
|
|
112
|
+
pluginName,
|
|
113
|
+
laws: '',
|
|
114
|
+
requires: {},
|
|
115
|
+
source: 'plugin',
|
|
116
|
+
skills: listSkillsIn(path.join(dir, 'skills'), pluginName),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Installed Claude Code plugins from installed_plugins.json. Never throws.
|
|
121
|
+
* @param {string} file @returns {{ packs: Pack[], errors: PackError[] }} */
|
|
122
|
+
function listPluginPacks(file) {
|
|
123
|
+
/** @type {Pack[]} */ const packs = [];
|
|
124
|
+
/** @type {PackError[]} */ const errors = [];
|
|
125
|
+
let raw;
|
|
126
|
+
try { raw = fs.readFileSync(file, 'utf8'); } catch (e) {
|
|
127
|
+
if (/** @type {NodeJS.ErrnoException} */ (e).code !== 'ENOENT') errors.push({ dir: file, error: `cannot read installed_plugins.json: ${/** @type {Error} */ (e).message}` });
|
|
128
|
+
return { packs, errors };
|
|
129
|
+
}
|
|
130
|
+
let data;
|
|
131
|
+
try { data = JSON.parse(raw); } catch (e) {
|
|
132
|
+
errors.push({ dir: file, error: `installed_plugins.json is not valid JSON: ${/** @type {Error} */ (e).message}` });
|
|
133
|
+
return { packs, errors };
|
|
134
|
+
}
|
|
135
|
+
const plugins = data && typeof data === 'object' ? data.plugins : null;
|
|
136
|
+
if (!plugins || typeof plugins !== 'object' || Array.isArray(plugins)) {
|
|
137
|
+
errors.push({ dir: file, error: 'installed_plugins.json has no plugins object' });
|
|
138
|
+
return { packs, errors };
|
|
139
|
+
}
|
|
140
|
+
for (const [key, installs] of Object.entries(plugins)) {
|
|
141
|
+
const id = key.split('@')[0];
|
|
142
|
+
const list = Array.isArray(installs) ? installs : [];
|
|
143
|
+
const last = list[list.length - 1];
|
|
144
|
+
const installPath = last && typeof last.installPath === 'string' ? last.installPath : '';
|
|
145
|
+
if (!installPath) { errors.push({ dir: file, error: `plugin "${key}" has no installPath` }); continue; }
|
|
146
|
+
try {
|
|
147
|
+
if (!fs.statSync(installPath).isDirectory()) throw new Error('not a directory');
|
|
148
|
+
} catch { errors.push({ dir: installPath, error: `plugin "${key}" installPath is missing` }); continue; }
|
|
149
|
+
try { packs.push(readPluginPack(installPath, id)); } catch (e) {
|
|
150
|
+
errors.push({ dir: installPath, error: String((e && /** @type {Error} */ (e).message) || e) });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return { packs, errors };
|
|
154
|
+
}
|
|
155
|
+
|
|
81
156
|
/**
|
|
82
157
|
* List every pack under `packsDir`. Never throws.
|
|
83
|
-
*
|
|
158
|
+
* Installed plugins are added unless `packsDir` is given without `home`/`pluginsFile`
|
|
159
|
+
* (a fixture-only call must not read the real ~/.claude).
|
|
160
|
+
* @param {{ packsDir?: string, home?: string, pluginsFile?: string }} [opts]
|
|
84
161
|
* @returns {{ packs: Pack[], errors: PackError[] }}
|
|
85
162
|
*/
|
|
86
|
-
function listPacks({ packsDir
|
|
163
|
+
function listPacks({ packsDir, home, pluginsFile } = {}) {
|
|
164
|
+
const withPlugins = packsDir === undefined || home !== undefined || pluginsFile !== undefined;
|
|
165
|
+
const r = listShipped(packsDir === undefined ? bundledPacksDir() : packsDir);
|
|
166
|
+
if (!withPlugins) return r;
|
|
167
|
+
const file = pluginsFile || path.join(home || os.homedir(), '.claude', 'plugins', 'installed_plugins.json');
|
|
168
|
+
const pl = listPluginPacks(file);
|
|
169
|
+
for (const p of pl.packs) {
|
|
170
|
+
if (r.packs.some((x) => x.id === p.id)) r.errors.push({ dir: p.dir, error: `plugin id "${p.id}" collides with a shipped pack; shipped pack kept` });
|
|
171
|
+
else r.packs.push(p);
|
|
172
|
+
}
|
|
173
|
+
r.errors.push(...pl.errors);
|
|
174
|
+
r.packs.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
175
|
+
return r;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** @param {string} packsDir @returns {{ packs: Pack[], errors: PackError[] }} */
|
|
179
|
+
function listShipped(packsDir) {
|
|
87
180
|
/** @type {Pack[]} */ const packs = [];
|
|
88
181
|
/** @type {PackError[]} */ const errors = [];
|
|
89
182
|
const root = path.resolve(packsDir);
|
|
@@ -110,11 +203,11 @@ function listPacks({ packsDir = bundledPacksDir() } = {}) {
|
|
|
110
203
|
|
|
111
204
|
/**
|
|
112
205
|
* @param {string} id
|
|
113
|
-
* @param {{ packsDir?: string }} [opts]
|
|
206
|
+
* @param {{ packsDir?: string, home?: string, pluginsFile?: string }} [opts]
|
|
114
207
|
* @returns {Pack|null}
|
|
115
208
|
*/
|
|
116
209
|
function getPack(id, opts) {
|
|
117
210
|
return listPacks(opts).packs.find((p) => p.id === id) || null;
|
|
118
211
|
}
|
|
119
212
|
|
|
120
|
-
module.exports = { listPacks, getPack, bundledPacksDir, PACK_LAWS_CHAR_CAP };
|
|
213
|
+
module.exports = { listPacks, listUnpackedSkills, getPack, bundledPacksDir, PACK_LAWS_CHAR_CAP };
|