@sentry/junior 0.316.0 → 0.318.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-UOHix_5P.js} +1 -1
- package/dist/{agent-runner-Cr5Fhjf-.js → agent-runner-DeYymwh2.js} +13494 -13135
- package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
- package/dist/{agent-update-delivery-BY13DPSD.js → agent-update-delivery-DH8bx7jU.js} +5 -5
- package/dist/api/schema.d.ts +600 -130
- package/dist/api/schema.js +6 -6
- package/dist/api.js +228 -214
- package/dist/{app-BhvzRD__.d.ts → app-DKAOuaoC.d.ts} +33 -18
- package/dist/app.d.ts +1 -1
- package/dist/app.js +193 -177
- package/dist/{thread-context-fiMNylbg.js → auth-pause-state-f9hJM_zO.js} +6 -59
- package/dist/catalog-runtime-BfdAnztW.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-A0de5lRv.js} +2 -42
- package/dist/{chat-core-engine-3dtlMku3.js → chat-core-engine-D3Wd7f5n.js} +6 -5
- package/dist/{child-message--2G3Ft26.js → child-message-peFWLcCZ.js} +2 -6
- package/dist/cli/chat.js +38 -30
- 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 +4 -2
- package/dist/cli/upgrade.js +5 -3
- package/dist/context-BKF_5zzI.js +1833 -0
- package/dist/{continue-in-slack-DbQUFe_F.js → continue-in-slack-YxwMQVeR.js} +3 -3
- package/dist/{conversation-feed-B84pMjHo.js → conversation-feed-Cj7IuBtM.js} +3 -3
- package/dist/{proxy-path-BTmXDjfx.js → conversation-privacy-Cr_dNW1p.js} +2 -16
- package/dist/{conversation-turn-DzEpTIaf.js → conversation-turn-Bru4w_FD.js} +196 -80
- package/dist/{create-DUJBXr6E.js → create-Btl1y1rq.js} +12 -11
- package/dist/{credential-sync-JH_K9Adg.js → credential-sync-DTarZ63K.js} +20 -15
- package/dist/{db-DhzvUY23.js → db-of6e3sGt.js} +20724 -27256
- package/dist/{deployment-BhvrhQeh.js → deployment-C0qXa0FD.js} +17 -15
- package/dist/{engine-context-C9Nal48K.js → engine-context-C_QL_bMQ.js} +304 -56
- package/dist/{html-B_12WjKT.js → html-9_pS9SjY.js} +6 -2
- package/dist/instrumentation.js +15 -7
- package/dist/{job-runner-DO8nslyY.js → job-runner-B2XEvpif.js} +392 -26
- package/dist/{lineage-D3AZAJVe.js → lineage-nh4z9iQN.js} +1 -1
- package/dist/{list-B0zsb5Cp.js → list-HRP3TIRl.js} +238 -550
- package/dist/{logging-B8KEJegM.js → logging-BnOG0qz2.js} +4 -50
- package/dist/{session-stop-DponjDUZ.js → mailbox-turn-Byrry9o1.js} +4807 -7102
- package/dist/{list-mkB_GU8R.js → markers-CTTtJqYn.js} +171 -124
- package/dist/{message-B5fKDYzz.js → message-BRUuLgrY.js} +13 -24
- package/dist/{model-input-CuMWy37l.js → model-input-CFC62mf-.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +21 -7
- package/dist/{oauth-callback-server-B3Vvlydo.js → oauth-callback-server-CjnnUr4o.js} +2 -2
- package/dist/{oauth-relay-6ERrGPbA.js → oauth-relay-BvHFH0fV.js} +2 -2
- package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
- package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
- package/dist/profile-iHw1uu32.js +4657 -0
- package/dist/{transcript-CCi7323k.js → prompt-DEkStuxG.js} +92 -98
- package/dist/proxy-path-BHYoKZdq.js +15 -0
- package/dist/registry-Cl7Labpe.js +3279 -0
- package/dist/reports-C1d9azyV.js +195 -0
- package/dist/{resolve-D5JVvv6A.js → resolve-DC6zBuDV.js} +9 -29
- package/dist/{result-CS_7mo8a.js → result-DxewDuXb.js} +27 -118
- package/dist/run-conversation-Cz2ubZK-.js +337 -0
- package/dist/{runner-BzAES5W3.js → runner-99YxVN_r.js} +10 -18
- package/dist/{sandbox-egress-signals-Dwhk2Q5F.js → sandbox-egress-signals-CgoX5CTI.js} +1 -1
- package/dist/{schema-z5-wA6N4.js → schema-BTojNBr5.js} +48 -86
- package/dist/sender-actors-77zTQbSG.js +84 -0
- package/dist/{service-account-D6AsAtc1.js → service-account-YDCPSByj.js} +3 -1
- package/dist/{skills-DgJ9GBPR.js → skills-CleC0Hze.js} +6 -5
- package/dist/{slack-conversation-unfurl-Dq71EkhM.js → slack-conversation-unfurl-BNQLC12R.js} +7 -6
- package/dist/{spawn-BJWpdwhQ.js → spawn-DuZfodPa.js} +5 -5
- package/dist/{system-prompt-table-iIgpmslr.js → system-prompt-table-Ci6Ck4gk.js} +88 -69
- package/dist/{task-runner-BJae4JwE.js → task-runner-BJ9Up3bG.js} +30 -53
- package/dist/topics-BoCkoPJJ.js +21 -0
- package/dist/turn-membership-VT7XZh-L.js +856 -0
- package/dist/{turn-wake-BjDW7x-5.js → turn-wake-C7HeLHAM.js} +3 -4
- package/dist/{media-BebquhET.js → types-DCzTAA63.js} +629 -593
- package/dist/user-customization-CvfuY9Eo.js +93 -0
- package/dist/users-Cb9c1k9q.js +181 -0
- package/dist/{validation-D5WmmmhX.js → validation-BiUmWPhy.js} +1 -1
- package/dist/{version-CBQoanXb.js → version-VEXiEcZu.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-Cyb4kF17.js → worker-ChWYQdhm.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/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
- package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -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,1833 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
|
|
2
|
+
import { o as toOptionalTrimmed } from "./topics-BoCkoPJJ.js";
|
|
3
|
+
import { G as mapBounded } from "./prompt-DEkStuxG.js";
|
|
4
|
+
import * as z from "zod";
|
|
5
|
+
import { calculateCost, completeSimple, getEnvApiKey, getModels, registerApiProvider } from "@earendil-works/pi-ai/compat";
|
|
6
|
+
import { stream as streamAnthropic, streamSimple as streamSimpleAnthropic } from "@earendil-works/pi-ai/api/anthropic-messages";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
9
|
+
import { createRedisState } from "@chat-adapter/state-redis";
|
|
10
|
+
import { setTimeout } from "node:timers/promises";
|
|
11
|
+
// src/config/attachments.ts
|
|
12
|
+
const DEFAULT_S3_REGION = "us-east-1";
|
|
13
|
+
const nonEmptyString = z.string().trim().min(1);
|
|
14
|
+
const s3StorageSchema = z.strictObject({
|
|
15
|
+
accessKeyId: nonEmptyString,
|
|
16
|
+
bucket: nonEmptyString,
|
|
17
|
+
/** Base URL of the S3 API. Objects use path-style URLs under it. */
|
|
18
|
+
endpoint: nonEmptyString,
|
|
19
|
+
region: nonEmptyString.default(DEFAULT_S3_REGION),
|
|
20
|
+
secretAccessKey: nonEmptyString
|
|
21
|
+
});
|
|
22
|
+
/** Object storage for attachments and public artifacts. */
|
|
23
|
+
const attachmentStorageSchema = z.discriminatedUnion("provider", [
|
|
24
|
+
z.strictObject({ provider: z.literal("vercel-blob") }),
|
|
25
|
+
z.strictObject({
|
|
26
|
+
provider: z.literal("s3"),
|
|
27
|
+
s3: s3StorageSchema
|
|
28
|
+
}),
|
|
29
|
+
z.strictObject({ provider: z.literal("memory") })
|
|
30
|
+
]);
|
|
31
|
+
/** Env var that sets each attachment storage field, for error messages. */
|
|
32
|
+
const attachmentStorageEnvNames = {
|
|
33
|
+
attachmentStorage: "JUNIOR_ATTACHMENT_STORAGE_PROVIDER",
|
|
34
|
+
"attachmentStorage.s3.accessKeyId": "JUNIOR_S3_ACCESS_KEY_ID",
|
|
35
|
+
"attachmentStorage.s3.bucket": "JUNIOR_S3_BUCKET",
|
|
36
|
+
"attachmentStorage.s3.endpoint": "JUNIOR_S3_ENDPOINT",
|
|
37
|
+
"attachmentStorage.s3.region": "JUNIOR_S3_REGION",
|
|
38
|
+
"attachmentStorage.s3.secretAccessKey": "JUNIOR_S3_SECRET_ACCESS_KEY"
|
|
39
|
+
};
|
|
40
|
+
function readS3Setting(env, name) {
|
|
41
|
+
const value = toOptionalTrimmed(env[name]);
|
|
42
|
+
if (value === void 0) throw new Error(`${name} is required when JUNIOR_ATTACHMENT_STORAGE_PROVIDER is s3`);
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
/** Read the attachment storage group from env. */
|
|
46
|
+
function readAttachmentStorage(env) {
|
|
47
|
+
const provider = toOptionalTrimmed(env["JUNIOR_ATTACHMENT_STORAGE_PROVIDER"]);
|
|
48
|
+
switch (provider) {
|
|
49
|
+
case void 0: return;
|
|
50
|
+
case "vercel-blob":
|
|
51
|
+
case "memory": return { provider };
|
|
52
|
+
case "s3": return {
|
|
53
|
+
provider,
|
|
54
|
+
s3: {
|
|
55
|
+
accessKeyId: readS3Setting(env, "JUNIOR_S3_ACCESS_KEY_ID"),
|
|
56
|
+
bucket: readS3Setting(env, "JUNIOR_S3_BUCKET"),
|
|
57
|
+
endpoint: readS3Setting(env, "JUNIOR_S3_ENDPOINT"),
|
|
58
|
+
region: toOptionalTrimmed(env["JUNIOR_S3_REGION"]),
|
|
59
|
+
secretAccessKey: readS3Setting(env, "JUNIOR_S3_SECRET_ACCESS_KEY")
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
default: throw new Error("JUNIOR_ATTACHMENT_STORAGE_PROVIDER must be vercel-blob, s3, or memory");
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// src/chat/pi/gateway-models.ts
|
|
66
|
+
/** Pi provider name for AI Gateway models. */
|
|
67
|
+
const GATEWAY_PROVIDER = "vercel-ai-gateway";
|
|
68
|
+
const GATEWAY_BASE_URL = "https://ai-gateway.vercel.sh";
|
|
69
|
+
const GATEWAY_MODEL_OVERRIDES = {
|
|
70
|
+
"anthropic/claude-opus-5.5": {
|
|
71
|
+
id: "anthropic/claude-opus-5.5",
|
|
72
|
+
name: "Claude Opus 5.5",
|
|
73
|
+
api: "anthropic-messages",
|
|
74
|
+
provider: GATEWAY_PROVIDER,
|
|
75
|
+
baseUrl: GATEWAY_BASE_URL,
|
|
76
|
+
reasoning: true,
|
|
77
|
+
input: ["text", "image"],
|
|
78
|
+
cost: {
|
|
79
|
+
input: 4,
|
|
80
|
+
output: 20,
|
|
81
|
+
cacheRead: .2,
|
|
82
|
+
cacheWrite: 5
|
|
83
|
+
},
|
|
84
|
+
contextWindow: 1e6,
|
|
85
|
+
maxTokens: 128e3,
|
|
86
|
+
thinkingLevelMap: {
|
|
87
|
+
xhigh: "xhigh",
|
|
88
|
+
max: "max"
|
|
89
|
+
},
|
|
90
|
+
compat: {
|
|
91
|
+
forceAdaptiveThinking: true,
|
|
92
|
+
supportsMidConvoSystemMessages: true,
|
|
93
|
+
supportsTemperature: false
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
"xai/grok-4.5": {
|
|
97
|
+
id: "xai/grok-4.5",
|
|
98
|
+
name: "Grok 4.5",
|
|
99
|
+
api: "anthropic-messages",
|
|
100
|
+
provider: GATEWAY_PROVIDER,
|
|
101
|
+
baseUrl: GATEWAY_BASE_URL,
|
|
102
|
+
reasoning: true,
|
|
103
|
+
input: ["text", "image"],
|
|
104
|
+
cost: {
|
|
105
|
+
input: 2,
|
|
106
|
+
output: 6,
|
|
107
|
+
cacheRead: .3,
|
|
108
|
+
cacheWrite: 0
|
|
109
|
+
},
|
|
110
|
+
contextWindow: 5e5,
|
|
111
|
+
maxTokens: 5e5
|
|
112
|
+
},
|
|
113
|
+
"openai/gpt-6-luna": {
|
|
114
|
+
id: "openai/gpt-6-luna",
|
|
115
|
+
name: "GPT-6 Luna",
|
|
116
|
+
api: "anthropic-messages",
|
|
117
|
+
provider: GATEWAY_PROVIDER,
|
|
118
|
+
baseUrl: GATEWAY_BASE_URL,
|
|
119
|
+
reasoning: true,
|
|
120
|
+
input: ["text", "image"],
|
|
121
|
+
cost: {
|
|
122
|
+
input: .1,
|
|
123
|
+
output: .5,
|
|
124
|
+
cacheRead: .01,
|
|
125
|
+
cacheWrite: .125,
|
|
126
|
+
tiers: [{
|
|
127
|
+
inputTokensAbove: 272e3,
|
|
128
|
+
input: .2,
|
|
129
|
+
output: .75,
|
|
130
|
+
cacheRead: .02,
|
|
131
|
+
cacheWrite: .25
|
|
132
|
+
}]
|
|
133
|
+
},
|
|
134
|
+
contextWindow: 105e4,
|
|
135
|
+
maxTokens: 128e3,
|
|
136
|
+
thinkingLevelMap: {
|
|
137
|
+
xhigh: "xhigh",
|
|
138
|
+
max: "max"
|
|
139
|
+
},
|
|
140
|
+
compat: { supportsMidConvoSystemMessages: true }
|
|
141
|
+
},
|
|
142
|
+
"openai/gpt-6-astra": {
|
|
143
|
+
id: "openai/gpt-6-astra",
|
|
144
|
+
name: "GPT-6 Astra",
|
|
145
|
+
api: "anthropic-messages",
|
|
146
|
+
provider: GATEWAY_PROVIDER,
|
|
147
|
+
baseUrl: GATEWAY_BASE_URL,
|
|
148
|
+
reasoning: true,
|
|
149
|
+
input: ["text", "image"],
|
|
150
|
+
cost: {
|
|
151
|
+
input: 10,
|
|
152
|
+
output: 50,
|
|
153
|
+
cacheRead: 1,
|
|
154
|
+
cacheWrite: 12.5,
|
|
155
|
+
tiers: [{
|
|
156
|
+
inputTokensAbove: 272e3,
|
|
157
|
+
input: 20,
|
|
158
|
+
output: 75,
|
|
159
|
+
cacheRead: 2,
|
|
160
|
+
cacheWrite: 25
|
|
161
|
+
}]
|
|
162
|
+
},
|
|
163
|
+
contextWindow: 105e4,
|
|
164
|
+
maxTokens: 128e3,
|
|
165
|
+
thinkingLevelMap: {
|
|
166
|
+
xhigh: "xhigh",
|
|
167
|
+
max: "max"
|
|
168
|
+
},
|
|
169
|
+
compat: { supportsTemperature: false }
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
/** Find a gateway model through local overrides, then Pi's bundled catalog. */
|
|
173
|
+
function findGatewayModel(modelId) {
|
|
174
|
+
return GATEWAY_MODEL_OVERRIDES[modelId] ?? getModels("vercel-ai-gateway").find((model) => model.id === modelId);
|
|
175
|
+
}
|
|
176
|
+
/** Resolve gateway models through local overrides, then Pi's bundled catalog. */
|
|
177
|
+
function resolveGatewayModel(modelId) {
|
|
178
|
+
const matched = findGatewayModel(modelId);
|
|
179
|
+
if (!matched) throw new Error(`Unknown AI Gateway model id: ${modelId}`);
|
|
180
|
+
return {
|
|
181
|
+
...matched,
|
|
182
|
+
compat: {
|
|
183
|
+
...matched.compat,
|
|
184
|
+
sendSessionAffinityHeaders: true
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
// src/chat/reasoning-level.ts
|
|
189
|
+
const TURN_REASONING_LEVELS = [
|
|
190
|
+
"none",
|
|
191
|
+
"low",
|
|
192
|
+
"medium",
|
|
193
|
+
"high",
|
|
194
|
+
"xhigh"
|
|
195
|
+
];
|
|
196
|
+
/** Validate a configured main-agent reasoning level. */
|
|
197
|
+
function parseTurnReasoningLevel(value) {
|
|
198
|
+
return z.enum(TURN_REASONING_LEVELS).parse(value);
|
|
199
|
+
}
|
|
200
|
+
/** Convert a reasoning level into the Pi Agent setting for a main Turn. */
|
|
201
|
+
function toPiReasoningLevel(level) {
|
|
202
|
+
return level === "none" ? "off" : level;
|
|
203
|
+
}
|
|
204
|
+
// src/config/fields.ts
|
|
205
|
+
/**
|
|
206
|
+
* A check that only createApp options reach. Its message names the option,
|
|
207
|
+
* so it stands alone without a field path or env var.
|
|
208
|
+
*/
|
|
209
|
+
function optionCheck(message) {
|
|
210
|
+
return {
|
|
211
|
+
message,
|
|
212
|
+
params: { option: true }
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
/** A positive integer field. */
|
|
216
|
+
const positiveInt = z.number().int().positive();
|
|
217
|
+
// src/config/function-duration.ts
|
|
218
|
+
const DEFAULT_FUNCTION_MAX_DURATION_SECONDS = 300;
|
|
219
|
+
/** Shortest agent turn timeout. */
|
|
220
|
+
const MIN_AGENT_TURN_TIMEOUT_MS = 1e4;
|
|
221
|
+
/** Additional buffer that makes conversation work yield before the hard request deadline. */
|
|
222
|
+
const CONVERSATION_WORK_SOFT_YIELD_BUFFER_SECONDS = 40;
|
|
223
|
+
/** Max duration of the Vercel function, in seconds. */
|
|
224
|
+
const functionMaxDurationSecondsSchema = z.number().default(DEFAULT_FUNCTION_MAX_DURATION_SECONDS);
|
|
225
|
+
/** Longest agent turn the function duration allows, after the teardown buffer. */
|
|
226
|
+
function resolveMaxTurnTimeoutMs(functionMaxDurationSeconds) {
|
|
227
|
+
const budgetSeconds = functionMaxDurationSeconds - 20;
|
|
228
|
+
return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, budgetSeconds * 1e3);
|
|
229
|
+
}
|
|
230
|
+
/** When conversation work yields, so it stops before the request deadline. */
|
|
231
|
+
function resolveConversationWorkSoftYieldAfterMs(functionMaxDurationSeconds) {
|
|
232
|
+
return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, (functionMaxDurationSeconds - CONVERSATION_WORK_SOFT_YIELD_BUFFER_SECONDS) * 1e3);
|
|
233
|
+
}
|
|
234
|
+
// src/config/bot.ts
|
|
235
|
+
const DEFAULT_AGENT_TURN_TIMEOUT_MS = 72e4;
|
|
236
|
+
const MAX_SLICES_PER_TURN = 100;
|
|
237
|
+
/**
|
|
238
|
+
* Max model spend in USD for one turn, including later execution slices of
|
|
239
|
+
* that turn. Sentry span estimates put a child agent that made 250 tool calls
|
|
240
|
+
* of real work at about $50.
|
|
241
|
+
*/
|
|
242
|
+
const MAX_TURN_COST_USD = 100;
|
|
243
|
+
/**
|
|
244
|
+
* Max tool calls for one turn, including later execution slices of that turn.
|
|
245
|
+
* A backstop for models without cost data. The spend limit should stop a turn
|
|
246
|
+
* first. 250 calls stopped child agents that were still doing real work.
|
|
247
|
+
*/
|
|
248
|
+
const MAX_TOOL_CALLS_PER_TURN = 1e3;
|
|
249
|
+
/**
|
|
250
|
+
* Max consecutive automated turns before event wakes stop until a user message.
|
|
251
|
+
* Resource-event CI watches and event-automation loops are the common runaway paths.
|
|
252
|
+
* Sentry telemetry has no direct instrumentation for how long real automated
|
|
253
|
+
* chains run (only failure paths on the notice are logged, and those show zero
|
|
254
|
+
* hits in the last 30d), so this is sized qualitatively: it stays well under
|
|
255
|
+
* the runaway CI-watch-loop range (hundreds of tool calls) while giving
|
|
256
|
+
* multi-phase event-automation/scheduled-automation work enough headroom to
|
|
257
|
+
* avoid pausing on legitimate longer-running automation.
|
|
258
|
+
*/
|
|
259
|
+
const MAX_CONSECUTIVE_AUTOMATED_TURNS = 25;
|
|
260
|
+
/**
|
|
261
|
+
* Max runs one Event automation can start in one rolling run window. Each run
|
|
262
|
+
* is a full agent turn, and Event automations skip the consecutive
|
|
263
|
+
* automated-turn limit. Kept low so a broad trigger, such as every message in
|
|
264
|
+
* a channel, blocks quickly instead of starting a turn for each Event.
|
|
265
|
+
*/
|
|
266
|
+
const MAX_EVENT_AUTOMATION_RUNS = 10;
|
|
267
|
+
/** Length of the rolling window for the Event automation run limit. */
|
|
268
|
+
const EVENT_AUTOMATION_RUN_WINDOW_MS = 6e4;
|
|
269
|
+
const DEFAULT_MODEL_CONTEXT_WINDOW_TOKENS = 4e5;
|
|
270
|
+
const DEFAULT_ASSISTANT_LOADING_MESSAGES = [
|
|
271
|
+
"Consulting the orb",
|
|
272
|
+
"Bribing the gremlins",
|
|
273
|
+
"Shuffling the papers dramatically",
|
|
274
|
+
"Summoning the right stack trace",
|
|
275
|
+
"Negotiating with the mutex",
|
|
276
|
+
"Poking the internet with a stick",
|
|
277
|
+
"Asking the docs nicely",
|
|
278
|
+
"Searching for the least cursed path",
|
|
279
|
+
"Pretending this was obvious",
|
|
280
|
+
"Waking up the test suite",
|
|
281
|
+
"Untangling the spaghetti carefully",
|
|
282
|
+
"Rattling the command line"
|
|
283
|
+
];
|
|
284
|
+
const DEFAULT_MODEL_ID = resolveGatewayModel("anthropic/claude-opus-5.5").id;
|
|
285
|
+
const DEFAULT_FAST_MODEL_ID = resolveGatewayModel("openai/gpt-6-luna").id;
|
|
286
|
+
const DEFAULT_GUARDIAN_MODEL_ID = resolveGatewayModel("openai/gpt-6-luna").id;
|
|
287
|
+
const DEFAULT_WEB_SEARCH_MODEL_ID = resolveGatewayModel("openai/gpt-6-luna").id;
|
|
288
|
+
const DEFAULT_DECISION_MODEL_ID = "typesafe-ai/jev";
|
|
289
|
+
const DEFAULT_EMBEDDING_MODEL_ID = "openai/text-embedding-3-small";
|
|
290
|
+
const DEFAULT_RERANKING_MODEL_ID = "voyage/rerank-2.5-lite";
|
|
291
|
+
const DEFAULT_IMAGE_GENERATION_MODEL_ID = "openai/gpt-image-2";
|
|
292
|
+
const DEFAULT_TRANSCRIPTION_MODEL_ID = "elevenlabs/scribe-v2";
|
|
293
|
+
const DEFAULT_VISION_MODEL_ID = resolveGatewayModel("openai/gpt-5.6-sol").id;
|
|
294
|
+
function modelId(option) {
|
|
295
|
+
return z.string().trim().refine((id) => id.length > 0, {
|
|
296
|
+
...optionCheck(`${option} must not be empty`),
|
|
297
|
+
abort: true
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
function gatewayModelId(option) {
|
|
301
|
+
return modelId(option).refine((id) => Boolean(resolveGatewayModel(id)));
|
|
302
|
+
}
|
|
303
|
+
function positiveLimit(name) {
|
|
304
|
+
return z.number().refine((value) => Number.isSafeInteger(value) && value > 0, optionCheck(`limits.${name} must be a positive integer`));
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Limits from `createApp({ limits })`. `derive` applies them over the bot
|
|
308
|
+
* settings, so they win over env, and the turn timeout is only capped by the
|
|
309
|
+
* function duration.
|
|
310
|
+
*/
|
|
311
|
+
const limitsSchema = z.strictObject({
|
|
312
|
+
contextWindowTokens: positiveLimit("contextWindowTokens").optional(),
|
|
313
|
+
maxAgentDepth: z.number().refine((value) => Number.isSafeInteger(value) && value >= 0, optionCheck("limits.maxAgentDepth must be a non-negative integer")).optional(),
|
|
314
|
+
maxConsecutiveAutomatedTurns: positiveLimit("maxConsecutiveAutomatedTurns").optional(),
|
|
315
|
+
eventAutomationRunLimit: z.strictObject({
|
|
316
|
+
maxRuns: positiveLimit("eventAutomationRunLimit.maxRuns").optional(),
|
|
317
|
+
windowMs: positiveLimit("eventAutomationRunLimit.windowMs").optional()
|
|
318
|
+
}).optional(),
|
|
319
|
+
maxSlicesPerTurn: positiveLimit("maxSlicesPerTurn").optional(),
|
|
320
|
+
maxToolCallsPerTurn: positiveLimit("maxToolCallsPerTurn").optional(),
|
|
321
|
+
maxTurnCostUsd: positiveLimit("maxTurnCostUsd").optional(),
|
|
322
|
+
turnTimeoutMs: positiveLimit("turnTimeoutMs").optional()
|
|
323
|
+
});
|
|
324
|
+
/** Models, the bot name, and per-turn limits. */
|
|
325
|
+
const botSchema = z.strictObject({
|
|
326
|
+
modelId: gatewayModelId("modelId").default(DEFAULT_MODEL_ID),
|
|
327
|
+
fastModelId: gatewayModelId("fastModelId").default(DEFAULT_FAST_MODEL_ID),
|
|
328
|
+
guardianModelId: gatewayModelId("guardianModelId").default(DEFAULT_GUARDIAN_MODEL_ID),
|
|
329
|
+
webSearchModelId: gatewayModelId("webSearchModelId").default(DEFAULT_WEB_SEARCH_MODEL_ID),
|
|
330
|
+
refusalFallbackModelId: gatewayModelId("refusalFallbackModelId").optional(),
|
|
331
|
+
visionModelId: gatewayModelId("visionModelId").nullable().default(DEFAULT_VISION_MODEL_ID),
|
|
332
|
+
decisionModelId: modelId("decisionModelId").default(DEFAULT_DECISION_MODEL_ID),
|
|
333
|
+
embeddingModelId: modelId("embeddingModelId").default(DEFAULT_EMBEDDING_MODEL_ID),
|
|
334
|
+
rerankingModelId: modelId("rerankingModelId").default(DEFAULT_RERANKING_MODEL_ID),
|
|
335
|
+
imageGenerationModelId: modelId("imageGenerationModelId").default(DEFAULT_IMAGE_GENERATION_MODEL_ID),
|
|
336
|
+
transcriptionModelId: modelId("transcriptionModelId").default(DEFAULT_TRANSCRIPTION_MODEL_ID),
|
|
337
|
+
userName: z.string().trim().refine((name) => name.length > 0, optionCheck("botName must not be empty")).default("junior"),
|
|
338
|
+
contextWindowTokens: positiveInt.default(DEFAULT_MODEL_CONTEXT_WINDOW_TOKENS),
|
|
339
|
+
reasoningLevel: z.enum(TURN_REASONING_LEVELS).default("high"),
|
|
340
|
+
loadingMessages: z.array(z.string()).default(() => [...DEFAULT_ASSISTANT_LOADING_MESSAGES]),
|
|
341
|
+
maxAgentDepth: z.number().int().nonnegative().default(2),
|
|
342
|
+
maxSlicesPerTurn: positiveInt.default(MAX_SLICES_PER_TURN),
|
|
343
|
+
maxToolCallsPerTurn: positiveInt.default(MAX_TOOL_CALLS_PER_TURN),
|
|
344
|
+
maxTurnCostUsd: positiveInt.default(MAX_TURN_COST_USD),
|
|
345
|
+
maxConsecutiveAutomatedTurns: positiveInt.default(MAX_CONSECUTIVE_AUTOMATED_TURNS),
|
|
346
|
+
maxEventAutomationRuns: positiveInt.default(MAX_EVENT_AUTOMATION_RUNS),
|
|
347
|
+
eventAutomationRunWindowMs: positiveInt.default(EVENT_AUTOMATION_RUN_WINDOW_MS),
|
|
348
|
+
turnTimeoutMs: z.number().int().optional()
|
|
349
|
+
});
|
|
350
|
+
/** Env var that sets each bot field, for error messages. */
|
|
351
|
+
const botEnvNames = {
|
|
352
|
+
"bot.modelId": "AI_MODEL",
|
|
353
|
+
"bot.fastModelId": "AI_FAST_MODEL",
|
|
354
|
+
"bot.guardianModelId": "AI_GUARDIAN_MODEL",
|
|
355
|
+
"bot.webSearchModelId": "AI_WEB_SEARCH_MODEL",
|
|
356
|
+
"bot.refusalFallbackModelId": "AI_REFUSAL_FALLBACK_MODEL",
|
|
357
|
+
"bot.visionModelId": "AI_VISION_MODEL",
|
|
358
|
+
"bot.decisionModelId": "AI_DECISION_MODEL",
|
|
359
|
+
"bot.embeddingModelId": "AI_EMBEDDING_MODEL",
|
|
360
|
+
"bot.rerankingModelId": "AI_RERANKING_MODEL",
|
|
361
|
+
"bot.imageGenerationModelId": "AI_IMAGE_MODEL",
|
|
362
|
+
"bot.transcriptionModelId": "AI_TRANSCRIPTION_MODEL",
|
|
363
|
+
"bot.userName": "JUNIOR_BOT_NAME",
|
|
364
|
+
"bot.contextWindowTokens": "AI_MODEL_CONTEXT_WINDOW_TOKENS",
|
|
365
|
+
"bot.reasoningLevel": "AI_REASONING_LEVEL",
|
|
366
|
+
"bot.loadingMessages": "JUNIOR_LOADING_MESSAGES",
|
|
367
|
+
"bot.turnTimeoutMs": "AGENT_TURN_TIMEOUT_MS"
|
|
368
|
+
};
|
|
369
|
+
function parseLoadingMessages(rawValue) {
|
|
370
|
+
const trimmed = rawValue?.trim();
|
|
371
|
+
if (!trimmed) return;
|
|
372
|
+
let parsed;
|
|
373
|
+
try {
|
|
374
|
+
parsed = JSON.parse(trimmed);
|
|
375
|
+
} catch {
|
|
376
|
+
throw new Error("JUNIOR_LOADING_MESSAGES must be a JSON array of strings");
|
|
377
|
+
}
|
|
378
|
+
if (!Array.isArray(parsed)) throw new Error("JUNIOR_LOADING_MESSAGES must be a JSON array of strings");
|
|
379
|
+
return parsed.map((value, index) => {
|
|
380
|
+
if (typeof value !== "string") throw new Error(`JUNIOR_LOADING_MESSAGES[${index}] must be a string`);
|
|
381
|
+
return value.trim();
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
function parseOptionalPositiveInteger(envName, rawValue) {
|
|
385
|
+
const trimmed = toOptionalTrimmed(rawValue);
|
|
386
|
+
if (trimmed === void 0) return;
|
|
387
|
+
const value = Number.parseInt(trimmed, 10);
|
|
388
|
+
if (!Number.isSafeInteger(value) || value <= 0 || String(value) !== trimmed) throw new Error(`${envName} must be a positive integer`);
|
|
389
|
+
return value;
|
|
390
|
+
}
|
|
391
|
+
function parseTurnTimeoutMs(rawValue) {
|
|
392
|
+
const value = Number.parseInt(rawValue ?? "", 10);
|
|
393
|
+
return Number.isNaN(value) ? void 0 : value;
|
|
394
|
+
}
|
|
395
|
+
function parseVisionModelId(rawValue) {
|
|
396
|
+
if (rawValue === void 0) return;
|
|
397
|
+
return toOptionalTrimmed(rawValue) ?? null;
|
|
398
|
+
}
|
|
399
|
+
/** Read the bot group from env. */
|
|
400
|
+
function readBotEnv(env) {
|
|
401
|
+
const reasoningLevel = toOptionalTrimmed(env["AI_REASONING_LEVEL"]);
|
|
402
|
+
return {
|
|
403
|
+
modelId: toOptionalTrimmed(env["AI_MODEL"]),
|
|
404
|
+
fastModelId: toOptionalTrimmed(env["AI_FAST_MODEL"] ?? env["AI_MODEL"]),
|
|
405
|
+
guardianModelId: toOptionalTrimmed(env["AI_GUARDIAN_MODEL"]),
|
|
406
|
+
webSearchModelId: toOptionalTrimmed(env["AI_WEB_SEARCH_MODEL"]),
|
|
407
|
+
refusalFallbackModelId: toOptionalTrimmed(env["AI_REFUSAL_FALLBACK_MODEL"]),
|
|
408
|
+
visionModelId: parseVisionModelId(env["AI_VISION_MODEL"]),
|
|
409
|
+
decisionModelId: toOptionalTrimmed(env["AI_DECISION_MODEL"]),
|
|
410
|
+
embeddingModelId: toOptionalTrimmed(env["AI_EMBEDDING_MODEL"]),
|
|
411
|
+
rerankingModelId: toOptionalTrimmed(env["AI_RERANKING_MODEL"]),
|
|
412
|
+
imageGenerationModelId: toOptionalTrimmed(env["AI_IMAGE_MODEL"]),
|
|
413
|
+
transcriptionModelId: toOptionalTrimmed(env["AI_TRANSCRIPTION_MODEL"]),
|
|
414
|
+
userName: toOptionalTrimmed(env["JUNIOR_BOT_NAME"]),
|
|
415
|
+
contextWindowTokens: parseOptionalPositiveInteger("AI_MODEL_CONTEXT_WINDOW_TOKENS", env["AI_MODEL_CONTEXT_WINDOW_TOKENS"]),
|
|
416
|
+
reasoningLevel: reasoningLevel === void 0 ? void 0 : parseTurnReasoningLevel(reasoningLevel),
|
|
417
|
+
loadingMessages: parseLoadingMessages(env["JUNIOR_LOADING_MESSAGES"]),
|
|
418
|
+
turnTimeoutMs: parseTurnTimeoutMs(env["AGENT_TURN_TIMEOUT_MS"])
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Apply the createApp limits over the bot settings, and cap the turn timeout
|
|
423
|
+
* at the function duration.
|
|
424
|
+
*/
|
|
425
|
+
function deriveBot(bot, limits, functionMaxDurationSeconds) {
|
|
426
|
+
const maxTurnTimeoutMs = resolveMaxTurnTimeoutMs(functionMaxDurationSeconds);
|
|
427
|
+
return {
|
|
428
|
+
...bot,
|
|
429
|
+
contextWindowTokens: limits.contextWindowTokens ?? bot.contextWindowTokens,
|
|
430
|
+
maxAgentDepth: limits.maxAgentDepth ?? bot.maxAgentDepth,
|
|
431
|
+
maxConsecutiveAutomatedTurns: limits.maxConsecutiveAutomatedTurns ?? bot.maxConsecutiveAutomatedTurns,
|
|
432
|
+
maxEventAutomationRuns: limits.eventAutomationRunLimit?.maxRuns ?? bot.maxEventAutomationRuns,
|
|
433
|
+
eventAutomationRunWindowMs: limits.eventAutomationRunLimit?.windowMs ?? bot.eventAutomationRunWindowMs,
|
|
434
|
+
maxSlicesPerTurn: limits.maxSlicesPerTurn ?? bot.maxSlicesPerTurn,
|
|
435
|
+
maxToolCallsPerTurn: limits.maxToolCallsPerTurn ?? bot.maxToolCallsPerTurn,
|
|
436
|
+
maxTurnCostUsd: limits.maxTurnCostUsd ?? bot.maxTurnCostUsd,
|
|
437
|
+
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),
|
|
438
|
+
visionModelId: bot.visionModelId ?? void 0
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
// src/config/config-defaults.ts
|
|
442
|
+
/**
|
|
443
|
+
* Install-wide defaults keyed by plugin config key. They are cloned, so a
|
|
444
|
+
* later change to the object that the host passed does not reach config.
|
|
445
|
+
*/
|
|
446
|
+
const configDefaultsSchema = z.unknown().optional().transform((defaults, ctx) => {
|
|
447
|
+
if (defaults === void 0) return {};
|
|
448
|
+
if (typeof defaults !== "object" || defaults === null || Array.isArray(defaults)) {
|
|
449
|
+
ctx.addIssue({
|
|
450
|
+
code: "custom",
|
|
451
|
+
...optionCheck("configDefaults must be an object keyed by plugin config key")
|
|
452
|
+
});
|
|
453
|
+
return z.NEVER;
|
|
454
|
+
}
|
|
455
|
+
return structuredClone(Object.fromEntries(Object.entries(defaults)));
|
|
456
|
+
});
|
|
457
|
+
// src/config/dashboard.ts
|
|
458
|
+
/** Where dashboard links point. Unset or disabled means no links. */
|
|
459
|
+
const dashboardSchema = z.strictObject({
|
|
460
|
+
basePath: z.string().optional(),
|
|
461
|
+
baseURL: z.string().optional(),
|
|
462
|
+
disabled: z.boolean().optional()
|
|
463
|
+
}).optional();
|
|
464
|
+
/** The public base URL and the Vercel deployment that runs this process. */
|
|
465
|
+
const deploymentSchema = z.strictObject({
|
|
466
|
+
/** Public base URL that the host sets: `dashboard.baseURL` or `JUNIOR_BASE_URL`. */
|
|
467
|
+
configuredBaseUrl: z.string().optional(),
|
|
468
|
+
/** Git commit of this deployment. */
|
|
469
|
+
commitSha: z.string().optional(),
|
|
470
|
+
/** Vercel deployment that runs this process. Unset outside Vercel. */
|
|
471
|
+
id: z.string().optional(),
|
|
472
|
+
/** Vercel hostnames, for the base URL when none is configured. */
|
|
473
|
+
vercelProductionUrl: z.string().optional(),
|
|
474
|
+
vercelUrl: z.string().optional(),
|
|
475
|
+
/** Timezone for people whose timezone Junior does not know. */
|
|
476
|
+
timezone: z.string().default("America/Los_Angeles"),
|
|
477
|
+
/** Sentry org slug for links to Sentry. */
|
|
478
|
+
sentryOrgSlug: z.string().optional()
|
|
479
|
+
}).prefault({});
|
|
480
|
+
function withHttps(host) {
|
|
481
|
+
return host.startsWith("https://") || host.startsWith("http://") ? host : `https://${host}`;
|
|
482
|
+
}
|
|
483
|
+
/** Read the deployment group from env. */
|
|
484
|
+
function readDeploymentEnv(env) {
|
|
485
|
+
return {
|
|
486
|
+
configuredBaseUrl: toOptionalTrimmed(env["JUNIOR_BASE_URL"]),
|
|
487
|
+
commitSha: toOptionalTrimmed(env["VERCEL_GIT_COMMIT_SHA"]),
|
|
488
|
+
id: toOptionalTrimmed(env["VERCEL_DEPLOYMENT_ID"]),
|
|
489
|
+
vercelProductionUrl: toOptionalTrimmed(env["VERCEL_PROJECT_PRODUCTION_URL"]),
|
|
490
|
+
vercelUrl: toOptionalTrimmed(env["VERCEL_URL"]),
|
|
491
|
+
timezone: toOptionalTrimmed(env["JUNIOR_TIMEZONE"]),
|
|
492
|
+
sentryOrgSlug: toOptionalTrimmed(env["SENTRY_ORG_SLUG"])
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
/** Resolve the public base URL: the configured one, else the Vercel URL. */
|
|
496
|
+
function deriveDeployment(deployment) {
|
|
497
|
+
const vercelUrl = deployment.vercelProductionUrl ?? deployment.vercelUrl;
|
|
498
|
+
return {
|
|
499
|
+
/** Public base URL: the configured one, else the Vercel URL. */
|
|
500
|
+
baseUrl: deployment.configuredBaseUrl ?? (vercelUrl ? withHttps(vercelUrl) : void 0),
|
|
501
|
+
configuredBaseUrl: deployment.configuredBaseUrl,
|
|
502
|
+
commitSha: deployment.commitSha,
|
|
503
|
+
id: deployment.id,
|
|
504
|
+
timezone: deployment.timezone,
|
|
505
|
+
sentryOrgSlug: deployment.sentryOrgSlug
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
// src/config/encryption.ts
|
|
509
|
+
const ENCRYPTION_KEY_BYTES = 32;
|
|
510
|
+
const ENCRYPTION_KEY_ID_PATTERN = /^[A-Za-z0-9._-]{1,32}$/;
|
|
511
|
+
const ENCRYPTION_KEY_MATERIAL_PATTERN = /^[A-Za-z0-9+/_-]+={0,2}$/;
|
|
512
|
+
/** How to generate a key, for the missing-keys error. */
|
|
513
|
+
const ENCRYPTION_KEYS_HINT = "Generate a key with: node -e \"console.log('k1:' + require('node:crypto').randomBytes(32).toString('base64url'))\"";
|
|
514
|
+
function isEncryptionKeyMaterial(material) {
|
|
515
|
+
return ENCRYPTION_KEY_MATERIAL_PATTERN.test(material) && Buffer.from(material, "base64").length === ENCRYPTION_KEY_BYTES;
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Keys for secrets at rest, as plain data. `createEncryptionKeyring` builds
|
|
519
|
+
* the keyring. Startup fails when they are missing or invalid.
|
|
520
|
+
*/
|
|
521
|
+
const encryptionSchema = z.strictObject({
|
|
522
|
+
/** Key for new values. */
|
|
523
|
+
activeKeyId: z.string(),
|
|
524
|
+
/** Every key that decrypts, as base64 key material. */
|
|
525
|
+
keys: z.array(z.strictObject({
|
|
526
|
+
id: z.string().regex(ENCRYPTION_KEY_ID_PATTERN),
|
|
527
|
+
key: z.string().refine(isEncryptionKeyMaterial, `must be ${ENCRYPTION_KEY_BYTES} bytes in base64`)
|
|
528
|
+
})).min(1)
|
|
529
|
+
}).refine(({ keys }) => new Set(keys.map(({ id }) => id)).size === keys.length, {
|
|
530
|
+
message: "must not repeat a key id",
|
|
531
|
+
path: ["keys"]
|
|
532
|
+
}).refine(({ activeKeyId, keys }) => keys.some(({ id }) => id === activeKeyId), {
|
|
533
|
+
message: "must name a listed key",
|
|
534
|
+
path: ["activeKeyId"]
|
|
535
|
+
});
|
|
536
|
+
/** Env var that sets each encryption field, for error messages. */
|
|
537
|
+
const encryptionEnvNames = {
|
|
538
|
+
encryption: "JUNIOR_ENCRYPTION_KEYS",
|
|
539
|
+
"encryption.activeKeyId": "JUNIOR_ENCRYPTION_KEY_ID"
|
|
540
|
+
};
|
|
541
|
+
function parseEncryptionKey(entry, index) {
|
|
542
|
+
const separator = entry.indexOf(":");
|
|
543
|
+
const id = entry.slice(0, separator).trim();
|
|
544
|
+
const key = entry.slice(separator + 1).trim();
|
|
545
|
+
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 "-"`);
|
|
546
|
+
if (!isEncryptionKeyMaterial(key)) throw new Error(`JUNIOR_ENCRYPTION_KEYS key "${id}" must be ${ENCRYPTION_KEY_BYTES} bytes in base64`);
|
|
547
|
+
return {
|
|
548
|
+
id,
|
|
549
|
+
key
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* `JUNIOR_ENCRYPTION_KEYS` lists `<id>:<key>` entries, comma-separated.
|
|
554
|
+
* `JUNIOR_ENCRYPTION_KEY_ID` names the key for new values; it is optional
|
|
555
|
+
* when there is one key. All listed keys decrypt.
|
|
556
|
+
*/
|
|
557
|
+
function readEncryption(env) {
|
|
558
|
+
const entries = (env["JUNIOR_ENCRYPTION_KEYS"] ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
559
|
+
if (entries.length === 0) return;
|
|
560
|
+
const keys = entries.map(parseEncryptionKey);
|
|
561
|
+
if (new Set(keys.map(({ id }) => id)).size !== keys.length) throw new Error("JUNIOR_ENCRYPTION_KEYS must not repeat a key id");
|
|
562
|
+
const activeKeyId = env["JUNIOR_ENCRYPTION_KEY_ID"]?.trim() || (keys.length === 1 ? keys[0]?.id : void 0);
|
|
563
|
+
if (!activeKeyId) throw new Error("JUNIOR_ENCRYPTION_KEY_ID is required when JUNIOR_ENCRYPTION_KEYS has more than one key");
|
|
564
|
+
if (!keys.some(({ id }) => id === activeKeyId)) throw new Error(`JUNIOR_ENCRYPTION_KEY_ID "${activeKeyId}" is not in JUNIOR_ENCRYPTION_KEYS`);
|
|
565
|
+
return {
|
|
566
|
+
activeKeyId,
|
|
567
|
+
keys
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
// src/config/development.ts
|
|
571
|
+
/** Settings of a local development run. */
|
|
572
|
+
const developmentSchema = z.strictObject({
|
|
573
|
+
/** True when `NODE_ENV` is `development`, such as under `pnpm dev`. */
|
|
574
|
+
enabled: z.boolean().default(false),
|
|
575
|
+
/** Port of the local dev server, for the CLI to reach it. */
|
|
576
|
+
port: z.string().default("3000")
|
|
577
|
+
}).prefault({});
|
|
578
|
+
/** Read the development group from env. */
|
|
579
|
+
function readDevelopmentEnv(env) {
|
|
580
|
+
return {
|
|
581
|
+
enabled: env["NODE_ENV"] === "development",
|
|
582
|
+
port: env["PORT"]?.trim() || void 0
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
// src/config/event-embeddings.ts
|
|
586
|
+
/** Whether Junior embeds Conversation events for meaning search. */
|
|
587
|
+
const eventEmbeddingsSchema = z.strictObject({ enabled: z.boolean().optional() }).prefault({});
|
|
588
|
+
// src/config/experimental.ts
|
|
589
|
+
/**
|
|
590
|
+
* Known unstable product features that must be opted into explicitly.
|
|
591
|
+
* Add new keys here as features graduate from private experiments; remove them
|
|
592
|
+
* once they become stable defaults.
|
|
593
|
+
*/
|
|
594
|
+
const EXPERIMENTAL_FEATURES = [
|
|
595
|
+
"operator-tools",
|
|
596
|
+
"passive-routing",
|
|
597
|
+
"user-customization"
|
|
598
|
+
];
|
|
599
|
+
const EXPERIMENTAL_FEATURE_SET = new Set(EXPERIMENTAL_FEATURES);
|
|
600
|
+
function isExperimentalFeature(value) {
|
|
601
|
+
return EXPERIMENTAL_FEATURE_SET.has(value);
|
|
602
|
+
}
|
|
603
|
+
/** Known feature names mapped to booleans. Unset features stay off. */
|
|
604
|
+
const experimentalSchema = z.record(z.string(), z.unknown()).transform((features, ctx) => {
|
|
605
|
+
const enabled = {};
|
|
606
|
+
for (const [name, value] of Object.entries(features)) {
|
|
607
|
+
if (value === void 0) continue;
|
|
608
|
+
if (typeof value !== "boolean") {
|
|
609
|
+
ctx.addIssue({
|
|
610
|
+
code: "custom",
|
|
611
|
+
...optionCheck(`experimental.${name} must be a boolean when provided`)
|
|
612
|
+
});
|
|
613
|
+
return z.NEVER;
|
|
614
|
+
}
|
|
615
|
+
if (!isExperimentalFeature(name)) {
|
|
616
|
+
ctx.addIssue({
|
|
617
|
+
code: "custom",
|
|
618
|
+
...optionCheck(`experimental.${name} is not a known experimental feature. Known features: ${EXPERIMENTAL_FEATURES.join(", ")}`)
|
|
619
|
+
});
|
|
620
|
+
return z.NEVER;
|
|
621
|
+
}
|
|
622
|
+
enabled[name] = value;
|
|
623
|
+
}
|
|
624
|
+
return enabled;
|
|
625
|
+
}).default({});
|
|
626
|
+
// src/config/kill-switches.ts
|
|
627
|
+
/** Kill switch fields at the top level of the config. */
|
|
628
|
+
const killSwitchFields = {
|
|
629
|
+
/** Kill switch for prompt cache warming. Defaults to true. */
|
|
630
|
+
cacheWarmingEnabled: z.boolean().default(true),
|
|
631
|
+
/**
|
|
632
|
+
* Kill switch for compaction on idle: a warmup of a prefix at or above the
|
|
633
|
+
* background compaction mark swaps in a ready background summary instead.
|
|
634
|
+
* Defaults to true. It runs only while cache warming is on.
|
|
635
|
+
*/
|
|
636
|
+
idleCompactionEnabled: z.boolean().default(true),
|
|
637
|
+
conversationWorkEnabled: z.boolean().default(true)
|
|
638
|
+
};
|
|
639
|
+
/** Env var that sets each kill switch, for error messages. */
|
|
640
|
+
const killSwitchEnvNames = {
|
|
641
|
+
cacheWarmingEnabled: "JUNIOR_CACHE_WARMING_ENABLED",
|
|
642
|
+
idleCompactionEnabled: "JUNIOR_IDLE_COMPACTION_ENABLED",
|
|
643
|
+
conversationWorkEnabled: "JUNIOR_CONVERSATION_WORK_ENABLED"
|
|
644
|
+
};
|
|
645
|
+
function parseKillSwitch(name, rawValue) {
|
|
646
|
+
const value = toOptionalTrimmed(rawValue)?.toLowerCase();
|
|
647
|
+
if (value === void 0 || value === "true") return true;
|
|
648
|
+
if (value === "false") return false;
|
|
649
|
+
throw new Error(`${name} must be true or false`);
|
|
650
|
+
}
|
|
651
|
+
/** Read the kill switches from env. */
|
|
652
|
+
function readKillSwitchesEnv(env) {
|
|
653
|
+
return {
|
|
654
|
+
cacheWarmingEnabled: parseKillSwitch("JUNIOR_CACHE_WARMING_ENABLED", env["JUNIOR_CACHE_WARMING_ENABLED"]),
|
|
655
|
+
idleCompactionEnabled: parseKillSwitch("JUNIOR_IDLE_COMPACTION_ENABLED", env["JUNIOR_IDLE_COMPACTION_ENABLED"]),
|
|
656
|
+
conversationWorkEnabled: parseKillSwitch("JUNIOR_CONVERSATION_WORK_ENABLED", env["JUNIOR_CONVERSATION_WORK_ENABLED"])
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
// src/config/memory.ts
|
|
660
|
+
/** Memory settings. */
|
|
661
|
+
const memorySchema = z.strictObject({
|
|
662
|
+
/** Disable automatic prompt recall while keeping explicit memory tools available. */
|
|
663
|
+
disableRecall: z.boolean().optional(),
|
|
664
|
+
/** Disable passive memory extraction from completed sessions. */
|
|
665
|
+
disableExtraction: z.boolean().optional(),
|
|
666
|
+
/** Model for extraction and supersession. Unset uses the app structured model. */
|
|
667
|
+
modelId: z.string().optional()
|
|
668
|
+
}).prefault({});
|
|
669
|
+
/** Read the memory group from env. */
|
|
670
|
+
function readMemoryEnv(env) {
|
|
671
|
+
return { modelId: toOptionalTrimmed(env["AI_MEMORY_MODEL"]) };
|
|
672
|
+
}
|
|
673
|
+
// src/config/queue.ts
|
|
674
|
+
function isHttpUrl(value) {
|
|
675
|
+
const protocol = URL.parse(value)?.protocol;
|
|
676
|
+
return protocol === "http:" || protocol === "https:";
|
|
677
|
+
}
|
|
678
|
+
/** Vercel Queues settings. */
|
|
679
|
+
const queueSchema = z.strictObject({
|
|
680
|
+
/** Vercel Queues API base URL, for a local queue server. */
|
|
681
|
+
apiUrl: z.string().refine(isHttpUrl, "must be an http or https URL").optional(),
|
|
682
|
+
/**
|
|
683
|
+
* Topic for conversation wake-up nudges, when it is not the default. The
|
|
684
|
+
* build reads the same env var for the queue trigger, so both stay on one
|
|
685
|
+
* topic.
|
|
686
|
+
*/
|
|
687
|
+
conversationWorkTopic: z.string().optional()
|
|
688
|
+
}).prefault({});
|
|
689
|
+
/** Env var that sets each queue field, for error messages. */
|
|
690
|
+
const queueEnvNames = { "queue.apiUrl": "JUNIOR_QUEUE_API_URL" };
|
|
691
|
+
function parseQueueApiUrl(rawValue) {
|
|
692
|
+
const value = toOptionalTrimmed(rawValue);
|
|
693
|
+
if (value === void 0 || isHttpUrl(value)) return value;
|
|
694
|
+
throw new Error("JUNIOR_QUEUE_API_URL must be an http or https URL");
|
|
695
|
+
}
|
|
696
|
+
/** Read the queue group from env. */
|
|
697
|
+
function readQueueEnv(env) {
|
|
698
|
+
return {
|
|
699
|
+
apiUrl: parseQueueApiUrl(env["JUNIOR_QUEUE_API_URL"]),
|
|
700
|
+
conversationWorkTopic: env["JUNIOR_CONVERSATION_WORK_QUEUE_TOPIC"]?.trim() || void 0
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
// src/config/sandbox.ts
|
|
704
|
+
const DEFAULT_SNAPSHOT_FLOATING_MAX_AGE_MS = 6048e5;
|
|
705
|
+
/** The sandbox provider and its settings. */
|
|
706
|
+
const sandboxSchema = z.strictObject({
|
|
707
|
+
/** Sandbox provider for this deployment. `docker` is for local development. */
|
|
708
|
+
provider: z.enum(["vercel", "docker"]).default("vercel"),
|
|
709
|
+
/**
|
|
710
|
+
* vCPUs of each sandbox. A Workspace vCPU count wins over it. Env only
|
|
711
|
+
* sets valid values, so the check reaches only `createApp({ sandbox })`.
|
|
712
|
+
*/
|
|
713
|
+
vcpus: z.custom((value) => Number.isSafeInteger(value) && Number(value) > 0, optionCheck("sandbox.vcpus must be a positive integer")).optional(),
|
|
714
|
+
/** Sandbox keepalive in ms. 0 turns it off. */
|
|
715
|
+
keepAliveMs: z.number().default(0),
|
|
716
|
+
/** Settings of the local Docker provider. */
|
|
717
|
+
docker: z.strictObject({
|
|
718
|
+
/** `DOCKER_HOST`. The provider accepts only `unix://` sockets. */
|
|
719
|
+
host: z.string().optional(),
|
|
720
|
+
/** Directory for machine-wide provider files, such as the egress CA key. */
|
|
721
|
+
dir: z.string().optional(),
|
|
722
|
+
/** PEM file with more CA certificates for each sandbox to trust. */
|
|
723
|
+
extraCaCertsFile: z.string().optional()
|
|
724
|
+
}).prefault({}),
|
|
725
|
+
/**
|
|
726
|
+
* Explicit Vercel Sandbox credentials. Junior uses them only when all
|
|
727
|
+
* three are set; otherwise the SDK reads ambient Vercel auth.
|
|
728
|
+
*/
|
|
729
|
+
vercel: z.strictObject({
|
|
730
|
+
token: z.string().optional(),
|
|
731
|
+
teamId: z.string().optional(),
|
|
732
|
+
projectId: z.string().optional()
|
|
733
|
+
}).prefault({}),
|
|
734
|
+
snapshot: z.strictObject({
|
|
735
|
+
/** Age in ms after which a snapshot with floating inputs is rebuilt. */
|
|
736
|
+
floatingMaxAgeMs: z.number().default(DEFAULT_SNAPSHOT_FLOATING_MAX_AGE_MS),
|
|
737
|
+
/** Changing this value rebuilds every snapshot. */
|
|
738
|
+
rebuildEpoch: z.string().default("")
|
|
739
|
+
}).prefault({})
|
|
740
|
+
}).prefault({});
|
|
741
|
+
/** Env var that sets each sandbox field, for error messages. */
|
|
742
|
+
const sandboxEnvNames = { "sandbox.provider": "JUNIOR_SANDBOX_PROVIDER" };
|
|
743
|
+
function parseVcpus(rawValue) {
|
|
744
|
+
const value = rawValue?.trim();
|
|
745
|
+
if (!value || !/^\d+$/.test(value)) return;
|
|
746
|
+
const vcpus = Number(value);
|
|
747
|
+
return Number.isSafeInteger(vcpus) && vcpus > 0 ? vcpus : void 0;
|
|
748
|
+
}
|
|
749
|
+
function parseKeepAliveMs(rawValue) {
|
|
750
|
+
const parsed = Number.parseInt(rawValue ?? "0", 10);
|
|
751
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
|
|
752
|
+
}
|
|
753
|
+
function parseFloatingMaxAgeMs(rawValue) {
|
|
754
|
+
if (!rawValue?.trim()) return DEFAULT_SNAPSHOT_FLOATING_MAX_AGE_MS;
|
|
755
|
+
const parsed = Number.parseInt(rawValue, 10);
|
|
756
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_SNAPSHOT_FLOATING_MAX_AGE_MS;
|
|
757
|
+
}
|
|
758
|
+
/** Read the sandbox group from env. */
|
|
759
|
+
function readSandboxEnv(env) {
|
|
760
|
+
return {
|
|
761
|
+
provider: env["JUNIOR_SANDBOX_PROVIDER"]?.trim().toLowerCase() === "docker" ? "docker" : void 0,
|
|
762
|
+
vcpus: parseVcpus(env["SANDBOX_VCPUS"]),
|
|
763
|
+
keepAliveMs: parseKeepAliveMs(env["VERCEL_SANDBOX_KEEPALIVE_MS"]),
|
|
764
|
+
docker: {
|
|
765
|
+
host: env["DOCKER_HOST"]?.trim() || void 0,
|
|
766
|
+
dir: env["JUNIOR_DOCKER_SANDBOX_DIR"]?.trim() || void 0,
|
|
767
|
+
extraCaCertsFile: env["JUNIOR_DOCKER_SANDBOX_EXTRA_CA_CERTS"]?.trim() || void 0
|
|
768
|
+
},
|
|
769
|
+
vercel: {
|
|
770
|
+
token: toOptionalTrimmed(env["VERCEL_TOKEN"]),
|
|
771
|
+
teamId: toOptionalTrimmed(env["VERCEL_TEAM_ID"]),
|
|
772
|
+
projectId: toOptionalTrimmed(env["VERCEL_PROJECT_ID"])
|
|
773
|
+
},
|
|
774
|
+
snapshot: {
|
|
775
|
+
floatingMaxAgeMs: parseFloatingMaxAgeMs(env["SANDBOX_SNAPSHOT_FLOATING_MAX_AGE_MS"]),
|
|
776
|
+
rebuildEpoch: env["SANDBOX_SNAPSHOT_REBUILD_EPOCH"]?.trim() ?? ""
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
// src/config/secrets.ts
|
|
781
|
+
/** Secrets that sign internal tokens and authenticate cron requests. */
|
|
782
|
+
const secretsSchema = z.strictObject({
|
|
783
|
+
/** Signs internal tokens and payloads. */
|
|
784
|
+
juniorSecret: z.string().optional(),
|
|
785
|
+
/** Bearer secret that internal cron requests must send. */
|
|
786
|
+
schedulerSecret: z.string().optional()
|
|
787
|
+
}).prefault({});
|
|
788
|
+
/** Read the secrets group from env. */
|
|
789
|
+
function readSecretsEnv(env) {
|
|
790
|
+
return {
|
|
791
|
+
juniorSecret: env["JUNIOR_SECRET"]?.trim() || void 0,
|
|
792
|
+
schedulerSecret: env["JUNIOR_SCHEDULER_SECRET"]?.trim() || env["CRON_SECRET"]?.trim()
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
// src/config/sign-in.ts
|
|
796
|
+
/** Dashboard Google sign-in, and the domains that may use Junior. */
|
|
797
|
+
const signInSchema = z.strictObject({
|
|
798
|
+
/**
|
|
799
|
+
* `JUNIOR_ALLOWED_DOMAINS` as set. The trust group parses it when the
|
|
800
|
+
* `createApp` option is unset.
|
|
801
|
+
*/
|
|
802
|
+
allowedDomains: z.string().optional(),
|
|
803
|
+
/** Whether the dashboard requires sign-in when `dashboard.authRequired` is unset. */
|
|
804
|
+
dashboardAuthRequired: z.boolean().default(true),
|
|
805
|
+
googleClientId: z.string().optional(),
|
|
806
|
+
googleClientSecret: z.string().optional(),
|
|
807
|
+
/** Dashboard session secret, as given. */
|
|
808
|
+
secret: z.string().optional(),
|
|
809
|
+
/**
|
|
810
|
+
* `JUNIOR_DASHBOARD_TRUSTED_ORIGINS` as set. Sign-in parses it when the
|
|
811
|
+
* dashboard does not set `trustedOrigins`.
|
|
812
|
+
*/
|
|
813
|
+
trustedOrigins: z.string().optional()
|
|
814
|
+
}).prefault({});
|
|
815
|
+
/** Read the sign-in group from env. */
|
|
816
|
+
function readSignInEnv(env) {
|
|
817
|
+
if (env["JUNIOR_DASHBOARD_GOOGLE_DOMAINS"]?.trim()) throw new Error("JUNIOR_DASHBOARD_GOOGLE_DOMAINS was removed; set JUNIOR_ALLOWED_DOMAINS instead");
|
|
818
|
+
return {
|
|
819
|
+
allowedDomains: env["JUNIOR_ALLOWED_DOMAINS"],
|
|
820
|
+
dashboardAuthRequired: env["JUNIOR_DASHBOARD_AUTH_REQUIRED"]?.trim() !== "false",
|
|
821
|
+
googleClientId: env["GOOGLE_CLIENT_ID"],
|
|
822
|
+
googleClientSecret: env["GOOGLE_CLIENT_SECRET"],
|
|
823
|
+
secret: env["BETTER_AUTH_SECRET"] ?? env["JUNIOR_SECRET"],
|
|
824
|
+
trustedOrigins: env["JUNIOR_DASHBOARD_TRUSTED_ORIGINS"]
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
// src/config/skills.ts
|
|
828
|
+
/** Skill discovery settings. */
|
|
829
|
+
const skillsSchema = z.strictObject({
|
|
830
|
+
/** Extra skill roots, searched before the default and plugin roots. */
|
|
831
|
+
dirs: z.array(z.string()).default([]) }).prefault({});
|
|
832
|
+
/** Read the skills group from env. `SKILL_DIRS` uses the OS path delimiter. */
|
|
833
|
+
function readSkillsEnv(env) {
|
|
834
|
+
return { dirs: env["SKILL_DIRS"]?.split(path.delimiter).filter(Boolean) };
|
|
835
|
+
}
|
|
836
|
+
// src/chat/slack/emoji.ts
|
|
837
|
+
const SLACK_EMOJI_NAME_RE = /^(?:[a-z0-9_+-]+)(?:::(?:skin-tone-[2-6]))?$/;
|
|
838
|
+
function normalizeSlackEmojiName(value) {
|
|
839
|
+
const trimmed = value.trim().toLowerCase();
|
|
840
|
+
if (!trimmed) return null;
|
|
841
|
+
const normalized = trimmed.startsWith(":") && trimmed.endsWith(":") ? trimmed.slice(1, -1) : trimmed;
|
|
842
|
+
return SLACK_EMOJI_NAME_RE.test(normalized) ? normalized : null;
|
|
843
|
+
}
|
|
844
|
+
// src/config/slack.ts
|
|
845
|
+
const DEFAULT_PROCESSING_REACTION_EMOJI = "eyes";
|
|
846
|
+
const DEFAULT_COMPLETED_REACTION_EMOJI = "white_check_mark";
|
|
847
|
+
function reactionEmoji(option, defaultEmoji) {
|
|
848
|
+
return z.string().transform((value, ctx) => {
|
|
849
|
+
if (!value.trim()) return defaultEmoji;
|
|
850
|
+
const normalized = normalizeSlackEmojiName(value);
|
|
851
|
+
if (normalized) return normalized;
|
|
852
|
+
ctx.addIssue({
|
|
853
|
+
code: "custom",
|
|
854
|
+
...optionCheck(`${option} must be a valid Slack emoji name (for example "eyes" or ":white_check_mark:")`)
|
|
855
|
+
});
|
|
856
|
+
return z.NEVER;
|
|
857
|
+
}).default(defaultEmoji);
|
|
858
|
+
}
|
|
859
|
+
/** The Slack app credentials and reaction emojis. */
|
|
860
|
+
const slackSchema = z.strictObject({
|
|
861
|
+
botToken: z.string().optional(),
|
|
862
|
+
clientId: z.string().optional(),
|
|
863
|
+
clientSecret: z.string().optional(),
|
|
864
|
+
completedReactionEmoji: reactionEmoji("completedReactionEmoji", DEFAULT_COMPLETED_REACTION_EMOJI),
|
|
865
|
+
processingReactionEmoji: reactionEmoji("processingReactionEmoji", DEFAULT_PROCESSING_REACTION_EMOJI),
|
|
866
|
+
signingSecret: z.string().optional()
|
|
867
|
+
}).prefault({});
|
|
868
|
+
/** Env var that sets each Slack field, for error messages. */
|
|
869
|
+
const slackEnvNames = {
|
|
870
|
+
"slack.botToken": "SLACK_BOT_TOKEN",
|
|
871
|
+
"slack.clientId": "SLACK_CLIENT_ID",
|
|
872
|
+
"slack.clientSecret": "SLACK_CLIENT_SECRET",
|
|
873
|
+
"slack.signingSecret": "SLACK_SIGNING_SECRET"
|
|
874
|
+
};
|
|
875
|
+
/** Read the Slack group from env. */
|
|
876
|
+
function readSlackEnv(env) {
|
|
877
|
+
return {
|
|
878
|
+
botToken: toOptionalTrimmed(env["SLACK_BOT_TOKEN"]) ?? toOptionalTrimmed(env["SLACK_BOT_USER_TOKEN"]),
|
|
879
|
+
clientId: toOptionalTrimmed(env["SLACK_CLIENT_ID"]),
|
|
880
|
+
clientSecret: toOptionalTrimmed(env["SLACK_CLIENT_SECRET"]),
|
|
881
|
+
signingSecret: toOptionalTrimmed(env["SLACK_SIGNING_SECRET"])
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
// src/config/sql.ts
|
|
885
|
+
/** Default SQL statement timeout. */
|
|
886
|
+
const DEFAULT_SQL_STATEMENT_TIMEOUT_MS = 3e4;
|
|
887
|
+
/** The database. No prefault: the database URL has no default. */
|
|
888
|
+
const sqlSchema = z.strictObject({
|
|
889
|
+
databaseUrl: z.string().trim().min(1),
|
|
890
|
+
driver: z.enum(["neon", "postgres"]).optional(),
|
|
891
|
+
statementTimeoutMs: z.union([positiveInt, z.literal(false)]).default(DEFAULT_SQL_STATEMENT_TIMEOUT_MS)
|
|
892
|
+
});
|
|
893
|
+
/** Env var that sets each SQL field, for error messages. */
|
|
894
|
+
const sqlEnvNames = {
|
|
895
|
+
"sql.databaseUrl": "DATABASE_URL",
|
|
896
|
+
"sql.driver": "JUNIOR_DATABASE_DRIVER",
|
|
897
|
+
"sql.statementTimeoutMs": "JUNIOR_SQL_STATEMENT_TIMEOUT_MS"
|
|
898
|
+
};
|
|
899
|
+
function parseSqlDriver(rawValue) {
|
|
900
|
+
const value = toOptionalTrimmed(rawValue);
|
|
901
|
+
if (value === void 0 || value === "neon" || value === "postgres") return value;
|
|
902
|
+
throw new Error("JUNIOR_DATABASE_DRIVER must be postgres or neon");
|
|
903
|
+
}
|
|
904
|
+
function parseSqlStatementTimeoutMs(rawValue) {
|
|
905
|
+
const trimmed = toOptionalTrimmed(rawValue);
|
|
906
|
+
if (trimmed === void 0) return;
|
|
907
|
+
const value = Number.parseInt(trimmed, 10);
|
|
908
|
+
if (!Number.isSafeInteger(value) || value < 0 || String(value) !== trimmed) throw new Error("JUNIOR_SQL_STATEMENT_TIMEOUT_MS must be a non-negative integer");
|
|
909
|
+
return value === 0 ? false : value;
|
|
910
|
+
}
|
|
911
|
+
/** Read the SQL group from env. */
|
|
912
|
+
function readSqlEnv(env) {
|
|
913
|
+
return {
|
|
914
|
+
databaseUrl: toOptionalTrimmed(env["DATABASE_URL"]),
|
|
915
|
+
driver: parseSqlDriver(env["JUNIOR_DATABASE_DRIVER"]),
|
|
916
|
+
statementTimeoutMs: parseSqlStatementTimeoutMs(env["JUNIOR_SQL_STATEMENT_TIMEOUT_MS"])
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
function defaultSqlDriver(databaseUrl) {
|
|
920
|
+
try {
|
|
921
|
+
const { hostname } = new URL(databaseUrl);
|
|
922
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" ? "postgres" : "neon";
|
|
923
|
+
} catch {
|
|
924
|
+
return "neon";
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
/** Default the driver from the database URL. */
|
|
928
|
+
function deriveSql(sql) {
|
|
929
|
+
return {
|
|
930
|
+
...sql,
|
|
931
|
+
driver: sql.driver ?? defaultSqlDriver(sql.databaseUrl)
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
// src/config/state.ts
|
|
935
|
+
/** The state adapter. */
|
|
936
|
+
const stateSchema = z.strictObject({
|
|
937
|
+
adapter: z.enum(["memory", "redis"]).default("redis"),
|
|
938
|
+
keyPrefix: z.string().optional(),
|
|
939
|
+
redisUrl: z.string().optional()
|
|
940
|
+
}).prefault({});
|
|
941
|
+
/** Env var that sets each state field, for error messages. */
|
|
942
|
+
const stateEnvNames = {
|
|
943
|
+
"state.adapter": "JUNIOR_STATE_ADAPTER",
|
|
944
|
+
"state.keyPrefix": "JUNIOR_STATE_KEY_PREFIX",
|
|
945
|
+
"state.redisUrl": "REDIS_URL"
|
|
946
|
+
};
|
|
947
|
+
/** Read the state group from env. */
|
|
948
|
+
function readStateEnv(env) {
|
|
949
|
+
return {
|
|
950
|
+
adapter: env["JUNIOR_STATE_ADAPTER"]?.trim().toLowerCase() === "memory" ? "memory" : void 0,
|
|
951
|
+
keyPrefix: toOptionalTrimmed(env["JUNIOR_STATE_KEY_PREFIX"]),
|
|
952
|
+
redisUrl: toOptionalTrimmed(env["REDIS_URL"])
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
// src/config/env-list.ts
|
|
956
|
+
/**
|
|
957
|
+
* Parse a list env var value: a JSON string array or comma-separated values.
|
|
958
|
+
* Comma-separated entries are trimmed, and empty entries are dropped.
|
|
959
|
+
*/
|
|
960
|
+
function parseEnvList(name, rawValue) {
|
|
961
|
+
const value = rawValue?.trim();
|
|
962
|
+
if (!value) return void 0;
|
|
963
|
+
if (!value.startsWith("[")) return value.split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
964
|
+
let parsed;
|
|
965
|
+
try {
|
|
966
|
+
parsed = JSON.parse(value);
|
|
967
|
+
} catch (error) {
|
|
968
|
+
throw new Error(`${name} must be a JSON string array`, { cause: error });
|
|
969
|
+
}
|
|
970
|
+
const list = z.array(z.string()).safeParse(parsed);
|
|
971
|
+
if (!list.success) throw new Error(`${name} must be a JSON string array`);
|
|
972
|
+
return list.data;
|
|
973
|
+
}
|
|
974
|
+
// src/config/trust.ts
|
|
975
|
+
/** The `createApp` settings that decide who is trusted. */
|
|
976
|
+
const trustSchema = z.strictObject({
|
|
977
|
+
/** `createApp({ slack: { allowedBotUserIds } })`: trusted without a profile email. */
|
|
978
|
+
allowedBotUserIds: z.array(z.string()).default([]),
|
|
979
|
+
/** `createApp({ allowedDomains })`. Unset falls back to `JUNIOR_ALLOWED_DOMAINS`. */
|
|
980
|
+
allowedDomains: z.array(z.string()).optional()
|
|
981
|
+
}).prefault({});
|
|
982
|
+
/**
|
|
983
|
+
* Resolve the allowed domains: the `createApp` option when set, else
|
|
984
|
+
* `JUNIOR_ALLOWED_DOMAINS`. An empty list allows every domain.
|
|
985
|
+
*/
|
|
986
|
+
function deriveTrust(trust, allowedDomainsEnv) {
|
|
987
|
+
return {
|
|
988
|
+
allowedBotUserIds: trust.allowedBotUserIds,
|
|
989
|
+
allowedDomains: [...new Set((trust.allowedDomains ?? parseEnvList("JUNIOR_ALLOWED_DOMAINS", allowedDomainsEnv) ?? []).map((value) => value.trim().toLowerCase()).filter(Boolean))]
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
// src/config/web-push.ts
|
|
993
|
+
/** VAPID settings for web push notifications. */
|
|
994
|
+
const webPushSchema = z.strictObject({
|
|
995
|
+
privateKey: z.string().optional(),
|
|
996
|
+
publicKey: z.string().optional(),
|
|
997
|
+
subject: z.string().optional()
|
|
998
|
+
}).prefault({});
|
|
999
|
+
/** Read the web push group from env. */
|
|
1000
|
+
function readWebPushEnv(env) {
|
|
1001
|
+
return {
|
|
1002
|
+
privateKey: env["JUNIOR_WEB_PUSH_PRIVATE_KEY"]?.trim(),
|
|
1003
|
+
publicKey: env["JUNIOR_WEB_PUSH_PUBLIC_KEY"]?.trim(),
|
|
1004
|
+
subject: env["JUNIOR_WEB_PUSH_SUBJECT"]?.trim()
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
// src/config/index.ts
|
|
1008
|
+
const configSchema = z.strictObject({
|
|
1009
|
+
/** Object storage for attachments and public artifacts. */
|
|
1010
|
+
attachmentStorage: attachmentStorageSchema.default({ provider: "vercel-blob" }),
|
|
1011
|
+
bot: botSchema.prefault({}),
|
|
1012
|
+
configDefaults: configDefaultsSchema,
|
|
1013
|
+
dashboard: dashboardSchema,
|
|
1014
|
+
deployment: deploymentSchema,
|
|
1015
|
+
development: developmentSchema,
|
|
1016
|
+
eventEmbeddings: eventEmbeddingsSchema,
|
|
1017
|
+
experimental: experimentalSchema,
|
|
1018
|
+
memory: memorySchema,
|
|
1019
|
+
queue: queueSchema,
|
|
1020
|
+
functionMaxDurationSeconds: functionMaxDurationSecondsSchema,
|
|
1021
|
+
limits: limitsSchema.optional(),
|
|
1022
|
+
...killSwitchFields,
|
|
1023
|
+
encryption: encryptionSchema,
|
|
1024
|
+
secrets: secretsSchema,
|
|
1025
|
+
signIn: signInSchema,
|
|
1026
|
+
webPush: webPushSchema,
|
|
1027
|
+
sql: sqlSchema,
|
|
1028
|
+
slack: slackSchema,
|
|
1029
|
+
sandbox: sandboxSchema,
|
|
1030
|
+
skills: skillsSchema,
|
|
1031
|
+
state: stateSchema,
|
|
1032
|
+
trust: trustSchema
|
|
1033
|
+
}).transform(derive);
|
|
1034
|
+
function derive({ limits = {}, ...config }) {
|
|
1035
|
+
const { bot, deployment, functionMaxDurationSeconds, signIn, sql, trust } = config;
|
|
1036
|
+
return {
|
|
1037
|
+
...config,
|
|
1038
|
+
bot: deriveBot(bot, limits, functionMaxDurationSeconds),
|
|
1039
|
+
deployment: deriveDeployment(deployment),
|
|
1040
|
+
conversationWorkSoftYieldAfterMs: resolveConversationWorkSoftYieldAfterMs(functionMaxDurationSeconds),
|
|
1041
|
+
sql: deriveSql(sql),
|
|
1042
|
+
trust: deriveTrust(trust, signIn.allowedDomains)
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
/** Env var that sets each config field, for error messages. */
|
|
1046
|
+
const ENV_NAMES = {
|
|
1047
|
+
...botEnvNames,
|
|
1048
|
+
...attachmentStorageEnvNames,
|
|
1049
|
+
...queueEnvNames,
|
|
1050
|
+
...killSwitchEnvNames,
|
|
1051
|
+
...encryptionEnvNames,
|
|
1052
|
+
...sqlEnvNames,
|
|
1053
|
+
...slackEnvNames,
|
|
1054
|
+
...sandboxEnvNames,
|
|
1055
|
+
...stateEnvNames
|
|
1056
|
+
};
|
|
1057
|
+
function readEnv(env) {
|
|
1058
|
+
return {
|
|
1059
|
+
attachmentStorage: readAttachmentStorage(env),
|
|
1060
|
+
bot: readBotEnv(env),
|
|
1061
|
+
deployment: readDeploymentEnv(env),
|
|
1062
|
+
development: readDevelopmentEnv(env),
|
|
1063
|
+
memory: readMemoryEnv(env),
|
|
1064
|
+
queue: readQueueEnv(env),
|
|
1065
|
+
...readKillSwitchesEnv(env),
|
|
1066
|
+
encryption: readEncryption(env),
|
|
1067
|
+
secrets: readSecretsEnv(env),
|
|
1068
|
+
signIn: readSignInEnv(env),
|
|
1069
|
+
webPush: readWebPushEnv(env),
|
|
1070
|
+
sql: readSqlEnv(env),
|
|
1071
|
+
slack: readSlackEnv(env),
|
|
1072
|
+
sandbox: readSandboxEnv(env),
|
|
1073
|
+
skills: readSkillsEnv(env),
|
|
1074
|
+
state: readStateEnv(env)
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
const plainObjectSchema = z.record(z.string(), z.unknown());
|
|
1078
|
+
function mergeConfig(a, b) {
|
|
1079
|
+
if (b === void 0) return a;
|
|
1080
|
+
const left = plainObjectSchema.safeParse(a);
|
|
1081
|
+
const right = plainObjectSchema.safeParse(b);
|
|
1082
|
+
if (!left.success || !right.success || right.data["provider"] !== void 0 && right.data["provider"] !== left.data["provider"]) return b;
|
|
1083
|
+
const merged = {};
|
|
1084
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(left.data), ...Object.keys(right.data)])) {
|
|
1085
|
+
const value = mergeConfig(left.data[key], right.data[key]);
|
|
1086
|
+
if (value !== void 0) merged[key] = value;
|
|
1087
|
+
}
|
|
1088
|
+
return merged;
|
|
1089
|
+
}
|
|
1090
|
+
function valueAt(input, path) {
|
|
1091
|
+
let value = input;
|
|
1092
|
+
for (const key of path) {
|
|
1093
|
+
const object = plainObjectSchema.safeParse(value);
|
|
1094
|
+
if (!object.success || typeof key === "symbol") return;
|
|
1095
|
+
value = object.data[String(key)];
|
|
1096
|
+
}
|
|
1097
|
+
return value;
|
|
1098
|
+
}
|
|
1099
|
+
function envNameFor(path) {
|
|
1100
|
+
const keys = path.filter((key) => typeof key === "string");
|
|
1101
|
+
for (let length = keys.length; length > 0; length--) {
|
|
1102
|
+
const envName = ENV_NAMES[keys.slice(0, length).join(".")];
|
|
1103
|
+
if (envName) return envName;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
function formatIssue(input, issue) {
|
|
1107
|
+
if (issue.code === "custom" && issue.params?.["option"] === true) return issue.message;
|
|
1108
|
+
const path = issue.path.map(String).join(".");
|
|
1109
|
+
const envName = envNameFor(issue.path);
|
|
1110
|
+
if (issue.code === "invalid_type" && valueAt(input, issue.path) === void 0) {
|
|
1111
|
+
const required = `${envName ?? path} is required`;
|
|
1112
|
+
return path === "encryption" ? `${required}. ${ENCRYPTION_KEYS_HINT}` : required;
|
|
1113
|
+
}
|
|
1114
|
+
return `${envName ? `${path} (${envName})` : path}: ${issue.message}`;
|
|
1115
|
+
}
|
|
1116
|
+
/** Resolve config: host options win over env, and the schema fills defaults. */
|
|
1117
|
+
function loadConfig({ env = {}, options = {} } = {}) {
|
|
1118
|
+
const input = mergeConfig(readEnv(env), options);
|
|
1119
|
+
const result = configSchema.safeParse(input);
|
|
1120
|
+
if (!result.success) throw new Error(result.error.issues.map((issue) => formatIssue(input, issue)).join("; "));
|
|
1121
|
+
return result.data;
|
|
1122
|
+
}
|
|
1123
|
+
// src/chat/config.ts
|
|
1124
|
+
let installed;
|
|
1125
|
+
/**
|
|
1126
|
+
* Return the config that createApp installed. Without one, such as in the
|
|
1127
|
+
* CLI, load it from `process.env` on the first read and keep it.
|
|
1128
|
+
*/
|
|
1129
|
+
function getChatConfig() {
|
|
1130
|
+
installed ??= loadConfig({ env: process.env });
|
|
1131
|
+
return installed;
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* Install the config that createApp resolved. Returns the previous config,
|
|
1135
|
+
* so a failed startup can install it again. `undefined` loads from env again
|
|
1136
|
+
* on the next read.
|
|
1137
|
+
*/
|
|
1138
|
+
function installChatConfig(config) {
|
|
1139
|
+
const previous = installed;
|
|
1140
|
+
installed = config;
|
|
1141
|
+
return previous;
|
|
1142
|
+
}
|
|
1143
|
+
function isBotConfigKey(bot, key) {
|
|
1144
|
+
return Object.hasOwn(bot, key);
|
|
1145
|
+
}
|
|
1146
|
+
/**
|
|
1147
|
+
* Bot settings of the current config. Readers keep this object, so it
|
|
1148
|
+
* forwards every read and write to `getChatConfig().bot`.
|
|
1149
|
+
*
|
|
1150
|
+
* Temporary: callers read `botConfig` as a plain property, so lazy loading
|
|
1151
|
+
* needs a read trap. Remove this Proxy once config is passed in explicitly.
|
|
1152
|
+
*/
|
|
1153
|
+
const botConfig = new Proxy({}, {
|
|
1154
|
+
defineProperty: (_, key, descriptor) => Reflect.defineProperty(getChatConfig().bot, key, descriptor),
|
|
1155
|
+
deleteProperty: (_, key) => Reflect.deleteProperty(getChatConfig().bot, key),
|
|
1156
|
+
get: (_, key) => {
|
|
1157
|
+
const bot = getChatConfig().bot;
|
|
1158
|
+
return isBotConfigKey(bot, key) ? bot[key] : void 0;
|
|
1159
|
+
},
|
|
1160
|
+
getOwnPropertyDescriptor: (_, key) => Reflect.getOwnPropertyDescriptor(getChatConfig().bot, key),
|
|
1161
|
+
has: (_, key) => Reflect.has(getChatConfig().bot, key),
|
|
1162
|
+
ownKeys: () => Reflect.ownKeys(getChatConfig().bot),
|
|
1163
|
+
set: (_, key, value) => Reflect.set(getChatConfig().bot, key, value)
|
|
1164
|
+
});
|
|
1165
|
+
function getSlackBotToken() {
|
|
1166
|
+
return getChatConfig().slack.botToken;
|
|
1167
|
+
}
|
|
1168
|
+
function getSlackSigningSecret() {
|
|
1169
|
+
return getChatConfig().slack.signingSecret;
|
|
1170
|
+
}
|
|
1171
|
+
function getSlackClientId() {
|
|
1172
|
+
return getChatConfig().slack.clientId;
|
|
1173
|
+
}
|
|
1174
|
+
function getSlackClientSecret() {
|
|
1175
|
+
return getChatConfig().slack.clientSecret;
|
|
1176
|
+
}
|
|
1177
|
+
/** Return runtime metadata (version from deploy environment). */
|
|
1178
|
+
function getRuntimeMetadata() {
|
|
1179
|
+
return { version: getChatConfig().deployment.commitSha };
|
|
1180
|
+
}
|
|
1181
|
+
// src/chat/slack/timestamp.ts
|
|
1182
|
+
/** Native Slack message timestamp, safe to pass as Slack Web API `message_ts`. */
|
|
1183
|
+
const slackMessageTsSchema = z.string().trim().regex(/^\d+(?:\.\d+)?$/).brand();
|
|
1184
|
+
/** Parse a native Slack message timestamp from untrusted message metadata. */
|
|
1185
|
+
function parseSlackMessageTs(value) {
|
|
1186
|
+
const parsed = slackMessageTsSchema.safeParse(value);
|
|
1187
|
+
return parsed.success ? parsed.data : void 0;
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
* Write a time in milliseconds as a Slack timestamp, for input that has no
|
|
1191
|
+
* Slack message of its own, such as a submitted form.
|
|
1192
|
+
*/
|
|
1193
|
+
function slackMessageTsFromMs(ms) {
|
|
1194
|
+
return slackMessageTsSchema.parse((ms / 1e3).toFixed(6));
|
|
1195
|
+
}
|
|
1196
|
+
// src/chat/slack/ids.ts
|
|
1197
|
+
const slackChannelIdSchema = z.string().regex(/^[CDG][A-Z0-9]+$/).brand();
|
|
1198
|
+
const slackTeamIdSchema = z.string().regex(/^T[A-Z0-9]+$/).brand();
|
|
1199
|
+
const slackUserIdSchema = z.string().regex(/^[UW][A-Z0-9]+$/).brand();
|
|
1200
|
+
const slackBotIdSchema = z.string().regex(/^B[A-Z0-9]+$/).brand();
|
|
1201
|
+
const SLACK_CHANNEL_MENTION_RE = /^<#([CDG][A-Z0-9]+)(?:\|[^>]*)?>$/;
|
|
1202
|
+
function slackChannelReferenceCandidate(value) {
|
|
1203
|
+
const trimmed = value.trim();
|
|
1204
|
+
if (!trimmed.startsWith("slack:")) return trimmed;
|
|
1205
|
+
const parts = trimmed.split(":");
|
|
1206
|
+
if (parts.length === 2) return parts[1]?.trim() ?? "";
|
|
1207
|
+
if (parts.length === 3 && parseSlackMessageTs(parts[2])) return parts[1]?.trim() ?? "";
|
|
1208
|
+
return "";
|
|
1209
|
+
}
|
|
1210
|
+
/** Parse an exact Slack channel/conversation ID from untrusted input. */
|
|
1211
|
+
function parseSlackChannelId(value) {
|
|
1212
|
+
if (typeof value !== "string") return void 0;
|
|
1213
|
+
const parsed = slackChannelIdSchema.safeParse(value.trim());
|
|
1214
|
+
return parsed.success ? parsed.data : void 0;
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Parse a channel id from common tool/model reference forms.
|
|
1218
|
+
*
|
|
1219
|
+
* Accepts exact ids (`C123`), Slack mentions (`<#C123>` / `<#C123|name>`),
|
|
1220
|
+
* and Junior slack references (`slack:C123`, `slack:C123:ts`). Plain channel
|
|
1221
|
+
* names are not ids and are rejected here.
|
|
1222
|
+
*/
|
|
1223
|
+
function parseSlackChannelReferenceId(value) {
|
|
1224
|
+
if (typeof value !== "string") return void 0;
|
|
1225
|
+
const trimmed = value.trim();
|
|
1226
|
+
const mentionMatch = SLACK_CHANNEL_MENTION_RE.exec(trimmed);
|
|
1227
|
+
if (mentionMatch?.[1]) return parseSlackChannelId(mentionMatch[1]);
|
|
1228
|
+
return parseSlackChannelId(slackChannelReferenceCandidate(trimmed));
|
|
1229
|
+
}
|
|
1230
|
+
/** Parse a Slack workspace/team ID from untrusted metadata. */
|
|
1231
|
+
function parseSlackTeamId(value) {
|
|
1232
|
+
if (typeof value !== "string") return void 0;
|
|
1233
|
+
const parsed = slackTeamIdSchema.safeParse(value.trim());
|
|
1234
|
+
return parsed.success ? parsed.data : void 0;
|
|
1235
|
+
}
|
|
1236
|
+
/** Parse a Slack user ID from untrusted metadata. */
|
|
1237
|
+
function parseSlackUserId(value) {
|
|
1238
|
+
if (typeof value !== "string") return void 0;
|
|
1239
|
+
const parsed = slackUserIdSchema.safeParse(value.trim());
|
|
1240
|
+
return parsed.success ? parsed.data : void 0;
|
|
1241
|
+
}
|
|
1242
|
+
// src/chat/state/locks.ts
|
|
1243
|
+
const ACTIVE_LOCK_TTL_MS = 9e4;
|
|
1244
|
+
const MUTATION_LOCK_TTL_MS = 1e4;
|
|
1245
|
+
/**
|
|
1246
|
+
* Acquire a lock for long-running work that the queued state adapter should
|
|
1247
|
+
* keep alive while the owning invocation is still making progress.
|
|
1248
|
+
*/
|
|
1249
|
+
async function acquireActiveLock(state, threadId) {
|
|
1250
|
+
return await state.acquireLock(threadId, ACTIVE_LOCK_TTL_MS);
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* Run work under one lock, optionally waiting for the current owner.
|
|
1254
|
+
* `keepAlive` is for multi-store mutations that must retain ownership until all
|
|
1255
|
+
* side effects finish; callers should still fence each blind write.
|
|
1256
|
+
*/
|
|
1257
|
+
async function withLock(state, key, run, options = {}) {
|
|
1258
|
+
const ttlMs = options.ttlMs ?? 9e4;
|
|
1259
|
+
const startedAtMs = Date.now();
|
|
1260
|
+
let lock;
|
|
1261
|
+
while (true) {
|
|
1262
|
+
lock = await state.acquireLock(key, ttlMs);
|
|
1263
|
+
if (lock) break;
|
|
1264
|
+
if (Date.now() - startedAtMs >= (options.waitMs ?? 0)) return { acquired: false };
|
|
1265
|
+
await setTimeout(options.retryMs ?? 25, void 0, { ref: false });
|
|
1266
|
+
}
|
|
1267
|
+
const heartbeat = options.keepAlive ? setInterval(() => void state.extendLock(lock, ttlMs).catch(() => void 0), Math.max(1, Math.floor(ttlMs / 3))) : void 0;
|
|
1268
|
+
heartbeat?.unref();
|
|
1269
|
+
try {
|
|
1270
|
+
return {
|
|
1271
|
+
acquired: true,
|
|
1272
|
+
value: await run(lock)
|
|
1273
|
+
};
|
|
1274
|
+
} finally {
|
|
1275
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
1276
|
+
await state.releaseLock(lock);
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* Prove lock ownership immediately before a blind write.
|
|
1281
|
+
*
|
|
1282
|
+
* Whole-record mutations must stop if their lock expired rather than overwrite
|
|
1283
|
+
* state committed by a newer owner.
|
|
1284
|
+
*/
|
|
1285
|
+
async function fenceLock(state, lock, ttlMs = MUTATION_LOCK_TTL_MS) {
|
|
1286
|
+
if (!await state.extendLock(lock, ttlMs)) throw new Error(`Lock ownership was lost before write for ${lock.threadId}`);
|
|
1287
|
+
}
|
|
1288
|
+
// src/chat/state/adapter.ts
|
|
1289
|
+
var adapter_exports = /* @__PURE__ */ __exportAll({ getStateAdapter: () => getStateAdapter });
|
|
1290
|
+
const ACTIVE_LOCK_HEARTBEAT_MS = 3e4;
|
|
1291
|
+
const REDIS_STATE_KEY_PREFIX = "chat-sdk";
|
|
1292
|
+
let stateAdapter;
|
|
1293
|
+
let redisStateAdapter;
|
|
1294
|
+
/** Lazily connect state operations, including queued-adapter lock heartbeats. */
|
|
1295
|
+
function createConnectingStateAdapter(base) {
|
|
1296
|
+
const connected = async (operation) => {
|
|
1297
|
+
await base.connect();
|
|
1298
|
+
return await operation();
|
|
1299
|
+
};
|
|
1300
|
+
return {
|
|
1301
|
+
appendToList: (key, value, options) => connected(() => base.appendToList(key, value, options)),
|
|
1302
|
+
connect: () => base.connect(),
|
|
1303
|
+
disconnect: () => base.disconnect(),
|
|
1304
|
+
subscribe: (threadId) => connected(() => base.subscribe(threadId)),
|
|
1305
|
+
unsubscribe: (threadId) => connected(() => base.unsubscribe(threadId)),
|
|
1306
|
+
isSubscribed: (threadId) => connected(() => base.isSubscribed(threadId)),
|
|
1307
|
+
acquireLock: (threadId, ttlMs) => connected(() => base.acquireLock(threadId, ttlMs)),
|
|
1308
|
+
releaseLock: (lock) => connected(() => base.releaseLock(lock)),
|
|
1309
|
+
extendLock: (lock, ttlMs) => connected(() => base.extendLock(lock, ttlMs)),
|
|
1310
|
+
forceReleaseLock: (threadId) => connected(() => base.forceReleaseLock(threadId)),
|
|
1311
|
+
enqueue: (threadId, entry, maxSize) => connected(() => base.enqueue(threadId, entry, maxSize)),
|
|
1312
|
+
dequeue: (threadId) => connected(() => base.dequeue(threadId)),
|
|
1313
|
+
queueDepth: (threadId) => connected(() => base.queueDepth(threadId)),
|
|
1314
|
+
get: (key) => connected(() => base.get(key)),
|
|
1315
|
+
getList: (key) => connected(() => base.getList(key)),
|
|
1316
|
+
set: (key, value, ttlMs) => connected(() => base.set(key, value, ttlMs)),
|
|
1317
|
+
setIfNotExists: (key, value, ttlMs) => connected(() => base.setIfNotExists(key, value, ttlMs)),
|
|
1318
|
+
delete: (key) => connected(() => base.delete(key))
|
|
1319
|
+
};
|
|
1320
|
+
}
|
|
1321
|
+
function createPrefixedStateAdapter(base, prefix) {
|
|
1322
|
+
const prefixed = (value) => `${prefix}:${value}`;
|
|
1323
|
+
const unprefixed = (value) => value.startsWith(`${prefix}:`) ? value.slice(prefix.length + 1) : value;
|
|
1324
|
+
const prefixLock = (lock) => ({
|
|
1325
|
+
...lock,
|
|
1326
|
+
threadId: prefixed(lock.threadId)
|
|
1327
|
+
});
|
|
1328
|
+
const unprefixLock = (lock) => ({
|
|
1329
|
+
...lock,
|
|
1330
|
+
threadId: unprefixed(lock.threadId)
|
|
1331
|
+
});
|
|
1332
|
+
return {
|
|
1333
|
+
appendToList: (key, value, options) => base.appendToList(prefixed(key), value, options),
|
|
1334
|
+
connect: () => base.connect(),
|
|
1335
|
+
disconnect: () => base.disconnect(),
|
|
1336
|
+
subscribe: (threadId) => base.subscribe(prefixed(threadId)),
|
|
1337
|
+
unsubscribe: (threadId) => base.unsubscribe(prefixed(threadId)),
|
|
1338
|
+
isSubscribed: (threadId) => base.isSubscribed(prefixed(threadId)),
|
|
1339
|
+
acquireLock: async (threadId, ttlMs) => {
|
|
1340
|
+
const lock = await base.acquireLock(prefixed(threadId), ttlMs);
|
|
1341
|
+
return lock ? unprefixLock(lock) : null;
|
|
1342
|
+
},
|
|
1343
|
+
releaseLock: (lock) => base.releaseLock(prefixLock(lock)),
|
|
1344
|
+
extendLock: async (lock, ttlMs) => {
|
|
1345
|
+
const prefixedLock = prefixLock(lock);
|
|
1346
|
+
const extended = await base.extendLock(prefixedLock, ttlMs);
|
|
1347
|
+
if (extended) lock.expiresAt = prefixedLock.expiresAt;
|
|
1348
|
+
return extended;
|
|
1349
|
+
},
|
|
1350
|
+
forceReleaseLock: (threadId) => base.forceReleaseLock(prefixed(threadId)),
|
|
1351
|
+
enqueue: (threadId, entry, maxSize) => base.enqueue(prefixed(threadId), entry, maxSize),
|
|
1352
|
+
dequeue: (threadId) => base.dequeue(prefixed(threadId)),
|
|
1353
|
+
queueDepth: (threadId) => base.queueDepth(prefixed(threadId)),
|
|
1354
|
+
get: (key) => base.get(prefixed(key)),
|
|
1355
|
+
getList: (key) => base.getList(prefixed(key)),
|
|
1356
|
+
set: (key, value, ttlMs) => base.set(prefixed(key), value, ttlMs),
|
|
1357
|
+
setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(prefixed(key), value, ttlMs),
|
|
1358
|
+
delete: (key) => base.delete(prefixed(key))
|
|
1359
|
+
};
|
|
1360
|
+
}
|
|
1361
|
+
function createQueuedStateAdapter(base, options) {
|
|
1362
|
+
const heartbeats = /* @__PURE__ */ new Map();
|
|
1363
|
+
const shouldHeartbeatLock = (ttlMs) => ttlMs === ACTIVE_LOCK_TTL_MS;
|
|
1364
|
+
const heartbeatKey = (lock) => `${lock.threadId}:${lock.token}`;
|
|
1365
|
+
const stopHeartbeatByKey = (key) => {
|
|
1366
|
+
const heartbeat = heartbeats.get(key);
|
|
1367
|
+
if (!heartbeat) return;
|
|
1368
|
+
clearInterval(heartbeat.timer);
|
|
1369
|
+
heartbeats.delete(key);
|
|
1370
|
+
};
|
|
1371
|
+
const stopHeartbeat = (lock) => {
|
|
1372
|
+
stopHeartbeatByKey(heartbeatKey(lock));
|
|
1373
|
+
};
|
|
1374
|
+
const stopHeartbeatsForThread = (threadId) => {
|
|
1375
|
+
for (const [key, heartbeat] of heartbeats) if (heartbeat.lock.threadId === threadId) stopHeartbeatByKey(key);
|
|
1376
|
+
};
|
|
1377
|
+
const stopAllHeartbeats = () => {
|
|
1378
|
+
for (const key of heartbeats.keys()) stopHeartbeatByKey(key);
|
|
1379
|
+
};
|
|
1380
|
+
const runHeartbeat = async (key) => {
|
|
1381
|
+
const heartbeat = heartbeats.get(key);
|
|
1382
|
+
if (!heartbeat || heartbeat.inFlight) return;
|
|
1383
|
+
heartbeat.inFlight = true;
|
|
1384
|
+
try {
|
|
1385
|
+
if (Date.now() - heartbeat.startedAtMs >= options.activeLockMaxAgeMs) {
|
|
1386
|
+
stopHeartbeatByKey(key);
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
if (!await base.extendLock(heartbeat.lock, heartbeat.ttlMs)) {
|
|
1390
|
+
stopHeartbeatByKey(key);
|
|
1391
|
+
return;
|
|
1392
|
+
}
|
|
1393
|
+
heartbeat.lock.expiresAt = Date.now() + heartbeat.ttlMs;
|
|
1394
|
+
} catch {} finally {
|
|
1395
|
+
const current = heartbeats.get(key);
|
|
1396
|
+
if (current === heartbeat) current.inFlight = false;
|
|
1397
|
+
}
|
|
1398
|
+
};
|
|
1399
|
+
const startOrUpdateHeartbeat = (lock, ttlMs) => {
|
|
1400
|
+
const key = heartbeatKey(lock);
|
|
1401
|
+
const existing = heartbeats.get(key);
|
|
1402
|
+
if (existing) {
|
|
1403
|
+
existing.ttlMs = ttlMs;
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
const timer = setInterval(() => {
|
|
1407
|
+
runHeartbeat(key);
|
|
1408
|
+
}, ACTIVE_LOCK_HEARTBEAT_MS);
|
|
1409
|
+
timer.unref?.();
|
|
1410
|
+
heartbeats.set(key, {
|
|
1411
|
+
inFlight: false,
|
|
1412
|
+
lock,
|
|
1413
|
+
startedAtMs: Date.now(),
|
|
1414
|
+
timer,
|
|
1415
|
+
ttlMs
|
|
1416
|
+
});
|
|
1417
|
+
};
|
|
1418
|
+
const acquireLock = async (threadId, ttlMs) => {
|
|
1419
|
+
const lock = await base.acquireLock(threadId, ttlMs);
|
|
1420
|
+
if (lock && shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
|
|
1421
|
+
return lock;
|
|
1422
|
+
};
|
|
1423
|
+
return {
|
|
1424
|
+
appendToList: (key, value, options) => base.appendToList(key, value, options),
|
|
1425
|
+
connect: () => base.connect(),
|
|
1426
|
+
disconnect: async () => {
|
|
1427
|
+
stopAllHeartbeats();
|
|
1428
|
+
await base.disconnect();
|
|
1429
|
+
},
|
|
1430
|
+
subscribe: (threadId) => base.subscribe(threadId),
|
|
1431
|
+
unsubscribe: (threadId) => base.unsubscribe(threadId),
|
|
1432
|
+
isSubscribed: (threadId) => base.isSubscribed(threadId),
|
|
1433
|
+
acquireLock,
|
|
1434
|
+
releaseLock: async (lock) => {
|
|
1435
|
+
stopHeartbeat(lock);
|
|
1436
|
+
await base.releaseLock(lock);
|
|
1437
|
+
},
|
|
1438
|
+
extendLock: async (lock, ttlMs) => {
|
|
1439
|
+
const extended = await base.extendLock(lock, ttlMs);
|
|
1440
|
+
if (extended) {
|
|
1441
|
+
lock.expiresAt = Date.now() + ttlMs;
|
|
1442
|
+
if (shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
|
|
1443
|
+
else stopHeartbeat(lock);
|
|
1444
|
+
} else stopHeartbeat(lock);
|
|
1445
|
+
return extended;
|
|
1446
|
+
},
|
|
1447
|
+
forceReleaseLock: async (threadId) => {
|
|
1448
|
+
stopHeartbeatsForThread(threadId);
|
|
1449
|
+
await base.forceReleaseLock(threadId);
|
|
1450
|
+
},
|
|
1451
|
+
enqueue: (threadId, entry, maxSize) => base.enqueue(threadId, entry, maxSize),
|
|
1452
|
+
dequeue: (threadId) => base.dequeue(threadId),
|
|
1453
|
+
queueDepth: (threadId) => base.queueDepth(threadId),
|
|
1454
|
+
get: (key) => base.get(key),
|
|
1455
|
+
getList: (key) => base.getList(key),
|
|
1456
|
+
set: (key, value, ttlMs) => base.set(key, value, ttlMs),
|
|
1457
|
+
setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(key, value, ttlMs),
|
|
1458
|
+
delete: (key) => base.delete(key)
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
function withOptionalPrefix(base, prefix) {
|
|
1462
|
+
return prefix ? createPrefixedStateAdapter(base, prefix) : base;
|
|
1463
|
+
}
|
|
1464
|
+
function createStateAdapter() {
|
|
1465
|
+
const config = getChatConfig();
|
|
1466
|
+
const activeLockMaxAgeMs = config.bot.turnTimeoutMs + ACTIVE_LOCK_TTL_MS;
|
|
1467
|
+
if (config.state.adapter === "memory") {
|
|
1468
|
+
redisStateAdapter = void 0;
|
|
1469
|
+
return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(createMemoryState(), config.state.keyPrefix)), { activeLockMaxAgeMs });
|
|
1470
|
+
}
|
|
1471
|
+
if (!config.state.redisUrl) throw new Error("REDIS_URL is required for durable Slack thread state");
|
|
1472
|
+
const redisState = createRedisState({
|
|
1473
|
+
keyPrefix: REDIS_STATE_KEY_PREFIX,
|
|
1474
|
+
url: config.state.redisUrl
|
|
1475
|
+
});
|
|
1476
|
+
redisStateAdapter = redisState;
|
|
1477
|
+
return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(redisState, config.state.keyPrefix)), { activeLockMaxAgeMs });
|
|
1478
|
+
}
|
|
1479
|
+
function getOptionalRedisStateAdapter() {
|
|
1480
|
+
getStateAdapter();
|
|
1481
|
+
return redisStateAdapter;
|
|
1482
|
+
}
|
|
1483
|
+
async function getConnectedStateContext() {
|
|
1484
|
+
const adapter = getStateAdapter();
|
|
1485
|
+
await adapter.connect();
|
|
1486
|
+
return {
|
|
1487
|
+
redisStateAdapter: getOptionalRedisStateAdapter(),
|
|
1488
|
+
stateAdapter: adapter
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
/** Return the Redis adapter only when the caller is using the default state adapter. */
|
|
1492
|
+
async function getDefaultRedisStateAdapterFor(adapter) {
|
|
1493
|
+
if (adapter !== stateAdapter) return;
|
|
1494
|
+
const context = await getConnectedStateContext();
|
|
1495
|
+
return context.stateAdapter === adapter ? context.redisStateAdapter : void 0;
|
|
1496
|
+
}
|
|
1497
|
+
/** The Redis key that the default Redis adapter uses for one state value key. */
|
|
1498
|
+
function redisStateKey(key) {
|
|
1499
|
+
const prefix = getChatConfig().state.keyPrefix;
|
|
1500
|
+
return `${REDIS_STATE_KEY_PREFIX}:cache:${prefix ? `${prefix}:` : ""}${key}`;
|
|
1501
|
+
}
|
|
1502
|
+
/** Read state values in one Redis round trip. Other adapters read each key. */
|
|
1503
|
+
async function getStateValues(state, keys) {
|
|
1504
|
+
if (keys.length === 0) return [];
|
|
1505
|
+
const redis = await getDefaultRedisStateAdapterFor(state);
|
|
1506
|
+
if (!redis) return await mapBounded(keys, (key) => state.get(key));
|
|
1507
|
+
return (await redis.getClient().mGet(keys.map(redisStateKey))).map((value) => {
|
|
1508
|
+
if (value === null) return null;
|
|
1509
|
+
try {
|
|
1510
|
+
return JSON.parse(value);
|
|
1511
|
+
} catch {
|
|
1512
|
+
return value;
|
|
1513
|
+
}
|
|
1514
|
+
});
|
|
1515
|
+
}
|
|
1516
|
+
/** Write state values with one TTL in one Redis round trip. */
|
|
1517
|
+
async function setStateValues(state, entries, ttlMs) {
|
|
1518
|
+
if (entries.length === 0) return;
|
|
1519
|
+
const redis = await getDefaultRedisStateAdapterFor(state);
|
|
1520
|
+
if (!redis) {
|
|
1521
|
+
await mapBounded(entries, ({ key, value }) => state.set(key, value, ttlMs));
|
|
1522
|
+
return;
|
|
1523
|
+
}
|
|
1524
|
+
const pipeline = redis.getClient().multi();
|
|
1525
|
+
for (const { key, value } of entries) pipeline.set(redisStateKey(key), JSON.stringify(value), { PX: ttlMs });
|
|
1526
|
+
await pipeline.execAsPipeline();
|
|
1527
|
+
}
|
|
1528
|
+
function getStateAdapter() {
|
|
1529
|
+
if (!stateAdapter) stateAdapter = createStateAdapter();
|
|
1530
|
+
return stateAdapter;
|
|
1531
|
+
}
|
|
1532
|
+
async function disconnectStateAdapter() {
|
|
1533
|
+
if (!stateAdapter) return;
|
|
1534
|
+
try {
|
|
1535
|
+
await stateAdapter.disconnect();
|
|
1536
|
+
} finally {
|
|
1537
|
+
stateAdapter = void 0;
|
|
1538
|
+
redisStateAdapter = void 0;
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
// src/chat/actor.ts
|
|
1542
|
+
/**
|
|
1543
|
+
* Canonical actor identity.
|
|
1544
|
+
*
|
|
1545
|
+
* Runtime actors are platform-scoped actors. Stored Slack actor parsing
|
|
1546
|
+
* remains explicit so durable conversation metadata is not repaired on read.
|
|
1547
|
+
*/
|
|
1548
|
+
const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
|
|
1549
|
+
const EMAIL_PATTERN = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
|
|
1550
|
+
const exactStoredStringSchema = z.string().min(1).refine((value) => value === value.trim());
|
|
1551
|
+
const storedSlackActorSchema = z.object({
|
|
1552
|
+
email: exactStoredStringSchema.optional(),
|
|
1553
|
+
fullName: exactStoredStringSchema.optional(),
|
|
1554
|
+
platform: z.literal("slack").optional(),
|
|
1555
|
+
slackUserId: exactStoredStringSchema.optional(),
|
|
1556
|
+
slackUserName: exactStoredStringSchema.optional(),
|
|
1557
|
+
teamId: exactStoredStringSchema.optional()
|
|
1558
|
+
}).strict();
|
|
1559
|
+
/** Return whether an actor is a platform-scoped user actor. */
|
|
1560
|
+
function isUserActor(actor) {
|
|
1561
|
+
return Boolean(actor && "userId" in actor);
|
|
1562
|
+
}
|
|
1563
|
+
function clean(value) {
|
|
1564
|
+
const trimmed = value?.trim();
|
|
1565
|
+
return trimmed ? trimmed : void 0;
|
|
1566
|
+
}
|
|
1567
|
+
function isSyntheticActorUserId(value) {
|
|
1568
|
+
return value.toLowerCase() === "unknown";
|
|
1569
|
+
}
|
|
1570
|
+
/** Return whether a value has the shape of a Slack user id. */
|
|
1571
|
+
function isSlackUserId(value) {
|
|
1572
|
+
return SLACK_USER_ID_DISPLAY_PATTERN.test(value);
|
|
1573
|
+
}
|
|
1574
|
+
function cleanActorDisplayName(value, userId) {
|
|
1575
|
+
const displayName = clean(value);
|
|
1576
|
+
if (!displayName) return;
|
|
1577
|
+
if (displayName.toLowerCase() === "unknown") return;
|
|
1578
|
+
if (userId && displayName === userId) return;
|
|
1579
|
+
return isSlackUserId(displayName) ? void 0 : displayName;
|
|
1580
|
+
}
|
|
1581
|
+
function cleanActorEmail(value) {
|
|
1582
|
+
const email = clean(value);
|
|
1583
|
+
return email && EMAIL_PATTERN.test(email) ? email : void 0;
|
|
1584
|
+
}
|
|
1585
|
+
/** Keep actor ids exact at platform boundaries before they enter owned state. */
|
|
1586
|
+
function parseActorUserId(value) {
|
|
1587
|
+
if (typeof value !== "string" || value.length === 0) return;
|
|
1588
|
+
if (value !== value.trim() || isSyntheticActorUserId(value)) return;
|
|
1589
|
+
return value;
|
|
1590
|
+
}
|
|
1591
|
+
/** Assert persisted actor ids without read-side repair. */
|
|
1592
|
+
function isActorUserId(value) {
|
|
1593
|
+
return parseActorUserId(value) === value;
|
|
1594
|
+
}
|
|
1595
|
+
/** Build Junior's canonical platform actor from exact actor ids and profile data. */
|
|
1596
|
+
function createActor(input, context) {
|
|
1597
|
+
const platform = context.platform ?? input?.platform;
|
|
1598
|
+
if (!platform) return;
|
|
1599
|
+
const contextUserId = parseActorUserId(context.userId);
|
|
1600
|
+
if (context.userId !== void 0 && !contextUserId) return;
|
|
1601
|
+
const inputUserId = parseActorUserId(input?.userId);
|
|
1602
|
+
if (input?.userId !== void 0 && !inputUserId) return;
|
|
1603
|
+
const actorUserId = contextUserId ?? inputUserId;
|
|
1604
|
+
if (!actorUserId) return;
|
|
1605
|
+
const contextTeamId = parseSlackTeamId(context.teamId);
|
|
1606
|
+
if (context.teamId !== void 0 && !contextTeamId) return;
|
|
1607
|
+
const inputTeamId = parseSlackTeamId(input?.teamId);
|
|
1608
|
+
if (input?.teamId !== void 0 && !inputTeamId) return;
|
|
1609
|
+
const actorTeamId = contextTeamId ?? inputTeamId;
|
|
1610
|
+
if (platform === "slack" && !actorTeamId) return;
|
|
1611
|
+
const canUseInputProfile = (!contextUserId || !inputUserId || contextUserId === inputUserId) && (platform !== "slack" || !contextTeamId || !inputTeamId || contextTeamId === inputTeamId);
|
|
1612
|
+
const actor = {
|
|
1613
|
+
...canUseInputProfile && cleanActorEmail(input?.email) ? { email: cleanActorEmail(input?.email) } : void 0,
|
|
1614
|
+
...canUseInputProfile && cleanActorDisplayName(input?.fullName, actorUserId) ? { fullName: cleanActorDisplayName(input?.fullName, actorUserId) } : void 0,
|
|
1615
|
+
platform,
|
|
1616
|
+
userId: actorUserId,
|
|
1617
|
+
...canUseInputProfile && cleanActorDisplayName(input?.userName, actorUserId) ? { userName: cleanActorDisplayName(input?.userName, actorUserId) } : void 0
|
|
1618
|
+
};
|
|
1619
|
+
if (platform === "slack") return {
|
|
1620
|
+
...actor,
|
|
1621
|
+
platform,
|
|
1622
|
+
teamId: actorTeamId
|
|
1623
|
+
};
|
|
1624
|
+
return {
|
|
1625
|
+
...actor,
|
|
1626
|
+
platform
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
/** Build Junior's canonical actor from Slack profile data. */
|
|
1630
|
+
function createSlackActor(teamId, userId, profile) {
|
|
1631
|
+
const actorUserId = parseActorUserId(userId);
|
|
1632
|
+
const actorTeamId = parseSlackTeamId(teamId);
|
|
1633
|
+
if (!actorTeamId || !actorUserId) throw new Error("Slack actor requires team and user ids");
|
|
1634
|
+
const actor = createActor({
|
|
1635
|
+
email: profile?.email,
|
|
1636
|
+
fullName: profile?.fullName,
|
|
1637
|
+
platform: "slack",
|
|
1638
|
+
teamId: actorTeamId,
|
|
1639
|
+
userId: actorUserId,
|
|
1640
|
+
userName: profile?.userName
|
|
1641
|
+
}, {
|
|
1642
|
+
teamId: actorTeamId,
|
|
1643
|
+
userId: actorUserId
|
|
1644
|
+
});
|
|
1645
|
+
if (!actor || actor.platform !== "slack") throw new Error("Slack actor requires team and user ids");
|
|
1646
|
+
return actor;
|
|
1647
|
+
}
|
|
1648
|
+
/** Parse a serialized Slack actor that crossed a runtime boundary. */
|
|
1649
|
+
function parseStoredSlackActor(value) {
|
|
1650
|
+
const parsed = storedSlackActorSchema.safeParse(value);
|
|
1651
|
+
if (!parsed.success) return;
|
|
1652
|
+
if (parsed.data.slackUserId !== void 0 && !parseActorUserId(parsed.data.slackUserId)) return;
|
|
1653
|
+
if (parsed.data.teamId !== void 0 && !parseSlackTeamId(parsed.data.teamId)) return;
|
|
1654
|
+
if ((parsed.data.platform !== void 0 || parsed.data.teamId !== void 0) && (!parsed.data.platform || !parsed.data.teamId)) return;
|
|
1655
|
+
return parsed.data;
|
|
1656
|
+
}
|
|
1657
|
+
/** Convert a runtime Slack actor into its durable session shape. */
|
|
1658
|
+
function toStoredSlackActor(actor) {
|
|
1659
|
+
return {
|
|
1660
|
+
...actor.email ? { email: actor.email } : void 0,
|
|
1661
|
+
...actor.fullName ? { fullName: actor.fullName } : void 0,
|
|
1662
|
+
platform: actor.platform,
|
|
1663
|
+
slackUserId: actor.userId,
|
|
1664
|
+
...actor.userName ? { slackUserName: actor.userName } : void 0,
|
|
1665
|
+
teamId: actor.teamId
|
|
1666
|
+
};
|
|
1667
|
+
}
|
|
1668
|
+
/**
|
|
1669
|
+
* Resolve a Slack resume actor from stored profile data and the active actor.
|
|
1670
|
+
*
|
|
1671
|
+
* TODO(dcramer): Require Actor and remove ID-only construction after no
|
|
1672
|
+
* deployed Turn cursor can omit Actor.
|
|
1673
|
+
*/
|
|
1674
|
+
function createSlackResumeActor(args) {
|
|
1675
|
+
if (args.actor) {
|
|
1676
|
+
if (args.actor.platform !== "slack" || args.actor.teamId !== args.teamId || args.actor.userId !== args.userId) throw new Error("Stored Slack actor did not match resume actor");
|
|
1677
|
+
}
|
|
1678
|
+
const actor = createActor(args.actor, {
|
|
1679
|
+
platform: "slack",
|
|
1680
|
+
teamId: args.teamId,
|
|
1681
|
+
userId: args.userId
|
|
1682
|
+
});
|
|
1683
|
+
if (!actor || actor.platform !== "slack") throw new Error("Slack actor requires team and user ids");
|
|
1684
|
+
return actor;
|
|
1685
|
+
}
|
|
1686
|
+
// src/chat/credentials/context.ts
|
|
1687
|
+
const exactActorIdSchema = z.string().refine((value) => parseActorUserId(value) === value);
|
|
1688
|
+
const exactNonBlankStringSchema = z.string().min(1).refine((value) => value === value.trim());
|
|
1689
|
+
const slackDirectCredentialSubjectBindingSchema = z.object({
|
|
1690
|
+
type: z.literal("slack-direct-conversation"),
|
|
1691
|
+
teamId: z.string().min(1),
|
|
1692
|
+
channelId: z.string().min(1),
|
|
1693
|
+
signature: z.string().min(1)
|
|
1694
|
+
}).strict();
|
|
1695
|
+
const scheduledAutomationCredentialSubjectBindingSchema = z.object({
|
|
1696
|
+
type: z.literal("scheduled-automation"),
|
|
1697
|
+
plugin: z.string().min(1),
|
|
1698
|
+
taskId: exactNonBlankStringSchema,
|
|
1699
|
+
signature: z.string().min(1)
|
|
1700
|
+
}).strict();
|
|
1701
|
+
const eventAutomationCredentialSubjectBindingSchema = z.object({
|
|
1702
|
+
type: z.literal("event-automation"),
|
|
1703
|
+
plugin: z.string().min(1),
|
|
1704
|
+
taskId: exactNonBlankStringSchema,
|
|
1705
|
+
signature: z.string().min(1)
|
|
1706
|
+
}).strict();
|
|
1707
|
+
const timerWatchCredentialSubjectBindingSchema = z.object({
|
|
1708
|
+
type: z.literal("timer-watch"),
|
|
1709
|
+
conversationId: exactNonBlankStringSchema,
|
|
1710
|
+
watchId: exactNonBlankStringSchema,
|
|
1711
|
+
signature: z.string().min(1)
|
|
1712
|
+
}).strict();
|
|
1713
|
+
z.discriminatedUnion("type", [
|
|
1714
|
+
slackDirectCredentialSubjectBindingSchema,
|
|
1715
|
+
scheduledAutomationCredentialSubjectBindingSchema,
|
|
1716
|
+
eventAutomationCredentialSubjectBindingSchema,
|
|
1717
|
+
timerWatchCredentialSubjectBindingSchema
|
|
1718
|
+
]);
|
|
1719
|
+
const credentialUserActorSchema = z.object({
|
|
1720
|
+
type: z.literal("user"),
|
|
1721
|
+
userId: exactActorIdSchema
|
|
1722
|
+
}).strict();
|
|
1723
|
+
const credentialSystemActorSchema = z.object({
|
|
1724
|
+
platform: z.literal("system"),
|
|
1725
|
+
name: exactActorIdSchema
|
|
1726
|
+
}).strict();
|
|
1727
|
+
const credentialSubjectSchema = z.discriminatedUnion("allowedWhen", [
|
|
1728
|
+
z.object({
|
|
1729
|
+
type: z.literal("user"),
|
|
1730
|
+
userId: exactActorIdSchema,
|
|
1731
|
+
allowedWhen: z.literal("private-direct-conversation"),
|
|
1732
|
+
binding: slackDirectCredentialSubjectBindingSchema
|
|
1733
|
+
}).strict(),
|
|
1734
|
+
z.object({
|
|
1735
|
+
type: z.literal("user"),
|
|
1736
|
+
userId: exactActorIdSchema,
|
|
1737
|
+
allowedWhen: z.literal("scheduled-automation"),
|
|
1738
|
+
taskId: exactNonBlankStringSchema,
|
|
1739
|
+
binding: scheduledAutomationCredentialSubjectBindingSchema
|
|
1740
|
+
}).strict().refine((subject) => subject.binding.taskId === subject.taskId, {
|
|
1741
|
+
message: "Scheduled automation credential subject requires task binding",
|
|
1742
|
+
path: ["binding"]
|
|
1743
|
+
}),
|
|
1744
|
+
z.object({
|
|
1745
|
+
type: z.literal("user"),
|
|
1746
|
+
userId: exactActorIdSchema,
|
|
1747
|
+
allowedWhen: z.literal("event-automation"),
|
|
1748
|
+
taskId: exactNonBlankStringSchema,
|
|
1749
|
+
binding: eventAutomationCredentialSubjectBindingSchema
|
|
1750
|
+
}).strict().refine((subject) => subject.binding.taskId === subject.taskId, {
|
|
1751
|
+
message: "Event automation credential subject requires task binding",
|
|
1752
|
+
path: ["binding"]
|
|
1753
|
+
}),
|
|
1754
|
+
z.object({
|
|
1755
|
+
type: z.literal("user"),
|
|
1756
|
+
userId: exactActorIdSchema,
|
|
1757
|
+
allowedWhen: z.literal("timer-watch"),
|
|
1758
|
+
binding: timerWatchCredentialSubjectBindingSchema
|
|
1759
|
+
}).strict()
|
|
1760
|
+
]);
|
|
1761
|
+
const credentialContextSchema = z.union([z.object({ actor: credentialUserActorSchema }).strict(), z.object({
|
|
1762
|
+
actor: credentialSystemActorSchema,
|
|
1763
|
+
subject: credentialSubjectSchema.optional()
|
|
1764
|
+
}).strict()]);
|
|
1765
|
+
/**
|
|
1766
|
+
* Build credential authority from the run actor.
|
|
1767
|
+
*
|
|
1768
|
+
* `actor` is the rich execution principal. This projects the credential stub
|
|
1769
|
+
* tools/auth need from it:
|
|
1770
|
+
* - user actor → `{ actor: { type: "user", userId } }`
|
|
1771
|
+
* - system actor → `{ actor: systemActor, subject? }`
|
|
1772
|
+
*
|
|
1773
|
+
* They only diverge when a system run carries an explicit delegated `subject`
|
|
1774
|
+
* (scheduled/event-automation creator credentials). Callers should set `actor` first,
|
|
1775
|
+
* then derive this — do not hand-build parallel shapes.
|
|
1776
|
+
*/
|
|
1777
|
+
function credentialContextForActor(actor, subject) {
|
|
1778
|
+
if (actor.platform === "system") return subject ? {
|
|
1779
|
+
actor,
|
|
1780
|
+
subject
|
|
1781
|
+
} : { actor };
|
|
1782
|
+
if (subject) throw new TypeError("Delegated credential subjects require a system actor");
|
|
1783
|
+
return { actor: {
|
|
1784
|
+
type: "user",
|
|
1785
|
+
userId: actor.userId
|
|
1786
|
+
} };
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* Name the person accountable for credential authority in logs.
|
|
1790
|
+
*
|
|
1791
|
+
* `userId` is the user actor, or the owner of delegated credentials when the
|
|
1792
|
+
* system acts for an Automation or Watch. `actorType` says who acted.
|
|
1793
|
+
*/
|
|
1794
|
+
function credentialLogContext(context) {
|
|
1795
|
+
if ("type" in context.actor) return {
|
|
1796
|
+
userId: context.actor.userId,
|
|
1797
|
+
actorType: "user",
|
|
1798
|
+
actorId: context.actor.userId
|
|
1799
|
+
};
|
|
1800
|
+
const subject = "subject" in context ? context.subject : void 0;
|
|
1801
|
+
return {
|
|
1802
|
+
actorType: "system",
|
|
1803
|
+
actorId: context.actor.name,
|
|
1804
|
+
...subject ? {
|
|
1805
|
+
userId: subject.userId,
|
|
1806
|
+
credentialAllowedWhen: subject.allowedWhen,
|
|
1807
|
+
..."taskId" in subject ? { taskId: subject.taskId } : void 0
|
|
1808
|
+
} : void 0
|
|
1809
|
+
};
|
|
1810
|
+
}
|
|
1811
|
+
/**
|
|
1812
|
+
* Name the run's people in logs: the accountable person and who acted.
|
|
1813
|
+
*
|
|
1814
|
+
* A user actor is the accountable person. A system actor names the owner of
|
|
1815
|
+
* delegated credentials, when the run has them.
|
|
1816
|
+
*/
|
|
1817
|
+
function actorLogContext(actor, credentialContext) {
|
|
1818
|
+
const credential = credentialContext ? credentialLogContext(credentialContext) : {};
|
|
1819
|
+
if (!isUserActor(actor)) return credential;
|
|
1820
|
+
return {
|
|
1821
|
+
...credential,
|
|
1822
|
+
userId: actor.userId,
|
|
1823
|
+
userName: actor.userName,
|
|
1824
|
+
userEmail: actor.email,
|
|
1825
|
+
userFullName: actor.fullName
|
|
1826
|
+
};
|
|
1827
|
+
}
|
|
1828
|
+
/** Return the user whose OAuth token may satisfy this credential request. */
|
|
1829
|
+
function credentialUserSubjectId(context) {
|
|
1830
|
+
if ("type" in context.actor) return context.actor.userId;
|
|
1831
|
+
return "subject" in context ? context.subject?.userId : void 0;
|
|
1832
|
+
}
|
|
1833
|
+
export { resolveGatewayModel as $, slackBotIdSchema as A, getSlackBotToken as B, acquireActiveLock as C, parseSlackChannelReferenceId as D, parseSlackChannelId as E, slackMessageTsFromMs as F, loadConfig as G, getSlackClientSecret as H, slackMessageTsSchema as I, normalizeSlackEmojiName as J, parseEnvList as K, botConfig as L, slackTeamIdSchema as M, slackUserIdSchema as N, parseSlackTeamId as O, parseSlackMessageTs as P, findGatewayModel as Q, getChatConfig as R, MUTATION_LOCK_TTL_MS as S, withLock as T, getSlackSigningSecret as U, getSlackClientId as V, installChatConfig as W, toPiReasoningLevel as X, TURN_REASONING_LEVELS as Y, GATEWAY_PROVIDER as Z, disconnectStateAdapter as _, credentialSubjectSchema as a, streamSimpleAnthropic as at, getStateValues as b, createSlackActor as c, isSlackUserId as d, calculateCost as et, isUserActor as f, adapter_exports as g, toStoredSlackActor as h, credentialLogContext as i, streamAnthropic as it, slackChannelIdSchema as j, parseSlackUserId as k, createSlackResumeActor as l, parseStoredSlackActor as m, credentialContextForActor as n, getEnvApiKey as nt, credentialUserSubjectId as o, parseActorUserId as p, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as q, credentialContextSchema as r, registerApiProvider as rt, createActor as s, actorLogContext as t, completeSimple as tt, isActorUserId as u, getDefaultRedisStateAdapterFor as v, fenceLock as w, setStateValues as x, getStateAdapter as y, getRuntimeMetadata as z };
|