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

address review (codex): complete the failure contracts and the 3.0.3 keyword set

Adam Eivy3b1cbc1105d8
diff --git a/server/lib/apiOperationContracts.js b/server/lib/apiOperationContracts.js
index 36d3a0a73f..2fda465ea1 100644
--- a/server/lib/apiOperationContracts.js
+++ b/server/lib/apiOperationContracts.js
@@ -50,7 +50,7 @@ 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', 'x-portos-error-codes': ['VALIDATION_ERROR'] },
+ 400: { description: 'Invalid payload or unknown voice', 'x-portos-error-codes': ['VALIDATION_ERROR', 'UNKNOWN_VOICE'] },
},
'x-portos-tool': {
name: 'voice.synthesize', version: 1,
@@ -96,21 +96,30 @@ export const API_OPERATION_CONTRACTS = Object.freeze({
'/sdapi/v1/sd-models': {
get: {
summary: 'List image models',
- responses: { 200: { description: 'Model catalog', content: { 'application/json': { schema: { type: 'array', items: { type: 'object' } } } } } },
+ responses: {
+ 200: { description: 'Model catalog', content: { 'application/json': { schema: { type: 'array', items: { type: 'object' } } } } },
+ 403: { description: 'A1111 API exposure is disabled' },
+ },
'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', content: { 'application/json': { schema: { type: 'array', items: { type: 'object' } } } } } },
+ responses: {
+ 200: { description: 'Sampler list', content: { 'application/json': { schema: { type: 'array', items: { type: 'object' } } } } },
+ 403: { description: 'A1111 API exposure is disabled' },
+ },
'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', content: { 'application/json': { schema: { type: 'object' } } } } },
+ responses: {
+ 200: { description: 'Active model and options', content: { 'application/json': { schema: { type: 'object' } } } },
+ 403: { description: 'A1111 API exposure is disabled' },
+ },
'x-portos-tool': { name: 'image.get-options', version: 1, policy: { privacy: 'internal', sideEffect: 'read', async: false } },
},
post: {
@@ -122,7 +131,10 @@ export const API_OPERATION_CONTRACTS = Object.freeze({
'/sdapi/v1/progress': {
get: {
summary: 'Read generation progress',
- responses: { 200: { description: 'Current generation progress or idle state', content: { 'application/json': { schema: { type: 'object' } } } } },
+ responses: {
+ 200: { description: 'Current generation progress or idle state', content: { 'application/json': { schema: { type: 'object' } } } },
+ 403: { description: 'A1111 API exposure is disabled' },
+ },
'x-portos-tool': { name: 'image.get-progress', version: 1, policy: { privacy: 'internal', sideEffect: 'read', async: false } },
},
},
diff --git a/server/lib/apiToolResource.js b/server/lib/apiToolResource.js
index 6410bc090b..f564c0c675 100644
--- a/server/lib/apiToolResource.js
+++ b/server/lib/apiToolResource.js
@@ -108,6 +108,11 @@ const outputSchemaFor = (operation) => {
/**
* The failures an operation declares, as `{ status, code }` pairs.
*
+ * These are the DECLARED failure modes — the ones the contract commits to — not
+ * an exhaustive enumeration of every error an internal service can surface. A
+ * caller should still handle an unlisted code, which is why the resource also
+ * publishes the full status/code vocabulary at the top level.
+ *
* 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
diff --git a/server/lib/apiToolResource.test.js b/server/lib/apiToolResource.test.js
index bd8886e93e..d3ccabe402 100644
--- a/server/lib/apiToolResource.test.js
+++ b/server/lib/apiToolResource.test.js
@@ -85,8 +85,22 @@ describe('buildToolResource', () => {
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' }]);
+ // BAD_REQUEST for a 400 that really reports VALIDATION_ERROR. One status can
+ // carry several codes: a schema-valid request naming an unknown voice is a
+ // 400 UNKNOWN_VOICE (see routes/voicePublic.test.js).
+ expect(byName('voice.synthesize').failures).toEqual([
+ { status: 400, code: 'VALIDATION_ERROR' },
+ { status: 400, code: 'UNKNOWN_VOICE' },
+ ]);
+ });
+
+ it('declares the router-wide exposure gate on every sdapi tool, not just the write one', () => {
+ // routes/sdapi.js gates the WHOLE router with `router.use(...)`, so a read
+ // tool returns 403 too when A1111 exposure is off. An agent that never saw
+ // that failure has no way to explain the refusal.
+ for (const name of ['image.list-models', 'image.list-samplers', 'image.get-options', 'image.get-progress']) {
+ expect(byName(name).failures).toEqual([{ status: 403, code: 'FORBIDDEN' }]);
+ }
});
it('emits one entry per code when a status carries several', () => {
@@ -100,7 +114,7 @@ describe('buildToolResource', () => {
});
it('omits failures entirely for a tool that declares no error responses', () => {
- expect(byName('image.list-models').failures).toBeUndefined();
+ expect(byName('voice.list-voices').failures).toBeUndefined();
});
it('marks read tools idempotent and side-effecting tools not', () => {
diff --git a/server/lib/openapiDowngrade.js b/server/lib/openapiDowngrade.js
index 693d338b33..430848eac2 100644
--- a/server/lib/openapiDowngrade.js
+++ b/server/lib/openapiDowngrade.js
@@ -34,6 +34,12 @@
* - `$schema` and `propertyNames` (no 3.0 equivalent) are dropped
*
* `$ref`/`$defs` are REFUSED rather than mangled — see `assertNoReferences`.
+ *
+ * KNOWN LOSSY CASE: 3.0's `nullable` only qualifies a `type` in the same Schema
+ * Object, so a nullable COMPOSED schema (`z.intersection(...).nullable()`, which
+ * collapses to `{allOf: [...], nullable: true}`) cannot express its null branch —
+ * 3.0 has no spelling for it. The flag is emitted anyway as the conventional
+ * best effort. No registered contract composes a nullable schema today.
*/
import { isPlainObject } from './objects.js';
@@ -42,13 +48,24 @@ import { isPlainObject } from './objects.js';
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
+// post-conversion (`{enum:[null], 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 NULL_MARKER_KEYS = new Set(['type', 'enum', 'nullable']);
+
+const isNullBranch = (branch) => {
+ if (!isPlainObject(branch)) return false;
+ const keys = Object.keys(branch);
+ if (!keys.every((key) => NULL_MARKER_KEYS.has(key))) return false;
+ if (branch.type === 'null') return true;
+ // `{type:'string', nullable:true}` shares the key set but is not a null
+ // marker — a converted marker carries no type at all.
+ return branch.type === undefined
+ && branch.nullable === true
+ && Array.isArray(branch.enum)
+ && branch.enum.every((value) => value === null);
+};
const collapseNullableUnion = (schema, keyword) => {
const branches = schema[keyword];
@@ -68,7 +85,9 @@ const collapseNullableUnion = (schema, keyword) => {
const collapseNullableType = (schema) => {
if (schema.type === 'null') {
const { type: _dropped, ...rest } = schema;
- return { ...rest, nullable: true };
+ // In 3.0 `nullable` only qualifies a `type` declared alongside it, so a
+ // null-only schema needs `enum: [null]` to actually accept null.
+ return { ...rest, ...(rest.enum === undefined ? { enum: [null] } : {}), nullable: true };
}
if (!Array.isArray(schema.type)) return schema;
const types = schema.type.filter((type) => type !== 'null');
@@ -100,12 +119,16 @@ const convertExclusiveBounds = (schema) => {
const convertTuple = (schema) => {
const { prefixItems, ...rest } = schema;
if (!Array.isArray(prefixItems)) return rest;
+ // A rest schema (`z.tuple([...]).rest(z.number())`) types every member past
+ // the prefix, so it joins the union rather than being overwritten by it —
+ // otherwise a valid tail element is rejected by the published contract.
+ const members = rest.items === undefined ? prefixItems : [...prefixItems, rest.items];
return {
...rest,
- items: prefixItems.length === 1 ? prefixItems[0] : { anyOf: prefixItems },
+ items: members.length === 1 ? members[0] : { anyOf: members },
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.
+ // An open-ended rest means extra members are allowed, so only a closed
+ // tuple gets a maximum.
...(rest.items === undefined ? { maxItems: rest.maxItems ?? prefixItems.length } : {}),
};
};
@@ -131,10 +154,13 @@ const assertNoReferences = (schema) => {
};
// 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'];
+// CLOSES the Schema Object (`additionalProperties: false` plus an `^x-` escape
+// hatch), so leaving any one of these in makes the whole document invalid — not
+// just the subschema. `propertyNames`/`patternProperties` come from `z.record()`
+// and their key constraints are not expressible in 3.0; `contentEncoding` /
+// `contentMediaType` come from `z.base64()` / `z.file()`, whose `format` and
+// `pattern` siblings survive and carry most of the meaning.
+const UNSUPPORTED_KEYWORDS = ['$schema', 'propertyNames', 'patternProperties', 'contentEncoding', 'contentMediaType'];
const NESTED_SCHEMA_KEYS = ['items', 'not', 'additionalProperties'];
const NESTED_SCHEMA_LIST_KEYS = ['anyOf', 'oneOf', 'allOf'];
diff --git a/server/lib/openapiDowngrade.test.js b/server/lib/openapiDowngrade.test.js
index 487b1cd626..e8fde497c1 100644
--- a/server/lib/openapiDowngrade.test.js
+++ b/server/lib/openapiDowngrade.test.js
@@ -22,7 +22,7 @@ describe('toOpenApi30Schema', () => {
// 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' }] });
+ .toEqual({ anyOf: [{ type: 'string' }, { enum: [null], nullable: true, title: 'explicitly absent' }] });
});
it('collapses a type array into a single type plus nullable', () => {
@@ -60,14 +60,26 @@ describe('toOpenApi30Schema', () => {
.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('keeps a tuple rest schema in the member union instead of overwriting it', () => {
+ // `z.tuple([string]).rest(number)`: dropping `items` would reject every
+ // valid numeric tail element.
+ expect(toOpenApi30Schema({ type: 'array', prefixItems: [{ type: 'string' }], items: { type: 'number' } }))
+ .toEqual({ type: 'array', items: { anyOf: [{ type: 'string' }, { type: 'number' }] }, minItems: 1 });
});
- it('collapses a bare null type, which 3.0.3 cannot express', () => {
- expect(toOpenApi30Schema({ type: 'null' })).toEqual({ nullable: true });
+ it('encodes a null-only schema as an enum, since bare nullable says nothing in 3.0', () => {
+ // 3.0's `nullable` only qualifies a `type` in the same Schema Object, so
+ // `{nullable:true}` alone does not actually accept null.
+ expect(toOpenApi30Schema({ type: 'null' })).toEqual({ enum: [null], nullable: true });
+ expect(toOpenApi30Schema({ type: 'null', enum: [null] })).toEqual({ enum: [null], nullable: true });
+ });
+
+ it('drops content keywords the closed 3.0 Schema Object rejects, keeping format and pattern', () => {
+ // z.base64() emits contentEncoding; one stray keyword invalidates the
+ // entire document, not just its subschema.
+ expect(toOpenApi30Schema({ type: 'string', format: 'base64', contentEncoding: 'base64', contentMediaType: 'text/plain', pattern: '^a' }))
+ .toEqual({ type: 'string', format: 'base64', pattern: '^a' });
+ expect(toOpenApi30Schema({ type: 'object', patternProperties: { '^a': { type: 'number' } } })).toEqual({ type: 'object' });
});
it('collapses a null branch that only surfaces after the branches convert', () => {
@@ -147,7 +159,8 @@ describe('OPENAPI_VERSION', () => {
// 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":'];
+ const FORBIDDEN_IN_30 = ['"type":"null"', '$schema', '"propertyNames"', '"prefixItems"', '"$defs"', '"$ref"', '"const":',
+ '"patternProperties"', '"contentEncoding"', '"contentMediaType"', '"unevaluatedProperties"'];
it.each([
['public', (m) => m.buildOpenApiSpec({ apiAccess: { voice: { exposed: true }, sdapi: { exposed: true } } }, { version: '1.0.0' })],