narrarium-engine 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +185 -13
- package/dist/ai/body.d.ts +20 -0
- package/dist/ai/body.d.ts.map +1 -0
- package/dist/ai/body.js +112 -0
- package/dist/ai/body.js.map +1 -0
- package/dist/ai/catalog-fetch.d.ts +51 -0
- package/dist/ai/catalog-fetch.d.ts.map +1 -0
- package/dist/ai/catalog-fetch.js +260 -0
- package/dist/ai/catalog-fetch.js.map +1 -0
- package/dist/ai/catalog-support.d.ts +13 -0
- package/dist/ai/catalog-support.d.ts.map +1 -0
- package/dist/ai/catalog-support.js +28 -0
- package/dist/ai/catalog-support.js.map +1 -0
- package/dist/ai/catalog.d.ts +148 -0
- package/dist/ai/catalog.d.ts.map +1 -0
- package/dist/ai/catalog.js +367 -0
- package/dist/ai/catalog.js.map +1 -0
- package/dist/ai/config.d.ts +83 -7
- package/dist/ai/config.d.ts.map +1 -1
- package/dist/ai/config.js +83 -11
- package/dist/ai/config.js.map +1 -1
- package/dist/ai/fetch-client.d.ts +20 -0
- package/dist/ai/fetch-client.d.ts.map +1 -1
- package/dist/ai/fetch-client.js +49 -24
- package/dist/ai/fetch-client.js.map +1 -1
- package/dist/ai/probe.d.ts +40 -0
- package/dist/ai/probe.d.ts.map +1 -0
- package/dist/ai/probe.js +110 -0
- package/dist/ai/probe.js.map +1 -0
- package/dist/ai/request.d.ts +58 -5
- package/dist/ai/request.d.ts.map +1 -1
- package/dist/ai/request.js +96 -7
- package/dist/ai/request.js.map +1 -1
- package/dist/ai/router.d.ts +12 -1
- package/dist/ai/router.d.ts.map +1 -1
- package/dist/ai/router.js +10 -2
- package/dist/ai/router.js.map +1 -1
- package/dist/ai/routing.d.ts +15 -4
- package/dist/ai/routing.d.ts.map +1 -1
- package/dist/ai/routing.js +25 -6
- package/dist/ai/routing.js.map +1 -1
- package/dist/ai/token-limit.d.ts +4 -4
- package/dist/ai/token-limit.d.ts.map +1 -1
- package/dist/ai/token-limit.js +5 -4
- package/dist/ai/token-limit.js.map +1 -1
- package/dist/ai/types.d.ts +12 -1
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/types.js +12 -0
- package/dist/ai/types.js.map +1 -1
- package/dist/autopilot/errors.d.ts +4 -3
- package/dist/autopilot/errors.d.ts.map +1 -1
- package/dist/autopilot/errors.js +21 -5
- package/dist/autopilot/errors.js.map +1 -1
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +21 -4
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.js +1 -1
- package/dist/autopilot/session.js.map +1 -1
- package/dist/autopilot/state.d.ts +4 -3
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +35 -9
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/tasks.js +2 -2
- package/dist/autopilot/tasks.js.map +1 -1
- package/dist/autopilot/types.d.ts +27 -5
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/autopilot/types.js +1 -1
- package/dist/autopilot/types.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/server/protocol.d.ts +6 -1
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -21,7 +21,8 @@ npm install narrarium-engine
|
|
|
21
21
|
| Ghostwriters | `parseGhostwriter`, `ghostwriterPrompt` |
|
|
22
22
|
| Markdown | `parseMarkdown` (with `error`), `splitFrontmatter`, `stripFrontmatter`, `renderMarkdown`, `FrontmatterError` |
|
|
23
23
|
| Text | `clipMiddle`, `truncate`, `tail`, `countWords`, `languageCode`, `tokensPerWord`, `scaleOutputTokens`, `sceneCharacterLimit` |
|
|
24
|
-
| AI | `AiPort` (the only door to language models), `createFetchAi` (OpenAI, Azure OpenAI, GitHub Models), `buildChatRequest`, `resolveAiCandidates`, `pickAiRuntimeConfig`, `effectiveAiBase`, `endpointOrigin`, `redactSecrets`, the deadlines and limits of a call (`DEFAULT_REQUEST_TIMEOUT_MS`, `MIN_REQUEST_TIMEOUT_MS`, `DEFAULT_IDLE_TIMEOUT_MS`, `TOTAL_REQUEST_CAP_MS`, `MAX_STREAM_TRANSPORT_BYTES`…) |
|
|
24
|
+
| AI | `AiPort` (the only door to language models), `createFetchAi` (OpenAI, Azure OpenAI, GitHub Models), `buildChatRequest`, `resolveAiCandidates`, `pickAiRuntimeConfig`, `redactAiRuntimeConfig`, `AI_THINKING_LEVELS`, `AI_REASONING_PARAMETERS`, `suggestedReasoningParameter`, `AiToolsRequiredError`, `effectiveAiBase`, `endpointOrigin`, `redactSecrets`, the deadlines and limits of a call (`DEFAULT_REQUEST_TIMEOUT_MS`, `MIN_REQUEST_TIMEOUT_MS`, `DEFAULT_IDLE_TIMEOUT_MS`, `TOTAL_REQUEST_CAP_MS`, `MAX_STREAM_TRANSPORT_BYTES`…) |
|
|
25
|
+
| Model catalog | `fetchModelCatalog` (the models of an OpenAI-compatible endpoint, with the window, the largest answer and the capabilities its gateway declares), `probeEndpoint` (does it answer, and how), `fetchLmStudioModels`, the pure parsers `parseModelList`, `parseModelDetails`, `parseModalities`, `tokenLimitsFromDetails`, `modelFieldsFromCatalogEntry`, `parseLmStudioModels`, `lmStudioContext`, `AiCatalogError`, `AI_MODEL_TYPES`, `catalogTarget`: see *Model catalog and declared capabilities* |
|
|
25
26
|
| Personal server | `NarrariumServerClient`, `pairWithServer`, `pairWithServerDetailed`, `verifyServerIdentity`, `serverCompatibility`, `serverSupportsAutopilotControls`, `serverSupportsAutopilotRules`, `remoteBookStore`, protocol types (scopes, pairing, updates), `ServerSentEventParser` |
|
|
26
27
|
| Sync | `planFileSync`, `syncBookStores` (three-way sync of two book stores, with the files it leaves out in `skipped`) |
|
|
27
28
|
| Testing | `narrarium-engine/testing`: `MemoryBookStore`, `seedBookFiles`, `createFakeAutopilotAi` |
|
|
@@ -122,9 +123,9 @@ Data the web app's pages used to have to guess (from the text of a step, from th
|
|
|
122
123
|
|
|
123
124
|
**The final verdict.** When the `final` step is done, `state.finalReview` is `{ verdict, score, text, at }`: the director's judgement of the whole book as data, where the line of the step said `approve 8/10 — …`. `verdict` is `"approve"` or `"revise"` (a `rewrite` is a `revise`, and so is an approval withheld because its score is under the `approvalScore` of `director.md`); the book is closed all the same, as it always was. `score` is on the scale of the chapters (0-10, one decimal at most), `text` is the director's summary cut with `clipText` at `FINAL_REVIEW_TEXT_CHARACTERS` (1200) characters, and `at` is when the director gave it. `summary.finalReview` has the same fields with the text cut at `FINAL_REVIEW_SUMMARY_CHARACTERS` (400). A book that is not complete any more (its chapters were extended, or a `rewrite` reopened it) has none until the final step is done again.
|
|
124
125
|
|
|
125
|
-
**Working time.** `stats.workedMs` is the sum, over every run, of the durations of the steps that were saved, each from its start to its end as its activity shows. Not counted: the wait for the author, the pauses between runs, the attempts of a step that failed and the waits between them (a step counts the attempt that was saved), the steps that were abandoned. A whole number of milliseconds, never negative, in the state (so it outlives the 200 activities of the log) and in `summary.stats`. A state written before it existed has none (and neither has its summary: not zero, not `NaN`) and it counts from zero at the first step that is saved.
|
|
126
|
+
**Working time.** `stats.workedMs` is the sum, over every run, of the durations of the steps that were saved, each from its start to its end as its activity shows. Not counted: the wait for the author, the pauses between runs, the attempts of a step that failed and the waits between them (a step counts the attempt that was saved), the steps that were abandoned. A whole number of milliseconds, never negative, in the state (so it outlives the 200 activities of the log) and in `summary.stats`. A state written before it existed has none (and neither has its summary: not zero, not `NaN`) and it counts from zero at the first step that is saved. `stats.workedMsSince` is the ISO time (UTC, `2026-02-01T08:00:00.000Z`) at which the first step that the count included began: the count is born with the first step it counts, and the moment is written then, once, and never changed after (not by the steps that follow, not by another run), so that a client can say *since when* the time is counted. A book whose count began before the moment was written has `workedMs` and no `workedMsSince`, and the engine does not make one up: it cannot know. Read from a file it is a date or a date and time with its zone (`2026-02-01`, `2026-02-01T10:00:00+02:00`, said again in UTC) and only next to `workedMs`; any other value is dropped.
|
|
126
127
|
|
|
127
|
-
**Errors.** A step that fails puts `errorKind` and `errorDetail` in its activity (the `task-finished` event carries them too) and, when it ends the run, in `state.lastError`; `summary.lastError` has the same two under the names `kind` and `detail` as well. A step that the author cancelled is no failure and has neither. `AutopilotErrorKind` is a closed list (`AUTOPILOT_ERROR_KINDS`), told from what the engine knows of its errors (`classifyAutopilotError(error)` is the one function, a status or a flag deciding before the words do):
|
|
128
|
+
**Errors.** A step that fails puts `errorKind` and `errorDetail` in its activity (the `task-finished` event carries them too) and, when it ends the run, in `state.lastError`; `summary.lastError` has the same two under the names `kind` and `detail` as well. A step that the author cancelled is no failure and has neither. `state.lastError` (and `summary.lastError`) also says *which* step failed: `activityId` is the id of its activity, the one in the log and in the `task-finished` event (the last attempt, when the step was retried), so a client does not have to guess it from the time. A failure that belongs to no step (the ceiling of steps of a run) has none, and neither has an error saved by an engine that did not say it; the id is read from a file only when it is short and made of letters, digits and `_ . : -`. `AutopilotErrorKind` is a closed list (`AUTOPILOT_ERROR_KINDS`), told from what the engine knows of its errors (`classifyAutopilotError(error)` is the one function, a status or a flag deciding before the words do):
|
|
128
129
|
|
|
129
130
|
| Kind | What it is |
|
|
130
131
|
|---|---|
|
|
@@ -138,16 +139,21 @@ Data the web app's pages used to have to guess (from the text of a step, from th
|
|
|
138
139
|
| `budget` | The routing limits leave no candidate to call (`AiRoutingBudgetError`). |
|
|
139
140
|
| `limit` | No context window holds the prompt (`AiPromptTooLargeError`), or the run's own ceiling of steps. |
|
|
140
141
|
| `profile` | A file of the book the autopilot would rewrite cannot be read: its frontmatter is not valid YAML (`FrontmatterError`). The author fixes it. |
|
|
142
|
+
| `config` | The AI configuration has to change, and repeating the step cannot help: with "Tools only" on, no model of the task can call a function (`AiToolsRequiredError`, see *Tools only*). Nothing was sent. |
|
|
141
143
|
| `conflict` | A file changed under the step and the retries are used up (`BookConflictError`). |
|
|
142
144
|
| `unknown` | Everything else. |
|
|
143
145
|
|
|
144
|
-
`errorDetail` is `{ status?, endpoint?, model?, provider?, integration?, attempt?, retries?, timeoutMs?, timeoutPhase? }`, short and with no secret in any field: `status` is the HTTP status when the provider answered; `endpoint` is only the **origin** of the integration's address (`new URL(address).origin`: never a path, a query, a fragment or credentials, and nothing at all for an address that is not a web address); `model`, `provider` and `integration` (the id) are passed through `redactSecrets` and cut at 160 characters. `attempt` and `retries` are there only for a failure that is retried: the retry it belongs to (the one that followed it, or the last one made when the run gave up) and how many retries this kind of failure gets, the numbers of the `failureRetry` insight; a failure that is never retried (a 401) has neither. `timeoutPhase` (`"start"`, `"idle"` or `"total"`) and `timeoutMs` are there only for a timeout of the engine's client: which deadline ran out (the provider did not begin answering, it went silent while it answered, or the call took longer than any call may) and how long it was, in milliseconds (a value read from a file is a whole number from 1 ms to a day, else it is dropped); see *Timeouts and streaming*. Where an error came from is `AiProviderError.target` (`{ provider, model, integrationId, endpoint? }`, the endpoint already an origin), which the engine's client sets on the error of the last candidate it tried; it is separate from the error's own `model`, `provider` and `integrationId`, whose presence means that the model had started to answer and is billed. A state written before the errors were classified has `lastError` with a message and no kind: `summary.lastError` then has none either.
|
|
146
|
+
`errorDetail` is `{ status?, endpoint?, model?, provider?, integration?, retryAfterMs?, attempt?, retries?, timeoutMs?, timeoutPhase? }`, short and with no secret in any field: `status` is the HTTP status when the provider answered; `retryAfterMs` is what the provider asked for with `Retry-After` in milliseconds, on a 429 or a 503 only and only when it said (the engine's client keeps at most five minutes of it, `0` is a value, and a value read from a file is a whole number from 0 to a day, else it is dropped), so that a client can say *the provider asks to wait 30 s* without guessing it from the retry; `endpoint` is only the **origin** of the integration's address (`new URL(address).origin`: never a path, a query, a fragment or credentials, and nothing at all for an address that is not a web address); `model`, `provider` and `integration` (the id) are passed through `redactSecrets` and cut at 160 characters. `attempt` and `retries` are there only for a failure that is retried: the retry it belongs to (the one that followed it, or the last one made when the run gave up) and how many retries this kind of failure gets, the numbers of the `failureRetry` insight; a failure that is never retried (a 401) has neither. `timeoutPhase` (`"start"`, `"idle"` or `"total"`) and `timeoutMs` are there only for a timeout of the engine's client: which deadline ran out (the provider did not begin answering, it went silent while it answered, or the call took longer than any call may) and how long it was, in milliseconds (a value read from a file is a whole number from 1 ms to a day, else it is dropped); see *Timeouts and streaming*. Where an error came from is `AiProviderError.target` (`{ provider, model, integrationId, endpoint? }`, the endpoint already an origin), which the engine's client sets on the error of the last candidate it tried; it is separate from the error's own `model`, `provider` and `integrationId`, whose presence means that the model had started to answer and is billed. A state written before the errors were classified has `lastError` with a message and no kind: `summary.lastError` then has none either.
|
|
145
147
|
|
|
146
148
|
**The retry that is waiting.** While the run waits to try a failed step again, `summary.retry` is `{ at, attempt, retries }`: `at` is the ISO time of the next attempt, `attempt` and `retries` those of the `failureRetry` insight (`retry 2 of 3`). It is never saved, and it is the fourth field of the summary that only a live session knows (see *What the summary says*). Every change is a `state` event, so a client counts down without guessing: one event when the wait begins (right after the `failureRetry` insight), one when it is over and the attempt starts (the summary has no `retry` then), and the last summary of a run that ends, or is paused, during the wait has none. A host that gets the state from a `state` event replaces its summary by the newest one it has seen, and so the retry goes away.
|
|
147
149
|
|
|
148
|
-
**The rounds of every chapter.** `PlannedChapter.rounds` is a compact history of the rounds of review of a chapter that closed: one `{ director?, readers?, accepted?, rejected? }` for each, oldest first, written when the director judges the round and kept after the chapter is closed (`state.review` is the round in progress and is cleared when the chapter closes). `director` is the director's vote and `readers` the average of the simulated readers' votes (0-10, one decimal at most); `accepted` and `rejected` are what the director decided, whole numbers. The readers read a chapter once, in the first round of its review, so only that round has `readers` (a chapter rewritten after the author's request is reviewed again without readers). A chapter keeps at most `MAX_CHAPTER_ROUNDS` (8): a chapter that is rewritten adds the rounds of its new review and the oldest leave. A chapter that was never reviewed has none (`rounds` is absent, never an empty list), and the history survives the plan being made again around the chapters when the author raises the number of chapters of a finished book. In `state.json` every round takes one line of about
|
|
150
|
+
**The rounds of every chapter.** `PlannedChapter.rounds` is a compact history of the rounds of review of a chapter that closed: one `{ director?, readers?, verdict?, accepted?, rejected? }` for each, oldest first, written when the director judges the round and kept after the chapter is closed (`state.review` is the round in progress and is cleared when the chapter closes). `director` is the director's vote and `readers` the average of the simulated readers' votes (0-10, one decimal at most); `accepted` and `rejected` are what the director decided, whole numbers. `verdict` is `"approve"` (the round closed the chapter) or `"revise"` (it sent the chapter back for fixes): the verdict the plan acted on, which is not always the one the model gave (an approval under the `approvalScore` of `director.md` is withheld and is a `revise`, and a revision with no applicable fix is an `approve`), so a client reads it here instead of from the text of the log. A round saved by an engine that did not say it has none; a `verdict` read from a file is `approve` or `revise` (case and spaces do not matter) or it is dropped, and a verdict with no number is no round. The readers read a chapter once, in the first round of its review, so only that round has `readers` (a chapter rewritten after the author's request is reviewed again without readers). A chapter keeps at most `MAX_CHAPTER_ROUNDS` (8): a chapter that is rewritten adds the rounds of its new review and the oldest leave. A chapter that was never reviewed has none (`rounds` is absent, never an empty list), and the history survives the plan being made again around the chapters when the author raises the number of chapters of a finished book. In `state.json` every round takes one line of about 100 bytes (the file is still plain JSON), so a book of 5000 chapters with three rounds each adds about 1.4 MiB, and with the eight rounds every chapter may keep about 3.9 MiB, to a file the server accepts up to 8 MiB.
|
|
149
151
|
|
|
150
|
-
**
|
|
152
|
+
**The step that is answering.** `task-progress` says that the model of the running step is answering. A step that writes prose says it as it always did: `preview` (the tail of the text so far) and `characters`, at most about three times a second. A step that answers with a structured value (the concept, the plan, a reader's evaluation, the director's decisions, the summary of a scene) says it with numbers only: `{ type: "task-progress", activityId, characters, bytes, preview: "" }`, where `bytes` is what has arrived of the reply and `characters` the characters of its function arguments, never a word of the reply, and **one event a second** for each step at most (the client reports up to four times a second, and the stream of a server is not flooded). It only exists while the provider streams: with `streamMode: "off"` there is nothing to say until the reply is whole. Like every `task-progress` it is never saved (not in `state.json`, not in the log, not a commit) and never replayed to a client that connects later; `snapshot().live` carries the last one (`{ activity, characters, preview, bytes? }`: `bytes` only when the last one was a structured one). The event is the same one the prose steps have: `preview` stays a string (empty here), and `bytes` is the only new field, so a client that knows nothing of it reads `characters` and an empty preview. A step that writes a scene and then asks for its summary says both kinds one after the other, and the empty `preview` of the second replaces the text of the first for a client that copies every `preview` (a client that wants to keep the scene on screen leaves `preview` alone when `bytes` is present). A client of the personal server gets the events as they are (the engine's client hands over every message of the stream, and a type it does not know is the host's to ignore).
|
|
153
|
+
|
|
154
|
+
**What a model declares.** The safe view of the AI configuration (`redactAiRuntimeConfig(config).integrations[].models[]`, which the personal server's `GET /ai` forwards as it is) says, for every model, what its configuration declares: `supportsToolCalls`, `supportsStreaming`, `supportsReasoning`, `supportsVision`, `maxInputTokens` and `maxOutputTokens`, and the `reasoningParameter` that says how its thinking level is sent (the "Thinking parameter" of the model, «Parametro del thinking»: `reasoning_effort`, `chat_template_kwargs.reasoning_strength` or `none`, with `AI_REASONING_PARAMETERS` for the list and `suggestedReasoningParameter(name, underlyingModel?)` for a hint that a screen may offer, which the engine never applies by itself), each only when it is declared or set (a model that declares nothing is `{ name, capabilities }`, as it always was). An attempt says what it did not do because of it: `onAttempt.notes` (English, absent when there is nothing to say; `ChatRequest.notes` for a host that builds the request itself), and `onAttempt.reasoningParameter` where the level went when it did not go as `reasoning_effort`. A reply cut with nothing written by a model declared as reasoning is a `truncated` error with `reasoningOnly`, so its `errorKind` is `truncated` like any cut reply. What an endpoint says of its models, and whether it answers at all, is what `fetchModelCatalog` and `probeEndpoint` return: see *Model catalog and declared capabilities*. All of it is additive: a configuration that declares nothing reads and runs as it always did.
|
|
155
|
+
|
|
156
|
+
**Older and newer engines.** Every new field is read tolerantly (a value that is not valid is dropped, never made up) and an older file reads as it always did. An engine from before these fields reads a file that has them without trouble but does not know them: `normalizeAutopilotState` of that engine drops `finalReview`, `stats.workedMs`, the kind and the detail of `lastError`, and the `rounds` of the chapters, so the first time it writes the state the history is lost (the activities keep their `errorKind` and `errorDetail`, which it does not look at). The worked time then starts again from zero in the engine that knows it, and the rounds start again with the next review. An engine that knows the rounds and the worked time but not what was added after them (the `verdict` of a round, `stats.workedMsSince`, `lastError.activityId` and the `retryAfterMs` of an error detail) drops those four on its first write, and the engine that knows them does not make them up again: a book that goes back and forth between the two keeps its rounds and its time, and loses the verdicts, the moment and the id of the failed step written meanwhile.
|
|
151
157
|
|
|
152
158
|
### Long books
|
|
153
159
|
|
|
@@ -227,16 +233,16 @@ What every host gets, whatever its options:
|
|
|
227
233
|
|
|
228
234
|
| What | How |
|
|
229
235
|
|---|---|
|
|
230
|
-
| Request | `buildChatRequest(candidate, request, { githubModelsBaseUrl })` is the only place a request is built: URL, headers, body, streaming, tools or JSON-in-prompt, and the output limit parameter of the model family. Pure and exported, so hosts can test their configuration against it. Every request streams (`stream: true`, `stream_options: { include_usage: true }`), a structured one included, unless the integration's `streamMode` is `"off"`: see *Timeouts and streaming*. |
|
|
231
|
-
| Output limit | A structured request gets at least `STRUCTURED_OUTPUT_FLOOR` (4096) tokens. A model known to reason by name (o1/o3/o4, gpt-5, codex-mini; for Azure the declared underlying model, else the deployment name) gets `REASONING_OUTPUT_MARGIN` (12 000) more, because its reasoning is counted in the limit. Never above the model's own `maxOutputTokens`. An Azure deployment of unknown identity gets `max_completion_tokens` from API version 2024-09-01, `max_tokens` before. |
|
|
236
|
+
| Request | `buildChatRequest(candidate, request, { githubModelsBaseUrl })` is the only place a request is built: URL, headers, body, streaming, tools or JSON-in-prompt, and the output limit parameter of the model family. Where the thinking level goes (`reasoning_effort`, or the chat-template argument the model says: see *Thinking*) is decided there too. Pure and exported, so hosts can test their configuration against it. Every request streams (`stream: true`, `stream_options: { include_usage: true }`), a structured one included, unless the integration's `streamMode` is `"off"` or the model declares `supportsStreaming: false`: see *Timeouts and streaming* and *Declared capabilities of a model*. |
|
|
237
|
+
| Output limit | A structured request gets at least `STRUCTURED_OUTPUT_FLOOR` (4096) tokens. A model known to reason by name (o1/o3/o4, gpt-5, codex-mini; for Azure the declared underlying model, else the deployment name) gets `REASONING_OUTPUT_MARGIN` (12 000) more, because its reasoning is counted in the limit; so does a model whose configuration declares `supportsReasoning: true` (a declaration never takes away the margin of a model known by its name). Never above the model's own `maxOutputTokens`. An Azure deployment of unknown identity gets `max_completion_tokens` from API version 2024-09-01, `max_tokens` before. |
|
|
232
238
|
| Prompt size | A candidate whose `maxInputTokens` (context window) cannot hold the prompt (estimated with `likelyMessageTokens`, the tool schema included, against `resolveModelTokenBudgets`: window minus the output reserve minus a 5% margin) is skipped. If no candidate can, `AiPromptTooLargeError` (not retryable) gives the estimate and the largest budget. A prompt is never cut. |
|
|
233
239
|
| Privacy of fallbacks | `fallbackDisclosure.sameBoundaryOnly` excludes fallbacks outside the primary's integration (the boundary). `requireAcknowledgement` asks `options.acknowledgeFallback(from, to, { capability, label })` before content goes to an integration it has not gone to: only `true` allows it, a throw cancels the call, and a host without the hook (the server) never crosses (fail closed). The engine asks at every call that needs the crossing (once per pair of accounts within a call), so a host that remembers acknowledgements answers from its memory. When nothing is left to call, the error names the setting and how to change it. |
|
|
234
240
|
| Routing limits | `routingExecution`: `maxCandidates`, `maxTotalDurationMs`, `maxTokenAttempts`, `maxEstimatedCost`. The total time never interrupts the first candidate before its own timeout; later candidates start only while time remains and run for what remains. Tokens and cost are estimated per attempt from the real prompt and the output limit (reasoning margin included): candidates are kept while the sum fits, and a first attempt that alone exceeds a limit gives `AiRoutingBudgetError`. A configuration without these fields (saved by an older host) has no such limits and no privacy policy. |
|
|
235
241
|
| Timeouts | Three, in every host: how long the provider has to begin answering (an integration's `requestTimeoutMs`, else `options.defaultTimeoutMs`, else `DEFAULT_REQUEST_TIMEOUT_MS`, 600 s; never under 30 s), the longest silence while it answers (`idleTimeoutMs`, 600 s) and the most one call may take (4 h). See *Timeouts and streaming*. |
|
|
236
|
-
| Hooks | `onAttempt(attempt)`: `attemptId`, the effective `messages` (with the JSON instruction a model without tools receives), the output limit, `stream`, `streamMode`, `tools`, `endpoint`, `timeoutMs` and `timeouts` (the three deadlines: see *Timeouts and streaming*). `onAttemptEnd(end)`: the same `attemptId`, `outcome` (`ok`, `failed`, `cancelled`), `usage`, `cost`, `usageKnown`, `costKnown`, the reply `text` or the `error` (without credentials), `failureKind` (`timeout`, `cancelled`, `provider`), `status`, `retryAfterMs`, `timeoutMs` and `timeoutPhase` (for a timeout), `streamed`, `firstByteMs`, `toolCalled` and `durationMs`, for every attempt that was sent, failed ones included. A hook that throws never breaks a call. |
|
|
242
|
+
| Hooks | `onAttempt(attempt)`: `attemptId`, the effective `messages` (with the JSON instruction a model without tools receives), the output limit, `stream`, `streamMode`, `tools`, `endpoint`, `timeoutMs` and `timeouts` (the three deadlines: see *Timeouts and streaming*), `toolsOnly` (whether Tools only was in force), `thinking` (the level sent, absent when none was), `reasoningParameter` (where it went, only when it went as the chat-template argument: see *Thinking*), `skipped` (the models left out, absent when none was: see *Tools only* and *Thinking*) and `notes` (what the attempt does not do that the configuration asked, because of what the model declares, in English; absent when there is nothing to say: see *Declared capabilities of a model*). `onAttemptEnd(end)`: the same `attemptId`, `outcome` (`ok`, `failed`, `cancelled`), `usage`, `cost`, `usageKnown`, `costKnown`, the reply `text` or the `error` (without credentials), `failureKind` (`timeout`, `cancelled`, `provider`), `status`, `retryAfterMs`, `timeoutMs` and `timeoutPhase` (for a timeout), `streamed`, `firstByteMs`, `toolCalled` and `durationMs`, for every attempt that was sent, failed ones included. A hook that throws never breaks a call. |
|
|
237
243
|
| Approving endpoints | `effectiveAiBase(integration, githubModelsBaseUrl?)` is the origin and path every request of an integration starts with, defaults included (`https://api.openai.com/v1`, `https://models.github.ai/inference`). A host that approves where API keys may be sent should compare these. |
|
|
238
244
|
| Wire format | Server-sent events with several `data:` lines are joined with a newline; the pieces of a forced function call (`delta.tool_calls[].function.arguments`) are joined into the arguments of the reply, and a last piece that carries the whole `message.tool_calls` is read too; a JSON reply to a streaming request (a server that ignores `stream`) is read as the reply; an `error` in a 200 reply is a provider error. |
|
|
239
|
-
| Errors | `AiProviderError` carries `status`, `retryable`, `transient` (it depends on the moment: 408, 429, 502, 503, 504, network), `retryAfterMs` (the `Retry-After` of a 429 or 503, at most five minutes), `timedOut` with `timeout` (which deadline ran out, for how long), `truncated` and `reasoningOnly
|
|
245
|
+
| Errors | `AiProviderError` carries `status`, `retryable`, `transient` (it depends on the moment: 408, 429, 502, 503, 504, network), `retryAfterMs` (the `Retry-After` of a 429 or 503, at most five minutes), `timedOut` with `timeout` (which deadline ran out, for how long), `truncated` and `reasoningOnly` (the reply was cut while the model reasoned: seen as reasoning, or, with nothing written at all, from a model declared as reasoning). `AiToolsRequiredError` (nothing can be asked: Tools only is on and no model can call a function; see *Tools only*) is the error of a call that was never sent. Keys, `Bearer …`, `api-key: …`, `?key=…` and `sk-…` are removed from every message (`redactSecrets`), also before the runner saves it. The error of a candidate that was tried carries `target` (`{ provider, model, integrationId, endpoint? }`, the endpoint only an origin: see *What the interface reads*). |
|
|
240
246
|
|
|
241
247
|
### Timeouts and streaming
|
|
242
248
|
|
|
@@ -271,7 +277,48 @@ An integration without its own value says `the default provider timeout` or `the
|
|
|
271
277
|
|
|
272
278
|
**What the hooks say.** `onAttempt(attempt)` carries `timeouts: { startMs, idleMs, capMs, raised?: { from } }` (the deadlines as they are applied, `raised` when the minimum lifted the provider timeout) and `streamMode`; `timeoutMs` is `timeouts.startMs`. `onAttemptEnd(end)` carries `streamed` (the reply was read as a stream), `firstByteMs` (milliseconds to the first byte of its body, or of the response for a JSON reply; absent when nothing arrived), `toolCalled` (for a structured request, whether the model delivered the result as a function call; absent otherwise) and, for a timeout, `timeoutMs` and `timeoutPhase`.
|
|
273
279
|
|
|
274
|
-
**Providers that cannot stream.** A provider that rejects `stream_options`, or does not stream with functions, answers 400: the error then adds `If this provider cannot stream its replies, set "Streaming" of the integration "…" to "off"` (only when its own message talks about streaming), and `streamMode: "off"` brings the old behavior back for that integration. A connection that is lost while the provider answers is told with what to check: the proxy or the tunnel between the app and the provider.
|
|
280
|
+
**Providers that cannot stream.** A provider that rejects `stream_options`, or does not stream with functions, answers 400: the error then adds `If this provider cannot stream its replies, set "Streaming" of the integration "…" to "off"` (only when its own message talks about streaming), and `streamMode: "off"` brings the old behavior back for that integration. A model that cannot stream while the others of its integration can declares `supportsStreaming: false` instead (see *Declared capabilities of a model*): only that model is called without `stream`. Leave a model that reasons streaming wherever you can: its reasoning counts against the output limit, and a reply that does not stream is silent until it is whole, which a proxy or a tunnel may cut (LlmProxy's own documentation says the same of its reasoning models). A connection that is lost while the provider answers is told with what to check: the proxy or the tunnel between the app and the provider.
|
|
281
|
+
|
|
282
|
+
### Tools only
|
|
283
|
+
|
|
284
|
+
Every autopilot agent answers through a function of its own (the concept, the plan, a reader's evaluation, the director's decisions, the summary of a scene… each has its schema, and the request forces the call with `tool_choice`): the answer is a field that is parsed, not a JSON that the message asked for and that the engine had to find in some text. *Tools only* makes that the only way. It is on unless the configuration turns it off: `AiRuntimeConfig.toolsOnly`, which `pickAiRuntimeConfig` reads from `settings.aiToolsOnly` (and from `toolsOnly` in a configuration that was already picked, which is what a personal server stores and reads back; the settings' own word wins when both are there, and a value that is not a boolean is ignored). A host with no such setting has it on. `redactAiRuntimeConfig(config).toolsOnly` says what is in force.
|
|
285
|
+
|
|
286
|
+
With Tools only on, a request with a function (`json`; a request for prose never changes) behaves like this:
|
|
287
|
+
|
|
288
|
+
- **A model marked as without tool calls is skipped** (`supportsToolCalls: false`: the "Forced tool calls" switch of the model in AI Integrations), a primary and a fallback alike, and nothing is sent to it. A model whose tool calls were never declared is asked as before: only an explicit `false` skips. The privacy policy is applied to the whole route first (a skipped primary is still the account that `sameBoundaryOnly` keeps the content in), and the position of a candidate in the route (`onAttempt.index`) does not move. `AttemptPlan.skipped` and `onAttempt.skipped` say what was left out (`[{ model, reason: "no-tool-calls" }]`, the same list on every attempt of the call, absent when nothing was skipped), and the final error of a call that failed says it too: `Skipped "beta-model" in "Beta": it is marked as without tool calls and "Tools only" is on.` The route is cut to `maxCandidates` before the skipping, so a skipped candidate counts against it.
|
|
289
|
+
- **If none is left**, the call ends before anything is sent with `AiToolsRequiredError` (an `AiProviderError`, not retryable, with `models`: the names of the models that were left out). Its message names them and says the two ways out: `"Tools only" is on, and every model this task can use is marked as without tool calls ("alpha-model" in "Alpha"), so a structured answer has nowhere to go. Turn on "Forced tool calls" for the model in AI Integrations, or turn off "Tools only" in the AI Router. Nothing was sent.` Its `errorKind` is `config`: the configuration has to change, so the run stops at once instead of retrying (see *What the interface reads*).
|
|
290
|
+
- **The answer must be the call of the function.** The arguments of the call are used, however they arrive (whole, or in the pieces of a stream) and with the tolerance they always had (double-encoded, or wrapped in `arguments` or `result`). The text of the reply is never read: not as the answer, and not as a fallback for arguments that are empty (`{}`, still rejected as they were) or that carry none of the expected fields. A reply that has text and no call is rejected, retryable like every rejected reply (the next candidate is tried, and the run repeats the step once with the reason), and what the attempt cost is kept: `openai muse-glimmer-30b: the model answered in text instead of calling the function "result": "Tools only" is on, so the text of a reply is never read as the answer. If this model cannot call functions, turn off "Tools only" in the AI Router.` A reply with nothing at all is still an empty reply.
|
|
291
|
+
|
|
292
|
+
With `toolsOnly: false` it is all as it was: a model without tool calls is used and gets the schema in its system message, and the JSON in a text reply is the answer when the function was not called. `onAttempt.toolsOnly` says which of the two was in force for a call.
|
|
293
|
+
|
|
294
|
+
### Thinking
|
|
295
|
+
|
|
296
|
+
How hard a model is asked to think, per integration and per route target, and in which parameter the level reaches each model. `AiIntegrationConfig.thinking` and `AiRouteTarget.thinking` (the primary and every fallback of a task's route) are one of `AI_THINKING_LEVELS`: `"automatic"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`. `pickAiRuntimeConfig` keeps a level spelled exactly so and drops anything else (the target, or the integration, is kept without it).
|
|
297
|
+
|
|
298
|
+
| The setting | What the request carries |
|
|
299
|
+
|---|---|
|
|
300
|
+
| absent on the target | the level of its integration, when it has one |
|
|
301
|
+
| absent on both | no level |
|
|
302
|
+
| `"automatic"` | no level, even when the integration has one |
|
|
303
|
+
| `"low"`, `"medium"`, `"high"`, `"xhigh"` | the level, in the parameter that the model it goes to says (*How the level is sent*): `reasoning_effort` unless the model says otherwise, in the body of every chat request (OpenAI-compatible, Azure OpenAI, GitHub Models), for prose and for a structured reply, streamed or not |
|
|
304
|
+
|
|
305
|
+
`AiCandidate.thinking` is the level the candidate resolves to (`target.thinking ?? integration.thinking`, absent when neither says), also for a task without a route of its own (then it is the integration's); a fallback has its own, the primary's is never carried to it. The `default` route only chooses the integration of the tasks that have no route, so its `thinking` is not used. `buildChatRequest` sends the four levels and nothing else, in the parameter of the model, and `ChatRequest.thinking` says what it sent; `onAttempt.thinking` is that level and is absent when nothing was sent.
|
|
306
|
+
|
|
307
|
+
*How the level is sent.* Not every model takes its level as `reasoning_effort`, the OpenAI field. Meta's documentation says of Muse Glimmer, the owner's main model, that it takes its level (`low`, `medium`, `high`, `xhigh`) as an argument of its chat template and that `reasoning_effort` is not implemented by llama.cpp (LlmProxy's `docs/model-profiles.md` says the same: «Do not assume the OpenAI field»); ExecuTorch rejects `reasoning_effort` with a 400. So the model says it: `AiChatModelConfig.reasoningParameter`, the **"Thinking parameter"** of the model in AI Integrations («Parametro del thinking» in Italian), one of `AI_REASONING_PARAMETERS`. `pickAiRuntimeConfig` keeps it only when it is spelled exactly so (`normalizeReasoningParameter`), the safe view shows it, and `AiCandidate` carries it.
|
|
308
|
+
|
|
309
|
+
| `reasoningParameter` | What the body carries for a level |
|
|
310
|
+
|---|---|
|
|
311
|
+
| absent, or `reasoning_effort` | `reasoning_effort: "<level>"`, as it always was: a model that does not say is called with the very requests it always had, byte for byte |
|
|
312
|
+
| `chat_template_kwargs.reasoning_strength` | `chat_template_kwargs: { "reasoning_strength": "<level>" }` and no `reasoning_effort`, in the place where `reasoning_effort` goes. It is merged with any other key that `chat_template_kwargs` already has in the body (`applyReasoningLevel` is the one place where a level lands in a body; the body has no other today) |
|
|
313
|
+
| `none` | Nothing, even when the task or the integration asks for a level. The attempt says so in its `notes`: `The thinking level "high" was not sent: "muse-glimmer-30b" has its thinking parameter set to "none".` (a model that is also declared as not reasoning says this one: it is the author's own word) |
|
|
314
|
+
|
|
315
|
+
The levels, and who sets them (the target, the integration, `automatic`), are the same for the three; `supportsReasoning: false` still sends no level, whatever the parameter. `ChatRequest.reasoningParameter` and `onAttempt.reasoningParameter` say where the level went, **only** when it went as the chat-template argument (absent: it went as `reasoning_effort`, or no level was sent), and `thinking` is the level either way. The gateway has to let the field through: LlmProxy does (it rewrites the `model` of the body and caps the token limits, and forwards the rest to the runtime).
|
|
316
|
+
|
|
317
|
+
*The hint.* `suggestedReasoningParameter(modelName, underlyingModel?)` is a pure hint for the screen that offers the setting, never an order: it gives `chat_template_kwargs.reasoning_strength` for the model names that a documented source ties to the chat-template argument, and `undefined` for every other name. Today that is Muse Glimmer and nothing else (`muse-glimmer`, `muse-glimmer-30B`, `meta-models/Muse-Glimmer-30B-GGUF:Q4_K_M`, `unsloth/Muse-Glimmer-30B-GGUF`, `muse-glimmer:30b-mlx`, `meta-muse-glimmer`: what comes before the last `/`, and a tag after the name, do not matter; Muse Spark and every other family are not guessed, because no source says it). The sources are cited in the comment of the function: Meta's "Run inference" and "Prompting guide" pages for Muse Glimmer, and LlmProxy's `docs/model-profiles.md` with its Muse Glimmer profile. With a declared `underlyingModel` (an Azure deployment) that is the name that is read, as `isReasoningModel` does. The engine never applies the hint by itself: a model is called with `reasoning_effort` until its author sets the parameter.
|
|
318
|
+
|
|
319
|
+
*A provider that does not accept it.* A 400 or a 422 that names `reasoning_effort`, `reasoning_strength` or `chat_template_kwargs`, in its message or in its error object (`"param": "reasoning_effort"`), while a level was sent, is a permanent error that is not repeated and says what to change. Either name is a refusal of the level, whichever of the two was sent (a gateway may answer with the name of the one it translated the level into), and the remedy names the setting of the model and offers the other parameter and `none`: `openai muse-glimmer-30b: the model does not accept a thinking level (HTTP 400 — Unrecognized request argument supplied: reasoning_effort). Nothing was applied. Set "Thinking parameter" of the model "muse-glimmer-30b" in AI Integrations to "chat_template_kwargs.reasoning_strength" (the level as an argument of the chat template, as Muse Glimmer takes it) or to "none" (no level is sent), or set thinking to "Automatic" for this task in the AI Router, or for the integration "LlmProxy" in AI Integrations.` When the level was sent as the chat-template argument, the parameter offered first is `"reasoning_effort"` (the OpenAI field). The next candidate of the route is tried (it may have no level, or another parameter); when the run ends on it, its `errorKind` is `provider` and `errorDetail.status` is 400. With no level sent (nothing chosen, `automatic`, `reasoningParameter: "none"` or `supportsReasoning: false`), on any other status, or for an error that talks about the chat template and not about its arguments, the error is the plain one it was. The engine does not know which models reason unless the configuration says it: with `supportsReasoning: false` on a model the level is not sent to it at all (and the attempt says so in its `notes`: `The thinking level "high" was not sent: "muse-glimmer-30b" is declared as not reasoning (supportsReasoning is off).`), so an integration with models of both kinds can carry a level and spare the ones that would refuse it; a model that declares nothing is sent the level, as before, so give a level to an integration that has only models that take one, or to the route targets that use them.
|
|
320
|
+
|
|
321
|
+
`redactAiRuntimeConfig(config)` shows what is set, none of it secret: the level of every integration (`integrations[].thinking`), the route of every routed task with the level of each target (`taskRouting`: `{ primary?, fallbacks }` for each task, `{}` when there is no route), `toolsOnly` and, for every model, what it declares and how its level is sent (`integrations[].models[]`: see *Declared capabilities of a model*, and `reasoningParameter` above).
|
|
275
322
|
|
|
276
323
|
### Costs and budgets
|
|
277
324
|
|
|
@@ -279,16 +326,140 @@ An integration without its own value says `the default provider timeout` or `the
|
|
|
279
326
|
|
|
280
327
|
### Retries
|
|
281
328
|
|
|
282
|
-
A step that failed with a transient provider error is retried up to three times, after about 4 s, 12 s and 36 s (with jitter, never sooner than the provider's `Retry-After`); the `failureRetry` insight carries `attempt`, `retries` and `waitMs`. A rejected reply, or a failure that is not the provider's, is retried once, the first with the reason. The same failure twice in a row that does not depend on the moment (an empty reply, a 500 with the same message) stops the run at once. A reply cut while the model had only reasoned is retried once with an output limit three times larger (`AiRequest.outputBoost`), and the next steps of that kind start with it. `retryDelayMs` is the base delay: every delay scales with it, `0` makes them instant. A pause ends the wait. While the run waits, `summary.retry` says when the next attempt is (see *What the interface reads*).
|
|
329
|
+
A step that failed with a transient provider error is retried up to three times, after about 4 s, 12 s and 36 s (with jitter, never sooner than the provider's `Retry-After`); the `failureRetry` insight carries `attempt`, `retries` and `waitMs`. A rejected reply, or a failure that is not the provider's, is retried once, the first with the reason. The same failure twice in a row that does not depend on the moment (an empty reply, a 500 with the same message) stops the run at once. A failure that is marked as not retryable is never repeated: the run stops with it (a 401, a call that no model can take because Tools only is on, a 400 that refuses the thinking level). A reply cut while the model had only reasoned is retried once with an output limit three times larger (`AiRequest.outputBoost`), and the next steps of that kind start with it; a model declared as reasoning (`supportsReasoning: true`) whose reply is cut with nothing written counts as one that only reasoned, even when its server does not show the reasoning. `retryDelayMs` is the base delay: every delay scales with it, `0` makes them instant. A pause ends the wait. While the run waits, `summary.retry` says when the next attempt is (see *What the interface reads*).
|
|
283
330
|
|
|
284
331
|
### What the model's replies must be
|
|
285
332
|
|
|
286
|
-
- A forced tool call must carry at least one of the schema's required fields (else one of its declared properties);
|
|
333
|
+
- A forced tool call must carry at least one of the schema's required fields (else one of its declared properties). With *Tools only* on (the default) the text of the reply is never read and a reply with no call is rejected; with it off the JSON in the text is used when the call says nothing useful, and a reply with neither is rejected. A rejected reply is retried once with the reason.
|
|
287
334
|
- `<think>` blocks are dropped, and so is everything up to the last `</think>` of a model that never opened it.
|
|
288
335
|
- What the engine escapes in prompts (`&`, `<`, `>`) is un-escaped in prose and in every text field of a structured reply (`unescapePromptData`).
|
|
289
336
|
- The director decides with a score: the reply must carry `verdict` and `score` (0-10; above 10 and up to 100 is read as a percentage). An `approve` below the `approvalScore` of `director.md` counts as `revise`, with the reason in the record, for the plan, every chapter, the final review and `askDirector`.
|
|
290
337
|
- A simulated reader must answer with a score and its reaction. A reader whose reply is still incomplete after the retry is skipped (and said so): the review goes on with those who answered.
|
|
291
338
|
|
|
339
|
+
## Model catalog and declared capabilities
|
|
340
|
+
|
|
341
|
+
*Why.* The models of an integration, their limits and what they can do used to be typed by hand: a model had a switch for tool calls and two numbers, nothing read an endpoint, and the engine did not know whether a model streams, reasons or reads images. An OpenAI-compatible gateway can say all of it. BookWriter reads `GET /models` and `GET /models/details` when the author presses "Read /models", and LlmProxy (the gateway this was built against: its `docs/api-contract.md`) adds `GET /v1/modalities`. The engine reads the same three, validates what comes back, and keeps what a model declares so that its requests follow it. Everything here is additive: a configuration that says none of it is called exactly as it was.
|
|
342
|
+
|
|
343
|
+
### What is read, and from where
|
|
344
|
+
|
|
345
|
+
| Request | Needed | What it gives |
|
|
346
|
+
|---|---|---|
|
|
347
|
+
| `GET <base>/models` | yes | The OpenAI list, `{ "data": [{ "id": … }] }`. Without it there is no catalog. |
|
|
348
|
+
| `GET <base>/models/details` | no | LlmProxy's: for each model its `type` (`chat`, `embedding`, `image`, `speech`, `transcription`, `realtime` or `classifier`), `context_window` (prompt and answer together), `max_output_tokens`, `input_modalities`, `output_modalities`, `endpoints` and `capabilities: { streaming, tools, vision, reasoning }`. |
|
|
349
|
+
| `GET <base>/modalities` | no | LlmProxy's: everything the gateway offers, grouped by type (always the seven, in its own order, the ones that run nothing included) with the paths, the modalities and the models that run for each. |
|
|
350
|
+
| `GET <origin>/api/v1/models` | no | LM Studio's own list, asked only on this computer (see *LM Studio*). |
|
|
351
|
+
|
|
352
|
+
`<base>` is `effectiveAiBase(integration)`: the very base that the chat requests of the integration use (its endpoint, trailing slashes aside, or OpenAI's own), with the key in the same header; `catalogTarget(integration, path)` works it out and is `null` for an integration with no such list. Only integrations of the provider `openai` (any OpenAI-compatible endpoint) have a list to read. Azure OpenAI (a deployment is made by hand, and nobody lists them), GitHub Models (its catalog is at another address and in another shape, which a host reads as it already does) and Microsoft 365 are an `AiCatalogError` of reason `unsupported`, and nothing is sent.
|
|
353
|
+
|
|
354
|
+
**The contract of LlmProxy, as the engine recognizes it.** An entry of `/models/details`:
|
|
355
|
+
|
|
356
|
+
```json
|
|
357
|
+
{ "id": "muse-glimmer-30b", "object": "model", "type": "chat", "context_window": 131072, "max_output_tokens": 8192,
|
|
358
|
+
"input_modalities": ["text", "image"], "output_modalities": ["text"], "endpoints": ["/v1/chat/completions", "/v1/responses"],
|
|
359
|
+
"capabilities": { "streaming": true, "tools": true, "vision": true, "reasoning": true } }
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
- `null` is "not declared": a number that is not a whole number from `CATALOG_MIN_TOKENS` (256) to `CATALOG_MAX_TOKENS` (10 000 000) is absent in the entry the engine makes, never a `0`.
|
|
363
|
+
- **`false` is not "cannot".** The capabilities of a model are `chat && flag`: everything that the administrator did not declare is sent as `false`. A model that streams well, with its box not ticked, says `streaming: false`.
|
|
364
|
+
- LlmProxy's implementation always sends `type`, but the example in its contract leaves it out: an entry with no `type` (or one the engine does not know) has the type `unknown`.
|
|
365
|
+
- `/models/details` and `/modalities` say the same thing about a model. When both are read, what `/models/details` says wins field by field, what only `/modalities` says is kept, and an id that only they know is added (up to 2000).
|
|
366
|
+
|
|
367
|
+
### The parsers
|
|
368
|
+
|
|
369
|
+
Pure: no I/O, no clock. Everything that comes in is data from a server nobody vouches for: it is bounded, validated field by field, never trusted for what it is called (`__proto__`, `constructor` and `prototype` are never an id) and never quoted in an error. The limits are BookWriter's (`fetchModels`, `tokenLimitsFromDetails`).
|
|
370
|
+
|
|
371
|
+
| Function | Reads | Gives |
|
|
372
|
+
|---|---|---|
|
|
373
|
+
| `parseModelList(payload)` | OpenAI `GET /models` | The ids, sorted and without repeats. **All or nothing**, as in BookWriter, so that a wrong answer never replaces a catalog that was right: a payload that is not a list, an entry without a good id (a string of 1 to `CATALOG_MAX_ID_LENGTH` (256) characters, no space at its edges, no control character), an empty list (`empty`), more than `CATALOG_MAX_MODELS` (2000) entries, or a list that says it goes on (`has_more: true`: a first page is not the catalog, and the engine does not follow pages) (`too-large`) is an `AiCatalogError`. |
|
|
374
|
+
| `parseModelDetails(payload)` | `GET /models/details` | `AiModelCatalogEntry[]`, in the order received: `{ id, type, contextWindow?, maxOutputTokens?, inputModalities?, outputModalities?, capabilities }`. The numbers are there only when they are whole and in range; a capability only when it is a boolean; `type` is one of `AI_MODEL_TYPES` (`chat`, `image`, `speech`, `transcription`, `embedding`, `realtime`, `classifier`; case and spaces do not matter) or `unknown`; the modalities are short lower-case words, at most 16. An entry that cannot be one is left out and the others stay; at most 2000 entries are read. Only a payload that is not a list is an `AiCatalogError`. |
|
|
375
|
+
| `parseModalities(payload)` | `GET /modalities` | `AiModalityGroup[]` in the order received: `{ type, endpoints, inputModalities?, outputModalities?, modelCount, models }`. A model with no type of its own has the type of its group; `modelCount` is the gateway's when it is a count, else the models that were read; `endpoints` are short paths, at most 16; at most 32 groups, and 2000 models in each, are read. A payload that is not a list is an `AiCatalogError`. |
|
|
376
|
+
| `tokenLimitsFromDetails(entry)` | an entry | BookWriter's formula: see *The limits*. |
|
|
377
|
+
| `modelFieldsFromCatalogEntry(entry)` | an entry | What the entry can fill in a model of the configuration: see *The limits* and *Declared capabilities of a model*. |
|
|
378
|
+
| `parseLmStudioModels(payload)`, `lmStudioContext(models, id)` | LM Studio | See *LM Studio*. |
|
|
379
|
+
|
|
380
|
+
### Reading an integration
|
|
381
|
+
|
|
382
|
+
`fetchModelCatalog(integration, { fetch?, signal?, timeoutMs? })` gives an `AiModelCatalog`:
|
|
383
|
+
|
|
384
|
+
```ts
|
|
385
|
+
{ models: AiModelCatalogEntry[]; // every model, of every kind, sorted by id
|
|
386
|
+
source: { models: true; details: boolean; modalities: boolean }; // which answers were read
|
|
387
|
+
modalities?: AiModalityGroup[] } // what the gateway offers by kind, when /modalities was read
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
- It asks `GET /models` first (needed), then, together, `/models/details` and `/modalities`. **Every failure of those two is silent**: the catalog is then what `/models` says, an id that only `/models` lists has `type: "unknown"` and says nothing of what it can do, and `source` says which answers were read.
|
|
391
|
+
- **The models of every kind come back, each with its `type`**, so that one call fills the models and the tables of the other tools (images, speech, transcription, embeddings). Without `/models/details` and `/modalities` the list has no kinds and every model is `unknown`: a screen that wants chat models then takes them all, as BookWriter does.
|
|
392
|
+
- A request is a plain GET: `accept` and the header of the key, nothing else, `credentials: "omit"`, `redirect: "error"` (a redirect is refused, not followed: the endpoint it points to is never asked), `cache: "no-store"`, `referrerPolicy: "no-referrer"`. The key is in no message and in no result.
|
|
393
|
+
- *Time.* An endpoint may be silent for `CATALOG_TIMEOUT_MS` (8 s) per request, before it answers and between two pieces of its answer (the silence is what is watched, not the total), and no request lasts more than `CATALOG_TOTAL_CAP_MS` (a minute), so an endpoint that trickles for ever is stopped all the same. `timeoutMs` is the host's choice of the silence, at most ten minutes (the cap is then that long, when it is longer than a minute). No timer outlives a call.
|
|
394
|
+
- *The body* is read in pieces, up to `CATALOG_MAX_BYTES` (600 KB): a type that is not JSON, a length that is not a number or is over the limit is refused before a byte is read; a body that grows past the limit, whatever its length said, is cut where it passes it; the reader is let go however the read ends.
|
|
395
|
+
- A cancelled `signal` is an `AbortError`, never a catalog (a call cancelled before it began sends nothing).
|
|
396
|
+
|
|
397
|
+
**Errors.** A failure of `/models` is an `AiCatalogError` (an `Error` with `name: "AiCatalogError"`, a `reason` and, when an HTTP status gave it, `status`). Its message is in English, names the integration, says why and what to do, and never quotes what the endpoint sent, the address or the key:
|
|
398
|
+
|
|
399
|
+
| `reason` | When | The message says |
|
|
400
|
+
|---|---|---|
|
|
401
|
+
| `unreachable` | No answer: the server is off, the address is wrong, a redirect was refused, the connection dropped (in a browser also CORS, which it cannot tell apart) | check that it runs, the address, the redirect, and CORS |
|
|
402
|
+
| `timeout` | It did not answer, or went silent, within the time; or the whole took longer than the cap | try again |
|
|
403
|
+
| `unauthorized` | 401, 403 | check the key |
|
|
404
|
+
| `not-found` | 404 | the address should end with the version path (`/v1`) |
|
|
405
|
+
| `rate-limited` | 429 | wait and try again |
|
|
406
|
+
| `server-error` | 5xx | it may be busy or restarting: try again |
|
|
407
|
+
| `http-error` | Any other status | check the address and the key |
|
|
408
|
+
| `invalid` | Not JSON, or not a list of models | the address may not be the API base |
|
|
409
|
+
| `empty` | A list with no model | start a model there (a gateway does not list one that is stopped) |
|
|
410
|
+
| `too-large` | More than 2000 models, a list that comes in pages (`has_more: true`), or more than 600 KB | enter the model names by hand |
|
|
411
|
+
| `unsupported` | Azure OpenAI, GitHub Models, Microsoft 365 | there is no list to read |
|
|
412
|
+
|
|
413
|
+
Every message that can be answered by typing says it: *enter the model names by hand*, which is what a host did before and still does.
|
|
414
|
+
|
|
415
|
+
**Providers whose `/models` is not OpenAI's.** Only the OpenAI shape, `{ "data": [{ "id": … }] }`, is read, and a list that comes in pages is refused: nothing here follows pages, and a first page must never pass for the catalog. Checked against the providers' documentation: Anthropic's `GET /v1/models` is `{ "data": [{ "id": …, … }], "has_more": … }` with 20 models to a page (its entries have an `id`, so without the refusal its first page would have been read as everything: it is `too-large`); Together AI answers a bare array; Cohere `{ "models": [{ "name": … }], "next_page_token": … }`; and Ollama's own list (`/api/tags`) is `{ "models": [{ "name": … }] }` (its OpenAI-compatible `/v1/models` is the OpenAI shape and is read). The bare array, `models` and `name` are `invalid`: never a half catalog, and the author enters the names by hand. The limits that a provider declares under other names (Anthropic's `max_input_tokens` and `max_tokens`, OpenRouter's `context_length`) are not read: only LlmProxy's `context_window` and `max_output_tokens` are.
|
|
416
|
+
|
|
417
|
+
### The limits
|
|
418
|
+
|
|
419
|
+
`tokenLimitsFromDetails(entry)` is BookWriter's formula, `{ inputTokens?, outputTokens? }`: **input** is the window minus the answer the model declares, or, when it declares none, minus a quarter of the window up to 4096; an answer with no window is only the answer; an answer that is not smaller than its window is not believed; an input that is not a usable number of tokens (it would be under 256) is not said. A window of 131072 and an answer of 8192 give `{ inputTokens: 122880, outputTokens: 8192 }`; with no answer, an input of 126976.
|
|
420
|
+
|
|
421
|
+
**Mind the difference.** BookWriter's `inputTokens` is what is left for the prompt once the answer is taken off. The engine's `maxInputTokens` is the context window itself (the field is labelled "Context window tokens"), and the engine takes off the answer and a 5% margin itself when it judges a prompt (`resolveModelTokenBudgets`): BookWriter's number put there would take the answer off twice. So `modelFieldsFromCatalogEntry(entry)` is what a host uses to fill a model: `maxInputTokens` is the declared window, `maxOutputTokens` is the declared answer (only when it is smaller than the window) and each capability is there only when it is `true`. `tokenLimitsFromDetails` is for a host that keeps BookWriter's numbers.
|
|
422
|
+
|
|
423
|
+
### Declared capabilities of a model
|
|
424
|
+
|
|
425
|
+
`AiChatModelConfig` has, besides `supportsToolCalls`, `maxInputTokens` and `maxOutputTokens`, three optional booleans: `supportsStreaming`, `supportsReasoning` and `supportsVision`. **Absent is as before**: a candidate that does not say is built into exactly the request it always was. `pickAiRuntimeConfig` keeps them only as booleans (anything else is dropped, so what is stored is picked again unchanged), `AiCandidate` carries them, and a personal server stores them and shows them (`PUT /ai` runs `pickAiRuntimeConfig`; `GET /ai` is the safe view) without any change to the protocol.
|
|
426
|
+
|
|
427
|
+
| Field | What it does |
|
|
428
|
+
|---|---|
|
|
429
|
+
| `supportsToolCalls` | Unchanged: with *Tools only* on, `false` skips the model for a structured request. Anything else is asked as before. |
|
|
430
|
+
| `supportsStreaming` | `false`: the model is called without `stream` and `stream_options` (and with `accept: application/json`), for prose and for a structured request alike (the function is forced all the same), whatever the `streamMode` of the integration says, and the attempt's `notes` say `Streaming was not used: "muse-glimmer-30b" is declared as not streaming (supportsStreaming is off).` It never turns on what `streamMode: "off"` turned off (and then there is no note: the integration already said it). |
|
|
431
|
+
| `supportsReasoning` | `true`: the model gets the output margin of a model that reasons (+12 000, never above its `maxOutputTokens`); a reply cut by the output limit with nothing written is a reply cut while reasoning (`reasoningOnly`: `…the model, which is declared as reasoning, used its output limit before writing the reply (its reasoning counts in the limit)`), which the autopilot retries once with a limit three times larger even when the server does not show its reasoning; and a thinking level may be sent (in the parameter of the model: see *Thinking*). `false`: a thinking level is **not** sent, and the attempt says so (see *Thinking*): a provider is never given a request that it would refuse. A model known to reason by its name keeps its margin whatever `false` says. The temperature and the name of the limit parameter (`max_tokens` or `max_completion_tokens`) do not change either: they follow the family of the model, not whether it reasons, because a local model that reasons takes both. |
|
|
432
|
+
| `supportsVision` | Nothing in a request depends on it: it is data for the interface (the engine sends no image). |
|
|
433
|
+
| `maxInputTokens`, `maxOutputTokens` | As before: the window decides whether a prompt fits (a candidate that cannot hold it is skipped) and no request asks for more than the largest answer. |
|
|
434
|
+
|
|
435
|
+
**Mind the window.** The margin of `supportsReasoning: true` comes out of the context window: the budget of a prompt is the window, minus the output limit of the request (the margin included), minus 5%. A model declared as reasoning with a window of 8192 and no declared answer, asked by a step for 2500 tokens, is asked for 14 500: the budget of the prompt is one token and the model is skipped (`AiPromptTooLargeError`, whose advice is about the window, not about the margin). With a window of 32 768 and a step that asks for 9000, the budget falls from 22 129 to 10 129 tokens; from 65 536 up there is room. Declare the largest answer of the model (`maxOutputTokens`: a catalog fills it in when the gateway declares it): no request asks for more, and the budget is computed with it (a window of 131 072 and an answer of 8192 leave 116 326 tokens for the prompt, margin or not). The same arithmetic has always applied to a model known to reason by its name.
|
|
436
|
+
|
|
437
|
+
`redactAiRuntimeConfig` shows `integrations[].models[]` as `RedactedAiModel`: `{ name, capabilities }` and, only for what the model declares, the six fields above (and its `reasoningParameter`, when it sets one: not a thing a catalog declares, but the author's word on how its level is sent, see *Thinking*).
|
|
438
|
+
|
|
439
|
+
**`false` is not a restriction.** LlmProxy says `false` for everything that nobody declared, so a catalog cannot tell a model that does not stream from one whose administrator did not tick the box. Importing `false` as `supportsStreaming: false` would turn streaming off for a model that works, and as `supportsToolCalls: false` it would take the model off every structured task: **`modelFieldsFromCatalogEntry` never turns `false` into a restriction, it only says `true`**, and a host that merges a catalog does `{ ...model, ...modelFieldsFromCatalogEntry(entry) }`: what the gateway declares wins for the fields it declares (as BookWriter's explicit "Read /models" does), and what it leaves out stays as the author wrote it. A `false` that the author sets by hand is respected. (This is also why the engine, unlike BookWriter, asks a model for a function unless it is marked `supportsToolCalls: false`: see *Tools only*.)
|
|
440
|
+
|
|
441
|
+
### The connection probe
|
|
442
|
+
|
|
443
|
+
`probeEndpoint(integration, { fetch?, signal?, timeoutMs? })` asks an OpenAI-compatible endpoint one short question, `GET <base>/models` (the same request as the first of the catalog, with the key, so that a gateway that refuses it is told from one that is off), and waits `PROBE_TIMEOUT_MS` (4 s, as BookWriter's `localEndpointTimeoutHint` does). It is the base of a "Check the connection" in an error panel (a failure of kind `network` or `timeout`: see *What the interface reads*). The result, `AiEndpointProbe`:
|
|
444
|
+
|
|
445
|
+
| `outcome` | When | The rest |
|
|
446
|
+
|---|---|---|
|
|
447
|
+
| `ok` | A 2xx arrived | `httpStatus`, `latencyMs` (until the answer began), `cors: "ok"` and, when the body is a list of models that could be read in time (up to 256 KB), `models`. A gateway with nothing running answers `models: 0` and the message says to start one. A 2xx that is not a list of models is `ok` all the same, without `models`, and the message says that the address may not be the API base (a web page, say). |
|
|
448
|
+
| `http-error` | Any other status: the server is reachable, and the status says what to fix | `httpStatus`, `latencyMs`, `cors: "ok"`; 401 and 403 say to check the key, 404 the version path (`/v1`), 429 to wait, 5xx that it may be busy or restarting. The body of an error is never read. |
|
|
449
|
+
| `unreachable` | No answer within the time, or the connection failed | `latencyMs`, `cors: "blocked-or-unreachable"`. **In a browser a request that CORS blocked looks exactly like a server that is off, an address that is wrong or a connection that failed**, and the message says so, and what to check. |
|
|
450
|
+
|
|
451
|
+
`message` is in English, with the remedy, and never has the key, the address or a word of what the endpoint sent. The probe throws only for a cancel (`AbortError`) and for an integration with no list to ask (`AiCatalogError`, reason `unsupported`): what the endpoint does is a result, never an exception.
|
|
452
|
+
|
|
453
|
+
### LM Studio
|
|
454
|
+
|
|
455
|
+
`parseLmStudioModels(payload)` reads LM Studio's own `GET /api/v1/models` as BookWriter's `lmstudio-models.ts` does: only the entries of `type: "llm"` (at most `LMSTUDIO_MAX_MODELS`, 500, with keys of at most `LMSTUDIO_MAX_KEY_LENGTH`, 200, characters), each as `{ key, reasoning?, maxContext?, loaded }`. `reasoning` is `{ options, default? }`, the levels the model allows in the engine's order (only `low`, `medium`, `high` and `xhigh` are levels: `off` and `on` are not) and the default when it is one of them; `null` when the server says the model has no level to choose; absent when it says nothing of reasoning. `maxContext` is the longest context the model supports and `loaded` the instances that are loaded now, with the context each was loaded with (at most 16). `lmStudioContext(models, modelId)` finds a model by its key or by the id of a loaded instance, as BookWriter does, and gives `{ loaded?, max? }`.
|
|
456
|
+
|
|
457
|
+
`fetchLmStudioModels(integration, options)` asks for that list at the root of the server (`<origin>/api/v1/models`, whatever path the endpoint has), **only of a server on this computer** (`localhost`, `127.0.0.1` or `[::1]`, with no credentials in its address) and only for an OpenAI-compatible integration; a key that is configured is sent, to this computer only. Anything else, and any failure (a server that is not LM Studio, one that cannot be reached, an answer that is not its list), gives `undefined`: this list is an extra, and the caller keeps what it knew. It throws only for a cancel.
|
|
458
|
+
|
|
459
|
+
### What stays with the host
|
|
460
|
+
|
|
461
|
+
The engine reads and says; it never reads a catalog by itself during a run and never saves one. The host decides when (an explicit "Read models" is what BookWriter does, and every failure there leaves the author typing), which models of the catalog become models of the configuration (the `chat` ones, and the `unknown` ones when neither `source.details` nor `source.modalities` was read), and keeps what the author typed for every field that the gateway leaves out. A host that runs these functions on a server must give them a `fetch` that applies its own policy for the endpoints that a key may be sent to: the functions do not decide that (`effectiveAiBase` is what to compare).
|
|
462
|
+
|
|
292
463
|
## Sync
|
|
293
464
|
|
|
294
465
|
`syncBookStores({ local, remote, base })` is a three-way sync of two `BookStore`s (the browser's working copy and the personal server's): it copies what changed on one side, reports what changed on both (`conflicts`, settled by `resolveConflict`) and returns the `base` to remember for the next one. It reads from a store that has `readMany` a batch of paths at a time, and commits in chunks of at most 400 changes and 24 MiB, so a book of any size passes the limits of one request.
|
|
@@ -310,6 +481,7 @@ A skipped file is not recorded as synced (a file that was never synced stays out
|
|
|
310
481
|
- **Version compatibility.** `serverCompatibility(info)` tells whether the server speaks an API this engine supports (`MIN_SUPPORTED_SERVER_API` to `MAX_SUPPORTED_SERVER_API`, both 1 today): `{ status: "ok" | "server-older" | "server-newer", message }`. A server that does not say which API it speaks is an older one. It never throws; `verifyServerIdentity` returns it as `compatibility`, and so does `client.verifiedInfo()` in `identity`, so the host decides how to show it (update the server, or update the app).
|
|
311
482
|
- **Pairing.** `pairWithServer(options)` still answers the token. `pairWithServerDetailed(options)` answers `{ token, verification?, requestVerification?, compatibility? }`, and `onWaitingApproval({ verification?, compatibility? })` is called while the owner approves. The verification is four digits the server derives (see the server README): while the request waits, the admin panel shows the same four digits next to it (`requestVerification`, which `onWaitingApproval` receives as `verification`), so the owner can tell this device's request from another one; once approved, the panel shows the digits of the token next to the client (`verification` of the result). `onPaired(pairing)` hands over the same details to a host that keeps calling `pairWithServer`. An older server that sends none is fine; a value that is not four digits is ignored.
|
|
312
483
|
- **Signing out.** `client.signOut()` revokes the token the client holds (`DELETE /api/v1/session`) and no other: `{ revoked: true }`, or `{ revoked: false }` when the token was already revoked. A server that cannot be reached is an error, because the token may still be valid there (`forgetSession()` is the older call and reports a revoked token as an error).
|
|
484
|
+
- **The AI status.** `client.aiStatus()` (`GET /api/v1/ai`) answers `ServerAiStatus`: `configured`, the `integrations` without their keys (an integration that sets a thinking level says it), `routedTasks`, `updatedAt` and, while the owner has to approve an endpoint, `pendingApproval`. A server that passes `redactAiRuntimeConfig` on may also say `toolsOnly` (whether Tools only is in force) and `taskRouting` (the route of every routed task, with the thinking level of each target): both are optional, and a client of an older server gets neither (a missing `toolsOnly` is *unknown*, not *on*). `putAiConfig(config)` (`PUT /api/v1/ai`) sends what `pickAiRuntimeConfig` reads, so `toolsOnly` and the `thinking` of the integrations and of the route targets travel with the rest, and a server that runs the same engine keeps them (it picks the configuration when it saves it and when it reads it back).
|
|
313
485
|
- **Quick controls.** Pause at the end of the chapter, the limits of one run and the settings that can change during a run (see *Quick controls* above) go through three calls. A server that implements them announces `SERVER_FEATURE_AUTOPILOT_CONTROLS` (`"autopilot-controls"`) in the `features` of `GET /api/v1/info`, and `serverSupportsAutopilotControls(info)` reads it (never throws; an older server, or an odd answer, says no). Ask before sending what an older server would read as something else: it ignores `limits` (the run would not stop after the step or the chapter that was asked for, and goes on spending) and takes every pause mode but `now` for `after-step` (a `cancel` would pause). The calls need the `run` permission, like the other commands that steer a run, answer the snapshot (`AutopilotSnapshot`, with the server session's `summary`: `pausePending`, `limits`, `publish`), and fail as `{ "code", "message" }` with the status below, which `ServerRequestError` carries as `status` and `code`. Every one also answers 401 `unauthorized`, 403 `scope` (no `run` permission) and 404 `book_not_found`.
|
|
314
486
|
|
|
315
487
|
| Client method | Request | Answer |
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { DeadlineClock } from "./deadlines.js";
|
|
2
|
+
/** Stops reading without waiting for the other side: whatever it does with the cancel, the call must not hang on it. */
|
|
3
|
+
export declare function release(reader: ReadableStreamDefaultReader<Uint8Array>): void;
|
|
4
|
+
/** Lets a body go that nobody is going to read (an error, a reply that arrived too late, or one that the call gave up). */
|
|
5
|
+
export declare function discardBody(response: Response): void;
|
|
6
|
+
/** Why a body could not be read as JSON: it is not (`invalid`), it is bigger than it may be (`too-large`), or the connection broke while it was read (`lost`). */
|
|
7
|
+
export type BodyFault = "invalid" | "too-large" | "lost";
|
|
8
|
+
/** A body that cannot be used. It says only why, never what the body held. */
|
|
9
|
+
export declare class BodyError extends Error {
|
|
10
|
+
readonly fault: BodyFault;
|
|
11
|
+
constructor(fault: BodyFault);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Reads a body that has to be one small JSON value, from an endpoint nobody vouches for. A type that says it is not JSON, a length that is not a number
|
|
15
|
+
* or is over `maxBytes` is refused before a byte is read (the body is let go); a body that grows past `maxBytes` whatever its length said is cut where
|
|
16
|
+
* it passes the limit; every piece restarts the silence the clock watches, and the reader is let go however the read ends but by the end of the body.
|
|
17
|
+
* A deadline or the author's cancel is the clock's (it rejects at once, whatever the read does); anything else that goes wrong is a `BodyError`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function readBoundedJson(response: Response, clock: DeadlineClock, maxBytes: number): Promise<unknown>;
|
|
20
|
+
//# sourceMappingURL=body.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"body.d.ts","sourceRoot":"","sources":["../../src/ai/body.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAIpD,wHAAwH;AACxH,wBAAgB,OAAO,CAAC,MAAM,EAAE,2BAA2B,CAAC,UAAU,CAAC,GAAG,IAAI,CAM7E;AAED,2HAA2H;AAC3H,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAMpD;AAED,kKAAkK;AAClK,MAAM,MAAM,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,MAAM,CAAC;AAEzD,8EAA8E;AAC9E,qBAAa,SAAU,SAAQ,KAAK;IACtB,QAAQ,CAAC,KAAK,EAAE,SAAS;gBAAhB,KAAK,EAAE,SAAS;CAItC;AAID;;;;;GAKG;AACH,wBAAsB,eAAe,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAkElH"}
|
package/dist/ai/body.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// What reading a body from an endpoint needs, whoever reads it: the chat client, the model catalog and the probe. Internal: not exported by the package.
|
|
2
|
+
/** Stops reading without waiting for the other side: whatever it does with the cancel, the call must not hang on it. */
|
|
3
|
+
export function release(reader) {
|
|
4
|
+
try {
|
|
5
|
+
void reader.cancel().catch(() => undefined);
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
// A reader that cannot be cancelled is of no use any more.
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** Lets a body go that nobody is going to read (an error, a reply that arrived too late, or one that the call gave up). */
|
|
12
|
+
export function discardBody(response) {
|
|
13
|
+
try {
|
|
14
|
+
void response.body?.cancel().catch(() => undefined);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// A body that is locked or already read has nothing left to discard.
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** A body that cannot be used. It says only why, never what the body held. */
|
|
21
|
+
export class BodyError extends Error {
|
|
22
|
+
fault;
|
|
23
|
+
constructor(fault) {
|
|
24
|
+
super(`The body could not be read (${fault}).`);
|
|
25
|
+
this.fault = fault;
|
|
26
|
+
this.name = "BodyError";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const JSON_TYPE = /\/json(?:\s*;|$)|\+json(?:\s*;|$)/i;
|
|
30
|
+
/**
|
|
31
|
+
* Reads a body that has to be one small JSON value, from an endpoint nobody vouches for. A type that says it is not JSON, a length that is not a number
|
|
32
|
+
* or is over `maxBytes` is refused before a byte is read (the body is let go); a body that grows past `maxBytes` whatever its length said is cut where
|
|
33
|
+
* it passes the limit; every piece restarts the silence the clock watches, and the reader is let go however the read ends but by the end of the body.
|
|
34
|
+
* A deadline or the author's cancel is the clock's (it rejects at once, whatever the read does); anything else that goes wrong is a `BodyError`.
|
|
35
|
+
*/
|
|
36
|
+
export async function readBoundedJson(response, clock, maxBytes) {
|
|
37
|
+
const type = response.headers?.get?.("content-type") ?? "";
|
|
38
|
+
if (type && !JSON_TYPE.test(type)) {
|
|
39
|
+
discardBody(response);
|
|
40
|
+
throw new BodyError("invalid");
|
|
41
|
+
}
|
|
42
|
+
const length = response.headers?.get?.("content-length") ?? null;
|
|
43
|
+
if (length !== null) {
|
|
44
|
+
if (!/^\d+$/.test(length.trim())) {
|
|
45
|
+
discardBody(response);
|
|
46
|
+
throw new BodyError("invalid");
|
|
47
|
+
}
|
|
48
|
+
if (Number(length) > maxBytes) {
|
|
49
|
+
discardBody(response);
|
|
50
|
+
throw new BodyError("too-large");
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
let reader;
|
|
54
|
+
try {
|
|
55
|
+
reader = response.body?.getReader();
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
discardBody(response);
|
|
59
|
+
throw new BodyError("invalid");
|
|
60
|
+
}
|
|
61
|
+
if (!reader)
|
|
62
|
+
throw new BodyError("invalid");
|
|
63
|
+
let exhausted = false;
|
|
64
|
+
try {
|
|
65
|
+
const chunks = [];
|
|
66
|
+
let size = 0;
|
|
67
|
+
for (;;) {
|
|
68
|
+
let piece;
|
|
69
|
+
try {
|
|
70
|
+
piece = await clock.guard(reader.read());
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
// A deadline or the author's cancel is told by the clock; anything else here is the connection.
|
|
74
|
+
if (clock.interrupted())
|
|
75
|
+
throw error;
|
|
76
|
+
throw new BodyError("lost");
|
|
77
|
+
}
|
|
78
|
+
if (piece.done) {
|
|
79
|
+
exhausted = true;
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
clock.activity();
|
|
83
|
+
size += piece.value.byteLength;
|
|
84
|
+
if (size > maxBytes)
|
|
85
|
+
throw new BodyError("too-large");
|
|
86
|
+
chunks.push(piece.value);
|
|
87
|
+
}
|
|
88
|
+
const bytes = new Uint8Array(size);
|
|
89
|
+
let offset = 0;
|
|
90
|
+
for (const chunk of chunks) {
|
|
91
|
+
bytes.set(chunk, offset);
|
|
92
|
+
offset += chunk.byteLength;
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw new BodyError("invalid");
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
if (!exhausted)
|
|
103
|
+
release(reader);
|
|
104
|
+
try {
|
|
105
|
+
reader.releaseLock();
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
// A read that is still pending cannot be released: the cancel above is what lets it go.
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
//# sourceMappingURL=body.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"body.js","sourceRoot":"","sources":["../../src/ai/body.ts"],"names":[],"mappings":"AAEA,yJAAyJ;AAEzJ,wHAAwH;AACxH,MAAM,UAAU,OAAO,CAAC,MAA+C;IACrE,IAAI,CAAC;QACH,KAAK,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC9C,CAAC;IAAC,MAAM,CAAC;QACP,2DAA2D;IAC7D,CAAC;AACH,CAAC;AAED,2HAA2H;AAC3H,MAAM,UAAU,WAAW,CAAC,QAAkB;IAC5C,IAAI,CAAC;QACH,KAAK,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IACtD,CAAC;IAAC,MAAM,CAAC;QACP,qEAAqE;IACvE,CAAC;AACH,CAAC;AAKD,8EAA8E;AAC9E,MAAM,OAAO,SAAU,SAAQ,KAAK;IACb;IAArB,YAAqB,KAAgB;QACnC,KAAK,CAAC,+BAA+B,KAAK,IAAI,CAAC,CAAC;QAD7B,UAAK,GAAL,KAAK,CAAW;QAEnC,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;IAC1B,CAAC;CACF;AAED,MAAM,SAAS,GAAG,oCAAoC,CAAC;AAEvD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,QAAkB,EAAE,KAAoB,EAAE,QAAgB;IAC9F,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC;IAC3D,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAClC,WAAW,CAAC,QAAQ,CAAC,CAAC;QACtB,MAAM,IAAI,SAAS,CAAC,SAAS,CAAC,CAAC;IACjC,CAAC;IACD,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,IAAI,IAAI,CAAC;IACjE,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QACpB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YACjC,WAAW,CAAC,QAAQ,CAAC,CAAC;YACtB,MAAM,IAAI,SAAS,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QACD,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,EAAE,CAAC;YAC9B,WAAW,CAAC,QAAQ,CAAC,CAAC;YACtB,MAAM,IAAI,SAAS,CAAC,WAAW,CAAC,CAAC;QACnC,CAAC;IACH,CAAC;IACD,IAAI,MAA2D,CAAC;IAChE,IAAI,CAAC;QACH,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC;IACtC,CAAC;IAAC,MAAM,CAAC;QACP,WAAW,CAAC,QAAQ,CAAC,CAAC;QACtB,MAAM,IAAI,SAAS,CAAC,SAAS,CAAC,CAAC;IACjC,CAAC;IACD,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,SAAS,CAAC,SAAS,CAAC,CAAC;IAC5C,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,CAAC;QACH,MAAM,MAAM,GAAiB,EAAE,CAAC;QAChC,IAAI,IAAI,GAAG,CAAC,CAAC;QACb,SAAS,CAAC;YACR,IAAI,KAA2C,CAAC;YAChD,IAAI,CAAC;gBACH,KAAK,GAAG,MAAM,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;YAC3C,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,gGAAgG;gBAChG,IAAI,KAAK,CAAC,WAAW,EAAE;oBAAE,MAAM,KAAK,CAAC;gBACrC,MAAM,IAAI,SAAS,CAAC,MAAM,CAAC,CAAC;YAC9B,CAAC;YACD,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC;gBACf,SAAS,GAAG,IAAI,CAAC;gBACjB,MAAM;YACR,CAAC;YACD,KAAK,CAAC,QAAQ,EAAE,CAAC;YACjB,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,UAAU,CAAC;YAC/B,IAAI,IAAI,GAAG,QAAQ;gBAAE,MAAM,IAAI,SAAS,CAAC,WAAW,CAAC,CAAC;YACtD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC3B,CAAC;QACD,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,MAAM,GAAG,CAAC,CAAC;QACf,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YAC3B,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,UAAU,CAAC;QAC7B,CAAC;QACD,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAY,CAAC;QACxF,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,SAAS,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;YAAS,CAAC;QACT,IAAI,CAAC,SAAS;YAAE,OAAO,CAAC,MAAM,CAAC,CAAC;QAChC,IAAI,CAAC;YACH,MAAM,CAAC,WAAW,EAAE,CAAC;QACvB,CAAC;QAAC,MAAM,CAAC;YACP,wFAAwF;QAC1F,CAAC;IACH,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type AiLmStudioModel, type AiModalityGroup, type AiModelCatalogEntry } from "./catalog.js";
|
|
2
|
+
import type { AiIntegrationConfig } from "./config.js";
|
|
3
|
+
/** The most bytes of an answer that are read. A longer one is refused as it passes the limit, whatever it said it weighed. */
|
|
4
|
+
export declare const CATALOG_MAX_BYTES = 600000;
|
|
5
|
+
/** How long an endpoint may be silent, for each request: before it answers, and between two pieces of its answer. */
|
|
6
|
+
export declare const CATALOG_TIMEOUT_MS = 8000;
|
|
7
|
+
/** The most a request may take in all, however the endpoint goes on sending: a safety, far above what a catalog needs. */
|
|
8
|
+
export declare const CATALOG_TOTAL_CAP_MS = 60000;
|
|
9
|
+
export interface FetchModelCatalogOptions {
|
|
10
|
+
/** The `fetch` to use (default the global one). Never given a cookie, and told not to follow a redirect. */
|
|
11
|
+
fetch?: typeof fetch;
|
|
12
|
+
/** Cancels the reading: an `AbortError`, never a catalog. */
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
/** How long an endpoint may be silent, per request (default `CATALOG_TIMEOUT_MS`, at most ten minutes). The most a request may take in all is a minute, or this when it is longer. */
|
|
15
|
+
timeoutMs?: number;
|
|
16
|
+
}
|
|
17
|
+
/** What an integration's endpoint says of its models, from its list and from its companions. */
|
|
18
|
+
export interface AiModelCatalog {
|
|
19
|
+
/** Every model the endpoint knows, sorted by id: the ids of `/models`, enriched with what `/models/details` and `/modalities` say, and the ids that only they know. Of every kind, with its `type`. */
|
|
20
|
+
models: AiModelCatalogEntry[];
|
|
21
|
+
/** Which of the answers were read: the list always (without it there is no catalog), the companions when the endpoint has them and they were as they should be. */
|
|
22
|
+
source: {
|
|
23
|
+
models: true;
|
|
24
|
+
details: boolean;
|
|
25
|
+
modalities: boolean;
|
|
26
|
+
};
|
|
27
|
+
/** What the gateway offers by kind of model, with the kinds that run nothing; absent when `/modalities` was not read. */
|
|
28
|
+
modalities?: AiModalityGroup[];
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Reads the models an integration's endpoint offers, as BookWriter does and as LlmProxy exposes them: `GET <base>/models` (the OpenAI list: without
|
|
32
|
+
* it there is no catalog, and a failure is an `AiCatalogError` that says why and what to do), then, together, `GET <base>/models/details` (the window,
|
|
33
|
+
* the largest answer and what each model can do) and `GET <base>/modalities` (what the gateway offers, by kind of model, and what runs for each), which
|
|
34
|
+
* an endpoint may not have and whose every failure is silent: the catalog is then what the list says. The base is the one the chat requests use.
|
|
35
|
+
* The models of every kind are returned, with their `type`, so that a screen can fill the tables of the tools that are not chat. Only OpenAI-compatible
|
|
36
|
+
* integrations have such a list: any other is an `AiCatalogError` of reason `unsupported`, and nothing is sent.
|
|
37
|
+
*
|
|
38
|
+
* What an endpoint sends is untrusted: a request is a plain GET with no cookie and no redirect, with the key in its header only; an endpoint may be
|
|
39
|
+
* silent for 8 s (before it answers, and between two pieces), a minute in all; a body is read in pieces up to 600 KB, and let go the moment it is too
|
|
40
|
+
* much, or not JSON; and nothing it says is quoted in an error. The key is in no message and no result. A cancelled reading is an `AbortError`.
|
|
41
|
+
*/
|
|
42
|
+
export declare function fetchModelCatalog(integration: AiIntegrationConfig, options?: FetchModelCatalogOptions): Promise<AiModelCatalog>;
|
|
43
|
+
/**
|
|
44
|
+
* The native list of an LM Studio on this computer (`GET /api/v1/models` at the root of its server): the thinking levels each language model declares
|
|
45
|
+
* and the context it loaded and supports, for `parseLmStudioModels`. Only a server that runs on this machine is asked (`localhost`, `127.0.0.1`, `::1`,
|
|
46
|
+
* with no credentials in its address), and only an OpenAI-compatible integration is read: for any other, and for any server that is not LM Studio,
|
|
47
|
+
* cannot be reached, or answers what is not its list, the answer is `undefined`, and the caller keeps what it knew. A key that is configured is sent, to this
|
|
48
|
+
* computer only. A cancelled reading is an `AbortError`.
|
|
49
|
+
*/
|
|
50
|
+
export declare function fetchLmStudioModels(integration: AiIntegrationConfig, options?: FetchModelCatalogOptions): Promise<AiLmStudioModel[] | undefined>;
|
|
51
|
+
//# sourceMappingURL=catalog-fetch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"catalog-fetch.d.ts","sourceRoot":"","sources":["../../src/ai/catalog-fetch.ts"],"names":[],"mappings":"AACA,OAAO,EAQL,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,mBAAmB,EACzB,MAAM,cAAc,CAAC;AAEtB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAMvD,8HAA8H;AAC9H,eAAO,MAAM,iBAAiB,SAAU,CAAC;AACzC,qHAAqH;AACrH,eAAO,MAAM,kBAAkB,OAAQ,CAAC;AACxC,0HAA0H;AAC1H,eAAO,MAAM,oBAAoB,QAAS,CAAC;AAE3C,MAAM,WAAW,wBAAwB;IACvC,4GAA4G;IAC5G,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,6DAA6D;IAC7D,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,sLAAsL;IACtL,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,gGAAgG;AAChG,MAAM,WAAW,cAAc;IAC7B,uMAAuM;IACvM,MAAM,EAAE,mBAAmB,EAAE,CAAC;IAC9B,mKAAmK;IACnK,MAAM,EAAE;QAAE,MAAM,EAAE,IAAI,CAAC;QAAC,OAAO,EAAE,OAAO,CAAC;QAAC,UAAU,EAAE,OAAO,CAAA;KAAE,CAAC;IAChE,yHAAyH;IACzH,UAAU,CAAC,EAAE,eAAe,EAAE,CAAC;CAChC;AAyKD;;;;;;;;;;;GAWG;AACH,wBAAsB,iBAAiB,CAAC,WAAW,EAAE,mBAAmB,EAAE,OAAO,GAAE,wBAA6B,GAAG,OAAO,CAAC,cAAc,CAAC,CA+BzI;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CAAC,WAAW,EAAE,mBAAmB,EAAE,OAAO,GAAE,wBAA6B,GAAG,OAAO,CAAC,eAAe,EAAE,GAAG,SAAS,CAAC,CAkB1J"}
|