@oneie/cli 5.8.0 → 5.9.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 (270) hide show
  1. package/README.md +114 -6
  2. package/dist/package.json +37 -11
  3. package/dist/src/age-1k8hs4ec.js +1 -0
  4. package/dist/src/client-n6fpnd9f.js +1 -0
  5. package/dist/src/evm-tx-cqhm9rtt.js +1 -0
  6. package/dist/src/hl-run-0pv1e0p2.js +1 -0
  7. package/dist/src/index-f5vhzspa.js +12 -0
  8. package/dist/src/index-h3nrt8bx.js +4 -0
  9. package/dist/src/index-st6k9vhc.js +2062 -0
  10. package/dist/src/index.js +1122 -134
  11. package/dist/src/message-key-yczrxszr.js +1 -0
  12. package/dist/src/message-lock-thr851d5.js +5 -0
  13. package/dist/src/sweep-order-jrq2hkye.js +1 -0
  14. package/dist/src/sweep-runner-jftw9em7.js +1 -0
  15. package/package.json +37 -11
  16. package/dist/src/agent.d.ts +0 -75
  17. package/dist/src/agent.js +0 -1334
  18. package/dist/src/agentverse.d.ts +0 -26
  19. package/dist/src/agentverse.js +0 -171
  20. package/dist/src/args.d.ts +0 -9
  21. package/dist/src/args.js +0 -61
  22. package/dist/src/auth.d.ts +0 -6
  23. package/dist/src/auth.js +0 -121
  24. package/dist/src/balances.d.ts +0 -89
  25. package/dist/src/balances.js +0 -202
  26. package/dist/src/banner.d.ts +0 -1
  27. package/dist/src/banner.js +0 -17
  28. package/dist/src/broadcast.d.ts +0 -8
  29. package/dist/src/broadcast.js +0 -175
  30. package/dist/src/catalog.d.ts +0 -12
  31. package/dist/src/catalog.js +0 -76
  32. package/dist/src/ceiling.d.ts +0 -36
  33. package/dist/src/ceiling.js +0 -189
  34. package/dist/src/chat.d.ts +0 -2
  35. package/dist/src/chat.js +0 -92
  36. package/dist/src/check.d.ts +0 -11
  37. package/dist/src/check.js +0 -53
  38. package/dist/src/client.d.ts +0 -5
  39. package/dist/src/client.js +0 -157
  40. package/dist/src/compiler.d.ts +0 -36
  41. package/dist/src/compiler.js +0 -366
  42. package/dist/src/config.d.ts +0 -24
  43. package/dist/src/config.js +0 -70
  44. package/dist/src/connect.d.ts +0 -2
  45. package/dist/src/connect.js +0 -64
  46. package/dist/src/coordinate.d.ts +0 -3
  47. package/dist/src/coordinate.js +0 -58
  48. package/dist/src/create.d.ts +0 -2
  49. package/dist/src/create.js +0 -113
  50. package/dist/src/credits.d.ts +0 -29
  51. package/dist/src/credits.js +0 -88
  52. package/dist/src/deploy.d.ts +0 -2
  53. package/dist/src/deploy.js +0 -19
  54. package/dist/src/dev.d.ts +0 -2
  55. package/dist/src/dev.js +0 -75
  56. package/dist/src/device-flow.d.ts +0 -57
  57. package/dist/src/device-flow.js +0 -173
  58. package/dist/src/doctor.d.ts +0 -26
  59. package/dist/src/doctor.js +0 -146
  60. package/dist/src/draw.d.ts +0 -18
  61. package/dist/src/draw.js +0 -156
  62. package/dist/src/endpoint.d.ts +0 -2
  63. package/dist/src/endpoint.js +0 -250
  64. package/dist/src/env.d.ts +0 -3
  65. package/dist/src/env.js +0 -37
  66. package/dist/src/eval.d.ts +0 -2
  67. package/dist/src/eval.js +0 -43
  68. package/dist/src/fn.d.ts +0 -2
  69. package/dist/src/fn.js +0 -70
  70. package/dist/src/group.d.ts +0 -2
  71. package/dist/src/group.js +0 -117
  72. package/dist/src/hl-run.d.ts +0 -119
  73. package/dist/src/hl-run.js +0 -480
  74. package/dist/src/hl.d.ts +0 -17
  75. package/dist/src/hl.js +0 -148
  76. package/dist/src/index.d.ts +0 -2
  77. package/dist/src/init.d.ts +0 -76
  78. package/dist/src/init.js +0 -278
  79. package/dist/src/join.d.ts +0 -11
  80. package/dist/src/join.js +0 -297
  81. package/dist/src/key-publish.d.ts +0 -40
  82. package/dist/src/key-publish.js +0 -232
  83. package/dist/src/key-seal.d.ts +0 -21
  84. package/dist/src/key-seal.js +0 -142
  85. package/dist/src/key-sweep.d.ts +0 -93
  86. package/dist/src/key-sweep.js +0 -270
  87. package/dist/src/key.d.ts +0 -26
  88. package/dist/src/key.js +0 -338
  89. package/dist/src/lib/age-plugin.d.ts +0 -51
  90. package/dist/src/lib/age-plugin.js +0 -130
  91. package/dist/src/lib/agent-env.d.ts +0 -12
  92. package/dist/src/lib/agent-env.js +0 -48
  93. package/dist/src/lib/api-path.d.ts +0 -2
  94. package/dist/src/lib/api-path.js +0 -40
  95. package/dist/src/lib/asker.d.ts +0 -34
  96. package/dist/src/lib/asker.js +0 -126
  97. package/dist/src/lib/check-words.d.ts +0 -57
  98. package/dist/src/lib/check-words.js +0 -144
  99. package/dist/src/lib/client.d.ts +0 -20
  100. package/dist/src/lib/client.js +0 -71
  101. package/dist/src/lib/env-sealed.d.ts +0 -53
  102. package/dist/src/lib/env-sealed.js +0 -184
  103. package/dist/src/lib/flow-tag.d.ts +0 -86
  104. package/dist/src/lib/flow-tag.js +0 -230
  105. package/dist/src/lib/hl-core/actions.d.ts +0 -99
  106. package/dist/src/lib/hl-core/actions.js +0 -69
  107. package/dist/src/lib/hl-core/eip712.d.ts +0 -33
  108. package/dist/src/lib/hl-core/eip712.js +0 -107
  109. package/dist/src/lib/hl-core/errors.d.ts +0 -10
  110. package/dist/src/lib/hl-core/errors.js +0 -15
  111. package/dist/src/lib/hl-core/exchange.d.ts +0 -24
  112. package/dist/src/lib/hl-core/exchange.js +0 -47
  113. package/dist/src/lib/hl-core/index.d.ts +0 -13
  114. package/dist/src/lib/hl-core/index.js +0 -14
  115. package/dist/src/lib/hl-core/meta.d.ts +0 -57
  116. package/dist/src/lib/hl-core/meta.js +0 -110
  117. package/dist/src/lib/hl-core/msgpack.d.ts +0 -18
  118. package/dist/src/lib/hl-core/msgpack.js +0 -136
  119. package/dist/src/lib/hl-core/net.d.ts +0 -2
  120. package/dist/src/lib/hl-core/net.js +0 -7
  121. package/dist/src/lib/hl-core/signing.d.ts +0 -103
  122. package/dist/src/lib/hl-core/signing.js +0 -295
  123. package/dist/src/lib/hl-core/wire.d.ts +0 -34
  124. package/dist/src/lib/hl-core/wire.js +0 -81
  125. package/dist/src/lib/invoked-as.d.ts +0 -2
  126. package/dist/src/lib/invoked-as.js +0 -24
  127. package/dist/src/lib/journey-words.d.ts +0 -84
  128. package/dist/src/lib/journey-words.js +0 -363
  129. package/dist/src/lib/journey.d.ts +0 -150
  130. package/dist/src/lib/journey.js +0 -264
  131. package/dist/src/lib/key-receipt.d.ts +0 -48
  132. package/dist/src/lib/key-receipt.js +0 -116
  133. package/dist/src/lib/key-source.d.ts +0 -9
  134. package/dist/src/lib/key-source.js +0 -33
  135. package/dist/src/lib/keyfile.d.ts +0 -136
  136. package/dist/src/lib/keyfile.js +0 -397
  137. package/dist/src/lib/launch-claude.d.ts +0 -5
  138. package/dist/src/lib/launch-claude.js +0 -45
  139. package/dist/src/lib/lock-lookup.d.ts +0 -40
  140. package/dist/src/lib/lock-lookup.js +0 -92
  141. package/dist/src/lib/message-seal.d.ts +0 -63
  142. package/dist/src/lib/message-seal.js +0 -150
  143. package/dist/src/lib/net-choice.d.ts +0 -28
  144. package/dist/src/lib/net-choice.js +0 -72
  145. package/dist/src/lib/network.d.ts +0 -22
  146. package/dist/src/lib/network.js +0 -50
  147. package/dist/src/lib/next-words.d.ts +0 -105
  148. package/dist/src/lib/next-words.js +0 -298
  149. package/dist/src/lib/paths.d.ts +0 -41
  150. package/dist/src/lib/paths.js +0 -91
  151. package/dist/src/lib/plan-draw.d.ts +0 -56
  152. package/dist/src/lib/plan-draw.js +0 -219
  153. package/dist/src/lib/plan-live.d.ts +0 -20
  154. package/dist/src/lib/plan-live.js +0 -192
  155. package/dist/src/lib/qr.d.ts +0 -21
  156. package/dist/src/lib/qr.js +0 -402
  157. package/dist/src/lib/roster.d.ts +0 -20
  158. package/dist/src/lib/roster.js +0 -79
  159. package/dist/src/lib/sale-card.d.ts +0 -117
  160. package/dist/src/lib/sale-card.js +0 -261
  161. package/dist/src/lib/shop-init.d.ts +0 -62
  162. package/dist/src/lib/shop-init.js +0 -63
  163. package/dist/src/lib/sui-grpc-send.d.ts +0 -90
  164. package/dist/src/lib/sui-grpc-send.js +0 -128
  165. package/dist/src/lib/swap-core.d.ts +0 -163
  166. package/dist/src/lib/swap-core.js +0 -405
  167. package/dist/src/lib/tasks-digest.d.ts +0 -66
  168. package/dist/src/lib/tasks-digest.js +0 -200
  169. package/dist/src/lib/tasks-graph.d.ts +0 -79
  170. package/dist/src/lib/tasks-graph.js +0 -463
  171. package/dist/src/lib/tasks-lens.d.ts +0 -31
  172. package/dist/src/lib/tasks-lens.js +0 -47
  173. package/dist/src/lib/tasks-next.d.ts +0 -25
  174. package/dist/src/lib/tasks-next.js +0 -103
  175. package/dist/src/lib/tasks-prove.d.ts +0 -15
  176. package/dist/src/lib/tasks-prove.js +0 -68
  177. package/dist/src/lib/tasks-route.d.ts +0 -29
  178. package/dist/src/lib/tasks-route.js +0 -151
  179. package/dist/src/lib/tasks-score.d.ts +0 -36
  180. package/dist/src/lib/tasks-score.js +0 -152
  181. package/dist/src/lib/tasks-workspace.d.ts +0 -18
  182. package/dist/src/lib/tasks-workspace.js +0 -73
  183. package/dist/src/lib/timed-fetch.d.ts +0 -33
  184. package/dist/src/lib/timed-fetch.js +0 -59
  185. package/dist/src/lib/vault-read.d.ts +0 -24
  186. package/dist/src/lib/vault-read.js +0 -77
  187. package/dist/src/lib/vaultfile.d.ts +0 -103
  188. package/dist/src/lib/vaultfile.js +0 -249
  189. package/dist/src/lib/wallet-money.d.ts +0 -222
  190. package/dist/src/lib/wallet-money.js +0 -578
  191. package/dist/src/lib/wallet-request.d.ts +0 -50
  192. package/dist/src/lib/wallet-request.js +0 -86
  193. package/dist/src/links.d.ts +0 -5
  194. package/dist/src/links.js +0 -45
  195. package/dist/src/media.d.ts +0 -29
  196. package/dist/src/media.js +0 -487
  197. package/dist/src/message-receipt.d.ts +0 -25
  198. package/dist/src/message-receipt.js +0 -71
  199. package/dist/src/message.d.ts +0 -13
  200. package/dist/src/message.js +0 -92
  201. package/dist/src/move.d.ts +0 -36
  202. package/dist/src/move.js +0 -152
  203. package/dist/src/network-cmd.d.ts +0 -17
  204. package/dist/src/network-cmd.js +0 -74
  205. package/dist/src/next.d.ts +0 -12
  206. package/dist/src/next.js +0 -67
  207. package/dist/src/onboard.d.ts +0 -16
  208. package/dist/src/onboard.js +0 -149
  209. package/dist/src/plugin.d.ts +0 -2
  210. package/dist/src/plugin.js +0 -193
  211. package/dist/src/push.d.ts +0 -2
  212. package/dist/src/push.js +0 -115
  213. package/dist/src/render.d.ts +0 -21
  214. package/dist/src/render.js +0 -32
  215. package/dist/src/secrets-device.d.ts +0 -32
  216. package/dist/src/secrets-device.js +0 -127
  217. package/dist/src/secrets-give.d.ts +0 -125
  218. package/dist/src/secrets-give.js +0 -236
  219. package/dist/src/secrets-list.d.ts +0 -27
  220. package/dist/src/secrets-list.js +0 -84
  221. package/dist/src/secrets-run.d.ts +0 -31
  222. package/dist/src/secrets-run.js +0 -182
  223. package/dist/src/secrets.d.ts +0 -33
  224. package/dist/src/secrets.js +0 -200
  225. package/dist/src/setup.d.ts +0 -6
  226. package/dist/src/setup.js +0 -127
  227. package/dist/src/ship.d.ts +0 -2
  228. package/dist/src/ship.js +0 -18
  229. package/dist/src/shop-buy.d.ts +0 -16
  230. package/dist/src/shop-buy.js +0 -101
  231. package/dist/src/shop.d.ts +0 -10
  232. package/dist/src/shop.js +0 -112
  233. package/dist/src/skill-parser.d.ts +0 -14
  234. package/dist/src/skill-parser.js +0 -113
  235. package/dist/src/skill.d.ts +0 -2
  236. package/dist/src/skill.js +0 -493
  237. package/dist/src/slug.d.ts +0 -2
  238. package/dist/src/slug.js +0 -6
  239. package/dist/src/social.d.ts +0 -2
  240. package/dist/src/social.js +0 -106
  241. package/dist/src/staff.d.ts +0 -2
  242. package/dist/src/staff.js +0 -104
  243. package/dist/src/start.d.ts +0 -27
  244. package/dist/src/start.js +0 -225
  245. package/dist/src/status.d.ts +0 -2
  246. package/dist/src/status.js +0 -52
  247. package/dist/src/substrate.d.ts +0 -2
  248. package/dist/src/substrate.js +0 -258
  249. package/dist/src/swap.d.ts +0 -93
  250. package/dist/src/swap.js +0 -622
  251. package/dist/src/tasks.d.ts +0 -2
  252. package/dist/src/tasks.js +0 -743
  253. package/dist/src/templates.d.ts +0 -1
  254. package/dist/src/templates.js +0 -213
  255. package/dist/src/thread.d.ts +0 -2
  256. package/dist/src/thread.js +0 -52
  257. package/dist/src/trade.d.ts +0 -2
  258. package/dist/src/trade.js +0 -91
  259. package/dist/src/trail.d.ts +0 -2
  260. package/dist/src/trail.js +0 -41
  261. package/dist/src/validate.d.ts +0 -13
  262. package/dist/src/validate.js +0 -35
  263. package/dist/src/wallet-money.d.ts +0 -158
  264. package/dist/src/wallet-money.js +0 -664
  265. package/dist/src/wallet.d.ts +0 -169
  266. package/dist/src/wallet.js +0 -973
  267. package/dist/src/workflow.d.ts +0 -2
  268. package/dist/src/workflow.js +0 -169
  269. package/dist/src/write.d.ts +0 -43
  270. package/dist/src/write.js +0 -180
