narrarium-engine 0.0.0-stage → 0.1.0

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.
Files changed (142) hide show
  1. package/README.md +104 -2
  2. package/dist/ai/config.d.ts +69 -0
  3. package/dist/ai/config.d.ts.map +1 -0
  4. package/dist/ai/config.js +100 -0
  5. package/dist/ai/config.js.map +1 -0
  6. package/dist/ai/fetch-client.d.ts +34 -0
  7. package/dist/ai/fetch-client.d.ts.map +1 -0
  8. package/dist/ai/fetch-client.js +322 -0
  9. package/dist/ai/fetch-client.js.map +1 -0
  10. package/dist/ai/router.d.ts +20 -0
  11. package/dist/ai/router.d.ts.map +1 -0
  12. package/dist/ai/router.js +95 -0
  13. package/dist/ai/router.js.map +1 -0
  14. package/dist/ai/structured.d.ts +59 -0
  15. package/dist/ai/structured.d.ts.map +1 -0
  16. package/dist/ai/structured.js +210 -0
  17. package/dist/ai/structured.js.map +1 -0
  18. package/dist/ai/token-limit.d.ts +5 -0
  19. package/dist/ai/token-limit.d.ts.map +1 -0
  20. package/dist/ai/token-limit.js +16 -0
  21. package/dist/ai/token-limit.js.map +1 -0
  22. package/dist/ai/types.d.ts +86 -0
  23. package/dist/ai/types.d.ts.map +1 -0
  24. package/dist/ai/types.js +46 -0
  25. package/dist/ai/types.js.map +1 -0
  26. package/dist/autopilot/planner.d.ts +56 -0
  27. package/dist/autopilot/planner.d.ts.map +1 -0
  28. package/dist/autopilot/planner.js +357 -0
  29. package/dist/autopilot/planner.js.map +1 -0
  30. package/dist/autopilot/prompts.d.ts +16 -0
  31. package/dist/autopilot/prompts.d.ts.map +1 -0
  32. package/dist/autopilot/prompts.js +284 -0
  33. package/dist/autopilot/prompts.js.map +1 -0
  34. package/dist/autopilot/runner.d.ts +92 -0
  35. package/dist/autopilot/runner.d.ts.map +1 -0
  36. package/dist/autopilot/runner.js +531 -0
  37. package/dist/autopilot/runner.js.map +1 -0
  38. package/dist/autopilot/session.d.ts +84 -0
  39. package/dist/autopilot/session.d.ts.map +1 -0
  40. package/dist/autopilot/session.js +248 -0
  41. package/dist/autopilot/session.js.map +1 -0
  42. package/dist/autopilot/state.d.ts +26 -0
  43. package/dist/autopilot/state.d.ts.map +1 -0
  44. package/dist/autopilot/state.js +398 -0
  45. package/dist/autopilot/state.js.map +1 -0
  46. package/dist/autopilot/story-so-far.d.ts +51 -0
  47. package/dist/autopilot/story-so-far.d.ts.map +1 -0
  48. package/dist/autopilot/story-so-far.js +137 -0
  49. package/dist/autopilot/story-so-far.js.map +1 -0
  50. package/dist/autopilot/tasks.d.ts +42 -0
  51. package/dist/autopilot/tasks.d.ts.map +1 -0
  52. package/dist/autopilot/tasks.js +1354 -0
  53. package/dist/autopilot/tasks.js.map +1 -0
  54. package/dist/autopilot/types.d.ts +373 -0
  55. package/dist/autopilot/types.d.ts.map +1 -0
  56. package/dist/autopilot/types.js +2 -0
  57. package/dist/autopilot/types.js.map +1 -0
  58. package/dist/book/context.d.ts +55 -0
  59. package/dist/book/context.d.ts.map +1 -0
  60. package/dist/book/context.js +163 -0
  61. package/dist/book/context.js.map +1 -0
  62. package/dist/book/paths.d.ts +57 -0
  63. package/dist/book/paths.d.ts.map +1 -0
  64. package/dist/book/paths.js +92 -0
  65. package/dist/book/paths.js.map +1 -0
  66. package/dist/book/snapshot.d.ts +69 -0
  67. package/dist/book/snapshot.d.ts.map +1 -0
  68. package/dist/book/snapshot.js +139 -0
  69. package/dist/book/snapshot.js.map +1 -0
  70. package/dist/book/store.d.ts +39 -0
  71. package/dist/book/store.d.ts.map +1 -0
  72. package/dist/book/store.js +28 -0
  73. package/dist/book/store.js.map +1 -0
  74. package/dist/director/opinion.d.ts +80 -0
  75. package/dist/director/opinion.d.ts.map +1 -0
  76. package/dist/director/opinion.js +302 -0
  77. package/dist/director/opinion.js.map +1 -0
  78. package/dist/index.d.ts +33 -0
  79. package/dist/index.d.ts.map +1 -0
  80. package/dist/index.js +33 -0
  81. package/dist/index.js.map +1 -0
  82. package/dist/markdown/frontmatter.d.ts +17 -0
  83. package/dist/markdown/frontmatter.d.ts.map +1 -0
  84. package/dist/markdown/frontmatter.js +67 -0
  85. package/dist/markdown/frontmatter.js.map +1 -0
  86. package/dist/profiles/director.d.ts +35 -0
  87. package/dist/profiles/director.d.ts.map +1 -0
  88. package/dist/profiles/director.js +169 -0
  89. package/dist/profiles/director.js.map +1 -0
  90. package/dist/profiles/ghostwriter.d.ts +30 -0
  91. package/dist/profiles/ghostwriter.d.ts.map +1 -0
  92. package/dist/profiles/ghostwriter.js +140 -0
  93. package/dist/profiles/ghostwriter.js.map +1 -0
  94. package/dist/profiles/readers.d.ts +35 -0
  95. package/dist/profiles/readers.d.ts.map +1 -0
  96. package/dist/profiles/readers.js +189 -0
  97. package/dist/profiles/readers.js.map +1 -0
  98. package/dist/prompt/trust.d.ts +6 -0
  99. package/dist/prompt/trust.d.ts.map +1 -0
  100. package/dist/prompt/trust.js +12 -0
  101. package/dist/prompt/trust.js.map +1 -0
  102. package/dist/readers/evaluation.d.ts +26 -0
  103. package/dist/readers/evaluation.d.ts.map +1 -0
  104. package/dist/readers/evaluation.js +92 -0
  105. package/dist/readers/evaluation.js.map +1 -0
  106. package/dist/server/client.d.ts +90 -0
  107. package/dist/server/client.d.ts.map +1 -0
  108. package/dist/server/client.js +231 -0
  109. package/dist/server/client.js.map +1 -0
  110. package/dist/server/protocol.d.ts +225 -0
  111. package/dist/server/protocol.d.ts.map +1 -0
  112. package/dist/server/protocol.js +120 -0
  113. package/dist/server/protocol.js.map +1 -0
  114. package/dist/sync/files.d.ts +43 -0
  115. package/dist/sync/files.d.ts.map +1 -0
  116. package/dist/sync/files.js +88 -0
  117. package/dist/sync/files.js.map +1 -0
  118. package/dist/testing/index.d.ts +46 -0
  119. package/dist/testing/index.d.ts.map +1 -0
  120. package/dist/testing/index.js +202 -0
  121. package/dist/testing/index.js.map +1 -0
  122. package/dist/util/abort.d.ts +11 -0
  123. package/dist/util/abort.d.ts.map +1 -0
  124. package/dist/util/abort.js +53 -0
  125. package/dist/util/abort.js.map +1 -0
  126. package/dist/util/hash.d.ts +4 -0
  127. package/dist/util/hash.d.ts.map +1 -0
  128. package/dist/util/hash.js +11 -0
  129. package/dist/util/hash.js.map +1 -0
  130. package/dist/util/json.d.ts +20 -0
  131. package/dist/util/json.d.ts.map +1 -0
  132. package/dist/util/json.js +133 -0
  133. package/dist/util/json.js.map +1 -0
  134. package/dist/util/text.d.ts +17 -0
  135. package/dist/util/text.d.ts.map +1 -0
  136. package/dist/util/text.js +99 -0
  137. package/dist/util/text.js.map +1 -0
  138. package/dist/version.d.ts +3 -0
  139. package/dist/version.d.ts.map +1 -0
  140. package/dist/version.js +3 -0
  141. package/dist/version.js.map +1 -0
  142. package/package.json +51 -4
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # narrarium-engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared Narrarium engine: the **autopilot**, the **director**, the **simulated readers** and the **personal-server sync**. The same code runs in the Narrarium web app (browser) and in [`narrarium-server`](../server/README.md) (Node.js), so a book behaves identically wherever its autopilot runs.
4
+
5
+ The package is isomorphic: it only uses `fetch`, Web Crypto, `AbortController` and `structuredClone`, with no Node or DOM APIs.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install narrarium-engine
11
+ ```
12
+
13
+ ## What it contains
14
+
15
+ | Area | Main exports |
16
+ |---|---|
17
+ | Book access | `BookStore` (list/read/commit with compare-and-swap), `BookConflictError`, `loadBookSnapshot` |
18
+ | Autopilot | `AutopilotSession`, `AutopilotRun`, `advanceState`, `nextStep`, `applyIntervention`, `summarizeAutopilotState` |
19
+ | Director | `askDirector`, `listDirectorOpinions`, `parseDirector`, `serializeDirector`, `directorPrompt` |
20
+ | Readers | `readerPersonaSystemPrompt`, `mergeReaderPersonas`, `READER_EVALUATION_TOOL`, `chapterReaderText` |
21
+ | Ghostwriters | `parseGhostwriter`, `ghostwriterPrompt` |
22
+ | AI | `AiPort` (the only door to language models), `createFetchAi` (OpenAI, Azure OpenAI, GitHub Models), `resolveAiCandidates`, `pickAiRuntimeConfig` |
23
+ | Personal server | `NarrariumServerClient`, `pairWithServer`, `verifyServerIdentity`, `remoteBookStore`, protocol types (scopes, pairing, updates), `ServerSentEventParser` |
24
+ | Sync | `planFileSync`, `syncBookStores` (three-way sync of two book stores) |
25
+ | Testing | `narrarium-engine/testing`: `MemoryBookStore`, `seedBookFiles`, `createFakeAutopilotAi` |
26
+
27
+ ## Running the autopilot
28
+
29
+ A host provides two adapters: a `BookStore` over the book files and an `AiPort` over its AI configuration.
30
+
31
+ ```ts
32
+ import { AutopilotSession, createFetchAi, pickAiRuntimeConfig } from "narrarium-engine";
33
+
34
+ const session = new AutopilotSession({
35
+ bookId: "my-book",
36
+ store, // your BookStore
37
+ ai: createFetchAi(pickAiRuntimeConfig(settings)),
38
+ host: "server",
39
+ hostLabel: "my laptop",
40
+ });
41
+
42
+ session.subscribe((event) => console.log(event.type, event));
43
+ await session.start({
44
+ brief: { idea: "A harbor town built on glass hides a lie.", targetChapters: 12 },
45
+ options: { pauseAfterPlan: true },
46
+ });
47
+ await session.waitForIdle();
48
+ ```
49
+
50
+ 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
+
52
+ ### Pipeline
53
+
54
+ 1. **Concept** — story design, world context, characters, locations, factions and secrets (skipped when the book already has a design or prose).
55
+ 2. **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.
56
+ 3. **Per chapter** — scene plan, prose scene by scene (streamed), then the review cycle:
57
+ - blind simulated readers (no canon, no secrets) and a panel summary;
58
+ - specialists (continuity, canon, secrets, timeline, voice, style, pacing) with evidence anchored in the text;
59
+ - the **director** accepts or rejects every finding; the software, not the model, derives the repairs;
60
+ - accepted fixes are applied; a new round verifies them, up to the director's round limit;
61
+ - consolidation: chapter summary, recap, story so far, `plot.md`.
62
+ 4. **Final** — the director's judgement on the whole book.
63
+
64
+ ### Author interventions
65
+
66
+ `session.intervene({ scope, text, interrupt? })`:
67
+
68
+ - `next_step` — delivered once to the next writing step;
69
+ - `from_now` — a permanent rule for every following step, the director included;
70
+ - `rewrite` — the director picks the written scenes that must change; they are rewritten and reviewed again.
71
+
72
+ With `interrupt: true` the running step is abandoned and repeated with the new instruction.
73
+
74
+ ## The director
75
+
76
+ The director is the author's stand-in: it approves plans and chapters during the autopilot and can be asked at any time what it thinks of the book, a chapter or a scene:
77
+
78
+ ```ts
79
+ import { askDirector } from "narrarium-engine";
80
+
81
+ const { opinion } = await askDirector({ store, ai, target: { kind: "chapter", chapter: "003-the-storm" }, question: "Is the ending strong enough?", save: true });
82
+ ```
83
+
84
+ 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
+
86
+ ## Files in the book
87
+
88
+ | Path | Content |
89
+ |---|---|
90
+ | `director.md` | Director profile (`type: director`). |
91
+ | `autopilot/state.json` | Autopilot state: brief, options, plan, review cycle, rules, interventions, statistics. |
92
+ | `autopilot/activity.json` | Last 200 activities (what, why, next, result, model, tokens, cost). |
93
+ | `autopilot/plan.md` | Human-readable mirror of the plan. |
94
+ | `evaluations/director/` | Director opinions (`book.md`, `chapters/<chapter>.md`, `paragraphs/<chapter>/<paragraph>.md`). |
95
+ | `evaluations/readers/` | Simulated reader evaluations, in the same format as the web app. |
96
+
97
+ ## AI tasks
98
+
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` (scene summaries). Missing routes fall back to models tagged `default`.
100
+
101
+ ## Tests
102
+
103
+ ```bash
104
+ npm test -w narrarium-engine
105
+ ```
@@ -0,0 +1,69 @@
1
+ export type AiProviderKind = "azure_openai" | "openai" | "github_models" | "m365_copilot";
2
+ export interface AiPricingConfig {
3
+ inputPerMTok?: number;
4
+ cachedPerMTok?: number;
5
+ outputPerMTok?: number;
6
+ }
7
+ export interface AiChatModelConfig {
8
+ id: string;
9
+ name: string;
10
+ underlyingModel?: string;
11
+ capabilities: string[];
12
+ supportsToolCalls?: boolean;
13
+ maxInputTokens?: number;
14
+ maxOutputTokens?: number;
15
+ pricing?: AiPricingConfig;
16
+ }
17
+ export interface AiIntegrationConfig {
18
+ id: string;
19
+ name: string;
20
+ provider: AiProviderKind;
21
+ endpoint?: string;
22
+ apiKey: string;
23
+ apiVersion?: string;
24
+ requestTimeoutMs?: number;
25
+ chatModels?: AiChatModelConfig[];
26
+ /** @deprecated legacy single-model fields, still honored. */
27
+ modelWriting?: string;
28
+ modelReview?: string;
29
+ pricing?: AiPricingConfig;
30
+ }
31
+ export interface AiRouteTarget {
32
+ integrationId: string;
33
+ model: string;
34
+ }
35
+ export interface AiTaskRoute {
36
+ primary?: AiRouteTarget;
37
+ fallbacks?: AiRouteTarget[];
38
+ }
39
+ /**
40
+ * The subset of the web app's AI router settings needed to run chat tasks.
41
+ * The same JSON is configured in the browser and, with consent, sent to a personal server.
42
+ */
43
+ export interface AiRuntimeConfig {
44
+ aiIntegrations: AiIntegrationConfig[];
45
+ taskRouting?: Record<string, AiTaskRoute | undefined>;
46
+ defaultWritingIntegrationId?: string;
47
+ defaultReviewIntegrationId?: string;
48
+ costCurrency?: string;
49
+ maxCandidates?: number;
50
+ }
51
+ /** Extract and sanitize the AI configuration from a web-app settings object (or a server config file). */
52
+ export declare function pickAiRuntimeConfig(settings: unknown): AiRuntimeConfig;
53
+ export interface RedactedAiIntegration {
54
+ id: string;
55
+ name: string;
56
+ provider: AiProviderKind;
57
+ endpoint?: string;
58
+ hasApiKey: boolean;
59
+ models: Array<{
60
+ name: string;
61
+ capabilities: string[];
62
+ }>;
63
+ }
64
+ /** Safe view of a configuration: never exposes API keys. */
65
+ export declare function redactAiRuntimeConfig(config: AiRuntimeConfig): {
66
+ integrations: RedactedAiIntegration[];
67
+ routedTasks: string[];
68
+ };
69
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +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,QAAQ,EAAE,cAAc,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,UAAU,CAAC,EAAE,iBAAiB,EAAE,CAAC;IACjC,6DAA6D;IAC7D,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,eAAe,CAAC;CAC3B;AAED,MAAM,WAAW,aAAa;IAC5B,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,CAAC,EAAE,aAAa,CAAC;IACxB,SAAS,CAAC,EAAE,aAAa,EAAE,CAAC;CAC7B;AAED;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,cAAc,EAAE,mBAAmB,EAAE,CAAC;IACtC,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,GAAG,SAAS,CAAC,CAAC;IACtD,2BAA2B,CAAC,EAAE,MAAM,CAAC;IACrC,0BAA0B,CAAC,EAAE,MAAM,CAAC;IACpC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAiCD,0GAA0G;AAC1G,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,OAAO,GAAG,eAAe,CAsDtE;AAED,MAAM,WAAW,qBAAqB;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,cAAc,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,OAAO,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC,CAAC;CACzD;AAED,4DAA4D;AAC5D,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,eAAe,GAAG;IAAE,YAAY,EAAE,qBAAqB,EAAE,CAAC;IAAC,WAAW,EAAE,MAAM,EAAE,CAAA;CAAE,CAY/H"}
@@ -0,0 +1,100 @@
1
+ const PROVIDERS = ["azure_openai", "openai", "github_models", "m365_copilot"];
2
+ function record(value) {
3
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
4
+ }
5
+ function text(value) {
6
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
7
+ }
8
+ function positive(value) {
9
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
10
+ }
11
+ function pricing(value) {
12
+ const source = record(value);
13
+ const output = {};
14
+ for (const key of ["inputPerMTok", "cachedPerMTok", "outputPerMTok"]) {
15
+ const amount = source[key];
16
+ if (typeof amount === "number" && Number.isFinite(amount) && amount >= 0)
17
+ output[key] = amount;
18
+ }
19
+ return Object.keys(output).length ? output : undefined;
20
+ }
21
+ function target(value) {
22
+ const source = record(value);
23
+ const integrationId = text(source.integrationId);
24
+ const model = text(source.model);
25
+ return integrationId && model ? { integrationId, model } : undefined;
26
+ }
27
+ /** Extract and sanitize the AI configuration from a web-app settings object (or a server config file). */
28
+ export function pickAiRuntimeConfig(settings) {
29
+ const source = record(settings);
30
+ const integrations = [];
31
+ for (const entry of Array.isArray(source.aiIntegrations) ? source.aiIntegrations : []) {
32
+ const item = record(entry);
33
+ const id = text(item.id);
34
+ const provider = PROVIDERS.includes(item.provider) ? item.provider : undefined;
35
+ if (!id || !provider)
36
+ continue;
37
+ const chatModels = [];
38
+ for (const modelEntry of Array.isArray(item.chatModels) ? item.chatModels : []) {
39
+ const model = record(modelEntry);
40
+ const name = text(model.name);
41
+ if (!name)
42
+ continue;
43
+ chatModels.push({
44
+ id: text(model.id) ?? name,
45
+ name,
46
+ underlyingModel: text(model.underlyingModel),
47
+ capabilities: Array.isArray(model.capabilities) ? model.capabilities.filter((capability) => typeof capability === "string") : [],
48
+ supportsToolCalls: typeof model.supportsToolCalls === "boolean" ? model.supportsToolCalls : undefined,
49
+ maxInputTokens: positive(model.maxInputTokens),
50
+ maxOutputTokens: positive(model.maxOutputTokens),
51
+ pricing: pricing(model.pricing),
52
+ });
53
+ }
54
+ integrations.push({
55
+ id,
56
+ name: text(item.name) ?? provider,
57
+ provider,
58
+ endpoint: text(item.endpoint),
59
+ apiKey: typeof item.apiKey === "string" ? item.apiKey.trim() : "",
60
+ apiVersion: text(item.apiVersion),
61
+ requestTimeoutMs: positive(item.requestTimeoutMs),
62
+ chatModels,
63
+ modelWriting: text(item.modelWriting),
64
+ modelReview: text(item.modelReview),
65
+ pricing: pricing(item.pricing),
66
+ });
67
+ }
68
+ const taskRouting = {};
69
+ for (const [task, routeValue] of Object.entries(record(source.taskRouting))) {
70
+ const route = record(routeValue);
71
+ const primary = target(route.primary);
72
+ const fallbacks = (Array.isArray(route.fallbacks) ? route.fallbacks : []).map(target).filter((entry) => Boolean(entry));
73
+ if (primary || fallbacks.length)
74
+ taskRouting[task] = { primary, fallbacks };
75
+ }
76
+ const execution = record(source.routingExecution);
77
+ return {
78
+ aiIntegrations: integrations,
79
+ taskRouting,
80
+ defaultWritingIntegrationId: text(source.defaultWritingIntegrationId),
81
+ defaultReviewIntegrationId: text(source.defaultReviewIntegrationId),
82
+ costCurrency: text(source.costCurrency),
83
+ maxCandidates: positive(execution.maxCandidates) ?? positive(source.maxCandidates),
84
+ };
85
+ }
86
+ /** Safe view of a configuration: never exposes API keys. */
87
+ export function redactAiRuntimeConfig(config) {
88
+ return {
89
+ integrations: config.aiIntegrations.map((integration) => ({
90
+ id: integration.id,
91
+ name: integration.name,
92
+ provider: integration.provider,
93
+ endpoint: integration.endpoint,
94
+ hasApiKey: Boolean(integration.apiKey),
95
+ models: (integration.chatModels ?? []).map((model) => ({ name: model.name, capabilities: model.capabilities })),
96
+ })),
97
+ routedTasks: Object.keys(config.taskRouting ?? {}).sort(),
98
+ };
99
+ }
100
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/ai/config.ts"],"names":[],"mappings":"AAyDA,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,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Q,EAAE,WAAW,CAAC,QAAQ;YAC9B,SAAS,EAAE,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC;YACtC,MAAM,EAAE,CAAC,WAAW,CAAC,UAAU,IAAI,EAAE,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;KAC1D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,34 @@
1
+ import type { AiPricingConfig, AiRuntimeConfig } from "./config.js";
2
+ import { type AiCandidate } from "./router.js";
3
+ import { type AiPort, type AiRequest, type AiUsage } from "./types.js";
4
+ export declare const GITHUB_MODELS_BASE_URL = "https://models.github.ai";
5
+ /** Reasoning models spend output tokens before replying: small structured tasks get at least this limit. */
6
+ export declare const STRUCTURED_OUTPUT_FLOOR = 4096;
7
+ export interface FetchAiAttempt {
8
+ label: string;
9
+ capability: string;
10
+ provider: string;
11
+ model: string;
12
+ integrationId: string;
13
+ index: number;
14
+ }
15
+ export interface FetchAiOptions {
16
+ fetch?: typeof fetch;
17
+ /** Origin of GitHub Models (or of a proxy forwarding `/inference`). */
18
+ githubModelsBaseUrl?: string;
19
+ /** Used when an integration has no request timeout. */
20
+ defaultTimeoutMs?: number;
21
+ onAttempt?: (attempt: FetchAiAttempt) => void;
22
+ }
23
+ /**
24
+ * OpenAI-compatible chat client built on `fetch`, usable from Node and browsers.
25
+ * Supports OpenAI and compatible endpoints, Azure OpenAI and GitHub Models, streaming text,
26
+ * forced function calls for structured output, and ordered fallbacks between candidates.
27
+ * What failed attempts cost is added to the final response (or error), so budgets never under-count.
28
+ */
29
+ export declare function createFetchAi(config: AiRuntimeConfig, options?: FetchAiOptions): AiPort;
30
+ /** Same formula as the web app's cost tracker: prices are per million tokens. */
31
+ export declare function estimateCost(usage: AiUsage | undefined, pricing: AiPricingConfig | undefined): number | undefined;
32
+ /** The request's output limit, never above the model's own limit; structured tasks get a floor. */
33
+ export declare function requestOutputLimit(request: Pick<AiRequest, "json" | "maxOutputTokens">, candidate: Pick<AiCandidate, "maxOutputTokens">): number | undefined;
34
+ //# sourceMappingURL=fetch-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-client.d.ts","sourceRoot":"","sources":["../../src/ai/fetch-client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAuB,eAAe,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACzF,OAAO,EAAuB,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAGpE,OAAO,EAAgF,KAAK,MAAM,EAA+B,KAAK,SAAS,EAAmB,KAAK,OAAO,EAAE,MAAM,YAAY,CAAC;AAEnM,eAAO,MAAM,sBAAsB,6BAA6B,CAAC;AAEjE,4GAA4G;AAC5G,eAAO,MAAM,uBAAuB,OAAO,CAAC;AAE5C,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,cAAc;IAC7B,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,uEAAuE;IACvE,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,uDAAuD;IACvD,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;CAC/C;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,eAAe,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CA2B3F;AAuED,iFAAiF;AACjF,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,EAAE,OAAO,EAAE,eAAe,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAMjH;AA4DD,mGAAmG;AACnG,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,iBAAiB,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,WAAW,EAAE,iBAAiB,CAAC,GAAG,MAAM,GAAG,SAAS,CAG5J"}
@@ -0,0 +1,322 @@
1
+ import { isAbortError, linkedSignal } from "../util/abort.js";
2
+ import { resolveAiCandidates } from "./router.js";
3
+ import { forcedToolChoice, splitReasoningBlock, structuredFromReply } from "./structured.js";
4
+ import { completionTokenLimit, isReasoningModel } from "./token-limit.js";
5
+ import { AiProviderError, AiReplyRejectedError, AiUnavailableError } from "./types.js";
6
+ export const GITHUB_MODELS_BASE_URL = "https://models.github.ai";
7
+ const DEFAULT_TIMEOUT_MS = 600_000;
8
+ /** Reasoning models spend output tokens before replying: small structured tasks get at least this limit. */
9
+ export const STRUCTURED_OUTPUT_FLOOR = 4096;
10
+ /**
11
+ * OpenAI-compatible chat client built on `fetch`, usable from Node and browsers.
12
+ * Supports OpenAI and compatible endpoints, Azure OpenAI and GitHub Models, streaming text,
13
+ * forced function calls for structured output, and ordered fallbacks between candidates.
14
+ * What failed attempts cost is added to the final response (or error), so budgets never under-count.
15
+ */
16
+ export function createFetchAi(config, options = {}) {
17
+ return {
18
+ async complete(request) {
19
+ const candidates = resolveAiCandidates(config, request.capability);
20
+ if (!candidates.length)
21
+ throw new AiUnavailableError(request.capability);
22
+ let lastError = null;
23
+ const spent = {};
24
+ for (const [index, candidate] of candidates.entries()) {
25
+ request.signal?.throwIfAborted();
26
+ options.onAttempt?.({ label: request.label, capability: request.capability, provider: candidate.integration.provider, model: candidate.model, integrationId: candidate.integration.id, index });
27
+ try {
28
+ return withSpent(await callCandidate(config, candidate, request, options), spent);
29
+ }
30
+ catch (error) {
31
+ if (request.signal?.aborted && isAbortError(error))
32
+ throw error;
33
+ addSpent(spent, error);
34
+ lastError = error;
35
+ request.onText?.("");
36
+ }
37
+ }
38
+ if (lastError instanceof AiProviderError) {
39
+ lastError.usage = spent.usage ?? lastError.usage;
40
+ lastError.cost = spent.cost ?? lastError.cost;
41
+ throw lastError;
42
+ }
43
+ throw lastError instanceof Error ? lastError : new AiProviderError("All AI candidates failed.");
44
+ },
45
+ };
46
+ }
47
+ function sumUsage(left, right) {
48
+ if (!left)
49
+ return right;
50
+ if (!right)
51
+ return left;
52
+ return {
53
+ inputTokens: left.inputTokens + right.inputTokens,
54
+ outputTokens: left.outputTokens + right.outputTokens,
55
+ cachedInputTokens: left.cachedInputTokens + right.cachedInputTokens,
56
+ };
57
+ }
58
+ function addSpent(spent, error) {
59
+ if (!(error instanceof AiProviderError))
60
+ return;
61
+ spent.usage = sumUsage(spent.usage, error.usage);
62
+ if (error.cost !== undefined)
63
+ spent.cost = (spent.cost ?? 0) + error.cost;
64
+ }
65
+ function withSpent(response, spent) {
66
+ if (!spent.usage && spent.cost === undefined)
67
+ return response;
68
+ return {
69
+ ...response,
70
+ usage: sumUsage(response.usage, spent.usage),
71
+ cost: spent.cost === undefined ? response.cost : (response.cost ?? 0) + spent.cost,
72
+ };
73
+ }
74
+ function requestTarget(integration, model, githubModelsBaseUrl) {
75
+ const key = integration.apiKey.trim();
76
+ if (integration.provider === "azure_openai") {
77
+ const base = (integration.endpoint ?? "").trim().replace(/\/+$/, "");
78
+ if (!base)
79
+ throw new AiProviderError(`Azure OpenAI integration "${integration.name}" has no endpoint.`);
80
+ const url = /\/openai\/v1$/i.test(base)
81
+ ? `${base}/chat/completions`
82
+ : `${base}/openai/deployments/${encodeURIComponent(model)}/chat/completions?api-version=${encodeURIComponent(integration.apiVersion || "2024-10-21")}`;
83
+ return { url, headers: key ? { "api-key": key } : {} };
84
+ }
85
+ if (integration.provider === "github_models") {
86
+ return { url: `${githubModelsBaseUrl.replace(/\/+$/, "")}/inference/chat/completions`, headers: key ? { authorization: `Bearer ${key}` } : {} };
87
+ }
88
+ if (integration.provider === "openai") {
89
+ const base = (integration.endpoint || "https://api.openai.com/v1").trim().replace(/\/+$/, "");
90
+ return { url: `${base}/chat/completions`, headers: key ? { authorization: `Bearer ${key}` } : {} };
91
+ }
92
+ throw new AiProviderError(`Provider ${integration.provider} cannot run chat tasks outside Microsoft 365.`);
93
+ }
94
+ function jsonInstruction(schema) {
95
+ return `Reply with ONLY one JSON object, without code fences or commentary, matching this JSON schema (${schema.name}: ${schema.description}):\n${JSON.stringify(schema.parameters)}`;
96
+ }
97
+ function normalizeUsage(value) {
98
+ if (!value || typeof value !== "object")
99
+ return undefined;
100
+ const usage = value;
101
+ return {
102
+ inputTokens: usage.prompt_tokens ?? 0,
103
+ outputTokens: usage.completion_tokens ?? 0,
104
+ cachedInputTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,
105
+ };
106
+ }
107
+ /** Same formula as the web app's cost tracker: prices are per million tokens. */
108
+ export function estimateCost(usage, pricing) {
109
+ if (!usage || !pricing)
110
+ return undefined;
111
+ const billedInput = Math.max(0, usage.inputTokens - usage.cachedInputTokens);
112
+ return (billedInput / 1_000_000) * (pricing.inputPerMTok ?? 0)
113
+ + (usage.cachedInputTokens / 1_000_000) * (pricing.cachedPerMTok ?? 0)
114
+ + (usage.outputTokens / 1_000_000) * (pricing.outputPerMTok ?? 0);
115
+ }
116
+ async function providerError(response, provider, model) {
117
+ let detail = "";
118
+ try {
119
+ const raw = (await response.text()).slice(0, 2000);
120
+ try {
121
+ const parsed = JSON.parse(raw);
122
+ const message = typeof parsed.error === "string" ? parsed.error : parsed.error?.message ?? parsed.message;
123
+ detail = typeof message === "string" ? message : raw;
124
+ }
125
+ catch {
126
+ detail = raw;
127
+ }
128
+ }
129
+ catch {
130
+ detail = response.statusText;
131
+ }
132
+ const retryable = response.status === 408 || response.status === 409 || response.status === 429 || response.status >= 500;
133
+ return new AiProviderError(`${provider} ${model}: HTTP ${response.status}${detail ? ` — ${detail.replace(/\s+/g, " ").slice(0, 400)}` : ""}`, response.status, retryable);
134
+ }
135
+ /** Reads server-sent events; resolves `true` when the provider closed the stream with `[DONE]`. */
136
+ async function readEventStream(response, onData) {
137
+ if (!response.body)
138
+ throw new AiProviderError("The provider returned an empty stream.", undefined, true);
139
+ const reader = response.body.getReader();
140
+ const decoder = new TextDecoder();
141
+ let buffer = "";
142
+ const flushLine = (line) => {
143
+ const clean = line.replace(/\r$/, "");
144
+ if (!clean.startsWith("data:"))
145
+ return false;
146
+ const data = clean.slice(5).trimStart();
147
+ if (data === "[DONE]")
148
+ return true;
149
+ if (data)
150
+ onData(data);
151
+ return false;
152
+ };
153
+ for (;;) {
154
+ const { value, done } = await reader.read();
155
+ if (done)
156
+ break;
157
+ buffer += decoder.decode(value, { stream: true });
158
+ let newline = buffer.indexOf("\n");
159
+ while (newline >= 0) {
160
+ const line = buffer.slice(0, newline);
161
+ buffer = buffer.slice(newline + 1);
162
+ if (flushLine(line)) {
163
+ await reader.cancel().catch(() => undefined);
164
+ return true;
165
+ }
166
+ newline = buffer.indexOf("\n");
167
+ }
168
+ }
169
+ buffer += decoder.decode();
170
+ return buffer.trim() ? flushLine(buffer) : false;
171
+ }
172
+ /** Characters of reasoning a reply carried. Only the count is kept, never the reasoning itself. */
173
+ function reasoningLength(source) {
174
+ if (!source || typeof source !== "object")
175
+ return 0;
176
+ const { reasoning_content: content, reasoning } = source;
177
+ return (typeof content === "string" ? content.length : 0) + (typeof reasoning === "string" ? reasoning.length : 0);
178
+ }
179
+ /** The request's output limit, never above the model's own limit; structured tasks get a floor. */
180
+ export function requestOutputLimit(request, candidate) {
181
+ const requested = request.json && request.maxOutputTokens ? Math.max(request.maxOutputTokens, STRUCTURED_OUTPUT_FLOOR) : request.maxOutputTokens;
182
+ return requested && candidate.maxOutputTokens ? Math.min(requested, candidate.maxOutputTokens) : requested ?? candidate.maxOutputTokens;
183
+ }
184
+ async function callCandidate(config, candidate, request, options) {
185
+ const { integration, model } = candidate;
186
+ const label = `${integration.provider} ${model}`;
187
+ const target = requestTarget(integration, model, options.githubModelsBaseUrl ?? GITHUB_MODELS_BASE_URL);
188
+ const useTools = Boolean(request.json) && candidate.supportsToolCalls !== false;
189
+ const stream = Boolean(request.onText) && !request.json;
190
+ const system = request.json && !useTools ? `${request.system}\n\n${jsonInstruction(request.json)}` : request.system;
191
+ const body = {
192
+ model,
193
+ messages: [
194
+ { role: "system", content: system },
195
+ { role: "user", content: request.user },
196
+ ],
197
+ ...completionTokenLimit(integration.provider, model, requestOutputLimit(request, candidate), candidate.underlyingModel),
198
+ };
199
+ if (request.temperature !== undefined && !isReasoningModel(integration.provider, model, candidate.underlyingModel))
200
+ body.temperature = request.temperature;
201
+ if (useTools && request.json) {
202
+ body.tools = [{ type: "function", function: request.json }];
203
+ body.tool_choice = forcedToolChoice(integration.provider, integration.apiVersion, request.json.name);
204
+ }
205
+ if (stream) {
206
+ body.stream = true;
207
+ body.stream_options = { include_usage: true };
208
+ }
209
+ const fetchImpl = options.fetch ?? fetch;
210
+ const timer = linkedSignal(request.signal, integration.requestTimeoutMs ?? options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS);
211
+ try {
212
+ let response;
213
+ try {
214
+ response = await fetchImpl(target.url, {
215
+ method: "POST",
216
+ headers: { "content-type": "application/json", accept: stream ? "text/event-stream" : "application/json", ...target.headers },
217
+ body: JSON.stringify(body),
218
+ signal: timer.signal,
219
+ });
220
+ }
221
+ catch (error) {
222
+ if (request.signal?.aborted)
223
+ throw error;
224
+ throw new AiProviderError(`${label}: ${timer.timedOut() ? "request timed out" : error instanceof Error ? error.message : String(error)}`, undefined, true);
225
+ }
226
+ if (!response.ok)
227
+ throw await providerError(response, integration.provider, model);
228
+ let text = "";
229
+ let toolArguments = "";
230
+ let usage;
231
+ let finishReason = "";
232
+ let reasoningCharacters = 0;
233
+ let complete = true;
234
+ const details = (extra = {}) => ({
235
+ usage,
236
+ cost: estimateCost(usage, candidate.pricing),
237
+ currency: config.costCurrency,
238
+ model,
239
+ provider: integration.provider,
240
+ integrationId: integration.id,
241
+ ...extra,
242
+ });
243
+ try {
244
+ if (stream) {
245
+ const sawDone = await readEventStream(response, (data) => {
246
+ let chunk;
247
+ try {
248
+ chunk = JSON.parse(data);
249
+ }
250
+ catch {
251
+ return;
252
+ }
253
+ const delta = chunk.choices?.[0]?.delta;
254
+ reasoningCharacters += reasoningLength(delta);
255
+ if (delta?.content) {
256
+ text += delta.content;
257
+ request.onText?.(text);
258
+ }
259
+ const reason = chunk.choices?.find((choice) => choice.finish_reason)?.finish_reason;
260
+ if (reason)
261
+ finishReason = reason;
262
+ if (chunk.usage)
263
+ usage = normalizeUsage(chunk.usage);
264
+ });
265
+ complete = sawDone || Boolean(finishReason);
266
+ }
267
+ else {
268
+ const payload = await response.json();
269
+ const choice = payload.choices?.[0];
270
+ text = typeof choice?.message?.content === "string" ? choice.message.content : "";
271
+ toolArguments = choice?.message?.tool_calls?.find((call) => typeof call.function?.arguments === "string")?.function?.arguments ?? "";
272
+ finishReason = choice?.finish_reason ?? "";
273
+ reasoningCharacters = reasoningLength(choice?.message);
274
+ usage = normalizeUsage(payload.usage);
275
+ }
276
+ }
277
+ catch (error) {
278
+ if (request.signal?.aborted || error instanceof AiProviderError)
279
+ throw error;
280
+ throw new AiProviderError(`${label}: ${timer.timedOut() ? "request timed out" : "the reply could not be read"}.`, undefined, true, details());
281
+ }
282
+ if (!complete)
283
+ throw new AiProviderError(`${label}: the stream ended before the reply was complete.`, undefined, true, details());
284
+ if (finishReason === "content_filter")
285
+ throw new AiProviderError(`${label}: the provider filtered the reply content.`, undefined, false, details());
286
+ // Some local servers leave the reasoning in the content as a leading <think> block: it is not the reply.
287
+ const inline = splitReasoningBlock(text);
288
+ text = inline.reply;
289
+ reasoningCharacters += inline.reasoningCharacters;
290
+ const answered = Boolean(text.trim() || toolArguments.trim());
291
+ if (finishReason === "length") {
292
+ throw new AiProviderError(`${label}: ${!answered && reasoningCharacters > 0 ? "the model used its output limit while reasoning, before writing the reply" : "the reply was cut by the output token limit"}. Nothing was applied.`, undefined, false, details({ truncated: true }));
293
+ }
294
+ if (!answered)
295
+ throw new AiProviderError(`${label}: ${reasoningCharacters > 0 ? "the model finished after reasoning without a reply" : "the provider returned an empty reply"}.`, undefined, true, details());
296
+ let json;
297
+ if (request.json) {
298
+ try {
299
+ json = structuredFromReply({ toolArguments, content: text, schema: request.json });
300
+ }
301
+ catch (error) {
302
+ throw new AiReplyRejectedError(`${label}: ${error instanceof Error ? error.message : "invalid structured reply"}`, details());
303
+ }
304
+ if (!text)
305
+ text = toolArguments;
306
+ }
307
+ return {
308
+ text,
309
+ json,
310
+ usage,
311
+ model,
312
+ provider: integration.provider,
313
+ integrationId: integration.id,
314
+ cost: estimateCost(usage, candidate.pricing),
315
+ currency: config.costCurrency,
316
+ };
317
+ }
318
+ finally {
319
+ timer.dispose();
320
+ }
321
+ }
322
+ //# sourceMappingURL=fetch-client.js.map