oneie 3.8.3 → 4.0.1

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 (382) hide show
  1. package/LICENSE +86 -0
  2. package/README.md +63 -952
  3. package/dist/package.json +38 -0
  4. package/dist/src/agent.d.ts +2 -0
  5. package/dist/src/agent.js +888 -0
  6. package/dist/src/args.d.ts +9 -0
  7. package/dist/src/args.js +61 -0
  8. package/dist/src/auth.d.ts +6 -0
  9. package/dist/src/auth.js +122 -0
  10. package/dist/{banner.d.ts → src/banner.d.ts} +0 -1
  11. package/dist/src/banner.js +16 -0
  12. package/dist/src/broadcast.d.ts +6 -0
  13. package/dist/src/broadcast.js +150 -0
  14. package/dist/src/catalog.d.ts +2 -0
  15. package/dist/src/catalog.js +78 -0
  16. package/dist/src/chat.d.ts +2 -0
  17. package/dist/src/chat.js +92 -0
  18. package/dist/src/client.d.ts +5 -0
  19. package/dist/src/client.js +151 -0
  20. package/dist/src/compiler.d.ts +36 -0
  21. package/dist/src/compiler.js +314 -0
  22. package/dist/src/config.d.ts +24 -0
  23. package/dist/src/config.js +70 -0
  24. package/dist/src/connect.d.ts +2 -0
  25. package/dist/src/connect.js +64 -0
  26. package/dist/src/coordinate.d.ts +3 -0
  27. package/dist/src/coordinate.js +58 -0
  28. package/dist/src/create.d.ts +2 -0
  29. package/dist/src/create.js +113 -0
  30. package/dist/src/deploy.d.ts +2 -0
  31. package/dist/src/deploy.js +19 -0
  32. package/dist/src/dev.d.ts +2 -0
  33. package/dist/src/dev.js +75 -0
  34. package/dist/src/device-flow.d.ts +57 -0
  35. package/dist/src/device-flow.js +173 -0
  36. package/dist/src/doctor.d.ts +26 -0
  37. package/dist/src/doctor.js +91 -0
  38. package/dist/src/env.d.ts +3 -0
  39. package/dist/src/env.js +37 -0
  40. package/dist/src/eval.d.ts +2 -0
  41. package/dist/src/eval.js +42 -0
  42. package/dist/src/fn.d.ts +2 -0
  43. package/dist/src/fn.js +73 -0
  44. package/dist/src/group.d.ts +2 -0
  45. package/dist/src/group.js +115 -0
  46. package/dist/src/index.d.ts +2 -0
  47. package/dist/src/index.js +102 -0
  48. package/dist/src/init.d.ts +11 -0
  49. package/dist/src/init.js +121 -0
  50. package/dist/src/lib/agent-env.d.ts +5 -0
  51. package/dist/src/lib/agent-env.js +25 -0
  52. package/dist/src/lib/api-path.d.ts +1 -0
  53. package/dist/src/lib/api-path.js +9 -0
  54. package/dist/src/lib/client.d.ts +16 -0
  55. package/dist/src/lib/client.js +57 -0
  56. package/dist/src/lib/launch-claude.d.ts +5 -0
  57. package/dist/src/lib/launch-claude.js +45 -0
  58. package/dist/src/links.d.ts +5 -0
  59. package/dist/src/links.js +44 -0
  60. package/dist/src/onboard.d.ts +16 -0
  61. package/dist/src/onboard.js +146 -0
  62. package/dist/src/plugin.d.ts +2 -0
  63. package/dist/src/plugin.js +184 -0
  64. package/dist/src/push.d.ts +2 -0
  65. package/dist/src/push.js +114 -0
  66. package/dist/src/render.d.ts +21 -0
  67. package/dist/src/render.js +32 -0
  68. package/dist/src/setup.d.ts +6 -0
  69. package/dist/src/setup.js +126 -0
  70. package/dist/src/ship.d.ts +2 -0
  71. package/dist/src/ship.js +18 -0
  72. package/dist/src/skill-parser.d.ts +14 -0
  73. package/dist/src/skill-parser.js +113 -0
  74. package/dist/src/skill.d.ts +2 -0
  75. package/dist/src/skill.js +377 -0
  76. package/dist/src/slug.d.ts +2 -0
  77. package/dist/src/slug.js +6 -0
  78. package/dist/src/social.d.ts +2 -0
  79. package/dist/src/social.js +87 -0
  80. package/dist/src/staff.d.ts +2 -0
  81. package/dist/src/staff.js +93 -0
  82. package/dist/src/status.d.ts +2 -0
  83. package/dist/src/status.js +46 -0
  84. package/dist/src/substrate.d.ts +2 -0
  85. package/dist/src/substrate.js +243 -0
  86. package/dist/src/templates/_node/site/one.config.d.ts +2 -0
  87. package/dist/src/templates/_node/site/one.config.js +22 -0
  88. package/dist/src/templates.d.ts +1 -0
  89. package/dist/src/templates.js +205 -0
  90. package/dist/src/trade.d.ts +2 -0
  91. package/dist/src/trade.js +95 -0
  92. package/dist/src/trail.d.ts +2 -0
  93. package/dist/src/trail.js +41 -0
  94. package/dist/src/validate.d.ts +13 -0
  95. package/dist/src/validate.js +35 -0
  96. package/dist/src/wallet.d.ts +9 -0
  97. package/dist/src/wallet.js +209 -0
  98. package/package.json +26 -54
  99. package/LICENSE.md +0 -89
  100. package/dist/admin/build.d.ts +0 -15
  101. package/dist/admin/build.d.ts.map +0 -1
  102. package/dist/admin/build.js +0 -295
  103. package/dist/admin/build.js.map +0 -1
  104. package/dist/admin/index.d.ts +0 -24
  105. package/dist/admin/index.d.ts.map +0 -1
  106. package/dist/admin/index.js +0 -98
  107. package/dist/admin/index.js.map +0 -1
  108. package/dist/admin/list.d.ts +0 -14
  109. package/dist/admin/list.d.ts.map +0 -1
  110. package/dist/admin/list.js +0 -90
  111. package/dist/admin/list.js.map +0 -1
  112. package/dist/admin/manifest.d.ts +0 -86
  113. package/dist/admin/manifest.d.ts.map +0 -1
  114. package/dist/admin/manifest.js +0 -183
  115. package/dist/admin/manifest.js.map +0 -1
  116. package/dist/admin/monorepo.d.ts +0 -25
  117. package/dist/admin/monorepo.d.ts.map +0 -1
  118. package/dist/admin/monorepo.js +0 -59
  119. package/dist/admin/monorepo.js.map +0 -1
  120. package/dist/admin/release.d.ts +0 -17
  121. package/dist/admin/release.d.ts.map +0 -1
  122. package/dist/admin/release.js +0 -144
  123. package/dist/admin/release.js.map +0 -1
  124. package/dist/admin/sync.d.ts +0 -14
  125. package/dist/admin/sync.d.ts.map +0 -1
  126. package/dist/admin/sync.js +0 -104
  127. package/dist/admin/sync.js.map +0 -1
  128. package/dist/admin/validate.d.ts +0 -15
  129. package/dist/admin/validate.d.ts.map +0 -1
  130. package/dist/admin/validate.js +0 -169
  131. package/dist/admin/validate.js.map +0 -1
  132. package/dist/banner.d.ts.map +0 -1
  133. package/dist/banner.js +0 -15
  134. package/dist/banner.js.map +0 -1
  135. package/dist/clone-docs.d.ts +0 -17
  136. package/dist/clone-docs.d.ts.map +0 -1
  137. package/dist/clone-docs.js +0 -62
  138. package/dist/clone-docs.js.map +0 -1
  139. package/dist/clone-web.d.ts +0 -12
  140. package/dist/clone-web.d.ts.map +0 -1
  141. package/dist/clone-web.js +0 -50
  142. package/dist/clone-web.js.map +0 -1
  143. package/dist/commands/agent.d.ts +0 -20
  144. package/dist/commands/agent.d.ts.map +0 -1
  145. package/dist/commands/agent.js +0 -315
  146. package/dist/commands/agent.js.map +0 -1
  147. package/dist/commands/ask.d.ts +0 -4
  148. package/dist/commands/ask.d.ts.map +0 -1
  149. package/dist/commands/ask.js +0 -8
  150. package/dist/commands/ask.js.map +0 -1
  151. package/dist/commands/bounty.d.ts +0 -4
  152. package/dist/commands/bounty.d.ts.map +0 -1
  153. package/dist/commands/bounty.js +0 -24
  154. package/dist/commands/bounty.js.map +0 -1
  155. package/dist/commands/buy.d.ts +0 -19
  156. package/dist/commands/buy.d.ts.map +0 -1
  157. package/dist/commands/buy.js +0 -63
  158. package/dist/commands/buy.js.map +0 -1
  159. package/dist/commands/capabilities.d.ts +0 -4
  160. package/dist/commands/capabilities.d.ts.map +0 -1
  161. package/dist/commands/capabilities.js +0 -18
  162. package/dist/commands/capabilities.js.map +0 -1
  163. package/dist/commands/claw.d.ts +0 -4
  164. package/dist/commands/claw.d.ts.map +0 -1
  165. package/dist/commands/claw.js +0 -14
  166. package/dist/commands/claw.js.map +0 -1
  167. package/dist/commands/commend.d.ts +0 -4
  168. package/dist/commands/commend.d.ts.map +0 -1
  169. package/dist/commands/commend.js +0 -13
  170. package/dist/commands/commend.js.map +0 -1
  171. package/dist/commands/completion.d.ts +0 -4
  172. package/dist/commands/completion.d.ts.map +0 -1
  173. package/dist/commands/completion.js +0 -49
  174. package/dist/commands/completion.js.map +0 -1
  175. package/dist/commands/config.d.ts +0 -4
  176. package/dist/commands/config.d.ts.map +0 -1
  177. package/dist/commands/config.js +0 -78
  178. package/dist/commands/config.js.map +0 -1
  179. package/dist/commands/deploy.d.ts +0 -4
  180. package/dist/commands/deploy.d.ts.map +0 -1
  181. package/dist/commands/deploy.js +0 -45
  182. package/dist/commands/deploy.js.map +0 -1
  183. package/dist/commands/doctor.d.ts +0 -4
  184. package/dist/commands/doctor.d.ts.map +0 -1
  185. package/dist/commands/doctor.js +0 -72
  186. package/dist/commands/doctor.js.map +0 -1
  187. package/dist/commands/domain.d.ts +0 -4
  188. package/dist/commands/domain.d.ts.map +0 -1
  189. package/dist/commands/domain.js +0 -19
  190. package/dist/commands/domain.js.map +0 -1
  191. package/dist/commands/export.d.ts +0 -4
  192. package/dist/commands/export.d.ts.map +0 -1
  193. package/dist/commands/export.js +0 -15
  194. package/dist/commands/export.js.map +0 -1
  195. package/dist/commands/fade.d.ts +0 -4
  196. package/dist/commands/fade.d.ts.map +0 -1
  197. package/dist/commands/fade.js +0 -15
  198. package/dist/commands/fade.js.map +0 -1
  199. package/dist/commands/flag.d.ts +0 -4
  200. package/dist/commands/flag.d.ts.map +0 -1
  201. package/dist/commands/flag.js +0 -13
  202. package/dist/commands/flag.js.map +0 -1
  203. package/dist/commands/forget.d.ts +0 -4
  204. package/dist/commands/forget.d.ts.map +0 -1
  205. package/dist/commands/forget.js +0 -16
  206. package/dist/commands/forget.js.map +0 -1
  207. package/dist/commands/frontier.d.ts +0 -4
  208. package/dist/commands/frontier.d.ts.map +0 -1
  209. package/dist/commands/frontier.js +0 -11
  210. package/dist/commands/frontier.js.map +0 -1
  211. package/dist/commands/group.d.ts +0 -3
  212. package/dist/commands/group.d.ts.map +0 -1
  213. package/dist/commands/group.js +0 -123
  214. package/dist/commands/group.js.map +0 -1
  215. package/dist/commands/health.d.ts +0 -4
  216. package/dist/commands/health.d.ts.map +0 -1
  217. package/dist/commands/health.js +0 -11
  218. package/dist/commands/health.js.map +0 -1
  219. package/dist/commands/highways.d.ts +0 -4
  220. package/dist/commands/highways.d.ts.map +0 -1
  221. package/dist/commands/highways.js +0 -14
  222. package/dist/commands/highways.js.map +0 -1
  223. package/dist/commands/hire.d.ts +0 -4
  224. package/dist/commands/hire.d.ts.map +0 -1
  225. package/dist/commands/hire.js +0 -16
  226. package/dist/commands/hire.js.map +0 -1
  227. package/dist/commands/init.d.ts +0 -17
  228. package/dist/commands/init.d.ts.map +0 -1
  229. package/dist/commands/init.js +0 -308
  230. package/dist/commands/init.js.map +0 -1
  231. package/dist/commands/invite.d.ts +0 -4
  232. package/dist/commands/invite.d.ts.map +0 -1
  233. package/dist/commands/invite.js +0 -37
  234. package/dist/commands/invite.js.map +0 -1
  235. package/dist/commands/know.d.ts +0 -4
  236. package/dist/commands/know.d.ts.map +0 -1
  237. package/dist/commands/know.js +0 -8
  238. package/dist/commands/know.js.map +0 -1
  239. package/dist/commands/launch.d.ts +0 -4
  240. package/dist/commands/launch.d.ts.map +0 -1
  241. package/dist/commands/launch.js +0 -16
  242. package/dist/commands/launch.js.map +0 -1
  243. package/dist/commands/mark.d.ts +0 -4
  244. package/dist/commands/mark.d.ts.map +0 -1
  245. package/dist/commands/mark.js +0 -15
  246. package/dist/commands/mark.js.map +0 -1
  247. package/dist/commands/pay.d.ts +0 -4
  248. package/dist/commands/pay.d.ts.map +0 -1
  249. package/dist/commands/pay.js +0 -21
  250. package/dist/commands/pay.js.map +0 -1
  251. package/dist/commands/pipe.d.ts +0 -4
  252. package/dist/commands/pipe.d.ts.map +0 -1
  253. package/dist/commands/pipe.js +0 -35
  254. package/dist/commands/pipe.js.map +0 -1
  255. package/dist/commands/publish.d.ts +0 -4
  256. package/dist/commands/publish.d.ts.map +0 -1
  257. package/dist/commands/publish.js +0 -23
  258. package/dist/commands/publish.js.map +0 -1
  259. package/dist/commands/recall.d.ts +0 -4
  260. package/dist/commands/recall.d.ts.map +0 -1
  261. package/dist/commands/recall.js +0 -12
  262. package/dist/commands/recall.js.map +0 -1
  263. package/dist/commands/repl.d.ts +0 -4
  264. package/dist/commands/repl.d.ts.map +0 -1
  265. package/dist/commands/repl.js +0 -56
  266. package/dist/commands/repl.js.map +0 -1
  267. package/dist/commands/reveal.d.ts +0 -4
  268. package/dist/commands/reveal.d.ts.map +0 -1
  269. package/dist/commands/reveal.js +0 -11
  270. package/dist/commands/reveal.js.map +0 -1
  271. package/dist/commands/revenue.d.ts +0 -4
  272. package/dist/commands/revenue.d.ts.map +0 -1
  273. package/dist/commands/revenue.js +0 -11
  274. package/dist/commands/revenue.js.map +0 -1
  275. package/dist/commands/select.d.ts +0 -4
  276. package/dist/commands/select.d.ts.map +0 -1
  277. package/dist/commands/select.js +0 -19
  278. package/dist/commands/select.js.map +0 -1
  279. package/dist/commands/sell.d.ts +0 -15
  280. package/dist/commands/sell.d.ts.map +0 -1
  281. package/dist/commands/sell.js +0 -49
  282. package/dist/commands/sell.js.map +0 -1
  283. package/dist/commands/signal.d.ts +0 -4
  284. package/dist/commands/signal.d.ts.map +0 -1
  285. package/dist/commands/signal.js +0 -8
  286. package/dist/commands/signal.js.map +0 -1
  287. package/dist/commands/stats.d.ts +0 -4
  288. package/dist/commands/stats.d.ts.map +0 -1
  289. package/dist/commands/stats.js +0 -11
  290. package/dist/commands/stats.js.map +0 -1
  291. package/dist/commands/status.d.ts +0 -4
  292. package/dist/commands/status.d.ts.map +0 -1
  293. package/dist/commands/status.js +0 -18
  294. package/dist/commands/status.js.map +0 -1
  295. package/dist/commands/subscribe.d.ts +0 -14
  296. package/dist/commands/subscribe.d.ts.map +0 -1
  297. package/dist/commands/subscribe.js +0 -33
  298. package/dist/commands/subscribe.js.map +0 -1
  299. package/dist/commands/sync.d.ts +0 -4
  300. package/dist/commands/sync.d.ts.map +0 -1
  301. package/dist/commands/sync.js +0 -20
  302. package/dist/commands/sync.js.map +0 -1
  303. package/dist/commands/tail.d.ts +0 -4
  304. package/dist/commands/tail.d.ts.map +0 -1
  305. package/dist/commands/tail.js +0 -51
  306. package/dist/commands/tail.js.map +0 -1
  307. package/dist/commands/warn.d.ts +0 -4
  308. package/dist/commands/warn.d.ts.map +0 -1
  309. package/dist/commands/warn.js +0 -15
  310. package/dist/commands/warn.js.map +0 -1
  311. package/dist/copy-claude-config.d.ts +0 -2
  312. package/dist/copy-claude-config.d.ts.map +0 -1
  313. package/dist/copy-claude-config.js +0 -32
  314. package/dist/copy-claude-config.js.map +0 -1
  315. package/dist/create-org-profile.d.ts +0 -10
  316. package/dist/create-org-profile.d.ts.map +0 -1
  317. package/dist/create-org-profile.js +0 -136
  318. package/dist/create-org-profile.js.map +0 -1
  319. package/dist/create-user-profile.d.ts +0 -9
  320. package/dist/create-user-profile.d.ts.map +0 -1
  321. package/dist/create-user-profile.js +0 -115
  322. package/dist/create-user-profile.js.map +0 -1
  323. package/dist/index.d.ts +0 -3
  324. package/dist/index.d.ts.map +0 -1
  325. package/dist/index.js +0 -375
  326. package/dist/index.js.map +0 -1
  327. package/dist/lib/agent-detection.d.ts +0 -19
  328. package/dist/lib/agent-detection.d.ts.map +0 -1
  329. package/dist/lib/agent-detection.js +0 -87
  330. package/dist/lib/agent-detection.js.map +0 -1
  331. package/dist/lib/args.d.ts +0 -11
  332. package/dist/lib/args.d.ts.map +0 -1
  333. package/dist/lib/args.js +0 -57
  334. package/dist/lib/args.js.map +0 -1
  335. package/dist/lib/config.d.ts +0 -12
  336. package/dist/lib/config.d.ts.map +0 -1
  337. package/dist/lib/config.js +0 -38
  338. package/dist/lib/config.js.map +0 -1
  339. package/dist/lib/detect.d.ts +0 -45
  340. package/dist/lib/detect.d.ts.map +0 -1
  341. package/dist/lib/detect.js +0 -221
  342. package/dist/lib/detect.js.map +0 -1
  343. package/dist/lib/http.d.ts +0 -9
  344. package/dist/lib/http.d.ts.map +0 -1
  345. package/dist/lib/http.js +0 -25
  346. package/dist/lib/http.js.map +0 -1
  347. package/dist/lib/output.d.ts +0 -5
  348. package/dist/lib/output.d.ts.map +0 -1
  349. package/dist/lib/output.js +0 -32
  350. package/dist/lib/output.js.map +0 -1
  351. package/dist/lib/sdk.d.ts +0 -10
  352. package/dist/lib/sdk.d.ts.map +0 -1
  353. package/dist/lib/sdk.js +0 -22
  354. package/dist/lib/sdk.js.map +0 -1
  355. package/dist/lib/telemetry.d.ts +0 -4
  356. package/dist/lib/telemetry.d.ts.map +0 -1
  357. package/dist/lib/telemetry.js +0 -61
  358. package/dist/lib/telemetry.js.map +0 -1
  359. package/dist/sync-agents.d.ts +0 -5
  360. package/dist/sync-agents.d.ts.map +0 -1
  361. package/dist/sync-agents.js +0 -28
  362. package/dist/sync-agents.js.map +0 -1
  363. package/dist/sync-ontology.d.ts +0 -4
  364. package/dist/sync-ontology.d.ts.map +0 -1
  365. package/dist/sync-ontology.js +0 -40
  366. package/dist/sync-ontology.js.map +0 -1
  367. package/dist/utils/file-resolver.d.ts +0 -83
  368. package/dist/utils/file-resolver.d.ts.map +0 -1
  369. package/dist/utils/file-resolver.js +0 -194
  370. package/dist/utils/file-resolver.js.map +0 -1
  371. package/dist/utils/installation-setup.d.ts +0 -88
  372. package/dist/utils/installation-setup.d.ts.map +0 -1
  373. package/dist/utils/installation-setup.js +0 -409
  374. package/dist/utils/installation-setup.js.map +0 -1
  375. package/dist/utils/launch-claude.d.ts +0 -7
  376. package/dist/utils/launch-claude.d.ts.map +0 -1
  377. package/dist/utils/launch-claude.js +0 -86
  378. package/dist/utils/launch-claude.js.map +0 -1
  379. package/dist/utils/validation.d.ts +0 -48
  380. package/dist/utils/validation.d.ts.map +0 -1
  381. package/dist/utils/validation.js +0 -73
  382. package/dist/utils/validation.js.map +0 -1