package/dist/src/agent.js DELETED
@@ -1,1334 +0,0 @@
1
- import { Command } from 'commander';
2
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
3
- import { basename, dirname, join, resolve } from 'node:path';
4
- import { TEMPLATES } from './templates.js';
5
- import { compileAgent, parseAgentMd } from '@oneie/sdk/compile';
6
- import { resolveKey } from './lib/client.js';
7
- import { askPath } from './lib/api-path.js';
8
- import { agentverseCmd, publishEndpoint } from './agentverse.js';
9
- import { watch } from 'fs';
10
- const DEFAULT_API = 'https://one.ie';
11
- /**
12
- * The CLI-wide key contract lives in one place — `resolveKey()` in
13
- * lib/client.ts: `--key` > ONE_API_KEY (canonical) > ONEIE_API_KEY (legacy) >
14
- * ~/.config/oneie/key. This module used to read ONLY the legacy var, so anyone
15
- * on the canonical `ONE_API_KEY` silently resolved to null.
16
- */
17
- function readApiKey() {
18
- return resolveKey() || null;
19
- }
20
- export function agentCmd() {
21
- const cmd = new Command('agent').description('Agent management');
22
- cmd.command('new <name>')
23
- .description('Scaffold a new agent from template')
24
- .option('--profile <profile>', 'Template profile: core | commerce | asi', 'core')
25
- .action((name, opts) => {
26
- if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {
27
- out(cmd, { ok: false, error: 'agent name must be lowercase alphanumeric with hyphens only' });
28
- return;
29
- }
30
- const tpl = TEMPLATES[opts.profile];
31
- if (!tpl) {
32
- out(cmd, { ok: false, error: `unknown profile: ${opts.profile}` });
33
- return;
34
- }
35
- const body = tpl.replace(/\btemplate\b/g, name);
36
- const outPath = `${name}/agent.md`;
37
- mkdirSync(dirname(outPath), { recursive: true });
38
- writeFileSync(outPath, body);
39
- out(cmd, { ok: true, path: outPath, lines: body.split('\n').length });
40
- });
41
- cmd.command('validate <path>')
42
- .description('Validate agent.md frontmatter against the ONE agent spec (text/agents-spec.md)')
43
- .option('--strict', 'Warnings are errors: unknown keys, off-enum values, list shapes the runtime cannot read')
44
- .action((path, opts) => {
45
- const { errors, warnings, unknownKeys } = validate(path, { strict: !!opts.strict });
46
- out(cmd, { ok: errors.length === 0, errors, warnings, unknownKeys, checked: 1 });
47
- });
48
- cmd.command('lint <path>')
49
- .description('Lint agent.md style and spec rules')
50
- .action((path) => {
51
- const issues = lint(path);
52
- out(cmd, { ok: issues.length === 0, issues, rules: 8 });
53
- });
54
- cmd.command('compile <path>')
55
- .description('Compile agent.md to target format')
56
- .option('--target <t>', `Output format: ${CLI_TARGETS.join(' | ')} (a2a and erc8004 are NOT implemented)`, 'mcp')
57
- .option('--skills <dir>', 'Directory holding the skill markdown declared in the agent frontmatter')
58
- .option('--out <file>', 'Write output to file instead of stdout')
59
- .action((path, opts) => {
60
- if (!existsSync(path)) {
61
- out(cmd, { ok: false, error: `not found: ${path}` });
62
- return;
63
- }
64
- const content = readFileSync(path, 'utf8');
65
- const found = resolveSkillMds(path, content, opts.skills);
66
- if (opts.target in TARGETS_USING_SKILLS)
67
- warnSkillGap(found, opts.target);
68
- let result;
69
- try {
70
- result = compileTarget(content, opts.target, found.skills);
71
- }
72
- catch (err) {
73
- out(cmd, { ok: false, target: opts.target, error: err.message });
74
- return;
75
- }
76
- if (opts.out) {
77
- mkdirSync(dirname(opts.out), { recursive: true });
78
- writeFileSync(opts.out, result);
79
- out(cmd, {
80
- ok: true, target: opts.target, written: opts.out, bytes: result.length,
81
- skillsDeclared: found.declared.length, skillsResolved: found.resolved.length,
82
- });
83
- }
84
- else {
85
- process.stdout.write(result + '\n');
86
- }
87
- });
88
- cmd.command('serve <path>')
89
- .description('Run agent as local A2A + MCP server on port 8000')
90
- .option('--port <port>', 'Port', '8000')
91
- .action((path, opts) => {
92
- if (!existsSync(path)) {
93
- out(cmd, { ok: false, error: `not found: ${path}` });
94
- return;
95
- }
96
- out(cmd, { ok: true, path, port: Number(opts.port), status: 'listening' });
97
- });
98
- cmd.command('publish <path>')
99
- .description('Upload agent.md to your workspace at one.ie, or publish it to Agentverse / ASI:One with --target agentverse')
100
- .option('--slug <slug>', 'Workspace slug to publish into (one.ie target; agentverse defaults to the key\'s own)')
101
- .option('--api <url>', 'API base URL', DEFAULT_API)
102
- .option('--name <name>', 'Override agent name (defaults to frontmatter name:)')
103
- .option('--target <t>', 'Publish target: oneie (default) | agentverse', 'oneie')
104
- .option('--hosted', 'agentverse target: deploy compiled Python to Agentverse HOSTING (needs a paid plan and an Agentverse key) instead of serving it from one.ie')
105
- .option('--agentverse-key <key>', 'Agentverse API key for --hosted (or set AGENTVERSE_API_KEY)')
106
- .option('--skills <dir>', 'Directory holding the skill markdown declared in the agent frontmatter (--hosted)')
107
- .option('--live', 'Set lifecycle: active before publishing (skip the draft step)')
108
- // The override for the Agentverse readiness refusal below. It is a flag, not a
109
- // prompt, so the decision to deploy a non-deterministic identity is explicit and
110
- // lands in the shell history of whoever made it.
111
- .option('--force', '--hosted only: deploy even when the agent is not Agentverse-ready (no seed: — a new address every deploy)')
112
- .action(async (path, opts) => {
113
- if (!existsSync(path)) {
114
- out(cmd, { ok: false, error: `not found: ${path}` });
115
- return;
116
- }
117
- // The PUBLISH door keeps the gate it always had — the receiver itself
118
- // refuses on `name:` alone (world-receivers.ts:1407) and this mirrors it.
119
- // The spec's required set (kind, body) changes `validate`'s verdict, not
120
- // whether a file may be uploaded; a stricter door here would be a reader
121
- // changing behaviour, which text/agents-spec.md forbids.
122
- const { errors } = validate(path, { door: 'publish' });
123
- if (errors.length) {
124
- out(cmd, { ok: false, errors });
125
- return;
126
- }
127
- let content = readFileSync(path, 'utf8');
128
- if (opts.live)
129
- content = content.replace(/^lifecycle:\s*draft/m, 'lifecycle: active');
130
- const frontmatterName = /^name:\s*(\S+)/m.exec(content)?.[1];
131
- const agentName = opts.name ?? frontmatterName ?? basename(path, '.md');
132
- // ── Agentverse, endpoint mode (default) ──────────────────────────────
133
- //
134
- // one.ie serves the agent at https://one.ie/api/uagents under an address it
135
- // derives, and registers it in the almanac. No Agentverse key, no hosting
136
- // plan, no seed: — the address is stable because one.ie derives it from
137
- // (workspace, actor), not from the file.
138
- if (opts.target === 'agentverse' && !opts.hosted) {
139
- await publishEndpoint(cmd, { actor: agentName, slug: opts.slug, api: opts.api });
140
- return;
141
- }
142
- // ── Agentverse HOSTING (--hosted) ─────────────────────────────────────
143
- if (opts.target === 'agentverse') {
144
- const avKey = opts.agentverseKey ?? process.env.AGENTVERSE_API_KEY;
145
- if (!avKey) {
146
- out(cmd, { ok: false, error: 'Agentverse API key required — pass --agentverse-key or set AGENTVERSE_API_KEY' });
147
- return;
148
- }
149
- // Compile agent.md → Python uAgents. The skills map is what makes the
150
- // compiler emit Protocol + on_message handlers; without it every
151
- // deployed agent is a shell that cannot answer a message.
152
- const found = resolveSkillMds(path, content, opts.skills);
153
- warnSkillGap(found, 'uagents');
154
- // ── The readiness gate — BEFORE the compile, and long before the network ──
155
- //
156
- // Placed next to warnSkillGap because it is the same kind of honesty: both
157
- // name a capability the deployed agent will not have. It differs in what it
158
- // does about it, and that difference is the whole cycle. A skill gap produces
159
- // an agent that cannot answer; a seed gap produces an agent at a DIFFERENT
160
- // ADDRESS each deploy — and the network cannot tell it is the same agent, so
161
- // the damage is done the moment the upload succeeds, silently, to a caller
162
- // who was told nothing. Warning and uploading anyway is the `--skip-tests`
163
- // shape: a notice where a gate belongs. So the default REFUSES.
164
- //
165
- // `--force` keeps the plan's letter — it warns, then it uploads — while
166
- // making the choice explicit and attributable.
167
- //
168
- // The refusal is STRUCTURED as well as spoken: `missing` rides the out()
169
- // envelope so a --json caller branches on the field instead of scraping
170
- // stderr. Naming which gate bit is the point.
171
- const readiness = agentverseReadiness(content);
172
- if (!readiness.ready) {
173
- warnAgentverseGap(readiness);
174
- if (!opts.force) {
175
- out(cmd, {
176
- ok: false,
177
- error: `not Agentverse-ready — missing: ${readiness.missing.join(', ')}. Add the field, or pass --force to deploy a non-deterministic identity anyway.`,
178
- ready: false,
179
- missing: readiness.missing,
180
- recommended: readiness.recommended,
181
- force: '--force',
182
- });
183
- return;
184
- }
185
- console.error(' --force given — deploying anyway. This address will not be stable.');
186
- }
187
- let python;
188
- try {
189
- python = compileAgent(content, { target: 'uagents', skills: found.skills });
190
- }
191
- catch (err) {
192
- out(cmd, { ok: false, error: `compile failed: ${err.message}` });
193
- return;
194
- }
195
- const AV = 'https://agentverse.ai/v1';
196
- const avFetch = async (method, avPath, body) => {
197
- const res = await fetch(`${AV}${avPath}`, {
198
- method,
199
- headers: { Authorization: `Bearer ${avKey}`, 'Content-Type': 'application/json' },
200
- body: body !== undefined ? JSON.stringify(body) : undefined,
201
- });
202
- const text = await res.text();
203
- if (!res.ok)
204
- throw new Error(`${method} ${avPath} → ${res.status}: ${text}`);
205
- return text ? JSON.parse(text) : {};
206
- };
207
- try {
208
- // 1. Create agent
209
- const created = await avFetch('POST', '/hosting/agents', { name: agentName });
210
- const address = created.address;
211
- if (!address)
212
- throw new Error('Agentverse did not return an agent address');
213
- // 2. Upload code (double-encoded JSON — Agentverse requirement)
214
- const codeArray = [{ language: 'python', name: 'agent.py', value: python }];
215
- await avFetch('PUT', `/hosting/agents/${address}/code`, { code: JSON.stringify(codeArray) });
216
- // 3. Inject the secrets the hosted agent needs. Never silent: a
217
- // swallowed failure here produced an agent that deploys, starts,
218
- // and then dies on its first message with no trace of why.
219
- const secrets = {};
220
- const putSecret = async (secretName, value) => {
221
- try {
222
- await avFetch('POST', '/hosting/secrets', { address, name: secretName, secret: value });
223
- secrets[secretName] = 'ok';
224
- }
225
- catch (e) {
226
- secrets[secretName] = `failed: ${e.message}`;
227
- console.error(`warning: ${secretName} was NOT set on the Agentverse agent — ${e.message}`);
228
- }
229
- };
230
- const oneKey = readApiKey();
231
- if (oneKey) {
232
- console.error('Uploading secret ONEIE_API_KEY to agentverse.ai (variable name only — the value is never printed).');
233
- await putSecret('ONEIE_API_KEY', oneKey);
234
- }
235
- else {
236
- secrets.ONEIE_API_KEY = 'skipped: no key resolved';
237
- console.error('warning: no ONE API key resolved (ONE_API_KEY / ONEIE_API_KEY / ~/.config/oneie/key) — ONEIE_API_KEY was NOT injected, so the deployed agent carries no credential for the ONE substrate. Run `oneie auth login` or set ONE_API_KEY.');
238
- }
239
- // The generated Python constructs Anthropic() with no explicit key,
240
- // so the SDK reads ANTHROPIC_API_KEY from the hosted environment.
241
- // Process env only — never a file, never invented.
242
- const anthropicKey = process.env.ANTHROPIC_API_KEY;
243
- if (anthropicKey) {
244
- console.error('Uploading secret ANTHROPIC_API_KEY to agentverse.ai — your own Anthropic credential is being sent to this third-party host so the agent can call the model (variable name only — the value is never printed).');
245
- await putSecret('ANTHROPIC_API_KEY', anthropicKey);
246
- }
247
- else {
248
- secrets.ANTHROPIC_API_KEY = 'skipped: not set in the environment';
249
- console.error('warning: ANTHROPIC_API_KEY is not set in this environment — it was NOT injected. The generated Python calls Anthropic() with no key, so this agent will fail on its first message.');
250
- }
251
- // 4. Start
252
- await avFetch('POST', `/hosting/agents/${address}/start`, {});
253
- // 5. Poll for compiled (up to 60s)
254
- let compiled = false;
255
- let walletAddress;
256
- for (let i = 0; i < 12; i++) {
257
- await new Promise(r => setTimeout(r, 5000));
258
- const status = await avFetch('GET', `/hosting/agents/${address}`);
259
- if (status.compiled || status.running) {
260
- compiled = true;
261
- walletAddress = status.wallet_address;
262
- break;
263
- }
264
- }
265
- out(cmd, {
266
- ok: true,
267
- target: 'agentverse',
268
- agentAddress: address,
269
- walletAddress,
270
- compiled,
271
- agentName,
272
- secrets,
273
- protocols: found.resolved.length,
274
- skillsDeclared: found.declared.length,
275
- skillsMissing: found.missing,
276
- agentverseUrl: `https://agentverse.ai/agents/details/${address}`,
277
- });
278
- }
279
- catch (err) {
280
- out(cmd, { ok: false, error: err.message });
281
- }
282
- return;
283
- }
284
- // ── ONE workspace publish path (default) ─────────────────────────────
285
- //
286
- // THE TOKEN IS THE PLAIN KEY. It used to be `${slug}:${key}`, and that one
287
- // line is why publish was unusable by anybody: `requireAuth`
288
- // (one.ie/web/src/lib/api-auth.ts) resolves a world key by PREFIX — `one-`
289
- // or `osk_` — so prepending "one:" turns a valid key into `one:one-abc...`,
290
- // which matches no prefix, falls through to session auth, and 401s. The same
291
- // line was copy-pasted across ten call sites in agent.ts and skill.ts, so
292
- // every workspace command in the CLI was broken the same way. The route
293
- // header comments claiming `Bearer <ownerId>:<SERVER_SECRET>` are STALE —
294
- // the code calls `requireAuthOver(request, "update_group", slug)`.
295
- //
296
- // Publish goes through the RECEIVER door rather than `/api/agents/publish`
297
- // for one reason: credential CLASS. `/api/ask/*` accepts a world key OR a
298
- // service credential; the route accepts only a world key or a browser
299
- // session. Both authorize with the same ownership walk, and since
300
- // `publishAgent` now writes the versioned archive too (world-receivers.ts),
301
- // the route no longer has any semantic the receiver lacks — so `agent
302
- // history` and `agent rollback` still see what this publishes.
303
- if (!opts.slug) {
304
- out(cmd, { ok: false, error: 'missing --slug <workspace>' });
305
- return;
306
- }
307
- const key = readApiKey();
308
- if (!key) {
309
- out(cmd, { ok: false, error: 'no API key — run `oneie auth login` or set ONE_API_KEY (legacy: ONEIE_API_KEY)' });
310
- return;
311
- }
312
- try {
313
- const res = await fetch(askPath(opts.api.replace(/\/$/, ''), 'world:publish-agent'), {
314
- method: 'POST',
315
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
316
- body: JSON.stringify({ data: { slug: opts.slug, name: agentName, content } }),
317
- });
318
- const text = await res.text();
319
- const envelope = (text ? JSON.parse(text) : {});
320
- const result = envelope.result ?? {};
321
- // THE ASK ENVELOPE ANSWERS HTTP 200 ON A REFUSAL. `outcome: "failure"`
322
- // carries the receiver's own error under a 200, so `res.ok` alone reports
323
- // a refused publish as a success. Check all three.
324
- if (!res.ok || envelope.outcome === 'failure' || result.ok === false) {
325
- // A bare "forbidden" is unactionable and its two causes need OPPOSITE
326
- // fixes, so read `callerRole` rather than guessing. `anonymous` = the
327
- // Bearer matched no world_keys row (wrong key, or not a key); anything
328
- // else = a real key the ownership walk refused for THIS workspace.
329
- const base = result.error ?? envelope.error ?? text ?? 'publish failed';
330
- const hint = result.error !== 'forbidden'
331
- ? undefined
332
- : result.callerRole === 'anonymous'
333
- ? 'the key was not recognised — run `oneie auth login`, or set ONE_API_KEY to a world key (it starts `one-` or `osk_`)'
334
- : `authenticated as ${result.callerRole}, but that identity does not control workspace "${opts.slug}"`;
335
- // out() prints only `error` in human mode, so the actionable half has to
336
- // live in that string; the structured fields stay for --json.
337
- out(cmd, {
338
- ok: false,
339
- status: res.status,
340
- error: hint ? `${base} — ${hint}` : base,
341
- ...(result.required ? { required: result.required } : {}),
342
- ...(result.callerRole ? { callerRole: result.callerRole } : {}),
343
- });
344
- return;
345
- }
346
- out(cmd, {
347
- ok: true,
348
- name: agentName,
349
- url: result.url,
350
- bytes: result.bytes,
351
- subscribes: result.subscribes ?? [],
352
- });
353
- }
354
- catch (err) {
355
- out(cmd, { ok: false, error: err.message });
356
- }
357
- });
358
- cmd.addCommand(agentverseCmd());
359
- cmd.command('pull <name>')
360
- .description('Download a published agent.md from your workspace into the current directory')
361
- .option('--slug <slug>', 'Workspace slug (required)')
362
- .option('--api <url>', 'API base URL', DEFAULT_API)
363
- .option('--out <path>', 'Output path (defaults to <name>/agent.md)')
364
- .action(async (name, opts) => {
365
- if (!opts.slug) {
366
- out(cmd, { ok: false, error: 'missing --slug <workspace>' });
367
- return;
368
- }
369
- const key = readApiKey();
370
- if (!key) {
371
- out(cmd, { ok: false, error: 'no API key — run `oneie auth login --key <key>` or set ONE_API_KEY (legacy: ONEIE_API_KEY)' });
372
- return;
373
- }
374
- const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
375
- const url = `${opts.api.replace(/\/$/, '')}/api/agents/publish?slug=${encodeURIComponent(opts.slug)}&name=${encodeURIComponent(name)}`;
376
- try {
377
- const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
378
- const text = await res.text();
379
- const data = text ? JSON.parse(text) : {};
380
- if (!res.ok) {
381
- out(cmd, { ok: false, status: res.status, error: data.error ?? text ?? 'pull failed' });
382
- return;
383
- }
384
- const outPath = opts.out ?? `${name}/agent.md`;
385
- mkdirSync(dirname(outPath), { recursive: true });
386
- writeFileSync(outPath, String(data.content ?? ''));
387
- out(cmd, { ok: true, path: outPath, bytes: data.bytes, key: data.key });
388
- }
389
- catch (err) {
390
- out(cmd, { ok: false, error: err.message });
391
- }
392
- });
393
- cmd.command('unpublish <name>')
394
- .description('Remove a published agent from your workspace')
395
- .option('--slug <slug>', 'Workspace slug (required)')
396
- .option('--api <url>', 'API base URL', DEFAULT_API)
397
- .action(async (name, opts) => {
398
- if (!opts.slug) {
399
- out(cmd, { ok: false, error: 'missing --slug <workspace>' });
400
- return;
401
- }
402
- const key = readApiKey();
403
- if (!key) {
404
- out(cmd, { ok: false, error: 'no API key — run `oneie auth login --key <key>` or set ONE_API_KEY (legacy: ONEIE_API_KEY)' });
405
- return;
406
- }
407
- const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
408
- const url = `${opts.api.replace(/\/$/, '')}/api/agents/publish?slug=${encodeURIComponent(opts.slug)}&name=${encodeURIComponent(name)}`;
409
- try {
410
- const res = await fetch(url, { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } });
411
- const text = await res.text();
412
- const data = text ? JSON.parse(text) : {};
413
- if (!res.ok) {
414
- out(cmd, { ok: false, status: res.status, error: data.error ?? text ?? 'unpublish failed' });
415
- return;
416
- }
417
- out(cmd, { ok: true, ...data });
418
- }
419
- catch (err) {
420
- out(cmd, { ok: false, error: err.message });
421
- }
422
- });
423
- cmd.command('sign <path>')
424
- .description('Sign agent with Sigstore keyless')
425
- .action((path) => {
426
- if (!existsSync(path)) {
427
- out(cmd, { ok: false, error: `not found: ${path}` });
428
- return;
429
- }
430
- out(cmd, { ok: true, path, bundle: 'pending — run oneie publish to trigger Sigstore' });
431
- });
432
- cmd.command('verify <path>')
433
- .description('Verify agent signatures and digests')
434
- .action((path) => {
435
- const exists = existsSync(path);
436
- out(cmd, { ok: exists, path, verified: exists ? 1 : 0, signatures: 0 });
437
- });
438
- cmd.command('eval <path>')
439
- .description('Run evals from the agent frontmatter evals: block (local) or via --slug for remote chat API')
440
- .option('--slug <slug>', 'Workspace slug — enables remote eval via /api/chat')
441
- .option('--api <url>', 'API base URL (remote mode only)', DEFAULT_API)
442
- .action(async (path, opts) => {
443
- if (!existsSync(path)) {
444
- out(cmd, { ok: false, error: `not found: ${path}` });
445
- return;
446
- }
447
- const raw = readFileSync(path, 'utf8');
448
- // Extract evals: block from frontmatter via regex
449
- const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
450
- if (!fmMatch) {
451
- out(cmd, { ok: false, error: 'no frontmatter found in agent.md' });
452
- return;
453
- }
454
- const fm = fmMatch[1];
455
- const promptBody = raw.slice(raw.indexOf('---', 3) + 3).trim();
456
- // Parse evals: as simple YAML list items { input, expect }
457
- const evalRe = /^\s+-\s+input:\s+"([^"]+)"\s*\n\s+expect:\s+"([^"]+)"/gm;
458
- const evalAlt = /^\s+-\s+input:\s+'([^']+)'\s*\n\s+expect:\s+'([^']+)'/gm;
459
- const cases = [];
460
- let m;
461
- while ((m = evalRe.exec(fm)) !== null)
462
- cases.push({ input: m[1], expect: m[2] });
463
- while ((m = evalAlt.exec(fm)) !== null)
464
- cases.push({ input: m[1], expect: m[2] });
465
- if (cases.length === 0) {
466
- out(cmd, { ok: false, error: 'no eval cases found — add evals: [ {input: "...", expect: "..."} ] to frontmatter' });
467
- return;
468
- }
469
- if (opts.slug) {
470
- // Remote mode: call /api/chat with messages + agentId
471
- const key = readApiKey();
472
- if (!key) {
473
- out(cmd, { ok: false, error: 'no API key for remote eval — set ONE_API_KEY (legacy: ONEIE_API_KEY) or run `oneie auth login`' });
474
- return;
475
- }
476
- const nameMatch = /^name:\s+([a-z0-9-]+)/m.exec(fm);
477
- const agentId = nameMatch?.[1];
478
- if (!agentId) {
479
- out(cmd, { ok: false, error: 'agent frontmatter missing name: field' });
480
- return;
481
- }
482
- let passed = 0, failed = 0;
483
- for (const c of cases) {
484
- try {
485
- const res = await fetch(`${opts.api.replace(/\/$/, '')}/api/chat`, {
486
- method: 'POST',
487
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
488
- body: JSON.stringify({ messages: [{ role: 'user', content: c.input }], agentId, slug: opts.slug }),
489
- });
490
- const text = await res.text();
491
- const ok = text.toLowerCase().includes(c.expect.toLowerCase());
492
- if (ok)
493
- passed++;
494
- else
495
- failed++;
496
- }
497
- catch {
498
- failed++;
499
- }
500
- }
501
- out(cmd, { ok: true, path, mode: 'remote', slug: opts.slug, agentId, passed, failed, total: cases.length });
502
- }
503
- else {
504
- // Local mode: check if agent prompt body contains expected keywords
505
- let passed = 0, failed = 0;
506
- for (const c of cases) {
507
- const ok = promptBody.toLowerCase().includes(c.expect.toLowerCase());
508
- if (ok)
509
- passed++;
510
- else
511
- failed++;
512
- }
513
- out(cmd, { ok: true, path, mode: 'local', passed, failed, total: cases.length });
514
- }
515
- });
516
- cmd.command('diff <a> <b>')
517
- .description('Semantic diff between two agent.md files')
518
- .action((a, b) => {
519
- if (!existsSync(a)) {
520
- out(cmd, { ok: false, error: `not found: ${a}` });
521
- return;
522
- }
523
- if (!existsSync(b)) {
524
- out(cmd, { ok: false, error: `not found: ${b}` });
525
- return;
526
- }
527
- out(cmd, { ok: true, a, b, ...semanticDiff(a, b) });
528
- });
529
- // C1 — agent dev: watch file, re-validate on change
530
- cmd.command('dev <path>')
531
- .description('Watch an agent.md file and re-validate on every change')
532
- .action((path) => {
533
- if (!existsSync(path)) {
534
- console.error(`not found: ${path}`);
535
- process.exit(1);
536
- }
537
- console.log(`Watching ${path} — press Ctrl+C to stop\n`);
538
- const run = () => {
539
- const { meta, issues } = (() => {
540
- try {
541
- const raw = readFileSync(path, 'utf8');
542
- const delta = parseQuickMd(path);
543
- const errs = issues_from_quick(delta, raw);
544
- return { meta: delta, issues: errs };
545
- }
546
- catch (e) {
547
- return { meta: null, issues: [{ level: 'error', path: '<read>', message: String(e) }] };
548
- }
549
- })();
550
- const errors = issues.filter((i) => i.level === 'error');
551
- const warns = issues.filter((i) => i.level === 'warn');
552
- if (errors.length === 0 && warns.length === 0) {
553
- console.log(`✓ ${new Date().toLocaleTimeString()} — valid`);
554
- }
555
- else {
556
- if (errors.length)
557
- console.log(`✗ ${errors.length} error(s):`);
558
- errors.forEach((i) => console.log(` [error] ${i.path}: ${i.message}`));
559
- if (warns.length)
560
- console.log(` ${warns.length} warning(s):`);
561
- warns.forEach((i) => console.log(` [warn] ${i.path}: ${i.message}`));
562
- }
563
- };
564
- run();
565
- watch(path, () => { console.log(''); run(); });
566
- });
567
- // C2 — agent list: list published agents for a workspace
568
- cmd.command('list')
569
- .description('List published agents for a workspace')
570
- .requiredOption('--slug <slug>', 'Workspace slug')
571
- .option('--api <url>', 'API base URL', DEFAULT_API)
572
- .action(async (opts) => {
573
- const key = readApiKey();
574
- if (!key) {
575
- out(cmd, { ok: false, error: 'no API key — set ONE_API_KEY (legacy: ONEIE_API_KEY) or run `oneie auth login`' });
576
- return;
577
- }
578
- const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
579
- const url = `${opts.api.replace(/\/$/, '')}/api/agents/list?slug=${encodeURIComponent(opts.slug)}`;
580
- try {
581
- const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
582
- const data = await res.json();
583
- if (!res.ok) {
584
- out(cmd, { ok: false, ...data });
585
- return;
586
- }
587
- out(cmd, { ok: true, ...data });
588
- }
589
- catch (e) {
590
- out(cmd, { ok: false, error: String(e) });
591
- }
592
- });
593
- // C3 — agent history: show version history for an agent
594
- cmd.command('history <name>')
595
- .description('Show version history for a published agent')
596
- .requiredOption('--slug <slug>', 'Workspace slug')
597
- .option('--api <url>', 'API base URL', DEFAULT_API)
598
- .action(async (name, opts) => {
599
- const key = readApiKey();
600
- if (!key) {
601
- out(cmd, { ok: false, error: 'no API key — set ONE_API_KEY (legacy: ONEIE_API_KEY) or run `oneie auth login`' });
602
- return;
603
- }
604
- const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
605
- const url = `${opts.api.replace(/\/$/, '')}/api/agents/history?slug=${encodeURIComponent(opts.slug)}&name=${encodeURIComponent(name)}`;
606
- try {
607
- const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
608
- const data = await res.json();
609
- if (!res.ok) {
610
- out(cmd, { ok: false, ...data });
611
- return;
612
- }
613
- out(cmd, { ok: true, ...data });
614
- }
615
- catch (e) {
616
- out(cmd, { ok: false, error: String(e) });
617
- }
618
- });
619
- // C4 — agent rollback: restore agent to a previous version
620
- cmd.command('rollback <name>')
621
- .description('Restore a published agent to a previous version')
622
- .requiredOption('--slug <slug>', 'Workspace slug')
623
- .requiredOption('--to <ts>', 'Epoch-ms timestamp of the version to restore (from agent history)')
624
- .option('--yes', 'Skip confirmation prompt')
625
- .option('--api <url>', 'API base URL', DEFAULT_API)
626
- .action(async (name, opts) => {
627
- const key = readApiKey();
628
- if (!key) {
629
- out(cmd, { ok: false, error: 'no API key — set ONE_API_KEY (legacy: ONEIE_API_KEY) or run `oneie auth login`' });
630
- return;
631
- }
632
- const ts = parseInt(opts.to, 10);
633
- if (isNaN(ts)) {
634
- out(cmd, { ok: false, error: `--to must be a numeric timestamp (got "${opts.to}")` });
635
- return;
636
- }
637
- if (!opts.yes) {
638
- process.stdout.write(`Roll back ${opts.slug}/${name} to version ${ts}? [y/N] `);
639
- const confirmed = await new Promise((resolve) => {
640
- process.stdin.once('data', (d) => resolve(d.toString().trim().toLowerCase() === 'y'));
641
- process.stdin.resume();
642
- });
643
- process.stdin.pause();
644
- if (!confirmed) {
645
- console.log('Aborted.');
646
- return;
647
- }
648
- }
649
- const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
650
- const url = `${opts.api.replace(/\/$/, '')}/api/agents/rollback`;
651
- try {
652
- const res = await fetch(url, {
653
- method: 'POST',
654
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
655
- body: JSON.stringify({ slug: opts.slug, name, ts }),
656
- });
657
- const data = await res.json();
658
- if (!res.ok) {
659
- out(cmd, { ok: false, ...data });
660
- return;
661
- }
662
- out(cmd, { ok: true, ...data });
663
- }
664
- catch (e) {
665
- out(cmd, { ok: false, error: String(e) });
666
- }
667
- });
668
- // TPL2 — agent ai-edit: apply a natural-language instruction to an agent.md
669
- cmd.command('ai-edit <path>')
670
- .description('Apply a natural-language instruction to an agent.md using Claude')
671
- .requiredOption('--prompt <instruction>', 'What to change, e.g. "make the tone more formal"')
672
- .option('--model <model>', 'Claude model', 'claude-haiku-4-5-20251001')
673
- .option('--yes', 'Write without diff preview')
674
- .action(async (filePath, opts) => {
675
- const apiKey = process.env.ANTHROPIC_API_KEY;
676
- if (!apiKey) {
677
- out(cmd, { ok: false, error: 'ANTHROPIC_API_KEY not set' });
678
- return;
679
- }
680
- if (!existsSync(filePath)) {
681
- out(cmd, { ok: false, error: `not found: ${filePath}` });
682
- return;
683
- }
684
- const original = readFileSync(filePath, 'utf8');
685
- console.log(`Applying instruction to ${filePath}…`);
686
- let revised = '';
687
- try {
688
- const res = await fetch('https://api.anthropic.com/v1/messages', {
689
- method: 'POST',
690
- headers: {
691
- 'Content-Type': 'application/json',
692
- 'x-api-key': apiKey,
693
- 'anthropic-version': '2023-06-01',
694
- },
695
- body: JSON.stringify({
696
- model: opts.model,
697
- max_tokens: 4096,
698
- messages: [
699
- {
700
- role: 'user',
701
- content: `You are editing an agent.md file. Return ONLY the updated file — no explanation, no markdown fences.
702
-
703
- Instruction: ${opts.prompt}
704
-
705
- --- agent.md ---
706
- ${original}`,
707
- },
708
- ],
709
- }),
710
- });
711
- if (!res.ok) {
712
- const err = await res.text();
713
- out(cmd, { ok: false, error: `Anthropic API error: ${err}` });
714
- return;
715
- }
716
- const data = await res.json();
717
- revised = data.content.find((b) => b.type === 'text')?.text?.trim() ?? '';
718
- if (!revised) {
719
- out(cmd, { ok: false, error: 'empty response from Claude' });
720
- return;
721
- }
722
- }
723
- catch (e) {
724
- out(cmd, { ok: false, error: `fetch failed: ${String(e)}` });
725
- return;
726
- }
727
- if (!opts.yes) {
728
- // Simple line-level diff preview
729
- const origLines = original.split('\n');
730
- const newLines = revised.split('\n');
731
- const maxLen = Math.max(origLines.length, newLines.length);
732
- let changes = 0;
733
- for (let i = 0; i < maxLen; i++) {
734
- const o = origLines[i] ?? '';
735
- const n = newLines[i] ?? '';
736
- if (o !== n) {
737
- if (changes === 0)
738
- console.log('\nDiff preview (first 20 changes):');
739
- if (changes < 20) {
740
- if (o)
741
- console.log(`- ${o}`);
742
- if (n)
743
- console.log(`+ ${n}`);
744
- }
745
- changes++;
746
- }
747
- }
748
- if (changes === 0) {
749
- console.log('No changes detected.');
750
- return;
751
- }
752
- console.log(`\n${changes} line(s) changed. Pass --yes to write.`);
753
- return;
754
- }
755
- writeFileSync(filePath, revised, 'utf8');
756
- out(cmd, { ok: true, path: filePath, instruction: opts.prompt });
757
- });
758
- // TPL1 — agent templates: list available starter templates
759
- cmd.command('templates')
760
- .description('List available agent starter templates')
761
- .action(() => {
762
- const list = Object.keys(TEMPLATES).map((name) => {
763
- const tpl = TEMPLATES[name];
764
- const titleMatch = tpl.match(/^title:\s*(.+)$/m);
765
- return { name, title: titleMatch ? titleMatch[1].trim() : name };
766
- });
767
- out(cmd, { ok: true, templates: list });
768
- });
769
- // TPL1 — agent fork: clone a template with a new name
770
- cmd.command('fork <template> <local-name>')
771
- .description('Clone a starter template into <local-name>/agent.md')
772
- .action((template, localName) => {
773
- if (!/^[a-z0-9][a-z0-9-]*$/.test(localName)) {
774
- out(cmd, { ok: false, error: 'local-name must be lowercase alphanumeric with hyphens only' });
775
- return;
776
- }
777
- const tpl = TEMPLATES[template];
778
- if (!tpl) {
779
- out(cmd, { ok: false, error: `unknown template: ${template}. Run "oneie agent templates" to list available templates.` });
780
- return;
781
- }
782
- const body = tpl.replace(/\bname:\s*\S+/m, `name: ${localName}`)
783
- .replace(/\btitle:\s*.+/m, (m) => m.replace(/template/gi, localName));
784
- const dir = localName;
785
- const outPath = `${dir}/agent.md`;
786
- if (existsSync(outPath)) {
787
- out(cmd, { ok: false, error: `${outPath} already exists` });
788
- return;
789
- }
790
- if (!existsSync(dir))
791
- mkdirSync(dir, { recursive: true });
792
- writeFileSync(outPath, body);
793
- out(cmd, { ok: true, path: outPath, template, name: localName });
794
- });
795
- return cmd;
796
- }
797
- function out(cmd, data) {
798
- const isJson = cmd.parent?.opts().json;
799
- if (isJson) {
800
- process.stdout.write(JSON.stringify(data) + '\n');
801
- }
802
- else if (data.ok) {
803
- const pairs = Object.entries(data)
804
- .filter(([k]) => k !== 'ok')
805
- .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
806
- .join(' ');
807
- console.log('✓', pairs);
808
- }
809
- else {
810
- const detail = data.error ?? data.errors ?? data.issues ?? data;
811
- console.error('✗', typeof detail === 'string' ? detail : JSON.stringify(detail));
812
- // Match the shared out() in lib/client.ts. Without this every `agent`
813
- // failure — including an unimplemented compile target — exited 0, so a CI
814
- // script could not tell a refusal from a success.
815
- process.exitCode = 1;
816
- }
817
- }
818
- /**
819
- * Structural validation — mirrors the rules enforced by the web's Zod schema
820
- * (web/src/lib/agent-schema.ts) without pulling Zod or js-yaml into the CLI
821
- * dependency graph. Catches the contract violations partners hit most often:
822
- * missing frontmatter, name shape, journey/section anchor mismatches, chip
823
- * id collisions, kebab-case ids. Anything outside these rules falls through
824
- * to the live server-side validation when the agent is published.
825
- */
826
- // ── The ONE agent spec — text/agents-spec.md ─────────────────────────────────
827
- //
828
- // Six programs read a `kind: agent` file and each reads a different key set. The
829
- // spec is derived from what they do; these constants are its machine half. Keep
830
- // them in step with the spec's field table — the test asserts the shape.
831
- /** Required: a reader REFUSES or silently SUBSTITUTES identity without it.
832
- * name → publish refuses (world-receivers.ts:1407). kind → one-agents.mjs:191
833
- * skips the file. (The non-empty body is checked separately.) */
834
- export const AGENT_REQUIRED = ['name', 'kind'];
835
- /** Recommended: every reader falls back without it, but the fallback is a
836
- * different agent on the page (title → dir, description → 'Generic helpful
837
- * assistant', tier/domain → inferred from the id). Warned when absent. */
838
- export const AGENT_RECOMMENDED = ['title', 'tier', 'domain', 'subscribes'];
839
- /** The closed enums the web schema owns (agent-schema.ts) — role-types.ts INFERS
840
- * a value from the id when the declared one is off-enum, so an off-enum value
841
- * is a silent re-placement on the org chart, not a load failure. */
842
- export const AGENT_ENUMS = {
843
- kind: ['agent', 'skill', 'pack', 'seed'],
844
- tier: ['chairman', 'ceo', 'director', 'specialist'],
845
- domain: ['marketing', 'sales', 'service', 'education', 'engineering', 'finance', 'community', 'governance'],
846
- tone: ['primary', 'secondary', 'tertiary', 'neutral'],
847
- };
848
- /** Keys the channels parser (channels/src/lib/agent-md.ts) can only read as a
849
- * BLOCK list. An inline `[a, b]` is stored as the string "[a, b]", so
850
- * `Array.isArray` fails in resolvePersona and the field is dropped at runtime. */
851
- export const AGENT_BLOCK_LIST_KEYS = ['tools', 'subscribes', 'emits', 'skills', 'tags'];
852
- /** Every top-level key at least one reader consumes — the union of AgentMeta
853
- * (agent-md.ts:435), agentFrontmatterSchema (agent-schema.ts:229), Persona
854
- * (channels/src/context.ts:590), compile.ts:319, one-agents.mjs:130,
855
- * role-types.ts and the publish path. A key outside this set is read by
856
- * nothing; the validator names it rather than refusing it. `direction` is NOT here on
857
- * purpose: C20 deleted it from 118 corpus files (0 readers; 93/95 `bidirectional`
858
- * merely restated subscribes+emits, the rest contradicted them) — keeping it out
859
- * is what makes `--strict` refuse a resurrection. */
860
- export const AGENT_KNOWN_KEYS = new Set([
861
- // identity + chart
862
- 'agentmd', 'name', 'kind', 'title', 'tier', 'reports_to', 'reportsTo', 'tone', 'icon', 'iconName', 'uid',
863
- 'tagline', 'domain', 'kpis', 'description', 'version', 'model', 'group', 'tags', 'channels', 'lifecycle',
864
- 'sensitivity', 'starters', 'skills', 'tools', 'features', 'subscribes', 'emits', 'url',
865
- // runtime (Persona)
866
- 'intents', 'maxSteps', 'integrations', 'hooks', 'remote', 'subAgents',
867
- // uAgents compile
868
- 'seed', 'port', 'agentverse', 'mailbox', 'startup', 'shutdown', 'intervals', 'endpoints', 'bureau',
869
- 'when_to_use', 'inputSchema', 'outputSchema', 'summary', 'evals',
870
- // payments
871
- 'wallet', 'accepts', 'price', 'currency',
872
- // A/B + web-only blocks
873
- 'variants', 'goals', 'journey', 'sections', 'branding', 'theme', 'ui', 'funnel', 'analytics', 'i18n', 'triggers',
874
- ]);
875
- /** Top-level frontmatter keys — a column-0 `key:` line. The same extraction the
876
- * corpus histogram in text/agents-spec.md used, so validator and measurement
877
- * agree by construction. */
878
- function topLevelKeys(fm) {
879
- const keys = [];
880
- const re = /^([A-Za-z_][A-Za-z0-9_-]*):/gm;
881
- let m;
882
- while ((m = re.exec(fm)))
883
- keys.push(m[1]);
884
- return keys;
885
- }
886
- /** The scalar value of a top-level `key:` line, unquoted, trailing `# comment` stripped. */
887
- function scalarOf(fm, key) {
888
- const m = new RegExp(`^${key}:[ \\t]*(.*)$`, 'm').exec(fm);
889
- if (!m)
890
- return undefined;
891
- return m[1].replace(/\s+#.*$/, '').trim().replace(/^["']|["']$/g, '');
892
- }
893
- export function validate(path, opts = {}) {
894
- const errors = [];
895
- const warnings = [];
896
- const unknownKeys = [];
897
- const door = opts.door ?? 'validate';
898
- const done = () => {
899
- if (opts.strict && door === 'validate') {
900
- errors.push(...warnings);
901
- warnings.length = 0;
902
- }
903
- return { errors, warnings, unknownKeys };
904
- };
905
- if (!existsSync(path)) {
906
- errors.push(`not found: ${path}`);
907
- return done();
908
- }
909
- const text = readFileSync(path, 'utf8');
910
- if (!text.startsWith('---')) {
911
- errors.push('missing frontmatter — agent.md must start with `---`');
912
- return done();
913
- }
914
- const fmMatch = text.match(/^---\n([\s\S]*?)\n---/);
915
- if (!fmMatch) {
916
- errors.push('frontmatter not terminated — missing closing `---`');
917
- return done();
918
- }
919
- const fm = fmMatch[1];
920
- const body = text.slice(fmMatch[0].length).trim();
921
- const nameMatch = /^name:\s*(\S+)/m.exec(fm);
922
- if (!nameMatch) {
923
- errors.push('missing required field: name');
924
- }
925
- else if (!/^[a-z0-9][a-z0-9-]*$/.test(nameMatch[1])) {
926
- errors.push(`name "${nameMatch[1]}" must be kebab-case (lowercase, digits, hyphens)`);
927
- }
928
- // Stage ids and section anchors should agree. Scan the YAML lines without
929
- // a full parser — good enough for catching the common authoring mistake.
930
- const stageIds = new Set();
931
- const stageRe = /^\s+-\s+id:\s+([a-z0-9-]+)\s*$/gm;
932
- let m;
933
- while ((m = stageRe.exec(fm)))
934
- stageIds.add(m[1]);
935
- const sectionIds = new Set();
936
- const sectionRe = /^\s+-\s+kind:\s+\S+\s*\n\s+id:\s+([a-z0-9-]+)/gm;
937
- while ((m = sectionRe.exec(fm)))
938
- sectionIds.add(m[1]);
939
- // Stage anchors `sections: [foo, bar]` should resolve to known section ids.
940
- // Strip quotes BEFORE the leading `#` — otherwise `'#brand'` keeps the hash.
941
- const anchorRe = /^\s+sections:\s*\[([^\]]+)\]/gm;
942
- while ((m = anchorRe.exec(fm))) {
943
- const refs = m[1].split(',').map((s) => s.trim().replace(/['"]/g, '').replace(/^#/, ''));
944
- for (const ref of refs) {
945
- if (ref && !sectionIds.has(ref)) {
946
- errors.push(`stage references section "${ref}" but no section with that id exists`);
947
- }
948
- }
949
- }
950
- // The publish door stops here — its gate is the receiver's own (name), and
951
- // the spec forbids a door changing behaviour under a stricter validator.
952
- if (door === 'publish')
953
- return done();
954
- // ── The spec's required set (text/agents-spec.md § required) ──────────────
955
- const keys = topLevelKeys(fm);
956
- const present = new Set(keys);
957
- const kind = scalarOf(fm, 'kind');
958
- if (!present.has('kind') || !kind) {
959
- errors.push('missing required field: kind — `kind: agent` is what one-agents.mjs:191 and the spec key on; without it the file is the other genus (text/template-agent.md)');
960
- }
961
- else if (kind !== 'agent') {
962
- errors.push(`kind: ${kind} — \`agent validate\` checks the kind: agent spec; a ${kind} file goes through \`oneie skill validate\``);
963
- }
964
- if (!body) {
965
- errors.push('empty body — the markdown after the closing `---` IS the system prompt; empty, channels substitutes personas.one.systemPrompt (context.ts:593) and the agent silently becomes a different agent');
966
- }
967
- // ── Recommended: absent → a fallback that is a different agent on the page ──
968
- for (const k of AGENT_RECOMMENDED) {
969
- if (!present.has(k))
970
- warnings.push(`missing recommended field: ${k}`);
971
- }
972
- if (!present.has('description') && !present.has('tagline')) {
973
- warnings.push('missing recommended field: description (or tagline) — Persona falls back to "Generic helpful assistant" (personas.ts:60)');
974
- }
975
- else if (!present.has('description') && present.has('tagline')) {
976
- warnings.push('tagline without description — the chart reads tagline (role-types.ts:396); the runtime reads only description (context.ts:591) and will answer as "Generic helpful assistant"');
977
- }
978
- // ── Off-enum values: the chart INFERS a placement instead of using yours ───
979
- for (const [k, allowed] of Object.entries(AGENT_ENUMS)) {
980
- if (k === 'kind')
981
- continue;
982
- const v = scalarOf(fm, k);
983
- if (v !== undefined && v !== '' && !allowed.includes(v)) {
984
- warnings.push(`${k}: ${v} is not one of ${allowed.join('|')} — the web schema reports it and role-types.ts infers ${k} from the id instead`);
985
- }
986
- }
987
- // ── Shapes the runtime cannot read ─────────────────────────────────────────
988
- for (const k of AGENT_BLOCK_LIST_KEYS) {
989
- if (new RegExp(`^${k}:[ \\t]*\\[`, 'm').test(fm)) {
990
- warnings.push(`${k}: is an inline [a, b] list — channels/src/lib/agent-md.ts stores it as a string and resolvePersona drops it; write a block list`);
991
- }
992
- }
993
- if (/^\s+-\s+(signal|tag):\s/m.test(fm)) {
994
- warnings.push('a `- signal: <tag>` list item — web keeps bare strings only, channels keeps the value, one-agents.mjs strips the prefix; write the bare tag');
995
- }
996
- // ── Keys read by nothing — named, never silently accepted ─────────────────
997
- for (const k of keys) {
998
- if (!AGENT_KNOWN_KEYS.has(k) && !unknownKeys.includes(k))
999
- unknownKeys.push(k);
1000
- }
1001
- if (unknownKeys.length) {
1002
- warnings.push(`unknown keys (read by no reader): ${unknownKeys.join(', ')}`);
1003
- }
1004
- return done();
1005
- }
1006
- function lint(path) {
1007
- if (!existsSync(path))
1008
- return [`not found: ${path}`];
1009
- const text = readFileSync(path, 'utf8');
1010
- const issues = [];
1011
- const fmMatch = text.match(/^---\n([\s\S]*?)\n---/);
1012
- const fm = fmMatch ? fmMatch[1] : '';
1013
- if (!/^description:/m.test(fm)) {
1014
- issues.push('missing description (one-line tagline shown on /agents and in chat)');
1015
- }
1016
- if (!/^title:/m.test(fm)) {
1017
- issues.push('missing title (display name distinct from kebab-case `name`)');
1018
- }
1019
- if (/^price:/m.test(fm) && !/^accepts:/m.test(fm)) {
1020
- issues.push('prefer accepts[] over price shorthand for multi-chain support');
1021
- }
1022
- // Chip id length — Zod warns when label > 28 chars. CLI does the same.
1023
- // Strip inline YAML comments before measuring; otherwise " # this is..." inflates length.
1024
- const labelRe = /^\s+label:\s+["']?([^"'\n#]+?)["']?(?:\s+#.*)?$/gm;
1025
- let m;
1026
- while ((m = labelRe.exec(fm))) {
1027
- const label = m[1].trim();
1028
- if (label.length > 28) {
1029
- issues.push(`label "${label}" is ${label.length} chars — wraps awkwardly above 28`);
1030
- }
1031
- }
1032
- // Stage continuation count — Zod schema caps at 4 per stage.
1033
- const stageBlocks = fm.split(/^\s+-\s+id:/m).slice(1);
1034
- for (const block of stageBlocks) {
1035
- const cont = /^\s+continuations:\s*\n((?:\s+-\s+id:[\s\S]*?)+)$/m.exec(block);
1036
- if (cont) {
1037
- const count = (cont[1].match(/^\s+-\s+id:/gm) ?? []).length;
1038
- if (count > 4) {
1039
- issues.push(`stage has ${count} continuations — max 4 fit the chip strip cleanly`);
1040
- }
1041
- }
1042
- }
1043
- return issues;
1044
- }
1045
- /**
1046
- * Targets the CLI can actually emit. `a2a` and `erc8004` were advertised in
1047
- * --target help and in the docs but had no branch — they fell through to
1048
- * `return content`, echoing the raw agent.md back as if it had compiled. They
1049
- * now FAIL LOUDLY: there is no a2a/erc8004 compiler anywhere in @oneie/sdk to
1050
- * delegate to, and inventing one here would be worse than an honest error.
1051
- */
1052
- export const CLI_TARGETS = ['mcp', 'uagents', 'skillmd', 'web'];
1053
- const UNIMPLEMENTED_TARGETS = {
1054
- a2a: 'no A2A agent-card compiler exists in @oneie/sdk/compile',
1055
- erc8004: 'no ERC-8004 identity-registry compiler exists in @oneie/sdk/compile',
1056
- };
1057
- /**
1058
- * Targets whose output is derived from the resolved skill markdown, and the
1059
- * noun each one actually emits — `mcp` emits tools, not protocols.
1060
- */
1061
- const TARGETS_USING_SKILLS = {
1062
- mcp: 'tools',
1063
- uagents: 'protocols (Protocol + on_message handlers)',
1064
- skillmd: 'SKILL.md blocks',
1065
- };
1066
- /**
1067
- * Resolve the skill markdown an agent's frontmatter declares.
1068
- *
1069
- * `compileAgent` derives uAgents protocols and MCP tools from a `skills` map
1070
- * keyed by skill name; with no map, `hasSkills` is false and NO on_message
1071
- * handler is emitted — every agent the CLI ever published to Agentverse was a
1072
- * shell with zero protocols. Callers pass the result through so the compiler's
1073
- * skills-to-protocols path is actually reachable.
1074
- *
1075
- * Layouts searched (both the flat `skill new` layout and the `skill emit`
1076
- * SKILL.md directory layout), nearest to the agent first.
1077
- */
1078
- function resolveSkillMds(agentPath, content, skillsDir) {
1079
- const { meta } = parseAgentMd(content);
1080
- const declared = (meta.skills ?? [])
1081
- .map(s => ('ref' in s ? s.ref : s.name))
1082
- .filter((n) => Boolean(n));
1083
- const dir = dirname(resolve(agentPath));
1084
- const roots = [
1085
- ...(skillsDir ? [resolve(skillsDir)] : []),
1086
- join(dir, 'skills'),
1087
- join(dir, '..', 'skills'),
1088
- resolve('skills'),
1089
- resolve('ai', 'skills'),
1090
- ];
1091
- const skills = {};
1092
- const missing = [];
1093
- for (const name of declared) {
1094
- let found;
1095
- for (const root of roots) {
1096
- for (const candidate of [join(root, `${name}.md`), join(root, name, 'SKILL.md')]) {
1097
- if (existsSync(candidate)) {
1098
- found = candidate;
1099
- break;
1100
- }
1101
- }
1102
- if (found)
1103
- break;
1104
- }
1105
- if (found)
1106
- skills[name] = readFileSync(found, 'utf8');
1107
- else
1108
- missing.push(name);
1109
- }
1110
- return { skills, declared, resolved: Object.keys(skills), missing, roots };
1111
- }
1112
- /**
1113
- * Never let a zero-protocol compile pass silently. Warnings go to stderr so
1114
- * `--json` stdout stays one machine-readable line.
1115
- */
1116
- function warnSkillGap(found, target) {
1117
- const noun = TARGETS_USING_SKILLS[target] ?? 'capabilities';
1118
- if (found.declared.length === 0) {
1119
- console.error(`warning: this agent declares no skills: — the compiled ${target} output has ZERO ${noun}.`);
1120
- return;
1121
- }
1122
- if (found.missing.length) {
1123
- console.error(`warning: ${found.missing.length}/${found.declared.length} declared skill(s) have no markdown file and were DROPPED: ${found.missing.join(', ')}`);
1124
- console.error(` searched, per skill <name>: ${found.roots.map(r => `${r}/<name>.md`).join(', ')} (and <root>/<name>/SKILL.md). Pass --skills <dir> to point elsewhere.`);
1125
- }
1126
- if (found.resolved.length === 0) {
1127
- console.error(`warning: ZERO skills resolved — the compiled ${target} output has ZERO ${noun}.`);
1128
- if (target === 'uagents') {
1129
- console.error(' A hosted agent with no protocols cannot answer a message.');
1130
- }
1131
- }
1132
- }
1133
- /** Why each recommended field is worth declaring. Absent ⇒ a capability the hosted agent simply does not have. */
1134
- const AGENTVERSE_RECOMMENDED = [
1135
- ['agentverse', 'no Agentverse registration URL — the agent is hosted but not discoverable by name'],
1136
- ['mailbox', 'mailbox is off — the agent can only be reached while it is running, never asynchronously'],
1137
- ['endpoints', 'no endpoints — nothing outside the uAgents protocol can call it'],
1138
- ['bureau', 'no bureau — it runs alone rather than beside its siblings'],
1139
- ['port', 'no port — the compiler leaves the uAgents default (8000)'],
1140
- ['when_to_use', 'no when_to_use — a discovering agent has nothing to route on'],
1141
- ['version', 'no version — two deploys are indistinguishable in the registry'],
1142
- // The three that emit BEHAVIOUR rather than configuration. Listed for the same
1143
- // reason as the rest — the cycle enumerated eleven fields and a list silently
1144
- // covering seven of them reads as an oversight — but they are the ones an operator
1145
- // should most often decline: each buys a real model call on a schedule.
1146
- ['intervals', 'no intervals — the agent only ever speaks when spoken to'],
1147
- ['startup', 'no startup — it announces nothing when it boots'],
1148
- ['shutdown', 'no shutdown — it announces nothing when it stops'],
1149
- ];
1150
- /**
1151
- * Is this agent.md ready to be a HOSTED Agentverse agent?
1152
- *
1153
- * `seed` is the only REQUIRED field, and it is required for one reason: it is the
1154
- * deterministic identity. Without it every deploy of the same file is a different
1155
- * agent as far as the network is concerned — a fresh address, so every peer that
1156
- * learned the old one is now talking to nobody.
1157
- */
1158
- export function agentverseReadiness(agentMd) {
1159
- const { meta } = parseAgentMd(agentMd);
1160
- const missing = [];
1161
- // The emitter's own predicate (compile.ts:512), deliberately — not `in`.
1162
- if (!meta.seed)
1163
- missing.push('seed');
1164
- const recommended = AGENTVERSE_RECOMMENDED
1165
- .filter(([k]) => !meta[k])
1166
- .map(([k, why]) => `${k}: ${why}`);
1167
- return { ready: missing.length === 0, missing, recommended };
1168
- }
1169
- /**
1170
- * Say what is missing, in `warnSkillGap`'s register and on the same stream — stderr,
1171
- * so a `--json` stdout stays one machine-readable line. The caller decides whether to
1172
- * refuse; this function only speaks.
1173
- */
1174
- function warnAgentverseGap(r) {
1175
- if (r.missing.includes('seed')) {
1176
- console.error('warning: this agent declares no seed: — its Agentverse identity is NOT deterministic.');
1177
- console.error(' The compiled Python emits `Agent(name=...)` with no `seed=`, so uAgents derives a');
1178
- console.error(' fresh key: a NEW agent address on every deploy, and every peer holding the old');
1179
- console.error(' address is talking to nobody. Add `seed: <a secret phrase>` to the frontmatter.');
1180
- }
1181
- for (const line of r.recommended)
1182
- console.error(` also absent — ${line}`);
1183
- }
1184
- export function compileTarget(content, target, skills = {}) {
1185
- const why = UNIMPLEMENTED_TARGETS[target];
1186
- if (why) {
1187
- throw new Error(`target "${target}" is not implemented — ${why}. Supported: ${CLI_TARGETS.join(' | ')}`);
1188
- }
1189
- if (target === 'mcp')
1190
- return compileAgent(content, { target: 'mcp', skills });
1191
- if (target === 'uagents')
1192
- return compileAgent(content, { target: 'uagents', skills });
1193
- if (target === 'skillmd') {
1194
- const emitted = compileAgent(content, { target: 'skillmd', skills });
1195
- if (!emitted.trim()) {
1196
- throw new Error('target "skillmd" resolved no skill markdown — nothing to emit. Pass --skills <dir> pointing at the skill files this agent declares.');
1197
- }
1198
- return emitted;
1199
- }
1200
- if (target === 'web') {
1201
- // Emit a typed TS module — the web app can import this at build time
1202
- // instead of parsing .md at request time. Matches the SDK's compileWeb()
1203
- // output shape; the CLI uses a lightweight inline build for portability.
1204
- const m = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
1205
- const fm = m ? m[1] : '';
1206
- const body = m ? m[2].trim() : content.trim();
1207
- return [
1208
- '// Generated by ONE — https://one.ie',
1209
- '// `oneie agent compile --target web` — do not edit by hand',
1210
- '',
1211
- 'export const frontmatterRaw = ' + JSON.stringify(fm),
1212
- 'export const prompt = ' + JSON.stringify(body),
1213
- '',
1214
- ].join('\n');
1215
- }
1216
- // Anything else used to `return content` — the raw agent.md echoed back as if
1217
- // it had compiled. A wrong-output-that-looks-right path is worse than a fail.
1218
- throw new Error(`unknown target "${target}" — supported: ${CLI_TARGETS.join(' | ')}`);
1219
- }
1220
- /** Lightweight issue extractor for dev-mode validation (no Zod — just structural checks). */
1221
- function issues_from_quick(_delta, raw) {
1222
- const issues = [];
1223
- const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
1224
- if (!fmMatch) {
1225
- issues.push({ level: 'error', path: '<frontmatter>', message: 'missing YAML frontmatter (no --- delimiters found)' });
1226
- return issues;
1227
- }
1228
- const fm = fmMatch[1];
1229
- if (!/^\s*name:/m.test(fm))
1230
- issues.push({ level: 'error', path: 'name', message: 'required field `name:` missing' });
1231
- if (!/^\s*title:/m.test(fm))
1232
- issues.push({ level: 'warn', path: 'title', message: 'recommended field `title:` missing' });
1233
- return issues;
1234
- }
1235
- function parseQuickMd(path) {
1236
- const text = readFileSync(path, 'utf8');
1237
- const m = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
1238
- const prompt = m ? m[2].trim() : text.trim();
1239
- // Lightweight regex-based extraction — avoids a YAML dep in the CLI.
1240
- const fm = m ? m[1] : '';
1241
- const skills = [];
1242
- const skillsLine = /^skills:\s*\[([^\]]+)\]/m.exec(fm);
1243
- if (skillsLine)
1244
- skills.push(...skillsLine[1].split(',').map((s) => s.trim().replace(/['"]/g, '')));
1245
- const stages = {};
1246
- const stageRe = /^\s+- id:\s+([a-z0-9-]+)\b([\s\S]*?)(?=^\s+- id:|^\s*pills:|^\s*sections:|^---)/gm;
1247
- let sm;
1248
- while ((sm = stageRe.exec(fm))) {
1249
- stages[sm[1]] = sm[2].trim();
1250
- }
1251
- const sections = [];
1252
- const sectionRe = /^\s+- kind:\s+\S+\s*\n\s+id:\s+([a-z0-9-]+)/gm;
1253
- let secM;
1254
- while ((secM = sectionRe.exec(fm)))
1255
- sections.push(secM[1]);
1256
- const pills = [];
1257
- // pills block: extract `- id: foo` items
1258
- const pillsBlock = /^\s*pills:[\s\S]*?(?=^\S|$(?![\r\n]))/m.exec(fm);
1259
- if (pillsBlock) {
1260
- const pillRe = /^\s+- id:\s+([a-z0-9-]+)/gm;
1261
- let pm;
1262
- while ((pm = pillRe.exec(pillsBlock[0])))
1263
- pills.push(pm[1]);
1264
- }
1265
- const uiMatch = /^\s*ui:[\s\S]*?(?=^[a-z]+:|^---)/m.exec(fm);
1266
- const themeMatch = /^\s*theme:[\s\S]*?(?=^[a-z]+:|^---)/m.exec(fm);
1267
- return {
1268
- prompt,
1269
- skills,
1270
- stages,
1271
- sections,
1272
- pills,
1273
- uiSerialized: uiMatch?.[0] ?? '',
1274
- themeSerialized: themeMatch?.[0] ?? '',
1275
- };
1276
- }
1277
- function semanticDiff(a, b) {
1278
- const A = parseQuickMd(a);
1279
- const B = parseQuickMd(b);
1280
- const setA = new Set(A.skills);
1281
- const setB = new Set(B.skills);
1282
- const skillsAdded = [...setB].filter((s) => !setA.has(s));
1283
- const skillsRemoved = [...setA].filter((s) => !setB.has(s));
1284
- const stageIdsA = new Set(Object.keys(A.stages));
1285
- const stageIdsB = new Set(Object.keys(B.stages));
1286
- const stagesAdded = [...stageIdsB].filter((s) => !stageIdsA.has(s));
1287
- const stagesRemoved = [...stageIdsA].filter((s) => !stageIdsB.has(s));
1288
- const stageContentChanged = [...stageIdsA]
1289
- .filter((s) => stageIdsB.has(s) && A.stages[s] !== B.stages[s]);
1290
- const secSetA = new Set(A.sections);
1291
- const secSetB = new Set(B.sections);
1292
- const sectionsAdded = [...secSetB].filter((s) => !secSetA.has(s));
1293
- const sectionsRemoved = [...secSetA].filter((s) => !secSetB.has(s));
1294
- const pillSetA = new Set(A.pills);
1295
- const pillSetB = new Set(B.pills);
1296
- const pillsAdded = [...pillSetB].filter((s) => !pillSetA.has(s));
1297
- const pillsRemoved = [...pillSetA].filter((s) => !pillSetB.has(s));
1298
- // Key-level ui/theme diff: extract top-level keys from serialized block strings
1299
- const extractKeys = (serialized) => {
1300
- const result = {};
1301
- const re = /^\s{2}([a-zA-Z][a-zA-Z0-9_]*):/gm;
1302
- let m;
1303
- while ((m = re.exec(serialized)) !== null)
1304
- result[m[1]] = m[1];
1305
- return result;
1306
- };
1307
- const uiA = extractKeys(A.uiSerialized);
1308
- const uiB = extractKeys(B.uiSerialized);
1309
- const allUiKeys = new Set([...Object.keys(uiA), ...Object.keys(uiB)]);
1310
- const uiKeys = [...allUiKeys].filter((k) => uiA[k] !== uiB[k]);
1311
- const themeA = extractKeys(A.themeSerialized);
1312
- const themeB = extractKeys(B.themeSerialized);
1313
- const allThemeKeys = new Set([...Object.keys(themeA), ...Object.keys(themeB)]);
1314
- const themeKeys = [...allThemeKeys].filter((k) => themeA[k] !== themeB[k]);
1315
- const delta = {
1316
- promptChanged: A.prompt !== B.prompt,
1317
- skillsAdded, skillsRemoved,
1318
- stagesAdded, stagesRemoved, stageContentChanged,
1319
- sectionsAdded, sectionsRemoved,
1320
- pillsAdded, pillsRemoved,
1321
- uiChanged: A.uiSerialized !== B.uiSerialized,
1322
- uiKeys,
1323
- themeChanged: A.themeSerialized !== B.themeSerialized,
1324
- themeKeys,
1325
- unchanged: false,
1326
- };
1327
- delta.unchanged = !delta.promptChanged
1328
- && skillsAdded.length === 0 && skillsRemoved.length === 0
1329
- && stagesAdded.length === 0 && stagesRemoved.length === 0 && stageContentChanged.length === 0
1330
- && sectionsAdded.length === 0 && sectionsRemoved.length === 0
1331
- && pillsAdded.length === 0 && pillsRemoved.length === 0
1332
- && !delta.uiChanged && !delta.themeChanged;
1333
- return delta;
1334
- }