@sentry/junior 0.1.1 → 0.3.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.
@@ -0,0 +1,1866 @@
1
+ import {
2
+ logInfo,
3
+ logWarn,
4
+ setSpanAttributes,
5
+ withSpan
6
+ } from "./chunk-PY4AI2GZ.js";
7
+ import {
8
+ discoverInstalledPluginPackageContent,
9
+ discoverProjectRoots
10
+ } from "./chunk-SP6LV35L.js";
11
+
12
+ // src/chat/config.ts
13
+ var MIN_AGENT_TURN_TIMEOUT_MS = 10 * 1e3;
14
+ var DEFAULT_AGENT_TURN_TIMEOUT_MS = 12 * 60 * 1e3;
15
+ var DEFAULT_QUEUE_CALLBACK_MAX_DURATION_SECONDS = 800;
16
+ var TURN_TIMEOUT_BUFFER_SECONDS = 20;
17
+ function parseAgentTurnTimeoutMs(rawValue, maxTimeoutMs) {
18
+ const value = Number.parseInt(rawValue ?? "", 10);
19
+ if (Number.isNaN(value)) {
20
+ return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, Math.min(DEFAULT_AGENT_TURN_TIMEOUT_MS, maxTimeoutMs));
21
+ }
22
+ return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, Math.min(value, maxTimeoutMs));
23
+ }
24
+ function resolveQueueCallbackMaxDurationSeconds() {
25
+ const value = Number.parseInt(process.env.QUEUE_CALLBACK_MAX_DURATION_SECONDS ?? "", 10);
26
+ if (Number.isNaN(value) || value <= 0) {
27
+ return DEFAULT_QUEUE_CALLBACK_MAX_DURATION_SECONDS;
28
+ }
29
+ return value;
30
+ }
31
+ function resolveMaxTurnTimeoutMs(queueCallbackMaxDurationSeconds) {
32
+ const budgetSeconds = queueCallbackMaxDurationSeconds - TURN_TIMEOUT_BUFFER_SECONDS;
33
+ return Math.max(MIN_AGENT_TURN_TIMEOUT_MS, budgetSeconds * 1e3);
34
+ }
35
+ function buildBotConfig() {
36
+ const queueCallbackMaxDurationSeconds = resolveQueueCallbackMaxDurationSeconds();
37
+ const maxTurnTimeoutMs = resolveMaxTurnTimeoutMs(queueCallbackMaxDurationSeconds);
38
+ return {
39
+ userName: process.env.JUNIOR_BOT_NAME ?? "junior",
40
+ modelId: process.env.AI_MODEL ?? "anthropic/claude-sonnet-4.6",
41
+ fastModelId: process.env.AI_FAST_MODEL ?? process.env.AI_MODEL ?? "anthropic/claude-haiku-4.5",
42
+ turnTimeoutMs: parseAgentTurnTimeoutMs(process.env.AGENT_TURN_TIMEOUT_MS, maxTurnTimeoutMs)
43
+ };
44
+ }
45
+ var botConfig = buildBotConfig();
46
+ function toOptionalTrimmed(value) {
47
+ if (!value) {
48
+ return void 0;
49
+ }
50
+ const trimmed = value.trim();
51
+ return trimmed.length > 0 ? trimmed : void 0;
52
+ }
53
+ function getSlackBotToken() {
54
+ return toOptionalTrimmed(process.env.SLACK_BOT_TOKEN) ?? toOptionalTrimmed(process.env.SLACK_BOT_USER_TOKEN);
55
+ }
56
+ function getSlackSigningSecret() {
57
+ return toOptionalTrimmed(process.env.SLACK_SIGNING_SECRET);
58
+ }
59
+ function getSlackClientId() {
60
+ return toOptionalTrimmed(process.env.SLACK_CLIENT_ID);
61
+ }
62
+ function getSlackClientSecret() {
63
+ return toOptionalTrimmed(process.env.SLACK_CLIENT_SECRET);
64
+ }
65
+ function hasRedisConfig() {
66
+ return Boolean(process.env.REDIS_URL);
67
+ }
68
+
69
+ // src/chat/state.ts
70
+ import { createRedisState } from "@chat-adapter/state-redis";
71
+ import { createMemoryState } from "@chat-adapter/state-memory";
72
+ var MIN_LOCK_TTL_MS = 1e3 * 60 * 5;
73
+ var QUEUE_INGRESS_DEDUP_PREFIX = "junior:queue_ingress";
74
+ var QUEUE_MESSAGE_PROCESSING_PREFIX = "junior:queue_message";
75
+ var AGENT_TURN_SESSION_PREFIX = "junior:agent_turn_session";
76
+ var QUEUE_MESSAGE_PROCESSING_TTL_MS = 30 * 60 * 1e3;
77
+ var QUEUE_MESSAGE_COMPLETED_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
78
+ var QUEUE_MESSAGE_FAILED_TTL_MS = 6 * 60 * 60 * 1e3;
79
+ var AGENT_TURN_SESSION_TTL_MS = 24 * 60 * 60 * 1e3;
80
+ var CLAIM_OR_RECLAIM_PROCESSING_SCRIPT = `
81
+ local key = KEYS[1]
82
+ local nowMs = tonumber(ARGV[1])
83
+ local ttlMs = tonumber(ARGV[2])
84
+ local payload = ARGV[3]
85
+ local current = redis.call("get", key)
86
+
87
+ if not current then
88
+ redis.call("set", key, payload, "PX", ttlMs)
89
+ return 1
90
+ end
91
+
92
+ local ok, parsed = pcall(cjson.decode, current)
93
+ if not ok or type(parsed) ~= "table" then
94
+ return 0
95
+ end
96
+
97
+ local status = parsed["status"]
98
+ if status == "failed" then
99
+ redis.call("set", key, payload, "PX", ttlMs)
100
+ return 3
101
+ end
102
+ if status ~= "processing" then
103
+ return 0
104
+ end
105
+
106
+ local updatedAtMs = tonumber(parsed["updatedAtMs"])
107
+ if not updatedAtMs then
108
+ return 0
109
+ end
110
+
111
+ if updatedAtMs + ttlMs < nowMs then
112
+ redis.call("set", key, payload, "PX", ttlMs)
113
+ return 2
114
+ end
115
+
116
+ return 0
117
+ `;
118
+ var UPDATE_PROCESSING_STATE_IF_OWNER_SCRIPT = `
119
+ local key = KEYS[1]
120
+ local ownerToken = ARGV[1]
121
+ local ttlMs = tonumber(ARGV[2])
122
+ local payload = ARGV[3]
123
+ local current = redis.call("get", key)
124
+
125
+ if not current then
126
+ return 0
127
+ end
128
+
129
+ local ok, parsed = pcall(cjson.decode, current)
130
+ if not ok or type(parsed) ~= "table" then
131
+ return 0
132
+ end
133
+
134
+ local currentOwner = parsed["ownerToken"]
135
+ local status = parsed["status"]
136
+ if currentOwner ~= ownerToken then
137
+ return 0
138
+ end
139
+ if status ~= "processing" then
140
+ return 0
141
+ end
142
+
143
+ redis.call("set", key, payload, "PX", ttlMs)
144
+ return 1
145
+ `;
146
+ function createQueuedStateAdapter(base) {
147
+ const acquireLock = async (threadId, ttlMs) => {
148
+ const effectiveTtlMs = Math.max(ttlMs, MIN_LOCK_TTL_MS);
149
+ const lock = await base.acquireLock(threadId, effectiveTtlMs);
150
+ return lock;
151
+ };
152
+ return {
153
+ connect: () => base.connect(),
154
+ disconnect: () => base.disconnect(),
155
+ subscribe: (threadId) => base.subscribe(threadId),
156
+ unsubscribe: (threadId) => base.unsubscribe(threadId),
157
+ isSubscribed: (threadId) => base.isSubscribed(threadId),
158
+ acquireLock,
159
+ releaseLock: (lock) => base.releaseLock(lock),
160
+ extendLock: (lock, ttlMs) => base.extendLock(lock, Math.max(ttlMs, MIN_LOCK_TTL_MS)),
161
+ get: (key) => base.get(key),
162
+ set: (key, value, ttlMs) => base.set(key, value, ttlMs),
163
+ setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(key, value, ttlMs),
164
+ delete: (key) => base.delete(key)
165
+ };
166
+ }
167
+ function createStateAdapter() {
168
+ if (process.env.JUNIOR_STATE_ADAPTER?.trim().toLowerCase() === "memory") {
169
+ _redisStateAdapter = void 0;
170
+ return createQueuedStateAdapter(createMemoryState());
171
+ }
172
+ if (!hasRedisConfig()) {
173
+ throw new Error("REDIS_URL is required for durable Slack thread state");
174
+ }
175
+ const redisState = createRedisState({
176
+ url: process.env.REDIS_URL
177
+ });
178
+ _redisStateAdapter = redisState;
179
+ return createQueuedStateAdapter(redisState);
180
+ }
181
+ var _stateAdapter;
182
+ var _redisStateAdapter;
183
+ function getRedisStateAdapter() {
184
+ if (!_redisStateAdapter) {
185
+ getStateAdapter();
186
+ }
187
+ if (!_redisStateAdapter) {
188
+ throw new Error("Redis state adapter is unavailable for this runtime");
189
+ }
190
+ return _redisStateAdapter;
191
+ }
192
+ function queueMessageKey(rawKey) {
193
+ return `${QUEUE_MESSAGE_PROCESSING_PREFIX}:${rawKey}`;
194
+ }
195
+ function parseQueueMessageState(value) {
196
+ if (typeof value !== "string") {
197
+ return void 0;
198
+ }
199
+ try {
200
+ const parsed = JSON.parse(value);
201
+ if (!parsed || parsed.status !== "processing" && parsed.status !== "completed" && parsed.status !== "failed" || typeof parsed.updatedAtMs !== "number") {
202
+ return void 0;
203
+ }
204
+ return {
205
+ status: parsed.status,
206
+ updatedAtMs: parsed.updatedAtMs,
207
+ ...typeof parsed.ownerToken === "string" ? { ownerToken: parsed.ownerToken } : {},
208
+ ...typeof parsed.queueMessageId === "string" ? { queueMessageId: parsed.queueMessageId } : {},
209
+ ...typeof parsed.errorMessage === "string" ? { errorMessage: parsed.errorMessage } : {}
210
+ };
211
+ } catch {
212
+ return void 0;
213
+ }
214
+ }
215
+ function agentTurnSessionKey(conversationId, sessionId) {
216
+ return `${AGENT_TURN_SESSION_PREFIX}:${conversationId}:${sessionId}`;
217
+ }
218
+ function isRecord(value) {
219
+ return typeof value === "object" && value !== null;
220
+ }
221
+ function parseAgentTurnSessionCheckpoint(value) {
222
+ if (typeof value !== "string") {
223
+ return void 0;
224
+ }
225
+ try {
226
+ const parsed = JSON.parse(value);
227
+ if (!isRecord(parsed)) {
228
+ return void 0;
229
+ }
230
+ const status = parsed.state;
231
+ if (status !== "running" && status !== "awaiting_resume" && status !== "completed" && status !== "failed") {
232
+ return void 0;
233
+ }
234
+ const conversationId = parsed.conversationId;
235
+ const sessionId = parsed.sessionId;
236
+ const sliceId = parsed.sliceId;
237
+ const checkpointVersion = parsed.checkpointVersion;
238
+ const updatedAtMs = parsed.updatedAtMs;
239
+ if (typeof conversationId !== "string" || typeof sessionId !== "string" || typeof sliceId !== "number" || typeof checkpointVersion !== "number" || typeof updatedAtMs !== "number") {
240
+ return void 0;
241
+ }
242
+ return {
243
+ checkpointVersion,
244
+ conversationId,
245
+ sessionId,
246
+ sliceId,
247
+ state: status,
248
+ updatedAtMs,
249
+ piMessages: Array.isArray(parsed.piMessages) ? parsed.piMessages : [],
250
+ ...typeof parsed.errorMessage === "string" ? { errorMessage: parsed.errorMessage } : {},
251
+ ...typeof parsed.resumedFromSliceId === "number" ? { resumedFromSliceId: parsed.resumedFromSliceId } : {}
252
+ };
253
+ } catch {
254
+ return void 0;
255
+ }
256
+ }
257
+ function getStateAdapter() {
258
+ if (!_stateAdapter) {
259
+ _stateAdapter = createStateAdapter();
260
+ }
261
+ return _stateAdapter;
262
+ }
263
+ async function disconnectStateAdapter() {
264
+ if (!_stateAdapter) {
265
+ return;
266
+ }
267
+ try {
268
+ await _stateAdapter.disconnect();
269
+ } finally {
270
+ _stateAdapter = void 0;
271
+ _redisStateAdapter = void 0;
272
+ }
273
+ }
274
+ async function claimQueueIngressDedup(rawKey, ttlMs) {
275
+ await getStateAdapter().connect();
276
+ const key = `${QUEUE_INGRESS_DEDUP_PREFIX}:${rawKey}`;
277
+ const result = await getRedisStateAdapter().getClient().set(key, "1", {
278
+ NX: true,
279
+ PX: ttlMs
280
+ });
281
+ return result === "OK";
282
+ }
283
+ async function hasQueueIngressDedup(rawKey) {
284
+ await getStateAdapter().connect();
285
+ const key = `${QUEUE_INGRESS_DEDUP_PREFIX}:${rawKey}`;
286
+ const value = await getRedisStateAdapter().getClient().get(key);
287
+ return typeof value === "string" && value.length > 0;
288
+ }
289
+ async function getQueueMessageProcessingState(rawKey) {
290
+ await getStateAdapter().connect();
291
+ const state = await getStateAdapter().get(queueMessageKey(rawKey));
292
+ return parseQueueMessageState(state);
293
+ }
294
+ async function acquireQueueMessageProcessingOwnership(args) {
295
+ await getStateAdapter().connect();
296
+ const key = queueMessageKey(args.rawKey);
297
+ const nowMs = Date.now();
298
+ const payload = JSON.stringify({
299
+ status: "processing",
300
+ updatedAtMs: nowMs,
301
+ ownerToken: args.ownerToken,
302
+ ...args.queueMessageId ? { queueMessageId: args.queueMessageId } : {}
303
+ });
304
+ const result = await getRedisStateAdapter().getClient().eval(CLAIM_OR_RECLAIM_PROCESSING_SCRIPT, {
305
+ keys: [key],
306
+ arguments: [String(nowMs), String(QUEUE_MESSAGE_PROCESSING_TTL_MS), payload]
307
+ });
308
+ if (result === 1) {
309
+ return "acquired";
310
+ }
311
+ if (result === 2) {
312
+ return "reclaimed";
313
+ }
314
+ if (result === 3) {
315
+ return "recovered";
316
+ }
317
+ return "blocked";
318
+ }
319
+ async function refreshQueueMessageProcessingOwnership(args) {
320
+ await getStateAdapter().connect();
321
+ const nowMs = Date.now();
322
+ const payload = JSON.stringify({
323
+ status: "processing",
324
+ updatedAtMs: nowMs,
325
+ ownerToken: args.ownerToken,
326
+ ...args.queueMessageId ? { queueMessageId: args.queueMessageId } : {}
327
+ });
328
+ const result = await getRedisStateAdapter().getClient().eval(UPDATE_PROCESSING_STATE_IF_OWNER_SCRIPT, {
329
+ keys: [queueMessageKey(args.rawKey)],
330
+ arguments: [args.ownerToken, String(QUEUE_MESSAGE_PROCESSING_TTL_MS), payload]
331
+ });
332
+ return result === 1;
333
+ }
334
+ async function completeQueueMessageProcessingOwnership(args) {
335
+ await getStateAdapter().connect();
336
+ const payload = JSON.stringify({
337
+ status: "completed",
338
+ updatedAtMs: Date.now(),
339
+ ownerToken: args.ownerToken,
340
+ ...args.queueMessageId ? { queueMessageId: args.queueMessageId } : {}
341
+ });
342
+ const result = await getRedisStateAdapter().getClient().eval(UPDATE_PROCESSING_STATE_IF_OWNER_SCRIPT, {
343
+ keys: [queueMessageKey(args.rawKey)],
344
+ arguments: [args.ownerToken, String(QUEUE_MESSAGE_COMPLETED_TTL_MS), payload]
345
+ });
346
+ return result === 1;
347
+ }
348
+ async function failQueueMessageProcessingOwnership(args) {
349
+ await getStateAdapter().connect();
350
+ const payload = JSON.stringify({
351
+ status: "failed",
352
+ updatedAtMs: Date.now(),
353
+ ownerToken: args.ownerToken,
354
+ errorMessage: args.errorMessage,
355
+ ...args.queueMessageId ? { queueMessageId: args.queueMessageId } : {}
356
+ });
357
+ const result = await getRedisStateAdapter().getClient().eval(UPDATE_PROCESSING_STATE_IF_OWNER_SCRIPT, {
358
+ keys: [queueMessageKey(args.rawKey)],
359
+ arguments: [args.ownerToken, String(QUEUE_MESSAGE_FAILED_TTL_MS), payload]
360
+ });
361
+ return result === 1;
362
+ }
363
+ async function getAgentTurnSessionCheckpoint(conversationId, sessionId) {
364
+ await getStateAdapter().connect();
365
+ const value = await getStateAdapter().get(agentTurnSessionKey(conversationId, sessionId));
366
+ return parseAgentTurnSessionCheckpoint(value);
367
+ }
368
+ async function upsertAgentTurnSessionCheckpoint(args) {
369
+ await getStateAdapter().connect();
370
+ const existing = await getAgentTurnSessionCheckpoint(args.conversationId, args.sessionId);
371
+ const checkpoint = {
372
+ checkpointVersion: (existing?.checkpointVersion ?? 0) + 1,
373
+ conversationId: args.conversationId,
374
+ sessionId: args.sessionId,
375
+ sliceId: args.sliceId,
376
+ state: args.state,
377
+ updatedAtMs: Date.now(),
378
+ piMessages: Array.isArray(args.piMessages) ? args.piMessages : [],
379
+ ...args.errorMessage ? { errorMessage: args.errorMessage } : {},
380
+ ...typeof args.resumedFromSliceId === "number" ? { resumedFromSliceId: args.resumedFromSliceId } : {}
381
+ };
382
+ const ttlMs = Math.max(1, args.ttlMs ?? AGENT_TURN_SESSION_TTL_MS);
383
+ await getStateAdapter().set(agentTurnSessionKey(args.conversationId, args.sessionId), JSON.stringify(checkpoint), ttlMs);
384
+ return checkpoint;
385
+ }
386
+
387
+ // src/chat/sandbox/runtime-dependency-snapshots.ts
388
+ import { createHash } from "crypto";
389
+ import { Sandbox } from "@vercel/sandbox";
390
+
391
+ // src/chat/plugins/registry.ts
392
+ import { readFileSync, readdirSync, statSync } from "fs";
393
+ import path2 from "path";
394
+ import { parse as parseYaml } from "yaml";
395
+
396
+ // src/chat/home.ts
397
+ import fs from "fs";
398
+ import path from "path";
399
+ function homeDir() {
400
+ return resolveHomeDir();
401
+ }
402
+ function unique(values) {
403
+ return [...new Set(values)];
404
+ }
405
+ function pathExists(targetPath) {
406
+ try {
407
+ fs.accessSync(targetPath);
408
+ return true;
409
+ } catch {
410
+ return false;
411
+ }
412
+ }
413
+ function hasAnyDataMarkers(appDir) {
414
+ return pathExists(path.join(appDir, "SOUL.md"));
415
+ }
416
+ function scoreAppCandidate(appDir) {
417
+ let score = 0;
418
+ if (pathExists(path.join(appDir, "SOUL.md"))) {
419
+ score += 4;
420
+ }
421
+ if (pathExists(path.join(appDir, "ABOUT.md"))) {
422
+ score += 2;
423
+ }
424
+ if (pathExists(path.join(appDir, "skills"))) {
425
+ score += 1;
426
+ }
427
+ if (pathExists(path.join(appDir, "plugins"))) {
428
+ score += 1;
429
+ }
430
+ return score;
431
+ }
432
+ function resolveCandidateAppDirs(cwd, projectRoots) {
433
+ const roots = projectRoots ?? discoverProjectRoots(cwd);
434
+ const resolved = [];
435
+ const seen = /* @__PURE__ */ new Set();
436
+ for (const root of roots) {
437
+ const appDir = path.resolve(root, "app");
438
+ if (!pathExists(appDir)) {
439
+ continue;
440
+ }
441
+ if (seen.has(appDir)) {
442
+ continue;
443
+ }
444
+ seen.add(appDir);
445
+ resolved.push(appDir);
446
+ }
447
+ return resolved;
448
+ }
449
+ function resolveHomeDir(cwd = process.cwd(), options) {
450
+ const resolvedCwd = path.resolve(cwd);
451
+ const directApp = path.resolve(resolvedCwd, "app");
452
+ if (pathExists(directApp) && hasAnyDataMarkers(directApp)) {
453
+ return directApp;
454
+ }
455
+ const candidates = resolveCandidateAppDirs(resolvedCwd, options?.projectRoots);
456
+ if (candidates.length === 0) {
457
+ return directApp;
458
+ }
459
+ candidates.sort((left, right) => {
460
+ const leftScore = scoreAppCandidate(left);
461
+ const rightScore = scoreAppCandidate(right);
462
+ if (leftScore !== rightScore) {
463
+ return rightScore - leftScore;
464
+ }
465
+ const leftDistance = path.relative(resolvedCwd, left).split(path.sep).length;
466
+ const rightDistance = path.relative(resolvedCwd, right).split(path.sep).length;
467
+ if (leftDistance !== rightDistance) {
468
+ return leftDistance - rightDistance;
469
+ }
470
+ return left.localeCompare(right);
471
+ });
472
+ return candidates[0];
473
+ }
474
+ function resolveContentRoots(subdir) {
475
+ if (subdir === "data") {
476
+ return [homeDir()];
477
+ }
478
+ if (subdir === "skills") {
479
+ return [path.join(homeDir(), "skills"), path.resolve(process.cwd(), "skills")];
480
+ }
481
+ return [path.join(homeDir(), "plugins")];
482
+ }
483
+ function dataRoots() {
484
+ return unique(resolveContentRoots("data"));
485
+ }
486
+ function skillRoots() {
487
+ return unique(resolveContentRoots("skills"));
488
+ }
489
+ function pluginRoots() {
490
+ return unique(resolveContentRoots("plugins"));
491
+ }
492
+ function soulPathCandidates() {
493
+ const candidates = dataRoots().map((root) => path.join(root, "SOUL.md"));
494
+ return unique(candidates);
495
+ }
496
+
497
+ // src/chat/plugins/github-app-broker.ts
498
+ import { createPrivateKey, createSign, randomUUID } from "crypto";
499
+
500
+ // src/chat/plugins/auth-token-placeholder.ts
501
+ var DEFAULT_PLACEHOLDERS = {
502
+ "oauth-bearer": "host_managed_credential",
503
+ "github-app": "ghp_host_managed_credential"
504
+ };
505
+ function resolveAuthTokenPlaceholder(credentials) {
506
+ return credentials.authTokenPlaceholder?.trim() || DEFAULT_PLACEHOLDERS[credentials.type];
507
+ }
508
+
509
+ // src/chat/plugins/github-app-broker.ts
510
+ var MAX_LEASE_MS = 60 * 60 * 1e3;
511
+ function normalizeTargetScope(target) {
512
+ const owner = target?.owner?.trim().toLowerCase();
513
+ const repo = target?.repo?.trim().toLowerCase();
514
+ if (!owner || !repo) {
515
+ return "all";
516
+ }
517
+ return `${owner}/${repo}`;
518
+ }
519
+ function base64Url(input) {
520
+ return Buffer.from(input).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
521
+ }
522
+ function normalizePrivateKey(raw) {
523
+ let normalized = raw.trim();
524
+ if (normalized.startsWith('"') && normalized.endsWith('"') || normalized.startsWith("'") && normalized.endsWith("'")) {
525
+ normalized = normalized.slice(1, -1);
526
+ }
527
+ normalized = normalized.replace(/\r\n/g, "\n");
528
+ if (normalized.includes("\\n")) {
529
+ normalized = normalized.replace(/\\n/g, "\n");
530
+ }
531
+ if (!normalized.includes("-----BEGIN")) {
532
+ try {
533
+ const decoded = Buffer.from(normalized, "base64").toString("utf8").trim();
534
+ if (decoded.includes("-----BEGIN")) {
535
+ normalized = decoded;
536
+ }
537
+ } catch {
538
+ }
539
+ }
540
+ return normalized;
541
+ }
542
+ function getPrivateKey(envName) {
543
+ const raw = process.env[envName];
544
+ if (!raw) {
545
+ throw new Error(`Missing ${envName}`);
546
+ }
547
+ const normalized = normalizePrivateKey(raw);
548
+ let key;
549
+ try {
550
+ key = createPrivateKey({ key: normalized, format: "pem" });
551
+ } catch {
552
+ throw new Error(
553
+ `Invalid ${envName}: expected a PEM-encoded RSA private key (raw PEM, escaped newlines, or base64-encoded PEM)`
554
+ );
555
+ }
556
+ if (key.asymmetricKeyType !== "rsa") {
557
+ throw new Error(`Invalid ${envName}: GitHub App signing requires an RSA private key`);
558
+ }
559
+ return key;
560
+ }
561
+ function createAppJwt(appId, privateKeyEnv) {
562
+ const now = Math.floor(Date.now() / 1e3);
563
+ const header = { alg: "RS256", typ: "JWT" };
564
+ const payload = { iat: now - 60, exp: now + 9 * 60, iss: appId };
565
+ const encodedHeader = base64Url(JSON.stringify(header));
566
+ const encodedPayload = base64Url(JSON.stringify(payload));
567
+ const signingInput = `${encodedHeader}.${encodedPayload}`;
568
+ const signer = createSign("RSA-SHA256");
569
+ signer.update(signingInput);
570
+ signer.end();
571
+ const signature = signer.sign(getPrivateKey(privateKeyEnv)).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
572
+ return `${signingInput}.${signature}`;
573
+ }
574
+ async function githubRequest(apiBase, path3, params) {
575
+ const response = await fetch(`${apiBase}${path3}`, {
576
+ method: params.method ?? "GET",
577
+ headers: {
578
+ Accept: "application/vnd.github+json",
579
+ Authorization: `Bearer ${params.token}`,
580
+ "X-GitHub-Api-Version": "2022-11-28",
581
+ ...params.body ? { "Content-Type": "application/json" } : {}
582
+ },
583
+ ...params.body ? { body: JSON.stringify(params.body) } : {}
584
+ });
585
+ const text = await response.text();
586
+ let parsed = void 0;
587
+ if (text) {
588
+ try {
589
+ parsed = JSON.parse(text);
590
+ } catch {
591
+ parsed = void 0;
592
+ }
593
+ }
594
+ if (!response.ok) {
595
+ const message = parsed && typeof parsed === "object" && "message" in parsed && typeof parsed.message === "string" ? parsed.message : `GitHub API error ${response.status}`;
596
+ throw new Error(message);
597
+ }
598
+ return parsed;
599
+ }
600
+ function capabilityToPermissions(capability, pluginName) {
601
+ if (capability === `${pluginName}.issues.read`) {
602
+ return { issues: "read" };
603
+ }
604
+ if (capability === `${pluginName}.issues.write` || capability === `${pluginName}.issues.comment` || capability === `${pluginName}.labels.write`) {
605
+ return { issues: "write" };
606
+ }
607
+ throw new Error(`Unsupported GitHub capability: ${capability}`);
608
+ }
609
+ function createGitHubAppBroker(manifest, credentials) {
610
+ const tokenCache = /* @__PURE__ */ new Map();
611
+ const provider = manifest.name;
612
+ const { apiDomains, authTokenEnv, appIdEnv, privateKeyEnv, installationIdEnv } = credentials;
613
+ const apiBase = `https://${apiDomains[0]}`;
614
+ const placeholder = resolveAuthTokenPlaceholder(credentials);
615
+ return {
616
+ async issue(input) {
617
+ const permissions = capabilityToPermissions(input.capability, provider);
618
+ const appId = process.env[appIdEnv];
619
+ if (!appId) {
620
+ throw new Error(`Missing ${appIdEnv}`);
621
+ }
622
+ const installationIdRaw = process.env[installationIdEnv]?.trim();
623
+ if (!installationIdRaw) {
624
+ throw new Error(`Missing ${installationIdEnv}`);
625
+ }
626
+ const installationId = Number(installationIdRaw);
627
+ if (!Number.isFinite(installationId)) {
628
+ throw new Error(`Invalid ${installationIdEnv}`);
629
+ }
630
+ const targetScope = normalizeTargetScope(input.target);
631
+ const cacheKey = `${installationId}:${input.capability}:${targetScope}`;
632
+ const cached = tokenCache.get(cacheKey);
633
+ const now = Date.now();
634
+ if (cached && cached.expiresAt - now > 2 * 60 * 1e3) {
635
+ return {
636
+ id: randomUUID(),
637
+ provider,
638
+ capability: input.capability,
639
+ env: { [authTokenEnv]: placeholder },
640
+ headerTransforms: apiDomains.map((domain) => ({
641
+ domain,
642
+ headers: {
643
+ Authorization: `Bearer ${cached.token}`
644
+ }
645
+ })),
646
+ expiresAt: new Date(cached.expiresAt).toISOString(),
647
+ metadata: {
648
+ installationId: String(cached.installationId),
649
+ targetScope,
650
+ reason: input.reason
651
+ }
652
+ };
653
+ }
654
+ const appJwt = createAppJwt(appId, privateKeyEnv);
655
+ const repositoryName = input.target?.repo?.trim().toLowerCase();
656
+ const tokenRequestBody = {
657
+ permissions
658
+ };
659
+ if (repositoryName) {
660
+ tokenRequestBody.repositories = [repositoryName];
661
+ }
662
+ const accessTokenResponse = await githubRequest(
663
+ apiBase,
664
+ `/app/installations/${installationId}/access_tokens`,
665
+ {
666
+ method: "POST",
667
+ token: appJwt,
668
+ body: tokenRequestBody
669
+ }
670
+ );
671
+ const providerExpiresAtMs = Date.parse(accessTokenResponse.expires_at);
672
+ const expiresAtMs = Math.min(providerExpiresAtMs, Date.now() + MAX_LEASE_MS);
673
+ tokenCache.set(cacheKey, {
674
+ installationId,
675
+ token: accessTokenResponse.token,
676
+ expiresAt: expiresAtMs
677
+ });
678
+ return {
679
+ id: randomUUID(),
680
+ provider,
681
+ capability: input.capability,
682
+ env: { [authTokenEnv]: placeholder },
683
+ headerTransforms: apiDomains.map((domain) => ({
684
+ domain,
685
+ headers: {
686
+ Authorization: `Bearer ${accessTokenResponse.token}`
687
+ }
688
+ })),
689
+ expiresAt: new Date(expiresAtMs).toISOString(),
690
+ metadata: {
691
+ installationId: String(installationId),
692
+ targetScope,
693
+ reason: input.reason
694
+ }
695
+ };
696
+ }
697
+ };
698
+ }
699
+
700
+ // src/chat/plugins/oauth-bearer-broker.ts
701
+ import { randomUUID as randomUUID2 } from "crypto";
702
+
703
+ // src/chat/credentials/broker.ts
704
+ var CredentialUnavailableError = class extends Error {
705
+ provider;
706
+ constructor(provider, message) {
707
+ super(message);
708
+ this.name = "CredentialUnavailableError";
709
+ this.provider = provider;
710
+ }
711
+ };
712
+
713
+ // src/chat/plugins/oauth-bearer-broker.ts
714
+ var MAX_LEASE_MS2 = 60 * 60 * 1e3;
715
+ var REFRESH_BUFFER_MS = 5 * 60 * 1e3;
716
+ async function refreshAccessToken(refreshToken, oauth) {
717
+ const clientId = process.env[oauth.clientIdEnv]?.trim();
718
+ const clientSecret = process.env[oauth.clientSecretEnv]?.trim();
719
+ if (!clientId || !clientSecret) {
720
+ throw new Error(`Missing ${oauth.clientIdEnv} or ${oauth.clientSecretEnv} for token refresh`);
721
+ }
722
+ const response = await fetch(oauth.tokenEndpoint, {
723
+ method: "POST",
724
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
725
+ body: new URLSearchParams({
726
+ grant_type: "refresh_token",
727
+ refresh_token: refreshToken,
728
+ client_id: clientId,
729
+ client_secret: clientSecret
730
+ })
731
+ });
732
+ if (!response.ok) {
733
+ throw new Error(`Token refresh failed: ${response.status}`);
734
+ }
735
+ const data = await response.json();
736
+ if (!data.access_token || !data.refresh_token || typeof data.expires_in !== "number") {
737
+ throw new Error("Token refresh returned malformed response");
738
+ }
739
+ return {
740
+ accessToken: data.access_token,
741
+ refreshToken: data.refresh_token,
742
+ expiresIn: data.expires_in
743
+ };
744
+ }
745
+ function createOAuthBearerBroker(manifest, credentials, deps) {
746
+ const provider = manifest.name;
747
+ const supportedCapabilities = new Set(manifest.capabilities);
748
+ const { apiDomains, authTokenEnv } = credentials;
749
+ const authTokenPlaceholder = resolveAuthTokenPlaceholder(credentials);
750
+ function buildLease(token, capability, expiresAtMs, reason) {
751
+ return {
752
+ id: randomUUID2(),
753
+ provider,
754
+ capability,
755
+ env: { [authTokenEnv]: authTokenPlaceholder },
756
+ headerTransforms: apiDomains.map((domain) => ({
757
+ domain,
758
+ headers: { Authorization: `Bearer ${token}` }
759
+ })),
760
+ expiresAt: new Date(expiresAtMs).toISOString(),
761
+ metadata: { reason }
762
+ };
763
+ }
764
+ return {
765
+ async issue(input) {
766
+ if (!supportedCapabilities.has(input.capability)) {
767
+ throw new Error(`Unsupported ${provider} capability: ${input.capability}`);
768
+ }
769
+ if (input.requesterId && deps.userTokenStore) {
770
+ const stored = await deps.userTokenStore.get(input.requesterId, provider);
771
+ if (stored) {
772
+ const now = Date.now();
773
+ if (stored.expiresAt - now < REFRESH_BUFFER_MS && stored.refreshToken && manifest.oauth) {
774
+ try {
775
+ const refreshed = await refreshAccessToken(stored.refreshToken, manifest.oauth);
776
+ const expiresAt = Date.now() + refreshed.expiresIn * 1e3;
777
+ await deps.userTokenStore.set(input.requesterId, provider, {
778
+ accessToken: refreshed.accessToken,
779
+ refreshToken: refreshed.refreshToken,
780
+ expiresAt
781
+ });
782
+ const leaseExpiry = Math.min(expiresAt, Date.now() + MAX_LEASE_MS2);
783
+ return buildLease(refreshed.accessToken, input.capability, leaseExpiry, input.reason);
784
+ } catch {
785
+ if (stored.expiresAt > Date.now()) {
786
+ const leaseExpiry = Math.min(stored.expiresAt, Date.now() + MAX_LEASE_MS2);
787
+ return buildLease(stored.accessToken, input.capability, leaseExpiry, input.reason);
788
+ }
789
+ throw new CredentialUnavailableError(
790
+ provider,
791
+ `Your ${provider} connection has expired.`
792
+ );
793
+ }
794
+ }
795
+ if (stored.expiresAt > Date.now()) {
796
+ const leaseExpiry = Math.min(stored.expiresAt, Date.now() + MAX_LEASE_MS2);
797
+ return buildLease(stored.accessToken, input.capability, leaseExpiry, input.reason);
798
+ }
799
+ throw new CredentialUnavailableError(
800
+ provider,
801
+ `Your ${provider} connection has expired.`
802
+ );
803
+ }
804
+ throw new CredentialUnavailableError(
805
+ provider,
806
+ `No ${provider} credentials available.`
807
+ );
808
+ }
809
+ const envToken = process.env[authTokenEnv]?.trim();
810
+ if (envToken) {
811
+ const expiresAtMs = Date.now() + MAX_LEASE_MS2;
812
+ return buildLease(envToken, input.capability, expiresAtMs, input.reason);
813
+ }
814
+ throw new CredentialUnavailableError(
815
+ provider,
816
+ `No ${provider} credentials available.`
817
+ );
818
+ }
819
+ };
820
+ }
821
+
822
+ // src/chat/plugins/registry.ts
823
+ var PLUGIN_NAME_RE = /^[a-z][a-z0-9-]*$/;
824
+ var SHORT_CAPABILITY_RE = /^[a-z0-9]+(\.[a-z0-9-]+)*$/;
825
+ var SHORT_CONFIG_KEY_RE = /^[a-z0-9]+(\.[a-z0-9-]+)*$/;
826
+ var AUTH_TOKEN_ENV_RE = /^[A-Z][A-Z0-9_]*$/;
827
+ var API_DOMAIN_RE = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
828
+ var RUNTIME_POSTINSTALL_CMD_RE = /^[A-Za-z0-9._/-]+$/;
829
+ function toRecord(value, errorMessage) {
830
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
831
+ throw new Error(errorMessage);
832
+ }
833
+ return value;
834
+ }
835
+ function requireStringField(record, field, errorMessage) {
836
+ const value = record[field];
837
+ if (typeof value !== "string" || !value.trim()) {
838
+ throw new Error(errorMessage);
839
+ }
840
+ return value.trim();
841
+ }
842
+ function requireEnvVarField(record, field, pluginName) {
843
+ const value = requireStringField(record, field, `Plugin ${pluginName} ${field} must be a non-empty string`);
844
+ if (!AUTH_TOKEN_ENV_RE.test(value)) {
845
+ throw new Error(`Plugin ${pluginName} ${field} must be an uppercase env var name`);
846
+ }
847
+ return value;
848
+ }
849
+ function requireHttpsUrlField(record, field, pluginName) {
850
+ const value = requireStringField(record, field, `Plugin ${pluginName} oauth.${field} must be a non-empty string`);
851
+ let parsed;
852
+ try {
853
+ parsed = new URL(value);
854
+ } catch {
855
+ throw new Error(`Plugin ${pluginName} oauth.${field} must be a valid URL`);
856
+ }
857
+ if (parsed.protocol !== "https:") {
858
+ throw new Error(`Plugin ${pluginName} oauth.${field} must use https`);
859
+ }
860
+ return value;
861
+ }
862
+ function normalizeApiDomain(rawDomain, name) {
863
+ const domain = typeof rawDomain === "string" ? rawDomain.trim().toLowerCase() : "";
864
+ if (!domain) {
865
+ throw new Error(`Plugin ${name} credentials.api-domains entries must be non-empty strings`);
866
+ }
867
+ if (!API_DOMAIN_RE.test(domain)) {
868
+ throw new Error(`Plugin ${name} credentials.api-domains entries must be valid domain names`);
869
+ }
870
+ return domain;
871
+ }
872
+ function parseBaseCredentialFields(data, name) {
873
+ const rawDomains = data["api-domains"];
874
+ if (!Array.isArray(rawDomains) || rawDomains.length === 0) {
875
+ throw new Error(`Plugin ${name} credentials.api-domains must be a non-empty array of strings`);
876
+ }
877
+ const apiDomains = rawDomains.map((rawDomain) => normalizeApiDomain(rawDomain, name));
878
+ const authTokenEnv = requireEnvVarField(data, "auth-token-env", name);
879
+ const authTokenPlaceholderRaw = data["auth-token-placeholder"];
880
+ if (authTokenPlaceholderRaw !== void 0 && (typeof authTokenPlaceholderRaw !== "string" || !authTokenPlaceholderRaw.trim())) {
881
+ throw new Error(`Plugin ${name} credentials.auth-token-placeholder must be a non-empty string when provided`);
882
+ }
883
+ return {
884
+ apiDomains,
885
+ authTokenEnv,
886
+ ...typeof authTokenPlaceholderRaw === "string" ? { authTokenPlaceholder: authTokenPlaceholderRaw.trim() } : {}
887
+ };
888
+ }
889
+ function parseCredentials(data, name) {
890
+ const type = data.type;
891
+ if (type === "oauth-bearer") {
892
+ const base = parseBaseCredentialFields(data, name);
893
+ return { type: "oauth-bearer", ...base };
894
+ }
895
+ if (type === "github-app") {
896
+ const base = parseBaseCredentialFields(data, name);
897
+ const appIdEnv = requireEnvVarField(data, "app-id-env", name);
898
+ const privateKeyEnv = requireEnvVarField(data, "private-key-env", name);
899
+ const installationIdEnv = requireEnvVarField(data, "installation-id-env", name);
900
+ return { type: "github-app", ...base, appIdEnv, privateKeyEnv, installationIdEnv };
901
+ }
902
+ throw new Error(`Plugin ${name} has unsupported credentials.type: "${type}"`);
903
+ }
904
+ function parseRuntimeDependencies(data, name) {
905
+ if (data === void 0) {
906
+ return void 0;
907
+ }
908
+ if (!Array.isArray(data)) {
909
+ throw new Error(`Plugin ${name} runtime-dependencies must be an array`);
910
+ }
911
+ const parsed = [];
912
+ const seen = /* @__PURE__ */ new Set();
913
+ for (const entry of data) {
914
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
915
+ throw new Error(`Plugin ${name} runtime-dependencies entries must be objects`);
916
+ }
917
+ const record = entry;
918
+ const type = record.type;
919
+ const packageName = record.package;
920
+ const packageUrl = record.url;
921
+ const version = record.version;
922
+ const sha256 = record.sha256;
923
+ if (typeof type !== "string" || type !== "npm" && type !== "system") {
924
+ throw new Error(`Plugin ${name} runtime dependency type must be "npm" or "system"`);
925
+ }
926
+ const normalizedPackage = typeof packageName === "string" ? packageName.trim() : "";
927
+ const normalizedUrl = typeof packageUrl === "string" ? packageUrl.trim() : "";
928
+ if (type === "npm") {
929
+ if (!normalizedPackage) {
930
+ throw new Error(`Plugin ${name} runtime dependency package must be a non-empty string`);
931
+ }
932
+ if (packageUrl !== void 0 || sha256 !== void 0) {
933
+ throw new Error(`Plugin ${name} npm runtime dependencies must only include package/version fields`);
934
+ }
935
+ const normalizedVersion = typeof version === "string" ? version.trim() : "latest";
936
+ if (!normalizedVersion) {
937
+ throw new Error(`Plugin ${name} runtime dependency version must be a non-empty string when provided`);
938
+ }
939
+ const dedupeKey2 = `${type}:${normalizedPackage}:${normalizedVersion}`;
940
+ if (seen.has(dedupeKey2)) {
941
+ continue;
942
+ }
943
+ seen.add(dedupeKey2);
944
+ parsed.push({
945
+ type: "npm",
946
+ package: normalizedPackage,
947
+ version: normalizedVersion
948
+ });
949
+ continue;
950
+ }
951
+ if (version !== void 0) {
952
+ throw new Error(`Plugin ${name} system runtime dependencies must not include a version`);
953
+ }
954
+ if (normalizedPackage && normalizedUrl) {
955
+ throw new Error(`Plugin ${name} system runtime dependencies must specify either package or url, not both`);
956
+ }
957
+ if (!normalizedPackage && !normalizedUrl) {
958
+ throw new Error(`Plugin ${name} system runtime dependencies must specify package or url`);
959
+ }
960
+ if (normalizedPackage) {
961
+ if (sha256 !== void 0) {
962
+ throw new Error(`Plugin ${name} system runtime dependency package entries must not include sha256`);
963
+ }
964
+ const dedupeKey2 = `${type}:package:${normalizedPackage}`;
965
+ if (seen.has(dedupeKey2)) {
966
+ continue;
967
+ }
968
+ seen.add(dedupeKey2);
969
+ parsed.push({
970
+ type: "system",
971
+ package: normalizedPackage
972
+ });
973
+ continue;
974
+ }
975
+ if (!/^https:\/\//i.test(normalizedUrl)) {
976
+ throw new Error(`Plugin ${name} system runtime dependency url must be an https URL`);
977
+ }
978
+ const normalizedSha256 = typeof sha256 === "string" ? sha256.trim().toLowerCase() : "";
979
+ if (!/^[a-f0-9]{64}$/.test(normalizedSha256)) {
980
+ throw new Error(`Plugin ${name} system runtime dependency url entries must include a valid sha256`);
981
+ }
982
+ const dedupeKey = `${type}:url:${normalizedUrl}:${normalizedSha256}`;
983
+ if (seen.has(dedupeKey)) {
984
+ continue;
985
+ }
986
+ seen.add(dedupeKey);
987
+ parsed.push({
988
+ type: "system",
989
+ url: normalizedUrl,
990
+ sha256: normalizedSha256
991
+ });
992
+ }
993
+ return parsed.length > 0 ? parsed : void 0;
994
+ }
995
+ function parseRuntimePostinstall(data, name) {
996
+ if (data === void 0) {
997
+ return void 0;
998
+ }
999
+ if (!Array.isArray(data)) {
1000
+ throw new Error(`Plugin ${name} runtime-postinstall must be an array`);
1001
+ }
1002
+ const parsed = [];
1003
+ for (const entry of data) {
1004
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
1005
+ throw new Error(`Plugin ${name} runtime-postinstall entries must be objects`);
1006
+ }
1007
+ const record = entry;
1008
+ const cmd = typeof record.cmd === "string" ? record.cmd.trim() : "";
1009
+ if (!cmd) {
1010
+ throw new Error(`Plugin ${name} runtime-postinstall cmd must be a non-empty string`);
1011
+ }
1012
+ if (!RUNTIME_POSTINSTALL_CMD_RE.test(cmd)) {
1013
+ throw new Error(
1014
+ `Plugin ${name} runtime-postinstall cmd must be a single executable token (letters, digits, ., _, /, -)`
1015
+ );
1016
+ }
1017
+ const argsRaw = record.args;
1018
+ if (argsRaw !== void 0 && (!Array.isArray(argsRaw) || !argsRaw.every((arg) => typeof arg === "string"))) {
1019
+ throw new Error(`Plugin ${name} runtime-postinstall args must be an array of strings when provided`);
1020
+ }
1021
+ const sudoRaw = record.sudo;
1022
+ if (sudoRaw !== void 0 && typeof sudoRaw !== "boolean") {
1023
+ throw new Error(`Plugin ${name} runtime-postinstall sudo must be a boolean when provided`);
1024
+ }
1025
+ const normalizedArgs = Array.isArray(argsRaw) ? argsRaw.map((arg) => arg.trim()).filter((arg) => arg.length > 0) : void 0;
1026
+ parsed.push({
1027
+ cmd,
1028
+ ...normalizedArgs && normalizedArgs.length > 0 ? { args: normalizedArgs } : {},
1029
+ ...typeof sudoRaw === "boolean" ? { sudo: sudoRaw } : {}
1030
+ });
1031
+ }
1032
+ return parsed.length > 0 ? parsed : void 0;
1033
+ }
1034
+ function parseManifest(raw, dir) {
1035
+ const data = toRecord(parseYaml(raw), `Invalid plugin manifest in ${dir}: expected an object`);
1036
+ const rawName = data.name;
1037
+ if (typeof rawName !== "string" || !PLUGIN_NAME_RE.test(rawName)) {
1038
+ throw new Error(`Invalid plugin name in ${dir}: "${rawName}"`);
1039
+ }
1040
+ const name = rawName;
1041
+ const rawDescription = data.description;
1042
+ if (typeof rawDescription !== "string" || !rawDescription.trim()) {
1043
+ throw new Error(`Invalid plugin description in ${dir}`);
1044
+ }
1045
+ const description = rawDescription;
1046
+ const rawCapabilities = data.capabilities;
1047
+ if (rawCapabilities !== void 0 && !Array.isArray(rawCapabilities)) {
1048
+ throw new Error(`Plugin ${name} capabilities must be an array when provided`);
1049
+ }
1050
+ const capabilities = [];
1051
+ for (const cap of rawCapabilities ?? []) {
1052
+ if (typeof cap !== "string" || !SHORT_CAPABILITY_RE.test(cap)) {
1053
+ throw new Error(`Invalid capability token "${cap}" in plugin ${name}`);
1054
+ }
1055
+ capabilities.push(`${name}.${cap}`);
1056
+ }
1057
+ const rawConfigKeys = data["config-keys"];
1058
+ if (rawConfigKeys !== void 0 && !Array.isArray(rawConfigKeys)) {
1059
+ throw new Error(`Plugin ${name} config-keys must be an array when provided`);
1060
+ }
1061
+ const configKeys = [];
1062
+ for (const key of rawConfigKeys ?? []) {
1063
+ if (typeof key !== "string" || !SHORT_CONFIG_KEY_RE.test(key)) {
1064
+ throw new Error(`Invalid config key "${key}" in plugin ${name}`);
1065
+ }
1066
+ configKeys.push(`${name}.${key}`);
1067
+ }
1068
+ const credentialsRaw = data.credentials;
1069
+ if (credentialsRaw !== void 0) {
1070
+ toRecord(credentialsRaw, `Plugin ${name} credentials must be an object when provided`);
1071
+ }
1072
+ const credentials = credentialsRaw ? parseCredentials(credentialsRaw, name) : void 0;
1073
+ const runtimeDependencies = parseRuntimeDependencies(data["runtime-dependencies"], name);
1074
+ const runtimePostinstall = parseRuntimePostinstall(data["runtime-postinstall"], name);
1075
+ const manifest = {
1076
+ name,
1077
+ description,
1078
+ capabilities,
1079
+ configKeys,
1080
+ ...credentials ? { credentials } : {},
1081
+ ...runtimeDependencies ? { runtimeDependencies } : {},
1082
+ ...runtimePostinstall ? { runtimePostinstall } : {}
1083
+ };
1084
+ const oauthRaw = data.oauth ? toRecord(data.oauth, `Plugin ${name} oauth must be an object`) : void 0;
1085
+ if (oauthRaw) {
1086
+ if (!credentials) {
1087
+ throw new Error(`Plugin ${name} oauth requires credentials`);
1088
+ }
1089
+ if (credentials.type !== "oauth-bearer") {
1090
+ throw new Error(`Plugin ${name} oauth requires credentials.type "oauth-bearer"`);
1091
+ }
1092
+ manifest.oauth = {
1093
+ clientIdEnv: requireEnvVarField(oauthRaw, "client-id-env", name),
1094
+ clientSecretEnv: requireEnvVarField(oauthRaw, "client-secret-env", name),
1095
+ authorizeEndpoint: requireHttpsUrlField(oauthRaw, "authorize-endpoint", name),
1096
+ tokenEndpoint: requireHttpsUrlField(oauthRaw, "token-endpoint", name),
1097
+ scope: requireStringField(oauthRaw, "scope", `Plugin ${name} oauth.scope must be a non-empty string`)
1098
+ };
1099
+ }
1100
+ const targetRaw = data.target ? toRecord(data.target, `Plugin ${name} target must be an object`) : void 0;
1101
+ if (targetRaw) {
1102
+ if (targetRaw.type !== "repo") {
1103
+ throw new Error(`Plugin ${name} target.type must be "repo"`);
1104
+ }
1105
+ const rawConfigKey = targetRaw["config-key"];
1106
+ if (typeof rawConfigKey !== "string" || !rawConfigKey.trim()) {
1107
+ throw new Error(`Plugin ${name} target.config-key must be a non-empty string`);
1108
+ }
1109
+ if (!SHORT_CONFIG_KEY_RE.test(rawConfigKey)) {
1110
+ throw new Error(`Plugin ${name} target.config-key "${rawConfigKey}" is invalid`);
1111
+ }
1112
+ const qualifiedKey = `${name}.${rawConfigKey}`;
1113
+ if (!configKeys.includes(qualifiedKey)) {
1114
+ throw new Error(`Plugin ${name} target.config-key "${rawConfigKey}" must be listed in config-keys`);
1115
+ }
1116
+ manifest.target = { type: "repo", configKey: qualifiedKey };
1117
+ }
1118
+ return manifest;
1119
+ }
1120
+ var pluginDefinitions = [];
1121
+ var capabilityToPlugin = /* @__PURE__ */ new Map();
1122
+ var pluginConfigKeys = /* @__PURE__ */ new Set();
1123
+ var pluginsByName = /* @__PURE__ */ new Map();
1124
+ var packageSkillRoots = /* @__PURE__ */ new Set();
1125
+ var pluginsLoaded = false;
1126
+ function registerPluginManifest(raw, pluginDir) {
1127
+ const manifest = parseManifest(raw, pluginDir);
1128
+ if (pluginsByName.has(manifest.name)) {
1129
+ return;
1130
+ }
1131
+ for (const cap of manifest.capabilities) {
1132
+ if (capabilityToPlugin.has(cap)) {
1133
+ throw new Error(`Duplicate capability "${cap}" in plugin "${manifest.name}"`);
1134
+ }
1135
+ }
1136
+ const definition = {
1137
+ manifest,
1138
+ dir: pluginDir,
1139
+ skillsDir: path2.join(pluginDir, "skills")
1140
+ };
1141
+ pluginDefinitions.push(definition);
1142
+ pluginsByName.set(manifest.name, definition);
1143
+ for (const cap of manifest.capabilities) {
1144
+ capabilityToPlugin.set(cap, definition);
1145
+ }
1146
+ for (const key of manifest.configKeys) {
1147
+ pluginConfigKeys.add(key);
1148
+ }
1149
+ }
1150
+ function loadPlugins() {
1151
+ if (pluginsLoaded) return;
1152
+ pluginsLoaded = true;
1153
+ const packagedContent = discoverInstalledPluginPackageContent();
1154
+ const localRoots = pluginRoots();
1155
+ const roots = [...localRoots, ...packagedContent.manifestRoots];
1156
+ for (const pluginsRoot of roots) {
1157
+ let entries;
1158
+ let rootStat;
1159
+ try {
1160
+ rootStat = statSync(pluginsRoot);
1161
+ } catch (error) {
1162
+ logWarn("plugin_root_read_failed", {}, {
1163
+ "file.directory": pluginsRoot,
1164
+ "error.message": error instanceof Error ? error.message : String(error)
1165
+ }, "Failed to read plugin root");
1166
+ continue;
1167
+ }
1168
+ if (rootStat.isDirectory()) {
1169
+ const manifestPath = path2.join(pluginsRoot, "plugin.yaml");
1170
+ let hasRootManifest = false;
1171
+ try {
1172
+ hasRootManifest = statSync(manifestPath).isFile();
1173
+ } catch {
1174
+ hasRootManifest = false;
1175
+ }
1176
+ if (hasRootManifest) {
1177
+ const rawRootManifest = readFileSync(manifestPath, "utf8");
1178
+ registerPluginManifest(rawRootManifest, pluginsRoot);
1179
+ continue;
1180
+ }
1181
+ }
1182
+ try {
1183
+ entries = readdirSync(pluginsRoot);
1184
+ } catch (error) {
1185
+ logWarn("plugin_root_read_failed", {}, {
1186
+ "file.directory": pluginsRoot,
1187
+ "error.message": error instanceof Error ? error.message : String(error)
1188
+ }, "Failed to read plugin root");
1189
+ continue;
1190
+ }
1191
+ for (const entry of entries.sort()) {
1192
+ const pluginDir = path2.join(pluginsRoot, entry);
1193
+ try {
1194
+ const stat = statSync(pluginDir);
1195
+ if (!stat.isDirectory()) continue;
1196
+ } catch {
1197
+ continue;
1198
+ }
1199
+ const manifestPath = path2.join(pluginDir, "plugin.yaml");
1200
+ let raw;
1201
+ try {
1202
+ raw = readFileSync(manifestPath, "utf8");
1203
+ } catch {
1204
+ continue;
1205
+ }
1206
+ registerPluginManifest(raw, pluginDir);
1207
+ }
1208
+ }
1209
+ for (const skillRoot of packagedContent.skillRoots) {
1210
+ packageSkillRoots.add(skillRoot);
1211
+ }
1212
+ logInfo(
1213
+ "plugins_loaded",
1214
+ {},
1215
+ {
1216
+ "file.directories": [...localRoots, ...packagedContent.manifestRoots],
1217
+ "app.plugin.count": pluginDefinitions.length,
1218
+ "app.plugin.names": pluginDefinitions.map((plugin) => plugin.manifest.name).sort(),
1219
+ "app.plugin.package_skill_roots": [...packageSkillRoots].sort()
1220
+ },
1221
+ "Loaded plugins"
1222
+ );
1223
+ }
1224
+ loadPlugins();
1225
+ function getPluginCapabilityProviders() {
1226
+ return pluginDefinitions.map((plugin) => ({
1227
+ provider: plugin.manifest.name,
1228
+ capabilities: [...plugin.manifest.capabilities],
1229
+ configKeys: [...plugin.manifest.configKeys],
1230
+ ...plugin.manifest.target ? { target: { ...plugin.manifest.target } } : {}
1231
+ }));
1232
+ }
1233
+ function getPluginProviders() {
1234
+ return [...pluginDefinitions];
1235
+ }
1236
+ function getPluginRuntimeDependencies() {
1237
+ const seen = /* @__PURE__ */ new Set();
1238
+ const deps = [];
1239
+ for (const plugin of pluginDefinitions) {
1240
+ for (const dep of plugin.manifest.runtimeDependencies ?? []) {
1241
+ const key = dep.type === "npm" ? `${dep.type}:${dep.package}:${dep.version}` : "package" in dep ? `${dep.type}:package:${dep.package}` : `${dep.type}:url:${dep.url}:${dep.sha256}`;
1242
+ if (seen.has(key)) {
1243
+ continue;
1244
+ }
1245
+ seen.add(key);
1246
+ deps.push(dep);
1247
+ }
1248
+ }
1249
+ return deps.sort((left, right) => {
1250
+ if (left.type !== right.type) {
1251
+ return left.type.localeCompare(right.type);
1252
+ }
1253
+ const leftIdentity = "package" in left ? `package:${left.package}` : `url:${left.url}:${left.sha256}`;
1254
+ const rightIdentity = "package" in right ? `package:${right.package}` : `url:${right.url}:${right.sha256}`;
1255
+ if (leftIdentity !== rightIdentity) {
1256
+ return leftIdentity.localeCompare(rightIdentity);
1257
+ }
1258
+ if (left.type === "npm" && right.type === "npm") {
1259
+ return left.version.localeCompare(right.version);
1260
+ }
1261
+ return 0;
1262
+ });
1263
+ }
1264
+ function getPluginRuntimePostinstall() {
1265
+ const commands = [];
1266
+ for (const plugin of pluginDefinitions) {
1267
+ for (const command of plugin.manifest.runtimePostinstall ?? []) {
1268
+ commands.push({
1269
+ cmd: command.cmd,
1270
+ ...command.args ? { args: [...command.args] } : {},
1271
+ ...command.sudo !== void 0 ? { sudo: command.sudo } : {}
1272
+ });
1273
+ }
1274
+ }
1275
+ return commands;
1276
+ }
1277
+ function getPluginOAuthConfig(provider) {
1278
+ const plugin = pluginsByName.get(provider);
1279
+ if (!plugin?.manifest.oauth) return void 0;
1280
+ const oauth = plugin.manifest.oauth;
1281
+ return {
1282
+ clientIdEnv: oauth.clientIdEnv,
1283
+ clientSecretEnv: oauth.clientSecretEnv,
1284
+ authorizeEndpoint: oauth.authorizeEndpoint,
1285
+ tokenEndpoint: oauth.tokenEndpoint,
1286
+ scope: oauth.scope,
1287
+ callbackPath: `/api/oauth/callback/${plugin.manifest.name}`
1288
+ };
1289
+ }
1290
+ function getPluginSkillRoots() {
1291
+ return [.../* @__PURE__ */ new Set([...pluginDefinitions.map((plugin) => plugin.skillsDir), ...packageSkillRoots])];
1292
+ }
1293
+ function isPluginProvider(provider) {
1294
+ return pluginsByName.has(provider);
1295
+ }
1296
+ function createPluginBroker(provider, deps) {
1297
+ const plugin = pluginsByName.get(provider);
1298
+ if (!plugin) {
1299
+ throw new Error(`Unknown plugin provider: "${provider}"`);
1300
+ }
1301
+ const { credentials, name } = plugin.manifest;
1302
+ if (!credentials) {
1303
+ throw new Error(`Provider "${name}" has no credentials configured`);
1304
+ }
1305
+ let broker;
1306
+ if (credentials.type === "oauth-bearer") {
1307
+ broker = createOAuthBearerBroker(plugin.manifest, credentials, deps);
1308
+ } else if (credentials.type === "github-app") {
1309
+ broker = createGitHubAppBroker(plugin.manifest, credentials);
1310
+ } else {
1311
+ throw new Error(`Unsupported credentials type for plugin "${name}"`);
1312
+ }
1313
+ setSpanAttributes({
1314
+ "app.plugin.name": name,
1315
+ "app.plugin.capabilities": plugin.manifest.capabilities,
1316
+ "app.plugin.has_oauth": Boolean(plugin.manifest.oauth)
1317
+ });
1318
+ return broker;
1319
+ }
1320
+
1321
+ // src/chat/sandbox/paths.ts
1322
+ function normalizeWorkspaceRoot(input) {
1323
+ const candidate = (input ?? "").trim();
1324
+ if (!candidate) {
1325
+ return "/vercel/sandbox";
1326
+ }
1327
+ const normalized = candidate.replace(/\/+$/, "");
1328
+ return normalized.startsWith("/") ? normalized : `/${normalized}`;
1329
+ }
1330
+ var SANDBOX_WORKSPACE_ROOT = normalizeWorkspaceRoot(process.env.VERCEL_SANDBOX_WORKSPACE_DIR);
1331
+ var SANDBOX_SKILLS_ROOT = `${SANDBOX_WORKSPACE_ROOT}/skills`;
1332
+ function sandboxSkillDir(skillName) {
1333
+ return `${SANDBOX_SKILLS_ROOT}/${skillName}`;
1334
+ }
1335
+
1336
+ // src/chat/sandbox/runtime-dependency-snapshots.ts
1337
+ var SNAPSHOT_CACHE_PREFIX = "junior:sandbox_snapshot_profile";
1338
+ var SNAPSHOT_LOCK_PREFIX = "junior:sandbox_snapshot_lock";
1339
+ var SNAPSHOT_PROFILE_VERSION = 1;
1340
+ var SNAPSHOT_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1341
+ var SNAPSHOT_BUILD_LOCK_TTL_MS = 10 * 60 * 1e3;
1342
+ var SNAPSHOT_WAIT_FOR_LOCK_MS = SNAPSHOT_BUILD_LOCK_TTL_MS + 30 * 1e3;
1343
+ var DEFAULT_FLOATING_DEP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1344
+ function sleep(ms) {
1345
+ return new Promise((resolve) => {
1346
+ setTimeout(resolve, ms);
1347
+ });
1348
+ }
1349
+ function profileCacheKey(profileHash) {
1350
+ return `${SNAPSHOT_CACHE_PREFIX}:${profileHash}`;
1351
+ }
1352
+ function profileLockKey(profileHash) {
1353
+ return `${SNAPSHOT_LOCK_PREFIX}:${profileHash}`;
1354
+ }
1355
+ function isExactNpmVersion(version) {
1356
+ return /^\d+\.\d+\.\d+(?:[-+][a-z0-9.]+)?$/i.test(version.trim());
1357
+ }
1358
+ function hasFloatingSelector(dep) {
1359
+ return dep.type === "npm" && !isExactNpmVersion(dep.version);
1360
+ }
1361
+ function parseFloatingDepMaxAgeMs() {
1362
+ const raw = process.env.SANDBOX_SNAPSHOT_FLOATING_MAX_AGE_MS;
1363
+ if (!raw?.trim()) {
1364
+ return DEFAULT_FLOATING_DEP_MAX_AGE_MS;
1365
+ }
1366
+ const parsed = Number.parseInt(raw, 10);
1367
+ if (!Number.isFinite(parsed) || parsed < 0) {
1368
+ return DEFAULT_FLOATING_DEP_MAX_AGE_MS;
1369
+ }
1370
+ return parsed;
1371
+ }
1372
+ function buildDependencyProfile(runtime) {
1373
+ const dependencies = getPluginRuntimeDependencies();
1374
+ const postinstall = getPluginRuntimePostinstall();
1375
+ if (dependencies.length === 0 && postinstall.length === 0) {
1376
+ return null;
1377
+ }
1378
+ const rebuildEpoch = process.env.SANDBOX_SNAPSHOT_REBUILD_EPOCH?.trim() ?? "";
1379
+ const hasFloatingVersions = dependencies.some((dep) => hasFloatingSelector(dep)) || postinstall.length > 0;
1380
+ const hashInput = JSON.stringify({
1381
+ version: SNAPSHOT_PROFILE_VERSION,
1382
+ runtime,
1383
+ rebuildEpoch,
1384
+ dependencies,
1385
+ postinstall
1386
+ });
1387
+ const profileHash = createHash("sha256").update(hashInput).digest("hex");
1388
+ return {
1389
+ profileHash,
1390
+ dependencyCount: dependencies.length,
1391
+ hasFloatingVersions,
1392
+ dependencies,
1393
+ postinstall
1394
+ };
1395
+ }
1396
+ function shouldRebuildCachedSnapshot(profile, cached) {
1397
+ if (!profile.hasFloatingVersions) {
1398
+ return false;
1399
+ }
1400
+ const maxAgeMs = parseFloatingDepMaxAgeMs();
1401
+ if (maxAgeMs === 0) {
1402
+ return true;
1403
+ }
1404
+ return Date.now() - cached.createdAtMs > maxAgeMs;
1405
+ }
1406
+ async function getCachedSnapshot(profileHash) {
1407
+ try {
1408
+ const state = getStateAdapter();
1409
+ await state.connect();
1410
+ const raw = await state.get(profileCacheKey(profileHash));
1411
+ if (typeof raw !== "string") {
1412
+ return null;
1413
+ }
1414
+ const parsed = JSON.parse(raw);
1415
+ if (!parsed || typeof parsed !== "object" || typeof parsed.profileHash !== "string" || typeof parsed.snapshotId !== "string" || typeof parsed.runtime !== "string" || typeof parsed.createdAtMs !== "number" || typeof parsed.dependencyCount !== "number") {
1416
+ return null;
1417
+ }
1418
+ return parsed;
1419
+ } catch {
1420
+ return null;
1421
+ }
1422
+ }
1423
+ async function setCachedSnapshot(entry) {
1424
+ const state = getStateAdapter();
1425
+ await state.connect();
1426
+ await state.set(profileCacheKey(entry.profileHash), JSON.stringify(entry), SNAPSHOT_CACHE_TTL_MS);
1427
+ }
1428
+ async function withSnapshotSpan(name, op, attributes, callback) {
1429
+ return await withSpan(name, op, {}, callback, attributes);
1430
+ }
1431
+ async function runOrThrow(sandbox, params, label) {
1432
+ const result = await sandbox.runCommand(params);
1433
+ if (result.exitCode === 0) {
1434
+ return;
1435
+ }
1436
+ const stderr = (await result.stderr()).trim();
1437
+ const stdout = (await result.stdout()).trim();
1438
+ const detail = stderr || stdout || "command failed";
1439
+ throw new Error(`${label} failed: ${detail}`);
1440
+ }
1441
+ async function tryRun(sandbox, params) {
1442
+ const result = await sandbox.runCommand(params);
1443
+ if (result.exitCode === 0) {
1444
+ return { ok: true };
1445
+ }
1446
+ const stderr = (await result.stderr()).trim();
1447
+ const stdout = (await result.stdout()).trim();
1448
+ return { ok: false, detail: stderr || stdout || "command failed" };
1449
+ }
1450
+ async function installGhCliViaDnf(sandbox) {
1451
+ const direct = await tryRun(sandbox, {
1452
+ cmd: "dnf",
1453
+ args: ["install", "-y", "gh"],
1454
+ sudo: true
1455
+ });
1456
+ if (direct.ok) {
1457
+ return;
1458
+ }
1459
+ const dnf5Repo = await tryRun(sandbox, {
1460
+ cmd: "dnf",
1461
+ args: ["config-manager", "addrepo", "--from-repofile=https://cli.github.com/packages/rpm/gh-cli.repo"],
1462
+ sudo: true
1463
+ });
1464
+ if (!dnf5Repo.ok) {
1465
+ await runOrThrow(
1466
+ sandbox,
1467
+ {
1468
+ cmd: "dnf",
1469
+ args: ["install", "-y", "dnf-command(config-manager)"],
1470
+ sudo: true
1471
+ },
1472
+ "dnf install dnf-command(config-manager)"
1473
+ );
1474
+ await runOrThrow(
1475
+ sandbox,
1476
+ {
1477
+ cmd: "dnf",
1478
+ args: ["config-manager", "--add-repo", "https://cli.github.com/packages/rpm/gh-cli.repo"],
1479
+ sudo: true
1480
+ },
1481
+ "dnf config-manager --add-repo gh-cli.repo"
1482
+ );
1483
+ }
1484
+ await runOrThrow(
1485
+ sandbox,
1486
+ {
1487
+ cmd: "dnf",
1488
+ args: ["install", "-y", "gh", "--repo", "gh-cli"],
1489
+ sudo: true
1490
+ },
1491
+ "dnf install gh --repo gh-cli"
1492
+ );
1493
+ }
1494
+ function runtimeDependencyFilePath(url, sha256) {
1495
+ let urlBasename = "package.rpm";
1496
+ try {
1497
+ const pathname = new URL(url).pathname;
1498
+ const segments = pathname.split("/").filter(Boolean);
1499
+ const candidate = segments[segments.length - 1];
1500
+ if (candidate) {
1501
+ urlBasename = candidate;
1502
+ }
1503
+ } catch {
1504
+ }
1505
+ const sanitizedBasename = urlBasename.replace(/[^a-zA-Z0-9._-]/g, "_");
1506
+ return `/tmp/junior-runtime-${sha256.slice(0, 12)}-${sanitizedBasename}`;
1507
+ }
1508
+ async function installRuntimeDependencies(sandbox, deps) {
1509
+ const systemDeps = deps.filter((dep) => dep.type === "system");
1510
+ const npmPackages = deps.filter((dep) => dep.type === "npm").map((dep) => `${dep.package}@${dep.version}`);
1511
+ if (systemDeps.length > 0) {
1512
+ await withSnapshotSpan(
1513
+ "sandbox.snapshot.install_system",
1514
+ "sandbox.snapshot.install.system",
1515
+ {
1516
+ "app.sandbox.snapshot.install.system_count": systemDeps.length
1517
+ },
1518
+ async () => {
1519
+ for (const dep of systemDeps) {
1520
+ if ("url" in dep) {
1521
+ const rpmPath = runtimeDependencyFilePath(dep.url, dep.sha256);
1522
+ await runOrThrow(
1523
+ sandbox,
1524
+ {
1525
+ cmd: "curl",
1526
+ args: ["-fsSL", dep.url, "-o", rpmPath]
1527
+ },
1528
+ `curl download ${dep.url}`
1529
+ );
1530
+ const checksumResult = await sandbox.runCommand({
1531
+ cmd: "sha256sum",
1532
+ args: [rpmPath]
1533
+ });
1534
+ const checksumStdout = (await checksumResult.stdout()).trim();
1535
+ const checksumStderr = (await checksumResult.stderr()).trim();
1536
+ if (checksumResult.exitCode !== 0) {
1537
+ throw new Error(`sha256sum failed: ${checksumStderr || checksumStdout || "command failed"}`);
1538
+ }
1539
+ const actualChecksum = checksumStdout.split(/\s+/)[0]?.toLowerCase();
1540
+ if (!actualChecksum) {
1541
+ throw new Error("sha256sum produced empty output");
1542
+ }
1543
+ if (actualChecksum !== dep.sha256) {
1544
+ throw new Error(
1545
+ `checksum mismatch for ${dep.url}: expected ${dep.sha256}, got ${actualChecksum}`
1546
+ );
1547
+ }
1548
+ await runOrThrow(
1549
+ sandbox,
1550
+ {
1551
+ cmd: "dnf",
1552
+ args: ["install", "-y", rpmPath],
1553
+ sudo: true
1554
+ },
1555
+ `dnf install ${dep.url}`
1556
+ );
1557
+ continue;
1558
+ }
1559
+ if (dep.package === "gh") {
1560
+ await installGhCliViaDnf(sandbox);
1561
+ continue;
1562
+ }
1563
+ await runOrThrow(
1564
+ sandbox,
1565
+ {
1566
+ cmd: "dnf",
1567
+ args: ["install", "-y", dep.package],
1568
+ sudo: true
1569
+ },
1570
+ `dnf install ${dep.package}`
1571
+ );
1572
+ }
1573
+ }
1574
+ );
1575
+ }
1576
+ if (npmPackages.length > 0) {
1577
+ await withSnapshotSpan(
1578
+ "sandbox.snapshot.install_npm",
1579
+ "sandbox.snapshot.install.npm",
1580
+ {
1581
+ "app.sandbox.snapshot.install.npm_count": npmPackages.length
1582
+ },
1583
+ async () => {
1584
+ await runOrThrow(
1585
+ sandbox,
1586
+ {
1587
+ cmd: "npm",
1588
+ args: [
1589
+ "install",
1590
+ "--global",
1591
+ "--prefix",
1592
+ `${SANDBOX_WORKSPACE_ROOT}/.junior`,
1593
+ ...npmPackages
1594
+ ]
1595
+ },
1596
+ "npm install"
1597
+ );
1598
+ }
1599
+ );
1600
+ }
1601
+ }
1602
+ async function runRuntimePostinstall(sandbox, commands) {
1603
+ if (commands.length === 0) {
1604
+ return;
1605
+ }
1606
+ await withSnapshotSpan(
1607
+ "sandbox.snapshot.runtime_postinstall",
1608
+ "sandbox.snapshot.runtime_postinstall",
1609
+ {
1610
+ "app.sandbox.snapshot.runtime_postinstall.count": commands.length
1611
+ },
1612
+ async () => {
1613
+ for (const command of commands) {
1614
+ const invocation = [JSON.stringify(command.cmd), ...(command.args ?? []).map((arg) => JSON.stringify(arg))].join(" ");
1615
+ const pathPrefix = `${SANDBOX_WORKSPACE_ROOT}/.junior/bin:$PATH`;
1616
+ await runOrThrow(
1617
+ sandbox,
1618
+ {
1619
+ cmd: "bash",
1620
+ args: ["-lc", `export PATH="${pathPrefix}" && ${invocation}`],
1621
+ ...command.sudo !== void 0 ? { sudo: command.sudo } : {}
1622
+ },
1623
+ `runtime-postinstall ${command.cmd}`
1624
+ );
1625
+ }
1626
+ }
1627
+ );
1628
+ }
1629
+ async function createDependencySnapshot(profile, runtime, timeoutMs) {
1630
+ return await withSnapshotSpan(
1631
+ "sandbox.snapshot.build",
1632
+ "sandbox.snapshot.build",
1633
+ {
1634
+ "app.sandbox.runtime": runtime,
1635
+ "app.sandbox.snapshot.dependency_count": profile.dependencyCount
1636
+ },
1637
+ async () => {
1638
+ const sandbox = await Sandbox.create({
1639
+ timeout: timeoutMs,
1640
+ runtime
1641
+ });
1642
+ try {
1643
+ await installRuntimeDependencies(sandbox, profile.dependencies);
1644
+ await runRuntimePostinstall(sandbox, profile.postinstall);
1645
+ return await withSnapshotSpan(
1646
+ "sandbox.snapshot.capture",
1647
+ "sandbox.snapshot.capture",
1648
+ {
1649
+ "app.sandbox.snapshot.dependency_count": profile.dependencyCount
1650
+ },
1651
+ async () => {
1652
+ const snapshot = await sandbox.snapshot();
1653
+ return snapshot.snapshotId;
1654
+ }
1655
+ );
1656
+ } finally {
1657
+ try {
1658
+ await sandbox.stop({ blocking: true });
1659
+ } catch {
1660
+ }
1661
+ }
1662
+ }
1663
+ );
1664
+ }
1665
+ async function withBuildLock(profileHash, callback, canUseCachedSnapshot, hooks) {
1666
+ const state = getStateAdapter();
1667
+ await state.connect();
1668
+ const lockKey = profileLockKey(profileHash);
1669
+ const tryAcquireLock = async () => await state.acquireLock(lockKey, SNAPSHOT_BUILD_LOCK_TTL_MS);
1670
+ let lock = await tryAcquireLock();
1671
+ if (lock) {
1672
+ try {
1673
+ const result = await callback();
1674
+ return {
1675
+ snapshotId: result.snapshotId,
1676
+ source: result.source,
1677
+ waitedForLock: false
1678
+ };
1679
+ } finally {
1680
+ await state.releaseLock(lock);
1681
+ }
1682
+ }
1683
+ return await withSnapshotSpan(
1684
+ "sandbox.snapshot.lock_wait",
1685
+ "sandbox.snapshot.lock_wait",
1686
+ {
1687
+ "app.sandbox.snapshot.profile_hash": profileHash
1688
+ },
1689
+ async () => {
1690
+ await hooks?.onWaitingForLock?.();
1691
+ const waitUntil = Date.now() + SNAPSHOT_WAIT_FOR_LOCK_MS;
1692
+ while (Date.now() < waitUntil) {
1693
+ const cached2 = await getCachedSnapshot(profileHash);
1694
+ if (cached2?.snapshotId && canUseCachedSnapshot(cached2)) {
1695
+ return {
1696
+ snapshotId: cached2.snapshotId,
1697
+ source: "wait_cache",
1698
+ waitedForLock: true
1699
+ };
1700
+ }
1701
+ lock = await tryAcquireLock();
1702
+ if (lock) {
1703
+ try {
1704
+ const result = await callback();
1705
+ return {
1706
+ snapshotId: result.snapshotId,
1707
+ source: result.source,
1708
+ waitedForLock: true
1709
+ };
1710
+ } finally {
1711
+ await state.releaseLock(lock);
1712
+ }
1713
+ }
1714
+ await sleep(500);
1715
+ }
1716
+ const cached = await getCachedSnapshot(profileHash);
1717
+ if (cached?.snapshotId && canUseCachedSnapshot(cached)) {
1718
+ return {
1719
+ snapshotId: cached.snapshotId,
1720
+ source: "wait_cache",
1721
+ waitedForLock: true
1722
+ };
1723
+ }
1724
+ throw new Error("Timed out waiting for snapshot build lock");
1725
+ }
1726
+ );
1727
+ }
1728
+ function toResolveOutcome(forceRebuild, source, waitedForLock) {
1729
+ if (source === "built") {
1730
+ return forceRebuild ? "forced_rebuild" : "rebuilt";
1731
+ }
1732
+ if (waitedForLock || source === "wait_cache") {
1733
+ return "cache_hit_after_lock_wait";
1734
+ }
1735
+ return "cache_hit";
1736
+ }
1737
+ function getRebuildReason(params) {
1738
+ if (params.forceRebuild) {
1739
+ return params.staleSnapshotId ? "snapshot_missing" : "force_rebuild";
1740
+ }
1741
+ if (params.cached?.snapshotId && params.shouldRebuildCached) {
1742
+ return "floating_stale";
1743
+ }
1744
+ if (!params.cached?.snapshotId) {
1745
+ return "cache_miss";
1746
+ }
1747
+ return void 0;
1748
+ }
1749
+ async function resolveRuntimeDependencySnapshot(params) {
1750
+ return await withSnapshotSpan(
1751
+ "sandbox.snapshot.resolve",
1752
+ "sandbox.snapshot.resolve",
1753
+ {
1754
+ "app.sandbox.runtime": params.runtime,
1755
+ "app.sandbox.snapshot.force_rebuild": Boolean(params.forceRebuild)
1756
+ },
1757
+ async () => {
1758
+ await params.onProgress?.("resolve_start");
1759
+ const resolveStartedAtMs = Date.now();
1760
+ const profile = buildDependencyProfile(params.runtime);
1761
+ if (!profile) {
1762
+ return {
1763
+ dependencyCount: 0,
1764
+ cacheHit: false,
1765
+ resolveOutcome: "no_profile"
1766
+ };
1767
+ }
1768
+ const cached = await getCachedSnapshot(profile.profileHash);
1769
+ const cachedNeedsRebuild = Boolean(cached?.snapshotId && shouldRebuildCachedSnapshot(profile, cached));
1770
+ if (!params.forceRebuild && cached?.snapshotId && !cachedNeedsRebuild) {
1771
+ await params.onProgress?.("cache_hit");
1772
+ return {
1773
+ snapshotId: cached.snapshotId,
1774
+ profileHash: profile.profileHash,
1775
+ dependencyCount: profile.dependencyCount,
1776
+ cacheHit: true,
1777
+ resolveOutcome: "cache_hit"
1778
+ };
1779
+ }
1780
+ const rebuildReason = getRebuildReason({
1781
+ forceRebuild: params.forceRebuild,
1782
+ staleSnapshotId: params.staleSnapshotId,
1783
+ cached,
1784
+ shouldRebuildCached: cachedNeedsRebuild
1785
+ });
1786
+ const canUseCachedSnapshot = (candidate) => {
1787
+ if (params.forceRebuild) {
1788
+ if (params.staleSnapshotId) {
1789
+ return candidate.snapshotId !== params.staleSnapshotId;
1790
+ }
1791
+ return candidate.createdAtMs > resolveStartedAtMs;
1792
+ }
1793
+ return !shouldRebuildCachedSnapshot(profile, candidate);
1794
+ };
1795
+ const lockResult = await withBuildLock(profile.profileHash, async () => {
1796
+ const latest = await getCachedSnapshot(profile.profileHash);
1797
+ if (latest?.snapshotId && canUseCachedSnapshot(latest)) {
1798
+ await params.onProgress?.("cache_hit");
1799
+ return { snapshotId: latest.snapshotId, source: "callback_cache" };
1800
+ }
1801
+ await params.onProgress?.("building_snapshot");
1802
+ const nextSnapshotId = await createDependencySnapshot(profile, params.runtime, params.timeoutMs);
1803
+ await setCachedSnapshot({
1804
+ profileHash: profile.profileHash,
1805
+ snapshotId: nextSnapshotId,
1806
+ runtime: params.runtime,
1807
+ createdAtMs: Date.now(),
1808
+ dependencyCount: profile.dependencyCount
1809
+ });
1810
+ await params.onProgress?.("build_complete");
1811
+ return { snapshotId: nextSnapshotId, source: "built" };
1812
+ }, canUseCachedSnapshot, {
1813
+ onWaitingForLock: async () => {
1814
+ await params.onProgress?.("waiting_for_lock");
1815
+ }
1816
+ });
1817
+ return {
1818
+ snapshotId: lockResult.snapshotId,
1819
+ profileHash: profile.profileHash,
1820
+ dependencyCount: profile.dependencyCount,
1821
+ cacheHit: lockResult.source !== "built",
1822
+ resolveOutcome: toResolveOutcome(Boolean(params.forceRebuild), lockResult.source, lockResult.waitedForLock),
1823
+ ...rebuildReason ? { rebuildReason } : {}
1824
+ };
1825
+ }
1826
+ );
1827
+ }
1828
+ function isSnapshotMissingError(error) {
1829
+ const searchable = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
1830
+ return searchable.includes("snapshot") && (searchable.includes("not found") || searchable.includes("unknown") || searchable.includes("404"));
1831
+ }
1832
+
1833
+ export {
1834
+ homeDir,
1835
+ skillRoots,
1836
+ soulPathCandidates,
1837
+ resolveAuthTokenPlaceholder,
1838
+ CredentialUnavailableError,
1839
+ getPluginCapabilityProviders,
1840
+ getPluginProviders,
1841
+ getPluginOAuthConfig,
1842
+ getPluginSkillRoots,
1843
+ isPluginProvider,
1844
+ createPluginBroker,
1845
+ botConfig,
1846
+ getSlackBotToken,
1847
+ getSlackSigningSecret,
1848
+ getSlackClientId,
1849
+ getSlackClientSecret,
1850
+ getStateAdapter,
1851
+ disconnectStateAdapter,
1852
+ claimQueueIngressDedup,
1853
+ hasQueueIngressDedup,
1854
+ getQueueMessageProcessingState,
1855
+ acquireQueueMessageProcessingOwnership,
1856
+ refreshQueueMessageProcessingOwnership,
1857
+ completeQueueMessageProcessingOwnership,
1858
+ failQueueMessageProcessingOwnership,
1859
+ getAgentTurnSessionCheckpoint,
1860
+ upsertAgentTurnSessionCheckpoint,
1861
+ SANDBOX_WORKSPACE_ROOT,
1862
+ SANDBOX_SKILLS_ROOT,
1863
+ sandboxSkillDir,
1864
+ resolveRuntimeDependencySnapshot,
1865
+ isSnapshotMissingError
1866
+ };