@connextar/house 0.23.1 → 0.24.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 (186) hide show
  1. package/README.md +55 -13
  2. package/dist/analytics/browser.d.ts +1 -0
  3. package/dist/analytics/browser.d.ts.map +1 -1
  4. package/dist/analytics/browser.js +22 -5
  5. package/dist/analytics/browser.js.map +1 -1
  6. package/dist/analytics/config.d.ts +5 -0
  7. package/dist/analytics/config.d.ts.map +1 -1
  8. package/dist/analytics/config.js +4 -1
  9. package/dist/analytics/config.js.map +1 -1
  10. package/dist/analytics/posthog-extensions.d.ts +19 -0
  11. package/dist/analytics/posthog-extensions.d.ts.map +1 -0
  12. package/dist/analytics/posthog-extensions.js +19 -0
  13. package/dist/analytics/posthog-extensions.js.map +1 -0
  14. package/dist/analytics/react.d.ts.map +1 -1
  15. package/dist/analytics/react.js +4 -2
  16. package/dist/analytics/react.js.map +1 -1
  17. package/dist/analytics/redact.d.ts.map +1 -1
  18. package/dist/analytics/redact.js +6 -1
  19. package/dist/analytics/redact.js.map +1 -1
  20. package/dist/house.css +19 -0
  21. package/package.json +17 -3
  22. package/src/account/data-contract.ts +112 -0
  23. package/src/account/index.ts +11 -0
  24. package/src/admin/access.ts +267 -0
  25. package/src/admin/audit.ts +238 -0
  26. package/src/admin/bootstrap.ts +220 -0
  27. package/src/admin/client-index.ts +19 -0
  28. package/src/admin/client.tsx +187 -0
  29. package/src/admin/index.ts +91 -0
  30. package/src/admin/proof.ts +155 -0
  31. package/src/admin/second-factor-index.ts +16 -0
  32. package/src/admin/second-factor.ts +403 -0
  33. package/src/admin/testing-index.ts +13 -0
  34. package/src/admin/testing.ts +299 -0
  35. package/src/admin/view-as.ts +511 -0
  36. package/src/ai/config-index.ts +40 -0
  37. package/src/ai/config.ts +176 -0
  38. package/src/ai/images.ts +18 -0
  39. package/src/ai/index.ts +21 -0
  40. package/src/ai/pricing.ts +107 -0
  41. package/src/ai/provider.ts +403 -0
  42. package/src/analytics/browser.ts +400 -0
  43. package/src/analytics/client-index.ts +12 -0
  44. package/src/analytics/config.ts +89 -0
  45. package/src/analytics/index.ts +17 -0
  46. package/src/analytics/ingest.ts +81 -0
  47. package/src/analytics/posthog-extensions.ts +19 -0
  48. package/src/analytics/react-index.ts +16 -0
  49. package/src/analytics/react.tsx +241 -0
  50. package/src/analytics/redact.ts +146 -0
  51. package/src/analytics/server-index.ts +17 -0
  52. package/src/analytics/server.ts +277 -0
  53. package/src/auth/index.ts +30 -0
  54. package/src/auth/second-factor-index.ts +16 -0
  55. package/src/auth/second-factor-next.ts +136 -0
  56. package/src/auth/second-factor-routes.ts +40 -0
  57. package/src/auth/second-factor.ts +226 -0
  58. package/src/auth/step-up-client-index.ts +13 -0
  59. package/src/auth/step-up-client.ts +23 -0
  60. package/src/auth/step-up-index.ts +19 -0
  61. package/src/auth/step-up-routes.ts +99 -0
  62. package/src/auth/step-up.ts +432 -0
  63. package/src/auth/two-factor-policy.ts +112 -0
  64. package/src/changelog/changelog.tsx +367 -0
  65. package/src/changelog/index.ts +12 -0
  66. package/src/editor/block-handle.tsx +312 -0
  67. package/src/editor/blocks.ts +169 -0
  68. package/src/editor/bubble-toolbar.tsx +208 -0
  69. package/src/editor/collapsible.ts +159 -0
  70. package/src/editor/content-index.ts +1 -0
  71. package/src/editor/content.tsx +343 -0
  72. package/src/editor/editor.tsx +333 -0
  73. package/src/editor/emoji-index.ts +1 -0
  74. package/src/editor/emoji-picker.tsx +114 -0
  75. package/src/editor/emoji.ts +436 -0
  76. package/src/editor/index.ts +6 -0
  77. package/src/editor/sections.ts +83 -0
  78. package/src/editor/suggestion-popup.tsx +136 -0
  79. package/src/editor/suggestions.ts +309 -0
  80. package/src/editor/ui.tsx +171 -0
  81. package/src/errors/error-shell.tsx +72 -0
  82. package/src/errors/global-error-shell.tsx +116 -0
  83. package/src/errors/index.ts +2 -0
  84. package/src/grid/columns.ts +48 -0
  85. package/src/grid/compare.ts +35 -0
  86. package/src/grid/hidden-columns.ts +95 -0
  87. package/src/grid/index.ts +27 -0
  88. package/src/grid/use-grid.ts +282 -0
  89. package/src/grid/views.ts +70 -0
  90. package/src/guides/guide-article.tsx +92 -0
  91. package/src/guides/guide-figure-zoom.tsx +533 -0
  92. package/src/guides/guide-figure.tsx +68 -0
  93. package/src/guides/guide-toc.tsx +133 -0
  94. package/src/guides/guides-landing.tsx +57 -0
  95. package/src/guides/guides-search.tsx +160 -0
  96. package/src/guides/guides-shell.tsx +60 -0
  97. package/src/guides/guides-sidebar.tsx +93 -0
  98. package/src/guides/index.ts +28 -0
  99. package/src/guides/library.ts +165 -0
  100. package/src/health/health.ts +115 -0
  101. package/src/health/index.ts +11 -0
  102. package/src/internal/cx.ts +4 -0
  103. package/src/internal/next-link.ts +23 -0
  104. package/src/jobs/counts.ts +151 -0
  105. package/src/jobs/cron-auth.ts +60 -0
  106. package/src/jobs/health.ts +315 -0
  107. package/src/jobs/idle.ts +86 -0
  108. package/src/jobs/index.ts +120 -0
  109. package/src/jobs/job-health-list.tsx +316 -0
  110. package/src/jobs/next-index.ts +4 -0
  111. package/src/jobs/next.ts +65 -0
  112. package/src/jobs/prisma-index.ts +12 -0
  113. package/src/jobs/prisma.ts +170 -0
  114. package/src/jobs/prune.ts +79 -0
  115. package/src/jobs/react-index.ts +35 -0
  116. package/src/jobs/registry.ts +189 -0
  117. package/src/jobs/scheduler.ts +437 -0
  118. package/src/jobs/store.ts +212 -0
  119. package/src/jobs/windows.ts +157 -0
  120. package/src/maintenance/core.ts +270 -0
  121. package/src/maintenance/gate.ts +171 -0
  122. package/src/maintenance/index.ts +40 -0
  123. package/src/maintenance/page.ts +76 -0
  124. package/src/maintenance/proxy.ts +88 -0
  125. package/src/maintenance/react-index.ts +7 -0
  126. package/src/maintenance/react.tsx +190 -0
  127. package/src/maintenance/route.ts +82 -0
  128. package/src/maintenance/unavailable.ts +61 -0
  129. package/src/markdown/figure.tsx +132 -0
  130. package/src/markdown/figures.ts +237 -0
  131. package/src/markdown/guide.tsx +536 -0
  132. package/src/markdown/index.ts +53 -0
  133. package/src/markdown/table-view.tsx +74 -0
  134. package/src/markdown/table.ts +90 -0
  135. package/src/password/common.ts +58 -0
  136. package/src/password/estimate-index.ts +18 -0
  137. package/src/password/estimate.ts +715 -0
  138. package/src/password/index.ts +40 -0
  139. package/src/password/password-input.tsx +116 -0
  140. package/src/password/password-strength.tsx +157 -0
  141. package/src/password/reveal.ts +151 -0
  142. package/src/rate-limit/better-auth.ts +94 -0
  143. package/src/rate-limit/index.ts +32 -0
  144. package/src/rate-limit/keys.ts +110 -0
  145. package/src/rate-limit/limiter.ts +276 -0
  146. package/src/rate-limit/prisma-index.ts +12 -0
  147. package/src/rate-limit/prisma.ts +157 -0
  148. package/src/rate-limit/store.ts +47 -0
  149. package/src/release/changelog.ts +364 -0
  150. package/src/release/index.ts +32 -0
  151. package/src/release/version.ts +64 -0
  152. package/src/setup-guide/bits.tsx +420 -0
  153. package/src/setup-guide/card.tsx +358 -0
  154. package/src/setup-guide/class-names.ts +144 -0
  155. package/src/setup-guide/context.tsx +239 -0
  156. package/src/setup-guide/guide.ts +271 -0
  157. package/src/setup-guide/index.ts +76 -0
  158. package/src/setup-guide/launcher.tsx +207 -0
  159. package/src/setup-guide/strip.tsx +127 -0
  160. package/src/styles/house.css +403 -0
  161. package/src/trail/index.ts +12 -0
  162. package/src/trail/rules.ts +84 -0
  163. package/src/trail/trail.tsx +367 -0
  164. package/src/ux/errors.ts +32 -0
  165. package/src/ux/feedback.tsx +41 -0
  166. package/src/ux/index.ts +44 -0
  167. package/src/ux/navigation-index.ts +16 -0
  168. package/src/ux/navigation-progress.tsx +270 -0
  169. package/src/ux/optimistic.ts +415 -0
  170. package/src/ux/use-action.ts +155 -0
  171. package/src/ux/use-optimistic-list.ts +227 -0
  172. package/src/ux/use-optimistic-value.ts +136 -0
  173. package/src/web-search/index.ts +13 -0
  174. package/src/web-search/providers.ts +177 -0
  175. package/src/web-search/types.ts +98 -0
  176. package/src/whats-new/body.tsx +190 -0
  177. package/src/whats-new/index.ts +43 -0
  178. package/src/whats-new/seen.ts +40 -0
  179. package/src/whats-new/select.ts +230 -0
  180. package/src/whats-new/use-whats-new.ts +109 -0
  181. package/src/wizard/index.ts +61 -0
  182. package/src/wizard/invalid.ts +152 -0
  183. package/src/wizard/react-hook-form-index.ts +11 -0
  184. package/src/wizard/rhf-adapter.ts +67 -0
  185. package/src/wizard/rules.ts +137 -0
  186. package/src/wizard/wizard.tsx +442 -0
