oneie 4.0.3 → 4.2.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.
package/dist/src/agent.js CHANGED
@@ -1,18 +1,20 @@
1
1
  import { Command } from 'commander';
2
2
  import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
3
- import { basename, dirname, resolve } from 'node:path';
4
- import { homedir } from 'node:os';
3
+ import { basename, dirname, join, resolve } from 'node:path';
5
4
  import { TEMPLATES } from './templates.js';
6
- import { compileAgent } from '@oneie/sdk/compile';
5
+ import { compileAgent, parseAgentMd } from '@oneie/sdk/compile';
6
+ import { resolveKey } from './lib/client.js';
7
+ import { askPath } from './lib/api-path.js';
7
8
  import { watch } from 'fs';
8
9
  const DEFAULT_API = 'https://one.ie';
9
- const KEY_FILE = resolve(homedir(), '.config', 'oneie', 'key');
10
+ /**
11
+ * The CLI-wide key contract lives in one place — `resolveKey()` in
12
+ * lib/client.ts: `--key` > ONE_API_KEY (canonical) > ONEIE_API_KEY (legacy) >
13
+ * ~/.config/oneie/key. This module used to read ONLY the legacy var, so anyone
14
+ * on the canonical `ONE_API_KEY` silently resolved to null.
15
+ */
10
16
  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;
17
+ return resolveKey() || null;
16
18
  }
17
19
  export function agentCmd() {
18
20
  const cmd = new Command('agent').description('Agent management');
@@ -36,10 +38,11 @@ export function agentCmd() {
36
38
  out(cmd, { ok: true, path: outPath, lines: body.split('\n').length });
37
39
  });
38
40
  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 });
41
+ .description('Validate agent.md frontmatter against the ONE agent spec (text/agents-spec.md)')
42
+ .option('--strict', 'Warnings are errors: unknown keys, off-enum values, list shapes the runtime cannot read')
43
+ .action((path, opts) => {
44
+ const { errors, warnings, unknownKeys } = validate(path, { strict: !!opts.strict });
45
+ out(cmd, { ok: errors.length === 0, errors, warnings, unknownKeys, checked: 1 });
43
46
  });
44
47
  cmd.command('lint <path>')
45
48
  .description('Lint agent.md style and spec rules')
@@ -49,7 +52,8 @@ export function agentCmd() {
49
52
  });
50
53
  cmd.command('compile <path>')
51
54
  .description('Compile agent.md to target format')
52
- .option('--target <t>', 'Output format: mcp | uagents | skillmd | web | a2a | erc8004', 'mcp')
55
+ .option('--target <t>', `Output format: ${CLI_TARGETS.join(' | ')} (a2a and erc8004 are NOT implemented)`, 'mcp')
56
+ .option('--skills <dir>', 'Directory holding the skill markdown declared in the agent frontmatter')
53
57
  .option('--out <file>', 'Write output to file instead of stdout')
