@1agents/acp-service 0.9.0 → 0.10.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 (274) hide show
  1. package/README.md +19 -13
  2. package/dist/bin/a2a.js +6 -2
  3. package/dist/bin/acp-service.js +25 -1
  4. package/dist/bin/process.d.ts +4 -0
  5. package/dist/bin/process.js +57 -0
  6. package/dist/bin/roles.js +21 -18
  7. package/dist/bin/rsi.d.ts +3 -0
  8. package/dist/bin/rsi.js +114 -0
  9. package/dist/bin/ticket.d.ts +13 -0
  10. package/dist/bin/ticket.js +97 -0
  11. package/dist/bin/trail.d.ts +4 -0
  12. package/dist/bin/trail.js +62 -0
  13. package/dist/src/a2a/artifact-content.d.ts +9 -0
  14. package/dist/src/a2a/artifact-content.js +45 -0
  15. package/dist/src/a2a/desktop-notify.d.ts +1 -0
  16. package/dist/src/a2a/desktop-notify.js +12 -0
  17. package/dist/src/a2a/execution-binding.d.ts +9 -0
  18. package/dist/src/a2a/execution-binding.js +19 -0
  19. package/dist/src/a2a/executor.d.ts +7 -2
  20. package/dist/src/a2a/executor.js +127 -60
  21. package/dist/src/a2a/gateway.d.ts +581 -10
  22. package/dist/src/a2a/gateway.js +1018 -95
  23. package/dist/src/a2a/index.d.ts +8 -1
  24. package/dist/src/a2a/index.js +4 -0
  25. package/dist/src/a2a/job-directory.d.ts +6 -0
  26. package/dist/src/a2a/job-directory.js +19 -0
  27. package/dist/src/a2a/preflight.js +16 -1
  28. package/dist/src/a2a/resubmit.d.ts +46 -0
  29. package/dist/src/a2a/resubmit.js +82 -0
  30. package/dist/src/a2a/result-metadata.d.ts +3 -0
  31. package/dist/src/a2a/result-metadata.js +27 -5
  32. package/dist/src/a2a/server.d.ts +10 -0
  33. package/dist/src/a2a/server.js +125 -1
  34. package/dist/src/a2a/session-lifecycle.d.ts +40 -0
  35. package/dist/src/a2a/session-lifecycle.js +54 -0
  36. package/dist/src/a2a/store.d.ts +4 -0
  37. package/dist/src/a2a/store.js +70 -1
  38. package/dist/src/a2a/types.d.ts +46 -6
  39. package/dist/src/a2a/types.js +4 -6
  40. package/dist/src/a2a/workbench-ui.d.ts +28 -0
  41. package/dist/src/a2a/workbench-ui.js +182 -0
  42. package/dist/src/acp-connection.js +27 -3
  43. package/dist/src/bridge.d.ts +1 -0
  44. package/dist/src/bridge.js +191 -39
  45. package/dist/src/capacity-queue.d.ts +35 -0
  46. package/dist/src/capacity-queue.js +139 -2
  47. package/dist/src/capacity.d.ts +25 -0
  48. package/dist/src/capacity.js +48 -9
  49. package/dist/src/dsh.js +1 -1
  50. package/dist/src/execution/agent-files.d.ts +25 -0
  51. package/dist/src/execution/agent-files.js +90 -0
  52. package/dist/src/execution/agent-registry.d.ts +164 -0
  53. package/dist/src/execution/agent-registry.js +275 -0
  54. package/dist/src/execution/human-review.d.ts +2 -0
  55. package/dist/src/execution/human-review.js +3 -1
  56. package/dist/src/execution/ledger.d.ts +52 -0
  57. package/dist/src/execution/ledger.js +83 -5
  58. package/dist/src/execution/ppt-delivery.d.ts +0 -5
  59. package/dist/src/execution/ppt-delivery.js +0 -26
  60. package/dist/src/execution/process-request.d.ts +151 -0
  61. package/dist/src/execution/process-request.js +177 -0
  62. package/dist/src/execution/targets.d.ts +64 -5
  63. package/dist/src/execution/targets.js +58 -7
  64. package/dist/src/execution/ticket-executor.d.ts +25 -0
  65. package/dist/src/execution/ticket-executor.js +27 -0
  66. package/dist/src/execution/ticket.d.ts +326 -0
  67. package/dist/src/execution/ticket.js +301 -0
  68. package/dist/src/execution/workbench-chat.d.ts +25 -0
  69. package/dist/src/execution/workbench-chat.js +54 -0
  70. package/dist/src/execution/workbench.d.ts +32 -1
  71. package/dist/src/execution/workbench.js +113 -22
  72. package/dist/src/roles/index.d.ts +1 -1
  73. package/dist/src/roles/index.js +1 -1
  74. package/dist/src/roles/skills.d.ts +27 -58
  75. package/dist/src/roles/skills.js +89 -404
  76. package/dist/src/rsi/gate.d.ts +25 -0
  77. package/dist/src/rsi/gate.js +59 -0
  78. package/dist/src/rsi/outline-run.d.ts +107 -0
  79. package/dist/src/rsi/outline-run.js +443 -0
  80. package/dist/workbench-ui/app.css +453 -0
  81. package/dist/workbench-ui/app.js +13 -0
  82. package/dist/workbench-ui/chunk-23JHGYT3.js +1 -0
  83. package/dist/workbench-ui/chunk-3H6STGPV.js +1 -0
  84. package/dist/workbench-ui/chunk-3SNBBMGH.js +1 -0
  85. package/dist/workbench-ui/chunk-3XJZ6DIE.js +1 -0
  86. package/dist/workbench-ui/chunk-44KDLLKJ.js +1 -0
  87. package/dist/workbench-ui/chunk-46H7FU5Y.js +7 -0
  88. package/dist/workbench-ui/chunk-4N44QPL7.js +1 -0
  89. package/dist/workbench-ui/chunk-4YN4BS7I.js +1 -0
  90. package/dist/workbench-ui/chunk-53EG4IVQ.js +96 -0
  91. package/dist/workbench-ui/chunk-5FIPUNR4.js +1 -0
  92. package/dist/workbench-ui/chunk-6DWWYA6G.js +2 -0
  93. package/dist/workbench-ui/chunk-6FU3T633.js +99 -0
  94. package/dist/workbench-ui/chunk-6XKIHRA4.js +1 -0
  95. package/dist/workbench-ui/chunk-7GIX43Y5.js +1 -0
  96. package/dist/workbench-ui/chunk-7Q4WBGX6.js +4 -0
  97. package/dist/workbench-ui/chunk-A3BQM7HR.js +1 -0
  98. package/dist/workbench-ui/chunk-AFCFDDOP.js +24 -0
  99. package/dist/workbench-ui/chunk-AG67EUYD.js +89 -0
  100. package/dist/workbench-ui/chunk-AGJHMMTN.js +1 -0
  101. package/dist/workbench-ui/chunk-AO6JUBV6.js +41 -0
  102. package/dist/workbench-ui/chunk-AUSLTP43.js +72 -0
  103. package/dist/workbench-ui/chunk-AVZL46TT.js +1 -0
  104. package/dist/workbench-ui/chunk-AZRIGIV2.js +168 -0
  105. package/dist/workbench-ui/chunk-B2LIVH37.js +1 -0
  106. package/dist/workbench-ui/chunk-B7YX5TR5.js +1 -0
  107. package/dist/workbench-ui/chunk-BCB4X4XX.js +1 -0
  108. package/dist/workbench-ui/chunk-BCRQUL2A.js +88 -0
  109. package/dist/workbench-ui/chunk-BI6UHHQP.js +1 -0
  110. package/dist/workbench-ui/chunk-BLSLQ4AQ.js +120 -0
  111. package/dist/workbench-ui/chunk-C3QSRS6E.js +1 -0
  112. package/dist/workbench-ui/chunk-CK7M2PJ3.js +62 -0
  113. package/dist/workbench-ui/chunk-CM6LZ7TU.js +1 -0
  114. package/dist/workbench-ui/chunk-CP63H27F.js +36 -0
  115. package/dist/workbench-ui/chunk-CPUMMIS2.js +70 -0
  116. package/dist/workbench-ui/chunk-CSEIBI5U.js +2 -0
  117. package/dist/workbench-ui/chunk-CUS65DKZ.js +161 -0
  118. package/dist/workbench-ui/chunk-CVQY7TNC.js +1 -0
  119. package/dist/workbench-ui/chunk-D6S3XBIX.js +106 -0
  120. package/dist/workbench-ui/chunk-E253Y562.js +1 -0
  121. package/dist/workbench-ui/chunk-EADDJUDC.js +1 -0
  122. package/dist/workbench-ui/chunk-EBGJ3YXG.js +206 -0
  123. package/dist/workbench-ui/chunk-EKPVZ3WY.js +8 -0
  124. package/dist/workbench-ui/chunk-EQDCEAFY.js +1 -0
  125. package/dist/workbench-ui/chunk-ES3SSDJY.js +40 -0
  126. package/dist/workbench-ui/chunk-ESFD2H7N.js +231 -0
  127. package/dist/workbench-ui/chunk-FVOHPMS6.js +1 -0
  128. package/dist/workbench-ui/chunk-FXMQAGVT.js +1 -0
  129. package/dist/workbench-ui/chunk-GGTADRXD.js +24 -0
  130. package/dist/workbench-ui/chunk-GHIVPGNQ.js +1 -0
  131. package/dist/workbench-ui/chunk-GLU2YQV2.js +1 -0
  132. package/dist/workbench-ui/chunk-GOCKBYSM.js +1 -0
  133. package/dist/workbench-ui/chunk-H2KMMTJB.js +1 -0
  134. package/dist/workbench-ui/chunk-HGVLDNPP.js +39 -0
  135. package/dist/workbench-ui/chunk-HSAVC5GY.js +1 -0
  136. package/dist/workbench-ui/chunk-HSEAD2JH.js +1 -0
  137. package/dist/workbench-ui/chunk-HSIHOBTY.js +1 -0
  138. package/dist/workbench-ui/chunk-IZXOKUGG.js +67 -0
  139. package/dist/workbench-ui/chunk-JFT2LC2T.js +1 -0
  140. package/dist/workbench-ui/chunk-JHL3ZDYK.js +3 -0
  141. package/dist/workbench-ui/chunk-JMORLCZG.js +257 -0
  142. package/dist/workbench-ui/chunk-JR4SIX7A.js +1 -0
  143. package/dist/workbench-ui/chunk-K23HAGEH.js +30 -0
  144. package/dist/workbench-ui/chunk-K43JDCBH.js +1 -0
  145. package/dist/workbench-ui/chunk-KINKFJY7.js +1 -0
  146. package/dist/workbench-ui/chunk-KKQSA4LI.js +2 -0
  147. package/dist/workbench-ui/chunk-KOUZX3UX.js +1 -0
  148. package/dist/workbench-ui/chunk-KR4DRHW2.js +78 -0
  149. package/dist/workbench-ui/chunk-KT4DJNOR.js +1 -0
  150. package/dist/workbench-ui/chunk-KTPNKRRZ.js +292 -0
  151. package/dist/workbench-ui/chunk-LFHIPGSU.js +7 -0
  152. package/dist/workbench-ui/chunk-LWDL4HZB.js +125 -0
  153. package/dist/workbench-ui/chunk-MVYC3CY4.js +1 -0
  154. package/dist/workbench-ui/chunk-NWUPALCY.js +129 -0
  155. package/dist/workbench-ui/chunk-NY7C662Z.js +1 -0
  156. package/dist/workbench-ui/chunk-O76WTHWP.js +1 -0
  157. package/dist/workbench-ui/chunk-OTF7YHRE.js +162 -0
  158. package/dist/workbench-ui/chunk-P6TKKRKP.js +1 -0
  159. package/dist/workbench-ui/chunk-PFHOOWV3.js +1 -0
  160. package/dist/workbench-ui/chunk-PUQLANIM.js +1 -0
  161. package/dist/workbench-ui/chunk-PZCGBYVO.js +1 -0
  162. package/dist/workbench-ui/chunk-QOHUZGP4.js +1 -0
  163. package/dist/workbench-ui/chunk-QSEG3OFF.js +1 -0
  164. package/dist/workbench-ui/chunk-QYPOXZIA.js +84 -0
  165. package/dist/workbench-ui/chunk-R6SOF3JC.js +1 -0
  166. package/dist/workbench-ui/chunk-RCLOYU5F.js +1 -0
  167. package/dist/workbench-ui/chunk-RSRUP64S.js +1 -0
  168. package/dist/workbench-ui/chunk-RVAIT6JW.js +1 -0
  169. package/dist/workbench-ui/chunk-S2CCN3II.js +1 -0
  170. package/dist/workbench-ui/chunk-S2Q52W46.js +1 -0
  171. package/dist/workbench-ui/chunk-S2W5THJ5.js +1 -0
  172. package/dist/workbench-ui/chunk-S6ZQZNOX.js +1 -0
  173. package/dist/workbench-ui/chunk-S74PLMMS.js +1 -0
  174. package/dist/workbench-ui/chunk-S7C4HKEY.js +1 -0
  175. package/dist/workbench-ui/chunk-SDTB3Q65.js +1 -0
  176. package/dist/workbench-ui/chunk-SLPRGYUV.js +32 -0
  177. package/dist/workbench-ui/chunk-SQE76S5B.js +1 -0
  178. package/dist/workbench-ui/chunk-SSDZPVPW.js +1 -0
  179. package/dist/workbench-ui/chunk-SVI7DGIE.js +1 -0
  180. package/dist/workbench-ui/chunk-T6QKLZ4H.js +62 -0
  181. package/dist/workbench-ui/chunk-TJNRPTFL.js +1 -0
  182. package/dist/workbench-ui/chunk-TP6U4EDH.js +2 -0
  183. package/dist/workbench-ui/chunk-TYAAT3GQ.js +1 -0
  184. package/dist/workbench-ui/chunk-U6OCY4ZH.js +1 -0
  185. package/dist/workbench-ui/chunk-UAN3NLRF.js +1 -0
  186. package/dist/workbench-ui/chunk-UMLU3FIX.js +1 -0
  187. package/dist/workbench-ui/chunk-URIY2OTM.js +1 -0
  188. package/dist/workbench-ui/chunk-V2NUKAA7.js +38 -0
  189. package/dist/workbench-ui/chunk-V4QLL4TE.js +139 -0
  190. package/dist/workbench-ui/chunk-VASHXUK4.js +2 -0
  191. package/dist/workbench-ui/chunk-VJLIWNIU.js +1 -0
  192. package/dist/workbench-ui/chunk-VQNQFBID.js +1 -0
  193. package/dist/workbench-ui/chunk-VSIWU7XA.js +3 -0
  194. package/dist/workbench-ui/chunk-VSJASPUZ.js +321 -0
  195. package/dist/workbench-ui/chunk-VXPNUNUX.js +3 -0
  196. package/dist/workbench-ui/chunk-WBKLDCV6.js +1 -0
  197. package/dist/workbench-ui/chunk-WOKJM3FY.js +1 -0
  198. package/dist/workbench-ui/chunk-X3U3NA3X.js +34 -0
  199. package/dist/workbench-ui/chunk-XBYU7M4J.js +1 -0
  200. package/dist/workbench-ui/chunk-XBZAO4ID.js +10 -0
  201. package/dist/workbench-ui/chunk-XLLPZ2WO.js +1 -0
  202. package/dist/workbench-ui/chunk-YFVL4NJL.js +1 -0
  203. package/dist/workbench-ui/chunk-YRFQENM4.js +1 -0
  204. package/dist/workbench-ui/chunk-YUADQVB2.js +1 -0
  205. package/dist/workbench-ui/chunk-Z3TCAKM5.js +1 -0
  206. package/dist/workbench-ui/chunk-Z6QR6FRE.js +10 -0
  207. package/dist/workbench-ui/chunk-ZJPSORPP.js +3 -0
  208. package/dist/workbench-ui/chunk-ZLGCSTR2.js +15 -0
  209. package/dist/workbench-ui/chunk-ZLR4SG5X.js +1 -0
  210. package/dist/workbench-ui/chunk-ZND3TTGF.js +1 -0
  211. package/dist/workbench-ui/chunk-ZOP3ZYH7.js +2 -0
  212. package/dist/workbench-ui/index.html +14 -0
  213. package/package.json +19 -8
  214. package/skills/acp-service/SKILL.md +4 -2
  215. package/skills/acp-service/references/a2a.md +18 -6
  216. package/skills/acp-service/references/dsh.md +2 -0
  217. package/skills/acp-service/references/roles-and-tasks.md +10 -10
  218. package/skills/rsi-coach/SKILL.md +134 -0
  219. package/vendor/dsh/README.md +10 -6
  220. package/vendor/dsh/a2a-executor.d.ts +56 -2
  221. package/vendor/dsh/a2a-executor.js +163 -17
  222. package/vendor/dsh/a2a.d.ts +12 -2
  223. package/vendor/dsh/a2a.js +9 -2
  224. package/vendor/dsh/adapter.d.ts +52 -3
  225. package/vendor/dsh/adapter.js +297 -30
  226. package/vendor/dsh/client.js +67 -11
  227. package/vendor/dsh/index.js +55 -3
  228. package/vendor/dsh/native-approvals.d.ts +4 -0
  229. package/vendor/dsh/native-approvals.js +44 -0
  230. package/vendor/dsh/preset-route.d.ts +49 -0
  231. package/vendor/dsh/preset-route.js +51 -0
  232. package/vendor/dsh/preset.js +10 -3
  233. package/vendor/dsh/process-admission.d.ts +25 -0
  234. package/vendor/dsh/process-admission.js +87 -0
  235. package/vendor/dsh/process-requests.d.ts +57 -0
  236. package/vendor/dsh/process-requests.js +49 -0
  237. package/vendor/dsh/review-mcp.d.ts +1 -0
  238. package/vendor/dsh/review-mcp.js +56 -0
  239. package/vendor/dsh/review.d.ts +30 -0
  240. package/vendor/dsh/review.js +149 -0
  241. package/vendor/dsh/session-settings.d.ts +34 -0
  242. package/vendor/dsh/session-settings.js +114 -0
  243. package/vendor/dsh/ticket-spec.d.ts +30 -0
  244. package/vendor/dsh/ticket-spec.js +10 -0
  245. package/vendor/dsh/ticket-tools.d.ts +21 -0
  246. package/vendor/dsh/ticket-tools.js +43 -0
  247. package/vendor/dsh/workbench.d.ts +18 -0
  248. package/vendor/dsh/workbench.js +91 -0
  249. package/vendor/runtime/README.md +6 -4
  250. package/vendor/runtime/dist/docs-site/CLI.html +2 -2
  251. package/vendor/runtime/dist/docs-site/VISION.html +2 -2
  252. package/vendor/runtime/dist/docs-site/agents.html +2 -2
  253. package/vendor/runtime/dist/docs-site/compare.html +2 -2
  254. package/vendor/runtime/dist/docs-site/config.html +2 -2
  255. package/vendor/runtime/dist/docs-site/custom-agents.html +2 -2
  256. package/vendor/runtime/dist/docs-site/exit-codes.html +2 -2
  257. package/vendor/runtime/dist/docs-site/flows.html +2 -2
  258. package/vendor/runtime/dist/docs-site/index.html +1 -1
  259. package/vendor/runtime/dist/docs-site/install.html +2 -2
  260. package/vendor/runtime/dist/docs-site/llms.txt +1 -1
  261. package/vendor/runtime/dist/docs-site/output-formats.html +2 -2
  262. package/vendor/runtime/dist/docs-site/permissions.html +2 -2
  263. package/vendor/runtime/dist/docs-site/prompting.html +2 -2
  264. package/vendor/runtime/dist/docs-site/quickstart.html +2 -2
  265. package/vendor/runtime/dist/docs-site/releasing.html +2 -2
  266. package/vendor/runtime/dist/docs-site/runtime-environment.html +2 -2
  267. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +2 -2
  268. package/vendor/runtime/dist/docs-site/safe-errors.html +2 -2
  269. package/vendor/runtime/dist/docs-site/session-control.html +2 -2
  270. package/vendor/runtime/dist/docs-site/session-watch.html +2 -2
  271. package/vendor/runtime/dist/docs-site/sessions.html +2 -2
  272. package/vendor/runtime/dist/docs-site/shared-sessions.html +2 -2
  273. package/vendor/runtime/package.json +6 -4
  274. package/vendor/runtime/skills/acpx/SKILL.md +2 -0
