@llblab/pi-actors 0.22.5 → 0.24.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.
Files changed (180) hide show
  1. package/AGENTS.md +125 -59
  2. package/BACKLOG.md +88 -403
  3. package/CHANGELOG.md +39 -0
  4. package/README.md +14 -1
  5. package/dist/fixtures/protocol/actor-message-branch.json +13 -0
  6. package/dist/fixtures/protocol/artifact-manifest.json +9 -0
  7. package/dist/fixtures/protocol/mailbox-contract.json +15 -0
  8. package/dist/fixtures/protocol/recipe-summary.json +16 -0
  9. package/dist/fixtures/protocol/room-message.json +11 -0
  10. package/dist/fixtures/protocol/room-roster.json +11 -0
  11. package/dist/fixtures/protocol/run-inbox-message.json +9 -0
  12. package/dist/fixtures/protocol/run-outbox-event.json +9 -0
  13. package/dist/fixtures/protocol/run-state.json +10 -0
  14. package/dist/index.js +18 -2
  15. package/dist/lib/actor-inspector-tui.d.ts +4 -0
  16. package/dist/lib/actor-inspector-tui.js +58 -44
  17. package/dist/lib/actor-rooms.d.ts +16 -0
  18. package/dist/lib/actor-rooms.js +123 -28
  19. package/dist/lib/actor-worker.d.ts +13 -0
  20. package/dist/lib/actor-worker.js +86 -0
  21. package/dist/lib/async-runner.d.ts +5 -0
  22. package/dist/lib/async-runner.js +134 -0
  23. package/dist/lib/async-runs.d.ts +34 -2
  24. package/dist/lib/async-runs.js +224 -50
  25. package/dist/lib/build-dist.d.ts +5 -0
  26. package/dist/lib/build-dist.js +24 -0
  27. package/dist/lib/command-templates.js +5 -5
  28. package/dist/lib/conformance.d.ts +12 -0
  29. package/dist/lib/conformance.js +28 -0
  30. package/dist/lib/coordinator.d.ts +5 -0
  31. package/dist/lib/coordinator.js +557 -0
  32. package/dist/lib/limits.d.ts +11 -0
  33. package/dist/lib/limits.js +11 -0
  34. package/dist/lib/locker.d.ts +5 -0
  35. package/dist/lib/locker.js +310 -0
  36. package/dist/lib/mailbox-loop.d.ts +41 -0
  37. package/dist/lib/mailbox-loop.js +62 -0
  38. package/dist/lib/observability.d.ts +2 -2
  39. package/dist/lib/observability.js +57 -57
  40. package/dist/lib/output.js +4 -5
  41. package/dist/lib/prompts.d.ts +1 -1
  42. package/dist/lib/prompts.js +1 -1
  43. package/dist/lib/recipe-discovery.js +1 -0
  44. package/dist/lib/recipe-references.d.ts +11 -2
  45. package/dist/lib/recipe-references.js +29 -4
  46. package/dist/lib/recipe-usage.d.ts +2 -1
  47. package/dist/lib/recipe-usage.js +15 -3
  48. package/dist/lib/recipe-utils.d.ts +5 -0
  49. package/dist/lib/recipe-utils.js +385 -0
  50. package/dist/lib/runtime-notifier.js +3 -7
  51. package/dist/lib/runtime.js +12 -2
  52. package/dist/lib/state-readers.d.ts +21 -0
  53. package/dist/lib/state-readers.js +74 -0
  54. package/dist/lib/tools.js +198 -39
  55. package/dist/lib/validate-recipe.d.ts +6 -0
  56. package/dist/lib/validate-recipe.js +104 -0
  57. package/dist/recipes/actor-worker.json +35 -0
  58. package/dist/recipes/coordinator-locker.json +45 -0
  59. package/dist/recipes/lens-swarm.json +66 -0
  60. package/dist/recipes/locker.json +45 -0
  61. package/dist/recipes/music-player.json +38 -0
  62. package/dist/recipes/pipeline-architect-coordinator.json +95 -0
  63. package/dist/recipes/pipeline-artifact-bundle.json +100 -0
  64. package/dist/recipes/pipeline-artifact-report.json +58 -0
  65. package/dist/recipes/pipeline-artifact-write.json +72 -0
  66. package/dist/recipes/pipeline-async-run-ops.json +70 -0
  67. package/dist/recipes/pipeline-checkpoint-continuation.json +67 -0
  68. package/dist/recipes/pipeline-development-tasking.json +81 -0
  69. package/dist/recipes/pipeline-docs-maintenance.json +80 -0
  70. package/dist/recipes/pipeline-media-library.json +59 -0
  71. package/dist/recipes/pipeline-quorum-review.json +79 -0
  72. package/dist/recipes/pipeline-release-readiness.json +110 -0
  73. package/dist/recipes/pipeline-release-summary.json +88 -0
  74. package/dist/recipes/pipeline-repo-health.json +89 -0
  75. package/dist/recipes/pipeline-research-synthesis.json +94 -0
  76. package/dist/recipes/pipeline-review-readiness.json +54 -0
  77. package/dist/recipes/pipeline-room-swarm.json +50 -0
  78. package/dist/recipes/subagent-artifact.json +32 -0
  79. package/dist/recipes/subagent-checkpoint.json +33 -0
  80. package/dist/recipes/subagent-conflict-report.json +32 -0
  81. package/dist/recipes/subagent-contradiction-map.json +33 -0
  82. package/dist/recipes/subagent-critic.json +35 -0
  83. package/dist/recipes/subagent-evidence-map.json +33 -0
  84. package/dist/recipes/subagent-followup.json +33 -0
  85. package/dist/recipes/subagent-judge.json +33 -0
  86. package/dist/recipes/subagent-merge.json +33 -0
  87. package/dist/recipes/subagent-message.json +34 -0
  88. package/dist/recipes/subagent-normalize.json +31 -0
  89. package/dist/recipes/subagent-plan.json +33 -0
  90. package/dist/recipes/subagent-prompt.json +28 -0
  91. package/dist/recipes/subagent-quorum.json +43 -0
  92. package/dist/recipes/subagent-review-coordinator.json +114 -0
  93. package/dist/recipes/subagent-review.json +37 -0
  94. package/dist/recipes/subagent-task-card.json +35 -0
  95. package/dist/recipes/subagent-tools.json +27 -0
  96. package/dist/recipes/subagent-verify.json +34 -0
  97. package/dist/recipes/subagents-prompts.json +51 -0
  98. package/dist/recipes/utility-actor-message.json +23 -0
  99. package/dist/recipes/utility-artifact-manifest.json +16 -0
  100. package/dist/recipes/utility-artifact-write.json +16 -0
  101. package/dist/recipes/utility-changelog-head.json +11 -0
  102. package/dist/recipes/utility-changelog-section.json +13 -0
  103. package/dist/recipes/utility-coordinator-lock-snapshot.json +13 -0
  104. package/dist/recipes/utility-git-log.json +11 -0
  105. package/dist/recipes/utility-git-status.json +9 -0
  106. package/dist/recipes/utility-jsonl-tail.json +10 -0
  107. package/dist/recipes/utility-markdown-index.json +14 -0
  108. package/dist/recipes/utility-package-summary.json +11 -0
  109. package/dist/recipes/utility-playlist-build.json +17 -0
  110. package/dist/recipes/utility-playlist-scan.json +11 -0
  111. package/dist/recipes/utility-run-ops-snapshot.json +17 -0
  112. package/dist/recipes/utility-run-state-files.json +13 -0
  113. package/dist/recipes/utility-run-summary.json +11 -0
  114. package/dist/recipes/utility-skill-summary.json +13 -0
  115. package/dist/recipes/utility-validate-recipe.json +13 -0
  116. package/dist/recipes/utility-validation-wrapper.json +13 -0
  117. package/dist/scripts/actor-worker.mjs +31 -0
  118. package/dist/scripts/async-runner.mjs +31 -0
  119. package/dist/scripts/build-dist.mjs +25 -0
  120. package/dist/scripts/conformance.mjs +33 -0
  121. package/dist/scripts/coordinator.mjs +31 -0
  122. package/dist/scripts/locker.mjs +33 -0
  123. package/dist/scripts/music-player.mjs +964 -0
  124. package/dist/scripts/recipe-utils.mjs +31 -0
  125. package/dist/scripts/validate-recipe.mjs +34 -0
  126. package/dist/skills/actors/SKILL.md +375 -0
  127. package/dist/skills/swarm/SKILL.md +467 -0
  128. package/dist/skills/swarm/references/development-swarm.md +596 -0
  129. package/docs/actor-messages.md +2 -2
  130. package/docs/async-runs.md +13 -1
  131. package/docs/template-recipes.md +2 -2
  132. package/docs/tool-registry.md +0 -1
  133. package/fixtures/protocol/actor-message-branch.json +13 -0
  134. package/fixtures/protocol/artifact-manifest.json +9 -0
  135. package/fixtures/protocol/mailbox-contract.json +15 -0
  136. package/fixtures/protocol/recipe-summary.json +16 -0
  137. package/fixtures/protocol/room-message.json +11 -0
  138. package/fixtures/protocol/room-roster.json +11 -0
  139. package/fixtures/protocol/run-inbox-message.json +9 -0
  140. package/fixtures/protocol/run-outbox-event.json +9 -0
  141. package/fixtures/protocol/run-state.json +10 -0
  142. package/index.ts +21 -0
  143. package/lib/actor-inspector-tui.ts +138 -59
  144. package/lib/actor-rooms.ts +241 -60
  145. package/lib/actor-worker.ts +118 -0
  146. package/lib/async-runner.ts +173 -0
  147. package/lib/async-runs.ts +302 -53
  148. package/lib/build-dist.ts +30 -0
  149. package/lib/command-templates.ts +5 -5
  150. package/lib/conformance.ts +46 -0
  151. package/lib/coordinator.ts +649 -0
  152. package/lib/limits.ts +12 -0
  153. package/lib/locker.ts +340 -0
  154. package/lib/mailbox-loop.ts +148 -0
  155. package/lib/observability.ts +34 -23
  156. package/lib/output.ts +4 -6
  157. package/lib/prompts.ts +1 -1
  158. package/lib/recipe-discovery.ts +1 -0
  159. package/lib/recipe-references.ts +57 -6
  160. package/lib/recipe-usage.ts +31 -4
  161. package/lib/recipe-utils.ts +486 -0
  162. package/lib/runtime-notifier.ts +4 -6
  163. package/lib/runtime.ts +31 -7
  164. package/lib/state-readers.ts +93 -0
  165. package/lib/tools.ts +297 -58
  166. package/lib/validate-recipe.ts +110 -0
  167. package/package.json +11 -2
  168. package/recipes/actor-worker.json +35 -0
  169. package/recipes/pipeline-quorum-review.json +12 -7
  170. package/scripts/actor-worker.mjs +31 -0
  171. package/scripts/async-runner.mjs +11 -195
  172. package/scripts/build-dist.mjs +25 -0
  173. package/scripts/conformance.mjs +33 -0
  174. package/scripts/coordinator.mjs +19 -616
  175. package/scripts/locker.mjs +23 -322
  176. package/scripts/music-player.mjs +21 -2
  177. package/scripts/recipe-utils.mjs +20 -467
  178. package/scripts/validate-recipe.mjs +23 -113
  179. package/skills/actors/SKILL.md +7 -4
  180. package/skills/swarm/SKILL.md +3 -1
