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

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

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

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

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

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

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

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

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-11 12:45:19 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 7a49aec0c3
commit 11b82cbb91
31 changed files with 7751 additions and 3 deletions
+335
View File
@@ -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()
+77
View File
@@ -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).
+38
View File
@@ -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.
+17
View File
@@ -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.
+28
View File
@@ -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.