From 96d6d648cf751bee496bbaa505f4326c81d1a68f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:18:28 +0000 Subject: [PATCH 1/2] chore: sync signed IgnitionRAG SDK contract --- .sdk-source.json | 4 +- README.md | 11 +- contracts/2026.11/public-sdk-contract.json | 1 + docs/compatibility.md | 52 +- docs/typescript-contract-2026-10.md | 91 + scripts/validate-release.ts | 2 +- typescript/CHANGELOG.md | 47 + typescript/README.md | 224 ++- typescript/package.json | 15 +- typescript/scripts/check-live.ts | 170 ++ typescript/scripts/generate-wire-types.ts | 32 +- typescript/scripts/verify-contract.ts | 59 +- typescript/src/browser.ts | 12 + typescript/src/client.ts | 1 + typescript/src/contract.ts | 8 +- typescript/src/errors.ts | 26 + typescript/src/generated/public-api.ts | 1626 +++++++++++++++-- typescript/src/index.ts | 76 +- typescript/src/resources/agent-chat.ts | 124 +- typescript/src/resources/agents.ts | 43 +- typescript/src/resources/chat.ts | 289 ++- typescript/src/resources/collections.ts | 42 + typescript/src/resources/data-chat.ts | 22 +- typescript/src/resources/feedback.ts | 13 + typescript/src/resources/ingest.ts | 161 +- typescript/src/resources/managed-contracts.ts | 311 ++++ typescript/src/resources/rag-ab-tests.ts | 14 + typescript/src/resources/traces.ts | 52 + typescript/src/resources/widgets.ts | 116 ++ typescript/src/resources/workflows.ts | 24 +- typescript/src/streaming.ts | 29 + typescript/src/types.ts | 520 ++++++ typescript/src/version.ts | 2 +- typescript/tests/agent-chat.test.ts | 53 + typescript/tests/agents.test.ts | 81 + typescript/tests/chat.test.ts | 94 + typescript/tests/collections.test.ts | 67 +- typescript/tests/compatibility.test.ts | 15 +- typescript/tests/contracts.types.ts | 84 + typescript/tests/data-chat.test.ts | 26 +- typescript/tests/errors.test.ts | 12 + typescript/tests/generate-wire-types.test.ts | 39 + typescript/tests/generated-contract.test.ts | 11 +- typescript/tests/ingest.test.ts | 197 ++ typescript/tests/live-check.test.ts | 90 + typescript/tests/operations-parity.test.ts | 39 + typescript/tests/readme-contract.test.ts | 9 + typescript/tests/verify-contract.test.ts | 74 + typescript/tests/widgets.test.ts | 89 + typescript/tests/workflows.test.ts | 37 +- 50 files changed, 4983 insertions(+), 253 deletions(-) create mode 100644 contracts/2026.11/public-sdk-contract.json create mode 100644 docs/typescript-contract-2026-10.md create mode 100644 typescript/CHANGELOG.md create mode 100644 typescript/scripts/check-live.ts create mode 100644 typescript/src/resources/feedback.ts create mode 100644 typescript/src/resources/managed-contracts.ts create mode 100644 typescript/src/resources/rag-ab-tests.ts create mode 100644 typescript/src/resources/traces.ts create mode 100644 typescript/src/resources/widgets.ts create mode 100644 typescript/tests/contracts.types.ts create mode 100644 typescript/tests/generate-wire-types.test.ts create mode 100644 typescript/tests/ingest.test.ts create mode 100644 typescript/tests/live-check.test.ts create mode 100644 typescript/tests/operations-parity.test.ts create mode 100644 typescript/tests/verify-contract.test.ts create mode 100644 typescript/tests/widgets.test.ts diff --git a/.sdk-source.json b/.sdk-source.json index cb58940..d69cb49 100644 --- a/.sdk-source.json +++ b/.sdk-source.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "sourceCommit": "60be0cdcc0ccb8cbc28c3840c0a3980370b41f5b", - "contract": "contracts/2026.07/public-sdk-contract.json", + "sourceCommit": "9996d0b44aa62d7e9dbcc9b7a533868c789d4d5c", + "contract": "contracts/2026.11/public-sdk-contract.json", "packages": [ "typescript" ] diff --git a/README.md b/README.md index 5bbdd9a..f88849a 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![npm](https://img.shields.io/npm/v/@ignitionai/sdk.svg)](https://www.npmjs.com/package/@ignitionai/sdk) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE) -Official open-source SDKs and signed public API contracts for IgnitionRAG deployments. +Official open-source TypeScript SDK and signed public API contracts for IgnitionRAG deployments. IgnitionRAG itself is licensed software. This repository contains client libraries only; it does not contain the product server, administration CLI, widgets, deployment tooling, customer configuration, or private MCP implementations. @@ -15,9 +15,10 @@ bun add @ignitionai/sdk@next # or npm install @ignitionai/sdk@next ``` -The current public release is `0.3.0-rc.3` under the npm `next` tag. The -unqualified install command remains on the stable `0.2.x` line until `0.3.0` is -promoted to `latest`. +This source tree prepares `1.0.0` for public contract `2026.11`; publication +requires the reviewed release workflow. `ingest.file` is a breaking change from +`0.3.0-rc.4`. The unqualified install command remains on the stable `0.2.x` line +until `1.0.0` is promoted to `latest`. ```ts import { IgnitionAI } from "@ignitionai/sdk"; @@ -39,8 +40,6 @@ See the [TypeScript SDK guide](./typescript/README.md) for server, browser, stre - `examples/` — minimal runtime smoke examples. - `docs/` — compatibility and release documentation. -The Python SDK may be added later. It is not part of the current support commitment. - ## Security API keys are server-side credentials. Browser applications must use `@ignitionai/sdk/browser` with a delegated token provider. See [SECURITY.md](./SECURITY.md) to report a vulnerability privately. diff --git a/contracts/2026.11/public-sdk-contract.json b/contracts/2026.11/public-sdk-contract.json new file mode 100644 index 0000000..785709e --- /dev/null +++ b/contracts/2026.11/public-sdk-contract.json @@ -0,0 +1 @@ +{"digest":"sha256:3310655bcef1575012a33d53a784045bbd40697d350e59e945a94beb46811a81","payload":{"contractVersion":"2026.11","manifest":{"capabilities":["agents","collections","deep_research","evaluations","feedback","ingestion","observability","rag_chat","rag_experiments","workflows"],"contractVersion":"2026.11","operations":[{"auth":"api_key_or_user_token","capability":"rag_chat","method":"post","operationId":"chat.send","path":"/api/chat","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"rag_chat","method":"post","operationId":"chat.stream","path":"/api/chat/stream","protocol":"chat_sse","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"rag_chat","method":"post","operationId":"chat.streamProgressive","path":"/api/chat/stream/progressive","protocol":"chat_sse","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"collections","method":"get","operationId":"collections.listPublic","path":"/api/public-collections","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"get","operationId":"collections.getPublic","path":"/api/public-collections/{slug}","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"get","operationId":"collections.list","path":"/api/collections","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"post","operationId":"collections.create","path":"/api/collections","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"get","operationId":"collections.get","path":"/api/collections/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"patch","operationId":"collections.update","path":"/api/collections/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"delete","operationId":"collections.delete","path":"/api/collections/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"get","operationId":"collections.insights","path":"/api/collections/:id/insights","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"post","operationId":"collections.regenerateInsights","path":"/api/collections/:id/insights/regenerate","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"collections","method":"get","operationId":"collections.chunks","path":"/api/collections/:id/chunks","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"get","operationId":"collections.search","path":"/api/collections/:id/search","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"get","operationId":"collections.stats","path":"/api/collections/:id/stats","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"get","operationId":"collections.qualityReport","path":"/api/collections/:id/quality-report","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"get","operationId":"collections.documents","path":"/api/collections/:id/documents","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"collections","method":"put","operationId":"collections.setRagConfig","path":"/api/collections/:collectionId/rag-config","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.url","path":"/api/ingest/url","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.document","path":"/api/ingest/document","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.file","path":"/api/ingest/file","protocol":"multipart_ingestion","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.crawl","path":"/api/ingest/crawl","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.dataset","path":"/api/ingest/dataset","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.fileAsync","path":"/api/ingest/file/async","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.crawlAsync","path":"/api/ingest/crawl/async","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.datasetAsync","path":"/api/ingest/dataset/async","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.discover","path":"/api/ingest/discover","protocol":"async_operation","stability":"experimental","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.crawlSelectedAsync","path":"/api/ingest/crawl-selected/async","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"ingestion","method":"get","operationId":"ingestion.getJob","path":"/api/ingest/jobs/{jobId}","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"ingestion","method":"get","operationId":"ingestion.listJobs","path":"/api/ingest/jobs","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"ingestion","method":"get","operationId":"ingestion.streamJob","path":"/api/ingest/jobs/{jobId}/stream","protocol":"ingestion_job_sse","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"ingestion","method":"post","operationId":"ingestion.cancelJob","path":"/api/ingest/jobs/{jobId}/cancel","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"agents","method":"get","operationId":"agents.listSkills","path":"/api/agents/skills","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"agents","method":"post","operationId":"agents.createSkill","path":"/api/agents/skills","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"agents","method":"patch","operationId":"agents.updateSkill","path":"/api/agents/skills/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"agents","method":"delete","operationId":"agents.deleteSkill","path":"/api/agents/skills/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"agents","method":"get","operationId":"agents.list","path":"/api/agents","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"agents","method":"post","operationId":"agents.create","path":"/api/agents","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"agents","method":"get","operationId":"agents.get","path":"/api/agents/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"agents","method":"patch","operationId":"agents.update","path":"/api/agents/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"agents","method":"delete","operationId":"agents.delete","path":"/api/agents/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"agents","method":"post","operationId":"agents.generate","path":"/api/agents/generate","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"agents","method":"post","operationId":"agents.chatStream","path":"/api/agents/:id/chat/stream","protocol":"agent_sse","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"deep_research","method":"post","operationId":"deepResearch.cancel","path":"/api/agents/:agentId/chat/cancel-deep","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"deep_research","method":"get","operationId":"deepResearch.status","path":"/api/agents/:agentId/chat/deep-status","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"deep_research","method":"get","operationId":"deepResearch.stream","path":"/api/agents/:agentId/chat/deep-stream","protocol":"agent_sse","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"workflows","method":"get","operationId":"workflows.list","path":"/api/workflows","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"workflows","method":"post","operationId":"workflows.create","path":"/api/workflows","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"workflows","method":"get","operationId":"workflows.get","path":"/api/workflows/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"workflows","method":"patch","operationId":"workflows.update","path":"/api/workflows/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"workflows","method":"delete","operationId":"workflows.delete","path":"/api/workflows/:id","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"workflows","method":"post","operationId":"workflows.validate","path":"/api/workflows/:id/validate","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"workflows","method":"post","operationId":"workflows.execute","path":"/api/workflows/:id/execute","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"workflows","method":"get","operationId":"workflows.listExecutions","path":"/api/workflows/:id/executions","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"workflows","method":"get","operationId":"workflows.getExecution","path":"/api/workflows/executions/:executionId","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"workflows","method":"delete","operationId":"workflows.cancelExecution","path":"/api/workflows/executions/:executionId","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"evaluations","method":"post","operationId":"evaluations.create","path":"/api/collections/:id/evaluations","protocol":"async_operation","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"evaluations","method":"get","operationId":"evaluations.list","path":"/api/collections/:id/evaluations","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"evaluations","method":"get","operationId":"evaluations.get","path":"/api/evaluations/:evaluationId","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"rag_experiments","method":"post","operationId":"ragExperiments.runAbTest","path":"/api/collections/:collectionId/rag-config/test","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"observability","method":"get","operationId":"observability.listTraces","path":"/api/traces","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"observability","method":"get","operationId":"observability.getTrace","path":"/api/traces/{id}","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"observability","method":"get","operationId":"observability.getTraceMetrics","path":"/api/traces/metrics","stability":"stable","versionSensitive":false},{"auth":"api_key_or_user_token","capability":"observability","method":"get","operationId":"observability.exportTraces","path":"/api/traces/export","stability":"stable","versionSensitive":true},{"auth":"api_key_or_user_token","capability":"feedback","method":"post","operationId":"feedback.submit","path":"/api/feedback","stability":"stable","versionSensitive":true}],"schemaVersion":1},"openapi":{"components":{"schemas":{"ABTestConfig":{"properties":{"configA":{"$ref":"#/components/schemas/RAGConfigInput"},"configB":{"$ref":"#/components/schemas/RAGConfigInput"},"evaluateQuality":{"default":false,"type":"boolean"},"testQuery":{"example":"What is machine learning?","minLength":1,"type":"string"}},"required":["configA","configB","testQuery"],"type":"object"},"ABTestResult":{"properties":{"comparison":{"properties":{"qualityConfidence":{"enum":["high","medium","low"],"type":"string"},"qualityDimensions":{"properties":{"clarity":{"properties":{"reasoning":{"type":"string"},"winner":{"enum":["A","B","tie"],"type":"string"}},"required":["winner","reasoning"],"type":"object"},"completeness":{"properties":{"reasoning":{"type":"string"},"winner":{"enum":["A","B","tie"],"type":"string"}},"required":["winner","reasoning"],"type":"object"},"faithfulness":{"properties":{"reasoning":{"type":"string"},"winner":{"enum":["A","B","tie"],"type":"string"}},"required":["winner","reasoning"],"type":"object"},"relevance":{"properties":{"reasoning":{"type":"string"},"winner":{"enum":["A","B","tie"],"type":"string"}},"required":["winner","reasoning"],"type":"object"}},"required":["relevance","faithfulness","completeness","clarity"],"type":"object"},"qualityReasoning":{"type":"string"},"qualityWinner":{"enum":["A","B","tie"],"type":"string"},"recommendation":{"type":"string"},"resultOverlap":{"type":"number"},"speedDifferenceMs":{"type":"number"},"speedWinner":{"enum":["A","B","tie"],"type":"string"}},"required":["speedDifferenceMs","speedWinner","resultOverlap","recommendation"],"type":"object"},"configA":{"properties":{"config":{"properties":{"features":{"properties":{"citations":{"type":"boolean"},"contextualRetrieval":{"type":"boolean"},"dynamicFeatureSelection":{"type":"boolean"},"hybridSearch":{"type":"boolean"},"hyde":{"type":"boolean"},"multiQuery":{"type":"boolean"},"parallelEnhancement":{"type":"boolean"},"queryExpansion":{"type":"boolean"},"queryRewriting":{"type":"boolean"},"reranking":{"type":"boolean"},"selfQuery":{"type":"boolean"}},"required":["hybridSearch","selfQuery","queryRewriting","queryExpansion","hyde","multiQuery","reranking","contextualRetrieval","citations","parallelEnhancement","dynamicFeatureSelection"],"type":"object"},"hybridSearch":{"properties":{"alpha":{"type":"number"},"bm25":{"properties":{"b":{"type":"number"},"k1":{"type":"number"}},"required":["k1","b"],"type":"object"},"rrf":{"properties":{"k":{"type":"number"}},"required":["k"],"type":"object"}},"required":["alpha","bm25","rrf"],"type":"object"},"llm":{"properties":{"citationFormat":{"enum":["brackets","footnote","inline"],"type":"string"}},"required":["citationFormat"],"type":"object"},"reranking":{"properties":{"provider":{"enum":["jina","llm"],"type":"string"},"topN":{"type":"number"}},"required":["provider","topN"],"type":"object"},"retrieval":{"properties":{"topK":{"type":"number"}},"required":["topK"],"type":"object"},"version":{"enum":[1],"type":"number"}},"required":["version","features","hybridSearch","reranking","retrieval","llm"],"type":"object"},"featuresUsed":{"items":{"type":"string"},"type":"array"},"metrics":{"properties":{"queryEnhancementMs":{"type":"number"},"rerankMs":{"type":"number"},"resultsCount":{"type":"number"},"searchMs":{"type":"number"},"totalTimeMs":{"type":"number"}},"required":["totalTimeMs","queryEnhancementMs","searchMs","rerankMs","resultsCount"],"type":"object"},"qualityScores":{"properties":{"clarity":{"maximum":5,"minimum":1,"type":"number"},"completeness":{"maximum":5,"minimum":1,"type":"number"},"faithfulness":{"maximum":5,"minimum":1,"type":"number"},"overall":{"type":"number"},"relevance":{"maximum":5,"minimum":1,"type":"number"}},"required":["relevance","faithfulness","completeness","clarity","overall"],"type":"object"},"response":{"type":"string"},"topResults":{"items":{"properties":{"id":{"type":"string"},"score":{"type":"number"},"title":{"type":"string"}},"required":["id","score"],"type":"object"},"type":"array"}},"required":["config","metrics","featuresUsed","topResults"],"type":"object"},"configB":{"properties":{"config":{"properties":{"features":{"properties":{"citations":{"type":"boolean"},"contextualRetrieval":{"type":"boolean"},"dynamicFeatureSelection":{"type":"boolean"},"hybridSearch":{"type":"boolean"},"hyde":{"type":"boolean"},"multiQuery":{"type":"boolean"},"parallelEnhancement":{"type":"boolean"},"queryExpansion":{"type":"boolean"},"queryRewriting":{"type":"boolean"},"reranking":{"type":"boolean"},"selfQuery":{"type":"boolean"}},"required":["hybridSearch","selfQuery","queryRewriting","queryExpansion","hyde","multiQuery","reranking","contextualRetrieval","citations","parallelEnhancement","dynamicFeatureSelection"],"type":"object"},"hybridSearch":{"properties":{"alpha":{"type":"number"},"bm25":{"properties":{"b":{"type":"number"},"k1":{"type":"number"}},"required":["k1","b"],"type":"object"},"rrf":{"properties":{"k":{"type":"number"}},"required":["k"],"type":"object"}},"required":["alpha","bm25","rrf"],"type":"object"},"llm":{"properties":{"citationFormat":{"enum":["brackets","footnote","inline"],"type":"string"}},"required":["citationFormat"],"type":"object"},"reranking":{"properties":{"provider":{"enum":["jina","llm"],"type":"string"},"topN":{"type":"number"}},"required":["provider","topN"],"type":"object"},"retrieval":{"properties":{"topK":{"type":"number"}},"required":["topK"],"type":"object"},"version":{"enum":[1],"type":"number"}},"required":["version","features","hybridSearch","reranking","retrieval","llm"],"type":"object"},"featuresUsed":{"items":{"type":"string"},"type":"array"},"metrics":{"properties":{"queryEnhancementMs":{"type":"number"},"rerankMs":{"type":"number"},"resultsCount":{"type":"number"},"searchMs":{"type":"number"},"totalTimeMs":{"type":"number"}},"required":["totalTimeMs","queryEnhancementMs","searchMs","rerankMs","resultsCount"],"type":"object"},"qualityScores":{"properties":{"clarity":{"maximum":5,"minimum":1,"type":"number"},"completeness":{"maximum":5,"minimum":1,"type":"number"},"faithfulness":{"maximum":5,"minimum":1,"type":"number"},"overall":{"type":"number"},"relevance":{"maximum":5,"minimum":1,"type":"number"}},"required":["relevance","faithfulness","completeness","clarity","overall"],"type":"object"},"response":{"type":"string"},"topResults":{"items":{"properties":{"id":{"type":"string"},"score":{"type":"number"},"title":{"type":"string"}},"required":["id","score"],"type":"object"},"type":"array"}},"required":["config","metrics","featuresUsed","topResults"],"type":"object"}},"required":["configA","configB","comparison"],"type":"object"},"Agent":{"properties":{"collectionId":{"nullable":true,"type":"string"},"collectionName":{"nullable":true,"type":"string"},"contextWindowSize":{"type":"number"},"createdAt":{"type":"string"},"description":{"nullable":true,"type":"string"},"enableContextEngineering":{"type":"boolean"},"enabledBuiltinTools":{"items":{"$ref":"#/components/schemas/BuiltinToolConfig"},"nullable":true,"type":"array"},"fallbackLlmConfigId":{"nullable":true,"type":"string"},"id":{"format":"uuid","type":"string"},"instructions":{"nullable":true,"type":"string"},"isActive":{"type":"boolean"},"isDefault":{"type":"boolean"},"llmConfigId":{"nullable":true,"type":"string"},"maxTokens":{"type":"number"},"mcpServers":{"items":{"$ref":"#/components/schemas/McpServer"},"nullable":true,"type":"array"},"model":{"type":"string"},"name":{"type":"string"},"openWebuiEnabled":{"type":"boolean"},"resources":{"items":{"$ref":"#/components/schemas/AgentResource"},"type":"array"},"runtimeConnectionId":{"format":"uuid","nullable":true,"type":"string"},"runtimeKind":{"enum":["byok_api","cli_runtime","ignis"],"type":"string"},"runtimePreferences":{"nullable":true,"properties":{"mode":{"nullable":true,"type":"string"},"model":{"nullable":true,"type":"string"},"reasoningLevel":{"nullable":true,"type":"string"}},"type":"object"},"runtimeProfileId":{"format":"uuid","nullable":true,"type":"string"},"scoreThreshold":{"type":"number"},"skillIds":{"items":{"format":"uuid","type":"string"},"type":"array"},"subAgentIds":{"items":{"type":"string"},"nullable":true,"type":"array"},"systemPrompt":{"nullable":true,"type":"string"},"temperature":{"type":"number"},"topK":{"type":"number"},"updatedAt":{"type":"string"},"workflowToolIds":{"items":{"format":"uuid","type":"string"},"type":"array"}},"required":["id","name","description","collectionId","resources","systemPrompt","instructions","llmConfigId","runtimeKind","runtimeProfileId","runtimeConnectionId","runtimePreferences","model","temperature","maxTokens","topK","scoreThreshold","mcpServers","enabledBuiltinTools","skillIds","workflowToolIds","isActive","isDefault","openWebuiEnabled","subAgentIds","enableContextEngineering","contextWindowSize","createdAt","updatedAt"],"type":"object"},"AgentChatRequest":{"properties":{"attachments":{"$ref":"#/components/schemas/ChatAttachments"},"depth":{"default":"quick","description":"Research depth: 'quick' for instant RAG, 'deep' for full deep research","enum":["quick","deep"],"type":"string"},"history":{"description":"Recent chat history (used if context engineering is disabled)","items":{"properties":{"content":{"type":"string"},"role":{"enum":["user","assistant"],"type":"string"}},"required":["role","content"],"type":"object"},"type":"array"},"query":{"minLength":1,"type":"string"},"sessionId":{"description":"Unique session ID for conversation continuity","example":"session_abc123","minLength":1,"type":"string"}},"required":["query","sessionId"],"type":"object"},"AgentResource":{"properties":{"id":{"format":"uuid","type":"string"},"name":{"nullable":true,"type":"string"},"priority":{"default":0,"maximum":100,"minimum":0,"type":"integer"},"type":{"enum":["collection"],"type":"string"}},"required":["type","id"],"type":"object"},"AgentSkill":{"properties":{"builtinTools":{"items":{"$ref":"#/components/schemas/BuiltinToolConfig"},"nullable":true,"type":"array"},"builtinVersion":{"type":"string"},"constraints":{"nullable":true,"type":"string"},"contentHash":{"type":"string"},"createdAt":{"type":"string"},"createdByUserId":{"nullable":true,"type":"string"},"currentVersion":{"minimum":0,"type":"integer"},"description":{"nullable":true,"type":"string"},"examples":{"items":{"$ref":"#/components/schemas/AgentSkillExample"},"nullable":true,"type":"array"},"id":{"format":"uuid","type":"string"},"instructions":{"nullable":true,"type":"string"},"mcpServerRefs":{"items":{"type":"string"},"nullable":true,"type":"array"},"name":{"type":"string"},"origin":{"enum":["organization","builtin"],"type":"string"},"readOnly":{"type":"boolean"},"status":{"$ref":"#/components/schemas/AgentSkillStatus"},"updatedAt":{"type":"string"},"workflowToolRefs":{"items":{"format":"uuid","type":"string"},"nullable":true,"type":"array"}},"required":["id","name","description","instructions","constraints","examples","builtinTools","mcpServerRefs","workflowToolRefs","status","createdByUserId","createdAt","updatedAt"],"type":"object"},"AgentSkillExample":{"properties":{"input":{"type":"string"},"notes":{"type":"string"},"output":{"type":"string"}},"type":"object"},"AgentSkillStatus":{"enum":["draft","published","archived"],"type":"string"},"BuiltinToolConfig":{"anyOf":[{"type":"string"},{"properties":{"humanInTheLoop":{"type":"boolean"},"id":{"type":"string"}},"required":["id"],"type":"object"}]},"ChatAttachments":{"description":"MCP prompts and resources to inject into the chat context","properties":{"prompts":{"items":{"$ref":"#/components/schemas/PromptAttachment"},"type":"array"},"resources":{"items":{"$ref":"#/components/schemas/ResourceAttachment"},"type":"array"}},"type":"object"},"ChatErrorResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"}},"required":["error"],"type":"object"},"ChatRequest":{"additionalProperties":false,"properties":{"collectionId":{"type":"string"},"filters":{"items":{"$ref":"#/components/schemas/FilterDefinition"},"type":"array"},"history":{"items":{"$ref":"#/components/schemas/Message"},"type":"array"},"includeImages":{"default":true,"type":"boolean"},"llmConfigId":{"type":"string"},"maximumMilliCredits":{"pattern":"^[1-9][0-9]{0,15}$","type":"string"},"query":{"minLength":1,"type":"string"}},"required":["collectionId","query"],"type":"object"},"ChatResponse":{"properties":{"answer":{"type":"string"},"featuresUsed":{"items":{"type":"string"},"type":"array"},"images":{"items":{"$ref":"#/components/schemas/ImageResult"},"type":"array"},"model":{"type":"string"},"pipelineMetrics":{"$ref":"#/components/schemas/PipelineMetrics"},"relevanceScore":{"type":"number"},"sources":{"items":{"$ref":"#/components/schemas/Source"},"type":"array"},"usage":{"properties":{"completionTokens":{"type":"number"},"promptTokens":{"type":"number"}},"required":["promptTokens","completionTokens"],"type":"object"}},"required":["answer","sources"],"type":"object"},"ChatValidationError":{"properties":{"code":{"enum":["VALIDATION_ERROR"],"type":"string"},"details":{"items":{"properties":{"field":{"type":"string"},"message":{"type":"string"},"path":{"items":{"anyOf":[{"type":"string"},{"type":"number"}]},"type":"array"}},"required":["field","message","path"],"type":"object"},"type":"array"},"error":{"type":"string"}},"required":["error","code","details"],"type":"object"},"Chunk":{"properties":{"blobPath":{"type":"string"},"chunkIndex":{"type":"number"},"content":{"type":"string"},"createdAt":{"type":"string"},"documentId":{"type":"string"},"entities":{"items":{"properties":{"confidence":{"maximum":1,"minimum":0,"type":"number"},"type":{"enum":["person","organization","location","date","money","percent","product","event"],"type":"string"},"value":{"type":"string"}},"required":["type","value","confidence"],"type":"object"},"type":"array"},"id":{"type":"string"},"imageIndex":{"type":"number"},"mimeType":{"type":"string"},"pageNumber":{"type":"number"},"signedUrl":{"type":"string"},"source":{"type":"string"},"sourceType":{"enum":["document","web","dataset"],"type":"string"},"summary":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array"},"title":{"type":"string"},"type":{"enum":["text","image"],"type":"string"}},"required":["id","content","type","sourceType","source"],"type":"object"},"ChunksList":{"properties":{"chunks":{"items":{"$ref":"#/components/schemas/Chunk"},"type":"array"},"hasMore":{"type":"boolean"},"limit":{"type":"number"},"offset":{"type":"number"},"total":{"type":"number"}},"required":["chunks","total","offset","limit","hasMore"],"type":"object"},"Collection":{"properties":{"accessPolicy":{"oneOf":[{"additionalProperties":false,"properties":{"mode":{"enum":["inherit"],"type":"string"}},"required":["mode"],"type":"object"},{"additionalProperties":false,"properties":{"mode":{"enum":["restricted"],"type":"string"},"roleIds":{"items":{"maxLength":200,"minLength":1,"type":"string"},"maxItems":100,"minItems":1,"type":"array"}},"required":["mode","roleIds"],"type":"object"},{"nullable":true}]},"accessTier":{"description":"How the caller can access this collection. Public/shared collections may be read-only for consumers.","enum":["owner","shared","public-free","public-gated"],"type":"string"},"createdAt":{"type":"string"},"createdByAdmin":{"default":false,"type":"boolean"},"description":{"nullable":true,"type":"string"},"documentCount":{"type":"number"},"embeddingConfig":{"description":"Embedding model configuration for this collection, null if not yet ingested","nullable":true,"properties":{"dimensions":{"type":"number"},"model":{"type":"string"},"provider":{"type":"string"}},"required":["provider","model","dimensions"],"type":"object"},"hasMultimodalEmbeddings":{"description":"Whether this collection has multimodal embeddings enabled","type":"boolean"},"id":{"type":"string"},"imagesCount":{"description":"Total number of images indexed (multimodal collections only)","type":"number"},"isReadOnly":{"type":"boolean"},"isSystemCollection":{"description":"Whether this is an admin-managed public collection","type":"boolean"},"lastSyncedAt":{"nullable":true,"type":"string"},"name":{"type":"string"},"publisherOrgId":{"description":"Owning organization id when this response represents a shared/public collection consumed by another scope.","nullable":true,"type":"string"},"requiredPlanId":{"description":"Minimum plan ID required to query this public collection (null = free-for-all). Used for pro/scale-gated datasets.","enum":["pro","scale","enterprise",null],"nullable":true,"type":"string"},"servedSource":{"properties":{"activatedAt":{"nullable":true,"type":"string"},"officialCorpusQualified":{"enum":[false],"type":"boolean"},"sourceRevision":{"nullable":true,"type":"string"},"sourceTimestamp":{"nullable":true,"type":"string"},"status":{"enum":["verified_receipt","unknown"],"type":"string"}},"required":["status","officialCorpusQualified","sourceRevision","sourceTimestamp","activatedAt"],"type":"object"},"slug":{"description":"URL-safe identifier for public collections (e.g., 'code-du-travail'). Unique across all public collections.","nullable":true,"type":"string"},"sourceDataset":{"description":"Source identifier for public collections (e.g., 'legifrance', 'insee-sirene')","nullable":true,"type":"string"},"storageBytes":{"type":"number"},"visibility":{"default":"private","enum":["private","shared","public"],"type":"string"}},"required":["id","name","description","documentCount","storageBytes","createdAt"],"type":"object"},"CollectionDocument":{"properties":{"accessPolicy":{"anyOf":[{"properties":{"mode":{"enum":["inherit"],"type":"string"}},"required":["mode"],"type":"object"},{"properties":{"mode":{"enum":["restricted"],"type":"string"},"roleIds":{"items":{"type":"string"},"type":"array"}},"required":["mode","roleIds"],"type":"object"},{"nullable":true}]},"chunksCount":{"type":"number"},"createdAt":{"anyOf":[{"type":"string"},{"format":"date-time","type":"string"}]},"embeddingModel":{"nullable":true,"type":"string"},"filename":{"type":"string"},"hasMultimodalEmbeddings":{"type":"boolean"},"id":{"type":"string"},"imagesCount":{"type":"number"},"ingestionReport":{"$ref":"#/components/schemas/CollectionDocumentIngestionReport"},"processingSummary":{"nullable":true,"properties":{"hasWarnings":{"type":"boolean"},"imagesDetected":{"type":"number"},"imagesIndexed":{"type":"number"},"pageCount":{"type":"number"},"pagesReadByOcr":{"type":"number"},"tablesDetected":{"type":"number"},"unreadablePages":{"type":"number"}},"required":["pagesReadByOcr","unreadablePages","imagesIndexed","imagesDetected","tablesDetected","hasWarnings"],"type":"object"},"sourceType":{"type":"string"},"sourceUrl":{"nullable":true,"type":"string"},"storageBytes":{"type":"number"}},"required":["id","filename","sourceType","sourceUrl","chunksCount","imagesCount","storageBytes","hasMultimodalEmbeddings","embeddingModel","createdAt","ingestionReport"],"type":"object"},"CollectionDocumentIngestionReport":{"nullable":true,"properties":{"chunking":{"properties":{"avgChars":{"type":"number"},"chunksCreated":{"type":"number"},"maxChars":{"type":"number"},"minChars":{"type":"number"},"strategy":{"type":"string"},"strategyExplanation":{"type":"string"},"strategyReason":{"enum":["explicit","auto","default-fallback"],"type":"string"}},"required":["strategy","chunksCreated","avgChars","minChars","maxChars"],"type":"object"},"durations":{"properties":{"chunkMs":{"type":"number"},"embedMs":{"type":"number"},"extractMs":{"type":"number"},"totalMs":{"type":"number"}},"required":["extractMs","chunkMs","embedMs","totalMs"],"type":"object"},"embedding":{"properties":{"model":{"type":"string"},"multimodal":{"type":"boolean"},"provider":{"type":"string"},"vectorDims":{"type":"number"}},"required":["provider","model","multimodal"],"type":"object"},"extraction":{"properties":{"confidence":{"nullable":true,"type":"number"},"engine":{"type":"string"},"fallbackEngines":{"items":{"type":"string"},"type":"array"},"layoutBlocks":{"type":"number"}},"required":["engine"],"type":"object"},"extractionMethod":{"type":"string"},"images":{"properties":{"extracted":{"type":"number"},"indexed":{"type":"number"},"skippedTooLarge":{"type":"number"}},"required":["extracted","indexed","skippedTooLarge"],"type":"object"},"ocr":{"nullable":true,"properties":{"charsExtracted":{"type":"number"},"pagesOcrd":{"type":"number"},"pagesRejected":{"type":"number"}},"required":["pagesOcrd","pagesRejected","charsExtracted"],"type":"object"},"pageCount":{"type":"number"},"tables":{"nullable":true,"properties":{"detected":{"type":"number"},"sheets":{"type":"number"},"totalCols":{"type":"number"},"totalRows":{"type":"number"}},"required":["detected"],"type":"object"},"version":{"enum":[1],"type":"number"},"warnings":{"items":{"type":"string"},"type":"array"}},"required":["version","extractionMethod","ocr","images","tables","chunking","embedding","durations","warnings"],"type":"object"},"CollectionDocumentsError":{"properties":{"error":{"type":"string"}},"required":["error"],"type":"object"},"CollectionDocumentsResponse":{"properties":{"documents":{"items":{"$ref":"#/components/schemas/CollectionDocument"},"type":"array"}},"required":["documents"],"type":"object"},"CollectionInsights":{"properties":{"importantDates":{"type":"string"},"keyFindings":{"type":"string"},"mainTopics":{"type":"string"},"methodology":{"type":"string"}},"required":["mainTopics","keyFindings","methodology","importantDates"],"type":"object"},"CollectionQualityReport":{"additionalProperties":{"nullable":true},"type":"object"},"CollectionStats":{"properties":{"bySourceType":{"items":{"$ref":"#/components/schemas/SourceStat"},"type":"array"},"byType":{"items":{"$ref":"#/components/schemas/TypeStat"},"type":"array"},"topSources":{"items":{"$ref":"#/components/schemas/TopSource"},"type":"array"},"totalChunks":{"type":"number"}},"required":["totalChunks","bySourceType","byType","topSources"],"type":"object"},"CrawlResponse":{"properties":{"chunksCount":{"type":"number"},"embeddingModel":{"type":"string"},"imagesCount":{"type":"number"},"message":{"type":"string"},"multimodalEnabled":{"type":"boolean"},"pagesCount":{"type":"number"},"success":{"type":"boolean"}},"required":["success","message","pagesCount","chunksCount"],"type":"object"},"CrawlSelectedPagesRequest":{"properties":{"chunkingConfiguration":{"additionalProperties":false,"properties":{"includeBreadcrumb":{"default":false,"type":"boolean"},"maxTokens":{"default":512,"maximum":4096,"minimum":64,"type":"integer"},"minTokens":{"default":80,"maximum":1024,"minimum":0,"type":"integer"},"overlapChars":{"maximum":4096,"minimum":0,"type":"integer"},"strategy":{"default":"default","enum":["default","legal-article","regulatory-section","csv-row-grouped","email-thread","markdown-heading"],"type":"string"}},"type":"object"},"collectionId":{"type":"string"},"enableMultimodal":{"description":"Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy.","type":"boolean"},"urls":{"items":{"format":"uri","type":"string"},"minItems":1,"type":"array"}},"required":["collectionId","urls"],"type":"object"},"CrawlSiteRequest":{"properties":{"chunkingConfiguration":{"additionalProperties":false,"properties":{"includeBreadcrumb":{"default":false,"type":"boolean"},"maxTokens":{"default":512,"maximum":4096,"minimum":64,"type":"integer"},"minTokens":{"default":80,"maximum":1024,"minimum":0,"type":"integer"},"overlapChars":{"maximum":4096,"minimum":0,"type":"integer"},"strategy":{"default":"default","enum":["default","legal-article","regulatory-section","csv-row-grouped","email-thread","markdown-heading"],"type":"string"}},"type":"object"},"collectionId":{"example":"coll_123","type":"string"},"enableMultimodal":{"description":"Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy.","example":false,"type":"boolean"},"maxDepth":{"example":3,"minimum":1,"type":"number"},"maxPages":{"example":100,"minimum":1,"type":"number"},"url":{"example":"https://docs.example.com","format":"uri","type":"string"}},"required":["collectionId","url"],"type":"object"},"CreateAgentRequest":{"properties":{"collectionId":{"format":"uuid","nullable":true,"type":"string"},"contextWindowSize":{"default":10,"maximum":50,"minimum":1,"type":"number"},"description":{"example":"Handles customer support queries","maxLength":500,"type":"string"},"enableContextEngineering":{"default":false,"type":"boolean"},"enabledBuiltinTools":{"default":["web_search","current_date","calculator"],"items":{"$ref":"#/components/schemas/BuiltinToolConfig"},"type":"array"},"fallbackLlmConfigId":{"format":"uuid","nullable":true,"type":"string"},"instructions":{"type":"string"},"llmConfigId":{"format":"uuid","nullable":true,"type":"string"},"maxTokens":{"maximum":32000,"minimum":100,"type":"number"},"mcpServers":{"items":{"$ref":"#/components/schemas/McpServer"},"type":"array"},"model":{"type":"string"},"name":{"example":"Support Assistant","maxLength":100,"minLength":1,"type":"string"},"openWebuiEnabled":{"default":false,"type":"boolean"},"resources":{"items":{"properties":{"id":{"format":"uuid","type":"string"},"priority":{"default":0,"maximum":100,"minimum":0,"type":"integer"},"type":{"enum":["collection"],"type":"string"}},"required":["type","id"],"type":"object"},"maxItems":30,"type":"array"},"runtimeConnectionId":{"format":"uuid","nullable":true,"type":"string"},"runtimeKind":{"default":"byok_api","enum":["byok_api"],"type":"string"},"runtimePreferences":{"nullable":true,"properties":{"mode":{"nullable":true,"type":"string"},"model":{"nullable":true,"type":"string"},"reasoningLevel":{"nullable":true,"type":"string"}},"type":"object"},"runtimeProfileId":{"format":"uuid","nullable":true,"type":"string"},"scoreThreshold":{"maximum":100,"minimum":0,"type":"number"},"skillIds":{"default":[],"items":{"format":"uuid","type":"string"},"type":"array"},"subAgentIds":{"items":{"format":"uuid","type":"string"},"type":"array"},"systemPrompt":{"type":"string"},"temperature":{"maximum":200,"minimum":0,"type":"number"},"topK":{"maximum":50,"minimum":1,"type":"number"},"workflowToolIds":{"default":[],"items":{"format":"uuid","type":"string"},"type":"array"}},"required":["name"],"type":"object"},"CreateAgentSkillRequest":{"properties":{"builtinTools":{"default":[],"items":{"$ref":"#/components/schemas/BuiltinToolConfig"},"type":"array"},"constraints":{"nullable":true,"type":"string"},"description":{"maxLength":500,"nullable":true,"type":"string"},"examples":{"default":[],"items":{"$ref":"#/components/schemas/AgentSkillExample"},"type":"array"},"instructions":{"nullable":true,"type":"string"},"mcpServerRefs":{"default":[],"items":{"type":"string"},"type":"array"},"name":{"maxLength":100,"minLength":1,"type":"string"},"status":{"$ref":"#/components/schemas/AgentSkillStatus"},"workflowToolRefs":{"default":[],"items":{"format":"uuid","type":"string"},"type":"array"}},"required":["name"],"type":"object"},"CreateCollectionRequest":{"properties":{"accessPolicy":{"oneOf":[{"additionalProperties":false,"properties":{"mode":{"enum":["inherit"],"type":"string"}},"required":["mode"],"type":"object"},{"additionalProperties":false,"properties":{"mode":{"enum":["restricted"],"type":"string"},"roleIds":{"items":{"maxLength":200,"minLength":1,"type":"string"},"maxItems":100,"minItems":1,"type":"array"}},"required":["mode","roleIds"],"type":"object"}]},"description":{"example":"Product documentation","maxLength":500,"type":"string"},"embeddingConfigId":{"description":"Optional embedding config ID to override the org default. Must reference a valid embedding config owned by this org/user.","type":"string"},"name":{"example":"Documentation","maxLength":100,"minLength":1,"type":"string"},"requiredPlanId":{"description":"Plan ID required to query this public collection (e.g. 'pro', 'scale'). Only admins can set.","enum":["pro","scale","enterprise"],"example":"pro","type":"string"},"slug":{"description":"URL-safe identifier for public collections. Only admins can set. Must be globally unique.","example":"code-du-travail","pattern":"^[a-z0-9][a-z0-9-]{1,63}$","type":"string"},"sourceDataset":{"description":"Source identifier for public collections. Only used for system collections.","example":"legifrance","maxLength":100,"type":"string"},"visibility":{"default":"private","description":"Must be omitted or 'private'. Public or shared create is rejected; publish with PATCH /api/collections/:id/visibility.","enum":["private","shared","public"],"example":"private","type":"string"}},"required":["name"],"type":"object"},"CreateEvaluationRequest":{"properties":{"goldenSet":{"items":{"properties":{"category":{"pattern":"^[a-z0-9][a-z0-9_-]{0,49}$","type":"string"},"expectedAnswer":{"type":"string"},"expectedBehavior":{"enum":["answer","abstain","clarify"],"type":"string"},"expectedKeywords":{"items":{"type":"string"},"type":"array"},"expectedSourceUrls":{"items":{"format":"uri","type":"string"},"type":"array"},"id":{"pattern":"^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$","type":"string"},"locale":{"pattern":"^[a-z]{2}(?:-[A-Z]{2})?$","type":"string"},"query":{"maxLength":500,"minLength":1,"type":"string"},"reviewStatus":{"enum":["pending_human_review","approved"],"type":"string"}},"required":["query"],"type":"object"},"maxItems":50,"minItems":1,"type":"array"},"inheritFromEvaluationId":{"minLength":1,"type":"string"},"notifyEmail":{"format":"email","type":"string"},"numQuestions":{"maximum":30,"minimum":1,"type":"integer"},"ragConfigOverride":{"additionalProperties":{"nullable":true},"description":"Optional licensed-mode pipeline override; managed SaaS requests must omit it.","type":"object"}},"type":"object"},"CreateWorkflowRequest":{"properties":{"defaultCollectionId":{"type":"string"},"description":{"maxLength":500,"type":"string"},"graph":{"properties":{"edges":{"items":{"properties":{"animated":{"type":"boolean"},"data":{"additionalProperties":{"nullable":true},"type":"object"},"id":{"type":"string"},"label":{"type":"string"},"source":{"type":"string"},"sourceHandle":{"type":"string"},"target":{"type":"string"},"targetHandle":{"type":"string"},"type":{"type":"string"}},"required":["id","source","target"],"type":"object"},"type":"array"},"nodes":{"items":{"properties":{"data":{"properties":{"config":{"additionalProperties":{"nullable":true},"type":"object"},"label":{"type":"string"}},"required":["label","config"],"type":"object"},"height":{"type":"number"},"id":{"type":"string"},"position":{"properties":{"x":{"type":"number"},"y":{"type":"number"}},"required":["x","y"],"type":"object"},"type":{"type":"string"},"width":{"type":"number"}},"required":["id","type","position","data"],"type":"object"},"type":"array"},"viewport":{"properties":{"x":{"type":"number"},"y":{"type":"number"},"zoom":{"type":"number"}},"required":["x","y","zoom"],"type":"object"}},"required":["nodes","edges"],"type":"object"},"isActive":{"type":"boolean"},"name":{"maxLength":100,"minLength":1,"type":"string"},"variables":{"items":{"properties":{"defaultValue":{"nullable":true},"description":{"type":"string"},"name":{"type":"string"},"required":{"type":"boolean"},"type":{"enum":["string","number","boolean","object","array","any","message","messages","documents","embedding"],"type":"string"}},"required":["name","type"],"type":"object"},"type":"array"}},"required":["name"],"type":"object"},"CreatedEvaluation":{"properties":{"collectionId":{"type":"string"},"createdAt":{"anyOf":[{"type":"string"},{"format":"date-time","type":"string"}]},"error":{"nullable":true,"type":"string"},"id":{"type":"string"},"notifyEmail":{"nullable":true,"type":"string"},"numQuestions":{"type":"number"},"parentEvaluationId":{"nullable":true,"type":"string"},"status":{"type":"string"}},"required":["id","collectionId","status","error","numQuestions","notifyEmail","parentEvaluationId","createdAt"],"type":"object"},"DiscoverResponse":{"properties":{"duration":{"type":"number"},"pages":{"items":{"$ref":"#/components/schemas/DiscoveredPage"},"type":"array"},"success":{"type":"boolean"},"totalFound":{"type":"number"}},"required":["success","pages","totalFound","duration"],"type":"object"},"DiscoverSiteRequest":{"properties":{"excludePatterns":{"items":{"type":"string"},"type":"array"},"includePatterns":{"items":{"type":"string"},"type":"array"},"maxDepth":{"minimum":1,"type":"number"},"maxPages":{"minimum":1,"type":"number"},"url":{"format":"uri","type":"string"}},"required":["url"],"type":"object"},"DiscoveredPage":{"properties":{"depth":{"type":"number"},"path":{"type":"string"},"title":{"nullable":true,"type":"string"},"url":{"type":"string"}},"required":["url","title","depth","path"],"type":"object"},"Error":{"properties":{"accessTier":{"enum":["owner","shared","public-free","public-gated"],"type":"string"},"code":{"type":"string"},"collectionId":{"type":"string"},"details":{"additionalProperties":{"nullable":true},"type":"object"},"error":{"type":"string"},"publisherOrgId":{"nullable":true,"type":"string"},"requiredPlanId":{"enum":["pro","scale","enterprise",null],"nullable":true,"type":"string"},"status":{"type":"number"}},"required":["error"],"type":"object"},"ErrorResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"success":{"type":"boolean"}},"required":["success","error"],"type":"object"},"EvaluationConflict":{"properties":{"error":{"type":"string"},"evaluationId":{"type":"string"},"status":{"type":"string"}},"required":["error","evaluationId","status"],"type":"object"},"EvaluationDetail":{"properties":{"collectionId":{"type":"string"},"completedAt":{"anyOf":[{"type":"string"},{"format":"date-time","type":"string"},{"nullable":true}]},"createdAt":{"anyOf":[{"type":"string"},{"format":"date-time","type":"string"}]},"error":{"nullable":true,"type":"string"},"id":{"type":"string"},"numQuestions":{"type":"number"},"parentEvaluationId":{"nullable":true,"type":"string"},"progress":{"nullable":true,"properties":{"current":{"type":"number"},"phase":{"enum":["generating","running","judging"],"type":"string"},"total":{"type":"number"}},"required":["phase","current","total"],"type":"object"},"result":{"nullable":true},"startedAt":{"anyOf":[{"type":"string"},{"format":"date-time","type":"string"},{"nullable":true}]},"status":{"type":"string"}},"required":["id","collectionId","status","numQuestions","progress","error","startedAt","completedAt","createdAt","parentEvaluationId"],"type":"object"},"EvaluationDetailError":{"properties":{"error":{"type":"string"}},"required":["error"],"type":"object"},"EvaluationError":{"properties":{"error":{"type":"string"}},"required":["error"],"type":"object"},"EvaluationSummary":{"properties":{"avgJudgeOverall":{"nullable":true,"type":"number"},"completedAt":{"anyOf":[{"type":"string"},{"format":"date-time","type":"string"},{"nullable":true}]},"createdAt":{"anyOf":[{"type":"string"},{"format":"date-time","type":"string"}]},"error":{"nullable":true,"type":"string"},"id":{"type":"string"},"numQuestions":{"type":"number"},"parentEvaluationId":{"nullable":true,"type":"string"},"progress":{"nullable":true},"ragConfigOverride":{"nullable":true},"retrievalHitRate":{"nullable":true,"type":"number"},"score":{"nullable":true,"type":"number"},"startedAt":{"anyOf":[{"type":"string"},{"format":"date-time","type":"string"},{"nullable":true}]},"status":{"type":"string"}},"required":["id","status","numQuestions","error","startedAt","completedAt","createdAt","parentEvaluationId","score","retrievalHitRate","avgJudgeOverall"],"type":"object"},"ExecuteRequest":{"properties":{"input":{"additionalProperties":{"nullable":true},"type":"object"},"maximumMilliCredits":{"pattern":"^[1-9][0-9]{0,15}$","type":"string"},"requestId":{"format":"uuid","type":"string"}},"type":"object"},"Execution":{"properties":{"completedAt":{"nullable":true,"type":"string"},"createdAt":{"type":"string"},"error":{"nullable":true,"type":"string"},"id":{"type":"string"},"input":{"nullable":true},"nodeStates":{"additionalProperties":{"nullable":true},"nullable":true,"type":"object"},"output":{"nullable":true},"startedAt":{"nullable":true,"type":"string"},"status":{"enum":["pending","running","pending_approval","completed","failed","cancelled"],"type":"string"},"triggeredBy":{"nullable":true,"type":"string"},"workflowId":{"type":"string"}},"required":["id","workflowId","status","nodeStates","startedAt","completedAt","error","triggeredBy","createdAt"],"type":"object"},"ExecutionResult":{"properties":{"error":{"type":"string"},"executionId":{"type":"string"},"output":{"nullable":true},"status":{"enum":["pending","running","pending_approval","completed","failed","cancelled"],"type":"string"}},"required":["executionId","status"],"type":"object"},"FaithfulnessConfigSchema":{"properties":{"enabled":{"type":"boolean"},"minSupport":{"maximum":1,"minimum":0,"type":"number"},"policy":{"enum":["report","qualify","remove","abstain"],"type":"string"}},"type":"object"},"FeedbackError":{"properties":{"error":{"type":"string"}},"required":["error"],"type":"object"},"FeedbackRequest":{"properties":{"message":{"description":"Feedback message content","example":"The chat feature crashes when I send a long message.","maxLength":2000,"minLength":10,"type":"string"},"type":{"description":"Type of feedback","enum":["bug","feature","other"],"example":"bug","type":"string"}},"required":["type","message"],"type":"object"},"FeedbackSuccess":{"properties":{"message":{"type":"string"},"success":{"type":"boolean"}},"required":["success","message"],"type":"object"},"FilterDefinition":{"properties":{"field":{"type":"string"},"operator":{"enum":["eq","neq","contains","gt","gte","lt","lte","in","nin","between","exists"],"type":"string"},"value":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"items":{"anyOf":[{"type":"string"},{"type":"number"}]},"type":"array"},{"properties":{"from":{"type":"number"},"to":{"type":"number"}},"required":["from","to"],"type":"object"}]}},"required":["field","operator","value"],"type":"object"},"GenerateAgentRequest":{"additionalProperties":false,"properties":{"collectionId":{"description":"Optional collection ID for RAG capabilities","maxLength":255,"minLength":1,"nullable":true,"type":"string"},"description":{"example":"I need an assistant that helps customers with technical support for a SaaS product. It should be friendly, professional, and know how to troubleshoot common issues.","maxLength":2000,"minLength":10,"type":"string"},"language":{"default":"en","description":"Target language (en, fr, es, etc.)","example":"en","type":"string"},"requestId":{"format":"uuid","type":"string"}},"required":["description"],"type":"object"},"GeneratedAgentConfig":{"allOf":[{"$ref":"#/components/schemas/GeneratedBusinessAgentConfig"},{"properties":{"maxTokens":{"type":"number"},"model":{"type":"string"},"scoreThreshold":{"type":"number"},"temperature":{"type":"number"},"topK":{"type":"number"}},"required":["model","temperature","maxTokens","topK","scoreThreshold"],"type":"object"}]},"GeneratedBusinessAgentConfig":{"properties":{"description":{"nullable":true,"type":"string"},"instructions":{"nullable":true,"type":"string"},"name":{"type":"string"},"suggestedTools":{"items":{"properties":{"description":{"type":"string"},"name":{"type":"string"}},"required":["name","description"],"type":"object"},"type":"array"},"systemPrompt":{"type":"string"}},"required":["name","description","systemPrompt","instructions"],"type":"object"},"HybridSearchConfig":{"properties":{"alpha":{"maximum":1,"minimum":0,"type":"number"},"bm25":{"properties":{"b":{"maximum":1,"minimum":0,"type":"number"},"k1":{"exclusiveMinimum":true,"minimum":0,"type":"number"}},"type":"object"},"rrf":{"properties":{"k":{"exclusiveMinimum":true,"minimum":0,"type":"number"}},"type":"object"}},"type":"object"},"ImageResult":{"properties":{"imageIndex":{"type":"number"},"mimeType":{"type":"string"},"pageNumber":{"type":"number"},"score":{"type":"number"},"signedUrl":{"type":"string"},"source":{"type":"string"}},"required":["source","score"],"type":"object"},"IngestDatasetRequest":{"properties":{"chunkingConfiguration":{"additionalProperties":false,"properties":{"includeBreadcrumb":{"default":false,"type":"boolean"},"maxTokens":{"default":512,"maximum":4096,"minimum":64,"type":"integer"},"minTokens":{"default":80,"maximum":1024,"minimum":0,"type":"integer"},"overlapChars":{"maximum":4096,"minimum":0,"type":"integer"},"strategy":{"default":"default","enum":["default","legal-article","regulatory-section","csv-row-grouped","email-thread","markdown-heading"],"type":"string"}},"type":"object"},"collectionId":{"example":"coll_123","type":"string"},"config":{"description":"Dataset config/subset name","example":"default","type":"string"},"datasetId":{"description":"Hugging Face dataset ID (e.g., 'squad', 'username/dataset')","example":"squad","type":"string"},"enableMultimodal":{"description":"Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy. Extracts and indexes images from image columns.","example":false,"type":"boolean"},"limit":{"description":"Maximum number of rows to ingest (max 1M)","example":10000,"maximum":1000000,"minimum":1,"type":"number"},"split":{"description":"Dataset split (train, test, validation)","example":"train","type":"string"}},"required":["collectionId","datasetId"],"type":"object"},"IngestDocumentRequest":{"properties":{"chunkingConfiguration":{"additionalProperties":false,"properties":{"includeBreadcrumb":{"default":false,"type":"boolean"},"maxTokens":{"default":512,"maximum":4096,"minimum":64,"type":"integer"},"minTokens":{"default":80,"maximum":1024,"minimum":0,"type":"integer"},"overlapChars":{"maximum":4096,"minimum":0,"type":"integer"},"strategy":{"default":"default","enum":["default","legal-article","regulatory-section","csv-row-grouped","email-thread","markdown-heading"],"type":"string"}},"type":"object"},"collectionId":{"example":"coll_123","type":"string"},"content":{"example":"Document content here...","minLength":1,"type":"string"},"filename":{"example":"manual.txt","minLength":1,"type":"string"}},"required":["collectionId","content","filename"],"type":"object"},"IngestResponse":{"properties":{"chunksCount":{"type":"number"},"documentId":{"type":"string"},"embeddingModel":{"type":"string"},"imagesCount":{"type":"number"},"message":{"type":"string"},"multimodalEnabled":{"type":"boolean"},"success":{"type":"boolean"}},"required":["success","message","chunksCount"],"type":"object"},"IngestUrlRequest":{"properties":{"chunkingConfiguration":{"additionalProperties":false,"properties":{"includeBreadcrumb":{"default":false,"type":"boolean"},"maxTokens":{"default":512,"maximum":4096,"minimum":64,"type":"integer"},"minTokens":{"default":80,"maximum":1024,"minimum":0,"type":"integer"},"overlapChars":{"maximum":4096,"minimum":0,"type":"integer"},"strategy":{"default":"default","enum":["default","legal-article","regulatory-section","csv-row-grouped","email-thread","markdown-heading"],"type":"string"}},"type":"object"},"collectionId":{"example":"coll_123","type":"string"},"enableMultimodal":{"description":"Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy.","example":false,"type":"boolean"},"url":{"example":"https://example.com/page","format":"uri","type":"string"}},"required":["collectionId","url"],"type":"object"},"LLMConfigSchema":{"properties":{"citationFormat":{"enum":["brackets","footnote","inline"],"type":"string"}},"type":"object"},"McpServer":{"properties":{"description":{"type":"string"},"name":{"type":"string"},"token":{"type":"string"},"toolPolicies":{"additionalProperties":{"properties":{"humanInTheLoop":{"type":"boolean"}},"type":"object"},"type":"object"},"url":{"format":"uri","type":"string"}},"required":["name","url"],"type":"object"},"Message":{"properties":{"content":{"type":"string"},"role":{"enum":["user","assistant"],"type":"string"}},"required":["role","content"],"type":"object"},"PipelineMetrics":{"properties":{"bm25IndexSize":{"type":"number"},"queryEnhancementMs":{"type":"number"},"rerankMs":{"type":"number"},"resultsCount":{"type":"number"},"searchMs":{"type":"number"},"totalTimeMs":{"type":"number"}},"required":["totalTimeMs","queryEnhancementMs","searchMs","rerankMs","resultsCount"],"type":"object"},"PromptAttachment":{"properties":{"arguments":{"additionalProperties":{"type":"string"},"type":"object"},"name":{"type":"string"},"server":{"type":"string"}},"required":["server","name"],"type":"object"},"PublicCollectionDetail":{"allOf":[{"$ref":"#/components/schemas/PublicCollectionSummary"},{"properties":{"sampleQueries":{"items":{"type":"string"},"type":"array"},"tags":{"items":{"type":"string"},"type":"array"}},"required":["tags","sampleQueries"],"type":"object"}]},"PublicCollectionError":{"properties":{"code":{"type":"string"},"error":{"type":"string"}},"required":["error","code"],"type":"object"},"PublicCollectionPublisher":{"properties":{"isSystem":{"type":"boolean"},"name":{"type":"string"}},"required":["name","isSystem"],"type":"object"},"PublicCollectionSummary":{"properties":{"accessible":{"type":"boolean"},"description":{"nullable":true,"type":"string"},"documentCount":{"minimum":0,"type":"integer"},"id":{"type":"string"},"lastSyncedAt":{"format":"date-time","nullable":true,"type":"string"},"name":{"type":"string"},"publisher":{"$ref":"#/components/schemas/PublicCollectionPublisher"},"requiredPlanId":{"enum":["pro","scale","enterprise",null],"nullable":true,"type":"string"},"servedSource":{"properties":{"activatedAt":{"nullable":true,"type":"string"},"officialCorpusQualified":{"enum":[false],"type":"boolean"},"sourceRevision":{"nullable":true,"type":"string"},"sourceTimestamp":{"nullable":true,"type":"string"},"status":{"enum":["verified_receipt","unknown"],"type":"string"}},"required":["status","officialCorpusQualified","sourceRevision","sourceTimestamp","activatedAt"],"type":"object"},"slug":{"type":"string"},"sourceDataset":{"nullable":true,"type":"string"},"updatedAt":{"format":"date-time","type":"string"}},"required":["id","slug","name","description","publisher","requiredPlanId","accessible","documentCount","updatedAt","sourceDataset","lastSyncedAt"],"type":"object"},"RAGCacheConfigSchema":{"properties":{"enabled":{"type":"boolean"},"maxSize":{"maximum":10000,"minimum":1,"type":"integer"},"ttlSeconds":{"maximum":86400,"minimum":1,"type":"integer"}},"type":"object"},"RAGConfigErrorResponse":{"properties":{"error":{"type":"string"}},"required":["error"],"type":"object"},"RAGConfigInput":{"properties":{"cache":{"$ref":"#/components/schemas/RAGCacheConfigSchema"},"faithfulness":{"$ref":"#/components/schemas/FaithfulnessConfigSchema"},"features":{"$ref":"#/components/schemas/RAGFeatures"},"hybridSearch":{"$ref":"#/components/schemas/HybridSearchConfig"},"llm":{"$ref":"#/components/schemas/LLMConfigSchema"},"reranking":{"$ref":"#/components/schemas/RerankingConfig"},"retrieval":{"$ref":"#/components/schemas/RetrievalConfig"}},"type":"object"},"RAGConfigResponse":{"properties":{"cache":{"properties":{"enabled":{"type":"boolean"},"maxSize":{"type":"integer"},"ttlSeconds":{"type":"integer"}},"required":["enabled","ttlSeconds","maxSize"],"type":"object"},"faithfulness":{"properties":{"enabled":{"type":"boolean"},"minSupport":{"maximum":1,"minimum":0,"type":"number"},"policy":{"enum":["report","qualify","remove","abstain"],"type":"string"}},"required":["enabled","policy","minSupport"],"type":"object"},"features":{"properties":{"citations":{"type":"boolean"},"contextualRetrieval":{"type":"boolean"},"dynamicFeatureSelection":{"type":"boolean"},"hybridSearch":{"type":"boolean"},"hyde":{"type":"boolean"},"multiQuery":{"type":"boolean"},"parallelEnhancement":{"type":"boolean"},"queryExpansion":{"type":"boolean"},"queryRewriting":{"type":"boolean"},"reranking":{"type":"boolean"},"selfQuery":{"type":"boolean"}},"required":["hybridSearch","selfQuery","queryRewriting","queryExpansion","hyde","multiQuery","reranking","contextualRetrieval","citations","parallelEnhancement","dynamicFeatureSelection"],"type":"object"},"hybridSearch":{"properties":{"alpha":{"type":"number"},"bm25":{"properties":{"b":{"type":"number"},"k1":{"type":"number"}},"required":["k1","b"],"type":"object"},"rrf":{"properties":{"k":{"type":"number"}},"required":["k"],"type":"object"}},"required":["alpha","bm25","rrf"],"type":"object"},"llm":{"properties":{"citationFormat":{"enum":["brackets","footnote","inline"],"type":"string"}},"required":["citationFormat"],"type":"object"},"reranking":{"properties":{"provider":{"enum":["jina","llm"],"type":"string"},"topN":{"type":"number"}},"required":["provider","topN"],"type":"object"},"retrieval":{"properties":{"topK":{"type":"number"}},"required":["topK"],"type":"object"},"version":{"enum":[1],"type":"number"}},"required":["version","features","hybridSearch","reranking","retrieval","llm","faithfulness","cache"],"type":"object"},"RAGFeatures":{"properties":{"citations":{"type":"boolean"},"contextualRetrieval":{"type":"boolean"},"dynamicFeatureSelection":{"type":"boolean"},"hybridSearch":{"type":"boolean"},"hyde":{"type":"boolean"},"multiQuery":{"type":"boolean"},"parallelEnhancement":{"type":"boolean"},"queryExpansion":{"type":"boolean"},"queryRewriting":{"type":"boolean"},"reranking":{"type":"boolean"},"selfQuery":{"type":"boolean"}},"type":"object"},"RerankingConfig":{"properties":{"provider":{"enum":["jina","llm"],"type":"string"},"topN":{"exclusiveMinimum":true,"minimum":0,"type":"number"}},"type":"object"},"ResourceAttachment":{"properties":{"server":{"type":"string"},"uri":{"type":"string"}},"required":["server","uri"],"type":"object"},"RetrievalConfig":{"properties":{"topK":{"exclusiveMinimum":true,"minimum":0,"type":"number"}},"type":"object"},"SearchResult":{"properties":{"blobPath":{"type":"string"},"chunkIndex":{"type":"number"},"content":{"type":"string"},"createdAt":{"type":"string"},"documentId":{"type":"string"},"entities":{"items":{"properties":{"confidence":{"maximum":1,"minimum":0,"type":"number"},"type":{"enum":["person","organization","location","date","money","percent","product","event"],"type":"string"},"value":{"type":"string"}},"required":["type","value","confidence"],"type":"object"},"type":"array"},"id":{"type":"string"},"imageIndex":{"type":"number"},"mimeType":{"type":"string"},"pageNumber":{"type":"number"},"score":{"type":"number"},"signedUrl":{"type":"string"},"source":{"type":"string"},"sourceType":{"enum":["document","web","dataset"],"type":"string"},"summary":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array"},"title":{"type":"string"},"type":{"enum":["text","image"],"type":"string"}},"required":["id","content","score","type","sourceType","source"],"type":"object"},"SearchResults":{"properties":{"query":{"type":"string"},"results":{"items":{"$ref":"#/components/schemas/SearchResult"},"type":"array"}},"required":["results","query"],"type":"object"},"Source":{"properties":{"content":{"type":"string"},"documentUrl":{"type":"string"},"imageIndex":{"type":"number"},"mimeType":{"type":"string"},"pageNumber":{"type":"number"},"score":{"type":"number"},"signedUrl":{"type":"string"},"source":{"type":"string"},"sourceType":{"type":"string"},"title":{"type":"string"},"type":{"enum":["text","image"],"type":"string"},"url":{"type":"string"}},"required":["type","score","source","sourceType"],"type":"object"},"SourceStat":{"properties":{"count":{"type":"number"},"sourceType":{"type":"string"}},"required":["sourceType","count"],"type":"object"},"StreamingCrawlRequest":{"properties":{"chunkingConfiguration":{"additionalProperties":false,"properties":{"includeBreadcrumb":{"default":false,"type":"boolean"},"maxTokens":{"default":512,"maximum":4096,"minimum":64,"type":"integer"},"minTokens":{"default":80,"maximum":1024,"minimum":0,"type":"integer"},"overlapChars":{"maximum":4096,"minimum":0,"type":"integer"},"strategy":{"default":"default","enum":["default","legal-article","regulatory-section","csv-row-grouped","email-thread","markdown-heading"],"type":"string"}},"type":"object"},"collectionId":{"type":"string"},"enableMultimodal":{"description":"Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy.","type":"boolean"},"maxDepth":{"minimum":1,"type":"number"},"maxPages":{"minimum":1,"type":"number"},"url":{"format":"uri","type":"string"}},"required":["collectionId","url"],"type":"object"},"StreamingDatasetRequest":{"properties":{"chunkingConfiguration":{"additionalProperties":false,"properties":{"includeBreadcrumb":{"default":false,"type":"boolean"},"maxTokens":{"default":512,"maximum":4096,"minimum":64,"type":"integer"},"minTokens":{"default":80,"maximum":1024,"minimum":0,"type":"integer"},"overlapChars":{"maximum":4096,"minimum":0,"type":"integer"},"strategy":{"default":"default","enum":["default","legal-article","regulatory-section","csv-row-grouped","email-thread","markdown-heading"],"type":"string"}},"type":"object"},"collectionId":{"type":"string"},"config":{"type":"string"},"datasetId":{"type":"string"},"limit":{"maximum":1000000,"minimum":1,"type":"number"},"split":{"type":"string"}},"required":["collectionId","datasetId"],"type":"object"},"StreamingErrorResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"success":{"type":"boolean"}},"required":["success","error"],"type":"object"},"StreamingIngestResponse":{"properties":{"jobId":{"type":"string"},"message":{"type":"string"},"success":{"type":"boolean"}},"required":["success","jobId","message"],"type":"object"},"TopSource":{"properties":{"count":{"type":"number"},"source":{"type":"string"},"title":{"type":"string"}},"required":["source","count"],"type":"object"},"TypeStat":{"properties":{"count":{"type":"number"},"type":{"type":"string"}},"required":["type","count"],"type":"object"},"UpdateAgentRequest":{"properties":{"collectionId":{"format":"uuid","nullable":true,"type":"string"},"contextWindowSize":{"maximum":50,"minimum":1,"type":"number"},"description":{"maxLength":500,"nullable":true,"type":"string"},"enableContextEngineering":{"type":"boolean"},"enabledBuiltinTools":{"items":{"$ref":"#/components/schemas/BuiltinToolConfig"},"nullable":true,"type":"array"},"fallbackLlmConfigId":{"format":"uuid","nullable":true,"type":"string"},"instructions":{"nullable":true,"type":"string"},"isActive":{"type":"boolean"},"llmConfigId":{"format":"uuid","nullable":true,"type":"string"},"maxTokens":{"maximum":32000,"minimum":100,"type":"number"},"mcpServers":{"items":{"$ref":"#/components/schemas/McpServer"},"nullable":true,"type":"array"},"model":{"type":"string"},"name":{"maxLength":100,"minLength":1,"type":"string"},"openWebuiEnabled":{"type":"boolean"},"resources":{"items":{"properties":{"id":{"format":"uuid","type":"string"},"priority":{"default":0,"maximum":100,"minimum":0,"type":"integer"},"type":{"enum":["collection"],"type":"string"}},"required":["type","id"],"type":"object"},"maxItems":30,"type":"array"},"runtimeConnectionId":{"format":"uuid","nullable":true,"type":"string"},"runtimeKind":{"enum":["byok_api"],"type":"string"},"runtimePreferences":{"nullable":true,"properties":{"mode":{"nullable":true,"type":"string"},"model":{"nullable":true,"type":"string"},"reasoningLevel":{"nullable":true,"type":"string"}},"type":"object"},"runtimeProfileId":{"format":"uuid","nullable":true,"type":"string"},"scoreThreshold":{"maximum":100,"minimum":0,"type":"number"},"skillIds":{"items":{"format":"uuid","type":"string"},"type":"array"},"subAgentIds":{"items":{"format":"uuid","type":"string"},"nullable":true,"type":"array"},"systemPrompt":{"nullable":true,"type":"string"},"temperature":{"maximum":200,"minimum":0,"type":"number"},"topK":{"maximum":50,"minimum":1,"type":"number"},"workflowToolIds":{"items":{"format":"uuid","type":"string"},"type":"array"}},"type":"object"},"UpdateAgentSkillRequest":{"properties":{"builtinTools":{"default":[],"items":{"$ref":"#/components/schemas/BuiltinToolConfig"},"type":"array"},"constraints":{"nullable":true,"type":"string"},"description":{"maxLength":500,"nullable":true,"type":"string"},"examples":{"default":[],"items":{"$ref":"#/components/schemas/AgentSkillExample"},"type":"array"},"instructions":{"nullable":true,"type":"string"},"mcpServerRefs":{"default":[],"items":{"type":"string"},"type":"array"},"name":{"maxLength":100,"minLength":1,"type":"string"},"status":{"$ref":"#/components/schemas/AgentSkillStatus"},"workflowToolRefs":{"default":[],"items":{"format":"uuid","type":"string"},"type":"array"}},"type":"object"},"UpdateCollectionRequest":{"properties":{"defaultChunkingStrategy":{"enum":["default","markdown-heading","legal-article","regulatory-section","csv-row-grouped","email-thread","semantic",null],"nullable":true,"type":"string"},"description":{"maxLength":500,"type":"string"},"name":{"maxLength":100,"minLength":1,"type":"string"}},"type":"object"},"UpdateWorkflowRequest":{"properties":{"defaultCollectionId":{"nullable":true,"type":"string"},"description":{"maxLength":500,"type":"string"},"graph":{"properties":{"edges":{"items":{"properties":{"animated":{"type":"boolean"},"data":{"additionalProperties":{"nullable":true},"type":"object"},"id":{"type":"string"},"label":{"type":"string"},"source":{"type":"string"},"sourceHandle":{"type":"string"},"target":{"type":"string"},"targetHandle":{"type":"string"},"type":{"type":"string"}},"required":["id","source","target"],"type":"object"},"type":"array"},"nodes":{"items":{"properties":{"data":{"properties":{"config":{"additionalProperties":{"nullable":true},"type":"object"},"label":{"type":"string"}},"required":["label","config"],"type":"object"},"height":{"type":"number"},"id":{"type":"string"},"position":{"properties":{"x":{"type":"number"},"y":{"type":"number"}},"required":["x","y"],"type":"object"},"type":{"type":"string"},"width":{"type":"number"}},"required":["id","type","position","data"],"type":"object"},"type":"array"},"viewport":{"properties":{"x":{"type":"number"},"y":{"type":"number"},"zoom":{"type":"number"}},"required":["x","y","zoom"],"type":"object"}},"required":["nodes","edges"],"type":"object"},"isActive":{"type":"boolean"},"name":{"maxLength":100,"minLength":1,"type":"string"},"variables":{"items":{"properties":{"defaultValue":{"nullable":true},"description":{"type":"string"},"name":{"type":"string"},"required":{"type":"boolean"},"type":{"enum":["string","number","boolean","object","array","any","message","messages","documents","embedding"],"type":"string"}},"required":["name","type"],"type":"object"},"type":"array"}},"type":"object"},"ValidationResult":{"properties":{"errors":{"items":{"properties":{"edgeId":{"type":"string"},"label":{"type":"string"},"message":{"type":"string"},"nodeId":{"type":"string"},"type":{"type":"string"}},"required":["type","message"],"type":"object"},"type":"array"},"valid":{"type":"boolean"},"warnings":{"items":{"properties":{"message":{"type":"string"},"nodeId":{"type":"string"},"type":{"type":"string"}},"required":["type","message"],"type":"object"},"type":"array"}},"required":["valid","errors","warnings"],"type":"object"},"Workflow":{"properties":{"createdAt":{"type":"string"},"defaultCollectionId":{"nullable":true,"type":"string"},"description":{"nullable":true,"type":"string"},"graph":{"properties":{"edges":{"items":{"properties":{"animated":{"type":"boolean"},"data":{"additionalProperties":{"nullable":true},"type":"object"},"id":{"type":"string"},"label":{"type":"string"},"source":{"type":"string"},"sourceHandle":{"type":"string"},"target":{"type":"string"},"targetHandle":{"type":"string"},"type":{"type":"string"}},"required":["id","source","target"],"type":"object"},"type":"array"},"nodes":{"items":{"properties":{"data":{"properties":{"config":{"additionalProperties":{"nullable":true},"type":"object"},"label":{"type":"string"}},"required":["label","config"],"type":"object"},"height":{"type":"number"},"id":{"type":"string"},"position":{"properties":{"x":{"type":"number"},"y":{"type":"number"}},"required":["x","y"],"type":"object"},"type":{"type":"string"},"width":{"type":"number"}},"required":["id","type","position","data"],"type":"object"},"type":"array"},"viewport":{"properties":{"x":{"type":"number"},"y":{"type":"number"},"zoom":{"type":"number"}},"required":["x","y","zoom"],"type":"object"}},"required":["nodes","edges"],"type":"object"},"id":{"type":"string"},"isActive":{"type":"boolean"},"name":{"type":"string"},"updatedAt":{"type":"string"},"variables":{"items":{"properties":{"defaultValue":{"nullable":true},"description":{"type":"string"},"name":{"type":"string"},"required":{"type":"boolean"},"type":{"enum":["string","number","boolean","object","array","any","message","messages","documents","embedding"],"type":"string"}},"required":["name","type"],"type":"object"},"nullable":true,"type":"array"}},"required":["id","name","description","graph","variables","isActive","defaultCollectionId","createdAt","updatedAt"],"type":"object"},"WorkflowListItem":{"properties":{"createdAt":{"type":"string"},"description":{"nullable":true,"type":"string"},"id":{"type":"string"},"isActive":{"type":"boolean"},"lastExecutedAt":{"nullable":true,"type":"string"},"lastExecutionStatus":{"nullable":true,"type":"string"},"name":{"type":"string"},"nodeCount":{"type":"number"},"updatedAt":{"type":"string"}},"required":["id","name","description","isActive","nodeCount","lastExecutionStatus","lastExecutedAt","createdAt","updatedAt"],"type":"object"}},"securitySchemes":{"Bearer":{"bearerFormat":"JWT","description":"Local self-hosted session token or ign_* API key","scheme":"bearer","type":"http"}}},"info":{"title":"IgnitionRAG Public SDK API","version":"2026.11"},"openapi":"3.1.0","paths":{"/api/agents":{"get":{"description":"Returns all agents for the current organization","operationId":"agents.list","responses":{"200":{"content":{"application/json":{"schema":{"items":{"$ref":"#/components/schemas/Agent"},"type":"array"}}},"description":"List of agents"}},"summary":"List all agents","tags":["Agents"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"post":{"description":"Creates a new agent. Optionally link to a collection for RAG capabilities.","operationId":"agents.create","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateAgentRequest"}}}},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Agent"}}},"description":"Agent created"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Invalid request or collection not found"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Agent limit exceeded"}},"summary":"Create a new agent","tags":["Agents"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/agents/:agentId/chat/cancel-deep":{"post":{"operationId":"deepResearch.cancel","parameters":[{"in":"path","name":"agentId","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"description":"Cancelled"},"404":{"description":"No active deep research found"}},"summary":"Cancel active deep research for an agent","tags":["Agents","Deep Agent"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"deep_research","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/agents/:agentId/chat/deep-status":{"get":{"operationId":"deepResearch.status","parameters":[{"in":"path","name":"agentId","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"description":"Execution status"},"204":{"description":"No execution found"}},"summary":"Get active or most recent deep research execution for reconnection","tags":["Agents","Deep Agent"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"deep_research","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/agents/:agentId/chat/deep-stream":{"get":{"operationId":"deepResearch.stream","parameters":[{"in":"path","name":"agentId","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"description":"SSE stream"},"404":{"description":"No running execution"}},"summary":"Reconnect to running deep research SSE stream","tags":["Agents","Deep Agent"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"deep_research","x-ignition-protocol":"agent_sse","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/agents/:id":{"delete":{"description":"Permanently deletes an agent and cascades related rows where configured.","operationId":"agents.delete","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"permanent":{"type":"boolean"},"success":{"type":"boolean"}},"required":["success","permanent"],"type":"object"}}},"description":"Agent deleted"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Agent not found"}},"summary":"Delete agent","tags":["Agents"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"get":{"operationId":"agents.get","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Agent"}}},"description":"Agent details"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Agent not found"}},"summary":"Get agent by ID","tags":["Agents"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"patch":{"operationId":"agents.update","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateAgentRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Agent"}}},"description":"Agent updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Invalid request or collection not found"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Agent not found"}},"summary":"Update agent","tags":["Agents"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/agents/:id/chat/stream":{"post":{"description":"Stream a chat response from the agent. Supports context engineering for long conversations.","operationId":"agents.chatStream","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentChatRequest"}}}},"responses":{"200":{"content":{"text/event-stream":{"schema":{"type":"string"}}},"description":"SSE stream of chat chunks"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Owner thread belongs to another actor"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Agent not found"}},"summary":"Chat with agent (streaming)","tags":["Agents"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-protocol":"agent_sse","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/agents/generate":{"post":{"description":"Uses AI to generate a complete agent configuration based on a natural language description. Returns a suggested config that can be reviewed and modified before creating the agent.","operationId":"agents.generate","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GenerateAgentRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"anyOf":[{"$ref":"#/components/schemas/GeneratedBusinessAgentConfig"},{"$ref":"#/components/schemas/GeneratedAgentConfig"}]}}},"description":"Generated agent configuration"},"400":{"content":{"application/json":{"schema":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"status":{"type":"integer"}},"required":["error"],"type":"object"}}},"description":"Invalid request"},"402":{"content":{"application/json":{"schema":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"status":{"type":"integer"}},"required":["error"],"type":"object"}}},"description":"Insufficient credits"},"409":{"content":{"application/json":{"schema":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"status":{"type":"integer"}},"required":["error"],"type":"object"}}},"description":"Request ID conflict or execution already dispatched"},"500":{"content":{"application/json":{"schema":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"status":{"type":"integer"}},"required":["error"],"type":"object"}}},"description":"Generation failed"},"502":{"content":{"application/json":{"schema":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"status":{"type":"integer"}},"required":["error"],"type":"object"}}},"description":"LLM returned invalid JSON"},"503":{"content":{"application/json":{"schema":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"status":{"type":"integer"}},"required":["error"],"type":"object"}}},"description":"Managed generation is unavailable"}},"summary":"Generate agent configuration from description","tags":["Agents"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/agents/skills":{"get":{"operationId":"agents.listSkills","responses":{"200":{"content":{"application/json":{"schema":{"items":{"$ref":"#/components/schemas/AgentSkill"},"type":"array"}}},"description":"List of agent skills"}},"summary":"List agent skills","tags":["Agent Skills"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"post":{"operationId":"agents.createSkill","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateAgentSkillRequest"}}}},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentSkill"}}},"description":"Agent skill created"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Not allowed"}},"summary":"Create an agent skill","tags":["Agent Skills"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/agents/skills/:id":{"delete":{"operationId":"agents.deleteSkill","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"success":{"type":"boolean"}},"required":["success"],"type":"object"}}},"description":"Agent skill deleted"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Not allowed"}},"summary":"Delete an agent skill","tags":["Agent Skills"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"patch":{"operationId":"agents.updateSkill","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateAgentSkillRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentSkill"}}},"description":"Agent skill updated"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Not allowed"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Agent skill not found"}},"summary":"Update an agent skill","tags":["Agent Skills"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"agents","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/chat":{"post":{"operationId":"chat.send","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatResponse"}}},"description":"Chat response with sources"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatValidationError"}}},"description":"Invalid request body"},"402":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatErrorResponse"}}},"description":"Credits unavailable or organization subscription required before execution/stream admission"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatErrorResponse"}}},"description":"Collection access denied"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatErrorResponse"}}},"description":"Collection not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatErrorResponse"}}},"description":"Credits are held by another in-flight request"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatErrorResponse"}}},"description":"Chat failed"}},"summary":"Chat with RAG agent","tags":["Chat"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"rag_chat","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/chat/stream":{"post":{"operationId":"chat.stream","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatRequest"}}}},"responses":{"200":{"description":"SSE stream; admission failures other than a zero credit balance emit an error event with a public business code, including SUBSCRIPTION_REQUIRED"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatValidationError"}}},"description":"Invalid request body"},"402":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatErrorResponse"}}},"description":"Credits unavailable before stream admission"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatErrorResponse"}}},"description":"Collection not found"}},"summary":"Chat with streaming response","tags":["Chat"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"rag_chat","x-ignition-protocol":"chat_sse","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/chat/stream/progressive":{"post":{"operationId":"chat.streamProgressive","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatRequest"}}}},"responses":{"200":{"description":"SSE stream with stage, enhancement, sources, chunk, metrics and error events; admission failures other than a zero credit balance expose a public business code, including SUBSCRIPTION_REQUIRED"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatValidationError"}}},"description":"Invalid request body"},"402":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatErrorResponse"}}},"description":"Credits unavailable before stream admission"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatErrorResponse"}}},"description":"Collection not found"}},"summary":"Chat with progressive streaming response","tags":["Chat"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"rag_chat","x-ignition-protocol":"chat_sse","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/collections":{"get":{"description":"Lists organization collections and optionally includes shared or public collections.","operationId":"collections.list","parameters":[{"description":"Set to 'true' to include shared collections","in":"query","name":"includeShared","required":false,"schema":{"description":"Set to 'true' to include shared collections","example":"true","type":"string"}},{"description":"Set to 'true' to include public collections","in":"query","name":"includePublic","required":false,"schema":{"description":"Set to 'true' to include public collections","example":"true","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"items":{"$ref":"#/components/schemas/Collection"},"type":"array"}}},"description":"List of collections"}},"summary":"List all collections","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"post":{"operationId":"collections.create","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCollectionRequest"}}}},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Collection"}}},"description":"Collection created"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Invalid request, duplicate name, or public/shared create (use PATCH /api/collections/:id/visibility)"}},"summary":"Create a new collection","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/collections/:collectionId/rag-config":{"put":{"description":"Updates the RAG configuration for the specified collection. Partial updates are supported - only provided fields are updated.","operationId":"collections.setRagConfig","parameters":[{"in":"path","name":"collectionId","required":true,"schema":{"example":"coll_123","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RAGConfigInput"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RAGConfigResponse"}}},"description":"Updated RAG configuration"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RAGConfigErrorResponse"}}},"description":"Invalid configuration"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RAGConfigErrorResponse"}}},"description":"Collection not found"}},"summary":"Update RAG configuration for a collection","tags":["RAG Config"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/collections/:collectionId/rag-config/test":{"post":{"operationId":"ragExperiments.runAbTest","parameters":[{"in":"path","name":"collectionId","required":true,"schema":{"example":"coll_123","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ABTestConfig"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ABTestResult"}}},"description":"A/B test results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RAGConfigErrorResponse"}}},"description":"Invalid test configuration"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RAGConfigErrorResponse"}}},"description":"Collection not found"}},"summary":"Run A/B test comparing two RAG configurations","tags":["RAG Config"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"rag_experiments","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/collections/:id":{"delete":{"description":"Permanently deletes a collection and its related database rows.","operationId":"collections.delete","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"permanent":{"type":"boolean"},"success":{"type":"boolean"}},"required":["success","permanent"],"type":"object"}}},"description":"Collection deleted"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Collection not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Deletion is blocked: unresolved write, active fence, managed collection (MANAGED_COLLECTION_READ_ONLY), or platform-linked collection (PLATFORM_COLLECTION_DELETE_FORBIDDEN) — superadmin en session interactive uniquement"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Collection storage or vector deletion could not be verified"}},"summary":"Delete collection","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"get":{"operationId":"collections.get","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Collection"}}},"description":"Collection details"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Plan does not allow access to this collection"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Collection not found"}},"summary":"Get collection by ID","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"patch":{"operationId":"collections.update","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCollectionRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Collection"}}},"description":"Collection updated"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Collection not found"}},"summary":"Update collection","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/collections/:id/chunks":{"get":{"description":"Returns paginated list of chunks stored in the collection","operationId":"collections.chunks","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}},{"in":"query","name":"offset","required":false,"schema":{"default":0,"minimum":0,"nullable":true,"type":"number"}},{"in":"query","name":"limit","required":false,"schema":{"default":20,"maximum":100,"minimum":1,"type":"number"}},{"in":"query","name":"sourceType","required":false,"schema":{"enum":["document","web","dataset"],"type":"string"}},{"in":"query","name":"type","required":false,"schema":{"enum":["text","image"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChunksList"}}},"description":"Paginated list of chunks"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Collection not found"}},"summary":"List chunks in collection","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/collections/:id/documents":{"get":{"operationId":"collections.documents","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CollectionDocumentsResponse"}}},"description":"Collection documents with their ingestion reports"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CollectionDocumentsError"}}},"description":"Collection not found"}},"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/collections/:id/evaluations":{"get":{"operationId":"evaluations.list","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"evaluations":{"items":{"$ref":"#/components/schemas/EvaluationSummary"},"type":"array"}},"required":["evaluations"],"type":"object"}}},"description":"Recent evaluation summaries"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EvaluationError"}}},"description":"Collection not found"}},"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"evaluations","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"post":{"operationId":"evaluations.create","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateEvaluationRequest"}}},"required":false},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreatedEvaluation"}}},"description":"Evaluation queued"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EvaluationError"}}},"description":"Invalid evaluation request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EvaluationError"}}},"description":"Collection or parent evaluation not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EvaluationConflict"}}},"description":"An evaluation is already in progress"}},"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"evaluations","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/collections/:id/insights":{"get":{"description":"Returns the auto-generated insights for a collection","operationId":"collections.insights","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CollectionInsights"}}},"description":"Collection insights"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Collection or insights not found"}},"summary":"Get collection insights","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/collections/:id/insights/regenerate":{"post":{"description":"Regenerates the 4 insight reports for a collection","operationId":"collections.regenerateInsights","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CollectionInsights"}}},"description":"Regenerated insights"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Collection not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Insights generation failed"}},"summary":"Regenerate collection insights","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/collections/:id/quality-report":{"get":{"description":"Rolls up per-document ingestion reports into a collection-level view (extraction methods, OCR stats, chunking strategies, warnings, chunk size distribution). Returns zeros for collections whose documents were ingested before the ingestion_report column landed.","operationId":"collections.qualityReport","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CollectionQualityReport"}}},"description":"Collection quality report"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Collection not found"}},"summary":"Ingestion quality aggregate for a collection","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/collections/:id/search":{"get":{"description":"Performs semantic search on collection chunks with optional explicit filters based on detected schema","operationId":"collections.search","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}},{"in":"query","name":"q","required":true,"schema":{"minLength":1,"type":"string"}},{"in":"query","name":"limit","required":false,"schema":{"default":10,"maximum":50,"minimum":1,"type":"number"}},{"in":"query","name":"sourceType","required":false,"schema":{"enum":["document","web","dataset"],"type":"string"}},{"in":"query","name":"type","required":false,"schema":{"enum":["text","image"],"type":"string"}},{"description":"JSON-encoded array of filter definitions: [{field, operator, value}]","in":"query","name":"filters","required":false,"schema":{"description":"JSON-encoded array of filter definitions: [{field, operator, value}]","example":"[{\"field\":\"category\",\"operator\":\"eq\",\"value\":\"Fruits\"}]","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SearchResults"}}},"description":"Search results"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Collection not found"}},"summary":"Search chunks in collection","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/collections/:id/stats":{"get":{"description":"Returns statistics about chunks distribution by source type, content type, and top sources","operationId":"collections.stats","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CollectionStats"}}},"description":"Collection statistics"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Collection not found"}},"summary":"Get collection statistics","tags":["Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/evaluations/:evaluationId":{"get":{"operationId":"evaluations.get","parameters":[{"in":"path","name":"evaluationId","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EvaluationDetail"}}},"description":"Full evaluation detail including per-question results"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EvaluationDetailError"}}},"description":"Evaluation not found in the active scope"}},"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"evaluations","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/feedback":{"post":{"description":"Submit a bug report, feature request, or general feedback","operationId":"feedback.submit","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeedbackRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeedbackSuccess"}}},"description":"Feedback submitted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeedbackError"}}},"description":"Invalid request"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeedbackError"}}},"description":"Failed to send feedback"}},"security":[{"Bearer":[]}],"summary":"Submit feedback","tags":["Feedback"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"feedback","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/ingest/crawl":{"post":{"description":"Crawls a website using the crawler service and indexes all pages","operationId":"ingestion.crawl","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CrawlSiteRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CrawlResponse"}}},"description":"Successfully crawled and ingested website"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Collection not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Crawl failed"}},"summary":"Crawl entire website","tags":["Ingestion"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/ingest/crawl-selected/async":{"post":{"description":"Crawl a specific list of URLs selected by the user after discovery. Returns a job ID for progress tracking.","operationId":"ingestion.crawlSelectedAsync","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CrawlSelectedPagesRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingIngestResponse"}}},"description":"Crawl started"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Invalid request"},"402":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Insufficient execution credits"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Subscription required or operation forbidden"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Idempotency key reused with different crawl parameters"},"413":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Import exceeds available storage quota"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Crawl failed"}},"summary":"Crawl selected pages","tags":["Ingestion Streaming"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/ingest/crawl/async":{"post":{"description":"Starts a website crawl and returns immediately with a jobId.","operationId":"ingestion.crawlAsync","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingCrawlRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingIngestResponse"}}},"description":"Crawl started, use SSE endpoint to track progress"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Invalid credit ceiling"},"402":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Insufficient execution credits"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Organization subscription required or multimodal feature disabled by administrator policy"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Collection not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Idempotency key reused with different crawl parameters"},"413":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Import exceeds available storage quota"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Internal server error"}},"summary":"Crawl website with progress streaming","tags":["Ingestion Streaming"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/ingest/dataset":{"post":{"description":"Streams a Parquet file from URL (e.g., Hugging Face datasets) and indexes rows. Supports large files via streaming.","operationId":"ingestion.dataset","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IngestDatasetRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IngestResponse"}}},"description":"Successfully ingested dataset"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Collection not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Ingestion failed"}},"summary":"Ingest Parquet dataset from URL","tags":["Ingestion"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/ingest/dataset/async":{"post":{"description":"Starts dataset ingestion and returns immediately with a jobId.","operationId":"ingestion.datasetAsync","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingDatasetRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingIngestResponse"}}},"description":"Dataset ingestion started, use SSE endpoint to track progress"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Invalid credit ceiling"},"402":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Insufficient execution credits"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Active subscription required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Collection not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Idempotency key reused with different dataset parameters"},"413":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Dataset output exceeds available storage quota"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Internal server error"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Billing admission is unavailable"}},"summary":"Ingest HuggingFace dataset with progress streaming","tags":["Ingestion Streaming"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/ingest/discover":{"post":{"description":"Discover all pages on a website without extracting content. Returns a list of URLs the user can select from before crawling.","operationId":"ingestion.discover","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DiscoverSiteRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DiscoverResponse"}}},"description":"Pages discovered"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Subscription required or operation forbidden"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Discovery failed"}},"summary":"Discover pages on a website","tags":["Ingestion Streaming"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-protocol":"async_operation","x-ignition-stability":"experimental","x-ignition-version-sensitive":true}},"/api/ingest/document":{"post":{"description":"Indexes raw text content as a document","operationId":"ingestion.document","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IngestDocumentRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IngestResponse"}}},"description":"Successfully ingested document"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Collection not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Ingestion failed"}},"summary":"Ingest text document","tags":["Ingestion"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/ingest/file":{"post":{"description":"Uploads and indexes a file in the current request. SaaS rejects this route with 503; use POST /api/ingest/file/async. Set enableMultimodal=true to use Jina CLIP v2 for cross-modal search when allowed by administrator policy.","operationId":"ingestion.file","requestBody":{"content":{"multipart/form-data":{"schema":{"properties":{"accessPolicy":{"description":"JSON access policy: inherit or restricted with active business role IDs.","type":"string"},"chunkingConfiguration":{"description":"JSON chunking configuration; unknown or unsupported fields are rejected.","type":"string"},"collectionId":{"type":"string"},"enableMultimodal":{"description":"Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy. Pass 'true' to enable.","example":"true","type":"string"},"file":{"format":"binary","type":"string"},"mode":{"description":"Ingestion mode: 'documents' (default), 'tabular', or 'web'","example":"documents","type":"string"},"ocrLanguages":{"description":"Comma-separated OCR languages. Supported in the runtime image: fr,en. Omit for automatic detection.","example":"fr,en","type":"string"},"ocrMode":{"description":"OCR policy: auto (default), disabled, or force full-page OCR.","enum":["auto","disabled","force"],"type":"string"},"ocrReviewThreshold":{"description":"Quality review threshold between 0 and 1.","example":"0.55","type":"string"}},"required":["collectionId"],"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IngestResponse"}}},"description":"Successfully ingested file"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"No file provided"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Subscription required or operation forbidden"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Collection not found"},"413":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"File exceeds the maximum upload size"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Unsupported file type or PDF requires the separate OCR pipeline"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Ingestion failed"},"504":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Synchronous embedding deadline reached"}},"summary":"Ingest file synchronously (license only)","tags":["Ingestion"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-protocol":"multipart_ingestion","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/ingest/file/async":{"post":{"description":"Uploads a file and returns immediately with a jobId. This is the supported file ingestion route in SaaS. Use the SSE endpoint to track progress. Set enableMultimodal=true for cross-modal search when allowed by administrator policy.","operationId":"ingestion.fileAsync","requestBody":{"content":{"multipart/form-data":{"schema":{"properties":{"accessPolicy":{"description":"JSON access policy: inherit or restricted with active business role IDs.","type":"string"},"chunkingConfiguration":{"description":"JSON chunking configuration; unknown or unsupported fields are rejected.","type":"string"},"collectionId":{"type":"string"},"enableMultimodal":{"description":"Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy. Pass 'true' to enable.","example":"true","type":"string"},"file":{"format":"binary","type":"string"},"ocrLanguages":{"description":"Comma-separated OCR languages supported by the runtime image: fr,en.","example":"fr,en","type":"string"},"ocrMode":{"enum":["auto","disabled","force"],"type":"string"},"ocrReviewThreshold":{"example":"0.55","type":"string"}},"required":["collectionId"],"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingIngestResponse"}}},"description":"Job started, use SSE endpoint to track progress"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"No file provided"},"402":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Insufficient execution credits"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Organization subscription required or multimodal feature disabled by administrator policy"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Collection not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Idempotency key reused with different content"},"413":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"File exceeds the maximum upload size or available storage quota"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Unsupported file type"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Internal server error"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StreamingErrorResponse"}}},"description":"Billing admission is unavailable"}},"summary":"Ingest file (PDF, DOCX, etc.)","tags":["Ingestion Streaming"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/ingest/jobs":{"get":{"operationId":"ingestion.listJobs","parameters":[{"in":"query","name":"collectionId","required":true,"schema":{"minLength":1,"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"jobs":{"items":{"additionalProperties":{"nullable":true},"type":"object"},"type":"array"},"success":{"enum":[true],"type":"boolean"}},"required":["success","jobs"],"type":"object"}}},"description":"Collection ingestion jobs"},"400":{"content":{"application/json":{"schema":{"properties":{"error":{"type":"string"},"success":{"enum":[false],"type":"boolean"}},"required":["success","error"],"type":"object"}}},"description":"Missing collection"}},"summary":"List durable ingestion jobs for a collection","tags":["Ingestion"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/ingest/jobs/{jobId}":{"get":{"operationId":"ingestion.getJob","parameters":[{"in":"path","name":"jobId","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"job":{"additionalProperties":{"nullable":true},"type":"object"},"success":{"enum":[true],"type":"boolean"}},"required":["success","job"],"type":"object"}}},"description":"Current job state"},"404":{"content":{"application/json":{"schema":{"properties":{"error":{"type":"string"},"success":{"enum":[false],"type":"boolean"}},"required":["success","error"],"type":"object"}}},"description":"Job not found"}},"summary":"Get durable ingestion job state","tags":["Ingestion"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/ingest/jobs/{jobId}/cancel":{"post":{"operationId":"ingestion.cancelJob","parameters":[{"in":"path","name":"jobId","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"message":{"type":"string"},"success":{"enum":[true],"type":"boolean"}},"required":["success","message"],"type":"object"}}},"description":"Cancellation requested"},"404":{"content":{"application/json":{"schema":{"properties":{"error":{"type":"string"},"success":{"enum":[false],"type":"boolean"}},"required":["success","error"],"type":"object"}}},"description":"Job not found or already terminal"}},"summary":"Cancel a durable ingestion job","tags":["Ingestion"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/ingest/jobs/{jobId}/stream":{"get":{"operationId":"ingestion.streamJob","parameters":[{"in":"path","name":"jobId","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"text/event-stream":{"schema":{"type":"string"}}},"description":"Ingestion job event stream"}},"summary":"Stream durable ingestion job state","tags":["Ingestion"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-protocol":"ingestion_job_sse","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/ingest/url":{"post":{"description":"Scrapes a URL using the crawler service and indexes the content","operationId":"ingestion.url","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IngestUrlRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IngestResponse"}}},"description":"Successfully ingested URL content"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Invalid request body"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Collection not found"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"URL is not a public address"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}},"description":"Ingestion failed"}},"summary":"Ingest content from URL","tags":["Ingestion"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"ingestion","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/public-collections":{"get":{"operationId":"collections.listPublic","parameters":[{"in":"query","name":"minTier","required":false,"schema":{"enum":["pro","scale","enterprise"],"type":"string"}},{"in":"query","name":"q","required":false,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"items":{"items":{"$ref":"#/components/schemas/PublicCollectionSummary"},"type":"array"}},"required":["items"],"type":"object"}}},"description":"List of public collections"}},"summary":"List public collections eligible for the consumer's plan","tags":["Public Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/public-collections/{slug}":{"get":{"operationId":"collections.getPublic","parameters":[{"in":"path","name":"slug","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PublicCollectionDetail"}}},"description":"Public collection metadata"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PublicCollectionError"}}},"description":"No public collection at this slug"}},"summary":"Resolve a single public collection by slug","tags":["Public Collections"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"collections","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/traces":{"get":{"operationId":"observability.listTraces","parameters":[{"in":"query","name":"page","required":false,"schema":{"default":1,"minimum":1,"type":"integer"}},{"in":"query","name":"limit","required":false,"schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"type","required":false,"schema":{"enum":["llm","agent","retrieval","rerank","tool","judge","workflow","ingestion","ab_test"],"type":"string"}},{"in":"query","name":"status","required":false,"schema":{"enum":["success","error"],"type":"string"}},{"in":"query","name":"surface","required":false,"schema":{"enum":["chat","agent","workflow","mcp","sdk","widget","public","ingestion","evaluation","unknown"],"type":"string"}},{"in":"query","name":"accessTier","required":false,"schema":{"enum":["owner","shared","public-free","public-gated","denied"],"type":"string"}},{"in":"query","name":"collectionVisibility","required":false,"schema":{"enum":["private","shared","public","unknown"],"type":"string"}},{"in":"query","name":"accessOutcome","required":false,"schema":{"enum":["allowed","denied","plan_gate","read_only"],"type":"string"}},{"in":"query","name":"search","required":false,"schema":{"maxLength":200,"type":"string"}},{"in":"query","name":"collectionId","required":false,"schema":{"type":"string"}},{"in":"query","name":"sessionId","required":false,"schema":{"type":"string"}},{"in":"query","name":"tags","required":false,"schema":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]}},{"in":"query","name":"startDate","required":false,"schema":{"format":"date-time","type":"string"}},{"in":"query","name":"endDate","required":false,"schema":{"format":"date-time","type":"string"}},{"in":"query","name":"parentOnly","required":false,"schema":{"default":true,"nullable":true,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{"nullable":true},"type":"object"}}},"description":"Paginated traces"}},"summary":"List scoped traces","tags":["Observability"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"observability","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/traces/export":{"get":{"operationId":"observability.exportTraces","parameters":[{"in":"query","name":"format","required":true,"schema":{"enum":["csv","json"],"type":"string"}},{"in":"query","name":"startDate","required":true,"schema":{"format":"date-time","type":"string"}},{"in":"query","name":"endDate","required":true,"schema":{"format":"date-time","type":"string"}},{"in":"query","name":"type","required":false,"schema":{"enum":["llm","agent","retrieval","rerank","tool","judge","workflow","ingestion","ab_test"],"type":"string"}},{"in":"query","name":"status","required":false,"schema":{"enum":["success","error"],"type":"string"}},{"in":"query","name":"surface","required":false,"schema":{"enum":["chat","agent","workflow","mcp","sdk","widget","public","ingestion","evaluation","unknown"],"type":"string"}},{"in":"query","name":"accessTier","required":false,"schema":{"enum":["owner","shared","public-free","public-gated","denied"],"type":"string"}},{"in":"query","name":"collectionVisibility","required":false,"schema":{"enum":["private","shared","public","unknown"],"type":"string"}},{"in":"query","name":"accessOutcome","required":false,"schema":{"enum":["allowed","denied","plan_gate","read_only"],"type":"string"}},{"in":"query","name":"search","required":false,"schema":{"maxLength":200,"type":"string"}},{"in":"query","name":"collectionId","required":false,"schema":{"type":"string"}},{"in":"query","name":"includeInputOutput","required":false,"schema":{"default":false,"nullable":true,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"nullable":true}},"text/csv":{"schema":{"type":"string"}}},"description":"CSV or JSON trace export"}},"summary":"Export scoped traces","tags":["Observability"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"observability","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/traces/metrics":{"get":{"operationId":"observability.getTraceMetrics","parameters":[{"in":"query","name":"startDate","required":true,"schema":{"type":"string"}},{"in":"query","name":"endDate","required":true,"schema":{"type":"string"}},{"in":"query","name":"collectionId","required":false,"schema":{"type":"string"}},{"in":"query","name":"type","required":false,"schema":{"enum":["llm","agent","retrieval","rerank","tool","judge","workflow","ingestion","ab_test"],"type":"string"}},{"in":"query","name":"granularity","required":false,"schema":{"default":"day","enum":["day","week","month"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{"nullable":true},"type":"object"}}},"description":"Aggregated trace metrics"}},"summary":"Get scoped trace metrics","tags":["Observability"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"observability","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/traces/{id}":{"get":{"operationId":"observability.getTrace","parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}},{"in":"query","name":"includeChildren","required":false,"schema":{"default":true,"nullable":true,"type":"boolean"}},{"in":"query","name":"maxDepth","required":false,"schema":{"default":10,"maximum":20,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"trace":{"nullable":true}},"type":"object"}}},"description":"Trace and optional children"},"404":{"content":{"application/json":{"schema":{"properties":{"error":{"type":"string"}},"required":["error"],"type":"object"}}},"description":"Trace not found"}},"summary":"Get a scoped trace","tags":["Observability"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"observability","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/workflows":{"get":{"operationId":"workflows.list","responses":{"200":{"content":{"application/json":{"schema":{"items":{"$ref":"#/components/schemas/WorkflowListItem"},"type":"array"}}},"description":"List of workflows"}},"summary":"List all workflows","tags":["Workflows"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"workflows","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"post":{"operationId":"workflows.create","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateWorkflowRequest"}}}},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Workflow"}}},"description":"Workflow created"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Feature not available on plan"}},"summary":"Create a new workflow","tags":["Workflows"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"workflows","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/workflows/:id":{"delete":{"description":"Permanently deletes a workflow and cascades related rows where configured.","operationId":"workflows.delete","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"permanent":{"type":"boolean"},"success":{"type":"boolean"}},"required":["success","permanent"],"type":"object"}}},"description":"Workflow deleted"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Workflow not found"}},"summary":"Delete workflow","tags":["Workflows"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"workflows","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"get":{"operationId":"workflows.get","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Workflow"}}},"description":"Workflow details"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Workflow not found"}},"summary":"Get workflow by ID","tags":["Workflows"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"workflows","x-ignition-stability":"stable","x-ignition-version-sensitive":false},"patch":{"operationId":"workflows.update","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateWorkflowRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Workflow"}}},"description":"Workflow updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Invalid request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Workflow not found"}},"summary":"Update workflow","tags":["Workflows"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"workflows","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/workflows/:id/execute":{"post":{"description":"Starts executing a workflow and returns the result","operationId":"workflows.execute","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecuteRequest"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecutionResult"}}},"description":"Execution result"},"202":{"content":{"application/json":{"schema":{"properties":{"chargedMilliCredits":{"nullable":true,"type":"string"},"executionId":{"type":"string"},"maximumMilliCredits":{"type":"string"},"output":{"nullable":true},"reconciliationRequired":{"type":"boolean"},"status":{"type":"string"}},"required":["executionId","status","reconciliationRequired","maximumMilliCredits","chargedMilliCredits"],"type":"object"}}},"description":"Budget reserved and execution admitted"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Invalid request"},"402":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Insufficient credits"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Forbidden"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Workflow not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Conflict"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Execution failed"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Temporarily unavailable"}},"summary":"Execute workflow","tags":["Workflows"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"workflows","x-ignition-protocol":"async_operation","x-ignition-stability":"stable","x-ignition-version-sensitive":true}},"/api/workflows/:id/executions":{"get":{"operationId":"workflows.listExecutions","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"query","name":"limit","required":false,"schema":{"default":20,"maximum":100,"minimum":1,"type":"number"}}],"responses":{"200":{"content":{"application/json":{"schema":{"items":{"$ref":"#/components/schemas/Execution"},"type":"array"}}},"description":"List of executions"}},"summary":"List workflow executions","tags":["Workflows"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"workflows","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/workflows/:id/validate":{"post":{"description":"Validates the workflow graph structure and connections","operationId":"workflows.validate","parameters":[{"in":"path","name":"id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationResult"}}},"description":"Validation result"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Workflow not found"}},"summary":"Validate workflow","tags":["Workflows"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"workflows","x-ignition-stability":"stable","x-ignition-version-sensitive":false}},"/api/workflows/executions/:executionId":{"delete":{"operationId":"workflows.cancelExecution","parameters":[{"in":"path","name":"executionId","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"properties":{"cancelled":{"type":"boolean"}},"required":["cancelled"],"type":"object"}}},"description":"Cancellation result"}},"summary":"Cancel execution","tags":["Workflows"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"workflows","x-ignition-stability":"stable","x-ignition-version-sensitive":true},"get":{"operationId":"workflows.getExecution","parameters":[{"in":"path","name":"executionId","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Execution"}}},"description":"Execution details"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"description":"Execution not found"}},"summary":"Get execution details","tags":["Workflows"],"x-ignition-auth":"api_key_or_user_token","x-ignition-capability":"workflows","x-ignition-stability":"stable","x-ignition-version-sensitive":false}}},"security":[{"Bearer":[]}]},"protocols":{"agent_sse":{"events":["chunk","tool_call","tool_result","sources","deep_status","deep_task","deep_finding","deep_synthesis","snapshot","status","task","finding","synthesis","heartbeat","error","done"],"maxFrameBytes":65536,"ordered":true,"partialErrorTerminatesStream":true,"replay":"none","schemaVersion":1,"terminalEvent":"done","transport":"text/event-stream"},"async_operation":{"schemaVersion":1,"states":["queued","running","succeeded","failed","cancelled"],"terminalStates":["succeeded","failed","cancelled"],"transportAbortCancelsRemote":false},"chat_sse":{"events":["chunk","sources","images","metrics","stage","enhancement","citation","error","done"],"maxFrameBytes":65536,"ordered":true,"partialErrorTerminatesStream":true,"replay":"none","schemaVersion":1,"terminalEvent":"done","transport":"text/event-stream"},"ingestion_job_sse":{"events":["state","heartbeat","error"],"maxFrameBytes":65536,"ordered":true,"partialErrorTerminatesStream":true,"replay":"durable_state","schemaVersion":1,"terminalEvent":"state","transport":"text/event-stream"},"multipart_ingestion":{"browserFallback":"bounded-native-body","maxBufferedFallbackBytes":10485760,"schemaVersion":1,"streamingPreferred":true,"transport":"multipart/form-data"}},"releaseSequence":5,"schemaVersion":1,"sourceCommit":"9996d0b44aa62d7e9dbcc9b7a533868c789d4d5c"},"signature":{"algorithm":"ed25519","keyId":"sdk-contract-2026-11","value":"LNuO35U0oSHqqV5Cm7UIEUg0n7UFFDILVn/LhdtYl12Wg5qh0c1bGYHot1Zr3Pvf1g4zwQgvH5cgUsx3U5AEBA=="}} diff --git a/docs/compatibility.md b/docs/compatibility.md index 3c6fa89..507d4dd 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -1,10 +1,58 @@ # Compatibility policy -IgnitionRAG exposes a signed public contract through `/api/meta`. The SDK verifies the contract version and digest before relying on deployment capabilities. +IgnitionRAG exposes a contract identity through `/api/meta`. Signed archives are +verified separately before SDK generation and public synchronization. Metadata +identifies a deployment; it is not itself a signed archive. - The current SDK supports the current public contract and the immediately previous contract version. -- A changed digest under an unchanged version is rejected as a protocol error. +- A changed digest under the current version is rejected as a protocol error. +- The previous revision is admitted by version and advertised capabilities; its + digest is not compared with the current revision digest. - Missing or disabled capabilities are reported explicitly; they are not silently redirected to another service. - Contract artifacts are verified with the public keys in `contracts/trusted-keys.json`. Upgrade the deployment or SDK when the compatibility check reports an unsupported contract version. + +## Live SDK diagnostic + +From `typescript/`, run `bun run test:live` with `IGNITION_BASE_URL` and +`IGNITION_API_KEY` supplied through the environment. Keep credentials out of +shell history and committed files. The command uses the checked-out SDK and +only sends GET requests, with retries disabled and a 15-second request timeout. + +It checks deployment compatibility, collection details and documents, +evaluation details, agents, skills, research status, workflows and execution +details. Output contains check labels and outcomes, never resource contents, +identifiers or API credentials. Any failed compatibility, HTTP or response +shape check produces a nonzero exit status, while the remaining checks continue. +Missing fixtures and unavailable insights are reported as `NOT PROVEN`. + +Run again with a group-bound key for group coverage. To probe collection +isolation, set `IGNITION_FORBIDDEN_COLLECTION_IDS` to comma-separated IDs of +known private collections in the other space. Only 403 or 404 counts as a +successful denial. Shared/public collections are unsuitable fixtures. Without +these fixtures, isolation is explicitly `NOT PROVEN`; successful resource +reads alone do not prove tenancy isolation. + +A zero exit status covers only the checks exercised. This diagnostic does not +validate chat/streaming, ingestion, writes, workflow execution or cancellation. +Contract identities must still come from the official signed synchronization; +do not change the accepted version or digest merely to make a live check pass. + +## Migration to 2026.11 + +The prepared TypeScript candidate is `1.0.0`. Its current contract is +`2026.11`; `2026.10` and `2026.09` remain accepted older revisions. `ingest.file` now returns +`AsyncIngestResult` — wait with `getJob` / `streamJob`. The sync HTTP route +`POST /api/ingest/file` is license-only. Deployment-specific crawler limits +remain enforced, but no longer change the versioned schema identity. +Upgrade the SDK before deploying `2026.11`. This source preparation is neither +a signed release nor an npm publication. The official workflow must sign and +verify the archive, regenerate the TypeScript identity and wire types and pass public synchronization +before release. Personal evaluation reads also require the server workspace +scope correction; upgrading the client alone does not fix the deployed 400. + +Revision `2026.11` regenerates the integrated public schemas, including optional +ingestion chunking configuration. The current digest remains strict; older +revision admission does not assert equivalent digests or qualify every operation. +No deprecated revision is removed and no existing signed archive is rewritten. diff --git a/docs/typescript-contract-2026-10.md b/docs/typescript-contract-2026-10.md new file mode 100644 index 0000000..6f6b5c4 --- /dev/null +++ b/docs/typescript-contract-2026-10.md @@ -0,0 +1,91 @@ +# TypeScript contract 2026.10 operation mapping + +The canonical allow-list contains 65 operations. The table maps each operation +to the ergonomic client. Inputs and wire responses are generated in +`src/generated/public-api.ts`; the package root exposes ergonomic types. +This inventory is not runtime proof for every operation. Existing focused tests +cover the resource families, multipart transport, asynchronous jobs, cancellation, +managed admission, streaming and errors; live coverage must be assessed separately. + +Legacy synchronous ingestion, discovery/crawling, skill mutations and agent SSE +remain deployment-dependent. Ordinary SaaS users must use durably admitted file +ingestion and managed agent execution. Availability on licensed deployments does +not imply SaaS availability. No private widgets/MCP routes enter this contract. + +| Operation | HTTP | Client method | +| --- | --- | --- | +| `chat.send` | `POST /api/chat` | `chat.send` | +| `chat.stream` | `POST /api/chat/stream` | `chat.stream` | +| `chat.streamProgressive` | `POST /api/chat/stream/progressive` | `chat.streamProgressive` | +| `collections.listPublic` | `GET /api/public-collections` | `collections.listPublic` | +| `collections.getPublic` | `GET /api/public-collections/{slug}` | `collections.getPublic` | +| `collections.list` | `GET /api/collections` | `collections.list` | +| `collections.create` | `POST /api/collections` | `collections.create` | +| `collections.get` | `GET /api/collections/:id` | `collections.get` | +| `collections.update` | `PATCH /api/collections/:id` | `collections.update` | +| `collections.delete` | `DELETE /api/collections/:id` | `collections.delete` | +| `collections.insights` | `GET /api/collections/:id/insights` | `collections.insights` | +| `collections.regenerateInsights` | `POST /api/collections/:id/insights/regenerate` | `collections.regenerateInsights` | +| `collections.chunks` | `GET /api/collections/:id/chunks` | `collections.chunks` | +| `collections.search` | `GET /api/collections/:id/search` | `collections.search` | +| `collections.stats` | `GET /api/collections/:id/stats` | `collections.stats` | +| `collections.qualityReport` | `GET /api/collections/:id/quality-report` | `collections.qualityReport` | +| `collections.documents` | `GET /api/collections/:id/documents` | `collections.documents` | +| `collections.setRagConfig` | `PUT /api/collections/:collectionId/rag-config` | `collections.applyRagPreset` | +| `ingestion.url` | `POST /api/ingest/url` | `ingest.url` | +| `ingestion.document` | `POST /api/ingest/document` | `ingest.document` | +| `ingestion.file` | `POST /api/ingest/file/async` | `ingest.file` (alias of `ingest.fileAsync`; SaaS rejects sync `/ingest/file`) | +| `ingestion.crawl` | `POST /api/ingest/crawl` | `ingest.crawl` | +| `ingestion.dataset` | `POST /api/ingest/dataset` | `ingest.dataset` | +| `ingestion.fileAsync` | `POST /api/ingest/file/async` | `ingest.fileAsync` | +| `ingestion.crawlAsync` | `POST /api/ingest/crawl/async` | `ingest.crawlAsync` | +| `ingestion.datasetAsync` | `POST /api/ingest/dataset/async` | `ingest.datasetAsync` | +| `ingestion.discover` | `POST /api/ingest/discover` | `ingest.discover` | +| `ingestion.crawlSelectedAsync` | `POST /api/ingest/crawl-selected/async` | `ingest.crawlSelectedAsync` | +| `ingestion.getJob` | `GET /api/ingest/jobs/{jobId}` | `ingest.getJob` | +| `ingestion.listJobs` | `GET /api/ingest/jobs` | `ingest.listJobs` | +| `ingestion.streamJob` | `GET /api/ingest/jobs/{jobId}/stream` | `ingest.streamJob` | +| `ingestion.cancelJob` | `POST /api/ingest/jobs/{jobId}/cancel` | `ingest.cancelJob` | +| `agents.listSkills` | `GET /api/agents/skills` | `agents.listSkills` | +| `agents.createSkill` | `POST /api/agents/skills` | `agents.createSkill` | +| `agents.updateSkill` | `PATCH /api/agents/skills/:id` | `agents.updateSkill` | +| `agents.deleteSkill` | `DELETE /api/agents/skills/:id` | `agents.deleteSkill` | +| `agents.list` | `GET /api/agents` | `agents.list` | +| `agents.create` | `POST /api/agents` | `agents.create` | +| `agents.get` | `GET /api/agents/:id` | `agents.get` | +| `agents.update` | `PATCH /api/agents/:id` | `agents.update` | +| `agents.delete` | `DELETE /api/agents/:id` | `agents.delete` | +| `agents.generate` | `POST /api/agents/generate` | `agents.generate` | +| `agents.chatStream` | `POST /api/agents/:id/chat/stream` | `agentChat.stream` | +| `deepResearch.cancel` | `POST /api/agents/:agentId/chat/cancel-deep` | `deepResearch.cancel` | +| `deepResearch.status` | `GET /api/agents/:agentId/chat/deep-status` | `deepResearch.status` | +| `deepResearch.stream` | `GET /api/agents/:agentId/chat/deep-stream` | `deepResearch.stream` | +| `workflows.list` | `GET /api/workflows` | `workflows.list` | +| `workflows.create` | `POST /api/workflows` | `workflows.create` | +| `workflows.get` | `GET /api/workflows/:id` | `workflows.get` | +| `workflows.update` | `PATCH /api/workflows/:id` | `workflows.update` | +| `workflows.delete` | `DELETE /api/workflows/:id` | `workflows.delete` | +| `workflows.validate` | `POST /api/workflows/:id/validate` | `workflows.validate` | +| `workflows.execute` | `POST /api/workflows/:id/execute` | `workflows.execute` | +| `workflows.listExecutions` | `GET /api/workflows/:id/executions` | `workflows.listExecutions` | +| `workflows.getExecution` | `GET /api/workflows/executions/:executionId` | `workflows.getExecution` | +| `workflows.cancelExecution` | `DELETE /api/workflows/executions/:executionId` | `workflows.cancelExecution` | +| `evaluations.create` | `POST /api/collections/:id/evaluations` | `evaluations.create` | +| `evaluations.list` | `GET /api/collections/:id/evaluations` | `evaluations.list` | +| `evaluations.get` | `GET /api/evaluations/:evaluationId` | `evaluations.get` | +| `ragExperiments.runAbTest` | `POST /api/collections/:collectionId/rag-config/test` | `ragAbTests.run` | +| `observability.listTraces` | `GET /api/traces` | `traces.list` | +| `observability.getTrace` | `GET /api/traces/{id}` | `traces.get` | +| `observability.getTraceMetrics` | `GET /api/traces/metrics` | `traces.metrics` | +| `observability.exportTraces` | `GET /api/traces/export` | `traces.export` | +| `feedback.submit` | `POST /api/feedback` | `feedback.submit` | + +`collections.applyRagPreset` accepts a preset or its inline retrieval config; +it deliberately does not expose arbitrary platform provider/model configuration. +`workflows.cancelExecution` returns `{ cancelled: boolean }`. It is a remote +cancellation request, distinct from aborting an HTTP request. SaaS durable +workflow/agent execution has separate managed helpers and admission rules. + +Full per-operation input/result conformance and both-space live completion +remain release gates. Empty lists, accepted submissions and skipped scenarios +do not establish completed execution or successful ingestion. diff --git a/scripts/validate-release.ts b/scripts/validate-release.ts index 9a4b659..5a2b64d 100644 --- a/scripts/validate-release.ts +++ b/scripts/validate-release.ts @@ -8,6 +8,6 @@ const packageJson = JSON.parse(await readFile("typescript/package.json", "utf8") if (tag !== `v${packageJson.version}`) { throw new Error(`Tag ${tag} does not match package version ${packageJson.version}`); } -process.argv.push("--built"); +if (!process.argv.includes("--metadata-only")) process.argv.push("--built"); await import("./validate-public-surface.ts"); console.log(`Validated release ${tag}`); diff --git a/typescript/CHANGELOG.md b/typescript/CHANGELOG.md new file mode 100644 index 0000000..0f4c1b3 --- /dev/null +++ b/typescript/CHANGELOG.md @@ -0,0 +1,47 @@ +# Changelog + +## 1.0.0 + +### Fixed + +- Collection creation exposes the canonical `embeddingConfigId` input so callers + can select an owned configuration without changing the workspace default. +- File ingestion forwards the canonical `ocrMode` selection, and workflow + creation accepts an explicit `isActive` flag. +- Licensed agent creation and updates expose the canonical `llmConfigId`, + `fallbackLlmConfigId`, and `runtimeKind: "byok_api"` inputs in TypeScript. + Nullable provider selections remain supported; managed agent inputs stay restricted. + +### Breaking + +- `ingest.file` now calls `POST /api/ingest/file/async` and returns `AsyncIngestResult` + (`success`, `jobId`, `message`) instead of a completed `IngestResult`. + `ingest.fileAsync` is unchanged. +- `ingest.url` now calls `POST /api/ingest/url/async` (single page) and returns + `AsyncIngestResult` (`success`, `jobId`, `message`) instead of a completed + `IngestResult` (`chunksCount`, `documentId`, …). Callers that read + `chunksCount` from `ingest.url` must wait on `getJob` / `streamJob`. + `ingest.document` also returns `AsyncIngestResult` (raw text uploaded through + `/file/async`). SaaS members no longer hit the closed synchronous routes. + +### Migration + +Wait for the durable job instead of treating `ingest.file` or `ingest.url` as a +synchronous ingest: + +```ts +const started = await client.ingest.file({ collectionId, file }); +const job = await client.ingest.getJob(started.jobId); +// or: for await (const event of client.ingest.streamJob(started.jobId)) { ... } + +const fromUrl = await client.ingest.url({ collectionId, url }); +await client.ingest.getJob(fromUrl.jobId); +``` + +`POST /api/ingest/file` and `POST /api/ingest/url` remain published for +**license** deployments only. SaaS rejects those sync routes; the SDK uses the +metered async paths (`ingest.file`, `ingest.url`, `ingest.document`). +Synchronous `ingest.crawl`, `ingest.dataset`, and `ingest.discover` stay on the +license routes and raise `OfferingUnavailableError` when SaaS returns 503 +`AI_TEMPORARILY_UNAVAILABLE`. Members should call `ingest.crawlAsync` or +`ingest.datasetAsync` instead. diff --git a/typescript/README.md b/typescript/README.md index ced1ea4..0420590 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -5,7 +5,7 @@ [![license](https://img.shields.io/npm/l/@ignitionai/sdk.svg)](./LICENSE) [![types](https://img.shields.io/npm/types/@ignitionai/sdk.svg)](https://www.npmjs.com/package/@ignitionai/sdk) -TypeScript SDK for your licensed or self-hosted IgnitionRAG deployment. Zero dependencies, compatible with Node.js 20+, Bun, edge runtimes and browsers. API keys stay in trusted server runtimes; browsers use delegated user tokens. +TypeScript SDK for managed SaaS, licensed, and self-hosted IgnitionRAG deployments. Zero dependencies, compatible with Node.js 20+, Bun, edge runtimes and browsers. API keys stay in trusted server runtimes; browsers use delegated user tokens. ## Installation @@ -15,8 +15,10 @@ npm install @ignitionai/sdk@next bun add @ignitionai/sdk@next ``` -The `0.3.0-rc.3` release candidate is published under the `next` tag. The -`latest` tag remains on the stable `0.2.x` line until the official promotion. +This source tree prepares `1.0.0` for contract `2026.11`; publication is a +separate reviewed release step. `ingest.file` and `ingest.url` are breaking +changes from `0.3.0-rc.4`: they return `AsyncIngestResult`. +The `latest` tag remains on the stable `0.2.x` line until the official promotion. ## Setup @@ -71,10 +73,22 @@ const deployment = await client.compatibility.assertCompatible(); console.log(deployment.contractVersion, deployment.capabilities); ``` -The SDK caches metadata briefly and fails explicitly on an unsupported version or a changed digest under the same contract version. +The SDK caches metadata briefly and fails explicitly on an unsupported version +or a changed digest under its current contract version. This client recognizes +deployments advertising `2026.11`, `2026.10` or `2026.09`. This is +new-client compatibility with older deployments: SDKs that do not recognize +`2026.11` must be upgraded before connecting to a `2026.11` deployment. +The current revision requires the exact generated shape digest. Previous-revision +admission checks the version and advertised capabilities; it does not compare +the previous deployment digest with the current revision digest. +The prospective compatibility policy starts with `2026.09`; it does not restore +capabilities removed before that baseline. ## RAG Chat +The direct `client.chat` methods below are the licensed/self-hosted contract. +Managed SaaS callers should use `client.chat.managed`, documented below. + ### Non-streaming ```typescript @@ -195,6 +209,10 @@ await client.deepResearch.cancel("agent_xxxx"); ## Agents +The direct agent methods below retain the licensed/self-hosted configuration +contract, including deployment-owned model and MCP settings. Managed SaaS uses +the separate `client.agents.managed` and `client.agentChat.managed` contracts. + ```typescript // List const agents = await client.agents.list(); @@ -251,6 +269,12 @@ const run = await client.workflows.execute("workflow_xxxx", { input: { question: "Summarize the latest customer feedback" }, }); +// SaaS: the server derives the credit envelope from the workspace balance. +const managedRun = await client.workflows.executeManaged("workflow_xxxx", { + requestId: crypto.randomUUID(), + input: { question: "Summarize the latest customer feedback" }, +}); + const execution = await client.workflows.getExecution(run.executionId); console.log(execution.status, execution.output); @@ -266,9 +290,53 @@ if (execution.status === "running") { Aborting the HTTP request does not cancel a remote workflow execution. Use `cancelExecution()` when the execution itself must stop. -## Data Chat +`execute()` remains the licensed deployment contract. SaaS callers must use +`executeManaged()`; the server resolves providers and tariffs and rejects +client-supplied model or secret fields. + +## Widgets + +The direct widget methods retain the licensed deployment contract. Managed SaaS +uses `client.widgets.managed` and omits provider selection and secret fields. + +Manage embeddable collection, agent, and workflow widgets through the same +authenticated client. -Query collections and external data connectors through the same governed +```typescript +const created = await client.widgets.create({ + name: "Support", + type: "agent", + agentId: "agent_xxxx", + allowedDomains: ["https://app.example.com"], + position: "bottom-right", +}); + +console.log(created.widgetKey, created.embedCode); + +await client.widgets.update(created.widget.id, { + welcomeMessage: "How can I help?", + theme: { preset: "dark", primaryColor: "#6d28d9" }, +}); + +const analytics = await client.widgets.analytics(created.widget.id, "30d"); +console.log(analytics.totalSessions, analytics.resolutionRate); + +const rotated = await client.widgets.regenerateKey(created.widget.id); +console.log(rotated.embedCode); +``` + +The widget key is returned only at creation or rotation time. Store it in the +integrating application; do not confuse it with the server-side API key. + +## Data Chat (legacy deployments only) + +`client.dataChat` is deprecated and retained for older deployments whose +`/api/meta` advertises `data_connectors`. Contract `2026.09` does not expose Data +Chat. Both helpers check that capability first and raise +`UnsupportedCapabilityError` before sending a request to a retired route when +it is absent. They do not redirect the query to another service. + +On a compatible legacy deployment, query collections and external data connectors through the same governed request. Run the precheck first when you want to surface incompatible or unavailable sources before execution. @@ -313,6 +381,14 @@ const readable = await client.collections.list({ includePublic: true, }); +// Browse the dedicated public catalog and resolve one item by slug +const publicCatalog = await client.collections.listPublic({ + minTier: "pro", + query: "labor", +}); +const publicDataset = await client.collections.getPublic("code-du-travail"); +console.log(publicDataset.sampleQueries); + for (const collection of readable) { if (collection.isReadOnly) { console.log(`${collection.name} is readable but not writable`); @@ -375,40 +451,74 @@ try { ## Ingestion +On managed SaaS, members use the metered async routes. `ingest.file`, +`ingest.url`, and `ingest.document` queue a durable job and return +`AsyncIngestResult`. Wait with `getJob` or `streamJob`. + ```typescript -// Ingest from URL -await client.ingest.url({ +// Single URL (POST /api/ingest/url/async) +const fromUrl = await client.ingest.url({ collectionId: "coll_xxxx", url: "https://docs.example.com/guide", }); +await client.ingest.getJob(fromUrl.jobId); -// Ingest raw text -await client.ingest.document({ +// Raw text as a file (POST /api/ingest/file/async) +const fromText = await client.ingest.document({ collectionId: "coll_xxxx", content: "Your document content...", filename: "guide.txt", }); +await client.ingest.getJob(fromText.jobId); -// Upload file -await client.ingest.file({ +// Upload file (durable job; SaaS rejects sync /ingest/file) +const started = await client.ingest.file({ collectionId: "coll_xxxx", file: new File([buffer], "report.pdf", { type: "application/pdf" }), + enableMultimodal: true, }); +await client.ingest.getJob(started.jobId); +``` -// Crawl website -await client.ingest.crawl({ +Synchronous site crawl, dataset import, and discovery remain license-only. +On SaaS they throw `OfferingUnavailableError` (`OFFERING_UNAVAILABLE`) instead +of a 503 `AI_TEMPORARILY_UNAVAILABLE` outage. Members should call the async +variants: + +```typescript +await client.ingest.crawlAsync({ collectionId: "coll_xxxx", url: "https://docs.example.com", maxPages: 50, }); - -// Import HuggingFace dataset -await client.ingest.dataset({ +await client.ingest.datasetAsync({ collectionId: "coll_xxxx", - source: "huggingface", datasetId: "squad", split: "train", - maxRows: 1000, + limit: 1000, +}); +``` + +Licensed and self-hosted deployments still admit `ingest.crawl`, +`ingest.dataset`, and `ingest.discover`. For long ingestions, the asynchronous +variants return a `jobId` immediately; transport cancellation does not cancel +the remote job. + +```typescript +const discovered = await client.ingest.discover({ + url: "https://docs.example.com", + maxPages: 500, +}); + +const job = await client.ingest.crawlSelectedAsync({ + collectionId: "coll_xxxx", + urls: discovered.pages.map((page) => page.url), +}); +console.log(job.jobId); + +await client.ingest.fileAsync({ + collectionId: "coll_xxxx", + file: new File([buffer], "manual.pdf", { type: "application/pdf" }), }); ``` @@ -596,6 +706,82 @@ return toAIStreamResponse(stream); | `IGNITION_API_KEY` | API key (starts with `ign_`) | Yes (or pass in constructor) | | `IGNITION_BASE_URL` | Your deployment URL (pass it as `baseURL`) | Yes | +### Managed SaaS chat + +Use the explicit `managed` namespace for SaaS chat. It accepts an optional +`maximumMilliCredits` ceiling as a positive integer string (at most 16 digits); +`"1000"` means a ceiling of one credit, not a fixed charge. These methods reject +model and LLM configuration overrides before sending a request, with or without +a budget. The server selects the model and applies workspace policy. + +```ts +await client.chat.managed.send({ + collectionId: "collection-id", + query: "Summarize the onboarding procedure.", + maximumMilliCredits: "1000", +}); + +const stream = client.chat.managed.stream({ + collectionId: "collection-id", + query: "Summarize the onboarding procedure.", +}); +for await (const event of stream) { + if (event.type === "chunk") process.stdout.write(event.content); +} +``` + +Managed response DTOs omit model/provider configuration and internal usage +metadata. Existing `client.chat.send`, `stream`, and `streamProgressive` methods +remain the licensed/self-hosted compatibility contract. + +### Managed SaaS agents + +Use the managed agent namespace for agent resources and the durable metered chat +admission API. Requests require an idempotency `requestId`, session, and server +credit ceiling. Poll or cancel the returned execution explicitly; a streaming +licensed agent-chat call is not the managed admission contract. + +```ts +const agent = await client.agents.managed.create({ + name: "Support assistant", + collectionId: "00000000-0000-4000-8000-000000000001", + systemPrompt: "Answer from the approved support content.", + enabledBuiltinTools: ["web_search"], +}); + +const execution = await client.agentChat.managed.start(agent.id, { + requestId: crypto.randomUUID(), + sessionId: "support-session-1", + query: "How do I update my billing details?", + maximumMilliCredits: "1000", +}); +const current = await client.agentChat.managed.get(agent.id, execution.executionId); +``` + +Managed agent contracts accept business prompts and resource references but +omit provider, model, MCP credential, and runtime fields. The existing +`client.agents` and `client.agentChat.stream` methods remain available for +licensed/self-hosted deployments. + +### Managed SaaS widgets + +```ts +const created = await client.widgets.managed.create({ + name: "Support widget", + type: "agent", + agentId: "agent-id", + allowedDomains: ["https://app.example.com"], + theme: { preset: "dark", primaryColor: "#6d28d9" }, +}); +console.log(created.widgetKey, created.embedCode); +``` + +Managed widget inputs allow presentation and supported business settings only. +The response omits provider selection and secret escalation targets. The +one-time widget key is returned at creation or rotation so the embed can be +installed. Existing `client.widgets` methods preserve the licensed deployment +contract. + ## Requirements - Node.js 20+ / Bun / modern browser diff --git a/typescript/package.json b/typescript/package.json index a734e7a..19ee4df 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -1,7 +1,7 @@ { "name": "@ignitionai/sdk", - "version": "0.3.0-rc.3", - "description": "TypeScript SDK for licensed and self-hosted IgnitionRAG deployments", + "version": "1.0.0", + "description": "TypeScript SDK for managed SaaS, licensed, and self-hosted IgnitionRAG deployments", "type": "module", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.js", @@ -51,7 +51,8 @@ "build:cjs": "tsc -p tsconfig.cjs.json", "build:cjs-pkg": "echo '{\"type\":\"commonjs\"}' > dist/cjs/package.json", "test": "bun test", - "typecheck": "tsc --noEmit && tsc -p tsconfig.generated.json", + "test:live": "bun run scripts/check-live.ts", + "typecheck": "tsc --noEmit && tsc -p tsconfig.generated.json && tsc --noEmit --strict --target ES2022 --module ES2022 --moduleResolution bundler --lib ES2022,DOM,DOM.Iterable tests/contracts.types.ts", "generate:types": "bun run scripts/generate-wire-types.ts", "verify:contract": "bun run scripts/verify-contract.ts" }, @@ -82,13 +83,13 @@ "engines": { "node": ">=20.0.0" }, + "overrides": { + "brace-expansion": "^2.1.7", + "js-yaml": "^4.3.2" + }, "devDependencies": { "@types/bun": "latest", "openapi-typescript": "^7.13.0", "typescript": "^5.3.0" - }, - "overrides": { - "brace-expansion": "^2.1.7", - "js-yaml": "^4.3.2" } } diff --git a/typescript/scripts/check-live.ts b/typescript/scripts/check-live.ts new file mode 100644 index 0000000..27aab81 --- /dev/null +++ b/typescript/scripts/check-live.ts @@ -0,0 +1,170 @@ +import { IgnitionAI, APIError, NotFoundError, ProtocolError } from "../src/index.js"; +import { PUBLIC_CONTRACT_VERSION, PUBLIC_CONTRACT_DIGEST } from "../src/contract.js"; + +type Outcome = "PASS" | "FAIL" | "NOT PROVEN"; +type Check = { name: string; outcome: Outcome; detail?: string; status?: number }; +const checks: Check[] = []; + +function record(check: Check): void { + checks.push(check); + process.stdout.write(`${JSON.stringify(check)}\n`); +} + +function object(value: unknown): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new ProtocolError("Expected an object"); + } + return value as Record; +} + +function entities(value: unknown): Array & { id: string }> { + if (!Array.isArray(value)) throw new ProtocolError("Expected an array"); + return value.map((item: unknown) => { + const entry = object(item); + if (typeof entry.id !== "string" || !entry.id) throw new ProtocolError("Missing ID"); + return { ...entry, id: entry.id }; + }); +} + +function requireFields(value: unknown, fields: Record): void { + const entry = object(value); + for (const [key, type] of Object.entries(fields)) { + const valid = type === "array" ? Array.isArray(entry[key]) : typeof entry[key] === type; + if (!valid) throw new ProtocolError("Invalid response fields"); + } +} + +async function check(name: string, call: () => Promise, validate: (value: T) => void, + allowMissing: (error: unknown) => boolean = () => false): Promise { + try { + const value = await call(); + validate(value); + record({ name, outcome: "PASS" }); + return value; + } catch (error) { + const missing = allowMissing(error); + record({ name, outcome: missing ? "NOT PROVEN" : "FAIL", + detail: missing ? "Resource unavailable" : error instanceof Error ? error.name : "UnknownError", + status: error instanceof APIError ? error.status : undefined }); + return undefined; + } +} + +async function list(name: string, call: () => Promise) { + const value = await check(name, call, entities); + if (value === undefined) return []; + const items = entities(value); + if (!items.length) record({ name: `${name}.details`, outcome: "NOT PROVEN", detail: "No fixtures" }); + return items; +} + +async function checkCollections(sdk: IgnitionAI): Promise { + const collections = await list("collections.list", () => sdk.collections.list()); + for (const [index, collection] of collections.entries()) { + const name = `collections[${index}]`; + const id = encodeURIComponent(collection.id); + await check(`${name}.get`, () => sdk.collections.get(id), value => { + requireFields(value, { id: "string", name: "string" }); + if (value.id !== collection.id) throw new ProtocolError("Wrong resource"); + }); + await check(`${name}.chunks`, () => sdk.collections.chunks(id, { limit: 1 }), value => { + requireFields(value, { chunks: "array", total: "number" }); + entities(value.chunks); + }); + await check(`${name}.stats`, () => sdk.collections.stats(id), value => { + requireFields(value, { totalChunks: "number", bySourceType: "array", byType: "array" }); + }); + await check(`${name}.insights`, () => sdk.collections.insights(id), value => { + requireFields(value, { mainTopics: "string", keyFindings: "string" }); + }, error => error instanceof NotFoundError && error.message === "Insights not yet generated"); + await check(`${name}.qualityReport`, () => sdk.collections.qualityReport(id), value => { + requireFields(value, { totalDocuments: "number" }); + }); + await check(`${name}.documents`, () => sdk.collections.documents(id), entities); + const evaluations = await list(`${name}.evaluations`, () => sdk.evaluations.list(id)); + for (const [evaluationIndex, evaluation] of evaluations.entries()) { + await check(`${name}.evaluations[${evaluationIndex}].get`, + () => sdk.evaluations.get(encodeURIComponent(evaluation.id)), value => { + requireFields(value, { id: "string", status: "string" }); + if (value.id !== evaluation.id) throw new ProtocolError("Wrong resource"); + }); + } + } +} + +async function checkAgents(sdk: IgnitionAI): Promise { + await check("agents.skills", () => sdk.agents.listSkills(), entities); + const agents = await list("agents.list", () => sdk.agents.list()); + for (const [index, agent] of agents.entries()) { + const id = encodeURIComponent(agent.id); + await check(`agents[${index}].get`, () => sdk.agents.get(id), value => { + requireFields(value, { id: "string", name: "string" }); + if (value.id !== agent.id) throw new ProtocolError("Wrong resource"); + }); + const value = await check(`agents[${index}].deepStatus`, () => sdk.deepResearch.status(id), value => { + if (value !== null) object(value); + }); + if (value === null) record({ name: `agents[${index}].deepStatus.active`, + outcome: "NOT PROVEN", detail: "No active research" }); + } +} + +async function checkWorkflows(sdk: IgnitionAI): Promise { + const workflows = await list("workflows.list", () => sdk.workflows.list()); + for (const [index, workflow] of workflows.entries()) { + const name = `workflows[${index}]`; + const id = encodeURIComponent(workflow.id); + await check(`${name}.get`, () => sdk.workflows.get(id), value => { + requireFields(value, { id: "string", name: "string" }); + requireFields(value.graph, { nodes: "array", edges: "array" }); + if (value.id !== workflow.id) throw new ProtocolError("Wrong resource"); + }); + const executions = await list(`${name}.executions`, () => sdk.workflows.listExecutions(id, { limit: 1 })); + for (const execution of executions) { + await check(`${name}.execution.get`, () => sdk.workflows.getExecution(encodeURIComponent(execution.id)), value => { + requireFields(value, { id: "string", status: "string" }); + if (value.id !== execution.id) throw new ProtocolError("Wrong resource"); + }); + } + } +} + +async function checkIsolation(sdk: IgnitionAI): Promise { + const ids = process.env.IGNITION_FORBIDDEN_COLLECTION_IDS?.split(",").filter(Boolean) ?? []; + if (!ids.length) { + record({ name: "scope.isolation", outcome: "NOT PROVEN", detail: "No foreign private fixtures supplied" }); + return; + } + for (const [index, id] of ids.entries()) { + try { + await sdk.collections.get(encodeURIComponent(id.trim())); + record({ name: `scope.isolation[${index}]`, outcome: "FAIL", detail: "Foreign private resource is readable" }); + } catch (error) { + const denied = error instanceof APIError && [403, 404].includes(error.status); + record({ name: `scope.isolation[${index}]`, outcome: denied ? "PASS" : "FAIL", + status: error instanceof APIError ? error.status : undefined }); + } + } +} + +async function main(): Promise { + const baseURL = process.env.IGNITION_BASE_URL; + if (!baseURL) throw new ProtocolError("IGNITION_BASE_URL is required"); + const sdk = IgnitionAI.fromEnv({ baseURL, maxRetries: 0, timeout: 15_000 }); + process.stdout.write(`${JSON.stringify({ sdkContract: PUBLIC_CONTRACT_VERSION, sdkDigest: PUBLIC_CONTRACT_DIGEST })}\n`); + await check("compatibility", () => sdk.compatibility.assertCompatible(), object); + await checkCollections(sdk); + await checkAgents(sdk); + await checkWorkflows(sdk); + await checkIsolation(sdk); + record({ name: "mutating-and-streaming-operations", outcome: "NOT PROVEN", detail: "Read-only diagnostic" }); + const failed = checks.filter(entry => entry.outcome === "FAIL").length; + process.stdout.write(`${JSON.stringify({ passed: checks.filter(entry => entry.outcome === "PASS").length, + failed, notProven: checks.filter(entry => entry.outcome === "NOT PROVEN").length })}\n`); + process.exitCode = failed ? 1 : 0; +} + +await main().catch(() => { + record({ name: "configuration", outcome: "FAIL", detail: "Check IGNITION_BASE_URL and IGNITION_API_KEY" }); + process.exitCode = 1; +}); diff --git a/typescript/scripts/generate-wire-types.ts b/typescript/scripts/generate-wire-types.ts index c5e8b99..a4ba85f 100644 --- a/typescript/scripts/generate-wire-types.ts +++ b/typescript/scripts/generate-wire-types.ts @@ -17,7 +17,16 @@ const outputPath = resolve( const identityOutputPath = resolve( valueAfter(process.argv, "--identity-output") ?? "src/contract.ts", ); -const previousContract = valueAfter(process.argv, "--previous-contract") ?? "2026.06"; +const pythonIdentityOutput = valueAfter(process.argv, "--python-identity-output"); +const previousContracts = process.argv.flatMap((arg, index) => { + if (arg !== "--previous-contract") return []; + const version = process.argv[index + 1]; + if (!version || !/^\d{4}\.(0[1-9]|1[0-2])$/.test(version)) { + throw new Error("--previous-contract requires a calendar contract revision"); + } + return [version]; +}); +if (previousContracts.length === 0) previousContracts.push("2026.09"); const artifact = JSON.parse(await Bun.file(resolve(contractPath)).text()) as { payload?: { @@ -34,13 +43,18 @@ if (!artifact.payload?.openapi || !artifact.payload.contractVersion) { throw new Error("The contract artifact does not contain payload.openapi"); } +if (previousContracts.some((version) => version >= artifact.payload!.contractVersion!)) { + throw new Error("--previous-contract must precede the generated contract revision"); +} +const supportedContracts = [...new Set([artifact.payload.contractVersion, ...previousContracts])]; + const ast = await openapiTS(artifact.payload.openapi, { alphabetize: true, exportType: true, immutable: true, }); const source = [ - "// Generated from the verified IgnitionRAG public contract.", + "// Generated from the canonical IgnitionRAG public contract.", "// Do not edit and do not export this module from the package root.", astToString(ast), ].join("\n"); @@ -68,11 +82,21 @@ const stableStringify = (value: unknown): string => { const digest = new Bun.CryptoHasher("sha256") .update(stableStringify(contractShape)) .digest("hex"); -const identitySource = `// Generated from the verified IgnitionRAG public contract.\n` + +const identitySource = `// Generated from the canonical IgnitionRAG public contract.\n` + `export const PUBLIC_CONTRACT_VERSION = ${JSON.stringify(artifact.payload.contractVersion)} as const;\n` + `export const PUBLIC_CONTRACT_DIGEST = ${JSON.stringify(`sha256:${digest}`)} as const;\n` + - `export const SUPPORTED_CONTRACT_VERSIONS = [${JSON.stringify(artifact.payload.contractVersion)}, ${JSON.stringify(previousContract)}] as const;\n`; + `export const SUPPORTED_CONTRACT_VERSIONS = ${JSON.stringify(supportedContracts)} as const;\n`; await mkdir(dirname(identityOutputPath), { recursive: true }); await Bun.write(identityOutputPath, identitySource); +if (pythonIdentityOutput) { + const pythonPath = resolve(pythonIdentityOutput); + const pythonSource = `\"\"\"Constants generated from the canonical IgnitionRAG public contract.\"\"\"\n\n` + + `PUBLIC_CONTRACT_VERSION = ${JSON.stringify(artifact.payload.contractVersion)}\n` + + `PUBLIC_CONTRACT_DIGEST = ${JSON.stringify(`sha256:${digest}`)}\n` + + `SUPPORTED_CONTRACT_VERSIONS = (${supportedContracts.map((version) => JSON.stringify(version)).join(", ")})\n`; + await mkdir(dirname(pythonPath), { recursive: true }); + await Bun.write(pythonPath, pythonSource); + console.log(`Generated Python public contract identity: ${pythonPath}`); +} console.log(`Generated public wire types: ${outputPath}`); console.log(`Generated public contract identity: ${identityOutputPath}`); diff --git a/typescript/scripts/verify-contract.ts b/typescript/scripts/verify-contract.ts index 3628bea..d4b15c2 100644 --- a/typescript/scripts/verify-contract.ts +++ b/typescript/scripts/verify-contract.ts @@ -1,5 +1,6 @@ import { existsSync } from "node:fs"; import { resolve } from "node:path"; +import { PUBLIC_CONTRACT_DIGEST, PUBLIC_CONTRACT_VERSION } from "../src/contract.js"; function valueAfter(argv: string[], flag: string): string | undefined { const index = argv.indexOf(flag); @@ -21,18 +22,29 @@ function decodeBase64(value: string): ArrayBuffer { return Uint8Array.from(atob(value), (character) => character.charCodeAt(0)).buffer; } -function resolvePublicFile(explicit: string | undefined, relativePath: string): string { +function resolvePublicFile(explicit: string | undefined, ...relativePaths: string[]): string { if (explicit) return resolve(explicit); - for (const candidate of [relativePath, `../${relativePath}`]) { - const absolute = resolve(candidate); - if (existsSync(absolute)) return absolute; + const roots = [resolve(import.meta.dir, ".."), resolve(import.meta.dir, "../..")]; + for (const relativePath of relativePaths) { + for (const root of roots) { + const absolute = resolve(root, relativePath); + if (existsSync(absolute)) return absolute; + } } - throw new Error(`Unable to locate ${relativePath}`); + throw new Error(`Unable to locate ${relativePaths.join(" or ")}`); } +const requireSdkIdentity = process.argv.includes("--require-sdk-identity"); +const explicitContract = valueAfter(process.argv, "--contract"); const contractPath = resolvePublicFile( - valueAfter(process.argv, "--contract"), - "contracts/2026.07/public-sdk-contract.json", + explicitContract, + `contracts/${PUBLIC_CONTRACT_VERSION}/public-sdk-contract.json`, + // Last signed artifact in this private archive. Identity 2026.11 is prepared + // but unsigned here; official signing targets IgnitionAI/sdk, not this path. + ...(requireSdkIdentity ? [] : ["contracts/2026.07/public-sdk-contract.json"]), +); +const usedPrivateFallback = !explicitContract && !contractPath.endsWith( + `/contracts/${PUBLIC_CONTRACT_VERSION}/public-sdk-contract.json`, ); const trustedKeysPath = resolvePublicFile( valueAfter(process.argv, "--trusted-keys"), @@ -46,7 +58,7 @@ if (!Number.isSafeInteger(minimumReleaseSequence) || minimumReleaseSequence < 1) } const artifact = JSON.parse(await Bun.file(contractPath).text()) as { - payload: { releaseSequence: number } & Record; + payload: { releaseSequence: number; contractVersion?: unknown } & Record; digest: string; signature: null | { algorithm: string; keyId: string; value: string }; }; @@ -87,6 +99,35 @@ const valid = await crypto.subtle.verify( ); if (!valid) throw new Error("Public contract signature mismatch"); +const verifiedVersion = typeof artifact.payload.contractVersion === "string" + ? artifact.payload.contractVersion + : "unknown"; +if (requireSdkIdentity && verifiedVersion !== PUBLIC_CONTRACT_VERSION) { + throw new Error(`Signed contract version ${verifiedVersion} does not match SDK identity ${PUBLIC_CONTRACT_VERSION}`); +} +if (verifiedVersion === PUBLIC_CONTRACT_VERSION) { + const { schemaVersion, contractVersion, manifest, openapi, protocols } = artifact.payload; + const shapeBytes = await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(stableStringify({ schemaVersion, contractVersion, manifest, openapi, protocols })), + ); + const shapeDigest = `sha256:${Buffer.from(shapeBytes).toString("hex")}`; + if (shapeDigest !== PUBLIC_CONTRACT_DIGEST) { + throw new Error("Signed contract shape does not match the generated SDK identity"); + } +} + console.log( - `Verified contract sequence ${artifact.payload.releaseSequence} with ${artifact.signature.keyId}`, + `Verified contract sequence ${artifact.payload.releaseSequence} version ${verifiedVersion} at ${contractPath} with ${artifact.signature.keyId}`, ); +if (verifiedVersion !== PUBLIC_CONTRACT_VERSION) { + if (usedPrivateFallback) { + console.log( + `Using last signed private archive ${verifiedVersion}; SDK identity ${PUBLIC_CONTRACT_VERSION} is unsigned in this tree.`, + ); + } else { + console.warn( + `Warning: verified archive version ${verifiedVersion} differs from SDK identity ${PUBLIC_CONTRACT_VERSION}`, + ); + } +} diff --git a/typescript/src/browser.ts b/typescript/src/browser.ts index fff94cf..0fe9317 100644 --- a/typescript/src/browser.ts +++ b/typescript/src/browser.ts @@ -10,6 +10,10 @@ import { DataChat } from "./resources/data-chat.js"; import { Compatibility } from "./resources/compatibility.js"; import { Workflows } from "./resources/workflows.js"; import { DeepResearch } from "./resources/deep-research.js"; +import { Widgets } from "./resources/widgets.js"; +import { Feedback } from "./resources/feedback.js"; +import { Traces } from "./resources/traces.js"; +import { RagAbTests } from "./resources/rag-ab-tests.js"; import type { ClientOptions } from "./types.js"; export type BrowserClientOptions = Omit< @@ -32,6 +36,10 @@ export class IgnitionAI extends BaseClient { readonly compatibility: Compatibility; readonly workflows: Workflows; readonly deepResearch: DeepResearch; + readonly widgets: Widgets; + readonly feedback: Feedback; + readonly traces: Traces; + readonly ragAbTests: RagAbTests; constructor(options: BrowserClientOptions) { if ("apiKey" in options) { @@ -50,6 +58,10 @@ export class IgnitionAI extends BaseClient { this.compatibility = new Compatibility(this); this.workflows = new Workflows(this); this.deepResearch = new DeepResearch(this); + this.widgets = new Widgets(this); + this.feedback = new Feedback(this); + this.traces = new Traces(this); + this.ragAbTests = new RagAbTests(this); } } diff --git a/typescript/src/client.ts b/typescript/src/client.ts index eae4e84..56de0b4 100644 --- a/typescript/src/client.ts +++ b/typescript/src/client.ts @@ -176,6 +176,7 @@ export class BaseClient { if ( retriesLeft > 0 && RETRYABLE_STATUS_CODES.has(response.status) && + body.error !== "AI_TEMPORARILY_UNAVAILABLE" && this._canRetry(method, options?.headers) ) { const delay = this._retryDelay( diff --git a/typescript/src/contract.ts b/typescript/src/contract.ts index 2dadf40..03adfa3 100644 --- a/typescript/src/contract.ts +++ b/typescript/src/contract.ts @@ -1,4 +1,4 @@ -// Generated from the verified IgnitionRAG public contract. -export const PUBLIC_CONTRACT_VERSION = "2026.07" as const; -export const PUBLIC_CONTRACT_DIGEST = "sha256:a83d9ad89dc77c3d2ab0daae07596aabe161cfe1c4e28ba4afbc500a04ed1fb5" as const; -export const SUPPORTED_CONTRACT_VERSIONS = ["2026.07", "2026.06"] as const; +// Generated from the canonical IgnitionRAG public contract. +export const PUBLIC_CONTRACT_VERSION = "2026.11" as const; +export const PUBLIC_CONTRACT_DIGEST = "sha256:37839de6724326e9d7ad949a08f95dcc2d960580d9fc2c8bad0933ce8b4ef78d" as const; +export const SUPPORTED_CONTRACT_VERSIONS = ["2026.11","2026.10","2026.09"] as const; diff --git a/typescript/src/errors.ts b/typescript/src/errors.ts index 717881c..fbf9366 100644 --- a/typescript/src/errors.ts +++ b/typescript/src/errors.ts @@ -26,6 +26,13 @@ export class ProtocolError extends IgnitionAIError { } } +export class UnsupportedCapabilityError extends ProtocolError { + constructor(readonly capability: string, readonly contractVersion: string) { + super(`Deployment contract ${contractVersion} does not support capability '${capability}'. Use a deployment that advertises this capability.`); + this.name = "UnsupportedCapabilityError"; + } +} + export class UnsupportedContractVersionError extends ProtocolError { constructor( readonly receivedVersion: string, @@ -185,6 +192,25 @@ export class InternalServerError extends APIError { } } +export class OfferingUnavailableError extends APIError { + constructor(message: string, headers: Record, status = 503) { + super(status, message, headers, "OFFERING_UNAVAILABLE"); + this.name = "OfferingUnavailableError"; + } +} + +export function isAiTemporarilyUnavailable(error: APIError): boolean { + return error.status === 503 && error.message === "AI_TEMPORARILY_UNAVAILABLE"; +} + +export function offeringUnavailable(operation: string, error: APIError): OfferingUnavailableError { + return new OfferingUnavailableError( + `${operation} is not available on this offering.`, + error.headers, + error.status, + ); +} + export class APIConnectionError extends IgnitionAIError { readonly cause?: Error; diff --git a/typescript/src/generated/public-api.ts b/typescript/src/generated/public-api.ts index 4b8bca8..27aff55 100644 --- a/typescript/src/generated/public-api.ts +++ b/typescript/src/generated/public-api.ts @@ -1,4 +1,4 @@ -// Generated from the verified IgnitionRAG public contract. +// Generated from the canonical IgnitionRAG public contract. // Do not edit and do not export this module from the package root. export type paths = { readonly "/api/agents": { @@ -234,7 +234,7 @@ export type paths = { }; /** * List all collections - * @description Lists organization's collections. Pro+ users can include shared/public collections with includeShared=true or includePublic=true. + * @description Lists organization collections and optionally includes shared or public collections. */ readonly get: operations["collections.list"]; readonly put?: never; @@ -266,6 +266,23 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; + readonly "/api/collections/:collectionId/rag-config/test": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly get?: never; + readonly put?: never; + /** Run A/B test comparing two RAG configurations */ + readonly post: operations["ragExperiments.runAbTest"]; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; readonly "/api/collections/:id": { readonly parameters: { readonly query?: never; @@ -440,24 +457,23 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; - readonly "/api/data-chat": { + readonly "/api/evaluations/:evaluationId": { readonly parameters: { readonly query?: never; readonly header?: never; readonly path?: never; readonly cookie?: never; }; - readonly get?: never; + readonly get: operations["evaluations.get"]; readonly put?: never; - /** Chat across selected collections and live data */ - readonly post: operations["dataChat.send"]; + readonly post?: never; readonly delete?: never; readonly options?: never; readonly head?: never; readonly patch?: never; readonly trace?: never; }; - readonly "/api/data-chat/precheck": { + readonly "/api/feedback": { readonly parameters: { readonly query?: never; readonly header?: never; @@ -466,24 +482,11 @@ export type paths = { }; readonly get?: never; readonly put?: never; - /** Precheck selected collection and connector compatibility */ - readonly post: operations["dataChat.precheck"]; - readonly delete?: never; - readonly options?: never; - readonly head?: never; - readonly patch?: never; - readonly trace?: never; - }; - readonly "/api/evaluations/:evaluationId": { - readonly parameters: { - readonly query?: never; - readonly header?: never; - readonly path?: never; - readonly cookie?: never; - }; - readonly get: operations["evaluations.get"]; - readonly put?: never; - readonly post?: never; + /** + * Submit feedback + * @description Submit a bug report, feature request, or general feedback + */ + readonly post: operations["feedback.submit"]; readonly delete?: never; readonly options?: never; readonly head?: never; @@ -640,8 +643,8 @@ export type paths = { readonly get?: never; readonly put?: never; /** - * Ingest file (PDF, DOCX, etc.) - * @description Uploads and indexes a file. Set enableMultimodal=true to use Jina CLIP v2 for cross-modal search (Pro+ plans only). + * Ingest file synchronously (license only) + * @description Uploads and indexes a file in the current request. SaaS rejects this route with 503; use POST /api/ingest/file/async. Set enableMultimodal=true to use Jina CLIP v2 for cross-modal search when allowed by administrator policy. */ readonly post: operations["ingestion.file"]; readonly delete?: never; @@ -660,8 +663,8 @@ export type paths = { readonly get?: never; readonly put?: never; /** - * Ingest file with progress streaming - * @description Uploads a file and returns immediately with a jobId. Use the SSE endpoint to track progress. Set enableMultimodal=true for cross-modal search (Pro+ plans only). + * Ingest file (PDF, DOCX, etc.) + * @description Uploads a file and returns immediately with a jobId. This is the supported file ingestion route in SaaS. Use the SSE endpoint to track progress. Set enableMultimodal=true for cross-modal search when allowed by administrator policy. */ readonly post: operations["ingestion.fileAsync"]; readonly delete?: never; @@ -670,6 +673,74 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; + readonly "/api/ingest/jobs": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** List durable ingestion jobs for a collection */ + readonly get: operations["ingestion.listJobs"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; + readonly "/api/ingest/jobs/{jobId}": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** Get durable ingestion job state */ + readonly get: operations["ingestion.getJob"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; + readonly "/api/ingest/jobs/{jobId}/cancel": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly get?: never; + readonly put?: never; + /** Cancel a durable ingestion job */ + readonly post: operations["ingestion.cancelJob"]; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; + readonly "/api/ingest/jobs/{jobId}/stream": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** Stream durable ingestion job state */ + readonly get: operations["ingestion.streamJob"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; readonly "/api/ingest/url": { readonly parameters: { readonly query?: never; @@ -724,6 +795,74 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; + readonly "/api/traces": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** List scoped traces */ + readonly get: operations["observability.listTraces"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; + readonly "/api/traces/{id}": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** Get a scoped trace */ + readonly get: operations["observability.getTrace"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; + readonly "/api/traces/export": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** Export scoped traces */ + readonly get: operations["observability.exportTraces"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; + readonly "/api/traces/metrics": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** Get scoped trace metrics */ + readonly get: operations["observability.getTraceMetrics"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; readonly "/api/workflows": { readonly parameters: { readonly query?: never; @@ -843,6 +982,174 @@ export type paths = { export type webhooks = Record; export type components = { schemas: { + readonly ABTestConfig: { + readonly configA: components["schemas"]["RAGConfigInput"]; + readonly configB: components["schemas"]["RAGConfigInput"]; + /** @default false */ + readonly evaluateQuality: boolean; + /** @example What is machine learning? */ + readonly testQuery: string; + }; + readonly ABTestResult: { + readonly comparison: { + /** @enum {string} */ + readonly qualityConfidence?: "high" | "medium" | "low"; + readonly qualityDimensions?: { + readonly clarity: { + readonly reasoning: string; + /** @enum {string} */ + readonly winner: "A" | "B" | "tie"; + }; + readonly completeness: { + readonly reasoning: string; + /** @enum {string} */ + readonly winner: "A" | "B" | "tie"; + }; + readonly faithfulness: { + readonly reasoning: string; + /** @enum {string} */ + readonly winner: "A" | "B" | "tie"; + }; + readonly relevance: { + readonly reasoning: string; + /** @enum {string} */ + readonly winner: "A" | "B" | "tie"; + }; + }; + readonly qualityReasoning?: string; + /** @enum {string} */ + readonly qualityWinner?: "A" | "B" | "tie"; + readonly recommendation: string; + readonly resultOverlap: number; + readonly speedDifferenceMs: number; + /** @enum {string} */ + readonly speedWinner: "A" | "B" | "tie"; + }; + readonly configA: { + readonly config: { + readonly features: { + readonly citations: boolean; + readonly contextualRetrieval: boolean; + readonly dynamicFeatureSelection: boolean; + readonly hybridSearch: boolean; + readonly hyde: boolean; + readonly multiQuery: boolean; + readonly parallelEnhancement: boolean; + readonly queryExpansion: boolean; + readonly queryRewriting: boolean; + readonly reranking: boolean; + readonly selfQuery: boolean; + }; + readonly hybridSearch: { + readonly alpha: number; + readonly bm25: { + readonly b: number; + readonly k1: number; + }; + readonly rrf: { + readonly k: number; + }; + }; + readonly llm: { + /** @enum {string} */ + readonly citationFormat: "brackets" | "footnote" | "inline"; + }; + readonly reranking: { + /** @enum {string} */ + readonly provider: "jina" | "llm"; + readonly topN: number; + }; + readonly retrieval: { + readonly topK: number; + }; + /** @enum {number} */ + readonly version: 1; + }; + readonly featuresUsed: readonly string[]; + readonly metrics: { + readonly queryEnhancementMs: number; + readonly rerankMs: number; + readonly resultsCount: number; + readonly searchMs: number; + readonly totalTimeMs: number; + }; + readonly qualityScores?: { + readonly clarity: number; + readonly completeness: number; + readonly faithfulness: number; + readonly overall: number; + readonly relevance: number; + }; + readonly response?: string; + readonly topResults: readonly { + readonly id: string; + readonly score: number; + readonly title?: string; + }[]; + }; + readonly configB: { + readonly config: { + readonly features: { + readonly citations: boolean; + readonly contextualRetrieval: boolean; + readonly dynamicFeatureSelection: boolean; + readonly hybridSearch: boolean; + readonly hyde: boolean; + readonly multiQuery: boolean; + readonly parallelEnhancement: boolean; + readonly queryExpansion: boolean; + readonly queryRewriting: boolean; + readonly reranking: boolean; + readonly selfQuery: boolean; + }; + readonly hybridSearch: { + readonly alpha: number; + readonly bm25: { + readonly b: number; + readonly k1: number; + }; + readonly rrf: { + readonly k: number; + }; + }; + readonly llm: { + /** @enum {string} */ + readonly citationFormat: "brackets" | "footnote" | "inline"; + }; + readonly reranking: { + /** @enum {string} */ + readonly provider: "jina" | "llm"; + readonly topN: number; + }; + readonly retrieval: { + readonly topK: number; + }; + /** @enum {number} */ + readonly version: 1; + }; + readonly featuresUsed: readonly string[]; + readonly metrics: { + readonly queryEnhancementMs: number; + readonly rerankMs: number; + readonly resultsCount: number; + readonly searchMs: number; + readonly totalTimeMs: number; + }; + readonly qualityScores?: { + readonly clarity: number; + readonly completeness: number; + readonly faithfulness: number; + readonly overall: number; + readonly relevance: number; + }; + readonly response?: string; + readonly topResults: readonly { + readonly id: string; + readonly score: number; + readonly title?: string; + }[]; + }; + }; readonly Agent: { readonly collectionId: string | null; readonly collectionName?: string | null; @@ -856,6 +1163,7 @@ export type components = { readonly id: string; readonly instructions: string | null; readonly isActive: boolean; + readonly isDefault: boolean; readonly llmConfigId: string | null; readonly maxTokens: number; readonly mcpServers: readonly components["schemas"]["McpServer"][] | null; @@ -863,6 +1171,17 @@ export type components = { readonly name: string; readonly openWebuiEnabled: boolean; readonly resources: readonly components["schemas"]["AgentResource"][]; + /** Format: uuid */ + readonly runtimeConnectionId: string | null; + /** @enum {string} */ + readonly runtimeKind: "byok_api" | "cli_runtime" | "ignis"; + readonly runtimePreferences: { + readonly mode?: string | null; + readonly model?: string | null; + readonly reasoningLevel?: string | null; + } | null; + /** Format: uuid */ + readonly runtimeProfileId: string | null; readonly scoreThreshold: number; readonly skillIds: readonly string[]; readonly subAgentIds: readonly string[] | null; @@ -900,13 +1219,16 @@ export type components = { /** @default 0 */ readonly priority: number; /** @enum {string} */ - readonly type: "collection" | "data_connector"; + readonly type: "collection"; }; readonly AgentSkill: { readonly builtinTools: readonly components["schemas"]["BuiltinToolConfig"][] | null; + readonly builtinVersion?: string; readonly constraints: string | null; + readonly contentHash?: string; readonly createdAt: string; readonly createdByUserId: string | null; + readonly currentVersion?: number; readonly description: string | null; readonly examples: readonly components["schemas"]["AgentSkillExample"][] | null; /** Format: uuid */ @@ -914,6 +1236,9 @@ export type components = { readonly instructions: string | null; readonly mcpServerRefs: readonly string[] | null; readonly name: string; + /** @enum {string} */ + readonly origin?: "organization" | "builtin"; + readonly readOnly?: boolean; readonly status: components["schemas"]["AgentSkillStatus"]; readonly updatedAt: string; readonly workflowToolRefs: readonly string[] | null; @@ -935,6 +1260,7 @@ export type components = { readonly resources?: readonly components["schemas"]["ResourceAttachment"][]; }; readonly ChatErrorResponse: { + readonly code?: string; readonly error: string; }; readonly ChatRequest: { @@ -944,6 +1270,7 @@ export type components = { /** @default true */ readonly includeImages: boolean; readonly llmConfigId?: string; + readonly maximumMilliCredits?: string; readonly query: string; }; readonly ChatResponse: { @@ -959,6 +1286,16 @@ export type components = { readonly promptTokens: number; }; }; + readonly ChatValidationError: { + /** @enum {string} */ + readonly code: "VALIDATION_ERROR"; + readonly details: readonly { + readonly field: string; + readonly message: string; + readonly path: readonly (string | number)[]; + }[]; + readonly error: string; + }; readonly Chunk: { readonly blobPath?: string; readonly chunkIndex?: number; @@ -993,6 +1330,14 @@ export type components = { readonly total: number; }; readonly Collection: { + readonly accessPolicy?: { + /** @enum {string} */ + readonly mode: "inherit"; + } | { + /** @enum {string} */ + readonly mode: "restricted"; + readonly roleIds: readonly string[]; + } | unknown; /** * @description How the caller can access this collection. Public/shared collections may be read-only for consumers. * @enum {string} @@ -1017,6 +1362,7 @@ export type components = { readonly isReadOnly?: boolean; /** @description Whether this is an admin-managed public collection */ readonly isSystemCollection?: boolean; + readonly lastSyncedAt?: string | null; readonly name: string; /** @description Owning organization id when this response represents a shared/public collection consumed by another scope. */ readonly publisherOrgId?: string | null; @@ -1025,6 +1371,15 @@ export type components = { * @enum {string|null} */ readonly requiredPlanId?: "pro" | "scale" | "enterprise" | null; + readonly servedSource?: { + readonly activatedAt: string | null; + /** @enum {boolean} */ + readonly officialCorpusQualified: false; + readonly sourceRevision: string | null; + readonly sourceTimestamp: string | null; + /** @enum {string} */ + readonly status: "verified_receipt" | "unknown"; + }; /** @description URL-safe identifier for public collections (e.g., 'code-du-travail'). Unique across all public collections. */ readonly slug?: string | null; /** @description Source identifier for public collections (e.g., 'legifrance', 'insee-sirene') */ @@ -1037,6 +1392,14 @@ export type components = { readonly visibility: "private" | "shared" | "public"; }; readonly CollectionDocument: { + readonly accessPolicy?: { + /** @enum {string} */ + readonly mode: "inherit"; + } | { + /** @enum {string} */ + readonly mode: "restricted"; + readonly roleIds: readonly string[]; + } | unknown; readonly chunksCount: number; readonly createdAt: string; readonly embeddingModel: string | null; @@ -1045,6 +1408,15 @@ export type components = { readonly id: string; readonly imagesCount: number; readonly ingestionReport: components["schemas"]["CollectionDocumentIngestionReport"]; + readonly processingSummary?: { + readonly hasWarnings: boolean; + readonly imagesDetected: number; + readonly imagesIndexed: number; + readonly pageCount?: number; + readonly pagesReadByOcr: number; + readonly tablesDetected: number; + readonly unreadablePages: number; + } | null; readonly sourceType: string; readonly sourceUrl: string | null; readonly storageBytes: number; @@ -1131,16 +1503,44 @@ export type components = { readonly success: boolean; }; readonly CrawlSelectedPagesRequest: { + readonly chunkingConfiguration?: { + /** @default false */ + readonly includeBreadcrumb: boolean; + /** @default 512 */ + readonly maxTokens: number; + /** @default 80 */ + readonly minTokens: number; + readonly overlapChars?: number; + /** + * @default default + * @enum {string} + */ + readonly strategy: "default" | "legal-article" | "regulatory-section" | "csv-row-grouped" | "email-thread" | "markdown-heading"; + }; readonly collectionId: string; - /** @description Enable multimodal embeddings (Jina CLIP v2). Requires Pro plan or higher. */ + /** @description Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy. */ readonly enableMultimodal?: boolean; readonly urls: readonly string[]; }; readonly CrawlSiteRequest: { + readonly chunkingConfiguration?: { + /** @default false */ + readonly includeBreadcrumb: boolean; + /** @default 512 */ + readonly maxTokens: number; + /** @default 80 */ + readonly minTokens: number; + readonly overlapChars?: number; + /** + * @default default + * @enum {string} + */ + readonly strategy: "default" | "legal-article" | "regulatory-section" | "csv-row-grouped" | "email-thread" | "markdown-heading"; + }; /** @example coll_123 */ readonly collectionId: string; /** - * @description Enable multimodal embeddings (Jina CLIP v2). Requires Pro plan or higher. + * @description Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy. * @example false */ readonly enableMultimodal?: boolean; @@ -1176,11 +1576,9 @@ export type components = { readonly instructions?: string; /** Format: uuid */ readonly llmConfigId?: string | null; - /** @default 2048 */ - readonly maxTokens: number; + readonly maxTokens?: number; readonly mcpServers?: readonly components["schemas"]["McpServer"][]; - /** @default gpt-4.1-mini */ - readonly model: string; + readonly model?: string; /** @example Support Assistant */ readonly name: string; /** @default false */ @@ -1191,18 +1589,29 @@ export type components = { /** @default 0 */ readonly priority: number; /** @enum {string} */ - readonly type: "collection" | "data_connector"; + readonly type: "collection"; }[]; - /** @default 0 */ - readonly scoreThreshold: number; + /** Format: uuid */ + readonly runtimeConnectionId?: string | null; + /** + * @default byok_api + * @enum {string} + */ + readonly runtimeKind: "byok_api"; + readonly runtimePreferences?: { + readonly mode?: string | null; + readonly model?: string | null; + readonly reasoningLevel?: string | null; + } | null; + /** Format: uuid */ + readonly runtimeProfileId?: string | null; + readonly scoreThreshold?: number; /** @default [] */ readonly skillIds: readonly string[]; readonly subAgentIds?: readonly string[]; readonly systemPrompt?: string; - /** @default 70 */ - readonly temperature: number; - /** @default 5 */ - readonly topK: number; + readonly temperature?: number; + readonly topK?: number; /** @default [] */ readonly workflowToolIds: readonly string[]; }; @@ -1222,6 +1631,14 @@ export type components = { readonly workflowToolRefs: readonly string[]; }; readonly CreateCollectionRequest: { + readonly accessPolicy?: { + /** @enum {string} */ + readonly mode: "inherit"; + } | { + /** @enum {string} */ + readonly mode: "restricted"; + readonly roleIds: readonly string[]; + }; /** @example Product documentation */ readonly description?: string; /** @description Optional embedding config ID to override the org default. Must reference a valid embedding config owned by this org/user. */ @@ -1245,7 +1662,7 @@ export type components = { */ readonly sourceDataset?: string; /** - * @description Collection visibility. Only admin users can set 'shared' or 'public'. Public collections require Pro+ plan. + * @description Must be omitted or 'private'. Public or shared create is rejected; publish with PATCH /api/collections/:id/visibility. * @default private * @example private * @enum {string} @@ -1255,6 +1672,7 @@ export type components = { readonly CreatedEvaluation: { readonly collectionId: string; readonly createdAt: string; + readonly error: string | null; readonly id: string; readonly notifyEmail: string | null; readonly numQuestions: number; @@ -1263,14 +1681,23 @@ export type components = { }; readonly CreateEvaluationRequest: { readonly goldenSet?: readonly { + readonly category?: string; readonly expectedAnswer?: string; + /** @enum {string} */ + readonly expectedBehavior?: "answer" | "abstain" | "clarify"; readonly expectedKeywords?: readonly string[]; + readonly expectedSourceUrls?: readonly string[]; + readonly id?: string; + readonly locale?: string; readonly query: string; + /** @enum {string} */ + readonly reviewStatus?: "pending_human_review" | "approved"; }[]; readonly inheritFromEvaluationId?: string; /** Format: email */ readonly notifyEmail?: string; readonly numQuestions?: number; + /** @description Optional licensed-mode pipeline override; managed SaaS requests must omit it. */ readonly ragConfigOverride?: { readonly [key: string]: unknown; }; @@ -1314,6 +1741,7 @@ export type components = { readonly zoom: number; }; }; + readonly isActive?: boolean; readonly name: string; readonly variables?: readonly { readonly defaultValue?: unknown; @@ -1359,6 +1787,7 @@ export type components = { readonly status?: number; }; readonly ErrorResponse: { + readonly code?: string; readonly error: string; readonly success: boolean; }; @@ -1410,6 +1839,9 @@ export type components = { readonly input?: { readonly [key: string]: unknown; }; + readonly maximumMilliCredits?: string; + /** Format: uuid */ + readonly requestId?: string; }; readonly Execution: { readonly completedAt: string | null; @@ -1434,6 +1866,32 @@ export type components = { /** @enum {string} */ readonly status: "pending" | "running" | "pending_approval" | "completed" | "failed" | "cancelled"; }; + readonly FaithfulnessConfigSchema: { + readonly enabled?: boolean; + readonly minSupport?: number; + /** @enum {string} */ + readonly policy?: "report" | "qualify" | "remove" | "abstain"; + }; + readonly FeedbackError: { + readonly error: string; + }; + readonly FeedbackRequest: { + /** + * @description Feedback message content + * @example The chat feature crashes when I send a long message. + */ + readonly message: string; + /** + * @description Type of feedback + * @example bug + * @enum {string} + */ + readonly type: "bug" | "feature" | "other"; + }; + readonly FeedbackSuccess: { + readonly message: string; + readonly success: boolean; + }; readonly FilterDefinition: { readonly field: string; /** @enum {string} */ @@ -1444,10 +1902,7 @@ export type components = { }; }; readonly GenerateAgentRequest: { - /** - * Format: uuid - * @description Optional collection ID for RAG capabilities - */ + /** @description Optional collection ID for RAG capabilities */ readonly collectionId?: string | null; /** @example I need an assistant that helps customers with technical support for a SaaS product. It should be friendly, professional, and know how to troubleshoot common issues. */ readonly description: string; @@ -1457,21 +1912,25 @@ export type components = { * @example en */ readonly language: string; + /** Format: uuid */ + readonly requestId?: string; }; - readonly GeneratedAgentConfig: { - readonly description: string | null; - readonly instructions: string | null; + readonly GeneratedAgentConfig: components["schemas"]["GeneratedBusinessAgentConfig"] & { readonly maxTokens: number; readonly model: string; - readonly name: string; readonly scoreThreshold: number; + readonly temperature: number; + readonly topK: number; + }; + readonly GeneratedBusinessAgentConfig: { + readonly description: string | null; + readonly instructions: string | null; + readonly name: string; readonly suggestedTools?: readonly { readonly description: string; readonly name: string; }[]; readonly systemPrompt: string; - readonly temperature: number; - readonly topK: number; }; readonly HybridSearchConfig: { readonly alpha?: number; @@ -1492,6 +1951,20 @@ export type components = { readonly source: string; }; readonly IngestDatasetRequest: { + readonly chunkingConfiguration?: { + /** @default false */ + readonly includeBreadcrumb: boolean; + /** @default 512 */ + readonly maxTokens: number; + /** @default 80 */ + readonly minTokens: number; + readonly overlapChars?: number; + /** + * @default default + * @enum {string} + */ + readonly strategy: "default" | "legal-article" | "regulatory-section" | "csv-row-grouped" | "email-thread" | "markdown-heading"; + }; /** @example coll_123 */ readonly collectionId: string; /** @@ -1505,7 +1978,7 @@ export type components = { */ readonly datasetId: string; /** - * @description Enable multimodal embeddings (Jina CLIP v2). Extracts and indexes images from image columns. Requires Pro plan or higher. + * @description Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy. Extracts and indexes images from image columns. * @example false */ readonly enableMultimodal?: boolean; @@ -1521,6 +1994,20 @@ export type components = { readonly split?: string; }; readonly IngestDocumentRequest: { + readonly chunkingConfiguration?: { + /** @default false */ + readonly includeBreadcrumb: boolean; + /** @default 512 */ + readonly maxTokens: number; + /** @default 80 */ + readonly minTokens: number; + readonly overlapChars?: number; + /** + * @default default + * @enum {string} + */ + readonly strategy: "default" | "legal-article" | "regulatory-section" | "csv-row-grouped" | "email-thread" | "markdown-heading"; + }; /** @example coll_123 */ readonly collectionId: string; /** @example Document content here... */ @@ -1538,10 +2025,24 @@ export type components = { readonly success: boolean; }; readonly IngestUrlRequest: { + readonly chunkingConfiguration?: { + /** @default false */ + readonly includeBreadcrumb: boolean; + /** @default 512 */ + readonly maxTokens: number; + /** @default 80 */ + readonly minTokens: number; + readonly overlapChars?: number; + /** + * @default default + * @enum {string} + */ + readonly strategy: "default" | "legal-article" | "regulatory-section" | "csv-row-grouped" | "email-thread" | "markdown-heading"; + }; /** @example coll_123 */ readonly collectionId: string; /** - * @description Enable multimodal embeddings (Jina CLIP v2). Requires Pro plan or higher. + * @description Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy. * @example false */ readonly enableMultimodal?: boolean; @@ -1604,18 +2105,37 @@ export type components = { readonly description: string | null; readonly documentCount: number; readonly id: string; + /** Format: date-time */ + readonly lastSyncedAt: string | null; readonly name: string; readonly publisher: components["schemas"]["PublicCollectionPublisher"]; /** @enum {string|null} */ readonly requiredPlanId: "pro" | "scale" | "enterprise" | null; + readonly servedSource?: { + readonly activatedAt: string | null; + /** @enum {boolean} */ + readonly officialCorpusQualified: false; + readonly sourceRevision: string | null; + readonly sourceTimestamp: string | null; + /** @enum {string} */ + readonly status: "verified_receipt" | "unknown"; + }; readonly slug: string; + readonly sourceDataset: string | null; /** Format: date-time */ readonly updatedAt: string; }; + readonly RAGCacheConfigSchema: { + readonly enabled?: boolean; + readonly maxSize?: number; + readonly ttlSeconds?: number; + }; readonly RAGConfigErrorResponse: { readonly error: string; }; readonly RAGConfigInput: { + readonly cache?: components["schemas"]["RAGCacheConfigSchema"]; + readonly faithfulness?: components["schemas"]["FaithfulnessConfigSchema"]; readonly features?: components["schemas"]["RAGFeatures"]; readonly hybridSearch?: components["schemas"]["HybridSearchConfig"]; readonly llm?: components["schemas"]["LLMConfigSchema"]; @@ -1623,6 +2143,17 @@ export type components = { readonly retrieval?: components["schemas"]["RetrievalConfig"]; }; readonly RAGConfigResponse: { + readonly cache: { + readonly enabled: boolean; + readonly maxSize: number; + readonly ttlSeconds: number; + }; + readonly faithfulness: { + readonly enabled: boolean; + readonly minSupport: number; + /** @enum {string} */ + readonly policy: "report" | "qualify" | "remove" | "abstain"; + }; readonly features: { readonly citations: boolean; readonly contextualRetrieval: boolean; @@ -1737,8 +2268,22 @@ export type components = { readonly sourceType: string; }; readonly StreamingCrawlRequest: { + readonly chunkingConfiguration?: { + /** @default false */ + readonly includeBreadcrumb: boolean; + /** @default 512 */ + readonly maxTokens: number; + /** @default 80 */ + readonly minTokens: number; + readonly overlapChars?: number; + /** + * @default default + * @enum {string} + */ + readonly strategy: "default" | "legal-article" | "regulatory-section" | "csv-row-grouped" | "email-thread" | "markdown-heading"; + }; readonly collectionId: string; - /** @description Enable multimodal embeddings (Jina CLIP v2). Requires Pro plan or higher. */ + /** @description Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy. */ readonly enableMultimodal?: boolean; readonly maxDepth?: number; readonly maxPages?: number; @@ -1746,6 +2291,20 @@ export type components = { readonly url: string; }; readonly StreamingDatasetRequest: { + readonly chunkingConfiguration?: { + /** @default false */ + readonly includeBreadcrumb: boolean; + /** @default 512 */ + readonly maxTokens: number; + /** @default 80 */ + readonly minTokens: number; + readonly overlapChars?: number; + /** + * @default default + * @enum {string} + */ + readonly strategy: "default" | "legal-article" | "regulatory-section" | "csv-row-grouped" | "email-thread" | "markdown-heading"; + }; readonly collectionId: string; readonly config?: string; readonly datasetId: string; @@ -1753,6 +2312,7 @@ export type components = { readonly split?: string; }; readonly StreamingErrorResponse: { + readonly code?: string; readonly error: string; readonly success: boolean; }; @@ -1794,8 +2354,19 @@ export type components = { /** @default 0 */ readonly priority: number; /** @enum {string} */ - readonly type: "collection" | "data_connector"; + readonly type: "collection"; }[]; + /** Format: uuid */ + readonly runtimeConnectionId?: string | null; + /** @enum {string} */ + readonly runtimeKind?: "byok_api"; + readonly runtimePreferences?: { + readonly mode?: string | null; + readonly model?: string | null; + readonly reasoningLevel?: string | null; + } | null; + /** Format: uuid */ + readonly runtimeProfileId?: string | null; readonly scoreThreshold?: number; readonly skillIds?: readonly string[]; readonly subAgentIds?: readonly string[] | null; @@ -1878,6 +2449,7 @@ export type components = { readonly ValidationResult: { readonly errors: readonly { readonly edgeId?: string; + readonly label?: string; readonly message: string; readonly nodeId?: string; readonly type: string; @@ -2238,6 +2810,15 @@ export interface operations { readonly "text/event-stream": string; }; }; + /** @description Owner thread belongs to another actor */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["Error"]; + }; + }; /** @description Agent not found */ readonly 404: { headers: { @@ -2268,7 +2849,7 @@ export interface operations { readonly [name: string]: unknown; }; content: { - readonly "application/json": components["schemas"]["GeneratedAgentConfig"]; + readonly "application/json": components["schemas"]["GeneratedBusinessAgentConfig"] | components["schemas"]["GeneratedAgentConfig"]; }; }; /** @description Invalid request */ @@ -2277,7 +2858,37 @@ export interface operations { readonly [name: string]: unknown; }; content: { - readonly "application/json": components["schemas"]["Error"]; + readonly "application/json": { + readonly code?: string; + readonly error: string; + readonly status?: number; + }; + }; + }; + /** @description Insufficient credits */ + readonly 402: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly code?: string; + readonly error: string; + readonly status?: number; + }; + }; + }; + /** @description Request ID conflict or execution already dispatched */ + readonly 409: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly code?: string; + readonly error: string; + readonly status?: number; + }; }; }; /** @description Generation failed */ @@ -2286,7 +2897,37 @@ export interface operations { readonly [name: string]: unknown; }; content: { - readonly "application/json": components["schemas"]["Error"]; + readonly "application/json": { + readonly code?: string; + readonly error: string; + readonly status?: number; + }; + }; + }; + /** @description LLM returned invalid JSON */ + readonly 502: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly code?: string; + readonly error: string; + readonly status?: number; + }; + }; + }; + /** @description Managed generation is unavailable */ + readonly 503: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly code?: string; + readonly error: string; + readonly status?: number; + }; }; }; }; @@ -2443,6 +3084,33 @@ export interface operations { readonly "application/json": components["schemas"]["ChatResponse"]; }; }; + /** @description Invalid request body */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ChatValidationError"]; + }; + }; + /** @description Credits unavailable or organization subscription required before execution/stream admission */ + readonly 402: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ChatErrorResponse"]; + }; + }; + /** @description Collection access denied */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ChatErrorResponse"]; + }; + }; /** @description Collection not found */ readonly 404: { headers: { @@ -2452,6 +3120,15 @@ export interface operations { readonly "application/json": components["schemas"]["ChatErrorResponse"]; }; }; + /** @description Credits are held by another in-flight request */ + readonly 409: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ChatErrorResponse"]; + }; + }; /** @description Chat failed */ readonly 500: { headers: { @@ -2476,13 +3153,31 @@ export interface operations { }; }; readonly responses: { - /** @description SSE stream */ + /** @description SSE stream; admission failures other than a zero credit balance emit an error event with a public business code, including SUBSCRIPTION_REQUIRED */ readonly 200: { headers: { readonly [name: string]: unknown; }; content?: never; }; + /** @description Invalid request body */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ChatValidationError"]; + }; + }; + /** @description Credits unavailable before stream admission */ + readonly 402: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ChatErrorResponse"]; + }; + }; /** @description Collection not found */ readonly 404: { headers: { @@ -2507,13 +3202,31 @@ export interface operations { }; }; readonly responses: { - /** @description SSE stream with stage, enhancement, sources, chunk, and metrics events */ + /** @description SSE stream with stage, enhancement, sources, chunk, metrics and error events; admission failures other than a zero credit balance expose a public business code, including SUBSCRIPTION_REQUIRED */ readonly 200: { headers: { readonly [name: string]: unknown; }; content?: never; }; + /** @description Invalid request body */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ChatValidationError"]; + }; + }; + /** @description Credits unavailable before stream admission */ + readonly 402: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ChatErrorResponse"]; + }; + }; /** @description Collection not found */ readonly 404: { headers: { @@ -2528,9 +3241,9 @@ export interface operations { readonly "collections.list": { readonly parameters: { readonly query?: { - /** @description Set to 'true' to include public collections (Pro+ plans only) */ + /** @description Set to 'true' to include public collections */ readonly includePublic?: string; - /** @description Set to 'true' to include shared collections (Pro+ plans only) */ + /** @description Set to 'true' to include shared collections */ readonly includeShared?: string; }; readonly header?: never; @@ -2572,7 +3285,7 @@ export interface operations { readonly "application/json": components["schemas"]["Collection"]; }; }; - /** @description Invalid request or collection already exists */ + /** @description Invalid request, duplicate name, or public/shared create (use PATCH /api/collections/:id/visibility) */ readonly 400: { headers: { readonly [name: string]: unknown; @@ -2627,6 +3340,50 @@ export interface operations { }; }; }; + readonly "ragExperiments.runAbTest": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path: { + readonly collectionId: string; + }; + readonly cookie?: never; + }; + readonly requestBody?: { + readonly content: { + readonly "application/json": components["schemas"]["ABTestConfig"]; + }; + }; + readonly responses: { + /** @description A/B test results */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ABTestResult"]; + }; + }; + /** @description Invalid test configuration */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["RAGConfigErrorResponse"]; + }; + }; + /** @description Collection not found */ + readonly 404: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["RAGConfigErrorResponse"]; + }; + }; + }; + }; readonly "collections.get": { readonly parameters: { readonly query?: never; @@ -2699,6 +3456,24 @@ export interface operations { readonly "application/json": components["schemas"]["Error"]; }; }; + /** @description Deletion is blocked: unresolved write, active fence, managed collection (MANAGED_COLLECTION_READ_ONLY), or platform-linked collection (PLATFORM_COLLECTION_DELETE_FORBIDDEN) — superadmin en session interactive uniquement */ + readonly 409: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Collection storage or vector deletion could not be verified */ + readonly 503: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["Error"]; + }; + }; }; }; readonly "collections.update": { @@ -3060,59 +3835,38 @@ export interface operations { }; }; }; - readonly "dataChat.send": { + readonly "evaluations.get": { readonly parameters: { readonly query?: never; readonly header?: never; - readonly path?: never; - readonly cookie?: never; - }; - readonly requestBody?: { - readonly content: { - readonly "application/json": { - readonly [key: string]: unknown; - }; + readonly path: { + readonly evaluationId: string; }; + readonly cookie?: never; }; + readonly requestBody?: never; readonly responses: { - /** @description Successful response */ + /** @description Full evaluation detail including per-question results */ readonly 200: { headers: { readonly [name: string]: unknown; }; content: { - readonly "application/json": { - readonly [key: string]: unknown; - }; - }; - }; - /** @description Invalid request */ - readonly 400: { - headers: { - readonly [name: string]: unknown; - }; - content: { - readonly "application/json": { - readonly code?: string; - readonly error: string; - }; + readonly "application/json": components["schemas"]["EvaluationDetail"]; }; }; - /** @description Forbidden, policy denied, or rollout flag disabled */ - readonly 403: { + /** @description Evaluation not found in the active scope */ + readonly 404: { headers: { readonly [name: string]: unknown; }; content: { - readonly "application/json": { - readonly code?: string; - readonly error: string; - }; + readonly "application/json": components["schemas"]["EvaluationDetailError"]; }; }; }; }; - readonly "dataChat.precheck": { + readonly "feedback.submit": { readonly parameters: { readonly query?: never; readonly header?: never; @@ -3121,21 +3875,17 @@ export interface operations { }; readonly requestBody?: { readonly content: { - readonly "application/json": { - readonly [key: string]: unknown; - }; + readonly "application/json": components["schemas"]["FeedbackRequest"]; }; }; readonly responses: { - /** @description Successful response */ + /** @description Feedback submitted successfully */ readonly 200: { headers: { readonly [name: string]: unknown; }; content: { - readonly "application/json": { - readonly [key: string]: unknown; - }; + readonly "application/json": components["schemas"]["FeedbackSuccess"]; }; }; /** @description Invalid request */ @@ -3144,58 +3894,63 @@ export interface operations { readonly [name: string]: unknown; }; content: { - readonly "application/json": { - readonly code?: string; - readonly error: string; - }; + readonly "application/json": components["schemas"]["FeedbackError"]; }; }; - /** @description Forbidden, policy denied, or rollout flag disabled */ - readonly 403: { + /** @description Failed to send feedback */ + readonly 500: { headers: { readonly [name: string]: unknown; }; content: { - readonly "application/json": { - readonly code?: string; - readonly error: string; - }; + readonly "application/json": components["schemas"]["FeedbackError"]; }; }; }; }; - readonly "evaluations.get": { + readonly "ingestion.crawl": { readonly parameters: { readonly query?: never; readonly header?: never; - readonly path: { - readonly evaluationId: string; - }; + readonly path?: never; readonly cookie?: never; }; - readonly requestBody?: never; + readonly requestBody?: { + readonly content: { + readonly "application/json": components["schemas"]["CrawlSiteRequest"]; + }; + }; readonly responses: { - /** @description Full evaluation detail including per-question results */ + /** @description Successfully crawled and ingested website */ readonly 200: { headers: { readonly [name: string]: unknown; }; content: { - readonly "application/json": components["schemas"]["EvaluationDetail"]; + readonly "application/json": components["schemas"]["CrawlResponse"]; }; }; - /** @description Evaluation not found in the active scope */ + /** @description Collection not found */ readonly 404: { headers: { readonly [name: string]: unknown; }; content: { - readonly "application/json": components["schemas"]["EvaluationDetailError"]; + readonly "application/json": components["schemas"]["ErrorResponse"]; + }; + }; + /** @description Crawl failed */ + readonly 500: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ErrorResponse"]; }; }; }; }; - readonly "ingestion.crawl": { + readonly "ingestion.crawlSelectedAsync": { readonly parameters: { readonly query?: never; readonly header?: never; @@ -3204,63 +3959,57 @@ export interface operations { }; readonly requestBody?: { readonly content: { - readonly "application/json": components["schemas"]["CrawlSiteRequest"]; + readonly "application/json": components["schemas"]["CrawlSelectedPagesRequest"]; }; }; readonly responses: { - /** @description Successfully crawled and ingested website */ + /** @description Crawl started */ readonly 200: { headers: { readonly [name: string]: unknown; }; content: { - readonly "application/json": components["schemas"]["CrawlResponse"]; + readonly "application/json": components["schemas"]["StreamingIngestResponse"]; }; }; - /** @description Collection not found */ - readonly 404: { + /** @description Invalid request */ + readonly 400: { headers: { readonly [name: string]: unknown; }; content: { - readonly "application/json": components["schemas"]["ErrorResponse"]; + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; }; }; - /** @description Crawl failed */ - readonly 500: { + /** @description Insufficient execution credits */ + readonly 402: { headers: { readonly [name: string]: unknown; }; content: { - readonly "application/json": components["schemas"]["ErrorResponse"]; + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; }; }; - }; - }; - readonly "ingestion.crawlSelectedAsync": { - readonly parameters: { - readonly query?: never; - readonly header?: never; - readonly path?: never; - readonly cookie?: never; - }; - readonly requestBody?: { - readonly content: { - readonly "application/json": components["schemas"]["CrawlSelectedPagesRequest"]; + /** @description Subscription required or operation forbidden */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; }; - }; - readonly responses: { - /** @description Crawl started */ - readonly 200: { + /** @description Idempotency key reused with different crawl parameters */ + readonly 409: { headers: { readonly [name: string]: unknown; }; content: { - readonly "application/json": components["schemas"]["StreamingIngestResponse"]; + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; }; }; - /** @description Invalid request */ - readonly 400: { + /** @description Import exceeds available storage quota */ + readonly 413: { headers: { readonly [name: string]: unknown; }; @@ -3301,7 +4050,25 @@ export interface operations { readonly "application/json": components["schemas"]["StreamingIngestResponse"]; }; }; - /** @description Multimodal feature requires Pro plan */ + /** @description Invalid credit ceiling */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; + /** @description Insufficient execution credits */ + readonly 402: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; + /** @description Organization subscription required or multimodal feature disabled by administrator policy */ readonly 403: { headers: { readonly [name: string]: unknown; @@ -3319,6 +4086,24 @@ export interface operations { readonly "application/json": components["schemas"]["StreamingErrorResponse"]; }; }; + /** @description Idempotency key reused with different crawl parameters */ + readonly 409: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; + /** @description Import exceeds available storage quota */ + readonly 413: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; /** @description Internal server error */ readonly 500: { headers: { @@ -3394,6 +4179,33 @@ export interface operations { readonly "application/json": components["schemas"]["StreamingIngestResponse"]; }; }; + /** @description Invalid credit ceiling */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; + /** @description Insufficient execution credits */ + readonly 402: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; + /** @description Active subscription required */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; /** @description Collection not found */ readonly 404: { headers: { @@ -3403,6 +4215,24 @@ export interface operations { readonly "application/json": components["schemas"]["StreamingErrorResponse"]; }; }; + /** @description Idempotency key reused with different dataset parameters */ + readonly 409: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; + /** @description Dataset output exceeds available storage quota */ + readonly 413: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; /** @description Internal server error */ readonly 500: { headers: { @@ -3412,6 +4242,15 @@ export interface operations { readonly "application/json": components["schemas"]["StreamingErrorResponse"]; }; }; + /** @description Billing admission is unavailable */ + readonly 503: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; }; }; readonly "ingestion.discover": { @@ -3436,6 +4275,15 @@ export interface operations { readonly "application/json": components["schemas"]["DiscoverResponse"]; }; }; + /** @description Subscription required or operation forbidden */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; /** @description Discovery failed */ readonly 500: { headers: { @@ -3499,9 +4347,13 @@ export interface operations { readonly requestBody?: { readonly content: { readonly "multipart/form-data": { + /** @description JSON access policy: inherit or restricted with active business role IDs. */ + readonly accessPolicy?: string; + /** @description JSON chunking configuration; unknown or unsupported fields are rejected. */ + readonly chunkingConfiguration?: string; readonly collectionId: string; /** - * @description Enable multimodal embeddings (Jina CLIP v2). Requires Pro plan or higher. Pass 'true' to enable. + * @description Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy. Pass 'true' to enable. * @example true */ readonly enableMultimodal?: string; @@ -3512,6 +4364,21 @@ export interface operations { * @example documents */ readonly mode?: string; + /** + * @description Comma-separated OCR languages. Supported in the runtime image: fr,en. Omit for automatic detection. + * @example fr,en + */ + readonly ocrLanguages?: string; + /** + * @description OCR policy: auto (default), disabled, or force full-page OCR. + * @enum {string} + */ + readonly ocrMode?: "auto" | "disabled" | "force"; + /** + * @description Quality review threshold between 0 and 1. + * @example 0.55 + */ + readonly ocrReviewThreshold?: string; }; }; }; @@ -3534,6 +4401,15 @@ export interface operations { readonly "application/json": components["schemas"]["ErrorResponse"]; }; }; + /** @description Subscription required or operation forbidden */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ErrorResponse"]; + }; + }; /** @description Collection not found */ readonly 404: { headers: { @@ -3543,6 +4419,24 @@ export interface operations { readonly "application/json": components["schemas"]["ErrorResponse"]; }; }; + /** @description File exceeds the maximum upload size */ + readonly 413: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ErrorResponse"]; + }; + }; + /** @description Unsupported file type or PDF requires the separate OCR pipeline */ + readonly 422: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ErrorResponse"]; + }; + }; /** @description Ingestion failed */ readonly 500: { headers: { @@ -3552,6 +4446,15 @@ export interface operations { readonly "application/json": components["schemas"]["ErrorResponse"]; }; }; + /** @description Synchronous embedding deadline reached */ + readonly 504: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ErrorResponse"]; + }; + }; }; }; readonly "ingestion.fileAsync": { @@ -3564,14 +4467,27 @@ export interface operations { readonly requestBody?: { readonly content: { readonly "multipart/form-data": { + /** @description JSON access policy: inherit or restricted with active business role IDs. */ + readonly accessPolicy?: string; + /** @description JSON chunking configuration; unknown or unsupported fields are rejected. */ + readonly chunkingConfiguration?: string; readonly collectionId: string; /** - * @description Enable multimodal embeddings (Jina CLIP v2). Requires Pro plan or higher. Pass 'true' to enable. + * @description Enable multimodal embeddings (Jina CLIP v2) when allowed by administrator policy. Pass 'true' to enable. * @example true */ readonly enableMultimodal?: string; /** Format: binary */ readonly file?: string; + /** + * @description Comma-separated OCR languages supported by the runtime image: fr,en. + * @example fr,en + */ + readonly ocrLanguages?: string; + /** @enum {string} */ + readonly ocrMode?: "auto" | "disabled" | "force"; + /** @example 0.55 */ + readonly ocrReviewThreshold?: string; }; }; }; @@ -3594,7 +4510,16 @@ export interface operations { readonly "application/json": components["schemas"]["StreamingErrorResponse"]; }; }; - /** @description Multimodal feature requires Pro plan */ + /** @description Insufficient execution credits */ + readonly 402: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; + /** @description Organization subscription required or multimodal feature disabled by administrator policy */ readonly 403: { headers: { readonly [name: string]: unknown; @@ -3612,6 +4537,33 @@ export interface operations { readonly "application/json": components["schemas"]["StreamingErrorResponse"]; }; }; + /** @description Idempotency key reused with different content */ + readonly 409: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; + /** @description File exceeds the maximum upload size or available storage quota */ + readonly 413: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; + /** @description Unsupported file type */ + readonly 422: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; /** @description Internal server error */ readonly 500: { headers: { @@ -3621,6 +4573,158 @@ export interface operations { readonly "application/json": components["schemas"]["StreamingErrorResponse"]; }; }; + /** @description Billing admission is unavailable */ + readonly 503: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["StreamingErrorResponse"]; + }; + }; + }; + }; + readonly "ingestion.listJobs": { + readonly parameters: { + readonly query: { + readonly collectionId: string; + }; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Collection ingestion jobs */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly jobs: readonly { + readonly [key: string]: unknown; + }[]; + /** @enum {boolean} */ + readonly success: true; + }; + }; + }; + /** @description Missing collection */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly error: string; + /** @enum {boolean} */ + readonly success: false; + }; + }; + }; + }; + }; + readonly "ingestion.getJob": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path: { + readonly jobId: string; + }; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Current job state */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly job: { + readonly [key: string]: unknown; + }; + /** @enum {boolean} */ + readonly success: true; + }; + }; + }; + /** @description Job not found */ + readonly 404: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly error: string; + /** @enum {boolean} */ + readonly success: false; + }; + }; + }; + }; + }; + readonly "ingestion.cancelJob": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path: { + readonly jobId: string; + }; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Cancellation requested */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly message: string; + /** @enum {boolean} */ + readonly success: true; + }; + }; + }; + /** @description Job not found or already terminal */ + readonly 404: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly error: string; + /** @enum {boolean} */ + readonly success: false; + }; + }; + }; + }; + }; + readonly "ingestion.streamJob": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path: { + readonly jobId: string; + }; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Ingestion job event stream */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "text/event-stream": string; + }; + }; }; }; readonly "ingestion.url": { @@ -3663,6 +4767,15 @@ export interface operations { readonly "application/json": components["schemas"]["ErrorResponse"]; }; }; + /** @description URL is not a public address */ + readonly 422: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ErrorResponse"]; + }; + }; /** @description Ingestion failed */ readonly 500: { headers: { @@ -3730,6 +4843,144 @@ export interface operations { }; }; }; + readonly "observability.listTraces": { + readonly parameters: { + readonly query?: { + readonly accessOutcome?: "allowed" | "denied" | "plan_gate" | "read_only"; + readonly accessTier?: "owner" | "shared" | "public-free" | "public-gated" | "denied"; + readonly collectionId?: string; + readonly collectionVisibility?: "private" | "shared" | "public" | "unknown"; + readonly endDate?: string; + readonly limit?: number; + readonly page?: number; + readonly parentOnly?: boolean | null; + readonly search?: string; + readonly sessionId?: string; + readonly startDate?: string; + readonly status?: "success" | "error"; + readonly surface?: "chat" | "agent" | "workflow" | "mcp" | "sdk" | "widget" | "public" | "ingestion" | "evaluation" | "unknown"; + readonly tags?: string | readonly string[]; + readonly type?: "llm" | "agent" | "retrieval" | "rerank" | "tool" | "judge" | "workflow" | "ingestion" | "ab_test"; + }; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Paginated traces */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly [key: string]: unknown; + }; + }; + }; + }; + }; + readonly "observability.getTrace": { + readonly parameters: { + readonly query?: { + readonly includeChildren?: boolean | null; + readonly maxDepth?: number; + }; + readonly header?: never; + readonly path: { + readonly id: string; + }; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Trace and optional children */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly trace?: unknown; + }; + }; + }; + /** @description Trace not found */ + readonly 404: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly error: string; + }; + }; + }; + }; + }; + readonly "observability.exportTraces": { + readonly parameters: { + readonly query: { + readonly accessOutcome?: "allowed" | "denied" | "plan_gate" | "read_only"; + readonly accessTier?: "owner" | "shared" | "public-free" | "public-gated" | "denied"; + readonly collectionId?: string; + readonly collectionVisibility?: "private" | "shared" | "public" | "unknown"; + readonly endDate: string; + readonly format: "csv" | "json"; + readonly includeInputOutput?: boolean | null; + readonly search?: string; + readonly startDate: string; + readonly status?: "success" | "error"; + readonly surface?: "chat" | "agent" | "workflow" | "mcp" | "sdk" | "widget" | "public" | "ingestion" | "evaluation" | "unknown"; + readonly type?: "llm" | "agent" | "retrieval" | "rerank" | "tool" | "judge" | "workflow" | "ingestion" | "ab_test"; + }; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description CSV or JSON trace export */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": unknown; + readonly "text/csv": string; + }; + }; + }; + }; + readonly "observability.getTraceMetrics": { + readonly parameters: { + readonly query: { + readonly collectionId?: string; + readonly endDate: string; + readonly granularity?: "day" | "week" | "month"; + readonly startDate: string; + readonly type?: "llm" | "agent" | "retrieval" | "rerank" | "tool" | "judge" | "workflow" | "ingestion" | "ab_test"; + }; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Aggregated trace metrics */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly [key: string]: unknown; + }; + }; + }; + }; + }; readonly "workflows.list": { readonly parameters: { readonly query?: never; @@ -3925,6 +5176,49 @@ export interface operations { readonly "application/json": components["schemas"]["ExecutionResult"]; }; }; + /** @description Budget reserved and execution admitted */ + readonly 202: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly chargedMilliCredits: string | null; + readonly executionId: string; + readonly maximumMilliCredits: string; + readonly output?: unknown; + readonly reconciliationRequired: boolean; + readonly status: string; + }; + }; + }; + /** @description Invalid request */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Insufficient credits */ + readonly 402: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Forbidden */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["Error"]; + }; + }; /** @description Workflow not found */ readonly 404: { headers: { @@ -3934,6 +5228,15 @@ export interface operations { readonly "application/json": components["schemas"]["Error"]; }; }; + /** @description Conflict */ + readonly 409: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["Error"]; + }; + }; /** @description Execution failed */ readonly 500: { headers: { @@ -3943,6 +5246,15 @@ export interface operations { readonly "application/json": components["schemas"]["Error"]; }; }; + /** @description Temporarily unavailable */ + readonly 503: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["Error"]; + }; + }; }; }; readonly "workflows.listExecutions": { diff --git a/typescript/src/index.ts b/typescript/src/index.ts index c803ef6..8f15054 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -10,6 +10,10 @@ import { DataChat } from "./resources/data-chat.js"; import { Compatibility } from "./resources/compatibility.js"; import { Workflows } from "./resources/workflows.js"; import { DeepResearch } from "./resources/deep-research.js"; +import { Widgets } from "./resources/widgets.js"; +import { Feedback } from "./resources/feedback.js"; +import { Traces } from "./resources/traces.js"; +import { RagAbTests } from "./resources/rag-ab-tests.js"; import { ConfigurationError } from "./errors.js"; import type { ClientOptions } from "./types.js"; @@ -26,6 +30,10 @@ export class IgnitionAI extends BaseClient { readonly compatibility: Compatibility; readonly workflows: Workflows; readonly deepResearch: DeepResearch; + readonly widgets: Widgets; + readonly feedback: Feedback; + readonly traces: Traces; + readonly ragAbTests: RagAbTests; constructor(options: ClientOptions) { super(options); @@ -40,6 +48,10 @@ export class IgnitionAI extends BaseClient { this.compatibility = new Compatibility(this); this.workflows = new Workflows(this); this.deepResearch = new DeepResearch(this); + this.widgets = new Widgets(this); + this.feedback = new Feedback(this); + this.traces = new Traces(this); + this.ragAbTests = new RagAbTests(this); } /** Construct a client from IGNITION_API_KEY in a trusted server runtime. */ @@ -59,6 +71,20 @@ export class IgnitionAI extends BaseClient { // Re-export types export type { ClientOptions, + FeedbackParams, + FeedbackResult, + Trace, + TraceType, + TraceStatus, + TraceListParams, + TraceListResponse, + TraceMetricsParams, + TraceMetrics, + TraceExportParams, + TraceExport, + RagConfigCandidate, + RagAbTestParams, + RagAbTestResult, Source, ImageResult, PipelineMetrics, @@ -76,12 +102,29 @@ export type { AgentSkillStatus, AgentSkillUpdateParams, Collection, + CollectionServedSource, CollectionAccessTier, CollectionCreateParams, PublicCollectionRequiredPlanId, + PublicCollectionPublisher, + PublicCollectionSummary, + PublicCollectionDetail, + PublicCollectionListParams, CollectionUpdateParams, + CollectionVisibilityUpdateParams, ChatParams, ChatResponse, + ManagedChatParams, + ManagedChatResponse, + ManagedProgressiveStreamEvent, + ManagedAgent, + ManagedAgentCreateParams, + ManagedAgentUpdateParams, + ManagedAgentChatStartParams, + ManagedAgentChatOutput, + ManagedAgentChatResponse, + ManagedAgentChatSummary, + ManagedAgentChatHistory, AgentChatParams, ChatStreamEvent, ProgressiveStreamEvent, @@ -93,6 +136,35 @@ export type { IngestDatasetParams, IngestResult, CrawlResult, + AsyncIngestResult, + IngestionJob, + IngestionJobStatus, + IngestionJobSource, + IngestionJobStep, + IngestionJobResponse, + IngestionJobsResponse, + IngestionJobCancelResponse, + IngestionJobStreamEvent, + DiscoverSiteParams, + DiscoveredPage, + DiscoverSiteResult, + CrawlSelectedParams, + WidgetType, + WidgetPosition, + WidgetTheme, + WidgetSuggestion, + WidgetHumanEscalation, + WidgetConfig, + ManagedWidgetConfig, + ManagedWidgetBusinessConfiguration, + ManagedWidgetCreateParams, + ManagedWidgetUpdateParams, + ManagedWidgetCreateResult, + WidgetCreateParams, + WidgetUpdateParams, + WidgetCreateResult, + WidgetKeyResult, + WidgetAnalytics, McpPrompt, McpResource, McpPromptContent, @@ -147,6 +219,7 @@ export { ConfigurationError, SecurityError, ProtocolError, + UnsupportedCapabilityError, UnsupportedContractVersionError, ContractDigestMismatchError, APIError, @@ -159,13 +232,14 @@ export { BadRequestError, RateLimitError, InternalServerError, + OfferingUnavailableError, APIConnectionError, APIConnectionTimeoutError, RequestCancelledError, } from "./errors.js"; // Re-export stream classes -export { ChatStream, AgentChatStream, ProgressiveStream, DeepResearchStream } from "./streaming.js"; +export { ChatStream, AgentChatStream, ProgressiveStream, DeepResearchStream, IngestionJobStream } from "./streaming.js"; // Re-export version export { VERSION } from "./version.js"; diff --git a/typescript/src/resources/agent-chat.ts b/typescript/src/resources/agent-chat.ts index 733622e..6900247 100644 --- a/typescript/src/resources/agent-chat.ts +++ b/typescript/src/resources/agent-chat.ts @@ -1,9 +1,129 @@ import type { BaseClient } from "../client.js"; -import type { AgentChatParams } from "../types.js"; +import type { AgentChatParams, ChatMessage, ManagedAgentChatHistory, ManagedAgentChatOutput, ManagedAgentChatResponse, ManagedAgentChatStartParams } from "../types.js"; import { AgentChatStream } from "../streaming.js"; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const object = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + +function serializeManagedAgentChat(value: ManagedAgentChatStartParams | Record): string { + if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Managed agent chat requires a request object"); + const raw = value as Record; + const allowed = ["requestId", "sessionId", "query", "history", "maximumMilliCredits"]; + for (const key of Object.keys(raw)) { + if (!allowed.includes(key)) throw new TypeError(`Managed agent chat does not accept ${key}`); + } + if (typeof raw.requestId !== "string" || !UUID.test(raw.requestId)) throw new TypeError("requestId must be a UUID"); + if (typeof raw.sessionId !== "string" || raw.sessionId.length < 1 || raw.sessionId.length > 200) throw new TypeError("sessionId must contain 1 to 200 characters"); + if (typeof raw.query !== "string" || raw.query.trim().length < 1 || raw.query.length > 8192) throw new TypeError("query must contain 1 to 8192 characters"); + if (typeof raw.maximumMilliCredits !== "string" || !/^[1-9][0-9]{0,15}$/.test(raw.maximumMilliCredits)) throw new TypeError("maximumMilliCredits must be a positive integer string of at most 16 digits"); + const history = raw.history === undefined ? [] : raw.history; + if (!Array.isArray(history) || history.length > 100) throw new TypeError("history must be an array with at most 100 messages"); + const body = { + requestId: raw.requestId, + sessionId: raw.sessionId, + query: raw.query, + history: history.map((item) => { + const message = object(item); + if (!item || typeof item !== "object" || Array.isArray(item) || Object.keys(message).some((key) => !["role", "content"].includes(key))) { + throw new TypeError("history messages accept only role and content"); + } + if ((message.role !== "user" && message.role !== "assistant") || typeof message.content !== "string" || message.content.length > 80000) { + throw new TypeError("history messages require a supported role and content up to 80000 characters"); + } + return { role: message.role, content: message.content }; + }), + maximumMilliCredits: raw.maximumMilliCredits, + }; + const serialized = JSON.stringify(body); + if (new TextEncoder().encode(serialized).byteLength > 262144) throw new TypeError("managed agent chat request exceeds 262144 bytes"); + return serialized; +} + +function presentHistory(value: unknown): ManagedAgentChatHistory { + const raw = object(value); + const items = Array.isArray(raw.items) ? raw.items.flatMap((item) => { + const entry = object(item); + return typeof entry.executionId === "string" && typeof entry.createdAt === "string" && typeof entry.question === "string" + ? [{ executionId: entry.executionId, createdAt: entry.createdAt, question: entry.question }] : []; + }) : []; + return { items, nextCursor: typeof raw.nextCursor === "string" ? raw.nextCursor : null }; +} + +function presentAgentChat(value: unknown): ManagedAgentChatResponse { + const raw = object(value); + const request = object(raw.request); + const presentMessages = (messages: unknown): ChatMessage[] => Array.isArray(messages) ? messages.flatMap((item) => { + const message = object(item); + return (message.role === "user" || message.role === "assistant") && typeof message.content === "string" + ? [{ role: message.role as "user" | "assistant", content: message.content }] : []; + }) : []; + const history = presentMessages(request.history); + const output = raw.output === null || raw.output === undefined ? null : (() => { + const result = object(raw.output); + if (typeof result.response !== "string") return null; + const sources: ManagedAgentChatOutput["sources"] = Array.isArray(result.sources) ? result.sources.flatMap((item) => { + const source = object(item); + const safe: Record = {}; + for (const key of ["id", "content", "type", "sourceType", "source", "documentId", "title"] as const) { + if (typeof source[key] === "string") safe[key] = source[key] as string; + } + for (const key of ["pageNumber", "imageIndex", "score"] as const) { + if (typeof source[key] === "number") safe[key] = source[key] as number; + } + return [safe as ManagedAgentChatOutput["sources"][number]]; + }) : []; + const outputHistory = presentMessages(result.history); + return { response: result.response, sources, history: outputHistory }; + })(); + const statuses = ["pending", "running", "completed", "failed", "cancelled", "cancelling"] as const; + const status = statuses.includes(raw.status as typeof statuses[number]) ? raw.status as typeof statuses[number] : "failed"; + return { + executionId: typeof raw.executionId === "string" ? raw.executionId : "", + request: { + requestId: typeof request.requestId === "string" ? request.requestId : "", + sessionId: typeof request.sessionId === "string" ? request.sessionId : "", + query: typeof request.query === "string" ? request.query : "", + history, + maximumMilliCredits: typeof request.maximumMilliCredits === "string" ? request.maximumMilliCredits : "", + }, + status, + reconciliationRequired: raw.reconciliationRequired === true, + output, + maximumMilliCredits: typeof raw.maximumMilliCredits === "string" ? raw.maximumMilliCredits : "0", + chargedMilliCredits: typeof raw.chargedMilliCredits === "string" ? raw.chargedMilliCredits : null, + }; +} + +class ManagedAgentChat { + constructor(private readonly client: BaseClient) {} + + async start(agentId: string, params: ManagedAgentChatStartParams): Promise { + return presentAgentChat(await this.client.request("POST", `/agents/${encodeURIComponent(agentId)}/chat/executions`, { + body: serializeManagedAgentChat(params), + })); + } + + async get(agentId: string, executionId: string): Promise { + return presentAgentChat(await this.client.request("GET", `/agents/${encodeURIComponent(agentId)}/chat/executions/${encodeURIComponent(executionId)}`)); + } + + async list(agentId: string, options: { before?: string } = {}): Promise { + if (options.before !== undefined && !UUID.test(options.before)) throw new TypeError("before must be a UUID"); + const query = options.before === undefined ? "" : `?before=${encodeURIComponent(options.before)}`; + return presentHistory(await this.client.request("GET", `/agents/${encodeURIComponent(agentId)}/chat/executions${query}`)); + } + + async cancel(agentId: string, executionId: string): Promise { + return presentAgentChat(await this.client.request("POST", `/agents/${encodeURIComponent(agentId)}/chat/executions/${encodeURIComponent(executionId)}/cancel`, { body: "{}" })); + } +} + export class AgentChat { - constructor(private client: BaseClient) {} + readonly managed: ManagedAgentChat; + + constructor(private client: BaseClient) { + this.managed = new ManagedAgentChat(client); + } /** * Chat with an agent via streaming SSE. diff --git a/typescript/src/resources/agents.ts b/typescript/src/resources/agents.ts index ab362c9..a4cab2a 100644 --- a/typescript/src/resources/agents.ts +++ b/typescript/src/resources/agents.ts @@ -8,10 +8,51 @@ import type { AgentUpdateParams, AgentGenerateParams, AgentGenerateResult, + ManagedAgent, + ManagedAgentCreateParams, + ManagedAgentUpdateParams, } from "../types.js"; +import { presentManagedAgent, serializeManagedAgent } from "./managed-contracts.js"; + +class ManagedAgents { + constructor(private readonly client: BaseClient) {} + + async list(): Promise { + const data = await this.client.request("GET", "/agents"); + const agents = Array.isArray(data) ? data : Array.isArray((data as { agents?: unknown[] } | null)?.agents) + ? (data as { agents: unknown[] }).agents : []; + return agents.map(presentManagedAgent); + } + + async get(id: string): Promise { + return presentManagedAgent(await this.client.request("GET", `/agents/${encodeURIComponent(id)}`)); + } + + async create(params: ManagedAgentCreateParams): Promise { + return presentManagedAgent(await this.client.request("POST", "/agents", { + body: serializeManagedAgent(params, true), + })); + } + + async update(id: string, params: ManagedAgentUpdateParams): Promise { + return presentManagedAgent(await this.client.request("PATCH", `/agents/${encodeURIComponent(id)}`, { + body: serializeManagedAgent(params as Record), + })); + } + + async delete(id: string): Promise<{ success: boolean; permanent?: boolean }> { + const value = await this.client.request("DELETE", `/agents/${encodeURIComponent(id)}`); + const result = value && typeof value === "object" ? value as Record : {}; + return { success: result.success === true, ...(typeof result.permanent === "boolean" ? { permanent: result.permanent } : {}) }; + } +} export class Agents { - constructor(private client: BaseClient) {} + readonly managed: ManagedAgents; + + constructor(private client: BaseClient) { + this.managed = new ManagedAgents(client); + } async list(): Promise { const data = await this.client.request( diff --git a/typescript/src/resources/chat.ts b/typescript/src/resources/chat.ts index 6b0f05a..41379d1 100644 --- a/typescript/src/resources/chat.ts +++ b/typescript/src/resources/chat.ts @@ -1,16 +1,295 @@ import type { BaseClient } from "../client.js"; -import type { ChatParams, ChatResponse } from "../types.js"; +import type { + ChatParams, + ChatResponse, + ManagedChatParams, + ManagedChatResponse, + ManagedProgressiveStreamEvent, + Source, + ImageResult, + PipelineMetrics, +} from "../types.js"; import { ChatStream, ProgressiveStream } from "../streaming.js"; +const object = (value: unknown): Record => + value && typeof value === "object" && !Array.isArray(value) + ? value as Record + : {}; + +function assertExactKeys(value: unknown, allowed: readonly string[], label: string): Record { + const record = object(value); + for (const key of Object.keys(record)) { + if (!allowed.includes(key)) { + if (key === "model" || key === "llmConfigId") { + throw new TypeError("Managed chat cannot override model or LLM configuration"); + } + throw new TypeError(`Managed ${label} does not accept ${key}`); + } + } + return record; +} + +const CHAT_FIELDS = ["collectionId", "query", "maximumMilliCredits", "history", "includeImages", "filters"] as const; +const FILTER_OPERATORS = ["eq", "neq", "contains", "gt", "gte", "lt", "lte", "in", "nin", "between", "exists"] as const; + +function serializeManagedChat(params: ManagedChatParams): string { + const value = assertExactKeys(params, CHAT_FIELDS, "chat"); + if (typeof value.collectionId !== "string" || typeof value.query !== "string" || value.query.length < 1) { + throw new TypeError("collectionId and a non-empty query are required"); + } + if (value.maximumMilliCredits !== undefined && + (typeof value.maximumMilliCredits !== "string" || !/^[1-9][0-9]{0,15}$/.test(value.maximumMilliCredits))) { + throw new TypeError("maximumMilliCredits must be a positive integer string of at most 16 digits"); + } + const body: Record = { + collectionId: value.collectionId, + query: value.query, + }; + if (value.maximumMilliCredits !== undefined) body.maximumMilliCredits = value.maximumMilliCredits; + if (value.includeImages !== undefined) { + if (typeof value.includeImages !== "boolean") throw new TypeError("includeImages must be a boolean"); + body.includeImages = value.includeImages; + } + if (value.history !== undefined) { + if (!Array.isArray(value.history)) throw new TypeError("history must be an array"); + body.history = value.history.map((item) => { + const message = assertExactKeys(item, ["role", "content"], "chat history message"); + if ((message.role !== "user" && message.role !== "assistant") || typeof message.content !== "string") { + throw new TypeError("history messages require a user or assistant role and string content"); + } + return { role: message.role, content: message.content }; + }); + } + if (value.filters !== undefined) { + if (!Array.isArray(value.filters)) throw new TypeError("filters must be an array"); + body.filters = value.filters.map((item) => { + const filter = assertExactKeys(item, ["field", "operator", "value"], "chat filter"); + if (typeof filter.field !== "string" || typeof filter.operator !== "string" || + !(FILTER_OPERATORS as readonly string[]).includes(filter.operator) || !("value" in filter)) { + throw new TypeError("filters require field, operator, and value"); + } + const filterValue = filter.value; + if (filterValue && typeof filterValue === "object" && !Array.isArray(filterValue)) { + const range = assertExactKeys(filterValue, ["from", "to"], "chat filter range"); + if (typeof range.from !== "number" || !Number.isFinite(range.from) || typeof range.to !== "number" || !Number.isFinite(range.to)) throw new TypeError("filter range bounds must be finite numbers"); + return { field: filter.field, operator: filter.operator, value: { from: range.from, to: range.to } }; + } + if (Array.isArray(filterValue)) { + if (!filterValue.every((item) => typeof item === "string" || (typeof item === "number" && Number.isFinite(item)))) { + throw new TypeError("filter arrays may contain only strings or numbers"); + } + return { field: filter.field, operator: filter.operator, value: [...filterValue] }; + } + if (!["string", "boolean"].includes(typeof filterValue) && !(typeof filterValue === "number" && Number.isFinite(filterValue))) { + throw new TypeError("filter value must be a scalar, array, or numeric range"); + } + return { field: filter.field, operator: filter.operator, value: filterValue }; + }); + } + return JSON.stringify(body); +} + +function presentSource(value: unknown): Source { + const source = object(value); + return { + type: source.type === "image" ? "image" : "text", + ...(typeof source.content === "string" ? { content: source.content } : {}), + ...(typeof source.score === "number" ? { score: source.score } : { score: 0 }), + ...(typeof source.source === "string" ? { source: source.source } : { source: "" }), + ...(typeof source.sourceType === "string" ? { sourceType: source.sourceType } : { sourceType: "" }), + ...(typeof source.title === "string" ? { title: source.title } : {}), + ...(typeof source.url === "string" ? { url: source.url } : {}), + ...(typeof source.pageNumber === "number" ? { pageNumber: source.pageNumber } : {}), + ...(typeof source.imageIndex === "number" ? { imageIndex: source.imageIndex } : {}), + ...(typeof source.mimeType === "string" ? { mimeType: source.mimeType } : {}), + }; +} + +function presentImage(value: unknown): ImageResult { + const image = object(value); + return { + source: typeof image.source === "string" ? image.source : "", + ...(typeof image.pageNumber === "number" ? { pageNumber: image.pageNumber } : {}), + ...(typeof image.imageIndex === "number" ? { imageIndex: image.imageIndex } : {}), + ...(typeof image.mimeType === "string" ? { mimeType: image.mimeType } : {}), + score: typeof image.score === "number" ? image.score : 0, + ...(typeof image.signedUrl === "string" ? { signedUrl: image.signedUrl } : {}), + }; +} + +function presentManagedResponse(value: unknown): ManagedChatResponse { + const response = object(value); + return { + answer: typeof response.answer === "string" ? response.answer : "", + sources: Array.isArray(response.sources) ? response.sources.map(presentSource) : [], + ...(Array.isArray(response.images) ? { images: response.images.map(presentImage) } : {}), + ...(typeof response.relevanceScore === "number" ? { relevanceScore: response.relevanceScore } : {}), + }; +} + +function presentMetrics(value: unknown): PipelineMetrics { + const metrics = object(value); + return { + totalTimeMs: typeof metrics.totalTimeMs === "number" ? metrics.totalTimeMs : 0, + queryEnhancementMs: typeof metrics.queryEnhancementMs === "number" ? metrics.queryEnhancementMs : 0, + searchMs: typeof metrics.searchMs === "number" ? metrics.searchMs : 0, + rerankMs: typeof metrics.rerankMs === "number" ? metrics.rerankMs : 0, + resultsCount: typeof metrics.resultsCount === "number" ? metrics.resultsCount : 0, + ...(typeof metrics.bm25IndexSize === "number" ? { bm25IndexSize: metrics.bm25IndexSize } : {}), + }; +} + +class ManagedChatStream implements AsyncIterable { + constructor(private readonly stream: ChatStream) {} + + async *[Symbol.asyncIterator](): AsyncIterableIterator { + for await (const event of this.stream) { + if (event.type === "sources") yield { type: "sources", sources: event.sources.map(presentSource) }; + else if (event.type === "images") yield { type: "images", images: event.images.map(presentImage) }; + else if (event.type === "metrics") yield { + type: "metrics", pipelineMetrics: presentMetrics(event.pipelineMetrics), + featuresUsed: event.featuresUsed.filter((item): item is string => typeof item === "string"), + }; + else if (event.type === "error") yield { type: "error", error: "Managed chat request failed" }; + else yield event; + } + } + + async *toTextStream(): AsyncIterableIterator { + for await (const event of this) if (event.type === "chunk") yield event.content; + } + + async getFullResponse(): Promise<{ text: string; sources: Source[]; images: ImageResult[]; metrics?: PipelineMetrics }> { + let text = ""; let sources: Source[] = []; let images: ImageResult[] = []; let metrics: PipelineMetrics | undefined; + for await (const event of this) { + if (event.type === "chunk") text += event.content; + else if (event.type === "sources") sources = event.sources; + else if (event.type === "images") images = event.images; + else if (event.type === "metrics") metrics = event.pipelineMetrics; + } + return { text, sources, images, ...(metrics ? { metrics } : {}) }; + } + + toReadableStream(): ReadableStream { + const iterator = this[Symbol.asyncIterator](); + return new ReadableStream({ + async pull(controller) { + const next = await iterator.next(); + if (next.done) controller.close(); + else controller.enqueue(next.value); + }, + async cancel() { await iterator.return?.(); }, + }); + } +} + +class ManagedProgressiveStream implements AsyncIterable { + constructor(private readonly stream: ProgressiveStream) {} + + async *[Symbol.asyncIterator](): AsyncIterableIterator { + for await (const event of this.stream) { + switch (event.type) { + case "stage": yield { type: "stage", stage: event.stage, elapsed: event.elapsed }; break; + case "enhancement": yield { + type: "enhancement", original: event.original, enhanced: event.enhanced, + ...(event.multiQueries ? { multiQueries: event.multiQueries.filter((item): item is string => typeof item === "string") } : {}), + featuresUsed: event.featuresUsed.filter((item): item is string => typeof item === "string"), + }; break; + case "sources": yield { + type: "sources", sources: event.sources.map(presentSource), + ...(event.images ? { images: event.images.map(presentImage) } : {}), retrievalTimeMs: event.retrievalTimeMs, + }; break; + case "chunk": yield { type: "chunk", content: event.content }; break; + case "citation": yield { type: "citation", index: event.index, sourceId: event.sourceId, position: event.position }; break; + case "metrics": yield { + type: "metrics", pipelineMetrics: presentMetrics(event.pipelineMetrics), + featuresUsed: event.featuresUsed.filter((item): item is string => typeof item === "string"), + }; break; + case "error": yield { type: "error", error: "Managed chat request failed" }; break; + case "done": yield { type: "done" }; break; + } + } + } + + async *toTextStream(): AsyncIterableIterator { + for await (const event of this) if (event.type === "chunk") yield event.content; + } + + async getFullResponse(): Promise<{ + text: string; + sources: Source[]; + metrics?: PipelineMetrics; + citations: Array<{ index: number; sourceId: string }>; + stages: Array<{ stage: string; elapsed: number }>; + }> { + let text = ""; + let sources: Source[] = []; + let metrics: PipelineMetrics | undefined; + const citations: Array<{ index: number; sourceId: string }> = []; + const stages: Array<{ stage: string; elapsed: number }> = []; + for await (const event of this) { + if (event.type === "chunk") text += event.content; + else if (event.type === "sources") sources = event.sources; + else if (event.type === "metrics") metrics = event.pipelineMetrics; + else if (event.type === "citation") citations.push({ index: event.index, sourceId: event.sourceId }); + else if (event.type === "stage") stages.push({ stage: event.stage, elapsed: event.elapsed }); + } + return { text, sources, ...(metrics ? { metrics } : {}), citations, stages }; + } + + toReadableStream(): ReadableStream { + const iterator = this[Symbol.asyncIterator](); + return new ReadableStream({ + async pull(controller) { + const next = await iterator.next(); + if (next.done) controller.close(); + else controller.enqueue(next.value); + }, + async cancel() { await iterator.return?.(); }, + }); + } +} + +class ManagedChat { + constructor(private readonly client: BaseClient) {} + + async send(params: ManagedChatParams): Promise { + const response = await this.client.request("POST", "/chat", { body: serializeManagedChat(params) }); + return presentManagedResponse(response); + } + + stream(params: ManagedChatParams): ManagedChatStream { + return new ManagedChatStream(new ChatStream(this.client.requestRaw("POST", "/chat/stream", { body: serializeManagedChat(params) }))); + } + + streamProgressive(params: ManagedChatParams): ManagedProgressiveStream { + return new ManagedProgressiveStream(new ProgressiveStream(this.client.requestRaw("POST", "/chat/stream/progressive", { body: serializeManagedChat(params) }))); + } +} + +function serializeChat(params: ChatParams): string { + if (params.maximumMilliCredits !== undefined) { + if (typeof params.maximumMilliCredits !== "string" || !/^[1-9][0-9]{0,15}$/.test(params.maximumMilliCredits)) + throw new TypeError("maximumMilliCredits must be a positive integer string of at most 16 digits"); + if (params.llmConfigId !== undefined) + throw new TypeError("A managed credit budget cannot select an LLM configuration"); + } + return JSON.stringify(params); +} + export class Chat { - constructor(private client: BaseClient) {} + readonly managed: ManagedChat; + + constructor(private client: BaseClient) { + this.managed = new ManagedChat(client); + } /** * Send a non-streaming RAG chat request. */ async send(params: ChatParams): Promise { return this.client.request("POST", "/chat", { - body: JSON.stringify(params), + body: serializeChat(params), }); } @@ -19,7 +298,7 @@ export class Chat { */ stream(params: ChatParams): ChatStream { const responsePromise = this.client.requestRaw("POST", "/chat/stream", { - body: JSON.stringify(params), + body: serializeChat(params), }); return new ChatStream(responsePromise); @@ -32,7 +311,7 @@ export class Chat { const responsePromise = this.client.requestRaw( "POST", "/chat/stream/progressive", - { body: JSON.stringify(params) } + { body: serializeChat(params) } ); return new ProgressiveStream(responsePromise); diff --git a/typescript/src/resources/collections.ts b/typescript/src/resources/collections.ts index 102a70f..2eb7840 100644 --- a/typescript/src/resources/collections.ts +++ b/typescript/src/resources/collections.ts @@ -3,6 +3,7 @@ import type { Collection, CollectionCreateParams, CollectionUpdateParams, + CollectionVisibilityUpdateParams, ChunkListParams, ChunkListResponse, SearchParams, @@ -12,6 +13,9 @@ import type { CollectionQualityReport, DocumentRecord, ChunkingStrategy, + PublicCollectionDetail, + PublicCollectionListParams, + PublicCollectionSummary, } from "../types.js"; import { RETRIEVAL_PRESETS, @@ -22,6 +26,29 @@ import { export class Collections { constructor(private client: BaseClient) {} + /** Browse the dedicated public collection catalog for the caller's plan. */ + async listPublic( + options: PublicCollectionListParams = {}, + ): Promise { + const params = new URLSearchParams(); + if (options.minTier) params.set("minTier", options.minTier); + if (options.query) params.set("q", options.query); + const query = params.toString() ? `?${params}` : ""; + const data = await this.client.request<{ items: PublicCollectionSummary[] }>( + "GET", + `/public-collections${query}`, + ); + return data.items; + } + + /** Resolve a public collection and its sample queries by stable slug. */ + async getPublic(slug: string): Promise { + return this.client.request( + "GET", + `/public-collections/${encodeURIComponent(slug)}`, + ); + } + async list(options?: { includeShared?: boolean; includePublic?: boolean; @@ -52,6 +79,21 @@ export class Collections { }); } + /** + * Dedicated publication command. Requires a platform super-admin in the + * collection's owner tenant. Create stays private. + */ + async updateVisibility( + id: string, + params: CollectionVisibilityUpdateParams + ): Promise { + return this.client.request( + "PATCH", + `/collections/${id}/visibility`, + { body: JSON.stringify(params) } + ); + } + async delete( id: string, force?: boolean diff --git a/typescript/src/resources/data-chat.ts b/typescript/src/resources/data-chat.ts index 8167320..bf2a4fc 100644 --- a/typescript/src/resources/data-chat.ts +++ b/typescript/src/resources/data-chat.ts @@ -1,14 +1,30 @@ import type { BaseClient } from "../client.js"; import type { DataChatParams, DataChatPrecheck, DataChatResponse } from "../types.js"; +import { UnsupportedCapabilityError } from "../errors.js"; +import { Compatibility } from "./compatibility.js"; +/** @deprecated Data Chat is retained for legacy deployments advertising data_connectors. */ export class DataChat { - constructor(private client: BaseClient) {} + private readonly compatibility: Compatibility; - precheck(params: Omit): Promise { + constructor(private client: BaseClient) { + this.compatibility = new Compatibility(client); + } + + async precheck(params: Omit): Promise { + await this.requireCapability(); return this.client.request("POST", "/data-chat/precheck", { body: JSON.stringify(params) }); } - send(params: DataChatParams): Promise { + async send(params: DataChatParams): Promise { + await this.requireCapability(); return this.client.request("POST", "/data-chat", { body: JSON.stringify(params) }); } + + private async requireCapability(): Promise { + const metadata = await this.compatibility.get(); + if (!metadata.capabilities.includes("data_connectors")) { + throw new UnsupportedCapabilityError("data_connectors", metadata.contractVersion); + } + } } diff --git a/typescript/src/resources/feedback.ts b/typescript/src/resources/feedback.ts new file mode 100644 index 0000000..c9db718 --- /dev/null +++ b/typescript/src/resources/feedback.ts @@ -0,0 +1,13 @@ +import type { BaseClient } from "../client.js"; +import type { FeedbackParams, FeedbackResult } from "../types.js"; + +export class Feedback { + constructor(private client: BaseClient) {} + + /** Submit product feedback. This is an explicit external side effect. */ + async submit(params: FeedbackParams): Promise { + return this.client.request("POST", "/feedback", { + body: JSON.stringify(params), + }); + } +} diff --git a/typescript/src/resources/ingest.ts b/typescript/src/resources/ingest.ts index 7d8dc2b..5171bfc 100644 --- a/typescript/src/resources/ingest.ts +++ b/typescript/src/resources/ingest.ts @@ -1,4 +1,9 @@ import type { BaseClient } from "../client.js"; +import { + APIError, + isAiTemporarilyUnavailable, + offeringUnavailable, +} from "../errors.js"; import type { IngestUrlParams, IngestDocumentParams, @@ -7,42 +12,168 @@ import type { IngestDatasetParams, IngestResult, CrawlResult, + AsyncIngestResult, + DiscoverSiteParams, + DiscoverSiteResult, + CrawlSelectedParams, + IngestionJobCancelResponse, + IngestionJobResponse, + IngestionJobsResponse, } from "../types.js"; +import { IngestionJobStream } from "../streaming.js"; export class Ingest { constructor(private client: BaseClient) {} - async url(params: IngestUrlParams): Promise { - return this.client.request("POST", "/ingest/url", { - body: JSON.stringify(params), - }); + /** + * Durable single-URL ingestion (`POST /api/ingest/url/async`). + * Breaking in 1.0.0: returns `AsyncIngestResult` (`jobId`). Wait with `getJob` + * or `streamJob`. Synchronous `POST /api/ingest/url` remains license-only. + */ + async url(params: IngestUrlParams): Promise { + return this.urlAsync(params); } - async document(params: IngestDocumentParams): Promise { - return this.client.request("POST", "/ingest/document", { - body: JSON.stringify(params), + /** + * Durable raw-text ingestion through `POST /api/ingest/file/async`. + * SaaS members cannot use synchronous `POST /api/ingest/document`. + */ + async document(params: IngestDocumentParams): Promise { + const file = new File([params.content], params.filename, { type: "text/plain" }); + return this.fileAsync({ collectionId: params.collectionId, file }); + } + + /** + * Durable file ingestion (`POST /api/ingest/file/async`). + * Breaking in 1.0.0: returns `AsyncIngestResult` (`jobId`). Wait with `getJob` or + * `streamJob`. Synchronous `POST /api/ingest/file` remains license-only. + */ + async file(params: IngestFileParams): Promise { + return this.fileAsync(params); + } + + async crawl(params: IngestCrawlParams): Promise { + return this.requestUnlessClosedOffering( + "ingest.crawl", + () => this.client.request("POST", "/ingest/crawl", { + body: JSON.stringify(params), + }), + ); + } + + async dataset(params: IngestDatasetParams): Promise { + return this.requestUnlessClosedOffering( + "ingest.dataset", + () => this.client.request("POST", "/ingest/dataset", { + body: JSON.stringify(params), + }), + ); + } + + async urlAsync(params: IngestUrlParams): Promise { + return this.client.request("POST", "/ingest/url/async", { + body: JSON.stringify({ + collectionId: params.collectionId, + url: params.url, + enableMultimodal: params.enableMultimodal, + maxPages: 1, + }), }); } - async file(params: IngestFileParams): Promise { + async fileAsync(params: IngestFileParams): Promise { const formData = new FormData(); formData.append("collectionId", params.collectionId); - formData.append("file", params.file); - return this.client.request("POST", "/ingest/file", { - body: formData as any, + const filename = "name" in params.file && typeof params.file.name === "string" + ? params.file.name + : undefined; + if (filename) formData.append("file", params.file, filename); + else formData.append("file", params.file); + if (params.enableMultimodal !== undefined) { + formData.append("enableMultimodal", String(params.enableMultimodal)); + } + if (params.mode) formData.append("mode", params.mode); + if (params.ocrMode !== undefined) formData.append("ocrMode", params.ocrMode); + return this.client.request("POST", "/ingest/file/async", { + body: formData, multipart: true, }); } - async crawl(params: IngestCrawlParams): Promise { - return this.client.request("POST", "/ingest/crawl", { + async crawlAsync(params: IngestCrawlParams): Promise { + return this.client.request("POST", "/ingest/crawl/async", { body: JSON.stringify(params), }); } - async dataset(params: IngestDatasetParams): Promise { - return this.client.request("POST", "/ingest/dataset", { + async datasetAsync(params: IngestDatasetParams): Promise { + return this.client.request("POST", "/ingest/dataset/async", { body: JSON.stringify(params), }); } + + async discover(params: DiscoverSiteParams): Promise { + return this.requestUnlessClosedOffering( + "ingest.discover", + () => this.client.request("POST", "/ingest/discover", { + body: JSON.stringify(params), + }), + ); + } + + async crawlSelectedAsync( + params: CrawlSelectedParams, + ): Promise { + return this.requestUnlessClosedOffering( + "ingest.crawlSelectedAsync", + () => this.client.request( + "POST", + "/ingest/crawl-selected/async", + { body: JSON.stringify(params) }, + ), + ); + } + + async getJob(jobId: string): Promise { + return this.client.request( + "GET", + `/ingest/jobs/${encodeURIComponent(jobId)}`, + ); + } + + async listJobs(collectionId: string): Promise { + return this.client.request( + "GET", + `/ingest/jobs?collectionId=${encodeURIComponent(collectionId)}`, + ); + } + + streamJob(jobId: string): IngestionJobStream { + return new IngestionJobStream(this.client.requestRaw( + "GET", + `/ingest/jobs/${encodeURIComponent(jobId)}/stream`, + )); + } + + async cancelJob(jobId: string): Promise { + return this.client.request( + "POST", + `/ingest/jobs/${encodeURIComponent(jobId)}/cancel`, + { body: "{}" }, + ); + } + + private async requestUnlessClosedOffering( + operation: string, + request: () => Promise, + ): Promise { + try { + return await request(); + } catch (error) { + if (error instanceof APIError && isAiTemporarilyUnavailable(error)) { + throw offeringUnavailable(operation, error); + } + throw error; + } + } } diff --git a/typescript/src/resources/managed-contracts.ts b/typescript/src/resources/managed-contracts.ts new file mode 100644 index 0000000..68e2325 --- /dev/null +++ b/typescript/src/resources/managed-contracts.ts @@ -0,0 +1,311 @@ +import type { + AgentBuiltinToolEntry, + ManagedAgent, + ManagedAgentCreateParams, + ManagedWidgetBusinessConfiguration, + ManagedWidgetConfig, + ManagedWidgetCreateParams, + ManagedWidgetUpdateParams, + WidgetAnalytics, + WidgetPosition, + WidgetTheme, + WidgetType, +} from "../types.js"; + +type RecordValue = Record; +const object = (value: unknown): RecordValue => + value && typeof value === "object" && !Array.isArray(value) ? value as RecordValue : {}; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +function exactObject(value: unknown, allowed: readonly string[], message: string): RecordValue { + if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError(message); + const record = value as RecordValue; + for (const key of Object.keys(record)) { + if (!allowed.includes(key)) { + if (["model", "llmConfigId", "fallbackLlmConfigId", "runtimeKind", "runtimeProfileId", "runtimeConnectionId", "runtimePreferences", "mcpServers", "llmModel", "llmSource", "humanEscalation"].includes(key)) { + throw new TypeError(message); + } + throw new TypeError(`Managed contract does not accept ${key}`); + } + } + return record; +} + +const AGENT_FIELDS = ["name", "description", "collectionId", "resources", "systemPrompt", "instructions", "enabledBuiltinTools", "skillIds", "workflowToolIds"] as const; +const AGENT_UPDATE_FIELDS = [...AGENT_FIELDS, "isActive"] as const; + +function presentBuiltinTools(value: unknown): AgentBuiltinToolEntry[] | null { + if (!Array.isArray(value)) return null; + const result: AgentBuiltinToolEntry[] = []; + for (const raw of value) { + if (typeof raw === "string") { + result.push(raw); + continue; + } + const item = object(raw); + if (typeof item.id !== "string") continue; + result.push({ id: item.id, ...(typeof item.humanInTheLoop === "boolean" ? { humanInTheLoop: item.humanInTheLoop } : {}) }); + } + return result; +} + +function projectAgent(value: unknown): ManagedAgent { + const raw = object(value); + const resources = Array.isArray(raw.resources) ? raw.resources.flatMap((item) => { + const resource = object(item); + return resource.type === "collection" && typeof resource.id === "string" + ? [{ type: "collection" as const, id: resource.id, + priority: typeof resource.priority === "number" ? resource.priority : 0, + ...(typeof resource.name === "string" || resource.name === null ? { name: resource.name } : {}) }] + : []; + }) : undefined; + return { + id: typeof raw.id === "string" ? raw.id : "", + name: typeof raw.name === "string" ? raw.name : "", + description: typeof raw.description === "string" || raw.description === null ? raw.description : null, + collectionId: typeof raw.collectionId === "string" || raw.collectionId === null ? raw.collectionId : null, + ...(typeof raw.collectionName === "string" || raw.collectionName === null ? { collectionName: raw.collectionName } : {}), + systemPrompt: typeof raw.systemPrompt === "string" || raw.systemPrompt === null ? raw.systemPrompt : null, + instructions: typeof raw.instructions === "string" || raw.instructions === null ? raw.instructions : null, + ...(resources ? { resources } : {}), + enabledBuiltinTools: presentBuiltinTools(raw.enabledBuiltinTools), + ...(Array.isArray(raw.skillIds) ? { skillIds: raw.skillIds.filter((item): item is string => typeof item === "string") } : {}), + ...(Array.isArray(raw.workflowToolIds) ? { workflowToolIds: raw.workflowToolIds.filter((item): item is string => typeof item === "string") } : {}), + isActive: raw.isActive === true, + createdAt: typeof raw.createdAt === "string" ? raw.createdAt : "", + updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : "", + }; +} + +export function serializeManagedAgent(value: ManagedAgentCreateParams | Record, requireName = false): string { + const raw = exactObject(value, requireName ? AGENT_FIELDS : AGENT_UPDATE_FIELDS, "Managed agents cannot override provider or runtime configuration"); + const stringFields = ["name", "systemPrompt", "instructions", "description", "collectionId"] as const; + for (const key of stringFields) { + const item = raw[key]; + if (item === undefined) continue; + if (item === null && !requireName && ["description", "systemPrompt", "instructions", "collectionId"].includes(key)) continue; + if (typeof item !== "string") throw new TypeError(`${key} must be a string`); + if (key === "name" && (item.trim().length === 0 || item.length > 100)) throw new TypeError("name must contain 1 to 100 characters"); + if (key === "description" && item.length > 500) throw new TypeError("description must be at most 500 characters"); + if (key === "collectionId" && !UUID.test(item)) throw new TypeError("collectionId must be a UUID"); + } + if (requireName && typeof raw.name !== "string") throw new TypeError("name is required"); + if (raw.isActive !== undefined && typeof raw.isActive !== "boolean") throw new TypeError("isActive must be a boolean"); + const body: RecordValue = { ...raw }; + if (raw.resources !== undefined) { + if (!Array.isArray(raw.resources) || raw.resources.length > 30) throw new TypeError("resources must contain at most 30 collection references"); + body.resources = raw.resources.map((item) => { + const resource = exactObject(item, ["type", "id", "priority"], "Managed agent resources accept collection references only"); + if (resource.type !== "collection" || typeof resource.id !== "string" || !UUID.test(resource.id) || + (resource.priority !== undefined && (!Number.isInteger(resource.priority) || Number(resource.priority) < 0 || Number(resource.priority) > 100))) { + throw new TypeError("Managed agent resources accept collection references only"); + } + return { type: "collection", id: resource.id, ...(resource.priority === undefined ? {} : { priority: resource.priority }) }; + }); + } + if (raw.enabledBuiltinTools !== undefined) body.enabledBuiltinTools = presentBuiltinToolsForRequest(raw.enabledBuiltinTools); + for (const key of ["skillIds", "workflowToolIds"] as const) { + if (raw[key] !== undefined && (!Array.isArray(raw[key]) || !raw[key].every((item) => typeof item === "string" && UUID.test(item)))) { + throw new TypeError(`${key} must be an array of UUIDs`); + } + } + return JSON.stringify(body); +} + +function presentBuiltinToolsForRequest(value: unknown): AgentBuiltinToolEntry[] { + if (!Array.isArray(value)) throw new TypeError("enabledBuiltinTools must be an array"); + return value.map((raw) => { + if (typeof raw === "string") return raw; + const item = exactObject(raw, ["id", "humanInTheLoop"], "Managed built-in tool settings accept only tool IDs and confirmation policy"); + if (typeof item.id !== "string" || (item.humanInTheLoop !== undefined && typeof item.humanInTheLoop !== "boolean")) { + throw new TypeError("Managed built-in tools require a string ID"); + } + return { id: item.id, ...(item.humanInTheLoop === undefined ? {} : { humanInTheLoop: item.humanInTheLoop }) }; + }); +} + +export const presentManagedAgent = projectAgent; + +const WIDGET_CREATE_FIELDS = ["name", "type", "collectionId", "agentId", "workflowId", "workflowConfig", "allowedDomains", "theme", "position", "welcomeMessage", "placeholder", "suggestions", "avatarUrl", "displayMode", "locale", "headerTitle", "hidePoweredBy", "customCss", "rateLimitPerMinute", "sessionTtlMinutes"] as const; +const WIDGET_UPDATE_FIELDS = ["name", "workflowConfig", "allowedDomains", "theme", "position", "welcomeMessage", "placeholder", "suggestions", "avatarUrl", "displayMode", "locale", "headerTitle", "hidePoweredBy", "customCss", "rateLimitPerMinute", "sessionTtlMinutes", "isActive"] as const; +const BUSINESS_FIELDS = ["deepActivation", "deepModeLabel", "buttonLabel", "submitLabel", "successMessage", "errorMessage", "fieldOverrides", "maxDisplayedExecutions", "showNodeProgress", "showDuration", "showOutput"] as const; +const FIELD_OVERRIDE_KEYS = ["label", "placeholder", "helpText", "inputType", "options", "required"] as const; +const THEME_KEYS = ["preset", "primaryColor", "primaryTextColor", "backgroundColor", "textColor", "secondaryTextColor", "borderColor", "inputBackgroundColor", "fontFamily", "borderRadius", "shadow", "userMessageBackgroundColor", "userMessageTextColor", "assistantMessageBackgroundColor", "assistantMessageTextColor"] as const; +const POSITIONS: readonly WidgetPosition[] = ["bottom-right", "bottom-left", "top-right", "top-left"]; +const TYPES: readonly WidgetType[] = ["collection", "agent", "workflow-button", "workflow-form", "workflow-webhook"]; +const INPUT_TYPES = ["text", "textarea", "number", "email", "url", "password", "select", "checkbox", "date"] as const; + +function presentBusinessConfig(value: unknown, strict: boolean): ManagedWidgetBusinessConfiguration | undefined { + if (value == null) return undefined; + const raw = strict ? exactObject(value, BUSINESS_FIELDS, "Managed widget configuration accepts business settings only") : object(value); + const result: RecordValue = {}; + for (const key of BUSINESS_FIELDS) { + const item = raw[key]; + if (item === undefined) continue; + if (key === "fieldOverrides") { + if (!item || typeof item !== "object" || Array.isArray(item)) { + if (strict) throw new TypeError("fieldOverrides must be an object"); + continue; + } + if (strict && Object.keys(item as RecordValue).length > 64) throw new TypeError("fieldOverrides supports at most 64 fields"); + const overrides: RecordValue = {}; + for (const [name, config] of Object.entries(item as RecordValue).slice(0, 64)) { + if (strict && name.length > 100) throw new TypeError("field override names must be at most 100 characters"); + const field = strict ? exactObject(config, FIELD_OVERRIDE_KEYS, "Managed widget field overrides accept supported UI fields only") : object(config); + const safe: RecordValue = {}; + for (const fieldKey of FIELD_OVERRIDE_KEYS) { + const child = field[fieldKey]; + if (fieldKey === "options" && Array.isArray(child)) { + if (strict && child.length > 100) throw new TypeError("widget field options support at most 100 values"); + safe.options = child.slice(0, 100).flatMap((option) => { + const optionRecord = strict ? exactObject(option, ["label", "value"], "Managed widget options accept label and value only") : object(option); + if (typeof optionRecord.label === "string" && typeof optionRecord.value === "string" && optionRecord.value.length <= 1000) { + return [{ label: optionRecord.label, value: optionRecord.value }]; + } + if (strict) throw new TypeError("widget options require string labels and values up to 1000 characters"); + return []; + }); + } else if (fieldKey === "options" && child !== undefined && strict) throw new TypeError("widget field options must be an array"); + else if (fieldKey === "inputType" && typeof child === "string" && (INPUT_TYPES as readonly string[]).includes(child)) safe.inputType = child; + else if (["label", "placeholder", "helpText"].includes(fieldKey) && typeof child === "string") { + const maximum = fieldKey === "helpText" ? 2000 : 500; + if (strict && child.length > maximum) throw new TypeError(`${fieldKey} exceeds ${maximum} characters`); + safe[fieldKey] = child; + } + else if (fieldKey === "required" && typeof child === "boolean") safe.required = child; + else if (child !== undefined && strict) throw new TypeError(`Invalid widget field setting: ${fieldKey}`); + } + overrides[name] = safe; + } + result.fieldOverrides = overrides; + } else if (["deepActivation"].includes(key) && (item === "disabled" || item === "visitor_allowed")) result[key] = item; + else if (["deepModeLabel", "buttonLabel", "submitLabel", "successMessage", "errorMessage"].includes(key) && typeof item === "string") { + const maximum = ["successMessage", "errorMessage"].includes(key) ? 2000 : 500; + if (strict && item.length > maximum) throw new TypeError(`${key} exceeds ${maximum} characters`); + result[key] = item; + } + else if (key === "maxDisplayedExecutions" && typeof item === "number" && Number.isInteger(item) && item >= 1 && item <= 50) result[key] = item; + else if (["showNodeProgress", "showDuration", "showOutput"].includes(key) && typeof item === "boolean") result[key] = item; + else if (strict) throw new TypeError(`Invalid managed widget business setting: ${key}`); + } + return result as ManagedWidgetBusinessConfiguration; +} + +function presentTheme(value: unknown, strict = false): WidgetTheme | undefined { + if (value == null) return undefined; + const raw = strict ? exactObject(value, THEME_KEYS, "Managed widget theme accepts presentation fields only") : object(value); + const result: RecordValue = {}; + for (const key of THEME_KEYS) { + if (raw[key] === undefined) continue; + if (key === "preset" && ["light", "dark", "auto"].includes(String(raw[key]))) result[key] = raw[key]; + else if (key !== "preset" && typeof raw[key] === "string") result[key] = raw[key]; + else if (strict) throw new TypeError(`Invalid managed widget theme field: ${key}`); + } + return result as WidgetTheme; +} + +function serializeWidget(value: ManagedWidgetCreateParams | ManagedWidgetUpdateParams | Record, create: boolean): string { + const raw = exactObject(value, create ? WIDGET_CREATE_FIELDS : WIDGET_UPDATE_FIELDS, "Managed widgets cannot select a provider or include secret configuration"); + const body: RecordValue = { ...raw }; + for (const key of ["name", "collectionId", "agentId", "workflowId", "welcomeMessage", "placeholder", "avatarUrl"] as const) { + if (raw[key] !== undefined && typeof raw[key] !== "string") throw new TypeError(`${key} must be a string`); + } + if (raw.name !== undefined && (!String(raw.name).trim() || String(raw.name).length > 100)) throw new TypeError("name must contain 1 to 100 characters"); + if (raw.welcomeMessage !== undefined && String(raw.welcomeMessage).length > 500) throw new TypeError("welcomeMessage must be at most 500 characters"); + if (raw.workflowId !== undefined && !UUID.test(String(raw.workflowId))) throw new TypeError("workflowId must be a UUID"); + if (raw.avatarUrl !== undefined) { + try { new URL(String(raw.avatarUrl)); } catch { throw new TypeError("avatarUrl must be a valid URL"); } + } + for (const key of ["headerTitle", "customCss"] as const) { + if (raw[key] !== undefined && raw[key] !== null && typeof raw[key] !== "string") throw new TypeError(`${key} must be a string or null`); + } + if (typeof raw.headerTitle === "string" && raw.headerTitle.length > 100) throw new TypeError("headerTitle must be at most 100 characters"); + if (typeof raw.customCss === "string" && raw.customCss.length > 20000) throw new TypeError("customCss must be at most 20000 characters"); + for (const key of ["hidePoweredBy", "isActive"] as const) { + if (raw[key] !== undefined && typeof raw[key] !== "boolean") throw new TypeError(`${key} must be a boolean`); + } + if (raw.displayMode !== undefined && raw.displayMode !== "support" && raw.displayMode !== "debug") throw new TypeError("Invalid displayMode"); + if (raw.locale !== undefined && raw.locale !== null && raw.locale !== "fr" && raw.locale !== "en") throw new TypeError("Invalid locale"); + if (raw.rateLimitPerMinute !== undefined && (!Number.isInteger(raw.rateLimitPerMinute) || Number(raw.rateLimitPerMinute) < 1 || Number(raw.rateLimitPerMinute) > 60)) throw new TypeError("rateLimitPerMinute must be an integer from 1 to 60"); + if (raw.sessionTtlMinutes !== undefined && (!Number.isInteger(raw.sessionTtlMinutes) || Number(raw.sessionTtlMinutes) < 5 || Number(raw.sessionTtlMinutes) > 120)) throw new TypeError("sessionTtlMinutes must be an integer from 5 to 120"); + if (raw.workflowConfig !== undefined) { + if (raw.workflowConfig === null) throw new TypeError("Managed widget configuration must be an object"); + body.workflowConfig = presentBusinessConfig(raw.workflowConfig, true); + } + if (raw.theme !== undefined) { + if (raw.theme === null) throw new TypeError("Managed widget theme must be an object"); + body.theme = presentTheme(raw.theme, true); + } + if (raw.suggestions !== undefined) { + if (!Array.isArray(raw.suggestions) || raw.suggestions.length > 5 || raw.suggestions.some((item) => { + const entry = exactObject(item, ["title", "prompt"], "Managed widget suggestions accept title and prompt only"); + return typeof entry.title !== "string" || typeof entry.prompt !== "string"; + })) throw new TypeError("Managed widget suggestions require title and prompt"); + body.suggestions = raw.suggestions.map((item) => ({ title: item.title, prompt: item.prompt })); + } + if (raw.allowedDomains !== undefined && (!Array.isArray(raw.allowedDomains) || !raw.allowedDomains.every((item) => typeof item === "string"))) throw new TypeError("allowedDomains must be an array of strings"); + if (raw.position !== undefined && !(POSITIONS as readonly unknown[]).includes(raw.position)) throw new TypeError("Invalid widget position"); + if (raw.type !== undefined && !(TYPES as readonly unknown[]).includes(raw.type)) throw new TypeError("Invalid widget type"); + if (create && (typeof raw.name !== "string" || !raw.name.trim() || typeof raw.type !== "string")) throw new TypeError("Managed widgets require a name and type"); + return JSON.stringify(body); +} + +function presentWidget(value: unknown): ManagedWidgetConfig { + const raw = object(value); + const suggestions = Array.isArray(raw.suggestions) ? raw.suggestions.flatMap((item) => { + const entry = object(item); + return typeof entry.title === "string" && typeof entry.prompt === "string" ? [{ title: entry.title, prompt: entry.prompt }] : []; + }) : null; + return { + id: typeof raw.id === "string" ? raw.id : "", + name: typeof raw.name === "string" ? raw.name : "", + type: (TYPES as readonly unknown[]).includes(raw.type) ? raw.type as WidgetType : "collection", + collectionId: typeof raw.collectionId === "string" || raw.collectionId === null ? raw.collectionId : null, + agentId: typeof raw.agentId === "string" || raw.agentId === null ? raw.agentId : null, + workflowId: typeof raw.workflowId === "string" || raw.workflowId === null ? raw.workflowId : null, + workflowConfig: presentBusinessConfig(raw.workflowConfig, false) ?? null, + keyPrefix: typeof raw.keyPrefix === "string" ? raw.keyPrefix : "", + allowedDomains: Array.isArray(raw.allowedDomains) ? raw.allowedDomains.filter((item): item is string => typeof item === "string") : [], + theme: presentTheme(raw.theme) ?? null, + position: (POSITIONS as readonly unknown[]).includes(raw.position) ? raw.position as WidgetPosition : "bottom-right", + welcomeMessage: typeof raw.welcomeMessage === "string" || raw.welcomeMessage === null ? raw.welcomeMessage : null, + placeholder: typeof raw.placeholder === "string" || raw.placeholder === null ? raw.placeholder : null, + suggestions, + avatarUrl: typeof raw.avatarUrl === "string" || raw.avatarUrl === null ? raw.avatarUrl : null, + displayMode: raw.displayMode === "debug" ? "debug" : "support", + locale: raw.locale === "fr" || raw.locale === "en" ? raw.locale : null, + headerTitle: typeof raw.headerTitle === "string" || raw.headerTitle === null ? raw.headerTitle : null, + hidePoweredBy: raw.hidePoweredBy === true, + customCss: typeof raw.customCss === "string" || raw.customCss === null ? raw.customCss : null, + rateLimitPerMinute: typeof raw.rateLimitPerMinute === "number" ? raw.rateLimitPerMinute : 10, + sessionTtlMinutes: typeof raw.sessionTtlMinutes === "number" ? raw.sessionTtlMinutes : 30, + isActive: raw.isActive === true, + createdAt: typeof raw.createdAt === "string" ? raw.createdAt : "", + updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : "", + }; +} + +function presentAnalytics(value: unknown): WidgetAnalytics { + const raw = object(value); + const number = (key: string) => typeof raw[key] === "number" ? raw[key] as number : 0; + return { + totalSessions: number("totalSessions"), totalMessages: number("totalMessages"), + averageMessagesPerSession: number("averageMessagesPerSession"), uniqueVisitors: number("uniqueVisitors"), + topQueries: Array.isArray(raw.topQueries) ? raw.topQueries.flatMap((item) => { + const entry = object(item); return typeof entry.message === "string" && typeof entry.count === "number" ? [{ message: entry.message, count: entry.count }] : []; + }) : [], + dailyBreakdown: Array.isArray(raw.dailyBreakdown) ? raw.dailyBreakdown.flatMap((item) => { + const entry = object(item); return typeof entry.date === "string" && typeof entry.sessions === "number" && typeof entry.messages === "number" + ? [{ date: entry.date, sessions: entry.sessions, messages: entry.messages }] : []; + }) : [], + conversationFeedbacks: number("conversationFeedbacks"), resolvedCount: number("resolvedCount"), + resolutionRate: number("resolutionRate"), averageRating: typeof raw.averageRating === "number" ? raw.averageRating : null, + }; +} + +export const managedWidgetContracts = { + serializeCreate: (value: ManagedWidgetCreateParams | Record) => serializeWidget(value, true), + serializeUpdate: (value: ManagedWidgetUpdateParams | Record) => serializeWidget(value, false), + present: presentWidget, + presentAnalytics, +}; diff --git a/typescript/src/resources/rag-ab-tests.ts b/typescript/src/resources/rag-ab-tests.ts new file mode 100644 index 0000000..485ffea --- /dev/null +++ b/typescript/src/resources/rag-ab-tests.ts @@ -0,0 +1,14 @@ +import type { BaseClient } from "../client.js"; +import type { RagAbTestParams, RagAbTestResult } from "../types.js"; + +export class RagAbTests { + constructor(private client: BaseClient) {} + + /** Compare two transient RAG configurations. Does not promote or persist either config. */ + async run(collectionId: string, params: RagAbTestParams): Promise { + return this.client.request("POST", `/collections/${encodeURIComponent(collectionId)}/rag-config/test`, { + body: JSON.stringify(params), + timeout: 120_000, + }); + } +} diff --git a/typescript/src/resources/traces.ts b/typescript/src/resources/traces.ts new file mode 100644 index 0000000..a3f6f26 --- /dev/null +++ b/typescript/src/resources/traces.ts @@ -0,0 +1,52 @@ +import type { BaseClient } from "../client.js"; +import type { + Trace, + TraceExport, + TraceExportParams, + TraceListParams, + TraceListResponse, + TraceMetrics, + TraceMetricsParams, +} from "../types.js"; + +function query(params: Record): string { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value === undefined || value === null || value === "") continue; + if (Array.isArray(value)) value.forEach((item) => search.append(key, String(item))); + else search.set(key, String(value)); + } + const encoded = search.toString(); + return encoded ? `?${encoded}` : ""; +} + +export class Traces { + constructor(private client: BaseClient) {} + + async list(params: TraceListParams = {}): Promise { + return this.client.request("GET", `/traces${query(params)}`); + } + + async get(traceId: string, options: { includeChildren?: boolean; maxDepth?: number } = {}): Promise { + const result = await this.client.request<{ trace: Trace }>( + "GET", + `/traces/${encodeURIComponent(traceId)}${query(options)}`, + ); + return result.trace; + } + + async metrics(params: TraceMetricsParams): Promise { + return this.client.request("GET", `/traces/metrics${query(params)}`); + } + + async export(params: TraceExportParams): Promise { + const response = await this.client.requestRaw("GET", `/traces/export${query(params)}`); + const disposition = response.headers.get("content-disposition") ?? ""; + const filename = /filename="?([^";]+)"?/i.exec(disposition)?.[1] ?? `traces.${params.format}`; + return { + filename, + contentType: response.headers.get("content-type") ?? "application/octet-stream", + content: await response.text(), + }; + } +} diff --git a/typescript/src/resources/widgets.ts b/typescript/src/resources/widgets.ts new file mode 100644 index 0000000..b91d33a --- /dev/null +++ b/typescript/src/resources/widgets.ts @@ -0,0 +1,116 @@ +import type { BaseClient } from "../client.js"; +import type { + WidgetAnalytics, + WidgetConfig, + WidgetCreateParams, + WidgetCreateResult, + WidgetKeyResult, + WidgetUpdateParams, + ManagedWidgetConfig, + ManagedWidgetCreateParams, + ManagedWidgetUpdateParams, + ManagedWidgetCreateResult, +} from "../types.js"; +import { managedWidgetContracts } from "./managed-contracts.js"; + +class ManagedWidgets { + constructor(private readonly client: BaseClient) {} + + async list(): Promise { + const data = await this.client.request("GET", "/widgets"); + const widgets = data && typeof data === "object" && Array.isArray((data as { widgets?: unknown[] }).widgets) + ? (data as { widgets: unknown[] }).widgets : []; + return widgets.map(managedWidgetContracts.present); + } + + async get(id: string): Promise { + return managedWidgetContracts.present(await this.client.request("GET", `/widgets/${encodeURIComponent(id)}`)); + } + + async create(params: ManagedWidgetCreateParams): Promise { + const value = await this.client.request("POST", "/widgets", { + body: managedWidgetContracts.serializeCreate(params), + }); + const result = value && typeof value === "object" ? value as Record : {}; + return { + widget: managedWidgetContracts.present(result.widget), + widgetKey: typeof result.widgetKey === "string" ? result.widgetKey : "", + embedCode: typeof result.embedCode === "string" ? result.embedCode : "", + }; + } + + async update(id: string, params: ManagedWidgetUpdateParams): Promise { + return managedWidgetContracts.present(await this.client.request("PUT", `/widgets/${encodeURIComponent(id)}`, { + body: managedWidgetContracts.serializeUpdate(params), + })); + } + + async delete(id: string): Promise { + await this.client.requestRaw("DELETE", `/widgets/${encodeURIComponent(id)}`); + } + + async regenerateKey(id: string): Promise { + const value = await this.client.request("POST", `/widgets/${encodeURIComponent(id)}/regenerate-key`, { body: "{}" }); + const result = value && typeof value === "object" ? value as Record : {}; + return { widgetKey: typeof result.widgetKey === "string" ? result.widgetKey : "", embedCode: typeof result.embedCode === "string" ? result.embedCode : "" }; + } + + async analytics(id: string, period: "7d" | "30d" | "90d" = "30d"): Promise { + const data = await this.client.request("GET", `/widgets/${encodeURIComponent(id)}/analytics?period=${period}`); + return managedWidgetContracts.presentAnalytics(data); + } +} + +export class Widgets { + readonly managed: ManagedWidgets; + + constructor(private readonly client: BaseClient) { + this.managed = new ManagedWidgets(client); + } + + async list(): Promise { + const data = await this.client.request<{ widgets: WidgetConfig[] }>( + "GET", + "/widgets", + ); + return data.widgets; + } + + async get(id: string): Promise { + return this.client.request("GET", `/widgets/${id}`); + } + + async create(params: WidgetCreateParams): Promise { + return this.client.request("POST", "/widgets", { + body: JSON.stringify(params), + }); + } + + async update(id: string, params: WidgetUpdateParams): Promise { + return this.client.request("PUT", `/widgets/${id}`, { + body: JSON.stringify(params), + }); + } + + async delete(id: string): Promise { + await this.client.requestRaw("DELETE", `/widgets/${id}`); + } + + async regenerateKey(id: string): Promise { + return this.client.request( + "POST", + `/widgets/${id}/regenerate-key`, + { body: "{}" }, + ); + } + + async analytics( + id: string, + period: "7d" | "30d" | "90d" = "30d", + ): Promise { + return this.client.request( + "GET", + `/widgets/${id}/analytics?period=${period}`, + ); + } +} diff --git a/typescript/src/resources/workflows.ts b/typescript/src/resources/workflows.ts index 604da63..bab1d36 100644 --- a/typescript/src/resources/workflows.ts +++ b/typescript/src/resources/workflows.ts @@ -4,11 +4,21 @@ import type { WorkflowCreateParams, WorkflowExecution, WorkflowExecutionResult, + ManagedWorkflowExecutionResult, WorkflowListItem, WorkflowUpdateParams, WorkflowValidationResult, } from "../types.js"; +function serializeManagedExecution(params: { + requestId: string; + input?: Record; +}): string { + if (typeof params.requestId !== "string" || params.requestId.length === 0) + throw new TypeError("requestId must be a non-empty string"); + return JSON.stringify(params); +} + export class Workflows { constructor(private readonly client: BaseClient) {} @@ -55,6 +65,18 @@ export class Workflows { ); } + /** Starts a SaaS execution through the durable credit admission contract. */ + async executeManaged( + id: string, + params: { requestId: string; input?: Record }, + ): Promise { + return this.client.request( + "POST", + `/workflows/${id}/execute`, + { body: serializeManagedExecution(params) }, + ); + } + async listExecutions( workflowId: string, options: { limit?: number } = {}, @@ -74,7 +96,7 @@ export class Workflows { } /** Cancels the remote execution. Aborting an HTTP request does not call this method. */ - async cancelExecution(executionId: string): Promise<{ success: boolean }> { + async cancelExecution(executionId: string): Promise<{ cancelled: boolean }> { return this.client.request( "DELETE", `/workflows/executions/${executionId}`, diff --git a/typescript/src/streaming.ts b/typescript/src/streaming.ts index ead5ba8..8011ab3 100644 --- a/typescript/src/streaming.ts +++ b/typescript/src/streaming.ts @@ -6,6 +6,8 @@ import type { AgentChatStreamEvent, ProgressiveStreamEvent, DeepResearchStreamEvent, + IngestionJob, + IngestionJobStreamEvent, } from "./types.js"; import { ProtocolError } from "./errors.js"; @@ -35,6 +37,33 @@ export class DeepResearchStream implements AsyncIterable { + private consumed = false; + + constructor(private readonly response: Response | Promise) {} + + async *[Symbol.asyncIterator](): AsyncIterableIterator { + if (this.consumed) throw new Error("Stream has already been consumed"); + this.consumed = true; + for await (const event of parseSSE(await this.response)) { + const parsed = tryParseJSON(event.data) ?? event.data; + const mapped: IngestionJobStreamEvent = { type: event.event, data: parsed }; + yield mapped; + if ( + event.event === "error" || + (event.event === "state" && + typeof parsed === "object" && + parsed !== null && + TERMINAL_INGESTION_STATES.has((parsed as IngestionJob).status)) + ) { + break; + } + } + } +} + export const MAX_SSE_FRAME_BYTES = 65_536; /** diff --git a/typescript/src/types.ts b/typescript/src/types.ts index 37e01d6..cde020f 100644 --- a/typescript/src/types.ts +++ b/typescript/src/types.ts @@ -1,3 +1,5 @@ +import type { components as PublicApiComponents, operations as PublicApiOperations } from "./generated/public-api.js"; + // ─── Client ──────────────────────────────────────────────────────── export interface ClientOptions { @@ -17,6 +19,55 @@ export interface ClientOptions { defaultHeaders?: Record; } +export type FeedbackParams = { + type: "bug" | "feature" | "other"; + message: string; +}; + +export type FeedbackResult = { + success: boolean; + message: string; +}; + +export type TraceType = "llm" | "agent" | "retrieval" | "rerank" | "tool" | "judge" | "workflow" | "ingestion" | "ab_test"; +export type TraceStatus = "success" | "error"; +export type Trace = Record & { id: string; type: TraceType; status: TraceStatus }; +export type TraceListParams = { + page?: number; limit?: number; type?: TraceType; status?: TraceStatus; + collectionId?: string; sessionId?: string; search?: string; tags?: string[]; + startDate?: string; endDate?: string; parentOnly?: boolean; +}; +export type TraceListResponse = { traces: Trace[]; pagination: Record }; +export type TraceMetricsParams = { + startDate: string; endDate: string; collectionId?: string; type?: TraceType; + granularity?: "day" | "week" | "month"; +}; +export type TraceMetrics = Record; +export type TraceExportParams = TraceMetricsParams & { + format: "csv" | "json"; status?: TraceStatus; includeInputOutput?: boolean; +}; +export type TraceExport = { filename: string; contentType: string; content: string }; + +export type RagConfigCandidate = Record; +export type RagAbTestParams = { + configA: RagConfigCandidate; + configB: RagConfigCandidate; + testQuery: string; + evaluateQuality?: boolean; +}; +export type RagAbTestResult = { + configA: Record; + configB: Record; + comparison: { + speedDifferenceMs: number; + speedWinner: "A" | "B" | "tie"; + resultOverlap: number; + recommendation: string; + qualityWinner?: "A" | "B" | "tie"; + [key: string]: unknown; + }; +}; + // ─── Workflows ──────────────────────────────────────────────────── export type WorkflowNode = { @@ -78,6 +129,7 @@ export type WorkflowListItem = Pick< export type WorkflowCreateParams = { name: string; + isActive?: PublicApiComponents["schemas"]["CreateWorkflowRequest"]["isActive"]; description?: string; graph?: WorkflowGraph; variables?: WorkflowVariable[]; @@ -113,6 +165,13 @@ export type WorkflowExecutionResult = { error?: string; }; +/** Server-admitted workflow execution used by the SaaS product mode. */ +export type ManagedWorkflowExecutionResult = WorkflowExecutionResult & { + reconciliationRequired: boolean; + maximumMilliCredits: string; + chargedMilliCredits: string | null; +}; + export type WorkflowValidationResult = { valid: boolean; errors: Array<{ type: string; message: string; nodeId?: string; edgeId?: string }>; @@ -287,6 +346,11 @@ export interface AgentSkill { createdByUserId: string | null; createdAt: string; updatedAt: string; + currentVersion?: number; + contentHash?: string; + origin?: "organization" | "builtin"; + readOnly?: boolean; + builtinVersion?: string; } export interface AgentSkillCreateParams { @@ -307,6 +371,10 @@ export interface AgentCreateParams { name: string; description?: string; collectionId?: string | null; + /** Licensed BYOK selection; managed SaaS uses agents.managed instead. */ + llmConfigId?: PublicApiComponents["schemas"]["CreateAgentRequest"]["llmConfigId"]; + fallbackLlmConfigId?: PublicApiComponents["schemas"]["CreateAgentRequest"]["fallbackLlmConfigId"]; + runtimeKind?: PublicApiComponents["schemas"]["CreateAgentRequest"]["runtimeKind"]; systemPrompt?: string; instructions?: string; model?: string; @@ -358,6 +426,46 @@ export type ChunkingStrategy = export type PublicCollectionRequiredPlanId = "pro" | "scale" | "enterprise"; +export interface PublicCollectionPublisher { + name: string; + isSystem: boolean; +} + +/** Receipt provenance is distinct from a qualification of the official corpus. */ +export interface CollectionServedSource { + status: "verified_receipt" | "unknown"; + officialCorpusQualified: false; + sourceRevision: string | null; + sourceTimestamp: string | null; + activatedAt: string | null; +} + +export interface PublicCollectionSummary { + /** Optional for compatibility with supported older server contracts. */ + sourceDataset?: string | null; + lastSyncedAt?: string | null; + servedSource?: CollectionServedSource; + id: string; + slug: string; + name: string; + description: string | null; + publisher: PublicCollectionPublisher; + requiredPlanId: PublicCollectionRequiredPlanId | null; + accessible: boolean; + documentCount: number; + updatedAt: string; +} + +export interface PublicCollectionDetail extends PublicCollectionSummary { + tags: string[]; + sampleQueries: string[]; +} + +export interface PublicCollectionListParams { + minTier?: PublicCollectionRequiredPlanId; + query?: string; +} + export type CollectionAccessTier = | "owner" | "shared" @@ -365,6 +473,8 @@ export type CollectionAccessTier = | "public-gated"; export interface Collection { + lastSyncedAt?: string | null; + servedSource?: CollectionServedSource; id: string; name: string; description: string | null; @@ -392,12 +502,20 @@ export interface Collection { export interface CollectionCreateParams { name: string; description?: string; + /** Select an owned embedding configuration instead of the workspace default. */ + embeddingConfigId?: PublicApiComponents["schemas"]["CreateCollectionRequest"]["embeddingConfigId"]; + /** Rejected unless omitted or `private`. Publish with `collections.updateVisibility`. */ visibility?: "private" | "shared" | "public"; sourceDataset?: string; slug?: string; requiredPlanId?: PublicCollectionRequiredPlanId; } +export interface CollectionVisibilityUpdateParams { + visibility: "private" | "shared" | "public"; + requiredPlanId?: PublicCollectionRequiredPlanId | null; +} + export interface CollectionUpdateParams { name?: string; description?: string; @@ -407,6 +525,8 @@ export interface CollectionUpdateParams { // ─── Chat ────────────────────────────────────────────────────────── export interface ChatParams { + /** Positive integer milli-credits. Required by SaaS; never a provider price. */ + maximumMilliCredits?: string; collectionId: string; query: string; history?: ChatMessage[]; @@ -424,6 +544,119 @@ export interface ChatResponse { featuresUsed?: string[]; } +/** Request accepted by the platform-managed RAG chat contract. */ +export interface ManagedChatParams { + collectionId: string; + query: string; + maximumMilliCredits?: string; + history?: ChatMessage[]; + includeImages?: boolean; + filters?: FilterDefinition[]; +} + +/** Public business response. Provider/model and internal usage details are omitted. */ +export interface ManagedChatResponse { + answer: string; + sources: Source[]; + images?: ImageResult[]; + relevanceScore?: number; +} + +export type ManagedProgressiveStreamEvent = + | { type: "stage"; stage: string; elapsed: number } + | { type: "enhancement"; original: string; enhanced: string; multiQueries?: string[]; featuresUsed: string[] } + | { type: "sources"; sources: Source[]; images?: ImageResult[]; retrievalTimeMs: number } + | { type: "chunk"; content: string } + | { type: "citation"; index: number; sourceId: string; position: number } + | { type: "metrics"; pipelineMetrics: PipelineMetrics; featuresUsed: string[] } + | { type: "done" } + | { type: "error"; error: string }; + +/** Business-facing agent fields available in managed workspaces. */ +export interface ManagedAgent { + id: string; + name: string; + description: string | null; + collectionId: string | null; + collectionName?: string | null; + systemPrompt: string | null; + instructions: string | null; + resources?: Array<{ type: "collection"; id: string; priority: number; name?: string | null }>; + enabledBuiltinTools: AgentBuiltinToolEntry[] | null; + skillIds?: string[]; + workflowToolIds?: string[]; + isActive: boolean; + createdAt: string; + updatedAt: string; +} + +/** Platform-managed agent configuration excludes model, provider, MCP, and runtime fields. */ +export interface ManagedAgentCreateParams { + name: string; + description?: string; + collectionId?: string | null; + resources?: Array<{ type: "collection"; id: string; priority?: number }>; + systemPrompt?: string; + instructions?: string; + enabledBuiltinTools?: AgentBuiltinToolEntry[]; + skillIds?: string[]; + workflowToolIds?: string[]; +} + +export type ManagedAgentUpdateParams = Omit, "description" | "systemPrompt" | "instructions"> & { + description?: string | null; + systemPrompt?: string | null; + instructions?: string | null; + isActive?: boolean; +}; + +/** Explicit durable, metered SaaS agent chat admission request. */ +export interface ManagedAgentChatStartParams { + requestId: string; + sessionId: string; + query: string; + history?: ChatMessage[]; + maximumMilliCredits: string; +} + +export interface ManagedAgentChatOutput { + response: string; + sources: Array<{ + id?: string; + content?: string; + type?: string; + sourceType?: string; + source?: string; + documentId?: string; + title?: string; + pageNumber?: number; + imageIndex?: number; + score?: number; + }>; + history: ChatMessage[]; +} + +export interface ManagedAgentChatResponse { + executionId: string; + request: ManagedAgentChatStartParams & { history: ChatMessage[] }; + status: "pending" | "running" | "completed" | "failed" | "cancelled" | "cancelling"; + reconciliationRequired: boolean; + output: ManagedAgentChatOutput | null; + maximumMilliCredits: string; + chargedMilliCredits: string | null; +} + +export interface ManagedAgentChatSummary { + executionId: string; + createdAt: string; + question: string; +} + +export interface ManagedAgentChatHistory { + items: ManagedAgentChatSummary[]; + nextCursor: string | null; +} + export interface AgentChatParams { query: string; sessionId?: string; @@ -527,6 +760,9 @@ export interface IngestDocumentParams { export interface IngestFileParams { collectionId: string; file: File | Blob; + ocrMode?: NonNullable["content"]["multipart/form-data"]["ocrMode"]; + enableMultimodal?: boolean; + mode?: "documents" | "tabular" | "web"; } export interface IngestCrawlParams { @@ -562,6 +798,290 @@ export interface CrawlResult extends IngestResult { pagesCount: number; } +export interface AsyncIngestResult { + success: boolean; + jobId: string; + message: string; +} + +export type IngestionJobStatus = + | "pending" + | "processing" + | "completed" + | "failed" + | "cancelled"; + +export type IngestionJobSource = "file" | "crawl" | "dataset" | "migration"; + +export type IngestionJobStep = + | "uploading" + | "extracting" + | "chunking" + | "embedding" + | "indexing"; + +export interface IngestionJob { + id: string; + collectionId: string; + source: IngestionJobSource; + status: IngestionJobStatus; + progress: { + current: number; + total: number; + step: IngestionJobStep; + }; + metrics: Record; + result?: Record; + error?: string; + startedAt: string; + completedAt?: string; + metadata?: Record; +} + +export interface IngestionJobResponse { + success: boolean; + job: IngestionJob; +} + +export interface IngestionJobsResponse { + success: boolean; + jobs: IngestionJob[]; +} + +export interface IngestionJobCancelResponse { + success: boolean; + message: string; +} + +export type IngestionJobStreamEvent = + | { type: "state"; data: IngestionJob } + | { type: "heartbeat"; data: { timestamp: number } } + | { type: "error"; data: unknown } + | { type: string; data: unknown }; + +export interface DiscoverSiteParams { + url: string; + maxPages?: number; + maxDepth?: number; + excludePatterns?: string[]; + includePatterns?: string[]; +} + +export interface DiscoveredPage { + url: string; + title: string | null; + depth: number; + path: string; +} + +export interface DiscoverSiteResult { + success: boolean; + pages: DiscoveredPage[]; + totalFound: number; + duration: number; +} + +export interface CrawlSelectedParams { + collectionId: string; + urls: string[]; + enableMultimodal?: boolean; +} + +// ─── Widgets ─────────────────────────────────────────────────────── + +export type WidgetType = + | "collection" + | "agent" + | "workflow-button" + | "workflow-form" + | "workflow-webhook"; + +export type WidgetPosition = + | "bottom-right" + | "bottom-left" + | "top-right" + | "top-left"; + +export interface WidgetTheme { + preset?: "light" | "dark" | "auto"; + primaryColor?: string; + primaryTextColor?: string; + backgroundColor?: string; + textColor?: string; + secondaryTextColor?: string; + borderColor?: string; + inputBackgroundColor?: string; + fontFamily?: string; + borderRadius?: string; + shadow?: string; + userMessageBackgroundColor?: string; + userMessageTextColor?: string; + assistantMessageBackgroundColor?: string; + assistantMessageTextColor?: string; +} + +export interface WidgetSuggestion { + title: string; + prompt: string; +} + +export interface WidgetHumanEscalation { + type: "mailto" | "url" | "webhook"; + target: string; + label?: string; +} + +export interface WidgetConfig { + id: string; + name: string; + type: WidgetType; + collectionId: string | null; + agentId: string | null; + workflowId: string | null; + workflowConfig: Record | null; + keyPrefix: string; + allowedDomains: string[]; + theme: WidgetTheme | null; + position: WidgetPosition; + welcomeMessage: string | null; + placeholder: string | null; + suggestions: WidgetSuggestion[] | null; + avatarUrl: string | null; + displayMode: "support" | "debug"; + locale: "fr" | "en" | null; + headerTitle: string | null; + hidePoweredBy: boolean; + customCss: string | null; + humanEscalation: WidgetHumanEscalation | null; + rateLimitPerMinute: number; + sessionTtlMinutes: number; + llmConfigId: string | null; + llmModel: string | null; + llmSource: "byok" | "platform"; + isActive: boolean; + createdAt: string; + updatedAt: string; +} + +/** Managed widget DTO; omits provider selection and potentially secret escalation targets. */ +export type ManagedWidgetConfig = Omit & { + workflowConfig: ManagedWidgetBusinessConfiguration | null; + }; + +export interface ManagedWidgetBusinessConfiguration { + deepActivation?: "disabled" | "visitor_allowed"; + deepModeLabel?: string; + buttonLabel?: string; + submitLabel?: string; + successMessage?: string; + errorMessage?: string; + fieldOverrides?: Record; + required?: boolean; + }>; + maxDisplayedExecutions?: number; + showNodeProgress?: boolean; + showDuration?: boolean; + showOutput?: boolean; +} + +export type ManagedWidgetCreateParams = Omit & { + workflowConfig?: ManagedWidgetBusinessConfiguration; + }; + +export type ManagedWidgetUpdateParams = Omit & { + workflowConfig?: ManagedWidgetBusinessConfiguration; + }; + +export interface ManagedWidgetCreateResult { + widget: ManagedWidgetConfig; + /** One-time public embed credential required to install the widget. */ + widgetKey: string; + embedCode: string; +} + +export interface WidgetCreateParams { + name: string; + type: WidgetType; + collectionId?: string; + agentId?: string; + workflowId?: string; + workflowConfig?: Record; + allowedDomains?: string[]; + theme?: WidgetTheme; + position?: WidgetPosition; + welcomeMessage?: string; + placeholder?: string; + suggestions?: WidgetSuggestion[]; + avatarUrl?: string; + displayMode?: "support" | "debug"; + locale?: "fr" | "en" | null; + headerTitle?: string | null; + hidePoweredBy?: boolean; + customCss?: string | null; + humanEscalation?: WidgetHumanEscalation | null; + rateLimitPerMinute?: number; + sessionTtlMinutes?: number; + llmConfigId?: string; + llmModel?: string; + llmSource?: "byok" | "platform"; +} + +export interface WidgetUpdateParams { + name?: string; + allowedDomains?: string[]; + theme?: WidgetTheme; + position?: WidgetPosition; + welcomeMessage?: string; + placeholder?: string; + suggestions?: WidgetSuggestion[]; + avatarUrl?: string; + displayMode?: "support" | "debug"; + locale?: "fr" | "en" | null; + headerTitle?: string | null; + hidePoweredBy?: boolean; + customCss?: string | null; + humanEscalation?: WidgetHumanEscalation | null; + rateLimitPerMinute?: number; + sessionTtlMinutes?: number; + llmConfigId?: string | null; + llmModel?: string | null; + llmSource?: "byok" | "platform"; + workflowConfig?: Record; + isActive?: boolean; +} + +export interface WidgetCreateResult { + widget: WidgetConfig; + widgetKey: string; + embedCode: string; +} + +export interface WidgetKeyResult { + widgetKey: string; + embedCode: string; +} + +export interface WidgetAnalytics { + totalSessions: number; + totalMessages: number; + averageMessagesPerSession: number; + uniqueVisitors: number; + topQueries: Array<{ message: string; count: number }>; + dailyBreakdown: Array<{ date: string; sessions: number; messages: number }>; + conversationFeedbacks: number; + resolvedCount: number; + resolutionRate: number; + averageRating: number | null; +} + // ─── MCP ─────────────────────────────────────────────────────────── export interface McpPrompt { diff --git a/typescript/src/version.ts b/typescript/src/version.ts index 0309754..aa2575b 100644 --- a/typescript/src/version.ts +++ b/typescript/src/version.ts @@ -1 +1 @@ -export const VERSION = "0.3.0-rc.3"; +export const VERSION = "1.0.0"; diff --git a/typescript/tests/agent-chat.test.ts b/typescript/tests/agent-chat.test.ts index 451ef61..d461352 100644 --- a/typescript/tests/agent-chat.test.ts +++ b/typescript/tests/agent-chat.test.ts @@ -171,3 +171,56 @@ describe("agentChat.stream", () => { expect(body.history.length).toBe(2); }); }); + +describe("managed agent chat contract", () => { + test("rejects undeclared provider fields before dispatch and uses durable admission", async () => { + const fetchMock = mock(() => Promise.resolve(new Response(JSON.stringify({ + executionId: "execution-id", request: { + requestId: "11111111-1111-4111-8111-111111111111", sessionId: "session-1", query: "Question", + history: [], maximumMilliCredits: "1000", model: "secret-model", + }, status: "pending", reconciliationRequired: false, output: null, + maximumMilliCredits: "1000", chargedMilliCredits: null, provider: "secret-provider", + }), { status: 202, headers: { "Content-Type": "application/json" } }))) as unknown as typeof fetch; + const client = createClient(fetchMock); + const valid = { + requestId: "11111111-1111-4111-8111-111111111111", sessionId: "session-1", query: "Question", maximumMilliCredits: "1000", + }; + + await expect(client.agentChat.managed.start("agent_1", { ...valid, model: "private-model" } as never)) + .rejects.toThrow("Managed agent chat does not accept model"); + expect(fetchMock).not.toHaveBeenCalled(); + + const result = await client.agentChat.managed.start("agent_1", valid); + expect(result.status).toBe("pending"); + expect(result.request.query).toBe("Question"); + expect(result.request).not.toHaveProperty("model"); + expect(result).not.toHaveProperty("provider"); + const call = (fetchMock as any).mock.calls[0]; + expect(call[0]).toContain("/api/agents/agent_1/chat/executions"); + expect(JSON.parse(call[1].body)).toEqual({ ...valid, history: [] }); + }); + + test("projects durable results and history without internal metadata", async () => { + const response = { + executionId: "execution-id", request: { + requestId: "11111111-1111-4111-8111-111111111111", sessionId: "session-1", query: "Question", + history: [], maximumMilliCredits: "1000", providerConfig: { key: "secret" }, + }, status: "completed", reconciliationRequired: false, + output: { response: "Answer", sources: [{ content: "source", score: 0.9, providerConfig: "secret" }], history: [], trace: { token: "secret" } }, + maximumMilliCredits: "1000", chargedMilliCredits: "250", model: "secret-model", + }; + const fetchMock = mock(() => Promise.resolve(new Response(JSON.stringify(response), { status: 200, headers: { "Content-Type": "application/json" } }))) as unknown as typeof fetch; + const client = createClient(fetchMock); + const result = await client.agentChat.managed.get("agent_1", "execution-id"); + expect(result.output?.response).toBe("Answer"); + expect(result.output?.sources[0]).not.toHaveProperty("providerConfig"); + expect(result.request).not.toHaveProperty("providerConfig"); + expect(result).not.toHaveProperty("model"); + + const historyFetch = mock(() => Promise.resolve(new Response(JSON.stringify({ items: [{ executionId: "e1", createdAt: "now", question: "Q", model: "secret" }], nextCursor: null, trace: "secret" }), { status: 200 }))) as unknown as typeof fetch; + const historyClient = createClient(historyFetch); + const history = await historyClient.agentChat.managed.list("agent_1"); + expect(history.items).toEqual([{ executionId: "e1", createdAt: "now", question: "Q" }]); + expect(history).not.toHaveProperty("trace"); + }); +}); diff --git a/typescript/tests/agents.test.ts b/typescript/tests/agents.test.ts index c338fd3..5a04611 100644 --- a/typescript/tests/agents.test.ts +++ b/typescript/tests/agents.test.ts @@ -55,6 +55,20 @@ describe("agents.get", () => { }); describe("agents.create", () => { + test("preserves explicit licensed provider selection and nullable update fields", async () => { + const bodies: unknown[] = []; + const client = createClient(async (_url, init) => { + bodies.push(JSON.parse(String(init?.body))); + return Response.json({ id: "agent-fixture", name: "Licensed" }); + }); + await client.agents.create({ name: "Licensed", llmConfigId: "primary-config", fallbackLlmConfigId: null, runtimeKind: "byok_api" }); + await client.agents.update("agent-fixture", { llmConfigId: null, fallbackLlmConfigId: "fallback-config", runtimeKind: "byok_api" }); + expect(bodies).toEqual([ + { name: "Licensed", llmConfigId: "primary-config", fallbackLlmConfigId: null, runtimeKind: "byok_api" }, + { llmConfigId: null, fallbackLlmConfigId: "fallback-config", runtimeKind: "byok_api" }, + ]); + }); + test("POST /agents with params", async () => { const created = { id: "agent_new", @@ -185,3 +199,70 @@ describe("agents.generate", () => { expect(body.language).toBe("fr"); }); }); + +describe("managed agent contract", () => { + test("rejects provider/runtime overrides before dispatch and strips private response fields", async () => { + const fetchMock = jsonFetch({ agents: [{ + id: "agent_1", name: "Support", description: null, collectionId: "collection_1", + systemPrompt: "Help customers", instructions: null, enabledBuiltinTools: ["web_search"], + skillIds: [], workflowToolIds: [], isActive: true, createdAt: "now", updatedAt: "now", + model: "secret-model", llmConfigId: "secret-config", mcpServers: [{ token: "secret-token" }], + runtimePreferences: { model: "also-secret" }, + }] }); + const client = createClient(fetchMock); + + await expect(client.agents.managed.create({ name: "Nope", model: "private-model" } as never)) + .rejects.toThrow("Managed agents cannot override provider or runtime configuration"); + await expect(client.agents.managed.create({ name: "Nope", mcpServers: [{ token: "private-token" }] } as never)) + .rejects.toThrow("Managed agents cannot override provider or runtime configuration"); + expect(fetchMock).not.toHaveBeenCalled(); + + const agents = await client.agents.managed.list(); + expect(agents).toHaveLength(1); + expect(agents[0].name).toBe("Support"); + expect(agents[0]).not.toHaveProperty("model"); + expect(agents[0]).not.toHaveProperty("llmConfigId"); + expect(agents[0]).not.toHaveProperty("mcpServers"); + expect(agents[0]).not.toHaveProperty("runtimePreferences"); + }); + + test("sends only managed business fields and preserves licensed resource methods", async () => { + const fetchMock = jsonFetch({ + id: "agent_1", name: "Support", description: null, collectionId: null, + systemPrompt: "Help", instructions: null, enabledBuiltinTools: ["web_search"], + skillIds: [], workflowToolIds: [], isActive: true, createdAt: "now", updatedAt: "now", + model: "private-model", llmConfigId: "private-config", + }); + const client = createClient(fetchMock); + const agent = await client.agents.managed.create({ name: "Support", systemPrompt: "Help" }); + expect(agent.name).toBe("Support"); + expect(agent).not.toHaveProperty("model"); + const body = JSON.parse((fetchMock as any).mock.calls[0][1].body); + expect(body).toEqual({ name: "Support", systemPrompt: "Help" }); + + await client.agents.create({ name: "Licensed", model: "local-model" }); + const legacyBody = JSON.parse((fetchMock as any).mock.calls[1][1].body); + expect(legacyBody.model).toBe("local-model"); + }); + + test("updates managed agent activation with a boolean and rejects invalid or provider fields before dispatch", async () => { + const fetchMock = jsonFetch({ + id: "agent_1", name: "Support", description: null, collectionId: null, + systemPrompt: "Help", instructions: null, enabledBuiltinTools: [], + skillIds: [], workflowToolIds: [], isActive: false, createdAt: "now", updatedAt: "now", + }); + const client = createClient(fetchMock); + + await expect(client.agents.managed.update("agent_1", { isActive: "false" as never })) + .rejects.toThrow("isActive must be a boolean"); + await expect(client.agents.managed.update("agent_1", { isActive: false, model: "private-model" } as never)) + .rejects.toThrow("Managed agents cannot override provider or runtime configuration"); + await expect(client.agents.managed.create({ name: "Support", isActive: false } as never)) + .rejects.toThrow("Managed contract does not accept isActive"); + expect(fetchMock).not.toHaveBeenCalled(); + + const updated = await client.agents.managed.update("agent_1", { isActive: false }); + expect(updated.isActive).toBe(false); + expect(JSON.parse((fetchMock as any).mock.calls[0][1].body)).toEqual({ isActive: false }); + }); +}); diff --git a/typescript/tests/chat.test.ts b/typescript/tests/chat.test.ts index b765001..48e993a 100644 --- a/typescript/tests/chat.test.ts +++ b/typescript/tests/chat.test.ts @@ -146,3 +146,97 @@ describe("chat.streamProgressive", () => { expect(call[0]).toContain("/api/chat/stream/progressive"); }); }); + +describe("managed chat budgets", () => { + for (const method of ["send", "stream", "streamProgressive"] as const) { + test(`${method} sends an exact budget without model configuration`, async () => { + const request = mock(() => Promise.resolve(new Response(JSON.stringify({ answer: "ok", sources: [] }), { status: 200 }))); + const client = createClient(request as unknown as typeof fetch); + await client.chat[method]({ collectionId: "collection", query: "Question", maximumMilliCredits: "9999999999999999" }); + const body = JSON.parse((request.mock.calls[0] as unknown as [string, RequestInit])[1].body as string); + expect(body.maximumMilliCredits).toBe("9999999999999999"); + expect(body).not.toHaveProperty("llmConfigId"); + }); + test(`${method} rejects invalid budgets and model overrides before dispatch`, async () => { + const request = mock(() => Promise.reject(new Error("must not dispatch"))); + const client = createClient(request as unknown as typeof fetch); + for (const maximumMilliCredits of ["0", "-1", "1.5", "1e6", "10000000000000000"]) { + await expect(Promise.resolve().then(() => client.chat[method]({ collectionId: "collection", query: "Question", maximumMilliCredits }))).rejects.toBeInstanceOf(TypeError); + } + await expect(Promise.resolve().then(() => client.chat[method]({ collectionId: "collection", query: "Question", maximumMilliCredits: "1000", llmConfigId: "private-model" }))).rejects.toBeInstanceOf(TypeError); + expect(request).not.toHaveBeenCalled(); + }); + } +}); + +describe("explicit managed chat contract", () => { + test("rejects model and LLM configuration overrides before dispatch with or without a budget", async () => { + const request = mock(() => Promise.reject(new Error("must not dispatch"))); + const client = createClient(request as unknown as typeof fetch); + const methods = ["send", "stream", "streamProgressive"] as const; + const overrides = [ + { llmConfigId: "private-llm-config" }, + { model: "private-model" }, + ]; + + for (const method of methods) { + for (const maximumMilliCredits of [undefined, "1000"]) { + for (const override of overrides) { + const params = { + collectionId: "collection", + query: "Question", + ...(maximumMilliCredits === undefined ? {} : { maximumMilliCredits }), + ...override, + }; + await expect( + Promise.resolve().then(() => client.chat.managed[method](params as never)), + ).rejects.toThrow("Managed chat cannot override model or LLM configuration"); + } + } + } + expect(request).not.toHaveBeenCalled(); + }); + + test("whitelists nested request and response fields and strips progressive diagnostics", async () => { + const responseBody = JSON.stringify({ + answer: "Safe answer", model: "private-model", usage: { promptTokens: 99 }, providerConfig: { key: "secret" }, + sources: [{ type: "text", content: "Excerpt", score: 0.9, source: "doc.pdf", sourceType: "document", providerConfig: "secret" }], + }); + const fetchMock = mock(() => Promise.resolve(new Response(responseBody, { status: 200, headers: { "Content-Type": "application/json" } }))) as unknown as typeof fetch; + const client = createClient(fetchMock); + const result = await client.chat.managed.send({ collectionId: "collection", query: "Question" }); + expect(result.answer).toBe("Safe answer"); + expect(result).not.toHaveProperty("model"); + expect(result).not.toHaveProperty("usage"); + expect(result.sources[0]).not.toHaveProperty("providerConfig"); + + const streamSse = `event: sources\ndata: ${JSON.stringify([{ type: "text", content: "Excerpt", score: 1, source: "doc", sourceType: "document", model: "secret" }])}\n\nevent: done\ndata: \n\n`; + const streamFetch = mock(() => Promise.resolve(new Response(sseBody(streamSse), { status: 200, headers: { "Content-Type": "text/event-stream" } }))) as unknown as typeof fetch; + const streamClient = createClient(streamFetch); + const events = []; + for await (const event of streamClient.chat.managed.stream({ collectionId: "collection", query: "Question" })) events.push(event); + expect(events[0].type).toBe("sources"); + if (events[0].type === "sources") expect(events[0].sources[0]).not.toHaveProperty("model"); + + const progressiveSse = [ + `event: stage\ndata: ${JSON.stringify({ stage: "searching", elapsed: 4, details: { config: "secret" } })}`, + `event: metrics\ndata: ${JSON.stringify({ pipelineMetrics: { totalTimeMs: 4, queryEnhancementMs: 0, searchMs: 4, rerankMs: 0, resultsCount: 1 }, featuresUsed: [], config: { apiKey: "secret" } })}`, + "event: done\ndata: ", + ].join("\n\n") + "\n\n"; + const progressiveFetch = mock(() => Promise.resolve(new Response(sseBody(progressiveSse), { status: 200, headers: { "Content-Type": "text/event-stream" } }))) as unknown as typeof fetch; + const progressiveClient = createClient(progressiveFetch); + const progressiveEvents = []; + for await (const event of progressiveClient.chat.managed.streamProgressive({ collectionId: "collection", query: "Question" })) progressiveEvents.push(event); + expect(progressiveEvents[0]).toEqual({ type: "stage", stage: "searching", elapsed: 4 }); + expect(progressiveEvents[1].type).toBe("metrics"); + if (progressiveEvents[1].type === "metrics") expect(progressiveEvents[1]).not.toHaveProperty("config"); + + const invalidNestedFetch = mock(() => Promise.reject(new Error("must not dispatch"))) as unknown as typeof fetch; + const invalidNestedClient = createClient(invalidNestedFetch); + await expect(invalidNestedClient.chat.managed.send({ + collectionId: "collection", query: "Question", + history: [{ role: "user", content: "Q", model: "private-model" } as never], + })).rejects.toThrow("Managed chat cannot override model or LLM configuration"); + expect(invalidNestedFetch).not.toHaveBeenCalled(); + }); +}); diff --git a/typescript/tests/collections.test.ts b/typescript/tests/collections.test.ts index d6fe0ad..49ae833 100644 --- a/typescript/tests/collections.test.ts +++ b/typescript/tests/collections.test.ts @@ -22,6 +22,16 @@ function createClient(fetchMock: typeof fetch): IgnitionAI { } describe("collections.list", () => { + test("creation serializes an explicit embedding selection without a default mutation", async () => { + const requests: { method: string | undefined; body: unknown }[] = []; + const client = createClient(async (_url, init) => { + requests.push({ method: init?.method, body: JSON.parse(String(init?.body)) }); + return Response.json({ id: "collection-fixture", name: "Private documents" }); + }); + await client.collections.create({ name: "Private documents", embeddingConfigId: "owned-embedding-config" }); + expect(requests).toEqual([{ method: "POST", body: { name: "Private documents", embeddingConfigId: "owned-embedding-config" } }]); + }); + test("GET /collections", async () => { const collections = [ { id: "coll_1", name: "Docs", documentCount: 10 }, @@ -87,6 +97,27 @@ describe("collections.list", () => { }); }); +describe("collections public catalog", () => { + test("lists and resolves public collections", async () => { + const fetchMock = jsonFetch({ items: [{ id: "public_1", slug: "labor-code" }] }); + const client = createClient(fetchMock); + + const items = await client.collections.listPublic({ + minTier: "pro", + query: "labor", + }); + await client.collections.getPublic("labor/code"); + + expect(items[0]?.slug).toBe("labor-code"); + expect((fetchMock as any).mock.calls[0][0]).toBe( + "http://localhost/api/public-collections?minTier=pro&q=labor", + ); + expect((fetchMock as any).mock.calls[1][0]).toBe( + "http://localhost/api/public-collections/labor%2Fcode", + ); + }); +}); + describe("collections.create", () => { test("POST /collections", async () => { const created = { id: "coll_new", name: "New", visibility: "private" }; @@ -144,6 +175,26 @@ describe("collections.update", () => { }); }); +describe("collections.updateVisibility", () => { + test("PATCH /collections/:id/visibility", async () => { + const fetchMock = jsonFetch({ id: "coll_1", visibility: "public" }); + const client = createClient(fetchMock); + + await client.collections.updateVisibility("coll_1", { + visibility: "public", + requiredPlanId: "pro", + }); + + const call = (fetchMock as any).mock.calls[0]; + expect(call[0]).toContain("/api/collections/coll_1/visibility"); + expect(call[1].method).toBe("PATCH"); + expect(JSON.parse(call[1].body)).toEqual({ + visibility: "public", + requiredPlanId: "pro", + }); + }); +}); + describe("collections.delete", () => { test("DELETE with force flag", async () => { const fetchMock = jsonFetch({ success: true, permanent: true }); @@ -264,7 +315,7 @@ describe("collections.qualityReport", () => { const report = { totalDocuments: 5, documentsWithReport: 5, - extractionMethods: { "pdf-mupdf": 3, "docx-mammoth": 2 }, + extractionMethods: { "pdf-unpdf": 3, "docx-mammoth": 2 }, ocr: { docsWithOcr: 1, totalPagesOcrd: 4, totalPagesRejected: 0, docsWithOcrRejections: 0, totalCharsExtracted: 2200 }, images: { totalExtracted: 8, totalIndexed: 8, totalSkipped: 0, docsWithImages: 2 }, tables: { docsWithTables: 0, totalTables: 0, totalRows: 0 }, @@ -345,3 +396,17 @@ describe("collections.applyRagPreset", () => { expect(body.features.dynamicFeatureSelection).toBe(false); }); }); + + +test("collection and public catalogue clients preserve receipt evidence without inventing corpus qualification", async () => { + for (const status of ["verified_receipt", "unknown"] as const) { + const servedSource = { status, officialCorpusQualified: false as const, sourceRevision: status === "verified_receipt" ? "source-r1" : null, sourceTimestamp: null, activatedAt: null }; + const item = { id: "collection-receipt", name: "Fixture", sourceDataset: "legifrance", lastSyncedAt: null, servedSource }; + const collection = await createClient(jsonFetch(item)).collections.get(item.id); + const catalogue = await createClient(jsonFetch({ items: [item] })).collections.listPublic(); + expect(collection.servedSource).toEqual(servedSource); + expect(catalogue[0]?.servedSource).toEqual(servedSource); + expect(catalogue[0]?.sourceDataset).toBe("legifrance"); + expect(catalogue[0]?.lastSyncedAt).toBeNull(); + } +}); diff --git a/typescript/tests/compatibility.test.ts b/typescript/tests/compatibility.test.ts index 4f259dd..6919467 100644 --- a/typescript/tests/compatibility.test.ts +++ b/typescript/tests/compatibility.test.ts @@ -21,13 +21,13 @@ function clientFor(metadata: Record) { describe("deployment compatibility", () => { test("accepts and caches the matching public contract", async () => { const { client, fetchMock } = clientFor({ - contractVersion: "2026.07", + contractVersion: "2026.11", contractDigest: PUBLIC_CONTRACT_DIGEST, capabilities: ["rag_chat", "collections"], }); await expect(client.compatibility.assertCompatible()).resolves.toMatchObject({ - contractVersion: "2026.07", + contractVersion: "2026.11", }); await client.compatibility.assertCompatible(); expect(fetchMock).toHaveBeenCalledTimes(1); @@ -46,7 +46,7 @@ describe("deployment compatibility", () => { test("rejects a changed contract under the current version", async () => { const { client } = clientFor({ - contractVersion: "2026.07", + contractVersion: "2026.11", contractDigest: `sha256:${"0".repeat(64)}`, capabilities: [], }); @@ -54,4 +54,13 @@ describe("deployment compatibility", () => { "digest does not match", ); }); + + test.each(["2026.10", "2026.09"])("retains older deployment %s without claiming retired capabilities", async (contractVersion) => { + const { client } = clientFor({ + contractVersion, + contractDigest: "sha256:a4bf84ca528369216fafe1613fc97304f1c7b0219b85032388b5003f7b2f0d98", + capabilities: ["collections"], + }); + await expect(client.compatibility.assertCompatible()).resolves.toMatchObject({ contractVersion, capabilities: ["collections"] }); + }); }); diff --git a/typescript/tests/contracts.types.ts b/typescript/tests/contracts.types.ts new file mode 100644 index 0000000..7fc0295 --- /dev/null +++ b/typescript/tests/contracts.types.ts @@ -0,0 +1,84 @@ +import type { + AgentCreateParams, + CollectionCreateParams, + CollectionServedSource, + ManagedAgentCreateParams, + ManagedAgentUpdateParams, + ManagedChatParams, + ManagedWidgetCreateParams, + WidgetCreateParams, +} from "../src/index.js"; +import { IgnitionAI } from "../src/index.js"; + +declare const client: IgnitionAI; + +const managedChat: ManagedChatParams = { + collectionId: "collection-id", + query: "Question", + maximumMilliCredits: "1000", +}; +void client.chat.managed.send(managedChat); +void client.chat.managed.stream(managedChat); +void client.chat.managed.streamProgressive(managedChat); + +// @ts-expect-error Managed SaaS chat cannot select a model. +const managedChatWithModel: ManagedChatParams = { collectionId: "collection-id", query: "Question", model: "private" }; +// @ts-expect-error Managed SaaS chat cannot select an LLM configuration. +const managedChatWithConfig: ManagedChatParams = { collectionId: "collection-id", query: "Question", llmConfigId: "private" }; +void managedChatWithModel; +void managedChatWithConfig; + +const managedAgent: ManagedAgentCreateParams = { name: "Support", systemPrompt: "Help" }; +void client.agents.managed.create(managedAgent); +const managedAgentUpdate: ManagedAgentUpdateParams = { isActive: false }; +void client.agents.managed.update("agent-id", managedAgentUpdate); +// @ts-expect-error Managed agent activation state must be boolean. +const managedAgentUpdateWithInvalidState: ManagedAgentUpdateParams = { isActive: "false" }; +void managedAgentUpdateWithInvalidState; +// @ts-expect-error Managed agent activation can only change through update. +const managedAgentCreateWithState: ManagedAgentCreateParams = { name: "Support", isActive: false }; +void managedAgentCreateWithState; +// @ts-expect-error Managed agent config has no provider/model fields. +const managedAgentWithModel: ManagedAgentCreateParams = { name: "Support", model: "private" }; +// @ts-expect-error Managed agent config has no MCP credentials. +const managedAgentWithMcp: ManagedAgentCreateParams = { name: "Support", mcpServers: [{ name: "mcp", url: "https://example.test", token: "private" }] }; +void managedAgentWithModel; +void managedAgentWithMcp; + +const managedWidget: ManagedWidgetCreateParams = { name: "Support", type: "agent", agentId: "agent-id" }; +void client.widgets.managed.create(managedWidget); +// @ts-expect-error Managed widget config has no LLM settings. +const managedWidgetWithModel: ManagedWidgetCreateParams = { name: "Support", type: "agent", llmModel: "private" }; +// @ts-expect-error Managed widget config has no secret escalation target. +const managedWidgetWithEscalation: ManagedWidgetCreateParams = { name: "Support", type: "agent", humanEscalation: { type: "webhook", target: "https://example.test/?token=private" } }; +void managedWidgetWithModel; +void managedWidgetWithEscalation; + +// Existing licensed/self-hosted contracts remain source-compatible. +const licensedAgent = { name: "Licensed", model: "local-model", llmConfigId: "local-config" }; +const explicitLicensedAgent: AgentCreateParams = { name: "Licensed", llmConfigId: "local-config", fallbackLlmConfigId: null, runtimeKind: "byok_api" }; +const explicitCollection: CollectionCreateParams = { name: "Private documents", embeddingConfigId: "owned-embedding-config" }; +void client.collections.create(explicitCollection); +void client.ingest.file({ collectionId: "collection-id", file: new Blob(), ocrMode: "disabled" }); +void client.ingest.url({ collectionId: "collection-id", url: "https://example.com/guide" }); +void client.ingest.document({ collectionId: "collection-id", content: "note", filename: "note.txt" }); +void client.workflows.create({ name: "Inert fixture", isActive: false }); +// @ts-expect-error OCR modes follow the canonical enum. +void client.ingest.file({ collectionId: "collection-id", file: new Blob(), ocrMode: "never" }); +// @ts-expect-error Collection creation accepts a string identifier, not null. +void client.collections.create({ name: "Invalid selection", embeddingConfigId: null }); +void client.agents.create(explicitLicensedAgent); +void client.agents.update("agent-id", { llmConfigId: null, fallbackLlmConfigId: "fallback-config", runtimeKind: "byok_api" }); +// @ts-expect-error The public create contract permits only the BYOK runtime. +void client.agents.create({ name: "Forbidden runtime", runtimeKind: "cli_runtime" }); +// @ts-expect-error Managed SaaS agents cannot select a private provider config. +void client.agents.managed.create({ name: "Managed", llmConfigId: "private-config" }); +const licensedWidget: WidgetCreateParams = { name: "Licensed", type: "agent", llmModel: "local-model" }; +void client.agents.create(licensedAgent); +void client.widgets.create(licensedWidget); + +const servedSource: CollectionServedSource = { status: "verified_receipt", officialCorpusQualified: false, sourceRevision: "receipt-r1", sourceTimestamp: null, activatedAt: null }; +// @ts-expect-error A verified receipt is not a qualification of the official corpus. +const inventedQualification: CollectionServedSource = { ...servedSource, officialCorpusQualified: true }; +void servedSource; +void inventedQualification; diff --git a/typescript/tests/data-chat.test.ts b/typescript/tests/data-chat.test.ts index 030b85d..dfc6e19 100644 --- a/typescript/tests/data-chat.test.ts +++ b/typescript/tests/data-chat.test.ts @@ -1,8 +1,12 @@ import { describe, expect, mock, test } from "bun:test"; import { IgnitionAI } from "../src/index"; -function clientWith(response: unknown) { - const fetchMock = mock(() => Promise.resolve(new Response(JSON.stringify(response), { +function clientWith(response: unknown, capabilities = ["data_connectors"]) { + const fetchMock = mock((url: string) => Promise.resolve(new Response(JSON.stringify(url.endsWith("/meta") ? { + contractVersion: capabilities.length ? "2026.08" : "2026.09", + contractDigest: "sha256:legacy-deployment", + capabilities, + } : response), { status: 200, headers: { "Content-Type": "application/json" }, }))) as unknown as typeof fetch; @@ -24,7 +28,7 @@ describe("dataChat", () => { llmConfigId: "llm_1", resources: [{ type: "data_connector", id: "connector_1" }], }); - const [url, init] = (fetchMock as any).mock.calls[0]; + const [url, init] = (fetchMock as any).mock.calls.find(([url]: [string]) => url.endsWith("/data-chat/precheck")); expect(url).toContain("/api/data-chat/precheck"); expect(init.method).toBe("POST"); expect(JSON.parse(init.body)).toEqual({ @@ -44,7 +48,21 @@ describe("dataChat", () => { ], }); expect(result.answer).toBe("ok"); - const [, init] = (fetchMock as any).mock.calls[0]; + const [, init] = (fetchMock as any).mock.calls.find(([url]: [string]) => url.endsWith("/data-chat")); expect(JSON.parse(init.body).resources).toHaveLength(2); }); + + test.each(["precheck", "send"] as const)("%s fails clearly when the deployment retired Data Chat", async (method) => { + const { client, fetchMock } = clientWith({ answer: "must not be requested" }, []); + await expect(client.dataChat[method]({ + query: "Revenue by region", + llmConfigId: "llm_1", + resources: [{ type: "data_connector", id: "connector_1" }], + })).rejects.toMatchObject({ + name: "UnsupportedCapabilityError", + capability: "data_connectors", + contractVersion: "2026.09", + }); + expect((fetchMock as any).mock.calls.map(([url]: [string]) => new URL(url).pathname)).toEqual(["/api/meta"]); + }); }); diff --git a/typescript/tests/errors.test.ts b/typescript/tests/errors.test.ts index e4824a9..5eb2ac4 100644 --- a/typescript/tests/errors.test.ts +++ b/typescript/tests/errors.test.ts @@ -14,6 +14,7 @@ import { CapabilityDisabledError, CapabilityNotLicensedError, ForbiddenIdentityError, + OfferingUnavailableError, } from "../src/errors"; const headers = { "x-request-id": "req_123" }; @@ -150,6 +151,17 @@ describe("castError", () => { expect(err).toBeInstanceOf(InternalServerError); }); + test("treats checkout conflict as a client APIError and provider unavailability as InternalServerError", () => { + const conflict = castError(409, { code: "CHECKOUT_REQUEST_CONFLICT" }, headers); + expect(conflict).toBeInstanceOf(APIError); + expect(conflict).not.toBeInstanceOf(InternalServerError); + expect(conflict.status).toBe(409); + const unavailable = castError(503, { code: "PAYMENT_PROVIDER_UNAVAILABLE" }, headers); + expect(unavailable).toBeInstanceOf(InternalServerError); + expect(unavailable.status).toBe(503); + expect(unavailable).not.toBeInstanceOf(OfferingUnavailableError); + }); + test("maps unknown status to generic APIError", () => { const err = castError(418, { error: "I'm a teapot" }, headers); expect(err).toBeInstanceOf(APIError); diff --git a/typescript/tests/generate-wire-types.test.ts b/typescript/tests/generate-wire-types.test.ts new file mode 100644 index 0000000..cf9cb28 --- /dev/null +++ b/typescript/tests/generate-wire-types.test.ts @@ -0,0 +1,39 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const directories: string[] = []; +afterEach(async () => { await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))); }); + +async function generate(previous: string[]) { + const directory = await mkdtemp(join(tmpdir(), "sdk-generations-")); + directories.push(directory); + const contract = join(directory, "candidate.json"); + await writeFile(contract, JSON.stringify({ payload: { + schemaVersion: 1, contractVersion: "2026.11", manifest: {}, protocols: {}, + openapi: { openapi: "3.1.0", info: { title: "Synthetic public contract", version: "2026.11" }, paths: {} }, + } })); + const identity = join(directory, "contract.ts"); + const python = join(directory, "contract.py"); + const proc = Bun.spawn([process.execPath, join(import.meta.dir, "../scripts/generate-wire-types.ts"), + "--contract", contract, "--output", join(directory, "wire.ts"), "--identity-output", identity, + "--python-identity-output", python, ...previous.flatMap((version) => ["--previous-contract", version]), + ], { stdout: "pipe", stderr: "pipe" }); + const [exit, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text(), new Response(proc.stdout).text()]); + return { exit, stderr, identity, python }; +} + +test("retains multiple previous revisions without replacing the current identity", async () => { + const result = await generate(["2026.10", "2026.09", "2026.10"]); + expect(result.exit).toBe(0); + expect(await readFile(result.identity, "utf8")).toContain('["2026.11","2026.10","2026.09"]'); + expect(await readFile(result.python, "utf8")).toContain('("2026.11", "2026.10", "2026.09")'); +}); + +test.each(["2026.13", "2026.12", "2026.11", "--output"])("rejects invalid or newer previous revision %s before writing identities", async (version) => { + const result = await generate([version]); + expect(result.exit).not.toBe(0); + expect(result.stderr).toContain("--previous-contract"); + expect(await Bun.file(result.identity).exists()).toBe(false); +}); diff --git a/typescript/tests/generated-contract.test.ts b/typescript/tests/generated-contract.test.ts index b837492..163ffaa 100644 --- a/typescript/tests/generated-contract.test.ts +++ b/typescript/tests/generated-contract.test.ts @@ -13,8 +13,15 @@ describe("generated public wire contract", () => { test("contains only the public operation surface", () => { expect(generated).toContain('"/api/chat"'); expect(generated).toContain('"/api/workflows/:id/execute"'); + expect(generated).toContain('"/api/ingest/jobs/{jobId}"'); + expect(generated).toContain('"/api/traces/{id}"'); + expect(generated).toContain('"/api/feedback"'); + expect(generated).toContain('"/api/collections/:collectionId/rag-config/test"'); + expect(generated).toContain("readonly servedSource?:"); + expect(generated).toContain("readonly officialCorpusQualified: false;"); expect(generated).not.toContain("/api/admin"); expect(generated).not.toContain("/api/internal/mcp"); + expect(generated).not.toContain("/api/data-chat"); }); test("is not re-exported from the ergonomic package root", () => { @@ -22,7 +29,7 @@ describe("generated public wire contract", () => { }); test("binds the SDK to the generated aggregate contract digest", () => { - expect(identity).toContain("sha256:a83d9ad89dc77c3d2ab0daae07596aabe161cfe1c4e28ba4afbc500a04ed1fb5"); - expect(identity).toContain('["2026.07", "2026.06"]'); + expect(identity).toContain("sha256:37839de6724326e9d7ad949a08f95dcc2d960580d9fc2c8bad0933ce8b4ef78d"); + expect(identity).toContain('["2026.11","2026.10","2026.09"]'); }); }); diff --git a/typescript/tests/ingest.test.ts b/typescript/tests/ingest.test.ts new file mode 100644 index 0000000..e25e326 --- /dev/null +++ b/typescript/tests/ingest.test.ts @@ -0,0 +1,197 @@ +import { describe, expect, mock, test } from "bun:test"; +import { IgnitionAI, InternalServerError, OfferingUnavailableError } from "../src/index"; + +function createClient() { + const fetchMock = mock(() => Promise.resolve(new Response(JSON.stringify({ + success: true, + jobId: "job_1", + message: "started", + pages: [], + totalFound: 0, + duration: 4, + }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }))) as unknown as typeof fetch; + return { + client: new IgnitionAI({ + apiKey: "ign_test", + baseURL: "http://localhost", + fetch: fetchMock, + maxRetries: 0, + }), + fetchMock, + }; +} + +describe("async ingestion", () => { + test("covers contract async and discovery endpoints", async () => { + const { client, fetchMock } = createClient(); + const file = new Blob(["hello"], { type: "text/plain" }); + + await client.ingest.fileAsync({ + collectionId: "coll_1", + file, + enableMultimodal: true, + }); + await client.ingest.crawlAsync({ collectionId: "coll_1", url: "https://example.com" }); + await client.ingest.datasetAsync({ collectionId: "coll_1", datasetId: "acme/docs" }); + await client.ingest.discover({ url: "https://example.com", maxPages: 25 }); + await client.ingest.crawlSelectedAsync({ + collectionId: "coll_1", + urls: ["https://example.com/a"], + }); + + expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([ + "http://localhost/api/ingest/file/async", + "http://localhost/api/ingest/crawl/async", + "http://localhost/api/ingest/dataset/async", + "http://localhost/api/ingest/discover", + "http://localhost/api/ingest/crawl-selected/async", + ]); + const form = fetchMock.mock.calls[0]?.[1]?.body as FormData; + expect(form.get("collectionId")).toBe("coll_1"); + expect(form.get("enableMultimodal")).toBe("true"); + expect(form.has("ocrMode")).toBe(false); + }); + + test("file() uses durable async ingestion", async () => { + const { client, fetchMock } = createClient(); + await client.ingest.file({ + collectionId: "coll_1", + file: new Blob(["a,b"], { type: "text/csv" }), + enableMultimodal: false, + mode: "tabular", + ocrMode: "disabled", + }); + + expect(fetchMock.mock.calls[0]?.[0]).toBe("http://localhost/api/ingest/file/async"); + const form = fetchMock.mock.calls[0]?.[1]?.body as FormData; + expect(form.get("mode")).toBe("tabular"); + expect(form.get("ocrMode")).toBe("disabled"); + expect(form.get("enableMultimodal")).toBe("false"); + }); + + test("url() queues durable async URL ingestion for SaaS members", async () => { + const { client, fetchMock } = createClient(); + const started = await client.ingest.url({ + collectionId: "coll_1", + url: "https://example.com/guide", + enableMultimodal: true, + }); + + expect(started.jobId).toBe("job_1"); + expect(fetchMock.mock.calls[0]?.[0]).toBe("http://localhost/api/ingest/url/async"); + expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({ + collectionId: "coll_1", + url: "https://example.com/guide", + enableMultimodal: true, + maxPages: 1, + }); + }); + + test("document() uploads raw text through durable file ingestion", async () => { + const { client, fetchMock } = createClient(); + await client.ingest.document({ + collectionId: "coll_1", + content: "hello from sdk", + filename: "note.txt", + }); + + expect(fetchMock.mock.calls[0]?.[0]).toBe("http://localhost/api/ingest/file/async"); + const form = fetchMock.mock.calls[0]?.[1]?.body as FormData; + expect(form.get("collectionId")).toBe("coll_1"); + const file = form.get("file") as File; + expect(file).toBeInstanceOf(Blob); + expect(file.name).toBe("note.txt"); + expect(await file.text()).toBe("hello from sdk"); + }); + + test("closed SaaS ingest methods raise OfferingUnavailableError instead of a 503 outage", async () => { + const fetchMock = mock(() => Promise.resolve(new Response(JSON.stringify({ + error: "AI_TEMPORARILY_UNAVAILABLE", + message: "This operation is temporarily unavailable.", + }), { + status: 503, + headers: { "Content-Type": "application/json" }, + }))) as unknown as typeof fetch; + const client = new IgnitionAI({ + apiKey: "ign_test", + baseURL: "http://localhost", + fetch: fetchMock, + maxRetries: 2, + }); + + const closed = [ + () => client.ingest.crawl({ collectionId: "coll_1", url: "https://example.com" }), + () => client.ingest.dataset({ collectionId: "coll_1", datasetId: "acme/docs" }), + () => client.ingest.discover({ url: "https://example.com" }), + ]; + + for (const call of closed) { + try { + await call(); + throw new Error("expected OfferingUnavailableError"); + } catch (error) { + expect(error).toBeInstanceOf(OfferingUnavailableError); + expect(error).not.toBeInstanceOf(InternalServerError); + expect((error as OfferingUnavailableError).code).toBe("OFFERING_UNAVAILABLE"); + expect((error as OfferingUnavailableError).message).toContain("not available on this offering"); + } + } + + expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([ + "http://localhost/api/ingest/crawl", + "http://localhost/api/ingest/dataset", + "http://localhost/api/ingest/discover", + ]); + }); + + test("tracks, lists, streams and cancels durable jobs", async () => { + const job = { + id: "job/1", + collectionId: "coll_1", + source: "crawl", + status: "completed", + progress: { current: 1, total: 1, step: "indexing" }, + metrics: {}, + startedAt: "2026-08-19T00:00:00.000Z", + }; + const fetchMock = mock((input: RequestInfo | URL) => { + const url = String(input); + if (url.endsWith("/stream")) { + return Promise.resolve(new Response( + `event: state\ndata: ${JSON.stringify(job)}\n\n`, + { headers: { "Content-Type": "text/event-stream" } }, + )); + } + if (url.includes("?collectionId=")) { + return Promise.resolve(Response.json({ success: true, jobs: [job] })); + } + if (url.endsWith("/cancel")) { + return Promise.resolve(Response.json({ success: true, message: "requested" })); + } + return Promise.resolve(Response.json({ success: true, job })); + }) as unknown as typeof fetch; + const client = new IgnitionAI({ + apiKey: "ign_test", + baseURL: "http://localhost", + fetch: fetchMock, + maxRetries: 0, + }); + + expect((await client.ingest.getJob("job/1")).job.id).toBe("job/1"); + expect((await client.ingest.listJobs("coll/1")).jobs).toHaveLength(1); + const events = []; + for await (const event of client.ingest.streamJob("job/1")) events.push(event); + expect(events).toEqual([{ type: "state", data: job }]); + expect((await client.ingest.cancelJob("job/1")).success).toBe(true); + + expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([ + "http://localhost/api/ingest/jobs/job%2F1", + "http://localhost/api/ingest/jobs?collectionId=coll%2F1", + "http://localhost/api/ingest/jobs/job%2F1/stream", + "http://localhost/api/ingest/jobs/job%2F1/cancel", + ]); + }); +}); diff --git a/typescript/tests/live-check.test.ts b/typescript/tests/live-check.test.ts new file mode 100644 index 0000000..99b8090 --- /dev/null +++ b/typescript/tests/live-check.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, test } from "bun:test"; +import { PUBLIC_CONTRACT_DIGEST, PUBLIC_CONTRACT_VERSION } from "../src/contract.js"; + +const fixtureKey = "ign_live_diagnostic_fixture"; +const privateId = "private-collection-fixture"; + +async function runDiagnostic(options: { + version?: string; collections?: unknown; deniedStatus?: number; insightsError?: string; +} = {}) { + const requests: Array<{ method: string; path: string; authenticated: boolean }> = []; + const server = Bun.serve({ + hostname: "127.0.0.1", port: 0, + fetch(request) { + const path = new URL(request.url).pathname; + requests.push({ method: request.method, path, + authenticated: request.headers.get("authorization") === `Bearer ${fixtureKey}` }); + if (path === "/api/meta") return Response.json({ + contractVersion: options.version ?? PUBLIC_CONTRACT_VERSION, + contractDigest: PUBLIC_CONTRACT_DIGEST, capabilities: [], + }); + if (path === "/api/collections") return Response.json(options.collections ?? + (options.insightsError ? [{ id: "collection-fixture" }] : [])); + if (path === "/api/collections/collection-fixture") return Response.json({ id: "collection-fixture", name: "Collection" }); + if (path.endsWith("/chunks")) return Response.json({ chunks: [], total: 0 }); + if (path.endsWith("/stats")) return Response.json({ totalChunks: 0, bySourceType: [], byType: [] }); + if (path.endsWith("/quality-report")) return Response.json({ totalDocuments: 0 }); + if (path.endsWith("/documents")) return Response.json({ documents: [] }); + if (path.endsWith("/evaluations")) return Response.json({ evaluations: [] }); + if (path.endsWith("/insights")) return Response.json({ error: options.insightsError }, { status: 404 }); + if (path === `/api/collections/${privateId}`) return Response.json( + { error: `Sensitive server message: ${fixtureKey}` }, { status: options.deniedStatus ?? 403 }); + if (path === "/api/workflows") return Response.json([{ id: "workflow-fixture" }]); + if (path === "/api/workflows/workflow-fixture") return Response.json({ + id: "workflow-fixture", name: "Private workflow name", graph: { nodes: [], edges: [] }, + }); + return Response.json([]); + }, + }); + try { + const child = Bun.spawn([process.execPath, "run", "scripts/check-live.ts"], { + cwd: `${import.meta.dir}/..`, + env: { ...process.env, IGNITION_BASE_URL: server.url.toString(), IGNITION_API_KEY: fixtureKey, + IGNITION_FORBIDDEN_COLLECTION_IDS: privateId }, + stdout: "pipe", stderr: "pipe", + }); + const [output, stderr, exitCode] = await Promise.all([ + new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited, + ]); + return { output, stderr, exitCode, requests }; + } finally { + await server.stop(true); + } +} + +describe("live diagnostic CLI", () => { + test("authenticates real GET requests, validates workflow graphs and reports missing coverage without leaking data", async () => { + const result = await runDiagnostic(); + expect(result.exitCode).toBe(0); + expect(result.requests.length).toBeGreaterThan(5); + expect(result.requests.every(request => request.method === "GET" && request.authenticated)).toBe(true); + expect(result.output).toContain('"name":"workflows[0].get","outcome":"PASS"'); + expect(result.output).toContain('"name":"scope.isolation[0]","outcome":"PASS"'); + expect(result.output).toContain('"outcome":"NOT PROVEN"'); + for (const sensitive of [fixtureKey, privateId, "Private workflow name", "Sensitive server message"]) { + expect(result.output + result.stderr).not.toContain(sensitive); + } + }); + + test.each([ + { version: "2099.01", expected: "UnsupportedContractVersionError" }, + { collections: { collections: [] }, expected: "ProtocolError" }, + { deniedStatus: 401, expected: '"name":"scope.isolation[0]","outcome":"FAIL"' }, + { deniedStatus: 200, expected: "Foreign private resource is readable" }, + ])("fails on incompatible deployments, invalid shapes or unsuccessful isolation ($expected)", async options => { + const result = await runDiagnostic(options); + expect(result.exitCode).toBe(1); + expect(result.output).toContain(options.expected); + expect(result.output).toContain('"name":"workflows[0].get","outcome":"PASS"'); + expect(result.output).not.toContain(fixtureKey); + }); + + test.each([ + { message: "Insights not yet generated", outcome: "NOT PROVEN", exitCode: 0 }, + { message: "Route not found", outcome: "FAIL", exitCode: 1 }, + ])("distinguishes unavailable insights from a missing route ($outcome)", async fixture => { + const result = await runDiagnostic({ insightsError: fixture.message }); + expect(result.exitCode).toBe(fixture.exitCode); + expect(result.output).toContain(`"name":"collections[0].insights","outcome":"${fixture.outcome}"`); + }); +}); diff --git a/typescript/tests/operations-parity.test.ts b/typescript/tests/operations-parity.test.ts new file mode 100644 index 0000000..e522de6 --- /dev/null +++ b/typescript/tests/operations-parity.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, mock, test } from "bun:test"; +import { IgnitionAI } from "../src/index"; + +function client(fetchImpl: typeof fetch) { + return new IgnitionAI({ apiKey: "ign_test", baseURL: "http://localhost", fetch: fetchImpl, maxRetries: 0 }); +} + +describe("operational SDK parity", () => { + test("submits feedback", async () => { + const fetchImpl = mock(() => Promise.resolve(Response.json({ success: true, message: "ok" }))) as unknown as typeof fetch; + await client(fetchImpl).feedback.submit({ type: "feature", message: "Please add this useful feature" }); + const call = (fetchImpl as unknown as { mock: { calls: unknown[][] } }).mock.calls[0]!; + expect(call[0]).toContain("/api/feedback"); + expect(JSON.parse((call[1] as RequestInit).body as string).type).toBe("feature"); + }); + + test("lists, gets metrics and exports traces", async () => { + const fetchImpl = mock((url: string) => { + if (url.includes("/export")) return Promise.resolve(new Response("id,status\n1,success", { headers: { "content-type": "text/csv", "content-disposition": 'attachment; filename="traces.csv"' } })); + if (url.includes("/metrics")) return Promise.resolve(Response.json({ summary: { count: 1 } })); + return Promise.resolve(Response.json({ traces: [], pagination: {} })); + }) as unknown as typeof fetch; + const sdk = client(fetchImpl); + await sdk.traces.list({ collectionId: "coll_1", limit: 10 }); + const metrics = await sdk.traces.metrics({ startDate: "2026-08-01T00:00:00.000Z", endDate: "2026-08-02T00:00:00.000Z" }); + const exported = await sdk.traces.export({ format: "csv", startDate: "2026-08-01T00:00:00.000Z", endDate: "2026-08-02T00:00:00.000Z" }); + expect(metrics.summary).toEqual({ count: 1 }); + expect(exported.filename).toBe("traces.csv"); + expect(exported.content).toContain("success"); + }); + + test("runs a transient RAG A/B test", async () => { + const fetchImpl = mock(() => Promise.resolve(Response.json({ configA: {}, configB: {}, comparison: { speedDifferenceMs: 2, speedWinner: "A", resultOverlap: 0.5, recommendation: "A" } }))) as unknown as typeof fetch; + const result = await client(fetchImpl).ragAbTests.run("coll/1", { configA: {}, configB: {}, testQuery: "question" }); + expect(result.comparison.speedWinner).toBe("A"); + const call = (fetchImpl as unknown as { mock: { calls: unknown[][] } }).mock.calls[0]!; + expect(call[0]).toContain("/collections/coll%2F1/rag-config/test"); + }); +}); diff --git a/typescript/tests/readme-contract.test.ts b/typescript/tests/readme-contract.test.ts index dbd020a..2aeb7d2 100644 --- a/typescript/tests/readme-contract.test.ts +++ b/typescript/tests/readme-contract.test.ts @@ -32,6 +32,15 @@ describe("README contract snippets", () => { expect(readme).toContain("`latest` tag remains on the stable `0.2.x` line"); }); + test("documents SaaS member ingest routes and offering errors", () => { + expect(readme).toContain("On managed SaaS, members use the metered async routes"); + expect(readme).toContain("POST /api/ingest/url/async"); + expect(readme).toContain("OfferingUnavailableError"); + expect(readme).toContain("AI_TEMPORARILY_UNAVAILABLE"); + expect(readme).toContain("ingest.crawlAsync"); + expect(readme).toContain("ingest.datasetAsync"); + }); + test("documents every first-class execution surface", () => { expect(dataChatSource).toContain("precheck("); expect(dataChatSource).toContain("send("); diff --git a/typescript/tests/verify-contract.test.ts b/typescript/tests/verify-contract.test.ts new file mode 100644 index 0000000..343199e --- /dev/null +++ b/typescript/tests/verify-contract.test.ts @@ -0,0 +1,74 @@ +import { existsSync, readFileSync } from "node:fs"; +import { describe, expect, test } from "bun:test"; +import { join } from "node:path"; +import { PUBLIC_CONTRACT_VERSION } from "../src/contract.js"; + +const packageRoot = join(import.meta.dir, ".."); + +function archivePath(version: string): string { + const relative = join("contracts", version, "public-sdk-contract.json"); + const candidates = [join(packageRoot, relative), join(packageRoot, "..", relative)]; + return candidates.find(existsSync) ?? candidates[0]!; +} + +const currentArchivePath = archivePath(PUBLIC_CONTRACT_VERSION); +const legacyArchivePath = archivePath("2026.07"); + +function runVerifyContract(args: string[] = []) { + return Bun.spawnSync(["bun", "run", "scripts/verify-contract.ts", ...args], { + cwd: packageRoot, + stdout: "pipe", + stderr: "pipe", + }); +} + +function releaseSequence(path: string): number { + return JSON.parse(readFileSync(path, "utf8")).payload.releaseSequence as number; +} + +describe("verify:contract default archive", () => { + test("verifies the current signed archive when present, otherwise the legacy private fallback", () => { + const expectedPath = existsSync(currentArchivePath) ? currentArchivePath : legacyArchivePath; + const expectedVersion = existsSync(currentArchivePath) ? PUBLIC_CONTRACT_VERSION : "2026.07"; + const result = runVerifyContract(["--minimum-release-sequence", String(releaseSequence(expectedPath))]); + expect(result.stderr.toString()).not.toContain("Unable to locate"); + expect(result.exitCode).toBe(0); + expect(result.stdout.toString()).toContain(`version ${expectedVersion}`); + expect(result.stdout.toString()).toContain(expectedPath); + expect(result.stderr.toString()).not.toContain("Warning: verified archive version"); + if (expectedVersion === PUBLIC_CONTRACT_VERSION) { + expect(result.stdout.toString()).not.toContain("Using last signed private archive"); + } else { + expect(result.stdout.toString()).toContain( + `Using last signed private archive ${expectedVersion}; SDK identity ${PUBLIC_CONTRACT_VERSION} is unsigned in this tree.`, + ); + } + }); + + test("verifies an explicitly selected preserved 2026.07 artifact and warns about its older identity", () => { + const result = runVerifyContract([ + "--contract", legacyArchivePath, + "--minimum-release-sequence", String(releaseSequence(legacyArchivePath)), + ]); + expect(result.exitCode).toBe(0); + expect(result.stdout.toString()).toContain("version 2026.07"); + expect(result.stdout.toString()).toContain(legacyArchivePath); + if (PUBLIC_CONTRACT_VERSION !== "2026.07") { + expect(result.stderr.toString()).toContain( + `Warning: verified archive version 2026.07 differs from SDK identity ${PUBLIC_CONTRACT_VERSION}`, + ); + } else { + expect(result.stderr.toString()).not.toContain("Warning: verified archive version"); + } + }); + + test("strict verification rejects a valid signed archive with a different SDK revision", () => { + if (PUBLIC_CONTRACT_VERSION === "2026.07") return; + const result = runVerifyContract(["--contract", legacyArchivePath, "--require-sdk-identity"]); + expect(result.exitCode).toBe(1); + expect(result.stderr.toString()).toContain( + `Signed contract version 2026.07 does not match SDK identity ${PUBLIC_CONTRACT_VERSION}`, + ); + expect(result.stdout.toString()).not.toContain("Verified contract sequence"); + }); +}); diff --git a/typescript/tests/widgets.test.ts b/typescript/tests/widgets.test.ts new file mode 100644 index 0000000..477db37 --- /dev/null +++ b/typescript/tests/widgets.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, mock, test } from "bun:test"; +import { IgnitionAI } from "../src/index"; + +function clientWith(response: unknown) { + const fetchMock = mock(() => Promise.resolve(new Response(JSON.stringify(response), { + status: 200, + headers: { "Content-Type": "application/json" }, + }))) as unknown as typeof fetch; + return { + client: new IgnitionAI({ + apiKey: "ign_test", + baseURL: "http://localhost", + fetch: fetchMock, + maxRetries: 0, + }), + fetchMock, + }; +} + +describe("widgets", () => { + test("supports management, key rotation, and analytics", async () => { + const { client, fetchMock } = clientWith({ widgets: [], id: "widget_1" }); + + await client.widgets.list(); + await client.widgets.get("widget_1"); + await client.widgets.create({ name: "Support", type: "agent", agentId: "agent_1" }); + await client.widgets.update("widget_1", { isActive: false }); + await client.widgets.regenerateKey("widget_1"); + await client.widgets.analytics("widget_1", "7d"); + await client.widgets.delete("widget_1"); + + expect(fetchMock.mock.calls.map((call) => [ + (call[1] as RequestInit).method, + call[0], + ])).toEqual([ + ["GET", "http://localhost/api/widgets"], + ["GET", "http://localhost/api/widgets/widget_1"], + ["POST", "http://localhost/api/widgets"], + ["PUT", "http://localhost/api/widgets/widget_1"], + ["POST", "http://localhost/api/widgets/widget_1/regenerate-key"], + ["GET", "http://localhost/api/widgets/widget_1/analytics?period=7d"], + ["DELETE", "http://localhost/api/widgets/widget_1"], + ]); + }); +}); + +describe("managed widget contract", () => { + test("rejects provider configuration before dispatch and projects a safe response", async () => { + const fetchMock = mock(() => Promise.resolve(new Response(JSON.stringify({ + id: "widget_1", name: "Support", type: "agent", collectionId: null, agentId: "agent_1", workflowId: null, + workflowConfig: { buttonLabel: "Run", apiKey: "secret" }, keyPrefix: "wgt_", allowedDomains: [], + theme: { preset: "dark", primaryColor: "#000", providerConfig: "secret" }, position: "bottom-right", + welcomeMessage: null, placeholder: null, suggestions: [], avatarUrl: null, displayMode: "support", locale: null, + headerTitle: null, hidePoweredBy: true, customCss: null, humanEscalation: { type: "webhook", target: "https://example.test/?token=secret" }, + rateLimitPerMinute: 10, sessionTtlMinutes: 30, isActive: true, createdAt: "now", updatedAt: "now", + llmConfigId: "private-config", llmModel: "private-model", llmSource: "byok", + }), { status: 200, headers: { "Content-Type": "application/json" } }))) as unknown as typeof fetch; + const client = new IgnitionAI({ apiKey: "ign_test", baseURL: "http://localhost", fetch: fetchMock, maxRetries: 0 }); + + await expect(client.widgets.managed.create({ name: "Nope", type: "agent", llmModel: "private-model" } as never)) + .rejects.toThrow("Managed widgets cannot select a provider or include secret configuration"); + await expect(client.widgets.managed.create({ name: "Nope", type: "workflow-form", workflowConfig: { providerKey: "private-key" } } as never)) + .rejects.toThrow("Managed contract does not accept providerKey"); + expect(fetchMock).not.toHaveBeenCalled(); + + const widget = await client.widgets.managed.get("widget_1"); + expect(widget.name).toBe("Support"); + expect(widget.theme).toEqual({ preset: "dark", primaryColor: "#000" }); + expect(widget.workflowConfig).toEqual({ buttonLabel: "Run" }); + expect(widget).not.toHaveProperty("llmConfigId"); + expect(widget).not.toHaveProperty("humanEscalation"); + }); + + test("sends the strict business contract and retains licensed widget fields", async () => { + const fetchMock = mock(() => Promise.resolve(new Response(JSON.stringify({ + widget: { id: "widget_1", name: "Managed", llmModel: "private-model", llmConfigId: "private-id" }, + widgetKey: "wgt_public_once", embedCode: "", + }), { status: 200, headers: { "Content-Type": "application/json" } }))) as unknown as typeof fetch; + const client = new IgnitionAI({ apiKey: "ign_test", baseURL: "http://localhost", fetch: fetchMock, maxRetries: 0 }); + const created = await client.widgets.managed.create({ name: "Managed", type: "agent", agentId: "agent_1" }); + expect(created.widget).not.toHaveProperty("llmModel"); + expect(created.widgetKey).toBe("wgt_public_once"); + const body = JSON.parse((fetchMock as any).mock.calls[0][1].body); + expect(body).toEqual({ name: "Managed", type: "agent", agentId: "agent_1" }); + + await client.widgets.create({ name: "Licensed", type: "agent", llmModel: "self-hosted-model" }); + expect(JSON.parse((fetchMock as any).mock.calls[1][1].body).llmModel).toBe("self-hosted-model"); + }); +}); diff --git a/typescript/tests/workflows.test.ts b/typescript/tests/workflows.test.ts index cfe3282..abbb244 100644 --- a/typescript/tests/workflows.test.ts +++ b/typescript/tests/workflows.test.ts @@ -22,7 +22,8 @@ describe("workflows", () => { const { client, fetchMock } = clientWith({ id: "wf_1", name: "Review" }); await client.workflows.list(); await client.workflows.get("wf_1"); - await client.workflows.create({ name: "Review" }); + await client.workflows.create({ name: "Review", isActive: false }); + expect(JSON.parse(String(fetchMock.mock.calls[2]?.[1]?.body))).toEqual({ name: "Review", isActive: false }); await client.workflows.update("wf_1", { isActive: true }); await client.workflows.validate("wf_1"); await client.workflows.delete("wf_1"); @@ -41,11 +42,13 @@ describe("workflows", () => { }); test("separates transport calls from explicit remote execution cancellation", async () => { - const { client, fetchMock } = clientWith({ executionId: "exec_1", status: "running", output: null }); + const { client, fetchMock } = clientWith({ cancelled: true }); await client.workflows.execute("wf_1", { input: { documentId: "doc_1" } }); await client.workflows.listExecutions("wf_1", { limit: 10 }); await client.workflows.getExecution("exec_1"); - await client.workflows.cancelExecution("exec_1"); + const cancellation = await client.workflows.cancelExecution("exec_1"); + + expect(cancellation.cancelled).toBe(true); expect(fetchMock.mock.calls.map((call) => [ (call[1] as RequestInit).method, @@ -57,4 +60,32 @@ describe("workflows", () => { ["DELETE", "http://localhost/api/workflows/executions/exec_1"], ]); }); + + test("supports the explicit managed SaaS execution contract", async () => { + const { client, fetchMock } = clientWith({ + executionId: "exec_1", + status: "admitted", + output: null, + reconciliationRequired: false, + maximumMilliCredits: "1000", + chargedMilliCredits: null, + }); + await client.workflows.executeManaged("wf_1", { + requestId: "00000000-0000-0000-0000-000000000001", + input: { query: "hello" }, + }); + const body = JSON.parse((fetchMock.mock.calls[0]![1] as RequestInit).body as string); + expect(body).toEqual({ + requestId: "00000000-0000-0000-0000-000000000001", + input: { query: "hello" }, + }); + }); + + test("rejects a missing managed request identity before transport", async () => { + const { client, fetchMock } = clientWith({}); + await expect(Promise.resolve().then(() => client.workflows.executeManaged("wf_1", { + requestId: "", + }))).rejects.toBeInstanceOf(TypeError); + expect(fetchMock).not.toHaveBeenCalled(); + }); }); From aded23e221d760316b15e06bb6cdad6b44ddc905 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:09:01 +0000 Subject: [PATCH 2/2] chore: sync signed IgnitionRAG SDK contract --- .sdk-source.json | 2 +- typescript/src/types.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.sdk-source.json b/.sdk-source.json index d69cb49..ab7f4e6 100644 --- a/.sdk-source.json +++ b/.sdk-source.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "sourceCommit": "9996d0b44aa62d7e9dbcc9b7a533868c789d4d5c", + "sourceCommit": "bd9e63c32f78a4a65929cece9ed128e4e2a67ae6", "contract": "contracts/2026.11/public-sdk-contract.json", "packages": [ "typescript" diff --git a/typescript/src/types.ts b/typescript/src/types.ts index cde020f..193bee8 100644 --- a/typescript/src/types.ts +++ b/typescript/src/types.ts @@ -926,8 +926,8 @@ export interface WidgetSuggestion { } export interface WidgetHumanEscalation { - type: "mailto" | "url" | "webhook"; - target: string; + type: "none" | "inbox" | "mailto" | "url" | "webhook"; + target?: string; label?: string; }