@@ -1,478 +1,31 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- appendFileSync,
4
- existsSync,
5
- mkdirSync,
6
- readFileSync,
7
- readdirSync,
8
- statSync,
9
- writeFileSync,
10
- } from "node:fs";
11
- import { dirname, extname, join, relative, resolve } from "node:path";
12
2
 
13
- function usage() {
14
- console.error(`Usage:
15
- recipe-utils.mjs run-summary <state-root>
16
- recipe-utils.mjs run-ops-snapshot <state-root> <run-id> [lines] [stale-minutes]
17
- recipe-utils.mjs playlist <source-dir> [extensions] [max-depth] [paths|m3u|inline]
18
- recipe-utils.mjs changelog-section <file> <version>
19
- recipe-utils.mjs artifact-manifest <artifact-path> <title> <status> [summary]
20
- recipe-utils.mjs artifact-write <artifact-path> [create|overwrite|append]
21
- recipe-utils.mjs actor-message <type> [to] [from] [summary] [metadata-json] [correlation-id] [reply-to]
22
- recipe-utils.mjs package-summary <package-json>
23
- recipe-utils.mjs skill-summary <skill-md> [package-json]`);
24
- }
25
-
26
- function fail(message) {
27
- console.error(message);
28
- process.exit(1);
29
- }
30
-
31
- const ADDRESS_PATTERN = /^[A-Za-z0-9_.-]+$/;
32
- const MESSAGE_TYPE_PATTERN = /^[A-Za-z][A-Za-z0-9_.:-]*$/;
33
- function assertToken(value, label) {
34
- const normalized = String(value ?? "").trim();
35
- if (!normalized) fail(`${label} is required`);
36
- if (!ADDRESS_PATTERN.test(normalized))
37
- fail(`${label} contains unsupported characters: ${value}`);
38
- return normalized;
39
- }
40
-
41
- function validateActorAddress(address, label) {
42
- const value = String(address ?? "").trim();
43
- if (value === "coordinator") return value;
44
- const separator = value.indexOf(":");
45
- if (separator < 0) fail(`${label} must include an actor kind: ${address}`);
46
- const kind = value.slice(0, separator);
47
- const rest = value.slice(separator + 1);
48
- if (kind === "branch") {
49
- const [run, branch, ...extra] = rest.split("/");
50
- if (extra.length > 0)
51
- fail(`${label} branch address has too many parts: ${address}`);
52
- return `branch:${assertToken(run, `${label} branch run`)}/${assertToken(branch, `${label} branch id`)}`;
53
- }
54
- if (["run", "session", "tool"].includes(kind))
55
- return `${kind}:${assertToken(rest, label)}`;
56
- fail(`${label} has unsupported actor kind: ${kind}`);
57
- }
58
-
59
- function validateMessageType(type) {
60
- const value = String(type ?? "").trim();
61
- if (!MESSAGE_TYPE_PATTERN.test(value))
62
- fail(`Invalid actor message type: ${type}`);
63
- return value;
64
- }
65
-
66
- function walkFiles(dir, maxDepth = 2, depth = 0, out = []) {
67
- if (depth > maxDepth || !existsSync(dir)) return out;
68
- for (const entry of readdirSync(dir)) {
69
- const path = join(dir, entry);
70
- const stat = statSync(path);
71
- if (stat.isDirectory()) walkFiles(path, maxDepth, depth + 1, out);
72
- else if (stat.isFile()) out.push(path);
73
- }
74
- return out;
75
- }
76
-
77
- function readJson(file) {
78
- if (!existsSync(file)) return undefined;
79
- try {
80
- return JSON.parse(readFileSync(file, "utf8"));
81
- } catch {
82
- return undefined;
83
- }
84
- }
85
-
86
- function getRunStatus(run, progress, result) {
87
- if (progress?.phase) return progress.phase;
88
- if (result?.code !== undefined) return result.code === 0 ? "done" : "failed";
89
- return run.status ?? "unknown";
90
- }
91
-
92
- function collectRunSummary(rootValue) {
93
- const root = resolve(
94
- rootValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"),
95
- );
96
- const files = walkFiles(root, 2).filter((file) => file.endsWith("/run.json"));
97
- const rows = [];
98
- for (const file of files) {
99
- const run = readJson(file);
100
- if (!run) {
101
- rows.push({
102
- run: relative(root, file),
103
- status: "invalid-json",
104
- recipe: "",
105
- updated: "",
106
- });
107
- continue;
108
- }
109
- const runDir = dirname(file);
110
- const progress = readJson(join(runDir, "progress.json"));
111
- const result = readJson(join(runDir, "result.json"));
112
- rows.push({
113
- run: run.run_id ?? run.run ?? relative(root, file).split("/")[0],
114
- status: getRunStatus(run, progress, result),
115
- recipe: run.recipe ?? run.recipe_file ?? "",
116
- updated:
117
- progress?.updatedAt ??
118
- result?.completedAt ??
119
- run.updated_at ??
120
- run.completed_at ??
121
- run.started_at ??
122
- "",
123
- });
124
- }
125
- rows.sort((a, b) =>
126
- `${a.status}:${a.run}`.localeCompare(`${b.status}:${b.run}`),
127
- );
128
- return rows;
129
- }
3
+ /**
4
+ * Recipe utility command bundle shim.
5
+ *
6
+ * Runtime logic lives in lib/recipe-utils.ts and is compiled to
7
+ * dist/lib/recipe-utils.js for installed JS-only packages.
8
+ */
130
9
 
