@sentry/junior 0.286.0 → 0.288.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 (78) hide show
  1. package/dist/{adapter-JQZaJ-B_.js → adapter-Cikcqdty.js} +1 -1
  2. package/dist/{admin-Dm2bimJ-.js → admin-BcSxHuTB.js} +2 -1
  3. package/dist/{agent-runner-DGCwOEyL.js → agent-runner-9MXyWUL8.js} +784 -368
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +9 -8
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +411 -65
  8. package/dist/{app-BKq0JzWx.d.ts → app-BUklJVBe.d.ts} +4 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +555 -71
  11. package/dist/{assistant-reply-CAPafcUY.js → assistant-reply-mj47jMRV.js} +1 -1
  12. package/dist/{automation-B-jJN_gM.js → automation-DDXwHQs5.js} +4 -7
  13. package/dist/{background-compaction-queue-Btu2oab_.js → background-compaction-queue-CjllSPir.js} +161 -90
  14. package/dist/{briefs-UMeYehUe.js → briefs-DW9iuolG.js} +7 -5
  15. package/dist/{catalog-runtime-Bym8GVdh.js → catalog-runtime-B3gfH58M.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/config-CLJcyYEF.js +1762 -0
  24. package/dist/{connections-CQ7p0aNJ.js → connections-BtdJftow.js} +9 -9
  25. package/dist/{conversation-BusI2uzj.js → conversation-DhoqHtQ7.js} +30 -6
  26. package/dist/{conversation-pending-messages-DwehU0Fd.js → conversation-pending-messages-DHV0S4uF.js} +2 -5
  27. package/dist/{conversation-privacy-Cd_nZZBM.js → conversation-privacy-BPirIVlX.js} +1 -1
  28. package/dist/core-model-BTt5E5b0.js +182 -0
  29. package/dist/{credential-sync-DmiJi_At.js → credential-sync-Co8Q2xRW.js} +28 -20
  30. package/dist/{viewer-CH-ASQzh.js → db-Co7DTYYh.js} +62 -358
  31. package/dist/{db-C5zi4ecs.d.ts → db-zIs8-Ba3.d.ts} +6 -2
  32. package/dist/{executor-Dipi2Ixl.js → executor-m0kIN71Q.js} +102 -14
  33. package/dist/{media-B-BpXo41.js → history-IjdmO_r6.js} +8 -88
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{logging-CMFhLLj4.js → logging-DbD-dErY.js} +3 -2
  36. package/dist/media-BAHvgkok.js +85 -0
  37. package/dist/{message-D1xLljUF.js → message-DKTdTYm-.js} +10 -10
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +19 -41
  40. package/dist/{oauth-callback-server-DCAFIUQr.js → oauth-callback-server-CpbepSbp.js} +2 -2
  41. package/dist/{projection-CoeMNxJ4.js → projection-BViECfYu.js} +361 -746
  42. package/dist/{prompt-C9OQEfan.js → prompt-KT6MaDHN.js} +1 -1
  43. package/dist/{registry-u-sFYtx_.js → registry-D-Acyjhh.js} +1 -1
  44. package/dist/{reporting-window-B4TwyuJo.js → reporting-window-B3Ze-Qnt.js} +4 -1
  45. package/dist/{resolve-DYqgL3Eo.js → resolve-gkT2R66z.js} +3 -3
  46. package/dist/{result-CescSwAw.js → result-DHmCFEt8.js} +8 -8
  47. package/dist/{runner-Cr67a8TB.js → runner-DBKjGjH-.js} +8 -8
  48. package/dist/{sandbox-egress-signals-DLOazy5W.js → sandbox-egress-signals-9n8hqx29.js} +1 -1
  49. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  50. package/dist/{schema-Ih60j59-.d.ts → schema-B_6aOcx5.d.ts} +159 -3
  51. package/dist/{schema-BUSi3sgv.js → schema-DxicIQbc.js} +79 -14
  52. package/dist/{service-account-CsKxktLk.js → service-account-Bi0HsY6w.js} +3 -3
  53. package/dist/{service-account-CGEqz9wG.js → service-account-CDlC9ssy.js} +3 -3
  54. package/dist/{session-stop-CGz5DByb.js → session-stop-BWOsuo8p.js} +62 -20
  55. package/dist/{skills-COCqf61f.js → skills-DO5K68Rq.js} +2 -2
  56. package/dist/spawn-BBqZDcPa.js +79 -0
  57. package/dist/{stop-GyFZkHuQ.js → stop-WC97cmHz.js} +832 -552
  58. package/dist/{store-D0-8plWp.js → store-ByR1Lr7e.js} +4 -16
  59. package/dist/{task-runner-xPuQmEot.js → task-runner-B-Ewf8TX.js} +30 -21
  60. package/dist/{turn-failure-response-BOviBdT-.js → turn-failure-response-CpdPoZSl.js} +25 -11
  61. package/dist/{validation-DZDKorGz.js → validation-B4sbIoES.js} +1 -1
  62. package/dist/{version-BTIz7fGi.js → version-D6lpuAgL.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/viewer-CeP27tC3.js +337 -0
  65. package/dist/warmup-P_GJCL1c.js +767 -0
  66. package/dist/{work-C75_IM5e.js → work-DI7x1Slm.js} +32 -20
  67. package/dist/{worker-Dl47I729.js → worker-CYPTOT4j.js} +6 -7
  68. package/migrations/0088_conversation_unsubscribe.sql +1 -0
  69. package/migrations/0089_conversation_paused_status.sql +3 -0
  70. package/migrations/0090_guardian_review_time_index.sql +20 -0
  71. package/migrations/meta/0088_snapshot.json +4372 -0
  72. package/migrations/meta/0089_snapshot.json +4372 -0
  73. package/migrations/meta/0090_snapshot.json +4388 -0
  74. package/migrations/meta/_journal.json +21 -0
  75. package/package.json +5 -4
  76. package/dist/client-B0aAs7wC.js +0 -793
  77. package/dist/config-B9f9Lqo5.js +0 -579
  78. package/dist/spawn-C8F_iXWO.js +0 -42
@@ -0,0 +1,1762 @@
1
+ import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
+ import { E as withSpan, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-DbD-dErY.js";
3
+ import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-BPirIVlX.js";
4
+ import { AwsClient } from "aws4fetch";
5
+ import { del, get, put } from "@vercel/blob";
6
+ import { calculateCost, completeSimple, getEnvApiKey, getModels, registerApiProvider } from "@earendil-works/pi-ai/compat";
7
+ import { stream as streamAnthropic, streamSimple as streamSimpleAnthropic } from "@earendil-works/pi-ai/api/anthropic-messages";
8
+ import { createGatewayProvider } from "@ai-sdk/gateway";
9
+ import { getVercelOidcToken } from "@vercel/oidc";
10
+ import { Experimental_DecisionRefusalError, NoObjectGeneratedError, embedMany, experimental_decide, generateObject, rerank, transcribe } from "ai";
11
+ import { createHash } from "node:crypto";
12
+ import * as z from "zod";
13
+ // src/chat/optional-string.ts
14
+ /**
15
+ * Normalize optional env-style strings so blank values do not masquerade as
16
+ * configured inputs.
17
+ */
18
+ function toOptionalTrimmed(value) {
19
+ if (!value) return;
20
+ const trimmed = value.trim();
21
+ return trimmed.length > 0 ? trimmed : void 0;
22
+ }
23
+ // src/chat/attachments/memory.ts
24
+ /**
25
+ * Store attachments in process memory, for tests.
26
+ *
27
+ * Objects are lost when the process stops, and each process has its own
28
+ * copy. Do not use this provider for deployed apps.
29
+ */
30
+ function createMemoryAttachmentStorage() {
31
+ const objects = /* @__PURE__ */ new Map();
32
+ return {
33
+ objects,
34
+ provider: "memory",
35
+ async put(input) {
36
+ objects.set(input.key, Buffer.from(input.body));
37
+ },
38
+ async get(key, range) {
39
+ const body = objects.get(key);
40
+ if (!body) return null;
41
+ const bytes = range ? body.subarray(range.start, range.end + 1) : body;
42
+ return new ReadableStream({ start(controller) {
43
+ controller.enqueue(new Uint8Array(bytes));
44
+ controller.close();
45
+ } });
46
+ },
47
+ async delete(keys) {
48
+ for (const key of keys) objects.delete(key);
49
+ }
50
+ };
51
+ }
52
+ // src/chat/attachments/vercel.ts
53
+ /** Store private conversation attachments in Vercel Blob. */
54
+ function createVercelAttachmentStorage() {
55
+ return {
56
+ provider: "vercel-blob",
57
+ async put(input) {
58
+ await put(input.key, input.body, {
59
+ access: "private",
60
+ addRandomSuffix: false,
61
+ allowOverwrite: true,
62
+ contentType: input.contentType
63
+ });
64
+ },
65
+ async get(key, range) {
66
+ const result = await get(key, {
67
+ access: "private",
68
+ useCache: false,
69
+ ...range ? { headers: { range: rangeHeader(range) } } : void 0
70
+ });
71
+ if (result?.statusCode !== 200) return null;
72
+ if (range && !result.headers.get("content-range")) {
73
+ await result.stream.cancel();
74
+ throw new Error("Vercel Blob get ignored the byte range");
75
+ }
76
+ return result.stream;
77
+ },
78
+ async delete(keys) {
79
+ if (keys.length === 0) return;
80
+ await del(keys);
81
+ }
82
+ };
83
+ }
84
+ // src/chat/attachments/storage.ts
85
+ /** Build the HTTP `Range` request header value for one byte range. */
86
+ function rangeHeader(range) {
87
+ return `bytes=${range.start}-${range.end}`;
88
+ }
89
+ /**
90
+ * Return attachment storage for the configured provider.
91
+ *
92
+ * Callers do not choose a provider. Chat config decides it.
93
+ */
94
+ function getAttachmentStorage() {
95
+ return createAttachmentStorage(getChatConfig().attachmentStorage);
96
+ }
97
+ /**
98
+ * Create attachment storage for one provider config.
99
+ *
100
+ * Runtime code uses `getAttachmentStorage()`. Call this only to test a
101
+ * provider adapter with its own config.
102
+ */
103
+ function createAttachmentStorage(config) {
104
+ switch (config.provider) {
105
+ case "vercel-blob": return createVercelAttachmentStorage();
106
+ case "s3": return createS3AttachmentStorage(config.s3);
107
+ case "memory": return createMemoryAttachmentStorage();
108
+ default: throw new Error(`Unsupported attachment storage provider: ${String(config.provider)}`);
109
+ }
110
+ }
111
+ // src/chat/attachments/s3.ts
112
+ function readRequiredSetting(env, name) {
113
+ const value = toOptionalTrimmed(env[name]);
114
+ if (value === void 0) throw new Error(`${name} is required when JUNIOR_ATTACHMENT_STORAGE_PROVIDER is s3`);
115
+ return value;
116
+ }
117
+ /** Read S3 settings from `JUNIOR_S3_*` environment variables. */
118
+ function readS3StorageConfig(env) {
119
+ return {
120
+ accessKeyId: readRequiredSetting(env, "JUNIOR_S3_ACCESS_KEY_ID"),
121
+ bucket: readRequiredSetting(env, "JUNIOR_S3_BUCKET"),
122
+ endpoint: readRequiredSetting(env, "JUNIOR_S3_ENDPOINT"),
123
+ region: toOptionalTrimmed(env.JUNIOR_S3_REGION) ?? "us-east-1",
124
+ secretAccessKey: readRequiredSetting(env, "JUNIOR_S3_SECRET_ACCESS_KEY")
125
+ };
126
+ }
127
+ /**
128
+ * Path-style object URL. Local S3 servers and AWS S3 both accept it.
129
+ *
130
+ * URL parsing removes `.` and `..` segments, also in `%2e` form. A key with
131
+ * such a segment would address a different object, so reject it.
132
+ */
133
+ function objectUrl(config, key) {
134
+ const endpoint = config.endpoint.replace(/\/+$/, "");
135
+ const segments = key.split("/");
136
+ if (segments.some((segment) => segment === "." || segment === "..")) throw new Error("S3 object keys cannot contain . or .. path segments");
137
+ const path = segments.map(encodeURIComponent).join("/");
138
+ return `${endpoint}/${encodeURIComponent(config.bucket)}/${path}`;
139
+ }
140
+ /**
141
+ * Read a small S3 response body to the end so the connection is released.
142
+ *
143
+ * Error and empty bodies are small. `body.cancel()` can hang under the test
144
+ * HTTP interceptor, so read the body instead.
145
+ */
146
+ async function drain(response) {
147
+ await response.arrayBuffer();
148
+ }
149
+ /** Throw on a failed S3 response, and release the response body. */
150
+ async function expectOk(response, operation) {
151
+ await drain(response);
152
+ if (!response.ok) throw new Error(`S3 ${operation} failed with status ${response.status}`);
153
+ }
154
+ /** Store private conversation attachments in an S3-compatible bucket. */
155
+ function createS3AttachmentStorage(config) {
156
+ const client = new AwsClient({
157
+ accessKeyId: config.accessKeyId,
158
+ region: config.region,
159
+ secretAccessKey: config.secretAccessKey,
160
+ service: "s3"
161
+ });
162
+ return {
163
+ provider: "s3",
164
+ async put(input) {
165
+ await expectOk(await client.fetch(objectUrl(config, input.key), {
166
+ body: new Uint8Array(input.body),
167
+ headers: { "content-type": input.contentType },
168
+ method: "PUT"
169
+ }), "put");
170
+ },
171
+ async get(key, range) {
172
+ const response = await client.fetch(objectUrl(config, key), range ? { headers: { range: rangeHeader(range) } } : void 0);
173
+ if (response.status === 404) {
174
+ await drain(response);
175
+ return null;
176
+ }
177
+ if (!response.ok) await expectOk(response, "get");
178
+ if (range && response.status !== 206) {
179
+ await drain(response);
180
+ throw new Error(`S3 get ignored the byte range with status ${response.status}`);
181
+ }
182
+ return response.body;
183
+ },
184
+ async delete(keys) {
185
+ await Promise.all(keys.map(async (key) => {
186
+ const response = await client.fetch(objectUrl(config, key), { method: "DELETE" });
187
+ if (response.status === 404) {
188
+ await drain(response);
189
+ return;
190
+ }
191
+ await expectOk(response, "delete");
192
+ }));
193
+ }
194
+ };
195
+ }
196
+ // src/chat/attachments/config.ts
197
+ /** Read attachment storage settings from environment variables. */
198
+ function readAttachmentStorageConfig(env) {
199
+ const provider = toOptionalTrimmed(env.JUNIOR_ATTACHMENT_STORAGE_PROVIDER) ?? "vercel-blob";
200
+ switch (provider) {
201
+ case "vercel-blob":
202
+ case "memory": return { provider };
203
+ case "s3": return {
204
+ provider,
205
+ s3: readS3StorageConfig(env)
206
+ };
207
+ default: throw new Error("JUNIOR_ATTACHMENT_STORAGE_PROVIDER must be vercel-blob, s3, or memory");
208
+ }
209
+ }
210
+ // src/chat/queue/config.ts
211
+ /** Jobs that one BullMQ worker runs at the same time, for each queue topic. */
212
+ const DEFAULT_BULLMQ_WORKER_CONCURRENCY = 4;
213
+ function readWorkerConcurrency(value) {
214
+ const raw = toOptionalTrimmed(value);
215
+ if (raw === void 0) return DEFAULT_BULLMQ_WORKER_CONCURRENCY;
216
+ const concurrency = Number(raw);
217
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(concurrency) || concurrency < 1) throw new Error("JUNIOR_QUEUE_WORKER_CONCURRENCY must be a positive integer");
218
+ return concurrency;
219
+ }
220
+ /** Read queue settings from environment variables. */
221
+ function readQueueConfig(env) {
222
+ const provider = toOptionalTrimmed(env.JUNIOR_QUEUE_PROVIDER) ?? "vercel";
223
+ switch (provider) {
224
+ case "vercel": return { provider };
225
+ case "bullmq": {
226
+ const redisUrl = toOptionalTrimmed(env.JUNIOR_QUEUE_REDIS_URL);
227
+ if (!redisUrl) throw new Error("JUNIOR_QUEUE_REDIS_URL is required when JUNIOR_QUEUE_PROVIDER is bullmq");
228
+ return {
229
+ provider,
230
+ redisUrl,
231
+ workerConcurrency: readWorkerConcurrency(env.JUNIOR_QUEUE_WORKER_CONCURRENCY)
232
+ };
233
+ }
234
+ default: throw new Error("JUNIOR_QUEUE_PROVIDER must be vercel or bullmq");
235
+ }
236
+ }
237
+ // src/chat/pi/gateway-auth.ts
238
+ /**
239
+ * AI Gateway credential resolution for every Junior model path.
240
+ *
241
+ * Prefer Vercel project OIDC so gateway usage attributes to the deploying
242
+ * project. Fall back to AI_GATEWAY_API_KEY for local/CI and non-Vercel hosts.
243
+ * Never cache resolved tokens: runtime OIDC rotates on each invocation.
244
+ */
245
+ const UNAUTHENTICATED_GATEWAY_TOKEN = "unauthenticated";
246
+ /**
247
+ * Resolve the AI Gateway bearer credential.
248
+ *
249
+ * Order:
250
+ * 1. Vercel OIDC via `@vercel/oidc` (request header `x-vercel-oidc-token`,
251
+ * then `VERCEL_OIDC_TOKEN`, with local refresh when needed)
252
+ * 2. Explicit `AI_GATEWAY_API_KEY` / pi-ai env mapping for vercel-ai-gateway
253
+ * 3. A placeholder token (`mode: "none"`), so auth fails on the server side
254
+ */
255
+ async function resolveGatewayCredential() {
256
+ try {
257
+ const oidcToken = toOptionalTrimmed(await getVercelOidcToken());
258
+ if (oidcToken) return {
259
+ mode: "oidc",
260
+ token: oidcToken
261
+ };
262
+ } catch {}
263
+ const apiKey = toOptionalTrimmed(getEnvApiKey("vercel-ai-gateway"));
264
+ if (apiKey) return {
265
+ mode: "api_key",
266
+ token: apiKey
267
+ };
268
+ return {
269
+ mode: "none",
270
+ token: UNAUTHENTICATED_GATEWAY_TOKEN
271
+ };
272
+ }
273
+ /** Resolve the bearer token string for Authorization headers and Pi getApiKey. */
274
+ async function getGatewayApiKey() {
275
+ return (await resolveGatewayCredential()).token;
276
+ }
277
+ // src/chat/services/provider-error.ts
278
+ /** Structured failure produced at an AI provider boundary. */
279
+ var ProviderError = class extends Error {
280
+ code = "provider_error";
281
+ kind;
282
+ modelId;
283
+ retryable;
284
+ retryAfterMs;
285
+ status;
286
+ constructor(details) {
287
+ super(`AI provider error: ${details.kind}`, details.cause !== void 0 ? { cause: details.cause } : {});
288
+ this.name = "ProviderError";
289
+ this.kind = details.kind;
290
+ this.modelId = details.modelId;
291
+ this.retryable = details.retryable;
292
+ this.retryAfterMs = details.retryAfterMs;
293
+ this.status = details.status;
294
+ }
295
+ };
296
+ const NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
297
+ "ECONNREFUSED",
298
+ "ECONNRESET",
299
+ "ENOTFOUND",
300
+ "EAI_AGAIN"
301
+ ]);
302
+ const TIMEOUT_ERROR_CODES = /* @__PURE__ */ new Set([
303
+ "ETIMEDOUT",
304
+ "ECONNABORTED",
305
+ "ESOCKETTIMEDOUT"
306
+ ]);
307
+ const CONTENT_POLICY_PATTERN = /\b(?:content|safety|usage)[ _-]?policy\b|\b(?:content|safety) (?:filter|violation)\b|\bmoderation (?:blocked|rejected|refused)\b/i;
308
+ const QUOTA_PATTERN = /insufficient.?quota|quota exceeded|usage limit|available balance|out of budget|billing (?:limit|quota|error)|payment required/i;
309
+ const AUTH_PATTERN = /unauthenticated|invalid.?api.?key|no api key|authentication (?:failed|error|required)|(?:invalid|missing|expired|revoked).{0,24}\bcredentials?\b|\bcredentials?\b.{0,24}(?:invalid|missing|expired|revoked)|\bno\b.{0,16}\bcredentials?\b/i;
310
+ const PERMISSION_PATTERN = /permission denied|forbidden|not authorized|authorization (?:failed|required|denied)/i;
311
+ const INVALID_REQUEST_PATTERN = /context.?length|context.?window|validation (?:error|failed)|bad request|unsupported model|invalid model|unknown (?:ai gateway )?model|mismatched api/i;
312
+ const CAPACITY_PATTERN = /overloaded|at capacity|capacity exceeded/i;
313
+ const TIMEOUT_PATTERN = /timed? out|timeout|gateway timeout/i;
314
+ const NETWORK_PATTERN = /network.?error|connection (?:error|refused|lost|closed)|fetch failed|socket (?:hang up|closed)|stream ended before/i;
315
+ const SERVER_PATTERN = /service(?: temporarily)?[ _-]?unavailable|server.?error|internal.?error|bad gateway|upstream (?:request )?failed/i;
316
+ const TERMINAL_KINDS = /* @__PURE__ */ new Set([
317
+ "auth",
318
+ "permission",
319
+ "invalid_request",
320
+ "invalid_response",
321
+ "quota",
322
+ "content_policy"
323
+ ]);
324
+ const RETRYABLE_KINDS = /* @__PURE__ */ new Set([
325
+ "rate_limit",
326
+ "capacity",
327
+ "timeout",
328
+ "network",
329
+ "server"
330
+ ]);
331
+ function providerMessage(error) {
332
+ return (error instanceof Error ? error.message : String(error)).trim();
333
+ }
334
+ const PROVIDER_ERROR_SUMMARY_MAX_CHARS = 240;
335
+ /** Short provider-boundary text for telemetry. Drop trailing JSON bodies. */
336
+ function summarizeProviderErrorMessage(message) {
337
+ const normalized = message.trim().replace(/\s+/g, " ");
338
+ if (!normalized) return void 0;
339
+ const jsonStart = normalized.indexOf("{");
340
+ const summary = (jsonStart >= 0 ? normalized.slice(0, jsonStart) : normalized).trim();
341
+ if (!summary) return void 0;
342
+ return summary.length > PROVIDER_ERROR_SUMMARY_MAX_CHARS ? `${summary.slice(0, PROVIDER_ERROR_SUMMARY_MAX_CHARS)}...` : summary;
343
+ }
344
+ function extractTransportKind(error, depth = 0) {
345
+ if (!(error instanceof Error) || depth > 4) return void 0;
346
+ const providerError = error;
347
+ const code = typeof providerError.code === "string" ? providerError.code.toUpperCase() : void 0;
348
+ if (code && TIMEOUT_ERROR_CODES.has(code)) return "timeout";
349
+ if (code && NETWORK_ERROR_CODES.has(code)) return "network";
350
+ return extractTransportKind(providerError.cause, depth + 1);
351
+ }
352
+ function extractStatus(error, message) {
353
+ if (error instanceof Error) {
354
+ const providerError = error;
355
+ if (typeof providerError.status === "number") return providerError.status;
356
+ if (typeof providerError.statusCode === "number") return providerError.statusCode;
357
+ }
358
+ const match = message.match(/^(?:Error:\s*)?([45]\d\d)\b|\bstatus(?:Code)?["'=:\s]+([45]\d\d)\b/i);
359
+ const status = match?.[1] ?? match?.[2];
360
+ return status ? Number(status) : void 0;
361
+ }
362
+ function extractRetryAfterMs(error, message) {
363
+ const headers = error instanceof Error ? error.responseHeaders ?? error.response?.headers : void 0;
364
+ const retryAfter = headers instanceof Headers ? headers.get("retry-after") : headers && typeof headers === "object" ? Object.entries(headers).find(([name]) => name.toLowerCase() === "retry-after")?.[1] : void 0;
365
+ const raw = typeof retryAfter === "string" || typeof retryAfter === "number" ? String(retryAfter) : message.match(/"retry-after"\s*:\s*"?([^",}]+)"?/i)?.[1];
366
+ if (!raw) return void 0;
367
+ const seconds = Number(raw);
368
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
369
+ const date = Date.parse(raw);
370
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
371
+ }
372
+ /** Classify stable provider signals without copying Pi's retry vocabulary. */
373
+ function classifyProviderError(status, message, transportKind) {
374
+ if (CONTENT_POLICY_PATTERN.test(message)) return "content_policy";
375
+ if (QUOTA_PATTERN.test(message)) return "quota";
376
+ if (status === 401 || AUTH_PATTERN.test(message)) return "auth";
377
+ if (status === 403 || PERMISSION_PATTERN.test(message)) return "permission";
378
+ if (INVALID_REQUEST_PATTERN.test(message)) return "invalid_request";
379
+ if (status === 429 || /rate.?limit|too many requests/i.test(message)) return "rate_limit";
380
+ if (status === 408) return "timeout";
381
+ if (CAPACITY_PATTERN.test(message)) return "capacity";
382
+ if (transportKind === "timeout" || TIMEOUT_PATTERN.test(message)) return "timeout";
383
+ if (transportKind === "network" || NETWORK_PATTERN.test(message)) return "network";
384
+ if (status !== void 0 && status >= 500 || SERVER_PATTERN.test(message)) return "server";
385
+ if (status !== void 0 && status >= 400) return "invalid_request";
386
+ return "unknown";
387
+ }
388
+ /** Normalize SDK, Gateway, and Pi failures into one provider error contract. */
389
+ function createProviderError(error, options = {}) {
390
+ if (error instanceof ProviderError) return error;
391
+ const message = providerMessage(error);
392
+ const status = extractStatus(error, message);
393
+ const kind = options.kind ?? classifyProviderError(status, message, extractTransportKind(error));
394
+ const retryable = !TERMINAL_KINDS.has(kind) && (options.retryable ?? RETRYABLE_KINDS.has(kind));
395
+ return new ProviderError({
396
+ cause: error,
397
+ kind,
398
+ modelId: options.modelId,
399
+ retryable,
400
+ retryAfterMs: extractRetryAfterMs(error, message),
401
+ status
402
+ });
403
+ }
404
+ /** Return whether a provider-boundary error should be retried. */
405
+ function isProviderRetryError(error) {
406
+ return error instanceof ProviderError && error.retryable;
407
+ }
408
+ /** Find the provider failure preserved inside a domain error cause chain. */
409
+ function findProviderError(error) {
410
+ const visited = /* @__PURE__ */ new Set();
411
+ let current = error;
412
+ while (current instanceof Error && !visited.has(current)) {
413
+ if (current instanceof ProviderError) return current;
414
+ visited.add(current);
415
+ current = current.cause;
416
+ }
417
+ }
418
+ /** Return stable, sanitized copy suitable for a terminal user response. */
419
+ function getProviderErrorUserMessage(error) {
420
+ switch (error.kind) {
421
+ case "capacity": return "The selected model is temporarily unavailable because it is at capacity. Please try again shortly.";
422
+ case "rate_limit": {
423
+ const seconds = error.retryAfterMs ? Math.max(1, Math.ceil(error.retryAfterMs / 1e3)) : void 0;
424
+ return seconds ? `The model is rate-limited. Please try again in about ${seconds} seconds.` : "The model is rate-limited. Please try again shortly.";
425
+ }
426
+ case "timeout":
427
+ case "network":
428
+ case "server": return "The model provider had a temporary connection problem. Please try again.";
429
+ case "auth": return "The model provider rejected the configured credentials. This needs an administrator or configuration fix.";
430
+ case "permission": return "The model provider denied access to this model or request. Ask an administrator to check model access, organization policy, and region availability.";
431
+ case "quota": return "The model provider's usage quota has been exhausted. This needs an administrator or billing configuration fix.";
432
+ case "content_policy": return "The model provider blocked this request under its content policy. Please revise the request and try again.";
433
+ case "invalid_request": return "The model provider rejected this request as invalid. Please revise the request or ask an administrator to check the model configuration.";
434
+ case "invalid_response": return "The model provider returned an invalid response. Please try again.";
435
+ default: return "The model provider returned an error. Please try again.";
436
+ }
437
+ }
438
+ /** Return safe structured fields for terminal failure telemetry. */
439
+ function getProviderErrorAttributes(error) {
440
+ const cause = error.cause;
441
+ const causeMessage = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : void 0;
442
+ const summary = causeMessage ? summarizeProviderErrorMessage(causeMessage) : void 0;
443
+ return {
444
+ "app.ai.provider_error.kind": error.kind,
445
+ "app.ai.provider_error.retryable": error.retryable,
446
+ ...error.status !== void 0 ? { "app.ai.provider_error.status": error.status } : void 0,
447
+ ...error.retryAfterMs !== void 0 ? { "app.ai.provider_error.retry_after_ms": error.retryAfterMs } : void 0,
448
+ ...summary ? { "app.ai.provider_error.summary": summary } : void 0,
449
+ ...error.modelId ? { "gen_ai.request.model": error.modelId } : void 0
450
+ };
451
+ }
452
+ // src/chat/xml.ts
453
+ /** Escape untrusted body text for a prompt tag. Quotes stay as written. */
454
+ function escapeXmlText(value) {
455
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
456
+ }
457
+ function escapeXml(value) {
458
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
459
+ }
460
+ /** Recover text escaped for an internal XML prompt boundary. */
461
+ function unescapeXml(value) {
462
+ return value.replaceAll("&quot;", "\"").replaceAll("&apos;", "'").replaceAll("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&amp;", "&");
463
+ }
464
+ // src/chat/current-instruction.ts
465
+ const CURRENT_INSTRUCTION_TAG = "current-instruction";
466
+ const CURRENT_INSTRUCTION_OPEN_PREFIX = `<${CURRENT_INSTRUCTION_TAG}`;
467
+ const CURRENT_INSTRUCTION_OPEN_BARE = `<${CURRENT_INSTRUCTION_TAG}>`;
468
+ const CURRENT_INSTRUCTION_OPEN_ATTR_PREFIX = `<${CURRENT_INSTRUCTION_TAG} `;
469
+ const CURRENT_INSTRUCTION_CLOSE = `\n</${CURRENT_INSTRUCTION_TAG}>`;
470
+ function isCurrentInstructionOpeningTag(value) {
471
+ return value === CURRENT_INSTRUCTION_OPEN_BARE || value.startsWith(CURRENT_INSTRUCTION_OPEN_ATTR_PREFIX) && value.endsWith(">");
472
+ }
473
+ function readCurrentInstructionBody(text) {
474
+ const start = text.indexOf(CURRENT_INSTRUCTION_OPEN_PREFIX);
475
+ if (start < 0) return;
476
+ const openingEnd = text.indexOf(">\n", start);
477
+ if (openingEnd < 0) return;
478
+ if (!isCurrentInstructionOpeningTag(text.slice(start, openingEnd + 1))) return;
479
+ const bodyStart = openingEnd + 2;
480
+ const bodyEnd = text.indexOf(CURRENT_INSTRUCTION_CLOSE, bodyStart);
481
+ if (bodyEnd < bodyStart) return;
482
+ return text.slice(bodyStart, bodyEnd);
483
+ }
484
+ /** Render the active user task in a stable prompt boundary. */
485
+ function renderCurrentInstruction(instruction, attrs) {
486
+ const renderedAttrs = [
487
+ attrs?.authorId ? `author_id="${escapeXml(attrs.authorId)}"` : void 0,
488
+ attrs?.authorName ? `author_name="${escapeXml(attrs.authorName)}"` : void 0,
489
+ attrs?.slackTs ? `slack_ts="${escapeXml(attrs.slackTs)}"` : void 0
490
+ ].filter((attr) => Boolean(attr)).join(" ");
491
+ return [
492
+ renderedAttrs ? `<${CURRENT_INSTRUCTION_TAG} ${renderedAttrs}>` : `<${CURRENT_INSTRUCTION_TAG}>`,
493
+ escapeXml(instruction),
494
+ `</${CURRENT_INSTRUCTION_TAG}>`
495
+ ].join("\n");
496
+ }
497
+ /** Recover display text from the internal current-task prompt boundary. */
498
+ function unwrapCurrentInstruction(text) {
499
+ const body = readCurrentInstructionBody(text);
500
+ return body === void 0 ? void 0 : unescapeXml(body);
501
+ }
502
+ // src/chat/services/context-compaction-marker.ts
503
+ const COMPACTION_SUMMARY_PREFIX = "Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:";
504
+ /** Return whether text is one of Junior's durable compacted-context markers. */
505
+ function isCompactionSummaryText(text) {
506
+ const normalized = (unwrapCurrentInstruction(text) ?? text).trimStart();
507
+ return normalized.startsWith("Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:") || normalized.startsWith("Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:");
508
+ }
509
+ /** Return whether model-visible history contains a durable compacted context marker. */
510
+ function hasCompactedConversationContext(messages) {
511
+ return messages.some((message) => {
512
+ const content = message.content;
513
+ if (typeof content === "string") return isCompactionSummaryText(content);
514
+ if (!Array.isArray(content)) return false;
515
+ return content.some((part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string" && isCompactionSummaryText(part.text));
516
+ });
517
+ }
518
+ // src/chat/services/image-dimensions.ts
519
+ const HEADER_BASE64_CHARS = 65536;
520
+ const READERS = {
521
+ "image/png": readPng,
522
+ "image/jpeg": readJpeg,
523
+ "image/gif": readGif,
524
+ "image/webp": readWebp
525
+ };
526
+ /**
527
+ * Read the pixel size from an image header without decoding the image.
528
+ * Returns undefined when the type is unknown or the header is not valid.
529
+ */
530
+ function readImageDimensions(image) {
531
+ const read = READERS[image.mimeType.toLowerCase()];
532
+ if (!read) return void 0;
533
+ const prefix = Buffer.from(image.data.slice(0, HEADER_BASE64_CHARS), "base64");
534
+ const canReadMore = read === readJpeg && image.data.length > HEADER_BASE64_CHARS;
535
+ const dimensions = read(prefix) ?? (canReadMore ? read(Buffer.from(image.data, "base64")) : void 0);
536
+ return dimensions && dimensions.width > 0 && dimensions.height > 0 ? dimensions : void 0;
537
+ }
538
+ function hasAscii(bytes, offset, text) {
539
+ return bytes.toString("latin1", offset, offset + text.length) === text;
540
+ }
541
+ function readPng(bytes) {
542
+ if (bytes.length < 24) return void 0;
543
+ if (bytes.readUInt32BE(0) !== 2303741511 || !hasAscii(bytes, 12, "IHDR")) return;
544
+ return {
545
+ width: bytes.readUInt32BE(16),
546
+ height: bytes.readUInt32BE(20)
547
+ };
548
+ }
549
+ function readGif(bytes) {
550
+ if (bytes.length < 10) return void 0;
551
+ if (!hasAscii(bytes, 0, "GIF87a") && !hasAscii(bytes, 0, "GIF89a")) return;
552
+ return {
553
+ width: bytes.readUInt16LE(6),
554
+ height: bytes.readUInt16LE(8)
555
+ };
556
+ }
557
+ function readJpeg(bytes) {
558
+ if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216) return;
559
+ let offset = 2;
560
+ while (offset + 4 <= bytes.length) {
561
+ if (bytes[offset] !== 255) return void 0;
562
+ const marker = bytes[offset + 1];
563
+ if (marker === 255) {
564
+ offset += 1;
565
+ continue;
566
+ }
567
+ if (marker === 1 || marker >= 208 && marker <= 215) {
568
+ offset += 2;
569
+ continue;
570
+ }
571
+ const length = bytes.readUInt16BE(offset + 2);
572
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
573
+ if (offset + 9 > bytes.length) return void 0;
574
+ return {
575
+ height: bytes.readUInt16BE(offset + 5),
576
+ width: bytes.readUInt16BE(offset + 7)
577
+ };
578
+ }
579
+ if (length < 2) return void 0;
580
+ offset += 2 + length;
581
+ }
582
+ }
583
+ function readWebp(bytes) {
584
+ if (bytes.length < 30) return void 0;
585
+ if (!hasAscii(bytes, 0, "RIFF") || !hasAscii(bytes, 8, "WEBP")) return;
586
+ if (hasAscii(bytes, 12, "VP8 ")) {
587
+ if (bytes.readUIntBE(23, 3) !== 10289450) return void 0;
588
+ return {
589
+ width: bytes.readUInt16LE(26) & 16383,
590
+ height: bytes.readUInt16LE(28) & 16383
591
+ };
592
+ }
593
+ if (hasAscii(bytes, 12, "VP8L")) {
594
+ if (bytes[20] !== 47) return void 0;
595
+ const bits = bytes.readUInt32LE(21);
596
+ return {
597
+ width: (bits & 16383) + 1,
598
+ height: (bits >>> 14 & 16383) + 1
599
+ };
600
+ }
601
+ if (hasAscii(bytes, 12, "VP8X")) return {
602
+ width: bytes.readUIntLE(24, 3) + 1,
603
+ height: bytes.readUIntLE(27, 3) + 1
604
+ };
605
+ }
606
+ // src/chat/services/token-estimate.ts
607
+ const CLAUDE_TOKEN_ESTIMATE = {
608
+ charsPerToken: 2.5,
609
+ toolResultOverheadTokens: 150
610
+ };
611
+ const DEFAULT_TOKEN_ESTIMATE = {
612
+ charsPerToken: 4,
613
+ toolResultOverheadTokens: 0
614
+ };
615
+ const IMAGE_CHARS = 4800;
616
+ const CLAUDE_HIGH_RES_IMAGE = {
617
+ maxEdge: 2576,
618
+ maxTokens: 4784
619
+ };
620
+ const CLAUDE_STANDARD_IMAGE = {
621
+ maxEdge: 1568,
622
+ maxTokens: 1568
623
+ };
624
+ const CLAUDE_STANDARD_IMAGE_MODEL = /^anthropic\/claude-(?:3\b|[a-z]+-4(?:\.[0-6])?(?![.\d]))/;
625
+ const CLAUDE_IMAGE_PATCH_PX = 28;
626
+ function getTokenEstimateProfile(modelId) {
627
+ return modelId.startsWith("anthropic/") ? CLAUDE_TOKEN_ESTIMATE : DEFAULT_TOKEN_ESTIMATE;
628
+ }
629
+ function tokensForChars(chars, profile) {
630
+ return Math.ceil(chars / profile.charsPerToken);
631
+ }
632
+ function messageChars(message) {
633
+ switch (message.role) {
634
+ case "user":
635
+ case "toolResult": return contentChars(message.content);
636
+ case "assistant": {
637
+ let chars = 0;
638
+ for (const block of message.content) if (block.type === "text") chars += block.text.length;
639
+ else if (block.type === "thinking") chars += block.thinking.length;
640
+ else chars += block.name.length + JSON.stringify(block.arguments).length;
641
+ return chars;
642
+ }
643
+ default: return 0;
644
+ }
645
+ }
646
+ function contentChars(content) {
647
+ if (typeof content === "string") return content.length;
648
+ return content.reduce((chars, block) => chars + (block.type === "text" ? block.text.length : 0), 0);
649
+ }
650
+ function messageImages(message) {
651
+ if (message.role !== "user" && message.role !== "toolResult") return [];
652
+ if (typeof message.content === "string") return [];
653
+ return message.content.filter((block) => block.type === "image");
654
+ }
655
+ function claudeImagePatches(width, height) {
656
+ return Math.ceil(width / CLAUDE_IMAGE_PATCH_PX) * Math.ceil(height / CLAUDE_IMAGE_PATCH_PX);
657
+ }
658
+ function roundHalfToEven(value) {
659
+ const floor = Math.floor(value);
660
+ if (value - floor !== .5) return Math.round(value);
661
+ return floor % 2 === 0 ? floor : floor + 1;
662
+ }
663
+ /**
664
+ * The size Claude resizes an image to before it counts patches. This is the
665
+ * reference implementation in "How Claude resizes and pads images" in
666
+ * https://platform.claude.com/docs/en/build-with-claude/vision-coordinates:
667
+ * the largest aspect-preserving size whose padded edges and patch count fit
668
+ * the tier limits.
669
+ */
670
+ function claudeResizedImageSize(width, height, limits) {
671
+ const fits = (w, h) => Math.ceil(w / CLAUDE_IMAGE_PATCH_PX) * CLAUDE_IMAGE_PATCH_PX <= limits.maxEdge && Math.ceil(h / CLAUDE_IMAGE_PATCH_PX) * CLAUDE_IMAGE_PATCH_PX <= limits.maxEdge && claudeImagePatches(w, h) <= limits.maxTokens;
672
+ if (fits(width, height)) return [width, height];
673
+ if (height > width) {
674
+ const [resizedHeight, resizedWidth] = claudeResizedImageSize(height, width, limits);
675
+ return [resizedWidth, resizedHeight];
676
+ }
677
+ const aspectRatio = width / height;
678
+ const shortEdge = (longEdge) => Math.max(roundHalfToEven(longEdge / aspectRatio), 1);
679
+ let low = 1;
680
+ let high = width;
681
+ while (low + 1 < high) {
682
+ const mid = Math.floor((low + high) / 2);
683
+ if (fits(mid, shortEdge(mid))) low = mid;
684
+ else high = mid;
685
+ }
686
+ return [low, shortEdge(low)];
687
+ }
688
+ /**
689
+ * Estimate one image for a model with the rule that `estimateMessagesTokens`
690
+ * uses. `sized` is false when the image used the flat per-image value.
691
+ */
692
+ function estimateImageTokens(image, modelId) {
693
+ const dimensions = modelId.startsWith("anthropic/") ? readImageDimensions(image) : void 0;
694
+ if (!dimensions) return {
695
+ tokens: tokensForChars(IMAGE_CHARS, getTokenEstimateProfile(modelId)),
696
+ sized: false
697
+ };
698
+ const limits = CLAUDE_STANDARD_IMAGE_MODEL.test(modelId) ? CLAUDE_STANDARD_IMAGE : CLAUDE_HIGH_RES_IMAGE;
699
+ const [width, height] = claudeResizedImageSize(dimensions.width, dimensions.height, limits);
700
+ return {
701
+ tokens: claudeImagePatches(width, height),
702
+ sized: true
703
+ };
704
+ }
705
+ /** Estimate text tokens for local budgets that have no model. */
706
+ function estimateTextTokens(text) {
707
+ return tokensForChars(text.length, DEFAULT_TOKEN_ESTIMATE);
708
+ }
709
+ /** Convert a local text token budget to the characters it allows. */
710
+ function textCharsForTokens(tokens) {
711
+ return tokens * DEFAULT_TOKEN_ESTIMATE.charsPerToken;
712
+ }
713
+ /**
714
+ * Estimate messages from their text size at the model's characters per token,
715
+ * plus the tokens of each image.
716
+ */
717
+ function estimateMessagesTokens(messages, modelId) {
718
+ const profile = getTokenEstimateProfile(modelId);
719
+ return messages.reduce((total, message) => {
720
+ const overhead = message.role === "toolResult" ? profile.toolResultOverheadTokens : 0;
721
+ const images = messageImages(message).reduce((tokens, image) => tokens + estimateImageTokens(image, modelId).tokens, 0);
722
+ return total + tokensForChars(messageChars(message), profile) + images + overhead;
723
+ }, 0);
724
+ }
725
+ /** Estimate the tokens that the system prompt and tool definitions add to a model request. */
726
+ function estimateRequestOverheadTokens(systemPrompt, tools, modelId) {
727
+ const definitions = tools.map(({ name, description, parameters }) => ({
728
+ name,
729
+ description,
730
+ parameters
731
+ }));
732
+ return tokensForChars(systemPrompt.length + JSON.stringify(definitions).length, getTokenEstimateProfile(modelId));
733
+ }
734
+ // src/chat/pi/request-prefix-attributes.ts
735
+ const HASH_HEX_CHARS = 16;
736
+ const MESSAGE_SEPARATOR = "\n";
737
+ function withoutCacheControl(key, value) {
738
+ return key === "cache_control" ? void 0 : value;
739
+ }
740
+ function canonicalMessageValue(key, value) {
741
+ if (key === "content" && typeof value === "string") return [{
742
+ type: "text",
743
+ text: value
744
+ }];
745
+ return withoutCacheControl(key, value);
746
+ }
747
+ function digest(hash) {
748
+ return hash.digest("hex").slice(0, HASH_HEX_CHARS);
749
+ }
750
+ function hashJson(value, replacer = withoutCacheControl) {
751
+ return digest(createHash("sha256").update(JSON.stringify(value, replacer)));
752
+ }
753
+ function lastAssistantIndex(messages) {
754
+ for (let index = messages.length - 1; index >= 0; index--) {
755
+ const message = messages[index];
756
+ if (typeof message === "object" && message !== null && message.role === "assistant") return index;
757
+ }
758
+ return -1;
759
+ }
760
+ function messagesHashes(messages) {
761
+ const lastReply = lastAssistantIndex(messages);
762
+ const hash = createHash("sha256");
763
+ let beforeLastReply;
764
+ for (const [index, message] of messages.entries()) {
765
+ if (index === lastReply) beforeLastReply = digest(hash.copy());
766
+ hash.update(JSON.stringify(message, canonicalMessageValue)).update(MESSAGE_SEPARATOR);
767
+ }
768
+ return {
769
+ full: digest(hash),
770
+ beforeLastReply
771
+ };
772
+ }
773
+ function sortedKeys(_key, value) {
774
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
775
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
776
+ }
777
+ function prefixHash(parts) {
778
+ return digest(createHash("sha256").update(parts.map((part) => part ?? "").join("\n")));
779
+ }
780
+ function readableString(value, key) {
781
+ if (typeof value !== "object" || value === null) return;
782
+ const field = value[key];
783
+ return typeof field === "string" ? field : void 0;
784
+ }
785
+ function requestImages(messages) {
786
+ const images = [];
787
+ const visit = (content) => {
788
+ if (!Array.isArray(content)) return;
789
+ for (const block of content) {
790
+ if (typeof block !== "object" || block === null) continue;
791
+ const { type, source, content: nested } = block;
792
+ if (type === "image") images.push({
793
+ type: "image",
794
+ data: readableString(source, "data") ?? "",
795
+ mimeType: readableString(source, "media_type") ?? ""
796
+ });
797
+ else if (type === "tool_result") visit(nested);
798
+ }
799
+ };
800
+ for (const message of messages) visit(message?.content);
801
+ return images;
802
+ }
803
+ function imageAttributes(messages, model) {
804
+ const images = Array.isArray(messages) ? requestImages(messages) : [];
805
+ if (images.length === 0) return {};
806
+ const modelId = typeof model === "string" ? model : "";
807
+ let estimate = 0;
808
+ let unsized = 0;
809
+ for (const image of images) {
810
+ const { tokens, sized } = estimateImageTokens(image, modelId);
811
+ estimate += tokens;
812
+ if (!sized) unsized += 1;
813
+ }
814
+ return {
815
+ "app.ai.request.images.count": images.length,
816
+ "app.ai.request.images.estimate": estimate,
817
+ "app.ai.request.images.unsized": unsized
818
+ };
819
+ }
820
+ function payloadAttributes(payload) {
821
+ const { model, system, tools, messages, thinking, output_config } = payload;
822
+ const systemHash = system !== void 0 ? hashJson(system) : void 0;
823
+ const toolsHash = Array.isArray(tools) ? hashJson(tools) : void 0;
824
+ const messagesHash = Array.isArray(messages) ? messagesHashes(messages) : void 0;
825
+ const settingsHash = hashJson({
826
+ thinking,
827
+ output_config
828
+ }, sortedKeys);
829
+ const prefixParts = [
830
+ typeof model === "string" ? model : void 0,
831
+ settingsHash,
832
+ toolsHash,
833
+ systemHash
834
+ ];
835
+ const thinkingType = readableString(thinking, "type");
836
+ const effort = readableString(output_config, "effort");
837
+ return {
838
+ ...systemHash ? { "app.ai.request.system_instructions.hash": systemHash } : void 0,
839
+ "app.ai.request.tools.count": Array.isArray(tools) ? tools.length : 0,
840
+ ...toolsHash ? { "app.ai.request.tools.hash": toolsHash } : void 0,
841
+ ...Array.isArray(messages) ? { "app.ai.request.messages.count": messages.length } : void 0,
842
+ ...messagesHash ? { "app.ai.request.messages.hash": messagesHash.full } : void 0,
843
+ ...messagesHash?.beforeLastReply ? { "app.ai.request.messages.before_last_reply.hash": messagesHash.beforeLastReply } : void 0,
844
+ "app.ai.request.prefix.hash": prefixHash([...prefixParts, messagesHash?.full]),
845
+ ...messagesHash?.beforeLastReply ? { "app.ai.request.prefix.before_last_reply.hash": prefixHash([...prefixParts, messagesHash.beforeLastReply]) } : void 0,
846
+ ...thinkingType ? { "app.ai.request.thinking.type": thinkingType } : void 0,
847
+ ...effort ? { "app.ai.request.effort": effort } : void 0,
848
+ ...imageAttributes(messages, model)
849
+ };
850
+ }
851
+ /**
852
+ * Hashes of the cache prefix parts of one provider request body, plus its
853
+ * thinking and effort settings, to tell a changed cache prefix apart from an
854
+ * expired cache. Also counts and estimates the request's images.
855
+ * Pass the payload that Pi gives to `onPayload`. Never throws: telemetry must
856
+ * not fail the request.
857
+ */
858
+ function requestPrefixAttributes(payload) {
859
+ if (typeof payload !== "object" || payload === null) return {};
860
+ try {
861
+ return payloadAttributes(payload);
862
+ } catch {
863
+ return {};
864
+ }
865
+ }
866
+ // src/chat/pi/client.ts
867
+ registerApiProvider({
868
+ api: "anthropic-messages",
869
+ stream: streamAnthropic,
870
+ streamSimple: streamSimpleAnthropic
871
+ });
872
+ const GATEWAY_PROVIDER = "vercel-ai-gateway";
873
+ const GATEWAY_BASE_URL = "https://ai-gateway.vercel.sh";
874
+ const GATEWAY_MODEL_OVERRIDES = {
875
+ "anthropic/claude-opus-5.5": {
876
+ id: "anthropic/claude-opus-5.5",
877
+ name: "Claude Opus 5.5",
878
+ api: "anthropic-messages",
879
+ provider: GATEWAY_PROVIDER,
880
+ baseUrl: GATEWAY_BASE_URL,
881
+ reasoning: true,
882
+ input: ["text", "image"],
883
+ cost: {
884
+ input: 4,
885
+ output: 20,
886
+ cacheRead: .2,
887
+ cacheWrite: 5
888
+ },
889
+ contextWindow: 1e6,
890
+ maxTokens: 128e3,
891
+ thinkingLevelMap: {
892
+ xhigh: "xhigh",
893
+ max: "max"
894
+ },
895
+ compat: {
896
+ forceAdaptiveThinking: true,
897
+ supportsTemperature: false
898
+ }
899
+ },
900
+ "xai/grok-4.5": {
901
+ id: "xai/grok-4.5",
902
+ name: "Grok 4.5",
903
+ api: "anthropic-messages",
904
+ provider: GATEWAY_PROVIDER,
905
+ baseUrl: GATEWAY_BASE_URL,
906
+ reasoning: true,
907
+ input: ["text", "image"],
908
+ cost: {
909
+ input: 2,
910
+ output: 6,
911
+ cacheRead: .3,
912
+ cacheWrite: 0
913
+ },
914
+ contextWindow: 5e5,
915
+ maxTokens: 5e5
916
+ },
917
+ "openai/gpt-6-luna": {
918
+ id: "openai/gpt-6-luna",
919
+ name: "GPT-6 Luna",
920
+ api: "anthropic-messages",
921
+ provider: GATEWAY_PROVIDER,
922
+ baseUrl: GATEWAY_BASE_URL,
923
+ reasoning: true,
924
+ input: ["text", "image"],
925
+ cost: {
926
+ input: .1,
927
+ output: .5,
928
+ cacheRead: .01,
929
+ cacheWrite: .125,
930
+ tiers: [{
931
+ inputTokensAbove: 272e3,
932
+ input: .2,
933
+ output: .75,
934
+ cacheRead: .02,
935
+ cacheWrite: .25
936
+ }]
937
+ },
938
+ contextWindow: 105e4,
939
+ maxTokens: 128e3,
940
+ thinkingLevelMap: {
941
+ xhigh: "xhigh",
942
+ max: "max"
943
+ }
944
+ },
945
+ "openai/gpt-6-astra": {
946
+ id: "openai/gpt-6-astra",
947
+ name: "GPT-6 Astra",
948
+ api: "anthropic-messages",
949
+ provider: GATEWAY_PROVIDER,
950
+ baseUrl: GATEWAY_BASE_URL,
951
+ reasoning: true,
952
+ input: ["text", "image"],
953
+ cost: {
954
+ input: 10,
955
+ output: 50,
956
+ cacheRead: 1,
957
+ cacheWrite: 12.5,
958
+ tiers: [{
959
+ inputTokensAbove: 272e3,
960
+ input: 20,
961
+ output: 75,
962
+ cacheRead: 2,
963
+ cacheWrite: 25
964
+ }]
965
+ },
966
+ contextWindow: 105e4,
967
+ maxTokens: 128e3,
968
+ thinkingLevelMap: {
969
+ xhigh: "xhigh",
970
+ max: "max"
971
+ },
972
+ compat: { supportsTemperature: false }
973
+ }
974
+ };
975
+ const GEN_AI_PROVIDER_NAME = GATEWAY_PROVIDER;
976
+ const GEN_AI_SERVER_ADDRESS = "ai-gateway.vercel.sh";
977
+ const GEN_AI_OPERATION_CHAT = "chat";
978
+ const GEN_AI_OPERATION_EMBEDDINGS = "embeddings";
979
+ const GEN_AI_OPERATION_RERANK = "rerank";
980
+ const GEN_AI_OPERATION_DECIDE = "decide";
981
+ const GEN_AI_OPERATION_TRANSCRIPTION = "transcription";
982
+ const EMBEDDING_INPUT_COST_USD_PER_MILLION_TOKENS = {
983
+ "cohere/embed-v4.0": .12,
984
+ "google/gemini-embedding-001": .15,
985
+ "google/text-embedding-005": .025,
986
+ "mistral/mistral-embed": .1,
987
+ "openai/text-embedding-3-large": .13,
988
+ "openai/text-embedding-3-small": .02,
989
+ "openai/text-embedding-ada-002": .1,
990
+ "voyage/voyage-3.5": .06,
991
+ "voyage/voyage-3.5-lite": .02,
992
+ "voyage/voyage-4": .06,
993
+ "voyage/voyage-4-large": .12,
994
+ "voyage/voyage-4-lite": .02
995
+ };
996
+ const DECISION_INPUT_COST_USD_PER_MILLION_TOKENS = {
997
+ "openai/gpt-6-luna-decisions": .1,
998
+ "typesafe-ai/jev": .042
999
+ };
1000
+ function decisionCostUsd(modelId, inputTokens) {
1001
+ const costPerMillionTokens = DECISION_INPUT_COST_USD_PER_MILLION_TOKENS[modelId];
1002
+ return costPerMillionTokens === void 0 || inputTokens === void 0 ? void 0 : inputTokens * costPerMillionTokens / 1e6;
1003
+ }
1004
+ function embeddingCostUsd(modelId, inputTokens) {
1005
+ const costPerMillionTokens = EMBEDDING_INPUT_COST_USD_PER_MILLION_TOKENS[modelId];
1006
+ return costPerMillionTokens === void 0 ? void 0 : inputTokens * costPerMillionTokens / 1e6;
1007
+ }
1008
+ function extractText(message) {
1009
+ return (message.content ?? []).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text ?? "").join("").trim();
1010
+ }
1011
+ /** Resolve gateway models through local overrides, then Pi's bundled catalog. */
1012
+ function resolveGatewayModel(modelId) {
1013
+ const matched = GATEWAY_MODEL_OVERRIDES[modelId] ?? getModels(GATEWAY_PROVIDER).find((model) => model.id === modelId);
1014
+ if (!matched) throw new Error(`Unknown AI Gateway model id: ${modelId}`);
1015
+ return {
1016
+ ...matched,
1017
+ compat: {
1018
+ ...matched.compat,
1019
+ sendSessionAffinityHeaders: true
1020
+ }
1021
+ };
1022
+ }
1023
+ /** Execute a direct chat completion inside a dedicated `gen_ai.chat` span. */
1024
+ async function completeText(params) {
1025
+ const model = resolveGatewayModel(params.modelId);
1026
+ const credential = await resolveGatewayCredential();
1027
+ const apiKey = credential.token;
1028
+ const authMode = credential.mode;
1029
+ const effectivePrivacy = getCurrentConversationPrivacy() ?? "private";
1030
+ const messageAttributeMode = params.messageAttributeMode ?? (effectivePrivacy === "public" ? "content" : "metadata");
1031
+ const requestMessagesAttribute = messageAttributeMode === "content" ? serializeGenAiAttribute(params.messages.map(toCanonicalInputMessage)) : void 0;
1032
+ const systemInstructionsAttribute = params.system && messageAttributeMode === "content" ? serializeGenAiAttribute([{
1033
+ type: "text",
1034
+ content: params.system
1035
+ }]) : void 0;
1036
+ const baseAttributes = {
1037
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
1038
+ "gen_ai.operation.name": GEN_AI_OPERATION_CHAT,
1039
+ "gen_ai.request.model": params.modelId,
1040
+ "gen_ai.output.type": "text",
1041
+ ...params.promptName ? { "gen_ai.prompt.name": params.promptName } : void 0,
1042
+ "server.address": GEN_AI_SERVER_ADDRESS,
1043
+ "server.port": 443,
1044
+ ...hasCompactedConversationContext(params.messages) ? { "gen_ai.conversation.compacted": true } : void 0,
1045
+ "app.conversation.privacy": effectivePrivacy,
1046
+ ...params.thinkingLevel ? { "gen_ai.request.reasoning.level": params.thinkingLevel } : void 0,
1047
+ ...params.temperature !== void 0 ? { "gen_ai.request.temperature": params.temperature } : void 0,
1048
+ ...params.maxTokens !== void 0 ? { "gen_ai.request.max_tokens": params.maxTokens } : void 0
1049
+ };
1050
+ const startAttributes = {
1051
+ ...baseAttributes,
1052
+ ...toGenAiMessagesTraceAttributes("gen_ai.input", params.messages),
1053
+ ...params.system ? { "gen_ai.system_instructions.content_chars": params.system.length } : void 0,
1054
+ ...systemInstructionsAttribute ? { "gen_ai.system_instructions": systemInstructionsAttribute } : void 0,
1055
+ ...requestMessagesAttribute ? { "gen_ai.input.messages": requestMessagesAttribute } : void 0,
1056
+ "gen_ai.provider.auth_mode": authMode
1057
+ };
1058
+ return withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
1059
+ let message;
1060
+ try {
1061
+ message = await completeSimple(model, {
1062
+ systemPrompt: params.system,
1063
+ messages: params.messages,
1064
+ ...params.tools ? { tools: params.tools } : void 0
1065
+ }, {
1066
+ apiKey,
1067
+ temperature: params.temperature,
1068
+ maxTokens: params.maxTokens,
1069
+ reasoning: params.thinkingLevel,
1070
+ cacheRetention: params.cacheRetention,
1071
+ signal: params.signal,
1072
+ metadata: params.metadata,
1073
+ sessionId: params.sessionId,
1074
+ onPayload: (payload) => {
1075
+ setSpanAttributes(requestPrefixAttributes(payload));
1076
+ }
1077
+ });
1078
+ } catch (error) {
1079
+ throw createProviderError(error, { modelId: params.modelId });
1080
+ }
1081
+ const outputText = extractText(message);
1082
+ const outputMessagesAttribute = serializeGenAiAttribute(messageAttributeMode === "content" ? [toCanonicalOutputMessage(message)] : void 0);
1083
+ const usageAttributes = extractGenAiUsageAttributes(message);
1084
+ setSpanAttributes({
1085
+ ...baseAttributes,
1086
+ ...toGenAiMessagesTraceAttributes("gen_ai.output", [{
1087
+ role: "assistant",
1088
+ content: outputText ? [{
1089
+ type: "text",
1090
+ text: outputText
1091
+ }] : []
1092
+ }]),
1093
+ ...outputMessagesAttribute ? { "gen_ai.output.messages": outputMessagesAttribute } : void 0,
1094
+ ...usageAttributes,
1095
+ ...message.stopReason ? { "gen_ai.response.finish_reasons": [normalizeGenAiFinishReason(message.stopReason)] } : void 0,
1096
+ ...message.model ? { "gen_ai.response.model": message.model } : void 0
1097
+ });
1098
+ if (message.stopReason === "error") {
1099
+ const providerMessage = message.errorMessage?.trim() || "Unknown provider error";
1100
+ logWarn("ai.completion.provider_error", {
1101
+ ...baseAttributes,
1102
+ "exception.message": providerMessage
1103
+ });
1104
+ throw createProviderError(providerMessage, { modelId: params.modelId });
1105
+ }
1106
+ return {
1107
+ message,
1108
+ text: outputText
1109
+ };
1110
+ }, startAttributes);
1111
+ }
1112
+ function logContextFromMetadata(modelId, metadata) {
1113
+ const conversationId = typeof metadata?.conversationId === "string" ? metadata.conversationId : typeof metadata?.threadId === "string" ? metadata.threadId : void 0;
1114
+ const messageConversationId = typeof metadata?.threadId === "string" ? metadata.threadId : void 0;
1115
+ const destinationName = typeof metadata?.channelId === "string" ? metadata.channelId : void 0;
1116
+ const runId = typeof metadata?.runId === "string" ? metadata.runId : void 0;
1117
+ return {
1118
+ modelId,
1119
+ ...conversationId ? { conversationId } : void 0,
1120
+ ...messageConversationId ? { messageConversationId } : void 0,
1121
+ ...destinationName ? { destinationName } : void 0,
1122
+ ...runId ? { runId } : void 0
1123
+ };
1124
+ }
1125
+ function objectCompletionCost(modelId, usage) {
1126
+ const cacheRead = usage.inputTokenDetails.cacheReadTokens;
1127
+ const cacheWrite = usage.inputTokenDetails.cacheWriteTokens;
1128
+ const input = usage.inputTokenDetails.noCacheTokens ?? (usage.inputTokens === void 0 ? void 0 : Math.max(0, usage.inputTokens - (cacheRead ?? 0) - (cacheWrite ?? 0)));
1129
+ if (input === void 0 && usage.outputTokens === void 0 && cacheRead === void 0 && cacheWrite === void 0) return;
1130
+ return calculateCost(resolveGatewayModel(modelId), {
1131
+ input: input ?? 0,
1132
+ output: usage.outputTokens ?? 0,
1133
+ cacheRead: cacheRead ?? 0,
1134
+ cacheWrite: cacheWrite ?? 0,
1135
+ ...usage.outputTokenDetails.reasoningTokens !== void 0 ? { reasoning: usage.outputTokenDetails.reasoningTokens } : void 0,
1136
+ totalTokens: usage.totalTokens ?? (input ?? 0) + (usage.outputTokens ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0),
1137
+ cost: {
1138
+ input: 0,
1139
+ output: 0,
1140
+ cacheRead: 0,
1141
+ cacheWrite: 0,
1142
+ total: 0
1143
+ }
1144
+ }).total;
1145
+ }
1146
+ /** Estimate cost without changing the outcome of a successful completion. */
1147
+ function bestEffortObjectCompletionCost(modelId, usage) {
1148
+ try {
1149
+ return objectCompletionCost(modelId, usage);
1150
+ } catch (error) {
1151
+ logWarn("ai.completion.cost_estimate.failed", {
1152
+ "exception.message": error instanceof Error ? error.message : String(error),
1153
+ "gen_ai.request.model": modelId
1154
+ });
1155
+ return;
1156
+ }
1157
+ }
1158
+ /** Execute a schema-constrained completion using the AI SDK structured output path. */
1159
+ async function completeObject(params) {
1160
+ const credential = await resolveGatewayCredential();
1161
+ const provider = createGatewayProvider({ apiKey: credential.token });
1162
+ let result;
1163
+ try {
1164
+ result = await withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
1165
+ const result = await generateObject({
1166
+ model: provider.chat(params.modelId),
1167
+ schema: params.schema,
1168
+ prompt: params.prompt,
1169
+ ...params.system !== void 0 ? { system: params.system } : void 0,
1170
+ ...params.temperature !== void 0 ? { temperature: params.temperature } : void 0,
1171
+ ...params.maxTokens !== void 0 ? { maxOutputTokens: params.maxTokens } : void 0,
1172
+ ...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
1173
+ });
1174
+ setSpanAttributes({
1175
+ "gen_ai.response.finish_reasons": [result.finishReason],
1176
+ ...extractGenAiUsageAttributes(result.usage)
1177
+ });
1178
+ return result;
1179
+ }, {
1180
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
1181
+ "gen_ai.operation.name": GEN_AI_OPERATION_CHAT,
1182
+ "gen_ai.request.model": params.modelId,
1183
+ "gen_ai.output.type": "json",
1184
+ ...params.promptName ? { "gen_ai.prompt.name": params.promptName } : void 0,
1185
+ "server.address": GEN_AI_SERVER_ADDRESS,
1186
+ "server.port": 443,
1187
+ "gen_ai.provider.auth_mode": credential.mode,
1188
+ ...params.thinkingLevel ? { "gen_ai.request.reasoning.level": params.thinkingLevel } : void 0,
1189
+ ...params.temperature !== void 0 ? { "gen_ai.request.temperature": params.temperature } : void 0,
1190
+ ...params.maxTokens !== void 0 ? { "gen_ai.request.max_tokens": params.maxTokens } : void 0
1191
+ });
1192
+ } catch (error) {
1193
+ throw createProviderError(error, {
1194
+ ...NoObjectGeneratedError.isInstance(error) ? { kind: "invalid_response" } : void 0,
1195
+ modelId: params.modelId
1196
+ });
1197
+ }
1198
+ const costUsd = bestEffortObjectCompletionCost(params.modelId, result.usage);
1199
+ return {
1200
+ object: result.object,
1201
+ ...costUsd !== void 0 ? { costUsd } : void 0
1202
+ };
1203
+ }
1204
+ /** Answer typed decision questions with an AI Gateway decision model, such as Jev. */
1205
+ async function completeDecision(params) {
1206
+ const credential = await resolveGatewayCredential();
1207
+ const provider = createGatewayProvider({ apiKey: credential.token });
1208
+ try {
1209
+ const result = await withSpan(`${GEN_AI_OPERATION_DECIDE} ${params.modelId}`, "gen_ai.decide", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
1210
+ const result = await experimental_decide({
1211
+ model: provider.decisionModel(params.modelId),
1212
+ state: params.state,
1213
+ questions: params.questions,
1214
+ ...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
1215
+ });
1216
+ const costUsd = decisionCostUsd(params.modelId, result.usage.inputTokens);
1217
+ setSpanAttributes(extractGenAiUsageAttributes({
1218
+ ...result.usage,
1219
+ ...costUsd !== void 0 ? { cost: {
1220
+ input: costUsd,
1221
+ total: costUsd
1222
+ } } : void 0
1223
+ }));
1224
+ return {
1225
+ answers: result.answers,
1226
+ costUsd
1227
+ };
1228
+ }, {
1229
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
1230
+ "gen_ai.operation.name": GEN_AI_OPERATION_DECIDE,
1231
+ "gen_ai.request.model": params.modelId,
1232
+ ...params.promptName ? { "gen_ai.prompt.name": params.promptName } : void 0,
1233
+ "server.address": GEN_AI_SERVER_ADDRESS,
1234
+ "server.port": 443,
1235
+ "gen_ai.provider.auth_mode": credential.mode
1236
+ });
1237
+ return {
1238
+ answers: result.answers,
1239
+ ...result.costUsd !== void 0 ? { costUsd: result.costUsd } : void 0
1240
+ };
1241
+ } catch (error) {
1242
+ throw createProviderError(error, {
1243
+ ...Experimental_DecisionRefusalError.isInstance(error) ? { kind: "invalid_response" } : void 0,
1244
+ modelId: params.modelId
1245
+ });
1246
+ }
1247
+ }
1248
+ /** Map the input type to the provider option for models that embed queries and documents differently. */
1249
+ function embeddingProviderOptions(modelId, inputType) {
1250
+ if (inputType === void 0 || !modelId.startsWith("voyage/")) return;
1251
+ return { voyage: { inputType } };
1252
+ }
1253
+ /** Generate text embeddings through the host-owned AI Gateway provider. */
1254
+ async function embedTexts(params) {
1255
+ const texts = params.texts.map((text) => text.trim());
1256
+ if (texts.length === 0 || texts.some((text) => text.length === 0)) throw new Error("Embedding text is required.");
1257
+ const credential = await resolveGatewayCredential();
1258
+ const provider = createGatewayProvider({ apiKey: credential.token });
1259
+ const providerOptions = embeddingProviderOptions(params.modelId, params.inputType);
1260
+ try {
1261
+ const result = await withSpan(`${GEN_AI_OPERATION_EMBEDDINGS} ${params.modelId}`, "gen_ai.embeddings", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
1262
+ const result = await embedMany({
1263
+ model: provider.embeddingModel(params.modelId),
1264
+ values: texts,
1265
+ ...providerOptions !== void 0 ? { providerOptions } : void 0,
1266
+ ...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
1267
+ });
1268
+ const dimensions = result.embeddings[0]?.length;
1269
+ if (result.embeddings.length !== texts.length || !dimensions || !result.embeddings.every((embedding) => embedding.length === dimensions)) throw createProviderError("Embedding provider returned invalid vectors.", {
1270
+ kind: "invalid_response",
1271
+ modelId: params.modelId
1272
+ });
1273
+ const costUsd = embeddingCostUsd(params.modelId, result.usage.tokens);
1274
+ setSpanAttributes({
1275
+ "gen_ai.embeddings.dimension.count": dimensions,
1276
+ ...extractGenAiUsageAttributes({
1277
+ inputTokens: result.usage.tokens,
1278
+ ...costUsd !== void 0 ? { cost: {
1279
+ input: costUsd,
1280
+ total: costUsd
1281
+ } } : void 0
1282
+ })
1283
+ });
1284
+ return {
1285
+ costUsd,
1286
+ dimensions,
1287
+ result
1288
+ };
1289
+ }, {
1290
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
1291
+ "gen_ai.operation.name": GEN_AI_OPERATION_EMBEDDINGS,
1292
+ "gen_ai.request.model": params.modelId,
1293
+ "server.address": GEN_AI_SERVER_ADDRESS,
1294
+ "server.port": 443,
1295
+ "gen_ai.provider.auth_mode": credential.mode
1296
+ });
1297
+ return {
1298
+ ...result.costUsd !== void 0 ? { costUsd: result.costUsd } : void 0,
1299
+ dimensions: result.dimensions,
1300
+ model: params.modelId,
1301
+ provider: GEN_AI_PROVIDER_NAME,
1302
+ vectors: result.result.embeddings
1303
+ };
1304
+ } catch (error) {
1305
+ const providerError = createProviderError(error, { modelId: params.modelId });
1306
+ if (isProviderRetryError(providerError)) throw providerError;
1307
+ logException(providerError, "ai.embeddings.failed", {
1308
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
1309
+ "gen_ai.operation.name": GEN_AI_OPERATION_EMBEDDINGS,
1310
+ "gen_ai.request.model": params.modelId
1311
+ });
1312
+ throw providerError;
1313
+ }
1314
+ }
1315
+ /** Read the billed cost that AI Gateway reports in provider metadata. */
1316
+ function gatewayCostUsd(providerMetadata) {
1317
+ const cost = providerMetadata?.gateway?.cost;
1318
+ const value = typeof cost === "string" ? Number(cost) : cost;
1319
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
1320
+ }
1321
+ /** Score documents against one query through the host-owned AI Gateway provider. */
1322
+ async function rerankTexts(params) {
1323
+ const query = params.query.trim();
1324
+ if (!query || params.documents.length === 0) throw new Error("Reranking query and documents are required.");
1325
+ const credential = await resolveGatewayCredential();
1326
+ const provider = createGatewayProvider({ apiKey: credential.token });
1327
+ try {
1328
+ return await withSpan(`${GEN_AI_OPERATION_RERANK} ${params.modelId}`, "gen_ai.rerank", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
1329
+ const result = await rerank({
1330
+ model: provider.rerankingModel(params.modelId),
1331
+ query,
1332
+ documents: params.documents
1333
+ });
1334
+ const scores = params.documents.map(() => NaN);
1335
+ for (const { originalIndex, score } of result.ranking) scores[originalIndex] = score;
1336
+ if (result.ranking.length !== params.documents.length || !scores.every(Number.isFinite)) throw createProviderError("Reranking provider returned invalid scores.", {
1337
+ kind: "invalid_response",
1338
+ modelId: params.modelId
1339
+ });
1340
+ const costUsd = gatewayCostUsd(result.providerMetadata);
1341
+ if (costUsd !== void 0) setSpanAttributes(extractGenAiUsageAttributes({ cost: { total: costUsd } }));
1342
+ return {
1343
+ ...costUsd !== void 0 ? { costUsd } : void 0,
1344
+ scores
1345
+ };
1346
+ }, {
1347
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
1348
+ "gen_ai.operation.name": GEN_AI_OPERATION_RERANK,
1349
+ "gen_ai.request.model": params.modelId,
1350
+ "server.address": GEN_AI_SERVER_ADDRESS,
1351
+ "server.port": 443,
1352
+ "gen_ai.provider.auth_mode": credential.mode,
1353
+ "app.rerank.document.count": params.documents.length
1354
+ });
1355
+ } catch (error) {
1356
+ const providerError = createProviderError(error, { modelId: params.modelId });
1357
+ if (isProviderRetryError(providerError)) throw providerError;
1358
+ logException(providerError, "ai.rerank.failed", {
1359
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
1360
+ "gen_ai.operation.name": GEN_AI_OPERATION_RERANK,
1361
+ "gen_ai.request.model": params.modelId
1362
+ });
1363
+ throw providerError;
1364
+ }
1365
+ }
1366
+ /** Transcribe one recorded audio clip through AI Gateway. */
1367
+ async function transcribeAudio(params) {
1368
+ const credential = await resolveGatewayCredential();
1369
+ const provider = createGatewayProvider({ apiKey: credential.token });
1370
+ try {
1371
+ return await withSpan(`${GEN_AI_OPERATION_TRANSCRIPTION} ${params.modelId}`, "gen_ai.transcription", { modelId: params.modelId }, async (setSpanAttributes) => {
1372
+ const result = await transcribe({
1373
+ model: provider.transcriptionModel(params.modelId),
1374
+ audio: params.audio,
1375
+ ...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
1376
+ });
1377
+ if (result.durationInSeconds !== void 0) setSpanAttributes({ "app.transcription.audio_seconds": result.durationInSeconds });
1378
+ return { text: result.text };
1379
+ }, {
1380
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
1381
+ "gen_ai.operation.name": GEN_AI_OPERATION_TRANSCRIPTION,
1382
+ "gen_ai.request.model": params.modelId,
1383
+ "server.address": GEN_AI_SERVER_ADDRESS,
1384
+ "server.port": 443,
1385
+ "gen_ai.provider.auth_mode": credential.mode,
1386
+ "app.transcription.audio_bytes": params.audio.byteLength
1387
+ });
1388
+ } catch (error) {
1389
+ const providerError = createProviderError(error, { modelId: params.modelId });
1390
+ logException(providerError, "ai.transcription.failed", {
1391
+ ...getProviderErrorAttributes(providerError),
1392
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
1393
+ "gen_ai.operation.name": GEN_AI_OPERATION_TRANSCRIPTION,
1394
+ "gen_ai.request.model": params.modelId
1395
+ });
1396
+ throw providerError;
1397
+ }
1398
+ }
1399
+ // src/chat/slack/emoji.ts
1400
+ const SLACK_EMOJI_NAME_RE = /^(?:[a-z0-9_+-]+)(?:::(?:skin-tone-[2-6]))?$/;
1401
+ function normalizeSlackEmojiName(value) {
1402
+ const trimmed = value.trim().toLowerCase();
1403
+ if (!trimmed) return null;
1404
+ const normalized = trimmed.startsWith(":") && trimmed.endsWith(":") ? trimmed.slice(1, -1) : trimmed;
1405
+ return SLACK_EMOJI_NAME_RE.test(normalized) ? normalized : null;
1406
+ }
1407
+ // src/chat/reasoning-level.ts
1408
+ const TURN_REASONING_LEVELS = [
1409
+ "none",
1410
+ "low",
1411
+ "medium",
1412
+ "high",
1413
+ "xhigh"
1414
+ ];
1415
+ /** Validate a configured main-agent reasoning level. */
1416
+ function parseTurnReasoningLevel(value) {
1417
+ return z.enum(TURN_REASONING_LEVELS).parse(value);
1418
+ }
1419
+ /** Convert a reasoning level into the Pi Agent setting for a main Turn. */
1420
+ function toPiReasoningLevel(level) {
1421
+ return level === "none" ? "off" : level;
1422
+ }
1423
+ // src/chat/config.ts
1424
+ var config_exports = /* @__PURE__ */ __exportAll({
1425
+ CONVERSATION_WORK_SOFT_YIELD_BUFFER_SECONDS: () => 40,
1426
+ DEFAULT_SQL_STATEMENT_TIMEOUT_MS: () => DEFAULT_SQL_STATEMENT_TIMEOUT_MS,
1427
+ FUNCTION_TIMEOUT_BUFFER_SECONDS: () => 20,
1428
+ botConfig: () => botConfig,
1429
+ getChatConfig: () => getChatConfig,
1430
+ getRuntimeMetadata: () => getRuntimeMetadata,
1431
+ getSlackBotToken: () => getSlackBotToken,
1432
+ getSlackClientId: () => getSlackClientId,
1433
+ getSlackClientSecret: () => getSlackClientSecret,
1434
+ getSlackSigningSecret: () => getSlackSigningSecret,
1435
+ readChatConfig: () => readChatConfig,
1436
+ resetRuntimeConfig: () => resetRuntimeConfig,
1437
+ restoreRuntimeConfig: () => restoreRuntimeConfig,
1438
+ setBotModelConfig: () => setBotModelConfig,
1439
+ setRuntimeLimits: () => setRuntimeLimits,
1440
+ setSlackReactionConfig: () => setSlackReactionConfig,
1441
+ snapshotRuntimeConfig: () => snapshotRuntimeConfig
1442
+ });
1443
+ const MIN_AGENT_TURN_TIMEOUT_MS = 1e4;
1444
+ const DEFAULT_AGENT_TURN_TIMEOUT_MS = 72e4;
1445
+ const MAX_SLICES_PER_TURN = 100;
1446
+ /**
1447
+ * Max model spend in USD for one turn, including later execution slices of
1448
+ * that turn. Sentry span estimates put a child agent that made 250 tool calls
1449
+ * of real work at about $50.
1450
+ */
1451
+ const MAX_TURN_COST_USD = 100;
1452
+ /**
1453
+ * Max tool calls for one turn, including later execution slices of that turn.
1454
+ * A backstop for models without cost data. The spend limit should stop a turn
1455
+ * first. 250 calls stopped child agents that were still doing real work.
1456
+ */
1457
+ const MAX_TOOL_CALLS_PER_TURN = 1e3;
1458
+ /**
1459
+ * Max consecutive automated turns before event wakes stop until a user message.
1460
+ * Resource-event CI watches and event-automation loops are the common runaway paths.
1461
+ * Sentry telemetry has no direct instrumentation for how long real automated
1462
+ * chains run (only failure paths on the notice are logged, and those show zero
1463
+ * hits in the last 30d), so this is sized qualitatively: it stays well under
1464
+ * the runaway CI-watch-loop range (hundreds of tool calls) while giving
1465
+ * multi-phase event-automation/scheduled-automation work enough headroom to
1466
+ * avoid pausing on legitimate longer-running automation.
1467
+ */
1468
+ const MAX_CONSECUTIVE_AUTOMATED_TURNS = 25;
1469
+ /**
1470
+ * Max runs one Event automation can start in one rolling run window. Each run
1471
+ * is a full agent turn, and Event automations skip the consecutive
1472
+ * automated-turn limit. Kept low so a broad trigger, such as every message in
1473
+ * a channel, blocks quickly instead of starting a turn for each Event.
1474
+ */
1475
+ const MAX_EVENT_AUTOMATION_RUNS = 10;
1476
+ /** Length of the rolling window for the Event automation run limit. */
1477
+ const EVENT_AUTOMATION_RUN_WINDOW_MS = 6e4;
1478
+ const DEFAULT_FUNCTION_MAX_DURATION_SECONDS = 300;
1479
+ const DEFAULT_PROCESSING_REACTION_EMOJI = "eyes";
1480
+ const DEFAULT_COMPLETED_REACTION_EMOJI = "white_check_mark";
1481
+ const DEFAULT_MODEL_CONTEXT_WINDOW_TOKENS = 4e5;
1482
+ const DEFAULT_SQL_STATEMENT_TIMEOUT_MS = 3e4;
1483
+ const DEFAULT_ASSISTANT_LOADING_MESSAGES = [
1484
+ "Consulting the orb",
1485
+ "Bribing the gremlins",
1486
+ "Shuffling the papers dramatically",
1487
+ "Summoning the right stack trace",
1488
+ "Negotiating with the mutex",
1489
+ "Poking the internet with a stick",
1490
+ "Asking the docs nicely",
1491
+ "Searching for the least cursed path",
1492
+ "Pretending this was obvious",
1493
+ "Waking up the test suite",
1494
+ "Untangling the spaghetti carefully",
1495
+ "Rattling the command line"
1496
+ ];
1497
+ function parseAgentTurnTimeoutMs(rawValue, maxTimeoutMs) {
1498
+ const value = Number.parseInt(rawValue ?? "", 10);
1499
+ if (Number.isNaN(value)) return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, Math.min(DEFAULT_AGENT_TURN_TIMEOUT_MS, maxTimeoutMs));
1500
+ return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, Math.min(value, maxTimeoutMs));
1501
+ }
1502
+ function resolveFunctionMaxDurationSeconds(functionMaxDurationSeconds) {
1503
+ return functionMaxDurationSeconds ?? DEFAULT_FUNCTION_MAX_DURATION_SECONDS;
1504
+ }
1505
+ function resolveConversationWorkSoftYieldAfterMs(functionMaxDurationSeconds) {
1506
+ return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, (functionMaxDurationSeconds - 40) * 1e3);
1507
+ }
1508
+ function resolveMaxTurnTimeoutMs(functionMaxDurationSeconds) {
1509
+ const budgetSeconds = functionMaxDurationSeconds - 20;
1510
+ return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, budgetSeconds * 1e3);
1511
+ }
1512
+ function parseLoadingMessages(rawValue) {
1513
+ const trimmed = rawValue?.trim();
1514
+ if (!trimmed) return [...DEFAULT_ASSISTANT_LOADING_MESSAGES];
1515
+ let parsed;
1516
+ try {
1517
+ parsed = JSON.parse(trimmed);
1518
+ } catch {
1519
+ throw new Error("JUNIOR_LOADING_MESSAGES must be a JSON array of strings");
1520
+ }
1521
+ if (!Array.isArray(parsed)) throw new Error("JUNIOR_LOADING_MESSAGES must be a JSON array of strings");
1522
+ return parsed.map((value, index) => {
1523
+ if (typeof value !== "string") throw new Error(`JUNIOR_LOADING_MESSAGES[${index}] must be a string`);
1524
+ return value.trim();
1525
+ });
1526
+ }
1527
+ function parseOptionalPositiveInteger(envName, rawValue) {
1528
+ const trimmed = toOptionalTrimmed(rawValue);
1529
+ if (trimmed === void 0) return;
1530
+ const value = Number.parseInt(trimmed, 10);
1531
+ if (!Number.isSafeInteger(value) || value <= 0 || String(value) !== trimmed) throw new Error(`${envName} must be a positive integer`);
1532
+ return value;
1533
+ }
1534
+ function parseKillSwitch(name, rawValue) {
1535
+ const value = toOptionalTrimmed(rawValue)?.toLowerCase();
1536
+ if (value === void 0 || value === "true") return true;
1537
+ if (value === "false") return false;
1538
+ throw new Error(`${name} must be true or false`);
1539
+ }
1540
+ const DEFAULT_MODEL_ID = resolveGatewayModel("anthropic/claude-opus-5.5").id;
1541
+ const DEFAULT_REASONING_LEVEL = "high";
1542
+ const DEFAULT_FAST_MODEL_ID = resolveGatewayModel("openai/gpt-6-luna").id;
1543
+ const DEFAULT_GUARDIAN_MODEL_ID = resolveGatewayModel("openai/gpt-6-luna").id;
1544
+ const DEFAULT_WEB_SEARCH_MODEL_ID = resolveGatewayModel("openai/gpt-6-luna").id;
1545
+ const DEFAULT_DECISION_MODEL_ID = "typesafe-ai/jev";
1546
+ const DEFAULT_EMBEDDING_MODEL_ID = "openai/text-embedding-3-small";
1547
+ const DEFAULT_RERANKING_MODEL_ID = "voyage/rerank-2.5-lite";
1548
+ const DEFAULT_IMAGE_GENERATION_MODEL_ID = "openai/gpt-image-2";
1549
+ const DEFAULT_TRANSCRIPTION_MODEL_ID = "spacexai/grok-stt";
1550
+ const DEFAULT_VISION_MODEL_ID = resolveGatewayModel("openai/gpt-5.6-sol").id;
1551
+ function validateGatewayModelId(raw) {
1552
+ const trimmed = toOptionalTrimmed(raw);
1553
+ if (trimmed === void 0) return void 0;
1554
+ resolveGatewayModel(trimmed);
1555
+ return trimmed;
1556
+ }
1557
+ function validateEmbeddingModelId(raw) {
1558
+ return toOptionalTrimmed(raw);
1559
+ }
1560
+ function requireModelId(configName, raw, validate) {
1561
+ const modelId = validate(raw);
1562
+ if (!modelId) throw new Error(`${configName} must not be empty`);
1563
+ return modelId;
1564
+ }
1565
+ function parseReactionEmoji(envName, rawValue, defaultEmoji) {
1566
+ const trimmed = toOptionalTrimmed(rawValue);
1567
+ if (trimmed === void 0) return defaultEmoji;
1568
+ const normalized = normalizeSlackEmojiName(trimmed);
1569
+ if (!normalized) throw new Error(`${envName} must be a valid Slack emoji name (for example "eyes" or ":white_check_mark:")`);
1570
+ return normalized;
1571
+ }
1572
+ function readBotConfig(env, functionMaxDurationSeconds) {
1573
+ const maxTurnTimeoutMs = resolveMaxTurnTimeoutMs(functionMaxDurationSeconds);
1574
+ const modelId = validateGatewayModelId(env.AI_MODEL) ?? DEFAULT_MODEL_ID;
1575
+ const reasoningLevel = toOptionalTrimmed(env.AI_REASONING_LEVEL);
1576
+ const fastModelId = validateGatewayModelId(env.AI_FAST_MODEL ?? env.AI_MODEL) ?? DEFAULT_FAST_MODEL_ID;
1577
+ const guardianModelId = validateGatewayModelId(env.AI_GUARDIAN_MODEL) ?? DEFAULT_GUARDIAN_MODEL_ID;
1578
+ return {
1579
+ userName: toOptionalTrimmed(env.JUNIOR_BOT_NAME) ?? "junior",
1580
+ modelId,
1581
+ contextWindowTokens: parseOptionalPositiveInteger("AI_MODEL_CONTEXT_WINDOW_TOKENS", env.AI_MODEL_CONTEXT_WINDOW_TOKENS) ?? DEFAULT_MODEL_CONTEXT_WINDOW_TOKENS,
1582
+ reasoningLevel: reasoningLevel === void 0 ? DEFAULT_REASONING_LEVEL : parseTurnReasoningLevel(reasoningLevel),
1583
+ decisionModelId: toOptionalTrimmed(env.AI_DECISION_MODEL) ?? DEFAULT_DECISION_MODEL_ID,
1584
+ fastModelId,
1585
+ guardianModelId,
1586
+ imageGenerationModelId: toOptionalTrimmed(env.AI_IMAGE_MODEL) ?? DEFAULT_IMAGE_GENERATION_MODEL_ID,
1587
+ transcriptionModelId: toOptionalTrimmed(env.AI_TRANSCRIPTION_MODEL) ?? DEFAULT_TRANSCRIPTION_MODEL_ID,
1588
+ embeddingModelId: validateEmbeddingModelId(env.AI_EMBEDDING_MODEL) ?? DEFAULT_EMBEDDING_MODEL_ID,
1589
+ rerankingModelId: toOptionalTrimmed(env.AI_RERANKING_MODEL) ?? DEFAULT_RERANKING_MODEL_ID,
1590
+ loadingMessages: parseLoadingMessages(env.JUNIOR_LOADING_MESSAGES),
1591
+ visionModelId: env.AI_VISION_MODEL === void 0 ? DEFAULT_VISION_MODEL_ID : validateGatewayModelId(env.AI_VISION_MODEL),
1592
+ maxAgentDepth: 0,
1593
+ maxSlicesPerTurn: MAX_SLICES_PER_TURN,
1594
+ maxToolCallsPerTurn: MAX_TOOL_CALLS_PER_TURN,
1595
+ maxTurnCostUsd: MAX_TURN_COST_USD,
1596
+ maxConsecutiveAutomatedTurns: MAX_CONSECUTIVE_AUTOMATED_TURNS,
1597
+ maxEventAutomationRuns: MAX_EVENT_AUTOMATION_RUNS,
1598
+ eventAutomationRunWindowMs: EVENT_AUTOMATION_RUN_WINDOW_MS,
1599
+ turnTimeoutMs: parseAgentTurnTimeoutMs(env.AGENT_TURN_TIMEOUT_MS, maxTurnTimeoutMs),
1600
+ webSearchModelId: validateGatewayModelId(env.AI_WEB_SEARCH_MODEL) ?? DEFAULT_WEB_SEARCH_MODEL_ID
1601
+ };
1602
+ }
1603
+ function readDatabaseUrl(env) {
1604
+ const databaseUrl = toOptionalTrimmed(env.DATABASE_URL);
1605
+ if (!databaseUrl) throw new Error("DATABASE_URL is required");
1606
+ return databaseUrl;
1607
+ }
1608
+ function isLocalDatabaseUrl(databaseUrl) {
1609
+ try {
1610
+ const { hostname } = new URL(databaseUrl);
1611
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
1612
+ } catch {
1613
+ return false;
1614
+ }
1615
+ }
1616
+ function readSqlDriver(env, databaseUrl) {
1617
+ const value = toOptionalTrimmed(env.JUNIOR_DATABASE_DRIVER);
1618
+ if (value === void 0) {
1619
+ if (isLocalDatabaseUrl(databaseUrl)) return "postgres";
1620
+ return "neon";
1621
+ }
1622
+ if (value === "neon" || value === "postgres") return value;
1623
+ throw new Error("JUNIOR_DATABASE_DRIVER must be postgres or neon");
1624
+ }
1625
+ function readSqlStatementTimeoutMs(env) {
1626
+ const rawValue = toOptionalTrimmed(env.JUNIOR_SQL_STATEMENT_TIMEOUT_MS);
1627
+ if (rawValue === void 0) return DEFAULT_SQL_STATEMENT_TIMEOUT_MS;
1628
+ const value = Number.parseInt(rawValue, 10);
1629
+ if (!Number.isSafeInteger(value) || value < 0 || String(value) !== rawValue) throw new Error("JUNIOR_SQL_STATEMENT_TIMEOUT_MS must be a non-negative integer");
1630
+ return value === 0 ? false : value;
1631
+ }
1632
+ /** Parse all chat configuration from environment variables. */
1633
+ function readChatConfig(env = process.env, functionMaxDurationSeconds = DEFAULT_FUNCTION_MAX_DURATION_SECONDS) {
1634
+ const databaseUrl = readDatabaseUrl(env);
1635
+ const resolvedFunctionMaxDurationSeconds = resolveFunctionMaxDurationSeconds(functionMaxDurationSeconds);
1636
+ return {
1637
+ attachmentStorage: readAttachmentStorageConfig(env),
1638
+ bot: readBotConfig(env, resolvedFunctionMaxDurationSeconds),
1639
+ queue: readQueueConfig(env),
1640
+ functionMaxDurationSeconds: resolvedFunctionMaxDurationSeconds,
1641
+ cacheWarmingEnabled: parseKillSwitch("JUNIOR_CACHE_WARMING_ENABLED", env.JUNIOR_CACHE_WARMING_ENABLED),
1642
+ conversationWorkEnabled: parseKillSwitch("JUNIOR_CONVERSATION_WORK_ENABLED", env.JUNIOR_CONVERSATION_WORK_ENABLED),
1643
+ conversationWorkSoftYieldAfterMs: resolveConversationWorkSoftYieldAfterMs(resolvedFunctionMaxDurationSeconds),
1644
+ sql: {
1645
+ databaseUrl,
1646
+ driver: readSqlDriver(env, databaseUrl),
1647
+ statementTimeoutMs: readSqlStatementTimeoutMs(env)
1648
+ },
1649
+ slack: {
1650
+ botToken: toOptionalTrimmed(env.SLACK_BOT_TOKEN) ?? toOptionalTrimmed(env.SLACK_BOT_USER_TOKEN),
1651
+ clientId: toOptionalTrimmed(env.SLACK_CLIENT_ID),
1652
+ clientSecret: toOptionalTrimmed(env.SLACK_CLIENT_SECRET),
1653
+ completedReactionEmoji: DEFAULT_COMPLETED_REACTION_EMOJI,
1654
+ processingReactionEmoji: DEFAULT_PROCESSING_REACTION_EMOJI,
1655
+ signingSecret: toOptionalTrimmed(env.SLACK_SIGNING_SECRET)
1656
+ },
1657
+ sandbox: { provider: env.JUNIOR_SANDBOX_PROVIDER?.trim().toLowerCase() === "docker" ? "docker" : "vercel" },
1658
+ state: {
1659
+ adapter: env.JUNIOR_STATE_ADAPTER?.trim().toLowerCase() === "memory" ? "memory" : "redis",
1660
+ keyPrefix: toOptionalTrimmed(env.JUNIOR_STATE_KEY_PREFIX),
1661
+ redisUrl: toOptionalTrimmed(env.REDIS_URL)
1662
+ }
1663
+ };
1664
+ }
1665
+ /** Chat configuration parsed once at module load from the process environment. */
1666
+ const chatConfig = readChatConfig(process.env);
1667
+ /** Copy the runtime config so a failed app setup can restore it. */
1668
+ function snapshotRuntimeConfig() {
1669
+ return {
1670
+ bot: { ...chatConfig.bot },
1671
+ completedReactionEmoji: chatConfig.slack.completedReactionEmoji,
1672
+ conversationWorkSoftYieldAfterMs: chatConfig.conversationWorkSoftYieldAfterMs,
1673
+ functionMaxDurationSeconds: chatConfig.functionMaxDurationSeconds,
1674
+ processingReactionEmoji: chatConfig.slack.processingReactionEmoji
1675
+ };
1676
+ }
1677
+ /** Replace the runtime config with a snapshot. */
1678
+ function restoreRuntimeConfig(snapshot) {
1679
+ replaceBotConfig(snapshot.bot);
1680
+ chatConfig.functionMaxDurationSeconds = snapshot.functionMaxDurationSeconds;
1681
+ chatConfig.conversationWorkSoftYieldAfterMs = snapshot.conversationWorkSoftYieldAfterMs;
1682
+ chatConfig.slack.completedReactionEmoji = snapshot.completedReactionEmoji;
1683
+ chatConfig.slack.processingReactionEmoji = snapshot.processingReactionEmoji;
1684
+ }
1685
+ /**
1686
+ * Reset bot, limit, and Slack settings to the environment defaults and apply
1687
+ * the host execution budget. Each app calls this before it applies options.
1688
+ */
1689
+ function resetRuntimeConfig(functionMaxDurationSeconds) {
1690
+ const resolved = resolveFunctionMaxDurationSeconds(functionMaxDurationSeconds);
1691
+ chatConfig.functionMaxDurationSeconds = resolved;
1692
+ chatConfig.conversationWorkSoftYieldAfterMs = resolveConversationWorkSoftYieldAfterMs(resolved);
1693
+ replaceBotConfig(readBotConfig(process.env, resolved));
1694
+ chatConfig.slack.completedReactionEmoji = DEFAULT_COMPLETED_REACTION_EMOJI;
1695
+ chatConfig.slack.processingReactionEmoji = DEFAULT_PROCESSING_REACTION_EMOJI;
1696
+ }
1697
+ function replaceBotConfig(next) {
1698
+ for (const key of Object.keys(chatConfig.bot)) delete chatConfig.bot[key];
1699
+ Object.assign(chatConfig.bot, next);
1700
+ }
1701
+ function requirePositiveLimit(name, value) {
1702
+ if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`limits.${name} must be a positive integer`);
1703
+ return value;
1704
+ }
1705
+ /** Apply limits from createApp(). Unset limits keep their defaults. */
1706
+ function setRuntimeLimits(limits) {
1707
+ const bot = chatConfig.bot;
1708
+ if (limits?.contextWindowTokens !== void 0) bot.contextWindowTokens = requirePositiveLimit("contextWindowTokens", limits.contextWindowTokens);
1709
+ if (limits?.maxAgentDepth !== void 0) {
1710
+ if (!Number.isSafeInteger(limits.maxAgentDepth) || limits.maxAgentDepth < 0) throw new Error("limits.maxAgentDepth must be a non-negative integer");
1711
+ bot.maxAgentDepth = limits.maxAgentDepth;
1712
+ }
1713
+ if (limits?.maxConsecutiveAutomatedTurns !== void 0) bot.maxConsecutiveAutomatedTurns = requirePositiveLimit("maxConsecutiveAutomatedTurns", limits.maxConsecutiveAutomatedTurns);
1714
+ const runLimit = limits?.eventAutomationRunLimit;
1715
+ if (runLimit?.maxRuns !== void 0) bot.maxEventAutomationRuns = requirePositiveLimit("eventAutomationRunLimit.maxRuns", runLimit.maxRuns);
1716
+ if (runLimit?.windowMs !== void 0) bot.eventAutomationRunWindowMs = requirePositiveLimit("eventAutomationRunLimit.windowMs", runLimit.windowMs);
1717
+ if (limits?.maxSlicesPerTurn !== void 0) bot.maxSlicesPerTurn = requirePositiveLimit("maxSlicesPerTurn", limits.maxSlicesPerTurn);
1718
+ if (limits?.maxToolCallsPerTurn !== void 0) bot.maxToolCallsPerTurn = requirePositiveLimit("maxToolCallsPerTurn", limits.maxToolCallsPerTurn);
1719
+ if (limits?.maxTurnCostUsd !== void 0) bot.maxTurnCostUsd = requirePositiveLimit("maxTurnCostUsd", limits.maxTurnCostUsd);
1720
+ if (limits?.turnTimeoutMs !== void 0) bot.turnTimeoutMs = Math.min(requirePositiveLimit("turnTimeoutMs", limits.turnTimeoutMs), resolveMaxTurnTimeoutMs(chatConfig.functionMaxDurationSeconds));
1721
+ }
1722
+ /** Return the chat configuration (parsed once at startup). */
1723
+ function getChatConfig() {
1724
+ return chatConfig;
1725
+ }
1726
+ /** Bot configuration derived from environment at module load. */
1727
+ const botConfig = chatConfig.bot;
1728
+ function getSlackBotToken() {
1729
+ return chatConfig.slack.botToken;
1730
+ }
1731
+ function getSlackSigningSecret() {
1732
+ return chatConfig.slack.signingSecret;
1733
+ }
1734
+ function getSlackClientId() {
1735
+ return chatConfig.slack.clientId;
1736
+ }
1737
+ function getSlackClientSecret() {
1738
+ return chatConfig.slack.clientSecret;
1739
+ }
1740
+ /** Return runtime metadata (version from deploy environment). */
1741
+ function getRuntimeMetadata() {
1742
+ return { version: toOptionalTrimmed(process.env.VERCEL_GIT_COMMIT_SHA) };
1743
+ }
1744
+ /** Apply model overrides from createApp(). */
1745
+ function setBotModelConfig(config) {
1746
+ if (config.modelId !== void 0) botConfig.modelId = requireModelId("modelId", config.modelId, validateGatewayModelId);
1747
+ if (config.decisionModelId !== void 0) botConfig.decisionModelId = requireModelId("decisionModelId", config.decisionModelId, toOptionalTrimmed);
1748
+ if (config.embeddingModelId !== void 0) botConfig.embeddingModelId = requireModelId("embeddingModelId", config.embeddingModelId, validateEmbeddingModelId);
1749
+ if (config.fastModelId !== void 0) botConfig.fastModelId = requireModelId("fastModelId", config.fastModelId, validateGatewayModelId);
1750
+ if (config.guardianModelId !== void 0) botConfig.guardianModelId = requireModelId("guardianModelId", config.guardianModelId, validateGatewayModelId);
1751
+ if (config.rerankingModelId !== void 0) botConfig.rerankingModelId = requireModelId("rerankingModelId", config.rerankingModelId, toOptionalTrimmed);
1752
+ if (config.imageGenerationModelId !== void 0) botConfig.imageGenerationModelId = requireModelId("imageGenerationModelId", config.imageGenerationModelId, validateEmbeddingModelId);
1753
+ if (config.transcriptionModelId !== void 0) botConfig.transcriptionModelId = requireModelId("transcriptionModelId", config.transcriptionModelId, toOptionalTrimmed);
1754
+ if (config.visionModelId !== void 0) botConfig.visionModelId = requireModelId("visionModelId", config.visionModelId, validateGatewayModelId);
1755
+ if (config.webSearchModelId !== void 0) botConfig.webSearchModelId = requireModelId("webSearchModelId", config.webSearchModelId, validateGatewayModelId);
1756
+ }
1757
+ /** Apply Slack reaction emoji overrides from createApp() options, validating names. */
1758
+ function setSlackReactionConfig(overrides) {
1759
+ if (overrides.processingReactionEmoji !== void 0) chatConfig.slack.processingReactionEmoji = parseReactionEmoji("processingReactionEmoji", overrides.processingReactionEmoji, chatConfig.slack.processingReactionEmoji);
1760
+ if (overrides.completedReactionEmoji !== void 0) chatConfig.slack.completedReactionEmoji = parseReactionEmoji("completedReactionEmoji", overrides.completedReactionEmoji, chatConfig.slack.completedReactionEmoji);
1761
+ }
1762
+ export { estimateRequestOverheadTokens as A, ProviderError as B, completeText as C, transcribeAudio as D, resolveGatewayModel as E, isCompactionSummaryText as F, isProviderRetryError as G, findProviderError as H, renderCurrentInstruction as I, getAttachmentStorage as J, getGatewayApiKey as K, unwrapCurrentInstruction as L, textCharsForTokens as M, COMPACTION_SUMMARY_PREFIX as N, requestPrefixAttributes as O, hasCompactedConversationContext as P, escapeXml as R, completeObject as S, rerankTexts as T, getProviderErrorAttributes as U, createProviderError as V, getProviderErrorUserMessage as W, toOptionalTrimmed as Y, toPiReasoningLevel as _, getRuntimeMetadata as a, GEN_AI_SERVER_ADDRESS as b, getSlackClientSecret as c, restoreRuntimeConfig as d, setBotModelConfig as f, TURN_REASONING_LEVELS as g, snapshotRuntimeConfig as h, getChatConfig as i, estimateTextTokens as j, estimateMessagesTokens as k, getSlackSigningSecret as l, setSlackReactionConfig as m, botConfig as n, getSlackBotToken as o, setRuntimeLimits as p, resolveGatewayCredential as q, config_exports as r, getSlackClientId as s, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as t, resetRuntimeConfig as u, normalizeSlackEmojiName as v, embedTexts as w, completeDecision as x, GEN_AI_PROVIDER_NAME as y, escapeXmlText as z };