@@ -0,0 +1,403 @@
1
+ import Anthropic from "@anthropic-ai/sdk";
2
+ import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
3
+ import OpenAI from "openai";
4
+ import { zodTextFormat } from "openai/helpers/zod";
5
+ import type { z } from "zod";
6
+
7
+ import {
8
+ aiStatus,
9
+ PROVIDER_LABELS,
10
+ publicAiStatus,
11
+ resolveAi,
12
+ type AiEnv,
13
+ type AiProviderName,
14
+ type AiStatus,
15
+ type AiTaskTable,
16
+ type PublicAiStatus,
17
+ type ResolvedAi,
18
+ } from "./config.js";
19
+ import type { AiImage } from "./images.js";
20
+
21
+ /**
22
+ * The one place either provider's SDK is called.
23
+ *
24
+ * Everything above this file asks for a job — "sort these bank lines", "write
25
+ * this month's summary" — and gets back text or a parsed object plus what it
26
+ * cost. Which company answered is a deployment decision (`config.ts`), not a
27
+ * decision any feature makes.
28
+ *
29
+ * The harness hides three real differences between the providers, and
30
+ * deliberately hides nothing else:
31
+ *
32
+ * 1. **Long requests must stream.** Both SDKs refuse a non-streaming call that
33
+ * could outlive their timeout, and transcribing a sixty-page document can.
34
+ * Structured calls stream and read the final message; nothing consumes the
35
+ * intermediate events.
36
+ * 2. **Output budgets mean different things.** An OpenAI reasoning model spends
37
+ * `max_output_tokens` on its reasoning before it writes a word, so a budget
38
+ * that is generous for Anthropic can return nothing at all. Hence the floor.
39
+ * 3. **Tuning parameters are model-specific.** Adaptive thinking and effort are
40
+ * sent only where they are asked for, and a model that rejects them produces
41
+ * a clear error naming the provider rather than a 500.
42
+ *
43
+ * Ported from AltEd's `lib/ai/provider.ts`, where it has run in production since
44
+ * tranche 113; the only change is that the jobs are the app's to name.
45
+ */
46
+
47
+ /** The feature is off, or the request never reached a model. */
48
+ export class AiUnavailableError extends Error {
49
+ constructor(message = "AI isn't available on this instance — no model is configured.") {
50
+ super(message);
51
+ this.name = "AiUnavailableError";
52
+ }
53
+ }
54
+
55
+ /** The provider answered, and said no. Carries its words: an operator can act on them. */
56
+ export class AiServiceError extends Error {
57
+ readonly status: number | undefined;
58
+
59
+ constructor(message: string, status?: number) {
60
+ super(message);
61
+ this.name = "AiServiceError";
62
+ this.status = status;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Why an answer was unusable (0.17.0):
68
+ *
69
+ * - `cut-off` — it ran out of output budget before it finished: the caller's
70
+ * `maxTokens`, which an OpenAI reasoning model also spends its thinking from.
71
+ * Trying again with the same budget usually fails the same way, and the
72
+ * budget is the app's choice, not the person's — an app may decide not to
73
+ * charge for it.
74
+ * - `refused` — the model declined, or the provider's filter stopped it.
75
+ * - `wrong-shape` — it finished, but not in the schema asked for.
76
+ */
77
+ export type AiUnusableReason = "cut-off" | "refused" | "wrong-shape";
78
+
79
+ /**
80
+ * The provider answered, but not with something usable — a refusal, a cut-off
81
+ * or an answer in the wrong shape. The tokens were spent all the same, so the
82
+ * usage travels with the error for the caller to record (AltEd round 10: these
83
+ * were free, and a failed step could be tried again without limit). `reason`
84
+ * says which, for a caller whose charging or wording depends on it.
85
+ */
86
+ export class AiUnusableAnswerError extends AiUnavailableError {
87
+ readonly usage: AiCallResult;
88
+ readonly reason: AiUnusableReason;
89
+
90
+ constructor(message: string, usage: AiCallResult, reason: AiUnusableReason = "wrong-shape") {
91
+ super(message);
92
+ this.name = "AiUnusableAnswerError";
93
+ this.usage = usage;
94
+ this.reason = reason;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * How hard an OpenAI reasoning model thinks before it answers (0.17.0).
100
+ * Its thinking is billed as output and shares `maxTokens`, so a job that is
101
+ * reading and listing rather than solving can save most of its time and cost
102
+ * with `"low"`. Sent only to models that reason — the gpt-5 family (not its
103
+ * `-chat` models) and the o-series — so a non-reasoning model an operator
104
+ * chooses still works. Anthropic ignores it; it has `thinking` and `effort`.
105
+ */
106
+ export type OpenAiReasoningEffort = "minimal" | "low" | "medium" | "high";
107
+
108
+ /** Whether an OpenAI model takes a reasoning effort. By name: the API has no way to ask. */
109
+ export function takesReasoningEffort(model: string): boolean {
110
+ return /^(gpt-5|o\d)/.test(model) && !/-chat/.test(model);
111
+ }
112
+
113
+ export interface AiCallResult {
114
+ provider: AiProviderName;
115
+ model: string;
116
+ inputTokens: number;
117
+ outputTokens: number;
118
+ /** Prompt tokens the provider served from its cache, and wrote to it. Billed apart. */
119
+ cacheReadTokens: number;
120
+ cacheWriteTokens: number;
121
+ }
122
+
123
+ export interface AiTextCall<Task extends string> {
124
+ task: Task;
125
+ system: string;
126
+ prompt: string;
127
+ /** Words the answer may run to. Raised automatically where reasoning shares the budget. */
128
+ maxTokens: number;
129
+ /**
130
+ * The longest the call may take, in milliseconds, with no retries — what is
131
+ * left of a serverless request, so a slow answer fails as an error rather than
132
+ * the function being killed mid-call.
133
+ */
134
+ timeoutMs?: number;
135
+ /** OpenAI reasoning models only; omitted = the model's own default. See `OpenAiReasoningEffort`. */
136
+ reasoningEffort?: OpenAiReasoningEffort;
137
+ }
138
+
139
+ export interface AiStructuredCall<Task extends string, T> extends AiTextCall<Task> {
140
+ schema: z.ZodType<T>;
141
+ /** A name for the schema. OpenAI requires one; Anthropic ignores it. */
142
+ schemaName: string;
143
+ /** A PDF for the model to read. Both providers fetch it themselves. */
144
+ documentUrl?: string;
145
+ /**
146
+ * Pictures for the model to look at, sent inline and in order. Inline rather
147
+ * than a URL because most of what an app shows a model sits behind its own
148
+ * access check — there is no public URL for a provider to fetch, and there
149
+ * must not be one.
150
+ */
151
+ images?: AiImage[];
152
+ /**
153
+ * Whether to ask Anthropic for adaptive thinking. Defaults to the job's own
154
+ * `thinking` setting. OpenAI's reasoning is the model's own and is unaffected.
155
+ */
156
+ thinking?: boolean;
157
+ /**
158
+ * How hard to think, on providers and models that take the instruction.
159
+ * Anthropic-only; for OpenAI see `reasoningEffort`.
160
+ */
161
+ effort?: "medium" | "high";
162
+ }
163
+
164
+ /**
165
+ * An OpenAI reasoning model bills its thinking against the same budget as its
166
+ * answer, so a 900-token ceiling can be spent entirely before the prose starts.
167
+ * Small requests get room; large ones already have it.
168
+ */
169
+ export const OPENAI_MIN_OUTPUT_TOKENS = 4000;
170
+
171
+ /** Turn either SDK's error into one a route can report in the provider's own words. */
172
+ function asServiceError(error: unknown, provider: AiProviderName): never {
173
+ if (error instanceof Anthropic.APIError || error instanceof OpenAI.APIError) {
174
+ // The two SDKs type `status` differently; narrow rather than trust either.
175
+ const status = typeof error.status === "number" ? error.status : undefined;
176
+ throw new AiServiceError(
177
+ `${PROVIDER_LABELS[provider]} refused the request (${status ?? "no status"}): ${error.message}`,
178
+ status,
179
+ );
180
+ }
181
+ throw error;
182
+ }
183
+
184
+ /** OpenAI counts cached prompt tokens inside `input_tokens`; move them out rather than bill them twice. */
185
+ function openAiUsage(
186
+ provider: AiProviderName,
187
+ model: string,
188
+ usage: OpenAI.Responses.ResponseUsage | undefined,
189
+ ): AiCallResult {
190
+ const cached = usage?.input_tokens_details?.cached_tokens ?? 0;
191
+ return {
192
+ provider,
193
+ model,
194
+ inputTokens: (usage?.input_tokens ?? 0) - cached,
195
+ outputTokens: usage?.output_tokens ?? 0,
196
+ cacheReadTokens: cached,
197
+ cacheWriteTokens: 0,
198
+ };
199
+ }
200
+
201
+ function anthropicUsage(provider: AiProviderName, message: Anthropic.Message): AiCallResult {
202
+ return {
203
+ provider,
204
+ model: message.model,
205
+ inputTokens: message.usage.input_tokens,
206
+ outputTokens: message.usage.output_tokens,
207
+ cacheReadTokens: message.usage.cache_read_input_tokens ?? 0,
208
+ cacheWriteTokens: message.usage.cache_creation_input_tokens ?? 0,
209
+ };
210
+ }
211
+
212
+ /** The `reasoning` field for an OpenAI request, or nothing when the model doesn't reason or none was asked for. */
213
+ function openAiReasoning(model: string, effort: OpenAiReasoningEffort | undefined) {
214
+ return effort && takesReasoningEffort(model) ? { reasoning: { effort } } : {};
215
+ }
216
+
217
+ export interface AiHarnessOptions<Task extends string> {
218
+ /** The app's jobs, each with a model per provider. */
219
+ tasks: AiTaskTable<Task>;
220
+ /** Where configuration is read from, on every call. Defaults to `process.env`. */
221
+ env?: () => AiEnv;
222
+ }
223
+
224
+ export interface AiHarness<Task extends string> {
225
+ /** Everything one call would use, or null when the feature is off. Never logged: it holds the key. */
226
+ resolve(task: Task): ResolvedAi | null;
227
+ /** For an operator: includes a misconfiguration, when there is one. */
228
+ status(): AiStatus<Task>;
229
+ /** For a person: everything but the misconfiguration. */
230
+ publicStatus(): PublicAiStatus<Task>;
231
+ /** Prose, from a system prompt and one user message. */
232
+ generateText(call: AiTextCall<Task>): Promise<AiCallResult & { text: string }>;
233
+ /** A parsed object in the shape of a Zod schema, optionally read from a PDF or pictures. */
234
+ generateStructured<T>(call: AiStructuredCall<Task, T>): Promise<AiCallResult & { parsed: T }>;
235
+ }
236
+
237
+ /**
238
+ * Bind the harness to an app's jobs.
239
+ *
240
+ * ```ts
241
+ * export const ai = createAiHarness({
242
+ * tasks: {
243
+ * categorise: {
244
+ * ANTHROPIC: { modelVar: "ANTHROPIC_MODEL", defaultModel: "claude-haiku-4-5-20251001" },
245
+ * OPENAI: { modelVar: "OPENAI_MODEL", defaultModel: "gpt-5-mini" },
246
+ * },
247
+ * },
248
+ * });
249
+ * ```
250
+ */
251
+ export function createAiHarness<Task extends string>(options: AiHarnessOptions<Task>): AiHarness<Task> {
252
+ const { tasks } = options;
253
+ const env = options.env ?? (() => process.env);
254
+
255
+ function resolve(task: Task): ResolvedAi {
256
+ const config = resolveAi(tasks, task, env());
257
+ if (!config) throw new AiUnavailableError();
258
+ return config;
259
+ }
260
+
261
+ async function generateText(call: AiTextCall<Task>): Promise<AiCallResult & { text: string }> {
262
+ const { provider, apiKey, model } = resolve(call.task);
263
+ const requestOptions = call.timeoutMs ? { timeout: call.timeoutMs, maxRetries: 0 } : undefined;
264
+
265
+ try {
266
+ if (provider === "ANTHROPIC") {
267
+ const message = await new Anthropic({ apiKey }).messages.create(
268
+ {
269
+ model,
270
+ max_tokens: call.maxTokens,
271
+ system: call.system,
272
+ messages: [{ role: "user", content: call.prompt }],
273
+ },
274
+ requestOptions,
275
+ );
276
+ const text = message.content
277
+ .filter((block): block is Anthropic.TextBlock => block.type === "text")
278
+ .map((block) => block.text)
279
+ .join("\n")
280
+ .trim();
281
+ return { text, ...anthropicUsage(provider, message) };
282
+ }
283
+
284
+ const response = await new OpenAI({ apiKey }).responses.create(
285
+ {
286
+ model,
287
+ instructions: call.system,
288
+ input: call.prompt,
289
+ max_output_tokens: Math.max(call.maxTokens, OPENAI_MIN_OUTPUT_TOKENS),
290
+ ...openAiReasoning(model, call.reasoningEffort),
291
+ },
292
+ requestOptions,
293
+ );
294
+ return { text: response.output_text.trim(), ...openAiUsage(provider, response.model, response.usage) };
295
+ } catch (error) {
296
+ asServiceError(error, provider);
297
+ }
298
+ }
299
+
300
+ async function generateStructured<T>(call: AiStructuredCall<Task, T>): Promise<AiCallResult & { parsed: T }> {
301
+ const { provider, apiKey, model } = resolve(call.task);
302
+ const requestOptions = call.timeoutMs ? { timeout: call.timeoutMs, maxRetries: 0 } : undefined;
303
+ const thinking = call.thinking ?? tasks[call.task].thinking ?? false;
304
+
305
+ try {
306
+ if (provider === "ANTHROPIC") {
307
+ const content: Anthropic.ContentBlockParam[] = [];
308
+ if (call.documentUrl) content.push({ type: "document", source: { type: "url", url: call.documentUrl } });
309
+ for (const image of call.images ?? []) {
310
+ content.push({
311
+ type: "image",
312
+ source: { type: "base64", media_type: image.mediaType, data: image.base64 },
313
+ });
314
+ }
315
+ content.push({ type: "text", text: call.prompt });
316
+
317
+ // Streamed, not because anything reads the stream, but because the SDK
318
+ // refuses a non-streaming call that could run past ten minutes.
319
+ const stream = new Anthropic({ apiKey }).messages.stream(
320
+ {
321
+ model,
322
+ max_tokens: call.maxTokens,
323
+ system: call.system,
324
+ ...(thinking ? { thinking: { type: "adaptive" as const } } : {}),
325
+ output_config: { ...(call.effort ? { effort: call.effort } : {}), format: zodOutputFormat(call.schema) },
326
+ messages: [{ role: "user", content }],
327
+ },
328
+ requestOptions,
329
+ );
330
+ const response = await stream.finalMessage();
331
+ const usage = anthropicUsage(provider, response);
332
+
333
+ if (response.stop_reason === "refusal") {
334
+ throw new AiUnusableAnswerError("The model declined to process this request.", usage, "refused");
335
+ }
336
+ if (response.stop_reason === "max_tokens") {
337
+ throw new AiUnusableAnswerError(
338
+ "The answer was cut off before it was complete (max_tokens). Try a model with more room, or a shorter input.",
339
+ usage,
340
+ "cut-off",
341
+ );
342
+ }
343
+ if (response.parsed_output === null || response.parsed_output === undefined) {
344
+ throw new AiUnusableAnswerError("The model's answer did not match the expected shape.", usage);
345
+ }
346
+ return { parsed: response.parsed_output as T, ...usage };
347
+ }
348
+
349
+ const content: OpenAI.Responses.ResponseInputContent[] = [];
350
+ if (call.documentUrl) content.push({ type: "input_file", file_url: call.documentUrl });
351
+ for (const image of call.images ?? []) {
352
+ content.push({
353
+ type: "input_image",
354
+ image_url: `data:${image.mediaType};base64,${image.base64}`,
355
+ detail: "auto",
356
+ });
357
+ }
358
+ content.push({ type: "input_text", text: call.prompt });
359
+
360
+ const stream = new OpenAI({ apiKey }).responses.stream(
361
+ {
362
+ model,
363
+ instructions: call.system,
364
+ input: [{ role: "user", content }],
365
+ max_output_tokens: Math.max(call.maxTokens, OPENAI_MIN_OUTPUT_TOKENS),
366
+ text: { format: zodTextFormat(call.schema, call.schemaName) },
367
+ ...openAiReasoning(model, call.reasoningEffort),
368
+ },
369
+ requestOptions,
370
+ );
371
+ const response = await stream.finalResponse();
372
+ const usage = openAiUsage(provider, response.model, response.usage);
373
+
374
+ if (response.status === "incomplete") {
375
+ const why = response.incomplete_details?.reason;
376
+ // A content filter stopping it is a refusal by another name; anything else is the budget running out.
377
+ if (why === "content_filter") {
378
+ throw new AiUnusableAnswerError("The provider's content filter stopped the answer.", usage, "refused");
379
+ }
380
+ throw new AiUnusableAnswerError(
381
+ `The answer was cut off before it was complete (${why ?? "no reason given"}). Try a model with more room, or a shorter input.`,
382
+ usage,
383
+ "cut-off",
384
+ );
385
+ }
386
+ if (response.output_parsed === null || response.output_parsed === undefined) {
387
+ throw new AiUnusableAnswerError("The model's answer did not match the expected shape.", usage);
388
+ }
389
+ return { parsed: response.output_parsed as T, ...usage };
390
+ } catch (error) {
391
+ if (error instanceof AiUnavailableError) throw error;
392
+ asServiceError(error, provider);
393
+ }
394
+ }
395
+
396
+ return {
397
+ resolve: (task) => resolveAi(tasks, task, env()),
398
+ status: () => aiStatus(tasks, env()),
399
+ publicStatus: () => publicAiStatus(tasks, env()),
400
+ generateText,
401
+ generateStructured,
402
+ };
403
+ }