@common-agent/agentdoc 0.0.0-stage → 0.1.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/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ // The executable: runs the command line tool on this process's arguments.
3
+ import { main } from "./cli.js";
4
+ main(process.argv.slice(2)).then((code) => {
5
+ process.exitCode = code;
6
+ }, (e) => {
7
+ console.error(e instanceof Error ? e.message : String(e));
8
+ process.exitCode = 2;
9
+ });
@@ -0,0 +1,14 @@
1
+ import type { AgentDoc, CheckOptions, CheckReport, Finding } from "./types.js";
2
+ /** The keys that are a summary grade wherever they appear (Section 9.3), and the endings that make one. */
3
+ export declare const GRADE_KEYS: string[];
4
+ export declare const GRADE_ENDINGS: string[];
5
+ /** The grades an Agent SoW clause carries (Agent SoW Section 3). A `grade` with one of these values grades a quoted clause, not the agent, and is allowed. */
6
+ export declare const CLAUSE_GRADES: string[];
7
+ /** The keys that are a statement of what an open-ended offering can do (Section 9.5). */
8
+ export declare const CLAIM_KEYS: string[];
9
+ /** What a package AgentDoc always names in `not_stated` (Section 13.4, rule 2). */
10
+ export declare const PACKAGE_NAMES: string[];
11
+ /** The twelve static checks, and the warnings that go with them. */
12
+ export declare function staticFindings(doc: unknown): Finding[];
13
+ /** Check an AgentDoc. Static checks always; with `fetchSources`, the sources themselves too. */
14
+ export declare function check(doc: AgentDoc | unknown, opts?: CheckOptions): Promise<CheckReport>;
package/dist/check.js ADDED
@@ -0,0 +1,351 @@
1
+ /**
2
+ * The checker: the fourteen checks of Section 9.10, by the rule ids every
3
+ * Common Agent checker shares.
4
+ *
5
+ * Twelve are static: they read the document alone, and each reads it exactly
6
+ * as the Common Agent Standards' reference checker does
7
+ * (`common-agent/conformance/lib/check-agentdoc.mjs`), so that this package
8
+ * and that checker agree on every conformance case. Two need the sources and
9
+ * run only with `fetchSources`: `source-digest` fetches each listed source and
10
+ * compares its digest, and `fact-in-source` looks for each fact of a section
11
+ * in the sources that section cites.
12
+ *
13
+ * A finding at level `fail` is a check the document fails. A finding at level
14
+ * `warn` is something Section 9 asks for that the shared reading leaves out,
15
+ * or something this checker could not decide, such as a source with no
16
+ * address to fetch. Warnings never make `ok` false.
17
+ */
18
+ import { canonicalJSON, sha256Digest } from "@common-agent/crypto";
19
+ import { KNOWN_SECTIONS, covered, offeringPaths } from "./paths.js";
20
+ import { ReadError, arr, isObj, parseBytes, str } from "./util.js";
21
+ /** The keys that are a summary grade wherever they appear (Section 9.3), and the endings that make one. */
22
+ export const GRADE_KEYS = ["score", "rating", "grade", "badge", "badges", "tier", "rank", "stars", "trust", "trust_label", "trust_level", "trust_mark"];
23
+ export const GRADE_ENDINGS = ["_score", "_rating", "_grade", "_badge", "_tier", "_rank", "_stars"];
24
+ /** The grades an Agent SoW clause carries (Agent SoW Section 3). A `grade` with one of these values grades a quoted clause, not the agent, and is allowed. */
25
+ export const CLAUSE_GRADES = ["enforced", "evidence", "recorded"];
26
+ /** The keys that are a statement of what an open-ended offering can do (Section 9.5). */
27
+ export const CLAIM_KEYS = ["does", "focus", "role", "can_do", "capabilities", "skills", "examples"];
28
+ /** What a package AgentDoc always names in `not_stated` (Section 13.4, rule 2). */
29
+ export const PACKAGE_NAMES = ["subject", "standing", "access", "handling", "shape.visibility", "sells.offerings.price"];
30
+ const isStr = (v) => typeof v === "string" && v.length > 0;
31
+ /** Every object under a value, with its path, the value itself included. */
32
+ function* objects(value, path) {
33
+ if (Array.isArray(value)) {
34
+ for (let i = 0; i < value.length; i++)
35
+ yield* objects(value[i], `${path}[${i}]`);
36
+ }
37
+ else if (isObj(value)) {
38
+ yield [value, path];
39
+ for (const [k, v] of Object.entries(value))
40
+ yield* objects(v, `${path}.${k}`);
41
+ }
42
+ }
43
+ /** The value at a dotted path, reading the rest of the path in each element of an array on the way. */
44
+ function valueAt(root, parts) {
45
+ if (!parts.length)
46
+ return root;
47
+ if (Array.isArray(root)) {
48
+ for (const el of root) {
49
+ const v = valueAt(el, parts);
50
+ if (v !== undefined)
51
+ return v;
52
+ }
53
+ return undefined;
54
+ }
55
+ if (!isObj(root) || !Object.prototype.hasOwnProperty.call(root, parts[0]))
56
+ return undefined;
57
+ return valueAt(root[parts[0]], parts.slice(1));
58
+ }
59
+ /** The twelve static checks, and the warnings that go with them. */
60
+ export function staticFindings(doc) {
61
+ const findings = [];
62
+ const add = (rule, path, message, level = "fail") => findings.push({ rule, path, message, level });
63
+ if (!isObj(doc)) {
64
+ add("section-has-source", "", "the document is not a JSON object");
65
+ return findings;
66
+ }
67
+ const isPackage = doc.package !== undefined;
68
+ const sources = arr(doc.sources);
69
+ const sourceIds = new Set(sources.filter(isObj).map((s) => s.id));
70
+ const sections = isObj(doc.sections) ? doc.sections : {};
71
+ const notStated = arr(doc.not_stated).filter((p) => typeof p === "string");
72
+ const named = (path) => notStated.some((e) => path === e || path.startsWith(`${e}.`));
73
+ // sources-exist and section-has-source (Section 9.3)
74
+ for (const [name, s] of Object.entries(sections)) {
75
+ if (!isObj(s) || !Array.isArray(s.from) || s.from.length === 0) {
76
+ add("section-has-source", `sections.${name}.from`, `the ${name} section names no source`);
77
+ continue;
78
+ }
79
+ for (const id of s.from) {
80
+ if (!sourceIds.has(id))
81
+ add("sources-exist", `sections.${name}.from`, `the ${name} section cites ${JSON.stringify(id)}, which is not among the sources`);
82
+ }
83
+ // A member's own pointer narrows the section's sources and never widens them (Section 9.3).
84
+ for (const [o, path] of objects(s, `sections.${name}`)) {
85
+ for (const [k, v] of Object.entries(o)) {
86
+ if (!k.endsWith("_from") || typeof v !== "string")
87
+ continue;
88
+ if (!sourceIds.has(v))
89
+ add("sources-exist", `${path}.${k}`, `${k} names ${JSON.stringify(v)}, which is not among the sources`);
90
+ else if (!s.from.includes(v))
91
+ add("sources-exist", `${path}.${k}`, `${k} names ${JSON.stringify(v)}, which the ${name} section does not cite`, "warn");
92
+ }
93
+ }
94
+ }
95
+ // no-summary-grade (Section 9.3)
96
+ for (const [o, path] of objects(doc, "")) {
97
+ for (const k of Object.keys(o)) {
98
+ const key = k.toLowerCase();
99
+ if (key === "grade" && CLAUSE_GRADES.includes(String(o[k])))
100
+ continue; // an Agent SoW clause grade grades the clause, not the agent
101
+ if (GRADE_KEYS.includes(key) || GRADE_ENDINGS.some((e) => key.endsWith(e))) {
102
+ add("no-summary-grade", `${path}.${k}`.replace(/^\./, ""), `${k} is a summary grade, and an AgentDoc carries none`);
103
+ }
104
+ }
105
+ }
106
+ // visibility-supports-claim and decided-by-rule (Sections 9.5.1 and 6.11): presented as enforced is "enforced": true.
107
+ const visibility = isObj(sections.shape) ? sections.shape.visibility : undefined;
108
+ for (const [o, path] of objects(sections, "sections")) {
109
+ if (o.enforced !== true)
110
+ continue;
111
+ const atDoor = path === "sections.access" || path.startsWith("sections.access.") || path.startsWith("sections.access[");
112
+ const supported = visibility === "verifiable" || (visibility === "observed" && atDoor);
113
+ if (!supported) {
114
+ add("visibility-supports-claim", path, `${path} is presented as enforced, and visibility ${visibility === undefined ? "absent" : JSON.stringify(visibility)} does not support that${visibility === "observed" ? " away from the door" : ""}`);
115
+ }
116
+ if (o.decided_by !== "rule") {
117
+ add("decided-by-rule", path, `${path} is presented as enforced, and what decides it is ${o.decided_by === undefined ? "not stated" : JSON.stringify(o.decided_by)}, not a rule`);
118
+ }
119
+ }
120
+ // sells-scope, open-offering-members and open-ended-no-claim (Sections 9.5 and 6.11)
121
+ const sells = isObj(sections.sells) ? sections.sells : undefined;
122
+ const offerings = sells && Array.isArray(sells.offerings) ? sells.offerings : [];
123
+ const handling = isObj(sections.handling) ? sections.handling : {};
124
+ offerings.forEach((o, i) => {
125
+ const at = `sections.sells.offerings[${i}]`;
126
+ if (!isObj(o)) {
127
+ add("sells-scope", at, "the offering is not an object");
128
+ return;
129
+ }
130
+ const label = str(o.name) || str(o.id) || String(i);
131
+ if (!isStr(o.scope)) {
132
+ add("sells-scope", at, `offering ${label} carries no scope`);
133
+ return;
134
+ }
135
+ if (o.scope !== "open-with-focus" && o.scope !== "open-ended")
136
+ return;
137
+ const lacks = [];
138
+ if (o.scope === "open-with-focus") {
139
+ if (!isStr(o.focus))
140
+ lacks.push("focus");
141
+ if (!Array.isArray(o.workspace))
142
+ lacks.push("workspace");
143
+ const outs = (Array.isArray(o.outputs) && o.outputs.length > 0) || (isObj(o.deliverables) && Array.isArray(o.deliverables.per_task) && o.deliverables.per_task.length > 0);
144
+ if (!outs)
145
+ lacks.push("an output");
146
+ }
147
+ if (!Array.isArray(o.authority))
148
+ lacks.push("authority");
149
+ if (!isObj(o.ceilings))
150
+ lacks.push("ceilings");
151
+ else {
152
+ for (const c of ["job_seconds", "cost_per_job"])
153
+ if (o.ceilings[c] === undefined)
154
+ lacks.push(`ceilings.${c}`);
155
+ const authority = arr(o.authority);
156
+ if (authority.includes("spends-money") && o.ceilings.spend_per_job === undefined)
157
+ lacks.push("ceilings.spend_per_job");
158
+ if (authority.includes("sends-messages") && o.ceilings.messages_per_job === undefined)
159
+ lacks.push("ceilings.messages_per_job");
160
+ }
161
+ for (const l of lacks)
162
+ add("open-offering-members", at, `the ${o.scope} offering ${label} lacks ${l}`);
163
+ if (o.scope === "open-ended") {
164
+ for (const k of CLAIM_KEYS)
165
+ if (o[k] !== undefined)
166
+ add("open-ended-no-claim", `${at}.${k}`, `the open-ended offering ${label} carries ${k}, a statement of what it can do`);
167
+ // Section 6.11 also asks an open-ended agent to declare its data use; the shared reading leaves that out, so it is a warning here.
168
+ const dataUse = ["retention_max_days", "processors", "memory"].filter((m) => handling[m] === undefined && !named(`handling.${m}`));
169
+ if (dataUse.length)
170
+ add("open-offering-members", at, `the open-ended offering ${label} has no data use in handling (${dataUse.join(", ")})`, "warn");
171
+ }
172
+ });
173
+ // assembled-at and fetched-at (Section 9.3), not applied to a package AgentDoc (Section 13.4, rule 3)
174
+ if (!isPackage) {
175
+ if (!isStr(doc.assembled_at))
176
+ add("assembled-at", "assembled_at", "the document does not say when it was assembled");
177
+ sources.forEach((s, i) => {
178
+ const ok = isObj(s) && (isStr(s.fetched_at) || (s.kind === "observation" && isStr(s.at)));
179
+ if (!ok)
180
+ add("fetched-at", `sources[${i}]`, `source ${isObj(s) ? String(s.id ?? i) : i} does not say when it was fetched`);
181
+ });
182
+ }
183
+ // not-stated-complete (Sections 9.5, 9.6, 9.5.1 and 13.4)
184
+ const need = (path, present) => {
185
+ if (!present && !named(path))
186
+ add("not-stated-complete", "not_stated", `${path} is absent and not named in not_stated`);
187
+ };
188
+ for (const name of KNOWN_SECTIONS)
189
+ need(name, sections[name] !== undefined);
190
+ if (sections.identity !== undefined)
191
+ need("identity.acts_for", isObj(sections.identity) && sections.identity.acts_for !== undefined);
192
+ if (sections.shape !== undefined)
193
+ need("shape.visibility", visibility !== undefined);
194
+ if (sections.access !== undefined) {
195
+ need("access.schemes", isObj(sections.access) && sections.access.schemes !== undefined);
196
+ need("access.admission", isObj(sections.access) && sections.access.admission !== undefined);
197
+ }
198
+ const interfaces = isObj(sections.asked) ? arr(sections.asked.interfaces) : [];
199
+ for (const iface of interfaces) {
200
+ if (isObj(iface) && isStr(iface.name))
201
+ need(`asked.${iface.name}`, Array.isArray(iface.exchanges) && iface.exchanges.length > 0);
202
+ }
203
+ if (isPackage)
204
+ for (const path of PACKAGE_NAMES)
205
+ need(path, false);
206
+ // What Section 9.5 also asks to be named, which the shared reading leaves out: warnings.
207
+ offerings.forEach((o, i) => {
208
+ if (!isObj(o))
209
+ return;
210
+ if (o.inputs === undefined && !covered(notStated, offeringPaths(o, "inputs")))
211
+ add("not-stated-complete", `sections.sells.offerings[${i}]`, `offering ${str(o.name) || str(o.id) || i} lists no inputs and does not name them in not_stated`, "warn");
212
+ if (o.outputs === undefined && o.deliverables === undefined && !covered(notStated, [...offeringPaths(o, "outputs"), ...offeringPaths(o, "deliverables")]))
213
+ add("not-stated-complete", `sections.sells.offerings[${i}]`, `offering ${str(o.name) || str(o.id) || i} lists no deliverables and does not name them in not_stated`, "warn");
214
+ });
215
+ if (isObj(sections.configs) && arr(sections.configs.settings).length && sections.configs.tested_models === undefined)
216
+ need2("configs.tested_models");
217
+ function need2(path) {
218
+ if (!named(path))
219
+ add("not-stated-complete", "not_stated", `${path} is absent and not named in not_stated`, "warn");
220
+ }
221
+ // no-default (Section 9.6): a path is read in the sections first, then at the top of the document.
222
+ for (const entry of notStated) {
223
+ const parts = entry.split(".");
224
+ const inSections = valueAt(sections, parts);
225
+ const v = inSections !== undefined ? inSections : valueAt(doc, parts);
226
+ if (v !== undefined)
227
+ add("no-default", `not_stated: ${entry}`, `${entry} is named in not_stated and given a value anyway`);
228
+ }
229
+ return findings;
230
+ }
231
+ // ── the two checks that need the sources ────────────────────────────────────
232
+ /** Members that say how the document was built, not what a source said: never looked for in a source. */
233
+ const CONSTRUCTION = new Set(["from", "state", "declared_in", "scope", "scopes", "visibility", "confirmed_at", "confirmed_by", "failed_at", "failed_by", "record", "signature", "protocol", "offered", "kind"]);
234
+ /** Every string and number a source holds, its member names included. */
235
+ function scalarsOf(v, out) {
236
+ if (Array.isArray(v))
237
+ for (const x of v)
238
+ scalarsOf(x, out);
239
+ else if (isObj(v))
240
+ for (const [k, x] of Object.entries(v)) {
241
+ out.add(k);
242
+ scalarsOf(x, out);
243
+ }
244
+ else if (typeof v === "string")
245
+ out.add(v);
246
+ else if (typeof v === "number")
247
+ out.add(String(v));
248
+ return out;
249
+ }
250
+ /** Every fact of a section: each string and number, with where it is, leaving out how the document was built. */
251
+ function factsOf(v, path, out) {
252
+ if (Array.isArray(v))
253
+ v.forEach((x, i) => factsOf(x, `${path}[${i}]`, out));
254
+ else if (isObj(v)) {
255
+ for (const [k, x] of Object.entries(v)) {
256
+ if (CONSTRUCTION.has(k) || k.endsWith("_from"))
257
+ continue;
258
+ factsOf(x, `${path}.${k}`, out);
259
+ }
260
+ }
261
+ else if (typeof v === "string" && v.length)
262
+ out.push([path, v]);
263
+ else if (typeof v === "number")
264
+ out.push([path, String(v)]);
265
+ return out;
266
+ }
267
+ /** Check an AgentDoc. Static checks always; with `fetchSources`, the sources themselves too. */
268
+ export async function check(doc, opts = {}) {
269
+ const findings = staticFindings(doc);
270
+ if (opts.fetchSources && isObj(doc))
271
+ findings.push(...(await sourceFindings(doc, opts.fetch ?? globalThis.fetch)));
272
+ return { ok: !findings.some((f) => f.level === "fail"), findings };
273
+ }
274
+ async function sourceFindings(doc, f) {
275
+ const findings = [];
276
+ const add = (rule, path, message, level = "fail") => findings.push({ rule, path, message, level });
277
+ const fetched = new Map();
278
+ const sources = arr(doc.sources);
279
+ for (let i = 0; i < sources.length; i++) {
280
+ const s = sources[i];
281
+ if (!isObj(s) || typeof s.id !== "string")
282
+ continue;
283
+ if (s.kind === "observation")
284
+ continue;
285
+ const url = str(s.url);
286
+ if (!/^https?:\/\//i.test(url)) {
287
+ add("source-digest", `sources[${i}]`, `source ${s.id} has no address to fetch, so its digest cannot be checked here`, "warn");
288
+ continue;
289
+ }
290
+ let bytes;
291
+ try {
292
+ const res = await f(url, { headers: { accept: "application/json" }, redirect: "follow", signal: AbortSignal.timeout(15000) });
293
+ if (!res.ok)
294
+ throw new ReadError(`it answered ${res.status}`);
295
+ bytes = new Uint8Array(await res.arrayBuffer());
296
+ }
297
+ catch (e) {
298
+ add("source-digest", `sources[${i}]`, `source ${s.id} at ${url} cannot be fetched: ${e.message}`);
299
+ continue;
300
+ }
301
+ let value;
302
+ try {
303
+ value = parseBytes(bytes, url);
304
+ }
305
+ catch {
306
+ value = undefined;
307
+ }
308
+ if (typeof s.digest === "string") {
309
+ // A digest is over the exact bytes; one over the canonical JSON is accepted too, which is how a document handed in parsed, or committed by Agent SoW's terms extension, is digested.
310
+ const exact = sha256Digest(bytes) === s.digest;
311
+ let canonical = false;
312
+ try {
313
+ canonical = value !== undefined && sha256Digest(canonicalJSON(value)) === s.digest;
314
+ }
315
+ catch {
316
+ canonical = false;
317
+ }
318
+ if (!exact && !canonical)
319
+ add("source-digest", `sources[${i}].digest`, `source ${s.id} at ${url} no longer matches its digest: it has changed since ${str(s.fetched_at) || "it was fetched"}, so assemble again`);
320
+ }
321
+ if (value !== undefined)
322
+ fetched.set(s.id, scalarsOf(value, new Set()));
323
+ }
324
+ const ids = new Set(sources.filter(isObj).map((s) => s.id));
325
+ const sections = isObj(doc.sections) ? doc.sections : {};
326
+ for (const [name, s] of Object.entries(sections)) {
327
+ if (!isObj(s))
328
+ continue;
329
+ const cited = arr(s.from).filter((x) => typeof x === "string" && ids.has(x));
330
+ const known = cited.filter((id) => fetched.has(id));
331
+ if (!known.length) {
332
+ if (cited.length)
333
+ add("fact-in-source", `sections.${name}`, `none of the sources the ${name} section cites could be read, so its facts were not checked`, "warn");
334
+ continue;
335
+ }
336
+ const pool = new Set();
337
+ for (const id of known)
338
+ for (const x of fetched.get(id))
339
+ pool.add(x);
340
+ const partial = known.length < cited.length;
341
+ const { from: _f, ...rest } = s;
342
+ for (const [path, fact] of factsOf(rest, `sections.${name}`, [])) {
343
+ if (pool.has(fact))
344
+ continue;
345
+ if (typeof fact === "string" && [...pool].some((x) => x.length > fact.length && x.includes(fact)))
346
+ continue;
347
+ add("fact-in-source", path, `${JSON.stringify(fact.length > 80 ? `${fact.slice(0, 77)}...` : fact)} is not in any source the ${name} section cites`, partial ? "warn" : "fail");
348
+ }
349
+ }
350
+ return findings;
351
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export declare const USAGE = "common-agent-doc 0.1.0: make, publish and check an AgentDoc.\n\nAn AgentDoc is one document that says what an agent is, what it offers and\nwhat it refuses, built only from what the agent itself publishes. Every line\nsays where it came from, and anything the agent has not said is listed as\nnot stated. See https://agentdoc.net\n\nCommands:\n build <address | card file> write the AgentDoc and its page\n check <file | url> check an AgentDoc against Section 9.10\n init <address | card file> draft a Descriptor from the agent's card\n keygen make the agent's signing key\n sign <descriptor file> sign the Descriptor with that key\n\nRun common-agent-doc <command> --help for the details of one command.";
2
+ /** Where the tool writes, what time it is, and how it fetches: the process's own, unless a test passes others. */
3
+ export interface Io {
4
+ out(line: string): void;
5
+ err(line: string): void;
6
+ now(): Date;
7
+ fetch?: typeof fetch;
8
+ cwd?: string;
9
+ }
10
+ /** Run the tool on its arguments (without the program name), and answer the exit code. */
11
+ export declare function main(argv: string[], io?: Io): Promise<number>;