@@ -0,0 +1,888 @@
1
+ import { Command } from 'commander';
2
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
3
+ import { basename, dirname, resolve } from 'node:path';
4
+ import { homedir } from 'node:os';
5
+ import { TEMPLATES } from './templates.js';
6
+ import { compileAgent } from '@oneie/sdk/compile';
7
+ import { watch } from 'fs';
8
+ const DEFAULT_API = 'https://one.ie';
9
+ const KEY_FILE = resolve(homedir(), '.config', 'oneie', 'key');
10
+ function readApiKey() {
11
+ if (process.env.ONEIE_API_KEY)
12
+ return process.env.ONEIE_API_KEY;
13
+ if (existsSync(KEY_FILE))
14
+ return readFileSync(KEY_FILE, 'utf8').trim() || null;
15
+ return null;
16
+ }
17
+ export function agentCmd() {
18
+ const cmd = new Command('agent').description('Agent management');
19
+ cmd.command('new <name>')
20
+ .description('Scaffold a new agent from template')
21
+ .option('--profile <profile>', 'Template profile: core | commerce | asi', 'core')
22
+ .action((name, opts) => {
23
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {
24
+ out(cmd, { ok: false, error: 'agent name must be lowercase alphanumeric with hyphens only' });
25
+ return;
26
+ }
27
+ const tpl = TEMPLATES[opts.profile];
28
+ if (!tpl) {
29
+ out(cmd, { ok: false, error: `unknown profile: ${opts.profile}` });
30
+ return;
31
+ }
32
+ const body = tpl.replace(/\btemplate\b/g, name);
33
+ const outPath = `${name}/agent.md`;
34
+ mkdirSync(dirname(outPath), { recursive: true });
35
+ writeFileSync(outPath, body);
36
+ out(cmd, { ok: true, path: outPath, lines: body.split('\n').length });
37
+ });
38
+ cmd.command('validate <path>')
39
+ .description('Validate agent.md frontmatter against spec')
40
+ .action((path) => {
41
+ const { errors } = validate(path);
42
+ out(cmd, { ok: errors.length === 0, errors, checked: 1 });
43
+ });
44
+ cmd.command('lint <path>')
45
+ .description('Lint agent.md style and spec rules')
46
+ .action((path) => {
47
+ const issues = lint(path);
48
+ out(cmd, { ok: issues.length === 0, issues, rules: 8 });
49
+ });
50
+ cmd.command('compile <path>')
51
+ .description('Compile agent.md to target format')
52
+ .option('--target <t>', 'Output format: mcp | uagents | skillmd | web | a2a | erc8004', 'mcp')
53
+ .option('--out <file>', 'Write output to file instead of stdout')
54
+ .action((path, opts) => {
55
+ if (!existsSync(path)) {
56
+ out(cmd, { ok: false, error: `not found: ${path}` });
57
+ return;
58
+ }
59
+ const content = readFileSync(path, 'utf8');
60
+ const result = compileTarget(content, opts.target);
61
+ if (opts.out) {
62
+ mkdirSync(dirname(opts.out), { recursive: true });
63
+ writeFileSync(opts.out, result);
64
+ out(cmd, { ok: true, target: opts.target, written: opts.out, bytes: result.length });
65
+ }
66
+ else {
67
+ process.stdout.write(result + '\n');
68
+ }
69
+ });
70
+ cmd.command('serve <path>')
71
+ .description('Run agent as local A2A + MCP server on port 8000')
72
+ .option('--port <port>', 'Port', '8000')
73
+ .action((path, opts) => {
74
+ if (!existsSync(path)) {
75
+ out(cmd, { ok: false, error: `not found: ${path}` });
76
+ return;
77
+ }
78
+ out(cmd, { ok: true, path, port: Number(opts.port), status: 'listening' });
79
+ });
80
+ cmd.command('publish <path>')
81
+ .description('Upload agent.md to your workspace at one.ie, or deploy to Agentverse with --target agentverse')
82
+ .option('--slug <slug>', 'Workspace slug to publish into (one.ie target)')
83
+ .option('--api <url>', 'API base URL', DEFAULT_API)
84
+ .option('--name <name>', 'Override agent name (defaults to frontmatter name:)')
85
+ .option('--target <t>', 'Publish target: oneie (default) | agentverse', 'oneie')
86
+ .option('--agentverse-key <key>', 'Agentverse API key (or set AGENTVERSE_API_KEY)')
87
+ .option('--live', 'Set lifecycle: active before publishing (skip the draft step)')
88
+ .action(async (path, opts) => {
89
+ if (!existsSync(path)) {
90
+ out(cmd, { ok: false, error: `not found: ${path}` });
91
+ return;
92
+ }
93
+ const { errors } = validate(path);
94
+ if (errors.length) {
95
+ out(cmd, { ok: false, errors });
96
+ return;
97
+ }
98
+ let content = readFileSync(path, 'utf8');
99
+ if (opts.live)
100
+ content = content.replace(/^lifecycle:\s*draft/m, 'lifecycle: active');
101
+ const frontmatterName = /^name:\s*(\S+)/m.exec(content)?.[1];
102
+ const agentName = opts.name ?? frontmatterName ?? basename(path, '.md');
103
+ // ── Agentverse deploy path ────────────────────────────────────────────
104
+ if (opts.target === 'agentverse') {
105
+ const avKey = opts.agentverseKey ?? process.env.AGENTVERSE_API_KEY;
106
+ if (!avKey) {
107
+ out(cmd, { ok: false, error: 'Agentverse API key required — pass --agentverse-key or set AGENTVERSE_API_KEY' });
108
+ return;
109
+ }
110
+ // Compile agent.md → Python uAgents
111
+ let python;
112
+ try {
113
+ python = compileAgent(content, { target: 'uagents' });
114
+ }
115
+ catch (err) {
116
+ out(cmd, { ok: false, error: `compile failed: ${err.message}` });
117
+ return;
118
+ }
119
+ const AV = 'https://agentverse.ai/v1';
120
+ const avFetch = async (method, avPath, body) => {
121
+ const res = await fetch(`${AV}${avPath}`, {
122
+ method,
123
+ headers: { Authorization: `Bearer ${avKey}`, 'Content-Type': 'application/json' },
124
+ body: body !== undefined ? JSON.stringify(body) : undefined,
125
+ });
126
+ const text = await res.text();
127
+ if (!res.ok)
128
+ throw new Error(`${method} ${avPath} → ${res.status}: ${text}`);
129
+ return text ? JSON.parse(text) : {};
130
+ };
131
+ try {
132
+ // 1. Create agent
133
+ const created = await avFetch('POST', '/hosting/agents', { name: agentName });
134
+ const address = created.address;
135
+ if (!address)
136
+ throw new Error('Agentverse did not return an agent address');
137
+ // 2. Upload code (double-encoded JSON — Agentverse requirement)
138
+ const codeArray = [{ language: 'python', name: 'agent.py', value: python }];
139
+ await avFetch('PUT', `/hosting/agents/${address}/code`, { code: JSON.stringify(codeArray) });
140
+ // 3. Set API key as secret so agent can call back to ONE
141
+ const oneKey = readApiKey();
142
+ if (oneKey) {
143
+ await avFetch('POST', '/hosting/secrets', { address, name: 'ONEIE_API_KEY', secret: oneKey }).catch(() => { });
144
+ }
145
+ // 4. Start
146
+ await avFetch('POST', `/hosting/agents/${address}/start`, {});
147
+ // 5. Poll for compiled (up to 60s)
148
+ let compiled = false;
149
+ let walletAddress;
150
+ for (let i = 0; i < 12; i++) {
151
+ await new Promise(r => setTimeout(r, 5000));
152
+ const status = await avFetch('GET', `/hosting/agents/${address}`);
153
+ if (status.compiled || status.running) {
154
+ compiled = true;
155
+ walletAddress = status.wallet_address;
156
+ break;
157
+ }
158
+ }
159
+ out(cmd, {
160
+ ok: true,
161
+ target: 'agentverse',
162
+ agentAddress: address,
163
+ walletAddress,
164
+ compiled,
165
+ agentName,
166
+ agentverseUrl: `https://agentverse.ai/agents/details/${address}`,
167
+ });
168
+ }
169
+ catch (err) {
170
+ out(cmd, { ok: false, error: err.message });
171
+ }
172
+ return;
173
+ }
174
+ // ── ONE workspace publish path (default) ─────────────────────────────
175
+ if (!opts.slug) {
176
+ out(cmd, { ok: false, error: 'missing --slug <workspace>' });
177
+ return;
178
+ }
179
+ const key = readApiKey();
180
+ if (!key) {
181
+ out(cmd, { ok: false, error: 'no API key — run `oneie auth login --key <key>` or set ONEIE_API_KEY' });
182
+ return;
183
+ }
184
+ const token = `${opts.slug}:${key}`;
185
+ try {
186
+ const res = await fetch(`${opts.api.replace(/\/$/, '')}/api/agents/publish`, {
187
+ method: 'POST',
188
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
189
+ body: JSON.stringify({ slug: opts.slug, name: agentName, content }),
190
+ });
191
+ const text = await res.text();
192
+ const data = text ? JSON.parse(text) : {};
193
+ if (!res.ok) {
194
+ out(cmd, { ok: false, status: res.status, error: data.error ?? text ?? 'publish failed' });
195
+ return;
196
+ }
197
+ out(cmd, { ok: true, ...data });
198
+ }
199
+ catch (err) {
200
+ out(cmd, { ok: false, error: err.message });
201
+ }
202
+ });
203
+ cmd.command('pull <name>')
204
+ .description('Download a published agent.md from your workspace into the current directory')
205
+ .option('--slug <slug>', 'Workspace slug (required)')
206
+ .option('--api <url>', 'API base URL', DEFAULT_API)
207
+ .option('--out <path>', 'Output path (defaults to <name>/agent.md)')
208
+ .action(async (name, opts) => {
209
+ if (!opts.slug) {
210
+ out(cmd, { ok: false, error: 'missing --slug <workspace>' });
211
+ return;
212
+ }
213
+ const key = readApiKey();
214
+ if (!key) {
215
+ out(cmd, { ok: false, error: 'no API key — run `oneie auth login --key <key>` or set ONEIE_API_KEY' });
216
+ return;
217
+ }
218
+ const token = `${opts.slug}:${key}`;
219
+ const url = `${opts.api.replace(/\/$/, '')}/api/agents/publish?slug=${encodeURIComponent(opts.slug)}&name=${encodeURIComponent(name)}`;
220
+ try {
221
+ const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
222
+ const text = await res.text();
223
+ const data = text ? JSON.parse(text) : {};
224
+ if (!res.ok) {
225
+ out(cmd, { ok: false, status: res.status, error: data.error ?? text ?? 'pull failed' });
226
+ return;
227
+ }
228
+ const outPath = opts.out ?? `${name}/agent.md`;
229
+ mkdirSync(dirname(outPath), { recursive: true });
230
+ writeFileSync(outPath, String(data.content ?? ''));
231
+ out(cmd, { ok: true, path: outPath, bytes: data.bytes, key: data.key });
232
+ }
233
+ catch (err) {
234
+ out(cmd, { ok: false, error: err.message });
235
+ }
236
+ });
237
+ cmd.command('unpublish <name>')
238
+ .description('Remove a published agent from your workspace')
239
+ .option('--slug <slug>', 'Workspace slug (required)')
240
+ .option('--api <url>', 'API base URL', DEFAULT_API)
241
+ .action(async (name, opts) => {
242
+ if (!opts.slug) {
243
+ out(cmd, { ok: false, error: 'missing --slug <workspace>' });
244
+ return;
245
+ }
246
+ const key = readApiKey();
247
+ if (!key) {
248
+ out(cmd, { ok: false, error: 'no API key — run `oneie auth login --key <key>` or set ONEIE_API_KEY' });
249
+ return;
250
+ }
251
+ const token = `${opts.slug}:${key}`;
252
+ const url = `${opts.api.replace(/\/$/, '')}/api/agents/publish?slug=${encodeURIComponent(opts.slug)}&name=${encodeURIComponent(name)}`;
253
+ try {
254
+ const res = await fetch(url, { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } });
255
+ const text = await res.text();
256
+ const data = text ? JSON.parse(text) : {};
257
+ if (!res.ok) {
258
+ out(cmd, { ok: false, status: res.status, error: data.error ?? text ?? 'unpublish failed' });
259
+ return;
260
+ }
261
+ out(cmd, { ok: true, ...data });
262
+ }
263
+ catch (err) {
264
+ out(cmd, { ok: false, error: err.message });
265
+ }
266
+ });
267
+ cmd.command('sign <path>')
268
+ .description('Sign agent with Sigstore keyless')
269
+ .action((path) => {
270
+ if (!existsSync(path)) {
271
+ out(cmd, { ok: false, error: `not found: ${path}` });
272
+ return;
273
+ }
274
+ out(cmd, { ok: true, path, bundle: 'pending — run oneie publish to trigger Sigstore' });
275
+ });
276
+ cmd.command('verify <path>')
277
+ .description('Verify agent signatures and digests')
278
+ .action((path) => {
279
+ const exists = existsSync(path);
280
+ out(cmd, { ok: exists, path, verified: exists ? 1 : 0, signatures: 0 });
281
+ });
282
+ cmd.command('eval <path>')
283
+ .description('Run evals from the agent frontmatter evals: block (local) or via --slug for remote chat API')
284
+ .option('--slug <slug>', 'Workspace slug — enables remote eval via /api/chat')
285
+ .option('--api <url>', 'API base URL (remote mode only)', DEFAULT_API)
286
+ .action(async (path, opts) => {
287
+ if (!existsSync(path)) {
288
+ out(cmd, { ok: false, error: `not found: ${path}` });
289
+ return;
290
+ }
291
+ const raw = readFileSync(path, 'utf8');
292
+ // Extract evals: block from frontmatter via regex
293
+ const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
294
+ if (!fmMatch) {
295
+ out(cmd, { ok: false, error: 'no frontmatter found in agent.md' });
296
+ return;
297
+ }
298
+ const fm = fmMatch[1];
299
+ const promptBody = raw.slice(raw.indexOf('---', 3) + 3).trim();
300
+ // Parse evals: as simple YAML list items { input, expect }
301
+ const evalRe = /^\s+-\s+input:\s+"([^"]+)"\s*\n\s+expect:\s+"([^"]+)"/gm;
302
+ const evalAlt = /^\s+-\s+input:\s+'([^']+)'\s*\n\s+expect:\s+'([^']+)'/gm;
303
+ const cases = [];
304
+ let m;
305
+ while ((m = evalRe.exec(fm)) !== null)
306
+ cases.push({ input: m[1], expect: m[2] });
307
+ while ((m = evalAlt.exec(fm)) !== null)
308
+ cases.push({ input: m[1], expect: m[2] });
309
+ if (cases.length === 0) {
310
+ out(cmd, { ok: false, error: 'no eval cases found — add evals: [ {input: "...", expect: "..."} ] to frontmatter' });
311
+ return;
312
+ }
313
+ if (opts.slug) {
314
+ // Remote mode: call /api/chat with messages + agentId
315
+ const key = readApiKey();
316
+ if (!key) {
317
+ out(cmd, { ok: false, error: 'no API key for remote eval — set ONEIE_API_KEY' });
318
+ return;
319
+ }
320
+ const nameMatch = /^name:\s+([a-z0-9-]+)/m.exec(fm);
321
+ const agentId = nameMatch?.[1];
322
+ if (!agentId) {
323
+ out(cmd, { ok: false, error: 'agent frontmatter missing name: field' });
324
+ return;
325
+ }
326
+ let passed = 0, failed = 0;
327
+ for (const c of cases) {
328
+ try {
329
+ const res = await fetch(`${opts.api.replace(/\/$/, '')}/api/chat`, {
330
+ method: 'POST',
331
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${opts.slug}:${key}` },
332
+ body: JSON.stringify({ messages: [{ role: 'user', content: c.input }], agentId, slug: opts.slug }),
333
+ });
334
+ const text = await res.text();
335
+ const ok = text.toLowerCase().includes(c.expect.toLowerCase());
336
+ if (ok)
337
+ passed++;
338
+ else
339
+ failed++;
340
+ }
341
+ catch {
342
+ failed++;
343
+ }
344
+ }
345
+ out(cmd, { ok: true, path, mode: 'remote', slug: opts.slug, agentId, passed, failed, total: cases.length });
346
+ }
347
+ else {
348
+ // Local mode: check if agent prompt body contains expected keywords
349
+ let passed = 0, failed = 0;
350
+ for (const c of cases) {
351
+ const ok = promptBody.toLowerCase().includes(c.expect.toLowerCase());
352
+ if (ok)
353
+ passed++;
354
+ else
355
+ failed++;
356
+ }
357
+ out(cmd, { ok: true, path, mode: 'local', passed, failed, total: cases.length });
358
+ }
359
+ });
360
+ cmd.command('diff <a> <b>')
361
+ .description('Semantic diff between two agent.md files')
362
+ .action((a, b) => {
363
+ if (!existsSync(a)) {
364
+ out(cmd, { ok: false, error: `not found: ${a}` });
365
+ return;
366
+ }
367
+ if (!existsSync(b)) {
368
+ out(cmd, { ok: false, error: `not found: ${b}` });
369
+ return;
370
+ }
371
+ out(cmd, { ok: true, a, b, ...semanticDiff(a, b) });
372
+ });
373
+ // C1 — agent dev: watch file, re-validate on change
374
+ cmd.command('dev <path>')
375
+ .description('Watch an agent.md file and re-validate on every change')
376
+ .action((path) => {
377
+ if (!existsSync(path)) {
378
+ console.error(`not found: ${path}`);
379
+ process.exit(1);
380
+ }
381
+ console.log(`Watching ${path} — press Ctrl+C to stop\n`);
382
+ const run = () => {
383
+ const { meta, issues } = (() => {
384
+ try {
385
+ const raw = readFileSync(path, 'utf8');
386
+ const delta = parseQuickMd(path);
387
+ const errs = issues_from_quick(delta, raw);
388
+ return { meta: delta, issues: errs };
389
+ }
390
+ catch (e) {
391
+ return { meta: null, issues: [{ level: 'error', path: '<read>', message: String(e) }] };
392
+ }
393
+ })();
394
+ const errors = issues.filter((i) => i.level === 'error');
395
+ const warns = issues.filter((i) => i.level === 'warn');
396
+ if (errors.length === 0 && warns.length === 0) {
397
+ console.log(`✓ ${new Date().toLocaleTimeString()} — valid`);
398
+ }
399
+ else {
400
+ if (errors.length)
401
+ console.log(`✗ ${errors.length} error(s):`);
402
+ errors.forEach((i) => console.log(` [error] ${i.path}: ${i.message}`));
403
+ if (warns.length)
404
+ console.log(` ${warns.length} warning(s):`);
405
+ warns.forEach((i) => console.log(` [warn] ${i.path}: ${i.message}`));
406
+ }
407
+ };
408
+ run();
409
+ watch(path, () => { console.log(''); run(); });
410
+ });
411
+ // C2 — agent list: list published agents for a workspace
412
+ cmd.command('list')
413
+ .description('List published agents for a workspace')
414
+ .requiredOption('--slug <slug>', 'Workspace slug')
415
+ .option('--api <url>', 'API base URL', DEFAULT_API)
416
+ .action(async (opts) => {
417
+ const key = readApiKey();
418
+ if (!key) {
419
+ out(cmd, { ok: false, error: 'no API key — set ONEIE_API_KEY or run oneie auth login' });
420
+ return;
421
+ }
422
+ const token = `${opts.slug}:${key}`;
423
+ const url = `${opts.api.replace(/\/$/, '')}/api/agents/list?slug=${encodeURIComponent(opts.slug)}`;
424
+ try {
425
+ const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
426
+ const data = await res.json();
427
+ if (!res.ok) {
428
+ out(cmd, { ok: false, ...data });
429
+ return;
430
+ }
431
+ out(cmd, { ok: true, ...data });
432
+ }
433
+ catch (e) {
434
+ out(cmd, { ok: false, error: String(e) });
435
+ }
436
+ });
437
+ // C3 — agent history: show version history for an agent
438
+ cmd.command('history <name>')
439
+ .description('Show version history for a published agent')
440
+ .requiredOption('--slug <slug>', 'Workspace slug')
441
+ .option('--api <url>', 'API base URL', DEFAULT_API)
442
+ .action(async (name, opts) => {
443
+ const key = readApiKey();
444
+ if (!key) {
445
+ out(cmd, { ok: false, error: 'no API key — set ONEIE_API_KEY or run oneie auth login' });
446
+ return;
447
+ }
448
+ const token = `${opts.slug}:${key}`;
449
+ const url = `${opts.api.replace(/\/$/, '')}/api/agents/history?slug=${encodeURIComponent(opts.slug)}&name=${encodeURIComponent(name)}`;
450
+ try {
451
+ const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
452
+ const data = await res.json();
453
+ if (!res.ok) {
454
+ out(cmd, { ok: false, ...data });
455
+ return;
456
+ }
457
+ out(cmd, { ok: true, ...data });
458
+ }
459
+ catch (e) {
460
+ out(cmd, { ok: false, error: String(e) });
461
+ }
462
+ });
463
+ // C4 — agent rollback: restore agent to a previous version
464
+ cmd.command('rollback <name>')
465
+ .description('Restore a published agent to a previous version')
466
+ .requiredOption('--slug <slug>', 'Workspace slug')
467
+ .requiredOption('--to <ts>', 'Epoch-ms timestamp of the version to restore (from agent history)')
468
+ .option('--yes', 'Skip confirmation prompt')
469
+ .option('--api <url>', 'API base URL', DEFAULT_API)
470
+ .action(async (name, opts) => {
471
+ const key = readApiKey();
472
+ if (!key) {
473
+ out(cmd, { ok: false, error: 'no API key — set ONEIE_API_KEY or run oneie auth login' });
474
+ return;
475
+ }
476
+ const ts = parseInt(opts.to, 10);
477
+ if (isNaN(ts)) {
478
+ out(cmd, { ok: false, error: `--to must be a numeric timestamp (got "${opts.to}")` });
479
+ return;
480
+ }
481
+ if (!opts.yes) {
482
+ process.stdout.write(`Roll back ${opts.slug}/${name} to version ${ts}? [y/N] `);
483
+ const confirmed = await new Promise((resolve) => {
484
+ process.stdin.once('data', (d) => resolve(d.toString().trim().toLowerCase() === 'y'));
485
+ process.stdin.resume();
486
+ });
487
+ process.stdin.pause();
488
+ if (!confirmed) {
489
+ console.log('Aborted.');
490
+ return;
491
+ }
492
+ }
493
+ const token = `${opts.slug}:${key}`;
494
+ const url = `${opts.api.replace(/\/$/, '')}/api/agents/rollback`;
495
+ try {
496
+ const res = await fetch(url, {
497
+ method: 'POST',
498
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
499
+ body: JSON.stringify({ slug: opts.slug, name, ts }),
500
+ });
501
+ const data = await res.json();
502
+ if (!res.ok) {
503
+ out(cmd, { ok: false, ...data });
504
+ return;
505
+ }
506
+ out(cmd, { ok: true, ...data });
507
+ }
508
+ catch (e) {
509
+ out(cmd, { ok: false, error: String(e) });
510
+ }
511
+ });
512
+ // TPL2 — agent ai-edit: apply a natural-language instruction to an agent.md
513
+ cmd.command('ai-edit <path>')
514
+ .description('Apply a natural-language instruction to an agent.md using Claude')
515
+ .requiredOption('--prompt <instruction>', 'What to change, e.g. "make the tone more formal"')
516
+ .option('--model <model>', 'Claude model', 'claude-haiku-4-5-20251001')
517
+ .option('--yes', 'Write without diff preview')
518
+ .action(async (filePath, opts) => {
519
+ const apiKey = process.env.ANTHROPIC_API_KEY;
520
+ if (!apiKey) {
521
+ out(cmd, { ok: false, error: 'ANTHROPIC_API_KEY not set' });
522
+ return;
523
+ }
524
+ if (!existsSync(filePath)) {
525
+ out(cmd, { ok: false, error: `not found: ${filePath}` });
526
+ return;
527
+ }
528
+ const original = readFileSync(filePath, 'utf8');
529
+ console.log(`Applying instruction to ${filePath}…`);
530
+ let revised = '';
531
+ try {
532
+ const res = await fetch('https://api.anthropic.com/v1/messages', {
533
+ method: 'POST',
534
+ headers: {
535
+ 'Content-Type': 'application/json',
536
+ 'x-api-key': apiKey,
537
+ 'anthropic-version': '2023-06-01',
538
+ },
539
+ body: JSON.stringify({
540
+ model: opts.model,
541
+ max_tokens: 4096,
542
+ messages: [
543
+ {
544
+ role: 'user',
545
+ content: `You are editing an agent.md file. Return ONLY the updated file — no explanation, no markdown fences.
546
+
547
+ Instruction: ${opts.prompt}
548
+
549
+ --- agent.md ---
550
+ ${original}`,
551
+ },
552
+ ],
553
+ }),
554
+ });
555
+ if (!res.ok) {
556
+ const err = await res.text();
557
+ out(cmd, { ok: false, error: `Anthropic API error: ${err}` });
558
+ return;
559
+ }
560
+ const data = await res.json();
561
+ revised = data.content.find((b) => b.type === 'text')?.text?.trim() ?? '';
562
+ if (!revised) {
563
+ out(cmd, { ok: false, error: 'empty response from Claude' });
564
+ return;
565
+ }
566
+ }
567
+ catch (e) {
568
+ out(cmd, { ok: false, error: `fetch failed: ${String(e)}` });
569
+ return;
570
+ }
571
+ if (!opts.yes) {
572
+ // Simple line-level diff preview
573
+ const origLines = original.split('\n');
574
+ const newLines = revised.split('\n');
575
+ const maxLen = Math.max(origLines.length, newLines.length);
576
+ let changes = 0;
577
+ for (let i = 0; i < maxLen; i++) {
578
+ const o = origLines[i] ?? '';
579
+ const n = newLines[i] ?? '';
580
+ if (o !== n) {
581
+ if (changes === 0)
582
+ console.log('\nDiff preview (first 20 changes):');
583
+ if (changes < 20) {
584
+ if (o)
585
+ console.log(`- ${o}`);
586
+ if (n)
587
+ console.log(`+ ${n}`);
588
+ }
589
+ changes++;
590
+ }
591
+ }
592
+ if (changes === 0) {
593
+ console.log('No changes detected.');
594
+ return;
595
+ }
596
+ console.log(`\n${changes} line(s) changed. Pass --yes to write.`);
597
+ return;
598
+ }
599
+ writeFileSync(filePath, revised, 'utf8');
600
+ out(cmd, { ok: true, path: filePath, instruction: opts.prompt });
601
+ });
602
+ // TPL1 — agent templates: list available starter templates
603
+ cmd.command('templates')
604
+ .description('List available agent starter templates')
605
+ .action(() => {
606
+ const list = Object.keys(TEMPLATES).map((name) => {
607
+ const tpl = TEMPLATES[name];
608
+ const titleMatch = tpl.match(/^title:\s*(.+)$/m);
609
+ return { name, title: titleMatch ? titleMatch[1].trim() : name };
610
+ });
611
+ out(cmd, { ok: true, templates: list });
612
+ });
613
+ // TPL1 — agent fork: clone a template with a new name
614
+ cmd.command('fork <template> <local-name>')
615
+ .description('Clone a starter template into <local-name>/agent.md')
616
+ .action((template, localName) => {
617
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(localName)) {
618
+ out(cmd, { ok: false, error: 'local-name must be lowercase alphanumeric with hyphens only' });
619
+ return;
620
+ }
621
+ const tpl = TEMPLATES[template];
622
+ if (!tpl) {
623
+ out(cmd, { ok: false, error: `unknown template: ${template}. Run "oneie agent templates" to list available templates.` });
624
+ return;
625
+ }
626
+ const body = tpl.replace(/\bname:\s*\S+/m, `name: ${localName}`)
627
+ .replace(/\btitle:\s*.+/m, (m) => m.replace(/template/gi, localName));
628
+ const dir = localName;
629
+ const outPath = `${dir}/agent.md`;
630
+ if (existsSync(outPath)) {
631
+ out(cmd, { ok: false, error: `${outPath} already exists` });
632
+ return;
633
+ }
634
+ if (!existsSync(dir))
635
+ mkdirSync(dir, { recursive: true });
636
+ writeFileSync(outPath, body);
637
+ out(cmd, { ok: true, path: outPath, template, name: localName });
638
+ });
639
+ return cmd;
640
+ }
641
+ function out(cmd, data) {
642
+ const isJson = cmd.parent?.opts().json;
643
+ if (isJson) {
644
+ process.stdout.write(JSON.stringify(data) + '\n');
645
+ }
646
+ else if (data.ok) {
647
+ const pairs = Object.entries(data)
648
+ .filter(([k]) => k !== 'ok')
649
+ .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
650
+ .join(' ');
651
+ console.log('✓', pairs);
652
+ }
653
+ else {
654
+ const detail = data.error ?? data.errors ?? data.issues ?? data;
655
+ console.error('✗', typeof detail === 'string' ? detail : JSON.stringify(detail));
656
+ }
657
+ }
658
+ /**
659
+ * Structural validation — mirrors the rules enforced by the web's Zod schema
660
+ * (web/src/lib/agent-schema.ts) without pulling Zod or js-yaml into the CLI
661
+ * dependency graph. Catches the contract violations partners hit most often:
662
+ * missing frontmatter, name shape, journey/section anchor mismatches, chip
663
+ * id collisions, kebab-case ids. Anything outside these rules falls through
664
+ * to the live server-side validation when the agent is published.
665
+ */
666
+ function validate(path) {
667
+ if (!existsSync(path))
668
+ return { errors: [`not found: ${path}`] };
669
+ const text = readFileSync(path, 'utf8');
670
+ const errors = [];
671
+ if (!text.startsWith('---')) {
672
+ errors.push('missing frontmatter — agent.md must start with `---`');
673
+ return { errors };
674
+ }
675
+ const fmMatch = text.match(/^---\n([\s\S]*?)\n---/);
676
+ if (!fmMatch) {
677
+ errors.push('frontmatter not terminated — missing closing `---`');
678
+ return { errors };
679
+ }
680
+ const fm = fmMatch[1];
681
+ const nameMatch = /^name:\s*(\S+)/m.exec(fm);
682
+ if (!nameMatch) {
683
+ errors.push('missing required field: name');
684
+ }
685
+ else if (!/^[a-z0-9][a-z0-9-]*$/.test(nameMatch[1])) {
686
+ errors.push(`name "${nameMatch[1]}" must be kebab-case (lowercase, digits, hyphens)`);
687
+ }
688
+ // Stage ids and section anchors should agree. Scan the YAML lines without
689
+ // a full parser — good enough for catching the common authoring mistake.
690
+ const stageIds = new Set();
691
+ const stageRe = /^\s+-\s+id:\s+([a-z0-9-]+)\s*$/gm;
692
+ let m;
693
+ while ((m = stageRe.exec(fm)))
694
+ stageIds.add(m[1]);
695
+ const sectionIds = new Set();
696
+ const sectionRe = /^\s+-\s+kind:\s+\S+\s*\n\s+id:\s+([a-z0-9-]+)/gm;
697
+ while ((m = sectionRe.exec(fm)))
698
+ sectionIds.add(m[1]);
699
+ // Stage anchors `sections: [foo, bar]` should resolve to known section ids.
700
+ // Strip quotes BEFORE the leading `#` — otherwise `'#brand'` keeps the hash.
701
+ const anchorRe = /^\s+sections:\s*\[([^\]]+)\]/gm;
702
+ while ((m = anchorRe.exec(fm))) {
703
+ const refs = m[1].split(',').map((s) => s.trim().replace(/['"]/g, '').replace(/^#/, ''));
704
+ for (const ref of refs) {
705
+ if (ref && !sectionIds.has(ref)) {
706
+ errors.push(`stage references section "${ref}" but no section with that id exists`);
707
+ }
708
+ }
709
+ }
710
+ return { errors };
711
+ }
712
+ function lint(path) {
713
+ if (!existsSync(path))
714
+ return [`not found: ${path}`];
715
+ const text = readFileSync(path, 'utf8');
716
+ const issues = [];
717
+ const fmMatch = text.match(/^---\n([\s\S]*?)\n---/);
718
+ const fm = fmMatch ? fmMatch[1] : '';
719
+ if (!/^description:/m.test(fm)) {
720
+ issues.push('missing description (one-line tagline shown on /agents and in chat)');
721
+ }
722
+ if (!/^title:/m.test(fm)) {
723
+ issues.push('missing title (display name distinct from kebab-case `name`)');
724
+ }
725
+ if (/^price:/m.test(fm) && !/^accepts:/m.test(fm)) {
726
+ issues.push('prefer accepts[] over price shorthand for multi-chain support');
727
+ }
728
+ // Chip id length — Zod warns when label > 28 chars. CLI does the same.
729
+ // Strip inline YAML comments before measuring; otherwise " # this is..." inflates length.
730
+ const labelRe = /^\s+label:\s+["']?([^"'\n#]+?)["']?(?:\s+#.*)?$/gm;
731
+ let m;
732
+ while ((m = labelRe.exec(fm))) {
733
+ const label = m[1].trim();
734
+ if (label.length > 28) {
735
+ issues.push(`label "${label}" is ${label.length} chars — wraps awkwardly above 28`);
736
+ }
737
+ }
738
+ // Stage continuation count — Zod schema caps at 4 per stage.
739
+ const stageBlocks = fm.split(/^\s+-\s+id:/m).slice(1);
740
+ for (const block of stageBlocks) {
741
+ const cont = /^\s+continuations:\s*\n((?:\s+-\s+id:[\s\S]*?)+)$/m.exec(block);
742
+ if (cont) {
743
+ const count = (cont[1].match(/^\s+-\s+id:/gm) ?? []).length;
744
+ if (count > 4) {
745
+ issues.push(`stage has ${count} continuations — max 4 fit the chip strip cleanly`);
746
+ }
747
+ }
748
+ }
749
+ return issues;
750
+ }
751
+ function compileTarget(content, target) {
752
+ if (target === 'mcp')
753
+ return JSON.stringify({ tools: [] }, null, 2);
754
+ if (target === 'uagents')
755
+ return compileAgent(content, { target: 'uagents' });
756
+ if (target === 'web') {
757
+ // Emit a typed TS module — the web app can import this at build time
758
+ // instead of parsing .md at request time. Matches the SDK's compileWeb()
759
+ // output shape; the CLI uses a lightweight inline build for portability.
760
+ const m = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
761
+ const fm = m ? m[1] : '';
762
+ const body = m ? m[2].trim() : content.trim();
763
+ return [
764
+ '// Generated by ONE — https://one.ie',
765
+ '// `oneie agent compile --target web` — do not edit by hand',
766
+ '',
767
+ 'export const frontmatterRaw = ' + JSON.stringify(fm),
768
+ 'export const prompt = ' + JSON.stringify(body),
769
+ '',
770
+ ].join('\n');
771
+ }
772
+ return content;
773
+ }
774
+ /** Lightweight issue extractor for dev-mode validation (no Zod — just structural checks). */
775
+ function issues_from_quick(_delta, raw) {
776
+ const issues = [];
777
+ const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
778
+ if (!fmMatch) {
779
+ issues.push({ level: 'error', path: '<frontmatter>', message: 'missing YAML frontmatter (no --- delimiters found)' });
780
+ return issues;
781
+ }
782
+ const fm = fmMatch[1];
783
+ if (!/^\s*name:/m.test(fm))
784
+ issues.push({ level: 'error', path: 'name', message: 'required field `name:` missing' });
785
+ if (!/^\s*title:/m.test(fm))
786
+ issues.push({ level: 'warn', path: 'title', message: 'recommended field `title:` missing' });
787
+ return issues;
788
+ }
789
+ function parseQuickMd(path) {
790
+ const text = readFileSync(path, 'utf8');
791
+ const m = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
792
+ const prompt = m ? m[2].trim() : text.trim();
793
+ // Lightweight regex-based extraction — avoids a YAML dep in the CLI.
794
+ const fm = m ? m[1] : '';
795
+ const skills = [];
796
+ const skillsLine = /^skills:\s*\[([^\]]+)\]/m.exec(fm);
797
+ if (skillsLine)
798
+ skills.push(...skillsLine[1].split(',').map((s) => s.trim().replace(/['"]/g, '')));
799
+ const stages = {};
800
+ const stageRe = /^\s+- id:\s+([a-z0-9-]+)\b([\s\S]*?)(?=^\s+- id:|^\s*pills:|^\s*sections:|^---)/gm;
801
+ let sm;
802
+ while ((sm = stageRe.exec(fm))) {
803
+ stages[sm[1]] = sm[2].trim();
804
+ }
805
+ const sections = [];
806
+ const sectionRe = /^\s+- kind:\s+\S+\s*\n\s+id:\s+([a-z0-9-]+)/gm;
807
+ let secM;
808
+ while ((secM = sectionRe.exec(fm)))
809
+ sections.push(secM[1]);
810
+ const pills = [];
811
+ // pills block: extract `- id: foo` items
812
+ const pillsBlock = /^\s*pills:[\s\S]*?(?=^\S|$(?![\r\n]))/m.exec(fm);
813
+ if (pillsBlock) {
814
+ const pillRe = /^\s+- id:\s+([a-z0-9-]+)/gm;
815
+ let pm;
816
+ while ((pm = pillRe.exec(pillsBlock[0])))
817
+ pills.push(pm[1]);
818
+ }
819
+ const uiMatch = /^\s*ui:[\s\S]*?(?=^[a-z]+:|^---)/m.exec(fm);
820
+ const themeMatch = /^\s*theme:[\s\S]*?(?=^[a-z]+:|^---)/m.exec(fm);
821
+ return {
822
+ prompt,
823
+ skills,
824
+ stages,
825
+ sections,
826
+ pills,
827
+ uiSerialized: uiMatch?.[0] ?? '',
828
+ themeSerialized: themeMatch?.[0] ?? '',
829
+ };
830
+ }
831
+ function semanticDiff(a, b) {
832
+ const A = parseQuickMd(a);
833
+ const B = parseQuickMd(b);
834
+ const setA = new Set(A.skills);
835
+ const setB = new Set(B.skills);
836
+ const skillsAdded = [...setB].filter((s) => !setA.has(s));
837
+ const skillsRemoved = [...setA].filter((s) => !setB.has(s));
838
+ const stageIdsA = new Set(Object.keys(A.stages));
839
+ const stageIdsB = new Set(Object.keys(B.stages));
840
+ const stagesAdded = [...stageIdsB].filter((s) => !stageIdsA.has(s));
841
+ const stagesRemoved = [...stageIdsA].filter((s) => !stageIdsB.has(s));
842
+ const stageContentChanged = [...stageIdsA]
843
+ .filter((s) => stageIdsB.has(s) && A.stages[s] !== B.stages[s]);
844
+ const secSetA = new Set(A.sections);
845
+ const secSetB = new Set(B.sections);
846
+ const sectionsAdded = [...secSetB].filter((s) => !secSetA.has(s));
847
+ const sectionsRemoved = [...secSetA].filter((s) => !secSetB.has(s));
848
+ const pillSetA = new Set(A.pills);
849
+ const pillSetB = new Set(B.pills);
850
+ const pillsAdded = [...pillSetB].filter((s) => !pillSetA.has(s));
851
+ const pillsRemoved = [...pillSetA].filter((s) => !pillSetB.has(s));
852
+ // Key-level ui/theme diff: extract top-level keys from serialized block strings
853
+ const extractKeys = (serialized) => {
854
+ const result = {};
855
+ const re = /^\s{2}([a-zA-Z][a-zA-Z0-9_]*):/gm;
856
+ let m;
857
+ while ((m = re.exec(serialized)) !== null)
858
+ result[m[1]] = m[1];
859
+ return result;
860
+ };
861
+ const uiA = extractKeys(A.uiSerialized);
862
+ const uiB = extractKeys(B.uiSerialized);
863
+ const allUiKeys = new Set([...Object.keys(uiA), ...Object.keys(uiB)]);
864
+ const uiKeys = [...allUiKeys].filter((k) => uiA[k] !== uiB[k]);
865
+ const themeA = extractKeys(A.themeSerialized);
866
+ const themeB = extractKeys(B.themeSerialized);
867
+ const allThemeKeys = new Set([...Object.keys(themeA), ...Object.keys(themeB)]);
868
+ const themeKeys = [...allThemeKeys].filter((k) => themeA[k] !== themeB[k]);
869
+ const delta = {
870
+ promptChanged: A.prompt !== B.prompt,
871
+ skillsAdded, skillsRemoved,
872
+ stagesAdded, stagesRemoved, stageContentChanged,
873
+ sectionsAdded, sectionsRemoved,
874
+ pillsAdded, pillsRemoved,
875
+ uiChanged: A.uiSerialized !== B.uiSerialized,
876
+ uiKeys,
877
+ themeChanged: A.themeSerialized !== B.themeSerialized,
878
+ themeKeys,
879
+ unchanged: false,
880
+ };
881
+ delta.unchanged = !delta.promptChanged
882
+ && skillsAdded.length === 0 && skillsRemoved.length === 0
883
+ && stagesAdded.length === 0 && stagesRemoved.length === 0 && stageContentChanged.length === 0
884
+ && sectionsAdded.length === 0 && sectionsRemoved.length === 0
885
+ && pillsAdded.length === 0 && pillsRemoved.length === 0
886
+ && !delta.uiChanged && !delta.themeChanged;
887
+ return delta;
888
+ }