From c1cf57d283d83db884ad12528185ef2883e4ae00 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:03:26 +0000 Subject: [PATCH 01/11] feat(spec): declare the AI answer follow-up routes and carry turn_id on conversation messages Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/spec/src/api/ai-answer.test.ts | 221 +++++++++++++++ packages/spec/src/api/ai-answer.zod.ts | 311 ++++++++++++++++++++++ packages/spec/src/api/index.ts | 3 + packages/spec/src/api/protocol.zod.ts | 14 +- packages/spec/src/contracts/ai-service.ts | 15 +- 5 files changed, 561 insertions(+), 3 deletions(-) create mode 100644 packages/spec/src/api/ai-answer.test.ts create mode 100644 packages/spec/src/api/ai-answer.zod.ts diff --git a/packages/spec/src/api/ai-answer.test.ts b/packages/spec/src/api/ai-answer.test.ts new file mode 100644 index 00000000000..07373b88375 --- /dev/null +++ b/packages/spec/src/api/ai-answer.test.ts @@ -0,0 +1,221 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The AI answer follow-up routes, held to the bodies their producer answers. + * + * The producer is cloud's `service-ai`, read at cloud commit `c21b372`; each + * fixture below names the file and line its shape was read from. Each route + * is pinned twice: a body built from the producer's shape parses, and the same + * body without a required member is refused. The error pins build the body the + * producer's `sendError` writes (`routes/envelope.ts:198-210`: + * `{ code, message, httpStatus, ...extra }`). + * + * Imported through the `./api` entry barrel, so a missing export reds here. + */ + +import { describe, expect, it } from 'vitest'; +import { + AiAnswerArtifactErrorSchema, + AiAnswerFeedbackErrorSchema, + AiConversationSchema, + AiSavedQuestionErrorSchema, + CreateAiAnswerArtifactRequestSchema, + CreateAiAnswerArtifactResponseSchema, + CreateAiSavedQuestionRequestSchema, + CreateAiSavedQuestionResponseSchema, + GetAiAnswerFeedbackResponseSchema, + ListAiSavedQuestionsResponseSchema, + RunAiSavedQuestionResponseSchema, + SetAiAnswerFeedbackRequestSchema, + SetAiAnswerFeedbackResponseSchema, +} from './index'; + +/** Drop one key from a fixture. */ +function without>(value: T, key: keyof T): Record { + const { [key]: _dropped, ...rest } = value; + return rest; +} + +// `saved/source-artifact.ts:122-139` (`parseResultSource`): an aggregate block. +const SOURCE = { + object: 'opportunity', + label: 'Opportunities', + filter: { stage: { $eq: 'won' } }, + scope: 'visible_to_you', + groupBy: ['region'], + aggregations: [{ function: 'sum', field: 'amount' }], + records: 42, + line: 'Source: Opportunities · stage = won', +}; + +// `saved/saved-question-store.ts:114-124` (`toSaved`), on the row `create` writes (:248-262). +const SAVED = { + id: 'sq_6f1c', + question: 'Won amount by region', + source: SOURCE, + agentId: 'ask', + conversationId: 'conv_1', + turnId: 'turn_1', + createdAt: '2026-11-18T10:00:00.000Z', +}; + +// `feedback/answer-feedback-store.ts:124-133` (`toFeedback`). +const FEEDBACK = { + conversationId: 'conv_1', + turnId: 'turn_1', + rating: 'down', + note: 'Wrong quarter', + createdAt: '2026-11-18T10:00:00.000Z', + updatedAt: '2026-11-18T10:00:00.000Z', +}; + +describe('saved questions', () => { + it('GET answers `{ questions }` (saved-question-routes.ts:274); a typed question carries null links', () => { + const typed = { ...SAVED, source: null, agentId: null, conversationId: null, turnId: null }; + expect(ListAiSavedQuestionsResponseSchema.safeParse({ questions: [SAVED, typed] }).success).toBe(true); + expect(ListAiSavedQuestionsResponseSchema.safeParse({ questions: [without(SAVED, 'createdAt')] }).success).toBe(false); + expect(ListAiSavedQuestionsResponseSchema.safeParse({}).success).toBe(false); + }); + + it('POST takes a typed question, or conversationId with turnId (saved-question-routes.ts:290-316)', () => { + expect(CreateAiSavedQuestionRequestSchema.safeParse({ question: 'Won amount by region' }).success).toBe(true); + expect(CreateAiSavedQuestionRequestSchema.safeParse({ conversationId: 'conv_1', turnId: 'turn_1', toolCallId: 'call_2' }).success).toBe(true); + // :297-298 — one of the pair without the other is refused. + expect(CreateAiSavedQuestionRequestSchema.safeParse({ conversationId: 'conv_1' }).success).toBe(false); + expect(CreateAiSavedQuestionRequestSchema.safeParse({ question: 'q', turnId: 'turn_1' }).success).toBe(false); + // :315-316 — no question and no turn. + expect(CreateAiSavedQuestionRequestSchema.safeParse({}).success).toBe(false); + }); + + it('POST answers `{ question }` (saved-question-routes.ts:330)', () => { + expect(CreateAiSavedQuestionResponseSchema.safeParse({ question: SAVED }).success).toBe(true); + expect(CreateAiSavedQuestionResponseSchema.safeParse({ question: without(SAVED, 'id') }).success).toBe(false); + }); + + it('run answers `{ question, toolName, result }` (saved-question-routes.ts:394)', () => { + const run = { question: 'Won amount by region', toolName: 'aggregate_data', result: { rows: [{ region: 'EMEA', sum_amount: 10 }] } }; + expect(RunAiSavedQuestionResponseSchema.safeParse(run).success).toBe(true); + expect(RunAiSavedQuestionResponseSchema.safeParse(without(run, 'toolName')).success).toBe(false); + }); + + it('the run refusal names its reason in details (saved-question-routes.ts:369-372, :392)', () => { + const noQuery = { + code: 'RESOURCE_CONFLICT', + message: 'This question was saved without a query. Ask it again in the chat.', + httpStatus: 409, + details: { reason: 'saved_question_has_no_query', question: 'Won amount by region' }, + }; + expect(AiSavedQuestionErrorSchema.safeParse(noQuery).success).toBe(true); + expect(AiSavedQuestionErrorSchema.safeParse({ ...noQuery, details: { reason: 'invented' } }).success).toBe(false); + // :319 — a code outside the route's vocabulary is refused. + expect(AiSavedQuestionErrorSchema.safeParse({ code: 'VALUE_TOO_LONG', message: 'too long', httpStatus: 413 }).success).toBe(true); + expect(AiSavedQuestionErrorSchema.safeParse({ code: 'QUOTA_EXCEEDED', message: 'x', httpStatus: 429 }).success).toBe(false); + }); +}); + +describe('answer → artifact', () => { + it('the request names a kind (saved-question-routes.ts:415-419; source-artifact.ts:49)', () => { + expect(CreateAiAnswerArtifactRequestSchema.safeParse({ kind: 'report', toolCallId: 'call_2', label: 'Won by region' }).success).toBe(true); + expect(CreateAiAnswerArtifactRequestSchema.safeParse({ toolCallId: 'call_2' }).success).toBe(false); + expect(CreateAiAnswerArtifactRequestSchema.safeParse({ kind: 'chart' }).success).toBe(false); + }); + + it('kind view answers the personal view row (saved-question-routes.ts:452; source-artifact.ts:539)', () => { + const view = { + kind: 'view', + view: { id: 'pv_1', object_name: 'opportunity', label: 'Open deals', config: { columns: [], sort: [{ field: 'amount', order: 'desc' }] } }, + }; + expect(CreateAiAnswerArtifactResponseSchema.safeParse(view).success).toBe(true); + expect(CreateAiAnswerArtifactResponseSchema.safeParse({ kind: 'view', view: without(view.view, 'object_name') }).success).toBe(false); + }); + + it('kind report and widget answer the staged drafts (saved-question-routes.ts:474-483)', () => { + const dataset = { name: 'ask_opportunity_1a2b3c4d', label: 'Won by region', object: 'opportunity', dimensions: [], measures: [] }; + const report = { + kind: 'report', + published: false, + drafts: [{ type: 'dataset', name: dataset.name }, { type: 'report', name: dataset.name }], + dataset, + report: { name: dataset.name, label: dataset.label, type: 'summary', dataset: dataset.name }, + }; + expect(CreateAiAnswerArtifactResponseSchema.safeParse(report).success).toBe(true); + expect(CreateAiAnswerArtifactResponseSchema.safeParse(without(report, 'drafts')).success).toBe(false); + // :455, :482 — a widget's presentation is a dashboard, under the `dashboard` key. + const widget = { + ...without(report, 'report'), + kind: 'widget', + drafts: [{ type: 'dataset', name: dataset.name }, { type: 'dashboard', name: dataset.name }], + dashboard: { name: dataset.name, label: dataset.label, widgets: [] }, + }; + expect(CreateAiAnswerArtifactResponseSchema.safeParse(widget).success).toBe(true); + expect(CreateAiAnswerArtifactResponseSchema.safeParse(without(widget, 'dashboard')).success).toBe(false); + }); + + it('a refusal names its reason (saved-question-routes.ts:233-238, :84-88)', () => { + const authoring = { + code: 'PERMISSION_DENIED', + message: 'A report or dashboard is shared metadata.', + httpStatus: 403, + category: 'authorization', + details: { reason: 'report_authoring_requires_manage_metadata' }, + }; + expect(AiAnswerArtifactErrorSchema.safeParse(authoring).success).toBe(true); + const sourceRefused = { + code: 'VALIDATION_ERROR', + message: 'This answer lists records and states no figure.', + httpStatus: 422, + details: { reason: 'not_an_aggregate' }, + }; + expect(AiAnswerArtifactErrorSchema.safeParse(sourceRefused).success).toBe(true); + expect(AiAnswerArtifactErrorSchema.safeParse({ ...sourceRefused, details: {} }).success).toBe(false); + }); +}); + +describe('answer feedback', () => { + it('GET answers `{ feedback }`, null when unrated (feedback-routes.ts:132)', () => { + expect(GetAiAnswerFeedbackResponseSchema.safeParse({ feedback: FEEDBACK }).success).toBe(true); + expect(GetAiAnswerFeedbackResponseSchema.safeParse({ feedback: null }).success).toBe(true); + expect(GetAiAnswerFeedbackResponseSchema.safeParse({ feedback: without(FEEDBACK, 'rating') }).success).toBe(false); + }); + + it('POST takes a rating and an optional note (feedback-routes.ts:148-164)', () => { + expect(SetAiAnswerFeedbackRequestSchema.safeParse({ rating: 'down', note: 'Wrong quarter' }).success).toBe(true); + expect(SetAiAnswerFeedbackRequestSchema.safeParse({ rating: 'up', note: null }).success).toBe(true); + expect(SetAiAnswerFeedbackRequestSchema.safeParse({ note: 'Wrong quarter' }).success).toBe(false); + expect(SetAiAnswerFeedbackRequestSchema.safeParse({ rating: 'meh' }).success).toBe(false); + }); + + it('POST answers `{ feedback }` (feedback-routes.ts:170)', () => { + expect(SetAiAnswerFeedbackResponseSchema.safeParse({ feedback: { ...FEEDBACK, note: null } }).success).toBe(true); + expect(SetAiAnswerFeedbackResponseSchema.safeParse({ feedback: without(FEEDBACK, 'turnId') }).success).toBe(false); + }); + + it('the owner refusal (feedback-routes.ts:107-110)', () => { + const notOwner = { code: 'PERMISSION_DENIED', message: 'You can rate only the answers in your own conversations.', httpStatus: 403, category: 'authorization' }; + expect(AiAnswerFeedbackErrorSchema.safeParse(notOwner).success).toBe(true); + expect(AiAnswerFeedbackErrorSchema.safeParse(without(notOwner, 'code')).success).toBe(false); + }); +}); + +describe('a conversation message carries its turn_id', () => { + const conversation = { + id: 'conv_1', + messages: [{ role: 'user', content: 'Won amount by region' }, { role: 'assistant', content: 'EMEA leads.' }], + createdAt: '2026-11-18T10:00:00.000Z', + updatedAt: '2026-11-18T10:00:00.000Z', + }; + + it('CONTROL: a stored conversation with no turn_id still parses', () => { + expect(AiConversationSchema.safeParse(conversation).success).toBe(true); + }); + + it('a message with turn_id keeps it, typed', () => { + const stamped = { + ...conversation, + messages: conversation.messages.map((m) => ({ ...m, turn_id: 'turn_1' })), + }; + const parsed = AiConversationSchema.parse(stamped); + expect(parsed.messages.map((m) => m.turn_id)).toEqual(['turn_1', 'turn_1']); + expect(AiConversationSchema.safeParse({ ...conversation, messages: [{ role: 'user', content: 'q', turn_id: 7 }] }).success).toBe(false); + }); +}); diff --git a/packages/spec/src/api/ai-answer.zod.ts b/packages/spec/src/api/ai-answer.zod.ts new file mode 100644 index 00000000000..2c836f47dad --- /dev/null +++ b/packages/spec/src/api/ai-answer.zod.ts @@ -0,0 +1,311 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; +import { lazySchema } from '../shared/lazy-schema'; +import { dependentRequired, requiredOneOf } from '../shared/refinement-projection'; +import { ObjectQuerySourceSchema } from '../ai/object-query-source.zod'; +import { ApiErrorSchema } from './contract.zod'; +import { StandardErrorCode } from './errors.zod'; + +/** + * The AI answer follow-up routes: saved questions, an answer turned into an + * artifact, and an answer's rating. + * + * | Method | Path | Request | `data` on success | + * |:--|:--|:--|:--| + * | GET | `/api/v1/ai/saved-questions` | none | {@link ListAiSavedQuestionsResponseSchema} | + * | POST | `/api/v1/ai/saved-questions` | {@link CreateAiSavedQuestionRequestSchema} | {@link CreateAiSavedQuestionResponseSchema} (201) | + * | DELETE | `/api/v1/ai/saved-questions/:id` | none | no body (204) | + * | POST | `/api/v1/ai/saved-questions/:id/run` | none | {@link RunAiSavedQuestionResponseSchema} | + * | POST | `/api/v1/ai/conversations/:id/turns/:turnId/artifact` | {@link CreateAiAnswerArtifactRequestSchema} | {@link CreateAiAnswerArtifactResponseSchema} (201) | + * | GET | `/api/v1/ai/conversations/:id/turns/:turnId/feedback` | none | {@link GetAiAnswerFeedbackResponseSchema} | + * | POST | `/api/v1/ai/conversations/:id/turns/:turnId/feedback` | {@link SetAiAnswerFeedbackRequestSchema} | {@link SetAiAnswerFeedbackResponseSchema} | + * | DELETE | `/api/v1/ai/conversations/:id/turns/:turnId/feedback` | none | no body (204), also when no rating was there | + * + * Like the other `/api/v1/ai/**` shapes in `protocol.zod.ts`, these describe + * the wire, not a protocol this repo serves: the producer is the cloud AI + * service (`service-ai`: `routes/saved-question-routes.ts`, + * `routes/feedback-routes.ts`, `saved/saved-question-store.ts`, + * `saved/source-artifact.ts`, `feedback/answer-feedback-store.ts`). Every + * success body is the platform envelope `{ success: true, data }` and each + * response schema here is the `data` payload; every failure body is + * `{ success: false, error }` with `error` one of the three route errors below. + * + * Every route is the signed-in caller's own: a saved question that is not the + * caller's answers 404, and a conversation that is not the caller's answers 403 + * on the artifact and feedback routes. + */ + +// ── Saved questions ─────────────────────────────────────────────────────── + +/** One saved question, as the saved-question routes answer it. */ +export const AiSavedQuestionSchema = lazySchema(() => z.object({ + id: z.string().describe('Saved question id'), + question: z.string().describe('The question text'), + source: ObjectQuerySourceSchema.nullable().describe( + 'The query the answer ran, read off the caller\'s stored turn when the question was saved from an answer; ' + + 'null for a typed question, or when the answer ran no query', + ), + agentId: z.string().nullable().describe('The agent of the conversation it was saved from; null for a typed question'), + conversationId: z.string().nullable().describe('The conversation it was saved from; null for a typed question'), + turnId: z.string().nullable().describe('The turn it was saved from; null for a typed question'), + createdAt: z.string().describe('Creation timestamp (ISO 8601)'), +})); + +/** `GET /api/v1/ai/saved-questions`. */ +export const ListAiSavedQuestionsResponseSchema = lazySchema(() => z.object({ + questions: z.array(AiSavedQuestionSchema).describe( + 'The caller\'s saved questions in the session\'s organization, newest first, at most 200', + ), +})); + +/** + * `POST /api/v1/ai/saved-questions` — a typed question (`question`), or one of + * the caller's answers (`conversationId` with `turnId`). Saved from an answer, + * the query comes off the stored turn; a `source` in the body is not read. + */ +export const CreateAiSavedQuestionRequestSchema = lazySchema(() => z.object({ + question: z.string().optional().describe( + 'The question text. Required without `conversationId`; from an answer it replaces the turn\'s own question. ' + + 'A question longer than 2000 characters is refused (413 VALUE_TOO_LONG)', + ), + conversationId: z.string().optional().describe('The caller\'s conversation the answer is in; sent with `turnId`'), + turnId: z.string().optional().describe('The turn of that conversation; sent with `conversationId`'), + toolCallId: z.string().optional().describe( + 'The tool call of the turn whose query is saved; the turn\'s last query when omitted', + ), +}) + .refine(dependentRequired({ conversationId: ['turnId'], turnId: ['conversationId'] }), { + message: 'conversationId and turnId are sent together', + }) + .refine(requiredOneOf(['question', 'conversationId']), { + message: 'a question, or a conversationId and turnId, is required', + })); + +/** `POST /api/v1/ai/saved-questions` — 201. */ +export const CreateAiSavedQuestionResponseSchema = lazySchema(() => z.object({ + question: AiSavedQuestionSchema.describe('The saved question'), +})); + +/** + * `POST /api/v1/ai/saved-questions/:id/run` — the stored query run again as the + * caller, under their current permissions. Nothing is stored. No request body. + */ +export const RunAiSavedQuestionResponseSchema = lazySchema(() => z.object({ + question: z.string().describe('The saved question text'), + toolName: z.enum(['aggregate_data', 'query_records']).describe( + 'The data tool that ran the query: aggregate_data for an aggregate, query_records for a record read', + ), + result: z.unknown().describe('The data tool\'s result, parsed from its JSON text'), +})); + +/** The `error.code` vocabulary of the saved-question routes. */ +export const AiSavedQuestionErrorCodeSchema = lazySchema(() => StandardErrorCode.extract([ + 'PERMISSION_DENIED', + 'MISSING_REQUIRED_FIELD', + 'VALIDATION_ERROR', + 'VALUE_TOO_LONG', + 'RESOURCE_NOT_FOUND', + 'RESOURCE_CONFLICT', + 'INTERNAL_ERROR', +])); + +/** + * `error.details.reason` on a saved-question run refusal: + * `saved_question_has_no_query` (409 RESOURCE_CONFLICT, the question was saved + * without a query; `details.question` carries its text) or + * `saved_question_run_failed` (422 VALIDATION_ERROR, the data tool refused). + */ +export const AiSavedQuestionRefusalReasonSchema = lazySchema(() => z.enum([ + 'saved_question_has_no_query', + 'saved_question_run_failed', +])); + +/** The `error` of a saved-question route failure. */ +export const AiSavedQuestionErrorSchema = lazySchema(() => ApiErrorSchema.extend({ + code: AiSavedQuestionErrorCodeSchema.describe('Error code'), + details: z.object({ + reason: AiSavedQuestionRefusalReasonSchema.describe('The named refusal'), + question: z.string().optional().describe('The saved question text, on saved_question_has_no_query'), + }).optional().describe('Present on a run refusal'), +})); + +// ── Answer → artifact ───────────────────────────────────────────────────── + +/** What an answer can be turned into. */ +export const AiAnswerArtifactKindSchema = lazySchema(() => z.enum(['view', 'report', 'widget'])); + +/** + * `POST /api/v1/ai/conversations/:id/turns/:turnId/artifact`. The artifact is + * built from the `source` block of the caller's stored turn, never from the + * request body. + */ +export const CreateAiAnswerArtifactRequestSchema = lazySchema(() => z.object({ + kind: AiAnswerArtifactKindSchema.describe( + 'view: the caller\'s own list view; report: a dataset and a report draft; widget: a dataset and a new ' + + 'one-widget dashboard draft. report and widget need the manage_metadata capability', + ), + toolCallId: z.string().optional().describe('The tool call of the turn to build from; the turn\'s last query when omitted'), + label: z.string().optional().describe( + 'The artifact label; the turn\'s question when omitted. Cut to 120 characters', + ), +})); + +/** One metadata draft the artifact route staged. */ +export const AiAnswerArtifactDraftSchema = lazySchema(() => z.object({ + type: z.enum(['dataset', 'report', 'dashboard']).describe('Metadata type of the draft'), + name: z.string().describe('Metadata item name of the draft'), +})); + +/** A metadata item body as the artifact route answers it. */ +const ArtifactItemSchema = () => z.record(z.string(), z.unknown()); + +/** `kind: 'view'` — the caller's own `sys_personal_view` row. */ +const AnswerViewArtifactSchema = () => z.object({ + kind: z.literal('view').describe('The artifact kind'), + view: z.object({ + id: z.string().optional().describe('The personal view row id, when the engine answered one'), + object_name: z.string().describe('The object the view lists'), + label: z.string().describe('The view label'), + config: z.record(z.string(), z.unknown()).describe('The list view configuration, a ListView'), + }).describe('The saved personal view'), +}); + +/** `kind: 'report'` — a dataset draft and a report draft, nothing published. */ +const AnswerReportArtifactSchema = () => z.object({ + kind: z.literal('report').describe('The artifact kind'), + published: z.literal(false).describe('Always false: the drafts are not published'), + drafts: z.array(AiAnswerArtifactDraftSchema).describe('The drafts staged: the dataset, then the report'), + dataset: ArtifactItemSchema().describe('The dataset draft body'), + report: ArtifactItemSchema().describe('The report draft body'), +}); + +/** `kind: 'widget'` — a dataset draft and a new one-widget dashboard draft, nothing published. */ +const AnswerWidgetArtifactSchema = () => z.object({ + kind: z.literal('widget').describe('The artifact kind'), + published: z.literal(false).describe('Always false: the drafts are not published'), + drafts: z.array(AiAnswerArtifactDraftSchema).describe('The drafts staged: the dataset, then the dashboard'), + dataset: ArtifactItemSchema().describe('The dataset draft body'), + dashboard: ArtifactItemSchema().describe('The dashboard draft body'), +}); + +/** `POST /api/v1/ai/conversations/:id/turns/:turnId/artifact` — 201, discriminated by `kind`. */ +export const CreateAiAnswerArtifactResponseSchema = lazySchema(() => z.discriminatedUnion('kind', [ + AnswerViewArtifactSchema(), + AnswerReportArtifactSchema(), + AnswerWidgetArtifactSchema(), +])); + +/** The `error.code` vocabulary of the artifact route. */ +export const AiAnswerArtifactErrorCodeSchema = lazySchema(() => StandardErrorCode.extract([ + 'PERMISSION_DENIED', + 'MISSING_REQUIRED_FIELD', + 'VALIDATION_ERROR', + 'RESOURCE_NOT_FOUND', + 'NOT_IMPLEMENTED', + 'INTERNAL_ERROR', +])); + +/** + * `error.details.reason` on an artifact refusal. 403 PERMISSION_DENIED: + * `report_authoring_requires_manage_metadata` (a report or widget without the + * manage_metadata capability) and `report_authoring_walled` (under the isolated + * or group tenancy posture). 422 VALIDATION_ERROR: `answer_has_no_query`, and + * the reasons the answer's query cannot be carried into the artifact kind. + */ +export const AiAnswerArtifactRefusalReasonSchema = lazySchema(() => z.enum([ + 'report_authoring_requires_manage_metadata', + 'report_authoring_walled', + 'answer_has_no_query', + 'not_an_aggregate', + 'not_a_record_list', + 'filter_not_expressible', + 'sort_not_expressible', + 'limit_not_expressible', + 'latest_per_not_expressible', + 'member_not_expressible', + 'spec_refused', +])); + +/** The `error` of an artifact route failure. */ +export const AiAnswerArtifactErrorSchema = lazySchema(() => ApiErrorSchema.extend({ + code: AiAnswerArtifactErrorCodeSchema.describe('Error code'), + details: z.object({ + reason: AiAnswerArtifactRefusalReasonSchema.describe('The named refusal'), + issues: z.unknown().optional().describe('The schema issues, on spec_refused'), + }).optional().describe('Present on a named refusal'), +})); + +// ── Answer feedback ─────────────────────────────────────────────────────── + +/** An answer's rating. */ +export const AiAnswerRatingSchema = lazySchema(() => z.enum(['up', 'down'])); + +/** The caller's rating of one answer. */ +export const AiAnswerFeedbackSchema = lazySchema(() => z.object({ + conversationId: z.string().describe('The conversation of the rated answer'), + turnId: z.string().describe('The turn of the rated answer'), + rating: AiAnswerRatingSchema.describe('The rating'), + note: z.string().nullable().describe('The caller\'s note; null when none'), + createdAt: z.string().describe('Creation timestamp (ISO 8601)'), + updatedAt: z.string().nullable().describe('Last change timestamp (ISO 8601); null when never set'), +})); + +/** `GET /api/v1/ai/conversations/:id/turns/:turnId/feedback`. */ +export const GetAiAnswerFeedbackResponseSchema = lazySchema(() => z.object({ + feedback: AiAnswerFeedbackSchema.nullable().describe('The caller\'s rating of the answer; null when unrated'), +})); + +/** `POST /api/v1/ai/conversations/:id/turns/:turnId/feedback` — rate, or change the rating. */ +export const SetAiAnswerFeedbackRequestSchema = lazySchema(() => z.object({ + rating: AiAnswerRatingSchema.describe('The rating'), + note: z.string().nullable().optional().describe( + 'A note on the answer. Trimmed; blank or null stores none. A note longer than 500 characters is refused ' + + '(413 VALUE_TOO_LONG)', + ), +})); + +/** `POST /api/v1/ai/conversations/:id/turns/:turnId/feedback`. */ +export const SetAiAnswerFeedbackResponseSchema = lazySchema(() => z.object({ + feedback: AiAnswerFeedbackSchema.describe('The stored rating'), +})); + +/** The `error.code` vocabulary of the feedback routes. */ +export const AiAnswerFeedbackErrorCodeSchema = lazySchema(() => StandardErrorCode.extract([ + 'PERMISSION_DENIED', + 'MISSING_REQUIRED_FIELD', + 'VALIDATION_ERROR', + 'VALUE_TOO_LONG', + 'RESOURCE_NOT_FOUND', + 'INTERNAL_ERROR', +])); + +/** The `error` of a feedback route failure. */ +export const AiAnswerFeedbackErrorSchema = lazySchema(() => ApiErrorSchema.extend({ + code: AiAnswerFeedbackErrorCodeSchema.describe('Error code'), +})); + +// ── Types ───────────────────────────────────────────────────────────────── + +export type AiSavedQuestion = z.input; +export type ListAiSavedQuestionsResponse = z.input; +export type CreateAiSavedQuestionRequest = z.input; +export type CreateAiSavedQuestionResponse = z.input; +export type RunAiSavedQuestionResponse = z.input; +export type AiSavedQuestionErrorCode = z.input; +export type AiSavedQuestionRefusalReason = z.input; +export type AiSavedQuestionError = z.input; +export type AiAnswerArtifactKind = z.input; +export type CreateAiAnswerArtifactRequest = z.input; +export type AiAnswerArtifactDraft = z.input; +export type CreateAiAnswerArtifactResponse = z.input; +export type AiAnswerArtifactErrorCode = z.input; +export type AiAnswerArtifactRefusalReason = z.input; +export type AiAnswerArtifactError = z.input; +export type AiAnswerRating = z.input; +export type AiAnswerFeedback = z.input; +export type GetAiAnswerFeedbackResponse = z.input; +export type SetAiAnswerFeedbackRequest = z.input; +export type SetAiAnswerFeedbackResponse = z.input; +export type AiAnswerFeedbackErrorCode = z.input; +export type AiAnswerFeedbackError = z.input; diff --git a/packages/spec/src/api/index.ts b/packages/spec/src/api/index.ts index cfdc96e0769..98c0bf2d0f7 100644 --- a/packages/spec/src/api/index.ts +++ b/packages/spec/src/api/index.ts @@ -68,6 +68,9 @@ export * from './error-code-ledger.zod'; export * from './protocol.zod'; export * from './push-delivery.zod'; export * from './push-relay.zod'; +// The AI answer follow-up routes cloud's service-ai serves: saved +// questions, an answer turned into an artifact, and an answer's rating. +export * from './ai-answer.zod'; // [#10235] Per-column sortability projection: the serve-time signal the object // metadata read publishes so grids never re-derive "virtual ⇒ unsortable" from // field type (2026-08-23 ruling, option A). diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index b03654f9aac..14eba32ff15 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -4399,13 +4399,24 @@ export const AiModelsResponseSchema = lazySchema(() => z.object({ defaultModel: z.string().optional().describe('Default model id, when the service reports one'), })); +/** + * One message of a persisted conversation, as the `/ai/conversations` routes + * return it: {@link AiMessageSchema} plus the turn it belongs to. + */ +export const AiConversationMessageSchema = lazySchema(() => AiMessageSchema.extend({ + turn_id: z.string().optional().describe( + 'The turn the server stamped on the message: the `turnId` of the chat request that wrote it. ' + + 'Absent on a message stored with no turn', + ), +})); + /** A persisted AI conversation, as the `/ai/conversations` routes return it. */ export const AiConversationSchema = lazySchema(() => z.object({ id: z.string().describe('Conversation id'), title: z.string().optional().describe('Title / summary'), agentId: z.string().optional().describe('Agent this conversation is bound to'), userId: z.string().optional().describe('Owning user'), - messages: z.array(AiMessageSchema).describe('Message history'), + messages: z.array(AiConversationMessageSchema).describe('Message history'), createdAt: z.string().describe('Creation timestamp (ISO 8601)'), updatedAt: z.string().describe('Last update timestamp (ISO 8601)'), metadata: z.record(z.string(), z.unknown()).optional().describe('Conversation metadata'), @@ -4958,6 +4969,7 @@ export type MarkAllNotificationsReadResponse = z.input; +export type AiConversationMessage = z.input; export type AiChatRequest = z.input; export type AiChatResponse = z.input; export type AiStreamChunk = z.input; diff --git a/packages/spec/src/contracts/ai-service.ts b/packages/spec/src/contracts/ai-service.ts index ccb37cc9571..11ade34d54e 100644 --- a/packages/spec/src/contracts/ai-service.ts +++ b/packages/spec/src/contracts/ai-service.ts @@ -1340,6 +1340,17 @@ export interface AIObjectResult { // Conversation Management // --------------------------------------------------------------------------- +/** + * One message of a persisted conversation: a Vercel `ModelMessage` plus the + * turn it belongs to, the `turnId` it was written under + * ({@link IAIConversationService.addMessage}). Absent on a message stored with + * no turn. The wire shape is `AiConversationMessageSchema` (`api/protocol.zod.ts`). + */ +export type AIConversationMessage = ModelMessage & { + /** The turn the message was written under. */ + turn_id?: string; +}; + /** * A persistent AI conversation with message history */ @@ -1352,8 +1363,8 @@ export interface AIConversation { agentId?: string; /** User who owns the conversation */ userId?: string; - /** Messages in the conversation */ - messages: ModelMessage[]; + /** Messages in the conversation, each with the turn it was written under */ + messages: AIConversationMessage[]; /** Creation timestamp (ISO 8601) */ createdAt: string; /** Last update timestamp (ISO 8601) */ From c0d1b52323700708b5083414ef52acfecea332e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:12:50 +0000 Subject: [PATCH 02/11] chore(spec): regenerate artifacts for the AI answer route shapes Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- content/docs/references/api/ai-answer.mdx | 490 ++++++++++++++++++ content/docs/references/api/index.mdx | 3 +- content/docs/references/api/meta.json | 1 + content/docs/references/api/protocol.mdx | 25 +- content/docs/references/index.mdx | 11 +- .../api.md | 2 +- packages/spec/api-surface/api.json | 46 ++ packages/spec/api-surface/contracts.json | 1 + packages/spec/authorable-surface/api.json | 62 +++ packages/spec/declaration-map/api.json | 46 ++ .../spec/dropped-refinements.baseline.json | 15 + packages/spec/export-origins/api.json | 46 ++ packages/spec/export-origins/contracts.json | 1 + packages/spec/json-schema.manifest/api.json | 23 + 14 files changed, 760 insertions(+), 12 deletions(-) create mode 100644 content/docs/references/api/ai-answer.mdx diff --git a/content/docs/references/api/ai-answer.mdx b/content/docs/references/api/ai-answer.mdx new file mode 100644 index 00000000000..59ccfd11264 --- /dev/null +++ b/content/docs/references/api/ai-answer.mdx @@ -0,0 +1,490 @@ +--- +title: Ai Answer schema — API Protocol reference +navTitle: Ai Answer +description: "The AI answer follow-up routes: saved questions, an answer turned into an artifact, and an answer's rating." +--- + +{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} + +The AI answer follow-up routes: saved questions, an answer turned into an +artifact, and an answer's rating. + +| Method | Path | Request | `data` on success | +|:--|:--|:--|:--| +| GET | `/api/v1/ai/saved-questions` | none | `ListAiSavedQuestionsResponseSchema` | +| POST | `/api/v1/ai/saved-questions` | [`CreateAiSavedQuestionResponseSchema](CreateAiSavedQuestionRequestSchema`) (201) | +| DELETE | `/api/v1/ai/saved-questions/:id` | none | no body (204) | +| POST | `/api/v1/ai/saved-questions/:id/run` | none | `RunAiSavedQuestionResponseSchema` | +| POST | `/api/v1/ai/conversations/:id/turns/:turnId/artifact` | [`CreateAiAnswerArtifactResponseSchema](CreateAiAnswerArtifactRequestSchema`) (201) | +| GET | `/api/v1/ai/conversations/:id/turns/:turnId/feedback` | none | `GetAiAnswerFeedbackResponseSchema` | +| POST | `/api/v1/ai/conversations/:id/turns/:turnId/feedback` | [`SetAiAnswerFeedbackResponseSchema](SetAiAnswerFeedbackRequestSchema`) | +| DELETE | `/api/v1/ai/conversations/:id/turns/:turnId/feedback` | none | no body (204), also when no rating was there | + +Like the other `/api/v1/ai/**` shapes in `protocol.zod.ts`, these describe +the wire, not a protocol this repo serves: the producer is the cloud AI +service (`service-ai`: `routes/saved-question-routes.ts`, +`routes/feedback-routes.ts`, `saved/saved-question-store.ts`, +`saved/source-artifact.ts`, `feedback/answer-feedback-store.ts`). Every +success body is the platform envelope `{ success: true, data }` and each +response schema here is the `data` payload; every failure body is +`{ success: false, error }` with `error` one of the three route errors below. + +Every route is the signed-in caller's own: a saved question that is not the +caller's answers 404, and a conversation that is not the caller's answers 403 +on the artifact and feedback routes. + + +**Source:** `packages/spec/src/api/ai-answer.zod.ts` + + +## TypeScript Usage + +```typescript +import { AiAnswerArtifactDraftSchema, AiAnswerArtifactErrorSchema, AiAnswerArtifactErrorCodeSchema, AiAnswerArtifactKindSchema, AiAnswerArtifactRefusalReasonSchema, AiAnswerFeedbackSchema, AiAnswerFeedbackErrorSchema, AiAnswerFeedbackErrorCodeSchema, AiAnswerRatingSchema, AiSavedQuestionSchema, AiSavedQuestionErrorSchema, AiSavedQuestionErrorCodeSchema, AiSavedQuestionRefusalReasonSchema, CreateAiAnswerArtifactRequestSchema, CreateAiAnswerArtifactResponseSchema, CreateAiSavedQuestionRequestSchema, CreateAiSavedQuestionResponseSchema, GetAiAnswerFeedbackResponseSchema, ListAiSavedQuestionsResponseSchema, RunAiSavedQuestionResponseSchema, SetAiAnswerFeedbackRequestSchema, SetAiAnswerFeedbackResponseSchema } from '@objectstack/spec/api'; +import type { AiAnswerArtifactDraft, AiAnswerArtifactError, AiAnswerArtifactErrorCode, AiAnswerArtifactKind, AiAnswerArtifactRefusalReason, AiAnswerFeedback, AiAnswerFeedbackError, AiAnswerFeedbackErrorCode, AiAnswerRating, AiSavedQuestion, AiSavedQuestionError, AiSavedQuestionErrorCode, AiSavedQuestionRefusalReason, CreateAiAnswerArtifactRequest, CreateAiAnswerArtifactResponse, CreateAiSavedQuestionRequest, CreateAiSavedQuestionResponse, GetAiAnswerFeedbackResponse, ListAiSavedQuestionsResponse, RunAiSavedQuestionResponse, SetAiAnswerFeedbackRequest, SetAiAnswerFeedbackResponse } from '@objectstack/spec/api'; + +// Validate data +const result = AiAnswerArtifactDraftSchema.parse(data); +``` + +--- + +## AiAnswerArtifactDraft + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `Enum<'dataset' \| 'report' \| 'dashboard'>` | ✅ | Metadata type of the draft | +| **name** | `string` | ✅ | Metadata item name of the draft | + + +--- + +## AiAnswerArtifactError + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **code** | `Enum<'PERMISSION_DENIED' \| 'MISSING_REQUIRED_FIELD' \| 'VALIDATION_ERROR' \| 'RESOURCE_NOT_FOUND' \| 'NOT_IMPLEMENTED' \| 'INTERNAL_ERROR'>` | ✅ | Error code | +| **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | +| **message** | `string` | ✅ | Readable error message | +| **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | +| **refusal** | `true` | optional | Producer-declared: the 5xx this envelope carries is a deliberate refusal whose `message` is authored for the caller, so a boundary that reads the declaration keeps it verbatim (until the withhold arms read it, a declared refusal is still withheld). Absent (the default) on a declared fault, whose `message` is withheld from the body and logged for the operator; redundant on a 4xx. Presence is the declaration — `true` is the only value. | +| **category** | `string` | optional | Error category (e.g. validation, authorization) | +| **httpStatus** | `integer` | optional | HTTP status of the response carrying this error | +| **details** | `{ reason: Enum<'report_authoring_requires_manage_metadata' \| 'report_authoring_walled' \| …>; issues?: any }` | optional | Present on a named refusal | +| **requestId** | `string` | optional | Request ID for tracking | + +### Nested Shape: `AiAnswerArtifactError.details` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **reason** | `Enum<'report_authoring_requires_manage_metadata' \| 'report_authoring_walled' \| …>` | ✅ | The named refusal | +| **issues** | `any` | optional | The schema issues, on spec_refused | + + +--- + +## AiAnswerArtifactErrorCode + +### Allowed Values + +* `PERMISSION_DENIED` +* `MISSING_REQUIRED_FIELD` +* `VALIDATION_ERROR` +* `RESOURCE_NOT_FOUND` +* `NOT_IMPLEMENTED` +* `INTERNAL_ERROR` + + +--- + +## AiAnswerArtifactKind + +### Allowed Values + +* `view` +* `report` +* `widget` + + +--- + +## AiAnswerArtifactRefusalReason + +### Allowed Values + +* `report_authoring_requires_manage_metadata` +* `report_authoring_walled` +* `answer_has_no_query` +* `not_an_aggregate` +* `not_a_record_list` +* `filter_not_expressible` +* `sort_not_expressible` +* `limit_not_expressible` +* `latest_per_not_expressible` +* `member_not_expressible` +* `spec_refused` + + +--- + +## AiAnswerFeedback + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **conversationId** | `string` | ✅ | The conversation of the rated answer | +| **turnId** | `string` | ✅ | The turn of the rated answer | +| **rating** | `Enum<'up' \| 'down'>` | ✅ | The rating | +| **note** | `string \| null` | ✅ | The caller's note; null when none | +| **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | +| **updatedAt** | `string \| null` | ✅ | Last change timestamp (ISO 8601); null when never set | + + +--- + +## AiAnswerFeedbackError + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **code** | `Enum<'PERMISSION_DENIED' \| 'MISSING_REQUIRED_FIELD' \| 'VALIDATION_ERROR' \| 'VALUE_TOO_LONG' \| 'RESOURCE_NOT_FOUND' \| 'INTERNAL_ERROR'>` | ✅ | Error code | +| **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | +| **message** | `string` | ✅ | Readable error message | +| **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | +| **refusal** | `true` | optional | Producer-declared: the 5xx this envelope carries is a deliberate refusal whose `message` is authored for the caller, so a boundary that reads the declaration keeps it verbatim (until the withhold arms read it, a declared refusal is still withheld). Absent (the default) on a declared fault, whose `message` is withheld from the body and logged for the operator; redundant on a 4xx. Presence is the declaration — `true` is the only value. | +| **category** | `string` | optional | Error category (e.g. validation, authorization) | +| **httpStatus** | `integer` | optional | HTTP status of the response carrying this error | +| **details** | `any` | optional | Additional error context (e.g. field validation errors) | +| **requestId** | `string` | optional | Request ID for tracking | + + +--- + +## AiAnswerFeedbackErrorCode + +### Allowed Values + +* `PERMISSION_DENIED` +* `MISSING_REQUIRED_FIELD` +* `VALIDATION_ERROR` +* `VALUE_TOO_LONG` +* `RESOURCE_NOT_FOUND` +* `INTERNAL_ERROR` + + +--- + +## AiAnswerRating + +### Allowed Values + +* `up` +* `down` + + +--- + +## AiSavedQuestion + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **id** | `string` | ✅ | Saved question id | +| **question** | `string` | ✅ | The question text | +| **source** | `{ object: string; label?: string; filter?: any; scope: Enum<'visible_to_you' \| 'all_records'>; … } \| null` | ✅ | The query the answer ran, read off the caller's stored turn when the question was saved from an answer; null for a typed question, or when the answer ran no query | +| **agentId** | `string \| null` | ✅ | The agent of the conversation it was saved from; null for a typed question | +| **conversationId** | `string \| null` | ✅ | The conversation it was saved from; null for a typed question | +| **turnId** | `string \| null` | ✅ | The turn it was saved from; null for a typed question | +| **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | + +### Nested Shape: `AiSavedQuestion.source` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **object** | `string` | ✅ | The machine name of the object the figures were read from | +| **label** | `string` | optional | The object's plural label, or its label when it declares no plural. Translated only when the request is in Chinese and a `zh*` translation pack names the object; otherwise the authored label, not the caller's UI locale. Absent when the producer sets none: a reader falls back to `object` | +| **filter** | `any` | optional | The caller's `where`, in the `$` query dialect, exactly as the engine accepted it: machine names only, no field labels, date placeholders such as `{today}` as written. Absent when no condition applied | +| **scope** | `Enum<'visible_to_you' \| 'all_records'>` | ✅ | The row scope the figures cover, judged by the producer per call from `ISecurityService.getReadFilter(object, ctx)` for this caller and `object`, under the same context the read ran under. `visible_to_you`: a row restriction applied, so the figures cover only the records the caller may read. The organization wall is a row restriction: under the `isolated` and `group` tenancy postures `getReadFilter` answers an `organization_id` predicate on every object that carries the column, for every caller but a platform admin whose object's posture lets them cross the wall, so an organization owner there reads `visible_to_you`. `all_records`: stated only when that call RESOLVED to `undefined`, so no row restriction applied; for a caller no row rule or sharing narrows, that is the `single` posture, an object outside tenancy, a platform admin crossing the wall, or a system context. An absent security service, an absent `getReadFilter`, a call that throws or rejects, or a call made under any other context than the read's own states `visible_to_you`. A restriction applied is the fact stated, not a count of rows excluded. The value speaks for `object` only, not for the objects behind `related` lookup paths. Always present, one of these two values | +| **groupBy** | `string[]` | optional | The field names the figures were grouped by, in order | +| **aggregations** | `{ function: Enum<'count' \| 'sum' \| 'avg' \| 'min' \| 'max' \| 'count_distinct'>; field?: string }[]` | optional | The aggregations computed, in order | +| **orderBy** | `{ field: string; order?: Enum<'asc' \| 'desc'> }[]` | optional | The ordering applied, in order of precedence | +| **limit** | `integer` | optional | The row or group cut applied (a top-N read or a group cut). Present only together with `orderBy` | +| **related** | `string[]` | optional | The lookup paths read in the same call, dotted from the object (for example `client.relationship_manager`) | +| **latestPer** | `{ groupBy: string; orderField: string }` | optional | Present when the answer keeps only the latest row per group | +| **records** | `integer` | optional | How many records the figures cover — a count, never a list: the match total for a page read, the summed group counts for an aggregate or a chart, 1 for `get_record`. Absent when unknown, never guessed | +| **line** | `string` | ✅ | The finished one-line citation, in the request language. The producer keeps it to at most 280 characters; a reader does not refuse a longer one | + + +--- + +## AiSavedQuestionError + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **code** | `Enum<'PERMISSION_DENIED' \| 'MISSING_REQUIRED_FIELD' \| 'VALIDATION_ERROR' \| 'VALUE_TOO_LONG' \| 'RESOURCE_NOT_FOUND' \| 'RESOURCE_CONFLICT' \| 'INTERNAL_ERROR'>` | ✅ | Error code | +| **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | +| **message** | `string` | ✅ | Readable error message | +| **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | +| **refusal** | `true` | optional | Producer-declared: the 5xx this envelope carries is a deliberate refusal whose `message` is authored for the caller, so a boundary that reads the declaration keeps it verbatim (until the withhold arms read it, a declared refusal is still withheld). Absent (the default) on a declared fault, whose `message` is withheld from the body and logged for the operator; redundant on a 4xx. Presence is the declaration — `true` is the only value. | +| **category** | `string` | optional | Error category (e.g. validation, authorization) | +| **httpStatus** | `integer` | optional | HTTP status of the response carrying this error | +| **details** | `{ reason: Enum<'saved_question_has_no_query' \| 'saved_question_run_failed'>; question?: string }` | optional | Present on a run refusal | +| **requestId** | `string` | optional | Request ID for tracking | + +### Nested Shape: `AiSavedQuestionError.details` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **reason** | `Enum<'saved_question_has_no_query' \| 'saved_question_run_failed'>` | ✅ | The named refusal | +| **question** | `string` | optional | The saved question text, on saved_question_has_no_query | + + +--- + +## AiSavedQuestionErrorCode + +### Allowed Values + +* `PERMISSION_DENIED` +* `MISSING_REQUIRED_FIELD` +* `VALIDATION_ERROR` +* `VALUE_TOO_LONG` +* `RESOURCE_NOT_FOUND` +* `RESOURCE_CONFLICT` +* `INTERNAL_ERROR` + + +--- + +## AiSavedQuestionRefusalReason + +### Allowed Values + +* `saved_question_has_no_query` +* `saved_question_run_failed` + + +--- + +## CreateAiAnswerArtifactRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **kind** | `Enum<'view' \| 'report' \| 'widget'>` | ✅ | view: the caller's own list view; report: a dataset and a report draft; widget: a dataset and a new one-widget dashboard draft. report and widget need the manage_metadata capability | +| **toolCallId** | `string` | optional | The tool call of the turn to build from; the turn's last query when omitted | +| **label** | `string` | optional | The artifact label; the turn's question when omitted. Cut to 120 characters | + + +--- + +## CreateAiAnswerArtifactResponse + +### Union Options + +This schema accepts one of the following structures: + +#### Option 1 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **kind** | `'view'` | ✅ | The artifact kind | +| **view** | `{ id?: string; object_name: string; label: string; config: Record }` | ✅ | The saved personal view | + +### Nested Shape: `CreateAiAnswerArtifactResponse[kind='view'].view` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **id** | `string` | optional | The personal view row id, when the engine answered one | +| **object_name** | `string` | ✅ | The object the view lists | +| **label** | `string` | ✅ | The view label | +| **config** | `Record` | ✅ | The list view configuration, a ListView | + +--- + +#### Option 2 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **kind** | `'report'` | ✅ | The artifact kind | +| **published** | `false` | ✅ | Always false: the drafts are not published | +| **drafts** | `{ type: Enum<'dataset' \| 'report' \| 'dashboard'>; name: string }[]` | ✅ | The drafts staged: the dataset, then the report | +| **dataset** | `Record` | ✅ | The dataset draft body | +| **report** | `Record` | ✅ | The report draft body | + +### Nested Shape: `CreateAiAnswerArtifactResponse[kind='report'].drafts[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `Enum<'dataset' \| 'report' \| 'dashboard'>` | ✅ | Metadata type of the draft | +| **name** | `string` | ✅ | Metadata item name of the draft | + +--- + +#### Option 3 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **kind** | `'widget'` | ✅ | The artifact kind | +| **published** | `false` | ✅ | Always false: the drafts are not published | +| **drafts** | `{ type: Enum<'dataset' \| 'report' \| 'dashboard'>; name: string }[]` | ✅ | The drafts staged: the dataset, then the dashboard | +| **dataset** | `Record` | ✅ | The dataset draft body | +| **dashboard** | `Record` | ✅ | The dashboard draft body | + +### Nested Shape: `CreateAiAnswerArtifactResponse[kind='widget'].drafts[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `Enum<'dataset' \| 'report' \| 'dashboard'>` | ✅ | Metadata type of the draft | +| **name** | `string` | ✅ | Metadata item name of the draft | + +--- + + +--- + +## CreateAiSavedQuestionRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **question** | `string` | optional | The question text. Required without `conversationId`; from an answer it replaces the turn's own question. A question longer than 2000 characters is refused (413 VALUE_TOO_LONG) | +| **conversationId** | `string` | optional | The caller's conversation the answer is in; sent with `turnId` | +| **turnId** | `string` | optional | The turn of that conversation; sent with `conversationId` | +| **toolCallId** | `string` | optional | The tool call of the turn whose query is saved; the turn's last query when omitted | + + +--- + +## CreateAiSavedQuestionResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **question** | `{ id: string; question: string; source: object \| null; agentId: string \| null; … }` | ✅ | The saved question | + +### Nested Shape: `CreateAiSavedQuestionResponse.question` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **id** | `string` | ✅ | Saved question id | +| **question** | `string` | ✅ | The question text | +| **source** | `{ object: string; label?: string; filter?: any; scope: Enum<'visible_to_you' \| 'all_records'>; … } \| null` | ✅ | The query the answer ran, read off the caller's stored turn when the question was saved from an answer; null for a typed question, or when the answer ran no query | +| **agentId** | `string \| null` | ✅ | The agent of the conversation it was saved from; null for a typed question | +| **conversationId** | `string \| null` | ✅ | The conversation it was saved from; null for a typed question | +| **turnId** | `string \| null` | ✅ | The turn it was saved from; null for a typed question | +| **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | + + +--- + +## GetAiAnswerFeedbackResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **feedback** | `{ conversationId: string; turnId: string; rating: Enum<'up' \| 'down'>; note: string \| null; … } \| null` | ✅ | The caller's rating of the answer; null when unrated | + +### Nested Shape: `GetAiAnswerFeedbackResponse.feedback` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **conversationId** | `string` | ✅ | The conversation of the rated answer | +| **turnId** | `string` | ✅ | The turn of the rated answer | +| **rating** | `Enum<'up' \| 'down'>` | ✅ | The rating | +| **note** | `string \| null` | ✅ | The caller's note; null when none | +| **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | +| **updatedAt** | `string \| null` | ✅ | Last change timestamp (ISO 8601); null when never set | + + +--- + +## ListAiSavedQuestionsResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **questions** | `{ id: string; question: string; source: object \| null; agentId: string \| null; … }[]` | ✅ | The caller's saved questions in the session's organization, newest first, at most 200 | + +### Nested Shape: `ListAiSavedQuestionsResponse.questions[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **id** | `string` | ✅ | Saved question id | +| **question** | `string` | ✅ | The question text | +| **source** | `{ object: string; label?: string; filter?: any; scope: Enum<'visible_to_you' \| 'all_records'>; … } \| null` | ✅ | The query the answer ran, read off the caller's stored turn when the question was saved from an answer; null for a typed question, or when the answer ran no query | +| **agentId** | `string \| null` | ✅ | The agent of the conversation it was saved from; null for a typed question | +| **conversationId** | `string \| null` | ✅ | The conversation it was saved from; null for a typed question | +| **turnId** | `string \| null` | ✅ | The turn it was saved from; null for a typed question | +| **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | + + +--- + +## RunAiSavedQuestionResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **question** | `string` | ✅ | The saved question text | +| **toolName** | `Enum<'aggregate_data' \| 'query_records'>` | ✅ | The data tool that ran the query: aggregate_data for an aggregate, query_records for a record read | +| **result** | `any` | ✅ | The data tool's result, parsed from its JSON text | + + +--- + +## SetAiAnswerFeedbackRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **rating** | `Enum<'up' \| 'down'>` | ✅ | The rating | +| **note** | `string \| null` | optional | A note on the answer. Trimmed; blank or null stores none. A note longer than 500 characters is refused (413 VALUE_TOO_LONG) | + + +--- + +## SetAiAnswerFeedbackResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **feedback** | `{ conversationId: string; turnId: string; rating: Enum<'up' \| 'down'>; note: string \| null; … }` | ✅ | The stored rating | + +### Nested Shape: `SetAiAnswerFeedbackResponse.feedback` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **conversationId** | `string` | ✅ | The conversation of the rated answer | +| **turnId** | `string` | ✅ | The turn of the rated answer | +| **rating** | `Enum<'up' \| 'down'>` | ✅ | The rating | +| **note** | `string \| null` | ✅ | The caller's note; null when none | +| **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | +| **updatedAt** | `string \| null` | ✅ | Last change timestamp (ISO 8601); null when never set | + + +--- + diff --git a/content/docs/references/api/index.mdx b/content/docs/references/api/index.mdx index c91135c2aa1..cb168c54756 100644 --- a/content/docs/references/api/index.mdx +++ b/content/docs/references/api/index.mdx @@ -1,7 +1,7 @@ --- title: API Protocol — complete schema reference navTitle: API Protocol -description: "The ObjectStack API Protocol in 36 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example." +description: "The ObjectStack API Protocol in 37 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -9,6 +9,7 @@ description: "The ObjectStack API Protocol in 36 reference pages: every schema i This section contains all protocol schemas for the api layer of ObjectStack. + diff --git a/content/docs/references/api/meta.json b/content/docs/references/api/meta.json index 0d0ce802c85..f5880925b65 100644 --- a/content/docs/references/api/meta.json +++ b/content/docs/references/api/meta.json @@ -32,6 +32,7 @@ "plugin-rest-api", "storage", "---More---", + "ai-answer", "app-bundle", "error-code-ledger", "misc", diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index feee8113694..273fc55fa21 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1,7 +1,7 @@ --- title: Protocol schema — API Protocol reference navTitle: Protocol -description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 147 more — each property with its type, default and a TypeScript example." +description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 148 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilit ## TypeScript Usage ```typescript -import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, BuildProbeReportSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DiffMetaItemRequestSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemRequestSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, RuntimeBuildIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; -import type { AiAgentCapabilities, AiAgentChatRequest, AiAgentSummary, AiAgentsResponse, AiChatRequest, AiChatResponse, AiCompleteRequest, AiConversation, AiMessage, AiModelsResponse, AiPendingAction, AiPendingActionStatus, AiStreamChunk, ApproveAiPendingActionResponse, AuditMetaItemRequest, AuditMetaItemResponse, AutomationActionsResponse, AutomationTriggerRequest, AutomationTriggerResponse, BatchDataRequest, BatchDataResponse, BuildProbeReport, CheckPermissionRequest, CheckPermissionResponse, CloneDataResponse, CreateAiConversationRequest, CreateDataRequest, CreateDataResponse, CreateManyDataRequest, CreateManyDataResponse, DeleteDataRequest, DeleteDataResponse, DeleteManyDataRequest, DeleteManyDataResponse, DeleteMetaItemRequest, DeleteMetaItemResponse, DiffMetaItemRequest, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, FindDataRequest, FindDataResponse, FindReferencesToMetaResponse, FlowRegistration, FlowRegistrationRefusal, GetDataRequest, GetDataResponse, GetDiscoveryRequest, GetDiscoveryResponse, GetEffectivePermissionsRequest, GetEffectivePermissionsResponse, GetFieldLabelsRequest, GetFieldLabelsResponse, GetLocalesRequest, GetLocalesResponse, GetMetaDiagnosticsResponse, GetMetaItemCachedRequest, GetMetaItemCachedResponse, GetMetaItemLayeredRequest, GetMetaItemLayeredResponse, GetMetaItemRequest, GetMetaItemResponse, GetMetaItemsRequest, GetMetaItemsResponse, GetMetaTypesRequest, GetMetaTypesResponse, GetNotificationPreferencesRequest, GetNotificationPreferencesResponse, GetObjectPermissionsRequest, GetObjectPermissionsResponse, GetPackageRequest, GetPackageResponse, GetPresenceRequest, GetPresenceResponse, GetPublishedMetaItemResponse, GetRecordFieldAccessResponse, GetTranslationsRequest, GetTranslationsResponse, GetUiViewRequest, GetUiViewResponse, HistoryMetaItemRequest, HistoryMetaItemResponse, InstallPackageRequest, InstallPackageResponse, ListAiConversationsRequest, ListAiConversationsResponse, ListAiPendingActionsRequest, ListAiPendingActionsResponse, ListDraftsResponse, ListNotificationsRequest, ListNotificationsResponse, ListPackagesRequest, ListPackagesResponse, MarkAllNotificationsReadRequest, MarkAllNotificationsReadResponse, MarkNotificationsReadRequest, MarkNotificationsReadResponse, MetadataAuthoringClient, MetadataAuthoringSurface, MetadataConflictError, Notification, NotificationPreferences, PublicFormSubmitResponse, PublishMetaItemRequest, PublishMetaItemResponse, PublishPackageDraftsRequest, PublishPackageDraftsResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeDisconnectRequest, RealtimeDisconnectResponse, RealtimeSubscribeRequest, RealtimeSubscribeResponse, RealtimeUnsubscribeRequest, RealtimeUnsubscribeResponse, RegisterDeviceRequest, RegisterDeviceResponse, RejectAiPendingActionResponse, RollbackMetaItemRequest, RollbackMetaItemResponse, RuntimeAuthoringIssue, RuntimeBuildIssue, SaveMetaItemRequest, SaveMetaItemResponse, SearchAllHit, SearchAllPageHit, SearchAllResponse, SeedAppliedIdList, SeedAppliedLanded, SetPresenceRequest, SetPresenceResponse, UninstallPackageRequest, UninstallPackageResponse, UnregisterDeviceRequest, UnregisterDeviceResponse, UpdateAiConversationRequest, UpdateDataRequest, UpdateDataResponse, UpdateManyDataRequest, UpdateManyDataResponse, UpdateNotificationPreferencesRequest, UpdateNotificationPreferencesResponse, ValidateDataIssue, ValidateDataRequest, ValidateDataResponse } from '@objectstack/spec/api'; +import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiConversationMessageSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, BuildProbeReportSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DiffMetaItemRequestSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemRequestSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, RuntimeBuildIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; +import type { AiAgentCapabilities, AiAgentChatRequest, AiAgentSummary, AiAgentsResponse, AiChatRequest, AiChatResponse, AiCompleteRequest, AiConversation, AiConversationMessage, AiMessage, AiModelsResponse, AiPendingAction, AiPendingActionStatus, AiStreamChunk, ApproveAiPendingActionResponse, AuditMetaItemRequest, AuditMetaItemResponse, AutomationActionsResponse, AutomationTriggerRequest, AutomationTriggerResponse, BatchDataRequest, BatchDataResponse, BuildProbeReport, CheckPermissionRequest, CheckPermissionResponse, CloneDataResponse, CreateAiConversationRequest, CreateDataRequest, CreateDataResponse, CreateManyDataRequest, CreateManyDataResponse, DeleteDataRequest, DeleteDataResponse, DeleteManyDataRequest, DeleteManyDataResponse, DeleteMetaItemRequest, DeleteMetaItemResponse, DiffMetaItemRequest, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, FindDataRequest, FindDataResponse, FindReferencesToMetaResponse, FlowRegistration, FlowRegistrationRefusal, GetDataRequest, GetDataResponse, GetDiscoveryRequest, GetDiscoveryResponse, GetEffectivePermissionsRequest, GetEffectivePermissionsResponse, GetFieldLabelsRequest, GetFieldLabelsResponse, GetLocalesRequest, GetLocalesResponse, GetMetaDiagnosticsResponse, GetMetaItemCachedRequest, GetMetaItemCachedResponse, GetMetaItemLayeredRequest, GetMetaItemLayeredResponse, GetMetaItemRequest, GetMetaItemResponse, GetMetaItemsRequest, GetMetaItemsResponse, GetMetaTypesRequest, GetMetaTypesResponse, GetNotificationPreferencesRequest, GetNotificationPreferencesResponse, GetObjectPermissionsRequest, GetObjectPermissionsResponse, GetPackageRequest, GetPackageResponse, GetPresenceRequest, GetPresenceResponse, GetPublishedMetaItemResponse, GetRecordFieldAccessResponse, GetTranslationsRequest, GetTranslationsResponse, GetUiViewRequest, GetUiViewResponse, HistoryMetaItemRequest, HistoryMetaItemResponse, InstallPackageRequest, InstallPackageResponse, ListAiConversationsRequest, ListAiConversationsResponse, ListAiPendingActionsRequest, ListAiPendingActionsResponse, ListDraftsResponse, ListNotificationsRequest, ListNotificationsResponse, ListPackagesRequest, ListPackagesResponse, MarkAllNotificationsReadRequest, MarkAllNotificationsReadResponse, MarkNotificationsReadRequest, MarkNotificationsReadResponse, MetadataAuthoringClient, MetadataAuthoringSurface, MetadataConflictError, Notification, NotificationPreferences, PublicFormSubmitResponse, PublishMetaItemRequest, PublishMetaItemResponse, PublishPackageDraftsRequest, PublishPackageDraftsResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeDisconnectRequest, RealtimeDisconnectResponse, RealtimeSubscribeRequest, RealtimeSubscribeResponse, RealtimeUnsubscribeRequest, RealtimeUnsubscribeResponse, RegisterDeviceRequest, RegisterDeviceResponse, RejectAiPendingActionResponse, RollbackMetaItemRequest, RollbackMetaItemResponse, RuntimeAuthoringIssue, RuntimeBuildIssue, SaveMetaItemRequest, SaveMetaItemResponse, SearchAllHit, SearchAllPageHit, SearchAllResponse, SeedAppliedIdList, SeedAppliedLanded, SetPresenceRequest, SetPresenceResponse, UninstallPackageRequest, UninstallPackageResponse, UnregisterDeviceRequest, UnregisterDeviceResponse, UpdateAiConversationRequest, UpdateDataRequest, UpdateDataResponse, UpdateManyDataRequest, UpdateManyDataResponse, UpdateNotificationPreferencesRequest, UpdateNotificationPreferencesResponse, ValidateDataIssue, ValidateDataRequest, ValidateDataResponse } from '@objectstack/spec/api'; // Validate data const result = AiAgentCapabilitiesSchema.parse(data); @@ -172,7 +172,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **title** | `string` | optional | Title / summary | | **agentId** | `string` | optional | Agent this conversation is bound to | | **userId** | `string` | optional | Owning user | -| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[] } & Record)[]` | ✅ | Message history | +| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turn_id?: string } & Record)[]` | ✅ | Message history | | **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | | **updatedAt** | `string` | ✅ | Last update timestamp (ISO 8601) | | **metadata** | `Record` | optional | Conversation metadata | @@ -184,6 +184,21 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **role** | `Enum<'system' \| 'user' \| 'assistant' \| 'tool'>` | ✅ | Message role | | **content** | `any` | optional | Message content: a string, or an array of content parts | | **parts** | `any[]` | optional | Vercel AI SDK v6 message parts (alternative to `content`) | +| **turn_id** | `string` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent on a message stored with no turn | + + +--- + +## AiConversationMessage + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **role** | `Enum<'system' \| 'user' \| 'assistant' \| 'tool'>` | ✅ | Message role | +| **content** | `any` | optional | Message content: a string, or an array of content parts | +| **parts** | `any[]` | optional | Vercel AI SDK v6 message parts (alternative to `content`) | +| **turn_id** | `string` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent on a message stored with no turn | --- @@ -2277,7 +2292,7 @@ Install package response | **title** | `string` | optional | Title / summary | | **agentId** | `string` | optional | Agent this conversation is bound to | | **userId** | `string` | optional | Owning user | -| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[] } & Record)[]` | ✅ | Message history | +| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turn_id?: string } & Record)[]` | ✅ | Message history | | **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | | **updatedAt** | `string` | ✅ | Last update timestamp (ISO 8601) | | **metadata** | `Record` | optional | Conversation metadata | diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 8a6f4058679..22670b105c4 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1675 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1698 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -21,7 +21,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | | [AI Protocol](/docs/references/ai) | 14 | 84 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](/docs/references/api) | 36 | 496 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](/docs/references/api) | 37 | 519 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 188 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | @@ -34,7 +34,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 180 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **218** | **1675** | 14 protocol modules | +| **Total** | **219** | **1698** | 14 protocol modules | --- @@ -65,12 +65,13 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **36 pages, 496 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 519 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. | File | Schemas | | :--- | :--- | +| [`ai-answer.zod.ts`](/docs/references/api/ai-answer) | `AiAnswerArtifactDraft`, `AiAnswerArtifactError`, `AiAnswerArtifactErrorCode`, `AiAnswerArtifactKind`, `AiAnswerArtifactRefusalReason`, `AiAnswerFeedback`, `AiAnswerFeedbackError`, `AiAnswerFeedbackErrorCode`, `AiAnswerRating`, `AiSavedQuestion`, `AiSavedQuestionError`, `AiSavedQuestionErrorCode`, `AiSavedQuestionRefusalReason`, `CreateAiAnswerArtifactRequest`, `CreateAiAnswerArtifactResponse`, `CreateAiSavedQuestionRequest`, `CreateAiSavedQuestionResponse`, `GetAiAnswerFeedbackResponse`, `ListAiSavedQuestionsResponse`, `RunAiSavedQuestionResponse`, `SetAiAnswerFeedbackRequest`, `SetAiAnswerFeedbackResponse` | | [`analytics.zod.ts`](/docs/references/api/analytics) | `AnalyticsEndpoint`, `AnalyticsMetadataResponse`, `AnalyticsQueryRequest`, `AnalyticsResultResponse`, `AnalyticsSqlResponse`, `DatasetCompareTo`, `DatasetQueryBatchEntry`, `DatasetQueryBatchRequest`, `DatasetQueryBatchResponse`, `DatasetSelection`, `DatasetTotals`, `GetAnalyticsMetaRequest` | | [`app-bundle.zod.ts`](/docs/references/api/app-bundle) | `AppMetadataBundleResponse` | | [`auth.zod.ts`](/docs/references/api/auth) | `AuthProvider`, `LoginRequest`, `LoginType`, `MePermissionsAnonymousResponse`, `MePermissionsAuthenticatedResponse`, `MePermissionsResponse`, `RefreshTokenRequest`, `RegisterRequest`, `Session`, `SessionResponse`, `SessionUser`, `UserProfileResponse` | @@ -94,7 +95,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`package-api-assembled.zod.ts`](/docs/references/api/package-api-assembled) | `AssembledInstalledPackage`, `GetInstalledPackageResponse`, `InstalledPackageAtEitherStage`, `ListInstalledPackagesResponse` | | [`package-lifecycle.zod.ts`](/docs/references/api/package-lifecycle) | `DiscardPackageDraftsResponse`, `DuplicatePackageResponse`, `EnsureCustomizationPackageRequest`, `EnsureCustomizationPackageResponse`, `GetPackageCustomizationsRequest`, `GetPackageCustomizationsResponse`, `ImportUnmanagedPackageRequest`, `ImportUnmanagedPackageResponse`, `ListPackageCommitsResponse`, `PackageExportBundle`, `PackageExportManifest`, `PackagePublishResult`, `ReassignOrphanedMetadataResponse`, `RevertPackageCommitResponse`, `RollbackToPackageCommitResponse` | | [`plugin-rest-api.zod.ts`](/docs/references/api/plugin-rest-api) | `ErrorHandlingConfig`, `OpenApiGenerationConfig`, `RequestValidationConfig`, `ResponseEnvelopeConfig`, `RestApiEndpoint`, `RestApiPluginConfig`, `RestApiRouteCategory`, `RestApiRouteRegistration`, `ValidationMode` | -| [`protocol.zod.ts`](/docs/references/api/protocol) | `AiAgentCapabilities`, `AiAgentChatRequest`, `AiAgentSummary`, `AiAgentsResponse`, `AiChatRequest`, `AiChatResponse`, `AiCompleteRequest`, `AiConversation`, `AiMessage`, `AiModelsResponse`, `AiPendingAction`, `AiPendingActionStatus`, `AiStreamChunk`, `ApproveAiPendingActionResponse`, `AuditMetaItemRequest`, `AuditMetaItemResponse`, `AutomationActionsResponse`, `AutomationTriggerRequest`, `AutomationTriggerResponse`, `BatchDataRequest`, `BatchDataResponse`, `BuildProbeReport`, `CheckPermissionRequest`, `CheckPermissionResponse`, `CloneDataResponse`, `CreateAiConversationRequest`, `CreateDataRequest`, `CreateDataResponse`, `CreateManyDataRequest`, `CreateManyDataResponse`, `DeleteDataRequest`, `DeleteDataResponse`, `DeleteManyDataRequest`, `DeleteManyDataResponse`, `DeleteMetaItemRequest`, `DeleteMetaItemResponse`, `DiffMetaItemRequest`, `DiffMetaItemResponse`, `DisablePackageRequest`, `DisablePackageResponse`, `EnablePackageRequest`, `EnablePackageResponse`, `FindDataRequest`, `FindDataResponse`, `FindReferencesToMetaResponse`, `FlowRegistration`, `FlowRegistrationRefusal`, `GetDataRequest`, `GetDataResponse`, `GetDiscoveryRequest`, `GetDiscoveryResponse`, `GetEffectivePermissionsRequest`, `GetEffectivePermissionsResponse`, `GetFieldLabelsRequest`, `GetFieldLabelsResponse`, `GetLocalesRequest`, `GetLocalesResponse`, `GetMetaDiagnosticsResponse`, `GetMetaItemCachedRequest`, `GetMetaItemCachedResponse`, `GetMetaItemLayeredRequest`, `GetMetaItemLayeredResponse`, `GetMetaItemRequest`, `GetMetaItemResponse`, `GetMetaItemsRequest`, `GetMetaItemsResponse`, `GetMetaTypesRequest`, `GetMetaTypesResponse`, `GetNotificationPreferencesRequest`, `GetNotificationPreferencesResponse`, `GetObjectPermissionsRequest`, `GetObjectPermissionsResponse`, `GetPackageRequest`, `GetPackageResponse`, `GetPresenceRequest`, `GetPresenceResponse`, `GetPublishedMetaItemResponse`, `GetRecordFieldAccessResponse`, `GetTranslationsRequest`, `GetTranslationsResponse`, `GetUiViewRequest`, `GetUiViewResponse`, `HistoryMetaItemRequest`, `HistoryMetaItemResponse`, `HttpFindQueryParams`, `InstallPackageRequest`, `InstallPackageResponse`, `ListAiConversationsRequest`, `ListAiConversationsResponse`, `ListAiPendingActionsRequest`, `ListAiPendingActionsResponse`, `ListDraftsResponse`, `ListNotificationsRequest`, `ListNotificationsResponse`, `ListPackagesRequest`, `ListPackagesResponse`, `MarkAllNotificationsReadRequest`, `MarkAllNotificationsReadResponse`, `MarkNotificationsReadRequest`, `MarkNotificationsReadResponse`, `MetadataAuthoringClient`, `MetadataAuthoringSurface`, `MetadataConflictError`, `Notification`, `NotificationPreferences`, `PublicFormSubmitResponse`, `PublishMetaItemRequest`, `PublishMetaItemResponse`, `PublishPackageDraftsRequest`, `PublishPackageDraftsResponse`, `RealtimeConnectRequest`, `RealtimeConnectResponse`, `RealtimeDisconnectRequest`, `RealtimeDisconnectResponse`, `RealtimeSubscribeRequest`, `RealtimeSubscribeResponse`, `RealtimeUnsubscribeRequest`, `RealtimeUnsubscribeResponse`, `RegisterDeviceRequest`, `RegisterDeviceResponse`, `RejectAiPendingActionResponse`, `RollbackMetaItemRequest`, `RollbackMetaItemResponse`, `RuntimeAuthoringIssue`, `RuntimeBuildIssue`, `SaveMetaItemRequest`, `SaveMetaItemResponse`, `SearchAllHit`, `SearchAllPageHit`, `SearchAllResponse`, `SeedAppliedIdList`, `SeedAppliedLanded`, `SetPresenceRequest`, `SetPresenceResponse`, `UninstallPackageRequest`, `UninstallPackageResponse`, `UnregisterDeviceRequest`, `UnregisterDeviceResponse`, `UpdateAiConversationRequest`, `UpdateDataRequest`, `UpdateDataResponse`, `UpdateManyDataRequest`, `UpdateManyDataResponse`, `UpdateNotificationPreferencesRequest`, `UpdateNotificationPreferencesResponse`, `ValidateDataIssue`, `ValidateDataRequest`, `ValidateDataResponse` | +| [`protocol.zod.ts`](/docs/references/api/protocol) | `AiAgentCapabilities`, `AiAgentChatRequest`, `AiAgentSummary`, `AiAgentsResponse`, `AiChatRequest`, `AiChatResponse`, `AiCompleteRequest`, `AiConversation`, `AiConversationMessage`, `AiMessage`, `AiModelsResponse`, `AiPendingAction`, `AiPendingActionStatus`, `AiStreamChunk`, `ApproveAiPendingActionResponse`, `AuditMetaItemRequest`, `AuditMetaItemResponse`, `AutomationActionsResponse`, `AutomationTriggerRequest`, `AutomationTriggerResponse`, `BatchDataRequest`, `BatchDataResponse`, `BuildProbeReport`, `CheckPermissionRequest`, `CheckPermissionResponse`, `CloneDataResponse`, `CreateAiConversationRequest`, `CreateDataRequest`, `CreateDataResponse`, `CreateManyDataRequest`, `CreateManyDataResponse`, `DeleteDataRequest`, `DeleteDataResponse`, `DeleteManyDataRequest`, `DeleteManyDataResponse`, `DeleteMetaItemRequest`, `DeleteMetaItemResponse`, `DiffMetaItemRequest`, `DiffMetaItemResponse`, `DisablePackageRequest`, `DisablePackageResponse`, `EnablePackageRequest`, `EnablePackageResponse`, `FindDataRequest`, `FindDataResponse`, `FindReferencesToMetaResponse`, `FlowRegistration`, `FlowRegistrationRefusal`, `GetDataRequest`, `GetDataResponse`, `GetDiscoveryRequest`, `GetDiscoveryResponse`, `GetEffectivePermissionsRequest`, `GetEffectivePermissionsResponse`, `GetFieldLabelsRequest`, `GetFieldLabelsResponse`, `GetLocalesRequest`, `GetLocalesResponse`, `GetMetaDiagnosticsResponse`, `GetMetaItemCachedRequest`, `GetMetaItemCachedResponse`, `GetMetaItemLayeredRequest`, `GetMetaItemLayeredResponse`, `GetMetaItemRequest`, `GetMetaItemResponse`, `GetMetaItemsRequest`, `GetMetaItemsResponse`, `GetMetaTypesRequest`, `GetMetaTypesResponse`, `GetNotificationPreferencesRequest`, `GetNotificationPreferencesResponse`, `GetObjectPermissionsRequest`, `GetObjectPermissionsResponse`, `GetPackageRequest`, `GetPackageResponse`, `GetPresenceRequest`, `GetPresenceResponse`, `GetPublishedMetaItemResponse`, `GetRecordFieldAccessResponse`, `GetTranslationsRequest`, `GetTranslationsResponse`, `GetUiViewRequest`, `GetUiViewResponse`, `HistoryMetaItemRequest`, `HistoryMetaItemResponse`, `HttpFindQueryParams`, `InstallPackageRequest`, `InstallPackageResponse`, `ListAiConversationsRequest`, `ListAiConversationsResponse`, `ListAiPendingActionsRequest`, `ListAiPendingActionsResponse`, `ListDraftsResponse`, `ListNotificationsRequest`, `ListNotificationsResponse`, `ListPackagesRequest`, `ListPackagesResponse`, `MarkAllNotificationsReadRequest`, `MarkAllNotificationsReadResponse`, `MarkNotificationsReadRequest`, `MarkNotificationsReadResponse`, `MetadataAuthoringClient`, `MetadataAuthoringSurface`, `MetadataConflictError`, `Notification`, `NotificationPreferences`, `PublicFormSubmitResponse`, `PublishMetaItemRequest`, `PublishMetaItemResponse`, `PublishPackageDraftsRequest`, `PublishPackageDraftsResponse`, `RealtimeConnectRequest`, `RealtimeConnectResponse`, `RealtimeDisconnectRequest`, `RealtimeDisconnectResponse`, `RealtimeSubscribeRequest`, `RealtimeSubscribeResponse`, `RealtimeUnsubscribeRequest`, `RealtimeUnsubscribeResponse`, `RegisterDeviceRequest`, `RegisterDeviceResponse`, `RejectAiPendingActionResponse`, `RollbackMetaItemRequest`, `RollbackMetaItemResponse`, `RuntimeAuthoringIssue`, `RuntimeBuildIssue`, `SaveMetaItemRequest`, `SaveMetaItemResponse`, `SearchAllHit`, `SearchAllPageHit`, `SearchAllResponse`, `SeedAppliedIdList`, `SeedAppliedLanded`, `SetPresenceRequest`, `SetPresenceResponse`, `UninstallPackageRequest`, `UninstallPackageResponse`, `UnregisterDeviceRequest`, `UnregisterDeviceResponse`, `UpdateAiConversationRequest`, `UpdateDataRequest`, `UpdateDataResponse`, `UpdateManyDataRequest`, `UpdateManyDataResponse`, `UpdateNotificationPreferencesRequest`, `UpdateNotificationPreferencesResponse`, `ValidateDataIssue`, `ValidateDataRequest`, `ValidateDataResponse` | | [`push-delivery.zod.ts`](/docs/references/api/push-delivery) | `PushDeliveryData`, `PushRoute` | | [`push-relay.zod.ts`](/docs/references/api/push-relay) | `PushRelayDelivery`, `PushRelayError`, `PushRelayErrorResponse`, `PushRelayPayload`, `PushRelayPriority`, `PushRelayRequest`, `PushRelayResponse`, `PushRelayResult`, `PushRelayResultStatus` | | [`query-adapter.zod.ts`](/docs/references/api/query-adapter) | `ODataQueryAdapter`, `OperatorMapping`, `QueryAdapterConfig`, `QueryAdapterTarget`, `RestQueryAdapter` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md index 2bf7a827cde..31269913097 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `api/` | 514 | +| `api/` | 531 | diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index 22d1341d6bb..e8f57c64392 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -13,6 +13,24 @@ "AiAgentSummarySchema (const)", "AiAgentsResponse (type)", "AiAgentsResponseSchema (const)", + "AiAnswerArtifactDraft (type)", + "AiAnswerArtifactDraftSchema (const)", + "AiAnswerArtifactError (type)", + "AiAnswerArtifactErrorCode (type)", + "AiAnswerArtifactErrorCodeSchema (const)", + "AiAnswerArtifactErrorSchema (const)", + "AiAnswerArtifactKind (type)", + "AiAnswerArtifactKindSchema (const)", + "AiAnswerArtifactRefusalReason (type)", + "AiAnswerArtifactRefusalReasonSchema (const)", + "AiAnswerFeedback (type)", + "AiAnswerFeedbackError (type)", + "AiAnswerFeedbackErrorCode (type)", + "AiAnswerFeedbackErrorCodeSchema (const)", + "AiAnswerFeedbackErrorSchema (const)", + "AiAnswerFeedbackSchema (const)", + "AiAnswerRating (type)", + "AiAnswerRatingSchema (const)", "AiChatRequest (type)", "AiChatRequestSchema (const)", "AiChatResponse (type)", @@ -20,6 +38,8 @@ "AiCompleteRequest (type)", "AiCompleteRequestSchema (const)", "AiConversation (type)", + "AiConversationMessage (type)", + "AiConversationMessageSchema (const)", "AiConversationSchema (const)", "AiMessage (type)", "AiMessageSchema (const)", @@ -29,6 +49,14 @@ "AiPendingActionSchema (const)", "AiPendingActionStatus (type)", "AiPendingActionStatusSchema (const)", + "AiSavedQuestion (type)", + "AiSavedQuestionError (type)", + "AiSavedQuestionErrorCode (type)", + "AiSavedQuestionErrorCodeSchema (const)", + "AiSavedQuestionErrorSchema (const)", + "AiSavedQuestionRefusalReason (type)", + "AiSavedQuestionRefusalReasonSchema (const)", + "AiSavedQuestionSchema (const)", "AiStreamChunk (type)", "AiStreamChunkSchema (const)", "AnalyticsEndpoint (const)", @@ -204,8 +232,16 @@ "ConceptListResponseSchema (const)", "ConflictResolutionStrategy (const)", "ConflictResolutionStrategy (type)", + "CreateAiAnswerArtifactRequest (type)", + "CreateAiAnswerArtifactRequestSchema (const)", + "CreateAiAnswerArtifactResponse (type)", + "CreateAiAnswerArtifactResponseSchema (const)", "CreateAiConversationRequest (type)", "CreateAiConversationRequestSchema (const)", + "CreateAiSavedQuestionRequest (type)", + "CreateAiSavedQuestionRequestSchema (const)", + "CreateAiSavedQuestionResponse (type)", + "CreateAiSavedQuestionResponseSchema (const)", "CreateDataRequest (type)", "CreateDataRequestSchema (const)", "CreateDataResponse (type)", @@ -447,6 +483,8 @@ "GeneratedApiDocumentationSchema (const)", "GeneratedEndpoint (type)", "GeneratedEndpointSchema (const)", + "GetAiAnswerFeedbackResponse (type)", + "GetAiAnswerFeedbackResponseSchema (const)", "GetAnalyticsMetaRequest (type)", "GetAnalyticsMetaRequestSchema (const)", "GetAuthConfigResponse (type)", @@ -617,6 +655,8 @@ "ListAiPendingActionsRequestSchema (const)", "ListAiPendingActionsResponse (type)", "ListAiPendingActionsResponseSchema (const)", + "ListAiSavedQuestionsResponse (type)", + "ListAiSavedQuestionsResponseSchema (const)", "ListDraftsResponse (type)", "ListDraftsResponseParsed (type)", "ListDraftsResponseSchema (const)", @@ -1086,6 +1126,8 @@ "RouterConfig (type)", "RouterConfigParsed (type)", "RouterConfigSchema (const)", + "RunAiSavedQuestionResponse (type)", + "RunAiSavedQuestionResponseSchema (const)", "RuntimeAuthoringIssue (type)", "RuntimeAuthoringIssueSchema (const)", "RuntimeBuildIssue (type)", @@ -1123,6 +1165,10 @@ "SessionUser (type)", "SessionUserParsed (type)", "SessionUserSchema (const)", + "SetAiAnswerFeedbackRequest (type)", + "SetAiAnswerFeedbackRequestSchema (const)", + "SetAiAnswerFeedbackResponse (type)", + "SetAiAnswerFeedbackResponseSchema (const)", "SetPresenceRequest (type)", "SetPresenceRequestSchema (const)", "SetPresenceResponse (type)", diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index f6f6480781d..0ded343f094 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -6,6 +6,7 @@ "ACTION_CONFIRMATION_SERVICE (const)", "AIActionConfirmation (interface)", "AIConversation (interface)", + "AIConversationMessage (type)", "AIMessage (type)", "AIMessageWithTools (type)", "AIObjectResult (interface)", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 3019499f8f7..10a15cbd1a0 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -20,6 +20,32 @@ "api/AiAgentSummary:name", "api/AiAgentSummary:role", "api/AiAgentsResponse:agents", + "api/AiAnswerArtifactDraft:name", + "api/AiAnswerArtifactDraft:type", + "api/AiAnswerArtifactError:category", + "api/AiAnswerArtifactError:code", + "api/AiAnswerArtifactError:declaredCode", + "api/AiAnswerArtifactError:details", + "api/AiAnswerArtifactError:httpStatus", + "api/AiAnswerArtifactError:message", + "api/AiAnswerArtifactError:refusal", + "api/AiAnswerArtifactError:requestId", + "api/AiAnswerArtifactError:userMessage", + "api/AiAnswerFeedback:conversationId", + "api/AiAnswerFeedback:createdAt", + "api/AiAnswerFeedback:note", + "api/AiAnswerFeedback:rating", + "api/AiAnswerFeedback:turnId", + "api/AiAnswerFeedback:updatedAt", + "api/AiAnswerFeedbackError:category", + "api/AiAnswerFeedbackError:code", + "api/AiAnswerFeedbackError:declaredCode", + "api/AiAnswerFeedbackError:details", + "api/AiAnswerFeedbackError:httpStatus", + "api/AiAnswerFeedbackError:message", + "api/AiAnswerFeedbackError:refusal", + "api/AiAnswerFeedbackError:requestId", + "api/AiAnswerFeedbackError:userMessage", "api/AiChatRequest:conversationId", "api/AiChatRequest:maxTokens", "api/AiChatRequest:messages", @@ -44,6 +70,10 @@ "api/AiConversation:title", "api/AiConversation:updatedAt", "api/AiConversation:userId", + "api/AiConversationMessage:content", + "api/AiConversationMessage:parts", + "api/AiConversationMessage:role", + "api/AiConversationMessage:turn_id", "api/AiMessage:content", "api/AiMessage:parts", "api/AiMessage:role", @@ -64,6 +94,22 @@ "api/AiPendingAction:status", "api/AiPendingAction:tool_input", "api/AiPendingAction:tool_name", + "api/AiSavedQuestion:agentId", + "api/AiSavedQuestion:conversationId", + "api/AiSavedQuestion:createdAt", + "api/AiSavedQuestion:id", + "api/AiSavedQuestion:question", + "api/AiSavedQuestion:source", + "api/AiSavedQuestion:turnId", + "api/AiSavedQuestionError:category", + "api/AiSavedQuestionError:code", + "api/AiSavedQuestionError:declaredCode", + "api/AiSavedQuestionError:details", + "api/AiSavedQuestionError:httpStatus", + "api/AiSavedQuestionError:message", + "api/AiSavedQuestionError:refusal", + "api/AiSavedQuestionError:requestId", + "api/AiSavedQuestionError:userMessage", "api/AiStreamChunk:type", "api/AnalyticsMetadataResponse:data", "api/AnalyticsMetadataResponse:error", @@ -365,9 +411,17 @@ "api/ConceptListResponse:error", "api/ConceptListResponse:meta", "api/ConceptListResponse:success", + "api/CreateAiAnswerArtifactRequest:kind", + "api/CreateAiAnswerArtifactRequest:label", + "api/CreateAiAnswerArtifactRequest:toolCallId", "api/CreateAiConversationRequest:agentId", "api/CreateAiConversationRequest:metadata", "api/CreateAiConversationRequest:title", + "api/CreateAiSavedQuestionRequest:conversationId", + "api/CreateAiSavedQuestionRequest:question", + "api/CreateAiSavedQuestionRequest:toolCallId", + "api/CreateAiSavedQuestionRequest:turnId", + "api/CreateAiSavedQuestionResponse:question", "api/CreateDataRequest:data", "api/CreateDataRequest:object", "api/CreateDataResponse:droppedFields", @@ -752,6 +806,7 @@ "api/GeneratedEndpoint:object", "api/GeneratedEndpoint:operation", "api/GeneratedEndpoint:path", + "api/GetAiAnswerFeedbackResponse:feedback", "api/GetAnalyticsMetaRequest:cube", "api/GetAuthConfigResponse:emailPassword", "api/GetAuthConfigResponse:features", @@ -1080,6 +1135,7 @@ "api/ListAiPendingActionsRequest:status", "api/ListAiPendingActionsResponse:items", "api/ListAiPendingActionsResponse:total", + "api/ListAiSavedQuestionsResponse:questions", "api/ListDraftsResponse:drafts", "api/ListImportJobsRequest:limit", "api/ListImportJobsRequest:object", @@ -1766,6 +1822,9 @@ "api/RouterConfig:cors", "api/RouterConfig:mounts", "api/RouterConfig:staticMounts", + "api/RunAiSavedQuestionResponse:question", + "api/RunAiSavedQuestionResponse:result", + "api/RunAiSavedQuestionResponse:toolName", "api/RuntimeAuthoringIssue:hint", "api/RuntimeAuthoringIssue:message", "api/RuntimeAuthoringIssue:path", @@ -1855,6 +1914,9 @@ "api/SessionUser:timezone", "api/SessionUser:updatedAt", "api/SessionUser:username", + "api/SetAiAnswerFeedbackRequest:note", + "api/SetAiAnswerFeedbackRequest:rating", + "api/SetAiAnswerFeedbackResponse:feedback", "api/SetPresenceRequest:channel", "api/SetPresenceRequest:state", "api/SetPresenceResponse:success", diff --git a/packages/spec/declaration-map/api.json b/packages/spec/declaration-map/api.json index 26d622013f3..b403cf17734 100644 --- a/packages/spec/declaration-map/api.json +++ b/packages/spec/declaration-map/api.json @@ -12,6 +12,24 @@ "AiAgentSummarySchema": "api/AiAgentSummary", "AiAgentsResponse": "api/AiAgentsResponse", "AiAgentsResponseSchema": "api/AiAgentsResponse", + "AiAnswerArtifactDraft": "api/AiAnswerArtifactDraft", + "AiAnswerArtifactDraftSchema": "api/AiAnswerArtifactDraft", + "AiAnswerArtifactError": "api/AiAnswerArtifactError", + "AiAnswerArtifactErrorCode": "api/AiAnswerArtifactErrorCode", + "AiAnswerArtifactErrorCodeSchema": "api/AiAnswerArtifactErrorCode", + "AiAnswerArtifactErrorSchema": "api/AiAnswerArtifactError", + "AiAnswerArtifactKind": "api/AiAnswerArtifactKind", + "AiAnswerArtifactKindSchema": "api/AiAnswerArtifactKind", + "AiAnswerArtifactRefusalReason": "api/AiAnswerArtifactRefusalReason", + "AiAnswerArtifactRefusalReasonSchema": "api/AiAnswerArtifactRefusalReason", + "AiAnswerFeedback": "api/AiAnswerFeedback", + "AiAnswerFeedbackError": "api/AiAnswerFeedbackError", + "AiAnswerFeedbackErrorCode": "api/AiAnswerFeedbackErrorCode", + "AiAnswerFeedbackErrorCodeSchema": "api/AiAnswerFeedbackErrorCode", + "AiAnswerFeedbackErrorSchema": "api/AiAnswerFeedbackError", + "AiAnswerFeedbackSchema": "api/AiAnswerFeedback", + "AiAnswerRating": "api/AiAnswerRating", + "AiAnswerRatingSchema": "api/AiAnswerRating", "AiChatRequest": "api/AiChatRequest", "AiChatRequestSchema": "api/AiChatRequest", "AiChatResponse": "api/AiChatResponse", @@ -19,6 +37,8 @@ "AiCompleteRequest": "api/AiCompleteRequest", "AiCompleteRequestSchema": "api/AiCompleteRequest", "AiConversation": "api/AiConversation", + "AiConversationMessage": "api/AiConversationMessage", + "AiConversationMessageSchema": "api/AiConversationMessage", "AiConversationSchema": "api/AiConversation", "AiMessage": "api/AiMessage", "AiMessageSchema": "api/AiMessage", @@ -28,6 +48,14 @@ "AiPendingActionSchema": "api/AiPendingAction", "AiPendingActionStatus": "api/AiPendingActionStatus", "AiPendingActionStatusSchema": "api/AiPendingActionStatus", + "AiSavedQuestion": "api/AiSavedQuestion", + "AiSavedQuestionError": "api/AiSavedQuestionError", + "AiSavedQuestionErrorCode": "api/AiSavedQuestionErrorCode", + "AiSavedQuestionErrorCodeSchema": "api/AiSavedQuestionErrorCode", + "AiSavedQuestionErrorSchema": "api/AiSavedQuestionError", + "AiSavedQuestionRefusalReason": "api/AiSavedQuestionRefusalReason", + "AiSavedQuestionRefusalReasonSchema": "api/AiSavedQuestionRefusalReason", + "AiSavedQuestionSchema": "api/AiSavedQuestion", "AiStreamChunk": "api/AiStreamChunk", "AiStreamChunkSchema": "api/AiStreamChunk", "AnalyticsEndpoint": "api/AnalyticsEndpoint", @@ -152,8 +180,16 @@ "ConceptListResponse": "api/ConceptListResponse", "ConceptListResponseSchema": "api/ConceptListResponse", "ConflictResolutionStrategy": "api/ConflictResolutionStrategy", + "CreateAiAnswerArtifactRequest": "api/CreateAiAnswerArtifactRequest", + "CreateAiAnswerArtifactRequestSchema": "api/CreateAiAnswerArtifactRequest", + "CreateAiAnswerArtifactResponse": "api/CreateAiAnswerArtifactResponse", + "CreateAiAnswerArtifactResponseSchema": "api/CreateAiAnswerArtifactResponse", "CreateAiConversationRequest": "api/CreateAiConversationRequest", "CreateAiConversationRequestSchema": "api/CreateAiConversationRequest", + "CreateAiSavedQuestionRequest": "api/CreateAiSavedQuestionRequest", + "CreateAiSavedQuestionRequestSchema": "api/CreateAiSavedQuestionRequest", + "CreateAiSavedQuestionResponse": "api/CreateAiSavedQuestionResponse", + "CreateAiSavedQuestionResponseSchema": "api/CreateAiSavedQuestionResponse", "CreateDataRequest": "api/CreateDataRequest", "CreateDataRequestSchema": "api/CreateDataRequest", "CreateDataResponse": "api/CreateDataResponse", @@ -318,6 +354,8 @@ "GeneratedApiDocumentationSchema": "api/GeneratedApiDocumentation", "GeneratedEndpoint": "api/GeneratedEndpoint", "GeneratedEndpointSchema": "api/GeneratedEndpoint", + "GetAiAnswerFeedbackResponse": "api/GetAiAnswerFeedbackResponse", + "GetAiAnswerFeedbackResponseSchema": "api/GetAiAnswerFeedbackResponse", "GetAnalyticsMetaRequest": "api/GetAnalyticsMetaRequest", "GetAnalyticsMetaRequestSchema": "api/GetAnalyticsMetaRequest", "GetAuthConfigResponse": "api/GetAuthConfigResponse", @@ -452,6 +490,8 @@ "ListAiPendingActionsRequestSchema": "api/ListAiPendingActionsRequest", "ListAiPendingActionsResponse": "api/ListAiPendingActionsResponse", "ListAiPendingActionsResponseSchema": "api/ListAiPendingActionsResponse", + "ListAiSavedQuestionsResponse": "api/ListAiSavedQuestionsResponse", + "ListAiSavedQuestionsResponseSchema": "api/ListAiSavedQuestionsResponse", "ListDraftsResponse": "api/ListDraftsResponse", "ListDraftsResponseSchema": "api/ListDraftsResponse", "ListImportJobsRequest": "api/ListImportJobsRequest", @@ -782,6 +822,8 @@ "RouteHealthReportSchema": "api/RouteHealthReport", "RouterConfig": "api/RouterConfig", "RouterConfigSchema": "api/RouterConfig", + "RunAiSavedQuestionResponse": "api/RunAiSavedQuestionResponse", + "RunAiSavedQuestionResponseSchema": "api/RunAiSavedQuestionResponse", "RuntimeAuthoringIssue": "api/RuntimeAuthoringIssue", "RuntimeAuthoringIssueSchema": "api/RuntimeAuthoringIssue", "RuntimeBuildIssue": "api/RuntimeBuildIssue", @@ -811,6 +853,10 @@ "SessionSchema": "api/Session", "SessionUser": "api/SessionUser", "SessionUserSchema": "api/SessionUser", + "SetAiAnswerFeedbackRequest": "api/SetAiAnswerFeedbackRequest", + "SetAiAnswerFeedbackRequestSchema": "api/SetAiAnswerFeedbackRequest", + "SetAiAnswerFeedbackResponse": "api/SetAiAnswerFeedbackResponse", + "SetAiAnswerFeedbackResponseSchema": "api/SetAiAnswerFeedbackResponse", "SetPresenceRequest": "api/SetPresenceRequest", "SetPresenceRequestSchema": "api/SetPresenceRequest", "SetPresenceResponse": "api/SetPresenceResponse", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 0f4c8408979..642da1d9f62 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -82,6 +82,11 @@ "schema" ] }, + "api/AiSavedQuestion": { + "sites": [ + "source.filter.lazy" + ] + }, "api/AnalyticsQueryRequest": { "sites": [ "where.lazy" @@ -207,6 +212,11 @@ "data.flow.variables.element" ] }, + "api/CreateAiSavedQuestionResponse": { + "sites": [ + "question.source.filter.lazy" + ] + }, "api/CreateFlowRequest": { "sites": [ "", @@ -532,6 +542,11 @@ "options[1].manifest.views.element.list.timeline.groupByField" ] }, + "api/ListAiSavedQuestionsResponse": { + "sites": [ + "questions.element.source.filter.lazy" + ] + }, "api/ListInstalledPackagesResponse": { "sites": [ "data.packages.element.options[0].manifest.data.element.records.element.valueType", diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index 999a5c34857..83837947df5 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -13,6 +13,24 @@ "AiAgentSummarySchema": "src/api/protocol.zod.ts#AiAgentSummarySchema (const)", "AiAgentsResponse": "src/api/protocol.zod.ts#AiAgentsResponse (type)", "AiAgentsResponseSchema": "src/api/protocol.zod.ts#AiAgentsResponseSchema (const)", + "AiAnswerArtifactDraft": "src/api/ai-answer.zod.ts#AiAnswerArtifactDraft (type)", + "AiAnswerArtifactDraftSchema": "src/api/ai-answer.zod.ts#AiAnswerArtifactDraftSchema (const)", + "AiAnswerArtifactError": "src/api/ai-answer.zod.ts#AiAnswerArtifactError (type)", + "AiAnswerArtifactErrorCode": "src/api/ai-answer.zod.ts#AiAnswerArtifactErrorCode (type)", + "AiAnswerArtifactErrorCodeSchema": "src/api/ai-answer.zod.ts#AiAnswerArtifactErrorCodeSchema (const)", + "AiAnswerArtifactErrorSchema": "src/api/ai-answer.zod.ts#AiAnswerArtifactErrorSchema (const)", + "AiAnswerArtifactKind": "src/api/ai-answer.zod.ts#AiAnswerArtifactKind (type)", + "AiAnswerArtifactKindSchema": "src/api/ai-answer.zod.ts#AiAnswerArtifactKindSchema (const)", + "AiAnswerArtifactRefusalReason": "src/api/ai-answer.zod.ts#AiAnswerArtifactRefusalReason (type)", + "AiAnswerArtifactRefusalReasonSchema": "src/api/ai-answer.zod.ts#AiAnswerArtifactRefusalReasonSchema (const)", + "AiAnswerFeedback": "src/api/ai-answer.zod.ts#AiAnswerFeedback (type)", + "AiAnswerFeedbackError": "src/api/ai-answer.zod.ts#AiAnswerFeedbackError (type)", + "AiAnswerFeedbackErrorCode": "src/api/ai-answer.zod.ts#AiAnswerFeedbackErrorCode (type)", + "AiAnswerFeedbackErrorCodeSchema": "src/api/ai-answer.zod.ts#AiAnswerFeedbackErrorCodeSchema (const)", + "AiAnswerFeedbackErrorSchema": "src/api/ai-answer.zod.ts#AiAnswerFeedbackErrorSchema (const)", + "AiAnswerFeedbackSchema": "src/api/ai-answer.zod.ts#AiAnswerFeedbackSchema (const)", + "AiAnswerRating": "src/api/ai-answer.zod.ts#AiAnswerRating (type)", + "AiAnswerRatingSchema": "src/api/ai-answer.zod.ts#AiAnswerRatingSchema (const)", "AiChatRequest": "src/api/protocol.zod.ts#AiChatRequest (type)", "AiChatRequestSchema": "src/api/protocol.zod.ts#AiChatRequestSchema (const)", "AiChatResponse": "src/api/protocol.zod.ts#AiChatResponse (type)", @@ -20,6 +38,8 @@ "AiCompleteRequest": "src/api/protocol.zod.ts#AiCompleteRequest (type)", "AiCompleteRequestSchema": "src/api/protocol.zod.ts#AiCompleteRequestSchema (const)", "AiConversation": "src/api/protocol.zod.ts#AiConversation (type)", + "AiConversationMessage": "src/api/protocol.zod.ts#AiConversationMessage (type)", + "AiConversationMessageSchema": "src/api/protocol.zod.ts#AiConversationMessageSchema (const)", "AiConversationSchema": "src/api/protocol.zod.ts#AiConversationSchema (const)", "AiMessage": "src/api/protocol.zod.ts#AiMessage (type)", "AiMessageSchema": "src/api/protocol.zod.ts#AiMessageSchema (const)", @@ -29,6 +49,14 @@ "AiPendingActionSchema": "src/api/protocol.zod.ts#AiPendingActionSchema (const)", "AiPendingActionStatus": "src/api/protocol.zod.ts#AiPendingActionStatus (type)", "AiPendingActionStatusSchema": "src/api/protocol.zod.ts#AiPendingActionStatusSchema (const)", + "AiSavedQuestion": "src/api/ai-answer.zod.ts#AiSavedQuestion (type)", + "AiSavedQuestionError": "src/api/ai-answer.zod.ts#AiSavedQuestionError (type)", + "AiSavedQuestionErrorCode": "src/api/ai-answer.zod.ts#AiSavedQuestionErrorCode (type)", + "AiSavedQuestionErrorCodeSchema": "src/api/ai-answer.zod.ts#AiSavedQuestionErrorCodeSchema (const)", + "AiSavedQuestionErrorSchema": "src/api/ai-answer.zod.ts#AiSavedQuestionErrorSchema (const)", + "AiSavedQuestionRefusalReason": "src/api/ai-answer.zod.ts#AiSavedQuestionRefusalReason (type)", + "AiSavedQuestionRefusalReasonSchema": "src/api/ai-answer.zod.ts#AiSavedQuestionRefusalReasonSchema (const)", + "AiSavedQuestionSchema": "src/api/ai-answer.zod.ts#AiSavedQuestionSchema (const)", "AiStreamChunk": "src/api/protocol.zod.ts#AiStreamChunk (type)", "AiStreamChunkSchema": "src/api/protocol.zod.ts#AiStreamChunkSchema (const)", "AnalyticsEndpoint": "src/api/analytics.zod.ts#AnalyticsEndpoint (type)", @@ -193,8 +221,16 @@ "ConceptListResponseParsed": "src/api/metadata.zod.ts#ConceptListResponseParsed (type)", "ConceptListResponseSchema": "src/api/metadata.zod.ts#ConceptListResponseSchema (const)", "ConflictResolutionStrategy": "src/api/router.zod.ts#ConflictResolutionStrategy (type)", + "CreateAiAnswerArtifactRequest": "src/api/ai-answer.zod.ts#CreateAiAnswerArtifactRequest (type)", + "CreateAiAnswerArtifactRequestSchema": "src/api/ai-answer.zod.ts#CreateAiAnswerArtifactRequestSchema (const)", + "CreateAiAnswerArtifactResponse": "src/api/ai-answer.zod.ts#CreateAiAnswerArtifactResponse (type)", + "CreateAiAnswerArtifactResponseSchema": "src/api/ai-answer.zod.ts#CreateAiAnswerArtifactResponseSchema (const)", "CreateAiConversationRequest": "src/api/protocol.zod.ts#CreateAiConversationRequest (type)", "CreateAiConversationRequestSchema": "src/api/protocol.zod.ts#CreateAiConversationRequestSchema (const)", + "CreateAiSavedQuestionRequest": "src/api/ai-answer.zod.ts#CreateAiSavedQuestionRequest (type)", + "CreateAiSavedQuestionRequestSchema": "src/api/ai-answer.zod.ts#CreateAiSavedQuestionRequestSchema (const)", + "CreateAiSavedQuestionResponse": "src/api/ai-answer.zod.ts#CreateAiSavedQuestionResponse (type)", + "CreateAiSavedQuestionResponseSchema": "src/api/ai-answer.zod.ts#CreateAiSavedQuestionResponseSchema (const)", "CreateDataRequest": "src/api/protocol.zod.ts#CreateDataRequest (type)", "CreateDataRequestSchema": "src/api/protocol.zod.ts#CreateDataRequestSchema (const)", "CreateDataResponse": "src/api/protocol.zod.ts#CreateDataResponse (type)", @@ -427,6 +463,8 @@ "GeneratedApiDocumentationSchema": "src/api/documentation.zod.ts#GeneratedApiDocumentationSchema (const)", "GeneratedEndpoint": "src/api/rest-server.zod.ts#GeneratedEndpoint (type)", "GeneratedEndpointSchema": "src/api/rest-server.zod.ts#GeneratedEndpointSchema (const)", + "GetAiAnswerFeedbackResponse": "src/api/ai-answer.zod.ts#GetAiAnswerFeedbackResponse (type)", + "GetAiAnswerFeedbackResponseSchema": "src/api/ai-answer.zod.ts#GetAiAnswerFeedbackResponseSchema (const)", "GetAnalyticsMetaRequest": "src/api/analytics.zod.ts#GetAnalyticsMetaRequest (type)", "GetAnalyticsMetaRequestSchema": "src/api/analytics.zod.ts#GetAnalyticsMetaRequestSchema (const)", "GetAuthConfigResponse": "src/api/auth-endpoints.zod.ts#GetAuthConfigResponse (type)", @@ -593,6 +631,8 @@ "ListAiPendingActionsRequestSchema": "src/api/protocol.zod.ts#ListAiPendingActionsRequestSchema (const)", "ListAiPendingActionsResponse": "src/api/protocol.zod.ts#ListAiPendingActionsResponse (type)", "ListAiPendingActionsResponseSchema": "src/api/protocol.zod.ts#ListAiPendingActionsResponseSchema (const)", + "ListAiSavedQuestionsResponse": "src/api/ai-answer.zod.ts#ListAiSavedQuestionsResponse (type)", + "ListAiSavedQuestionsResponseSchema": "src/api/ai-answer.zod.ts#ListAiSavedQuestionsResponseSchema (const)", "ListDraftsResponse": "src/api/protocol.zod.ts#ListDraftsResponse (type)", "ListDraftsResponseParsed": "src/api/protocol.zod.ts#ListDraftsResponseParsed (type)", "ListDraftsResponseSchema": "src/api/protocol.zod.ts#ListDraftsResponseSchema (const)", @@ -1048,6 +1088,8 @@ "RouterConfig": "src/api/router.zod.ts#RouterConfig (type)", "RouterConfigParsed": "src/api/router.zod.ts#RouterConfigParsed (type)", "RouterConfigSchema": "src/api/router.zod.ts#RouterConfigSchema (const)", + "RunAiSavedQuestionResponse": "src/api/ai-answer.zod.ts#RunAiSavedQuestionResponse (type)", + "RunAiSavedQuestionResponseSchema": "src/api/ai-answer.zod.ts#RunAiSavedQuestionResponseSchema (const)", "RuntimeAuthoringIssue": "src/api/protocol.zod.ts#RuntimeAuthoringIssue (type)", "RuntimeAuthoringIssueSchema": "src/api/protocol.zod.ts#RuntimeAuthoringIssueSchema (const)", "RuntimeBuildIssue": "src/api/protocol.zod.ts#RuntimeBuildIssue (type)", @@ -1084,6 +1126,10 @@ "SessionUser": "src/api/auth.zod.ts#SessionUser (type)", "SessionUserParsed": "src/api/auth.zod.ts#SessionUserParsed (type)", "SessionUserSchema": "src/api/auth.zod.ts#SessionUserSchema (const)", + "SetAiAnswerFeedbackRequest": "src/api/ai-answer.zod.ts#SetAiAnswerFeedbackRequest (type)", + "SetAiAnswerFeedbackRequestSchema": "src/api/ai-answer.zod.ts#SetAiAnswerFeedbackRequestSchema (const)", + "SetAiAnswerFeedbackResponse": "src/api/ai-answer.zod.ts#SetAiAnswerFeedbackResponse (type)", + "SetAiAnswerFeedbackResponseSchema": "src/api/ai-answer.zod.ts#SetAiAnswerFeedbackResponseSchema (const)", "SetPresenceRequest": "src/api/protocol.zod.ts#SetPresenceRequest (type)", "SetPresenceRequestSchema": "src/api/protocol.zod.ts#SetPresenceRequestSchema (const)", "SetPresenceResponse": "src/api/protocol.zod.ts#SetPresenceResponse (type)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 873ccde9668..12555bd19c8 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -6,6 +6,7 @@ "ACTION_CONFIRMATION_SERVICE": "src/contracts/ai-service.ts#ACTION_CONFIRMATION_SERVICE (const)", "AIActionConfirmation": "src/contracts/ai-service.ts#AIActionConfirmation (interface)", "AIConversation": "src/contracts/ai-service.ts#AIConversation (interface)", + "AIConversationMessage": "src/contracts/ai-service.ts#AIConversationMessage (type)", "AIMessage": "src/contracts/ai-service.ts#AIMessage (type)", "AIMessageWithTools": "src/contracts/ai-service.ts#AIMessageWithTools (type)", "AIObjectResult": "src/contracts/ai-service.ts#AIObjectResult (interface)", diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index bdfc2060587..c1cc71812dd 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -7,14 +7,28 @@ "api/AiAgentChatRequest", "api/AiAgentSummary", "api/AiAgentsResponse", + "api/AiAnswerArtifactDraft", + "api/AiAnswerArtifactError", + "api/AiAnswerArtifactErrorCode", + "api/AiAnswerArtifactKind", + "api/AiAnswerArtifactRefusalReason", + "api/AiAnswerFeedback", + "api/AiAnswerFeedbackError", + "api/AiAnswerFeedbackErrorCode", + "api/AiAnswerRating", "api/AiChatRequest", "api/AiChatResponse", "api/AiCompleteRequest", "api/AiConversation", + "api/AiConversationMessage", "api/AiMessage", "api/AiModelsResponse", "api/AiPendingAction", "api/AiPendingActionStatus", + "api/AiSavedQuestion", + "api/AiSavedQuestionError", + "api/AiSavedQuestionErrorCode", + "api/AiSavedQuestionRefusalReason", "api/AiStreamChunk", "api/AnalyticsEndpoint", "api/AnalyticsMetadataResponse", @@ -81,7 +95,11 @@ "api/CompleteUploadRequest", "api/ConceptListResponse", "api/ConflictResolutionStrategy", + "api/CreateAiAnswerArtifactRequest", + "api/CreateAiAnswerArtifactResponse", "api/CreateAiConversationRequest", + "api/CreateAiSavedQuestionRequest", + "api/CreateAiSavedQuestionResponse", "api/CreateDataRequest", "api/CreateDataResponse", "api/CreateFlowRequest", @@ -173,6 +191,7 @@ "api/FlowRegistrationRefusal", "api/GeneratedApiDocumentation", "api/GeneratedEndpoint", + "api/GetAiAnswerFeedbackResponse", "api/GetAnalyticsMetaRequest", "api/GetAuthConfigResponse", "api/GetDataRequest", @@ -247,6 +266,7 @@ "api/ListAiConversationsResponse", "api/ListAiPendingActionsRequest", "api/ListAiPendingActionsResponse", + "api/ListAiSavedQuestionsResponse", "api/ListDraftsResponse", "api/ListImportJobsRequest", "api/ListImportJobsResponse", @@ -424,6 +444,7 @@ "api/RouteHealthEntry", "api/RouteHealthReport", "api/RouterConfig", + "api/RunAiSavedQuestionResponse", "api/RuntimeAuthoringIssue", "api/RuntimeBuildIssue", "api/SaveMetaItemRequest", @@ -439,6 +460,8 @@ "api/Session", "api/SessionResponse", "api/SessionUser", + "api/SetAiAnswerFeedbackRequest", + "api/SetAiAnswerFeedbackResponse", "api/SetPresenceRequest", "api/SetPresenceResponse", "api/SimpleCursorPosition", From a2726ac74fa181eaf72097bc1e7069fb35ce69f1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:14:01 +0000 Subject: [PATCH 03/11] chore(changeset): spec AI answer route shapes Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .changeset/32642-ai-answer-routes.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/32642-ai-answer-routes.md diff --git a/.changeset/32642-ai-answer-routes.md b/.changeset/32642-ai-answer-routes.md new file mode 100644 index 00000000000..21f60ca2bc1 --- /dev/null +++ b/.changeset/32642-ai-answer-routes.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': patch +--- + +feat(spec): declare the AI answer follow-up routes (saved questions, answer artifact, answer feedback) and carry `turn_id` on a conversation's messages + +Clause-②: yes (widening) +Metadata-protocol: none + +`@objectstack/spec/api` now declares the request, response and error shapes of the AI answer follow-up routes the cloud AI service serves, so the console and the client SDK can type them instead of guessing: + +- **Saved questions.** `GET /api/v1/ai/saved-questions` (`ListAiSavedQuestionsResponseSchema`), `POST /api/v1/ai/saved-questions` (`CreateAiSavedQuestionRequestSchema` / `CreateAiSavedQuestionResponseSchema`: a typed `question`, or `conversationId` with `turnId`), `DELETE /api/v1/ai/saved-questions/:id` (204) and `POST /api/v1/ai/saved-questions/:id/run` (`RunAiSavedQuestionResponseSchema`). One saved question is `AiSavedQuestionSchema`; its `source` is the Ask data tools' `ObjectQuerySourceSchema` block. +- **Answer → artifact.** `POST /api/v1/ai/conversations/:id/turns/:turnId/artifact` (`CreateAiAnswerArtifactRequestSchema` with `kind: 'view' | 'report' | 'widget'`; `CreateAiAnswerArtifactResponseSchema`, discriminated by `kind`: the caller's own list view, or a dataset plus a report or dashboard draft with `published: false`). +- **Answer feedback.** `GET|POST|DELETE /api/v1/ai/conversations/:id/turns/:turnId/feedback` (`GetAiAnswerFeedbackResponseSchema`, `SetAiAnswerFeedbackRequestSchema` with `rating: 'up' | 'down'` and an optional `note`, `SetAiAnswerFeedbackResponseSchema`; DELETE answers 204). +- **Errors.** Each family's `error` is `ApiErrorSchema` with its closed `code` vocabulary (`AiSavedQuestionErrorSchema`, `AiAnswerArtifactErrorSchema`, `AiAnswerFeedbackErrorSchema`) and, where the route names one, the refusal in `details.reason` (`AiSavedQuestionRefusalReasonSchema`, `AiAnswerArtifactRefusalReasonSchema`). + +A persisted conversation's messages may now carry the turn they were written under: `AiConversationSchema.messages` is `AiConversationMessageSchema` (`AiMessageSchema` plus an optional `turn_id`), and the `AIConversation` contract's `messages` are `AIConversationMessage` (`ModelMessage` plus an optional `turn_id`). Optional: a stored conversation whose messages carry none still parses, and a service that writes none still satisfies the contract. From 0576b8eb6b68c6167555ccebb6d5a9b3416d89dc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:41:02 +0000 Subject: [PATCH 04/11] chore(spec): declare the new shapes in llms.txt, variant-docs and the dropped-refinements totals Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/spec/dropped-refinements.baseline.json | 4 ++-- packages/spec/llms.txt | 4 ++-- packages/spec/variant-docs.json | 6 ++++++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 642da1d9f62..70d70d03422 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -2,8 +2,8 @@ "description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.", "measured": { "zod": "4.4.3", - "publishedSchemasWithDroppedRefinements": 271, - "droppedRefinementSites": 1148, + "publishedSchemasWithDroppedRefinements": 274, + "droppedRefinementSites": 1151, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index 9822e9d4a29..a0f298d8db4 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -77,7 +77,7 @@ const query = { --- -## 3. Schema Inventory by Domain (227 schemas) +## 3. Schema Inventory by Domain (228 schemas) Counted as `*.zod.ts` modules under `packages/spec/src//` — the sources that ship in this tarball (`files` includes `src/**/*.zod.ts`), so every number @@ -88,7 +88,7 @@ here is verifiable from the installed package. | system | 40 | Auth, Cache, Demo Staff, Dev Login, Email / SMS / Push Config, Push Device, Encryption, Fate Supplement (organization ownership), HTTP Server, License, Logging, Metrics, Restriction Profile | | kernel | 31 | Plugin, Manifest, Events (6 sub-modules), Feature, Context, Package Registry, Override Declaration | | data | 37 | Object, Field, Picklist, Query, Filter, Driver (SQL/NoSQL/Memory/Mongo/Postgres/Oracle/SQL Server), Cube, Seed, Recycle Bin, Declared Entry (refusal / text) | -| api | 35 | Endpoint, REST Server, Discovery, OData, Batch, WebSocket, Response Envelope, Package Lifecycle, Package API (assembled stage), Record Page, App Metadata Bundle, Push Delivery, Push Relay | +| api | 36 | Endpoint, REST Server, Discovery, OData, Batch, WebSocket, Response Envelope, Package Lifecycle, Package API (assembled stage), Record Page, App Metadata Bundle, Push Delivery, Push Relay, AI Answer Follow-ups | | ui | 18 | View, App, Action, Dashboard, Page, Chart, Component, Animation | | automation | 16 | Flow, Approval, Assignment Rule, BPMN Interop, Control Flow, Webhook, Schedule Organization | | shared | 16 | Enums, HTTP, Identifiers, Mapping, Metadata Types, Connector Auth, Retry Policy, Conditional Formatting, Value Domain, Epoch Instant (EpochMs), Duration (DurationMs / DurationSeconds) | diff --git a/packages/spec/variant-docs.json b/packages/spec/variant-docs.json index 0de5e8c41a4..fa8c74f3f96 100644 --- a/packages/spec/variant-docs.json +++ b/packages/spec/variant-docs.json @@ -137,6 +137,12 @@ "exempt": "not-authorable", "reason": "Wire protocol between a server's push channel and the hosted push relay: the relay answers it and nobody writes it into metadata. The generated page at content/docs/references/api/push-relay.mdx is the reference." }, + { + "key": "kind:report|view|widget", + "label": "AI answer artifact response", + "exempt": "not-authorable", + "reason": "Wire protocol: the response body the AI service answers after turning an answer into a personal view, a report draft or a dashboard draft. Nobody writes it into metadata. The generated page at content/docs/references/api/ai-answer.mdx is the reference." + }, { "key": "type:ack|cursor|edit|error|event|ping|pong|presence|subscribe|unsubscribe", "label": "websocket message", From 414775746ee7fbc30452e89b23dbb2201769bd0c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:58:58 +0000 Subject: [PATCH 05/11] test(spec): pin the AI answer route aliases as isomorphic (ADR-0122) Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .../src/type-alias-convention.pin.test.ts | 40 +++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 894979f28c6..7d7924d5ce4 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -302,9 +302,11 @@ import type * as M203 from './system/restriction-profile.zod.js'; import type * as M204 from './ai/dataset-tools.zod.js'; // The Ask data tools' object-query `source` block -- new module, next free index. import type * as M205 from './ai/object-query-source.zod.js'; +// The AI answer follow-up routes (saved questions, answer artifact, answer feedback) -- new module, next free index. +import type * as M207 from './api/ai-answer.zod.js'; // --------------------------------------------------------------------------- -// 863 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 886 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -441,6 +443,30 @@ export type Iso_ai_tool__ToolSchema = Assert export type Iso_ai_usage__AIUsageRecordSchema = Assert, z.infer< typeof M10.AIUsageRecordSchema > >>; export type Iso_ai_usage__TokenUsageSchema = Assert, z.infer< typeof M10.TokenUsageSchema > >>; +// api/ai-answer.zod.ts +export type Iso_api_aiAnswer__AiAnswerArtifactDraftSchema = Assert, z.infer< typeof M207.AiAnswerArtifactDraftSchema > >>; +export type Iso_api_aiAnswer__AiAnswerArtifactErrorCodeSchema = Assert, z.infer< typeof M207.AiAnswerArtifactErrorCodeSchema > >>; +export type Iso_api_aiAnswer__AiAnswerArtifactErrorSchema = Assert, z.infer< typeof M207.AiAnswerArtifactErrorSchema > >>; +export type Iso_api_aiAnswer__AiAnswerArtifactKindSchema = Assert, z.infer< typeof M207.AiAnswerArtifactKindSchema > >>; +export type Iso_api_aiAnswer__AiAnswerArtifactRefusalReasonSchema = Assert, z.infer< typeof M207.AiAnswerArtifactRefusalReasonSchema > >>; +export type Iso_api_aiAnswer__AiAnswerFeedbackErrorCodeSchema = Assert, z.infer< typeof M207.AiAnswerFeedbackErrorCodeSchema > >>; +export type Iso_api_aiAnswer__AiAnswerFeedbackErrorSchema = Assert, z.infer< typeof M207.AiAnswerFeedbackErrorSchema > >>; +export type Iso_api_aiAnswer__AiAnswerFeedbackSchema = Assert, z.infer< typeof M207.AiAnswerFeedbackSchema > >>; +export type Iso_api_aiAnswer__AiAnswerRatingSchema = Assert, z.infer< typeof M207.AiAnswerRatingSchema > >>; +export type Iso_api_aiAnswer__AiSavedQuestionErrorCodeSchema = Assert, z.infer< typeof M207.AiSavedQuestionErrorCodeSchema > >>; +export type Iso_api_aiAnswer__AiSavedQuestionErrorSchema = Assert, z.infer< typeof M207.AiSavedQuestionErrorSchema > >>; +export type Iso_api_aiAnswer__AiSavedQuestionRefusalReasonSchema = Assert, z.infer< typeof M207.AiSavedQuestionRefusalReasonSchema > >>; +export type Iso_api_aiAnswer__AiSavedQuestionSchema = Assert, z.infer< typeof M207.AiSavedQuestionSchema > >>; +export type Iso_api_aiAnswer__CreateAiAnswerArtifactRequestSchema = Assert, z.infer< typeof M207.CreateAiAnswerArtifactRequestSchema > >>; +export type Iso_api_aiAnswer__CreateAiAnswerArtifactResponseSchema = Assert, z.infer< typeof M207.CreateAiAnswerArtifactResponseSchema > >>; +export type Iso_api_aiAnswer__CreateAiSavedQuestionRequestSchema = Assert, z.infer< typeof M207.CreateAiSavedQuestionRequestSchema > >>; +export type Iso_api_aiAnswer__CreateAiSavedQuestionResponseSchema = Assert, z.infer< typeof M207.CreateAiSavedQuestionResponseSchema > >>; +export type Iso_api_aiAnswer__GetAiAnswerFeedbackResponseSchema = Assert, z.infer< typeof M207.GetAiAnswerFeedbackResponseSchema > >>; +export type Iso_api_aiAnswer__ListAiSavedQuestionsResponseSchema = Assert, z.infer< typeof M207.ListAiSavedQuestionsResponseSchema > >>; +export type Iso_api_aiAnswer__RunAiSavedQuestionResponseSchema = Assert, z.infer< typeof M207.RunAiSavedQuestionResponseSchema > >>; +export type Iso_api_aiAnswer__SetAiAnswerFeedbackRequestSchema = Assert, z.infer< typeof M207.SetAiAnswerFeedbackRequestSchema > >>; +export type Iso_api_aiAnswer__SetAiAnswerFeedbackResponseSchema = Assert, z.infer< typeof M207.SetAiAnswerFeedbackResponseSchema > >>; + // api/analytics.zod.ts // [#17551] The ADR-0021 dataset selection (`DatasetSelectionSchema`) and its two // nested directives (`DatasetCompareToSchema`, `DatasetTotalsSchema`). Their @@ -594,6 +620,7 @@ export type Iso_api_protocol__AiChatRequestSchema = Assert, z.infer< typeof M28.AiChatResponseSchema > >>; export type Iso_api_protocol__AiCompleteRequestSchema = Assert, z.infer< typeof M28.AiCompleteRequestSchema > >>; export type Iso_api_protocol__AiConversationSchema = Assert, z.infer< typeof M28.AiConversationSchema > >>; +export type Iso_api_protocol__AiConversationMessageSchema = Assert, z.infer< typeof M28.AiConversationMessageSchema > >>; export type Iso_api_protocol__AiMessageSchema = Assert, z.infer< typeof M28.AiMessageSchema > >>; export type Iso_api_protocol__AiModelsResponseSchema = Assert, z.infer< typeof M28.AiModelsResponseSchema > >>; export type Iso_api_protocol__AiPendingActionSchema = Assert, z.infer< typeof M28.AiPendingActionSchema > >>; @@ -1838,7 +1865,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 863 isomorphic pins', () => { + it('still declares all 886 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2943,7 +2970,14 @@ describe('ADR-0122 type-alias convention', () => { // declared-entry factory as `HookTextSchema` and closed at the same two // keys with no default or transform, pinned here // (Iso_ui_action__ActionTextSchema). +1 added. - expect(pins).toHaveLength(863); + // 863 -> 886 is the AI answer follow-up routes (`api/ai-answer.zod.ts`): + // its twenty-two schemas are plain objects, closed enums, a discriminated + // union of plain objects and `ApiErrorSchema` extensions, none with a + // default or a transform (Iso_api_aiAnswer__*), and + // `AiConversationMessageSchema` (`api/protocol.zod.ts`), `AiMessageSchema` + // plus an optional string (Iso_api_protocol__AiConversationMessageSchema). + // +23 added. + expect(pins).toHaveLength(886); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either From 4f312a82e7a74555a21c5e9d5ecff2514e74cd4c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:42:17 +0000 Subject: [PATCH 06/11] fix(spec): spell the conversation message turn id turnId, as the rest of the AI wire Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .changeset/32642-ai-answer-routes.md | 4 ++-- packages/spec/src/api/ai-answer.test.ts | 12 ++++++------ packages/spec/src/api/protocol.zod.ts | 2 +- packages/spec/src/contracts/ai-service.ts | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.changeset/32642-ai-answer-routes.md b/.changeset/32642-ai-answer-routes.md index 21f60ca2bc1..c6061bb1d4a 100644 --- a/.changeset/32642-ai-answer-routes.md +++ b/.changeset/32642-ai-answer-routes.md @@ -2,7 +2,7 @@ '@objectstack/spec': patch --- -feat(spec): declare the AI answer follow-up routes (saved questions, answer artifact, answer feedback) and carry `turn_id` on a conversation's messages +feat(spec): declare the AI answer follow-up routes (saved questions, answer artifact, answer feedback) and carry `turnId` on a conversation's messages Clause-②: yes (widening) Metadata-protocol: none @@ -14,4 +14,4 @@ Metadata-protocol: none - **Answer feedback.** `GET|POST|DELETE /api/v1/ai/conversations/:id/turns/:turnId/feedback` (`GetAiAnswerFeedbackResponseSchema`, `SetAiAnswerFeedbackRequestSchema` with `rating: 'up' | 'down'` and an optional `note`, `SetAiAnswerFeedbackResponseSchema`; DELETE answers 204). - **Errors.** Each family's `error` is `ApiErrorSchema` with its closed `code` vocabulary (`AiSavedQuestionErrorSchema`, `AiAnswerArtifactErrorSchema`, `AiAnswerFeedbackErrorSchema`) and, where the route names one, the refusal in `details.reason` (`AiSavedQuestionRefusalReasonSchema`, `AiAnswerArtifactRefusalReasonSchema`). -A persisted conversation's messages may now carry the turn they were written under: `AiConversationSchema.messages` is `AiConversationMessageSchema` (`AiMessageSchema` plus an optional `turn_id`), and the `AIConversation` contract's `messages` are `AIConversationMessage` (`ModelMessage` plus an optional `turn_id`). Optional: a stored conversation whose messages carry none still parses, and a service that writes none still satisfies the contract. +A persisted conversation's messages may now carry the turn they were written under: `AiConversationSchema.messages` is `AiConversationMessageSchema` (`AiMessageSchema` plus an optional `turnId`), and the `AIConversation` contract's `messages` are `AIConversationMessage` (`ModelMessage` plus an optional `turnId`). Optional: a stored conversation whose messages carry none still parses, and a service that writes none still satisfies the contract. diff --git a/packages/spec/src/api/ai-answer.test.ts b/packages/spec/src/api/ai-answer.test.ts index 07373b88375..efbbb1c4452 100644 --- a/packages/spec/src/api/ai-answer.test.ts +++ b/packages/spec/src/api/ai-answer.test.ts @@ -197,7 +197,7 @@ describe('answer feedback', () => { }); }); -describe('a conversation message carries its turn_id', () => { +describe('a conversation message carries its turnId', () => { const conversation = { id: 'conv_1', messages: [{ role: 'user', content: 'Won amount by region' }, { role: 'assistant', content: 'EMEA leads.' }], @@ -205,17 +205,17 @@ describe('a conversation message carries its turn_id', () => { updatedAt: '2026-11-18T10:00:00.000Z', }; - it('CONTROL: a stored conversation with no turn_id still parses', () => { + it('CONTROL: a stored conversation with no turnId still parses', () => { expect(AiConversationSchema.safeParse(conversation).success).toBe(true); }); - it('a message with turn_id keeps it, typed', () => { + it('a message with turnId keeps it, typed', () => { const stamped = { ...conversation, - messages: conversation.messages.map((m) => ({ ...m, turn_id: 'turn_1' })), + messages: conversation.messages.map((m) => ({ ...m, turnId: 'turn_1' })), }; const parsed = AiConversationSchema.parse(stamped); - expect(parsed.messages.map((m) => m.turn_id)).toEqual(['turn_1', 'turn_1']); - expect(AiConversationSchema.safeParse({ ...conversation, messages: [{ role: 'user', content: 'q', turn_id: 7 }] }).success).toBe(false); + expect(parsed.messages.map((m) => m.turnId)).toEqual(['turn_1', 'turn_1']); + expect(AiConversationSchema.safeParse({ ...conversation, messages: [{ role: 'user', content: 'q', turnId: 7 }] }).success).toBe(false); }); }); diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 14eba32ff15..4afb53a2d91 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -4404,7 +4404,7 @@ export const AiModelsResponseSchema = lazySchema(() => z.object({ * return it: {@link AiMessageSchema} plus the turn it belongs to. */ export const AiConversationMessageSchema = lazySchema(() => AiMessageSchema.extend({ - turn_id: z.string().optional().describe( + turnId: z.string().optional().describe( 'The turn the server stamped on the message: the `turnId` of the chat request that wrote it. ' + 'Absent on a message stored with no turn', ), diff --git a/packages/spec/src/contracts/ai-service.ts b/packages/spec/src/contracts/ai-service.ts index 11ade34d54e..a4c4c132e68 100644 --- a/packages/spec/src/contracts/ai-service.ts +++ b/packages/spec/src/contracts/ai-service.ts @@ -1348,7 +1348,7 @@ export interface AIObjectResult { */ export type AIConversationMessage = ModelMessage & { /** The turn the message was written under. */ - turn_id?: string; + turnId?: string; }; /** From a9d47c0f2125abbbd68f5fa8eb7472dfef627b65 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:47:38 +0000 Subject: [PATCH 07/11] chore(spec): regenerate the authorable surface and reference docs for turnId Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- content/docs/references/api/protocol.mdx | 8 ++++---- packages/spec/authorable-surface/api.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 273fc55fa21..913e636b10b 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -172,7 +172,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **title** | `string` | optional | Title / summary | | **agentId** | `string` | optional | Agent this conversation is bound to | | **userId** | `string` | optional | Owning user | -| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turn_id?: string } & Record)[]` | ✅ | Message history | +| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turnId?: string } & Record)[]` | ✅ | Message history | | **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | | **updatedAt** | `string` | ✅ | Last update timestamp (ISO 8601) | | **metadata** | `Record` | optional | Conversation metadata | @@ -184,7 +184,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **role** | `Enum<'system' \| 'user' \| 'assistant' \| 'tool'>` | ✅ | Message role | | **content** | `any` | optional | Message content: a string, or an array of content parts | | **parts** | `any[]` | optional | Vercel AI SDK v6 message parts (alternative to `content`) | -| **turn_id** | `string` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent on a message stored with no turn | +| **turnId** | `string` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent on a message stored with no turn | --- @@ -198,7 +198,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **role** | `Enum<'system' \| 'user' \| 'assistant' \| 'tool'>` | ✅ | Message role | | **content** | `any` | optional | Message content: a string, or an array of content parts | | **parts** | `any[]` | optional | Vercel AI SDK v6 message parts (alternative to `content`) | -| **turn_id** | `string` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent on a message stored with no turn | +| **turnId** | `string` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent on a message stored with no turn | --- @@ -2292,7 +2292,7 @@ Install package response | **title** | `string` | optional | Title / summary | | **agentId** | `string` | optional | Agent this conversation is bound to | | **userId** | `string` | optional | Owning user | -| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turn_id?: string } & Record)[]` | ✅ | Message history | +| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turnId?: string } & Record)[]` | ✅ | Message history | | **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | | **updatedAt** | `string` | ✅ | Last update timestamp (ISO 8601) | | **metadata** | `Record` | optional | Conversation metadata | diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 10a15cbd1a0..46ae7595197 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -73,7 +73,7 @@ "api/AiConversationMessage:content", "api/AiConversationMessage:parts", "api/AiConversationMessage:role", - "api/AiConversationMessage:turn_id", + "api/AiConversationMessage:turnId", "api/AiMessage:content", "api/AiMessage:parts", "api/AiMessage:role", From a27aab1edff015f2b8659a2feb04ffcaea67af06 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:02:47 +0000 Subject: [PATCH 08/11] chore(changeset): grade spec minor, Metadata-protocol added (the authorable surface gains keys) Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .changeset/32642-ai-answer-routes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/32642-ai-answer-routes.md b/.changeset/32642-ai-answer-routes.md index c6061bb1d4a..f2e61a70ab5 100644 --- a/.changeset/32642-ai-answer-routes.md +++ b/.changeset/32642-ai-answer-routes.md @@ -1,11 +1,11 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor --- feat(spec): declare the AI answer follow-up routes (saved questions, answer artifact, answer feedback) and carry `turnId` on a conversation's messages Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added `@objectstack/spec/api` now declares the request, response and error shapes of the AI answer follow-up routes the cloud AI service serves, so the console and the client SDK can type them instead of guessing: From 51a4665cccca6e3bb7d0c664fe0fb26ab8cd4011 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:21:00 +0000 Subject: [PATCH 09/11] fix(spec): AI answer route errors admit the framework door's codes; turnId may be null The three closed code lists now hold UNAUTHENTICATED, NOT_IMPLEMENTED and SERVICE_UNAVAILABLE, the codes the runtime AI door answers ahead of the route handler. A conversation message's turnId is optional and nullable on the wire schema and the AIConversationMessage contract. Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .changeset/32642-ai-answer-routes.md | 4 +-- packages/spec/src/api/ai-answer.test.ts | 35 +++++++++++++++++++++ packages/spec/src/api/ai-answer.zod.ts | 37 +++++++++++++++++++---- packages/spec/src/api/protocol.zod.ts | 4 +-- packages/spec/src/contracts/ai-service.ts | 8 ++--- 5 files changed, 74 insertions(+), 14 deletions(-) diff --git a/.changeset/32642-ai-answer-routes.md b/.changeset/32642-ai-answer-routes.md index f2e61a70ab5..76adeecab98 100644 --- a/.changeset/32642-ai-answer-routes.md +++ b/.changeset/32642-ai-answer-routes.md @@ -12,6 +12,6 @@ Metadata-protocol: added - **Saved questions.** `GET /api/v1/ai/saved-questions` (`ListAiSavedQuestionsResponseSchema`), `POST /api/v1/ai/saved-questions` (`CreateAiSavedQuestionRequestSchema` / `CreateAiSavedQuestionResponseSchema`: a typed `question`, or `conversationId` with `turnId`), `DELETE /api/v1/ai/saved-questions/:id` (204) and `POST /api/v1/ai/saved-questions/:id/run` (`RunAiSavedQuestionResponseSchema`). One saved question is `AiSavedQuestionSchema`; its `source` is the Ask data tools' `ObjectQuerySourceSchema` block. - **Answer → artifact.** `POST /api/v1/ai/conversations/:id/turns/:turnId/artifact` (`CreateAiAnswerArtifactRequestSchema` with `kind: 'view' | 'report' | 'widget'`; `CreateAiAnswerArtifactResponseSchema`, discriminated by `kind`: the caller's own list view, or a dataset plus a report or dashboard draft with `published: false`). - **Answer feedback.** `GET|POST|DELETE /api/v1/ai/conversations/:id/turns/:turnId/feedback` (`GetAiAnswerFeedbackResponseSchema`, `SetAiAnswerFeedbackRequestSchema` with `rating: 'up' | 'down'` and an optional `note`, `SetAiAnswerFeedbackResponseSchema`; DELETE answers 204). -- **Errors.** Each family's `error` is `ApiErrorSchema` with its closed `code` vocabulary (`AiSavedQuestionErrorSchema`, `AiAnswerArtifactErrorSchema`, `AiAnswerFeedbackErrorSchema`) and, where the route names one, the refusal in `details.reason` (`AiSavedQuestionRefusalReasonSchema`, `AiAnswerArtifactRefusalReasonSchema`). +- **Errors.** Each family's `error` is `ApiErrorSchema` with its closed `code` vocabulary (`AiSavedQuestionErrorSchema`, `AiAnswerArtifactErrorSchema`, `AiAnswerFeedbackErrorSchema`) and, where the route names one, the refusal in `details.reason` (`AiSavedQuestionRefusalReasonSchema`, `AiAnswerArtifactRefusalReasonSchema`). Each `code` list holds the route handler's codes and the framework door's, which answers ahead of the handler: `UNAUTHENTICATED` (401, no session), `NOT_IMPLEMENTED` (501, no AI served) and `SERVICE_UNAVAILABLE` (503, AI routes not yet published). -A persisted conversation's messages may now carry the turn they were written under: `AiConversationSchema.messages` is `AiConversationMessageSchema` (`AiMessageSchema` plus an optional `turnId`), and the `AIConversation` contract's `messages` are `AIConversationMessage` (`ModelMessage` plus an optional `turnId`). Optional: a stored conversation whose messages carry none still parses, and a service that writes none still satisfies the contract. +A persisted conversation's messages may now carry the turn they were written under: `AiConversationSchema.messages` is `AiConversationMessageSchema` (`AiMessageSchema` plus a `turnId` that may be absent or null), and the `AIConversation` contract's `messages` are `AIConversationMessage` (`ModelMessage` plus `turnId?: string | null`). A stored conversation whose messages carry no turn, absent or null, still parses, and a service that writes none still satisfies the contract. diff --git a/packages/spec/src/api/ai-answer.test.ts b/packages/spec/src/api/ai-answer.test.ts index efbbb1c4452..3e20edea1e8 100644 --- a/packages/spec/src/api/ai-answer.test.ts +++ b/packages/spec/src/api/ai-answer.test.ts @@ -29,6 +29,7 @@ import { SetAiAnswerFeedbackRequestSchema, SetAiAnswerFeedbackResponseSchema, } from './index'; +import { serviceUnavailableMessage } from '../system'; /** Drop one key from a fixture. */ function without>(value: T, key: keyof T): Record { @@ -197,6 +198,35 @@ describe('answer feedback', () => { }); }); +describe('the framework door\'s refusals parse against each route error', () => { + // The door answers ahead of the route handler. `packages/runtime/src/domains/ai.ts:63-67`: + // `deps.error(ANONYMOUS_DENY_MESSAGE, 401, { code: 'UNAUTHENTICATED' })`, written by + // `error-envelope.ts` `buildApiError` as `{ code, message, httpStatus }` (the `details.code` + // is promoted, so no `details` remains). `dispatcher-plugin.ts:290-301` answers the same + // code on a route mounted on the HTTP server. 501 (`domains/unavailable.ts`) and 503 + // (`domains/ai.ts`) carry the status-derived code (`HttpStatusErrorCodeMap`). + const DOOR = [ + { code: 'UNAUTHENTICATED', message: 'Authentication is required to access this endpoint.', httpStatus: 401 }, + { code: 'NOT_IMPLEMENTED', message: serviceUnavailableMessage('ai'), httpStatus: 501 }, + { code: 'SERVICE_UNAVAILABLE', message: 'AI service routes not yet initialized', httpStatus: 503 }, + ]; + const ROUTE_ERRORS = { + savedQuestion: AiSavedQuestionErrorSchema, + artifact: AiAnswerArtifactErrorSchema, + feedback: AiAnswerFeedbackErrorSchema, + }; + + for (const [route, schema] of Object.entries(ROUTE_ERRORS)) { + it(`the ${route} error admits the door's 401, 501 and 503`, () => { + for (const body of DOOR) expect(schema.safeParse(body).success, `${route} ${body.code}`).toBe(true); + }); + + it(`CONTROL: the ${route} code list stays closed`, () => { + expect(schema.safeParse({ ...DOOR[0], code: 'RATE_LIMIT_EXCEEDED', httpStatus: 429 }).success).toBe(false); + }); + } +}); + describe('a conversation message carries its turnId', () => { const conversation = { id: 'conv_1', @@ -209,6 +239,11 @@ describe('a conversation message carries its turnId', () => { expect(AiConversationSchema.safeParse(conversation).success).toBe(true); }); + it('a message stored with no turn may carry turnId: null (the column is nullable)', () => { + const unstamped = { ...conversation, messages: conversation.messages.map((m) => ({ ...m, turnId: null })) }; + expect(AiConversationSchema.safeParse(unstamped).success).toBe(true); + }); + it('a message with turnId keeps it, typed', () => { const stamped = { ...conversation, diff --git a/packages/spec/src/api/ai-answer.zod.ts b/packages/spec/src/api/ai-answer.zod.ts index 2c836f47dad..721e838e065 100644 --- a/packages/spec/src/api/ai-answer.zod.ts +++ b/packages/spec/src/api/ai-answer.zod.ts @@ -28,12 +28,20 @@ import { StandardErrorCode } from './errors.zod'; * `routes/feedback-routes.ts`, `saved/saved-question-store.ts`, * `saved/source-artifact.ts`, `feedback/answer-feedback-store.ts`). Every * success body is the platform envelope `{ success: true, data }` and each - * response schema here is the `data` payload; every failure body is - * `{ success: false, error }` with `error` one of the three route errors below. + * response schema here is the `data` payload. A failure body is + * `{ success: false, error }` with `error` one of the three route errors below, + * whose `code` lists hold both the route handler's codes and the framework + * door's. The door answers ahead of the handler, with no `details`: 401 + * UNAUTHENTICATED for a caller with no session (`packages/runtime` + * `domains/ai.ts`; a route mounted on the HTTP server answers the flat + * `{ error, code, message }` body instead, `dispatcher-plugin.ts`, ADR-0112), + * 501 NOT_IMPLEMENTED when the deployment serves no AI, and 503 + * SERVICE_UNAVAILABLE before the AI routes are published. * * Every route is the signed-in caller's own: a saved question that is not the * caller's answers 404, and a conversation that is not the caller's answers 403 - * on the artifact and feedback routes. + * when a question is saved from one of its answers, and on the artifact and + * feedback routes. */ // ── Saved questions ─────────────────────────────────────────────────────── @@ -99,8 +107,12 @@ export const RunAiSavedQuestionResponseSchema = lazySchema(() => z.object({ result: z.unknown().describe('The data tool\'s result, parsed from its JSON text'), })); -/** The `error.code` vocabulary of the saved-question routes. */ +/** + * The `error.code` vocabulary of the saved-question routes: the handler's codes + * and the framework door's (UNAUTHENTICATED, NOT_IMPLEMENTED, SERVICE_UNAVAILABLE). + */ export const AiSavedQuestionErrorCodeSchema = lazySchema(() => StandardErrorCode.extract([ + 'UNAUTHENTICATED', 'PERMISSION_DENIED', 'MISSING_REQUIRED_FIELD', 'VALIDATION_ERROR', @@ -108,6 +120,8 @@ export const AiSavedQuestionErrorCodeSchema = lazySchema(() => StandardErrorCode 'RESOURCE_NOT_FOUND', 'RESOURCE_CONFLICT', 'INTERNAL_ERROR', + 'NOT_IMPLEMENTED', + 'SERVICE_UNAVAILABLE', ])); /** @@ -196,14 +210,19 @@ export const CreateAiAnswerArtifactResponseSchema = lazySchema(() => z.discrimin AnswerWidgetArtifactSchema(), ])); -/** The `error.code` vocabulary of the artifact route. */ +/** + * The `error.code` vocabulary of the artifact route: the handler's codes and the + * framework door's (UNAUTHENTICATED, NOT_IMPLEMENTED, SERVICE_UNAVAILABLE). + */ export const AiAnswerArtifactErrorCodeSchema = lazySchema(() => StandardErrorCode.extract([ + 'UNAUTHENTICATED', 'PERMISSION_DENIED', 'MISSING_REQUIRED_FIELD', 'VALIDATION_ERROR', 'RESOURCE_NOT_FOUND', 'NOT_IMPLEMENTED', 'INTERNAL_ERROR', + 'SERVICE_UNAVAILABLE', ])); /** @@ -270,14 +289,20 @@ export const SetAiAnswerFeedbackResponseSchema = lazySchema(() => z.object({ feedback: AiAnswerFeedbackSchema.describe('The stored rating'), })); -/** The `error.code` vocabulary of the feedback routes. */ +/** + * The `error.code` vocabulary of the feedback routes: the handler's codes and the + * framework door's (UNAUTHENTICATED, NOT_IMPLEMENTED, SERVICE_UNAVAILABLE). + */ export const AiAnswerFeedbackErrorCodeSchema = lazySchema(() => StandardErrorCode.extract([ + 'UNAUTHENTICATED', 'PERMISSION_DENIED', 'MISSING_REQUIRED_FIELD', 'VALIDATION_ERROR', 'VALUE_TOO_LONG', 'RESOURCE_NOT_FOUND', 'INTERNAL_ERROR', + 'NOT_IMPLEMENTED', + 'SERVICE_UNAVAILABLE', ])); /** The `error` of a feedback route failure. */ diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 4afb53a2d91..5a777978dc7 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -4404,9 +4404,9 @@ export const AiModelsResponseSchema = lazySchema(() => z.object({ * return it: {@link AiMessageSchema} plus the turn it belongs to. */ export const AiConversationMessageSchema = lazySchema(() => AiMessageSchema.extend({ - turnId: z.string().optional().describe( + turnId: z.string().nullable().optional().describe( 'The turn the server stamped on the message: the `turnId` of the chat request that wrote it. ' - + 'Absent on a message stored with no turn', + + 'Absent or null on a message stored with no turn', ), })); diff --git a/packages/spec/src/contracts/ai-service.ts b/packages/spec/src/contracts/ai-service.ts index a4c4c132e68..627588a561b 100644 --- a/packages/spec/src/contracts/ai-service.ts +++ b/packages/spec/src/contracts/ai-service.ts @@ -1343,12 +1343,12 @@ export interface AIObjectResult { /** * One message of a persisted conversation: a Vercel `ModelMessage` plus the * turn it belongs to, the `turnId` it was written under - * ({@link IAIConversationService.addMessage}). Absent on a message stored with - * no turn. The wire shape is `AiConversationMessageSchema` (`api/protocol.zod.ts`). + * ({@link IAIConversationService.addMessage}). Absent or null on a message + * stored with no turn. The wire shape is `AiConversationMessageSchema` (`api/protocol.zod.ts`). */ export type AIConversationMessage = ModelMessage & { - /** The turn the message was written under. */ - turnId?: string; + /** The turn the message was written under; absent or null when it had none. */ + turnId?: string | null; }; /** From 75a91d1817e0c8bcb6cad9c2dbd121867e5a8db1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:22:46 +0000 Subject: [PATCH 10/11] chore(spec): regenerate the reference docs for the door codes and nullable turnId Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- content/docs/references/api/ai-answer.mdx | 64 ++++++++++++++++++++--- content/docs/references/api/protocol.mdx | 8 +-- 2 files changed, 62 insertions(+), 10 deletions(-) diff --git a/content/docs/references/api/ai-answer.mdx b/content/docs/references/api/ai-answer.mdx index 59ccfd11264..5961265395e 100644 --- a/content/docs/references/api/ai-answer.mdx +++ b/content/docs/references/api/ai-answer.mdx @@ -26,12 +26,20 @@ service (`service-ai`: `routes/saved-question-routes.ts`, `routes/feedback-routes.ts`, `saved/saved-question-store.ts`, `saved/source-artifact.ts`, `feedback/answer-feedback-store.ts`). Every success body is the platform envelope `{ success: true, data }` and each -response schema here is the `data` payload; every failure body is -`{ success: false, error }` with `error` one of the three route errors below. +response schema here is the `data` payload. A failure body is +`{ success: false, error }` with `error` one of the three route errors below, +whose `code` lists hold both the route handler's codes and the framework +door's. The door answers ahead of the handler, with no `details`: 401 +UNAUTHENTICATED for a caller with no session (`packages/runtime` +`domains/ai.ts`; a route mounted on the HTTP server answers the flat +`{ error, code, message }` body instead, `dispatcher-plugin.ts`, ADR-0112), +501 NOT_IMPLEMENTED when the deployment serves no AI, and 503 +SERVICE_UNAVAILABLE before the AI routes are published. Every route is the signed-in caller's own: a saved question that is not the caller's answers 404, and a conversation that is not the caller's answers 403 -on the artifact and feedback routes. +when a question is saved from one of its answers, and on the artifact and +feedback routes. **Source:** `packages/spec/src/api/ai-answer.zod.ts` @@ -67,7 +75,7 @@ const result = AiAnswerArtifactDraftSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'PERMISSION_DENIED' \| 'MISSING_REQUIRED_FIELD' \| 'VALIDATION_ERROR' \| 'RESOURCE_NOT_FOUND' \| 'NOT_IMPLEMENTED' \| 'INTERNAL_ERROR'>` | ✅ | Error code | +| **code** | `Enum<'UNAUTHENTICATED' \| 'PERMISSION_DENIED' \| 'MISSING_REQUIRED_FIELD' \| 'VALIDATION_ERROR' \| 'RESOURCE_NOT_FOUND' \| 'NOT_IMPLEMENTED' \| 'INTERNAL_ERROR' \| … +1 more>` | ✅ | Error code | | **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | | **message** | `string` | ✅ | Readable error message | | **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | @@ -77,6 +85,17 @@ const result = AiAnswerArtifactDraftSchema.parse(data); | **details** | `{ reason: Enum<'report_authoring_requires_manage_metadata' \| 'report_authoring_walled' \| …>; issues?: any }` | optional | Present on a named refusal | | **requestId** | `string` | optional | Request ID for tracking | +### Allowed Values: `AiAnswerArtifactError.code` + +* `UNAUTHENTICATED` +* `PERMISSION_DENIED` +* `MISSING_REQUIRED_FIELD` +* `VALIDATION_ERROR` +* `RESOURCE_NOT_FOUND` +* `NOT_IMPLEMENTED` +* `INTERNAL_ERROR` +* `SERVICE_UNAVAILABLE` + ### Nested Shape: `AiAnswerArtifactError.details` | Property | Type | Required | Description | @@ -91,12 +110,14 @@ const result = AiAnswerArtifactDraftSchema.parse(data); ### Allowed Values +* `UNAUTHENTICATED` * `PERMISSION_DENIED` * `MISSING_REQUIRED_FIELD` * `VALIDATION_ERROR` * `RESOURCE_NOT_FOUND` * `NOT_IMPLEMENTED` * `INTERNAL_ERROR` +* `SERVICE_UNAVAILABLE` --- @@ -153,7 +174,7 @@ const result = AiAnswerArtifactDraftSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'PERMISSION_DENIED' \| 'MISSING_REQUIRED_FIELD' \| 'VALIDATION_ERROR' \| 'VALUE_TOO_LONG' \| 'RESOURCE_NOT_FOUND' \| 'INTERNAL_ERROR'>` | ✅ | Error code | +| **code** | `Enum<'UNAUTHENTICATED' \| 'PERMISSION_DENIED' \| 'MISSING_REQUIRED_FIELD' \| 'VALIDATION_ERROR' \| 'VALUE_TOO_LONG' \| 'RESOURCE_NOT_FOUND' \| 'INTERNAL_ERROR' \| … +2 more>` | ✅ | Error code | | **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | | **message** | `string` | ✅ | Readable error message | | **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | @@ -163,6 +184,18 @@ const result = AiAnswerArtifactDraftSchema.parse(data); | **details** | `any` | optional | Additional error context (e.g. field validation errors) | | **requestId** | `string` | optional | Request ID for tracking | +### Allowed Values: `AiAnswerFeedbackError.code` + +* `UNAUTHENTICATED` +* `PERMISSION_DENIED` +* `MISSING_REQUIRED_FIELD` +* `VALIDATION_ERROR` +* `VALUE_TOO_LONG` +* `RESOURCE_NOT_FOUND` +* `INTERNAL_ERROR` +* `NOT_IMPLEMENTED` +* `SERVICE_UNAVAILABLE` + --- @@ -170,12 +203,15 @@ const result = AiAnswerArtifactDraftSchema.parse(data); ### Allowed Values +* `UNAUTHENTICATED` * `PERMISSION_DENIED` * `MISSING_REQUIRED_FIELD` * `VALIDATION_ERROR` * `VALUE_TOO_LONG` * `RESOURCE_NOT_FOUND` * `INTERNAL_ERROR` +* `NOT_IMPLEMENTED` +* `SERVICE_UNAVAILABLE` --- @@ -230,7 +266,7 @@ const result = AiAnswerArtifactDraftSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'PERMISSION_DENIED' \| 'MISSING_REQUIRED_FIELD' \| 'VALIDATION_ERROR' \| 'VALUE_TOO_LONG' \| 'RESOURCE_NOT_FOUND' \| 'RESOURCE_CONFLICT' \| 'INTERNAL_ERROR'>` | ✅ | Error code | +| **code** | `Enum<'UNAUTHENTICATED' \| 'PERMISSION_DENIED' \| 'MISSING_REQUIRED_FIELD' \| 'VALIDATION_ERROR' \| 'VALUE_TOO_LONG' \| 'RESOURCE_NOT_FOUND' \| 'RESOURCE_CONFLICT' \| … +3 more>` | ✅ | Error code | | **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | | **message** | `string` | ✅ | Readable error message | | **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | @@ -240,6 +276,19 @@ const result = AiAnswerArtifactDraftSchema.parse(data); | **details** | `{ reason: Enum<'saved_question_has_no_query' \| 'saved_question_run_failed'>; question?: string }` | optional | Present on a run refusal | | **requestId** | `string` | optional | Request ID for tracking | +### Allowed Values: `AiSavedQuestionError.code` + +* `UNAUTHENTICATED` +* `PERMISSION_DENIED` +* `MISSING_REQUIRED_FIELD` +* `VALIDATION_ERROR` +* `VALUE_TOO_LONG` +* `RESOURCE_NOT_FOUND` +* `RESOURCE_CONFLICT` +* `INTERNAL_ERROR` +* `NOT_IMPLEMENTED` +* `SERVICE_UNAVAILABLE` + ### Nested Shape: `AiSavedQuestionError.details` | Property | Type | Required | Description | @@ -254,6 +303,7 @@ const result = AiAnswerArtifactDraftSchema.parse(data); ### Allowed Values +* `UNAUTHENTICATED` * `PERMISSION_DENIED` * `MISSING_REQUIRED_FIELD` * `VALIDATION_ERROR` @@ -261,6 +311,8 @@ const result = AiAnswerArtifactDraftSchema.parse(data); * `RESOURCE_NOT_FOUND` * `RESOURCE_CONFLICT` * `INTERNAL_ERROR` +* `NOT_IMPLEMENTED` +* `SERVICE_UNAVAILABLE` --- diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 913e636b10b..fb06941288d 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -172,7 +172,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **title** | `string` | optional | Title / summary | | **agentId** | `string` | optional | Agent this conversation is bound to | | **userId** | `string` | optional | Owning user | -| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turnId?: string } & Record)[]` | ✅ | Message history | +| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turnId?: string \| null } & Record)[]` | ✅ | Message history | | **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | | **updatedAt** | `string` | ✅ | Last update timestamp (ISO 8601) | | **metadata** | `Record` | optional | Conversation metadata | @@ -184,7 +184,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **role** | `Enum<'system' \| 'user' \| 'assistant' \| 'tool'>` | ✅ | Message role | | **content** | `any` | optional | Message content: a string, or an array of content parts | | **parts** | `any[]` | optional | Vercel AI SDK v6 message parts (alternative to `content`) | -| **turnId** | `string` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent on a message stored with no turn | +| **turnId** | `string \| null` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent or null on a message stored with no turn | --- @@ -198,7 +198,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **role** | `Enum<'system' \| 'user' \| 'assistant' \| 'tool'>` | ✅ | Message role | | **content** | `any` | optional | Message content: a string, or an array of content parts | | **parts** | `any[]` | optional | Vercel AI SDK v6 message parts (alternative to `content`) | -| **turnId** | `string` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent on a message stored with no turn | +| **turnId** | `string \| null` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent or null on a message stored with no turn | --- @@ -2292,7 +2292,7 @@ Install package response | **title** | `string` | optional | Title / summary | | **agentId** | `string` | optional | Agent this conversation is bound to | | **userId** | `string` | optional | Owning user | -| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turnId?: string } & Record)[]` | ✅ | Message history | +| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turnId?: string \| null } & Record)[]` | ✅ | Message history | | **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | | **updatedAt** | `string` | ✅ | Last update timestamp (ISO 8601) | | **metadata** | `Record` | optional | Conversation metadata | From 3f9f00da9a9f9649d643204f87d50880d4037530 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:45:47 +0000 Subject: [PATCH 11/11] test(spec): cite the door by symbol anchors, not line numbers Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/spec/src/api/ai-answer.test.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/spec/src/api/ai-answer.test.ts b/packages/spec/src/api/ai-answer.test.ts index 3e20edea1e8..d34abe4fb68 100644 --- a/packages/spec/src/api/ai-answer.test.ts +++ b/packages/spec/src/api/ai-answer.test.ts @@ -199,12 +199,14 @@ describe('answer feedback', () => { }); describe('the framework door\'s refusals parse against each route error', () => { - // The door answers ahead of the route handler. `packages/runtime/src/domains/ai.ts:63-67`: - // `deps.error(ANONYMOUS_DENY_MESSAGE, 401, { code: 'UNAUTHENTICATED' })`, written by - // `error-envelope.ts` `buildApiError` as `{ code, message, httpStatus }` (the `details.code` - // is promoted, so no `details` remains). `dispatcher-plugin.ts:290-301` answers the same - // code on a route mounted on the HTTP server. 501 (`domains/unavailable.ts`) and 503 - // (`domains/ai.ts`) carry the status-derived code (`HttpStatusErrorCodeMap`). + // The door answers ahead of the route handler. `packages/runtime/src/domains/ai.ts` + // refuses a caller with no session through `deps.error(ANONYMOUS_DENY_MESSAGE, 401, + // { code: ANONYMOUS_DENY_CODE })` (`packages/core/src/security/anonymous-deny.ts#ANONYMOUS_DENY_CODE`), + // written by `packages/runtime/src/error-envelope.ts#buildApiError` as + // `{ code, message, httpStatus }`: the `details.code` is promoted, so no `details` remains. + // `packages/runtime/src/dispatcher-plugin.ts` answers the same code on a route mounted on + // the HTTP server. The 501 (`packages/runtime/src/domains/unavailable.ts#capabilityUnavailable`) + // and the 503 carry the status-derived code (`packages/spec/src/api/errors.zod.ts#HttpStatusErrorCodeMap`). const DOOR = [ { code: 'UNAUTHENTICATED', message: 'Authentication is required to access this endpoint.', httpStatus: 401 }, { code: 'NOT_IMPLEMENTED', message: serviceUnavailableMessage('ai'), httpStatus: 501 },