@@ -1,427 +1,112 @@
1
- /** Task-pinned skills from a DreamMate catalogue; this module never invokes a model or executes skill code. */
2
- import { createHash, randomUUID } from 'node:crypto';
3
- import { copyFile, link, lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
4
- import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
1
+ /**
2
+ * Role skills for a working directory. Skills live in `<cwd>/.agents/skills/<name>/` (read by DSH and Codex when a
3
+ * session starts) and are exposed to Claude Code through `<cwd>/.claude/skills`. Nothing here talks to a network
4
+ * catalogue or pins revisions: the directory is used as it is, and acceptance checks are what guard drift.
5
+ * `syncRoleSkills` copies skills, assets included, from a distribution directory when a role is set up.
6
+ */
7
+ import { cp, lstat, mkdir, readFile, realpath, rename, rm, stat, symlink } from 'node:fs/promises';
8
+ import { randomUUID } from 'node:crypto';
9
+ import { dirname, join, relative, resolve } from 'node:path';
5
10
  import { z } from 'zod';
6
- const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
7
11
  const identifier = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/);
8
- const sha = z.string().regex(/^[a-f0-9]{64}$/);
9
- const absolute = z.string().refine(isAbsolute, 'Expected an absolute path');
10
- const endpoint = z.string().url().refine(value => {
11
- const url = new URL(value);
12
- return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash;
13
- }, 'Expected an HTTP(S) URL without credentials, query or fragment');
14
- const resourcePath = z.string().min(1).max(4096).refine(value => !value.includes('\\') && !value.includes('\0')
15
- && !value.startsWith('/') && value.split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..'), 'Invalid relative resource path');
16
- const requirement = z.object({ key: identifier, name: z.string().min(1), nodeUrl: endpoint.optional(),
17
- skillId: z.string().min(1).optional(), sourceId: z.string().min(1).optional(), assetsManifest: resourcePath.optional() }).strict();
12
+ const requirement = z.object({ key: identifier, name: z.string().min(1) }).strict();
18
13
  export const roleSkillProfileSchema = z.object({ id: identifier, version: z.string().min(1), instructionsPath: z.string().min(1).optional(),
19
- network: z.object({ agentUrl: endpoint, timeoutMs: z.number().int().min(100).max(120000).default(30000) }).strict(),
20
14
  skills: z.array(requirement).min(1).max(100), entrySkill: identifier.optional() }).strict().superRefine((value, ctx) => {
21
15
  if (new Set(value.skills.map(skill => skill.key)).size !== value.skills.length)
22
16
  ctx.addIssue({ code: 'custom', message: 'Duplicate skill key' });
23
17
  if (value.entrySkill && !value.skills.some(skill => skill.key === value.entrySkill))
24
18
  ctx.addIssue({ code: 'custom', message: 'Unknown entrySkill' });
25
19
  });
26
- const inventoryEntry = z.object({ path: resourcePath, bytes: z.number().int().nonnegative().max(128 * 1024 * 1024), sha256: sha }).strict();
27
- const assetEntry = inventoryEntry.extend({ url: endpoint });
28
- const lockedSkill = z.object({ key: identifier, nodeUrl: endpoint, skillId: z.string().min(1), sourceId: z.string().min(1), name: z.string().min(1),
29
- revision: sha, cacheDirectory: absolute, directory: absolute, guidePath: absolute, guideResource: resourcePath,
30
- files: z.array(inventoryEntry).min(1).max(2000), assets: z.array(assetEntry).max(2000) }).strict();
31
- export const roleSkillLockSchema = z.object({ schemaVersion: z.literal(1), roleId: identifier, roleVersion: z.string().min(1),
32
- profilePath: absolute, profileSha256: sha, cacheRoot: absolute, roleDirectory: absolute, createdAt: z.string(),
33
- instructionsPath: absolute.optional(), instructionsSha256: sha.optional(), instructionsBytes: z.number().int().nonnegative().optional(),
34
- entrySkill: identifier.optional(), entryGuidePath: absolute.optional(), skills: z.array(lockedSkill).min(1).max(100) }).strict();
35
- const catalogueEntry = z.object({ id: z.string().min(1), source_id: z.string().min(1), name: z.string().min(1), revision: sha }).passthrough();
36
- const readResult = z.object({ id: z.string().min(1), source_id: z.string().min(1), name: z.string().min(1), revision: sha,
37
- resource: resourcePath, content: z.string(), encoding: z.enum(['utf8', 'base64']),
38
- resources: z.array(z.object({ path: resourcePath, bytes: z.number().int().nonnegative().max(8 * 1024 * 1024) }).passthrough()).max(2000).optional() }).passthrough();
39
- const receiptSchema = z.object({ schemaVersion: z.literal(1), nodeUrl: endpoint, skillId: z.string().min(1), sourceId: z.string().min(1),
40
- name: z.string().min(1), revision: sha, guideResource: resourcePath, files: z.array(inventoryEntry).min(1).max(2000) }).strict();
41
- /** Same content revision as Skill Manager: paths sorted by UTF-8 bytes, then path\0length\0 + file bytes. */
42
- export function skillContentRevision(files) {
43
- const result = createHash('sha256');
44
- for (const file of [...files].sort((a, b) => Buffer.compare(Buffer.from(a.path), Buffer.from(b.path)))) {
45
- result.update(`${file.path}\0${file.bytes.length}\0`).update(file.bytes);
46
- }
47
- return result.digest('hex');
48
- }
49
- const inside = (root, path) => { const rel = relative(root, path); return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)); };
50
- function identity(skill) { return hash(JSON.stringify([skill.nodeUrl, skill.skillId])); }
51
- function snapshotId(lock) {
52
- return hash(JSON.stringify({ profile: lock.profileSha256, instructions: lock.instructionsSha256,
53
- skills: lock.skills.map(skill => [skill.key, skill.nodeUrl, skill.skillId, skill.revision, skill.assets]) }));
54
- }
55
- async function exists(path) {
20
+ export const SKILLS_DIRECTORY = '.agents/skills';
21
+ export const CLAUDE_SKILLS_DIRECTORY = '.claude/skills';
22
+ async function lstatOrUndefined(path) {
56
23
  try {
57
- await lstat(path);
58
- return true;
24
+ return await lstat(path);
59
25
  }
60
26
  catch (error) {
61
27
  if (error.code === 'ENOENT')
62
- return false;
28
+ return undefined;
63
29
  throw error;
64
30
  }
65
31
  }
66
- async function checkParents(root, target, create = false) {
67
- if (!inside(root, target))
68
- throw new Error('Cache path escapes root');
69
- const segments = relative(root, target).split(sep).filter(Boolean);
70
- let current = root;
71
- for (const segment of segments) {
72
- current = join(current, segment);
73
- if (create)
74
- await mkdir(current).catch(error => { if (error.code !== 'EEXIST')
75
- throw error; });
76
- const info = await lstat(current);
77
- if (info.isSymbolicLink() || !info.isDirectory())
78
- throw new Error('Cache directory contains symlink or non-directory');
79
- }
80
- }
81
- async function regularBytes(root, path) {
82
- await checkParents(root, dirname(path));
83
- const info = await lstat(path);
84
- if (!info.isFile() || info.isSymbolicLink())
85
- throw new Error('Cache resource is not a regular file');
86
- return readFile(path);
87
- }
88
- async function verifyFile(root, path, expected) {
89
- const bytes = await regularBytes(root, path);
90
- if (bytes.length !== expected.bytes || hash(bytes) !== expected.sha256)
91
- throw new Error('Cached resource byte/hash mismatch');
92
- }
93
- async function listFiles(root, directory = root) {
94
- const paths = [];
95
- for (const name of await readdir(directory)) {
96
- const path = join(directory, name), info = await lstat(path);
97
- if (info.isSymbolicLink())
98
- throw new Error('Symlink found in cached skill');
99
- if (info.isDirectory())
100
- paths.push(...await listFiles(root, path));
101
- else if (info.isFile())
102
- paths.push(relative(root, path).split(sep).join('/'));
103
- else
104
- throw new Error('Unsupported cache filesystem entry');
105
- }
106
- return paths.sort();
107
- }
108
- async function verifyReceipt(root, directory, expected) {
109
- const receipt = receiptSchema.parse(JSON.parse((await regularBytes(root, join(directory, 'receipt.json'))).toString('utf8')));
110
- if (expected && JSON.stringify(receipt) !== JSON.stringify(expected))
111
- throw new Error('Cached skill receipt differs from locked identity');
112
- const files = join(directory, 'files');
113
- await checkParents(root, files);
114
- const inventory = await listFiles(files);
115
- if (new Set(receipt.files.map(file => file.path)).size !== receipt.files.length || JSON.stringify(inventory) !== JSON.stringify(receipt.files.map(file => file.path).sort()))
116
- throw new Error('Cached skill inventory mismatch');
117
- const content = [];
118
- for (const file of receipt.files) {
119
- const bytes = await regularBytes(root, join(files, file.path));
120
- if (bytes.length !== file.bytes || hash(bytes) !== file.sha256)
121
- throw new Error('Cached skill byte/hash mismatch');
122
- content.push({ path: file.path, bytes });
123
- }
124
- if (skillContentRevision(content) !== receipt.revision)
125
- throw new Error('Cached skill content revision mismatch');
126
- return receipt;
127
- }
128
- async function bounded(response, limit) {
129
- if (!response.ok) {
130
- await response.body?.cancel();
131
- throw new Error(`Skill network request failed (HTTP ${response.status})`);
132
- }
133
- if (Number(response.headers.get('content-length') ?? 0) > limit) {
134
- await response.body?.cancel();
135
- throw new Error('Skill network response exceeds byte limit');
136
- }
137
- if (!response.body)
138
- return Buffer.alloc(0);
139
- const reader = response.body.getReader(), chunks = [];
140
- let total = 0;
141
- try {
142
- while (true) {
143
- const chunk = await reader.read();
144
- if (chunk.done)
145
- break;
146
- total += chunk.value.length;
147
- if (total > limit)
148
- throw new Error('Skill network response exceeds byte limit');
149
- chunks.push(chunk.value);
150
- }
151
- }
152
- finally {
153
- await reader.cancel().catch(() => { });
154
- }
155
- return Buffer.concat(chunks);
156
- }
157
- function networkUrl(base, suffix, params = {}) {
158
- const url = new URL(base);
159
- url.pathname = url.pathname.replace(/\/$/, '') + suffix;
160
- for (const [key, value] of Object.entries(params))
161
- url.searchParams.set(key, value);
162
- return url;
163
- }
164
- async function networkJson(url, timeout, signal) {
165
- const response = await fetch(url, { redirect: 'error', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout) });
166
- return JSON.parse((await bounded(response, 24 * 1024 * 1024)).toString('utf8'));
167
- }
168
- async function selectSkill(base, wanted, timeout, signal) {
169
- let offset = 0;
170
- const matches = [];
171
- for (let page = 0; page < 50; page++) {
172
- const result = z.object({ skills: z.array(catalogueEntry).max(200), has_more: z.boolean().optional(), next_offset: z.number().int().nonnegative().nullable().optional() }).passthrough()
173
- .parse(await networkJson(networkUrl(base, '/skills', { limit: '200', offset: String(offset) }), timeout, signal));
174
- for (const skill of result.skills)
175
- if (skill.name === wanted.name && (!wanted.skillId || wanted.skillId === skill.id) && (!wanted.sourceId || wanted.sourceId === skill.source_id))
176
- matches.push(skill);
177
- if (!result.has_more) {
178
- if (matches.length !== 1)
179
- throw new Error(matches.length ? `Ambiguous skill: ${wanted.name}; pin sourceId/skillId` : `Required skill unavailable: ${wanted.name}`);
180
- return matches[0];
181
- }
182
- if (result.next_offset == null || result.next_offset <= offset)
183
- throw new Error('Invalid skill catalogue pagination');
184
- offset = result.next_offset;
185
- }
186
- throw new Error('Skill catalogue exceeds bounded page limit');
187
- }
188
- function decoded(result, expectedBytes) {
189
- if (result.encoding === 'utf8') {
190
- const bytes = Buffer.from(result.content, 'utf8');
191
- // Manager's TextDecoder strips one leading UTF-8 BOM. Restore it only when
192
- // the byte inventory requires exactly those three bytes; the package hash
193
- // below still has to match the provider's original revision.
194
- return bytes.length + 3 === expectedBytes ? Buffer.concat([Buffer.from([239, 187, 191]), bytes]) : bytes;
195
- }
196
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(result.content))
197
- throw new Error('Invalid base64 skill resource');
198
- return Buffer.from(result.content, 'base64');
199
- }
200
- async function installDirectory(temporary, target) {
201
- try {
202
- await rename(temporary, target);
203
- }
204
- catch (error) {
205
- if (!['EEXIST', 'ENOTEMPTY'].includes(error.code ?? ''))
206
- throw error;
207
- await rm(temporary, { recursive: true, force: true });
208
- }
209
- }
210
- async function loadSkill(root, base, wanted, timeout, signal) {
211
- const chosen = await selectSkill(base, wanted, timeout, signal);
212
- const parent = join(root, 'skills', identity({ nodeUrl: base, skillId: chosen.id }));
213
- await checkParents(root, parent, true);
214
- const directory = join(parent, chosen.revision);
215
- if (await exists(directory)) {
216
- const receipt = await verifyReceipt(root, directory);
217
- if (receipt.nodeUrl !== base || receipt.skillId !== chosen.id || receipt.sourceId !== chosen.source_id || receipt.name !== chosen.name || receipt.revision !== chosen.revision)
218
- throw new Error('Cached skill catalogue identity mismatch');
219
- return { directory, receipt };
220
- }
221
- const read = async (resource) => {
222
- const result = readResult.parse(await networkJson(networkUrl(base, `/skills/${encodeURIComponent(chosen.id)}`, { revision: chosen.revision, ...(resource ? { resource } : {}) }), timeout, signal));
223
- if (result.id !== chosen.id || result.source_id !== chosen.source_id || result.name !== chosen.name || result.revision !== chosen.revision || (resource && result.resource !== resource))
224
- throw new Error('Skill resource identity/revision mismatch');
225
- return result;
226
- };
227
- const main = await read();
228
- const resources = main.resources;
229
- if (!resources?.length || new Set(resources.map(file => file.path)).size !== resources.length || !resources.some(file => file.path === main.resource))
230
- throw new Error('Invalid skill resource inventory');
231
- if (resources.reduce((total, file) => total + file.bytes, 0) > 32 * 1024 * 1024)
232
- throw new Error('Skill package exceeds size limit');
233
- const temporary = join(parent, `.download-${randomUUID()}`);
234
- await mkdir(temporary, { mode: 0o700 });
235
- await mkdir(join(temporary, 'files'));
236
- try {
237
- const files = [], contents = [];
238
- for (const file of resources) {
239
- const result = file.path === main.resource ? main : await read(file.path);
240
- const bytes = decoded(result, file.bytes);
241
- if (bytes.length !== file.bytes)
242
- throw new Error(`Skill resource size differs from inventory: ${chosen.name}/${file.path}; expected ${file.bytes}, received ${bytes.length}`);
243
- const path = join(temporary, 'files', file.path);
244
- await checkParents(root, dirname(path), true);
245
- await writeFile(path, bytes, { flag: 'wx', mode: 0o600 });
246
- files.push({ path: file.path, bytes: bytes.length, sha256: hash(bytes) });
247
- contents.push({ path: file.path, bytes });
248
- }
249
- if (skillContentRevision(contents) !== chosen.revision)
250
- throw new Error('Downloaded skill package revision mismatch');
251
- const receipt = { schemaVersion: 1, nodeUrl: base, skillId: chosen.id, sourceId: chosen.source_id, name: chosen.name, revision: chosen.revision, guideResource: main.resource, files };
252
- await writeFile(join(temporary, 'receipt.json'), JSON.stringify(receipt), { mode: 0o600, flag: 'wx' });
253
- await installDirectory(temporary, directory);
254
- return { directory, receipt: await verifyReceipt(root, directory, receipt) };
255
- }
256
- finally {
257
- await rm(temporary, { recursive: true, force: true });
258
- }
259
- }
260
- async function loadAssets(root, directory, wanted, timeout, signal) {
261
- if (!wanted.assetsManifest)
262
- return [];
263
- const manifest = z.object({ assets: z.array(assetEntry).max(2000) }).strict().parse(JSON.parse((await regularBytes(root, join(directory, 'files', wanted.assetsManifest))).toString('utf8')));
264
- if (new Set(manifest.assets.map(asset => asset.path)).size !== manifest.assets.length)
265
- throw new Error('Duplicate skill asset path');
266
- if (manifest.assets.reduce((total, asset) => total + asset.bytes, 0) > 1024 * 1024 * 1024)
267
- throw new Error('Skill assets exceed size budget');
268
- for (const asset of manifest.assets) {
269
- if (await exists(join(directory, 'files', asset.path)))
270
- throw new Error('Asset path collides with skill resource');
271
- const parent = join(root, 'assets', asset.sha256);
272
- await checkParents(root, parent, true);
273
- const blob = join(parent, 'blob');
274
- if (!(await exists(blob))) {
275
- const response = await fetch(asset.url, { redirect: 'error', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout) });
276
- const bytes = await bounded(response, Math.min(asset.bytes + 1, 128 * 1024 * 1024));
277
- if (bytes.length !== asset.bytes || hash(bytes) !== asset.sha256)
278
- throw new Error('Downloaded asset byte/hash mismatch');
279
- const temporary = join(parent, `.download-${randomUUID()}`);
280
- await writeFile(temporary, bytes, { flag: 'wx', mode: 0o600 });
281
- try {
282
- await link(temporary, blob);
283
- }
284
- catch (error) {
285
- if (error.code !== 'EEXIST')
286
- throw error;
287
- }
288
- finally {
289
- await rm(temporary, { force: true });
290
- }
291
- }
292
- await verifyFile(root, blob, asset);
293
- }
294
- return manifest.assets;
295
- }
296
- async function validateLock(trustedRoot, lock) {
297
- // A migration may preserve the lock's original paths through a root alias.
298
- // Only that root alias may differ: every descendant keeps the same exact
299
- // binding and the existing directory/file symlink checks below still apply.
300
- const root = lock.cacheRoot;
301
- if (root !== trustedRoot && await realpath(root) !== trustedRoot)
302
- throw new Error('Role lock cache binding mismatch');
303
- const roleDirectory = join(root, 'roles', lock.roleId, snapshotId(lock));
304
- if (lock.roleDirectory !== roleDirectory || new Set(lock.skills.map(skill => skill.key)).size !== lock.skills.length)
305
- throw new Error('Role lock cache binding mismatch');
306
- const profileBytes = await regularBytes(root, join(roleDirectory, 'profile.json'));
307
- if (hash(profileBytes) !== lock.profileSha256)
308
- throw new Error('Cached role profile byte/hash mismatch');
309
- const profile = roleSkillProfileSchema.parse(JSON.parse(profileBytes.toString('utf8')));
310
- if (profile.id !== lock.roleId || profile.version !== lock.roleVersion || profile.entrySkill !== lock.entrySkill
311
- || Boolean(profile.instructionsPath) !== Boolean(lock.instructionsPath) || profile.skills.length !== lock.skills.length)
312
- throw new Error('Role lock profile binding mismatch');
313
- for (const skill of lock.skills) {
314
- const wanted = profile.skills.find(wanted => wanted.key === skill.key);
315
- if (!wanted || wanted.name !== skill.name || (wanted.skillId && wanted.skillId !== skill.skillId)
316
- || (wanted.sourceId && wanted.sourceId !== skill.sourceId) || (wanted.nodeUrl ?? profile.network.agentUrl) !== skill.nodeUrl)
317
- throw new Error('Role lock skill requirement mismatch');
318
- const directory = join(root, 'skills', identity(skill), skill.revision), materialized = join(roleDirectory, 'skills', skill.key);
319
- if (skill.cacheDirectory !== directory || skill.directory !== materialized || skill.guidePath !== join(materialized, skill.guideResource))
320
- throw new Error('Role lock skill path mismatch');
321
- const receipt = { schemaVersion: 1, nodeUrl: skill.nodeUrl, skillId: skill.skillId, sourceId: skill.sourceId, name: skill.name, revision: skill.revision, guideResource: skill.guideResource, files: skill.files };
322
- await verifyReceipt(root, directory, receipt);
323
- if (JSON.stringify((await listFiles(materialized)).sort()) !== JSON.stringify([...skill.files, ...skill.assets].map(file => file.path).sort()))
324
- throw new Error('Materialized skill inventory mismatch');
325
- for (const file of skill.files)
326
- await verifyFile(root, join(materialized, file.path), file);
327
- for (const asset of skill.assets) {
328
- await verifyFile(root, join(root, 'assets', asset.sha256, 'blob'), asset);
329
- await verifyFile(root, join(materialized, asset.path), asset);
330
- }
331
- }
332
- if (lock.instructionsPath) {
333
- if (lock.instructionsPath !== join(roleDirectory, 'ROLE.md') || !lock.instructionsSha256 || lock.instructionsBytes === undefined)
334
- throw new Error('Role instruction binding mismatch');
335
- await verifyFile(root, lock.instructionsPath, { bytes: lock.instructionsBytes, sha256: lock.instructionsSha256 });
336
- }
337
- if (lock.entrySkill && lock.entryGuidePath !== lock.skills.find(skill => skill.key === lock.entrySkill)?.guidePath)
338
- throw new Error('Role entry skill binding mismatch');
339
- const snapshotFiles = lock.skills.flatMap(skill => [...skill.files, ...skill.assets].map(file => `skills/${skill.key}/${file.path}`))
340
- .concat('profile.json', ...(lock.instructionsPath ? ['ROLE.md'] : [])).sort();
341
- if (JSON.stringify(await listFiles(roleDirectory)) !== JSON.stringify(snapshotFiles))
342
- throw new Error('Role snapshot inventory mismatch');
343
- return lock;
344
- }
345
- /** New lock => latest catalogue revisions; existing lock => checked, fully offline reuse even if the source/profile changed. */
346
- export async function resolveRoleSkills(options) {
347
- const cache = resolve(options.cacheRoot);
348
- await mkdir(cache, { recursive: true, mode: 0o700 });
349
- const root = await realpath(cache);
350
- const lockPath = resolve(options.lockPath), profilePath = resolve(options.profilePath);
351
- if (await exists(lockPath)) {
352
- const info = await lstat(lockPath);
353
- if (!info.isFile() || info.isSymbolicLink())
354
- throw new Error('Role lock is not a regular file');
355
- const lock = roleSkillLockSchema.parse(JSON.parse(await readFile(lockPath, 'utf8')));
356
- if (lock.profilePath !== profilePath && await realpath(lock.profilePath) !== await realpath(profilePath))
357
- throw new Error('Role lock belongs to another profile');
358
- return validateLock(root, lock);
359
- }
360
- options.signal?.throwIfAborted();
361
- const bytes = await readFile(profilePath), profile = roleSkillProfileSchema.parse(JSON.parse(bytes.toString('utf8')));
362
- const instructions = profile.instructionsPath ? await readFile(resolve(dirname(profilePath), profile.instructionsPath)) : undefined;
363
- const lock = { schemaVersion: 1, roleId: profile.id, roleVersion: profile.version, profilePath,
364
- profileSha256: hash(bytes), cacheRoot: root, roleDirectory: root, createdAt: new Date().toISOString(),
365
- ...(instructions ? { instructionsSha256: hash(instructions), instructionsBytes: instructions.length } : {}),
366
- ...(profile.entrySkill ? { entrySkill: profile.entrySkill } : {}), skills: [] };
32
+ /** A skill name becomes a directory name under `.agents/skills`, so it must not be able to leave it. */
33
+ async function readProfile(profilePath) {
34
+ const profile = roleSkillProfileSchema.parse(JSON.parse(await readFile(profilePath, 'utf8')));
35
+ for (const skill of profile.skills)
36
+ if (!identifier.safeParse(skill.name).success)
37
+ throw new Error(`Unsafe skill name: ${skill.name.slice(0, 64)}`);
38
+ return profile;
39
+ }
40
+ function frontMatterName(text) {
41
+ const block = /^?---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1];
42
+ const line = block?.split(/\r?\n/).find(item => /^name\s*:/.test(item));
43
+ return line?.replace(/^name\s*:\s*/, '').trim().replace(/^(['"])(.*)\1$/, '$2');
44
+ }
45
+ /** Make `.claude/skills` reach `.agents/skills`. An existing real `.claude/skills` directory only gains links for the named skills. */
46
+ export async function linkClaudeSkills(cwd, names) {
47
+ const source = join(cwd, SKILLS_DIRECTORY), link = join(cwd, CLAUDE_SKILLS_DIRECTORY);
48
+ await mkdir(dirname(link), { recursive: true });
49
+ const info = await lstatOrUndefined(link);
50
+ if (!info) {
51
+ await symlink(relative(dirname(link), source), link, 'dir');
52
+ return;
53
+ }
54
+ if (info.isSymbolicLink()) {
55
+ if (await realpath(link).catch(() => undefined) !== await realpath(source))
56
+ throw new Error(`${CLAUDE_SKILLS_DIRECTORY} is a link to somewhere other than ${SKILLS_DIRECTORY}`);
57
+ return;
58
+ }
59
+ if (!info.isDirectory())
60
+ throw new Error(`${CLAUDE_SKILLS_DIRECTORY} is not a directory`);
61
+ for (const name of names) {
62
+ const entry = join(link, name);
63
+ if (await lstatOrUndefined(entry))
64
+ continue;
65
+ await symlink(relative(link, join(source, name)), entry, 'dir');
66
+ }
67
+ }
68
+ /** Check that every skill the profile names is present under `<cwd>/.agents/skills`, link it for Claude Code and return what the prompt needs. */
69
+ export async function loadRoleSkills(options) {
70
+ const profilePath = resolve(options.profilePath), cwd = resolve(options.cwd), profile = await readProfile(profilePath);
71
+ const instructions = profile.instructionsPath ? await readFile(resolve(dirname(profilePath), profile.instructionsPath), 'utf8') : '';
72
+ const skills = [];
367
73
  for (const wanted of profile.skills) {
368
- const base = wanted.nodeUrl ?? profile.network.agentUrl;
369
- const { directory, receipt } = await loadSkill(root, base, wanted, profile.network.timeoutMs, options.signal);
370
- const assets = await loadAssets(root, directory, wanted, profile.network.timeoutMs, options.signal);
371
- lock.skills.push({ key: wanted.key, nodeUrl: base, skillId: receipt.skillId, sourceId: receipt.sourceId, name: receipt.name,
372
- revision: receipt.revision, cacheDirectory: directory, directory: root, guidePath: root, guideResource: receipt.guideResource, files: receipt.files, assets });
373
- }
374
- lock.roleDirectory = join(root, 'roles', profile.id, snapshotId(lock));
375
- if (instructions)
376
- lock.instructionsPath = join(lock.roleDirectory, 'ROLE.md');
377
- for (const skill of lock.skills) {
378
- skill.directory = join(lock.roleDirectory, 'skills', skill.key);
379
- skill.guidePath = join(skill.directory, skill.guideResource);
380
- }
381
- if (profile.entrySkill)
382
- lock.entryGuidePath = lock.skills.find(skill => skill.key === profile.entrySkill).guidePath;
383
- const parent = dirname(lock.roleDirectory);
384
- await checkParents(root, parent, true);
385
- if (!(await exists(lock.roleDirectory))) {
386
- const temporary = join(parent, `.materialize-${randomUUID()}`);
387
- await mkdir(temporary, { mode: 0o700 });
74
+ const directory = join(cwd, SKILLS_DIRECTORY, wanted.name), guidePath = join(directory, 'SKILL.md');
75
+ const info = await stat(guidePath).catch(() => undefined);
76
+ if (!info?.isFile())
77
+ throw new Error(`Required skill unavailable in ${cwd}: ${wanted.name}`);
78
+ const declared = frontMatterName(await readFile(guidePath, 'utf8'));
79
+ if (declared !== undefined && declared !== wanted.name)
80
+ throw new Error(`Skill directory ${wanted.name} declares name ${declared}`);
81
+ skills.push({ key: wanted.key, name: wanted.name, directory, guidePath });
82
+ }
83
+ await linkClaudeSkills(cwd, skills.map(skill => skill.name));
84
+ const entry = profile.entrySkill ? skills.find(skill => skill.key === profile.entrySkill) : undefined;
85
+ return { roleId: profile.id, roleVersion: profile.version, roleDirectory: dirname(profilePath), instructions,
86
+ ...(entry ? { entryGuidePath: entry.guidePath } : {}), skills };
87
+ }
88
+ /** Copy the profile's skills from a distribution directory into `<cwd>/.agents/skills`, then verify and link them. No network, no model. */
89
+ export async function syncRoleSkills(options) {
90
+ const profile = await readProfile(resolve(options.profilePath)), cwd = resolve(options.cwd), source = resolve(options.source);
91
+ const target = join(cwd, SKILLS_DIRECTORY);
92
+ await mkdir(target, { recursive: true });
93
+ for (const wanted of profile.skills) {
94
+ const from = join(source, wanted.name);
95
+ if (!(await stat(join(from, 'SKILL.md')).catch(() => undefined))?.isFile())
96
+ throw new Error(`Skill not found in source: ${wanted.name}`);
97
+ const destination = join(target, wanted.name);
98
+ // Skip a skill that is already this very directory (for instance when source and target are the same place).
99
+ if (await realpath(destination).catch(() => undefined) === await realpath(from))
100
+ continue;
101
+ const staging = join(target, `.sync-${randomUUID()}`);
388
102
  try {
389
- for (const skill of lock.skills)
390
- for (const file of [...skill.files, ...skill.assets]) {
391
- const path = join(temporary, 'skills', skill.key, file.path);
392
- await checkParents(root, dirname(path), true);
393
- const source = skill.files.includes(file) ? join(skill.cacheDirectory, 'files', file.path) : join(root, 'assets', file.sha256, 'blob');
394
- await copyFile(source, path);
395
- }
396
- await writeFile(join(temporary, 'profile.json'), bytes, { mode: 0o600 });
397
- if (instructions)
398
- await writeFile(join(temporary, 'ROLE.md'), instructions, { mode: 0o600 });
399
- await installDirectory(temporary, lock.roleDirectory);
103
+ await cp(from, staging, { recursive: true, dereference: true });
104
+ await rm(destination, { recursive: true, force: true });
105
+ await rename(staging, destination);
400
106
  }
401
107
  finally {
402
- await rm(temporary, { recursive: true, force: true });
108
+ await rm(staging, { recursive: true, force: true });
403
109
  }
404
110
  }
405
- await validateLock(root, lock);
406
- options.signal?.throwIfAborted();
407
- await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 });
408
- const temporary = join(dirname(lockPath), `.role-lock-${randomUUID()}`);
409
- await writeFile(temporary, JSON.stringify(lock, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
410
- try {
411
- await link(temporary, lockPath);
412
- }
413
- catch (error) {
414
- if (error.code !== 'EEXIST')
415
- throw error;
416
- }
417
- finally {
418
- await rm(temporary, { force: true });
419
- }
420
- const storedInfo = await lstat(lockPath);
421
- if (!storedInfo.isFile() || storedInfo.isSymbolicLink())
422
- throw new Error('Role lock is not a regular file');
423
- const stored = roleSkillLockSchema.parse(JSON.parse(await readFile(lockPath, 'utf8')));
424
- if (stored.profilePath !== profilePath)
425
- throw new Error('Concurrent role lock belongs to another profile');
426
- return validateLock(root, stored);
111
+ return loadRoleSkills({ profilePath: options.profilePath, cwd });
427
112
  }
@@ -0,0 +1,25 @@
1
+ import { type LedgerEntry, type RoleVersion } from './outline-run.js';
2
+ export interface GateReport {
3
+ roleId: string;
4
+ role: RoleVersion;
5
+ ready: boolean;
6
+ reasons: string[];
7
+ required: number;
8
+ /** The latest development runs on this version, newest last. */
9
+ devRuns: LedgerEntry[];
10
+ /** Development runs on this version that never reached a verdict and so do not count. */
11
+ unfinished: LedgerEntry[];
12
+ /** Every case in the role, with its latest test result on this version. */
13
+ testCases: {
14
+ caseId: string;
15
+ kind: string;
16
+ result: 'passed' | 'failed' | 'not_run';
17
+ }[];
18
+ }
19
+ export declare function checkGate(options: {
20
+ roleDirectory: string;
21
+ workspace: string;
22
+ required?: number;
23
+ /** The gateway, for the proposals' current state; without it every proposal in the ledger counts as open. */
24
+ invoke?: (method: string, params: Record<string, unknown>) => Promise<unknown>;
25
+ }): Promise<GateReport>;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The gate from development to testing, decided from the role's ledger. Development is done when the current
3
+ * committed role version has passed the development case several times in a row, each first draft passed the
4
+ * program checks, and every proposal QA made to codify a check or change a locked item has been settled by a
5
+ * person (accepted, rejected or done on the ticket). Any change to the role directory is a new version, so the
6
+ * count starts again. Runs that never reached a verdict (the executor or QA task did not finish, e.g. the model
7
+ * quota ran out, or the host itself failed) say nothing about the role and are left out.
8
+ */
9
+ import { readdir, readFile } from 'node:fs/promises';
10
+ import path from 'node:path';
11
+ import { z } from 'zod';
12
+ import { ledgerPath, roleVersion } from './outline-run.js';
13
+ const UNFINISHED = ['not_completed', 'review_failed', 'host_error'];
14
+ export async function checkGate(options) {
15
+ const roleDirectory = path.resolve(options.roleDirectory), required = options.required ?? 2;
16
+ const roleId = z.object({ id: z.string().min(1) }).passthrough().parse(JSON.parse(await readFile(path.join(roleDirectory, 'profile.json'), 'utf8'))).id;
17
+ const role = await roleVersion(roleDirectory);
18
+ const text = await readFile(ledgerPath(options.workspace, roleId), 'utf8').catch(() => '');
19
+ // A resumed run appends a new line for the same work directory; its latest line is the run.
20
+ const lines = text.split('\n').filter(Boolean).map(line => JSON.parse(line));
21
+ const entries = lines.filter((entry, index) => !lines.slice(index + 1).some(later => later.workDirectory === entry.workDirectory))
22
+ .filter(entry => role.commit && entry.role.commit === role.commit && !entry.role.dirty);
23
+ const dev = entries.filter(entry => entry.phase === 'dev' && entry.caseKind === 'original');
24
+ const unfinished = dev.filter(entry => UNFINISHED.includes(entry.stopReason));
25
+ const devRuns = dev.filter(entry => !UNFINISHED.includes(entry.stopReason)).slice(-required);
26
+ const reasons = [];
27
+ if (role.dirty)
28
+ reasons.push('角色目录有未提交的改动,先提交成一个版本');
29
+ if (devRuns.length < required)
30
+ reasons.push(`当前版本在开发题上有 ${devRuns.length} 次运行,需要连续 ${required} 次通过`);
31
+ for (const run of devRuns) {
32
+ const at = `${run.startedAt} ${run.caseId}`;
33
+ if (!run.passed)
34
+ reasons.push(`${at}:未通过(${run.stopReason})`);
35
+ if (!run.firstDraftPassed)
36
+ reasons.push(`${at}:初稿没有一次通过程序检查`);
37
+ if (run.mustIssues)
38
+ reasons.push(`${at}:还有 ${run.mustIssues} 条必须改`);
39
+ // Entries written before the ledger carried the job fall back to the run's own record.
40
+ const jobId = run.jobId ?? await readFile(path.join(run.workDirectory, 'run.json'), 'utf8')
41
+ .then(text => JSON.parse(text).rounds?.[0]?.jobId, () => undefined);
42
+ const ticket = options.invoke && jobId
43
+ ? await options.invoke('ticket_get', { originSessionId: run.originSessionId ?? 'rsi-cli', jobId }) : undefined;
44
+ const open = (ticket ? ticket.proposals.filter(p => p.state === 'open') : run.proposals.map((p, i) => ({ ...p, id: `#${i + 1}` })))
45
+ .filter(p => p.kind === 'check' || p.kind === 'locked');
46
+ if (open.length)
47
+ reasons.push(`${at}:质检有 ${open.length} 条提议还没人处理(${open.map(p => `${p.id} ${p.kind}`).join('、')})`
48
+ + (jobId ? `,用 acp-service ticket proposal --job ${jobId} --id <编号> accept|reject|done 处理` : ''));
49
+ }
50
+ const casesDirectory = path.join(roleDirectory, 'cases');
51
+ const testCases = [];
52
+ const names = (await readdir(casesDirectory, { withFileTypes: true })).filter(entry => entry.isDirectory()).map(entry => entry.name).sort();
53
+ for (const name of names) {
54
+ const kase = JSON.parse(await readFile(path.join(casesDirectory, name, 'case.json'), 'utf8'));
55
+ const latest = entries.filter(entry => entry.phase === 'test' && entry.caseId === kase.id).at(-1);
56
+ testCases.push({ caseId: kase.id, kind: kase.kind, result: !latest ? 'not_run' : latest.passed ? 'passed' : 'failed' });
57
+ }
58
+ return { roleId, role, ready: reasons.length === 0, reasons, required, devRuns, unfinished, testCases };
59
+ }