Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(api): publish a minimized semantic tool resource and emit OpenAPI 3.0.3

[._.]/ Adam Eivyf3d424a819d3
diff --git a/README.md b/README.md
index d1b60cb1c5..29faee432d 100644
--- a/README.md
+++ b/README.md
@@ -237,7 +237,7 @@ Everything you need to manage your dev environment without leaving the browser.
- **Flows** — Rendered architecture/data-flow diagrams of how PortOS subsystems and integrations actually connect
- **Video Downloader** — Pull clips from YouTube/X via `yt-dlp` into the media library
- **Local LLM Playground** — Side-by-side comparison of local Ollama/LM Studio models with TTFT and tokens/sec
-- **API Explorer** — Searchable complete HTTP and Socket.IO inventories, rendered OpenAPI 3.1, AsyncAPI 3, and governed agent-tool contracts; external TTS/image exposure remains explicitly gated
+- **API Explorer** — Searchable complete HTTP and Socket.IO inventories, rendered OpenAPI 3.0.3, AsyncAPI 3, and governed agent-tool contracts; external TTS/image exposure remains explicitly gated
- **Templates** — Scaffold new apps from pre-built templates wired up to your AI providers
- **Review Hub** — Single inbox for actionable items (CoS approvals, alerts, todos, briefings) across every PortOS subsystem
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 0abd8ad5e5..d5cd8db183 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -84,7 +84,7 @@ export const getAiAssignments = (options) => request('/settings/ai-assignments',
// the peer-facing status endpoint only ever reports already-shared models.
export const getMediaShareCandidates = (options) => request('/settings/media-share-candidates', options);
-// API Access — the OpenAPI 3.1 spec for the public API surface (built from the
+// API Access — the OpenAPI 3.0.3 spec for the public API surface (built from the
// exposed entries in apiAccess settings). Rendered by the API Access settings tab.
export const getOpenApiSpec = (options) => request('/api-docs/openapi.json', options);
export const getInternalOpenApiSpec = (options) => request('/api-docs/internal/openapi.json', options);
diff --git a/docs/API.md b/docs/API.md
index 8d3d248dab..a9da69605d 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -18,14 +18,15 @@ the shipped semantic registry, MCP context/action schemas, authority matrix,
and the current-vs-proposed boundary.
- `GET /api/api-docs/catalog.json` — searchable metadata for every mounted HTTP operation.
-- `GET /api/api-docs/internal/openapi.json` — OpenAPI 3.1 for the complete internal HTTP surface.
-- `GET /api/api-docs/openapi.json` — OpenAPI 3.1 for only the external APIs currently exposed in Settings.
+- `GET /api/api-docs/internal/openapi.json` — OpenAPI 3.0.3 for the complete internal HTTP surface.
+- `GET /api/api-docs/openapi.json` — OpenAPI 3.0.3 for only the external APIs currently exposed in Settings.
- `GET /api/api-docs/events.json` — searchable Socket.IO event inventory.
- `GET /api/api-docs/asyncapi.json` — AsyncAPI 3 for the Socket.IO transport.
+- `GET /api/api-docs/tools.min.json` — the minimized semantic tool resource: only the operations annotated `x-portos-tool`, flattened to provider-neutral tool records with an HTTP binding. Sized for an agent to read whole, unlike the full internal document.
Generated entries are explicitly marked `generated` until a runtime-backed payload contract exists; detailed entries are marked `modeled`. Regenerate the checked-in route and event manifests with `npm run generate:api-docs`. Drift tests fail when source declarations and committed manifests diverge.
-When adding an HTTP route, keep its request Zod schema in a reusable server library and register the detailed documentation in `server/lib/apiOperationContracts.js`; the route and OpenAPI should consume the same schema object. Socket payload schemas follow the same pattern in `server/lib/socketEventContracts.js`. The generators guarantee inventory coverage, while these small registries make richer contracts incremental without maintaining a second handwritten list of paths or events.
+When adding an HTTP route, keep its request Zod schema in a reusable server library and register the detailed documentation in `server/lib/apiOperationContracts.js`; the route and OpenAPI should consume the same schema object. Add an `x-portos-tool` annotation to that contract entry to also publish the operation as an agent-callable tool in `tools.min.json`, and declare the codes its error responses really throw in `x-portos-error-codes` — the HTTP status alone does not identify the code, since `errorHandler` prefers an explicit `err.code` over the status map. Socket payload schemas follow the same pattern in `server/lib/socketEventContracts.js`. The generators guarantee inventory coverage, while these small registries make richer contracts incremental without maintaining a second handwritten list of paths or events.
Building a native companion client? See [COMPANION_APP_API.md](./COMPANION_APP_API.md) — the stable, pre-auth-discoverable contract (discovery/identity, HTTP Basic auth, instance management, palette actions, daily-log, POST progress, and the iCloud-sync precedent) that the PortDeck app consumes.
@@ -587,7 +588,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/lmstudio`, `/api/local-llm` | Local LLM backends and the local runtime servers PortOS can start/stop (Ollama, LM Studio, `llama-server`, MTPLX — the last two as PM2 processes; `POST /api/local-llm/save-startup` is `pm2 save`), plus MTPLX's checkpoint catalog — `GET /api/local-llm/mtplx/models/search`, `POST .../models/pull` (byte progress on the `mtplx:download` socket event), `POST .../models/remove` |
| `/api/code-review` | Code review runs |
| `/api/voice`, `/api/voice/public` | Voice assistant |
-| `/api/api-docs` | Generated HTTP/event catalogs, OpenAPI 3.1 documents, and AsyncAPI 3 document |
+| `/api/api-docs` | Generated HTTP/event catalogs, OpenAPI 3.0.3 documents, AsyncAPI 3 document, and the minimized semantic tool resource |
| `/api/data` | Data manager/sync |
| `/api/datadog`, `/api/jira`, `/api/github`, `/api/telegram` | External integrations |
| `/api/health` | Health check |
diff --git a/server/lib/README.md b/server/lib/README.md
index 901e92c081..8404a89498 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -24,7 +24,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `appDeployFlags.js` | Shared allowlist of flags PortOS may forward to a managed app's `deploy.sh`, consumed by socket validation and deployment orchestration without reversing the lib/services dependency. |
-| `apiContractSchemas.js` | Canonical Zod request contracts for externally callable APIs plus `zodToOpenApiSchema`; runtime routes and OpenAPI use the same schema objects. |
+| `apiContractSchemas.js` | Canonical Zod request contracts for externally callable APIs plus `zodToOpenApiSchema` (plain JSON Schema — the 3.0.3 conversion happens at the OpenAPI document boundary, not here); runtime routes and OpenAPI use the same schema objects. |
| `socketEventContracts.js` | Runtime-backed payload contracts for modeled inbound Socket.IO events, reusing the same Zod schemas as live validation. |
| `agentContextValidation.js` | Shared settings, MCP request/tool input/output schemas, result + approximate-token bounds, source-freshness status, and `advertiseAgentContextTools(scopes)` for the opt-in read-only agent-context surface. |
| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parseIndexParam`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |
@@ -426,7 +426,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. |
| `markedSection.js` | Marker-delimited section replacement (pure). `buildMarkers(id)` → `{ start, end }` HTML-comment marker pair; `replaceMarkedSection(content, body, markers)` splices/replaces/removes an auto-generated region without touching surrounding user content (idempotent); `extractMarkedSection` / `hasMarkedSection` read it back. Powers the daily-log activity-digest auto-drafts (#2155) via `brainJournal.upsertAutoSection()`. |
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
-| `openapiSpec.js` | Builds two OpenAPI 3.1 documents: the Settings-controlled exposed public surface and the complete internal HTTP inventory. Detailed operations reuse canonical Zod contracts; generated operations are visibly labeled rather than claiming unmodeled schemas. |
+| `openapiSpec.js` | Builds two OpenAPI 3.0.3 documents: the Settings-controlled exposed public surface and the complete internal HTTP inventory. Detailed operations reuse canonical Zod contracts; generated operations are visibly labeled rather than claiming unmodeled schemas. |
+| `openapiDowngrade.js` | `OPENAPI_VERSION` plus `toOpenApi30Schema` / `toOpenApi30Operation`, which rewrite Zod's draft-2020-12 output (null unions, numeric exclusive bounds, `const`, tuples, `propertyNames`) into the OpenAPI 3.0.3 dialect. Apply ONLY at the OpenAPI document boundary — the AsyncAPI payloads, CoS provider tool definitions, and tool resource read the same schemas as plain JSON Schema, where these rewrites silently widen bounds and drop null branches. |
+| `apiToolResource.js` | Builds the minimized semantic tool resource served at `/api/api-docs/tools.min.json` — only `x-portos-tool`-annotated operations, flattened to provider-neutral tool records with an HTTP binding and a shared error vocabulary. |
| `asyncApiSpec.js` | Builds the AsyncAPI 3 Socket.IO document from the generated event catalog with direction-aware operations and explicit modeled/generated payload status. |
| `prDisposition.js` | `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOwnsPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. |
| `repoStateExpectations.js` | Post-completion repo-state audit, pure half. `resolveRepoStateExpectation({...})` answers whether one finished worktree agent should be audited — naming every not-audited path via `REPO_STATE_SKIPS` (a failed run is preserved for its retry; a review-loop follow-up or pr-watcher pending merge still owns the branch) — and returns just `staysOpen` + `prExpected`, from which `classifyRepoStateIssues(expectation, observed)` derives every check into `REPO_STATE_ISSUES` codes. Observations are tri-state: `null` ("could not ask") never produces an issue. `repoStateVerificationEnabled(app)` reads the per-app `verifyRepoStateOnCompletion` switch (unset = on). Probing + remediation live in `services/agentRepoStateVerification.js`. |
diff --git a/server/lib/apiContractSchemas.js b/server/lib/apiContractSchemas.js
index 9684e9740b..7f93106fb7 100644
--- a/server/lib/apiContractSchemas.js
+++ b/server/lib/apiContractSchemas.js
@@ -28,6 +28,15 @@ export const sdapiTxt2imgBodySchema = z.object({
sd_model_checkpoint: z.string().max(128).optional(),
}).passthrough();
+/**
+ * Convert a Zod contract to plain JSON Schema (draft 2020-12, minus `$schema`).
+ *
+ * Stays JSON Schema on purpose. Consumers that need it are the AsyncAPI
+ * document's `payload`, the CoS provider tool definitions, and the semantic
+ * tool resource — all JSON Schema dialects. The OpenAPI 3.0.3 documents convert
+ * at their own boundary via `toOpenApi30Operation`; doing it here instead
+ * silently corrupts the other three (see `openapiDowngrade.js`).
+ */
export const zodToOpenApiSchema = (schema) => {
const jsonSchema = z.toJSONSchema(schema);
delete jsonSchema.$schema;
diff --git a/server/lib/apiOperationContracts.js b/server/lib/apiOperationContracts.js
index 6dbad36f2b..36d3a0a73f 100644
--- a/server/lib/apiOperationContracts.js
+++ b/server/lib/apiOperationContracts.js
@@ -15,10 +15,10 @@ const jsonBody = (schema, required = true) => ({
export const API_OPERATION_CONTRACTS = Object.freeze({
'/api/api-docs/openapi.json': {
- get: { summary: 'Read exposed OpenAPI document', responses: { 200: { description: 'OpenAPI 3.1 document for currently exposed external APIs' } } },
+ get: { summary: 'Read exposed OpenAPI document', responses: { 200: { description: 'OpenAPI 3.0.3 document for currently exposed external APIs' } } },
},
'/api/api-docs/internal/openapi.json': {
- get: { summary: 'Read complete internal OpenAPI document', responses: { 200: { description: 'OpenAPI 3.1 document for every mounted HTTP operation' } } },
+ get: { summary: 'Read complete internal OpenAPI document', responses: { 200: { description: 'OpenAPI 3.0.3 document for every mounted HTTP operation' } } },
},
'/api/api-docs/catalog.json': {
get: { summary: 'Read HTTP API catalog', responses: { 200: { description: 'Searchable generated HTTP operation metadata and coverage' } } },
@@ -29,6 +29,9 @@ export const API_OPERATION_CONTRACTS = Object.freeze({
'/api/api-docs/asyncapi.json': {
get: { summary: 'Read AsyncAPI document', responses: { 200: { description: 'AsyncAPI 3 document for the Socket.IO transport' } } },
},
+ '/api/api-docs/tools.min.json': {
+ get: { summary: 'Read minimized semantic tool resource', responses: { 200: { description: 'Schema-optimized provider-neutral tool resource' } } },
+ },
'/api/agent-context/manifest': {
get: { summary: 'Read local Agent Tools MCP manifest', responses: { 200: { description: 'MCP transport, context scopes, semantic grants, schemas, and limits' } } },
},
@@ -47,7 +50,11 @@ export const API_OPERATION_CONTRACTS = Object.freeze({
requestBody: jsonBody(voiceSynthesizeBodySchema),
responses: {
200: { description: 'WAV audio', content: { 'audio/wav': { schema: { type: 'string', format: 'binary' } } } },
- 400: { description: 'Invalid payload or unknown voice' },
+ 400: { description: 'Invalid payload or unknown voice', 'x-portos-error-codes': ['VALIDATION_ERROR'] },
+ },
+ 'x-portos-tool': {
+ name: 'voice.synthesize', version: 1,
+ policy: { privacy: 'personal', sideEffect: 'local-compute', async: false },
},
},
},
@@ -56,14 +63,16 @@ export const API_OPERATION_CONTRACTS = Object.freeze({
summary: 'List voices',
description: 'Enumerate available voices for an engine. Defaults to the active engine.',
parameters: [{ name: 'engine', in: 'query', required: false, schema: { type: 'string', enum: ['kokoro', 'piper'] } }],
- responses: { 200: { description: 'Voice list' } },
+ responses: { 200: { description: 'Voice list', content: { 'application/json': { schema: { type: 'object' } } } } },
+ 'x-portos-tool': { name: 'voice.list-voices', version: 1, policy: { privacy: 'internal', sideEffect: 'read', async: false } },
},
},
'/api/voice/public/engines': {
get: {
summary: 'List engines',
description: 'Discover available TTS engines and the configured default voice per engine.',
- responses: { 200: { description: 'Engine list and defaults' } },
+ responses: { 200: { description: 'Engine list and defaults', content: { 'application/json': { schema: { type: 'object' } } } } },
+ 'x-portos-tool': { name: 'voice.list-engines', version: 1, policy: { privacy: 'internal', sideEffect: 'read', async: false } },
},
},
'/sdapi/v1/txt2img': {
@@ -73,19 +82,37 @@ export const API_OPERATION_CONTRACTS = Object.freeze({
requestBody: jsonBody(sdapiTxt2imgBodySchema),
responses: {
200: { description: 'Generated images in AUTOMATIC1111 response format' },
- 400: { description: 'Invalid generation payload' },
+ 400: { description: 'Invalid generation payload', 'x-portos-error-codes': ['VALIDATION_ERROR'] },
403: { description: 'A1111 API exposure is disabled' },
+ 500: { description: 'Generation failed or its output could not be read', 'x-portos-error-codes': ['GEN_FAILED', 'GEN_OUTPUT_MISSING'] },
+ 504: { description: 'Generation timed out', 'x-portos-error-codes': ['GEN_TIMEOUT'] },
+ },
+ 'x-portos-tool': {
+ name: 'image.generate', version: 1,
+ policy: { privacy: 'personal', sideEffect: 'local-compute', async: true },
},
},
},
'/sdapi/v1/sd-models': {
- get: { summary: 'List image models', responses: { 200: { description: 'Model catalog' } } },
+ get: {
+ summary: 'List image models',
+ responses: { 200: { description: 'Model catalog', content: { 'application/json': { schema: { type: 'array', items: { type: 'object' } } } } } },
+ 'x-portos-tool': { name: 'image.list-models', version: 1, policy: { privacy: 'internal', sideEffect: 'read', async: false } },
+ },
},
'/sdapi/v1/samplers': {
- get: { summary: 'List samplers', responses: { 200: { description: 'Sampler list' } } },
+ get: {
+ summary: 'List samplers',
+ responses: { 200: { description: 'Sampler list', content: { 'application/json': { schema: { type: 'array', items: { type: 'object' } } } } } },
+ 'x-portos-tool': { name: 'image.list-samplers', version: 1, policy: { privacy: 'internal', sideEffect: 'read', async: false } },
+ },
},
'/sdapi/v1/options': {
- get: { summary: 'Read active image options', responses: { 200: { description: 'Active model and options' } } },
+ get: {
+ summary: 'Read active image options',
+ responses: { 200: { description: 'Active model and options', content: { 'application/json': { schema: { type: 'object' } } } } },
+ 'x-portos-tool': { name: 'image.get-options', version: 1, policy: { privacy: 'internal', sideEffect: 'read', async: false } },
+ },
post: {
summary: 'Acknowledge image options',
description: 'Compatibility endpoint. PortOS does not switch its underlying model from this request.',
@@ -93,7 +120,11 @@ export const API_OPERATION_CONTRACTS = Object.freeze({
},
},
'/sdapi/v1/progress': {
- get: { summary: 'Read generation progress', responses: { 200: { description: 'Current generation progress or idle state' } } },
+ get: {
+ summary: 'Read generation progress',
+ responses: { 200: { description: 'Current generation progress or idle state', content: { 'application/json': { schema: { type: 'object' } } } } },
+ 'x-portos-tool': { name: 'image.get-progress', version: 1, policy: { privacy: 'internal', sideEffect: 'read', async: false } },
+ },
},
'/sdapi/v1/portos/video-models': {
get: { summary: 'List PortOS video models', responses: { 200: { description: 'Video model catalog and default' } } },
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index ac59471c3d..2f8837b210 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -1057,7 +1057,7 @@
"sources": [
{
"source": "server/routes/apiDocs.js",
- "line": 57
+ "line": 60
}
]
},
@@ -1068,7 +1068,7 @@
"sources": [
{
"source": "server/routes/apiDocs.js",
- "line": 47
+ "line": 50
}
]
},
@@ -1079,7 +1079,7 @@
"sources": [
{
"source": "server/routes/apiDocs.js",
- "line": 52
+ "line": 55
}
]
},
@@ -1090,7 +1090,7 @@
"sources": [
{
"source": "server/routes/apiDocs.js",
- "line": 41
+ "line": 44
}
]
},
@@ -1101,7 +1101,18 @@
"sources": [
{
"source": "server/routes/apiDocs.js",
- "line": 35
+ "line": 38
+ }
+ ]
+ },
+ {
+ "method": "GET",
+ "path": "/api/api-docs/tools.min.json",
+ "mountPath": "/api/api-docs",
+ "sources": [
+ {
+ "source": "server/routes/apiDocs.js",
+ "line": 66
}
]
},
@@ -22927,8 +22938,8 @@
],
"stats": {
"mounts": 145,
- "operations": 2068,
- "declarations": 2071,
+ "operations": 2069,
+ "declarations": 2072,
"sourceFiles": 224
}
}
diff --git a/server/lib/apiToolResource.js b/server/lib/apiToolResource.js
new file mode 100644
index 0000000000..6410bc090b
--- /dev/null
+++ b/server/lib/apiToolResource.js
@@ -0,0 +1,188 @@
+/**
+ * Minimized semantic tool resource for PortOS's HTTP surface.
+ *
+ * The internal OpenAPI document describes every one of the ~2000 mounted
+ * operations, which is the wrong shape (and far too large) to hand an agent
+ * that just wants to know what it can call. This builds the small counterpart:
+ * only the operations that opted in with an `x-portos-tool` annotation, flattened
+ * from an OpenAPI operation into one provider-neutral tool record with an
+ * explicit HTTP binding.
+ *
+ * "Minimized" is about document overhead, not semantics — the OpenAPI envelope,
+ * per-response prose, security schemes, and source annotations are dropped, and
+ * the shared error vocabulary is hoisted to a single top-level `errors` list
+ * instead of being repeated per operation. Property-level `description`s are
+ * KEPT: they are what lets a model pick arguments correctly.
+ *
+ * Deliberately parallel to `services/cosToolRegistry.js`, which publishes the
+ * in-process CoS tool catalog. Same `portos_tool` entry vocabulary
+ * (`name` / `version` / `providerName` / `input_schema` / `output_schema` /
+ * `policy`) so an agent reads one shape across both surfaces; this one adds
+ * `binding` because these tools are called over HTTP rather than in-process.
+ */
+
+import { pathParametersFor } from './apiCatalog.js';
+import { API_OPERATION_CONTRACTS } from './apiOperationContracts.js';
+import { providerToolName } from './cosToolContracts.js';
+import { ERROR_CODES_BY_STATUS } from './errorHandler.js';
+import { OPENAPI_VERSION } from './openapiDowngrade.js';
+
+export const TOOL_RESOURCE_TYPE = 'portos_tool_resource';
+
+const OBJECT_OUTPUT_SCHEMA = Object.freeze({ type: 'object', additionalProperties: true });
+
+// Query/header/path parameters become ordinary input properties so a caller
+// sees one argument object instead of an OpenAPI parameter list.
+const parametersToSchema = (parameters = []) => {
+ const properties = {};
+ const required = [];
+ for (const parameter of parameters) {
+ if (!parameter?.name || !parameter.schema) continue;
+ properties[parameter.name] = parameter.description
+ ? { ...parameter.schema, description: parameter.description }
+ : parameter.schema;
+ if (parameter.required === true) required.push(parameter.name);
+ }
+ return { properties, required };
+};
+
+const jsonSchemaOf = (payload) => payload?.content?.['application/json']?.schema;
+
+/**
+ * Merge an operation's request body and parameters into one argument schema.
+ * A body that isn't an object (or isn't JSON at all) can't be merged with
+ * parameters, so it is exposed under an explicit `body` property rather than
+ * being silently flattened.
+ */
+const inputSchemaFor = (operation, path) => {
+ // Path parameters are as required as body fields — a tool missing them is
+ // uncallable. `pathParametersFor` is the same helper the OpenAPI builder uses.
+ const { properties, required } = parametersToSchema([
+ ...pathParametersFor(path),
+ ...(operation.parameters ?? []),
+ ]);
+ const body = jsonSchemaOf(operation.requestBody);
+ const bodyIsObject = body?.type === 'object';
+ const bodyIsRequired = operation.requestBody?.required !== false;
+
+ // An object body flattens into the argument object; anything else (an array,
+ // a binary upload) can't merge with parameters and stays under `body`.
+ const bodyProperties = bodyIsObject ? (body.properties ?? {}) : (body ? { body } : {});
+ const bodyRequiredNames = !bodyIsRequired ? [] : bodyIsObject ? (body.required ?? []) : (body ? ['body'] : []);
+ const allRequired = [...new Set([...required, ...bodyRequiredNames])];
+
+ // A body field and a parameter sharing a name would collapse into one
+ // property, silently dropping the parameter's constraint and leaving the
+ // caller no way to address it. Refuse at build time rather than publish an
+ // ambiguous tool. Unreachable from the contracts registered today.
+ const collision = Object.keys(bodyProperties).find((name) => name in properties);
+ if (collision) {
+ throw new Error(`Tool argument collision on "${collision}": a request-body field shadows a parameter of the same name.`);
+ }
+
+ return {
+ type: 'object',
+ properties: { ...properties, ...bodyProperties },
+ ...(allRequired.length > 0 ? { required: allRequired } : {}),
+ // `additionalProperties` rides along from a passthrough body contract (the
+ // A1111 txt2img schema is deliberately open); closed otherwise so a model
+ // doesn't invent arguments.
+ additionalProperties: bodyIsObject ? (body.additionalProperties ?? false) : false,
+ };
+};
+
+/**
+ * Describe the success payload. A modeled `application/json` 200 wins; a
+ * non-JSON 200 (the WAV synthesize response) is reported by media type so a
+ * caller knows not to parse it as JSON.
+ */
+const outputSchemaFor = (operation) => {
+ const success = operation.responses?.[200];
+ const json = jsonSchemaOf(success);
+ if (json) return json;
+ const mediaType = Object.keys(success?.content ?? {})[0];
+ if (mediaType) return { type: 'string', format: 'binary', 'x-portos-media-type': mediaType };
+ return OBJECT_OUTPUT_SCHEMA;
+};
+
+/**
+ * The failures an operation declares, as `{ status, code }` pairs.
+ *
+ * A status does NOT determine the code: `errorHandler` uses
+ * `err.code || getErrorCode(status)`, so a route that passes an explicit code
+ * (most do) emits something the status map would never produce — PortOS throws
+ * `VALIDATION_ERROR` at 400, where the map says `BAD_REQUEST`. The contract
+ * therefore declares the real codes in `x-portos-error-codes`, and the status
+ * map is only the fallback for a response that didn't. One status can carry
+ * several codes, so each pair gets its own entry.
+ */
+const failuresFor = (operation) => Object.entries(operation.responses ?? {})
+ .map(([status, response]) => [Number(status), response])
+ .filter(([status]) => Number.isFinite(status) && status >= 400)
+ .sort(([a], [b]) => a - b)
+ .flatMap(([status, response]) => {
+ const declared = response?.['x-portos-error-codes'];
+ const codes = Array.isArray(declared) && declared.length > 0
+ ? declared
+ : [ERROR_CODES_BY_STATUS[status] ?? 'INTERNAL_ERROR'];
+ return codes.map((code) => ({ status, code }));
+ });
+
+const toolFor = ({ path, method, operation }) => {
+ const annotation = operation['x-portos-tool'];
+ const failures = failuresFor(operation);
+ return {
+ type: 'portos_tool',
+ name: annotation.name,
+ version: annotation.version,
+ providerName: providerToolName(annotation.name),
+ description: operation.description || operation.summary,
+ input_schema: inputSchemaFor(operation, path),
+ output_schema: outputSchemaFor(operation),
+ policy: {
+ ...annotation.policy,
+ idempotent: annotation.policy?.sideEffect === 'read',
+ },
+ binding: { protocol: 'http', method: method.toUpperCase(), path },
+ ...(failures.length > 0 ? { failures } : {}),
+ };
+};
+
+/** Every contract operation carrying an `x-portos-tool` annotation, in declaration order. */
+const annotatedOperations = () => Object.entries(API_OPERATION_CONTRACTS).flatMap(
+ ([path, pathItem]) => Object.entries(pathItem)
+ .filter(([, operation]) => operation['x-portos-tool'])
+ .map(([method, operation]) => ({ path, method, operation })),
+);
+
+/**
+ * Build the minimized semantic tool resource.
+ *
+ * Independent of Settings > API Access on purpose: like the internal OpenAPI
+ * document, this describes the annotated surface itself. Whether a given tool
+ * is currently reachable is enforced at call time by the API registry, not by
+ * hiding it from the catalog — an agent that can't see a tool can't be told
+ * why its call was refused.
+ */
+export const buildToolResource = ({ version = '0.0.0' } = {}) => {
+ const tools = annotatedOperations().map(toolFor);
+ return {
+ type: TOOL_RESOURCE_TYPE,
+ schemaVersion: 1,
+ portosVersion: version,
+ // Where the tools come from, and how to read their schemas — the two are
+ // deliberately different. The operations are the ones the 3.0.3 document
+ // publishes, but `input_schema`/`output_schema` stay plain JSON Schema
+ // because that is what a provider tool definition takes; a 3.0.3 `nullable`
+ // would be an unknown keyword there and the null branch would be lost.
+ source: { document: 'openapi', version: OPENAPI_VERSION },
+ schemaDialect: 'https://json-schema.org/draft/2020-12/schema',
+ tools,
+ errors: Object.entries(ERROR_CODES_BY_STATUS).map(([status, code]) => ({ status: Number(status), code })),
+ stats: {
+ total: tools.length,
+ read: tools.filter((tool) => tool.policy.sideEffect === 'read').length,
+ write: tools.filter((tool) => tool.policy.sideEffect !== 'read').length,
+ },
+ };
+};
diff --git a/server/lib/apiToolResource.test.js b/server/lib/apiToolResource.test.js
new file mode 100644
index 0000000000..bd8886e93e
--- /dev/null
+++ b/server/lib/apiToolResource.test.js
@@ -0,0 +1,129 @@
+import { describe, it, expect } from 'vitest';
+import { buildToolResource, TOOL_RESOURCE_TYPE } from './apiToolResource.js';
+import { API_OPERATION_CONTRACTS } from './apiOperationContracts.js';
+import { ERROR_CODES_BY_STATUS } from './errorHandler.js';
+
+const resource = buildToolResource({ version: '9.9.9' });
+const byName = (name) => resource.tools.find((tool) => tool.name === name);
+
+describe('buildToolResource', () => {
+ it('declares the resource envelope and the source document version', () => {
+ expect(resource.type).toBe(TOOL_RESOURCE_TYPE);
+ expect(resource.schemaVersion).toBe(1);
+ expect(resource.portosVersion).toBe('9.9.9');
+ expect(resource.source).toEqual({ document: 'openapi', version: '3.0.3' });
+ });
+
+ it('publishes JSON Schema, not the 3.0.3 dialect, so the schemas work as provider tool definitions', () => {
+ expect(resource.schemaDialect).toBe('https://json-schema.org/draft/2020-12/schema');
+ // A 3.0.3 `nullable: true` is not a JSON Schema keyword — converting here
+ // would DROP the null branch and make a legal `null` argument invalid.
+ expect(byName('image.generate').input_schema.properties.negative_prompt)
+ .toEqual({ anyOf: [{ type: 'string', maxLength: 8000 }, { type: 'null' }] });
+ });
+
+ it('includes exactly the operations carrying an x-portos-tool annotation', () => {
+ const annotated = Object.values(API_OPERATION_CONTRACTS)
+ .flatMap((pathItem) => Object.values(pathItem))
+ .filter((operation) => operation['x-portos-tool']);
+ expect(resource.tools).toHaveLength(annotated.length);
+ expect(resource.tools.map((tool) => tool.name).sort())
+ .toEqual(annotated.map((operation) => operation['x-portos-tool'].name).sort());
+ });
+
+ it('is not filtered by API exposure settings', () => {
+ // The registry enforces reachability at call time; hiding a tool here would
+ // leave an agent unable to learn why its call was refused.
+ expect(buildToolResource().tools).toHaveLength(resource.tools.length);
+ });
+
+ it('binds each tool to its HTTP method and path', () => {
+ expect(byName('voice.synthesize').binding)
+ .toEqual({ protocol: 'http', method: 'POST', path: '/api/voice/public/synthesize' });
+ expect(byName('image.list-models').binding)
+ .toEqual({ protocol: 'http', method: 'GET', path: '/sdapi/v1/sd-models' });
+ });
+
+ it('derives a snake_case provider name from the dotted canonical name', () => {
+ expect(byName('image.list-models').providerName).toBe('image_list_models');
+ expect(byName('voice.synthesize').providerName).toBe('voice_synthesize');
+ });
+
+ it('flattens an object request body into the argument schema and keeps property descriptions', () => {
+ const input = byName('voice.synthesize').input_schema;
+ expect(input.required).toEqual(['text']);
+ expect(input.properties.engine.enum).toEqual(['kokoro', 'piper']);
+ // The description is what lets a model pick a valid rate — minimization must not strip it.
+ expect(input.properties.rate.description).toMatch(/Speech rate/);
+ expect(input.additionalProperties).toBe(false);
+ });
+
+ it('turns query parameters into input properties', () => {
+ const input = byName('voice.list-voices').input_schema;
+ expect(input.properties.engine).toEqual({ type: 'string', enum: ['kokoro', 'piper'] });
+ expect(input.required).toBeUndefined(); // the engine param is optional
+ });
+
+ it('preserves an open body contract rather than closing it', () => {
+ // sdapiTxt2imgBodySchema is .passthrough() for A1111 compatibility.
+ expect(byName('image.generate').input_schema.additionalProperties).not.toBe(false);
+ });
+
+ it('reports a non-JSON success payload by media type instead of claiming JSON', () => {
+ expect(byName('voice.synthesize').output_schema)
+ .toEqual({ type: 'string', format: 'binary', 'x-portos-media-type': 'audio/wav' });
+ });
+
+ it('uses the modeled JSON response schema when the contract has one', () => {
+ expect(byName('image.list-models').output_schema).toEqual({ type: 'array', items: { type: 'object' } });
+ });
+
+ it('falls back to an open object when no success payload is modeled', () => {
+ expect(byName('image.generate').output_schema).toEqual({ type: 'object', additionalProperties: true });
+ });
+
+ it('publishes the error code a route actually throws, not one derived from the status', () => {
+ // errorHandler resolves `err.code || getErrorCode(status)`, and both write
+ // routes pass an explicit code — so a status-derived guess would publish
+ // BAD_REQUEST for a 400 that really reports VALIDATION_ERROR.
+ expect(byName('voice.synthesize').failures).toEqual([{ status: 400, code: 'VALIDATION_ERROR' }]);
+ });
+
+ it('emits one entry per code when a status carries several', () => {
+ expect(byName('image.generate').failures).toEqual([
+ { status: 400, code: 'VALIDATION_ERROR' },
+ { status: 403, code: 'FORBIDDEN' }, // undeclared: falls back to the status map
+ { status: 500, code: 'GEN_FAILED' },
+ { status: 500, code: 'GEN_OUTPUT_MISSING' },
+ { status: 504, code: 'GEN_TIMEOUT' },
+ ]);
+ });
+
+ it('omits failures entirely for a tool that declares no error responses', () => {
+ expect(byName('image.list-models').failures).toBeUndefined();
+ });
+
+ it('marks read tools idempotent and side-effecting tools not', () => {
+ expect(byName('image.list-models').policy).toMatchObject({ sideEffect: 'read', idempotent: true });
+ expect(byName('image.generate').policy).toMatchObject({ sideEffect: 'local-compute', idempotent: false, async: true });
+ });
+
+ it('publishes the full error vocabulary from the shared status map', () => {
+ expect(resource.errors).toEqual(
+ Object.entries(ERROR_CODES_BY_STATUS).map(([status, code]) => ({ status: Number(status), code })),
+ );
+ expect(resource.errors.some((error) => error.code === 'VALIDATION_ERROR')).toBe(true);
+ });
+
+ it('counts read versus side-effecting tools', () => {
+ expect(resource.stats.total).toBe(resource.tools.length);
+ expect(resource.stats.read + resource.stats.write).toBe(resource.tools.length);
+ });
+
+ it('stays smaller than the OpenAPI document it is derived from', async () => {
+ // The point of the resource is that an agent can read it whole.
+ const { buildInternalOpenApiSpec } = await import('./openapiSpec.js');
+ const internal = JSON.stringify(buildInternalOpenApiSpec({}, { version: '9.9.9' }));
+ expect(JSON.stringify(resource).length).toBeLessThan(internal.length / 100);
+ });
+});
diff --git a/server/lib/cosToolContracts.js b/server/lib/cosToolContracts.js
index 495f3f0dae..8e1378664e 100644
--- a/server/lib/cosToolContracts.js
+++ b/server/lib/cosToolContracts.js
@@ -31,6 +31,15 @@ export const normalizePortosSemanticToolGrants = (raw) => {
};
};
+/**
+ * The provider-facing name for a canonical dotted tool name. Model providers
+ * conventionally accept `[A-Za-z0-9_-]` function names, so `voice.list-voices`
+ * is published as `voice_list_voices`. Shared by both tool surfaces — the
+ * in-process CoS catalog and the HTTP tool resource — so the same tool never
+ * gets two different provider names.
+ */
+export const providerToolName = (name) => name.replaceAll('.', '_').replaceAll('-', '_');
+
export const cosToolRequestIdSchema = z.string()
.trim()
.min(1)
diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.js
index 08ea0eade2..cd528cd648 100644
--- a/server/lib/errorHandler.js
+++ b/server/lib/errorHandler.js
@@ -242,22 +242,31 @@ export function normalizeError(err) {
});
}
+/**
+ * The machine-readable error vocabulary PortOS speaks, keyed by HTTP status.
+ *
+ * Exported because it is a published contract, not just an internal lookup:
+ * the semantic tool resource (`apiToolResource.js`) advertises these codes to
+ * agent callers. Both read this object so the documented vocabulary and the
+ * codes routes actually emit cannot drift.
+ */
+export const ERROR_CODES_BY_STATUS = Object.freeze({
+ 400: 'BAD_REQUEST',
+ 401: 'UNAUTHORIZED',
+ 403: 'FORBIDDEN',
+ 404: 'NOT_FOUND',
+ 409: 'CONFLICT',
+ 422: 'VALIDATION_ERROR',
+ 500: 'INTERNAL_ERROR',
+ 502: 'BAD_GATEWAY',
+ 503: 'SERVICE_UNAVAILABLE',
+});
+
/**
* Get appropriate error code from HTTP status
*/
export function getErrorCode(status) {
- const codeMap = {
- 400: 'BAD_REQUEST',
- 401: 'UNAUTHORIZED',
- 403: 'FORBIDDEN',
- 404: 'NOT_FOUND',
- 409: 'CONFLICT',
- 422: 'VALIDATION_ERROR',
- 500: 'INTERNAL_ERROR',
- 502: 'BAD_GATEWAY',
- 503: 'SERVICE_UNAVAILABLE'
- };
- return codeMap[status] || 'INTERNAL_ERROR';
+ return ERROR_CODES_BY_STATUS[status] || 'INTERNAL_ERROR';
}
/**
diff --git a/server/lib/index.js b/server/lib/index.js
index 94fe8bdf9b..0e9ea6e012 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -405,6 +405,8 @@ export * from './markedSection.js';
export * from './mirrorParity.js';
export * from './objects.js';
export * from './openapiSpec.js';
+export * from './openapiDowngrade.js';
+export * from './apiToolResource.js';
export * from './prDisposition.js';
export * from './repoStateExpectations.js';
export * from './shellCd.js';
diff --git a/server/lib/openapiDowngrade.js b/server/lib/openapiDowngrade.js
new file mode 100644
index 0000000000..693d338b33
--- /dev/null
+++ b/server/lib/openapiDowngrade.js
@@ -0,0 +1,223 @@
+/**
+ * OpenAPI 3.0.3 compatibility for JSON Schema produced against draft 2020-12.
+ *
+ * PortOS publishes 3.0.3 rather than 3.1 because the documents are consumed by
+ * agent tooling (tool-schema converters, validators, generators) whose 3.1
+ * support is still thin, while 3.0.3 is universally understood. The gap is
+ * narrow but real: `zodToOpenApiSchema` emits draft 2020-12, which uses
+ * constructs 3.0.3 rejects outright. `toOpenApi30Schema` rewrites them so a
+ * document labeled 3.0.3 actually validates as 3.0.3.
+ *
+ * APPLY THIS ONLY AT THE OPENAPI DOCUMENT BOUNDARY (`openapiSpec.js`), never
+ * inside `zodToOpenApiSchema` itself. Three other surfaces consume that helper's
+ * output as ORDINARY JSON SCHEMA — the AsyncAPI document's `payload`, the CoS
+ * provider tool definitions, and the semantic tool resource — and these rewrites
+ * are wrong there. `exclusiveMinimum: true` is a draft-4 spelling that a JSON
+ * Schema validator reads as a type error and ignores, silently widening
+ * `value > 0` to `value >= 0`; `nullable: true` is not a JSON Schema keyword at
+ * all, so the null branch is simply lost. Both turn a correct contract into a
+ * quietly wrong one.
+ *
+ * Rewrites applied:
+ * - a `null` branch in `anyOf`/`oneOf` becomes `nullable: true` on the
+ * surviving branches (3.0 has no `null` type); a sole survivor is inlined,
+ * with the PARENT's keywords winning any collision so an inner constraint
+ * can't widen an outer one
+ * - `type: ['string', 'null']` and a bare `type: 'null'` collapse the same way
+ * - numeric `exclusiveMinimum`/`exclusiveMaximum` become the 3.0 boolean form
+ * paired with `minimum`/`maximum`
+ * - `const: x` becomes `enum: [x]`
+ * - `examples: [...]` becomes `example: examples[0]`
+ * - `prefixItems` (a tuple) becomes `items: { anyOf: [...] }` plus
+ * `minItems`/`maxItems`, preserving arity and member types even though 3.0.3
+ * cannot express positional typing
+ * - `$schema` and `propertyNames` (no 3.0 equivalent) are dropped
+ *
+ * `$ref`/`$defs` are REFUSED rather than mangled — see `assertNoReferences`.
+ */
+
+import { isPlainObject } from './objects.js';
+
+/** The OpenAPI version every PortOS-generated document declares. */
+export const OPENAPI_VERSION = '3.0.3';
+
+// A `null` union member, in either the pre-conversion (`{type:'null'}`) or
+// post-conversion (`{nullable:true}`) spelling — the second appears when a
+// nested branch was converted before its parent union was collapsed. Only a
+// BARE marker counts; a null branch carrying other keywords is left alone
+// rather than silently dropping those keywords.
+const isNullBranch = (branch) => isPlainObject(branch)
+ && Object.keys(branch).length === 1
+ && (branch.type === 'null' || branch.nullable === true);
+
+const collapseNullableUnion = (schema, keyword) => {
+ const branches = schema[keyword];
+ if (!Array.isArray(branches) || !branches.some(isNullBranch)) return schema;
+ const survivors = branches.filter((branch) => !isNullBranch(branch));
+ const { [keyword]: _dropped, ...rest } = schema;
+ if (survivors.length === 0) return { ...rest, nullable: true };
+ // A single survivor inlines. The parent's own keywords are applied LAST so a
+ // branch constraint cannot overwrite (and possibly widen) an outer one, and
+ // an outer `description` survives an inner one.
+ if (survivors.length === 1) return { ...survivors[0], ...rest, nullable: true };
+ // Several survivors stay a union; 3.0 has no way to mark the union itself
+ // nullable, so each branch carries the flag.
+ return { ...rest, [keyword]: survivors.map((branch) => ({ ...branch, nullable: true })) };
+};
+
+const collapseNullableType = (schema) => {
+ if (schema.type === 'null') {
+ const { type: _dropped, ...rest } = schema;
+ return { ...rest, nullable: true };
+ }
+ if (!Array.isArray(schema.type)) return schema;
+ const types = schema.type.filter((type) => type !== 'null');
+ const { type: _dropped, ...rest } = schema;
+ const nullable = types.length !== schema.type.length ? { nullable: true } : {};
+ // 3.0 allows exactly one `type`; a genuine multi-type union has no 3.0
+ // equivalent, so drop the constraint rather than emit an invalid document.
+ return types.length === 1 ? { ...rest, type: types[0], ...nullable } : { ...rest, ...nullable };
+};
+
+// Draft 2020-12 makes these numeric; 3.0.3 keeps draft-4's boolean flag beside
+// `minimum`/`maximum`.
+const convertExclusiveBounds = (schema) => {
+ const out = { ...schema };
+ if (typeof out.exclusiveMinimum === 'number') {
+ out.minimum = out.exclusiveMinimum;
+ out.exclusiveMinimum = true;
+ }
+ if (typeof out.exclusiveMaximum === 'number') {
+ out.maximum = out.exclusiveMaximum;
+ out.exclusiveMaximum = true;
+ }
+ return out;
+};
+
+// 3.0.3 has no positional array typing. `items: {anyOf: [...members]}` plus a
+// fixed arity keeps every member type and the length, which is strictly better
+// than dropping to "array of anything".
+const convertTuple = (schema) => {
+ const { prefixItems, ...rest } = schema;
+ if (!Array.isArray(prefixItems)) return rest;
+ return {
+ ...rest,
+ items: prefixItems.length === 1 ? prefixItems[0] : { anyOf: prefixItems },
+ minItems: rest.minItems ?? prefixItems.length,
+ // An open-ended `items` schema means extra members are allowed past the
+ // prefix, so only a closed tuple gets a maximum.
+ ...(rest.items === undefined ? { maxItems: rest.maxItems ?? prefixItems.length } : {}),
+ };
+};
+
+/**
+ * Refuse a schema carrying `$ref`/`$defs` rather than publishing a broken one.
+ *
+ * Zod emits `$ref: '#'` for a self-recursive contract. Inlined into a path item
+ * that `#` resolves to the ROOT OPENAPI DOCUMENT, not the schema — a silently
+ * broken pointer for every consumer — and in 3.0.3 a `$ref` ignores its
+ * siblings, so an adjacent `nullable` is dropped too. Correctly supporting this
+ * means hoisting `$defs` into `#/components/schemas` and rewriting pointers;
+ * until a contract actually needs that, failing loudly at build time beats
+ * shipping a document whose references don't resolve.
+ */
+const assertNoReferences = (schema) => {
+ if (schema.$ref !== undefined || schema.$defs !== undefined) {
+ throw new Error(
+ 'OpenAPI 3.0.3 downgrade cannot represent a $ref/$defs schema (recursive or reused Zod contract). '
+ + 'Inline the contract, or add $defs hoisting to openapiDowngrade.js before registering it.',
+ );
+ }
+};
+
+// Keywords with no 3.0.3 Schema Object equivalent. The OAS 3.0 meta-schema
+// closes the Schema Object, so leaving one in makes the whole document invalid.
+// `propertyNames` comes from `z.record()` and its key constraint is simply not
+// expressible in 3.0.
+const UNSUPPORTED_KEYWORDS = ['$schema', 'propertyNames'];
+
+const NESTED_SCHEMA_KEYS = ['items', 'not', 'additionalProperties'];
+const NESTED_SCHEMA_LIST_KEYS = ['anyOf', 'oneOf', 'allOf'];
+
+/**
+ * Rewrite a draft-2020-12 JSON Schema into the OpenAPI 3.0.3 Schema Object
+ * dialect. Returns a new object; the input is never mutated.
+ *
+ * @throws when the schema uses `$ref`/`$defs` (see `assertNoReferences`).
+ */
+export const toOpenApi30Schema = (schema) => {
+ if (Array.isArray(schema)) return schema.map(toOpenApi30Schema);
+ if (!isPlainObject(schema)) return schema;
+
+ assertNoReferences(schema);
+
+ let out = { ...schema };
+ for (const keyword of UNSUPPORTED_KEYWORDS) delete out[keyword];
+
+ if (out.const !== undefined) {
+ out.enum = [out.const];
+ delete out.const;
+ }
+ if (Array.isArray(out.examples)) {
+ if (out.example === undefined && out.examples.length > 0) out.example = out.examples[0];
+ delete out.examples;
+ }
+
+ out = convertTuple(out);
+ out = convertExclusiveBounds(out);
+ out = collapseNullableType(out);
+ for (const keyword of ['anyOf', 'oneOf']) out = collapseNullableUnion(out, keyword);
+
+ for (const key of NESTED_SCHEMA_KEYS) {
+ if (out[key] !== undefined && typeof out[key] !== 'boolean') out[key] = toOpenApi30Schema(out[key]);
+ }
+ for (const key of NESTED_SCHEMA_LIST_KEYS) {
+ if (Array.isArray(out[key])) out[key] = out[key].map(toOpenApi30Schema);
+ }
+ if (isPlainObject(out.properties)) {
+ out.properties = Object.fromEntries(
+ Object.entries(out.properties).map(([name, value]) => [name, toOpenApi30Schema(value)]),
+ );
+ }
+
+ // Converting the branches above can turn a nested `{type:'null'}` into the
+ // `{nullable:true}` marker, exposing a collapse the first pass couldn't see.
+ for (const keyword of ['anyOf', 'oneOf']) out = collapseNullableUnion(out, keyword);
+
+ return out;
+};
+
+// Every spot an OpenAPI Operation Object can carry a Schema Object.
+const convertContent = (content) => (isPlainObject(content)
+ ? Object.fromEntries(Object.entries(content).map(([mediaType, media]) => [
+ mediaType,
+ isPlainObject(media?.schema) ? { ...media, schema: toOpenApi30Schema(media.schema) } : media,
+ ]))
+ : content);
+
+const convertPayload = (payload) => (isPlainObject(payload?.content)
+ ? { ...payload, content: convertContent(payload.content) }
+ : payload);
+
+/**
+ * Downgrade every schema an OpenAPI operation carries — request body, response
+ * bodies, and parameters. This is the boundary the conversion belongs at: the
+ * operation is on its way into a document that declares 3.0.3, whereas the same
+ * contract schemas reach other consumers as plain JSON Schema.
+ */
+export const toOpenApi30Operation = (operation) => {
+ if (!isPlainObject(operation)) return operation;
+ const out = { ...operation };
+ if (out.requestBody) out.requestBody = convertPayload(out.requestBody);
+ if (isPlainObject(out.responses)) {
+ out.responses = Object.fromEntries(
+ Object.entries(out.responses).map(([status, response]) => [status, convertPayload(response)]),
+ );
+ }
+ if (Array.isArray(out.parameters)) {
+ out.parameters = out.parameters.map((parameter) => (isPlainObject(parameter?.schema)
+ ? { ...parameter, schema: toOpenApi30Schema(parameter.schema) }
+ : parameter));
+ }
+ return out;
+};
diff --git a/server/lib/openapiDowngrade.test.js b/server/lib/openapiDowngrade.test.js
new file mode 100644
index 0000000000..487b1cd626
--- /dev/null
+++ b/server/lib/openapiDowngrade.test.js
@@ -0,0 +1,173 @@
+import { describe, it, expect } from 'vitest';
+import { OPENAPI_VERSION, toOpenApi30Schema } from './openapiDowngrade.js';
+import { zodToOpenApiSchema, sdapiTxt2imgBodySchema } from './apiContractSchemas.js';
+
+describe('toOpenApi30Schema', () => {
+ it('collapses an anyOf null branch into nullable on the surviving branch', () => {
+ expect(toOpenApi30Schema({ anyOf: [{ type: 'string', maxLength: 10 }, { type: 'null' }] }))
+ .toEqual({ type: 'string', maxLength: 10, nullable: true });
+ });
+
+ it('keeps a multi-branch union but marks each branch nullable', () => {
+ expect(toOpenApi30Schema({ anyOf: [{ type: 'string' }, { type: 'number' }, { type: 'null' }] }))
+ .toEqual({ anyOf: [{ type: 'string', nullable: true }, { type: 'number', nullable: true }] });
+ });
+
+ it('leaves a union with no null branch untouched', () => {
+ const input = { oneOf: [{ type: 'string' }, { type: 'number' }] };
+ expect(toOpenApi30Schema(input)).toEqual(input);
+ });
+
+ it('does not treat a null branch carrying other keywords as the nullable marker', () => {
+ // Collapsing it would silently discard `title`, so the branch survives as a
+ // branch — converted to the 3.0.3 spelling, but never folded into the parent.
+ expect(toOpenApi30Schema({ anyOf: [{ type: 'string' }, { type: 'null', title: 'explicitly absent' }] }))
+ .toEqual({ anyOf: [{ type: 'string' }, { nullable: true, title: 'explicitly absent' }] });
+ });
+
+ it('collapses a type array into a single type plus nullable', () => {
+ expect(toOpenApi30Schema({ type: ['string', 'null'], minLength: 1 }))
+ .toEqual({ type: 'string', nullable: true, minLength: 1 });
+ });
+
+ it('drops an unrepresentable multi-type constraint rather than emitting an invalid type array', () => {
+ expect(toOpenApi30Schema({ type: ['string', 'number'] })).toEqual({});
+ });
+
+ it('converts numeric exclusive bounds to the 3.0 boolean form', () => {
+ expect(toOpenApi30Schema({ type: 'number', exclusiveMinimum: 0, exclusiveMaximum: 10 }))
+ .toEqual({ type: 'number', minimum: 0, exclusiveMinimum: true, maximum: 10, exclusiveMaximum: true });
+ });
+
+ it('rewrites const to a single-value enum and examples to example', () => {
+ expect(toOpenApi30Schema({ const: 'portos' })).toEqual({ enum: ['portos'] });
+ expect(toOpenApi30Schema({ type: 'string', examples: ['a', 'b'] })).toEqual({ type: 'string', example: 'a' });
+ });
+
+ it('keeps an existing example rather than overwriting it from examples', () => {
+ expect(toOpenApi30Schema({ example: 'kept', examples: ['ignored'] })).toEqual({ example: 'kept' });
+ });
+
+ it('drops keywords 3.0.3 has no equivalent for', () => {
+ // `propertyNames` comes from z.record() and makes the whole document
+ // invalid: the OAS 3.0 meta-schema closes the Schema Object.
+ expect(toOpenApi30Schema({ $schema: 'https://json-schema.org/draft/2020-12/schema', type: 'object', propertyNames: { type: 'string' } }))
+ .toEqual({ type: 'object' });
+ });
+
+ it('converts a tuple to a bounded array instead of dropping its members', () => {
+ expect(toOpenApi30Schema({ type: 'array', prefixItems: [{ type: 'string' }, { type: 'number' }] }))
+ .toEqual({ type: 'array', items: { anyOf: [{ type: 'string' }, { type: 'number' }] }, minItems: 2, maxItems: 2 });
+ });
+
+ it('leaves a tuple with a rest schema open-ended', () => {
+ const result = toOpenApi30Schema({ type: 'array', prefixItems: [{ type: 'string' }], items: { type: 'number' } });
+ expect(result.minItems).toBe(1);
+ expect(result.maxItems).toBeUndefined();
+ });
+
+ it('collapses a bare null type, which 3.0.3 cannot express', () => {
+ expect(toOpenApi30Schema({ type: 'null' })).toEqual({ nullable: true });
+ });
+
+ it('collapses a null branch that only surfaces after the branches convert', () => {
+ // The inner union converts to `{nullable:true}`, which the second collapse
+ // pass then recognizes as the null marker.
+ expect(toOpenApi30Schema({ anyOf: [{ type: 'string' }, { type: 'null' }] }))
+ .toEqual({ type: 'string', nullable: true });
+ expect(toOpenApi30Schema({ anyOf: [{ anyOf: [{ type: 'string' }, { type: 'null' }] }, { type: 'null' }] }))
+ .toEqual({ type: 'string', nullable: true });
+ });
+
+ it('refuses a $ref/$defs schema rather than emitting a broken pointer', () => {
+ // Zod emits `$ref: '#'` for a recursive contract; inlined into a path item
+ // that resolves to the ROOT DOCUMENT, not the schema.
+ expect(() => toOpenApi30Schema({ $ref: '#' })).toThrow(/\$ref/);
+ expect(() => toOpenApi30Schema({ type: 'object', $defs: { Node: { type: 'object' } } })).toThrow(/\$ref/);
+ });
+
+ it('lets the parent keep its own keywords when a sole survivor inlines', () => {
+ // Survivor-wins would WIDEN maxLength from 5 to 10 and silently replace the
+ // outer description Zod puts at the parent level.
+ expect(toOpenApi30Schema({ maxLength: 5, description: 'outer', anyOf: [{ type: 'string', maxLength: 10, description: 'inner' }, { type: 'null' }] }))
+ .toEqual({ type: 'string', maxLength: 5, description: 'outer', nullable: true });
+ });
+
+ it('recurses through properties, items, and nested unions', () => {
+ const result = toOpenApi30Schema({
+ type: 'object',
+ properties: {
+ tags: { type: 'array', items: { anyOf: [{ type: 'string' }, { type: 'null' }] } },
+ nested: { type: 'object', properties: { seed: { type: ['integer', 'null'] } } },
+ },
+ });
+ expect(result.properties.tags.items).toEqual({ type: 'string', nullable: true });
+ expect(result.properties.nested.properties.seed).toEqual({ type: 'integer', nullable: true });
+ });
+
+ it('never mutates the input schema', () => {
+ const input = { anyOf: [{ type: 'string' }, { type: 'null' }] };
+ const snapshot = structuredClone(input);
+ toOpenApi30Schema(input);
+ expect(input).toEqual(snapshot);
+ });
+
+ it('passes a boolean additionalProperties through untouched', () => {
+ expect(toOpenApi30Schema({ type: 'object', additionalProperties: false }))
+ .toEqual({ type: 'object', additionalProperties: false });
+ });
+});
+
+describe('zodToOpenApiSchema', () => {
+ it('stays plain JSON Schema so its other consumers are not corrupted', () => {
+ // The AsyncAPI payloads, the CoS provider tool definitions, and the tool
+ // resource all read this as JSON Schema. Downgrading here (as an earlier
+ // revision did) turns `exclusiveMinimum: 0` into the draft-4 boolean form,
+ // which a JSON Schema validator ignores — silently widening `> 0` to `>= 0`.
+ const schema = zodToOpenApiSchema(sdapiTxt2imgBodySchema);
+ expect(schema.$schema).toBeUndefined();
+ expect(schema.properties.negative_prompt)
+ .toEqual({ anyOf: [{ type: 'string', maxLength: 8000 }, { type: 'null' }] });
+ });
+
+ it('converts to 3.0.3 only at the document boundary', () => {
+ const converted = toOpenApi30Schema(zodToOpenApiSchema(sdapiTxt2imgBodySchema));
+ expect(JSON.stringify(converted)).not.toContain('"type":"null"');
+ expect(converted.properties.negative_prompt).toEqual({ type: 'string', maxLength: 8000, nullable: true });
+ });
+});
+
+describe('OPENAPI_VERSION', () => {
+ it('is the 3.0.x version PortOS publishes', () => {
+ expect(OPENAPI_VERSION).toBe('3.0.3');
+ });
+});
+
+// The findings that motivated this module were all "the document says 3.0.3 but
+// contains a construct 3.0.3 rejects". Scan the real published documents rather
+// than trusting the unit cases above to have enumerated every source.
+describe('the published documents are actually 3.0.3', () => {
+ const FORBIDDEN_IN_30 = ['"type":"null"', '$schema', '"propertyNames"', '"prefixItems"', '"$defs"', '"$ref"', '"const":'];
+
+ it.each([
+ ['public', (m) => m.buildOpenApiSpec({ apiAccess: { voice: { exposed: true }, sdapi: { exposed: true } } }, { version: '1.0.0' })],
+ ['internal', (m) => m.buildInternalOpenApiSpec({}, { version: '1.0.0' })],
+ ])('%s document carries no 3.1-only construct', async (_label, build) => {
+ const spec = build(await import('./openapiSpec.js'));
+ expect(spec.openapi).toBe(OPENAPI_VERSION);
+ const serialized = JSON.stringify(spec);
+ for (const construct of FORBIDDEN_IN_30) expect(serialized).not.toContain(construct);
+ // A type array is the other 3.1-only spelling and needs a regex.
+ expect(serialized).not.toMatch(/"type":\s*\[/);
+ });
+
+ it('leaves the AsyncAPI document as JSON Schema', async () => {
+ // AsyncAPI 3 payloads are JSON Schema, NOT OAS 3.0 — the draft-4 boolean
+ // `exclusiveMinimum` a downgrade would introduce reads as a type error
+ // there, widening `lines > 0` into `lines >= 0`.
+ const { buildAsyncApiSpec } = await import('./asyncApiSpec.js');
+ const serialized = JSON.stringify(buildAsyncApiSpec({ version: '1.0.0' }));
+ expect(serialized).not.toContain('"exclusiveMinimum":true');
+ expect(serialized).not.toContain('"nullable"');
+ });
+});
diff --git a/server/lib/openapiSpec.js b/server/lib/openapiSpec.js
index f0481ba5e8..03405b0284 100644
--- a/server/lib/openapiSpec.js
+++ b/server/lib/openapiSpec.js
@@ -1,4 +1,4 @@
-/** OpenAPI 3.1 builders for PortOS's exposed and complete HTTP API surfaces. */
+/** OpenAPI 3.0.3 builders for PortOS's exposed and complete HTTP API surfaces. */
import { API_OPERATION_CONTRACTS } from './apiOperationContracts.js';
import {
@@ -7,6 +7,7 @@ import {
pathParametersFor,
} from './apiCatalog.js';
import { resolveApiAccess } from './apiRegistry.js';
+import { OPENAPI_VERSION, toOpenApi30Operation } from './openapiDowngrade.js';
const SECURITY_SCHEMES = {
bearerAuth: { type: 'http', scheme: 'bearer', description: 'PortOS session token, when instance authentication is enabled.' },
@@ -23,7 +24,7 @@ const applySecurity = (pathItem, requireAuth) => Object.fromEntries(
);
const commonEnvelope = ({ title, description, baseUrl, version, tags, paths }) => ({
- openapi: '3.1.0',
+ openapi: OPENAPI_VERSION,
info: { title, version, description },
servers: baseUrl ? [{ url: baseUrl }] : [],
tags,
@@ -69,7 +70,9 @@ const generatedOperation = (operation) => {
};
};
-const modeledOperation = (operation, contract) => ({
+// The contract's schemas are JSON Schema; this document declares 3.0.3, so they
+// convert on the way in. Generated operations model no schemas and need none.
+const modeledOperation = (operation, contract) => toOpenApi30Operation({
...generatedOperation(operation),
...contract,
operationId: apiOperationId(operation.method, operation.path),
@@ -90,7 +93,10 @@ export const buildOpenApiSpec = (settings, { baseUrl, version = '0.0.0' } = {})
const pathItem = API_OPERATION_CONTRACTS[path];
if (!pathItem) continue;
const tagged = Object.fromEntries(
- Object.entries(pathItem).map(([method, operation]) => [method, { tags: [api.id], ...operation }]),
+ Object.entries(pathItem).map(([method, operation]) => [
+ method,
+ toOpenApi30Operation({ tags: [api.id], ...operation }),
+ ]),
);
paths[path] = applySecurity(tagged, api.requireAuth);
}
diff --git a/server/lib/openapiSpec.test.js b/server/lib/openapiSpec.test.js
index ded6377b5c..5183465f10 100644
--- a/server/lib/openapiSpec.test.js
+++ b/server/lib/openapiSpec.test.js
@@ -9,7 +9,7 @@ const exposed = (apiAccess) => ({ apiAccess });
describe('buildOpenApiSpec', () => {
it('produces a valid 3.1 envelope with security schemes', () => {
const spec = buildOpenApiSpec({}, { baseUrl: 'https://host:5555', version: '1.2.3' });
- expect(spec.openapi).toBe('3.1.0');
+ expect(spec.openapi).toBe('3.0.3');
expect(spec.info.version).toBe('1.2.3');
expect(spec.servers).toEqual([{ url: 'https://host:5555' }]);
expect(spec.components.securitySchemes.bearerAuth).toBeDefined();
diff --git a/server/lib/socketEventCatalog.generated.json b/server/lib/socketEventCatalog.generated.json
index 868851b29b..8f332b1dd4 100644
--- a/server/lib/socketEventCatalog.generated.json
+++ b/server/lib/socketEventCatalog.generated.json
@@ -1965,7 +1965,7 @@
{
"direction": "server-to-client",
"source": "server/lib/errorHandler.js",
- "line": 309
+ "line": 318
}
]
},
@@ -4405,7 +4405,7 @@
{
"direction": "server-to-client",
"source": "server/lib/errorHandler.js",
- "line": 321
+ "line": 330
}
]
},
diff --git a/server/routes/apiDocs.js b/server/routes/apiDocs.js
index 7f65f80b73..3a84bde924 100644
--- a/server/routes/apiDocs.js
+++ b/server/routes/apiDocs.js
@@ -1,9 +1,11 @@
/**
* API Docs routes.
*
- * Serves generated OpenAPI 3.1, AsyncAPI 3, and searchable catalog documents.
- * The client renders the OpenAPI documents with the lazy-loaded Scalar viewer
- * and uses the compact catalogs for the native HTTP/event explorer tabs.
+ * Serves generated OpenAPI 3.0.3, AsyncAPI 3, and searchable catalog documents,
+ * plus the minimized semantic tool resource agents read to discover callable
+ * PortOS tools. The client renders the OpenAPI documents with the lazy-loaded
+ * Scalar viewer and uses the compact catalogs for the native HTTP/event
+ * explorer tabs.
*
* Mounted at /api/api-docs. Stays GATED when the PortOS password is on (it's a
* normal /api/* route, not in the registry's public prefixes): the spec
@@ -18,6 +20,7 @@ import { getCurrentVersion } from '../services/updateChecker.js';
import { buildApiCatalog } from '../lib/apiCatalog.js';
import { buildAsyncApiSpec } from '../lib/asyncApiSpec.js';
import { buildInternalOpenApiSpec, buildOpenApiSpec } from '../lib/openapiSpec.js';
+import { buildToolResource } from '../lib/apiToolResource.js';
import { buildSocketEventCatalog } from '../lib/socketEventCatalog.js';
const router = Router();
@@ -31,7 +34,7 @@ const baseUrlFromReq = (req) => {
return host ? `${proto}://${host}` : '';
};
-// GET /api/api-docs/openapi.json — the OpenAPI 3.1 document for exposed APIs.
+// GET /api/api-docs/openapi.json — the OpenAPI 3.0.3 document for exposed APIs.
router.get('/openapi.json', asyncHandler(async (req, res) => {
const [settings, version] = await Promise.all([getSettings(), getCurrentVersion()]);
res.json(buildOpenApiSpec(settings, { baseUrl: baseUrlFromReq(req), version }));
@@ -59,4 +62,9 @@ router.get('/asyncapi.json', asyncHandler(async (req, res) => {
res.json(buildAsyncApiSpec({ baseUrl: baseUrlFromReq(req), version }));
}));
+// GET /api/api-docs/tools.min.json — the minimized semantic tool resource.
+router.get('/tools.min.json', asyncHandler(async (_req, res) => {
+ res.json(buildToolResource({ version: await getCurrentVersion() }));
+}));
+
export default router;
diff --git a/server/routes/apiDocs.test.js b/server/routes/apiDocs.test.js
index b81bc3dc90..0eb998bb9c 100644
--- a/server/routes/apiDocs.test.js
+++ b/server/routes/apiDocs.test.js
@@ -19,10 +19,10 @@ const buildApp = () => {
describe('GET /api/api-docs/openapi.json', () => {
beforeEach(() => { store = {}; });
- it('returns an empty-paths 3.1 spec when nothing exposed', async () => {
+ it('returns an empty-paths 3.0.3 spec when nothing exposed', async () => {
const res = await request(buildApp()).get('/api/api-docs/openapi.json');
expect(res.status).toBe(200);
- expect(res.body.openapi).toBe('3.1.0');
+ expect(res.body.openapi).toBe('3.0.3');
expect(Object.keys(res.body.paths)).toHaveLength(0);
expect(res.body.info.version).not.toBe('0.0.0'); // real package.json version
});
@@ -67,4 +67,13 @@ describe('GET /api/api-docs/openapi.json', () => {
expect(asyncapi.body.asyncapi).toBe('3.0.0');
expect(Object.values(asyncapi.body.channels).some((channel) => channel.address === 'shell:start')).toBe(true);
});
+
+ it('serves the minimized semantic tool resource', async () => {
+ const res = await request(buildApp()).get('/api/api-docs/tools.min.json');
+ expect(res.status).toBe(200);
+ expect(res.body.type).toBe('portos_tool_resource');
+ expect(res.body.source.version).toBe('3.0.3');
+ expect(res.body.tools).toHaveLength(8);
+ expect(res.body.errors.some((error) => error.code === 'VALIDATION_ERROR')).toBe(true);
+ });
});
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 7123031bae..41ef8fe2c7 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -47,6 +47,7 @@ vi.mock('../services/jira.js', () => ({
import settingsRoutes from './settings.js';
import { hasConfiguredInstances as hasConfiguredDatadogInstances } from '../services/datadog.js';
+import { hasConfiguredInstances as hasConfiguredJiraInstances } from '../services/jira.js';
const buildApp = () => {
const app = express();
@@ -130,6 +131,26 @@ describe('Settings routes — instance feature participation', () => {
expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'datadog', enabled: true, source: 'auto' }));
});
+ it('detects each integration independently, so one configured integration does not enable another', async () => {
+ hasConfiguredJiraInstances.mockResolvedValueOnce(true);
+
+ const res = await request(buildApp()).get('/api/settings/features');
+
+ expect(res.status).toBe(200);
+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'jira', enabled: true, source: 'auto' }));
+ // Detection is per-feature; a configured JIRA must not switch Datadog on.
+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'datadog', enabled: false, source: 'auto' }));
+ });
+
+ it('keeps an explicit opt-out off even when the integration is configured', async () => {
+ hasConfiguredJiraInstances.mockResolvedValueOnce(true);
+ store = { instanceFeatures: { jira: { enabled: false } } };
+
+ const res = await request(buildApp()).get('/api/settings/features');
+
+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'jira', enabled: false, source: 'explicit' }));
+ });
+
it('updates one feature without replacing unrelated settings', async () => {
store = { theme: 'dark', instanceFeatures: { post: { enabled: true } } };
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index 8a0f0a778e..bd741ee3e0 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -8,6 +8,7 @@ import {
COS_TOOL_SCHEMA_VERSION,
cosToolCallSchema,
normalizePortosSemanticToolGrants,
+ providerToolName,
} from '../lib/cosToolContracts.js';
import { zodToOpenApiSchema } from '../lib/apiContractSchemas.js';
import { canonicalStringify } from '../lib/objects.js';
@@ -71,7 +72,7 @@ const voiceTools = (intent) => {
const legacyName = spec.function.name;
const adapter = VOICE_ADAPTERS[legacyName];
if (!adapter) return [];
- const providerName = adapter.id.replaceAll('.', '_').replaceAll('-', '_');
+ const providerName = providerToolName(adapter.id);
return [{
type: 'portos_tool',
name: adapter.id,