feat(api): installable accounted-api agent skill + openapi-to-skill generator (#1516)

* feat(api): installable accounted-api agent skill + openapi-to-skill generator

Three layers, per the July/August 2026 agent-skills ecosystem (skills.sh /
npx skills add, as used by Stripe/Cloudflare/Supabase for their APIs):

- skills/openapi-to-skill/: generic, installable skill that turns any
  OpenAPI spec into a consumer-side integration skill, with a portable
  stdlib-only inventory/condenser tool and an output template + quality
  checklist encoding the distill-not-restate methodology.
- skills/accounted-api/: the installable skill for our own API, rendered
  deterministically by scripts/api-skill/generate.ts from the v1 endpoint
  registry + hand-authored overlays (auth, conventions, domain gotchas).
  CI gate: npm run apiskill:check (core-build.yml).
- lib/api/v1/registry.ts: generateOpenApiSpec now emits requestBody (incl.
  multipart binary parts) and path parameters, and the Zod converter learned
  .default()/z.record()/.pipe()/.transform(), so the public spec carries
  request contracts instead of prose-only.

Docs: /docs/api landing + /llms.txt now point agents at the skill install;
corrected the stale test-key description in the landing (test keys read
real data and force dry-run writes; they are not sandbox-company bound).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(skills): escape backslashes in markdown table cells (CodeQL js/incomplete-sanitization)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-11 12:45:19 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 7a49aec0c3
commit 11b82cbb91
31 changed files with 7751 additions and 3 deletions
@@ -0,0 +1,77 @@
/**
* The OpenAPI generator emits machine-readable request contracts:
* path `parameters` derived from the route pattern and `requestBody` from
* the registered Zod body schema. Historically the spec only carried
* response schemas + prose, which forced spec consumers (agent skills,
* client generators) to guess request shapes.
*/
import { describe, expect, it } from 'vitest'
import { generateOpenApiSpec } from '../registry'
// Side-effect import: populates the ENDPOINTS registry from every route file.
import '../load-routes'
type OperationObject = {
parameters?: Array<{ name: string; in: string; required: boolean; schema: unknown }>
requestBody?: {
required: boolean
content: Record<string, { schema: { properties?: Record<string, unknown>; required?: string[] } }>
}
}
const spec = generateOpenApiSpec('https://unit.test')
function operation(path: string, method: string): OperationObject {
const op = (spec.paths[path] as Record<string, OperationObject> | undefined)?.[method]
expect(op, `${method.toUpperCase()} ${path} missing from spec`).toBeDefined()
return op as OperationObject
}
describe('generateOpenApiSpec request contracts', () => {
it('declares a path parameter for every templated segment, on every operation', () => {
for (const [path, item] of Object.entries(spec.paths)) {
const templated = [...path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1])
for (const [method, op] of Object.entries(item as Record<string, OperationObject>)) {
const declared = (op.parameters ?? []).filter((p) => p.in === 'path').map((p) => p.name)
expect(declared.sort(), `${method.toUpperCase()} ${path}`).toEqual([...templated].sort())
}
}
})
it('emits requestBody from the registered Zod body schema', () => {
const op = operation('/api/v1/companies/{companyId}/invoices', 'post')
expect(op.requestBody?.required).toBe(true)
const schema = op.requestBody?.content['application/json']?.schema
expect(schema?.properties).toHaveProperty('customer_id')
expect(schema?.properties).toHaveProperty('items')
expect(schema?.required).toContain('customer_id')
})
it('renders multipart z.unknown() parts as binary file parts', () => {
const op = operation('/api/v1/companies/{companyId}/documents', 'post')
const schema = op.requestBody?.content['multipart/form-data']?.schema
expect(schema?.properties?.file).toEqual({ type: 'string', format: 'binary' })
// Non-file parts keep their real schema.
expect(schema?.properties?.journal_entry_id).toMatchObject({ type: 'string' })
})
it('omits requestBody on endpoints without a registered body', () => {
expect(operation('/api/v1/companies', 'get').requestBody).toBeUndefined()
})
it('converts wrapped Zod constructs (.default, z.record) instead of degrading to {}', () => {
const op = operation('/api/v1/companies/{companyId}/journal-entries', 'post')
const schema = op.requestBody?.content['application/json']?.schema as {
properties: Record<string, { type?: string; enum?: unknown[]; items?: { properties: Record<string, { type?: string; additionalProperties?: unknown }> } }>
required?: string[]
}
// JournalEntrySourceTypeSchema.default('manual'): enum survives, field not required.
expect(schema.properties.source_type.enum).toContain('manual')
expect(schema.required).not.toContain('source_type')
const line = schema.properties.lines.items!.properties
// nonNegativeAmount.default(0) is a number, and z.record renders as an
// object with additionalProperties rather than an empty schema.
expect(line.debit_amount.type).toBe('number')
expect(line.dimensions.additionalProperties).toBeTruthy()
})
})
+68 -2
View File
@@ -275,10 +275,34 @@ function zodToJsonSchema(schema: ZodTypeAny): JsonSchema {
case 'optional':
case 'ZodOptional':
case 'nullable':
case 'ZodNullable': {
case 'ZodNullable':
// A `.default()` field accepts the inner type on input; the object case
// below additionally treats it as not-required.
case 'default':
case 'ZodDefault': {
const inner = (def as { innerType: ZodTypeAny }).innerType
return zodToJsonSchema(inner)
}
case 'record':
case 'ZodRecord': {
const valueType = (def as { valueType?: ZodTypeAny }).valueType
return {
type: 'object',
additionalProperties: valueType ? zodToJsonSchema(valueType) : true,
}
}
// `.transform()` / `.pipe()` wrappers: describe the INPUT side, which is
// what an API caller must send.
case 'pipe':
case 'ZodPipeline': {
const input = (def as { in?: ZodTypeAny }).in
return input ? zodToJsonSchema(input) : {}
}
case 'effects':
case 'ZodEffects': {
const inner = (def as { schema?: ZodTypeAny }).schema
return inner ? zodToJsonSchema(inner) : {}
}
case 'object':
case 'ZodObject': {
const shape = (schema as unknown as { shape: Record<string, ZodTypeAny> }).shape
@@ -288,7 +312,9 @@ function zodToJsonSchema(schema: ZodTypeAny): JsonSchema {
properties[key] = zodToJsonSchema(value)
const valueDef = (value as unknown as { _def: { typeName?: string; type?: string } })._def
const valueDisc = valueDef.type ?? valueDef.typeName ?? ''
if (valueDisc !== 'optional' && valueDisc !== 'ZodOptional') {
// Optional and defaulted fields may be omitted by the caller.
const mayOmit = ['optional', 'ZodOptional', 'default', 'ZodDefault'].includes(valueDisc)
if (!mayOmit) {
required.push(key)
}
}
@@ -362,6 +388,44 @@ export function generateOpenApiSpec(serverUrl: string): OpenApiSpec {
? { '204': { description: 'No Content' } }
: { '200': { description: 'Success', content: successContent } }
// Path parameters, derived from the `:param` pattern itself so every
// templated segment is declared even though routes don't register a
// params schema. All v1 path params are string ids.
const parameters = [...def.path.matchAll(/:([^/]+)/g)].map(([, name]) => ({
name,
in: 'path',
required: true,
schema: { type: 'string' },
}))
// Request body from the registered Zod schema. In multipart bodies a
// part registered as `z.unknown()` is by convention the binary file part
// (see documents.upload); the converter turns it into an empty schema,
// which is rewritten here to `format: binary` so client generators
// produce correct multipart uploads.
let requestBody: Record<string, unknown> | undefined
if (def.request?.body) {
const contentType = def.request.contentType ?? 'application/json'
let bodySchema = zodToJsonSchema(def.request.body)
if (contentType === 'multipart/form-data' && bodySchema.properties) {
bodySchema = {
...bodySchema,
properties: Object.fromEntries(
Object.entries(bodySchema.properties).map(([key, prop]) => [
key,
Object.keys(prop).length === 0
? { type: 'string', format: 'binary' }
: prop,
]),
),
}
}
requestBody = {
required: true,
content: { [contentType]: { schema: bodySchema } },
}
}
const operationDef: Record<string, unknown> = {
operationId: def.operation,
summary: def.summary,
@@ -377,6 +441,8 @@ export function generateOpenApiSpec(serverUrl: string): OpenApiSpec {
'x-reversible': def.reversible,
'x-dry-run-supported': def.dryRunSupported,
...(def.scope ? { 'x-required-scope': def.scope } : {}),
...(parameters.length > 0 ? { parameters } : {}),
...(requestBody ? { requestBody } : {}),
responses: {
...successResponse,
'400': { description: 'Validation error', $ref: '#/components/responses/Error' },