narrarium-engine 0.1.3 → 0.1.5
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 +163 -10
- package/dist/ai/budget.d.ts +26 -0
- package/dist/ai/budget.d.ts.map +1 -0
- package/dist/ai/budget.js +35 -0
- package/dist/ai/budget.js.map +1 -0
- package/dist/ai/config.d.ts +26 -0
- package/dist/ai/config.d.ts.map +1 -1
- package/dist/ai/config.js +33 -2
- package/dist/ai/config.js.map +1 -1
- package/dist/ai/fetch-client.d.ts +80 -9
- package/dist/ai/fetch-client.d.ts.map +1 -1
- package/dist/ai/fetch-client.js +287 -114
- package/dist/ai/fetch-client.js.map +1 -1
- package/dist/ai/redact.d.ts +7 -0
- package/dist/ai/redact.d.ts.map +1 -0
- package/dist/ai/redact.js +34 -0
- package/dist/ai/redact.js.map +1 -0
- package/dist/ai/request.d.ts +34 -0
- package/dist/ai/request.d.ts.map +1 -0
- package/dist/ai/request.js +86 -0
- package/dist/ai/request.js.map +1 -0
- package/dist/ai/router.js +1 -1
- package/dist/ai/router.js.map +1 -1
- package/dist/ai/routing.d.ts +47 -0
- package/dist/ai/routing.d.ts.map +1 -0
- package/dist/ai/routing.js +83 -0
- package/dist/ai/routing.js.map +1 -0
- package/dist/ai/structured.d.ts +13 -4
- package/dist/ai/structured.d.ts.map +1 -1
- package/dist/ai/structured.js +58 -8
- package/dist/ai/structured.js.map +1 -1
- package/dist/ai/token-limit.d.ts +21 -2
- package/dist/ai/token-limit.d.ts.map +1 -1
- package/dist/ai/token-limit.js +48 -4
- package/dist/ai/token-limit.js.map +1 -1
- package/dist/ai/types.d.ts +40 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/types.js +32 -0
- package/dist/ai/types.js.map +1 -1
- package/dist/autopilot/planner.d.ts +22 -1
- package/dist/autopilot/planner.d.ts.map +1 -1
- package/dist/autopilot/planner.js +166 -14
- package/dist/autopilot/planner.js.map +1 -1
- package/dist/autopilot/profile-check.d.ts +24 -0
- package/dist/autopilot/profile-check.d.ts.map +1 -0
- package/dist/autopilot/profile-check.js +38 -0
- package/dist/autopilot/profile-check.js.map +1 -0
- package/dist/autopilot/prompts.d.ts +1 -0
- package/dist/autopilot/prompts.d.ts.map +1 -1
- package/dist/autopilot/prompts.js +9 -0
- package/dist/autopilot/prompts.js.map +1 -1
- package/dist/autopilot/runner.d.ts +131 -11
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +581 -96
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +83 -6
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +211 -26
- package/dist/autopilot/session.js.map +1 -1
- package/dist/autopilot/state.d.ts +37 -2
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +71 -1
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/tasks.d.ts +2 -0
- package/dist/autopilot/tasks.d.ts.map +1 -1
- package/dist/autopilot/tasks.js +233 -59
- package/dist/autopilot/tasks.js.map +1 -1
- package/dist/autopilot/types.d.ts +81 -4
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/autopilot/types.js +3 -0
- package/dist/autopilot/types.js.map +1 -1
- package/dist/book/context.d.ts +20 -3
- package/dist/book/context.d.ts.map +1 -1
- package/dist/book/context.js +120 -20
- package/dist/book/context.js.map +1 -1
- package/dist/book/store.d.ts +5 -0
- package/dist/book/store.d.ts.map +1 -1
- package/dist/book/store.js.map +1 -1
- package/dist/director/opinion.d.ts +10 -0
- package/dist/director/opinion.d.ts.map +1 -1
- package/dist/director/opinion.js +43 -13
- package/dist/director/opinion.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/markdown/frontmatter.d.ts +22 -1
- package/dist/markdown/frontmatter.d.ts.map +1 -1
- package/dist/markdown/frontmatter.js +67 -11
- package/dist/markdown/frontmatter.js.map +1 -1
- package/dist/profiles/director.d.ts +15 -0
- package/dist/profiles/director.d.ts.map +1 -1
- package/dist/profiles/director.js +98 -37
- package/dist/profiles/director.js.map +1 -1
- package/dist/profiles/ghostwriter.d.ts +7 -0
- package/dist/profiles/ghostwriter.d.ts.map +1 -1
- package/dist/profiles/ghostwriter.js +54 -16
- package/dist/profiles/ghostwriter.js.map +1 -1
- package/dist/profiles/read.d.ts +33 -0
- package/dist/profiles/read.d.ts.map +1 -0
- package/dist/profiles/read.js +96 -0
- package/dist/profiles/read.js.map +1 -0
- package/dist/profiles/readers.d.ts +8 -0
- package/dist/profiles/readers.d.ts.map +1 -1
- package/dist/profiles/readers.js +82 -12
- package/dist/profiles/readers.js.map +1 -1
- package/dist/prompt/trust.d.ts +11 -0
- package/dist/prompt/trust.d.ts.map +1 -1
- package/dist/prompt/trust.js +26 -0
- package/dist/prompt/trust.js.map +1 -1
- package/dist/readers/evaluation.d.ts.map +1 -1
- package/dist/readers/evaluation.js +3 -2
- package/dist/readers/evaluation.js.map +1 -1
- package/dist/server/client.d.ts +55 -5
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +63 -9
- package/dist/server/client.js.map +1 -1
- package/dist/server/protocol.d.ts +44 -2
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js +37 -2
- package/dist/server/protocol.js.map +1 -1
- package/dist/sync/files.d.ts +21 -1
- package/dist/sync/files.d.ts.map +1 -1
- package/dist/sync/files.js +84 -15
- package/dist/sync/files.js.map +1 -1
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +2 -0
- package/dist/testing/index.js.map +1 -1
- package/dist/util/text.d.ts +28 -0
- package/dist/util/text.d.ts.map +1 -1
- package/dist/util/text.js +80 -1
- package/dist/util/text.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
|
@@ -14,14 +14,16 @@ npm install narrarium-engine
|
|
|
14
14
|
|
|
15
15
|
| Area | Main exports |
|
|
16
16
|
|---|---|
|
|
17
|
-
| Book access | `BookStore` (list/read/commit with compare-and-swap), `BookConflictError`, `loadBookSnapshot` |
|
|
18
|
-
| Autopilot | `AutopilotSession`, `AutopilotRun`, `advanceState`, `nextStep`, `applyIntervention`, `summarizeAutopilotState` |
|
|
17
|
+
| Book access | `BookStore` (list/read/commit with compare-and-swap, `readMany`), `BookConflictError`, `loadBookSnapshot` |
|
|
18
|
+
| Autopilot | `AutopilotSession`, `AutopilotRun`, `advanceState`, `nextStep`, `applyIntervention`, `summarizeAutopilotState`, `effectivePublish`, `hostDefaultPublish`, `normalizeRunLimits`, `runnerActivity`, `runnerHeartbeatAgeMs`, `AutopilotRuleError` |
|
|
19
19
|
| Director | `askDirector`, `listDirectorOpinions`, `parseDirector`, `serializeDirector`, `directorPrompt` |
|
|
20
20
|
| Readers | `readerPersonaSystemPrompt`, `mergeReaderPersonas`, `READER_EVALUATION_TOOL`, `chapterReaderText` |
|
|
21
21
|
| Ghostwriters | `parseGhostwriter`, `ghostwriterPrompt` |
|
|
22
|
-
|
|
|
23
|
-
|
|
|
24
|
-
|
|
|
22
|
+
| Markdown | `parseMarkdown` (with `error`), `splitFrontmatter`, `stripFrontmatter`, `renderMarkdown`, `FrontmatterError` |
|
|
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`, `redactSecrets` |
|
|
25
|
+
| Personal server | `NarrariumServerClient`, `pairWithServer`, `pairWithServerDetailed`, `verifyServerIdentity`, `serverCompatibility`, `remoteBookStore`, protocol types (scopes, pairing, updates), `ServerSentEventParser` |
|
|
26
|
+
| Sync | `planFileSync`, `syncBookStores` (three-way sync of two book stores, with the files it leaves out in `skipped`) |
|
|
25
27
|
| Testing | `narrarium-engine/testing`: `MemoryBookStore`, `seedBookFiles`, `createFakeAutopilotAi` |
|
|
26
28
|
|
|
27
29
|
## Running the autopilot
|
|
@@ -49,17 +51,35 @@ await session.waitForIdle();
|
|
|
49
51
|
|
|
50
52
|
Every step is one atomic commit of the book files plus `autopilot/state.json` and `autopilot/activity.json`. A step whose files changed in the meantime (for example because the author edited them) is never overwritten: it is repeated on the latest text.
|
|
51
53
|
|
|
54
|
+
### Session options
|
|
55
|
+
|
|
56
|
+
| Option | Meaning |
|
|
57
|
+
|---|---|
|
|
58
|
+
| `bookId`, `store`, `ai`, `host`, `hostLabel` | Required: the book, its `BookStore`, the `AiPort`, `"browser"` or `"server"`, and the name the author sees. |
|
|
59
|
+
| `hostId` | Stable identity of the host (device or server id). Without it the label identifies the host. |
|
|
60
|
+
| `ownRunnerAlive` | Whether a run recorded by this same host is alive outside this session (another tab). Without it such a run is taken for interrupted. |
|
|
61
|
+
| `hooks` | `beforeStep(signal)`, `afterCommit({ task, message, paths })` and `afterChapter({ chapterNumber, title })`, for a host that syncs. Which of the last two is called, and when, is decided by the engine from where the book is published: see *Quick controls → Publishing*. |
|
|
62
|
+
| `defaultPublish` | Where the host publishes when the author has not chosen (`options.publishEvery`): `"step"`, `"chapter"` or `"off"`. Without it a server host publishes after every step, as it always did, and a browser host as `options.syncAfterChapter` says. |
|
|
63
|
+
| `now`, `maxEvents` | The clock, and how many live events are kept for late subscribers (400). |
|
|
64
|
+
| `retryDelayMs` | The base delay of the retries of a failed step (4000 ms): see *Retries*. `0` makes them instant. |
|
|
65
|
+
| `random` | Source of the retry jitter, in [0, 1) (default `Math.random`). |
|
|
66
|
+
| `heartbeatMs` | While a run is active the session emits a `state` event this often (default 30 000 ms), with the run's heartbeat in memory; nothing is saved for it. `0` switches it off. |
|
|
67
|
+
| `persistHeartbeatMs` | The longest silence of `autopilot/state.json` during a run (default 300 000 ms): after it the run saves a fresh `runner.heartbeatAt`, so that another host does not take a long step for a dead run. `0` switches it off. |
|
|
68
|
+
|
|
69
|
+
A run whose heartbeat is older than `RUNNER_STALE_MINUTES` (20) is taken for dead. `runnerActivity(state)` says `"none"`, `"active"` or `"stale"`, and `runnerHeartbeatAgeMs(state)` how old the heartbeat is, in milliseconds, for a state and for the summary of a live `state` event (`null` when nobody runs).
|
|
70
|
+
|
|
52
71
|
### Pipeline
|
|
53
72
|
|
|
54
73
|
1. **Concept** — story design, world context, characters, locations, factions and secrets (skipped when the book already has a design or prose).
|
|
55
|
-
2. **
|
|
56
|
-
3. **
|
|
74
|
+
2. **Summaries of the author's chapters** — only for a book with chapters written by the author: see *Chapters the author wrote*.
|
|
75
|
+
3. **Plan** — chapter plan; simulated readers react to it and the director approves it or asks for changes. The run can pause here for the author.
|
|
76
|
+
4. **Per chapter** — scene plan, prose scene by scene (streamed), then the review cycle:
|
|
57
77
|
- blind simulated readers (no canon, no secrets) and a panel summary;
|
|
58
78
|
- specialists (continuity, canon, secrets, timeline, voice, style, pacing) with evidence anchored in the text;
|
|
59
79
|
- the **director** accepts or rejects every finding; the software, not the model, derives the repairs;
|
|
60
80
|
- accepted fixes are applied; a new round verifies them, up to the director's round limit;
|
|
61
81
|
- consolidation: chapter summary, recap, story so far, `plot.md`.
|
|
62
|
-
|
|
82
|
+
5. **Final** — the director's judgement on the whole book.
|
|
63
83
|
|
|
64
84
|
### Author interventions
|
|
65
85
|
|
|
@@ -69,7 +89,40 @@ Every step is one atomic commit of the book files plus `autopilot/state.json` an
|
|
|
69
89
|
- `from_now` — a permanent rule for every following step, the director included;
|
|
70
90
|
- `rewrite` — the director picks the written scenes that must change; they are rewritten and reviewed again.
|
|
71
91
|
|
|
72
|
-
With `interrupt: true` the running step is abandoned and repeated with the new instruction.
|
|
92
|
+
With `interrupt: true` the running step is abandoned and repeated with the new instruction. An intervention is saved at once, also while a step runs.
|
|
93
|
+
|
|
94
|
+
Permanent rules (`from_now`) are edited with `session.updateRule(index, text, expectedText?)` and `session.removeRule(index, expectedText?)`; `expectedText` is the rule as the author saw it, and a rule that changed in the meantime is never overwritten. A rule that cannot be saved throws `AutopilotRuleError`, whose `code` is `rule_empty`, `rule_too_long` (a rule is at most `MAX_RULE_CHARACTERS`, 800, because it goes into every request; it is refused, never cut), `rule_not_found`, `rule_changed` or `rule_duplicate`. The author's answer to a question of the director (`QuestionAnswer`) is a note used once; with `asRule: true` it becomes a permanent rule instead (never the default).
|
|
95
|
+
|
|
96
|
+
### Quick controls
|
|
97
|
+
|
|
98
|
+
What the web app's quick-command bar uses: pause at the end of the chapter, the limits of one run, where the book is published, and the settings that can change while a run goes on. They live here, once, so the browser and the personal server behave the same.
|
|
99
|
+
|
|
100
|
+
**Pausing.** `session.pause(mode)` takes `"now"` (the request in flight is abandoned), `"after-step"` (the default: the step in flight finishes and is saved, then the run pauses) or `"after-chapter"` (the step in flight finishes and the run goes on to the end of the chapter in progress, its closing and the publishing of the chapter included, then pauses with `Chapter N completed: paused, as you asked.`, in the language of the book). It answers whether there was a run, or a start in flight, to ask.
|
|
101
|
+
|
|
102
|
+
- A chapter is *in progress* from the moment its scenes are planned until it is closed. With none in progress (the concept, the plan, the summaries of the author's chapters, the first step of a chapter that has not started, the moment between two chapters) it is `"after-step"`, and so is a wait before the retry of such a step; the wait before the retry of a step of the chapter goes on, because the chapter still has to be finished. A request made at the boundary, right after a chapter was closed, pauses before the next one starts. After the last step of the book the run is complete, and says so.
|
|
103
|
+
- The stricter request counts, whatever the order: `"now"`, then `"after-step"`, then `"after-chapter"`. A request made while `start()` is in flight is kept for the run.
|
|
104
|
+
- `session.cancelPause()` takes back a pause that is waiting (`"after-step"` or `"after-chapter"`) without stopping anything, and answers whether there was one. A `"now"` that happened cannot be taken back. `AutopilotRun` has the same: `stopAfterChapter()`, `cancelPause()` and `pausePending`.
|
|
105
|
+
- When the run ends for it, `run-ended` carries `code: "chapterPause"`. If the option `pauseAfterEachChapter` would pause at the same moment, the request that was just made is the one that is said.
|
|
106
|
+
|
|
107
|
+
**Limits of one run.** `session.start({ limits: { steps, chapters } })` pauses the run after that many steps saved, or chapters completed, by this run. Nothing of it is saved: the next run has no limit unless it asks. A value that is not a whole number above zero is no limit (`normalizeRunLimits`). A step that fails or is abandoned does not count; with `steps: 1` a run makes one step (also one of the plan, or the final judgement) and stops, so three of them make three steps and three commits. `chapters` is the same limit as the saved option `chaptersPerRun`: the stricter of the two counts. A limit never takes the place of a reason the book has to stop (a plan that waits for the author, a question, a complete book), and the pause the author asked for is the one reported when both are due at once. `run-ended` carries `code: "stepLimit"` or `code: "chapterLimit"`.
|
|
108
|
+
|
|
109
|
+
**Publishing.** `options.publishEvery` is `"step"` (after every saved step, and again when a chapter is closed, so that the chapter is published whole), `"chapter"` (when a chapter is closed) or `"off"` (never). It is saved with the other options and can change while a run goes on. `effectivePublish(options, defaultPublish)` is the one rule that says where the book is published: `options.publishEvery`, else the host's `defaultPublish`, else the older option `options.syncAfterChapter` (`"chapter"` when it is on, `"off"` when it is off), so the files of an older engine behave as they did. A host that passes no `defaultPublish` gets `hostDefaultPublish(host)`: a `"server"` host publishes after every step (its `afterCommit` hook has always been called then), a `"browser"` host has none, so `syncAfterChapter` decides.
|
|
110
|
+
|
|
111
|
+
The engine applies it, so a host only says *how* to publish: `hooks.afterCommit` is called after every saved step when the way is `"step"`; `hooks.afterChapter` when a chapter is closed and the way is `"chapter"` or `"step"`; neither when it is `"off"`. A host that publishes in every way needs both hooks. The way is read at the end of every step and of every chapter, from the state that step saved. A publish that fails is reported as before (a `sync` event with `syncFailed`, or `publishFailed` for a chapter) and never stops the run. `beforeStep` is not a publish: it is called before every step whatever the way.
|
|
112
|
+
|
|
113
|
+
**Changing settings during a run.** `session.updateOptions(partial)` saves the options and answers the saved state. While a run is active only `publishEvery` (`null` takes the choice back, so that the host decides again) and `pauseAfterEachChapter` can change (`LIVE_AUTOPILOT_OPTIONS`); any other option throws `AutopilotBusyError`, as `configure` does, and nothing of that request is applied. With no run active any option can change. The change is a compare-and-swap commit, like an intervention: the step in flight is neither failed nor repeated, the run takes the author's value into the state the step saves (`reconcileAuthorChanges`) and reads it at the end of that step, or of the chapter. A value nobody knows changes nothing, and a request that changes nothing writes nothing.
|
|
114
|
+
|
|
115
|
+
**What the summary says.** `AutopilotStateSummary`, which the `state` events carry and `snapshot().summary` holds for a client that connects later, has three fields that are never saved: `pausePending` (`"after-step"`, `"after-chapter"` or `null`), `limits` (`{ steps?, chapters?, stepsDone, chaptersDone }` of the run in progress, `null` when it has none or is over; `chapters` is the stricter of the run's limit and `chaptersPerRun`) and `publish` (`effectivePublish` of the options and the host's default). A summary made from the state file alone (`summarizeAutopilotState(state)`) has no `pausePending` and no `limits`: nothing in the file says them, so a client takes them from the events and the snapshot. They change without the state being written, so `updatedAt` does not move: every change of the pause that waits, and every saved step, is a `state` event, and a client keeps the newest event it has seen, whatever its `updatedAt`.
|
|
116
|
+
|
|
117
|
+
**Message codes.** `run-ended` and `insight` events carry a `code` when a client can say it in its own language: `chapterPause`, `stepLimit` and `chapterLimit` join `takenOver` and the others (`AutopilotMessageCode`). The `message` of the event, and of the saved state, is always in the language of the book.
|
|
118
|
+
|
|
119
|
+
### Long books
|
|
120
|
+
|
|
121
|
+
There is no maximum number of chapters. A plan longer than `PLAN_BATCH_CHAPTERS` (20) is made of several `plan` steps, one per batch, so that no reply outgrows the model's output; `plan.revisionBatches` lists the first chapter of every batch a revision of the plan still has to regenerate, and `plan.skippedReaders` the readers whose reaction stayed incomplete after a retry and who are not asked again. The lists of chapters in a prompt are windowed around the chapter at hand (`outline`, at most `OUTLINE_MAX_CHARS`, 24 000 characters), so a prompt never outgrows its budget and the work to build it grows linearly with the book.
|
|
122
|
+
|
|
123
|
+
### Chapters the author wrote
|
|
124
|
+
|
|
125
|
+
A chapter written before the autopilot took over has no summary unless the author wrote one, and without it the story so far of the chapter that follows would start blind. Before anything is planned or written after them, the planner adds one `summarize-imported` step for every such chapter without a `summary`: the model of the `simple-tasks` route summarizes it in two to four sentences, and the summary is saved in its `chapter.md` (created when there is only a folder of scenes) and in its resume file when it has none. A chapter that already has a summary, in its file or in the plan, is skipped and its file is not touched; the plan learns the summaries the files have. One chapter is one step and one commit, with a title and a reason in the language of the book, so it respects pause and budget like any other step, is repeated safely and resumed where it stopped, and is never asked again once the summary is saved. A finished book is not summarized.
|
|
73
126
|
|
|
74
127
|
## The director
|
|
75
128
|
|
|
@@ -83,6 +136,18 @@ const { opinion } = await askDirector({ store, ai, target: { kind: "chapter", ch
|
|
|
83
136
|
|
|
84
137
|
Its profile lives in `director.md` at the book root (persona, autonomy, strictness, approval score, review rounds, priorities, taste, red lines, simulated reader weights and a free vision). Saved opinions go to `evaluations/director/`.
|
|
85
138
|
|
|
139
|
+
Values are read as the author wrote them: an autonomy whatever its case (`Full`, `ask on critical`), numbers with their decimals (`approval_score: 7.5`, a reader weight of `0.4`) and a decimal comma (`'9,5'`).
|
|
140
|
+
|
|
141
|
+
### Profiles that cannot be read
|
|
142
|
+
|
|
143
|
+
`parseDirector`, `parseGhostwriter` and `parseReaderPersona` never throw and never hide a problem: they return `warnings: string[]` (empty when the file is as it says), each naming the file. A warning is YAML that cannot be read (with its line), a value that is not understood (an autonomy nobody knows, a score that is not a number, a list that is not a list, a reader type that is none of `standard`, `genre`, `custom`, a switch that is neither yes nor no), and the profile then has the default for that value, as it always had. The defaults themselves carry `warnings: []`.
|
|
144
|
+
|
|
145
|
+
A profile with warnings is not what the author wrote, so the engine never goes on with it silently and never replaces the file with the defaults:
|
|
146
|
+
|
|
147
|
+
- before a step, the autopilot checks the director, the files of the simulated readers when readers are used, and the ghostwriter of the chapter for a step that writes. When one has warnings it spends nothing, emits an insight with code `profileProblems` and stops with `status: "waiting-author"` and a `message` that lists the problems (in the language of the book); the author corrects the file and resumes.
|
|
148
|
+
- `askDirector` still gives its opinion, and reports the problems of `director.md` in `warnings` next to it.
|
|
149
|
+
- a host that saves a profile should not do it over a file that has warnings.
|
|
150
|
+
|
|
86
151
|
## Files in the book
|
|
87
152
|
|
|
88
153
|
| Path | Content |
|
|
@@ -91,12 +156,100 @@ Its profile lives in `director.md` at the book root (persona, autonomy, strictne
|
|
|
91
156
|
| `autopilot/state.json` | Autopilot state: brief, options, plan, review cycle, rules, interventions, statistics. |
|
|
92
157
|
| `autopilot/activity.json` | Last 200 activities (what, why, next, result, model, tokens, cost). |
|
|
93
158
|
| `autopilot/plan.md` | Human-readable mirror of the plan. |
|
|
159
|
+
| `chapters/<chapter>/chapter.md` | The chapter, with its `summary` (written when it is closed, or by the summary step for a chapter the author wrote). |
|
|
160
|
+
| `resumes/` | `total.md` (one section per chapter) and `chapters/<chapter>.md` (the recap of each one). |
|
|
94
161
|
| `evaluations/director/` | Director opinions (`book.md`, `chapters/<chapter>.md`, `paragraphs/<chapter>/<paragraph>.md`). |
|
|
95
162
|
| `evaluations/readers/` | Simulated reader evaluations, in the same format as the web app. |
|
|
96
163
|
|
|
97
164
|
## AI tasks
|
|
98
165
|
|
|
99
|
-
The engine asks the host for these router tasks (capabilities): `autopilot` (concept, plan, scenes, prose, repairs), `director`, `reader-evaluation`, `reader-evaluation-summary`, `review` (specialists) and `simple-tasks` (
|
|
166
|
+
The engine asks the host for these router tasks (capabilities): `autopilot` (concept, plan, scenes, prose, repairs), `director`, `reader-evaluation`, `reader-evaluation-summary`, `review` (specialists) and `simple-tasks` (summaries of scenes and of the chapters the author wrote). Missing routes fall back to models tagged `default`.
|
|
167
|
+
|
|
168
|
+
### What the models read of a scene
|
|
169
|
+
|
|
170
|
+
Prose that is judged or summarized (the specialists, the director's review of a chapter, the consolidation, the director's opinion on a scene or a chapter, the summary of a chapter the author wrote) is cut, when it is too long, in the middle: `clipMiddle(text, max, { head: 0.6 })` keeps the start and the end, joined by `[…]` (on a line of its own when the text has several lines), at a word and never inside a character. The limit comes from the book: `sceneCharacterLimit(wordsPerScene)` is ten characters a word (as much as the longest words of any script written with spaces) and half as much again, so a scene of the length the brief asks for is never clipped; the fixed limits these prompts always had stay as the least a prompt keeps, so no scene is cut that was not cut before. A scene within the limit reaches the model exactly as it is written. The ending the next scene is continued from is the real end of the previous one, however long it is.
|
|
171
|
+
|
|
172
|
+
### Secrets in a prompt
|
|
173
|
+
|
|
174
|
+
`secretRules(store, snapshot, chapterNumber?)` lists the secrets with the rule that holds for the chapter (`HIDDEN until chapter N`, `The reveal is planned in THIS chapter`, `Already revealable…`, or `No reveal threshold`) and, for each, its truth. A book with few secrets gets all of them, exactly as ever. A list over `SECRET_RULES_MAX_CHARS` (24 000 characters) is windowed like a list of chapters: secrets revealed more than `SECRET_WINDOW_CHAPTERS` (30) chapters before drop out first, then the truths and the long wording; what the chapter must not reveal (a reveal still to come, or none planned) and the reveal of the chapter itself stay as long as anything can, the nearest chapters first, and the last line says how many are not listed. Only the files of the secrets that are listed with their truth are read, so a book of thousands of secrets costs the same as a small one.
|
|
175
|
+
|
|
176
|
+
### Languages
|
|
177
|
+
|
|
178
|
+
Limits on the reply of a step are sized for Latin script (2.4 tokens a word) and grown for the language of the book: `tokensPerWord(language)` gives the factor of the language (by code, name or region: `ru`, `русский`, `zh-CN`), `UNKNOWN_TOKENS_PER_WORD` (6) for one the engine does not know, and `scaleOutputTokens` applies it up to `OUTPUT_TOKENS_CEILING`. Words are counted by `countWords` for every script, with `Intl.Segmenter` where a language has no spaces.
|
|
179
|
+
|
|
180
|
+
## The AI client
|
|
181
|
+
|
|
182
|
+
`createFetchAi(config, options)` is the one AI client of every host: the browser and the personal server give it the same `AiRuntimeConfig` (`pickAiRuntimeConfig(settings)`) and get the same requests and the same outcomes. A host adds only what is its own, through `options`:
|
|
183
|
+
|
|
184
|
+
| Option | Meaning |
|
|
185
|
+
|---|---|
|
|
186
|
+
| `fetch` | The `fetch` to use (default the global one). |
|
|
187
|
+
| `githubModelsBaseUrl` | Origin of GitHub Models, or of a proxy that forwards `/inference`. |
|
|
188
|
+
| `defaultTimeoutMs` | Timeout for an integration that has none (default `DEFAULT_REQUEST_TIMEOUT_MS`). |
|
|
189
|
+
| `onAttempt`, `onAttemptEnd` | Hooks that see every attempt that is sent and how it ended (below). |
|
|
190
|
+
| `acknowledgeFallback` | Asked before content goes to an integration of another account than the one it went to so far (below). |
|
|
191
|
+
|
|
192
|
+
What every host gets, whatever its options:
|
|
193
|
+
|
|
194
|
+
| What | How |
|
|
195
|
+
|---|---|
|
|
196
|
+
| 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. |
|
|
197
|
+
| 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. |
|
|
198
|
+
| 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. |
|
|
199
|
+
| 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. |
|
|
200
|
+
| 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. |
|
|
201
|
+
| Timeout | An integration's `requestTimeoutMs`, else `options.defaultTimeoutMs`, else `DEFAULT_REQUEST_TIMEOUT_MS` (600 s), in every host. |
|
|
202
|
+
| Hooks | `onAttempt(attempt)`: `attemptId`, the effective `messages` (with the JSON instruction a model without tools receives), the output limit, `stream`, `tools`, `endpoint` and `timeoutMs`. `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` and `durationMs`, for every attempt that was sent, failed ones included. A hook that throws never breaks a call. |
|
|
203
|
+
| 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. |
|
|
204
|
+
| Wire format | Server-sent events with several `data:` lines are joined with a newline; 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. |
|
|
205
|
+
| 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`, `truncated` and `reasoningOnly`. Keys, `Bearer …`, `api-key: …`, `?key=…` and `sk-…` are removed from every message (`redactSecrets`), also before the runner saves it. |
|
|
206
|
+
|
|
207
|
+
### Costs and budgets
|
|
208
|
+
|
|
209
|
+
`estimateCost` bills cached tokens like normal input unless the model has a `cachedPerMTok`. A reply carries `usageKnown` and `costKnown`: when the provider reports no tokens, `usage` is an estimate (`usageKnown: false`, `costKnown: false`); a model without a price has no `cost`. The autopilot counts those calls in `stats.usageUnknownCalls` and `stats.costUnknownCalls`, says once per run that the money budget (`options.budgetLimit`) cannot apply to a model without a price (`budgetNotApplicable`), and `options.budgetTokens` stops the run at a number of tokens instead (0 = off).
|
|
210
|
+
|
|
211
|
+
### Retries
|
|
212
|
+
|
|
213
|
+
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.
|
|
214
|
+
|
|
215
|
+
### What the model's replies must be
|
|
216
|
+
|
|
217
|
+
- A forced tool call must carry at least one of the schema's required fields (else one of its declared properties); otherwise the JSON in the text is used, and a reply with neither is rejected and retried once with the reason.
|
|
218
|
+
- `<think>` blocks are dropped, and so is everything up to the last `</think>` of a model that never opened it.
|
|
219
|
+
- What the engine escapes in prompts (`&`, `<`, `>`) is un-escaped in prose and in every text field of a structured reply (`unescapePromptData`).
|
|
220
|
+
- 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`.
|
|
221
|
+
- 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.
|
|
222
|
+
|
|
223
|
+
## Sync
|
|
224
|
+
|
|
225
|
+
`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.
|
|
226
|
+
|
|
227
|
+
What it does not move is reported, never silently ignored and never a reason for the sync to fail. `result.skipped` lists, in path order, each file with its `reason`:
|
|
228
|
+
|
|
229
|
+
| Reason | Meaning |
|
|
230
|
+
|---|---|
|
|
231
|
+
| `too-large` | The file is over `maxFileBytes` (`SYNC_MAX_FILE_BYTES`, 8 MiB, what the personal server accepts), with its `size` in bytes; or a store refused to send it because it is too much (HTTP 413), without a `size`. The size is checked before the file goes into a commit: a store may list `size` in its `BookFileEntry`, and then the file is not even read. |
|
|
232
|
+
| `unsafe-path` | A path that is not a safe repository path (`../x.md`, `.git/…`, absolute): the same paths as `rejected`. |
|
|
233
|
+
| `not-text` | A file that is not text (binary assets are left to the hosts) and is not the same on both sides. |
|
|
234
|
+
|
|
235
|
+
A skipped file is not recorded as synced (a file that was never synced stays out of `base`, one that was keeps the version the other side has), so the next sync says it again until it can be moved; the deletion of a file is never skipped.
|
|
236
|
+
|
|
237
|
+
## The personal server client
|
|
238
|
+
|
|
239
|
+
`NarrariumServerClient` is the typed client of the personal server API, shared by the web app and the CLI (see the [server README](../server/README.md)).
|
|
240
|
+
|
|
241
|
+
- **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).
|
|
242
|
+
- **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.
|
|
243
|
+
- **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).
|
|
244
|
+
- **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`.
|
|
245
|
+
|
|
246
|
+
| Client method | Request | Answer |
|
|
247
|
+
|---|---|---|
|
|
248
|
+
| `pauseAutopilot(bookId, mode)` | `POST /api/v1/books/:id/autopilot/pause` with `{ "mode": "now" \| "after-step" \| "after-chapter" \| "cancel" }`. A body without `mode` is `after-step`, as it always was. | `200` the snapshot. `cancel` with nothing waiting, and any mode with nothing running, are `200` too: the summary's `pausePending` says what is waiting now. `400 invalid_request` for a `mode` that is none of the four, or a body that is not a JSON object. |
|
|
249
|
+
| `startAutopilot(bookId, input)` | `POST /api/v1/books/:id/autopilot/start` with the body it always had (`brief`, `options`, `force`) and `limits?: { "steps"?: number, "chapters"?: number }`. | `200` the snapshot. `400 invalid_request` when `limits` is present and is not a JSON object. The server hands the numbers to the engine as they are (a value that is not a whole number above zero is no limit) and does not save them. The other answers are as before: `409 busy`, `412 ai_not_configured`, `429 too_many_runs`, `503 maintenance`. |
|
|
250
|
+
| `updateAutopilotOptions(bookId, input)`, also `updateOptions` | `PUT /api/v1/books/:id/autopilot/options` with `{ "publishEvery"?: "off" \| "chapter" \| "step" \| null, "pauseAfterEachChapter"?: boolean }`: at least one of the two, and nothing else. `null` takes the choice back, so that the server's default decides again. | `200` the snapshot, of the state that was saved (as `configure` answers), also while the autopilot runs: the step in flight is not repeated, and the run reads the new value at the end of the step, or of the chapter. `400 invalid_request` for a body that is not a JSON object, has none of the two keys or has another key, or a value of the wrong type (`publishEvery` that is not one of the four, `pauseAfterEachChapter` that is not a boolean). `409 conflict` when the state file kept changing under the write (try again) and `409 state_corrupt` when it cannot be read; `503 maintenance` while the server is about to restart. |
|
|
251
|
+
|
|
252
|
+
The server answers with the engine's `session.pause`, `session.cancelPause`, `session.start({ …, limits })` and `session.updateOptions`, and takes `defaultPublish: "step"` as its default (which is what it does when it passes none). It can validate the bodies against the lists the engine exports for that: `PAUSE_AUTOPILOT_MODES`, `AUTOPILOT_PUBLISH_MODES` and `LIVE_AUTOPILOT_OPTIONS`. For a GitHub book its `afterCommit` hook pushes (what the engine calls after every step in `step` mode) and its `afterChapter` hook pushes too (what it calls when a chapter is closed in `chapter` and `step` mode): without that one, `chapter` would publish nothing.
|
|
100
253
|
|
|
101
254
|
## Tests
|
|
102
255
|
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export declare const DEFAULT_MAX_INPUT_TOKENS = 32000;
|
|
2
|
+
export declare const DEFAULT_MAX_OUTPUT_TOKENS = 2048;
|
|
3
|
+
/** Byte-level BPE tokenizers cannot emit more tokens than the UTF-8 bytes supplied: a safe upper bound. */
|
|
4
|
+
export declare function textTokenUpperBound(value: string): number;
|
|
5
|
+
/**
|
|
6
|
+
* Likely token count, about four characters per token. Unlike the upper bound it can be lower than the provider's
|
|
7
|
+
* count, so it only serves to refuse prompts that clearly cannot fit a known window and to estimate what a reply used.
|
|
8
|
+
*/
|
|
9
|
+
export declare function likelyTextTokens(value: string): number;
|
|
10
|
+
export declare function likelyMessageTokens(messages: ReadonlyArray<{
|
|
11
|
+
content: string;
|
|
12
|
+
}>): number;
|
|
13
|
+
export declare function estimateMessageTokens(messages: ReadonlyArray<{
|
|
14
|
+
content: string;
|
|
15
|
+
}>): number;
|
|
16
|
+
/**
|
|
17
|
+
* What a model's context window leaves for the prompt once its output and a 5% safety margin are reserved
|
|
18
|
+
* (same rule as the web app, so a prompt is judged the same way in every host).
|
|
19
|
+
*/
|
|
20
|
+
export declare function resolveModelTokenBudgets(maxContextTokens?: number, configuredOutputTokens?: number): {
|
|
21
|
+
contextTokens: number;
|
|
22
|
+
inputTokens: number;
|
|
23
|
+
outputTokens: number;
|
|
24
|
+
safetyTokens: number;
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=budget.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"budget.d.ts","sourceRoot":"","sources":["../../src/ai/budget.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,wBAAwB,QAAS,CAAC;AAC/C,eAAO,MAAM,yBAAyB,OAAQ,CAAC;AAI/C,2GAA2G;AAC3G,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,aAAa,CAAC;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,MAAM,CAExF;AAED,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,aAAa,CAAC;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,MAAM,CAE1F;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,gBAAgB,SAA2B,EAAE,sBAAsB,CAAC,EAAE,MAAM,GAAG;IAAE,aAAa,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAQjN"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const MESSAGE_OVERHEAD_TOKENS = 4;
|
|
2
|
+
export const DEFAULT_MAX_INPUT_TOKENS = 32_000;
|
|
3
|
+
export const DEFAULT_MAX_OUTPUT_TOKENS = 2_048;
|
|
4
|
+
const encoder = new TextEncoder();
|
|
5
|
+
/** Byte-level BPE tokenizers cannot emit more tokens than the UTF-8 bytes supplied: a safe upper bound. */
|
|
6
|
+
export function textTokenUpperBound(value) {
|
|
7
|
+
return encoder.encode(value).byteLength;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Likely token count, about four characters per token. Unlike the upper bound it can be lower than the provider's
|
|
11
|
+
* count, so it only serves to refuse prompts that clearly cannot fit a known window and to estimate what a reply used.
|
|
12
|
+
*/
|
|
13
|
+
export function likelyTextTokens(value) {
|
|
14
|
+
return Math.ceil((value ?? "").length / 4);
|
|
15
|
+
}
|
|
16
|
+
export function likelyMessageTokens(messages) {
|
|
17
|
+
return messages.reduce((total, message) => total + MESSAGE_OVERHEAD_TOKENS + likelyTextTokens(message.content), 0);
|
|
18
|
+
}
|
|
19
|
+
export function estimateMessageTokens(messages) {
|
|
20
|
+
return messages.reduce((total, message) => total + MESSAGE_OVERHEAD_TOKENS + textTokenUpperBound(message.content), 0);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* What a model's context window leaves for the prompt once its output and a 5% safety margin are reserved
|
|
24
|
+
* (same rule as the web app, so a prompt is judged the same way in every host).
|
|
25
|
+
*/
|
|
26
|
+
export function resolveModelTokenBudgets(maxContextTokens = DEFAULT_MAX_INPUT_TOKENS, configuredOutputTokens) {
|
|
27
|
+
const contextTokens = Math.max(3, Math.floor(maxContextTokens || DEFAULT_MAX_INPUT_TOKENS));
|
|
28
|
+
const safetyTokens = Math.min(Math.max(32, Math.ceil(contextTokens * 0.05)), contextTokens - 2);
|
|
29
|
+
const requestedOutput = configuredOutputTokens && configuredOutputTokens > 0
|
|
30
|
+
? Math.floor(configuredOutputTokens)
|
|
31
|
+
: Math.min(DEFAULT_MAX_OUTPUT_TOKENS, Math.max(1, Math.floor(contextTokens * 0.25)));
|
|
32
|
+
const outputTokens = Math.min(requestedOutput, Math.max(1, contextTokens - safetyTokens - 1));
|
|
33
|
+
return { contextTokens, inputTokens: contextTokens - safetyTokens - outputTokens, outputTokens, safetyTokens };
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=budget.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"budget.js","sourceRoot":"","sources":["../../src/ai/budget.ts"],"names":[],"mappings":"AAAA,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAClC,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAC;AAC/C,MAAM,CAAC,MAAM,yBAAyB,GAAG,KAAK,CAAC;AAE/C,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,2GAA2G;AAC3G,MAAM,UAAU,mBAAmB,CAAC,KAAa;IAC/C,OAAO,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,UAAU,CAAC;AAC1C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAa;IAC5C,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,QAA4C;IAC9E,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,KAAK,GAAG,uBAAuB,GAAG,gBAAgB,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;AACrH,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,QAA4C;IAChF,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,KAAK,GAAG,uBAAuB,GAAG,mBAAmB,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;AACxH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CAAC,gBAAgB,GAAG,wBAAwB,EAAE,sBAA+B;IACnH,MAAM,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,gBAAgB,IAAI,wBAAwB,CAAC,CAAC,CAAC;IAC5F,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,IAAI,CAAC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC,EAAE,aAAa,GAAG,CAAC,CAAC,CAAC;IAChG,MAAM,eAAe,GAAG,sBAAsB,IAAI,sBAAsB,GAAG,CAAC;QAC1E,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,sBAAsB,CAAC;QACpC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,yBAAyB,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACvF,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,aAAa,GAAG,YAAY,GAAG,CAAC,CAAC,CAAC,CAAC;IAC9F,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,aAAa,GAAG,YAAY,GAAG,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,CAAC;AACjH,CAAC"}
|
package/dist/ai/config.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export type AiProviderKind = "azure_openai" | "openai" | "github_models" | "m365_copilot";
|
|
2
|
+
/** The Azure OpenAI API version used when an integration does not name one. */
|
|
3
|
+
export declare const DEFAULT_AZURE_API_VERSION = "2024-10-21";
|
|
2
4
|
export interface AiPricingConfig {
|
|
3
5
|
inputPerMTok?: number;
|
|
4
6
|
cachedPerMTok?: number;
|
|
@@ -36,6 +38,22 @@ export interface AiTaskRoute {
|
|
|
36
38
|
primary?: AiRouteTarget;
|
|
37
39
|
fallbacks?: AiRouteTarget[];
|
|
38
40
|
}
|
|
41
|
+
/** Privacy of fallbacks: what may leave the primary integration's account (the boundary is the integration). */
|
|
42
|
+
export interface AiFallbackDisclosure {
|
|
43
|
+
/** Never send content to a fallback outside the primary's integration. */
|
|
44
|
+
sameBoundaryOnly: boolean;
|
|
45
|
+
/** Ask the host before sending content to a fallback outside the boundary the content already went to. */
|
|
46
|
+
requireAcknowledgement: boolean;
|
|
47
|
+
}
|
|
48
|
+
/** Limits of one routed call: candidates tried, time, estimated tokens and estimated cost across attempts. */
|
|
49
|
+
export interface AiRoutingExecution {
|
|
50
|
+
maxCandidates: number;
|
|
51
|
+
maxTotalDurationMs: number;
|
|
52
|
+
maxTokenAttempts: number;
|
|
53
|
+
maxEstimatedCost: number;
|
|
54
|
+
}
|
|
55
|
+
/** The web app's defaults for the routing limits. */
|
|
56
|
+
export declare const DEFAULT_ROUTING_EXECUTION: Readonly<AiRoutingExecution>;
|
|
39
57
|
/**
|
|
40
58
|
* The subset of the web app's AI router settings needed to run chat tasks.
|
|
41
59
|
* The same JSON is configured in the browser and, with consent, sent to a personal server.
|
|
@@ -47,7 +65,13 @@ export interface AiRuntimeConfig {
|
|
|
47
65
|
defaultReviewIntegrationId?: string;
|
|
48
66
|
costCurrency?: string;
|
|
49
67
|
maxCandidates?: number;
|
|
68
|
+
/** Absent (a configuration saved before this existed): fallbacks are not restricted. */
|
|
69
|
+
fallbackDisclosure?: AiFallbackDisclosure;
|
|
70
|
+
/** Absent fields are not limited: a call has no total time, token or cost limit. A configuration sent by the web app has them all. */
|
|
71
|
+
routingExecution?: Partial<AiRoutingExecution>;
|
|
50
72
|
}
|
|
73
|
+
/** The routing limits with the web app's normalization: whole numbers within the same bounds, the same defaults. */
|
|
74
|
+
export declare function normalizeRoutingExecution(raw: unknown): AiRoutingExecution;
|
|
51
75
|
/** Extract and sanitize the AI configuration from a web-app settings object (or a server config file). */
|
|
52
76
|
export declare function pickAiRuntimeConfig(settings: unknown): AiRuntimeConfig;
|
|
53
77
|
export interface RedactedAiIntegration {
|
|
@@ -65,5 +89,7 @@ export interface RedactedAiIntegration {
|
|
|
65
89
|
export declare function redactAiRuntimeConfig(config: AiRuntimeConfig): {
|
|
66
90
|
integrations: RedactedAiIntegration[];
|
|
67
91
|
routedTasks: string[];
|
|
92
|
+
fallbackDisclosure?: AiFallbackDisclosure;
|
|
93
|
+
routingExecution?: Partial<AiRoutingExecution>;
|
|
68
94
|
};
|
|
69
95
|
//# sourceMappingURL=config.d.ts.map
|
package/dist/ai/config.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/ai/config.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,cAAc,GAAG,cAAc,GAAG,QAAQ,GAAG,eAAe,GAAG,cAAc,CAAC;AAE1F,MAAM,WAAW,eAAe;IAC9B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,eAAe,CAAC;CAC3B;AAED,MAAM,WAAW,mBAAmB;IAClC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,QA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CAc1N"}
|
package/dist/ai/config.js
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
/** The Azure OpenAI API version used when an integration does not name one. */
|
|
2
|
+
export const DEFAULT_AZURE_API_VERSION = "2024-10-21";
|
|
3
|
+
/** The web app's defaults for the routing limits. */
|
|
4
|
+
export const DEFAULT_ROUTING_EXECUTION = Object.freeze({
|
|
5
|
+
maxCandidates: 4,
|
|
6
|
+
maxTotalDurationMs: 180_000,
|
|
7
|
+
maxTokenAttempts: 200_000,
|
|
8
|
+
maxEstimatedCost: 5,
|
|
9
|
+
});
|
|
1
10
|
const PROVIDERS = ["azure_openai", "openai", "github_models", "m365_copilot"];
|
|
2
11
|
function record(value) {
|
|
3
12
|
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
@@ -24,6 +33,23 @@ function target(value) {
|
|
|
24
33
|
const model = text(source.model);
|
|
25
34
|
return integrationId && model ? { integrationId, model } : undefined;
|
|
26
35
|
}
|
|
36
|
+
/** The routing limits with the web app's normalization: whole numbers within the same bounds, the same defaults. */
|
|
37
|
+
export function normalizeRoutingExecution(raw) {
|
|
38
|
+
const source = record(raw);
|
|
39
|
+
const bounded = (key, min, max) => {
|
|
40
|
+
const value = source[key];
|
|
41
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : DEFAULT_ROUTING_EXECUTION[key];
|
|
42
|
+
};
|
|
43
|
+
return {
|
|
44
|
+
maxCandidates: Math.floor(bounded("maxCandidates", 1, 8)),
|
|
45
|
+
maxTotalDurationMs: Math.floor(bounded("maxTotalDurationMs", 1_000, 600_000)),
|
|
46
|
+
maxTokenAttempts: Math.floor(bounded("maxTokenAttempts", 1_000, 2_000_000)),
|
|
47
|
+
maxEstimatedCost: bounded("maxEstimatedCost", 0.01, 1_000),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function isObject(value) {
|
|
51
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
52
|
+
}
|
|
27
53
|
/** Extract and sanitize the AI configuration from a web-app settings object (or a server config file). */
|
|
28
54
|
export function pickAiRuntimeConfig(settings) {
|
|
29
55
|
const source = record(settings);
|
|
@@ -73,14 +99,17 @@ export function pickAiRuntimeConfig(settings) {
|
|
|
73
99
|
if (primary || fallbacks.length)
|
|
74
100
|
taskRouting[task] = { primary, fallbacks };
|
|
75
101
|
}
|
|
76
|
-
const
|
|
102
|
+
const routingExecution = isObject(source.routingExecution) ? normalizeRoutingExecution(source.routingExecution) : undefined;
|
|
103
|
+
const disclosure = isObject(source.fallbackDisclosure) ? source.fallbackDisclosure : undefined;
|
|
77
104
|
return {
|
|
78
105
|
aiIntegrations: integrations,
|
|
79
106
|
taskRouting,
|
|
80
107
|
defaultWritingIntegrationId: text(source.defaultWritingIntegrationId),
|
|
81
108
|
defaultReviewIntegrationId: text(source.defaultReviewIntegrationId),
|
|
82
109
|
costCurrency: text(source.costCurrency),
|
|
83
|
-
maxCandidates:
|
|
110
|
+
maxCandidates: routingExecution?.maxCandidates ?? positive(source.maxCandidates),
|
|
111
|
+
...(disclosure ? { fallbackDisclosure: { sameBoundaryOnly: disclosure.sameBoundaryOnly === true, requireAcknowledgement: disclosure.requireAcknowledgement === true } } : {}),
|
|
112
|
+
...(routingExecution ? { routingExecution } : {}),
|
|
84
113
|
};
|
|
85
114
|
}
|
|
86
115
|
/** Safe view of a configuration: never exposes API keys. */
|
|
@@ -95,6 +124,8 @@ export function redactAiRuntimeConfig(config) {
|
|
|
95
124
|
models: (integration.chatModels ?? []).map((model) => ({ name: model.name, capabilities: model.capabilities })),
|
|
96
125
|
})),
|
|
97
126
|
routedTasks: Object.keys(config.taskRouting ?? {}).sort(),
|
|
127
|
+
...(config.fallbackDisclosure ? { fallbackDisclosure: config.fallbackDisclosure } : {}),
|
|
128
|
+
...(config.routingExecution ? { routingExecution: config.routingExecution } : {}),
|
|
98
129
|
};
|
|
99
130
|
}
|
|
100
131
|
//# sourceMappingURL=config.js.map
|
package/dist/ai/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/ai/config.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/ai/config.ts"],"names":[],"mappings":"AAEA,+EAA+E;AAC/E,MAAM,CAAC,MAAM,yBAAyB,GAAG,YAAY,CAAC;AA4DtD,qDAAqD;AACrD,MAAM,CAAC,MAAM,yBAAyB,GAAiC,MAAM,CAAC,MAAM,CAAC;IACnF,aAAa,EAAE,CAAC;IAChB,kBAAkB,EAAE,OAAO;IAC3B,gBAAgB,EAAE,OAAO;IACzB,gBAAgB,EAAE,CAAC;CACpB,CAAC,CAAC;AAmBH,MAAM,SAAS,GAAqB,CAAC,cAAc,EAAE,QAAQ,EAAE,eAAe,EAAE,cAAc,CAAC,CAAC;AAEhG,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAgC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC7G,CAAC;AAED,SAAS,IAAI,CAAC,KAAc;IAC1B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9E,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9F,CAAC;AAED,SAAS,OAAO,CAAC,KAAc;IAC7B,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC7B,MAAM,MAAM,GAAo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CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,CAAC,CAAC;SAChH,CAAC,CAAC;QACH,WAAW,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE;QACzD,GAAG,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,kBAAkB,EAAE,MAAM,CAAC,kBAAkB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvF,GAAG,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,MAAM,CAAC,gBAAgB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAClF,CAAC;AACJ,CAAC"}
|
|
@@ -1,33 +1,106 @@
|
|
|
1
1
|
import type { AiPricingConfig, AiRuntimeConfig } from "./config.js";
|
|
2
|
-
import { type
|
|
3
|
-
|
|
4
|
-
export declare const
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
import { type AiPort, type AiUsage } from "./types.js";
|
|
3
|
+
/** How long one candidate may take before it is given up, for every host (an integration's own timeout wins). */
|
|
4
|
+
export declare const DEFAULT_REQUEST_TIMEOUT_MS = 600000;
|
|
5
|
+
export interface FetchAiMessage {
|
|
6
|
+
role: "system" | "user";
|
|
7
|
+
content: string;
|
|
8
|
+
}
|
|
7
9
|
export interface FetchAiAttempt {
|
|
8
10
|
label: string;
|
|
9
11
|
capability: string;
|
|
10
12
|
provider: string;
|
|
11
13
|
model: string;
|
|
12
14
|
integrationId: string;
|
|
15
|
+
/** Position of the candidate in the route's order: 0 is the primary. */
|
|
13
16
|
index: number;
|
|
17
|
+
/** Identifies this attempt: the `onAttemptEnd` call that closes it carries the same id. */
|
|
18
|
+
attemptId: string;
|
|
19
|
+
/** The messages actually sent: a model without tools gets the JSON instruction in the system prompt. */
|
|
20
|
+
messages: FetchAiMessage[];
|
|
21
|
+
/** The output token limit sent, when there is one. */
|
|
22
|
+
maxOutputTokens?: number;
|
|
23
|
+
stream: boolean;
|
|
24
|
+
/** The structured reply is requested as a forced function call. */
|
|
25
|
+
tools: boolean;
|
|
26
|
+
/** The origin and path every request of this integration starts with (never a key). */
|
|
27
|
+
endpoint: string | null;
|
|
28
|
+
/** How long this attempt may take. */
|
|
29
|
+
timeoutMs: number;
|
|
30
|
+
}
|
|
31
|
+
export interface FetchAiAttemptEnd {
|
|
32
|
+
attemptId: string;
|
|
33
|
+
label: string;
|
|
34
|
+
capability: string;
|
|
35
|
+
provider: string;
|
|
36
|
+
model: string;
|
|
37
|
+
integrationId: string;
|
|
38
|
+
index: number;
|
|
39
|
+
/** `cancelled`: the caller aborted the request. */
|
|
40
|
+
outcome: "ok" | "failed" | "cancelled";
|
|
41
|
+
/** What the attempt used, also when it failed after the model had started to answer. */
|
|
42
|
+
usage?: AiUsage;
|
|
43
|
+
/** `false` when `usage` is an estimate or missing because the provider reported no tokens. */
|
|
44
|
+
usageKnown: boolean;
|
|
45
|
+
cost?: number;
|
|
46
|
+
/** `false` when the model has no price or the usage was estimated. */
|
|
47
|
+
costKnown: boolean;
|
|
48
|
+
currency?: string;
|
|
49
|
+
/** The reply, when the attempt succeeded. */
|
|
50
|
+
text?: string;
|
|
51
|
+
/** Why the attempt failed: the provider's message, already cleaned of credentials. */
|
|
52
|
+
error?: string;
|
|
53
|
+
failureKind?: "timeout" | "cancelled" | "provider";
|
|
54
|
+
status?: number;
|
|
55
|
+
retryAfterMs?: number;
|
|
56
|
+
/** The limit that ran out, for a timeout. */
|
|
57
|
+
timeoutMs?: number;
|
|
58
|
+
durationMs: number;
|
|
59
|
+
}
|
|
60
|
+
/** One side of a fallback that crosses a privacy boundary. */
|
|
61
|
+
export interface FetchAiFallbackTarget {
|
|
62
|
+
integrationId: string;
|
|
63
|
+
integrationName: string;
|
|
64
|
+
provider: string;
|
|
65
|
+
model: string;
|
|
66
|
+
/** What the policy compares: `integration:<id>`. */
|
|
67
|
+
boundary: string;
|
|
68
|
+
}
|
|
69
|
+
export interface FetchAiFallbackInfo {
|
|
70
|
+
capability: string;
|
|
71
|
+
label: string;
|
|
14
72
|
}
|
|
15
73
|
export interface FetchAiOptions {
|
|
16
74
|
fetch?: typeof fetch;
|
|
17
75
|
/** Origin of GitHub Models (or of a proxy forwarding `/inference`). */
|
|
18
76
|
githubModelsBaseUrl?: string;
|
|
19
|
-
/** Used when an integration has no request timeout. */
|
|
77
|
+
/** Used when an integration has no request timeout (default `DEFAULT_REQUEST_TIMEOUT_MS`). */
|
|
20
78
|
defaultTimeoutMs?: number;
|
|
79
|
+
/** An attempt is about to be sent. Never breaks the call. */
|
|
21
80
|
onAttempt?: (attempt: FetchAiAttempt) => void;
|
|
81
|
+
/** An attempt ended, whether it worked or not: for costs and debug panels. Never breaks the call. */
|
|
82
|
+
onAttemptEnd?: (end: FetchAiAttemptEnd) => void;
|
|
83
|
+
/**
|
|
84
|
+
* With `fallbackDisclosure.requireAcknowledgement`, asked before content goes to a fallback in another account than
|
|
85
|
+
* the one it went to so far. Return `true` to allow it; anything else, or a host without this hook, keeps the content
|
|
86
|
+
* where it is. Throw to cancel the whole call.
|
|
87
|
+
*/
|
|
88
|
+
acknowledgeFallback?: (from: FetchAiFallbackTarget, to: FetchAiFallbackTarget, info: FetchAiFallbackInfo) => boolean | Promise<boolean>;
|
|
22
89
|
}
|
|
23
90
|
/**
|
|
24
91
|
* OpenAI-compatible chat client built on `fetch`, usable from Node and browsers.
|
|
25
92
|
* Supports OpenAI and compatible endpoints, Azure OpenAI and GitHub Models, streaming text,
|
|
26
93
|
* forced function calls for structured output, and ordered fallbacks between candidates.
|
|
94
|
+
* It is the one client of every host, so the same book and configuration produce the same requests and the same
|
|
95
|
+
* outcomes: requests come from `buildChatRequest`, the routing limits and the privacy policy of the configuration are
|
|
96
|
+
* applied here, and a prompt is never cut to fit a window.
|
|
27
97
|
* What failed attempts cost is added to the final response (or error), so budgets never under-count.
|
|
28
98
|
*/
|
|
29
99
|
export declare function createFetchAi(config: AiRuntimeConfig, options?: FetchAiOptions): AiPort;
|
|
30
|
-
/**
|
|
100
|
+
/**
|
|
101
|
+
* Same formula as the web app's cost tracker: prices are per million tokens. Tokens served from the cache cost like
|
|
102
|
+
* normal input unless the model has its own cached price.
|
|
103
|
+
*/
|
|
31
104
|
export declare function estimateCost(usage: AiUsage | undefined, pricing: AiPricingConfig | undefined): number | undefined;
|
|
32
105
|
export type FinishOutcome = "complete" | "truncated" | "filtered" | "failed" | "unexpected" | "incomplete";
|
|
33
106
|
/**
|
|
@@ -36,6 +109,4 @@ export type FinishOutcome = "complete" | "truncated" | "filtered" | "failed" | "
|
|
|
36
109
|
* reason at all, only that end marker makes the reply complete.
|
|
37
110
|
*/
|
|
38
111
|
export declare function classifyFinishReason(reason: string, ended: boolean): FinishOutcome;
|
|
39
|
-
/** The request's output limit, never above the model's own limit; structured tasks get a floor. */
|
|
40
|
-
export declare function requestOutputLimit(request: Pick<AiRequest, "json" | "maxOutputTokens">, candidate: Pick<AiCandidate, "maxOutputTokens">): number | undefined;
|
|
41
112
|
//# sourceMappingURL=fetch-client.d.ts.map
|