@sentry/junior 0.316.0 → 0.317.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.
- package/dist/{admin-QYiDMnsu.js → admin-CAugg87B.js} +1 -1
- package/dist/{agent-runner-Cr5Fhjf-.js → agent-runner-AjrEV6Qe.js} +13438 -13149
- package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
- package/dist/{agent-update-delivery-BY13DPSD.js → agent-update-delivery-B_YIZcgf.js} +5 -5
- package/dist/api/schema.d.ts +558 -102
- package/dist/api/schema.js +6 -6
- package/dist/api.js +230 -213
- package/dist/{app-BhvzRD__.d.ts → app-MoNAsVV5.d.ts} +34 -14
- package/dist/app.d.ts +1 -1
- package/dist/app.js +167 -122
- package/dist/catalog-runtime-DfSpJZdY.js +6 -0
- package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
- package/dist/{adapter-context-Bref7aPI.js → channel-access-j-YAVYK4.js} +2 -42
- package/dist/{chat-core-engine-3dtlMku3.js → chat-core-engine-aH85nEHv.js} +4 -3
- package/dist/{child-message--2G3Ft26.js → child-message-DHjQLEd1.js} +1 -1
- package/dist/cli/chat.js +23 -23
- package/dist/cli/check.js +5 -5
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.js +5 -4
- package/dist/cli/snapshot-create.js +5 -2
- package/dist/cli/upgrade.js +5 -3
- package/dist/config-CHQ8X251.js +2422 -0
- package/dist/{continue-in-slack-DbQUFe_F.js → continue-in-slack-D-FZ8Fin.js} +2 -3
- package/dist/{conversation-feed-B84pMjHo.js → conversation-feed--9S0_PXL.js} +3 -3
- package/dist/{proxy-path-BTmXDjfx.js → conversation-privacy-B1uXn5sf.js} +2 -16
- package/dist/{conversation-turn-DzEpTIaf.js → conversation-turn-BUE_7xaN.js} +99 -76
- package/dist/{create-DUJBXr6E.js → create-DoDIYgtZ.js} +12 -9
- package/dist/{credential-sync-JH_K9Adg.js → credential-sync-BJOqGnjV.js} +17 -12
- package/dist/{db-DhzvUY23.js → db-BFmyYZtJ.js} +20265 -27551
- package/dist/{deployment-BhvrhQeh.js → deployment-DXq9ZLU4.js} +17 -15
- package/dist/{engine-context-C9Nal48K.js → engine-context-CgQ7mlHt.js} +264 -47
- package/dist/{html-B_12WjKT.js → html-B3VKTGbJ.js} +6 -2
- package/dist/instrumentation.js +15 -7
- package/dist/{job-runner-DO8nslyY.js → job-runner-A1lCkybD.js} +391 -24
- package/dist/{lineage-D3AZAJVe.js → lineage-Bktb0UcV.js} +1 -1
- package/dist/{list-B0zsb5Cp.js → list-Bxvg5wXf.js} +224 -544
- package/dist/{logging-B8KEJegM.js → logging--smS7XRK.js} +2 -2
- package/dist/{session-stop-DponjDUZ.js → mailbox-turn-uSXhUFc9.js} +4747 -7039
- package/dist/{message-B5fKDYzz.js → message-BNenhsmB.js} +12 -22
- package/dist/{model-input-CuMWy37l.js → model-input-BReSnwHp.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +20 -6
- package/dist/{oauth-callback-server-B3Vvlydo.js → oauth-callback-server-CE4soEIY.js} +2 -2
- package/dist/{oauth-relay-6ERrGPbA.js → oauth-relay-C36gX1gH.js} +2 -2
- package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
- package/dist/{list-mkB_GU8R.js → parent-result-Ck1rFYRQ.js} +107 -92
- package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
- package/dist/profile-BQ-iBDsZ.js +4657 -0
- package/dist/{transcript-CCi7323k.js → prompt-Dv7gkpD6.js} +97 -103
- package/dist/proxy-path-BHYoKZdq.js +15 -0
- package/dist/registry-iXMT5Jmh.js +3279 -0
- package/dist/reports-WKHfGTsU.js +195 -0
- package/dist/{resolve-D5JVvv6A.js → resolve-tony4ibz.js} +9 -29
- package/dist/{result-CS_7mo8a.js → result-Bta_dlWa.js} +25 -116
- package/dist/run-conversation-DL6ru7iW.js +336 -0
- package/dist/{runner-BzAES5W3.js → runner-BstDRbD9.js} +7 -7
- package/dist/{sandbox-egress-signals-Dwhk2Q5F.js → sandbox-egress-signals-oSJMJOnn.js} +1 -1
- package/dist/{schema-z5-wA6N4.js → schema-DfqrHACA.js} +48 -86
- package/dist/sender-actors-CPglLd5R.js +83 -0
- package/dist/{service-account-D6AsAtc1.js → service-account-CTV_jaNu.js} +3 -1
- package/dist/{skills-DgJ9GBPR.js → skills-BCEU41zM.js} +4 -4
- package/dist/{slack-conversation-unfurl-Dq71EkhM.js → slack-conversation-unfurl-DxVmhbGP.js} +7 -6
- package/dist/{spawn-BJWpdwhQ.js → spawn-frczVPIr.js} +11 -8
- package/dist/{system-prompt-table-iIgpmslr.js → system-prompt-table-CiXy0eNR.js} +88 -69
- package/dist/{task-runner-BJae4JwE.js → task-runner-C9Yc2_ae.js} +20 -46
- package/dist/{thread-context-fiMNylbg.js → thread-context-CqZDKErp.js} +6 -6
- package/dist/topics-SRN7IVX-.js +24 -0
- package/dist/turn-membership-CENFf3kI.js +856 -0
- package/dist/{turn-wake-BjDW7x-5.js → turn-wake-BhloiI2h.js} +4 -5
- package/dist/{media-BebquhET.js → types-C4iC-IMC.js} +801 -771
- package/dist/user-customization-CvfuY9Eo.js +93 -0
- package/dist/users-ByG5RCEJ.js +181 -0
- package/dist/{validation-D5WmmmhX.js → validation-8gjfR91V.js} +1 -1
- package/dist/{version-CBQoanXb.js → version-BeZhWWBE.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-Cyb4kF17.js → worker-BqMQQNRk.js} +5 -4
- package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
- package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
- package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
- package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
- package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
- package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
- package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
- package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
- package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
- package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
- package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
- package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
- package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
- package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
- package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
- package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
- package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
- package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
- package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
- package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
- package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
- package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
- package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
- package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
- package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
- package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
- package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
- package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
- package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
- package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
- package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
- package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
- package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
- package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
- package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
- package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
- package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
- package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
- package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
- package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
- package/package.json +5 -5
- package/dist/people-CUtFApfL.js +0 -81
- package/dist/start-conversation-B-LIqqNi.js +0 -162
- package/dist/turn-session-routing-D15orfwy.js +0 -1309
- package/dist/user-customization-B27StpVQ.js +0 -9
- package/dist/web-message-id-C6P83ans.js +0 -10
|
@@ -0,0 +1,2422 @@
|
|
|
1
|
+
import { o as toOptionalTrimmed } from "./topics-SRN7IVX-.js";
|
|
2
|
+
import { E as withSpan, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging--smS7XRK.js";
|
|
3
|
+
import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-B1uXn5sf.js";
|
|
4
|
+
import { z as unwrapCurrentInstruction } from "./prompt-Dv7gkpD6.js";
|
|
5
|
+
import { Kn as gatewayOnlyProviders } from "./types-C4iC-IMC.js";
|
|
6
|
+
import * as z from "zod";
|
|
7
|
+
import { calculateCost, completeSimple, getEnvApiKey, getModels, registerApiProvider } from "@earendil-works/pi-ai/compat";
|
|
8
|
+
import { stream as streamAnthropic, streamSimple as streamSimpleAnthropic } from "@earendil-works/pi-ai/api/anthropic-messages";
|
|
9
|
+
import { createGatewayProvider } from "@ai-sdk/gateway";
|
|
10
|
+
import { getVercelOidcToken } from "@vercel/oidc";
|
|
11
|
+
import { Experimental_DecisionRefusalError, NoImageGeneratedError, NoObjectGeneratedError, embedMany, experimental_decide, generateImage, generateObject, generateText, rerank } from "ai";
|
|
12
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
13
|
+
import { renderSystemMessageUpdate } from "@earendil-works/pi-ai";
|
|
14
|
+
import { setTimeout } from "node:timers/promises";
|
|
15
|
+
// src/config/attachments.ts
|
|
16
|
+
const DEFAULT_S3_REGION = "us-east-1";
|
|
17
|
+
const nonEmptyString = z.string().trim().min(1);
|
|
18
|
+
const s3StorageSchema = z.strictObject({
|
|
19
|
+
accessKeyId: nonEmptyString,
|
|
20
|
+
bucket: nonEmptyString,
|
|
21
|
+
/** Base URL of the S3 API. Objects use path-style URLs under it. */
|
|
22
|
+
endpoint: nonEmptyString,
|
|
23
|
+
region: nonEmptyString.default(DEFAULT_S3_REGION),
|
|
24
|
+
secretAccessKey: nonEmptyString
|
|
25
|
+
});
|
|
26
|
+
/** Object storage for attachments and public artifacts. */
|
|
27
|
+
const attachmentStorageSchema = z.discriminatedUnion("provider", [
|
|
28
|
+
z.strictObject({ provider: z.literal("vercel-blob") }),
|
|
29
|
+
z.strictObject({
|
|
30
|
+
provider: z.literal("s3"),
|
|
31
|
+
s3: s3StorageSchema
|
|
32
|
+
}),
|
|
33
|
+
z.strictObject({ provider: z.literal("memory") })
|
|
34
|
+
]);
|
|
35
|
+
/** Env var that sets each attachment storage field, for error messages. */
|
|
36
|
+
const attachmentStorageEnvNames = {
|
|
37
|
+
attachmentStorage: "JUNIOR_ATTACHMENT_STORAGE_PROVIDER",
|
|
38
|
+
"attachmentStorage.s3.accessKeyId": "JUNIOR_S3_ACCESS_KEY_ID",
|
|
39
|
+
"attachmentStorage.s3.bucket": "JUNIOR_S3_BUCKET",
|
|
40
|
+
"attachmentStorage.s3.endpoint": "JUNIOR_S3_ENDPOINT",
|
|
41
|
+
"attachmentStorage.s3.region": "JUNIOR_S3_REGION",
|
|
42
|
+
"attachmentStorage.s3.secretAccessKey": "JUNIOR_S3_SECRET_ACCESS_KEY"
|
|
43
|
+
};
|
|
44
|
+
function readS3Setting(env, name) {
|
|
45
|
+
const value = toOptionalTrimmed(env[name]);
|
|
46
|
+
if (value === void 0) throw new Error(`${name} is required when JUNIOR_ATTACHMENT_STORAGE_PROVIDER is s3`);
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
/** Read the attachment storage group from env. */
|
|
50
|
+
function readAttachmentStorage(env) {
|
|
51
|
+
const provider = toOptionalTrimmed(env["JUNIOR_ATTACHMENT_STORAGE_PROVIDER"]);
|
|
52
|
+
switch (provider) {
|
|
53
|
+
case void 0: return;
|
|
54
|
+
case "vercel-blob":
|
|
55
|
+
case "memory": return { provider };
|
|
56
|
+
case "s3": return {
|
|
57
|
+
provider,
|
|
58
|
+
s3: {
|
|
59
|
+
accessKeyId: readS3Setting(env, "JUNIOR_S3_ACCESS_KEY_ID"),
|
|
60
|
+
bucket: readS3Setting(env, "JUNIOR_S3_BUCKET"),
|
|
61
|
+
endpoint: readS3Setting(env, "JUNIOR_S3_ENDPOINT"),
|
|
62
|
+
region: toOptionalTrimmed(env["JUNIOR_S3_REGION"]),
|
|
63
|
+
secretAccessKey: readS3Setting(env, "JUNIOR_S3_SECRET_ACCESS_KEY")
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
default: throw new Error("JUNIOR_ATTACHMENT_STORAGE_PROVIDER must be vercel-blob, s3, or memory");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
// src/chat/pi/gateway-auth.ts
|
|
70
|
+
/**
|
|
71
|
+
* AI Gateway credential resolution for every Junior model path.
|
|
72
|
+
*
|
|
73
|
+
* Prefer Vercel project OIDC so gateway usage attributes to the deploying
|
|
74
|
+
* project. Fall back to AI_GATEWAY_API_KEY for local/CI and non-Vercel hosts.
|
|
75
|
+
* Never cache resolved tokens: runtime OIDC rotates on each invocation.
|
|
76
|
+
*/
|
|
77
|
+
const UNAUTHENTICATED_GATEWAY_TOKEN = "unauthenticated";
|
|
78
|
+
/**
|
|
79
|
+
* Resolve the AI Gateway bearer credential.
|
|
80
|
+
*
|
|
81
|
+
* Order:
|
|
82
|
+
* 1. Vercel OIDC via `@vercel/oidc` (request header `x-vercel-oidc-token`,
|
|
83
|
+
* then `VERCEL_OIDC_TOKEN`, with local refresh when needed)
|
|
84
|
+
* 2. Explicit `AI_GATEWAY_API_KEY` / pi-ai env mapping for vercel-ai-gateway
|
|
85
|
+
* 3. A placeholder token (`mode: "none"`), so auth fails on the server side
|
|
86
|
+
*/
|
|
87
|
+
async function resolveGatewayCredential() {
|
|
88
|
+
try {
|
|
89
|
+
const oidcToken = toOptionalTrimmed(await getVercelOidcToken());
|
|
90
|
+
if (oidcToken) return {
|
|
91
|
+
mode: "oidc",
|
|
92
|
+
token: oidcToken
|
|
93
|
+
};
|
|
94
|
+
} catch {}
|
|
95
|
+
const apiKey = toOptionalTrimmed(getEnvApiKey("vercel-ai-gateway"));
|
|
96
|
+
if (apiKey) return {
|
|
97
|
+
mode: "api_key",
|
|
98
|
+
token: apiKey
|
|
99
|
+
};
|
|
100
|
+
return {
|
|
101
|
+
mode: "none",
|
|
102
|
+
token: UNAUTHENTICATED_GATEWAY_TOKEN
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/** Resolve the bearer token string for Authorization headers and Pi getApiKey. */
|
|
106
|
+
async function getGatewayApiKey() {
|
|
107
|
+
return (await resolveGatewayCredential()).token;
|
|
108
|
+
}
|
|
109
|
+
// src/chat/pi/object-completion.ts
|
|
110
|
+
/**
|
|
111
|
+
* Output tokens added on top of the object size that a caller asks for.
|
|
112
|
+
* Reasoning models spend output tokens before they write the object, and the
|
|
113
|
+
* provider counts both against one `maxOutputTokens` limit. With Guardian's
|
|
114
|
+
* 2,000-token assessment, this keeps the 8,000 limit its evals pass at.
|
|
115
|
+
*/
|
|
116
|
+
const STRUCTURED_OUTPUT_REASONING_TOKENS = 6e3;
|
|
117
|
+
/**
|
|
118
|
+
* Output token limit for an object of `objectTokens`, with room for reasoning.
|
|
119
|
+
* It never exceeds the model's own output limit, which providers enforce.
|
|
120
|
+
*/
|
|
121
|
+
function structuredOutputTokenLimit(objectTokens, modelMaxTokens) {
|
|
122
|
+
if (objectTokens === void 0) return void 0;
|
|
123
|
+
const limit = objectTokens + STRUCTURED_OUTPUT_REASONING_TOKENS;
|
|
124
|
+
return modelMaxTokens !== void 0 ? Math.min(limit, modelMaxTokens) : limit;
|
|
125
|
+
}
|
|
126
|
+
/** Span attributes for the finish reason and usage of one object completion. */
|
|
127
|
+
function objectCompletionAttributes(finishReason, usage) {
|
|
128
|
+
const reasoningTokens = usage?.outputTokenDetails?.reasoningTokens;
|
|
129
|
+
return {
|
|
130
|
+
...finishReason ? { "gen_ai.response.finish_reasons": [finishReason] } : void 0,
|
|
131
|
+
...extractGenAiUsageAttributes(usage),
|
|
132
|
+
...reasoningTokens !== void 0 ? { "gen_ai.usage.reasoning.output_tokens": reasoningTokens } : void 0
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Keep only the fixed message and stack of a failed structured output. The SDK
|
|
137
|
+
* error's `text` and its parse or validation cause hold the raw model output.
|
|
138
|
+
* A `length` finish gets its own error, so a spent budget is not reported as a
|
|
139
|
+
* malformed object.
|
|
140
|
+
*/
|
|
141
|
+
function structuredOutputErrorCause(error) {
|
|
142
|
+
const spentBudget = error.finishReason === "length";
|
|
143
|
+
const cause = new Error(spentBudget ? "Structured output hit the output token limit" : error.message);
|
|
144
|
+
cause.name = spentBudget ? "StructuredOutputLengthError" : error.name;
|
|
145
|
+
cause.stack = error.stack;
|
|
146
|
+
return cause;
|
|
147
|
+
}
|
|
148
|
+
// src/chat/services/provider-error.ts
|
|
149
|
+
/** Structured failure produced at an AI provider boundary. */
|
|
150
|
+
var ProviderError = class extends Error {
|
|
151
|
+
code = "provider_error";
|
|
152
|
+
kind;
|
|
153
|
+
modelId;
|
|
154
|
+
retryable;
|
|
155
|
+
retryAfterMs;
|
|
156
|
+
status;
|
|
157
|
+
constructor(details) {
|
|
158
|
+
super(`AI provider error: ${details.kind}`, details.cause !== void 0 ? { cause: details.cause } : {});
|
|
159
|
+
this.name = "ProviderError";
|
|
160
|
+
this.kind = details.kind;
|
|
161
|
+
this.modelId = details.modelId;
|
|
162
|
+
this.retryable = details.retryable;
|
|
163
|
+
this.retryAfterMs = details.retryAfterMs;
|
|
164
|
+
this.status = details.status;
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
const NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
168
|
+
"ECONNREFUSED",
|
|
169
|
+
"ECONNRESET",
|
|
170
|
+
"ENOTFOUND",
|
|
171
|
+
"EAI_AGAIN"
|
|
172
|
+
]);
|
|
173
|
+
const TIMEOUT_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
174
|
+
"ETIMEDOUT",
|
|
175
|
+
"ECONNABORTED",
|
|
176
|
+
"ESOCKETTIMEDOUT"
|
|
177
|
+
]);
|
|
178
|
+
const CONTENT_POLICY_PATTERN = /\b(?:content|safety|usage)[ _-]?policy\b|\b(?:content|safety) (?:filter|violation)\b|\bmoderation (?:blocked|rejected|refused)\b/i;
|
|
179
|
+
const QUOTA_PATTERN = /insufficient.?quota|quota exceeded|usage limit|available balance|out of budget|billing (?:limit|quota|error)|payment required/i;
|
|
180
|
+
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;
|
|
181
|
+
const PERMISSION_PATTERN = /permission denied|forbidden|not authorized|authorization (?:failed|required|denied)/i;
|
|
182
|
+
const INVALID_REQUEST_PATTERN = /context.?length|context.?window|validation (?:error|failed)|bad request|unsupported model|invalid model|unknown (?:ai gateway )?model|mismatched api/i;
|
|
183
|
+
const CAPACITY_PATTERN = /overloaded|at capacity|capacity exceeded/i;
|
|
184
|
+
const TIMEOUT_PATTERN = /timed? out|timeout|gateway timeout/i;
|
|
185
|
+
const NETWORK_PATTERN = /network.?error|connection (?:error|refused|lost|closed)|fetch failed|cannot connect to api|socket (?:hang up|closed)|stream ended before/i;
|
|
186
|
+
const SERVER_PATTERN = /service(?: temporarily)?[ _-]?unavailable|server.?error|internal.?error|bad gateway|upstream (?:request )?failed/i;
|
|
187
|
+
const TERMINAL_KINDS = /* @__PURE__ */ new Set([
|
|
188
|
+
"auth",
|
|
189
|
+
"permission",
|
|
190
|
+
"invalid_request",
|
|
191
|
+
"invalid_response",
|
|
192
|
+
"quota",
|
|
193
|
+
"content_policy"
|
|
194
|
+
]);
|
|
195
|
+
const RETRYABLE_KINDS = /* @__PURE__ */ new Set([
|
|
196
|
+
"rate_limit",
|
|
197
|
+
"capacity",
|
|
198
|
+
"timeout",
|
|
199
|
+
"network",
|
|
200
|
+
"server"
|
|
201
|
+
]);
|
|
202
|
+
function providerMessage(error) {
|
|
203
|
+
return (error instanceof Error ? error.message : String(error)).trim();
|
|
204
|
+
}
|
|
205
|
+
const PROVIDER_ERROR_SUMMARY_MAX_CHARS = 240;
|
|
206
|
+
/** Short provider-boundary text for telemetry. Drop trailing JSON bodies. */
|
|
207
|
+
function summarizeProviderErrorMessage(message) {
|
|
208
|
+
const normalized = message.trim().replace(/\s+/g, " ");
|
|
209
|
+
if (!normalized) return void 0;
|
|
210
|
+
const jsonStart = normalized.indexOf("{");
|
|
211
|
+
const summary = (jsonStart >= 0 ? normalized.slice(0, jsonStart) : normalized).trim();
|
|
212
|
+
if (!summary) return void 0;
|
|
213
|
+
return summary.length > PROVIDER_ERROR_SUMMARY_MAX_CHARS ? `${summary.slice(0, PROVIDER_ERROR_SUMMARY_MAX_CHARS)}...` : summary;
|
|
214
|
+
}
|
|
215
|
+
function extractTransportKind(error, depth = 0) {
|
|
216
|
+
if (!(error instanceof Error) || depth > 4) return void 0;
|
|
217
|
+
const providerError = error;
|
|
218
|
+
const code = typeof providerError.code === "string" ? providerError.code.toUpperCase() : void 0;
|
|
219
|
+
if (code && TIMEOUT_ERROR_CODES.has(code)) return "timeout";
|
|
220
|
+
if (code && NETWORK_ERROR_CODES.has(code)) return "network";
|
|
221
|
+
if (depth > 0 && NETWORK_PATTERN.test(providerError.message)) return "network";
|
|
222
|
+
return extractTransportKind(providerError.cause, depth + 1);
|
|
223
|
+
}
|
|
224
|
+
function extractStatus(error, message) {
|
|
225
|
+
if (error instanceof Error) {
|
|
226
|
+
const providerError = error;
|
|
227
|
+
if (typeof providerError.status === "number") return providerError.status;
|
|
228
|
+
if (typeof providerError.statusCode === "number") return providerError.statusCode;
|
|
229
|
+
}
|
|
230
|
+
const match = message.match(/^(?:Error:\s*)?([45]\d\d)\b|\bstatus(?:Code)?["'=:\s]+([45]\d\d)\b/i);
|
|
231
|
+
const status = match?.[1] ?? match?.[2];
|
|
232
|
+
return status ? Number(status) : void 0;
|
|
233
|
+
}
|
|
234
|
+
function extractRetryAfterMs(error, message) {
|
|
235
|
+
const headers = error instanceof Error ? error.responseHeaders ?? error.response?.headers : void 0;
|
|
236
|
+
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;
|
|
237
|
+
const raw = typeof retryAfter === "string" || typeof retryAfter === "number" ? String(retryAfter) : message.match(/"retry-after"\s*:\s*"?([^",}]+)"?/i)?.[1];
|
|
238
|
+
if (!raw) return void 0;
|
|
239
|
+
const seconds = Number(raw);
|
|
240
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
|
|
241
|
+
const date = Date.parse(raw);
|
|
242
|
+
return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
|
|
243
|
+
}
|
|
244
|
+
/** Classify stable provider signals without copying Pi's retry vocabulary. */
|
|
245
|
+
function classifyProviderError(status, message, transportKind) {
|
|
246
|
+
if (CONTENT_POLICY_PATTERN.test(message)) return "content_policy";
|
|
247
|
+
if (QUOTA_PATTERN.test(message)) return "quota";
|
|
248
|
+
if (status === 401 || AUTH_PATTERN.test(message)) return "auth";
|
|
249
|
+
if (status === 403 || PERMISSION_PATTERN.test(message)) return "permission";
|
|
250
|
+
if (INVALID_REQUEST_PATTERN.test(message)) return "invalid_request";
|
|
251
|
+
if (status === 429 || /rate.?limit|too many requests/i.test(message)) return "rate_limit";
|
|
252
|
+
if (status === 408) return "timeout";
|
|
253
|
+
if (CAPACITY_PATTERN.test(message)) return "capacity";
|
|
254
|
+
if (transportKind === "timeout" || TIMEOUT_PATTERN.test(message)) return "timeout";
|
|
255
|
+
if (transportKind === "network" || NETWORK_PATTERN.test(message)) return "network";
|
|
256
|
+
if (status !== void 0 && status >= 500 || SERVER_PATTERN.test(message)) return "server";
|
|
257
|
+
if (status !== void 0 && status >= 400) return "invalid_request";
|
|
258
|
+
return "unknown";
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* The AI SDK retries a call and then throws `AI_RetryError`. The error of
|
|
262
|
+
* its last attempt has the status and the transport cause.
|
|
263
|
+
*/
|
|
264
|
+
function lastAttemptError(error) {
|
|
265
|
+
return error instanceof Error && error.name === "AI_RetryError" && "lastError" in error ? error.lastError : error;
|
|
266
|
+
}
|
|
267
|
+
/** Normalize SDK, Gateway, and Pi failures into one provider error contract. */
|
|
268
|
+
function createProviderError(error, options = {}) {
|
|
269
|
+
if (error instanceof ProviderError) return error;
|
|
270
|
+
const message = providerMessage(error);
|
|
271
|
+
const attempt = lastAttemptError(error);
|
|
272
|
+
const status = extractStatus(attempt, message);
|
|
273
|
+
const kind = options.kind ?? classifyProviderError(status, message, extractTransportKind(attempt));
|
|
274
|
+
const retryable = !TERMINAL_KINDS.has(kind) && (options.retryable ?? RETRYABLE_KINDS.has(kind));
|
|
275
|
+
return new ProviderError({
|
|
276
|
+
cause: error,
|
|
277
|
+
kind,
|
|
278
|
+
modelId: options.modelId,
|
|
279
|
+
retryable,
|
|
280
|
+
retryAfterMs: extractRetryAfterMs(attempt, message),
|
|
281
|
+
status
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
const REFUSAL_STOP_REASONS = /* @__PURE__ */ new Set(["refusal", "sensitive"]);
|
|
285
|
+
/** Return whether the provider refused to answer a Pi assistant message. */
|
|
286
|
+
function isProviderRefusal(message) {
|
|
287
|
+
return message.rawStopReason !== void 0 && REFUSAL_STOP_REASONS.has(message.rawStopReason);
|
|
288
|
+
}
|
|
289
|
+
/** Normalize a failed Pi assistant message. A provider refusal is a content policy block. */
|
|
290
|
+
function createAssistantProviderError(message, options = {}) {
|
|
291
|
+
return createProviderError(message.errorMessage ?? "", {
|
|
292
|
+
...options,
|
|
293
|
+
...isProviderRefusal(message) ? { kind: "content_policy" } : void 0
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
/** Return whether a provider-boundary error should be retried. */
|
|
297
|
+
function isProviderRetryError(error) {
|
|
298
|
+
return error instanceof ProviderError && error.retryable;
|
|
299
|
+
}
|
|
300
|
+
/** Find the provider failure preserved inside a domain error cause chain. */
|
|
301
|
+
function findProviderError(error) {
|
|
302
|
+
const visited = /* @__PURE__ */ new Set();
|
|
303
|
+
let current = error;
|
|
304
|
+
while (current instanceof Error && !visited.has(current)) {
|
|
305
|
+
if (current instanceof ProviderError) return current;
|
|
306
|
+
visited.add(current);
|
|
307
|
+
current = current.cause;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const PROVIDER_NAMES = {
|
|
311
|
+
anthropic: "Anthropic",
|
|
312
|
+
google: "Google",
|
|
313
|
+
openai: "OpenAI",
|
|
314
|
+
xai: "xAI"
|
|
315
|
+
};
|
|
316
|
+
/**
|
|
317
|
+
* Name the failing model for user copy, such as `OpenAI (gpt-6-luna)`. A
|
|
318
|
+
* model that serves another step, such as action review, says so, because
|
|
319
|
+
* the person did not pick it.
|
|
320
|
+
*/
|
|
321
|
+
function providerSubject(modelId, purpose) {
|
|
322
|
+
const slash = modelId?.indexOf("/") ?? -1;
|
|
323
|
+
if (!modelId || slash <= 0) return purpose ? `The model provider used for ${purpose}` : "The model provider";
|
|
324
|
+
const vendor = modelId.slice(0, slash);
|
|
325
|
+
const model = modelId.slice(slash + 1);
|
|
326
|
+
const details = purpose ? `${model}, used for ${purpose}` : model;
|
|
327
|
+
return `${PROVIDER_NAMES[vendor] ?? vendor} (${details})`;
|
|
328
|
+
}
|
|
329
|
+
const UPSTREAM = "This is an upstream provider problem, not something you did. Please try again shortly.";
|
|
330
|
+
const PROVIDER_ERROR_MESSAGES = {
|
|
331
|
+
capacity: (subject) => `${subject} is at capacity right now. ${UPSTREAM}`,
|
|
332
|
+
rate_limit: (subject) => `${subject} is rate-limiting requests right now. Please try again shortly.`,
|
|
333
|
+
timeout: (subject) => `${subject} is timing out right now. ${UPSTREAM}`,
|
|
334
|
+
network: (subject) => `${subject} cannot be reached right now. ${UPSTREAM}`,
|
|
335
|
+
server: (subject) => `${subject} is returning errors right now. ${UPSTREAM}`,
|
|
336
|
+
auth: (subject) => `${subject} rejected the configured credentials. This needs an administrator or configuration fix.`,
|
|
337
|
+
permission: (subject) => `${subject} denied access to this model or request. Ask an administrator to check model access, organization policy, and region availability.`,
|
|
338
|
+
quota: (subject) => `${subject} reports that the usage quota is exhausted. This needs an administrator or billing configuration fix.`,
|
|
339
|
+
content_policy: (subject) => `${subject} blocked this request under its content policy. Please revise the request and try again.`,
|
|
340
|
+
invalid_request: (subject) => `${subject} rejected this request as invalid. Please revise the request or ask an administrator to check the model configuration.`,
|
|
341
|
+
invalid_response: (subject) => `${subject} returned an invalid response. ${UPSTREAM}`,
|
|
342
|
+
unknown: (subject) => `${subject} returned an error. ${UPSTREAM}`
|
|
343
|
+
};
|
|
344
|
+
/**
|
|
345
|
+
* Return stable, sanitized copy suitable for a terminal user response. It
|
|
346
|
+
* names the provider and model, and `purpose` names the step that the model
|
|
347
|
+
* serves when it is not the agent model.
|
|
348
|
+
*/
|
|
349
|
+
function getProviderErrorUserMessage(error, options = {}) {
|
|
350
|
+
const subject = providerSubject(error.modelId, options.purpose);
|
|
351
|
+
if (error.kind === "rate_limit" && error.retryAfterMs) return `${subject} is rate-limiting requests right now. Please try again in about ${Math.max(1, Math.ceil(error.retryAfterMs / 1e3))} seconds.`;
|
|
352
|
+
return PROVIDER_ERROR_MESSAGES[error.kind](subject);
|
|
353
|
+
}
|
|
354
|
+
/** Return safe structured fields for terminal failure telemetry. */
|
|
355
|
+
function getProviderErrorAttributes(error) {
|
|
356
|
+
const cause = error.cause;
|
|
357
|
+
const causeMessage = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : void 0;
|
|
358
|
+
const summary = causeMessage ? summarizeProviderErrorMessage(causeMessage) : void 0;
|
|
359
|
+
return {
|
|
360
|
+
"app.ai.provider_error.kind": error.kind,
|
|
361
|
+
"app.ai.provider_error.retryable": error.retryable,
|
|
362
|
+
...error.status !== void 0 ? { "app.ai.provider_error.status": error.status } : void 0,
|
|
363
|
+
...error.retryAfterMs !== void 0 ? { "app.ai.provider_error.retry_after_ms": error.retryAfterMs } : void 0,
|
|
364
|
+
...summary ? { "app.ai.provider_error.summary": summary } : void 0,
|
|
365
|
+
...error.modelId ? { "gen_ai.request.model": error.modelId } : void 0
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
// src/chat/services/context-compaction-marker.ts
|
|
369
|
+
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:";
|
|
370
|
+
/** Return whether text is one of Junior's durable compacted-context markers. */
|
|
371
|
+
function isCompactionSummaryText(text) {
|
|
372
|
+
const normalized = (unwrapCurrentInstruction(text) ?? text).trimStart();
|
|
373
|
+
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:");
|
|
374
|
+
}
|
|
375
|
+
/** Return whether model-visible history contains a durable compacted context marker. */
|
|
376
|
+
function hasCompactedConversationContext(messages) {
|
|
377
|
+
return messages.some((message) => {
|
|
378
|
+
const content = message.content;
|
|
379
|
+
if (typeof content === "string") return isCompactionSummaryText(content);
|
|
380
|
+
if (!Array.isArray(content)) return false;
|
|
381
|
+
return content.some((part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string" && isCompactionSummaryText(part.text));
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
// src/chat/pi/gateway-routing-attributes.ts
|
|
385
|
+
const providerAttemptSchema = z.object({
|
|
386
|
+
success: z.boolean().optional(),
|
|
387
|
+
credentialType: z.string().optional(),
|
|
388
|
+
inferenceEndpoint: z.object({ geoRegion: z.string().optional() }).optional()
|
|
389
|
+
});
|
|
390
|
+
const routingSchema = z.object({
|
|
391
|
+
finalProvider: z.string().optional(),
|
|
392
|
+
totalProviderAttemptCount: z.number().optional(),
|
|
393
|
+
clientSessionIdSource: z.string().optional(),
|
|
394
|
+
affinity: z.object({
|
|
395
|
+
pinned: z.boolean().optional(),
|
|
396
|
+
pinnedProvider: z.string().optional(),
|
|
397
|
+
outcome: z.string().optional()
|
|
398
|
+
}).optional(),
|
|
399
|
+
modelAttempts: z.array(z.object({ providerAttempts: z.array(providerAttemptSchema).optional() })).optional()
|
|
400
|
+
});
|
|
401
|
+
const messageDeltaSchema = z.object({
|
|
402
|
+
type: z.literal("message_delta"),
|
|
403
|
+
provider_metadata: z.object({ gateway: z.object({ routing: routingSchema }) })
|
|
404
|
+
});
|
|
405
|
+
/**
|
|
406
|
+
* Read the AI Gateway routing of one Anthropic Messages stream event as
|
|
407
|
+
* `app.ai.gateway.*` span attributes. Returns undefined for any other event.
|
|
408
|
+
*/
|
|
409
|
+
function gatewayRoutingAttributes(event) {
|
|
410
|
+
const parsed = messageDeltaSchema.safeParse(event);
|
|
411
|
+
if (!parsed.success) return;
|
|
412
|
+
const routing = parsed.data.provider_metadata.gateway.routing;
|
|
413
|
+
const served = routing.modelAttempts?.flatMap((attempt) => attempt.providerAttempts ?? []).find((attempt) => attempt.success === true);
|
|
414
|
+
const attributes = {};
|
|
415
|
+
const set = (key, value) => {
|
|
416
|
+
if (value !== void 0) attributes[`app.ai.gateway.${key}`] = value;
|
|
417
|
+
};
|
|
418
|
+
set("provider", routing.finalProvider);
|
|
419
|
+
set("credential_type", served?.credentialType);
|
|
420
|
+
set("region", served?.inferenceEndpoint?.geoRegion);
|
|
421
|
+
set("provider_attempts", routing.totalProviderAttemptCount);
|
|
422
|
+
set("session_id_source", routing.clientSessionIdSource);
|
|
423
|
+
set("affinity.pinned", routing.affinity?.pinned);
|
|
424
|
+
set("affinity.pinned_provider", routing.affinity?.pinnedProvider);
|
|
425
|
+
set("affinity.outcome", routing.affinity?.outcome);
|
|
426
|
+
return attributes;
|
|
427
|
+
}
|
|
428
|
+
// src/chat/services/image-dimensions.ts
|
|
429
|
+
const HEADER_BASE64_CHARS = 65536;
|
|
430
|
+
const READERS = {
|
|
431
|
+
"image/png": readPng,
|
|
432
|
+
"image/jpeg": readJpeg,
|
|
433
|
+
"image/gif": readGif,
|
|
434
|
+
"image/webp": readWebp
|
|
435
|
+
};
|
|
436
|
+
/**
|
|
437
|
+
* Read the pixel size from an image header without decoding the image.
|
|
438
|
+
* Returns undefined when the type is unknown or the header is not valid.
|
|
439
|
+
*/
|
|
440
|
+
function readImageDimensions(image) {
|
|
441
|
+
const read = READERS[image.mimeType.toLowerCase()];
|
|
442
|
+
if (!read) return void 0;
|
|
443
|
+
const prefix = Buffer.from(image.data.slice(0, HEADER_BASE64_CHARS), "base64");
|
|
444
|
+
const canReadMore = read === readJpeg && image.data.length > HEADER_BASE64_CHARS;
|
|
445
|
+
const dimensions = read(prefix) ?? (canReadMore ? read(Buffer.from(image.data, "base64")) : void 0);
|
|
446
|
+
return dimensions && dimensions.width > 0 && dimensions.height > 0 ? dimensions : void 0;
|
|
447
|
+
}
|
|
448
|
+
function hasAscii(bytes, offset, text) {
|
|
449
|
+
return bytes.toString("latin1", offset, offset + text.length) === text;
|
|
450
|
+
}
|
|
451
|
+
function readPng(bytes) {
|
|
452
|
+
if (bytes.length < 24) return void 0;
|
|
453
|
+
if (bytes.readUInt32BE(0) !== 2303741511 || !hasAscii(bytes, 12, "IHDR")) return;
|
|
454
|
+
return {
|
|
455
|
+
width: bytes.readUInt32BE(16),
|
|
456
|
+
height: bytes.readUInt32BE(20)
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
function readGif(bytes) {
|
|
460
|
+
if (bytes.length < 10) return void 0;
|
|
461
|
+
if (!hasAscii(bytes, 0, "GIF87a") && !hasAscii(bytes, 0, "GIF89a")) return;
|
|
462
|
+
return {
|
|
463
|
+
width: bytes.readUInt16LE(6),
|
|
464
|
+
height: bytes.readUInt16LE(8)
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
function readJpeg(bytes) {
|
|
468
|
+
if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216) return;
|
|
469
|
+
let offset = 2;
|
|
470
|
+
while (offset + 4 <= bytes.length) {
|
|
471
|
+
if (bytes[offset] !== 255) return void 0;
|
|
472
|
+
const marker = bytes[offset + 1];
|
|
473
|
+
if (marker === 255) {
|
|
474
|
+
offset += 1;
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
if (marker === 1 || marker >= 208 && marker <= 215) {
|
|
478
|
+
offset += 2;
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
const length = bytes.readUInt16BE(offset + 2);
|
|
482
|
+
if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
|
|
483
|
+
if (offset + 9 > bytes.length) return void 0;
|
|
484
|
+
return {
|
|
485
|
+
height: bytes.readUInt16BE(offset + 5),
|
|
486
|
+
width: bytes.readUInt16BE(offset + 7)
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
if (length < 2) return void 0;
|
|
490
|
+
offset += 2 + length;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
function readWebp(bytes) {
|
|
494
|
+
if (bytes.length < 30) return void 0;
|
|
495
|
+
if (!hasAscii(bytes, 0, "RIFF") || !hasAscii(bytes, 8, "WEBP")) return;
|
|
496
|
+
if (hasAscii(bytes, 12, "VP8 ")) {
|
|
497
|
+
if (bytes.readUIntBE(23, 3) !== 10289450) return void 0;
|
|
498
|
+
return {
|
|
499
|
+
width: bytes.readUInt16LE(26) & 16383,
|
|
500
|
+
height: bytes.readUInt16LE(28) & 16383
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
if (hasAscii(bytes, 12, "VP8L")) {
|
|
504
|
+
if (bytes[20] !== 47) return void 0;
|
|
505
|
+
const bits = bytes.readUInt32LE(21);
|
|
506
|
+
return {
|
|
507
|
+
width: (bits & 16383) + 1,
|
|
508
|
+
height: (bits >>> 14 & 16383) + 1
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
if (hasAscii(bytes, 12, "VP8X")) return {
|
|
512
|
+
width: bytes.readUIntLE(24, 3) + 1,
|
|
513
|
+
height: bytes.readUIntLE(27, 3) + 1
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
// src/chat/services/token-estimate.ts
|
|
517
|
+
const CLAUDE_TOKEN_ESTIMATE = {
|
|
518
|
+
charsPerToken: 2.5,
|
|
519
|
+
toolResultOverheadTokens: 150
|
|
520
|
+
};
|
|
521
|
+
const DEFAULT_TOKEN_ESTIMATE = {
|
|
522
|
+
charsPerToken: 4,
|
|
523
|
+
toolResultOverheadTokens: 0
|
|
524
|
+
};
|
|
525
|
+
const IMAGE_CHARS = 4800;
|
|
526
|
+
const CLAUDE_HIGH_RES_IMAGE = {
|
|
527
|
+
maxEdge: 2576,
|
|
528
|
+
maxTokens: 4784
|
|
529
|
+
};
|
|
530
|
+
const CLAUDE_STANDARD_IMAGE = {
|
|
531
|
+
maxEdge: 1568,
|
|
532
|
+
maxTokens: 1568
|
|
533
|
+
};
|
|
534
|
+
const CLAUDE_STANDARD_IMAGE_MODEL = /^anthropic\/claude-(?:3\b|[a-z]+-4(?:\.[0-6])?(?![.\d]))/;
|
|
535
|
+
const CLAUDE_IMAGE_PATCH_PX = 28;
|
|
536
|
+
function getTokenEstimateProfile(modelId) {
|
|
537
|
+
return modelId.startsWith("anthropic/") ? CLAUDE_TOKEN_ESTIMATE : DEFAULT_TOKEN_ESTIMATE;
|
|
538
|
+
}
|
|
539
|
+
function tokensForChars(chars, profile) {
|
|
540
|
+
return Math.ceil(chars / profile.charsPerToken);
|
|
541
|
+
}
|
|
542
|
+
function messageChars(message) {
|
|
543
|
+
switch (message.role) {
|
|
544
|
+
case "system": return renderSystemMessageUpdate(message).length;
|
|
545
|
+
case "user":
|
|
546
|
+
case "toolResult": return contentChars(message.content);
|
|
547
|
+
case "assistant": {
|
|
548
|
+
let chars = 0;
|
|
549
|
+
for (const block of message.content) if (block.type === "text") chars += block.text.length;
|
|
550
|
+
else if (block.type === "thinking") chars += block.thinking.length;
|
|
551
|
+
else chars += block.name.length + JSON.stringify(block.arguments).length;
|
|
552
|
+
return chars;
|
|
553
|
+
}
|
|
554
|
+
default: return 0;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
function contentChars(content) {
|
|
558
|
+
if (typeof content === "string") return content.length;
|
|
559
|
+
return content.reduce((chars, block) => chars + (block.type === "text" ? block.text.length : 0), 0);
|
|
560
|
+
}
|
|
561
|
+
function messageImages(message) {
|
|
562
|
+
if (message.role !== "user" && message.role !== "toolResult") return [];
|
|
563
|
+
if (typeof message.content === "string") return [];
|
|
564
|
+
return message.content.filter((block) => block.type === "image");
|
|
565
|
+
}
|
|
566
|
+
function claudeImagePatches(width, height) {
|
|
567
|
+
return Math.ceil(width / CLAUDE_IMAGE_PATCH_PX) * Math.ceil(height / CLAUDE_IMAGE_PATCH_PX);
|
|
568
|
+
}
|
|
569
|
+
function roundHalfToEven(value) {
|
|
570
|
+
const floor = Math.floor(value);
|
|
571
|
+
if (value - floor !== .5) return Math.round(value);
|
|
572
|
+
return floor % 2 === 0 ? floor : floor + 1;
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* The size Claude resizes an image to before it counts patches. This is the
|
|
576
|
+
* reference implementation in "How Claude resizes and pads images" in
|
|
577
|
+
* https://platform.claude.com/docs/en/build-with-claude/vision-coordinates:
|
|
578
|
+
* the largest aspect-preserving size whose padded edges and patch count fit
|
|
579
|
+
* the tier limits.
|
|
580
|
+
*/
|
|
581
|
+
function claudeResizedImageSize(width, height, limits) {
|
|
582
|
+
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;
|
|
583
|
+
if (fits(width, height)) return [width, height];
|
|
584
|
+
if (height > width) {
|
|
585
|
+
const [resizedHeight, resizedWidth] = claudeResizedImageSize(height, width, limits);
|
|
586
|
+
return [resizedWidth, resizedHeight];
|
|
587
|
+
}
|
|
588
|
+
const aspectRatio = width / height;
|
|
589
|
+
const shortEdge = (longEdge) => Math.max(roundHalfToEven(longEdge / aspectRatio), 1);
|
|
590
|
+
let low = 1;
|
|
591
|
+
let high = width;
|
|
592
|
+
while (low + 1 < high) {
|
|
593
|
+
const mid = Math.floor((low + high) / 2);
|
|
594
|
+
if (fits(mid, shortEdge(mid))) low = mid;
|
|
595
|
+
else high = mid;
|
|
596
|
+
}
|
|
597
|
+
return [low, shortEdge(low)];
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* The largest size that any Claude model reads an image at. Claude scales a
|
|
601
|
+
* larger image down to this size, so an image at this size loses no detail.
|
|
602
|
+
*/
|
|
603
|
+
function claudeMaxImageSize(width, height) {
|
|
604
|
+
return claudeResizedImageSize(width, height, CLAUDE_HIGH_RES_IMAGE);
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Estimate one image for a model with the rule that `estimateMessagesTokens`
|
|
608
|
+
* uses. `sized` is false when the image used the flat per-image value.
|
|
609
|
+
*/
|
|
610
|
+
function estimateImageTokens(image, modelId) {
|
|
611
|
+
const dimensions = modelId.startsWith("anthropic/") ? readImageDimensions(image) : void 0;
|
|
612
|
+
if (!dimensions) return {
|
|
613
|
+
tokens: tokensForChars(IMAGE_CHARS, getTokenEstimateProfile(modelId)),
|
|
614
|
+
sized: false
|
|
615
|
+
};
|
|
616
|
+
const limits = CLAUDE_STANDARD_IMAGE_MODEL.test(modelId) ? CLAUDE_STANDARD_IMAGE : CLAUDE_HIGH_RES_IMAGE;
|
|
617
|
+
const [width, height] = claudeResizedImageSize(dimensions.width, dimensions.height, limits);
|
|
618
|
+
return {
|
|
619
|
+
tokens: claudeImagePatches(width, height),
|
|
620
|
+
sized: true
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
/** Estimate text tokens for local budgets that have no model. */
|
|
624
|
+
function estimateTextTokens(text) {
|
|
625
|
+
return tokensForChars(text.length, DEFAULT_TOKEN_ESTIMATE);
|
|
626
|
+
}
|
|
627
|
+
/** Convert a local text token budget to the characters it allows. */
|
|
628
|
+
function textCharsForTokens(tokens) {
|
|
629
|
+
return tokens * DEFAULT_TOKEN_ESTIMATE.charsPerToken;
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Estimate messages from their text size at the model's characters per token,
|
|
633
|
+
* plus the tokens of each image.
|
|
634
|
+
*/
|
|
635
|
+
function estimateMessagesTokens(messages, modelId) {
|
|
636
|
+
const profile = getTokenEstimateProfile(modelId);
|
|
637
|
+
return messages.reduce((total, message) => {
|
|
638
|
+
const overhead = message.role === "toolResult" ? profile.toolResultOverheadTokens : 0;
|
|
639
|
+
const images = messageImages(message).reduce((tokens, image) => tokens + estimateImageTokens(image, modelId).tokens, 0);
|
|
640
|
+
return total + tokensForChars(messageChars(message), profile) + images + overhead;
|
|
641
|
+
}, 0);
|
|
642
|
+
}
|
|
643
|
+
/** Estimate the tokens that the system prompt and tool definitions add to a model request. */
|
|
644
|
+
function estimateRequestOverheadTokens(systemPrompt, tools, modelId) {
|
|
645
|
+
const definitions = tools.map(({ name, description, parameters }) => ({
|
|
646
|
+
name,
|
|
647
|
+
description,
|
|
648
|
+
parameters
|
|
649
|
+
}));
|
|
650
|
+
return tokensForChars(systemPrompt.length + JSON.stringify(definitions).length, getTokenEstimateProfile(modelId));
|
|
651
|
+
}
|
|
652
|
+
// src/chat/pi/request-prefix-attributes.ts
|
|
653
|
+
const HASH_HEX_CHARS = 16;
|
|
654
|
+
const MESSAGE_SEPARATOR = "\n";
|
|
655
|
+
function withoutCacheControl(key, value) {
|
|
656
|
+
return key === "cache_control" ? void 0 : value;
|
|
657
|
+
}
|
|
658
|
+
function canonicalMessageValue(key, value) {
|
|
659
|
+
if (key === "content" && typeof value === "string") return [{
|
|
660
|
+
type: "text",
|
|
661
|
+
text: value
|
|
662
|
+
}];
|
|
663
|
+
return withoutCacheControl(key, value);
|
|
664
|
+
}
|
|
665
|
+
function digest(hash) {
|
|
666
|
+
return hash.digest("hex").slice(0, HASH_HEX_CHARS);
|
|
667
|
+
}
|
|
668
|
+
function hashJson(value, replacer = withoutCacheControl) {
|
|
669
|
+
return digest(createHash("sha256").update(JSON.stringify(value, replacer)));
|
|
670
|
+
}
|
|
671
|
+
function lastAssistantIndex(messages) {
|
|
672
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
673
|
+
const message = messages[index];
|
|
674
|
+
if (typeof message === "object" && message !== null && message.role === "assistant") return index;
|
|
675
|
+
}
|
|
676
|
+
return -1;
|
|
677
|
+
}
|
|
678
|
+
function messagesHashes(messages) {
|
|
679
|
+
const lastReply = lastAssistantIndex(messages);
|
|
680
|
+
const hash = createHash("sha256");
|
|
681
|
+
let beforeLastReply;
|
|
682
|
+
for (const [index, message] of messages.entries()) {
|
|
683
|
+
if (index === lastReply) beforeLastReply = digest(hash.copy());
|
|
684
|
+
hash.update(JSON.stringify(message, canonicalMessageValue)).update(MESSAGE_SEPARATOR);
|
|
685
|
+
}
|
|
686
|
+
return {
|
|
687
|
+
full: digest(hash),
|
|
688
|
+
beforeLastReply
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
function sortedKeys(_key, value) {
|
|
692
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
|
|
693
|
+
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
694
|
+
}
|
|
695
|
+
function prefixHash(parts) {
|
|
696
|
+
return digest(createHash("sha256").update(parts.map((part) => part ?? "").join("\n")));
|
|
697
|
+
}
|
|
698
|
+
function readableString(value, key) {
|
|
699
|
+
if (typeof value !== "object" || value === null) return;
|
|
700
|
+
const field = value[key];
|
|
701
|
+
return typeof field === "string" ? field : void 0;
|
|
702
|
+
}
|
|
703
|
+
function requestImages(messages) {
|
|
704
|
+
const images = [];
|
|
705
|
+
const visit = (content) => {
|
|
706
|
+
if (!Array.isArray(content)) return;
|
|
707
|
+
for (const block of content) {
|
|
708
|
+
if (typeof block !== "object" || block === null) continue;
|
|
709
|
+
const { type, source, content: nested } = block;
|
|
710
|
+
if (type === "image") images.push({
|
|
711
|
+
type: "image",
|
|
712
|
+
data: readableString(source, "data") ?? "",
|
|
713
|
+
mimeType: readableString(source, "media_type") ?? ""
|
|
714
|
+
});
|
|
715
|
+
else if (type === "tool_result") visit(nested);
|
|
716
|
+
}
|
|
717
|
+
};
|
|
718
|
+
for (const message of messages) visit(message?.content);
|
|
719
|
+
return images;
|
|
720
|
+
}
|
|
721
|
+
function imageAttributes(messages, model) {
|
|
722
|
+
const images = Array.isArray(messages) ? requestImages(messages) : [];
|
|
723
|
+
if (images.length === 0) return {};
|
|
724
|
+
const modelId = typeof model === "string" ? model : "";
|
|
725
|
+
let estimate = 0;
|
|
726
|
+
let unsized = 0;
|
|
727
|
+
for (const image of images) {
|
|
728
|
+
const { tokens, sized } = estimateImageTokens(image, modelId);
|
|
729
|
+
estimate += tokens;
|
|
730
|
+
if (!sized) unsized += 1;
|
|
731
|
+
}
|
|
732
|
+
return {
|
|
733
|
+
"app.ai.request.images.count": images.length,
|
|
734
|
+
"app.ai.request.images.estimate": estimate,
|
|
735
|
+
"app.ai.request.images.unsized": unsized
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
function payloadAttributes(payload) {
|
|
739
|
+
const { model, system, tools, messages, thinking, output_config } = payload;
|
|
740
|
+
const systemHash = system !== void 0 ? hashJson(system) : void 0;
|
|
741
|
+
const toolsHash = Array.isArray(tools) ? hashJson(tools) : void 0;
|
|
742
|
+
const messagesHash = Array.isArray(messages) ? messagesHashes(messages) : void 0;
|
|
743
|
+
const settingsHash = hashJson({
|
|
744
|
+
thinking,
|
|
745
|
+
output_config
|
|
746
|
+
}, sortedKeys);
|
|
747
|
+
const prefixParts = [
|
|
748
|
+
typeof model === "string" ? model : void 0,
|
|
749
|
+
settingsHash,
|
|
750
|
+
toolsHash,
|
|
751
|
+
systemHash
|
|
752
|
+
];
|
|
753
|
+
const thinkingType = readableString(thinking, "type");
|
|
754
|
+
const effort = readableString(output_config, "effort");
|
|
755
|
+
return {
|
|
756
|
+
...systemHash ? { "app.ai.request.system_instructions.hash": systemHash } : void 0,
|
|
757
|
+
"app.ai.request.tools.count": Array.isArray(tools) ? tools.length : 0,
|
|
758
|
+
...toolsHash ? { "app.ai.request.tools.hash": toolsHash } : void 0,
|
|
759
|
+
...Array.isArray(messages) ? { "app.ai.request.messages.count": messages.length } : void 0,
|
|
760
|
+
...messagesHash ? { "app.ai.request.messages.hash": messagesHash.full } : void 0,
|
|
761
|
+
...messagesHash?.beforeLastReply ? { "app.ai.request.messages.before_last_reply.hash": messagesHash.beforeLastReply } : void 0,
|
|
762
|
+
"app.ai.request.prefix.hash": prefixHash([...prefixParts, messagesHash?.full]),
|
|
763
|
+
...messagesHash?.beforeLastReply ? { "app.ai.request.prefix.before_last_reply.hash": prefixHash([...prefixParts, messagesHash.beforeLastReply]) } : void 0,
|
|
764
|
+
...thinkingType ? { "app.ai.request.thinking.type": thinkingType } : void 0,
|
|
765
|
+
...effort ? { "app.ai.request.effort": effort } : void 0,
|
|
766
|
+
...imageAttributes(messages, model)
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Hashes of the cache prefix parts of one provider request body, plus its
|
|
771
|
+
* thinking and effort settings, to tell a changed cache prefix apart from an
|
|
772
|
+
* expired cache. Also counts and estimates the request's images.
|
|
773
|
+
* Pass the payload that Pi gives to `onPayload`. Never throws: telemetry must
|
|
774
|
+
* not fail the request.
|
|
775
|
+
*
|
|
776
|
+
* To classify a cache miss, compare a `gen_ai.chat` span with the previous
|
|
777
|
+
* call in the same `gen_ai.conversation.id`:
|
|
778
|
+
* 1. `prefix.before_last_reply.hash` differs from the previous
|
|
779
|
+
* `prefix.hash`: Junior changed the prefix. The system or tools hash shows
|
|
780
|
+
* a prompt or tool change; `thinking.type` or `effort` shows a settings
|
|
781
|
+
* change; with all part hashes equal, the model or a thinking budget
|
|
782
|
+
* changed. `messages.before_last_reply.hash` not equal to the previous
|
|
783
|
+
* `messages.hash` means a history rewrite, expected with
|
|
784
|
+
* `gen_ai.conversation.compacted`.
|
|
785
|
+
* 2. Equal, with a gap of 5 minutes or more: the cache expired.
|
|
786
|
+
* 3. Equal, with a shorter gap: the provider or the gateway did not use it.
|
|
787
|
+
*
|
|
788
|
+
* `images.estimate` is the only per-image number, because Anthropic usage has
|
|
789
|
+
* no per-image split. Check it against the change in
|
|
790
|
+
* `gen_ai.usage.input_tokens` from the previous call.
|
|
791
|
+
*/
|
|
792
|
+
function requestPrefixAttributes(payload) {
|
|
793
|
+
if (typeof payload !== "object" || payload === null) return {};
|
|
794
|
+
try {
|
|
795
|
+
return payloadAttributes(payload);
|
|
796
|
+
} catch {
|
|
797
|
+
return {};
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
// src/chat/state/locks.ts
|
|
801
|
+
const ACTIVE_LOCK_TTL_MS = 9e4;
|
|
802
|
+
const MUTATION_LOCK_TTL_MS = 1e4;
|
|
803
|
+
/**
|
|
804
|
+
* Acquire a lock for long-running work that the queued state adapter should
|
|
805
|
+
* keep alive while the owning invocation is still making progress.
|
|
806
|
+
*/
|
|
807
|
+
async function acquireActiveLock(state, threadId) {
|
|
808
|
+
return await state.acquireLock(threadId, ACTIVE_LOCK_TTL_MS);
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* Run work under one lock, optionally waiting for the current owner.
|
|
812
|
+
* `keepAlive` is for multi-store mutations that must retain ownership until all
|
|
813
|
+
* side effects finish; callers should still fence each blind write.
|
|
814
|
+
*/
|
|
815
|
+
async function withLock(state, key, run, options = {}) {
|
|
816
|
+
const ttlMs = options.ttlMs ?? 9e4;
|
|
817
|
+
const startedAtMs = Date.now();
|
|
818
|
+
let lock;
|
|
819
|
+
while (true) {
|
|
820
|
+
lock = await state.acquireLock(key, ttlMs);
|
|
821
|
+
if (lock) break;
|
|
822
|
+
if (Date.now() - startedAtMs >= (options.waitMs ?? 0)) return { acquired: false };
|
|
823
|
+
await setTimeout(options.retryMs ?? 25, void 0, { ref: false });
|
|
824
|
+
}
|
|
825
|
+
const heartbeat = options.keepAlive ? setInterval(() => void state.extendLock(lock, ttlMs).catch(() => void 0), Math.max(1, Math.floor(ttlMs / 3))) : void 0;
|
|
826
|
+
heartbeat?.unref();
|
|
827
|
+
try {
|
|
828
|
+
return {
|
|
829
|
+
acquired: true,
|
|
830
|
+
value: await run(lock)
|
|
831
|
+
};
|
|
832
|
+
} finally {
|
|
833
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
834
|
+
await state.releaseLock(lock);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Prove lock ownership immediately before a blind write.
|
|
839
|
+
*
|
|
840
|
+
* Whole-record mutations must stop if their lock expired rather than overwrite
|
|
841
|
+
* state committed by a newer owner.
|
|
842
|
+
*/
|
|
843
|
+
async function fenceLock(state, lock, ttlMs = MUTATION_LOCK_TTL_MS) {
|
|
844
|
+
if (!await state.extendLock(lock, ttlMs)) throw new Error(`Lock ownership was lost before write for ${lock.threadId}`);
|
|
845
|
+
}
|
|
846
|
+
// src/chat/state/cache.ts
|
|
847
|
+
const MAX_CACHE_KEY_LENGTH = 512;
|
|
848
|
+
const LOAD_WAIT_MS = 1e4;
|
|
849
|
+
const LAST_GOOD_MS = 864e5;
|
|
850
|
+
const WRITE_MARK_TTL_MS = 36e5;
|
|
851
|
+
function isFresh(entry) {
|
|
852
|
+
return entry.freshUntilMs === void 0 || Date.now() < entry.freshUntilMs;
|
|
853
|
+
}
|
|
854
|
+
async function storeEntry(state, cacheKey, entry) {
|
|
855
|
+
if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
|
|
856
|
+
await state.set(cacheKey, entry.staleIfError ? {
|
|
857
|
+
freshUntilMs: Date.now() + entry.ttlMs,
|
|
858
|
+
value: entry.value
|
|
859
|
+
} : { value: entry.value }, entry.staleIfError ? entry.ttlMs + LAST_GOOD_MS : entry.ttlMs);
|
|
860
|
+
}
|
|
861
|
+
function writeMarkKey(cacheKey) {
|
|
862
|
+
return `${cacheKey}:written`;
|
|
863
|
+
}
|
|
864
|
+
async function writeUnderLoadLock(state, cacheKey, write) {
|
|
865
|
+
await state.connect();
|
|
866
|
+
if ((await withLock(state, `${cacheKey}:load`, async () => await write(cacheKey), {
|
|
867
|
+
keepAlive: true,
|
|
868
|
+
waitMs: LOAD_WAIT_MS
|
|
869
|
+
})).acquired) return;
|
|
870
|
+
await state.set(writeMarkKey(cacheKey), randomUUID(), WRITE_MARK_TTL_MS);
|
|
871
|
+
await state.delete(cacheKey);
|
|
872
|
+
}
|
|
873
|
+
/** The prefix of every state key of one cache namespace. */
|
|
874
|
+
function cacheKeyPrefix(namespace) {
|
|
875
|
+
return `junior:cache:${namespace}:`;
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* Create a cache in the state adapter under `junior:cache:{namespace}:`.
|
|
879
|
+
* Entries are wrapped, so `null` and `false` values are cache hits. A stale
|
|
880
|
+
* `staleIfError` entry is returned when its reload throws, unless the caller
|
|
881
|
+
* asked for `refresh`.
|
|
882
|
+
*/
|
|
883
|
+
function createCache(state, namespace) {
|
|
884
|
+
const stateKey = (key) => {
|
|
885
|
+
if (!key.trim()) throw new Error("Cache key is required");
|
|
886
|
+
if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
|
|
887
|
+
return `${cacheKeyPrefix(namespace)}${key}`;
|
|
888
|
+
};
|
|
889
|
+
return {
|
|
890
|
+
async get(key) {
|
|
891
|
+
const cacheKey = stateKey(key);
|
|
892
|
+
await state.connect();
|
|
893
|
+
const hit = await state.get(cacheKey);
|
|
894
|
+
return hit && isFresh(hit) ? hit.value : void 0;
|
|
895
|
+
},
|
|
896
|
+
async getOrLoad(key, load, options) {
|
|
897
|
+
const cacheKey = stateKey(key);
|
|
898
|
+
const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
|
|
899
|
+
await state.connect();
|
|
900
|
+
const hit = await cached();
|
|
901
|
+
if (hit && isFresh(hit)) return hit.value;
|
|
902
|
+
try {
|
|
903
|
+
const attempt = await withLock(state, `${cacheKey}:load`, async () => {
|
|
904
|
+
const loadedMeanwhile = await cached();
|
|
905
|
+
if (loadedMeanwhile && isFresh(loadedMeanwhile)) return loadedMeanwhile.value;
|
|
906
|
+
const mark = await state.get(writeMarkKey(cacheKey));
|
|
907
|
+
const entry = await load();
|
|
908
|
+
if (entry.ttlMs !== void 0) {
|
|
909
|
+
await storeEntry(state, cacheKey, {
|
|
910
|
+
...entry,
|
|
911
|
+
ttlMs: entry.ttlMs
|
|
912
|
+
});
|
|
913
|
+
const markNow = await state.get(writeMarkKey(cacheKey));
|
|
914
|
+
if (markNow && markNow !== mark) await state.delete(cacheKey);
|
|
915
|
+
}
|
|
916
|
+
return entry.value;
|
|
917
|
+
}, {
|
|
918
|
+
keepAlive: true,
|
|
919
|
+
waitMs: LOAD_WAIT_MS
|
|
920
|
+
});
|
|
921
|
+
if (attempt.acquired) return attempt.value;
|
|
922
|
+
return (await load()).value;
|
|
923
|
+
} catch (error) {
|
|
924
|
+
if (hit) return hit.value;
|
|
925
|
+
throw error;
|
|
926
|
+
}
|
|
927
|
+
},
|
|
928
|
+
async update(key, next) {
|
|
929
|
+
await writeUnderLoadLock(state, stateKey(key), async (cacheKey) => {
|
|
930
|
+
const entry = next((await state.get(cacheKey))?.value);
|
|
931
|
+
if (entry?.ttlMs !== void 0) await storeEntry(state, cacheKey, {
|
|
932
|
+
...entry,
|
|
933
|
+
ttlMs: entry.ttlMs
|
|
934
|
+
});
|
|
935
|
+
});
|
|
936
|
+
},
|
|
937
|
+
async delete(key) {
|
|
938
|
+
await writeUnderLoadLock(state, stateKey(key), async (cacheKey) => {
|
|
939
|
+
await state.delete(cacheKey);
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
// src/chat/gateway-providers/routing.ts
|
|
945
|
+
const ENABLED_PROVIDERS_KEY = "junior:gateway:enabled_providers";
|
|
946
|
+
const MODEL_ENDPOINTS_URL = "https://ai-gateway.vercel.sh/v1/models";
|
|
947
|
+
const SERVED_PROVIDERS_CACHE_NAMESPACE = "gateway-served-providers";
|
|
948
|
+
const SERVED_PROVIDERS_TTL_MS = 36e5;
|
|
949
|
+
const ENDPOINTS_TIMEOUT_MS = 5e3;
|
|
950
|
+
const PROVIDER_SLUGS = { vertexAnthropic: "vertex" };
|
|
951
|
+
const LOCAL_TTL_MS = 6e4;
|
|
952
|
+
const localEnabledProviders = /* @__PURE__ */ new Map();
|
|
953
|
+
const localServedProviders = /* @__PURE__ */ new Map();
|
|
954
|
+
function readLocal(entries, key, load) {
|
|
955
|
+
const entry = entries.get(key);
|
|
956
|
+
if (entry && entry.expiresAtMs > Date.now()) return entry.value;
|
|
957
|
+
const value = load();
|
|
958
|
+
entries.set(key, {
|
|
959
|
+
value,
|
|
960
|
+
expiresAtMs: Date.now() + LOCAL_TTL_MS
|
|
961
|
+
});
|
|
962
|
+
value.catch(() => {
|
|
963
|
+
if (entries.get(key)?.value === value) entries.delete(key);
|
|
964
|
+
});
|
|
965
|
+
return value;
|
|
966
|
+
}
|
|
967
|
+
const enabledProvidersSchema = z.array(z.string());
|
|
968
|
+
const messagesBodySchema = z.looseObject({ providerOptions: z.looseObject({ gateway: z.looseObject({}).optional() }).optional() });
|
|
969
|
+
const modelEndpointsSchema = z.object({ data: z.object({ endpoints: z.array(z.object({ provider_name: z.string() })) }) });
|
|
970
|
+
/** Read the enabled providers. Null means every provider is enabled. */
|
|
971
|
+
async function readEnabledProviders(state) {
|
|
972
|
+
const stored = await state.get(ENABLED_PROVIDERS_KEY);
|
|
973
|
+
return stored === null ? null : enabledProvidersSchema.parse(stored);
|
|
974
|
+
}
|
|
975
|
+
/**
|
|
976
|
+
* Save the enabled providers. Null enables every provider again.
|
|
977
|
+
*
|
|
978
|
+
* Model calls in this process see the change right away. Other processes see
|
|
979
|
+
* it when their local copy expires.
|
|
980
|
+
*/
|
|
981
|
+
async function saveEnabledProviders(state, enabled) {
|
|
982
|
+
if (enabled === null) await state.delete(ENABLED_PROVIDERS_KEY);
|
|
983
|
+
else await state.set(ENABLED_PROVIDERS_KEY, [...new Set(enabled)].sort());
|
|
984
|
+
localEnabledProviders.clear();
|
|
985
|
+
}
|
|
986
|
+
async function fetchServedProviders(modelId) {
|
|
987
|
+
const path = modelId.split("/").map(encodeURIComponent).join("/");
|
|
988
|
+
const response = await fetch(`${MODEL_ENDPOINTS_URL}/${path}/endpoints`, { signal: AbortSignal.timeout(ENDPOINTS_TIMEOUT_MS) });
|
|
989
|
+
if (response.status === 404) return [];
|
|
990
|
+
if (!response.ok) throw new Error(`AI Gateway endpoints returned ${response.status}`);
|
|
991
|
+
const { data } = modelEndpointsSchema.parse(await response.json());
|
|
992
|
+
const slugs = data.endpoints.map(({ provider_name }) => PROVIDER_SLUGS[provider_name] ?? provider_name);
|
|
993
|
+
return [...new Set(slugs)];
|
|
994
|
+
}
|
|
995
|
+
/** List the providers that AI Gateway can route one model to. */
|
|
996
|
+
async function readServedProviders(state, modelId) {
|
|
997
|
+
return await createCache(state, SERVED_PROVIDERS_CACHE_NAMESPACE).getOrLoad(modelId, async () => ({
|
|
998
|
+
value: await fetchServedProviders(modelId),
|
|
999
|
+
ttlMs: SERVED_PROVIDERS_TTL_MS
|
|
1000
|
+
}));
|
|
1001
|
+
}
|
|
1002
|
+
async function gatewayOnlyForModel(modelId) {
|
|
1003
|
+
const { getStateAdapter } = await import("./db-BFmyYZtJ.js").then((n) => n.Wu);
|
|
1004
|
+
const state = getStateAdapter();
|
|
1005
|
+
const enabled = await readLocal(localEnabledProviders, "enabled", () => readEnabledProviders(state));
|
|
1006
|
+
if (enabled === null) return void 0;
|
|
1007
|
+
let served;
|
|
1008
|
+
try {
|
|
1009
|
+
served = await readLocal(localServedProviders, modelId, () => readServedProviders(state, modelId));
|
|
1010
|
+
} catch (error) {
|
|
1011
|
+
logWarn("ai.gateway.served_providers.failed", {
|
|
1012
|
+
"gen_ai.request.model": modelId,
|
|
1013
|
+
"exception.message": error instanceof Error ? error.message : String(error)
|
|
1014
|
+
});
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
return gatewayOnlyProviders(enabled, served);
|
|
1018
|
+
}
|
|
1019
|
+
function withGatewayOnly(payload, only) {
|
|
1020
|
+
const body = messagesBodySchema.parse(payload);
|
|
1021
|
+
return {
|
|
1022
|
+
...body,
|
|
1023
|
+
providerOptions: {
|
|
1024
|
+
...body.providerOptions,
|
|
1025
|
+
gateway: {
|
|
1026
|
+
...body.providerOptions?.gateway,
|
|
1027
|
+
only
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* Wrap a Pi Messages stream so each request body carries the `only` list of
|
|
1034
|
+
* the enabled providers. AI Gateway reads it from
|
|
1035
|
+
* `providerOptions.gateway.only` in the Messages API body.
|
|
1036
|
+
*/
|
|
1037
|
+
function withEnabledGatewayProviders(stream) {
|
|
1038
|
+
return (model, context, options) => stream(model, context, Object.assign({}, options, { onPayload: async (payload, payloadModel) => {
|
|
1039
|
+
const replaced = await options?.onPayload?.(payload, payloadModel);
|
|
1040
|
+
const only = await gatewayOnlyForModel(model.id);
|
|
1041
|
+
return only ? withGatewayOnly(replaced ?? payload, only) : replaced;
|
|
1042
|
+
} }));
|
|
1043
|
+
}
|
|
1044
|
+
// src/chat/pi/client.ts
|
|
1045
|
+
registerApiProvider({
|
|
1046
|
+
api: "anthropic-messages",
|
|
1047
|
+
stream: withEnabledGatewayProviders(streamAnthropic),
|
|
1048
|
+
streamSimple: withEnabledGatewayProviders(streamSimpleAnthropic)
|
|
1049
|
+
});
|
|
1050
|
+
const GATEWAY_PROVIDER = "vercel-ai-gateway";
|
|
1051
|
+
const GATEWAY_BASE_URL = "https://ai-gateway.vercel.sh";
|
|
1052
|
+
const GATEWAY_MODEL_OVERRIDES = {
|
|
1053
|
+
"anthropic/claude-opus-5.5": {
|
|
1054
|
+
id: "anthropic/claude-opus-5.5",
|
|
1055
|
+
name: "Claude Opus 5.5",
|
|
1056
|
+
api: "anthropic-messages",
|
|
1057
|
+
provider: GATEWAY_PROVIDER,
|
|
1058
|
+
baseUrl: GATEWAY_BASE_URL,
|
|
1059
|
+
reasoning: true,
|
|
1060
|
+
input: ["text", "image"],
|
|
1061
|
+
cost: {
|
|
1062
|
+
input: 4,
|
|
1063
|
+
output: 20,
|
|
1064
|
+
cacheRead: .2,
|
|
1065
|
+
cacheWrite: 5
|
|
1066
|
+
},
|
|
1067
|
+
contextWindow: 1e6,
|
|
1068
|
+
maxTokens: 128e3,
|
|
1069
|
+
thinkingLevelMap: {
|
|
1070
|
+
xhigh: "xhigh",
|
|
1071
|
+
max: "max"
|
|
1072
|
+
},
|
|
1073
|
+
compat: {
|
|
1074
|
+
forceAdaptiveThinking: true,
|
|
1075
|
+
supportsMidConvoSystemMessages: true,
|
|
1076
|
+
supportsTemperature: false
|
|
1077
|
+
}
|
|
1078
|
+
},
|
|
1079
|
+
"xai/grok-4.5": {
|
|
1080
|
+
id: "xai/grok-4.5",
|
|
1081
|
+
name: "Grok 4.5",
|
|
1082
|
+
api: "anthropic-messages",
|
|
1083
|
+
provider: GATEWAY_PROVIDER,
|
|
1084
|
+
baseUrl: GATEWAY_BASE_URL,
|
|
1085
|
+
reasoning: true,
|
|
1086
|
+
input: ["text", "image"],
|
|
1087
|
+
cost: {
|
|
1088
|
+
input: 2,
|
|
1089
|
+
output: 6,
|
|
1090
|
+
cacheRead: .3,
|
|
1091
|
+
cacheWrite: 0
|
|
1092
|
+
},
|
|
1093
|
+
contextWindow: 5e5,
|
|
1094
|
+
maxTokens: 5e5
|
|
1095
|
+
},
|
|
1096
|
+
"openai/gpt-6-luna": {
|
|
1097
|
+
id: "openai/gpt-6-luna",
|
|
1098
|
+
name: "GPT-6 Luna",
|
|
1099
|
+
api: "anthropic-messages",
|
|
1100
|
+
provider: GATEWAY_PROVIDER,
|
|
1101
|
+
baseUrl: GATEWAY_BASE_URL,
|
|
1102
|
+
reasoning: true,
|
|
1103
|
+
input: ["text", "image"],
|
|
1104
|
+
cost: {
|
|
1105
|
+
input: .1,
|
|
1106
|
+
output: .5,
|
|
1107
|
+
cacheRead: .01,
|
|
1108
|
+
cacheWrite: .125,
|
|
1109
|
+
tiers: [{
|
|
1110
|
+
inputTokensAbove: 272e3,
|
|
1111
|
+
input: .2,
|
|
1112
|
+
output: .75,
|
|
1113
|
+
cacheRead: .02,
|
|
1114
|
+
cacheWrite: .25
|
|
1115
|
+
}]
|
|
1116
|
+
},
|
|
1117
|
+
contextWindow: 105e4,
|
|
1118
|
+
maxTokens: 128e3,
|
|
1119
|
+
thinkingLevelMap: {
|
|
1120
|
+
xhigh: "xhigh",
|
|
1121
|
+
max: "max"
|
|
1122
|
+
},
|
|
1123
|
+
compat: { supportsMidConvoSystemMessages: true }
|
|
1124
|
+
},
|
|
1125
|
+
"openai/gpt-6-astra": {
|
|
1126
|
+
id: "openai/gpt-6-astra",
|
|
1127
|
+
name: "GPT-6 Astra",
|
|
1128
|
+
api: "anthropic-messages",
|
|
1129
|
+
provider: GATEWAY_PROVIDER,
|
|
1130
|
+
baseUrl: GATEWAY_BASE_URL,
|
|
1131
|
+
reasoning: true,
|
|
1132
|
+
input: ["text", "image"],
|
|
1133
|
+
cost: {
|
|
1134
|
+
input: 10,
|
|
1135
|
+
output: 50,
|
|
1136
|
+
cacheRead: 1,
|
|
1137
|
+
cacheWrite: 12.5,
|
|
1138
|
+
tiers: [{
|
|
1139
|
+
inputTokensAbove: 272e3,
|
|
1140
|
+
input: 20,
|
|
1141
|
+
output: 75,
|
|
1142
|
+
cacheRead: 2,
|
|
1143
|
+
cacheWrite: 25
|
|
1144
|
+
}]
|
|
1145
|
+
},
|
|
1146
|
+
contextWindow: 105e4,
|
|
1147
|
+
maxTokens: 128e3,
|
|
1148
|
+
thinkingLevelMap: {
|
|
1149
|
+
xhigh: "xhigh",
|
|
1150
|
+
max: "max"
|
|
1151
|
+
},
|
|
1152
|
+
compat: { supportsTemperature: false }
|
|
1153
|
+
}
|
|
1154
|
+
};
|
|
1155
|
+
const GEN_AI_PROVIDER_NAME = GATEWAY_PROVIDER;
|
|
1156
|
+
const GEN_AI_SERVER_ADDRESS = "ai-gateway.vercel.sh";
|
|
1157
|
+
const GEN_AI_OPERATION_CHAT = "chat";
|
|
1158
|
+
const GEN_AI_OPERATION_EMBEDDINGS = "embeddings";
|
|
1159
|
+
const GEN_AI_OPERATION_RERANK = "rerank";
|
|
1160
|
+
const GEN_AI_OPERATION_DECIDE = "decide";
|
|
1161
|
+
const EMBEDDING_INPUT_COST_USD_PER_MILLION_TOKENS = {
|
|
1162
|
+
"cohere/embed-v4.0": .12,
|
|
1163
|
+
"google/gemini-embedding-001": .15,
|
|
1164
|
+
"google/text-embedding-005": .025,
|
|
1165
|
+
"mistral/mistral-embed": .1,
|
|
1166
|
+
"openai/text-embedding-3-large": .13,
|
|
1167
|
+
"openai/text-embedding-3-small": .02,
|
|
1168
|
+
"openai/text-embedding-ada-002": .1,
|
|
1169
|
+
"voyage/voyage-3.5": .06,
|
|
1170
|
+
"voyage/voyage-3.5-lite": .02,
|
|
1171
|
+
"voyage/voyage-4": .06,
|
|
1172
|
+
"voyage/voyage-4-large": .12,
|
|
1173
|
+
"voyage/voyage-4-lite": .02
|
|
1174
|
+
};
|
|
1175
|
+
const DECISION_INPUT_COST_USD_PER_MILLION_TOKENS = {
|
|
1176
|
+
"openai/gpt-6-luna-decisions": .1,
|
|
1177
|
+
"typesafe-ai/jev": .042
|
|
1178
|
+
};
|
|
1179
|
+
function decisionCostUsd(modelId, inputTokens) {
|
|
1180
|
+
const costPerMillionTokens = DECISION_INPUT_COST_USD_PER_MILLION_TOKENS[modelId];
|
|
1181
|
+
return costPerMillionTokens === void 0 || inputTokens === void 0 ? void 0 : inputTokens * costPerMillionTokens / 1e6;
|
|
1182
|
+
}
|
|
1183
|
+
function embeddingCostUsd(modelId, inputTokens) {
|
|
1184
|
+
const costPerMillionTokens = EMBEDDING_INPUT_COST_USD_PER_MILLION_TOKENS[modelId];
|
|
1185
|
+
return costPerMillionTokens === void 0 ? void 0 : inputTokens * costPerMillionTokens / 1e6;
|
|
1186
|
+
}
|
|
1187
|
+
function extractText(message) {
|
|
1188
|
+
return (message.content ?? []).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text ?? "").join("").trim();
|
|
1189
|
+
}
|
|
1190
|
+
function findGatewayModel(modelId) {
|
|
1191
|
+
return GATEWAY_MODEL_OVERRIDES[modelId] ?? getModels(GATEWAY_PROVIDER).find((model) => model.id === modelId);
|
|
1192
|
+
}
|
|
1193
|
+
/** Resolve gateway models through local overrides, then Pi's bundled catalog. */
|
|
1194
|
+
function resolveGatewayModel(modelId) {
|
|
1195
|
+
const matched = findGatewayModel(modelId);
|
|
1196
|
+
if (!matched) throw new Error(`Unknown AI Gateway model id: ${modelId}`);
|
|
1197
|
+
return {
|
|
1198
|
+
...matched,
|
|
1199
|
+
compat: {
|
|
1200
|
+
...matched.compat,
|
|
1201
|
+
sendSessionAffinityHeaders: true
|
|
1202
|
+
}
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
/** Execute a direct chat completion inside a dedicated `gen_ai.chat` span. */
|
|
1206
|
+
async function completeText(params) {
|
|
1207
|
+
const model = resolveGatewayModel(params.modelId);
|
|
1208
|
+
const credential = await resolveGatewayCredential();
|
|
1209
|
+
const apiKey = credential.token;
|
|
1210
|
+
const authMode = credential.mode;
|
|
1211
|
+
const effectivePrivacy = getCurrentConversationPrivacy() ?? "private";
|
|
1212
|
+
const recordContent = (params.messageAttributeMode ?? (effectivePrivacy === "public" ? "content" : "metadata")) === "content";
|
|
1213
|
+
const baseAttributes = {
|
|
1214
|
+
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
1215
|
+
"gen_ai.operation.name": GEN_AI_OPERATION_CHAT,
|
|
1216
|
+
"gen_ai.request.model": params.modelId,
|
|
1217
|
+
"gen_ai.prompt.name": params.promptName,
|
|
1218
|
+
"server.address": GEN_AI_SERVER_ADDRESS,
|
|
1219
|
+
"gen_ai.conversation.compacted": hasCompactedConversationContext(params.messages) || void 0,
|
|
1220
|
+
"app.conversation.privacy": effectivePrivacy,
|
|
1221
|
+
"gen_ai.request.reasoning.level": params.thinkingLevel,
|
|
1222
|
+
"gen_ai.request.max_tokens": params.maxTokens
|
|
1223
|
+
};
|
|
1224
|
+
const startAttributes = {
|
|
1225
|
+
...baseAttributes,
|
|
1226
|
+
...toGenAiMessagesTraceAttributes("gen_ai.input", params.messages),
|
|
1227
|
+
"gen_ai.system_instructions.content_chars": params.system?.length,
|
|
1228
|
+
"gen_ai.system_instructions": recordContent && params.system ? serializeGenAiAttribute([{
|
|
1229
|
+
type: "text",
|
|
1230
|
+
content: params.system
|
|
1231
|
+
}]) : void 0,
|
|
1232
|
+
"gen_ai.input.messages": recordContent ? serializeGenAiAttribute(params.messages.map(toCanonicalInputMessage)) : void 0,
|
|
1233
|
+
"gen_ai.provider.auth_mode": authMode
|
|
1234
|
+
};
|
|
1235
|
+
return withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
1236
|
+
let message;
|
|
1237
|
+
try {
|
|
1238
|
+
message = await completeSimple(model, {
|
|
1239
|
+
systemPrompt: params.system,
|
|
1240
|
+
messages: params.messages,
|
|
1241
|
+
...params.tools ? { tools: params.tools } : void 0
|
|
1242
|
+
}, {
|
|
1243
|
+
apiKey,
|
|
1244
|
+
maxTokens: params.maxTokens,
|
|
1245
|
+
reasoning: params.thinkingLevel,
|
|
1246
|
+
cacheRetention: params.cacheRetention,
|
|
1247
|
+
signal: params.signal,
|
|
1248
|
+
metadata: params.metadata,
|
|
1249
|
+
sessionId: params.sessionId,
|
|
1250
|
+
onPayload: (payload) => {
|
|
1251
|
+
setSpanAttributes(requestPrefixAttributes(payload));
|
|
1252
|
+
},
|
|
1253
|
+
onResponse: (response) => {
|
|
1254
|
+
setSpanAttributes({ "app.ai.gateway.vercel_id": response.headers["x-vercel-id"] });
|
|
1255
|
+
},
|
|
1256
|
+
onProviderStreamEvent: (event) => {
|
|
1257
|
+
setSpanAttributes(gatewayRoutingAttributes(event) ?? {});
|
|
1258
|
+
}
|
|
1259
|
+
});
|
|
1260
|
+
} catch (error) {
|
|
1261
|
+
throw createProviderError(error, { modelId: params.modelId });
|
|
1262
|
+
}
|
|
1263
|
+
const outputText = extractText(message);
|
|
1264
|
+
setSpanAttributes({
|
|
1265
|
+
...toGenAiMessagesTraceAttributes("gen_ai.output", [{
|
|
1266
|
+
role: "assistant",
|
|
1267
|
+
content: outputText ? [{
|
|
1268
|
+
type: "text",
|
|
1269
|
+
text: outputText
|
|
1270
|
+
}] : []
|
|
1271
|
+
}]),
|
|
1272
|
+
"gen_ai.output.messages": recordContent ? serializeGenAiAttribute([toCanonicalOutputMessage(message)]) : void 0,
|
|
1273
|
+
...extractGenAiUsageAttributes(message),
|
|
1274
|
+
"gen_ai.response.finish_reasons": [message.stopReason],
|
|
1275
|
+
"gen_ai.response.model": message.model,
|
|
1276
|
+
"gen_ai.response.id": message.responseId
|
|
1277
|
+
});
|
|
1278
|
+
if (message.stopReason === "error") {
|
|
1279
|
+
const providerMessage = message.errorMessage?.trim() || "Unknown provider error";
|
|
1280
|
+
logWarn("ai.completion.provider_error", {
|
|
1281
|
+
...baseAttributes,
|
|
1282
|
+
"exception.message": providerMessage
|
|
1283
|
+
});
|
|
1284
|
+
throw createProviderError(providerMessage, { modelId: params.modelId });
|
|
1285
|
+
}
|
|
1286
|
+
return {
|
|
1287
|
+
message,
|
|
1288
|
+
text: outputText
|
|
1289
|
+
};
|
|
1290
|
+
}, startAttributes);
|
|
1291
|
+
}
|
|
1292
|
+
function logContextFromMetadata(modelId, metadata) {
|
|
1293
|
+
const conversationId = typeof metadata?.["conversationId"] === "string" && metadata["conversationId"] ? metadata["conversationId"] : void 0;
|
|
1294
|
+
const messageConversationId = typeof metadata?.["threadId"] === "string" ? metadata["threadId"] : void 0;
|
|
1295
|
+
const destinationName = typeof metadata?.["channelId"] === "string" ? metadata["channelId"] : void 0;
|
|
1296
|
+
const runId = typeof metadata?.["runId"] === "string" ? metadata["runId"] : void 0;
|
|
1297
|
+
return {
|
|
1298
|
+
modelId,
|
|
1299
|
+
...conversationId ? { conversationId } : void 0,
|
|
1300
|
+
...messageConversationId ? { messageConversationId } : void 0,
|
|
1301
|
+
...destinationName ? { destinationName } : void 0,
|
|
1302
|
+
...runId ? { runId } : void 0
|
|
1303
|
+
};
|
|
1304
|
+
}
|
|
1305
|
+
function objectCompletionCost(modelId, usage) {
|
|
1306
|
+
const cacheRead = usage.inputTokenDetails.cacheReadTokens;
|
|
1307
|
+
const cacheWrite = usage.inputTokenDetails.cacheWriteTokens;
|
|
1308
|
+
const input = usage.inputTokenDetails.noCacheTokens ?? (usage.inputTokens === void 0 ? void 0 : Math.max(0, usage.inputTokens - (cacheRead ?? 0) - (cacheWrite ?? 0)));
|
|
1309
|
+
if (input === void 0 && usage.outputTokens === void 0 && cacheRead === void 0 && cacheWrite === void 0) return;
|
|
1310
|
+
return calculateCost(resolveGatewayModel(modelId), {
|
|
1311
|
+
input: input ?? 0,
|
|
1312
|
+
output: usage.outputTokens ?? 0,
|
|
1313
|
+
cacheRead: cacheRead ?? 0,
|
|
1314
|
+
cacheWrite: cacheWrite ?? 0,
|
|
1315
|
+
...usage.outputTokenDetails.reasoningTokens !== void 0 ? { reasoning: usage.outputTokenDetails.reasoningTokens } : void 0,
|
|
1316
|
+
totalTokens: usage.totalTokens ?? (input ?? 0) + (usage.outputTokens ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0),
|
|
1317
|
+
cost: {
|
|
1318
|
+
input: 0,
|
|
1319
|
+
output: 0,
|
|
1320
|
+
cacheRead: 0,
|
|
1321
|
+
cacheWrite: 0,
|
|
1322
|
+
total: 0
|
|
1323
|
+
}
|
|
1324
|
+
}).total;
|
|
1325
|
+
}
|
|
1326
|
+
/** Estimate cost without changing the outcome of a successful completion. */
|
|
1327
|
+
function bestEffortObjectCompletionCost(modelId, usage) {
|
|
1328
|
+
try {
|
|
1329
|
+
return objectCompletionCost(modelId, usage);
|
|
1330
|
+
} catch (error) {
|
|
1331
|
+
logWarn("ai.completion.cost_estimate.failed", {
|
|
1332
|
+
"exception.message": error instanceof Error ? error.message : String(error),
|
|
1333
|
+
"gen_ai.request.model": modelId
|
|
1334
|
+
});
|
|
1335
|
+
return;
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
/** Execute a schema-constrained completion using the AI SDK structured output path. */
|
|
1339
|
+
async function completeObject(params) {
|
|
1340
|
+
const maxOutputTokens = structuredOutputTokenLimit(params.maxTokens, findGatewayModel(params.modelId)?.maxTokens);
|
|
1341
|
+
const credential = await resolveGatewayCredential();
|
|
1342
|
+
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
1343
|
+
let result;
|
|
1344
|
+
try {
|
|
1345
|
+
result = await withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
1346
|
+
const result = await generateObject({
|
|
1347
|
+
model: provider.chat(params.modelId),
|
|
1348
|
+
schema: params.schema,
|
|
1349
|
+
prompt: params.prompt,
|
|
1350
|
+
...params.system !== void 0 ? { system: params.system } : void 0,
|
|
1351
|
+
...maxOutputTokens !== void 0 ? { maxOutputTokens } : void 0,
|
|
1352
|
+
...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
|
|
1353
|
+
}).catch((error) => {
|
|
1354
|
+
if (NoObjectGeneratedError.isInstance(error)) setSpanAttributes(objectCompletionAttributes(error.finishReason, error.usage));
|
|
1355
|
+
throw error;
|
|
1356
|
+
});
|
|
1357
|
+
setSpanAttributes(objectCompletionAttributes(result.finishReason, result.usage));
|
|
1358
|
+
return result;
|
|
1359
|
+
}, {
|
|
1360
|
+
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
1361
|
+
"gen_ai.operation.name": GEN_AI_OPERATION_CHAT,
|
|
1362
|
+
"gen_ai.request.model": params.modelId,
|
|
1363
|
+
"gen_ai.prompt.name": params.promptName,
|
|
1364
|
+
"server.address": GEN_AI_SERVER_ADDRESS,
|
|
1365
|
+
"gen_ai.provider.auth_mode": credential.mode,
|
|
1366
|
+
"gen_ai.request.reasoning.level": params.thinkingLevel,
|
|
1367
|
+
"gen_ai.request.max_tokens": maxOutputTokens
|
|
1368
|
+
});
|
|
1369
|
+
} catch (error) {
|
|
1370
|
+
if (NoObjectGeneratedError.isInstance(error)) throw createProviderError(structuredOutputErrorCause(error), {
|
|
1371
|
+
kind: "invalid_response",
|
|
1372
|
+
modelId: params.modelId
|
|
1373
|
+
});
|
|
1374
|
+
throw createProviderError(error, { modelId: params.modelId });
|
|
1375
|
+
}
|
|
1376
|
+
const costUsd = bestEffortObjectCompletionCost(params.modelId, result.usage);
|
|
1377
|
+
return {
|
|
1378
|
+
object: result.object,
|
|
1379
|
+
...costUsd !== void 0 ? { costUsd } : void 0
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
/** Answer typed decision questions with an AI Gateway decision model, such as Jev. */
|
|
1383
|
+
async function completeDecision(params) {
|
|
1384
|
+
const credential = await resolveGatewayCredential();
|
|
1385
|
+
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
1386
|
+
try {
|
|
1387
|
+
const result = await withSpan(`${GEN_AI_OPERATION_DECIDE} ${params.modelId}`, "gen_ai.decide", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
1388
|
+
const result = await experimental_decide({
|
|
1389
|
+
model: provider.decisionModel(params.modelId),
|
|
1390
|
+
state: params.state,
|
|
1391
|
+
questions: params.questions,
|
|
1392
|
+
...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
|
|
1393
|
+
});
|
|
1394
|
+
const costUsd = decisionCostUsd(params.modelId, result.usage.inputTokens);
|
|
1395
|
+
setSpanAttributes(extractGenAiUsageAttributes(result.usage, { cost: {
|
|
1396
|
+
input: costUsd,
|
|
1397
|
+
total: costUsd
|
|
1398
|
+
} }));
|
|
1399
|
+
return {
|
|
1400
|
+
answers: result.answers,
|
|
1401
|
+
costUsd
|
|
1402
|
+
};
|
|
1403
|
+
}, {
|
|
1404
|
+
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
1405
|
+
"gen_ai.operation.name": GEN_AI_OPERATION_DECIDE,
|
|
1406
|
+
"gen_ai.request.model": params.modelId,
|
|
1407
|
+
"gen_ai.prompt.name": params.promptName,
|
|
1408
|
+
"server.address": GEN_AI_SERVER_ADDRESS,
|
|
1409
|
+
"gen_ai.provider.auth_mode": credential.mode
|
|
1410
|
+
});
|
|
1411
|
+
return {
|
|
1412
|
+
answers: result.answers,
|
|
1413
|
+
...result.costUsd !== void 0 ? { costUsd: result.costUsd } : void 0
|
|
1414
|
+
};
|
|
1415
|
+
} catch (error) {
|
|
1416
|
+
throw createProviderError(error, {
|
|
1417
|
+
...Experimental_DecisionRefusalError.isInstance(error) ? { kind: "invalid_response" } : void 0,
|
|
1418
|
+
modelId: params.modelId
|
|
1419
|
+
});
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
/** Map the input type to the provider option for models that embed queries and documents differently. */
|
|
1423
|
+
function embeddingProviderOptions(modelId, inputType) {
|
|
1424
|
+
if (inputType === void 0 || !modelId.startsWith("voyage/")) return;
|
|
1425
|
+
return { voyage: { inputType } };
|
|
1426
|
+
}
|
|
1427
|
+
/** Generate text embeddings through the host-owned AI Gateway provider. */
|
|
1428
|
+
async function embedTexts(params) {
|
|
1429
|
+
const texts = params.texts.map((text) => text.trim());
|
|
1430
|
+
if (texts.length === 0 || texts.some((text) => text.length === 0)) throw new Error("Embedding text is required.");
|
|
1431
|
+
const credential = await resolveGatewayCredential();
|
|
1432
|
+
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
1433
|
+
const providerOptions = embeddingProviderOptions(params.modelId, params.inputType);
|
|
1434
|
+
try {
|
|
1435
|
+
const result = await withSpan(`${GEN_AI_OPERATION_EMBEDDINGS} ${params.modelId}`, "gen_ai.embeddings", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
1436
|
+
const result = await embedMany({
|
|
1437
|
+
model: provider.embeddingModel(params.modelId),
|
|
1438
|
+
values: texts,
|
|
1439
|
+
...providerOptions !== void 0 ? { providerOptions } : void 0,
|
|
1440
|
+
...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
|
|
1441
|
+
});
|
|
1442
|
+
const dimensions = result.embeddings[0]?.length;
|
|
1443
|
+
if (result.embeddings.length !== texts.length || !dimensions || !result.embeddings.every((embedding) => embedding.length === dimensions)) throw createProviderError("Embedding provider returned invalid vectors.", {
|
|
1444
|
+
kind: "invalid_response",
|
|
1445
|
+
modelId: params.modelId
|
|
1446
|
+
});
|
|
1447
|
+
const costUsd = embeddingCostUsd(params.modelId, result.usage.tokens);
|
|
1448
|
+
setSpanAttributes({
|
|
1449
|
+
"gen_ai.embeddings.dimension.count": dimensions,
|
|
1450
|
+
...extractGenAiUsageAttributes({
|
|
1451
|
+
inputTokens: result.usage.tokens,
|
|
1452
|
+
cost: {
|
|
1453
|
+
input: costUsd,
|
|
1454
|
+
total: costUsd
|
|
1455
|
+
}
|
|
1456
|
+
})
|
|
1457
|
+
});
|
|
1458
|
+
return {
|
|
1459
|
+
costUsd,
|
|
1460
|
+
dimensions,
|
|
1461
|
+
result
|
|
1462
|
+
};
|
|
1463
|
+
}, {
|
|
1464
|
+
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
1465
|
+
"gen_ai.operation.name": GEN_AI_OPERATION_EMBEDDINGS,
|
|
1466
|
+
"gen_ai.request.model": params.modelId,
|
|
1467
|
+
"server.address": GEN_AI_SERVER_ADDRESS,
|
|
1468
|
+
"gen_ai.provider.auth_mode": credential.mode
|
|
1469
|
+
});
|
|
1470
|
+
return {
|
|
1471
|
+
...result.costUsd !== void 0 ? { costUsd: result.costUsd } : void 0,
|
|
1472
|
+
dimensions: result.dimensions,
|
|
1473
|
+
model: params.modelId,
|
|
1474
|
+
provider: GEN_AI_PROVIDER_NAME,
|
|
1475
|
+
vectors: result.result.embeddings
|
|
1476
|
+
};
|
|
1477
|
+
} catch (error) {
|
|
1478
|
+
const providerError = createProviderError(error, { modelId: params.modelId });
|
|
1479
|
+
if (isProviderRetryError(providerError)) throw providerError;
|
|
1480
|
+
logException(providerError, "ai.embeddings.failed", {
|
|
1481
|
+
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
1482
|
+
"gen_ai.operation.name": GEN_AI_OPERATION_EMBEDDINGS,
|
|
1483
|
+
"gen_ai.request.model": params.modelId
|
|
1484
|
+
});
|
|
1485
|
+
throw providerError;
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
/** Read the billed cost that AI Gateway reports in provider metadata. */
|
|
1489
|
+
function gatewayCostUsd(providerMetadata) {
|
|
1490
|
+
const cost = providerMetadata?.gateway?.cost;
|
|
1491
|
+
const value = typeof cost === "string" ? Number(cost) : cost;
|
|
1492
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
1493
|
+
}
|
|
1494
|
+
/** Score documents against one query through the host-owned AI Gateway provider. */
|
|
1495
|
+
async function rerankTexts(params) {
|
|
1496
|
+
const query = params.query.trim();
|
|
1497
|
+
if (!query || params.documents.length === 0) throw new Error("Reranking query and documents are required.");
|
|
1498
|
+
const credential = await resolveGatewayCredential();
|
|
1499
|
+
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
1500
|
+
try {
|
|
1501
|
+
return await withSpan(`${GEN_AI_OPERATION_RERANK} ${params.modelId}`, "gen_ai.rerank", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
1502
|
+
const result = await rerank({
|
|
1503
|
+
model: provider.rerankingModel(params.modelId),
|
|
1504
|
+
query,
|
|
1505
|
+
documents: params.documents
|
|
1506
|
+
});
|
|
1507
|
+
const scores = params.documents.map(() => NaN);
|
|
1508
|
+
for (const { originalIndex, score } of result.ranking) scores[originalIndex] = score;
|
|
1509
|
+
if (result.ranking.length !== params.documents.length || !scores.every(Number.isFinite)) throw createProviderError("Reranking provider returned invalid scores.", {
|
|
1510
|
+
kind: "invalid_response",
|
|
1511
|
+
modelId: params.modelId
|
|
1512
|
+
});
|
|
1513
|
+
const costUsd = gatewayCostUsd(result.providerMetadata);
|
|
1514
|
+
setSpanAttributes(extractGenAiUsageAttributes({ cost: { total: costUsd } }));
|
|
1515
|
+
return {
|
|
1516
|
+
...costUsd !== void 0 ? { costUsd } : void 0,
|
|
1517
|
+
scores
|
|
1518
|
+
};
|
|
1519
|
+
}, {
|
|
1520
|
+
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
1521
|
+
"gen_ai.operation.name": GEN_AI_OPERATION_RERANK,
|
|
1522
|
+
"gen_ai.request.model": params.modelId,
|
|
1523
|
+
"server.address": GEN_AI_SERVER_ADDRESS,
|
|
1524
|
+
"gen_ai.provider.auth_mode": credential.mode,
|
|
1525
|
+
"app.rerank.document.count": params.documents.length
|
|
1526
|
+
});
|
|
1527
|
+
} catch (error) {
|
|
1528
|
+
const providerError = createProviderError(error, { modelId: params.modelId });
|
|
1529
|
+
if (isProviderRetryError(providerError)) throw providerError;
|
|
1530
|
+
logException(providerError, "ai.rerank.failed", {
|
|
1531
|
+
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
1532
|
+
"gen_ai.operation.name": GEN_AI_OPERATION_RERANK,
|
|
1533
|
+
"gen_ai.request.model": params.modelId
|
|
1534
|
+
});
|
|
1535
|
+
throw providerError;
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
const WEB_SEARCH_TOOL_NAME = "parallelSearch";
|
|
1539
|
+
/** Run one AI Gateway parallel search inside a `gen_ai.chat` span. */
|
|
1540
|
+
async function searchWeb(params) {
|
|
1541
|
+
const credential = await resolveGatewayCredential();
|
|
1542
|
+
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
1543
|
+
return await withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", {}, async (setSpanAttributes) => {
|
|
1544
|
+
const response = await generateText({
|
|
1545
|
+
model: provider.chat(params.modelId),
|
|
1546
|
+
prompt: params.query,
|
|
1547
|
+
tools: { [WEB_SEARCH_TOOL_NAME]: provider.tools.parallelSearch({
|
|
1548
|
+
mode: "agentic",
|
|
1549
|
+
maxResults: params.maxResults
|
|
1550
|
+
}) },
|
|
1551
|
+
toolChoice: {
|
|
1552
|
+
type: "tool",
|
|
1553
|
+
toolName: WEB_SEARCH_TOOL_NAME
|
|
1554
|
+
},
|
|
1555
|
+
abortSignal: params.signal
|
|
1556
|
+
});
|
|
1557
|
+
const costUsd = gatewayCostUsd(response.providerMetadata);
|
|
1558
|
+
setSpanAttributes({
|
|
1559
|
+
"gen_ai.response.finish_reasons": [response.finishReason],
|
|
1560
|
+
...extractGenAiUsageAttributes(response.usage, { cost: { total: costUsd } })
|
|
1561
|
+
});
|
|
1562
|
+
return {
|
|
1563
|
+
...costUsd !== void 0 ? { costUsd } : void 0,
|
|
1564
|
+
outputs: response.toolResults.filter((result) => result.toolName === WEB_SEARCH_TOOL_NAME).map((result) => result.output)
|
|
1565
|
+
};
|
|
1566
|
+
}, {
|
|
1567
|
+
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
1568
|
+
"gen_ai.operation.name": GEN_AI_OPERATION_CHAT,
|
|
1569
|
+
"gen_ai.request.model": params.modelId,
|
|
1570
|
+
"gen_ai.prompt.name": params.promptName,
|
|
1571
|
+
"server.address": GEN_AI_SERVER_ADDRESS,
|
|
1572
|
+
"gen_ai.provider.auth_mode": credential.mode
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
/** Generate or edit images with an AI Gateway image model. */
|
|
1576
|
+
async function generateImages(params) {
|
|
1577
|
+
const provider = createGatewayProvider({
|
|
1578
|
+
apiKey: await getGatewayApiKey(),
|
|
1579
|
+
...params.fetch ? { fetch: params.fetch } : void 0
|
|
1580
|
+
});
|
|
1581
|
+
try {
|
|
1582
|
+
const result = await generateImage({
|
|
1583
|
+
model: provider.imageModel(params.modelId),
|
|
1584
|
+
prompt: params.prompt,
|
|
1585
|
+
n: 1
|
|
1586
|
+
});
|
|
1587
|
+
const costUsd = gatewayCostUsd(result.providerMetadata);
|
|
1588
|
+
return {
|
|
1589
|
+
...costUsd !== void 0 ? { costUsd } : void 0,
|
|
1590
|
+
images: result.images
|
|
1591
|
+
};
|
|
1592
|
+
} catch (error) {
|
|
1593
|
+
if (NoImageGeneratedError.isInstance(error)) return { images: [] };
|
|
1594
|
+
throw error;
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
// src/chat/reasoning-level.ts
|
|
1598
|
+
const TURN_REASONING_LEVELS = [
|
|
1599
|
+
"none",
|
|
1600
|
+
"low",
|
|
1601
|
+
"medium",
|
|
1602
|
+
"high",
|
|
1603
|
+
"xhigh"
|
|
1604
|
+
];
|
|
1605
|
+
/** Validate a configured main-agent reasoning level. */
|
|
1606
|
+
function parseTurnReasoningLevel(value) {
|
|
1607
|
+
return z.enum(TURN_REASONING_LEVELS).parse(value);
|
|
1608
|
+
}
|
|
1609
|
+
/** Convert a reasoning level into the Pi Agent setting for a main Turn. */
|
|
1610
|
+
function toPiReasoningLevel(level) {
|
|
1611
|
+
return level === "none" ? "off" : level;
|
|
1612
|
+
}
|
|
1613
|
+
// src/config/fields.ts
|
|
1614
|
+
/**
|
|
1615
|
+
* A check that only createApp options reach. Its message names the option,
|
|
1616
|
+
* so it stands alone without a field path or env var.
|
|
1617
|
+
*/
|
|
1618
|
+
function optionCheck(message) {
|
|
1619
|
+
return {
|
|
1620
|
+
message,
|
|
1621
|
+
params: { option: true }
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1624
|
+
/** A positive integer field. */
|
|
1625
|
+
const positiveInt = z.number().int().positive();
|
|
1626
|
+
// src/config/function-duration.ts
|
|
1627
|
+
const DEFAULT_FUNCTION_MAX_DURATION_SECONDS = 300;
|
|
1628
|
+
/** Shortest agent turn timeout. */
|
|
1629
|
+
const MIN_AGENT_TURN_TIMEOUT_MS = 1e4;
|
|
1630
|
+
/** Additional buffer that makes conversation work yield before the hard request deadline. */
|
|
1631
|
+
const CONVERSATION_WORK_SOFT_YIELD_BUFFER_SECONDS = 40;
|
|
1632
|
+
/** Max duration of the Vercel function, in seconds. */
|
|
1633
|
+
const functionMaxDurationSecondsSchema = z.number().default(DEFAULT_FUNCTION_MAX_DURATION_SECONDS);
|
|
1634
|
+
/** Longest agent turn the function duration allows, after the teardown buffer. */
|
|
1635
|
+
function resolveMaxTurnTimeoutMs(functionMaxDurationSeconds) {
|
|
1636
|
+
const budgetSeconds = functionMaxDurationSeconds - 20;
|
|
1637
|
+
return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, budgetSeconds * 1e3);
|
|
1638
|
+
}
|
|
1639
|
+
/** When conversation work yields, so it stops before the request deadline. */
|
|
1640
|
+
function resolveConversationWorkSoftYieldAfterMs(functionMaxDurationSeconds) {
|
|
1641
|
+
return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, (functionMaxDurationSeconds - CONVERSATION_WORK_SOFT_YIELD_BUFFER_SECONDS) * 1e3);
|
|
1642
|
+
}
|
|
1643
|
+
// src/config/bot.ts
|
|
1644
|
+
const DEFAULT_AGENT_TURN_TIMEOUT_MS = 72e4;
|
|
1645
|
+
const MAX_SLICES_PER_TURN = 100;
|
|
1646
|
+
/**
|
|
1647
|
+
* Max model spend in USD for one turn, including later execution slices of
|
|
1648
|
+
* that turn. Sentry span estimates put a child agent that made 250 tool calls
|
|
1649
|
+
* of real work at about $50.
|
|
1650
|
+
*/
|
|
1651
|
+
const MAX_TURN_COST_USD = 100;
|
|
1652
|
+
/**
|
|
1653
|
+
* Max tool calls for one turn, including later execution slices of that turn.
|
|
1654
|
+
* A backstop for models without cost data. The spend limit should stop a turn
|
|
1655
|
+
* first. 250 calls stopped child agents that were still doing real work.
|
|
1656
|
+
*/
|
|
1657
|
+
const MAX_TOOL_CALLS_PER_TURN = 1e3;
|
|
1658
|
+
/**
|
|
1659
|
+
* Max consecutive automated turns before event wakes stop until a user message.
|
|
1660
|
+
* Resource-event CI watches and event-automation loops are the common runaway paths.
|
|
1661
|
+
* Sentry telemetry has no direct instrumentation for how long real automated
|
|
1662
|
+
* chains run (only failure paths on the notice are logged, and those show zero
|
|
1663
|
+
* hits in the last 30d), so this is sized qualitatively: it stays well under
|
|
1664
|
+
* the runaway CI-watch-loop range (hundreds of tool calls) while giving
|
|
1665
|
+
* multi-phase event-automation/scheduled-automation work enough headroom to
|
|
1666
|
+
* avoid pausing on legitimate longer-running automation.
|
|
1667
|
+
*/
|
|
1668
|
+
const MAX_CONSECUTIVE_AUTOMATED_TURNS = 25;
|
|
1669
|
+
/**
|
|
1670
|
+
* Max runs one Event automation can start in one rolling run window. Each run
|
|
1671
|
+
* is a full agent turn, and Event automations skip the consecutive
|
|
1672
|
+
* automated-turn limit. Kept low so a broad trigger, such as every message in
|
|
1673
|
+
* a channel, blocks quickly instead of starting a turn for each Event.
|
|
1674
|
+
*/
|
|
1675
|
+
const MAX_EVENT_AUTOMATION_RUNS = 10;
|
|
1676
|
+
/** Length of the rolling window for the Event automation run limit. */
|
|
1677
|
+
const EVENT_AUTOMATION_RUN_WINDOW_MS = 6e4;
|
|
1678
|
+
const DEFAULT_MODEL_CONTEXT_WINDOW_TOKENS = 4e5;
|
|
1679
|
+
const DEFAULT_ASSISTANT_LOADING_MESSAGES = [
|
|
1680
|
+
"Consulting the orb",
|
|
1681
|
+
"Bribing the gremlins",
|
|
1682
|
+
"Shuffling the papers dramatically",
|
|
1683
|
+
"Summoning the right stack trace",
|
|
1684
|
+
"Negotiating with the mutex",
|
|
1685
|
+
"Poking the internet with a stick",
|
|
1686
|
+
"Asking the docs nicely",
|
|
1687
|
+
"Searching for the least cursed path",
|
|
1688
|
+
"Pretending this was obvious",
|
|
1689
|
+
"Waking up the test suite",
|
|
1690
|
+
"Untangling the spaghetti carefully",
|
|
1691
|
+
"Rattling the command line"
|
|
1692
|
+
];
|
|
1693
|
+
const DEFAULT_MODEL_ID = resolveGatewayModel("anthropic/claude-opus-5.5").id;
|
|
1694
|
+
const DEFAULT_FAST_MODEL_ID = resolveGatewayModel("openai/gpt-6-luna").id;
|
|
1695
|
+
const DEFAULT_GUARDIAN_MODEL_ID = resolveGatewayModel("openai/gpt-6-luna").id;
|
|
1696
|
+
const DEFAULT_WEB_SEARCH_MODEL_ID = resolveGatewayModel("openai/gpt-6-luna").id;
|
|
1697
|
+
const DEFAULT_DECISION_MODEL_ID = "typesafe-ai/jev";
|
|
1698
|
+
const DEFAULT_EMBEDDING_MODEL_ID = "openai/text-embedding-3-small";
|
|
1699
|
+
const DEFAULT_RERANKING_MODEL_ID = "voyage/rerank-2.5-lite";
|
|
1700
|
+
const DEFAULT_IMAGE_GENERATION_MODEL_ID = "openai/gpt-image-2";
|
|
1701
|
+
const DEFAULT_TRANSCRIPTION_MODEL_ID = "elevenlabs/scribe-v2";
|
|
1702
|
+
const DEFAULT_VISION_MODEL_ID = resolveGatewayModel("openai/gpt-5.6-sol").id;
|
|
1703
|
+
function modelId(option) {
|
|
1704
|
+
return z.string().trim().refine((id) => id.length > 0, {
|
|
1705
|
+
...optionCheck(`${option} must not be empty`),
|
|
1706
|
+
abort: true
|
|
1707
|
+
});
|
|
1708
|
+
}
|
|
1709
|
+
function gatewayModelId(option) {
|
|
1710
|
+
return modelId(option).refine((id) => Boolean(resolveGatewayModel(id)));
|
|
1711
|
+
}
|
|
1712
|
+
function positiveLimit(name) {
|
|
1713
|
+
return z.number().refine((value) => Number.isSafeInteger(value) && value > 0, optionCheck(`limits.${name} must be a positive integer`));
|
|
1714
|
+
}
|
|
1715
|
+
/**
|
|
1716
|
+
* Limits from `createApp({ limits })`. `derive` applies them over the bot
|
|
1717
|
+
* settings, so they win over env, and the turn timeout is only capped by the
|
|
1718
|
+
* function duration.
|
|
1719
|
+
*/
|
|
1720
|
+
const limitsSchema = z.strictObject({
|
|
1721
|
+
contextWindowTokens: positiveLimit("contextWindowTokens").optional(),
|
|
1722
|
+
maxAgentDepth: z.number().refine((value) => Number.isSafeInteger(value) && value >= 0, optionCheck("limits.maxAgentDepth must be a non-negative integer")).optional(),
|
|
1723
|
+
maxConsecutiveAutomatedTurns: positiveLimit("maxConsecutiveAutomatedTurns").optional(),
|
|
1724
|
+
eventAutomationRunLimit: z.strictObject({
|
|
1725
|
+
maxRuns: positiveLimit("eventAutomationRunLimit.maxRuns").optional(),
|
|
1726
|
+
windowMs: positiveLimit("eventAutomationRunLimit.windowMs").optional()
|
|
1727
|
+
}).optional(),
|
|
1728
|
+
maxSlicesPerTurn: positiveLimit("maxSlicesPerTurn").optional(),
|
|
1729
|
+
maxToolCallsPerTurn: positiveLimit("maxToolCallsPerTurn").optional(),
|
|
1730
|
+
maxTurnCostUsd: positiveLimit("maxTurnCostUsd").optional(),
|
|
1731
|
+
turnTimeoutMs: positiveLimit("turnTimeoutMs").optional()
|
|
1732
|
+
});
|
|
1733
|
+
/** Models, the bot name, and per-turn limits. */
|
|
1734
|
+
const botSchema = z.strictObject({
|
|
1735
|
+
modelId: gatewayModelId("modelId").default(DEFAULT_MODEL_ID),
|
|
1736
|
+
fastModelId: gatewayModelId("fastModelId").default(DEFAULT_FAST_MODEL_ID),
|
|
1737
|
+
guardianModelId: gatewayModelId("guardianModelId").default(DEFAULT_GUARDIAN_MODEL_ID),
|
|
1738
|
+
webSearchModelId: gatewayModelId("webSearchModelId").default(DEFAULT_WEB_SEARCH_MODEL_ID),
|
|
1739
|
+
refusalFallbackModelId: gatewayModelId("refusalFallbackModelId").optional(),
|
|
1740
|
+
visionModelId: gatewayModelId("visionModelId").nullable().default(DEFAULT_VISION_MODEL_ID),
|
|
1741
|
+
decisionModelId: modelId("decisionModelId").default(DEFAULT_DECISION_MODEL_ID),
|
|
1742
|
+
embeddingModelId: modelId("embeddingModelId").default(DEFAULT_EMBEDDING_MODEL_ID),
|
|
1743
|
+
rerankingModelId: modelId("rerankingModelId").default(DEFAULT_RERANKING_MODEL_ID),
|
|
1744
|
+
imageGenerationModelId: modelId("imageGenerationModelId").default(DEFAULT_IMAGE_GENERATION_MODEL_ID),
|
|
1745
|
+
transcriptionModelId: modelId("transcriptionModelId").default(DEFAULT_TRANSCRIPTION_MODEL_ID),
|
|
1746
|
+
userName: z.string().trim().refine((name) => name.length > 0, optionCheck("botName must not be empty")).default("junior"),
|
|
1747
|
+
contextWindowTokens: positiveInt.default(DEFAULT_MODEL_CONTEXT_WINDOW_TOKENS),
|
|
1748
|
+
reasoningLevel: z.enum(TURN_REASONING_LEVELS).default("high"),
|
|
1749
|
+
loadingMessages: z.array(z.string()).default(() => [...DEFAULT_ASSISTANT_LOADING_MESSAGES]),
|
|
1750
|
+
maxAgentDepth: z.number().int().nonnegative().default(1),
|
|
1751
|
+
maxSlicesPerTurn: positiveInt.default(MAX_SLICES_PER_TURN),
|
|
1752
|
+
maxToolCallsPerTurn: positiveInt.default(MAX_TOOL_CALLS_PER_TURN),
|
|
1753
|
+
maxTurnCostUsd: positiveInt.default(MAX_TURN_COST_USD),
|
|
1754
|
+
maxConsecutiveAutomatedTurns: positiveInt.default(MAX_CONSECUTIVE_AUTOMATED_TURNS),
|
|
1755
|
+
maxEventAutomationRuns: positiveInt.default(MAX_EVENT_AUTOMATION_RUNS),
|
|
1756
|
+
eventAutomationRunWindowMs: positiveInt.default(EVENT_AUTOMATION_RUN_WINDOW_MS),
|
|
1757
|
+
turnTimeoutMs: z.number().int().optional()
|
|
1758
|
+
});
|
|
1759
|
+
/** Env var that sets each bot field, for error messages. */
|
|
1760
|
+
const botEnvNames = {
|
|
1761
|
+
"bot.modelId": "AI_MODEL",
|
|
1762
|
+
"bot.fastModelId": "AI_FAST_MODEL",
|
|
1763
|
+
"bot.guardianModelId": "AI_GUARDIAN_MODEL",
|
|
1764
|
+
"bot.webSearchModelId": "AI_WEB_SEARCH_MODEL",
|
|
1765
|
+
"bot.refusalFallbackModelId": "AI_REFUSAL_FALLBACK_MODEL",
|
|
1766
|
+
"bot.visionModelId": "AI_VISION_MODEL",
|
|
1767
|
+
"bot.decisionModelId": "AI_DECISION_MODEL",
|
|
1768
|
+
"bot.embeddingModelId": "AI_EMBEDDING_MODEL",
|
|
1769
|
+
"bot.rerankingModelId": "AI_RERANKING_MODEL",
|
|
1770
|
+
"bot.imageGenerationModelId": "AI_IMAGE_MODEL",
|
|
1771
|
+
"bot.transcriptionModelId": "AI_TRANSCRIPTION_MODEL",
|
|
1772
|
+
"bot.userName": "JUNIOR_BOT_NAME",
|
|
1773
|
+
"bot.contextWindowTokens": "AI_MODEL_CONTEXT_WINDOW_TOKENS",
|
|
1774
|
+
"bot.reasoningLevel": "AI_REASONING_LEVEL",
|
|
1775
|
+
"bot.loadingMessages": "JUNIOR_LOADING_MESSAGES",
|
|
1776
|
+
"bot.turnTimeoutMs": "AGENT_TURN_TIMEOUT_MS"
|
|
1777
|
+
};
|
|
1778
|
+
function parseLoadingMessages(rawValue) {
|
|
1779
|
+
const trimmed = rawValue?.trim();
|
|
1780
|
+
if (!trimmed) return;
|
|
1781
|
+
let parsed;
|
|
1782
|
+
try {
|
|
1783
|
+
parsed = JSON.parse(trimmed);
|
|
1784
|
+
} catch {
|
|
1785
|
+
throw new Error("JUNIOR_LOADING_MESSAGES must be a JSON array of strings");
|
|
1786
|
+
}
|
|
1787
|
+
if (!Array.isArray(parsed)) throw new Error("JUNIOR_LOADING_MESSAGES must be a JSON array of strings");
|
|
1788
|
+
return parsed.map((value, index) => {
|
|
1789
|
+
if (typeof value !== "string") throw new Error(`JUNIOR_LOADING_MESSAGES[${index}] must be a string`);
|
|
1790
|
+
return value.trim();
|
|
1791
|
+
});
|
|
1792
|
+
}
|
|
1793
|
+
function parseOptionalPositiveInteger(envName, rawValue) {
|
|
1794
|
+
const trimmed = toOptionalTrimmed(rawValue);
|
|
1795
|
+
if (trimmed === void 0) return;
|
|
1796
|
+
const value = Number.parseInt(trimmed, 10);
|
|
1797
|
+
if (!Number.isSafeInteger(value) || value <= 0 || String(value) !== trimmed) throw new Error(`${envName} must be a positive integer`);
|
|
1798
|
+
return value;
|
|
1799
|
+
}
|
|
1800
|
+
function parseTurnTimeoutMs(rawValue) {
|
|
1801
|
+
const value = Number.parseInt(rawValue ?? "", 10);
|
|
1802
|
+
return Number.isNaN(value) ? void 0 : value;
|
|
1803
|
+
}
|
|
1804
|
+
function parseVisionModelId(rawValue) {
|
|
1805
|
+
if (rawValue === void 0) return;
|
|
1806
|
+
return toOptionalTrimmed(rawValue) ?? null;
|
|
1807
|
+
}
|
|
1808
|
+
/** Read the bot group from env. */
|
|
1809
|
+
function readBotEnv(env) {
|
|
1810
|
+
const reasoningLevel = toOptionalTrimmed(env["AI_REASONING_LEVEL"]);
|
|
1811
|
+
return {
|
|
1812
|
+
modelId: toOptionalTrimmed(env["AI_MODEL"]),
|
|
1813
|
+
fastModelId: toOptionalTrimmed(env["AI_FAST_MODEL"] ?? env["AI_MODEL"]),
|
|
1814
|
+
guardianModelId: toOptionalTrimmed(env["AI_GUARDIAN_MODEL"]),
|
|
1815
|
+
webSearchModelId: toOptionalTrimmed(env["AI_WEB_SEARCH_MODEL"]),
|
|
1816
|
+
refusalFallbackModelId: toOptionalTrimmed(env["AI_REFUSAL_FALLBACK_MODEL"]),
|
|
1817
|
+
visionModelId: parseVisionModelId(env["AI_VISION_MODEL"]),
|
|
1818
|
+
decisionModelId: toOptionalTrimmed(env["AI_DECISION_MODEL"]),
|
|
1819
|
+
embeddingModelId: toOptionalTrimmed(env["AI_EMBEDDING_MODEL"]),
|
|
1820
|
+
rerankingModelId: toOptionalTrimmed(env["AI_RERANKING_MODEL"]),
|
|
1821
|
+
imageGenerationModelId: toOptionalTrimmed(env["AI_IMAGE_MODEL"]),
|
|
1822
|
+
transcriptionModelId: toOptionalTrimmed(env["AI_TRANSCRIPTION_MODEL"]),
|
|
1823
|
+
userName: toOptionalTrimmed(env["JUNIOR_BOT_NAME"]),
|
|
1824
|
+
contextWindowTokens: parseOptionalPositiveInteger("AI_MODEL_CONTEXT_WINDOW_TOKENS", env["AI_MODEL_CONTEXT_WINDOW_TOKENS"]),
|
|
1825
|
+
reasoningLevel: reasoningLevel === void 0 ? void 0 : parseTurnReasoningLevel(reasoningLevel),
|
|
1826
|
+
loadingMessages: parseLoadingMessages(env["JUNIOR_LOADING_MESSAGES"]),
|
|
1827
|
+
turnTimeoutMs: parseTurnTimeoutMs(env["AGENT_TURN_TIMEOUT_MS"])
|
|
1828
|
+
};
|
|
1829
|
+
}
|
|
1830
|
+
/**
|
|
1831
|
+
* Apply the createApp limits over the bot settings, and cap the turn timeout
|
|
1832
|
+
* at the function duration.
|
|
1833
|
+
*/
|
|
1834
|
+
function deriveBot(bot, limits, functionMaxDurationSeconds) {
|
|
1835
|
+
const maxTurnTimeoutMs = resolveMaxTurnTimeoutMs(functionMaxDurationSeconds);
|
|
1836
|
+
return {
|
|
1837
|
+
...bot,
|
|
1838
|
+
contextWindowTokens: limits.contextWindowTokens ?? bot.contextWindowTokens,
|
|
1839
|
+
maxAgentDepth: limits.maxAgentDepth ?? bot.maxAgentDepth,
|
|
1840
|
+
maxConsecutiveAutomatedTurns: limits.maxConsecutiveAutomatedTurns ?? bot.maxConsecutiveAutomatedTurns,
|
|
1841
|
+
maxEventAutomationRuns: limits.eventAutomationRunLimit?.maxRuns ?? bot.maxEventAutomationRuns,
|
|
1842
|
+
eventAutomationRunWindowMs: limits.eventAutomationRunLimit?.windowMs ?? bot.eventAutomationRunWindowMs,
|
|
1843
|
+
maxSlicesPerTurn: limits.maxSlicesPerTurn ?? bot.maxSlicesPerTurn,
|
|
1844
|
+
maxToolCallsPerTurn: limits.maxToolCallsPerTurn ?? bot.maxToolCallsPerTurn,
|
|
1845
|
+
maxTurnCostUsd: limits.maxTurnCostUsd ?? bot.maxTurnCostUsd,
|
|
1846
|
+
turnTimeoutMs: limits.turnTimeoutMs === void 0 ? Math.max(MIN_AGENT_TURN_TIMEOUT_MS, Math.min(bot.turnTimeoutMs ?? DEFAULT_AGENT_TURN_TIMEOUT_MS, maxTurnTimeoutMs)) : Math.min(limits.turnTimeoutMs, maxTurnTimeoutMs),
|
|
1847
|
+
visionModelId: bot.visionModelId ?? void 0
|
|
1848
|
+
};
|
|
1849
|
+
}
|
|
1850
|
+
// src/config/deployment.ts
|
|
1851
|
+
/** The public base URL and the Vercel deployment that runs this process. */
|
|
1852
|
+
const deploymentSchema = z.strictObject({
|
|
1853
|
+
/** Public base URL that the host sets: `dashboard.baseURL` or `JUNIOR_BASE_URL`. */
|
|
1854
|
+
configuredBaseUrl: z.string().optional(),
|
|
1855
|
+
/** Git commit of this deployment. */
|
|
1856
|
+
commitSha: z.string().optional(),
|
|
1857
|
+
/** Vercel deployment that runs this process. Unset outside Vercel. */
|
|
1858
|
+
id: z.string().optional(),
|
|
1859
|
+
/** Vercel hostnames, for the base URL when none is configured. */
|
|
1860
|
+
vercelProductionUrl: z.string().optional(),
|
|
1861
|
+
vercelUrl: z.string().optional()
|
|
1862
|
+
}).prefault({});
|
|
1863
|
+
function withHttps(host) {
|
|
1864
|
+
return host.startsWith("https://") || host.startsWith("http://") ? host : `https://${host}`;
|
|
1865
|
+
}
|
|
1866
|
+
/** Read the deployment group from env. */
|
|
1867
|
+
function readDeploymentEnv(env) {
|
|
1868
|
+
return {
|
|
1869
|
+
configuredBaseUrl: toOptionalTrimmed(env["JUNIOR_BASE_URL"]),
|
|
1870
|
+
commitSha: toOptionalTrimmed(env["VERCEL_GIT_COMMIT_SHA"]),
|
|
1871
|
+
id: toOptionalTrimmed(env["VERCEL_DEPLOYMENT_ID"]),
|
|
1872
|
+
vercelProductionUrl: toOptionalTrimmed(env["VERCEL_PROJECT_PRODUCTION_URL"]),
|
|
1873
|
+
vercelUrl: toOptionalTrimmed(env["VERCEL_URL"])
|
|
1874
|
+
};
|
|
1875
|
+
}
|
|
1876
|
+
/** Resolve the public base URL: the configured one, else the Vercel URL. */
|
|
1877
|
+
function deriveDeployment(deployment) {
|
|
1878
|
+
const vercelUrl = deployment.vercelProductionUrl ?? deployment.vercelUrl;
|
|
1879
|
+
return {
|
|
1880
|
+
/** Public base URL: the configured one, else the Vercel URL. */
|
|
1881
|
+
baseUrl: deployment.configuredBaseUrl ?? (vercelUrl ? withHttps(vercelUrl) : void 0),
|
|
1882
|
+
configuredBaseUrl: deployment.configuredBaseUrl,
|
|
1883
|
+
commitSha: deployment.commitSha,
|
|
1884
|
+
id: deployment.id
|
|
1885
|
+
};
|
|
1886
|
+
}
|
|
1887
|
+
// src/config/encryption.ts
|
|
1888
|
+
const ENCRYPTION_KEY_BYTES = 32;
|
|
1889
|
+
const ENCRYPTION_KEY_ID_PATTERN = /^[A-Za-z0-9._-]{1,32}$/;
|
|
1890
|
+
const ENCRYPTION_KEY_MATERIAL_PATTERN = /^[A-Za-z0-9+/_-]+={0,2}$/;
|
|
1891
|
+
/** How to generate a key, for the missing-keys error. */
|
|
1892
|
+
const ENCRYPTION_KEYS_HINT = "Generate a key with: node -e \"console.log('k1:' + require('node:crypto').randomBytes(32).toString('base64url'))\"";
|
|
1893
|
+
function isEncryptionKeyMaterial(material) {
|
|
1894
|
+
return ENCRYPTION_KEY_MATERIAL_PATTERN.test(material) && Buffer.from(material, "base64").length === ENCRYPTION_KEY_BYTES;
|
|
1895
|
+
}
|
|
1896
|
+
/**
|
|
1897
|
+
* Keys for secrets at rest, as plain data. `createEncryptionKeyring` builds
|
|
1898
|
+
* the keyring. Startup fails when they are missing or invalid.
|
|
1899
|
+
*/
|
|
1900
|
+
const encryptionSchema = z.strictObject({
|
|
1901
|
+
/** Key for new values. */
|
|
1902
|
+
activeKeyId: z.string(),
|
|
1903
|
+
/** Every key that decrypts, as base64 key material. */
|
|
1904
|
+
keys: z.array(z.strictObject({
|
|
1905
|
+
id: z.string().regex(ENCRYPTION_KEY_ID_PATTERN),
|
|
1906
|
+
key: z.string().refine(isEncryptionKeyMaterial, `must be ${ENCRYPTION_KEY_BYTES} bytes in base64`)
|
|
1907
|
+
})).min(1)
|
|
1908
|
+
}).refine(({ keys }) => new Set(keys.map(({ id }) => id)).size === keys.length, {
|
|
1909
|
+
message: "must not repeat a key id",
|
|
1910
|
+
path: ["keys"]
|
|
1911
|
+
}).refine(({ activeKeyId, keys }) => keys.some(({ id }) => id === activeKeyId), {
|
|
1912
|
+
message: "must name a listed key",
|
|
1913
|
+
path: ["activeKeyId"]
|
|
1914
|
+
});
|
|
1915
|
+
/** Env var that sets each encryption field, for error messages. */
|
|
1916
|
+
const encryptionEnvNames = {
|
|
1917
|
+
encryption: "JUNIOR_ENCRYPTION_KEYS",
|
|
1918
|
+
"encryption.activeKeyId": "JUNIOR_ENCRYPTION_KEY_ID"
|
|
1919
|
+
};
|
|
1920
|
+
function parseEncryptionKey(entry, index) {
|
|
1921
|
+
const separator = entry.indexOf(":");
|
|
1922
|
+
const id = entry.slice(0, separator).trim();
|
|
1923
|
+
const key = entry.slice(separator + 1).trim();
|
|
1924
|
+
if (separator < 0 || !ENCRYPTION_KEY_ID_PATTERN.test(id)) throw new Error(`JUNIOR_ENCRYPTION_KEYS entry ${index + 1} must be <id>:<key> with an id of letters, digits, ".", "_", or "-"`);
|
|
1925
|
+
if (!isEncryptionKeyMaterial(key)) throw new Error(`JUNIOR_ENCRYPTION_KEYS key "${id}" must be ${ENCRYPTION_KEY_BYTES} bytes in base64`);
|
|
1926
|
+
return {
|
|
1927
|
+
id,
|
|
1928
|
+
key
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
/**
|
|
1932
|
+
* `JUNIOR_ENCRYPTION_KEYS` lists `<id>:<key>` entries, comma-separated.
|
|
1933
|
+
* `JUNIOR_ENCRYPTION_KEY_ID` names the key for new values; it is optional
|
|
1934
|
+
* when there is one key. All listed keys decrypt.
|
|
1935
|
+
*/
|
|
1936
|
+
function readEncryption(env) {
|
|
1937
|
+
const entries = (env["JUNIOR_ENCRYPTION_KEYS"] ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
1938
|
+
if (entries.length === 0) return;
|
|
1939
|
+
const keys = entries.map(parseEncryptionKey);
|
|
1940
|
+
if (new Set(keys.map(({ id }) => id)).size !== keys.length) throw new Error("JUNIOR_ENCRYPTION_KEYS must not repeat a key id");
|
|
1941
|
+
const activeKeyId = env["JUNIOR_ENCRYPTION_KEY_ID"]?.trim() || (keys.length === 1 ? keys[0]?.id : void 0);
|
|
1942
|
+
if (!activeKeyId) throw new Error("JUNIOR_ENCRYPTION_KEY_ID is required when JUNIOR_ENCRYPTION_KEYS has more than one key");
|
|
1943
|
+
if (!keys.some(({ id }) => id === activeKeyId)) throw new Error(`JUNIOR_ENCRYPTION_KEY_ID "${activeKeyId}" is not in JUNIOR_ENCRYPTION_KEYS`);
|
|
1944
|
+
return {
|
|
1945
|
+
activeKeyId,
|
|
1946
|
+
keys
|
|
1947
|
+
};
|
|
1948
|
+
}
|
|
1949
|
+
// src/config/kill-switches.ts
|
|
1950
|
+
/** Kill switch fields at the top level of the config. */
|
|
1951
|
+
const killSwitchFields = {
|
|
1952
|
+
/** Kill switch for prompt cache warming. Defaults to true. */
|
|
1953
|
+
cacheWarmingEnabled: z.boolean().default(true),
|
|
1954
|
+
/**
|
|
1955
|
+
* Kill switch for compaction on idle: a warmup of a prefix at or above the
|
|
1956
|
+
* background compaction mark swaps in a ready background summary instead.
|
|
1957
|
+
* Defaults to true. It runs only while cache warming is on.
|
|
1958
|
+
*/
|
|
1959
|
+
idleCompactionEnabled: z.boolean().default(true),
|
|
1960
|
+
conversationWorkEnabled: z.boolean().default(true)
|
|
1961
|
+
};
|
|
1962
|
+
/** Env var that sets each kill switch, for error messages. */
|
|
1963
|
+
const killSwitchEnvNames = {
|
|
1964
|
+
cacheWarmingEnabled: "JUNIOR_CACHE_WARMING_ENABLED",
|
|
1965
|
+
idleCompactionEnabled: "JUNIOR_IDLE_COMPACTION_ENABLED",
|
|
1966
|
+
conversationWorkEnabled: "JUNIOR_CONVERSATION_WORK_ENABLED"
|
|
1967
|
+
};
|
|
1968
|
+
function parseKillSwitch(name, rawValue) {
|
|
1969
|
+
const value = toOptionalTrimmed(rawValue)?.toLowerCase();
|
|
1970
|
+
if (value === void 0 || value === "true") return true;
|
|
1971
|
+
if (value === "false") return false;
|
|
1972
|
+
throw new Error(`${name} must be true or false`);
|
|
1973
|
+
}
|
|
1974
|
+
/** Read the kill switches from env. */
|
|
1975
|
+
function readKillSwitchesEnv(env) {
|
|
1976
|
+
return {
|
|
1977
|
+
cacheWarmingEnabled: parseKillSwitch("JUNIOR_CACHE_WARMING_ENABLED", env["JUNIOR_CACHE_WARMING_ENABLED"]),
|
|
1978
|
+
idleCompactionEnabled: parseKillSwitch("JUNIOR_IDLE_COMPACTION_ENABLED", env["JUNIOR_IDLE_COMPACTION_ENABLED"]),
|
|
1979
|
+
conversationWorkEnabled: parseKillSwitch("JUNIOR_CONVERSATION_WORK_ENABLED", env["JUNIOR_CONVERSATION_WORK_ENABLED"])
|
|
1980
|
+
};
|
|
1981
|
+
}
|
|
1982
|
+
// src/config/queue.ts
|
|
1983
|
+
function isHttpUrl(value) {
|
|
1984
|
+
const protocol = URL.parse(value)?.protocol;
|
|
1985
|
+
return protocol === "http:" || protocol === "https:";
|
|
1986
|
+
}
|
|
1987
|
+
/** Vercel Queues settings. */
|
|
1988
|
+
const queueSchema = z.strictObject({
|
|
1989
|
+
/** Vercel Queues API base URL, for a local queue server. */
|
|
1990
|
+
apiUrl: z.string().refine(isHttpUrl, "must be an http or https URL").optional() }).prefault({});
|
|
1991
|
+
/** Env var that sets each queue field, for error messages. */
|
|
1992
|
+
const queueEnvNames = { "queue.apiUrl": "JUNIOR_QUEUE_API_URL" };
|
|
1993
|
+
function parseQueueApiUrl(rawValue) {
|
|
1994
|
+
const value = toOptionalTrimmed(rawValue);
|
|
1995
|
+
if (value === void 0 || isHttpUrl(value)) return value;
|
|
1996
|
+
throw new Error("JUNIOR_QUEUE_API_URL must be an http or https URL");
|
|
1997
|
+
}
|
|
1998
|
+
/** Read the queue group from env. */
|
|
1999
|
+
function readQueueEnv(env) {
|
|
2000
|
+
return { apiUrl: parseQueueApiUrl(env["JUNIOR_QUEUE_API_URL"]) };
|
|
2001
|
+
}
|
|
2002
|
+
// src/config/sandbox.ts
|
|
2003
|
+
const DEFAULT_SNAPSHOT_FLOATING_MAX_AGE_MS = 6048e5;
|
|
2004
|
+
/** The sandbox provider and its settings. */
|
|
2005
|
+
const sandboxSchema = z.strictObject({
|
|
2006
|
+
/** Sandbox provider for this deployment. `docker` is for local development. */
|
|
2007
|
+
provider: z.enum(["vercel", "docker"]).default("vercel"),
|
|
2008
|
+
/**
|
|
2009
|
+
* vCPUs of each sandbox. A Workspace vCPU count wins over it. Env only
|
|
2010
|
+
* sets valid values, so the check reaches only `createApp({ sandbox })`.
|
|
2011
|
+
*/
|
|
2012
|
+
vcpus: z.custom((value) => Number.isSafeInteger(value) && Number(value) > 0, optionCheck("sandbox.vcpus must be a positive integer")).optional(),
|
|
2013
|
+
/** Sandbox keepalive in ms. 0 turns it off. */
|
|
2014
|
+
keepAliveMs: z.number().default(0),
|
|
2015
|
+
/** Settings of the local Docker provider. */
|
|
2016
|
+
docker: z.strictObject({
|
|
2017
|
+
/** `DOCKER_HOST`. The provider accepts only `unix://` sockets. */
|
|
2018
|
+
host: z.string().optional(),
|
|
2019
|
+
/** Directory for machine-wide provider files, such as the egress CA key. */
|
|
2020
|
+
dir: z.string().optional(),
|
|
2021
|
+
/** PEM file with more CA certificates for each sandbox to trust. */
|
|
2022
|
+
extraCaCertsFile: z.string().optional()
|
|
2023
|
+
}).prefault({}),
|
|
2024
|
+
/**
|
|
2025
|
+
* Explicit Vercel Sandbox credentials. Junior uses them only when all
|
|
2026
|
+
* three are set; otherwise the SDK reads ambient Vercel auth.
|
|
2027
|
+
*/
|
|
2028
|
+
vercel: z.strictObject({
|
|
2029
|
+
token: z.string().optional(),
|
|
2030
|
+
teamId: z.string().optional(),
|
|
2031
|
+
projectId: z.string().optional()
|
|
2032
|
+
}).prefault({}),
|
|
2033
|
+
snapshot: z.strictObject({
|
|
2034
|
+
/** Age in ms after which a snapshot with floating inputs is rebuilt. */
|
|
2035
|
+
floatingMaxAgeMs: z.number().default(DEFAULT_SNAPSHOT_FLOATING_MAX_AGE_MS),
|
|
2036
|
+
/** Changing this value rebuilds every snapshot. */
|
|
2037
|
+
rebuildEpoch: z.string().default("")
|
|
2038
|
+
}).prefault({})
|
|
2039
|
+
}).prefault({});
|
|
2040
|
+
/** Env var that sets each sandbox field, for error messages. */
|
|
2041
|
+
const sandboxEnvNames = { "sandbox.provider": "JUNIOR_SANDBOX_PROVIDER" };
|
|
2042
|
+
function parseVcpus(rawValue) {
|
|
2043
|
+
const value = rawValue?.trim();
|
|
2044
|
+
if (!value || !/^\d+$/.test(value)) return;
|
|
2045
|
+
const vcpus = Number(value);
|
|
2046
|
+
return Number.isSafeInteger(vcpus) && vcpus > 0 ? vcpus : void 0;
|
|
2047
|
+
}
|
|
2048
|
+
function parseKeepAliveMs(rawValue) {
|
|
2049
|
+
const parsed = Number.parseInt(rawValue ?? "0", 10);
|
|
2050
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
|
|
2051
|
+
}
|
|
2052
|
+
function parseFloatingMaxAgeMs(rawValue) {
|
|
2053
|
+
if (!rawValue?.trim()) return DEFAULT_SNAPSHOT_FLOATING_MAX_AGE_MS;
|
|
2054
|
+
const parsed = Number.parseInt(rawValue, 10);
|
|
2055
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_SNAPSHOT_FLOATING_MAX_AGE_MS;
|
|
2056
|
+
}
|
|
2057
|
+
/** Read the sandbox group from env. */
|
|
2058
|
+
function readSandboxEnv(env) {
|
|
2059
|
+
return {
|
|
2060
|
+
provider: env["JUNIOR_SANDBOX_PROVIDER"]?.trim().toLowerCase() === "docker" ? "docker" : void 0,
|
|
2061
|
+
vcpus: parseVcpus(env["SANDBOX_VCPUS"]),
|
|
2062
|
+
keepAliveMs: parseKeepAliveMs(env["VERCEL_SANDBOX_KEEPALIVE_MS"]),
|
|
2063
|
+
docker: {
|
|
2064
|
+
host: env["DOCKER_HOST"]?.trim() || void 0,
|
|
2065
|
+
dir: env["JUNIOR_DOCKER_SANDBOX_DIR"]?.trim() || void 0,
|
|
2066
|
+
extraCaCertsFile: env["JUNIOR_DOCKER_SANDBOX_EXTRA_CA_CERTS"]?.trim() || void 0
|
|
2067
|
+
},
|
|
2068
|
+
vercel: {
|
|
2069
|
+
token: toOptionalTrimmed(env["VERCEL_TOKEN"]),
|
|
2070
|
+
teamId: toOptionalTrimmed(env["VERCEL_TEAM_ID"]),
|
|
2071
|
+
projectId: toOptionalTrimmed(env["VERCEL_PROJECT_ID"])
|
|
2072
|
+
},
|
|
2073
|
+
snapshot: {
|
|
2074
|
+
floatingMaxAgeMs: parseFloatingMaxAgeMs(env["SANDBOX_SNAPSHOT_FLOATING_MAX_AGE_MS"]),
|
|
2075
|
+
rebuildEpoch: env["SANDBOX_SNAPSHOT_REBUILD_EPOCH"]?.trim() ?? ""
|
|
2076
|
+
}
|
|
2077
|
+
};
|
|
2078
|
+
}
|
|
2079
|
+
// src/config/secrets.ts
|
|
2080
|
+
/** Secrets that sign internal tokens and authenticate cron requests. */
|
|
2081
|
+
const secretsSchema = z.strictObject({
|
|
2082
|
+
/** Signs internal tokens and payloads. */
|
|
2083
|
+
juniorSecret: z.string().optional(),
|
|
2084
|
+
/** Bearer secret that internal cron requests must send. */
|
|
2085
|
+
schedulerSecret: z.string().optional()
|
|
2086
|
+
}).prefault({});
|
|
2087
|
+
/** Read the secrets group from env. */
|
|
2088
|
+
function readSecretsEnv(env) {
|
|
2089
|
+
return {
|
|
2090
|
+
juniorSecret: env["JUNIOR_SECRET"]?.trim() || void 0,
|
|
2091
|
+
schedulerSecret: env["JUNIOR_SCHEDULER_SECRET"]?.trim() || env["CRON_SECRET"]?.trim()
|
|
2092
|
+
};
|
|
2093
|
+
}
|
|
2094
|
+
// src/config/sign-in.ts
|
|
2095
|
+
/** Dashboard Google sign-in, and the domains that may use Junior. */
|
|
2096
|
+
const signInSchema = z.strictObject({
|
|
2097
|
+
/**
|
|
2098
|
+
* `JUNIOR_ALLOWED_DOMAINS` as set. `chat/sign-in/allowlist` parses it
|
|
2099
|
+
* when `createApp` resolves the allowed domains.
|
|
2100
|
+
*/
|
|
2101
|
+
allowedDomains: z.string().optional(),
|
|
2102
|
+
/** Whether the dashboard requires sign-in when `dashboard.authRequired` is unset. */
|
|
2103
|
+
dashboardAuthRequired: z.boolean().default(true),
|
|
2104
|
+
googleClientId: z.string().optional(),
|
|
2105
|
+
googleClientSecret: z.string().optional(),
|
|
2106
|
+
/** Dashboard session secret, as given. */
|
|
2107
|
+
secret: z.string().optional(),
|
|
2108
|
+
/**
|
|
2109
|
+
* `JUNIOR_DASHBOARD_TRUSTED_ORIGINS` as set. Sign-in parses it when the
|
|
2110
|
+
* dashboard does not set `trustedOrigins`.
|
|
2111
|
+
*/
|
|
2112
|
+
trustedOrigins: z.string().optional()
|
|
2113
|
+
}).prefault({});
|
|
2114
|
+
/** Read the sign-in group from env. */
|
|
2115
|
+
function readSignInEnv(env) {
|
|
2116
|
+
if (env["JUNIOR_DASHBOARD_GOOGLE_DOMAINS"]?.trim()) throw new Error("JUNIOR_DASHBOARD_GOOGLE_DOMAINS was removed; set JUNIOR_ALLOWED_DOMAINS instead");
|
|
2117
|
+
return {
|
|
2118
|
+
allowedDomains: env["JUNIOR_ALLOWED_DOMAINS"],
|
|
2119
|
+
dashboardAuthRequired: env["JUNIOR_DASHBOARD_AUTH_REQUIRED"]?.trim() !== "false",
|
|
2120
|
+
googleClientId: env["GOOGLE_CLIENT_ID"],
|
|
2121
|
+
googleClientSecret: env["GOOGLE_CLIENT_SECRET"],
|
|
2122
|
+
secret: env["BETTER_AUTH_SECRET"] ?? env["JUNIOR_SECRET"],
|
|
2123
|
+
trustedOrigins: env["JUNIOR_DASHBOARD_TRUSTED_ORIGINS"]
|
|
2124
|
+
};
|
|
2125
|
+
}
|
|
2126
|
+
// src/chat/slack/emoji.ts
|
|
2127
|
+
const SLACK_EMOJI_NAME_RE = /^(?:[a-z0-9_+-]+)(?:::(?:skin-tone-[2-6]))?$/;
|
|
2128
|
+
function normalizeSlackEmojiName(value) {
|
|
2129
|
+
const trimmed = value.trim().toLowerCase();
|
|
2130
|
+
if (!trimmed) return null;
|
|
2131
|
+
const normalized = trimmed.startsWith(":") && trimmed.endsWith(":") ? trimmed.slice(1, -1) : trimmed;
|
|
2132
|
+
return SLACK_EMOJI_NAME_RE.test(normalized) ? normalized : null;
|
|
2133
|
+
}
|
|
2134
|
+
// src/config/slack.ts
|
|
2135
|
+
const DEFAULT_PROCESSING_REACTION_EMOJI = "eyes";
|
|
2136
|
+
const DEFAULT_COMPLETED_REACTION_EMOJI = "white_check_mark";
|
|
2137
|
+
function reactionEmoji(option, defaultEmoji) {
|
|
2138
|
+
return z.string().transform((value, ctx) => {
|
|
2139
|
+
if (!value.trim()) return defaultEmoji;
|
|
2140
|
+
const normalized = normalizeSlackEmojiName(value);
|
|
2141
|
+
if (normalized) return normalized;
|
|
2142
|
+
ctx.addIssue({
|
|
2143
|
+
code: "custom",
|
|
2144
|
+
...optionCheck(`${option} must be a valid Slack emoji name (for example "eyes" or ":white_check_mark:")`)
|
|
2145
|
+
});
|
|
2146
|
+
return z.NEVER;
|
|
2147
|
+
}).default(defaultEmoji);
|
|
2148
|
+
}
|
|
2149
|
+
/** The Slack app credentials and reaction emojis. */
|
|
2150
|
+
const slackSchema = z.strictObject({
|
|
2151
|
+
botToken: z.string().optional(),
|
|
2152
|
+
clientId: z.string().optional(),
|
|
2153
|
+
clientSecret: z.string().optional(),
|
|
2154
|
+
completedReactionEmoji: reactionEmoji("completedReactionEmoji", DEFAULT_COMPLETED_REACTION_EMOJI),
|
|
2155
|
+
processingReactionEmoji: reactionEmoji("processingReactionEmoji", DEFAULT_PROCESSING_REACTION_EMOJI),
|
|
2156
|
+
signingSecret: z.string().optional()
|
|
2157
|
+
}).prefault({});
|
|
2158
|
+
/** Env var that sets each Slack field, for error messages. */
|
|
2159
|
+
const slackEnvNames = {
|
|
2160
|
+
"slack.botToken": "SLACK_BOT_TOKEN",
|
|
2161
|
+
"slack.clientId": "SLACK_CLIENT_ID",
|
|
2162
|
+
"slack.clientSecret": "SLACK_CLIENT_SECRET",
|
|
2163
|
+
"slack.signingSecret": "SLACK_SIGNING_SECRET"
|
|
2164
|
+
};
|
|
2165
|
+
/** Read the Slack group from env. */
|
|
2166
|
+
function readSlackEnv(env) {
|
|
2167
|
+
return {
|
|
2168
|
+
botToken: toOptionalTrimmed(env["SLACK_BOT_TOKEN"]) ?? toOptionalTrimmed(env["SLACK_BOT_USER_TOKEN"]),
|
|
2169
|
+
clientId: toOptionalTrimmed(env["SLACK_CLIENT_ID"]),
|
|
2170
|
+
clientSecret: toOptionalTrimmed(env["SLACK_CLIENT_SECRET"]),
|
|
2171
|
+
signingSecret: toOptionalTrimmed(env["SLACK_SIGNING_SECRET"])
|
|
2172
|
+
};
|
|
2173
|
+
}
|
|
2174
|
+
// src/config/sql.ts
|
|
2175
|
+
/** Default SQL statement timeout. */
|
|
2176
|
+
const DEFAULT_SQL_STATEMENT_TIMEOUT_MS = 3e4;
|
|
2177
|
+
/** The database. No prefault: the database URL has no default. */
|
|
2178
|
+
const sqlSchema = z.strictObject({
|
|
2179
|
+
databaseUrl: z.string().trim().min(1),
|
|
2180
|
+
driver: z.enum(["neon", "postgres"]).optional(),
|
|
2181
|
+
statementTimeoutMs: z.union([positiveInt, z.literal(false)]).default(DEFAULT_SQL_STATEMENT_TIMEOUT_MS)
|
|
2182
|
+
});
|
|
2183
|
+
/** Env var that sets each SQL field, for error messages. */
|
|
2184
|
+
const sqlEnvNames = {
|
|
2185
|
+
"sql.databaseUrl": "DATABASE_URL",
|
|
2186
|
+
"sql.driver": "JUNIOR_DATABASE_DRIVER",
|
|
2187
|
+
"sql.statementTimeoutMs": "JUNIOR_SQL_STATEMENT_TIMEOUT_MS"
|
|
2188
|
+
};
|
|
2189
|
+
function parseSqlDriver(rawValue) {
|
|
2190
|
+
const value = toOptionalTrimmed(rawValue);
|
|
2191
|
+
if (value === void 0 || value === "neon" || value === "postgres") return value;
|
|
2192
|
+
throw new Error("JUNIOR_DATABASE_DRIVER must be postgres or neon");
|
|
2193
|
+
}
|
|
2194
|
+
function parseSqlStatementTimeoutMs(rawValue) {
|
|
2195
|
+
const trimmed = toOptionalTrimmed(rawValue);
|
|
2196
|
+
if (trimmed === void 0) return;
|
|
2197
|
+
const value = Number.parseInt(trimmed, 10);
|
|
2198
|
+
if (!Number.isSafeInteger(value) || value < 0 || String(value) !== trimmed) throw new Error("JUNIOR_SQL_STATEMENT_TIMEOUT_MS must be a non-negative integer");
|
|
2199
|
+
return value === 0 ? false : value;
|
|
2200
|
+
}
|
|
2201
|
+
/** Read the SQL group from env. */
|
|
2202
|
+
function readSqlEnv(env) {
|
|
2203
|
+
return {
|
|
2204
|
+
databaseUrl: toOptionalTrimmed(env["DATABASE_URL"]),
|
|
2205
|
+
driver: parseSqlDriver(env["JUNIOR_DATABASE_DRIVER"]),
|
|
2206
|
+
statementTimeoutMs: parseSqlStatementTimeoutMs(env["JUNIOR_SQL_STATEMENT_TIMEOUT_MS"])
|
|
2207
|
+
};
|
|
2208
|
+
}
|
|
2209
|
+
function defaultSqlDriver(databaseUrl) {
|
|
2210
|
+
try {
|
|
2211
|
+
const { hostname } = new URL(databaseUrl);
|
|
2212
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" ? "postgres" : "neon";
|
|
2213
|
+
} catch {
|
|
2214
|
+
return "neon";
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
/** Default the driver from the database URL. */
|
|
2218
|
+
function deriveSql(sql) {
|
|
2219
|
+
return {
|
|
2220
|
+
...sql,
|
|
2221
|
+
driver: sql.driver ?? defaultSqlDriver(sql.databaseUrl)
|
|
2222
|
+
};
|
|
2223
|
+
}
|
|
2224
|
+
// src/config/state.ts
|
|
2225
|
+
/** The state adapter. */
|
|
2226
|
+
const stateSchema = z.strictObject({
|
|
2227
|
+
adapter: z.enum(["memory", "redis"]).default("redis"),
|
|
2228
|
+
keyPrefix: z.string().optional(),
|
|
2229
|
+
redisUrl: z.string().optional()
|
|
2230
|
+
}).prefault({});
|
|
2231
|
+
/** Env var that sets each state field, for error messages. */
|
|
2232
|
+
const stateEnvNames = {
|
|
2233
|
+
"state.adapter": "JUNIOR_STATE_ADAPTER",
|
|
2234
|
+
"state.keyPrefix": "JUNIOR_STATE_KEY_PREFIX",
|
|
2235
|
+
"state.redisUrl": "REDIS_URL"
|
|
2236
|
+
};
|
|
2237
|
+
/** Read the state group from env. */
|
|
2238
|
+
function readStateEnv(env) {
|
|
2239
|
+
return {
|
|
2240
|
+
adapter: env["JUNIOR_STATE_ADAPTER"]?.trim().toLowerCase() === "memory" ? "memory" : void 0,
|
|
2241
|
+
keyPrefix: toOptionalTrimmed(env["JUNIOR_STATE_KEY_PREFIX"]),
|
|
2242
|
+
redisUrl: toOptionalTrimmed(env["REDIS_URL"])
|
|
2243
|
+
};
|
|
2244
|
+
}
|
|
2245
|
+
// src/config/web-push.ts
|
|
2246
|
+
/** VAPID settings for web push notifications. */
|
|
2247
|
+
const webPushSchema = z.strictObject({
|
|
2248
|
+
privateKey: z.string().optional(),
|
|
2249
|
+
publicKey: z.string().optional(),
|
|
2250
|
+
subject: z.string().optional()
|
|
2251
|
+
}).prefault({});
|
|
2252
|
+
/** Read the web push group from env. */
|
|
2253
|
+
function readWebPushEnv(env) {
|
|
2254
|
+
return {
|
|
2255
|
+
privateKey: env["JUNIOR_WEB_PUSH_PRIVATE_KEY"]?.trim(),
|
|
2256
|
+
publicKey: env["JUNIOR_WEB_PUSH_PUBLIC_KEY"]?.trim(),
|
|
2257
|
+
subject: env["JUNIOR_WEB_PUSH_SUBJECT"]?.trim()
|
|
2258
|
+
};
|
|
2259
|
+
}
|
|
2260
|
+
// src/config/index.ts
|
|
2261
|
+
const configSchema = z.strictObject({
|
|
2262
|
+
/** Object storage for attachments and public artifacts. */
|
|
2263
|
+
attachmentStorage: attachmentStorageSchema.default({ provider: "vercel-blob" }),
|
|
2264
|
+
bot: botSchema.prefault({}),
|
|
2265
|
+
deployment: deploymentSchema,
|
|
2266
|
+
queue: queueSchema,
|
|
2267
|
+
functionMaxDurationSeconds: functionMaxDurationSecondsSchema,
|
|
2268
|
+
limits: limitsSchema.optional(),
|
|
2269
|
+
...killSwitchFields,
|
|
2270
|
+
encryption: encryptionSchema,
|
|
2271
|
+
secrets: secretsSchema,
|
|
2272
|
+
signIn: signInSchema,
|
|
2273
|
+
webPush: webPushSchema,
|
|
2274
|
+
sql: sqlSchema,
|
|
2275
|
+
slack: slackSchema,
|
|
2276
|
+
sandbox: sandboxSchema,
|
|
2277
|
+
state: stateSchema
|
|
2278
|
+
}).transform(derive);
|
|
2279
|
+
function derive({ limits = {}, ...config }) {
|
|
2280
|
+
const { bot, deployment, functionMaxDurationSeconds, sql } = config;
|
|
2281
|
+
return {
|
|
2282
|
+
...config,
|
|
2283
|
+
bot: deriveBot(bot, limits, functionMaxDurationSeconds),
|
|
2284
|
+
deployment: deriveDeployment(deployment),
|
|
2285
|
+
conversationWorkSoftYieldAfterMs: resolveConversationWorkSoftYieldAfterMs(functionMaxDurationSeconds),
|
|
2286
|
+
sql: deriveSql(sql)
|
|
2287
|
+
};
|
|
2288
|
+
}
|
|
2289
|
+
/** Env var that sets each config field, for error messages. */
|
|
2290
|
+
const ENV_NAMES = {
|
|
2291
|
+
...botEnvNames,
|
|
2292
|
+
...attachmentStorageEnvNames,
|
|
2293
|
+
...queueEnvNames,
|
|
2294
|
+
...killSwitchEnvNames,
|
|
2295
|
+
...encryptionEnvNames,
|
|
2296
|
+
...sqlEnvNames,
|
|
2297
|
+
...slackEnvNames,
|
|
2298
|
+
...sandboxEnvNames,
|
|
2299
|
+
...stateEnvNames
|
|
2300
|
+
};
|
|
2301
|
+
function readEnv(env) {
|
|
2302
|
+
return {
|
|
2303
|
+
attachmentStorage: readAttachmentStorage(env),
|
|
2304
|
+
bot: readBotEnv(env),
|
|
2305
|
+
deployment: readDeploymentEnv(env),
|
|
2306
|
+
queue: readQueueEnv(env),
|
|
2307
|
+
...readKillSwitchesEnv(env),
|
|
2308
|
+
encryption: readEncryption(env),
|
|
2309
|
+
secrets: readSecretsEnv(env),
|
|
2310
|
+
signIn: readSignInEnv(env),
|
|
2311
|
+
webPush: readWebPushEnv(env),
|
|
2312
|
+
sql: readSqlEnv(env),
|
|
2313
|
+
slack: readSlackEnv(env),
|
|
2314
|
+
sandbox: readSandboxEnv(env),
|
|
2315
|
+
state: readStateEnv(env)
|
|
2316
|
+
};
|
|
2317
|
+
}
|
|
2318
|
+
const plainObjectSchema = z.record(z.string(), z.unknown());
|
|
2319
|
+
function mergeConfig(a, b) {
|
|
2320
|
+
if (b === void 0) return a;
|
|
2321
|
+
const left = plainObjectSchema.safeParse(a);
|
|
2322
|
+
const right = plainObjectSchema.safeParse(b);
|
|
2323
|
+
if (!left.success || !right.success || right.data["provider"] !== void 0 && right.data["provider"] !== left.data["provider"]) return b;
|
|
2324
|
+
const merged = {};
|
|
2325
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(left.data), ...Object.keys(right.data)])) {
|
|
2326
|
+
const value = mergeConfig(left.data[key], right.data[key]);
|
|
2327
|
+
if (value !== void 0) merged[key] = value;
|
|
2328
|
+
}
|
|
2329
|
+
return merged;
|
|
2330
|
+
}
|
|
2331
|
+
function valueAt(input, path) {
|
|
2332
|
+
let value = input;
|
|
2333
|
+
for (const key of path) {
|
|
2334
|
+
const object = plainObjectSchema.safeParse(value);
|
|
2335
|
+
if (!object.success || typeof key === "symbol") return;
|
|
2336
|
+
value = object.data[String(key)];
|
|
2337
|
+
}
|
|
2338
|
+
return value;
|
|
2339
|
+
}
|
|
2340
|
+
function envNameFor(path) {
|
|
2341
|
+
const keys = path.filter((key) => typeof key === "string");
|
|
2342
|
+
for (let length = keys.length; length > 0; length--) {
|
|
2343
|
+
const envName = ENV_NAMES[keys.slice(0, length).join(".")];
|
|
2344
|
+
if (envName) return envName;
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
function formatIssue(input, issue) {
|
|
2348
|
+
if (issue.code === "custom" && issue.params?.["option"] === true) return issue.message;
|
|
2349
|
+
const path = issue.path.map(String).join(".");
|
|
2350
|
+
const envName = envNameFor(issue.path);
|
|
2351
|
+
if (issue.code === "invalid_type" && valueAt(input, issue.path) === void 0) {
|
|
2352
|
+
const required = `${envName ?? path} is required`;
|
|
2353
|
+
return path === "encryption" ? `${required}. ${ENCRYPTION_KEYS_HINT}` : required;
|
|
2354
|
+
}
|
|
2355
|
+
return `${envName ? `${path} (${envName})` : path}: ${issue.message}`;
|
|
2356
|
+
}
|
|
2357
|
+
/** Resolve config: host options win over env, and the schema fills defaults. */
|
|
2358
|
+
function loadConfig({ env = {}, options = {} } = {}) {
|
|
2359
|
+
const input = mergeConfig(readEnv(env), options);
|
|
2360
|
+
const result = configSchema.safeParse(input);
|
|
2361
|
+
if (!result.success) throw new Error(result.error.issues.map((issue) => formatIssue(input, issue)).join("; "));
|
|
2362
|
+
return result.data;
|
|
2363
|
+
}
|
|
2364
|
+
// src/chat/config.ts
|
|
2365
|
+
let installed;
|
|
2366
|
+
/**
|
|
2367
|
+
* Return the config that createApp installed. Without one, such as in the
|
|
2368
|
+
* CLI, load it from `process.env` on the first read and keep it.
|
|
2369
|
+
*/
|
|
2370
|
+
function getChatConfig() {
|
|
2371
|
+
installed ??= loadConfig({ env: process.env });
|
|
2372
|
+
return installed;
|
|
2373
|
+
}
|
|
2374
|
+
/**
|
|
2375
|
+
* Install the config that createApp resolved. Returns the previous config,
|
|
2376
|
+
* so a failed startup can install it again. `undefined` loads from env again
|
|
2377
|
+
* on the next read.
|
|
2378
|
+
*/
|
|
2379
|
+
function installChatConfig(config) {
|
|
2380
|
+
const previous = installed;
|
|
2381
|
+
installed = config;
|
|
2382
|
+
return previous;
|
|
2383
|
+
}
|
|
2384
|
+
function isBotConfigKey(bot, key) {
|
|
2385
|
+
return Object.hasOwn(bot, key);
|
|
2386
|
+
}
|
|
2387
|
+
/**
|
|
2388
|
+
* Bot settings of the current config. Readers keep this object, so it
|
|
2389
|
+
* forwards every read and write to `getChatConfig().bot`.
|
|
2390
|
+
*
|
|
2391
|
+
* Temporary: callers read `botConfig` as a plain property, so lazy loading
|
|
2392
|
+
* needs a read trap. Remove this Proxy once config is passed in explicitly.
|
|
2393
|
+
*/
|
|
2394
|
+
const botConfig = new Proxy({}, {
|
|
2395
|
+
defineProperty: (_, key, descriptor) => Reflect.defineProperty(getChatConfig().bot, key, descriptor),
|
|
2396
|
+
deleteProperty: (_, key) => Reflect.deleteProperty(getChatConfig().bot, key),
|
|
2397
|
+
get: (_, key) => {
|
|
2398
|
+
const bot = getChatConfig().bot;
|
|
2399
|
+
return isBotConfigKey(bot, key) ? bot[key] : void 0;
|
|
2400
|
+
},
|
|
2401
|
+
getOwnPropertyDescriptor: (_, key) => Reflect.getOwnPropertyDescriptor(getChatConfig().bot, key),
|
|
2402
|
+
has: (_, key) => Reflect.has(getChatConfig().bot, key),
|
|
2403
|
+
ownKeys: () => Reflect.ownKeys(getChatConfig().bot),
|
|
2404
|
+
set: (_, key, value) => Reflect.set(getChatConfig().bot, key, value)
|
|
2405
|
+
});
|
|
2406
|
+
function getSlackBotToken() {
|
|
2407
|
+
return getChatConfig().slack.botToken;
|
|
2408
|
+
}
|
|
2409
|
+
function getSlackSigningSecret() {
|
|
2410
|
+
return getChatConfig().slack.signingSecret;
|
|
2411
|
+
}
|
|
2412
|
+
function getSlackClientId() {
|
|
2413
|
+
return getChatConfig().slack.clientId;
|
|
2414
|
+
}
|
|
2415
|
+
function getSlackClientSecret() {
|
|
2416
|
+
return getChatConfig().slack.clientSecret;
|
|
2417
|
+
}
|
|
2418
|
+
/** Return runtime metadata (version from deploy environment). */
|
|
2419
|
+
function getRuntimeMetadata() {
|
|
2420
|
+
return { version: getChatConfig().deployment.commitSha };
|
|
2421
|
+
}
|
|
2422
|
+
export { isProviderRetryError as $, ACTIVE_LOCK_TTL_MS as A, textCharsForTokens as B, resolveGatewayModel as C, saveEnabledProviders as D, readServedProviders as E, requestPrefixAttributes as F, isCompactionSummaryText as G, gatewayRoutingAttributes as H, claudeMaxImageSize as I, createProviderError as J, ProviderError as K, estimateMessagesTokens as L, acquireActiveLock as M, fenceLock as N, cacheKeyPrefix as O, withLock as P, isProviderRefusal as Q, estimateRequestOverheadTokens as R, rerankTexts as S, readEnabledProviders as T, COMPACTION_SUMMARY_PREFIX as U, readImageDimensions as V, hasCompactedConversationContext as W, getProviderErrorAttributes as X, findProviderError as Y, getProviderErrorUserMessage as Z, completeObject as _, getSlackClientId as a, gatewayCostUsd as b, installChatConfig as c, normalizeSlackEmojiName as d, getGatewayApiKey as et, TURN_REASONING_LEVELS as f, completeDecision as g, GEN_AI_SERVER_ADDRESS as h, getSlackBotToken as i, MUTATION_LOCK_TTL_MS as j, createCache as k, loadConfig as l, GEN_AI_PROVIDER_NAME as m, getChatConfig as n, getSlackClientSecret as o, toPiReasoningLevel as p, createAssistantProviderError as q, getRuntimeMetadata as r, getSlackSigningSecret as s, botConfig as t, resolveGatewayCredential as tt, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as u, completeText as v, searchWeb as w, generateImages as x, embedTexts as y, estimateTextTokens as z };
|