Skip to content

docs: add OpenAPI schema context for AI agents#72

Merged
Kilerd merged 2 commits intomainfrom
codex/openapi-schema-agent-context
Apr 24, 2026
Merged

docs: add OpenAPI schema context for AI agents#72
Kilerd merged 2 commits intomainfrom
codex/openapi-schema-agent-context

Conversation

@Kilerd
Copy link
Copy Markdown
Contributor

@Kilerd Kilerd commented Apr 24, 2026

Summary

  • add an OpenAPI schema section to the API introduction page for AI coding agent usage
  • add a script to refresh api-reference/openapi.json from https://api.fish.audio/openapi.json
  • add CI to validate and automatically propose OpenAPI schema updates

Tests

  • npm run check:openapi

Summary by CodeRabbit

Release Notes

  • Documentation

    • Updated API reference with OpenAPI schema section for IDE assistants and developers.
    • Added README documentation on OpenAPI synchronization and local validation workflow.
  • Chores

    • Set up automated GitHub Actions workflow to keep OpenAPI schema synchronized with upstream source.
    • Added new npm scripts for OpenAPI schema updates and validation.

@mintlify
Copy link
Copy Markdown

mintlify Bot commented Apr 24, 2026

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
hanabiaiinc 🟢 Ready View Preview Apr 24, 2026, 8:01 AM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 24, 2026

Warning

Rate limit exceeded

@Kilerd has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 55 minutes and 55 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 55 minutes and 55 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3e2d60a2-6bcc-4bb0-bea1-5496207e1887

📥 Commits

Reviewing files that changed from the base of the PR and between 274812a and ad402b0.

📒 Files selected for processing (1)
  • api-reference/openapi.json
📝 Walkthrough

Walkthrough

This PR introduces automated OpenAPI schema synchronization via a GitHub Actions workflow. It fetches and validates the OpenAPI specification from an upstream source, enforcing consistency on pull requests and creating automatic update commits on the main branch. Supporting npm scripts and documentation guide local development and explain the workflow.

Changes

Cohort / File(s) Summary
Workflow Automation
.github/workflows/openapi-schema.yaml
New GitHub Actions workflow runs on schedule and manual dispatch to fetch, validate, and sync OpenAPI schema. On PRs, enforces that api-reference/openapi.json matches latest output via git diff. On non-PR events, creates automated commit and PR with schema updates.
Documentation
README.md, api-reference/introduction.mdx
README updated with OpenAPI workflow explanation and new npm script documentation. Introduction section adds canonical OpenAPI schema link and guidance for AI agents/IDEs. Formatting adjustments to frontmatter and whitespace.
Scripts and Configuration
package.json, scripts/update-openapi.mjs
New npm scripts added: update:openapi (fetch/update schema), check:openapi (validate), and validate (combined flow). New Node script fetches OpenAPI document with timeout enforcement, validates schema structure, formats JSON, and atomically writes to file with temp/rename pattern.

Sequence Diagram

sequenceDiagram
    participant GHA as GitHub Actions
    participant API as Upstream OpenAPI URL
    participant Script as update-openapi.mjs
    participant FS as File System
    participant Git as Git Operations
    participant GHPull as GitHub Pull Request

    GHA->>API: fetch OpenAPI schema
    API-->>Script: return JSON document
    Script->>Script: validate openapi field (v3.x)
    Script->>Script: validate paths object exists
    Script->>Script: format JSON with trailing newline
    Script->>FS: write to *.tmp file
    Script->>FS: atomically rename to target
    FS-->>Script: write complete
    
    alt On Pull Request
        Script->>Git: git diff api-reference/openapi.json
        Git-->>GHA: exit code 0 if unchanged
    else On Main Branch Event
        Script->>Git: git commit api-reference/openapi.json
        Git->>GHPull: create automated PR
        GHPull-->>GHA: PR created with schema changes
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Hops of joy for schemas true,
Fetching specs from URLs new,
Validating paths so neat,
Automated sync—what a treat!
OpenAPI flows, our docs complete!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately describes the main objective: adding OpenAPI schema documentation for AI agents, which is reflected in the api-reference/introduction.mdx changes and related infrastructure.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/openapi-schema-agent-context

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (6)
api-reference/introduction.mdx (1)