54
58
  .action((path, opts) => {
55
59
  if (!existsSync(path)) {
@@ -57,11 +61,24 @@ export function agentCmd() {
57
61
  return;
58
62
  }
59
63
  const content = readFileSync(path, 'utf8');
60
- const result = compileTarget(content, opts.target);
64
+ const found = resolveSkillMds(path, content, opts.skills);
65
+ if (opts.target in TARGETS_USING_SKILLS)
66
+ warnSkillGap(found, opts.target);
67
+ let result;
68
+ try {
69
+ result = compileTarget(content, opts.target, found.skills);
70
+ }
71
+ catch (err) {
72
+ out(cmd, { ok: false, target: opts.target, error: err.message });
73
+ return;
74
+ }
61
75
  if (opts.out) {
62
76
  mkdirSync(dirname(opts.out), { recursive: true });
63
77
  writeFileSync(opts.out, result);
64
- out(cmd, { ok: true, target: opts.target, written: opts.out, bytes: result.length });
78
+ out(cmd, {
79
+ ok: true, target: opts.target, written: opts.out, bytes: result.length,
80
+ skillsDeclared: found.declared.length, skillsResolved: found.resolved.length,
81
+ });
65
82
  }
66
83
  else {
67
84
  process.stdout.write(result + '\n');
@@ -84,13 +101,23 @@ export function agentCmd() {
84
101
  .option('--name <name>', 'Override agent name (defaults to frontmatter name:)')
85
102
  .option('--target <t>', 'Publish target: oneie (default) | agentverse', 'oneie')
86
103
  .option('--agentverse-key <key>', 'Agentverse API key (or set AGENTVERSE_API_KEY)')
104
+ .option('--skills <dir>', 'Directory holding the skill markdown declared in the agent frontmatter (agentverse target)')
87
105
  .option('--live', 'Set lifecycle: active before publishing (skip the draft step)')
106
+ // The override for the Agentverse readiness refusal below. It is a flag, not a
107
+ // prompt, so the decision to deploy a non-deterministic identity is explicit and
108
+ // lands in the shell history of whoever made it.
109
+ .option('--force', 'Deploy to Agentverse even when the agent is not Agentverse-ready (no seed: — a new address every deploy)')
88
110
  .action(async (path, opts) => {
89
111
  if (!existsSync(path)) {
90
112
  out(cmd, { ok: false, error: `not found: ${path}` });
91
113
  return;
92
114
  }
93
- const { errors } = validate(path);
115
+ // The PUBLISH door keeps the gate it always had — the receiver itself
116
+ // refuses on `name:` alone (world-receivers.ts:1407) and this mirrors it.
117
+ // The spec's required set (kind, body) changes `validate`'s verdict, not
118
+ // whether a file may be uploaded; a stricter door here would be a reader
119
+ // changing behaviour, which text/agents-spec.md forbids.
120
+ const { errors } = validate(path, { door: 'publish' });
94
121
  if (errors.length) {
95
122
  out(cmd, { ok: false, errors });
96
123
  return;
@@ -107,10 +134,47 @@ export function agentCmd() {
107
134
  out(cmd, { ok: false, error: 'Agentverse API key required — pass --agentverse-key or set AGENTVERSE_API_KEY' });
108
135
  return;
109
136
  }
110
- // Compile agent.md → Python uAgents
137
+ // Compile agent.md → Python uAgents. The skills map is what makes the
138
+ // compiler emit Protocol + on_message handlers; without it every
139
+ // deployed agent is a shell that cannot answer a message.
140
+ const found = resolveSkillMds(path, content, opts.skills);
141
+ warnSkillGap(found, 'uagents');
142
+ // ── The readiness gate — BEFORE the compile, and long before the network ──
143
+ //
144
+ // Placed next to warnSkillGap because it is the same kind of honesty: both
145
+ // name a capability the deployed agent will not have. It differs in what it
146
+ // does about it, and that difference is the whole cycle. A skill gap produces
147
+ // an agent that cannot answer; a seed gap produces an agent at a DIFFERENT
148
+ // ADDRESS each deploy — and the network cannot tell it is the same agent, so
149
+ // the damage is done the moment the upload succeeds, silently, to a caller
150
+ // who was told nothing. Warning and uploading anyway is the `--skip-tests`
151
+ // shape: a notice where a gate belongs. So the default REFUSES.
152
+ //
153
+ // `--force` keeps the plan's letter — it warns, then it uploads — while
154
+ // making the choice explicit and attributable.
155
+ //
156
+ // The refusal is STRUCTURED as well as spoken: `missing` rides the out()
157
+ // envelope so a --json caller branches on the field instead of scraping
158
+ // stderr. Naming which gate bit is the point.
159
+ const readiness = agentverseReadiness(content);
160
+ if (!readiness.ready) {
161
+ warnAgentverseGap(readiness);
162
+ if (!opts.force) {
163
+ out(cmd, {
164
+ ok: false,
165
+ error: `not Agentverse-ready — missing: ${readiness.missing.join(', ')}. Add the field, or pass --force to deploy a non-deterministic identity anyway.`,
166
+ ready: false,
167
+ missing: readiness.missing,
168
+ recommended: readiness.recommended,
169
+ force: '--force',
170
+ });
171
+ return;
172
+ }
173
+ console.error(' --force given — deploying anyway. This address will not be stable.');
174
+ }
111
175
  let python;
112
176
  try {
113
- python = compileAgent(content, { target: 'uagents' });
177
+ python = compileAgent(content, { target: 'uagents', skills: found.skills });
114
178
  }
115
179
  catch (err) {
116
180
  out(cmd, { ok: false, error: `compile failed: ${err.message}` });
@@ -137,10 +201,40 @@ export function agentCmd() {
137
201
  // 2. Upload code (double-encoded JSON — Agentverse requirement)
138
202
  const codeArray = [{ language: 'python', name: 'agent.py', value: python }];
139
203
  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
204
+ // 3. Inject the secrets the hosted agent needs. Never silent: a
205
+ // swallowed failure here produced an agent that deploys, starts,
206
+ // and then dies on its first message with no trace of why.
207
+ const secrets = {};
208
+ const putSecret = async (secretName, value) => {
209
+ try {
210
+ await avFetch('POST', '/hosting/secrets', { address, name: secretName, secret: value });
211
+ secrets[secretName] = 'ok';
212
+ }
213
+ catch (e) {
214
+ secrets[secretName] = `failed: ${e.message}`;
215
+ console.error(`warning: ${secretName} was NOT set on the Agentverse agent — ${e.message}`);
216
+ }
217
+ };
141
218
  const oneKey = readApiKey();
142
219
  if (oneKey) {
143
- await avFetch('POST', '/hosting/secrets', { address, name: 'ONEIE_API_KEY', secret: oneKey }).catch(() => { });
220
+ console.error('Uploading secret ONEIE_API_KEY to agentverse.ai (variable name only — the value is never printed).');
221
+ await putSecret('ONEIE_API_KEY', oneKey);
222
+ }
223
+ else {
224
+ secrets.ONEIE_API_KEY = 'skipped: no key resolved';
225
+ 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.');
226
+ }
227
+ // The generated Python constructs Anthropic() with no explicit key,
228
+ // so the SDK reads ANTHROPIC_API_KEY from the hosted environment.
229
+ // Process env only — never a file, never invented.
230
+ const anthropicKey = process.env.ANTHROPIC_API_KEY;
231
+ if (anthropicKey) {
232
+ 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).');
233
+ await putSecret('ANTHROPIC_API_KEY', anthropicKey);
234
+ }
235
+ else {
236
+ secrets.ANTHROPIC_API_KEY = 'skipped: not set in the environment';
237
+ 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.');
144
238
  }
145
239
  // 4. Start
146
240
  await avFetch('POST', `/hosting/agents/${address}/start`, {});
@@ -163,6 +257,10 @@ export function agentCmd() {
163
257
  walletAddress,
164
258
  compiled,
165
259
  agentName,
260
+ secrets,
261
+ protocols: found.resolved.length,
262
+ skillsDeclared: found.declared.length,
263
+ skillsMissing: found.missing,
166
264
  agentverseUrl: `https://agentverse.ai/agents/details/${address}`,
167
265
  });
168
266
  }
@@ -172,29 +270,74 @@ export function agentCmd() {
172
270
  return;
173
271
  }
174
272
  // ── ONE workspace publish path (default) ─────────────────────────────
273
+ //
274
+ // THE TOKEN IS THE PLAIN KEY. It used to be `${slug}:${key}`, and that one
275
+ // line is why publish was unusable by anybody: `requireAuth`
276
+ // (one.ie/web/src/lib/api-auth.ts) resolves a world key by PREFIX — `one-`
277
+ // or `osk_` — so prepending "one:" turns a valid key into `one:one-abc...`,
278
+ // which matches no prefix, falls through to session auth, and 401s. The same
279
+ // line was copy-pasted across ten call sites in agent.ts and skill.ts, so
280
+ // every workspace command in the CLI was broken the same way. The route
281
+ // header comments claiming `Bearer <ownerId>:<SERVER_SECRET>` are STALE —
282
+ // the code calls `requireAuthOver(request, "update_group", slug)`.
283
+ //
284
+ // Publish goes through the RECEIVER door rather than `/api/agents/publish`
285
+ // for one reason: credential CLASS. `/api/ask/*` accepts a world key OR a
286
+ // service credential; the route accepts only a world key or a browser
287
+ // session. Both authorize with the same ownership walk, and since
288
+ // `publishAgent` now writes the versioned archive too (world-receivers.ts),
289
+ // the route no longer has any semantic the receiver lacks — so `agent
290
+ // history` and `agent rollback` still see what this publishes.
175
291
  if (!opts.slug) {
176
292
  out(cmd, { ok: false, error: 'missing --slug <workspace>' });
177
293
  return;
178
294
  }
179
295
  const key = readApiKey();
180
296
  if (!key) {
181
- out(cmd, { ok: false, error: 'no API key — run `oneie auth login --key <key>` or set ONEIE_API_KEY' });
297
+ out(cmd, { ok: false, error: 'no API key — run `oneie auth login` or set ONE_API_KEY (legacy: ONEIE_API_KEY)' });
182
298
  return;
183
299
  }
184
- const token = `${opts.slug}:${key}`;
185
300
  try {
186
- const res = await fetch(`${opts.api.replace(/\/$/, '')}/api/agents/publish`, {
301
+ const res = await fetch(askPath(opts.api.replace(/\/$/, ''), 'world:publish-agent'), {
187
302
  method: 'POST',
188
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
189
- body: JSON.stringify({ slug: opts.slug, name: agentName, content }),
303
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
304
+ body: JSON.stringify({ data: { slug: opts.slug, name: agentName, content } }),
190
305
  });
191
306
  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' });
307
+ const envelope = (text ? JSON.parse(text) : {});
308
+ const result = envelope.result ?? {};
309
+ // THE ASK ENVELOPE ANSWERS HTTP 200 ON A REFUSAL. `outcome: "failure"`
310
+ // carries the receiver's own error under a 200, so `res.ok` alone reports
311
+ // a refused publish as a success. Check all three.
312
+ if (!res.ok || envelope.outcome === 'failure' || result.ok === false) {
313
+ // A bare "forbidden" is unactionable and its two causes need OPPOSITE
314
+ // fixes, so read `callerRole` rather than guessing. `anonymous` = the
315
+ // Bearer matched no world_keys row (wrong key, or not a key); anything
316
+ // else = a real key the ownership walk refused for THIS workspace.
317
+ const base = result.error ?? envelope.error ?? text ?? 'publish failed';
318
+ const hint = result.error !== 'forbidden'
319
+ ? undefined
320
+ : result.callerRole === 'anonymous'
321
+ ? 'the key was not recognised — run `oneie auth login`, or set ONE_API_KEY to a world key (it starts `one-` or `osk_`)'
322
+ : `authenticated as ${result.callerRole}, but that identity does not control workspace "${opts.slug}"`;
323
+ // out() prints only `error` in human mode, so the actionable half has to
324
+ // live in that string; the structured fields stay for --json.
325
+ out(cmd, {
326
+ ok: false,
327
+ status: res.status,
328
+ error: hint ? `${base} — ${hint}` : base,
329
+ ...(result.required ? { required: result.required } : {}),
330
+ ...(result.callerRole ? { callerRole: result.callerRole } : {}),
331
+ });
195
332
  return;
196
333
  }
197
- out(cmd, { ok: true, ...data });
334
+ out(cmd, {
335
+ ok: true,
336
+ name: agentName,
337
+ url: result.url,
338
+ bytes: result.bytes,
339
+ subscribes: result.subscribes ?? [],
340
+ });
198
341
  }
199
342
  catch (err) {
200
343
  out(cmd, { ok: false, error: err.message });
@@ -212,10 +355,10 @@ export function agentCmd() {
212
355
  }
213
356
  const key = readApiKey();
214
357
  if (!key) {
215
- out(cmd, { ok: false, error: 'no API key — run `oneie auth login --key <key>` or set ONEIE_API_KEY' });
358
+ out(cmd, { ok: false, error: 'no API key — run `oneie auth login --key <key>` or set ONE_API_KEY (legacy: ONEIE_API_KEY)' });
216
359
  return;
217
360
  }
218
- const token = `${opts.slug}:${key}`;
361
+ const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
219
362
  const url = `${opts.api.replace(/\/$/, '')}/api/agents/publish?slug=${encodeURIComponent(opts.slug)}&name=${encodeURIComponent(name)}`;
220
363
  try {
221
364
  const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
@@ -245,10 +388,10 @@ export function agentCmd() {
245
388
  }
246
389
  const key = readApiKey();
247
390
  if (!key) {
248
- out(cmd, { ok: false, error: 'no API key — run `oneie auth login --key <key>` or set ONEIE_API_KEY' });
391
+ out(cmd, { ok: false, error: 'no API key — run `oneie auth login --key <key>` or set ONE_API_KEY (legacy: ONEIE_API_KEY)' });
249
392
  return;
250
393
  }
251
- const token = `${opts.slug}:${key}`;
394
+ const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
252
395
  const url = `${opts.api.replace(/\/$/, '')}/api/agents/publish?slug=${encodeURIComponent(opts.slug)}&name=${encodeURIComponent(name)}`;
253
396
  try {
254
397
  const res = await fetch(url, { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } });
@@ -314,7 +457,7 @@ export function agentCmd() {
314
457
  // Remote mode: call /api/chat with messages + agentId
315
458
  const key = readApiKey();
316
459
  if (!key) {
317
- out(cmd, { ok: false, error: 'no API key for remote eval — set ONEIE_API_KEY' });
460
+ out(cmd, { ok: false, error: 'no API key for remote eval — set ONE_API_KEY (legacy: ONEIE_API_KEY) or run `oneie auth login`' });
318
461
  return;
319
462
  }
320
463
  const nameMatch = /^name:\s+([a-z0-9-]+)/m.exec(fm);
@@ -328,7 +471,7 @@ export function agentCmd() {
328
471
  try {
329
472
  const res = await fetch(`${opts.api.replace(/\/$/, '')}/api/chat`, {
330
473
  method: 'POST',
331
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${opts.slug}:${key}` },
474
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
332
475
  body: JSON.stringify({ messages: [{ role: 'user', content: c.input }], agentId, slug: opts.slug }),
333
476
  });
334
477
  const text = await res.text();
@@ -416,10 +559,10 @@ export function agentCmd() {
416
559
  .action(async (opts) => {
417
560
  const key = readApiKey();
418
561
  if (!key) {
419
- out(cmd, { ok: false, error: 'no API key — set ONEIE_API_KEY or run oneie auth login' });
562
+ out(cmd, { ok: false, error: 'no API key — set ONE_API_KEY (legacy: ONEIE_API_KEY) or run `oneie auth login`' });
420
563
  return;
421
564
  }
422
- const token = `${opts.slug}:${key}`;
565
+ const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
423
566
  const url = `${opts.api.replace(/\/$/, '')}/api/agents/list?slug=${encodeURIComponent(opts.slug)}`;
424
567
  try {
425
568
  const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
@@ -442,10 +585,10 @@ export function agentCmd() {
442
585
  .action(async (name, opts) => {
443
586
  const key = readApiKey();
444
587
  if (!key) {
445
- out(cmd, { ok: false, error: 'no API key — set ONEIE_API_KEY or run oneie auth login' });
588
+ out(cmd, { ok: false, error: 'no API key — set ONE_API_KEY (legacy: ONEIE_API_KEY) or run `oneie auth login`' });
446
589
  return;
447
590
  }
448
- const token = `${opts.slug}:${key}`;
591
+ const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
449
592
  const url = `${opts.api.replace(/\/$/, '')}/api/agents/history?slug=${encodeURIComponent(opts.slug)}&name=${encodeURIComponent(name)}`;
450
593
  try {
451
594
  const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
@@ -470,7 +613,7 @@ export function agentCmd() {
470
613
  .action(async (name, opts) => {
471
614
  const key = readApiKey();
472
615
  if (!key) {
473
- out(cmd, { ok: false, error: 'no API key — set ONEIE_API_KEY or run oneie auth login' });
616
+ out(cmd, { ok: false, error: 'no API key — set ONE_API_KEY (legacy: ONEIE_API_KEY) or run `oneie auth login`' });
474
617
  return;
475
618
  }
476
619
  const ts = parseInt(opts.to, 10);
@@ -490,7 +633,7 @@ export function agentCmd() {
490
633
  return;
491
634
  }
492
635
  }
493
- const token = `${opts.slug}:${key}`;
636
+ const token = key; // PLAIN key: requireAuth resolves a world key by `one-`/`osk_` PREFIX; a `slug:` prefix breaks it
494
637
  const url = `${opts.api.replace(/\/$/, '')}/api/agents/rollback`;
495
638
  try {
496
639
  const res = await fetch(url, {
@@ -653,6 +796,10 @@ function out(cmd, data) {
653
796
  else {
654
797
  const detail = data.error ?? data.errors ?? data.issues ?? data;
655
798
  console.error('✗', typeof detail === 'string' ? detail : JSON.stringify(detail));
799
+ // Match the shared out() in lib/client.ts. Without this every `agent`
800
+ // failure — including an unimplemented compile target — exited 0, so a CI
801
+ // script could not tell a refusal from a success.
802
+ process.exitCode = 1;
656
803
  }
657
804
  }
658
805
  /**
@@ -663,21 +810,101 @@ function out(cmd, data) {
663
810
  * id collisions, kebab-case ids. Anything outside these rules falls through
664
811
  * to the live server-side validation when the agent is published.
665
812
  */
666
- function validate(path) {
667
- if (!existsSync(path))
668
- return { errors: [`not found: ${path}`] };
669
- const text = readFileSync(path, 'utf8');
813
+ // ── The ONE agent spec — text/agents-spec.md ─────────────────────────────────
814
+ //
815
+ // Six programs read a `kind: agent` file and each reads a different key set. The
816
+ // spec is derived from what they do; these constants are its machine half. Keep
817
+ // them in step with the spec's field table — the test asserts the shape.
818
+ /** Required: a reader REFUSES or silently SUBSTITUTES identity without it.
819
+ * name → publish refuses (world-receivers.ts:1407). kind → one-agents.mjs:191
820
+ * skips the file. (The non-empty body is checked separately.) */
821
+ export const AGENT_REQUIRED = ['name', 'kind'];
822
+ /** Recommended: every reader falls back without it, but the fallback is a
823
+ * different agent on the page (title → dir, description → 'Generic helpful
824
+ * assistant', tier/domain → inferred from the id). Warned when absent. */
825
+ export const AGENT_RECOMMENDED = ['title', 'tier', 'domain', 'subscribes'];
826
+ /** The closed enums the web schema owns (agent-schema.ts) — role-types.ts INFERS
827
+ * a value from the id when the declared one is off-enum, so an off-enum value
828
+ * is a silent re-placement on the org chart, not a load failure. */
829
+ export const AGENT_ENUMS = {
830
+ kind: ['agent', 'skill', 'pack', 'seed'],
831
+ tier: ['chairman', 'ceo', 'director', 'specialist'],
832
+ domain: ['marketing', 'sales', 'service', 'education', 'engineering', 'finance', 'community', 'governance'],
833
+ tone: ['primary', 'secondary', 'tertiary', 'neutral'],
834
+ };
835
+ /** Keys the channels parser (channels/src/lib/agent-md.ts) can only read as a
836
+ * BLOCK list. An inline `[a, b]` is stored as the string "[a, b]", so
837
+ * `Array.isArray` fails in resolvePersona and the field is dropped at runtime. */
838
+ export const AGENT_BLOCK_LIST_KEYS = ['tools', 'subscribes', 'emits', 'skills', 'tags'];
839
+ /** Every top-level key at least one reader consumes — the union of AgentMeta
840
+ * (agent-md.ts:435), agentFrontmatterSchema (agent-schema.ts:229), Persona
841
+ * (channels/src/context.ts:590), compile.ts:319, one-agents.mjs:130,
842
+ * role-types.ts and the publish path. A key outside this set is read by
843
+ * nothing; the validator names it rather than refusing it. `direction` is NOT here on
844
+ * purpose: C20 deleted it from 118 corpus files (0 readers; 93/95 `bidirectional`
845
+ * merely restated subscribes+emits, the rest contradicted them) — keeping it out
846
+ * is what makes `--strict` refuse a resurrection. */
847
+ export const AGENT_KNOWN_KEYS = new Set([
848
+ // identity + chart
849
+ 'agentmd', 'name', 'kind', 'title', 'tier', 'reports_to', 'reportsTo', 'tone', 'icon', 'iconName', 'uid',
850
+ 'tagline', 'domain', 'kpis', 'description', 'version', 'model', 'group', 'tags', 'channels', 'lifecycle',
851
+ 'sensitivity', 'starters', 'skills', 'tools', 'features', 'subscribes', 'emits', 'url',
852
+ // runtime (Persona)
853
+ 'intents', 'maxSteps', 'integrations', 'hooks', 'remote', 'subAgents',
854
+ // uAgents compile
855
+ 'seed', 'port', 'agentverse', 'mailbox', 'startup', 'shutdown', 'intervals', 'endpoints', 'bureau',
856
+ 'when_to_use', 'inputSchema', 'outputSchema', 'summary', 'evals',
857
+ // payments
858
+ 'wallet', 'accepts', 'price', 'currency',
859
+ // A/B + web-only blocks
860
+ 'variants', 'goals', 'journey', 'sections', 'branding', 'theme', 'ui', 'funnel', 'analytics', 'i18n', 'triggers',
861
+ ]);
862
+ /** Top-level frontmatter keys — a column-0 `key:` line. The same extraction the
863
+ * corpus histogram in text/agents-spec.md used, so validator and measurement
864
+ * agree by construction. */
865
+ function topLevelKeys(fm) {
866
+ const keys = [];
867
+ const re = /^([A-Za-z_][A-Za-z0-9_-]*):/gm;
868
+ let m;
869
+ while ((m = re.exec(fm)))
870
+ keys.push(m[1]);
871
+ return keys;
872
+ }
873
+ /** The scalar value of a top-level `key:` line, unquoted, trailing `# comment` stripped. */
874
+ function scalarOf(fm, key) {
875
+ const m = new RegExp(`^${key}:[ \\t]*(.*)$`, 'm').exec(fm);
876
+ if (!m)
877
+ return undefined;
878
+ return m[1].replace(/\s+#.*$/, '').trim().replace(/^["']|["']$/g, '');
879
+ }
880
+ export function validate(path, opts = {}) {
670
881
  const errors = [];
882
+ const warnings = [];
883
+ const unknownKeys = [];
884
+ const door = opts.door ?? 'validate';
885
+ const done = () => {
886
+ if (opts.strict && door === 'validate') {
887
+ errors.push(...warnings);
888
+ warnings.length = 0;
889
+ }
890
+ return { errors, warnings, unknownKeys };
891
+ };
892
+ if (!existsSync(path)) {
893
+ errors.push(`not found: ${path}`);
894
+ return done();
895
+ }
896
+ const text = readFileSync(path, 'utf8');
671
897
  if (!text.startsWith('---')) {
672
898
  errors.push('missing frontmatter — agent.md must start with `---`');
673
- return { errors };
899
+ return done();
674
900
  }
675
901
  const fmMatch = text.match(/^---\n([\s\S]*?)\n---/);
676
902
  if (!fmMatch) {
677
903
  errors.push('frontmatter not terminated — missing closing `---`');
678
- return { errors };
904
+ return done();
679
905
  }
680
906
  const fm = fmMatch[1];
907
+ const body = text.slice(fmMatch[0].length).trim();
681
908
  const nameMatch = /^name:\s*(\S+)/m.exec(fm);
682
909
  if (!nameMatch) {
683
910
  errors.push('missing required field: name');
@@ -707,7 +934,61 @@ function validate(path) {
707
934
  }
708
935
  }
709
936
  }
710
- return { errors };
937
+ // The publish door stops here — its gate is the receiver's own (name), and
938
+ // the spec forbids a door changing behaviour under a stricter validator.
939
+ if (door === 'publish')
940
+ return done();
941
+ // ── The spec's required set (text/agents-spec.md § required) ──────────────
942
+ const keys = topLevelKeys(fm);
943
+ const present = new Set(keys);
944
+ const kind = scalarOf(fm, 'kind');
945
+ if (!present.has('kind') || !kind) {
946
+ 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)');
947
+ }
948
+ else if (kind !== 'agent') {
949
+ errors.push(`kind: ${kind} — \`agent validate\` checks the kind: agent spec; a ${kind} file goes through \`oneie skill validate\``);
950
+ }
951
+ if (!body) {
952
+ 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');
953
+ }
954
+ // ── Recommended: absent → a fallback that is a different agent on the page ──
955
+ for (const k of AGENT_RECOMMENDED) {
956
+ if (!present.has(k))
957
+ warnings.push(`missing recommended field: ${k}`);
958
+ }
959
+ if (!present.has('description') && !present.has('tagline')) {
960
+ warnings.push('missing recommended field: description (or tagline) — Persona falls back to "Generic helpful assistant" (personas.ts:60)');
961
+ }
962
+ else if (!present.has('description') && present.has('tagline')) {
963
+ 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"');
964
+ }
965
+ // ── Off-enum values: the chart INFERS a placement instead of using yours ───
966
+ for (const [k, allowed] of Object.entries(AGENT_ENUMS)) {
967
+ if (k === 'kind')
968
+ continue;
969
+ const v = scalarOf(fm, k);
970
+ if (v !== undefined && v !== '' && !allowed.includes(v)) {
971
+ 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`);
972
+ }
973
+ }
974
+ // ── Shapes the runtime cannot read ─────────────────────────────────────────
975
+ for (const k of AGENT_BLOCK_LIST_KEYS) {
976
+ if (new RegExp(`^${k}:[ \\t]*\\[`, 'm').test(fm)) {
977
+ 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`);
978
+ }
979
+ }
980
+ if (/^\s+-\s+(signal|tag):\s/m.test(fm)) {
981
+ 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');
982
+ }
983
+ // ── Keys read by nothing — named, never silently accepted ─────────────────
984
+ for (const k of keys) {
985
+ if (!AGENT_KNOWN_KEYS.has(k) && !unknownKeys.includes(k))
986
+ unknownKeys.push(k);
987
+ }
988
+ if (unknownKeys.length) {
989
+ warnings.push(`unknown keys (read by no reader): ${unknownKeys.join(', ')}`);
990
+ }
991
+ return done();
711
992
  }
712
993
  function lint(path) {
713
994
  if (!existsSync(path))
@@ -748,11 +1029,161 @@ function lint(path) {
748
1029
  }
749
1030
  return issues;
750
1031
  }
751
- function compileTarget(content, target) {
1032
+ /**
1033
+ * Targets the CLI can actually emit. `a2a` and `erc8004` were advertised in
1034
+ * --target help and in the docs but had no branch — they fell through to
1035
+ * `return content`, echoing the raw agent.md back as if it had compiled. They
1036
+ * now FAIL LOUDLY: there is no a2a/erc8004 compiler anywhere in @oneie/sdk to
1037
+ * delegate to, and inventing one here would be worse than an honest error.
1038
+ */
1039
+ export const CLI_TARGETS = ['mcp', 'uagents', 'skillmd', 'web'];
1040
+ const UNIMPLEMENTED_TARGETS = {
1041
+ a2a: 'no A2A agent-card compiler exists in @oneie/sdk/compile',
1042
+ erc8004: 'no ERC-8004 identity-registry compiler exists in @oneie/sdk/compile',
1043
+ };
1044
+ /**
1045
+ * Targets whose output is derived from the resolved skill markdown, and the
1046
+ * noun each one actually emits — `mcp` emits tools, not protocols.
1047
+ */
1048
+ const TARGETS_USING_SKILLS = {
1049
+ mcp: 'tools',
1050
+ uagents: 'protocols (Protocol + on_message handlers)',
1051
+ skillmd: 'SKILL.md blocks',
1052
+ };
1053
+ /**
1054
+ * Resolve the skill markdown an agent's frontmatter declares.
1055
+ *
1056
+ * `compileAgent` derives uAgents protocols and MCP tools from a `skills` map
1057
+ * keyed by skill name; with no map, `hasSkills` is false and NO on_message
1058
+ * handler is emitted — every agent the CLI ever published to Agentverse was a
1059
+ * shell with zero protocols. Callers pass the result through so the compiler's
1060
+ * skills-to-protocols path is actually reachable.
1061
+ *
1062
+ * Layouts searched (both the flat `skill new` layout and the `skill emit`
1063
+ * SKILL.md directory layout), nearest to the agent first.
1064
+ */
1065
+ function resolveSkillMds(agentPath, content, skillsDir) {
1066
+ const { meta } = parseAgentMd(content);
1067
+ const declared = (meta.skills ?? [])
1068
+ .map(s => ('ref' in s ? s.ref : s.name))
1069
+ .filter((n) => Boolean(n));
1070
+ const dir = dirname(resolve(agentPath));
1071
+ const roots = [
1072
+ ...(skillsDir ? [resolve(skillsDir)] : []),
1073
+ join(dir, 'skills'),
1074
+ join(dir, '..', 'skills'),
1075
+ resolve('skills'),
1076
+ resolve('ai', 'skills'),
1077
+ ];
1078
+ const skills = {};
1079
+ const missing = [];
1080
+ for (const name of declared) {
1081
+ let found;
1082
+ for (const root of roots) {
1083
+ for (const candidate of [join(root, `${name}.md`), join(root, name, 'SKILL.md')]) {
1084
+ if (existsSync(candidate)) {
1085
+ found = candidate;
1086
+ break;
1087
+ }
1088
+ }
1089
+ if (found)
1090
+ break;
1091
+ }
1092
+ if (found)
1093
+ skills[name] = readFileSync(found, 'utf8');
1094
+ else
1095
+ missing.push(name);
1096
+ }
1097
+ return { skills, declared, resolved: Object.keys(skills), missing, roots };
1098
+ }
1099
+ /**
1100
+ * Never let a zero-protocol compile pass silently. Warnings go to stderr so
1101
+ * `--json` stdout stays one machine-readable line.
1102
+ */
1103
+ function warnSkillGap(found, target) {
1104
+ const noun = TARGETS_USING_SKILLS[target] ?? 'capabilities';
1105
+ if (found.declared.length === 0) {
1106
+ console.error(`warning: this agent declares no skills: — the compiled ${target} output has ZERO ${noun}.`);
1107
+ return;
1108
+ }
1109
+ if (found.missing.length) {
1110
+ console.error(`warning: ${found.missing.length}/${found.declared.length} declared skill(s) have no markdown file and were DROPPED: ${found.missing.join(', ')}`);
1111
+ 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.`);
1112
+ }
1113
+ if (found.resolved.length === 0) {
1114
+ console.error(`warning: ZERO skills resolved — the compiled ${target} output has ZERO ${noun}.`);
1115
+ if (target === 'uagents') {
1116
+ console.error(' A hosted agent with no protocols cannot answer a message.');
1117
+ }
1118
+ }
1119
+ }
1120
+ /** Why each recommended field is worth declaring. Absent ⇒ a capability the hosted agent simply does not have. */
1121
+ const AGENTVERSE_RECOMMENDED = [
1122
+ ['agentverse', 'no Agentverse registration URL — the agent is hosted but not discoverable by name'],
1123
+ ['mailbox', 'mailbox is off — the agent can only be reached while it is running, never asynchronously'],
1124
+ ['endpoints', 'no endpoints — nothing outside the uAgents protocol can call it'],
1125
+ ['bureau', 'no bureau — it runs alone rather than beside its siblings'],
1126
+ ['port', 'no port — the compiler leaves the uAgents default (8000)'],
1127
+ ['when_to_use', 'no when_to_use — a discovering agent has nothing to route on'],
1128
+ ['version', 'no version — two deploys are indistinguishable in the registry'],
1129
+ // The three that emit BEHAVIOUR rather than configuration. Listed for the same
1130
+ // reason as the rest — the cycle enumerated eleven fields and a list silently
1131
+ // covering seven of them reads as an oversight — but they are the ones an operator
1132
+ // should most often decline: each buys a real model call on a schedule.
1133
+ ['intervals', 'no intervals — the agent only ever speaks when spoken to'],
1134
+ ['startup', 'no startup — it announces nothing when it boots'],
1135
+ ['shutdown', 'no shutdown — it announces nothing when it stops'],
1136
+ ];
1137
+ /**
1138
+ * Is this agent.md ready to be a HOSTED Agentverse agent?
1139
+ *
1140
+ * `seed` is the only REQUIRED field, and it is required for one reason: it is the
1141
+ * deterministic identity. Without it every deploy of the same file is a different
1142
+ * agent as far as the network is concerned — a fresh address, so every peer that
1143
+ * learned the old one is now talking to nobody.
1144
+ */
1145
+ export function agentverseReadiness(agentMd) {
1146
+ const { meta } = parseAgentMd(agentMd);
1147
+ const missing = [];
1148
+ // The emitter's own predicate (compile.ts:512), deliberately — not `in`.
1149
+ if (!meta.seed)
1150
+ missing.push('seed');
1151
+ const recommended = AGENTVERSE_RECOMMENDED
1152
+ .filter(([k]) => !meta[k])
1153
+ .map(([k, why]) => `${k}: ${why}`);
1154
+ return { ready: missing.length === 0, missing, recommended };
1155
+ }
1156
+ /**
1157
+ * Say what is missing, in `warnSkillGap`'s register and on the same stream — stderr,
1158
+ * so a `--json` stdout stays one machine-readable line. The caller decides whether to
1159
+ * refuse; this function only speaks.
1160
+ */
1161
+ function warnAgentverseGap(r) {
1162
+ if (r.missing.includes('seed')) {
1163
+ console.error('warning: this agent declares no seed: — its Agentverse identity is NOT deterministic.');
1164
+ console.error(' The compiled Python emits `Agent(name=...)` with no `seed=`, so uAgents derives a');
1165
+ console.error(' fresh key: a NEW agent address on every deploy, and every peer holding the old');
1166
+ console.error(' address is talking to nobody. Add `seed: <a secret phrase>` to the frontmatter.');
1167
+ }
1168
+ for (const line of r.recommended)
1169
+ console.error(` also absent — ${line}`);
1170
+ }
1171
+ export function compileTarget(content, target, skills = {}) {
1172
+ const why = UNIMPLEMENTED_TARGETS[target];
1173
+ if (why) {
1174
+ throw new Error(`target "${target}" is not implemented — ${why}. Supported: ${CLI_TARGETS.join(' | ')}`);
1175
+ }
752
1176
  if (target === 'mcp')
753
- return JSON.stringify({ tools: [] }, null, 2);
1177
+ return compileAgent(content, { target: 'mcp', skills });
754
1178
  if (target === 'uagents')
755
- return compileAgent(content, { target: 'uagents' });
1179
+ return compileAgent(content, { target: 'uagents', skills });
1180
+ if (target === 'skillmd') {
1181
+ const emitted = compileAgent(content, { target: 'skillmd', skills });
1182
+ if (!emitted.trim()) {
1183
+ throw new Error('target "skillmd" resolved no skill markdown — nothing to emit. Pass --skills <dir> pointing at the skill files this agent declares.');
1184
+ }
1185
+ return emitted;
1186
+ }
756
1187
  if (target === 'web') {
757
1188
  // Emit a typed TS module — the web app can import this at build time
758
1189
  // instead of parsing .md at request time. Matches the SDK's compileWeb()
@@ -769,7 +1200,9 @@ function compileTarget(content, target) {
769
1200
  '',
770
1201
  ].join('\n');
771
1202
  }
772
- return content;
1203
+ // Anything else used to `return content` — the raw agent.md echoed back as if
1204
+ // it had compiled. A wrong-output-that-looks-right path is worse than a fail.
1205
+ throw new Error(`unknown target "${target}" — supported: ${CLI_TARGETS.join(' | ')}`);
773
1206
  }
774
1207
  /** Lightweight issue extractor for dev-mode validation (no Zod — just structural checks). */
775
1208
  function issues_from_quick(_delta, raw) {