@common-agent/agentdoc 0.0.0-stage → 0.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/cli.js ADDED
@@ -0,0 +1,368 @@
1
+ /**
2
+ * The command line tool, common-agent-doc: the host around the library. It
3
+ * is the only file in the package that touches a disk.
4
+ *
5
+ * common-agent-doc build <agent address | card file> [--descriptor <file|url>] [--out <dir>]
6
+ * common-agent-doc check <agentdoc file | url> [--fetch-sources]
7
+ * common-agent-doc init <agent address | card file> [--out agent-descriptor.json]
8
+ * common-agent-doc keygen [--out agent.key]
9
+ * common-agent-doc sign <descriptor file> --key <file> [--out <file>]
10
+ */
11
+ import { randomBytes } from "node:crypto";
12
+ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
13
+ import { dirname, join, resolve } from "node:path";
14
+ import { signerFromUserSeed } from "@common-agent/crypto";
15
+ import { AGENTDOC_PATH, AssembleError, assembleWithNotes, cardCandidates } from "./assemble.js";
16
+ import { check } from "./check.js";
17
+ import { draftFromCard, signingProblems } from "./descriptor.js";
18
+ import { render } from "./render.js";
19
+ import { encodeUserSeed, signDescriptor } from "./signatures.js";
20
+ import { ReadError, fetchJson, isObj, isUrl, isoSecond, parseBytes } from "./util.js";
21
+ import { VERSION } from "./version.js";
22
+ export const USAGE = `common-agent-doc ${VERSION}: make, publish and check an AgentDoc.
23
+
24
+ An AgentDoc is one document that says what an agent is, what it offers and
25
+ what it refuses, built only from what the agent itself publishes. Every line
26
+ says where it came from, and anything the agent has not said is listed as
27
+ not stated. See https://agentdoc.net
28
+
29
+ Commands:
30
+ build <address | card file> write the AgentDoc and its page
31
+ check <file | url> check an AgentDoc against Section 9.10
32
+ init <address | card file> draft a Descriptor from the agent's card
33
+ keygen make the agent's signing key
34
+ sign <descriptor file> sign the Descriptor with that key
35
+
36
+ Run common-agent-doc <command> --help for the details of one command.`;
37
+ const HELP = {
38
+ build: `common-agent-doc build <agent address | card file> [options]
39
+
40
+ Reads the agent's A2A card (at /.well-known/agent-card.json, or the older
41
+ /.well-known/agent.json) and its signed Descriptor if it serves one (at
42
+ /.well-known/agent-descriptor.json), and writes:
43
+
44
+ <out>/.well-known/agentdoc.json the AgentDoc, for programs
45
+ <out>/agentdoc.html the same document as a page for people
46
+
47
+ Publish both on the agent's own site, so that
48
+ https://your-agent.example/.well-known/agentdoc.json and
49
+ https://your-agent.example/agentdoc.html serve them.
50
+
51
+ Options:
52
+ --descriptor <file|url> use this Descriptor instead of looking for one
53
+ --terms <file|url> signed terms (an Agent SoW standing proposal); repeatable
54
+ --attestation <file> an attestation someone published about the agent; repeatable
55
+ --eval-record <file> a signed evaluation record about the agent; repeatable
56
+ --out <dir> where to write (default ./agentdoc-out)
57
+ --json print the result as JSON
58
+
59
+ Exits 0 when the AgentDoc is written and passes every check, 1 when it is
60
+ written and a check fails or the Descriptor's signature does not verify, and
61
+ 2 when nothing could be read.`,
62
+ check: `common-agent-doc check <agentdoc file | url> [--fetch-sources] [--json]
63
+
64
+ Checks an AgentDoc against the checks of Section 9.10 and prints each
65
+ problem it finds. With --fetch-sources it also fetches every source the
66
+ document lists, checks each digest, and looks for each fact in the sources
67
+ its section cites.
68
+
69
+ Exits 0 when the AgentDoc passes, 1 when it does not, and 2 when it cannot
70
+ be read.`,
71
+ init: `common-agent-doc init <agent address | card file> [--out agent-descriptor.json]
72
+
73
+ Drafts a Descriptor for your agent from its A2A card. The draft is not bound
74
+ to a key and not signed. Every value it had to guess, and every member you
75
+ must fill in, is listed under "_draft" at the top of the file. Check each one,
76
+ fill in what is missing, delete "_draft", then run keygen and sign.
77
+
78
+ It never overwrites a file that already exists.`,
79
+ keygen: `common-agent-doc keygen [--out agent.key]
80
+
81
+ Makes an Ed25519 key for your agent on this machine. It writes the secret
82
+ seed to the file, readable only by you, and prints the public key. Keep the
83
+ file secret: anyone who has it can sign as your agent. Do not commit it.
84
+
85
+ It never overwrites a file that already exists.`,
86
+ sign: `common-agent-doc sign <descriptor file> --key <file> [--out <file>]
87
+
88
+ Binds the Descriptor to your agent's key and signs it, so anyone can check
89
+ that it is your agent's own statement (Common Agent Specification, Section
90
+ 6.6). It writes the signed Descriptor back to the same file unless --out names
91
+ another. Publish it at https://your-agent.example/.well-known/agent-descriptor.json
92
+ exactly as written: readers cite it by the digest of its bytes.
93
+
94
+ It refuses a Descriptor that still has guesses to check, or that lacks a
95
+ member a signed Descriptor must hold, and says which.`,
96
+ };
97
+ const processIo = {
98
+ out: (l) => console.log(l),
99
+ err: (l) => console.error(l),
100
+ now: () => new Date(),
101
+ };
102
+ const VALUED = ["--out", "--key", "--descriptor", "--terms", "--attestation", "--eval-record"];
103
+ function parse(argv) {
104
+ const f = { positional: [], terms: [], attestations: [], evalRecords: [], json: false, fetchSources: false, help: false };
105
+ for (let i = 0; i < argv.length; i++) {
106
+ const a = argv[i];
107
+ if (a === "--json")
108
+ f.json = true;
109
+ else if (a === "--fetch-sources")
110
+ f.fetchSources = true;
111
+ else if (a === "--help" || a === "-h")
112
+ f.help = true;
113
+ else if (VALUED.includes(a)) {
114
+ const v = argv[++i];
115
+ if (v === undefined || v.startsWith("--"))
116
+ return `${a} needs a value`;
117
+ if (a === "--out")
118
+ f.out = v;
119
+ else if (a === "--key")
120
+ f.key = v;
121
+ else if (a === "--descriptor")
122
+ f.descriptor = v;
123
+ else if (a === "--terms")
124
+ f.terms.push(v);
125
+ else if (a === "--attestation")
126
+ f.attestations.push(v);
127
+ else
128
+ f.evalRecords.push(v);
129
+ }
130
+ else if (a.startsWith("--"))
131
+ return `${a} is not an option this tool knows`;
132
+ else
133
+ f.positional.push(a);
134
+ }
135
+ return f;
136
+ }
137
+ class UsageError extends Error {
138
+ }
139
+ /** A file's bytes, or a URL left for the library to fetch. */
140
+ function fileOrUrl(io, v, what) {
141
+ if (isUrl(v))
142
+ return v;
143
+ const p = resolve(io.cwd ?? process.cwd(), v);
144
+ if (!existsSync(p) || !statSync(p).isFile())
145
+ throw new UsageError(`The ${what} ${v} is not a file or an address.`);
146
+ return new Uint8Array(readFileSync(p));
147
+ }
148
+ function jsonFile(io, v, what) {
149
+ const p = resolve(io.cwd ?? process.cwd(), v);
150
+ if (!existsSync(p))
151
+ throw new UsageError(`The ${what} ${v} does not exist.`);
152
+ const value = parseBytes(new Uint8Array(readFileSync(p)), v);
153
+ if (!isObj(value))
154
+ throw new UsageError(`The ${what} ${v} is not a JSON object.`);
155
+ return value;
156
+ }
157
+ /** The target of build and init: a card file on disk, or an agent's address. */
158
+ function target(io, t) {
159
+ const p = resolve(io.cwd ?? process.cwd(), t);
160
+ if (!isUrl(t) && existsSync(p) && statSync(p).isFile())
161
+ return { card: new Uint8Array(readFileSync(p)) };
162
+ return { address: t };
163
+ }
164
+ function printFindings(io, findings) {
165
+ for (const x of findings)
166
+ io.err(` ${x.level === "fail" ? "problem" : "note"}: ${x.message} (${x.rule}, at ${x.path || "the top"})`);
167
+ }
168
+ const writeJson = (path, v) => {
169
+ mkdirSync(dirname(path), { recursive: true });
170
+ writeFileSync(path, `${JSON.stringify(v, null, 2)}\n`);
171
+ };
172
+ async function cmdBuild(f, io) {
173
+ const t = f.positional[1];
174
+ if (!t)
175
+ throw new UsageError("build needs the agent's address or its card file.");
176
+ const input = {
177
+ ...target(io, t),
178
+ ...(f.descriptor ? { descriptor: fileOrUrl(io, f.descriptor, "Descriptor") } : {}),
179
+ ...(f.terms.length ? { terms: f.terms.map((x) => fileOrUrl(io, x, "terms")) } : {}),
180
+ ...(f.attestations.length ? { attestations: f.attestations.map((x) => jsonFile(io, x, "attestation")) } : {}),
181
+ ...(f.evalRecords.length ? { evalRecords: f.evalRecords.map((x) => jsonFile(io, x, "evaluation record")) } : {}),
182
+ now: io.now(),
183
+ ...(io.fetch ? { fetch: io.fetch } : {}),
184
+ };
185
+ const { doc, notes } = await assembleWithNotes(input);
186
+ const outDir = resolve(io.cwd ?? process.cwd(), f.out ?? "agentdoc-out");
187
+ const jsonPath = join(outDir, ...AGENTDOC_PATH.split("/").filter(Boolean));
188
+ const htmlPath = join(outDir, "agentdoc.html");
189
+ writeJson(jsonPath, doc);
190
+ writeFileSync(htmlPath, render(doc));
191
+ const report = await check(doc);
192
+ const descriptorFailed = doc.sources.some((s) => s.kind === "agent-descriptor" && s.signature === "failed");
193
+ const code = report.ok && !descriptorFailed ? 0 : 1;
194
+ if (f.json) {
195
+ io.out(JSON.stringify({ ok: code === 0, agentdoc: jsonPath, page: htmlPath, sources: doc.sources.map((s) => ({ id: s.id, kind: s.kind, signature: s.signature })), not_stated: doc.not_stated, notes, findings: report.findings }, null, 2));
196
+ return code;
197
+ }
198
+ for (const n of notes)
199
+ io.err(` ${n}`);
200
+ io.out(`Wrote the AgentDoc for ${doc.subject?.name ?? doc.subject?.id ?? "the agent"}.`);
201
+ io.out(` ${jsonPath}`);
202
+ io.out(` ${htmlPath}`);
203
+ for (const s of doc.sources)
204
+ io.out(` source ${s.id}: ${s.kind}, ${s.signature === "verified" ? "signature verified" : s.signature === "failed" ? "signature does NOT verify" : s.signature === "not_checked" ? "signature not checked" : "not signed"}${s.not_used ? `, not used: ${String(s.not_used)}` : ""}`);
205
+ io.out(` ${doc.not_stated.length} thing${doc.not_stated.length === 1 ? " is" : "s are"} listed as not stated.`);
206
+ if (!doc.sources.some((s) => s.kind === "agent-descriptor")) {
207
+ io.out(" It has no Descriptor yet. To add a signed one: common-agent-doc init, then keygen, then sign.");
208
+ }
209
+ printFindings(io, report.findings);
210
+ io.out("Publish both files on the agent's site: the JSON at /.well-known/agentdoc.json and the page at /agentdoc.html.");
211
+ return code;
212
+ }
213
+ async function cmdCheck(f, io) {
214
+ const t = f.positional[1];
215
+ if (!t)
216
+ throw new UsageError("check needs an AgentDoc file or address.");
217
+ let value;
218
+ if (isUrl(t))
219
+ value = (await fetchJson(io.fetch ?? globalThis.fetch, t, isoSecond(io.now()))).value;
220
+ else {
221
+ const p = resolve(io.cwd ?? process.cwd(), t);
222
+ if (!existsSync(p))
223
+ throw new UsageError(`${t} does not exist.`);
224
+ value = parseBytes(new Uint8Array(readFileSync(p)), t);
225
+ }
226
+ if (!isObj(value) || value.agentdoc !== "v1")
227
+ throw new UsageError(`${t} is not an AgentDoc: it has no "agentdoc": "v1".`);
228
+ const report = await check(value, { fetchSources: f.fetchSources, ...(io.fetch ? { fetch: io.fetch } : {}) });
229
+ if (f.json) {
230
+ io.out(JSON.stringify(report, null, 2));
231
+ return report.ok ? 0 : 1;
232
+ }
233
+ const fails = report.findings.filter((x) => x.level === "fail").length;
234
+ printFindings(io, report.findings);
235
+ io.out(report.ok ? `The AgentDoc passes every check${f.fetchSources ? "" : " that reads the document alone. Add --fetch-sources to check its sources too"}.` : `The AgentDoc has ${fails} problem${fails === 1 ? "" : "s"}.`);
236
+ return report.ok ? 0 : 1;
237
+ }
238
+ async function cmdInit(f, io) {
239
+ const t = f.positional[1];
240
+ if (!t)
241
+ throw new UsageError("init needs the agent's address or its card file.");
242
+ const outPath = resolve(io.cwd ?? process.cwd(), f.out ?? "agent-descriptor.json");
243
+ if (existsSync(outPath))
244
+ throw new UsageError(`${outPath} already exists. Choose another --out, or move it first.`);
245
+ const tg = target(io, t);
246
+ let card;
247
+ if (tg.card)
248
+ card = parseBytes(tg.card, t);
249
+ else {
250
+ const fx = io.fetch ?? globalThis.fetch;
251
+ for (const url of cardCandidates(t)) {
252
+ try {
253
+ card = (await fetchJson(fx, url, isoSecond(io.now()))).value;
254
+ break;
255
+ }
256
+ catch (e) {
257
+ if (!(e instanceof ReadError && e.status === 404))
258
+ throw e;
259
+ }
260
+ }
261
+ if (card === undefined)
262
+ throw new ReadError(`No A2A Agent Card was found at ${t}.`);
263
+ }
264
+ if (!isObj(card))
265
+ throw new UsageError("The agent card is not a JSON object.");
266
+ const draft = draftFromCard(card);
267
+ writeJson(outPath, draft);
268
+ const d = draft._draft;
269
+ io.out(`Wrote a draft Descriptor to ${outPath}.`);
270
+ io.out(` ${d.guesses.length} guess${d.guesses.length === 1 ? "" : "es"} to check and ${d.fill_in.length} member${d.fill_in.length === 1 ? "" : "s"} to fill in, listed under "_draft" in the file.`);
271
+ io.out(" When it is right, delete \"_draft\", then run: common-agent-doc keygen, and common-agent-doc sign " + (f.out ?? "agent-descriptor.json") + " --key agent.key");
272
+ return 0;
273
+ }
274
+ async function cmdKeygen(f, io) {
275
+ const outPath = resolve(io.cwd ?? process.cwd(), f.out ?? "agent.key");
276
+ if (existsSync(outPath))
277
+ throw new UsageError(`${outPath} already exists. This tool never overwrites a key. Choose another --out.`);
278
+ const seed = encodeUserSeed(new Uint8Array(randomBytes(32)));
279
+ const key = signerFromUserSeed(seed).getPublicKey();
280
+ mkdirSync(dirname(outPath), { recursive: true });
281
+ writeFileSync(outPath, `${seed}\n`, { mode: 0o600, flag: "wx" });
282
+ try {
283
+ chmodSync(outPath, 0o600);
284
+ }
285
+ catch {
286
+ /* a filesystem without modes keeps what it can */
287
+ }
288
+ if (f.json) {
289
+ io.out(JSON.stringify({ public_key: key, key_file: outPath }, null, 2));
290
+ return 0;
291
+ }
292
+ io.out(`Made a signing key for your agent.`);
293
+ io.out(` public key ${key}`);
294
+ io.out(` secret ${outPath} (readable only by you)`);
295
+ io.out(" Keep the secret file safe and out of version control. Anyone who has it can sign as your agent.");
296
+ return 0;
297
+ }
298
+ async function cmdSign(f, io) {
299
+ const t = f.positional[1];
300
+ if (!t)
301
+ throw new UsageError("sign needs the Descriptor file.");
302
+ if (!f.key)
303
+ throw new UsageError("sign needs --key <file>, the file keygen wrote.");
304
+ const d = jsonFile(io, t, "Descriptor");
305
+ const problems = signingProblems(d);
306
+ if (problems.length) {
307
+ io.err(`The Descriptor is not ready to sign:`);
308
+ for (const p of problems)
309
+ io.err(` - ${p}`);
310
+ return 1;
311
+ }
312
+ const keyPath = resolve(io.cwd ?? process.cwd(), f.key);
313
+ if (!existsSync(keyPath))
314
+ throw new UsageError(`The key file ${f.key} does not exist. Make one with common-agent-doc keygen.`);
315
+ let signed;
316
+ try {
317
+ signed = signDescriptor(d, readFileSync(keyPath, "utf8").trim());
318
+ }
319
+ catch (e) {
320
+ const m = e.message;
321
+ io.err(/not an nkey user seed/.test(m) ? `${f.key} does not hold a key this tool made (an nkey user seed, SU...).` : m);
322
+ return 1;
323
+ }
324
+ const outPath = resolve(io.cwd ?? process.cwd(), f.out ?? t);
325
+ writeJson(outPath, signed);
326
+ io.out(`Signed the Descriptor as ${signed.subject.id}.`);
327
+ io.out(` ${outPath}`);
328
+ io.out(" Publish this file exactly as written at https://your-agent.example/.well-known/agent-descriptor.json, then run common-agent-doc build again.");
329
+ return 0;
330
+ }
331
+ /** Run the tool on its arguments (without the program name), and answer the exit code. */
332
+ export async function main(argv, io = processIo) {
333
+ const f = parse(argv);
334
+ if (typeof f === "string") {
335
+ io.err(`${f}\n\n${USAGE}`);
336
+ return 2;
337
+ }
338
+ const cmd = f.positional[0];
339
+ if (!cmd || (cmd === "help" && !f.positional[1])) {
340
+ (f.help || cmd === "help" ? io.out : io.err)(USAGE);
341
+ return f.help || cmd === "help" ? 0 : 2;
342
+ }
343
+ const name = cmd === "help" ? f.positional[1] : cmd;
344
+ if (!HELP[name]) {
345
+ io.err(`${name} is not a command this tool knows.\n\n${USAGE}`);
346
+ return 2;
347
+ }
348
+ if (f.help || cmd === "help") {
349
+ io.out(HELP[name]);
350
+ return 0;
351
+ }
352
+ try {
353
+ switch (name) {
354
+ case "build": return await cmdBuild(f, io);
355
+ case "check": return await cmdCheck(f, io);
356
+ case "init": return await cmdInit(f, io);
357
+ case "keygen": return await cmdKeygen(f, io);
358
+ default: return await cmdSign(f, io);
359
+ }
360
+ }
361
+ catch (e) {
362
+ if (e instanceof UsageError || e instanceof AssembleError || e instanceof ReadError) {
363
+ io.err(e.message);
364
+ return 2;
365
+ }
366
+ throw e;
367
+ }
368
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The Descriptor an owner adds to an agent that has only a card: a draft
3
+ * written from the card, for the owner to correct, and the check that a
4
+ * Descriptor holds what a signed one must before it is signed.
5
+ *
6
+ * The draft adds no address, no key and no claim the card does not make.
7
+ * Every value it had to guess is listed under `_draft.guesses`, and every
8
+ * member it could not fill is listed under `_draft.fill_in`. `sign` refuses a
9
+ * Descriptor that still carries `_draft`, so no guess is signed unread.
10
+ */
11
+ import { type Rec } from "./util.js";
12
+ /** The member that marks a draft written by `init`. */
13
+ export declare const DRAFT_MARK = "_draft";
14
+ /** A draft Descriptor from an A2A card: unbound, unsigned, and every guess marked. */
15
+ export declare function draftFromCard(card: Rec): Rec;
16
+ /**
17
+ * What stops a Descriptor from being signed as an agent's own: the members of
18
+ * the minimal Descriptor (Section 6.2) it lacks, and a `_draft` left in it.
19
+ * Empty when it can be signed.
20
+ */
21
+ export declare function signingProblems(d: unknown): string[];
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The Descriptor an owner adds to an agent that has only a card: a draft
3
+ * written from the card, for the owner to correct, and the check that a
4
+ * Descriptor holds what a signed one must before it is signed.
5
+ *
6
+ * The draft adds no address, no key and no claim the card does not make.
7
+ * Every value it had to guess is listed under `_draft.guesses`, and every
8
+ * member it could not fill is listed under `_draft.fill_in`. `sign` refuses a
9
+ * Descriptor that still carries `_draft`, so no guess is signed unread.
10
+ */
11
+ import { arr, isObj, str, text } from "./util.js";
12
+ /** The member that marks a draft written by `init`. */
13
+ export const DRAFT_MARK = "_draft";
14
+ const ACTS_FOR = ["person", "organization", "anyone"];
15
+ /** The value kind (Section 6.3) a media type from a card coarsens back to: our best guess, marked as one. */
16
+ function kindOf(mode) {
17
+ const m = str(mode).toLowerCase();
18
+ if (!m || m === "text" || m === "text/plain")
19
+ return "text";
20
+ return m;
21
+ }
22
+ /** A draft Descriptor from an A2A card: unbound, unsigned, and every guess marked. */
23
+ export function draftFromCard(card) {
24
+ const guesses = [];
25
+ const fillIn = [];
26
+ const version = text(card.version);
27
+ if (!version)
28
+ guesses.push("/agent_version: the card gives no version, so 0.1.0 is a placeholder");
29
+ const does = text(card.description);
30
+ if (!does)
31
+ fillIn.push("does: one sentence on what the agent does");
32
+ const offerings = arr(card.skills).filter(isObj).map((s, i) => {
33
+ const inModes = arr(Array.isArray(s.inputModes) ? s.inputModes : card.defaultInputModes);
34
+ const outModes = arr(Array.isArray(s.outputModes) ? s.outputModes : card.defaultOutputModes);
35
+ const at = `/offerings/${i}`;
36
+ guesses.push(`${at}/inputs: the card lists accepted media types, not named inputs; name each input and say whether it is required`);
37
+ guesses.push(`${at}/outputs: the card lists returned media types, not named deliverables; name each one`);
38
+ if (!text(s.description))
39
+ fillIn.push(`${at}/does: one sentence on what this offering does`);
40
+ return {
41
+ id: text(s.id) ?? `offering-${i + 1}`,
42
+ name: text(s.name) ?? text(s.id) ?? `Offering ${i + 1}`,
43
+ ...(text(s.description) ? { does: text(s.description) } : {}),
44
+ inputs: (inModes.length ? inModes : ["text"]).slice(0, 1).map((m) => ({ name: "request", kind: kindOf(m), required: true })),
45
+ outputs: (outModes.length ? outModes : ["text"]).slice(0, 1).map((m) => ({ name: "reply", kind: kindOf(m), when: "per_task" })),
46
+ };
47
+ });
48
+ if (!offerings.length)
49
+ fillIn.push("offerings: the card lists no skills; an empty list says the agent takes no work");
50
+ fillIn.push(`acts_for: whom the agent acts for, one of ${ACTS_FOR.join(", ")} (add organization_name beside organization)`);
51
+ fillIn.push("refusals: what the agent will not do, in your own words");
52
+ fillIn.push('triggers: what makes the agent act when nobody has asked: the events it watches, the schedules it keeps, whether it may set its own (sets_own) and whom it contacts; an agent that acts only when asked says { "events": [], "schedules": [], "sets_own": false }');
53
+ return {
54
+ [DRAFT_MARK]: {
55
+ note: "A draft written from your agent's card by common-agent-doc init. Check every guess, fill in each missing member, then delete this _draft member and sign it with common-agent-doc sign.",
56
+ guesses,
57
+ fill_in: fillIn,
58
+ },
59
+ format: "agent-descriptor-v1",
60
+ agent_version: version ?? "0.1.0",
61
+ ...(does ? { does } : {}),
62
+ offerings,
63
+ };
64
+ }
65
+ /**
66
+ * What stops a Descriptor from being signed as an agent's own: the members of
67
+ * the minimal Descriptor (Section 6.2) it lacks, and a `_draft` left in it.
68
+ * Empty when it can be signed.
69
+ */
70
+ export function signingProblems(d) {
71
+ if (!isObj(d))
72
+ return ["it is not a JSON object"];
73
+ const out = [];
74
+ if (d[DRAFT_MARK] !== undefined)
75
+ out.push(`it still carries ${DRAFT_MARK}: check each guess, fill in what it lists, then delete it`);
76
+ if (d.format !== "agent-descriptor-v1")
77
+ out.push('format must be "agent-descriptor-v1"');
78
+ if (typeof d.agent_version !== "string" || !d.agent_version)
79
+ out.push("agent_version is missing");
80
+ if (typeof d.does !== "string" || !d.does.trim())
81
+ out.push("does is missing: one sentence on what the agent does");
82
+ if (!ACTS_FOR.includes(str(d.acts_for)))
83
+ out.push(`acts_for must be one of ${ACTS_FOR.join(", ")}`);
84
+ if (d.organization_name !== undefined && d.acts_for !== "organization")
85
+ out.push("organization_name goes only beside acts_for organization");
86
+ if (!Array.isArray(d.offerings))
87
+ out.push("offerings is missing (an empty list says the agent takes no work)");
88
+ else
89
+ d.offerings.forEach((o, i) => {
90
+ if (!isObj(o))
91
+ return out.push(`offering ${i + 1} is not an object`);
92
+ for (const k of ["id", "name"])
93
+ if (!text(o[k]))
94
+ out.push(`offering ${i + 1} has no ${k}`);
95
+ if (!Array.isArray(o.inputs))
96
+ out.push(`offering ${str(o.id) || i + 1} has no inputs list (it may be empty)`);
97
+ if (!Array.isArray(o.outputs))
98
+ out.push(`offering ${str(o.id) || i + 1} has no outputs list (it may be empty)`);
99
+ });
100
+ if (d.shape !== undefined)
101
+ out.push("shape was removed from the format; take it out (Section 6.12)");
102
+ // every event names a system the Descriptor declares, because watching a system is reaching it (Section 6.2)
103
+ if (isObj(d.triggers) && Array.isArray(d.triggers.events)) {
104
+ const systems = arr(d.systems).filter(isObj).map((s) => str(s.name ?? s.role));
105
+ d.triggers.events.forEach((e, i) => {
106
+ const sys = isObj(e) ? str(e.system) : "";
107
+ if (!sys)
108
+ out.push(`trigger event ${i + 1} names no system`);
109
+ else if (!systems.includes(sys))
110
+ out.push(`trigger event ${i + 1} comes from ${sys}, which systems does not declare`);
111
+ });
112
+ }
113
+ return out;
114
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @common-agent/agentdoc: make, publish and check an AgentDoc (Common Agent
3
+ * Specification, Chapter 9, https://agentdoc.net).
4
+ *
5
+ * An AgentDoc is one document that assembles what an agent publishes about
6
+ * itself, its A2A card and its signed Descriptor first, and says where every
7
+ * line came from. `assemble` builds one, `check` runs the checks of Section
8
+ * 9.10, and `render` writes the page a person reads.
9
+ */
10
+ export { AGENTDOC_PATH, AssembleError, CARD_PATHS, DESCRIPTOR_PATH, INTERFACE_REGISTRY, TERMS_EXTENSION, assemble, assembleWithNotes, cardCandidates, notStatedOf, type Assembled } from "./assemble.js";
11
+ export { CLAIM_KEYS, GRADE_ENDINGS, GRADE_KEYS, PACKAGE_NAMES, check, staticFindings } from "./check.js";
12
+ export { DRAFT_MARK, draftFromCard, signingProblems } from "./descriptor.js";
13
+ export { KNOWN_SECTIONS } from "./paths.js";
14
+ export { render } from "./render.js";
15
+ export { DESCRIPTOR_TAG, EVAL_TAG, SOW_TAG, checkDescriptorSignature, checkEvalSignature, checkTermsSignature, encodeUserSeed, openAttestation, signDescriptor, type SignatureCheck } from "./signatures.js";
16
+ export { RULE_IDS, type AgentDoc, type AgentDocSection, type AgentDocSource, type AssembleInput, type CheckOptions, type CheckReport, type DocumentInput, type Finding, type RuleId, type SignatureState } from "./types.js";
17
+ export { VERSION } from "./version.js";
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @common-agent/agentdoc: make, publish and check an AgentDoc (Common Agent
3
+ * Specification, Chapter 9, https://agentdoc.net).
4
+ *
5
+ * An AgentDoc is one document that assembles what an agent publishes about
6
+ * itself, its A2A card and its signed Descriptor first, and says where every
7
+ * line came from. `assemble` builds one, `check` runs the checks of Section
8
+ * 9.10, and `render` writes the page a person reads.
9
+ */
10
+ export { AGENTDOC_PATH, AssembleError, CARD_PATHS, DESCRIPTOR_PATH, INTERFACE_REGISTRY, TERMS_EXTENSION, assemble, assembleWithNotes, cardCandidates, notStatedOf } from "./assemble.js";
11
+ export { CLAIM_KEYS, GRADE_ENDINGS, GRADE_KEYS, PACKAGE_NAMES, check, staticFindings } from "./check.js";
12
+ export { DRAFT_MARK, draftFromCard, signingProblems } from "./descriptor.js";
13
+ export { KNOWN_SECTIONS } from "./paths.js";
14
+ export { render } from "./render.js";
15
+ export { DESCRIPTOR_TAG, EVAL_TAG, SOW_TAG, checkDescriptorSignature, checkEvalSignature, checkTermsSignature, encodeUserSeed, openAttestation, signDescriptor } from "./signatures.js";
16
+ export { RULE_IDS } from "./types.js";
17
+ export { VERSION } from "./version.js";
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The paths of `not_stated`, read the same way by the assembler that writes
3
+ * them and the checker that reads them.
4
+ *
5
+ * A path is dotted: a section, then members, such as `handling.processed_in`.
6
+ * A path whose first word is not a section names a top-level member, such as
7
+ * `subject` in a package AgentDoc. Inside a list, a word that is an entry's
8
+ * `id` or `name` picks that entry (`sells.offerings.summarize.inputs`), and
9
+ * any other word applies to every entry (`sells.offerings.price`). Under
10
+ * `sells`, a word that is not a member of the section applies to each
11
+ * offering (`sells.price`). A path covers itself and every path below it.
12
+ */
13
+ import { type Rec } from "./util.js";
14
+ /** The sections of Section 9.5, in the order a reader meets them. */
15
+ export declare const KNOWN_SECTIONS: readonly ["identity", "shape", "asked", "role", "sells", "access", "refuses", "reaches", "leaves", "configs", "triggers", "handling", "standing"];
16
+ /** Every value present at a path; empty when nothing is there. */
17
+ export declare function valuesAt(doc: Rec, path: string): unknown[];
18
+ /** Whether `not_stated` names one of these paths or a path above one of them. */
19
+ export declare function covered(notStated: readonly string[], candidates: readonly string[]): boolean;
20
+ /** The paths that name an offering's member, under every spelling a reader accepts. */
21
+ export declare function offeringPaths(o: Rec, member: string): string[];
22
+ /** The paths that name a declared interface's exchanges. */
23
+ export declare function interfacePaths(name: string): string[];
package/dist/paths.js ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The paths of `not_stated`, read the same way by the assembler that writes
3
+ * them and the checker that reads them.
4
+ *
5
+ * A path is dotted: a section, then members, such as `handling.processed_in`.
6
+ * A path whose first word is not a section names a top-level member, such as
7
+ * `subject` in a package AgentDoc. Inside a list, a word that is an entry's
8
+ * `id` or `name` picks that entry (`sells.offerings.summarize.inputs`), and
9
+ * any other word applies to every entry (`sells.offerings.price`). Under
10
+ * `sells`, a word that is not a member of the section applies to each
11
+ * offering (`sells.price`). A path covers itself and every path below it.
12
+ */
13
+ import { isObj } from "./util.js";
14
+ /** The sections of Section 9.5, in the order a reader meets them. */
15
+ export const KNOWN_SECTIONS = ["identity", "shape", "asked", "role", "sells", "access", "refuses", "reaches", "leaves", "configs", "triggers", "handling", "standing"];
16
+ const isSection = (doc, word) => KNOWN_SECTIONS.includes(word) || (isObj(doc.sections) && Object.prototype.hasOwnProperty.call(doc.sections, word));
17
+ function step(v, segs, parent) {
18
+ if (v === undefined)
19
+ return [];
20
+ if (!segs.length)
21
+ return [v];
22
+ const [s, ...rest] = segs;
23
+ if (Array.isArray(v)) {
24
+ const hit = v.find((e) => isObj(e) && (e.id === s || e.name === s));
25
+ if (hit !== undefined)
26
+ return step(hit, rest, s);
27
+ return v.flatMap((e) => step(e, segs, parent));
28
+ }
29
+ if (isObj(v)) {
30
+ if (Object.prototype.hasOwnProperty.call(v, s))
31
+ return step(v[s], rest, s);
32
+ if (parent === "sells" && Array.isArray(v.offerings))
33
+ return step(v.offerings, segs, "offerings");
34
+ }
35
+ return [];
36
+ }
37
+ /** Every value present at a path; empty when nothing is there. */
38
+ export function valuesAt(doc, path) {
39
+ const segs = path.split(".").filter(Boolean);
40
+ if (!segs.length)
41
+ return [];
42
+ const [first, ...rest] = segs;
43
+ const root = isSection(doc, first) ? (isObj(doc.sections) ? doc.sections[first] : undefined) : doc[first];
44
+ return step(root, rest, first).filter((x) => x !== undefined && x !== null);
45
+ }
46
+ /** Whether `not_stated` names one of these paths or a path above one of them. */
47
+ export function covered(notStated, candidates) {
48
+ return candidates.some((c) => notStated.some((n) => n === c || c.startsWith(`${n}.`)));
49
+ }
50
+ /** The paths that name an offering's member, under every spelling a reader accepts. */
51
+ export function offeringPaths(o, member) {
52
+ const keys = [o.id, o.name].filter((k) => typeof k === "string" && k.length > 0);
53
+ return [...keys.map((k) => `sells.offerings.${k}.${member}`), `sells.offerings.${member}`, `sells.${member}`];
54
+ }
55
+ /** The paths that name a declared interface's exchanges. */
56
+ export function interfacePaths(name) {
57
+ return [`asked.interfaces.${name}.exchanges`, `asked.interfaces.${name}`, `asked.${name}`];
58
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The human page (Section 9.8): one self-contained HTML file rendered from
3
+ * the AgentDoc alone, readable without JavaScript.
4
+ *
5
+ * What it keeps from Section 9.8: every section shows which sources it came
6
+ * from; `not_stated` is shown as plainly as what was stated; the assembly time
7
+ * is shown, and `stale_after` where there is one; nothing is added that the
8
+ * document does not hold, so there is no badge, score or trust mark. And the
9
+ * five differences that vanish once lost: an absent `reaches` is not an empty
10
+ * reach, a grant is shown apart from a file, an absent `access` is not an open
11
+ * door, an open offering is shown with its scope in words, never as a list of
12
+ * work it can do, and an absent `triggers` is no promise to wait to be asked.
13
+ *
14
+ * Nothing is presented above what `shape.visibility` supports (Section
15
+ * 9.5.1). A ceiling decided by rule is shown as the operator's word that a
16
+ * rule holds the agent to it, and as enforced only where the document itself
17
+ * marks it so at a visibility that allows it.
18
+ */
19
+ import type { AgentDoc } from "./types.js";
20
+ /** Render an AgentDoc as a self-contained page. */
21
+ export declare function render(doc: AgentDoc): string;