docs: generate ACP reference documentation from release schemas (#11770)
This commit is contained in:
@@ -0,0 +1,293 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const ROOT = path.join(__dirname, '..', '..');
|
||||
const SCHEMA_FILE = path.join(ROOT, 'crates', 'goose', 'acp-schema.json');
|
||||
const META_FILE = path.join(ROOT, 'crates', 'goose', 'acp-meta.json');
|
||||
const OUTPUT_FILE = path.join(
|
||||
ROOT,
|
||||
'documentation',
|
||||
'docs',
|
||||
'reference',
|
||||
'goose-acp-reference.md'
|
||||
);
|
||||
const UNSUPPORTED_KEYWORDS = [
|
||||
'contains',
|
||||
'dependentSchemas',
|
||||
'else',
|
||||
'if',
|
||||
'not',
|
||||
'patternProperties',
|
||||
'prefixItems',
|
||||
'propertyNames',
|
||||
'then',
|
||||
'unevaluatedProperties',
|
||||
];
|
||||
|
||||
function escapeCode(value) {
|
||||
return String(value)
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('{', '{')
|
||||
.replaceAll('}', '}')
|
||||
.replaceAll('`', '`');
|
||||
}
|
||||
|
||||
function code(value) {
|
||||
return `<code>${escapeCode(value)}</code>`;
|
||||
}
|
||||
|
||||
function methodCode(value) {
|
||||
return `<code>${escapeCode(value).replaceAll('/', '/<wbr />')}</code>`;
|
||||
}
|
||||
|
||||
function schemaCode(value) {
|
||||
const escaped = escapeCode(value)
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1<wbr />$2')
|
||||
.replaceAll('_', '_<wbr />');
|
||||
return `<code>${escaped}</code>`;
|
||||
}
|
||||
|
||||
function text(value, fallback = '') {
|
||||
const result = String(value ?? '').trim();
|
||||
return result
|
||||
? result.replaceAll('|', '\\|').replaceAll('\r\n', '\n').replaceAll('\n', '<br />')
|
||||
: fallback;
|
||||
}
|
||||
|
||||
function literal(value) {
|
||||
return code(JSON.stringify(value));
|
||||
}
|
||||
|
||||
function refName(reference) {
|
||||
const prefix = '#/$defs/';
|
||||
if (typeof reference !== 'string' || !reference.startsWith(prefix)) {
|
||||
throw new Error(`Unsupported schema reference: ${JSON.stringify(reference)}`);
|
||||
}
|
||||
return reference.slice(prefix.length);
|
||||
}
|
||||
|
||||
function schemaId(name) {
|
||||
return `schema-${name.toLowerCase()}`;
|
||||
}
|
||||
|
||||
function schemaLink(name) {
|
||||
return `[${schemaCode(name)}](#${schemaId(name)})`;
|
||||
}
|
||||
|
||||
function schemaType(schema, inlineObject = false) {
|
||||
if (schema === true) return code('unknown');
|
||||
if (schema === false) return code('never');
|
||||
if (!schema || Array.isArray(schema) || typeof schema !== 'object') {
|
||||
throw new Error(`Unsupported schema: ${JSON.stringify(schema)}`);
|
||||
}
|
||||
|
||||
const unsupported = UNSUPPORTED_KEYWORDS.find((keyword) => keyword in schema);
|
||||
if (unsupported) throw new Error(`Unsupported schema keyword: ${unsupported}`);
|
||||
|
||||
if (schema.$ref) {
|
||||
const structuralSiblings = Object.fromEntries(
|
||||
Object.entries(schema).filter(
|
||||
([key]) =>
|
||||
![
|
||||
'$ref',
|
||||
'default',
|
||||
'description',
|
||||
'format',
|
||||
'maximum',
|
||||
'minimum',
|
||||
'pattern',
|
||||
'title',
|
||||
].includes(key) && !key.startsWith('x-')
|
||||
)
|
||||
);
|
||||
const reference = schemaLink(refName(schema.$ref));
|
||||
return Object.keys(structuralSiblings).length === 0
|
||||
? reference
|
||||
: `${reference} & ${schemaType(structuralSiblings, true)}`;
|
||||
}
|
||||
if (Object.hasOwn(schema, 'const')) return literal(schema.const);
|
||||
if (schema.enum) return schema.enum.map(literal).join(' \\| ');
|
||||
|
||||
for (const keyword of ['anyOf', 'oneOf', 'allOf']) {
|
||||
if (schema[keyword]) {
|
||||
if (!Array.isArray(schema[keyword]) || schema[keyword].length === 0) {
|
||||
throw new Error(`Invalid ${keyword} schema`);
|
||||
}
|
||||
const separator = keyword === 'allOf' ? ' & ' : ' \\| ';
|
||||
return schema[keyword].map((part) => schemaType(part, true)).join(separator);
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(schema.type)) {
|
||||
return schema.type
|
||||
.map((type) => schemaType({...schema, type}, inlineObject))
|
||||
.join(' \\| ');
|
||||
}
|
||||
|
||||
if (schema.type === 'array') {
|
||||
if (!Object.hasOwn(schema, 'items')) throw new Error('Array schema is missing items');
|
||||
return `Array<${schemaType(schema.items, true)}>`;
|
||||
}
|
||||
|
||||
if (
|
||||
schema.type === 'object' ||
|
||||
(!schema.type && (schema.properties || Object.hasOwn(schema, 'additionalProperties')))
|
||||
) {
|
||||
if (schema.properties && inlineObject) {
|
||||
const required = new Set(schema.required ?? []);
|
||||
const fields = Object.entries(schema.properties).map(
|
||||
([name, property]) =>
|
||||
`${code(name)}${required.has(name) ? '' : '?'}: ${schemaType(property, true)}`
|
||||
);
|
||||
return `{ ${fields.join('; ')} }`;
|
||||
}
|
||||
if (Object.hasOwn(schema, 'additionalProperties') && !schema.properties) {
|
||||
return `Record<${code('string')}, ${schemaType(schema.additionalProperties, true)}>`;
|
||||
}
|
||||
return code('object');
|
||||
}
|
||||
|
||||
if (typeof schema.type === 'string') return code(schema.type);
|
||||
if (
|
||||
Object.keys(schema).every(
|
||||
(key) =>
|
||||
key === 'default' || key === 'description' || key === 'title' || key.startsWith('x-')
|
||||
)
|
||||
) {
|
||||
return code('unknown');
|
||||
}
|
||||
throw new Error(`Unsupported schema shape: ${JSON.stringify(schema)}`);
|
||||
}
|
||||
|
||||
function constraints(schema) {
|
||||
const values = [];
|
||||
if (Object.hasOwn(schema, 'default')) values.push(`Default: ${literal(schema.default)}`);
|
||||
if (schema.format !== undefined) values.push(`Format: ${code(schema.format)}`);
|
||||
if (schema.minimum !== undefined) values.push(`Minimum: ${code(schema.minimum)}`);
|
||||
if (schema.maximum !== undefined) values.push(`Maximum: ${code(schema.maximum)}`);
|
||||
if (schema.pattern !== undefined) values.push(`Pattern: ${code(schema.pattern)}`);
|
||||
return values.join('<br />');
|
||||
}
|
||||
|
||||
function renderProperties(schema) {
|
||||
const properties = Object.entries(schema.properties ?? {});
|
||||
if (properties.length === 0) return '';
|
||||
|
||||
const required = new Set(schema.required ?? []);
|
||||
const rows = properties.map(([name, property]) =>
|
||||
`| ${code(name)} | ${schemaType(property)} | ${required.has(name) ? 'Yes' : 'No'} | ${text(property.description, '—')} | ${constraints(property) || '—'} |`
|
||||
);
|
||||
return [
|
||||
'| Field | Type | Required | Description | Constraints |',
|
||||
'|---|---|:---:|---|---|',
|
||||
...rows,
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function renderMethods(entries, schemas, notification = false) {
|
||||
if (entries.length === 0) return '_None._\n';
|
||||
|
||||
const rows = [...entries]
|
||||
.sort((left, right) => left.method.localeCompare(right.method))
|
||||
.map((entry) => {
|
||||
const inputType = notification ? entry.paramsType : entry.requestType;
|
||||
const inputSchema = schemas.$defs[inputType];
|
||||
if (!inputSchema) {
|
||||
throw new Error(`${entry.method} references missing type ${inputType}`);
|
||||
}
|
||||
if (!notification && !schemas.$defs[entry.responseType]) {
|
||||
throw new Error(`${entry.method} references missing type ${entry.responseType}`);
|
||||
}
|
||||
const links = notification
|
||||
? `**Parameters:** ${schemaLink(inputType)}`
|
||||
: `**Request:** ${schemaLink(inputType)}<br />**Response:** ${schemaLink(entry.responseType)}`;
|
||||
const description = text(inputSchema.description);
|
||||
const method = description
|
||||
? `${methodCode(entry.method)}<br />${description}`
|
||||
: methodCode(entry.method);
|
||||
return `| ${method} | ${links} |`;
|
||||
});
|
||||
|
||||
return ['| Method | Schemas |', '|---|---|', ...rows, ''].join('\n');
|
||||
}
|
||||
|
||||
function renderSchema(name, schema) {
|
||||
const lines = [`### ${code(name)} {#${schemaId(name)}}`, ''];
|
||||
if (schema.description) lines.push(text(schema.description), '');
|
||||
lines.push(`**Type:** ${schemaType(schema)}`, '');
|
||||
|
||||
const schemaConstraints = constraints(schema);
|
||||
if (schemaConstraints) lines.push(`**Constraints:** ${schemaConstraints}`, '');
|
||||
|
||||
const properties = renderProperties(schema);
|
||||
if (properties) lines.push(properties);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function renderDocumentation(schemas, meta, gooseVersion = 'Preview') {
|
||||
if (!schemas.$defs || typeof schemas.$defs !== 'object') {
|
||||
throw new Error('Schema document is missing $defs');
|
||||
}
|
||||
|
||||
const definitions = Object.entries(schemas.$defs)
|
||||
.filter(([, schema]) => !schema['x-docs-ignore'])
|
||||
.sort(([left], [right]) => left.localeCompare(right));
|
||||
|
||||
const output = [
|
||||
'---',
|
||||
'title: goose ACP Reference',
|
||||
'sidebar_label: goose ACP Reference',
|
||||
'---',
|
||||
'',
|
||||
'# goose ACP Reference',
|
||||
'',
|
||||
'This reference documents goose-specific Agent Client Protocol methods. Standard ACP methods are documented by the [Agent Client Protocol specification](https://agentclientprotocol.com/).',
|
||||
'',
|
||||
`**goose version:** ${code(gooseVersion)}`,
|
||||
'',
|
||||
'> This file is generated from `crates/goose/acp-schema.json` and `crates/goose/acp-meta.json`. Do not edit it manually.',
|
||||
'',
|
||||
'## Client-to-agent requests',
|
||||
'',
|
||||
renderMethods(meta.methods ?? [], schemas),
|
||||
'## Agent-to-client requests',
|
||||
'',
|
||||
renderMethods(meta.agentRequests ?? [], schemas),
|
||||
'## Agent-to-client notifications',
|
||||
'',
|
||||
renderMethods(meta.notifications ?? [], schemas, true),
|
||||
'## Schemas',
|
||||
'',
|
||||
...definitions.map(([name, schema]) => renderSchema(name, schema)),
|
||||
];
|
||||
return `${output.join('\n').trimEnd()}\n`;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const args = process.argv.slice(2);
|
||||
if (args.length !== 0 && args.length !== 3 && args.length !== 4) {
|
||||
throw new Error(
|
||||
'Usage: generate-acp-docs.js [schema-file meta-file output-file [goose-version]]'
|
||||
);
|
||||
}
|
||||
|
||||
const [
|
||||
schemaFile = SCHEMA_FILE,
|
||||
metaFile = META_FILE,
|
||||
outputFile = OUTPUT_FILE,
|
||||
gooseVersion = 'Preview',
|
||||
] = args;
|
||||
const schemas = JSON.parse(fs.readFileSync(schemaFile, 'utf8'));
|
||||
const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8'));
|
||||
const output = renderDocumentation(schemas, meta, gooseVersion);
|
||||
fs.mkdirSync(path.dirname(outputFile), {recursive: true});
|
||||
fs.writeFileSync(outputFile, output);
|
||||
console.log(`[generate-acp-docs] Generated: ${outputFile}`);
|
||||
}
|
||||
|
||||
if (require.main === module) main();
|
||||
|
||||
module.exports = {renderDocumentation, schemaType};
|
||||
@@ -0,0 +1,53 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const test = require('node:test');
|
||||
|
||||
const {renderDocumentation, schemaType} = require('./generate-acp-docs');
|
||||
|
||||
const schema = {
|
||||
$defs: {
|
||||
Request: {
|
||||
type: 'object',
|
||||
description: 'Run the example.',
|
||||
properties: {
|
||||
target: {$ref: '#/$defs/Target'},
|
||||
tags: {type: ['array', 'null'], items: {type: 'string'}},
|
||||
values: {type: 'object', additionalProperties: {type: 'integer'}},
|
||||
mode: {enum: ['fast', 'safe'], default: 'safe'},
|
||||
count: {type: 'integer', minimum: 1, maximum: 10},
|
||||
label: {type: 'string', format: 'slug', pattern: '^[a-z]+$'},
|
||||
},
|
||||
required: ['target'],
|
||||
},
|
||||
Response: {type: 'object'},
|
||||
Target: {
|
||||
oneOf: [
|
||||
{$ref: '#/$defs/Response', type: 'object', properties: {kind: {const: 'object'}}},
|
||||
{type: 'string'},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
const meta = {
|
||||
methods: [{method: '_goose/example', requestType: 'Request', responseType: 'Response'}],
|
||||
agentRequests: [],
|
||||
notifications: [],
|
||||
};
|
||||
|
||||
test('renders representative schema forms deterministically', () => {
|
||||
const output = renderDocumentation(schema, meta, 'v1.2.3');
|
||||
|
||||
assert.equal(output, renderDocumentation(schema, meta, 'v1.2.3'));
|
||||
assert.match(output, /\*\*goose version:\*\* <code>v1\.2\.3<\/code>/);
|
||||
assert.match(output, /\[<code>Target<\/code>\]\(#schema-target\)/);
|
||||
assert.match(output, /### <code>Target<\/code> \{#schema-target\}/);
|
||||
assert.match(output, /\[<code>Response<\/code>\]\(#schema-response\) & .*<code>kind<\/code>/);
|
||||
assert.match(output, /Array<<code>string<\/code>> \\| <code>null<\/code>/);
|
||||
assert.match(output, /Record<<code>string<\/code>, <code>integer<\/code>>/);
|
||||
assert.match(output, /Default: <code>"safe"<\/code>/);
|
||||
assert.match(output, /Minimum: <code>1<\/code><br \/>Maximum: <code>10<\/code>/);
|
||||
assert.match(output, /Format: <code>slug<\/code><br \/>Pattern: <code>\^\[a-z\]\+\$<\/code>/);
|
||||
});
|
||||
|
||||
test('rejects unsupported schema shapes', () => {
|
||||
assert.throws(() => schemaType({not: {type: 'string'}}), /Unsupported schema keyword: not/);
|
||||
});
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")/../.."
|
||||
|
||||
acp_ref=$(gh api 'repos/{owner}/{repo}/releases/latest' --jq '.tag_name')
|
||||
echo "Using goose release $acp_ref for ACP documentation."
|
||||
|
||||
if ! git rev-parse --verify --quiet "refs/tags/$acp_ref" >/dev/null; then
|
||||
echo "Release tag $acp_ref is not available locally. Run 'git fetch --tags'." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
temp_dir=$(mktemp -d)
|
||||
trap 'rm -rf "$temp_dir"' EXIT
|
||||
|
||||
schema="$temp_dir/acp-schema.json"
|
||||
meta="$temp_dir/acp-meta.json"
|
||||
|
||||
git show "$acp_ref:crates/goose/acp-schema.json" > "$schema"
|
||||
git show "$acp_ref:crates/goose/acp-meta.json" > "$meta"
|
||||
node documentation/scripts/generate-acp-docs.js "$schema" "$meta" \
|
||||
documentation/docs/reference/goose-acp-reference.md "$acp_ref"
|
||||
Reference in New Issue
Block a user