131
- function runSummary(rootValue) {
132
- console.log(JSON.stringify(collectRunSummary(rootValue), null, 2));
133
- }
134
-
135
- function tailJsonl(fileValue, linesValue = "80") {
136
- const file = resolve(
137
- fileValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"),
138
- );
139
- if (!existsSync(file)) return [];
140
- const lines = Number.parseInt(linesValue, 10);
141
- const count = Number.isFinite(lines) && lines > 0 ? lines : 80;
142
- return readFileSync(file, "utf8")
143
- .trimEnd()
144
- .split("\n")
145
- .filter(Boolean)
146
- .slice(-count)
147
- .map((line) => {
148
- try {
149
- return JSON.parse(line);
150
- } catch {
151
- return { raw: line };
152
- }
153
- });
154
- }
155
-
156
- function runOpsSnapshot(
157
- rootValue,
158
- runIdValue = "music",
159
- linesValue = "80",
160
- staleMinutesValue = "60",
161
- ) {
162
- const runs = collectRunSummary(rootValue);
163
- const root = resolve(
164
- rootValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"),
165
- );
166
- const inspectedRun = String(runIdValue || "music");
167
- const messageFile = join(root, inspectedRun, "outbox.jsonl");
168
- const staleMs = Number(staleMinutesValue) * 60 * 1000;
169
- const now = Date.now();
170
- const recommendations = runs.flatMap((run) => {
171
- const updatedMs = Date.parse(run.updated || "");
172
- const stale =
173
- Number.isFinite(updatedMs) &&
174
- Number.isFinite(staleMs) &&
175
- now - updatedMs > staleMs;
176
- if (run.status === "running" && stale) {
177
- return [
178
- {
179
- run: run.run,
180
- reason: "running-stale",
181
- suggested_message: {
182
- to: `run:${run.run}`,
183
- type: "control.stop",
184
- body: "stop",
185
- },
186
- },
187
- ];
188
- }
189
- if (["failed", "exited", "killed"].includes(run.status)) {
190
- return [
191
- {
192
- run: run.run,
193
- reason: `terminal-${run.status}`,
194
- suggested_inspect: { target: `run:${run.run}`, view: "tail" },
195
- },
196
- ];
197
- }
198
- return [];
199
- });
200
- console.log(
201
- JSON.stringify(
202
- {
203
- runs,
204
- inspectedRun,
205
- messages: tailJsonl(messageFile, linesValue),
206
- recommendations,
207
- },
208
- null,
209
- 2,
210
- ),
211
- );
212
- }
213
-
214
- function playlist(
215
- sourceValue,
216
- extensionsValue = ".mp3,.ogg,.wav,.flac,.m4a",
217
- maxDepthValue = "2",
218
- outputMode = "paths",
219
- ) {
220
- const source = resolve(
221
- sourceValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"),
222
- );
223
- const maxDepth = Number.parseInt(maxDepthValue, 10);
224
- const extensions = new Set(
225
- extensionsValue
226
- .split(",")
227
- .map((item) => item.trim().toLowerCase())
228
- .filter(Boolean),
229
- );
230
- const files = walkFiles(source, Number.isFinite(maxDepth) ? maxDepth : 2)
231
- .filter((file) => extensions.has(extname(file).toLowerCase()))
232
- .sort((a, b) => a.localeCompare(b));
233
- if (outputMode === "m3u") console.log(["#EXTM3U", ...files].join("\n"));
234
- else if (outputMode === "inline") console.log(files.join("|"));
235
- else console.log(files.join("\n"));
236
- }
237
-
238
- function artifactManifest(
239
- pathValue,
240
- title = "Artifact",
241
- status = "draft",
242
- summary = "",
243
- ) {
244
- const path = resolve(
245
- pathValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"),
246
- );
247
- const exists = existsSync(path);
248
- const stat = exists ? statSync(path) : undefined;
249
- console.log(
250
- JSON.stringify(
251
- {
252
- title,
253
- status,
254
- path,
255
- exists,
256
- bytes: stat?.size ?? 0,
257
- modified: stat?.mtime?.toISOString?.() ?? null,
258
- summary,
259
- },
260
- null,
261
- 2,
262
- ),
263
- );
264
- }
10
+ import { existsSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ import { fileURLToPath, pathToFileURL } from "node:url";
265
13
 
266
- function artifactWrite(pathValue, mode = "create") {
267
- const path = resolve(
268
- pathValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"),
269
- );
270
- if (!["create", "overwrite", "append"].includes(mode)) {
271
- fail(`Invalid artifact write mode: ${mode}`);
272
- }
273
- if (mode === "create" && existsSync(path)) {
274
- fail(`Artifact already exists: ${path}`);
275
- }
276
- const content = readFileSync(0, "utf8");
277
- mkdirSync(dirname(path), { recursive: true });
278
- if (mode === "append") appendFileSync(path, content);
279
- else writeFileSync(path, content, "utf8");
280
- const stat = statSync(path);
281
- console.log(
282
- JSON.stringify({ path, mode, bytes: stat.size, written: true }, null, 2),
283
- );
14
+ function packageRoot() {
15
+ return dirname(dirname(fileURLToPath(import.meta.url)));
284
16
  }
285
17
 
286
- function actorMessage(
287
- type = "event",
288
- to = "coordinator",
289
- from = "run:{run_id}",
290
- summary = "",
291
- metadataValue = "",
292
- correlationId = "",
293
- replyTo = "",
294
- ) {
295
- const messageType = validateMessageType(type);
296
- const messageTo = validateActorAddress(to, "message.to");
297
- const messageFrom = validateActorAddress(from, "message.from");
298
- let metadata = {};
299
- if (metadataValue) {
300
- try {
301
- const parsed = JSON.parse(metadataValue);
302
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
303
- metadata = parsed;
304
- else fail("Actor message metadata must be a JSON object");
305
- } catch (error) {
306
- fail(`Invalid actor message metadata JSON: ${error.message}`);
307
- }
308
- }
309
- const bodyText = readFileSync(0, "utf8");
310
- const trimmed = bodyText.trim();
311
- let body = bodyText;
312
- if (trimmed) {
313
- try {
314
- body = JSON.parse(trimmed);
315
- } catch {
316
- body = bodyText;
317
- }
318
- }
319
- console.log(
320
- JSON.stringify(
321
- {
322
- to: messageTo,
323
- from: messageFrom,
324
- type: messageType,
325
- summary: summary || messageType,
326
- body,
327
- ...(correlationId ? { correlation_id: correlationId } : {}),
328
- ...(replyTo ? { reply_to: replyTo } : {}),
329
- metadata,
330
- },
331
- null,
332
- 2,
333
- ),
334
- );
18
+ function mainModulePath() {
19
+ const root = packageRoot();
20
+ const compiled = join(root, "dist", "lib", "recipe-utils.js");
21
+ return existsSync(compiled) ? compiled : join(root, "lib", "recipe-utils.ts");
335
22
  }
336
23
 
337
- function packageSummary(fileValue = "package.json") {
338
- const file = resolve(
339
- fileValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"),
340
- );
341
- const pkg = readJson(file);
342
- if (!pkg) fail(`Package JSON not found or invalid: ${fileValue}`);
343
- const scripts =
344
- pkg.scripts && typeof pkg.scripts === "object"
345
- ? Object.keys(pkg.scripts).sort()
346
- : [];
347
- const dependencies =
348
- pkg.dependencies && typeof pkg.dependencies === "object"
349
- ? Object.keys(pkg.dependencies).sort()
350
- : [];
351
- const devDependencies =
352
- pkg.devDependencies && typeof pkg.devDependencies === "object"
353
- ? Object.keys(pkg.devDependencies).sort()
354
- : [];
355
- console.log(
356
- JSON.stringify(
357
- {
358
- name: pkg.name ?? "",
359
- version: pkg.version ?? "",
360
- type: pkg.type ?? "",
361
- private: Boolean(pkg.private),
362
- packageManager: pkg.packageManager ?? "",
363
- files: Array.isArray(pkg.files) ? pkg.files : [],
364
- bin: pkg.bin ?? null,
365
- main: pkg.main ?? "",
366
- exports: pkg.exports ?? null,
367
- scripts,
368
- dependencyCount: dependencies.length,
369
- devDependencyCount: devDependencies.length,
370
- dependencies,
371
- devDependencies,
372
- },
373
- null,
374
- 2,
375
- ),
376
- );
377
- }
378
-
379
- function parseSkillFrontmatter(content) {
380
- const frontmatter = content.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? "";
381
- const fields = {};
382
- for (const line of frontmatter.split(/\r?\n/)) {
383
- const match = line.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);
384
- if (match) fields[match[1]] = match[2].trim();
385
- }
386
- return { frontmatter, fields };
387
- }
388
-
389
- function skillSummary(skillValue, packageValue = "package.json") {
390
- const skillFile = resolve(
391
- skillValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"),
392
- );
393
- const packageFile = resolve(
394
- packageValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"),
395
- );
396
- const content = readFileSync(skillFile, "utf8");
397
- const pkg = readJson(packageFile) ?? {};
398
- const { frontmatter, fields } = parseSkillFrontmatter(content);
399
- const scalarLines = frontmatter
400
- .split(/\r?\n/)
401
- .filter((line) => /^\w+:\s*\S/.test(line));
402
- const extraColonLines = scalarLines.filter(
403
- (line) => (line.match(/:/g) ?? []).length > 1,
404
- );
405
- const body = content.replace(/^---\n[\s\S]*?\n---\n?/, "");
406
- const version =
407
- fields.version ??
408
- frontmatter.match(/^\s+version:\s*([^\n]+)\s*$/m)?.[1]?.trim() ??
409
- "";
410
- console.log(
411
- JSON.stringify(
412
- {
413
- path: skillValue,
414
- name: fields.name ?? "",
415
- description: fields.description ?? "",
416
- version,
417
- packageVersion: pkg.version ?? "",
418
- versionMatchesPackage: version === pkg.version,
419
- frontmatterExtraColonLines: extraColonLines,
420
- bodyLineCount: body.split(/\r?\n/).length,
421
- headings: body.split(/\r?\n/).filter((line) => /^#{1,6}\s/.test(line)),
422
- },
423
- null,
424
- 2,
425
- ),
426
- );
427
- }
24
+ const { runRecipeUtils } = await import(pathToFileURL(mainModulePath()).href);
428
25
 
429
- function changelogSection(fileValue, version) {
430
- const file = resolve(fileValue);
431
- const lines = readFileSync(file, "utf8").split(/\r?\n/);
432
- const start = lines.findIndex(
433
- (line) => line.startsWith("## ") && line.includes(version),
434
- );
435
- if (start < 0) fail(`Version section not found: ${version}`);
436
- let end = lines.length;
437
- for (let index = start + 1; index < lines.length; index += 1) {
438
- if (lines[index].startsWith("## ")) {
439
- end = index;
440
- break;
441
- }
442
- }
443
- console.log(lines.slice(start, end).join("\n").trimEnd());
444
- }
445
-
446
- const [command, ...args] = process.argv.slice(2);
447
- if (!command) {
448
- usage();
26
+ try {
27
+ runRecipeUtils(process.argv.slice(2));
28
+ } catch (error) {
29
+ console.error(error instanceof Error ? error.message : String(error));
449
30
  process.exit(1);
450
31
  }
451
-
452
- if (command === "run-summary")
453
- runSummary(args[0] ?? "~/.pi/agent/tmp/pi-actors/runs");
454
- else if (command === "run-ops-snapshot")
455
- runOpsSnapshot(
456
- args[0] ?? "~/.pi/agent/tmp/pi-actors/runs",
457
- args[1] ?? "music",
458
- args[2],
459
- args[3],
460
- );
461
- else if (command === "playlist")
462
- playlist(args[0] ?? "~/Music", args[1], args[2], args[3]);
463
- else if (command === "changelog-section")
464
- changelogSection(args[0] ?? "CHANGELOG.md", args[1] ?? "Unreleased");
465
- else if (command === "artifact-manifest")
466
- artifactManifest(args[0] ?? "artifact.md", args[1], args[2], args[3]);
467
- else if (command === "artifact-write")
468
- artifactWrite(args[0] ?? "artifact.md", args[1] ?? "create");
469
- else if (command === "actor-message")
470
- actorMessage(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
471
- else if (command === "package-summary")
472
- packageSummary(args[0] ?? "package.json");
473
- else if (command === "skill-summary")
474
- skillSummary(args[0] ?? "skills/actors/SKILL.md", args[1] ?? "package.json");
475
- else {
476
- usage();
477
- fail(`Unknown command: ${command}`);
478
- }
@@ -1,124 +1,34 @@
1
1
  #!/usr/bin/env -S node --experimental-strip-types
2
- import { existsSync, readdirSync, statSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { dirname, join, resolve } from "node:path";
5
- import { fileURLToPath, pathToFileURL } from "node:url";
6
2
 
7
- function scriptFile() {
8
- return fileURLToPath(import.meta.url);
9
- }
3
+ /**
4
+ * Template recipe validator CLI shim.
5
+ *
6
+ * Runtime logic lives in lib/validate-recipe.ts and is compiled to
7
+ * dist/lib/validate-recipe.js for installed JS-only packages.
8
+ */
9
+
10
+ import { existsSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
13
 
11
14
  function packageRoot() {
12
- return dirname(dirname(scriptFile()));
15
+ return dirname(dirname(fileURLToPath(import.meta.url)));
13
16
  }
14
17
 
15
- function libModulePath(name) {
18
+ function mainModulePath() {
16
19
  const root = packageRoot();
17
- const compiled = join(root, "dist", "lib", `${name}.js`);
18
- return existsSync(compiled) ? compiled : join(root, "lib", `${name}.ts`);
19
- }
20
-
21
- const { readResolvedRecipeConfig } = await import(
22
- pathToFileURL(libModulePath("recipe-references")).href
23
- );
24
-
25
- function usage() {
26
- console.error(`Usage:
27
- validate-recipe.mjs <recipe-file-or-dir> [--all]
28
-
29
- Validates one template recipe file, or all *.json/*.md files in a directory when --all is set.`);
20
+ const compiled = join(root, "dist", "lib", "validate-recipe.js");
21
+ return existsSync(compiled) ? compiled : join(root, "lib", "validate-recipe.ts");
30
22
  }
31
23
 
32
- function expandPath(value) {
33
- return resolve(
34
- String(value).replace(/^~(?=\/|$)/, process.env.HOME ?? homedir()),
35
- );
36
- }
37
-
38
- function templateKind(template) {
39
- if (typeof template === "string") return "leaf";
40
- if (Array.isArray(template)) return "sequence";
41
- if (template && typeof template === "object") {
42
- if (typeof template.template === "string") return "leaf";
43
- if (Array.isArray(template.template))
44
- return template.parallel === true ? "parallel" : "sequence";
45
- if (template.parallel === true) return "parallel";
46
- return "object";
47
- }
48
- return "unknown";
49
- }
50
-
51
- function recipeFiles(target, all) {
52
- if (!existsSync(target)) throw new Error(`Recipe path not found: ${target}`);
53
- const stat = statSync(target);
54
- if (stat.isFile()) return [target];
55
- if (!stat.isDirectory())
56
- throw new Error(`Recipe path is not a file or directory: ${target}`);
57
- if (!all) throw new Error("Directory validation requires --all.");
58
- return readdirSync(target)
59
- .filter((file) => file.endsWith(".json") || file.endsWith(".md"))
60
- .sort((a, b) => a.localeCompare(b))
61
- .map((file) => resolve(target, file));
62
- }
63
-
64
- function validateFile(file) {
65
- try {
66
- const config = readResolvedRecipeConfig(file);
67
- if (!config?.template)
68
- throw new Error("Recipe must define a non-empty template.");
69
- return {
70
- file,
71
- ok: true,
72
- name: config.name ?? "",
73
- async: Boolean(config.async),
74
- args: Array.isArray(config.args) ? config.args : [],
75
- defaults:
76
- config.defaults && typeof config.defaults === "object"
77
- ? Object.keys(config.defaults).sort()
78
- : [],
79
- imports:
80
- config.imports && typeof config.imports === "object"
81
- ? Object.keys(config.imports).sort()
82
- : [],
83
- mailbox:
84
- config.mailbox && typeof config.mailbox === "object"
85
- ? {
86
- accepts: Array.isArray(config.mailbox.accepts)
87
- ? config.mailbox.accepts
88
- : [],
89
- emits: Array.isArray(config.mailbox.emits)
90
- ? config.mailbox.emits
91
- : [],
92
- }
93
- : undefined,
94
- template: templateKind(config.template),
95
- };
96
- } catch (error) {
97
- return {
98
- file,
99
- ok: false,
100
- error: error instanceof Error ? error.message : String(error),
101
- };
102
- }
103
- }
24
+ const { validateRecipes } = await import(pathToFileURL(mainModulePath()).href);
104
25
 
105
- const args = process.argv.slice(2);
106
- const targetArg = args.find((arg) => !arg.startsWith("-"));
107
- const all = args.includes("--all");
108
- if (!targetArg || args.includes("--help") || args.includes("-h")) {
109
- usage();
110
- process.exit(targetArg ? 0 : 1);
26
+ try {
27
+ const report = validateRecipes(process.argv.slice(2));
28
+ if (report.help) console.error(report.usage);
29
+ else console.log(JSON.stringify(report, null, 2));
30
+ process.exit(report.ok ? 0 : 1);
31
+ } catch (error) {
32
+ console.error(error instanceof Error ? error.message : String(error));
33
+ process.exit(1);
111
34
  }
112
-
113
- const files = recipeFiles(expandPath(targetArg), all);
114
- const results = files.map(validateFile);
115
- const failed = results.filter((result) => !result.ok).length;
116
- const report = {
117
- ok: failed === 0,
118
- total: results.length,
119
- passed: results.length - failed,
120
- failed,
121
- results,
122
- };
123
- console.log(JSON.stringify(report, null, 2));
124
- process.exit(report.ok ? 0 : 1);