10-10: Prefer descriptive anchor text over raw URL text.

For readability, consider changing the visible link text to something like “API Keys page” while keeping the same target URL.

As per coding guidelines: Prioritize accuracy and usability of information.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api-reference/introduction.mdx` at line 10, Replace the raw URL visible text
with a descriptive anchor label: update the link in
api-reference/introduction.mdx so the href remains
https://fish.audio/app/api-keys/ but the visible text becomes something like
"API Keys page" (or similar descriptive text) to improve readability and
usability while keeping the target URL unchanged.
.github/workflows/openapi-schema.yaml (2)

36-41: Add a concurrency group to avoid overlapping auto-update runs.

Cron, push-to-main, and manual dispatch can all overlap. While peter-evans/create-pull-request is idempotent on the same branch, adding a concurrency group avoids wasted minutes and noisy intermediate commits.

♻️ Proposed change
   update-openapi:
     if: github.event_name != 'pull_request'
     runs-on: ubuntu-latest
+    concurrency:
+      group: openapi-schema-update
+      cancel-in-progress: false
     permissions:
       contents: write
       pull-requests: write
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/openapi-schema.yaml around lines 36 - 41, The workflow job
"update-openapi" needs a concurrency group to prevent overlapping runs; add a
top-level concurrency key for that job (using a stable group name like
"update-openapi" or including the workflow/branch via github.ref) so concurrent
runs are queued or cancelled, e.g., add a concurrency: { group: "...",
cancel-in-progress: true } entry to the update-openapi job so cron/push/manual
dispatches don't overlap with each other.

12-16: Apply least-privilege at the workflow level.

The check-openapi job inherits the default GITHUB_TOKEN permissions. Declaring a restrictive top-level permissions: block (and keeping the broader grant scoped to update-openapi) follows the least-privilege recommendation for GitHub Actions.

🛡️ Proposed change
 on:
   pull_request:
     branches: [main]
   push:
     branches: [main]
   schedule:
     - cron: "0 3 * * *"
   workflow_dispatch:

+permissions:
+  contents: read
+
 jobs:
   check-openapi:
     if: github.event_name == 'pull_request'
     runs-on: ubuntu-latest

Also applies to: 36-41

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/openapi-schema.yaml around lines 12 - 16, Add a top-level
restrictive permissions block to the workflow (e.g., set minimal rights such as
contents: read) so jobs do not inherit broad GITHUB_TOKEN privileges; then scope
any broader permissions only to the specific job that needs them (keep the wider
grant for the update-openapi job). Update the workflow YAML to include a
top-level permissions: block and ensure the check-openapi job (and other jobs)
either inherit that minimal set or explicitly declare only the narrower
permissions they require, while the job that runs update-openapi gets the larger
permission set.
scripts/update-openapi.mjs (2)

24-25: Produce a clearer error when the upstream returns a 200 with non-JSON.

If api.fish.audio ever serves an HTML maintenance/login page with a 200 response, JSON.parse throws a terse SyntaxError that doesn't reference the URL or the status — making CI failures hard to diagnose. Wrap the parse and attach context.

♻️ Proposed change
-  const rawSchema = await response.text();
-  const schema = JSON.parse(rawSchema);
+  const rawSchema = await response.text();
+  let schema;
+  try {
+    schema = JSON.parse(rawSchema);
+  } catch (error) {
+    throw new Error(
+      `Response from ${schemaUrl} was not valid JSON (content-type: ${response.headers.get("content-type") ?? "unknown"}): ${error.message}`
+    );
+  }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/update-openapi.mjs` around lines 24 - 25, Wrap the
JSON.parse(rawSchema) call in a try/catch and surface a richer error that
includes the response URL and status (use response.url and response.status) plus
a short excerpt of rawSchema; replace the current direct assignment to schema
with code that attempts schema = JSON.parse(rawSchema) inside the try, and in
the catch throw or log a new Error that combines a descriptive message like
"Failed to parse JSON from <response.url> (status: <response.status>):
<snippet>" so CI failures show the upstream URL/status and a bit of the non-JSON
payload for debugging.

