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 <[email protected]> * fix(skills): escape backslashes in markdown table cells (CodeQL js/incomplete-sanitization) Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Jakob Wennberg <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5
Jakob Wennberg
parent
7a49aec0c3
commit
11b82cbb91
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: openapi-to-skill
|
||||
description: >-
|
||||
Turn an OpenAPI/Swagger spec (JSON or YAML, file or URL) into an installable
|
||||
agent skill for consuming that API. Use when the user invokes
|
||||
/openapi-to-skill, points at an openapi.json or swagger.yaml, or asks to
|
||||
"build a skill for this API" or "make these API docs agent-ready".
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
This is a local pointer so the skill is invocable inside this repo. The
|
||||
canonical skill (kept installable for external consumers via
|
||||
`npx skills add erp-mafia/accounted --skill openapi-to-skill`) lives at:
|
||||
|
||||
**`skills/openapi-to-skill/SKILL.md`** (repo root)
|
||||
|
||||
Read that file and follow it. Its bundled tool is at
|
||||
`skills/openapi-to-skill/scripts/openapi-inventory.mjs` and the output
|
||||
template at `skills/openapi-to-skill/references/output-template.md`.
|
||||
@@ -44,6 +44,13 @@ jobs:
|
||||
# so drift here means filings tagged against a stale concept set.
|
||||
run: npm run taxonomy:check
|
||||
|
||||
- name: Verify the accounted-api agent skill is in sync with the registry
|
||||
# Fails if a v1 endpoint / registry schema / overlay changed without
|
||||
# regenerating skills/accounted-api (npm run apiskill:generate). The
|
||||
# skill is the installable API reference for external coding agents;
|
||||
# drift here means agents integrate against stale endpoint contracts.
|
||||
run: npm run apiskill:check
|
||||
|
||||
- name: Lint ratchet (no new ESLint errors)
|
||||
# `npm run lint` was never wired into CI, so ~60 legacy errors
|
||||
# accumulated. This ratchet (sibling of check:guards) fails only when
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -50,6 +50,7 @@ declarations, ingest SIE files, and subscribe to webhooks for state changes.
|
||||
|
||||
## Resources
|
||||
|
||||
- Agent skill (full API surface for coding agents): \`npx skills add erp-mafia/accounted --skill accounted-api\`
|
||||
- OpenAPI 3.1 spec: ${base}/api/v1/openapi.json
|
||||
- Skills catalogue: ${base}/.well-known/skills/index.json
|
||||
- Health check: ${base}/api/v1/health
|
||||
|
||||
@@ -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
@@ -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' },
|
||||
|
||||
@@ -20,7 +20,7 @@ curl https://app.gnubok.se/api/v1/companies \\
|
||||
Create keys in the accounted dashboard at **/settings/api**. Two key prefixes are available:
|
||||
|
||||
- \`gnubok_sk_live_*\`: hits real customer data. Use in production.
|
||||
- \`gnubok_sk_test_*\`: bound to deterministic sandbox companies. Safe for evals, demos, and agent learning. Same surface, different blast radius.
|
||||
- \`gnubok_sk_test_*\`: reads real company data, but every write is forced into dry-run and nothing persists (responses carry \`X-Gnubok-Mode: test\`). Safe for evals, demos, and agent learning. Same surface, different blast radius.
|
||||
|
||||
Each key carries one or more **scopes** (\`invoices:read\`, \`invoices:write\`, \`payroll:write\`, \`webhooks:manage\`, ...) that gate which endpoints it can call. Scopes are listed on every endpoint reference page.
|
||||
|
||||
@@ -102,6 +102,7 @@ Every error code is documented in the [error reference](/docs/api/errors).
|
||||
- **[Changelog](/docs/api/changelog)**: what shipped when.
|
||||
|
||||
For LLM-based agents:
|
||||
- **Agent skill for integrators**: \`npx skills add erp-mafia/accounted --skill accounted-api\` teaches your coding agent (Claude Code, Cursor, Codex, ...) this entire API: auth, conventions, and every endpoint with request/response schemas. Generated from the same registry that serves this spec, so it cannot drift.
|
||||
- **[\`/llms.txt\`](/llms.txt)**: concise agent-discovery index.
|
||||
- **[\`/llms-full.txt\`](/llms-full.txt)**: full docs concatenated for ingestion.
|
||||
- **[\`/api/v1/openapi.json\`](/api/v1/openapi.json)**: machine-readable OpenAPI 3.1 spec.
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
"setup:extensions": "npx tsx scripts/generate-extension-registry.ts",
|
||||
"skills:generate": "npx tsx scripts/generate-skill-bodies.ts",
|
||||
"skills:check": "npx tsx scripts/generate-skill-bodies.ts --check",
|
||||
"apiskill:generate": "npx tsx --conditions react-server scripts/api-skill/generate.ts",
|
||||
"apiskill:check": "npx tsx --conditions react-server scripts/api-skill/generate.ts --check",
|
||||
"crontabs:generate": "npx tsx scripts/generate-crontabs.ts",
|
||||
"taxonomy:generate": "npx tsx scripts/generate-taxonomy-registry.ts",
|
||||
"taxonomy:check": "npx tsx scripts/generate-taxonomy-registry.ts --check",
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
/**
|
||||
* Deterministic generator for the installable `accounted-api` agent skill
|
||||
* (skills/accounted-api/), the consumer-side skill that teaches coding
|
||||
* agents to build against the v1 REST API.
|
||||
*
|
||||
* Renders straight from the same endpoint registry that serves the API and
|
||||
* its OpenAPI spec, so the skill cannot drift from the server. Hand-authored
|
||||
* knowledge (auth, conventions, domain gotchas) lives in
|
||||
* scripts/api-skill/overlays/*.md and is stitched in verbatim.
|
||||
*
|
||||
* Run with the react-server condition so the `server-only` guards in the
|
||||
* route import chain resolve (see package.json):
|
||||
*
|
||||
* npm run apiskill:generate # write skills/accounted-api/
|
||||
* npm run apiskill:check # CI staleness gate (no writes)
|
||||
*
|
||||
* The per-operation rendering is done by the portable inventory tool that
|
||||
* ships inside the sibling `openapi-to-skill` skill: the generic tool has to
|
||||
* be good enough to build our own skill, or it is not good enough to ship.
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, existsSync } from 'node:fs'
|
||||
import { join, dirname } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import '@/lib/api/v1/load-routes'
|
||||
import { generateOpenApiSpec } from '@/lib/api/v1/registry'
|
||||
import { API_V1_VERSION } from '@/lib/api/v1/version'
|
||||
|
||||
import {
|
||||
listOperations,
|
||||
formatOpLine,
|
||||
renderOperationMd,
|
||||
type OperationEntry,
|
||||
} from '../../skills/openapi-to-skill/scripts/openapi-inventory.mjs'
|
||||
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
|
||||
const OVERLAY_DIR = join(ROOT, 'scripts', 'api-skill', 'overlays')
|
||||
const OUT_DIR = join(ROOT, 'skills', 'accounted-api')
|
||||
|
||||
/** Base URL shown in examples: the permanent machine host (see lib/api/v1/base-url.ts). */
|
||||
const MACHINE_BASE = 'https://app.gnubok.se'
|
||||
|
||||
/**
|
||||
* Reference-file layout: every derived path group must be claimed by exactly
|
||||
* one file. A new v1 resource fails apiskill:check until it is mapped here,
|
||||
* which is the point: grouping is an editorial decision, not a default.
|
||||
*/
|
||||
const GROUPS: Array<{ file: string; title: string; members: string[]; blurb: string }> = [
|
||||
{
|
||||
file: 'core.md',
|
||||
title: 'Core',
|
||||
members: ['health', 'companies', 'operations', 'settings'],
|
||||
blurb:
|
||||
'Connectivity, company discovery, async-operation polling, and company settings. ' +
|
||||
'Every session starts with GET /companies to resolve the companyId that all other URLs need.',
|
||||
},
|
||||
{
|
||||
file: 'journal-entries.md',
|
||||
title: 'Journal entries',
|
||||
members: ['journal-entries', 'voucher-gap-explanations'],
|
||||
blurb:
|
||||
'The ledger itself: journal entries follow draft -> commit -> immutable. There is no ' +
|
||||
'edit or delete after commit; undo via reverse (storno) or correct. Voucher numbers are ' +
|
||||
'server-assigned and gapless; explain unavoidable gaps via voucher-gap-explanations.',
|
||||
},
|
||||
{
|
||||
file: 'periods.md',
|
||||
title: 'Periods and registers',
|
||||
members: ['fiscal-periods', 'accounts', 'compliance', 'dimensions'],
|
||||
blurb:
|
||||
'Fiscal periods and their lock/close/year-end lifecycle (async operations), the BAS ' +
|
||||
'chart of accounts, cost-center/project dimensions, and the compliance pre-flight check.',
|
||||
},
|
||||
{
|
||||
file: 'invoices.md',
|
||||
title: 'Invoices (AR)',
|
||||
members: ['invoices'],
|
||||
blurb:
|
||||
'Accounts receivable invoices: draft -> send -> paid/credited; the F-series number is ' +
|
||||
'assigned at send, not create. Supplier bills you receive are a different resource: see ' +
|
||||
'suppliers.md. Customer and article registers: customers.md.',
|
||||
},
|
||||
{
|
||||
file: 'customers.md',
|
||||
title: 'Customers and articles',
|
||||
members: ['customers', 'articles'],
|
||||
blurb:
|
||||
'The customer register (bulk-create supported, archive via DELETE) and the read-only ' +
|
||||
'article register used for invoice line linkage.',
|
||||
},
|
||||
{
|
||||
file: 'suppliers.md',
|
||||
title: 'Suppliers (AP)',
|
||||
members: ['suppliers', 'supplier-invoices'],
|
||||
blurb:
|
||||
'Accounts payable: supplier register and received supplier invoices ' +
|
||||
'(register -> approve -> mark-paid, or credit).',
|
||||
},
|
||||
{
|
||||
file: 'documents.md',
|
||||
title: 'Documents',
|
||||
members: ['documents', 'inbox-items'],
|
||||
blurb:
|
||||
'The WORM document archive (7-year legal retention: uploads are permanent) and inbox-item stamping. ' +
|
||||
'Link every uploaded receipt/invoice document to its journal entry.',
|
||||
},
|
||||
{
|
||||
file: 'banking.md',
|
||||
title: 'Banking',
|
||||
members: ['transactions', 'reconciliation', 'imports'],
|
||||
blurb:
|
||||
'Bank transactions (ingest, categorize, match against invoices), bank reconciliation runs, ' +
|
||||
'and file imports (SIE, bank statements).',
|
||||
},
|
||||
{
|
||||
file: 'employees.md',
|
||||
title: 'Employees',
|
||||
members: ['employees', 'salary'],
|
||||
blurb:
|
||||
'The employee register plus absence (frånvaro), vacation balances and year close, and ' +
|
||||
'payroll cutover opening balances. Running payroll itself: salary-runs.md.',
|
||||
},
|
||||
{
|
||||
file: 'salary-runs.md',
|
||||
title: 'Salary runs',
|
||||
members: ['salary-runs'],
|
||||
blurb:
|
||||
'Swedish payroll runs: create -> calculate -> approve -> book/mark-paid -> generate-agi ' +
|
||||
'(arbetsgivardeklaration), with per-employee payslips and draft-only line edits.',
|
||||
},
|
||||
{
|
||||
file: 'reports.md',
|
||||
title: 'Reports',
|
||||
members: ['reports'],
|
||||
blurb:
|
||||
'Read-only statutory and management reports: trial balance, balance sheet, income statement, ' +
|
||||
'general ledger, VAT declaration, AR/AP ledgers, salary journal, and SIE export.',
|
||||
},
|
||||
{
|
||||
file: 'webhooks.md',
|
||||
title: 'Webhooks',
|
||||
members: ['webhooks', 'webhook-deliveries'],
|
||||
blurb:
|
||||
'HMAC-signed event subscriptions with delivery logs, test pings, retries, and secret rotation.',
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* The standard error line every operation shares; lifted into the
|
||||
* conventions overlay once instead of repeated 124 times. Operations with
|
||||
* additional codes keep their (then non-matching) line.
|
||||
*/
|
||||
const STANDARD_ERRORS_LINE =
|
||||
'Errors: `400` (Validation error), `401` (Unauthorized), `403` (Insufficient scope), ' +
|
||||
'`404` (Not found), `429` (Rate limited), `500` (Internal error)'
|
||||
|
||||
const GENERATED_NOTE =
|
||||
'<!-- GENERATED FILE, do not edit. Source: lib/api/v1 registry + scripts/api-skill/overlays. ' +
|
||||
'Regenerate with `npm run apiskill:generate`. -->'
|
||||
|
||||
function overlay(name: string): string {
|
||||
return readFileSync(join(OVERLAY_DIR, name), 'utf8').trim()
|
||||
}
|
||||
|
||||
function methodRank(method: string): number {
|
||||
return ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].indexOf(method)
|
||||
}
|
||||
|
||||
function buildFiles(): Map<string, string> {
|
||||
const spec = generateOpenApiSpec(MACHINE_BASE)
|
||||
const ops = listOperations(spec)
|
||||
|
||||
const memberToFile = new Map<string, (typeof GROUPS)[number]>()
|
||||
for (const group of GROUPS) {
|
||||
for (const member of group.members) {
|
||||
if (memberToFile.has(member)) throw new Error(`group member mapped twice: ${member}`)
|
||||
memberToFile.set(member, group)
|
||||
}
|
||||
}
|
||||
|
||||
const byFile = new Map<string, OperationEntry[]>()
|
||||
for (const entry of ops) {
|
||||
const group = memberToFile.get(entry.group)
|
||||
if (!group) {
|
||||
throw new Error(
|
||||
`Unmapped endpoint group "${entry.group}" (${entry.method} ${entry.path}). ` +
|
||||
'Add it to a reference file in scripts/api-skill/generate.ts GROUPS.',
|
||||
)
|
||||
}
|
||||
if (!byFile.has(group.file)) byFile.set(group.file, [])
|
||||
byFile.get(group.file)!.push(entry)
|
||||
}
|
||||
for (const list of byFile.values()) {
|
||||
list.sort((a, b) => a.path.localeCompare(b.path) || methodRank(a.method) - methodRank(b.method))
|
||||
}
|
||||
|
||||
const files = new Map<string, string>()
|
||||
|
||||
// Reference files.
|
||||
for (const group of GROUPS) {
|
||||
const members = byFile.get(group.file) ?? []
|
||||
if (members.length === 0) throw new Error(`reference file with no operations: ${group.file}`)
|
||||
const blocks = members.map((entry) =>
|
||||
renderOperationMd(spec, entry).replace(STANDARD_ERRORS_LINE, '').trimEnd(),
|
||||
)
|
||||
files.set(
|
||||
join('references', group.file),
|
||||
[
|
||||
GENERATED_NOTE,
|
||||
'',
|
||||
`# ${group.title} endpoints`,
|
||||
'',
|
||||
group.blurb,
|
||||
'',
|
||||
'Conventions (auth, envelope, pagination, dry-run, idempotency, standard errors)',
|
||||
'are in SKILL.md and are not repeated per endpoint.',
|
||||
'',
|
||||
blocks.join('\n\n---\n\n'),
|
||||
'',
|
||||
].join('\n'),
|
||||
)
|
||||
}
|
||||
|
||||
// SKILL.md: frontmatter + overlays + endpoint index.
|
||||
const indexSections = GROUPS.map((group) => {
|
||||
const members = byFile.get(group.file)!
|
||||
const lines = members.map((entry) =>
|
||||
formatOpLine(entry).replace(` ${entry.path} `, ` ${entry.path.replace('/api/v1', '')} `),
|
||||
)
|
||||
return [
|
||||
`### ${group.title} (${members.length})`,
|
||||
'',
|
||||
`Full detail: [references/${group.file}](references/${group.file})`,
|
||||
'',
|
||||
'```text',
|
||||
...lines,
|
||||
'```',
|
||||
].join('\n')
|
||||
})
|
||||
|
||||
const frontmatter = [
|
||||
'---',
|
||||
'name: accounted-api',
|
||||
'description: >-',
|
||||
' Consume the Accounted REST API (Swedish double-entry bookkeeping SaaS,',
|
||||
` ${MACHINE_BASE}/api/v1). Use when building an integration, app, backend`,
|
||||
' job, or agent tool layer against Accounted: invoices, customers,',
|
||||
' suppliers, supplier invoices, journal entries (bokföring), bank',
|
||||
' transactions and reconciliation, payroll (lön), VAT/moms and financial',
|
||||
' reports, SIE import/export, documents, webhooks. Covers auth with',
|
||||
` gnubok_sk_ API keys, conventions (dry-run, idempotency, cursor`,
|
||||
` pagination, scopes), and all ${ops.length} endpoints.`,
|
||||
'---',
|
||||
].join('\n')
|
||||
|
||||
files.set(
|
||||
'SKILL.md',
|
||||
[
|
||||
frontmatter,
|
||||
'',
|
||||
GENERATED_NOTE,
|
||||
'',
|
||||
overlay('intro.md'),
|
||||
'',
|
||||
overlay('quickstart.md'),
|
||||
'',
|
||||
overlay('conventions.md'),
|
||||
'',
|
||||
'## Endpoint index',
|
||||
'',
|
||||
`API version \`${API_V1_VERSION}\`, ${ops.length} operations. Paths are shown without`,
|
||||
`their \`/api/v1\` prefix (full base URL: \`${MACHINE_BASE}/api/v1\`).`,
|
||||
'',
|
||||
indexSections.join('\n\n'),
|
||||
'',
|
||||
overlay('gotchas.md'),
|
||||
'',
|
||||
overlay('verification.md'),
|
||||
'',
|
||||
].join('\n'),
|
||||
)
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
function listMarkdownFiles(dir: string, prefix = ''): string[] {
|
||||
if (!existsSync(dir)) return []
|
||||
const out: string[] = []
|
||||
for (const dirent of readdirSync(dir, { withFileTypes: true })) {
|
||||
const rel = prefix ? join(prefix, dirent.name) : dirent.name
|
||||
if (dirent.isDirectory()) out.push(...listMarkdownFiles(join(dir, dirent.name), rel))
|
||||
else if (dirent.name.endsWith('.md')) out.push(rel)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function main() {
|
||||
const check = process.argv.includes('--check')
|
||||
const files = buildFiles()
|
||||
|
||||
const existing = listMarkdownFiles(OUT_DIR)
|
||||
const orphans = existing.filter((rel) => !files.has(rel))
|
||||
|
||||
if (check) {
|
||||
const stale: string[] = []
|
||||
for (const [rel, content] of files) {
|
||||
const abs = join(OUT_DIR, rel)
|
||||
if (!existsSync(abs)) stale.push(`${rel} (missing)`)
|
||||
else if (readFileSync(abs, 'utf8') !== content) stale.push(`${rel} (outdated)`)
|
||||
}
|
||||
stale.push(...orphans.map((rel) => `${rel} (orphaned)`))
|
||||
if (stale.length > 0) {
|
||||
console.error('skills/accounted-api is stale relative to the endpoint registry/overlays:')
|
||||
for (const entry of stale) console.error(` - ${entry}`)
|
||||
console.error('Run `npm run apiskill:generate` and commit the result.')
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`skills/accounted-api is up to date (${files.size} files).`)
|
||||
return
|
||||
}
|
||||
|
||||
for (const [rel, content] of files) {
|
||||
const abs = join(OUT_DIR, rel)
|
||||
mkdirSync(dirname(abs), { recursive: true })
|
||||
writeFileSync(abs, content)
|
||||
}
|
||||
for (const rel of orphans) {
|
||||
rmSync(join(OUT_DIR, rel))
|
||||
console.log(`removed orphan: ${rel}`)
|
||||
}
|
||||
console.log(`wrote ${files.size} files to skills/accounted-api/`)
|
||||
}
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,77 @@
|
||||
## Conventions
|
||||
|
||||
These rules hold across the whole surface; endpoint entries below do not
|
||||
repeat them.
|
||||
|
||||
**Response envelope.** Success: `{ "data": ..., "meta": { "request_id",
|
||||
"api_version", "next_cursor"?, "audit"?, "partial_expansions"? } }`. Errors
|
||||
replace `data` with `error` (no `meta`; `request_id` moves inside `error`).
|
||||
|
||||
**Errors.** Stable machine codes with agent-oriented remediation:
|
||||
|
||||
```json
|
||||
{ "error": { "code": "PERIOD_LOCKED", "message": "Svenska", "message_en": "English",
|
||||
"details": {}, "recovery_hint": "next step", "docs_url": "...",
|
||||
"valid_alternatives": {}, "request_id": "req_..." } }
|
||||
```
|
||||
|
||||
React to `code`, read `message_en` and `recovery_hint`, follow
|
||||
`valid_alternatives` when present (e.g. `next_open_period`). Standard codes on
|
||||
every endpoint: `400` validation, `401` bad key, `403` missing scope, `404`,
|
||||
`429` rate limited (honor `Retry-After`), `500`. Full catalogue:
|
||||
https://app.gnubok.se/docs/api/errors. Only endpoint-specific codes are
|
||||
mentioned per endpoint below.
|
||||
|
||||
**Cursor pagination.** List endpoints take `?cursor=` and return
|
||||
`meta.next_cursor`; loop until it is absent/null. A stale or tampered cursor
|
||||
is NOT an error: the first page is returned again, so terminate on
|
||||
`next_cursor`, never on "page looks familiar".
|
||||
|
||||
**Dry-run on every write that supports it** (`dry-run` badge in the index).
|
||||
Send `?dry_run=true` (or `X-Dry-Run: true`): the response is always `200` with
|
||||
`data.dry_run: true` plus a preview (would-be record, journal lines, voucher
|
||||
number) and the `X-Dry-Run: true` response header; nothing is committed.
|
||||
Commit by re-issuing without the flag and with the SAME `Idempotency-Key`
|
||||
(the dry run is not cached against the key). Preview first on any financial
|
||||
write; it is free.
|
||||
|
||||
**Idempotency-Key.** Send a fresh UUID header on every POST/PATCH/DELETE;
|
||||
several endpoints reject writes without one (`400`). Replaying the same
|
||||
key+body returns the original response with the `Idempotent-Replayed: true`
|
||||
header; the same key with a different body returns `409 IDEMPOTENCY_KEY_REUSE`
|
||||
(24h window). Safe retry loop: keep the key, keep the body.
|
||||
|
||||
**Test keys are simulation-only.** With a `gnubok_sk_test_*` key, reads
|
||||
return real company data (responses carry `X-Gnubok-Mode: test`) and every
|
||||
write is forced into dry-run; writes that cannot be simulated return
|
||||
`403 TEST_KEY_WRITE_BLOCKED`. Nothing a test key does ever persists: it is
|
||||
`?dry_run=true` baked into the credential. Full end-to-end write tests
|
||||
therefore need a live key against a company you own.
|
||||
|
||||
**Atomic writes.** A mutation either commits fully or errors with no side
|
||||
effects. There is no partial state to clean up after an error response
|
||||
(`bulk-create` endpoints that do partial success say so explicitly).
|
||||
|
||||
**Audit inline.** Successful financial writes include `meta.audit` (voucher
|
||||
number, audit-trail URL, immutability timestamp). No follow-up read needed to
|
||||
confirm what was booked.
|
||||
|
||||
**Expansion.** Some list/detail endpoints take `?expand=a,b` (documented per
|
||||
endpoint). If an expansion fails the response still succeeds and names the
|
||||
failed parts in `meta.partial_expansions`; check it before trusting expanded
|
||||
fields.
|
||||
|
||||
**Async operations.** Long-running actions (fiscal-period lock/close/year-end,
|
||||
imports) return `202` with an operation id; poll `GET /api/v1/operations/{id}`
|
||||
until `status` is `succeeded`/`failed`. The response shape is identical
|
||||
whether the work ran inline or queued.
|
||||
|
||||
**Versioning.** Dated versions (current: see `meta.api_version`). Pin with the
|
||||
`Gnubok-Version` request header; responses echo it. Additive changes ship
|
||||
without a version bump; see https://app.gnubok.se/docs/api/versioning.
|
||||
|
||||
**Index badges.** Every operation line below carries machine-readable
|
||||
annotations from the spec: `scope:` (required key scope), `risk:` (low/medium/
|
||||
high; confirm with a human before unprompted high-risk calls), `idempotent`
|
||||
(safe to retry), `dry-run` (previewable), `reversible` (a single follow-up
|
||||
call can undo it, e.g. invoice credit).
|
||||
@@ -0,0 +1,38 @@
|
||||
## Gotchas (Swedish accounting domain)
|
||||
|
||||
Rules a generic REST integration will violate unless told:
|
||||
|
||||
- **Account numbers are strings, not numbers.** BAS accounts (`"1930"`,
|
||||
`"3001"`) are identifiers; send them as JSON strings. Arithmetic on them,
|
||||
zero-stripping, or number coercion corrupts postings.
|
||||
- **Posted journal entries are immutable by law** (Bokföringslagen). There is
|
||||
no PATCH or DELETE on a committed entry, ever. Undo with
|
||||
`POST .../journal-entries/{id}/reverse` (storno), fix with
|
||||
`POST .../journal-entries/{id}/correct`. Design flows around
|
||||
reverse-and-repost, not edit-in-place.
|
||||
- **Voucher numbers are gapless and server-assigned.** Never assume or
|
||||
pre-allocate one; read it from `meta.audit.voucher_number` after commit. A
|
||||
legally required gap explanation goes through
|
||||
`POST .../voucher-gap-explanations`.
|
||||
- **Every entry balances.** `sum(debit) === sum(credit)` to the öre, amounts
|
||||
are decimal SEK numbers (max 2 decimals). Do rounding with
|
||||
round-half-away-from-zero on öre; never float-accumulate line totals
|
||||
client-side and "fix" the difference on a random line.
|
||||
- **Period locks are a feature, not an error to retry.** Writes into a
|
||||
locked/closed period return `PERIOD_LOCKED` (with `valid_alternatives`
|
||||
pointing at open periods). Retrying the same request cannot succeed; either
|
||||
target an open period or surface the lock to the user.
|
||||
- **Drafts vs posted.** Invoices are created as drafts with
|
||||
`invoice_number: null`; the F-series number is assigned atomically on send.
|
||||
Journal entries follow draft -> commit. Nothing financial exists in the
|
||||
ledger until the commit/send action.
|
||||
- **Two invoice worlds.** `invoices` = accounts receivable (you bill
|
||||
customers); `supplier-invoices` = accounts payable (you receive bills).
|
||||
They are different resources with different lifecycles.
|
||||
- **Swedish user-facing text.** `error.message` is Swedish by design; show it
|
||||
to Swedish end users, and use `message_en` for your own logs/logic. Domain
|
||||
terms in responses (moms, verifikat, kostnadsställe) are not translatable
|
||||
labels but legal concepts.
|
||||
- **Compliance pre-flight.** Before building your own validation for Swedish
|
||||
rules, call `GET .../compliance/check`: it runs the server's own rule set
|
||||
(VAT plausibility, sequence integrity, period status) and returns findings.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Accounted API integration
|
||||
|
||||
Accounted is Swedish double-entry bookkeeping (bokföring) as a service: BAS
|
||||
chart of accounts, verifikationer with legally immutable audit trails, VAT
|
||||
(moms), payroll (lön), invoicing, bank reconciliation, and statutory reports,
|
||||
exposed as a REST API designed for agents and integrations first.
|
||||
|
||||
**This skill is for building software against the REST API** (an app, a
|
||||
backend job, an agent tool layer). If the goal is to *operate* a ledger
|
||||
conversationally (book receipts, run month close), use the Accounted MCP
|
||||
connector and its workflow skills instead: install the `accounted` plugin or
|
||||
see https://app.gnubok.se/docs/api/connect-claude.
|
||||
|
||||
If you have used Stripe's API the shape will feel familiar: bearer keys, dated
|
||||
versions, idempotency keys, webhook signatures, cursor pagination. The domain
|
||||
rules are Swedish accounting law; the Gotchas section below stops the classic
|
||||
violations before you ship them.
|
||||
@@ -0,0 +1,28 @@
|
||||
## Auth and base URL
|
||||
|
||||
Every request sends a bearer key:
|
||||
|
||||
```bash
|
||||
curl https://app.gnubok.se/api/v1/companies \
|
||||
-H "Authorization: Bearer gnubok_sk_live_..."
|
||||
```
|
||||
|
||||
- Base URL: `https://app.gnubok.se/api/v1` (legacy machine host, permanent).
|
||||
`https://app.accounted.se/api/v1` serves the identical API.
|
||||
- Keys are created in the Accounted dashboard under **Settings -> API**
|
||||
(`/settings/api`). Two prefixes:
|
||||
- `gnubok_sk_live_*` commits real writes.
|
||||
- `gnubok_sk_test_*` reads real company data but forces every write into
|
||||
dry-run (responses carry `X-Gnubok-Mode: test`). Develop and run evals
|
||||
with a test key; switch to live last.
|
||||
- Each key carries **scopes** (`invoices:read`, `invoices:write`,
|
||||
`payroll:write`, `webhooks:manage`, ...). Every endpoint in the index below
|
||||
is annotated with its required scope; a missing scope returns `403`.
|
||||
- Rate limit: 100 requests/minute per key. On `429`, honor `Retry-After`.
|
||||
- URLs carry the company id explicitly
|
||||
(`/api/v1/companies/{companyId}/invoices`). A key can act on any company its
|
||||
user is a member of; start every session with `GET /api/v1/companies` to
|
||||
discover ids. There is no implicit "current company".
|
||||
|
||||
First calls, in order: `GET /api/v1/health` (no auth, connectivity), then
|
||||
`GET /api/v1/companies` (auth works, discover `companyId`).
|
||||
@@ -0,0 +1,18 @@
|
||||
## Verification
|
||||
|
||||
This skill is generated (`npm run apiskill:generate` in the Accounted repo)
|
||||
from the same endpoint registry that serves the live API, its OpenAPI spec
|
||||
(`https://app.gnubok.se/api/v1/openapi.json`), and its runtime request
|
||||
validators, so schema drift between this text and the server cannot occur for
|
||||
a matching `api_version`. CI regenerates and diffs it on every change.
|
||||
|
||||
Before first use in a new environment, smoke-test:
|
||||
|
||||
```bash
|
||||
curl -s https://app.gnubok.se/api/v1/health
|
||||
curl -s https://app.gnubok.se/api/v1/companies -H "Authorization: Bearer $ACCOUNTED_API_KEY"
|
||||
```
|
||||
|
||||
If `meta.api_version` in responses is newer than the version in this skill's
|
||||
index header, refetch the skill (or read the changelog at
|
||||
https://app.gnubok.se/docs/api/changelog) before relying on endpoint details.
|
||||
@@ -0,0 +1,410 @@
|
||||
---
|
||||
name: accounted-api
|
||||
description: >-
|
||||
Consume the Accounted REST API (Swedish double-entry bookkeeping SaaS,
|
||||
https://app.gnubok.se/api/v1). Use when building an integration, app, backend
|
||||
job, or agent tool layer against Accounted: invoices, customers,
|
||||
suppliers, supplier invoices, journal entries (bokföring), bank
|
||||
transactions and reconciliation, payroll (lön), VAT/moms and financial
|
||||
reports, SIE import/export, documents, webhooks. Covers auth with
|
||||
gnubok_sk_ API keys, conventions (dry-run, idempotency, cursor
|
||||
pagination, scopes), and all 124 endpoints.
|
||||
---
|
||||
|
||||
<!-- GENERATED FILE, do not edit. Source: lib/api/v1 registry + scripts/api-skill/overlays. Regenerate with `npm run apiskill:generate`. -->
|
||||
|
||||
# Accounted API integration
|
||||
|
||||
Accounted is Swedish double-entry bookkeeping (bokföring) as a service: BAS
|
||||
chart of accounts, verifikationer with legally immutable audit trails, VAT
|
||||
(moms), payroll (lön), invoicing, bank reconciliation, and statutory reports,
|
||||
exposed as a REST API designed for agents and integrations first.
|
||||
|
||||
**This skill is for building software against the REST API** (an app, a
|
||||
backend job, an agent tool layer). If the goal is to *operate* a ledger
|
||||
conversationally (book receipts, run month close), use the Accounted MCP
|
||||
connector and its workflow skills instead: install the `accounted` plugin or
|
||||
see https://app.gnubok.se/docs/api/connect-claude.
|
||||
|
||||
If you have used Stripe's API the shape will feel familiar: bearer keys, dated
|
||||
versions, idempotency keys, webhook signatures, cursor pagination. The domain
|
||||
rules are Swedish accounting law; the Gotchas section below stops the classic
|
||||
violations before you ship them.
|
||||
|
||||
## Auth and base URL
|
||||
|
||||
Every request sends a bearer key:
|
||||
|
||||
```bash
|
||||
curl https://app.gnubok.se/api/v1/companies \
|
||||
-H "Authorization: Bearer gnubok_sk_live_..."
|
||||
```
|
||||
|
||||
- Base URL: `https://app.gnubok.se/api/v1` (legacy machine host, permanent).
|
||||
`https://app.accounted.se/api/v1` serves the identical API.
|
||||
- Keys are created in the Accounted dashboard under **Settings -> API**
|
||||
(`/settings/api`). Two prefixes:
|
||||
- `gnubok_sk_live_*` commits real writes.
|
||||
- `gnubok_sk_test_*` reads real company data but forces every write into
|
||||
dry-run (responses carry `X-Gnubok-Mode: test`). Develop and run evals
|
||||
with a test key; switch to live last.
|
||||
- Each key carries **scopes** (`invoices:read`, `invoices:write`,
|
||||
`payroll:write`, `webhooks:manage`, ...). Every endpoint in the index below
|
||||
is annotated with its required scope; a missing scope returns `403`.
|
||||
- Rate limit: 100 requests/minute per key. On `429`, honor `Retry-After`.
|
||||
- URLs carry the company id explicitly
|
||||
(`/api/v1/companies/{companyId}/invoices`). A key can act on any company its
|
||||
user is a member of; start every session with `GET /api/v1/companies` to
|
||||
discover ids. There is no implicit "current company".
|
||||
|
||||
First calls, in order: `GET /api/v1/health` (no auth, connectivity), then
|
||||
`GET /api/v1/companies` (auth works, discover `companyId`).
|
||||
|
||||
## Conventions
|
||||
|
||||
These rules hold across the whole surface; endpoint entries below do not
|
||||
repeat them.
|
||||
|
||||
**Response envelope.** Success: `{ "data": ..., "meta": { "request_id",
|
||||
"api_version", "next_cursor"?, "audit"?, "partial_expansions"? } }`. Errors
|
||||
replace `data` with `error` (no `meta`; `request_id` moves inside `error`).
|
||||
|
||||
**Errors.** Stable machine codes with agent-oriented remediation:
|
||||
|
||||
```json
|
||||
{ "error": { "code": "PERIOD_LOCKED", "message": "Svenska", "message_en": "English",
|
||||
"details": {}, "recovery_hint": "next step", "docs_url": "...",
|
||||
"valid_alternatives": {}, "request_id": "req_..." } }
|
||||
```
|
||||
|
||||
React to `code`, read `message_en` and `recovery_hint`, follow
|
||||
`valid_alternatives` when present (e.g. `next_open_period`). Standard codes on
|
||||
every endpoint: `400` validation, `401` bad key, `403` missing scope, `404`,
|
||||
`429` rate limited (honor `Retry-After`), `500`. Full catalogue:
|
||||
https://app.gnubok.se/docs/api/errors. Only endpoint-specific codes are
|
||||
mentioned per endpoint below.
|
||||
|
||||
**Cursor pagination.** List endpoints take `?cursor=` and return
|
||||
`meta.next_cursor`; loop until it is absent/null. A stale or tampered cursor
|
||||
is NOT an error: the first page is returned again, so terminate on
|
||||
`next_cursor`, never on "page looks familiar".
|
||||
|
||||
**Dry-run on every write that supports it** (`dry-run` badge in the index).
|
||||
Send `?dry_run=true` (or `X-Dry-Run: true`): the response is always `200` with
|
||||
`data.dry_run: true` plus a preview (would-be record, journal lines, voucher
|
||||
number) and the `X-Dry-Run: true` response header; nothing is committed.
|
||||
Commit by re-issuing without the flag and with the SAME `Idempotency-Key`
|
||||
(the dry run is not cached against the key). Preview first on any financial
|
||||
write; it is free.
|
||||
|
||||
**Idempotency-Key.** Send a fresh UUID header on every POST/PATCH/DELETE;
|
||||
several endpoints reject writes without one (`400`). Replaying the same
|
||||
key+body returns the original response with the `Idempotent-Replayed: true`
|
||||
header; the same key with a different body returns `409 IDEMPOTENCY_KEY_REUSE`
|
||||
(24h window). Safe retry loop: keep the key, keep the body.
|
||||
|
||||
**Test keys are simulation-only.** With a `gnubok_sk_test_*` key, reads
|
||||
return real company data (responses carry `X-Gnubok-Mode: test`) and every
|
||||
write is forced into dry-run; writes that cannot be simulated return
|
||||
`403 TEST_KEY_WRITE_BLOCKED`. Nothing a test key does ever persists: it is
|
||||
`?dry_run=true` baked into the credential. Full end-to-end write tests
|
||||
therefore need a live key against a company you own.
|
||||
|
||||
**Atomic writes.** A mutation either commits fully or errors with no side
|
||||
effects. There is no partial state to clean up after an error response
|
||||
(`bulk-create` endpoints that do partial success say so explicitly).
|
||||
|
||||
**Audit inline.** Successful financial writes include `meta.audit` (voucher
|
||||
number, audit-trail URL, immutability timestamp). No follow-up read needed to
|
||||
confirm what was booked.
|
||||
|
||||
**Expansion.** Some list/detail endpoints take `?expand=a,b` (documented per
|
||||
endpoint). If an expansion fails the response still succeeds and names the
|
||||
failed parts in `meta.partial_expansions`; check it before trusting expanded
|
||||
fields.
|
||||
|
||||
**Async operations.** Long-running actions (fiscal-period lock/close/year-end,
|
||||
imports) return `202` with an operation id; poll `GET /api/v1/operations/{id}`
|
||||
until `status` is `succeeded`/`failed`. The response shape is identical
|
||||
whether the work ran inline or queued.
|
||||
|
||||
**Versioning.** Dated versions (current: see `meta.api_version`). Pin with the
|
||||
`Gnubok-Version` request header; responses echo it. Additive changes ship
|
||||
without a version bump; see https://app.gnubok.se/docs/api/versioning.
|
||||
|
||||
**Index badges.** Every operation line below carries machine-readable
|
||||
annotations from the spec: `scope:` (required key scope), `risk:` (low/medium/
|
||||
high; confirm with a human before unprompted high-risk calls), `idempotent`
|
||||
(safe to retry), `dry-run` (previewable), `reversible` (a single follow-up
|
||||
call can undo it, e.g. invoice credit).
|
||||
|
||||
## Endpoint index
|
||||
|
||||
API version `2026-05-12`, 124 operations. Paths are shown without
|
||||
their `/api/v1` prefix (full base URL: `https://app.gnubok.se/api/v1`).
|
||||
|
||||
### Core (4)
|
||||
|
||||
Full detail: [references/core.md](references/core.md)
|
||||
|
||||
```text
|
||||
GET /companies : List companies the API key can access [scope:companies:read risk:low idempotent]
|
||||
PATCH /companies/{companyId}/settings : Partially update company settings [scope:companies:write risk:medium idempotent dry-run reversible]
|
||||
GET /health : Health check [risk:low idempotent]
|
||||
GET /operations/{id} : Poll a long-running operation by id [scope:operations:read risk:low idempotent]
|
||||
```
|
||||
|
||||
### Journal entries (8)
|
||||
|
||||
Full detail: [references/journal-entries.md](references/journal-entries.md)
|
||||
|
||||
```text
|
||||
GET /companies/{companyId}/journal-entries : List journal entries (verifikationer) [scope:reports:read risk:low idempotent]
|
||||
POST /companies/{companyId}/journal-entries : Create a draft journal entry (verifikation) [scope:bookkeeping:write risk:high idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/journal-entries/{id} : Retrieve a single verifikation by id [scope:reports:read risk:low idempotent]
|
||||
POST /companies/{companyId}/journal-entries/{id}/commit : Commit a draft journal entry [scope:bookkeeping:write risk:high idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/journal-entries/{id}/correct : Correct a posted journal entry (BFL 5:5 storno-then-replace) [scope:bookkeeping:write risk:high idempotent dry-run]
|
||||
POST /companies/{companyId}/journal-entries/{id}/reverse : Storno a posted journal entry [scope:bookkeeping:write risk:high idempotent dry-run]
|
||||
POST /companies/{companyId}/journal-entries/batch-create : Create up to 50 draft journal entries (partial-success) [scope:bookkeeping:write risk:high idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/voucher-gap-explanations : Document a gap in the verifikationsserie (BFL 5 kap 6-7 §§) [scope:bookkeeping:write risk:low idempotent dry-run]
|
||||
```
|
||||
|
||||
### Periods and registers (12)
|
||||
|
||||
Full detail: [references/periods.md](references/periods.md)
|
||||
|
||||
```text
|
||||
GET /companies/{companyId}/accounts : List chart-of-accounts entries (BAS chart) [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/compliance/check : Run a structured compliance pre-flight check [scope:compliance:read risk:low idempotent]
|
||||
GET /companies/{companyId}/dimensions : List dimensions (kostnadsställe/projekt) with their values [scope:reports:read risk:low idempotent]
|
||||
POST /companies/{companyId}/dimensions/{id}/values : Create a dimension value (kostnadsställe/projekt code) [scope:bookkeeping:write risk:low idempotent dry-run reversible]
|
||||
PATCH /companies/{companyId}/dimensions/{id}/values/{valueId} : Update a dimension value (rename, archive, set start/end date) [scope:bookkeeping:write risk:low idempotent dry-run reversible]
|
||||
DELETE /companies/{companyId}/dimensions/{id}/values/{valueId} : Delete an unreferenced dimension value [scope:bookkeeping:write risk:medium idempotent]
|
||||
GET /companies/{companyId}/fiscal-periods : List fiscal periods (räkenskapsår) [scope:reports:read risk:low idempotent]
|
||||
POST /companies/{companyId}/fiscal-periods/{id}/close : Close a fiscal period (IRREVERSIBLE per BFL 5 kap 8 §) [scope:bookkeeping:write risk:high idempotent]
|
||||
POST /companies/{companyId}/fiscal-periods/{id}/currency-revaluation : Run FX revaluation for the fiscal period [scope:bookkeeping:write risk:high idempotent reversible]
|
||||
POST /companies/{companyId}/fiscal-periods/{id}/lock : Lock a fiscal period (no new entries can be posted into it) [scope:bookkeeping:write risk:high idempotent reversible]
|
||||
POST /companies/{companyId}/fiscal-periods/{id}/opening-balances : Generate opening-balance verifikation for the next fiscal period [scope:bookkeeping:write risk:high idempotent reversible]
|
||||
POST /companies/{companyId}/fiscal-periods/{id}/year-end : Execute year-end closing (currency revaluation + closing entry) [scope:bookkeeping:write risk:high idempotent]
|
||||
```
|
||||
|
||||
### Invoices (AR) (10)
|
||||
|
||||
Full detail: [references/invoices.md](references/invoices.md)
|
||||
|
||||
```text
|
||||
GET /companies/{companyId}/invoices : List invoices for a company [scope:invoices:read risk:low idempotent]
|
||||
POST /companies/{companyId}/invoices : Create a draft invoice, proforma, or delivery note [scope:invoices:write risk:medium idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/invoices/{id} : Retrieve a single invoice by id [scope:invoices:read risk:low idempotent]
|
||||
PATCH /companies/{companyId}/invoices/{id} : Update a draft invoice (metadata fields, optionally replacing line items) [scope:invoices:write risk:low idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/invoices/{id}/credit : Issue a credit note (kreditfaktura) against an invoice [scope:invoices:write risk:high idempotent dry-run]
|
||||
POST /companies/{companyId}/invoices/{id}/mark-paid : Record a payment against an invoice [scope:invoices:write risk:medium idempotent dry-run]
|
||||
POST /companies/{companyId}/invoices/{id}/mark-sent : Transition a draft invoice to sent (without emailing) [scope:invoices:write risk:medium idempotent dry-run]
|
||||
GET /companies/{companyId}/invoices/{id}/pdf : Download the rendered invoice PDF [scope:invoices:read risk:low idempotent]
|
||||
POST /companies/{companyId}/invoices/{id}/send : Send a draft invoice to the customer by email [scope:invoices:write risk:high idempotent dry-run]
|
||||
POST /companies/{companyId}/invoices/bulk-create : Create up to 50 draft invoices in one call (partial-success) [scope:invoices:write risk:medium idempotent dry-run reversible]
|
||||
```
|
||||
|
||||
### Customers and articles (7)
|
||||
|
||||
Full detail: [references/customers.md](references/customers.md)
|
||||
|
||||
```text
|
||||
GET /companies/{companyId}/articles : List the article register (artikelregister) [scope:invoices:read risk:low idempotent]
|
||||
GET /companies/{companyId}/customers : List customers for a company [scope:customers:read risk:low idempotent]
|
||||
POST /companies/{companyId}/customers : Create a customer [scope:customers:write risk:low idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/customers/{id} : Retrieve a single customer by id [scope:customers:read risk:low idempotent]
|
||||
PATCH /companies/{companyId}/customers/{id} : Partially update a customer [scope:customers:write risk:low idempotent dry-run reversible]
|
||||
DELETE /companies/{companyId}/customers/{id} : Archive a customer (soft-delete) [scope:customers:write risk:medium idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/customers/bulk-create : Create up to 50 customers in one call (partial-success) [scope:customers:write risk:low idempotent dry-run reversible]
|
||||
```
|
||||
|
||||
### Suppliers (AP) (13)
|
||||
|
||||
Full detail: [references/suppliers.md](references/suppliers.md)
|
||||
|
||||
```text
|
||||
GET /companies/{companyId}/supplier-invoices : List supplier invoices for a company [scope:suppliers:read risk:low idempotent]
|
||||
POST /companies/{companyId}/supplier-invoices : Register a new supplier invoice [scope:suppliers:write risk:medium idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/supplier-invoices/{id} : Retrieve a single supplier invoice by id [scope:suppliers:read risk:low idempotent]
|
||||
PATCH /companies/{companyId}/supplier-invoices/{id} : Update a registered supplier invoice [scope:suppliers:write risk:low idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/supplier-invoices/{id}/approve : Approve a registered or overdue supplier invoice [scope:suppliers:write risk:low idempotent dry-run]
|
||||
POST /companies/{companyId}/supplier-invoices/{id}/credit : Issue a credit note for a supplier invoice [scope:suppliers:write risk:high idempotent dry-run]
|
||||
POST /companies/{companyId}/supplier-invoices/{id}/mark-paid : Record a payment against a supplier invoice [scope:suppliers:write risk:medium idempotent dry-run]
|
||||
GET /companies/{companyId}/suppliers : List suppliers for a company [scope:suppliers:read risk:low idempotent]
|
||||
POST /companies/{companyId}/suppliers : Create a supplier [scope:suppliers:write risk:low idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/suppliers/{id} : Retrieve a single supplier by id [scope:suppliers:read risk:low idempotent]
|
||||
PATCH /companies/{companyId}/suppliers/{id} : Partially update a supplier [scope:suppliers:write risk:low idempotent dry-run reversible]
|
||||
DELETE /companies/{companyId}/suppliers/{id} : Archive a supplier (soft-delete) [scope:suppliers:write risk:medium idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/suppliers/bulk-create : Create up to 50 suppliers in one call (partial-success) [scope:suppliers:write risk:low idempotent dry-run reversible]
|
||||
```
|
||||
|
||||
### Documents (4)
|
||||
|
||||
Full detail: [references/documents.md](references/documents.md)
|
||||
|
||||
```text
|
||||
POST /companies/{companyId}/documents : Upload a document to the WORM archive [scope:documents:write risk:medium idempotent]
|
||||
GET /companies/{companyId}/documents/{id}/download : Get a time-limited signed download URL for a document [scope:documents:read risk:low idempotent]
|
||||
POST /companies/{companyId}/documents/{id}/link : Link a document to a journal entry [scope:documents:write risk:medium idempotent dry-run]
|
||||
POST /companies/{companyId}/inbox-items/{id}/stamp : Mark an inbox item as consumed by a journal entry [scope:documents:write risk:low idempotent]
|
||||
```
|
||||
|
||||
### Banking (12)
|
||||
|
||||
Full detail: [references/banking.md](references/banking.md)
|
||||
|
||||
```text
|
||||
POST /companies/{companyId}/imports/bank : Import a bank-file (CSV / XML / CAMT053) [scope:transactions:write risk:medium idempotent]
|
||||
POST /companies/{companyId}/imports/sie : Import a SIE4 file [scope:bookkeeping:write risk:high idempotent]
|
||||
POST /companies/{companyId}/reconciliation/bank/run : Run the bank-reconciliation matcher [scope:transactions:write risk:medium idempotent dry-run]
|
||||
GET /companies/{companyId}/reconciliation/bank/status : Bank-reconciliation health snapshot [scope:transactions:read risk:low idempotent]
|
||||
GET /companies/{companyId}/transactions : List transactions for a company [scope:transactions:read risk:low idempotent]
|
||||
GET /companies/{companyId}/transactions/{id} : Retrieve a single transaction by id [scope:transactions:read risk:low idempotent]
|
||||
POST /companies/{companyId}/transactions/{id}/categorize : Categorize a transaction and create the journal entry [scope:transactions:write risk:medium idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/transactions/{id}/match-invoice : Match a positive bank transaction to a customer invoice [scope:transactions:write risk:high idempotent]
|
||||
POST /companies/{companyId}/transactions/{id}/match-supplier-invoice : Match a negative bank transaction to a supplier invoice [scope:transactions:write risk:high idempotent]
|
||||
POST /companies/{companyId}/transactions/{id}/uncategorize : Reverse the categorization of a transaction (storno + reset) [scope:transactions:write risk:medium idempotent dry-run]
|
||||
POST /companies/{companyId}/transactions/batch-categorize : Categorize up to 100 transactions in one call (partial-success) [scope:transactions:write risk:medium idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/transactions/ingest : Bulk-ingest transactions (up to 500 per call) [scope:transactions:write risk:medium idempotent dry-run]
|
||||
```
|
||||
|
||||
### Employees (13)
|
||||
|
||||
Full detail: [references/employees.md](references/employees.md)
|
||||
|
||||
```text
|
||||
GET /companies/{companyId}/employees : List employees for a company [scope:payroll:read risk:low idempotent]
|
||||
POST /companies/{companyId}/employees : Create an employee [scope:payroll:write risk:low idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/employees/{id} : Get a single employee [scope:payroll:read risk:low idempotent]
|
||||
PATCH /companies/{companyId}/employees/{id} : Update an employee [scope:payroll:write risk:low idempotent dry-run]
|
||||
DELETE /companies/{companyId}/employees/{id} : Soft-delete an employee [scope:payroll:write risk:low idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/employees/{id}/absence : List absence days for an employee in a date range [scope:payroll:read risk:low idempotent]
|
||||
PUT /companies/{companyId}/employees/{id}/absence : Register absence for an employee over a date range [scope:payroll:write risk:low idempotent dry-run reversible]
|
||||
DELETE /companies/{companyId}/employees/{id}/absence : Delete absence days for an employee in a date range [scope:payroll:write risk:low idempotent dry-run]
|
||||
GET /companies/{companyId}/employees/{id}/opening-balances : Get an employee's payroll cutover opening balances [scope:payroll:read risk:low idempotent]
|
||||
PUT /companies/{companyId}/employees/{id}/opening-balances : Set an employee's payroll cutover opening balances [scope:payroll:write risk:medium idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/employees/{id}/vacation-balance : Get an employee's current vacation balance [scope:payroll:read risk:low idempotent]
|
||||
PUT /companies/{companyId}/employees/opening-balances : Bulk-set payroll cutover opening balances (atomic) [scope:payroll:write risk:medium idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/salary/vacation-year-close : Close a vacation year (semesterberedning + arsavslut) [scope:payroll:write risk:high idempotent dry-run]
|
||||
```
|
||||
|
||||
### Salary runs (18)
|
||||
|
||||
Full detail: [references/salary-runs.md](references/salary-runs.md)
|
||||
|
||||
```text
|
||||
GET /companies/{companyId}/salary-runs : List salary runs [scope:payroll:read risk:low idempotent]
|
||||
POST /companies/{companyId}/salary-runs : Create a salary run [scope:payroll:write risk:low idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/salary-runs/{id} : Get a salary run [scope:payroll:read risk:low idempotent]
|
||||
PATCH /companies/{companyId}/salary-runs/{id} : Update a draft salary run [scope:payroll:write risk:low idempotent dry-run]
|
||||
DELETE /companies/{companyId}/salary-runs/{id} : Delete a draft salary run [scope:payroll:write risk:low idempotent dry-run]
|
||||
POST /companies/{companyId}/salary-runs/{id}/approve : Approve a reviewed salary run [scope:payroll:write risk:low idempotent dry-run]
|
||||
POST /companies/{companyId}/salary-runs/{id}/book : Post the verifikationer for a paid salary run [scope:payroll:write risk:high idempotent dry-run]
|
||||
POST /companies/{companyId}/salary-runs/{id}/calculate : Calculate a draft salary run and advance it to review [scope:payroll:write risk:medium idempotent dry-run]
|
||||
GET /companies/{companyId}/salary-runs/{id}/employees : List per-employee results of a salary run [scope:payroll:read risk:low idempotent]
|
||||
POST /companies/{companyId}/salary-runs/{id}/employees : Add an employee to a draft salary run [scope:payroll:write risk:low idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/salary-runs/{id}/employees/{employeeId} : Get one employee's payslip in a salary run [scope:payroll:read risk:low idempotent]
|
||||
DELETE /companies/{companyId}/salary-runs/{id}/employees/{employeeId} : Remove an employee from a draft salary run [scope:payroll:write risk:low idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/salary-runs/{id}/employees/{employeeId}/lines : Add a payslip line to an employee in a draft salary run [scope:payroll:write risk:low idempotent dry-run reversible]
|
||||
POST /companies/{companyId}/salary-runs/{id}/generate-agi : Generate the Skatteverket AGI XML for a salary run [scope:payroll:write risk:medium idempotent]
|
||||
PATCH /companies/{companyId}/salary-runs/{id}/lines/{lineId} : Update a payslip line in a draft salary run [scope:payroll:write risk:low idempotent dry-run reversible]
|
||||
DELETE /companies/{companyId}/salary-runs/{id}/lines/{lineId} : Delete a payslip line from a draft salary run [scope:payroll:write risk:low idempotent dry-run]
|
||||
POST /companies/{companyId}/salary-runs/{id}/mark-paid : Mark an approved salary run as paid [scope:payroll:write risk:low idempotent dry-run]
|
||||
GET /companies/{companyId}/salary-runs/{id}/payslips/{employeeId}/pdf : Download one employee's payslip as PDF [scope:payroll:read risk:low idempotent]
|
||||
```
|
||||
|
||||
### Reports (14)
|
||||
|
||||
Full detail: [references/reports.md](references/reports.md)
|
||||
|
||||
```text
|
||||
GET /companies/{companyId}/reports/ar-ledger : AR ledger: unpaid customer invoices with aging [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/avgifter-basis : Annual arbetsgivaravgifter basis per employee [scope:payroll:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/balance-sheet : Balance sheet (balansräkning) for a fiscal period [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/continuity-check : IB/UB continuity check: opening balances match prior closing [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/general-ledger : General ledger (huvudbok) for a fiscal period [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/income-statement : Income statement (resultatrapport) for a fiscal period [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/journal-register : Journal register (verifikationsregister) for a fiscal period [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/monthly-breakdown : Income statement broken down by month for a fiscal period [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/salary-journal : Salary journal (lönejournal) for a year and optional month range [scope:payroll:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/sie-export : SIE4 export (.se file) for a fiscal period [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/supplier-ledger : Supplier ledger: unpaid supplier invoices with aging [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/trial-balance : Trial balance (huvudboksrapport) for a fiscal period [scope:reports:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/vacation-liability : Vacation liability (semesterlöneskuld) per employee at year-end [scope:payroll:read risk:low idempotent]
|
||||
GET /companies/{companyId}/reports/vat-declaration : Swedish VAT declaration (momsdeklaration) for a period [scope:reports:read risk:low idempotent]
|
||||
```
|
||||
|
||||
### Webhooks (9)
|
||||
|
||||
Full detail: [references/webhooks.md](references/webhooks.md)
|
||||
|
||||
```text
|
||||
GET /companies/{companyId}/webhooks : List webhook subscriptions for a company [scope:webhooks:manage risk:low idempotent]
|
||||
POST /companies/{companyId}/webhooks : Register a webhook subscription [scope:webhooks:manage risk:low idempotent dry-run reversible]
|
||||
GET /companies/{companyId}/webhooks/{id} : Get a webhook subscription by id [scope:webhooks:manage risk:low idempotent]
|
||||
PATCH /companies/{companyId}/webhooks/{id} : Update a webhook subscription [scope:webhooks:manage risk:low idempotent dry-run reversible]
|
||||
DELETE /companies/{companyId}/webhooks/{id} : Delete a webhook subscription [scope:webhooks:manage risk:medium idempotent]
|
||||
GET /companies/{companyId}/webhooks/{id}/deliveries : List deliveries for a webhook subscription [scope:webhooks:manage risk:low idempotent]
|
||||
POST /companies/{companyId}/webhooks/{id}/rotate-secret : Rotate the HMAC signing secret on a webhook [scope:webhooks:manage risk:medium]
|
||||
POST /companies/{companyId}/webhooks/{id}/test : Send a synthetic test event to a webhook [scope:webhooks:manage risk:low]
|
||||
POST /webhook-deliveries/{id}/retry : Retry a webhook delivery [scope:webhooks:manage risk:medium]
|
||||
```
|
||||
|
||||
## Gotchas (Swedish accounting domain)
|
||||
|
||||
Rules a generic REST integration will violate unless told:
|
||||
|
||||
- **Account numbers are strings, not numbers.** BAS accounts (`"1930"`,
|
||||
`"3001"`) are identifiers; send them as JSON strings. Arithmetic on them,
|
||||
zero-stripping, or number coercion corrupts postings.
|
||||
- **Posted journal entries are immutable by law** (Bokföringslagen). There is
|
||||
no PATCH or DELETE on a committed entry, ever. Undo with
|
||||
`POST .../journal-entries/{id}/reverse` (storno), fix with
|
||||
`POST .../journal-entries/{id}/correct`. Design flows around
|
||||
reverse-and-repost, not edit-in-place.
|
||||
- **Voucher numbers are gapless and server-assigned.** Never assume or
|
||||
pre-allocate one; read it from `meta.audit.voucher_number` after commit. A
|
||||
legally required gap explanation goes through
|
||||
`POST .../voucher-gap-explanations`.
|
||||
- **Every entry balances.** `sum(debit) === sum(credit)` to the öre, amounts
|
||||
are decimal SEK numbers (max 2 decimals). Do rounding with
|
||||
round-half-away-from-zero on öre; never float-accumulate line totals
|
||||
client-side and "fix" the difference on a random line.
|
||||
- **Period locks are a feature, not an error to retry.** Writes into a
|
||||
locked/closed period return `PERIOD_LOCKED` (with `valid_alternatives`
|
||||
pointing at open periods). Retrying the same request cannot succeed; either
|
||||
target an open period or surface the lock to the user.
|
||||
- **Drafts vs posted.** Invoices are created as drafts with
|
||||
`invoice_number: null`; the F-series number is assigned atomically on send.
|
||||
Journal entries follow draft -> commit. Nothing financial exists in the
|
||||
ledger until the commit/send action.
|
||||
- **Two invoice worlds.** `invoices` = accounts receivable (you bill
|
||||
customers); `supplier-invoices` = accounts payable (you receive bills).
|
||||
They are different resources with different lifecycles.
|
||||
- **Swedish user-facing text.** `error.message` is Swedish by design; show it
|
||||
to Swedish end users, and use `message_en` for your own logs/logic. Domain
|
||||
terms in responses (moms, verifikat, kostnadsställe) are not translatable
|
||||
labels but legal concepts.
|
||||
- **Compliance pre-flight.** Before building your own validation for Swedish
|
||||
rules, call `GET .../compliance/check`: it runs the server's own rule set
|
||||
(VAT plausibility, sequence integrity, period status) and returns findings.
|
||||
|
||||
## Verification
|
||||
|
||||
This skill is generated (`npm run apiskill:generate` in the Accounted repo)
|
||||
from the same endpoint registry that serves the live API, its OpenAPI spec
|
||||
(`https://app.gnubok.se/api/v1/openapi.json`), and its runtime request
|
||||
validators, so schema drift between this text and the server cannot occur for
|
||||
a matching `api_version`. CI regenerates and diffs it on every change.
|
||||
|
||||
Before first use in a new environment, smoke-test:
|
||||
|
||||
```bash
|
||||
curl -s https://app.gnubok.se/api/v1/health
|
||||
curl -s https://app.gnubok.se/api/v1/companies -H "Authorization: Bearer $ACCOUNTED_API_KEY"
|
||||
```
|
||||
|
||||
If `meta.api_version` in responses is newer than the version in this skill's
|
||||
index header, refetch the skill (or read the changelog at
|
||||
https://app.gnubok.se/docs/api/changelog) before relying on endpoint details.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,184 @@
|
||||
<!-- GENERATED FILE, do not edit. Source: lib/api/v1 registry + scripts/api-skill/overlays. Regenerate with `npm run apiskill:generate`. -->
|
||||
|
||||
# Core endpoints
|
||||
|
||||
Connectivity, company discovery, async-operation polling, and company settings. Every session starts with GET /companies to resolve the companyId that all other URLs need.
|
||||
|
||||
Conventions (auth, envelope, pagination, dry-run, idempotency, standard errors)
|
||||
are in SKILL.md and are not repeated per endpoint.
|
||||
|
||||
### `GET /api/v1/companies`
|
||||
|
||||
**List companies the API key can access.**
|
||||
`scope:companies:read · risk:low · idempotent`
|
||||
|
||||
Returns every non-archived company the API key user is a member of, together with their role. Use the returned `id` as `{companyId}` in subsequent endpoints.
|
||||
|
||||
**Use when:** You need to discover which company IDs an API key has access to before calling company-scoped endpoints.
|
||||
**Do not use for:** Fetching a single company you already know the id of: use GET /api/v1/companies/{companyId} for that.
|
||||
|
||||
**Pitfalls:**
|
||||
- Multi-company keys (e.g. consultants) will see >1 result. Always pass the correct companyId in subsequent paths.
|
||||
- Archived companies are excluded; if a company disappears the user has been removed from it or it was archived.
|
||||
|
||||
Response `200`:
|
||||
```ts
|
||||
{
|
||||
data: { id: string, name: string, org_number: string, entity_type: string, role: "owner" | "admin" | "member" | "viewer", created_at: string }[],
|
||||
meta: {
|
||||
request_id: string,
|
||||
api_version: string,
|
||||
next_cursor?: string,
|
||||
audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string },
|
||||
partial_expansions?: string[]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `PATCH /api/v1/companies/{companyId}/settings`
|
||||
|
||||
**Partially update company settings.**
|
||||
`scope:companies:write · risk:medium · idempotent · dry-run · reversible`
|
||||
|
||||
Patches the company payment details (bank account, Bankgiro, Plusgiro, Swish, IBAN/BIC), the contact details shown on invoices (contact_person, email, phone, website), and the custom invoice email texts. All fields optional; at least one must be supplied. Idempotent (mandatory Idempotency-Key). Dry-runnable. The same validation as the MCP staging tool applies: Bankgiro/Plusgiro numbers are Luhn-checked and invoice email texts only accept a fixed placeholder set.
|
||||
|
||||
**Use when:** You need to change the payment or contact details that appear on invoices, or override the invoice email texts, directly over REST instead of the staged MCP flow.
|
||||
**Do not use for:** Legal or tax profile changes (org number, VAT registration, fiscal year, accounting method): those are not exposed on the public API. Reading settings (no GET endpoint yet; use the MCP tool gnubok_get_company_settings).
|
||||
|
||||
**Pitfalls:**
|
||||
- Idempotency-Key is mandatory; calls without it return 400.
|
||||
- contact_person is stored as default_our_reference: the default "Our reference" value on new invoices.
|
||||
- bankgiro and plusgiro must carry a valid Luhn check digit; null or empty string clears them.
|
||||
- invoice_email_texts only accepts the placeholders {fakturanummer} {kundnamn} {förnamn} {företag} {förfallodatum} {belopp}; any other {token} is rejected. Null clears every override.
|
||||
|
||||
| Parameter | In | Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `companyId` | path | `string` | yes | |
|
||||
|
||||
Request body:
|
||||
```ts
|
||||
{
|
||||
bank_name?: string,
|
||||
clearing_number: string | "",
|
||||
account_number: string | "",
|
||||
bankgiro: string | "",
|
||||
plusgiro: string | "",
|
||||
swish?: string,
|
||||
iban: string | "",
|
||||
bic: string | "",
|
||||
contact_person?: string,
|
||||
email: string | "",
|
||||
phone?: string,
|
||||
website: string | "",
|
||||
invoice_email_texts?: {
|
||||
sv?: { subject?: string, greeting?: string, body?: string, signoff?: string },
|
||||
en?: { subject?: string, greeting?: string, body?: string, signoff?: string }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Response `200`:
|
||||
```ts
|
||||
{
|
||||
data: {
|
||||
company_id: string,
|
||||
bank_name: string,
|
||||
clearing_number: string,
|
||||
account_number: string,
|
||||
bankgiro: string,
|
||||
plusgiro: string,
|
||||
swish: string,
|
||||
iban: string,
|
||||
bic: string,
|
||||
contact_person: string,
|
||||
email: string,
|
||||
phone: string,
|
||||
website: string,
|
||||
invoice_email_texts: { sv?: { subject?: string, greeting?: string, body?: string, signoff?: string }, en?: { subject?: string, greeting?: string, body?: string, signoff?: string } }
|
||||
},
|
||||
meta: {
|
||||
request_id: string,
|
||||
api_version: string,
|
||||
next_cursor?: string,
|
||||
audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string },
|
||||
partial_expansions?: string[]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/health`
|
||||
|
||||
**Health check.**
|
||||
`risk:low · idempotent`
|
||||
|
||||
Reports the API is reachable and what version is currently served. Public; no auth required.
|
||||
|
||||
**Use when:** You want to verify connectivity, latency, or which API version is live before issuing other requests.
|
||||
**Do not use for:** Anything that needs authenticated data. This endpoint returns no company-specific information.
|
||||
|
||||
**Pitfalls:**
|
||||
- A 200 here only means the API process responds: downstream Postgres/Supabase may still be degraded.
|
||||
|
||||
Response `200`:
|
||||
```ts
|
||||
{
|
||||
data: { status: "ok" | "degraded", service: "gnubok", api_version: string, timestamp: string },
|
||||
meta: {
|
||||
request_id: string,
|
||||
api_version: string,
|
||||
next_cursor?: string,
|
||||
audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string },
|
||||
partial_expansions?: string[]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/operations/{id}`
|
||||
|
||||
**Poll a long-running operation by id.**
|
||||
`scope:operations:read · risk:low · idempotent`
|
||||
|
||||
Returns the current snapshot of a v1 async operation: status (queued / running / succeeded / failed / cancelled), progress (jsonb, free-form), result (on success), and error (on failure). The operation_id is returned by the POST endpoints that initiate async work (period close, year-end, currency revaluation, SIE import).
|
||||
|
||||
**Use when:** You started an async operation and need to know whether it has finished. Poll every 5-30 seconds until a terminal status. (The 202 response advertises `operation.completed` as the eventual push signal, but that webhook event is not deliverable yet — polling is the only supported completion signal today.)
|
||||
**Do not use for:** Fetching the resource the operation produced: once status=succeeded, read the result field or call the resource-specific GET endpoint. Cancelling a running operation (no cancel endpoint exists in v1).
|
||||
|
||||
**Pitfalls:**
|
||||
- Terminal statuses (`succeeded`, `failed`, `cancelled`) are final; the row never transitions out of them.
|
||||
- progress is free-form jsonb; agents should treat it as opaque except for the documented fields `phase` (string), `current` / `total` (numbers for percent calculation).
|
||||
- started_at is null while status=queued (the work has not begun yet); completed_at is null until a terminal status is reached.
|
||||
|
||||
| Parameter | In | Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `id` | path | `string` | yes | |
|
||||
|
||||
Response `200`:
|
||||
```ts
|
||||
{
|
||||
data: {
|
||||
operation_id: string,
|
||||
type: string,
|
||||
status: "queued" | "running" | "succeeded" | "failed" | "cancelled",
|
||||
progress?: Record<string, unknown>,
|
||||
result: unknown,
|
||||
error: { code?: string, message?: string, details?: unknown },
|
||||
started_at: string,
|
||||
completed_at: string,
|
||||
poll_url: string,
|
||||
webhook_event: "operation.completed"
|
||||
},
|
||||
meta: {
|
||||
request_id: string,
|
||||
api_version: string,
|
||||
next_cursor?: string,
|
||||
audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string },
|
||||
partial_expansions?: string[]
|
||||
}
|
||||
}
|
||||
```
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,192 @@
|
||||
<!-- GENERATED FILE, do not edit. Source: lib/api/v1 registry + scripts/api-skill/overlays. Regenerate with `npm run apiskill:generate`. -->
|
||||
|
||||
# Documents endpoints
|
||||
|
||||
The WORM document archive (7-year legal retention: uploads are permanent) and inbox-item stamping. Link every uploaded receipt/invoice document to its journal entry.
|
||||
|
||||
Conventions (auth, envelope, pagination, dry-run, idempotency, standard errors)
|
||||
are in SKILL.md and are not repeated per endpoint.
|
||||
|
||||
### `POST /api/v1/companies/{companyId}/documents`
|
||||
|
||||
**Upload a document to the WORM archive.**
|
||||
`scope:documents:write · risk:medium · idempotent`
|
||||
|
||||
Multipart upload of a document (PDF / image) under the BFL 7 kap retention regime. The bytes are hashed (SHA-256), written to Supabase Storage, and recorded in document_attachments at version=1. Allowed MIME types: application/pdf, image/jpeg, image/png, image/webp. Max size: 10 MB.
|
||||
|
||||
**Use when:** You have a receipt, invoice scan, or supporting document for a posted verifikation and want it archived for the 7-year BFL retention period. Optionally link to a journal entry at upload time via journal_entry_id.
|
||||
**Do not use for:** Updating an existing document (no v1 update endpoint; new versions go through the dashboard). Bulk uploads: call once per file.
|
||||
|
||||
**Pitfalls:**
|
||||
- Idempotency-Key is mandatory; multipart retries with the same key replay the cached response.
|
||||
- Max size 10 MB enforced server-side: DOC_UPLOAD_TOO_LARGE on overrun.
|
||||
- Only application/pdf / image/jpeg / image/png / image/webp accepted: DOC_UPLOAD_UNSUPPORTED_TYPE otherwise.
|
||||
- WORM: once linked to a posted journal entry, the document row cannot be modified or deleted (DB trigger). Upload-then-link is reversible (the document exists with journal_entry_id=null until linked); once linked, treat as immutable.
|
||||
- Dry-run is not supported on this endpoint: the engine hashes + stores + inserts in one atomic flow.
|
||||
|
||||
| Parameter | In | Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `companyId` | path | `string` | yes | |
|
||||
|
||||
Request body (`multipart/form-data`):
|
||||
```ts
|
||||
{
|
||||
file: string,
|
||||
upload_source?: "file_upload" | "camera" | "email" | "api",
|
||||
journal_entry_id?: string,
|
||||
journal_entry_line_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
Response `200`:
|
||||
```ts
|
||||
{
|
||||
data: {
|
||||
id: string,
|
||||
file_name: string,
|
||||
mime_type: string,
|
||||
file_size_bytes: number,
|
||||
sha256_hash: string,
|
||||
version: number,
|
||||
is_current_version: boolean,
|
||||
upload_source: string,
|
||||
journal_entry_id: string,
|
||||
journal_entry_line_id: string,
|
||||
created_at: string
|
||||
},
|
||||
meta: {
|
||||
request_id: string,
|
||||
api_version: string,
|
||||
next_cursor?: string,
|
||||
audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string },
|
||||
partial_expansions?: string[]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/v1/companies/{companyId}/documents/{id}/download`
|
||||
|
||||
**Get a time-limited signed download URL for a document.**
|
||||
`scope:documents:read · risk:low · idempotent`
|
||||
|
||||
Returns a Supabase Storage signed URL valid for 15 minutes. The URL itself is the canonical download: fetch it with any HTTP client; no API key needed on the storage host. Verify file integrity client-side against the returned sha256_hash if your workflow requires it.
|
||||
|
||||
**Use when:** You need the bytes of an archived document (e.g. for OCR, attachment to an email, regulatory export). Always re-fetch the URL before each download: old URLs expire.
|
||||
**Do not use for:** Persisting the URL anywhere: it expires. Storing the URL in a webhook payload or audit log makes the audit trail dependent on URL state.
|
||||
|
||||
**Pitfalls:**
|
||||
- The signed URL expires after 15 minutes. Don't cache it beyond the immediate transaction.
|
||||
- The URL leaks the Supabase Storage origin; this is benign (the signature alone authorizes the read) but rate-limit any forwarding so you don't reveal the storage layout to untrusted callers.
|
||||
- Each call emits a document.accessed event. Polling this endpoint produces audit noise; cache the URL for its full TTL.
|
||||
|
||||
| Parameter | In | Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `companyId` | path | `string` | yes | |
|
||||
| `id` | path | `string` | yes | |
|
||||
|
||||
Response `200`:
|
||||
```ts
|
||||
{
|
||||
data: {
|
||||
id: string,
|
||||
file_name: string,
|
||||
mime_type: string,
|
||||
sha256_hash: string,
|
||||
is_current_version: boolean,
|
||||
download_url: string,
|
||||
expires_in_seconds: number
|
||||
},
|
||||
meta: {
|
||||
request_id: string,
|
||||
api_version: string,
|
||||
next_cursor?: string,
|
||||
audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string },
|
||||
partial_expansions?: string[]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/companies/{companyId}/documents/{id}/link`
|
||||
|
||||
**Link a document to a journal entry.**
|
||||
`scope:documents:write · risk:medium · idempotent · dry-run`
|
||||
|
||||
Sets journal_entry_id (and optionally journal_entry_line_id) on an existing document. Optionally stamps the originating invoice_inbox_items row as consumed via inbox_item_id. Use this after /documents upload when the link target was unknown at upload time, or to re-link a stray document. Once the target JE is posted, the document row is effectively immutable per BFL 7 kap retention.
|
||||
|
||||
**Use when:** A document was uploaded without a journal_entry_id (e.g. bulk import) and you now want to attach it to a posted verifikation. Pass inbox_item_id when the document came from the invoice inbox so the item is marked resolved in one call.
|
||||
**Do not use for:** Unlinking: no v1 unlink endpoint. The dashboard exposes a manual override; v1 keeps the WORM contract by refusing to revert posted-JE links.
|
||||
|
||||
**Pitfalls:**
|
||||
- Idempotency-Key is mandatory.
|
||||
- Both the document and the journal_entry_id must belong to the caller's company. NOT_FOUND on mismatch (enumeration hardening).
|
||||
- Re-linking an already-linked document overwrites the previous journal_entry_id: confirm the old target is what you intend to break.
|
||||
- inbox_item_id stamping is best-effort: if the stamp fails the document link still succeeds. Use POST /api/v1/companies/:companyId/inbox-items/:id/stamp to stamp independently.
|
||||
|
||||
| Parameter | In | Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `companyId` | path | `string` | yes | |
|
||||
| `id` | path | `string` | yes | |
|
||||
|
||||
Request body:
|
||||
```ts
|
||||
{ journal_entry_id: string, journal_entry_line_id?: string, inbox_item_id?: string }
|
||||
```
|
||||
|
||||
Response `200`:
|
||||
```ts
|
||||
{
|
||||
data: { id: string, journal_entry_id: string, journal_entry_line_id: string, file_name: string },
|
||||
meta: {
|
||||
request_id: string,
|
||||
api_version: string,
|
||||
next_cursor?: string,
|
||||
audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string },
|
||||
partial_expansions?: string[]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/v1/companies/{companyId}/inbox-items/{id}/stamp`
|
||||
|
||||
**Mark an inbox item as consumed by a journal entry.**
|
||||
`scope:documents:write · risk:low · idempotent`
|
||||
|
||||
Sets created_journal_entry_id on an invoice_inbox_items row so the item drops out of the active inbox todo list. Use when the document was linked to a JE via a separate call and you need to close the inbox item independently.
|
||||
|
||||
**Use when:** An inbox document has already been attached to a verifikation (via documents link) but the inbox item itself was not stamped at link time: e.g. when using the v1 link endpoint without inbox_item_id.
|
||||
**Do not use for:** Creating a new journal entry from an inbox item: use the invoice-inbox extension book-direct route for that.
|
||||
|
||||
**Pitfalls:**
|
||||
- Idempotency-Key is mandatory.
|
||||
- The inbox item and journal_entry_id must both belong to the caller's company.
|
||||
- Stamping with a different journal_entry_id than the one already set returns CONFLICT: the item is already resolved.
|
||||
|
||||
| Parameter | In | Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `companyId` | path | `string` | yes | |
|
||||
| `id` | path | `string` | yes | |
|
||||
|
||||
Request body:
|
||||
```ts
|
||||
{ journal_entry_id: string }
|
||||
```
|
||||
|
||||
Response `200`:
|
||||
```ts
|
||||
{
|
||||
data: { id: string, created_journal_entry_id: string },
|
||||
meta: {
|
||||
request_id: string,
|
||||
api_version: string,
|
||||
next_cursor?: string,
|
||||
audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string },
|
||||
partial_expansions?: string[]
|
||||
}
|
||||
}
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,127 @@
|
||||
---
|
||||
name: openapi-to-skill
|
||||
description: >-
|
||||
Turn an OpenAPI/Swagger spec (JSON or YAML, file or URL) into an installable
|
||||
agent skill that teaches coding agents how to call that API correctly. Use
|
||||
when the user says "build a skill for this API", "generate a skill from this
|
||||
spec", "make our API docs agent-ready", or points at an openapi.json /
|
||||
swagger.yaml and wants an integration skill. Produces a SKILL.md +
|
||||
references/ folder ready for `npx skills add`.
|
||||
---
|
||||
|
||||
# OpenAPI spec to agent skill
|
||||
|
||||
You are building a **consumer-side skill**: a folder of distilled instructions
|
||||
that lets an agent integrate correctly against an API on the first attempt.
|
||||
The output is NOT a restatement of the spec. A spec restatement grades D: the
|
||||
agent could have read the spec itself. The value you add is selection
|
||||
(what matters), compression (condensed schemas), conventions (the cross-cutting
|
||||
rules), and verification (what the live API actually does).
|
||||
|
||||
## Inputs
|
||||
|
||||
Collect these before starting (ask only for what is missing):
|
||||
|
||||
1. **Spec location**: file path or URL. If URL, download it next to your work.
|
||||
2. **Output directory**: `skills/<api-name>/` in the repo when the skill will
|
||||
be distributed (installable via `npx skills add owner/repo --skill <api-name>`),
|
||||
`.claude/skills/<api-name>/` when it is for personal/project use only.
|
||||
3. **Credentials for verification** (optional but strongly preferred): a base
|
||||
URL and an env var holding a low-privilege or test API key. Read-only
|
||||
verification only; never call write endpoints without explicit user consent.
|
||||
|
||||
## Process
|
||||
|
||||
### 1. Inventory the spec
|
||||
|
||||
Run the bundled tool (portable, stdlib-only Node):
|
||||
|
||||
```bash
|
||||
node scripts/openapi-inventory.mjs <spec.json> # overview: groups + one line per operation
|
||||
node scripts/openapi-inventory.mjs <spec.json> --group <g> # full detail for one group
|
||||
```
|
||||
|
||||
YAML specs: convert first (`npx -y js-yaml spec.yaml > spec.json`).
|
||||
|
||||
The overview gives you: title, servers, auth schemes, operation count, and
|
||||
operations grouped by tag (or by dominant path segment when the spec has no
|
||||
tags). Read it fully before writing anything.
|
||||
|
||||
### 2. Extract the conventions
|
||||
|
||||
The conventions section is the most valuable part of the output skill: it is
|
||||
what lets an agent predict endpoint behaviour instead of looking everything up.
|
||||
Hunt for them in this order:
|
||||
|
||||
- `info.description`: many agent-first APIs state their invariants here.
|
||||
- `components.securitySchemes`: auth header shape, token format, where keys
|
||||
come from (docs often say; if not, ask the user).
|
||||
- Recurring response envelope: sample 3-4 operations with `--group` and
|
||||
compare. Note pagination style (cursor vs offset), error envelope, request
|
||||
id fields.
|
||||
- Recurring parameters and headers: idempotency keys, dry-run flags, expand
|
||||
parameters, rate limits.
|
||||
- `x-*` extensions: risk levels, scopes, idempotency markers. Surface them;
|
||||
they exist for agents.
|
||||
|
||||
If the spec is thin on conventions, check the API's human docs (ask the user
|
||||
for the docs URL) rather than guessing.
|
||||
|
||||
### 3. Choose the reference grouping
|
||||
|
||||
Target 6 to 12 reference files. Merge tiny groups thematically (e.g.
|
||||
`customers` + `articles` into `invoicing`); split any group that would exceed
|
||||
roughly 500 lines rendered. Every operation must land in exactly one
|
||||
reference file.
|
||||
|
||||
### 4. Write the skill
|
||||
|
||||
Follow `references/output-template.md` for the exact shape. Non-negotiables:
|
||||
|
||||
- **SKILL.md stays under ~400 lines.** Frontmatter description must name the
|
||||
API and its domain so the skill triggers (the agent sees only name +
|
||||
description at discovery time).
|
||||
- **Conventions before endpoints.** Auth + base URL + envelope + pagination +
|
||||
error handling first; the endpoint index after.
|
||||
- **Endpoint index**: one line per operation (`METHOD path : summary [badges]`),
|
||||
grouped, each group naming its reference file. The inventory tool's overview
|
||||
output is already in this format.
|
||||
- **References**: start from `--group` output, then edit. Deduplicate
|
||||
boilerplate the spec repeats per operation (shared error lists, envelope
|
||||
wrappers) up into the conventions section, keep operation-specific pitfalls
|
||||
inline, and add a worked example (request + realistic response) for the 2-3
|
||||
most-used operations per group.
|
||||
- **Schemas in condensed TypeScript-ish form**, never raw JSON Schema.
|
||||
|
||||
### 5. Verify against the live API
|
||||
|
||||
This step separates a usable skill from a plausible-looking one. Desk review
|
||||
and live testing find different failure classes.
|
||||
|
||||
With credentials: smoke-test read-only endpoints (health/list endpoints, one
|
||||
or two per group), using the exact auth header the skill documents. Compare
|
||||
actual responses against the documented envelope and schemas. Every mismatch
|
||||
is gold: record it in a **Gotchas** section in SKILL.md. Replace invented
|
||||
examples with real (redacted) response bodies.
|
||||
|
||||
Without credentials: add a **Verification** section stating the skill was
|
||||
generated from the spec and not yet tested live, with the smoke-test commands
|
||||
a future session should run once a key exists.
|
||||
|
||||
### 6. Grade it
|
||||
|
||||
Score the output against the checklist at the bottom of
|
||||
`references/output-template.md`. Fix what fails, once. Then report to the
|
||||
user: what was generated, what was verified live vs. desk-only, and how to
|
||||
install it (`npx skills add <owner>/<repo> --skill <name>`).
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Restating the spec operation-by-operation with no selection or added
|
||||
operational knowledge.
|
||||
- Raw JSON Schema dumps, or full request/response schemas for every endpoint
|
||||
when a condensed form plus one worked example carries more information.
|
||||
- Auth buried mid-file. It is always the first section after the intro.
|
||||
- Inventing example responses when a live call could have produced a real one.
|
||||
- A giant single SKILL.md instead of progressive disclosure via references/.
|
||||
- Skipping the grade step because the output "looks complete".
|
||||
@@ -0,0 +1,116 @@
|
||||
# Output skill template
|
||||
|
||||
The generated skill is a folder:
|
||||
|
||||
```
|
||||
<api-name>/
|
||||
SKILL.md # conventions + endpoint index; under ~400 lines
|
||||
references/
|
||||
<group-a>.md # full operation detail for one resource group
|
||||
<group-b>.md
|
||||
...
|
||||
```
|
||||
|
||||
## SKILL.md skeleton
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: <api-name>
|
||||
description: >-
|
||||
Consume the <API title> (<domain, e.g. "Swedish bookkeeping">, <base URL>).
|
||||
Use when building an integration or app against <API name>: <the 5-8
|
||||
resource nouns, e.g. "invoices, customers, payroll, reports">. Covers auth,
|
||||
conventions, and every endpoint.
|
||||
---
|
||||
|
||||
# <API title> integration
|
||||
|
||||
<Two or three sentences: what the API is, what a consumer can do with it,
|
||||
and the one thing that makes it different from a generic REST API.>
|
||||
|
||||
## Auth and base URL
|
||||
|
||||
<Auth header with exact format, where keys are created, test vs live keys,
|
||||
scopes if any, rate limits. A copy-pasteable curl that lists something.>
|
||||
|
||||
## Conventions
|
||||
|
||||
<The cross-cutting rules, each with a one-line example where the shape is not
|
||||
obvious: response envelope, pagination, error envelope + how to react to the
|
||||
common codes, idempotency, dry-run, expansion, async patterns. This section
|
||||
is why the skill exists; spend your effort here.>
|
||||
|
||||
## Endpoint index
|
||||
|
||||
<One line per operation, grouped. Each group heading names its reference
|
||||
file: "Full detail: references/<group>.md". Line format:
|
||||
`METHOD /path : summary [scope:x risk:y idempotent dry-run]`>
|
||||
|
||||
## Gotchas
|
||||
|
||||
<Only entries that are true and non-obvious: verified live mismatches,
|
||||
sharp edges from the spec's own pitfall notes that apply across endpoints,
|
||||
domain rules a generic developer would violate. No padding; delete this
|
||||
section rather than fill it with restatements.>
|
||||
|
||||
## Verification
|
||||
|
||||
<Either: "Verified live on <date> against <base URL>: <what was called>."
|
||||
Or: "Generated from spec, NOT yet verified live. Before first use run:
|
||||
<smoke-test curl commands>.">
|
||||
```
|
||||
|
||||
## references/<group>.md skeleton
|
||||
|
||||
```markdown
|
||||
# <Group> endpoints
|
||||
|
||||
<One or two sentences: what this resource is and the state machine if any
|
||||
(e.g. draft -> sent -> paid). Cross-reference sibling groups.>
|
||||
|
||||
<For each operation:>
|
||||
### `METHOD /path`
|
||||
|
||||
**<Summary>.**
|
||||
`scope:<s> · risk:<r> · idempotent · dry-run`
|
||||
|
||||
<Description from the spec, kept if it earns its lines: use-when,
|
||||
do-not-use-for, pitfalls.>
|
||||
|
||||
<Parameters table if any beyond path ids.>
|
||||
|
||||
Request body: (writes only)
|
||||
```ts
|
||||
{ condensed: "typescript-ish" }
|
||||
```
|
||||
|
||||
Response `200`:
|
||||
```ts
|
||||
{ condensed: "typescript-ish" }
|
||||
```
|
||||
|
||||
<For the 2-3 most-used operations in the group: a worked example with a
|
||||
realistic request and a real (redacted) or spec-example response.>
|
||||
```
|
||||
|
||||
## Quality checklist
|
||||
|
||||
Grade the generated skill against every item. Fix failures before delivering.
|
||||
|
||||
1. **First-call test**: could an agent with only SKILL.md (no references) make
|
||||
a correct authenticated list call? Auth format, base URL, and envelope must
|
||||
be sufficient.
|
||||
2. **Trigger test**: does the frontmatter description name the API, its
|
||||
domain, and its resource nouns? An agent that has never seen this skill
|
||||
must match it from a prompt like "add <API> invoicing to our app".
|
||||
3. **Coverage test**: every operation in the spec appears exactly once in the
|
||||
endpoint index, and every index group has a reference file.
|
||||
4. **Restatement test**: does SKILL.md contain anything an agent would learn
|
||||
anyway from one endpoint call? Cut it.
|
||||
5. **Convention test**: pagination, error handling, and idempotency are
|
||||
documented as rules, not repeated per endpoint.
|
||||
6. **Honesty test**: every example response is real or clearly marked as
|
||||
spec-derived; the Verification section says what was and was not tested.
|
||||
7. **Size test**: SKILL.md under ~400 lines; no reference file over ~700.
|
||||
8. **Write-safety test**: destructive or high-risk operations are visibly
|
||||
marked so an agent knows to confirm before calling.
|
||||
@@ -0,0 +1,45 @@
|
||||
/** Type surface of openapi-inventory.mjs for TypeScript consumers. */
|
||||
|
||||
export interface OperationObjectLite {
|
||||
operationId?: string
|
||||
summary?: string
|
||||
description?: string
|
||||
tags?: string[]
|
||||
deprecated?: boolean
|
||||
parameters?: unknown[]
|
||||
requestBody?: unknown
|
||||
responses?: Record<string, unknown>
|
||||
[extension: string]: unknown
|
||||
}
|
||||
|
||||
export interface OperationEntry {
|
||||
path: string
|
||||
method: string
|
||||
op: OperationObjectLite
|
||||
pathItem: Record<string, unknown>
|
||||
segments: string[]
|
||||
depth: number
|
||||
group: string
|
||||
}
|
||||
|
||||
export interface Inventory {
|
||||
title: string
|
||||
version: string
|
||||
description: string
|
||||
servers: string[]
|
||||
securitySchemes: Record<string, unknown>
|
||||
operationCount: number
|
||||
groups: Array<{ name: string; operations: OperationEntry[] }>
|
||||
}
|
||||
|
||||
export function loadSpec(specPath: string): unknown
|
||||
export function resolveRef(spec: unknown, ref: string): unknown
|
||||
export function condenseSchema(
|
||||
spec: unknown,
|
||||
schema: unknown,
|
||||
opts?: { depth?: number; seen?: Set<string> },
|
||||
): string
|
||||
export function listOperations(spec: unknown): OperationEntry[]
|
||||
export function buildInventory(spec: unknown): Inventory
|
||||
export function formatOpLine(entry: OperationEntry): string
|
||||
export function renderOperationMd(spec: unknown, entry: OperationEntry): string
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user