@moda-ai/cli 1.55.10 → 1.55.12
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/dist/agent-rd9deae9.js +459 -0
- package/dist/cli-09rr5smg.js +30 -0
- package/dist/cli-34zdvcpg.js +811 -0
- package/dist/cli-4qe6n8am.js +345 -0
- package/dist/cli-4x9w6ey7.js +70 -0
- package/dist/{cli-d3c95kks.js → cli-90hb4ng0.js} +18 -1733
- package/dist/cli-97fnztpy.js +140 -0
- package/dist/{cli-7s48d6ty.js → cli-bfmn3bsk.js} +2 -2
- package/dist/cli-k7vwt56h.js +496 -0
- package/dist/{cli-0qnghzg4.js → cli-kwz900s4.js} +95 -85
- package/dist/{cli-v27q5dvh.js → cli-m0fa54ny.js} +189 -970
- package/dist/cli-ryd7nzke.js +159 -0
- package/dist/{cli-4f0p8erk.js → cli-ssqb8bfw.js} +5 -7
- package/dist/cli-y8gbbe9k.js +946 -0
- package/dist/cli.js +1461 -7021
- package/dist/doctor-8yb6r66e.js +23 -0
- package/dist/fix-bt5zn07e.js +1444 -0
- package/dist/{harness-0tnqw849.js → harness-9psndqtm.js} +7 -2
- package/dist/{harness-github-actions-wpkr7jjr.js → harness-github-actions-nph5t2s7.js} +7 -2
- package/dist/{index-jqexf7kn.js → index-qjaprhrv.js} +31 -20
- package/dist/production-intelligence-mg3qp2dg.js +1802 -0
- package/dist/profile-commands-2g5bjzj2.js +481 -0
- package/dist/prompt-source-mcp.js +7 -2
- package/dist/prompts-mzazn8ce.js +40 -0
- package/dist/{provision-5pkn25hh.js → provision-rm0yc08f.js} +7 -5
- package/dist/registry-mbz65bjy.js +1201 -0
- package/dist/skills-sagxq9sc.js +19 -0
- package/dist/sync-gkwexz68.js +54 -0
- package/package.json +6 -6
- package/skills/integration/index.json +2 -2
- package/skills/moda-cli/SKILL.md +10 -4
|
@@ -0,0 +1,946 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createCommandContext
|
|
3
|
+
} from "./cli-4x9w6ey7.js";
|
|
4
|
+
import {
|
|
5
|
+
assertFlags,
|
|
6
|
+
assertPositionals
|
|
7
|
+
} from "./cli-k7vwt56h.js";
|
|
8
|
+
import {
|
|
9
|
+
callControlAPI
|
|
10
|
+
} from "./cli-ryd7nzke.js";
|
|
11
|
+
import {
|
|
12
|
+
CliInputError,
|
|
13
|
+
recordApiRequest,
|
|
14
|
+
resolveApiKey,
|
|
15
|
+
resolveIngestUrl,
|
|
16
|
+
resolveTenantId
|
|
17
|
+
} from "./cli-kwz900s4.js";
|
|
18
|
+
import {
|
|
19
|
+
SKILL_SOURCE_HARNESS,
|
|
20
|
+
SKILL_SOURCE_INTEGRATION_BUNDLED,
|
|
21
|
+
claudeSkillToCursorRule,
|
|
22
|
+
detectAgents,
|
|
23
|
+
pruneManagedSkillPaths,
|
|
24
|
+
readSkillsManifest,
|
|
25
|
+
writeSkillsManifest
|
|
26
|
+
} from "./cli-ssfq84k5.js";
|
|
27
|
+
import {
|
|
28
|
+
__require
|
|
29
|
+
} from "./cli-0v6na3yp.js";
|
|
30
|
+
|
|
31
|
+
// src/skills.ts
|
|
32
|
+
import { execFileSync } from "node:child_process";
|
|
33
|
+
import { createHash } from "node:crypto";
|
|
34
|
+
import {
|
|
35
|
+
existsSync as existsSync2,
|
|
36
|
+
lstatSync,
|
|
37
|
+
mkdirSync as mkdirSync2,
|
|
38
|
+
readdirSync,
|
|
39
|
+
readFileSync as readFileSync2,
|
|
40
|
+
writeFileSync as writeFileSync2
|
|
41
|
+
} from "node:fs";
|
|
42
|
+
import { basename, dirname as dirname2, join as join2, relative } from "node:path";
|
|
43
|
+
|
|
44
|
+
// src/agents-md.ts
|
|
45
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
46
|
+
import { dirname, join } from "node:path";
|
|
47
|
+
var AGENTS_MD_FILENAME = "AGENTS.md";
|
|
48
|
+
var FIXES_BLOCK_BEGIN = "<!-- moda:fixes:begin -->";
|
|
49
|
+
var FIXES_BLOCK_END = "<!-- moda:fixes:end -->";
|
|
50
|
+
function renderFixesBlock() {
|
|
51
|
+
return [
|
|
52
|
+
FIXES_BLOCK_BEGIN,
|
|
53
|
+
"## Fixing production issues with Moda (managed block — edits inside are overwritten by moda-cli)",
|
|
54
|
+
"",
|
|
55
|
+
"Moda supplies the production evidence; you propose and make the fix yourself.",
|
|
56
|
+
"",
|
|
57
|
+
"- Find what to fix: `moda investigate` ranks tool failures, user frustrations,",
|
|
58
|
+
" and top Problems with evidence; `moda problems` ranks cross-signal Problems",
|
|
59
|
+
" by root cause; `moda failures` lists tool failures only.",
|
|
60
|
+
"- Read the evidence before editing: `moda problem <problem_id>` (dossier),",
|
|
61
|
+
" `moda problem <problem_id> --evidence` (attribution rationales and anchors),",
|
|
62
|
+
" `moda problem <problem_id> --traces` (affected traces),",
|
|
63
|
+
" `moda tool-failure-detail <tool_name>` (failing calls in context), and",
|
|
64
|
+
" `moda context <conversation_id>` (the messages around a turn; `--all` for",
|
|
65
|
+
" the whole trace).",
|
|
66
|
+
"- Propose the change in the code, prompt, tool definition, or skill that",
|
|
67
|
+
" causes the issue, and cite the Moda problem or trace ids it is based on",
|
|
68
|
+
" in the PR description.",
|
|
69
|
+
"- Prompts live in `.moda/prompts.yml` (version 2: `prompt_paths` globs plus",
|
|
70
|
+
" `sources:` mappings for prompts defined in code); after `moda prompts sync`,",
|
|
71
|
+
" pass `prompt: lock.prompts['<key>']` to createThinkTelemetry/createAI7Telemetry.",
|
|
72
|
+
"- After the fix ships, record it with",
|
|
73
|
+
" `moda problem-feedback <problem_id> --action=mark_fixed`; if the issue",
|
|
74
|
+
" is detected again, the Problem comes back.",
|
|
75
|
+
FIXES_BLOCK_END
|
|
76
|
+
].join(`
|
|
77
|
+
`);
|
|
78
|
+
}
|
|
79
|
+
function upsertManagedBlock(existing, block) {
|
|
80
|
+
if (existing === null) {
|
|
81
|
+
return `${block}
|
|
82
|
+
`;
|
|
83
|
+
}
|
|
84
|
+
const beginIdx = existing.indexOf(FIXES_BLOCK_BEGIN);
|
|
85
|
+
const endIdx = existing.indexOf(FIXES_BLOCK_END);
|
|
86
|
+
if (beginIdx !== -1 && endIdx !== -1 && endIdx >= beginIdx) {
|
|
87
|
+
const before = existing.slice(0, beginIdx);
|
|
88
|
+
const after = existing.slice(endIdx + FIXES_BLOCK_END.length);
|
|
89
|
+
return `${before}${block}${after}`;
|
|
90
|
+
}
|
|
91
|
+
const separator = existing === "" || existing.endsWith(`
|
|
92
|
+
|
|
93
|
+
`) ? "" : existing.endsWith(`
|
|
94
|
+
`) ? `
|
|
95
|
+
` : `
|
|
96
|
+
|
|
97
|
+
`;
|
|
98
|
+
return `${existing}${separator}${block}
|
|
99
|
+
`;
|
|
100
|
+
}
|
|
101
|
+
function writeFileIfChanged(filePath, content) {
|
|
102
|
+
try {
|
|
103
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
104
|
+
if (existsSync(filePath)) {
|
|
105
|
+
const current = readFileSync(filePath, "utf8");
|
|
106
|
+
if (current === content)
|
|
107
|
+
return "unchanged";
|
|
108
|
+
writeFileSync(filePath, content);
|
|
109
|
+
return "updated";
|
|
110
|
+
}
|
|
111
|
+
writeFileSync(filePath, content);
|
|
112
|
+
return "wrote";
|
|
113
|
+
} catch {
|
|
114
|
+
return "failed";
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function upsertFixesAgentsBlock(cwd) {
|
|
118
|
+
const filePath = join(cwd, AGENTS_MD_FILENAME);
|
|
119
|
+
let existing = null;
|
|
120
|
+
if (existsSync(filePath)) {
|
|
121
|
+
try {
|
|
122
|
+
existing = readFileSync(filePath, "utf8");
|
|
123
|
+
} catch {
|
|
124
|
+
return { path: AGENTS_MD_FILENAME, status: "failed" };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const next = upsertManagedBlock(existing, renderFixesBlock());
|
|
128
|
+
return { path: AGENTS_MD_FILENAME, status: writeFileIfChanged(filePath, next) };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// src/skills.ts
|
|
132
|
+
var SKILLS_REQUEST_TIMEOUT_MS = 15000;
|
|
133
|
+
var VALID_STATUSES = new Set(["approved", "proposed", "all"]);
|
|
134
|
+
var SKILL_PROPOSALS_MANIFEST_PATH = join2(".moda", "skill-proposals.yml");
|
|
135
|
+
async function fetchSkills(status) {
|
|
136
|
+
const apiKey = resolveApiKey();
|
|
137
|
+
if (!apiKey) {
|
|
138
|
+
throw new CliInputError("No Moda API key found. Run `moda init` first (or set MODA_API_KEY).");
|
|
139
|
+
}
|
|
140
|
+
const ingestUrl = resolveIngestUrl().replace(/\/$/, "");
|
|
141
|
+
const url = `${ingestUrl}/v1/skills?status=${encodeURIComponent(status)}`;
|
|
142
|
+
const controller = new AbortController;
|
|
143
|
+
const timeout = setTimeout(() => controller.abort(), SKILLS_REQUEST_TIMEOUT_MS);
|
|
144
|
+
let response;
|
|
145
|
+
try {
|
|
146
|
+
recordApiRequest();
|
|
147
|
+
response = await fetch(url, {
|
|
148
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
149
|
+
signal: controller.signal
|
|
150
|
+
});
|
|
151
|
+
} catch (err) {
|
|
152
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
153
|
+
throw new Error(`Network error: failed to reach ${ingestUrl} (${message})`);
|
|
154
|
+
} finally {
|
|
155
|
+
clearTimeout(timeout);
|
|
156
|
+
}
|
|
157
|
+
if (!response.ok) {
|
|
158
|
+
const body = await response.text().catch(() => "");
|
|
159
|
+
throw new Error(`Failed to fetch skills (HTTP ${response.status}): ${body.slice(0, 200)}`);
|
|
160
|
+
}
|
|
161
|
+
const data = await response.json();
|
|
162
|
+
if (!data.success) {
|
|
163
|
+
throw new Error(data.message || "Failed to fetch skills");
|
|
164
|
+
}
|
|
165
|
+
const skills = Array.isArray(data.skills) ? data.skills : [];
|
|
166
|
+
const release = data.release && typeof data.release === "object" ? data.release : null;
|
|
167
|
+
return {
|
|
168
|
+
skills,
|
|
169
|
+
tenantId: data.tenant_id || resolveTenantId() || "",
|
|
170
|
+
release,
|
|
171
|
+
releaseKey: releaseKeyFor(release, skills, status),
|
|
172
|
+
status
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
async function skillRunsRequest(url) {
|
|
176
|
+
const apiKey = resolveApiKey();
|
|
177
|
+
if (!apiKey) {
|
|
178
|
+
throw new CliInputError("No Moda API key found. Run `moda init` first (or set MODA_API_KEY).");
|
|
179
|
+
}
|
|
180
|
+
const controller = new AbortController;
|
|
181
|
+
const timeout = setTimeout(() => controller.abort(), SKILLS_REQUEST_TIMEOUT_MS);
|
|
182
|
+
let response;
|
|
183
|
+
try {
|
|
184
|
+
recordApiRequest();
|
|
185
|
+
response = await fetch(url, {
|
|
186
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
187
|
+
signal: controller.signal
|
|
188
|
+
});
|
|
189
|
+
} catch (err) {
|
|
190
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
191
|
+
throw new Error(`Network error: failed to reach ${url} (${message})`);
|
|
192
|
+
} finally {
|
|
193
|
+
clearTimeout(timeout);
|
|
194
|
+
}
|
|
195
|
+
const text = await response.text().catch(() => "");
|
|
196
|
+
if (!response.ok && response.status !== 404) {
|
|
197
|
+
throw new Error(`Failed to fetch run status (HTTP ${response.status}): ${text.slice(0, 200)}`);
|
|
198
|
+
}
|
|
199
|
+
let body = {};
|
|
200
|
+
try {
|
|
201
|
+
body = text ? JSON.parse(text) : {};
|
|
202
|
+
} catch {
|
|
203
|
+
body = {};
|
|
204
|
+
}
|
|
205
|
+
return { status: response.status, body };
|
|
206
|
+
}
|
|
207
|
+
async function fetchSkillRunStatus(runId) {
|
|
208
|
+
const ingestUrl = resolveIngestUrl().replace(/\/$/, "");
|
|
209
|
+
let resolvedRunId = runId;
|
|
210
|
+
if (!resolvedRunId) {
|
|
211
|
+
const list = await skillRunsRequest(`${ingestUrl}/v1/skills/runs?limit=1`);
|
|
212
|
+
const listBody = list.body;
|
|
213
|
+
const latest = Array.isArray(listBody.runs) ? listBody.runs[0] : undefined;
|
|
214
|
+
if (!latest)
|
|
215
|
+
return { run: null, events: [] };
|
|
216
|
+
resolvedRunId = latest.generation_run_id;
|
|
217
|
+
if (!resolvedRunId)
|
|
218
|
+
return { run: latest, events: [] };
|
|
219
|
+
}
|
|
220
|
+
const detail = await skillRunsRequest(`${ingestUrl}/v1/skills/runs/${encodeURIComponent(resolvedRunId)}`);
|
|
221
|
+
if (detail.status === 404) {
|
|
222
|
+
if (runId) {
|
|
223
|
+
throw new CliInputError(`No skill generation run found with id '${runId}'`);
|
|
224
|
+
}
|
|
225
|
+
return { run: null, events: [] };
|
|
226
|
+
}
|
|
227
|
+
const detailBody = detail.body;
|
|
228
|
+
return {
|
|
229
|
+
run: detailBody.run ?? null,
|
|
230
|
+
events: Array.isArray(detailBody.events) ? detailBody.events : []
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
var STATUS_HUMAN_EVENT_LIMIT = 10;
|
|
234
|
+
function formatRunStatusHuman(run, events) {
|
|
235
|
+
const counters = run.counters ?? {};
|
|
236
|
+
const lines = [
|
|
237
|
+
run.generation_run_id && `run: ${run.generation_run_id}`,
|
|
238
|
+
`status: ${run.status || "unknown"}`,
|
|
239
|
+
run.current_stage && `stage: ${run.current_stage}`,
|
|
240
|
+
run.outcome && `outcome: ${run.outcome}`,
|
|
241
|
+
`processed: ${Number(counters.sessions_processed ?? 0)}`,
|
|
242
|
+
`failed: ${Number(counters.sessions_failed ?? 0)}`,
|
|
243
|
+
Number(counters.distilled_skills_generated ?? 0) > 0 && `distilled: ${Number(counters.distilled_skills_generated ?? 0)}`,
|
|
244
|
+
Number(counters.skills_indexed ?? 0) > 0 && `indexed: ${Number(counters.skills_indexed ?? 0)}`,
|
|
245
|
+
(run.generated_skill_ids?.length ?? 0) > 0 && `skills: ${(run.generated_skill_ids ?? []).join(", ")}`,
|
|
246
|
+
run.error && `error: ${run.error}`,
|
|
247
|
+
run.started_at && `started: ${run.started_at}`,
|
|
248
|
+
run.updated_at && `updated: ${run.updated_at}`
|
|
249
|
+
].filter(Boolean);
|
|
250
|
+
if (events.length > 0) {
|
|
251
|
+
lines.push("recent events (newest first):");
|
|
252
|
+
for (const event of events.slice(0, STATUS_HUMAN_EVENT_LIMIT)) {
|
|
253
|
+
lines.push(` ${[event.created_at, event.level, event.stage, event.message].filter(Boolean).join(" ")}`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return lines.join(`
|
|
257
|
+
`);
|
|
258
|
+
}
|
|
259
|
+
function writeIfChanged(filePath, content) {
|
|
260
|
+
try {
|
|
261
|
+
mkdirSync2(dirname2(filePath), { recursive: true });
|
|
262
|
+
if (existsSync2(filePath)) {
|
|
263
|
+
const current = readFileSync2(filePath, "utf8");
|
|
264
|
+
if (current === content)
|
|
265
|
+
return "unchanged";
|
|
266
|
+
writeFileSync2(filePath, content);
|
|
267
|
+
return "updated";
|
|
268
|
+
}
|
|
269
|
+
writeFileSync2(filePath, content);
|
|
270
|
+
return "wrote";
|
|
271
|
+
} catch {
|
|
272
|
+
return "failed";
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
async function pullSkills(options = {}) {
|
|
276
|
+
const status = options.status ?? "approved";
|
|
277
|
+
const cwd = options.cwd ?? process.cwd();
|
|
278
|
+
const log = (msg) => {
|
|
279
|
+
if (!options.silent)
|
|
280
|
+
console.log(msg);
|
|
281
|
+
};
|
|
282
|
+
const fetched = await fetchSkills(status);
|
|
283
|
+
const { skills } = fetched;
|
|
284
|
+
const summary = {
|
|
285
|
+
total: skills.length,
|
|
286
|
+
pruned: 0,
|
|
287
|
+
wrote: 0,
|
|
288
|
+
updated: 0,
|
|
289
|
+
unchanged: 0,
|
|
290
|
+
failed: 0
|
|
291
|
+
};
|
|
292
|
+
if (skills.length === 0) {
|
|
293
|
+
log(" No skills to pull yet.");
|
|
294
|
+
return summary;
|
|
295
|
+
}
|
|
296
|
+
const previousManifest = readSkillsManifest(cwd);
|
|
297
|
+
const preservedIntegrationRecords = (previousManifest?.records ?? []).filter((record) => record.source === SKILL_SOURCE_INTEGRATION_BUNDLED);
|
|
298
|
+
if (previousManifest && previousManifest.managedPaths.length > 0 && previousManifest.releaseKey !== fetched.releaseKey) {
|
|
299
|
+
const integrationPaths = new Set(preservedIntegrationRecords.flatMap((record) => record.paths));
|
|
300
|
+
const harnessPaths = previousManifest.managedPaths.filter((path) => !integrationPaths.has(path));
|
|
301
|
+
if (harnessPaths.length > 0) {
|
|
302
|
+
summary.pruned = pruneManagedSkillPaths(cwd, harnessPaths, log);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const agents = detectAgents();
|
|
306
|
+
const writeCursor = agents.includes("Cursor") || existsSync2(join2(cwd, ".cursor"));
|
|
307
|
+
const records = [];
|
|
308
|
+
for (const skill of skills) {
|
|
309
|
+
if (!skill.skill_id || !skill.skill_md) {
|
|
310
|
+
summary.failed++;
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
const safeId = basename(skill.skill_id);
|
|
314
|
+
if (!safeId || !/^[A-Za-z0-9_-]+$/.test(safeId)) {
|
|
315
|
+
summary.failed++;
|
|
316
|
+
log(` skipped invalid skill_id: ${JSON.stringify(skill.skill_id).slice(0, 80)}`);
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
const claudePath = join2(cwd, ".claude", "skills", safeId, "SKILL.md");
|
|
320
|
+
const claudeStatus = writeIfChanged(claudePath, skill.skill_md);
|
|
321
|
+
const claudeRelativePath = `.claude/skills/${safeId}/SKILL.md`;
|
|
322
|
+
recordOutcome(summary, claudeStatus, log, claudeRelativePath);
|
|
323
|
+
const paths = [];
|
|
324
|
+
if (claudeStatus !== "failed")
|
|
325
|
+
paths.push(claudeRelativePath);
|
|
326
|
+
if (writeCursor) {
|
|
327
|
+
const cursorPath = join2(cwd, ".cursor", "rules", `${safeId}.mdc`);
|
|
328
|
+
const cursorStatus = writeIfChanged(cursorPath, claudeSkillToCursorRule(skill.skill_md));
|
|
329
|
+
const cursorRelativePath = `.cursor/rules/${safeId}.mdc`;
|
|
330
|
+
recordOutcome(summary, cursorStatus, log, cursorRelativePath);
|
|
331
|
+
if (cursorStatus !== "failed")
|
|
332
|
+
paths.push(cursorRelativePath);
|
|
333
|
+
}
|
|
334
|
+
if (paths.length > 0) {
|
|
335
|
+
records.push({
|
|
336
|
+
skillId: safeId,
|
|
337
|
+
contentHash: sha256(skill.skill_md),
|
|
338
|
+
source: SKILL_SOURCE_HARNESS,
|
|
339
|
+
paths
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
writeSkillsManifest(cwd, manifestHeaderFor(fetched), [...records, ...preservedIntegrationRecords]);
|
|
344
|
+
return summary;
|
|
345
|
+
}
|
|
346
|
+
function recordOutcome(summary, status, log, relativePath) {
|
|
347
|
+
switch (status) {
|
|
348
|
+
case "wrote":
|
|
349
|
+
summary.wrote++;
|
|
350
|
+
log(` wrote ${relativePath}`);
|
|
351
|
+
break;
|
|
352
|
+
case "updated":
|
|
353
|
+
summary.updated++;
|
|
354
|
+
log(` updated ${relativePath}`);
|
|
355
|
+
break;
|
|
356
|
+
case "unchanged":
|
|
357
|
+
summary.unchanged++;
|
|
358
|
+
break;
|
|
359
|
+
case "failed":
|
|
360
|
+
summary.failed++;
|
|
361
|
+
log(` failed ${relativePath}`);
|
|
362
|
+
break;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
var SKILLS_DIR = join2(".claude", "skills");
|
|
366
|
+
var SKILL_FILE = "SKILL.md";
|
|
367
|
+
var MAX_SKILL_WALK_DEPTH = 4;
|
|
368
|
+
async function runSkillSync(flags = {}, profileOptions = {}, options = {}) {
|
|
369
|
+
const cwd = options.cwd ?? process.cwd();
|
|
370
|
+
const dryRun = flags["dry-run"] === "true";
|
|
371
|
+
const agentsMd = dryRun ? undefined : upsertFixesAgentsBlock(cwd);
|
|
372
|
+
const skills = discoverLocalSkills(cwd);
|
|
373
|
+
if (skills.length === 0) {
|
|
374
|
+
return { synced: [], dryRun, ...agentsMd ? { agentsMd } : {} };
|
|
375
|
+
}
|
|
376
|
+
const sourceCommit = getGitCommit(cwd);
|
|
377
|
+
const response = await callControlAPI("/skills/sync", {
|
|
378
|
+
method: "POST",
|
|
379
|
+
body: JSON.stringify({
|
|
380
|
+
skills: skills.map((skill) => ({
|
|
381
|
+
key: skill.key,
|
|
382
|
+
name: skill.name,
|
|
383
|
+
description: skill.description,
|
|
384
|
+
skillMd: skill.skillMd,
|
|
385
|
+
sourcePath: skill.sourcePath,
|
|
386
|
+
contentHash: skill.contentHash,
|
|
387
|
+
sourceCommit
|
|
388
|
+
})),
|
|
389
|
+
sourceCommit,
|
|
390
|
+
dryRun
|
|
391
|
+
})
|
|
392
|
+
}, profileOptions);
|
|
393
|
+
return { synced: response.synced ?? [], dryRun, ...agentsMd ? { agentsMd } : {} };
|
|
394
|
+
}
|
|
395
|
+
function discoverLocalSkills(cwd) {
|
|
396
|
+
const skillsRoot = join2(cwd, SKILLS_DIR);
|
|
397
|
+
if (!existsSync2(skillsRoot))
|
|
398
|
+
return [];
|
|
399
|
+
const managed = new Set(managedSkillPaths(cwd));
|
|
400
|
+
const skills = [];
|
|
401
|
+
for (const absPath of walkSkillFiles(skillsRoot, 0)) {
|
|
402
|
+
const sourcePath = relative(cwd, absPath).replace(/\\/g, "/");
|
|
403
|
+
if (managed.has(sourcePath))
|
|
404
|
+
continue;
|
|
405
|
+
const key = basename(dirname2(absPath));
|
|
406
|
+
if (key === "moda-cli" || !/^[A-Za-z0-9_-]+$/.test(key))
|
|
407
|
+
continue;
|
|
408
|
+
let content;
|
|
409
|
+
try {
|
|
410
|
+
content = readFileSync2(absPath, "utf8");
|
|
411
|
+
} catch {
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
if (!content.trim())
|
|
415
|
+
continue;
|
|
416
|
+
const { name, description } = parseSkillFrontmatter(content, key);
|
|
417
|
+
skills.push({
|
|
418
|
+
key,
|
|
419
|
+
name,
|
|
420
|
+
description,
|
|
421
|
+
skillMd: content,
|
|
422
|
+
sourcePath,
|
|
423
|
+
contentHash: sha256(content)
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
return skills.sort((a, b) => a.key.localeCompare(b.key));
|
|
427
|
+
}
|
|
428
|
+
function managedSkillPaths(cwd) {
|
|
429
|
+
const manifest = readSkillsManifest(cwd);
|
|
430
|
+
if (!manifest)
|
|
431
|
+
return [];
|
|
432
|
+
return manifest.managedPaths.filter((path) => path.startsWith(".claude/skills/") && path.endsWith("/SKILL.md"));
|
|
433
|
+
}
|
|
434
|
+
function walkSkillFiles(dir, depth) {
|
|
435
|
+
if (depth > MAX_SKILL_WALK_DEPTH)
|
|
436
|
+
return [];
|
|
437
|
+
let entries;
|
|
438
|
+
try {
|
|
439
|
+
entries = readdirSync(dir);
|
|
440
|
+
} catch {
|
|
441
|
+
return [];
|
|
442
|
+
}
|
|
443
|
+
const files = [];
|
|
444
|
+
for (const entry of entries) {
|
|
445
|
+
const fullPath = join2(dir, entry);
|
|
446
|
+
let stat;
|
|
447
|
+
try {
|
|
448
|
+
stat = lstatSync(fullPath);
|
|
449
|
+
} catch {
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
if (stat.isSymbolicLink())
|
|
453
|
+
continue;
|
|
454
|
+
if (stat.isDirectory()) {
|
|
455
|
+
files.push(...walkSkillFiles(fullPath, depth + 1));
|
|
456
|
+
} else if (stat.isFile() && entry === SKILL_FILE) {
|
|
457
|
+
files.push(fullPath);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
return files;
|
|
461
|
+
}
|
|
462
|
+
function parseSkillFrontmatter(raw, fallbackKey) {
|
|
463
|
+
let name = fallbackKey;
|
|
464
|
+
let description;
|
|
465
|
+
if (raw.startsWith("---")) {
|
|
466
|
+
const end = raw.indexOf(`
|
|
467
|
+
---`, 3);
|
|
468
|
+
if (end !== -1) {
|
|
469
|
+
const frontmatter = raw.slice(3, end);
|
|
470
|
+
const nameMatch = frontmatter.match(/^name:\s*(.+)$/m);
|
|
471
|
+
const descMatch = frontmatter.match(/^description:\s*(.+)$/m);
|
|
472
|
+
if (nameMatch)
|
|
473
|
+
name = stripQuotes(nameMatch[1].trim()) || fallbackKey;
|
|
474
|
+
if (descMatch)
|
|
475
|
+
description = stripQuotes(descMatch[1].trim()) || undefined;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
return { name, description };
|
|
479
|
+
}
|
|
480
|
+
function stripQuotes(value) {
|
|
481
|
+
return value.replace(/^["']|["']$/g, "");
|
|
482
|
+
}
|
|
483
|
+
function getGitCommit(cwd) {
|
|
484
|
+
try {
|
|
485
|
+
return execFileSync("git", ["rev-parse", "HEAD"], {
|
|
486
|
+
cwd,
|
|
487
|
+
encoding: "utf8",
|
|
488
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
489
|
+
}).trim();
|
|
490
|
+
} catch {
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
async function fetchSkillProposals(flags, profileOptions = {}) {
|
|
495
|
+
const params = new URLSearchParams;
|
|
496
|
+
if (flags["generation-run-id"])
|
|
497
|
+
params.set("generationRunId", flags["generation-run-id"]);
|
|
498
|
+
const status = flags.status ?? "ready_for_pr";
|
|
499
|
+
if (status !== "all")
|
|
500
|
+
params.set("status", status);
|
|
501
|
+
if (flags["tenant-id"])
|
|
502
|
+
params.set("tenantId", flags["tenant-id"]);
|
|
503
|
+
const suffix = params.toString() ? `?${params.toString()}` : "";
|
|
504
|
+
const response = await callControlAPI(`/skills/proposals${suffix}`, { method: "GET" }, profileOptions);
|
|
505
|
+
return Array.isArray(response.proposals) ? response.proposals : [];
|
|
506
|
+
}
|
|
507
|
+
async function applySkillProposal(proposalId, flags, profileOptions = {}, options = {}) {
|
|
508
|
+
const cwd = options.cwd ?? process.cwd();
|
|
509
|
+
const params = new URLSearchParams;
|
|
510
|
+
if (flags["tenant-id"])
|
|
511
|
+
params.set("tenantId", flags["tenant-id"]);
|
|
512
|
+
const suffix = params.toString() ? `?${params.toString()}` : "";
|
|
513
|
+
const proposal = await callControlAPI(`/skills/proposals/${encodeURIComponent(proposalId)}${suffix}`, { method: "GET" }, profileOptions);
|
|
514
|
+
if (!proposal.skillMd?.trim()) {
|
|
515
|
+
throw new CliInputError(`Proposal ${proposalId} does not include SKILL.md content`);
|
|
516
|
+
}
|
|
517
|
+
const safeId = safeSkillId(proposal.skillId);
|
|
518
|
+
const relativePath = `.claude/skills/${safeId}/SKILL.md`;
|
|
519
|
+
const writeStatus = writeIfChanged(join2(cwd, relativePath), proposal.skillMd);
|
|
520
|
+
if (writeStatus === "failed") {
|
|
521
|
+
throw new Error(`Failed to write ${relativePath}`);
|
|
522
|
+
}
|
|
523
|
+
writeSkillProposalManifest(cwd, proposal, relativePath);
|
|
524
|
+
let acknowledged = true;
|
|
525
|
+
let ackError;
|
|
526
|
+
try {
|
|
527
|
+
await callControlAPI(`/skills/proposals/${encodeURIComponent(proposalId)}/mark-applied${suffix}`, {
|
|
528
|
+
method: "POST",
|
|
529
|
+
body: JSON.stringify({ appliedBy: "moda-cli" })
|
|
530
|
+
}, profileOptions);
|
|
531
|
+
} catch (err) {
|
|
532
|
+
acknowledged = false;
|
|
533
|
+
ackError = err instanceof Error ? err.message : String(err);
|
|
534
|
+
}
|
|
535
|
+
return {
|
|
536
|
+
proposalId,
|
|
537
|
+
skillId: proposal.skillId,
|
|
538
|
+
path: relativePath,
|
|
539
|
+
status: writeStatus,
|
|
540
|
+
acknowledged,
|
|
541
|
+
ackError
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
function safeSkillId(skillId) {
|
|
545
|
+
const safeId = basename(skillId || "");
|
|
546
|
+
if (!safeId || !/^[A-Za-z0-9_-]+$/.test(safeId)) {
|
|
547
|
+
throw new CliInputError(`Invalid skill_id in proposal: ${JSON.stringify(skillId).slice(0, 80)}`);
|
|
548
|
+
}
|
|
549
|
+
return safeId;
|
|
550
|
+
}
|
|
551
|
+
function writeSkillProposalManifest(cwd, proposal, relativePath) {
|
|
552
|
+
const manifestPath = join2(cwd, SKILL_PROPOSALS_MANIFEST_PATH);
|
|
553
|
+
mkdirSync2(dirname2(manifestPath), { recursive: true });
|
|
554
|
+
const existing = existsSync2(manifestPath) ? readFileSync2(manifestPath, "utf8") : `applied_proposals:
|
|
555
|
+
`;
|
|
556
|
+
const entry = [
|
|
557
|
+
` - proposal_id: "${escapeYamlString(proposal.proposalId)}"`,
|
|
558
|
+
` skill_id: "${escapeYamlString(proposal.skillId)}"`,
|
|
559
|
+
` skill_family_id: "${escapeYamlString(proposal.skillFamilyId)}"`,
|
|
560
|
+
` skill_version: ${Number(proposal.skillVersion || 0)}`,
|
|
561
|
+
` generation_run_id: "${escapeYamlString(proposal.generationRunId)}"`,
|
|
562
|
+
` clustering_run_id: "${escapeYamlString(proposal.clusteringRunId)}"`,
|
|
563
|
+
` topic_id: "${escapeYamlString(proposal.topicId)}"`,
|
|
564
|
+
` replay_set_id: "${escapeYamlString(proposal.replaySetId)}"`,
|
|
565
|
+
` delta_pass_rate: ${Number(proposal.deltaPassRate || 0)}`,
|
|
566
|
+
` path: "${escapeYamlString(relativePath)}"`,
|
|
567
|
+
` applied_at: "${new Date().toISOString()}"`
|
|
568
|
+
].join(`
|
|
569
|
+
`);
|
|
570
|
+
const prefix = existing.endsWith(`
|
|
571
|
+
`) ? existing : `${existing}
|
|
572
|
+
`;
|
|
573
|
+
writeFileSync2(manifestPath, `${prefix}${entry}
|
|
574
|
+
`);
|
|
575
|
+
}
|
|
576
|
+
function escapeYamlString(value) {
|
|
577
|
+
return String(value ?? "").replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
|
|
578
|
+
}
|
|
579
|
+
function formatProposalRate(value) {
|
|
580
|
+
return `${(Number(value || 0) * 100).toFixed(1)}%`;
|
|
581
|
+
}
|
|
582
|
+
var SKILLS_SUBCOMMAND_FLAGS = {
|
|
583
|
+
gen: [
|
|
584
|
+
"replay",
|
|
585
|
+
"source",
|
|
586
|
+
"wait",
|
|
587
|
+
"clustering-poll-seconds",
|
|
588
|
+
"clustering-run-id",
|
|
589
|
+
"clustering-timeout-seconds",
|
|
590
|
+
"end-at",
|
|
591
|
+
"eval-set-id",
|
|
592
|
+
"force-reprocess",
|
|
593
|
+
"harness-url",
|
|
594
|
+
"improve-candidates",
|
|
595
|
+
"improvement-rounds",
|
|
596
|
+
"lookback-hours",
|
|
597
|
+
"max-cluster-pct",
|
|
598
|
+
"max-sessions",
|
|
599
|
+
"max-traces",
|
|
600
|
+
"no-clustering",
|
|
601
|
+
"no-replay",
|
|
602
|
+
"replay-set-id",
|
|
603
|
+
"reprocess-segments",
|
|
604
|
+
"start-at",
|
|
605
|
+
"tenant-id",
|
|
606
|
+
"wait-for-completion"
|
|
607
|
+
],
|
|
608
|
+
status: ["run-id"],
|
|
609
|
+
pull: ["status"],
|
|
610
|
+
proposals: ["status", "generation-run-id", "tenant-id"],
|
|
611
|
+
proposal: ["proposal-id", "tenant-id"],
|
|
612
|
+
install: ["list"]
|
|
613
|
+
};
|
|
614
|
+
async function runSkillsCommand(input) {
|
|
615
|
+
const context = "output" in input ? input : createCommandContext({
|
|
616
|
+
command: input.command,
|
|
617
|
+
positional: input.positional,
|
|
618
|
+
positionals: input.positionals,
|
|
619
|
+
flags: input.flags
|
|
620
|
+
}, {
|
|
621
|
+
outputMode: input.flags.agent === "true" ? "agent" : input.flags.json === "true" ? "json" : "human"
|
|
622
|
+
});
|
|
623
|
+
const sub = context.positional;
|
|
624
|
+
const positionals = context.positionals ?? (sub ? [sub] : []);
|
|
625
|
+
const flags = context.flags;
|
|
626
|
+
if (sub && SKILLS_SUBCOMMAND_FLAGS[sub])
|
|
627
|
+
assertFlags(`skills ${sub}`, flags, SKILLS_SUBCOMMAND_FLAGS[sub]);
|
|
628
|
+
if (sub === "gen") {
|
|
629
|
+
const result = await generateSkills(flags);
|
|
630
|
+
if (context.outputMode !== "human") {
|
|
631
|
+
context.output.writeData(result, {
|
|
632
|
+
status: Number(result.sessions_failed ?? 0) > 0 ? "error" : "success"
|
|
633
|
+
});
|
|
634
|
+
} else if (result.accepted) {
|
|
635
|
+
console.log([
|
|
636
|
+
"accepted: true",
|
|
637
|
+
result.generation_run_id && `generation_run_id: ${result.generation_run_id}`,
|
|
638
|
+
result.message && `message: ${result.message}`,
|
|
639
|
+
result.generation_run_id && `follow progress: moda skills status ${result.generation_run_id}`
|
|
640
|
+
].filter(Boolean).join(`
|
|
641
|
+
`));
|
|
642
|
+
} else {
|
|
643
|
+
console.log([
|
|
644
|
+
`processed: ${result.sessions_processed ?? 0}`,
|
|
645
|
+
`failed: ${result.sessions_failed ?? 0}`,
|
|
646
|
+
`pending: ${result.sessions_pending ?? 0}`,
|
|
647
|
+
`pending_found: ${result.pending_sessions_found ?? 0}`,
|
|
648
|
+
`distilled: ${Number(result.cluster_result?.distilled_skills_generated ?? 0)}`,
|
|
649
|
+
`indexed: ${Number(result.cluster_result?.skills_indexed ?? 0)}`,
|
|
650
|
+
result.distillation_skipped && `distillation skipped: ${result.distillation_skip_reason || "unknown"}`
|
|
651
|
+
].filter(Boolean).join(`
|
|
652
|
+
`));
|
|
653
|
+
}
|
|
654
|
+
return Number(result.sessions_failed ?? 0) > 0 ? 1 : 0;
|
|
655
|
+
}
|
|
656
|
+
if (sub === "status") {
|
|
657
|
+
const runId = positionals[1] || flags["run-id"] || undefined;
|
|
658
|
+
const { run, events } = await fetchSkillRunStatus(runId);
|
|
659
|
+
if (context.outputMode !== "human") {
|
|
660
|
+
context.output.writeData({ run, events }, { status: run?.status === "failed" ? "error" : "success" });
|
|
661
|
+
} else if (!run) {
|
|
662
|
+
console.log("No skill generation runs found yet. Start one with `moda skills gen`.");
|
|
663
|
+
} else {
|
|
664
|
+
console.log(formatRunStatusHuman(run, events));
|
|
665
|
+
}
|
|
666
|
+
return run?.status === "failed" ? 1 : 0;
|
|
667
|
+
}
|
|
668
|
+
if (sub === "proposals" && positionals[1] === "list") {
|
|
669
|
+
const proposals = await fetchSkillProposals(flags, { profile: context.profile });
|
|
670
|
+
if (flags.json === "true") {
|
|
671
|
+
console.log(JSON.stringify({ proposals }));
|
|
672
|
+
} else if (proposals.length === 0) {
|
|
673
|
+
console.log("No skill proposals found.");
|
|
674
|
+
} else {
|
|
675
|
+
for (const proposal of proposals) {
|
|
676
|
+
console.log([
|
|
677
|
+
proposal.proposalId,
|
|
678
|
+
proposal.proposalStatus,
|
|
679
|
+
`${proposal.skillId}@v${proposal.skillVersion}`,
|
|
680
|
+
`delta=${formatProposalRate(proposal.deltaPassRate)}`,
|
|
681
|
+
`baseline=${formatProposalRate(proposal.baselinePassRate)}`,
|
|
682
|
+
`candidate=${formatProposalRate(proposal.candidatePassRate)}`,
|
|
683
|
+
proposal.name
|
|
684
|
+
].filter(Boolean).join("\t"));
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
return 0;
|
|
688
|
+
}
|
|
689
|
+
if (sub === "proposal" && positionals[1] === "apply") {
|
|
690
|
+
const proposalId = positionals[2] || flags["proposal-id"];
|
|
691
|
+
if (!proposalId) {
|
|
692
|
+
throw new CliInputError("A proposal id is required", "Usage: moda skills proposal apply <proposal-id>");
|
|
693
|
+
}
|
|
694
|
+
const result = await applySkillProposal(proposalId, flags, { profile: context.profile });
|
|
695
|
+
if (flags.json === "true") {
|
|
696
|
+
console.log(JSON.stringify(result));
|
|
697
|
+
} else {
|
|
698
|
+
console.log([
|
|
699
|
+
`${result.status} ${result.path}`,
|
|
700
|
+
result.acknowledged ? "acknowledged: true" : "acknowledged: false"
|
|
701
|
+
].join(`
|
|
702
|
+
`));
|
|
703
|
+
}
|
|
704
|
+
if (!result.acknowledged) {
|
|
705
|
+
console.error(`Warning: wrote ${result.path} but failed to acknowledge proposal ${proposalId} on the server` + (result.ackError ? ` (${result.ackError})` : "") + ". The proposal is still listed as ready — re-run `moda skills proposal apply` to acknowledge it.");
|
|
706
|
+
return 1;
|
|
707
|
+
}
|
|
708
|
+
return 0;
|
|
709
|
+
}
|
|
710
|
+
if (sub === "list" || sub === "show" || sub === "policy") {
|
|
711
|
+
return runSkillRegistryCommand(sub, positionals, flags, context);
|
|
712
|
+
}
|
|
713
|
+
if (sub === "sync") {
|
|
714
|
+
assertFlags("skills sync", flags, ["dry-run"]);
|
|
715
|
+
const result = await runSkillSync(flags, { profile: context.profile, env: context.env });
|
|
716
|
+
context.output.writeData({
|
|
717
|
+
synced: result.synced,
|
|
718
|
+
dryRun: result.dryRun,
|
|
719
|
+
...result.agentsMd ? { agentsMd: result.agentsMd } : {}
|
|
720
|
+
});
|
|
721
|
+
return 0;
|
|
722
|
+
}
|
|
723
|
+
if (sub === "install") {
|
|
724
|
+
return runSkillsInstall(context, positionals.slice(1));
|
|
725
|
+
}
|
|
726
|
+
if (sub !== "pull") {
|
|
727
|
+
throw new CliInputError(sub ? `Unknown skills subcommand '${sub}'` : "A skills subcommand is required", "Usage: moda skills gen [--source=all|sdk] [--max-sessions=N (default 200)] [--lookback-hours=N (default 720)] [--max-traces=N] [--improvement-rounds=1-3] [--start-at=ISO] [--end-at=ISO] [--replay] [--replay-set-id=ID] [--reprocess-segments] [--force-reprocess] [--wait] | moda skills status [run-id] | moda skills proposals list [--status=ready_for_pr] | moda skills proposal apply <proposal-id> | moda skills pull [--status=approved|proposed|all] | moda skills sync [--dry-run] | moda skills install [--list] <id...>");
|
|
728
|
+
}
|
|
729
|
+
const status = (flags.status ?? "approved").toLowerCase();
|
|
730
|
+
if (!VALID_STATUSES.has(status)) {
|
|
731
|
+
throw new CliInputError(`Invalid --status '${status}'`, `Must be one of: ${[...VALID_STATUSES].join(", ")}`);
|
|
732
|
+
}
|
|
733
|
+
const summary = await pullSkills({ status, silent: context.outputMode !== "human" });
|
|
734
|
+
const parts = [
|
|
735
|
+
summary.pruned && `${summary.pruned} pruned`,
|
|
736
|
+
summary.wrote && `${summary.wrote} written`,
|
|
737
|
+
summary.updated && `${summary.updated} updated`,
|
|
738
|
+
summary.unchanged && `${summary.unchanged} unchanged`,
|
|
739
|
+
summary.failed && `${summary.failed} failed`
|
|
740
|
+
].filter(Boolean);
|
|
741
|
+
if (context.outputMode === "human" && summary.total > 0) {
|
|
742
|
+
console.log(` Done — ${parts.join(", ") || "no changes"}`);
|
|
743
|
+
}
|
|
744
|
+
if (context.outputMode !== "human") {
|
|
745
|
+
context.output.writeData({ status, summary });
|
|
746
|
+
}
|
|
747
|
+
return summary.failed > 0 ? 1 : 0;
|
|
748
|
+
}
|
|
749
|
+
async function generateSkills(flags) {
|
|
750
|
+
const apiKey = resolveApiKey();
|
|
751
|
+
if (!apiKey) {
|
|
752
|
+
throw new CliInputError("No Moda API key found. Run `moda init` first (or set MODA_API_KEY).");
|
|
753
|
+
}
|
|
754
|
+
const tenantId = flags["tenant-id"] || resolveTenantId();
|
|
755
|
+
const directHarnessUrl = flags["harness-url"] || process.env.MODA_SKILL_HARNESS_URL;
|
|
756
|
+
if (directHarnessUrl && !tenantId) {
|
|
757
|
+
throw new CliInputError("No Moda tenant id found. Run `moda init` first (or set MODA_TENANT_ID / --tenant-id).");
|
|
758
|
+
}
|
|
759
|
+
const endpoint = directHarnessUrl ? `${directHarnessUrl.replace(/\/+$/, "")}/skills/generate` : `${resolveIngestUrl().replace(/\/+$/, "")}/v1/skills/generate`;
|
|
760
|
+
const waitForCompletion = flags.wait === "true" || flags["wait-for-completion"] === "true";
|
|
761
|
+
const forceReprocess = flags["force-reprocess"] === "true";
|
|
762
|
+
const source = normalizeSkillSource(flags.source);
|
|
763
|
+
if (source === "coding_agent") {
|
|
764
|
+
console.error("Note: --source=coding-agent is deprecated for skills gen (SDK-only). The run will find no coding-agent sessions; use --source=all or --source=sdk.");
|
|
765
|
+
}
|
|
766
|
+
const body = compactObject({
|
|
767
|
+
tenant_id: tenantId || undefined,
|
|
768
|
+
max_sessions: parseScopeInt(flags["max-sessions"], "max-sessions"),
|
|
769
|
+
lookback_hours: parseScopeInt(flags["lookback-hours"], "lookback-hours"),
|
|
770
|
+
start_at: flags["start-at"] || undefined,
|
|
771
|
+
end_at: flags["end-at"] || undefined,
|
|
772
|
+
clustering_run_id: flags["clustering-run-id"] || undefined,
|
|
773
|
+
replay_set_id: flags["replay-set-id"] || flags["eval-set-id"] || undefined,
|
|
774
|
+
run_clustering: flags["no-clustering"] !== "true",
|
|
775
|
+
source,
|
|
776
|
+
clustering_timeout_seconds: parsePositiveInt(flags["clustering-timeout-seconds"], 7200),
|
|
777
|
+
clustering_poll_seconds: parsePositiveInt(flags["clustering-poll-seconds"], 15),
|
|
778
|
+
max_cluster_pct: parseOptionalFloat(flags["max-cluster-pct"]),
|
|
779
|
+
reprocess_segments: flags["reprocess-segments"] === "true" || forceReprocess,
|
|
780
|
+
run_replay: flags.replay === "true" && flags["no-replay"] !== "true",
|
|
781
|
+
max_traces: parseScopeInt(flags["max-traces"], "max-traces"),
|
|
782
|
+
improve_candidates: flags["improve-candidates"] === "true",
|
|
783
|
+
improvement_rounds: parseScopeInt(flags["improvement-rounds"], "improvement-rounds", MAX_IMPROVEMENT_ROUNDS) ?? 2,
|
|
784
|
+
force_reprocess: forceReprocess,
|
|
785
|
+
wait_for_completion: waitForCompletion
|
|
786
|
+
});
|
|
787
|
+
const headers = {
|
|
788
|
+
Authorization: `Bearer ${apiKey}`,
|
|
789
|
+
"Content-Type": "application/json"
|
|
790
|
+
};
|
|
791
|
+
if (tenantId)
|
|
792
|
+
headers["X-Moda-Tenant-Id"] = tenantId;
|
|
793
|
+
recordApiRequest();
|
|
794
|
+
const response = await fetch(endpoint, {
|
|
795
|
+
method: "POST",
|
|
796
|
+
headers,
|
|
797
|
+
body: JSON.stringify(body)
|
|
798
|
+
});
|
|
799
|
+
if (!response.ok) {
|
|
800
|
+
const text = await response.text().catch(() => "");
|
|
801
|
+
throw new Error(`Failed to generate skills (HTTP ${response.status}): ${text.slice(0, 200)}`);
|
|
802
|
+
}
|
|
803
|
+
return await response.json();
|
|
804
|
+
}
|
|
805
|
+
var MAX_IMPROVEMENT_ROUNDS = 3;
|
|
806
|
+
function parseScopeInt(value, flag, max) {
|
|
807
|
+
if (value === undefined)
|
|
808
|
+
return;
|
|
809
|
+
const parsed = /^\d+$/.test(value.trim()) ? Number.parseInt(value, 10) : Number.NaN;
|
|
810
|
+
if (!Number.isFinite(parsed) || parsed < 1) {
|
|
811
|
+
throw new CliInputError(`--${flag}=${value} is not a positive integer, so nothing was sent.`, `0 would mean unlimited server-side; omit --${flag} for the server default, or pass a number of 1 or more.`);
|
|
812
|
+
}
|
|
813
|
+
if (max !== undefined && parsed > max) {
|
|
814
|
+
throw new CliInputError(`--${flag}=${value} is above the maximum of ${max}, so nothing was sent.`);
|
|
815
|
+
}
|
|
816
|
+
return parsed;
|
|
817
|
+
}
|
|
818
|
+
function parsePositiveInt(value, fallback) {
|
|
819
|
+
if (!value)
|
|
820
|
+
return fallback;
|
|
821
|
+
const parsed = Number.parseInt(value, 10);
|
|
822
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
|
|
823
|
+
}
|
|
824
|
+
function parseOptionalFloat(value) {
|
|
825
|
+
if (!value)
|
|
826
|
+
return;
|
|
827
|
+
const parsed = Number.parseFloat(value);
|
|
828
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
829
|
+
}
|
|
830
|
+
function compactObject(input) {
|
|
831
|
+
return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined));
|
|
832
|
+
}
|
|
833
|
+
function normalizeSkillSource(value) {
|
|
834
|
+
const normalized = (value || "all").toLowerCase().replace(/-/g, "_");
|
|
835
|
+
if (["all", "sdk", "coding_agent"].includes(normalized))
|
|
836
|
+
return normalized;
|
|
837
|
+
return "all";
|
|
838
|
+
}
|
|
839
|
+
function releaseKeyFor(release, skills, status) {
|
|
840
|
+
if (release?.generation_run_id)
|
|
841
|
+
return `${status}:run:${release.generation_run_id}`;
|
|
842
|
+
if (Number(release?.generation_version || 0) > 0) {
|
|
843
|
+
return `${status}:version:${Number(release?.generation_version)}`;
|
|
844
|
+
}
|
|
845
|
+
return `${status}:legacy:${sha256(JSON.stringify(skills.map((skill) => ({
|
|
846
|
+
skill_id: skill.skill_id,
|
|
847
|
+
hash: sha256(skill.skill_md || "")
|
|
848
|
+
})).sort((a, b) => a.skill_id.localeCompare(b.skill_id))))}`;
|
|
849
|
+
}
|
|
850
|
+
function manifestHeaderFor(fetched) {
|
|
851
|
+
const release = fetched.release;
|
|
852
|
+
return {
|
|
853
|
+
tenantId: fetched.tenantId,
|
|
854
|
+
releaseKey: fetched.releaseKey,
|
|
855
|
+
statusFilter: fetched.status,
|
|
856
|
+
generationRunId: release?.generation_run_id || "",
|
|
857
|
+
generationVersion: Number(release?.generation_version || 0),
|
|
858
|
+
releasedAt: release?.released_at || ""
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
function sha256(input) {
|
|
862
|
+
return createHash("sha256").update(input).digest("hex");
|
|
863
|
+
}
|
|
864
|
+
async function runSkillsInstall(context, ids) {
|
|
865
|
+
const { installIntegrationSkill, readBundledIndex, readBundledSkillMd } = await import("./skills-bundled-mdmhzfsr.js");
|
|
866
|
+
const index = readBundledIndex();
|
|
867
|
+
if (context.flags.list === "true" || ids.length === 0) {
|
|
868
|
+
if (!index) {
|
|
869
|
+
throw new CliInputError("This CLI build has no bundled integration guides", "Install a published @moda-ai/cli, or run `bun run bundle:skills` in apps/moda-cli.");
|
|
870
|
+
}
|
|
871
|
+
const skills = index.skills.map((skill) => ({
|
|
872
|
+
id: skill.id,
|
|
873
|
+
version: skill.version,
|
|
874
|
+
language: skill.targets.language,
|
|
875
|
+
summary: skill.summary
|
|
876
|
+
}));
|
|
877
|
+
if (context.outputMode !== "human") {
|
|
878
|
+
context.output.writeData({ skills });
|
|
879
|
+
} else {
|
|
880
|
+
for (const skill of skills)
|
|
881
|
+
console.log(`${skill.id} ${skill.version} ${skill.summary}`);
|
|
882
|
+
if (ids.length === 0 && context.flags.list !== "true") {
|
|
883
|
+
console.error("Install one or more with: moda skills install <id...>");
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
return 0;
|
|
887
|
+
}
|
|
888
|
+
const unknown = ids.filter((id) => !/^[a-z0-9-]+$/.test(id) || readBundledSkillMd(id) === null);
|
|
889
|
+
if (unknown.length > 0) {
|
|
890
|
+
throw new CliInputError(`Not bundled with this CLI: ${unknown.map((id) => JSON.stringify(id).slice(0, 80)).join(", ")}`, "List the bundled guides with: moda skills install --list");
|
|
891
|
+
}
|
|
892
|
+
const results = [];
|
|
893
|
+
for (const id of ids) {
|
|
894
|
+
try {
|
|
895
|
+
results.push(installIntegrationSkill(id));
|
|
896
|
+
} catch (error) {
|
|
897
|
+
const done = results.map((result) => result.skillId);
|
|
898
|
+
throw new CliInputError(error instanceof Error ? error.message : String(error), done.length > 0 ? `Already installed before the failure: ${done.join(", ")}. Fix the error and rerun; installed guides are left as they are.` : "List the bundled guides with: moda skills install --list");
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
if (context.outputMode !== "human") {
|
|
902
|
+
context.output.writeData({ installed: results });
|
|
903
|
+
} else {
|
|
904
|
+
for (const result of results) {
|
|
905
|
+
console.log(`${result.status} ${result.skillId}`);
|
|
906
|
+
for (const path of result.paths)
|
|
907
|
+
console.log(` ${path}`);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
return 0;
|
|
911
|
+
}
|
|
912
|
+
var RESERVED_SKILL_PATHS = new Set(["inbox", "library", "observed", "runs", "sync", "surface", "families", "proposals"]);
|
|
913
|
+
async function runSkillRegistryCommand(sub, positionals, flags, context) {
|
|
914
|
+
const profileOptions = { profile: context.profile, env: context.env };
|
|
915
|
+
assertFlags(`skills ${sub}`, flags, sub === "policy" ? ["live", "local", "dry-run"] : []);
|
|
916
|
+
assertPositionals(`skills ${sub}`, positionals, sub === "list" ? 1 : 2, sub === "list" ? "moda skills list" : `moda skills ${sub} <key>${sub === "policy" ? " --live|--local" : ""}`);
|
|
917
|
+
if (sub === "list") {
|
|
918
|
+
context.output.writeData(await callControlAPI("/skills", {}, profileOptions));
|
|
919
|
+
return 0;
|
|
920
|
+
}
|
|
921
|
+
const idOrKey = positionals[1];
|
|
922
|
+
if (!idOrKey) {
|
|
923
|
+
throw new CliInputError(`A skill key or id is required for skills ${sub}.`, sub === "show" ? "Usage: moda skills show <key>" : "Usage: moda skills policy <key> --live|--local");
|
|
924
|
+
}
|
|
925
|
+
if (RESERVED_SKILL_PATHS.has(idOrKey)) {
|
|
926
|
+
throw new CliInputError(`'${idOrKey}' is a reserved path, so this skill must be addressed by its id.`, "Find the id (skill_…) with `moda skills list`, then pass that instead of the key.");
|
|
927
|
+
}
|
|
928
|
+
if (sub === "show") {
|
|
929
|
+
context.output.writeData(await callControlAPI(`/skills/${encodeURIComponent(idOrKey)}`, {}, profileOptions));
|
|
930
|
+
return 0;
|
|
931
|
+
}
|
|
932
|
+
const live = flags.live === "true";
|
|
933
|
+
const local = flags.local === "true";
|
|
934
|
+
if (live === local) {
|
|
935
|
+
throw new CliInputError("Pass exactly one of --live or --local.", "Usage: moda skills policy <key> --live|--local");
|
|
936
|
+
}
|
|
937
|
+
const surfacePolicy = live ? "include" : "local_only";
|
|
938
|
+
if (context.dryRun) {
|
|
939
|
+
context.output.writeData({ dryRun: true, planned: { method: "PATCH", endpoint: `/api/skills/${encodeURIComponent(idOrKey)}/surface-policy`, body: { surfacePolicy } } });
|
|
940
|
+
return 0;
|
|
941
|
+
}
|
|
942
|
+
context.output.writeData(await callControlAPI(`/skills/${encodeURIComponent(idOrKey)}/surface-policy`, { method: "PATCH", body: JSON.stringify({ surfacePolicy }) }, profileOptions, { retries: 0 }));
|
|
943
|
+
return 0;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
export { pullSkills, runSkillSync, runSkillsCommand, parseScopeInt };
|