10-22: Consider a small retry for transient upstream failures.

Given the PR-gate workflow depends on a live fetch on every contributor PR, a single transient 5xx or socket hiccup on api.fish.audio will red-x an otherwise valid PR. A simple bounded retry with backoff (e.g., 2–3 attempts) on network errors and 5xx statuses would materially reduce CI flakiness without complicating the script much.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/update-openapi.mjs` around lines 10 - 22, The fetch in main() that
downloads schemaUrl using fetchTimeoutMs should be made resilient with a bounded
retry loop (2–3 attempts) and exponential backoff: wrap the fetch call in a
for-loop, on each attempt recreate the AbortSignal.timeout(fetchTimeoutMs),
catch network errors (fetch throws) and treat HTTP 5xx (response.status >= 500)
as retryable, sleeping an increasing delay (e.g., 200ms, 400ms, 800ms) between
retries; return the successful response when response.ok is true and, after
exhausting attempts, throw the original or last error as before. Use the
existing symbols main(), schemaUrl, fetchTimeoutMs and check
response.ok/response.status to implement this logic.
package.json (1)

12-12: validate now requires network and silently overwrites the local schema.

Running npm run validate will always fetch from api.fish.audio and rewrite api-reference/openapi.json before running mint validate. This makes local validation non-reproducible, fails offline, and discards any in-progress local edits to the schema (which can be surprising when diagnosing issues against a modified/pinned spec).

Consider splitting the flow so validate is non-mutating and a separate target performs the refresh.

♻️ Proposed refactor
-    "update:openapi": "node scripts/update-openapi.mjs",
-    "check:openapi": "mint openapi-check api-reference/openapi.json",
-    "validate": "npm run update:openapi && mint validate"
+    "update:openapi": "node scripts/update-openapi.mjs",
+    "check:openapi": "mint openapi-check api-reference/openapi.json",
+    "validate": "npm run check:openapi && mint validate",
+    "validate:refresh": "npm run update:openapi && npm run validate"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@package.json` at line 12, The "validate" npm script currently runs
"update:openapi && mint validate", which fetches from the network and overwrites
the local schema before validation; split this into two scripts so validation is
non-mutating: keep a script named "validate" that runs only "mint validate" (so
it can run offline and won't overwrite local files) and add a separate script
like "refresh:openapi" (or "update:openapi:remote") that runs "update:openapi"
to fetch and overwrite the schema when explicitly requested; update any CI or
docs to call the appropriate script (validate vs refresh:openapi) instead of the
combined command.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/openapi-schema.yaml:
- Around line 13-34: The check-openapi job refreshes the upstream schema with
npm run update:openapi and then always runs git diff --exit-code --
api-reference/openapi.json, which causes unrelated PRs to fail if the upstream
schema changed; change the workflow so the strict git diff gate only runs when
the PR actually modifies api-reference/openapi.json (e.g., add a pre-step using
dorny/paths-filter or run git diff --name-only against the PR base vs head and
set a conditional on the step), or remove the update step and run only npm run
check:openapi in PRs while leaving updates to the scheduled job; update the step
that runs git diff --exit-code -- api-reference/openapi.json to be conditional
(only when the path filter detects changes) or to use continue-on-error: true
depending on the chosen option.

In `@scripts/update-openapi.mjs`:
- Line 8: Validate OPENAPI_FETCH_TIMEOUT_MS before using it: replace the raw
Number(process.env.OPENAPI_FETCH_TIMEOUT_MS ?? 30000) assignment for
fetchTimeoutMs with logic that parses the env var, checks Number.isFinite(value)
and value > 0, and if invalid (NaN, non-finite, <= 0) fall back to the default
30000 (or set a safe minimum) while logging or throwing a clear error message;
update any use of AbortSignal.timeout(fetchTimeoutMs) to rely on this validated
fetchTimeoutMs to avoid RangeError.

---

Nitpick comments:
In @.github/workflows/openapi-schema.yaml:
- Around line 36-41: The workflow job "update-openapi" needs a concurrency group
to prevent overlapping runs; add a top-level concurrency key for that job (using
a stable group name like "update-openapi" or including the workflow/branch via
github.ref) so concurrent runs are queued or cancelled, e.g., add a concurrency:
{ group: "...", cancel-in-progress: true } entry to the update-openapi job so
cron/push/manual dispatches don't overlap with each other.
- Around line 12-16: Add a top-level restrictive permissions block to the
workflow (e.g., set minimal rights such as contents: read) so jobs do not
inherit broad GITHUB_TOKEN privileges; then scope any broader permissions only
to the specific job that needs them (keep the wider grant for the update-openapi
job). Update the workflow YAML to include a top-level permissions: block and
ensure the check-openapi job (and other jobs) either inherit that minimal set or
explicitly declare only the narrower permissions they require, while the job
that runs update-openapi gets the larger permission set.

In `@api-reference/introduction.mdx`:
- Line 10: Replace the raw URL visible text with a descriptive anchor label:
update the link in api-reference/introduction.mdx so the href remains
https://fish.audio/app/api-keys/ but the visible text becomes something like
"API Keys page" (or similar descriptive text) to improve readability and
usability while keeping the target URL unchanged.

In `@package.json`:
- Line 12: The "validate" npm script currently runs "update:openapi && mint
validate", which fetches from the network and overwrites the local schema before
validation; split this into two scripts so validation is non-mutating: keep a
script named "validate" that runs only "mint validate" (so it can run offline
and won't overwrite local files) and add a separate script like
"refresh:openapi" (or "update:openapi:remote") that runs "update:openapi" to
fetch and overwrite the schema when explicitly requested; update any CI or docs
to call the appropriate script (validate vs refresh:openapi) instead of the
combined command.

In `@scripts/update-openapi.mjs`:
- Around line 24-25: Wrap the JSON.parse(rawSchema) call in a try/catch and
surface a richer error that includes the response URL and status (use
response.url and response.status) plus a short excerpt of rawSchema; replace the
current direct assignment to schema with code that attempts schema =
JSON.parse(rawSchema) inside the try, and in the catch throw or log a new Error
that combines a descriptive message like "Failed to parse JSON from
<response.url> (status: <response.status>): <snippet>" so CI failures show the
upstream URL/status and a bit of the non-JSON payload for debugging.
- Around line 10-22: The fetch in main() that downloads schemaUrl using
fetchTimeoutMs should be made resilient with a bounded retry loop (2–3 attempts)
and exponential backoff: wrap the fetch call in a for-loop, on each attempt
recreate the AbortSignal.timeout(fetchTimeoutMs), catch network errors (fetch
throws) and treat HTTP 5xx (response.status >= 500) as retryable, sleeping an
increasing delay (e.g., 200ms, 400ms, 800ms) between retries; return the
successful response when response.ok is true and, after exhausting attempts,
throw the original or last error as before. Use the existing symbols main(),
schemaUrl, fetchTimeoutMs and check response.ok/response.status to implement
this logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 30bebddc-d9e4-48f7-a1bc-72e94b0e231f

📥 Commits

Reviewing files that changed from the base of the PR and between 72f03d8 and 274812a.

📒 Files selected for processing (6)
  • .github/workflows/openapi-schema.yaml
  • README.md
  • api-reference/introduction.mdx
  • api-reference/openapi.json
  • package.json
  • scripts/update-openapi.mjs

Comment on lines +13 to +34
check-openapi:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- uses: actions/setup-node@v6
with:
node-version: 20
cache: npm

- run: npm ci

- name: Pull latest OpenAPI schema
run: npm run update:openapi

- name: Validate OpenAPI schema
run: npm run check:openapi

- name: Ensure committed schema is current
run: git diff --exit-code -- api-reference/openapi.json
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

PR check can fail for contributors who didn't touch the schema.

This job re-fetches the upstream schema on every PR and blocks on git diff --exit-code. If the upstream spec changes between the last auto-update merge and a contributor's PR, unrelated PRs will start failing CI with a confusing diff in api-reference/openapi.json that the contributor cannot reasonably fix themselves.

Options to soften this:

  • Only enforce git diff --exit-code when the PR actually modifies api-reference/openapi.json (use dorny/paths-filter or git diff against base).
  • Let the scheduled update-openapi job be the sole source of truth and keep the PR job as check:openapi only (no refresh, no diff gate).
  • Treat the diff step as a warning (continue-on-error: true) and rely on the nightly update PR to reconcile.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/openapi-schema.yaml around lines 13 - 34, The
check-openapi job refreshes the upstream schema with npm run update:openapi and
then always runs git diff --exit-code -- api-reference/openapi.json, which
causes unrelated PRs to fail if the upstream schema changed; change the workflow
so the strict git diff gate only runs when the PR actually modifies
api-reference/openapi.json (e.g., add a pre-step using dorny/paths-filter or run
git diff --name-only against the PR base vs head and set a conditional on the
step), or remove the update step and run only npm run check:openapi in PRs while
leaving updates to the scheduled job; update the step that runs git diff
--exit-code -- api-reference/openapi.json to be conditional (only when the path
filter detects changes) or to use continue-on-error: true depending on the
chosen option.

process.env.OPENAPI_SCHEMA_URL ?? "https://api.fish.audio/openapi.json";
const outputPath =
process.env.OPENAPI_OUTPUT_PATH ?? "api-reference/openapi.json";
const fetchTimeoutMs = Number(process.env.OPENAPI_FETCH_TIMEOUT_MS ?? 30000);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Guard against non-numeric / non-positive OPENAPI_FETCH_TIMEOUT_MS.

Number("abc") === NaN and AbortSignal.timeout(NaN) throws RangeError. Likewise a 0 or negative value would abort immediately. Validate and fall back to the default with a clear error instead of surfacing a cryptic stack trace.

🛡️ Proposed change
-const fetchTimeoutMs = Number(process.env.OPENAPI_FETCH_TIMEOUT_MS ?? 30000);
+const rawTimeout = process.env.OPENAPI_FETCH_TIMEOUT_MS;
+const parsedTimeout = rawTimeout === undefined ? 30000 : Number(rawTimeout);
+if (!Number.isFinite(parsedTimeout) || parsedTimeout <= 0) {
+  throw new Error(
+    `Invalid OPENAPI_FETCH_TIMEOUT_MS: ${rawTimeout!r ?? rawTimeout}`
+  );
+}
+const fetchTimeoutMs = parsedTimeout;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/update-openapi.mjs` at line 8, Validate OPENAPI_FETCH_TIMEOUT_MS
before using it: replace the raw Number(process.env.OPENAPI_FETCH_TIMEOUT_MS ??
30000) assignment for fetchTimeoutMs with logic that parses the env var, checks
Number.isFinite(value) and value > 0, and if invalid (NaN, non-finite, <= 0)
fall back to the default 30000 (or set a safe minimum) while logging or throwing
a clear error message; update any use of AbortSignal.timeout(fetchTimeoutMs) to
rely on this validated fetchTimeoutMs to avoid RangeError.

@Kilerd Kilerd merged commit b5bdc5e into main Apr 24, 2026
6 checks passed
@Kilerd Kilerd deleted the codex/openapi-schema-agent-context branch April 24, 2026 08:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant