@sentry/junior 0.294.0 → 0.295.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/{admin-vt8aSiCD.js → admin-ifgjyfpF.js} +2 -2
  2. package/dist/{agent-runner-DJu7w6mI.js → agent-runner-DjMTPWEO.js} +147 -90
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +5 -5
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +52 -28
  7. package/dist/{app--a5RLOrr.d.ts → app-uiTzRbvq.d.ts} +3 -3
  8. package/dist/app.d.ts +2 -2
  9. package/dist/app.js +33 -34
  10. package/dist/{automation-BM-OBsKW.js → automation-yJX3C7i3.js} +3 -3
  11. package/dist/{background-compaction-queue-D2j-0XkH.js → background-compaction-queue-DUkHZjmL.js} +7 -9
  12. package/dist/{briefs-JOAoCb6d.js → briefs-CbNYM-q2.js} +3 -3
  13. package/dist/{catalog-runtime-CLMA9AXd.js → catalog-runtime-DgouZKZm.js} +1 -1
  14. package/dist/cli/chat.d.ts +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +2 -0
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +4 -4
  21. package/dist/cli/snapshot-create.js +4 -4
  22. package/dist/cli/upgrade.d.ts +2 -2
  23. package/dist/cli/upgrade.js +3 -3
  24. package/dist/{config-mIZeGEWv.js → config-DvnTPCfp.js} +43 -2
  25. package/dist/{connections-XhdVg7OR.js → connections-CWaIVl_1.js} +6 -6
  26. package/dist/{conversation-CDWejM4R.js → conversation-CMkSmi02.js} +2 -11
  27. package/dist/{conversation-pending-messages-Dh2tfbaw.js → conversation-feed-BVAOga0H.js} +27 -2
  28. package/dist/{conversation-privacy-C6h-X2cZ.js → conversation-privacy-DPjv4SnA.js} +1 -1
  29. package/dist/{credential-sync-zigBlXS3.js → credential-sync-BhbaZfmO.js} +16 -15
  30. package/dist/{db-DV5AbcGM.d.ts → db-CCUqQe0E.d.ts} +6 -1
  31. package/dist/{db--xuNV7g6.js → db-Dts2XvLu.js} +54 -10
  32. package/dist/{executor-BItuRqAR.js → executor-Ck73J0wP.js} +8 -3
  33. package/dist/instrumentation.js +2 -2
  34. package/dist/{logging-Cb6MGvdt.js → logging-9OAq-fdg.js} +2 -1
  35. package/dist/{message-BTGgSmaH.js → message-CtaPzC7m.js} +9 -9
  36. package/dist/nitro.d.ts +2 -2
  37. package/dist/nitro.js +2 -2
  38. package/dist/{oauth-callback-server-Dvh1aOIi.js → oauth-callback-server-C_LXY1d4.js} +2 -2
  39. package/dist/{oauth-relay-D6xxVywK.js → oauth-relay-CsfIazeF.js} +2 -1
  40. package/dist/{plugins-DtmjkTza.d.ts → plugins-B_0Cr0MO.d.ts} +0 -1
  41. package/dist/{projection-DLQgfO5N.js → projection-BzJQncZV.js} +248 -77
  42. package/dist/{prompt-qp_LdxLX.js → prompt-Cbq5b4SO.js} +4 -4
  43. package/dist/{registry-MtwokaqW.js → registry-cbpOxO4M.js} +3 -13
  44. package/dist/{resolve-BnJA0UNE.js → resolve-t-pmRdwS.js} +3 -3
  45. package/dist/{result-ChL-1KyW.js → result-DhgjR3nQ.js} +8 -8
  46. package/dist/{runner-BONN7Dp2.js → runner-CHv9X9TH.js} +8 -8
  47. package/dist/{sandbox-egress-signals-nmlmI5Ab.js → sandbox-egress-signals-Yy3fSCbg.js} +1 -1
  48. package/dist/{schema-yr0ccDni.js → schema-BhneuGYv.js} +13 -6
  49. package/dist/{schema-DgvcyJ1y.d.ts → schema-TSEisVJR.d.ts} +50 -14
  50. package/dist/secrets-DebYU866.js +18 -0
  51. package/dist/{service-account-Bd0lBaGr.js → service-account-C4rBP8ne.js} +3 -3
  52. package/dist/{service-account-kio5nXSD.js → service-account-DjPIwCMj.js} +42 -26
  53. package/dist/{session-stop-CeCXL3j9.js → session-stop-DkxI5vc3.js} +20 -775
  54. package/dist/{skills-e3DDNlKO.js → skills-BZE2DP8I.js} +2 -2
  55. package/dist/{spawn--cRxITWQ.js → spawn-BvULxIiu.js} +5 -5
  56. package/dist/{adapter-DxLhJEnO.js → state-CO9ETDzk.js} +132 -2
  57. package/dist/{stop-Iai5N2PU.js → stop-CL-rdtQb.js} +84 -30
  58. package/dist/{store-C8LsaJwS.js → store-DgD78_NK.js} +3 -3
  59. package/dist/{task-runner-Dw7exu0-.js → task-runner-CKOj6xla.js} +11 -11
  60. package/dist/{turn-failure-response-BqTTx3XG.js → turn-failure-response-BTSo6SMJ.js} +8 -8
  61. package/dist/{validation-BrGahtnv.js → validation-CXeYgBzq.js} +1 -1
  62. package/dist/{version-Bdqhx8Qh.js → version-AQa7Fr2H.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/{viewer-CjRFHR5U.js → viewer-Bqkb678l.js} +3 -3
  65. package/dist/warmup-h6u1e9n0.js +1869 -0
  66. package/dist/{work-BWBG1EGV.js → work-yN_GAuXY.js} +11 -11
  67. package/dist/{worker-DAnBIVMs.js → worker-Hl7N292I.js} +6 -6
  68. package/migrations/0098_review_item_plugin_actions.sql +5 -0
  69. package/migrations/0099_conversation_last_message_at.sql +1 -0
  70. package/migrations/0100_automation_task_kind_repair.sql +48 -0
  71. package/migrations/meta/0098_snapshot.json +4490 -0
  72. package/migrations/meta/0099_snapshot.json +4720 -0
  73. package/migrations/meta/0100_snapshot.json +4496 -0
  74. package/migrations/meta/_journal.json +21 -0
  75. package/package.json +5 -5
  76. package/dist/assistant-reply-iTtEdDyc.js +0 -58
  77. package/dist/warmup-DuxCtzKC.js +0 -1039
@@ -1,27 +1,28 @@
1
1
  import { a as getClient$1, h as startSpan, n as captureMessage, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { A as estimateTextTokens, E as resolveGatewayModel, I as unwrapCurrentInstruction, L as escapeXml, S as completeObject, T as rerankTexts, X as toOptionalTrimmed, i as getChatConfig, n as botConfig, o as getSlackBotToken, v as normalizeSlackEmojiName, w as embedTexts, x as completeDecision, y as GEN_AI_PROVIDER_NAME } from "./config-mIZeGEWv.js";
3
- import { E as withSpan, G as isRecord$2, K as toOptionalNumber, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, d as logAudit, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, q as toOptionalString, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-Cb6MGvdt.js";
4
- import { t as canExposeConversationPayload } from "./conversation-privacy-C6h-X2cZ.js";
2
+ import { A as estimateTextTokens, E as resolveGatewayModel, I as unwrapCurrentInstruction, L as escapeXml, S as completeObject, T as rerankTexts, X as toOptionalTrimmed, i as getChatConfig, n as botConfig, o as getSlackBotToken, v as normalizeSlackEmojiName, w as embedTexts, x as completeDecision, y as GEN_AI_PROVIDER_NAME } from "./config-DvnTPCfp.js";
3
+ import { E as withSpan, G as isRecord$2, K as toOptionalNumber, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, d as logAudit, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, q as toOptionalString, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-9OAq-fdg.js";
4
+ import { t as canExposeConversationPayload } from "./conversation-privacy-DPjv4SnA.js";
5
5
  import { c as parseStoredSlackActor, d as parseSlackChannelReferenceId, f as parseSlackTeamId, h as parseSlackMessageTs, i as isActorUserId, l as toStoredSlackActor, p as parseSlackUserId, s as parseActorUserId } from "./actor-6jsm_v96.js";
6
- import { G as addAgentTurnUsage, L as readUserTimezone, M as resolveActorIdentityId, Q as conversationDetailTouch, S as isPersonInput, V as bindProviderConversation, Y as hasAgentTurnUsage, a as getConversationStore, d as createSqlConversationEventStore, f as eventFromRow, it as sameDestination, k as startLocationThread, nt as parseDestination, o as getDb, p as withConversationEventLock, r as getConversationEventStore, s as getSqlExecutor, y as createSqlStore, z as saveUserTimezone } from "./db--xuNV7g6.js";
7
- import { A as juniorConversations, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, O as juniorCodeRepositories, a as juniorPushSubscriptions, b as juniorConversationBriefs, f as juniorAutomations, i as juniorWorkspaces, j as juniorIdentities, k as juniorAttachments, l as juniorReviewItems, m as juniorLocationConfigurations, n as juniorSnapshots, o as juniorReviewItemAssignees, r as juniorWorkspaceRepos, s as juniorReviewItemConversations, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-BItuRqAR.js";
6
+ import { P as resolveActorIdentityId, U as bindProviderConversation, V as saveUserTimezone, Z as hasAgentTurnUsage, a as getConversationStore, d as createSqlConversationEventStore, et as conversationDetailTouch, f as eventFromRow, it as parseDestination, j as startLocationThread, o as getDb, ot as sameDestination, p as withConversationEventLock, q as addAgentTurnUsage, r as getConversationEventStore, s as getSqlExecutor, w as isPersonInput, x as createSqlStore, z as readUserTimezone } from "./db-Dts2XvLu.js";
7
+ import { A as juniorConversations, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, O as juniorCodeRepositories, a as juniorPushSubscriptions, b as juniorConversationBriefs, f as juniorAutomations, i as juniorWorkspaces, j as juniorIdentities, k as juniorAttachments, l as juniorReviewItems, m as juniorLocationConfigurations, n as juniorSnapshots, o as juniorReviewItemAssignees, r as juniorWorkspaceRepos, s as juniorReviewItemConversations, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-Ck73J0wP.js";
8
8
  import { _ as instructionProvenanceFor, g as instructionActors, h as contextProvenance, o as agentHistoryItemSchema } from "./media-BepyEUNm.js";
9
- import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, f as credentialContextForActor, h as credentialSubjectSchema, m as credentialLogContext, o as resolvePluginCommandEnv, p as credentialContextSchema } from "./registry-MtwokaqW.js";
10
- import { n as pluginCatalogRuntime } from "./catalog-runtime-CLMA9AXd.js";
11
- import { d as JUNIOR_NATIVE_EVENT_NAMESPACE, f as agentsInstructionsUpdatedEvent, g as renderJuniorNativeConversationEvent, l as completeObject$1, m as authenticationUnlinkedEvent, n as briefEntriesFromReportEvents, o as isEventConversationMessage, p as authenticationLinkedEvent, s as generateBrief, t as BRIEF_PROMPT, u as completeText } from "./prompt-qp_LdxLX.js";
9
+ import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, f as credentialContextForActor, g as credentialUserSubjectId, h as credentialSubjectSchema, m as credentialLogContext, o as resolvePluginCommandEnv, p as credentialContextSchema } from "./registry-cbpOxO4M.js";
10
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DgouZKZm.js";
11
+ import { d as JUNIOR_NATIVE_EVENT_NAMESPACE, f as agentsInstructionsUpdatedEvent, g as renderJuniorNativeConversationEvent, l as completeObject$1, m as authenticationUnlinkedEvent, n as briefEntriesFromReportEvents, o as isEventConversationMessage, p as authenticationLinkedEvent, s as generateBrief, t as BRIEF_PROMPT, u as completeText } from "./prompt-Cbq5b4SO.js";
12
12
  import { a as withLock, i as fenceLock, n as MUTATION_LOCK_TTL_MS, r as acquireActiveLock } from "./locks-D-0h111u.js";
13
- import { g as createCache, i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-CjRFHR5U.js";
14
- import { a as setStateValues, i as getStateValues, n as getDefaultRedisStateAdapterFor, r as getStateAdapter } from "./adapter-DxLhJEnO.js";
13
+ import { g as createCache, i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-Bqkb678l.js";
14
+ import { a as getStateAdapter, i as getDefaultRedisStateAdapterFor, n as readEncryptedState, o as getStateValues, s as setStateValues, t as createEncryptedState } from "./state-CO9ETDzk.js";
15
15
  import { n as isWithinNotificationSchedule, r as notificationScheduleSchema, s as isValidTimeZone, t as DEFAULT_NOTIFICATION_SCHEDULE } from "./schedule-cP0AACm1.js";
16
- import { I as messageCardRef, J as briefResourceLabel, P as reviewItemChangeRecordSchema, R as readMessageCardRefs, W as readMessageAttachments, X as parseBriefInput, Y as conversationBriefSchema, Z as parseStoredBrief, _ as conversationReportEventSchema, v as conversationReportMessageEventSchema } from "./conversation-CDWejM4R.js";
16
+ import { F as messageCardRef, J as conversationBriefSchema, L as readMessageCardRefs, N as reviewItemChangeRecordSchema, U as readMessageAttachments, X as parseStoredBrief, Y as parseBriefInput, _ as conversationReportMessageEventSchema, g as conversationReportEventSchema, q as briefResourceLabel } from "./conversation-CMkSmi02.js";
17
17
  import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
18
+ import { i as readWebPushPrivateKey, t as readJuniorSecret } from "./secrets-DebYU866.js";
18
19
  import path from "node:path";
19
20
  import { isDeepStrictEqual } from "node:util";
20
21
  import { AsyncLocalStorage } from "node:async_hooks";
21
22
  import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, timingSafeEqual } from "node:crypto";
22
23
  import * as z from "zod";
23
- import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, not, or, sql } from "drizzle-orm";
24
- import { EgressAuthRequired, EgressPolicyDenied, actorSchema, codeChangeInputSchema, conversationAnnotationInputSchema, defineConversationEvent, destinationSchema, eventDataSchema, eventInputSchema, eventMatchSchema, eventMatches, eventTypeSchema, isPluginModelCostEventName, missingToolAnnotationKeys, normalizeEventIdentifier, objectAnnotationSchema, objectIconPath, objectTypeSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, sourceSchema, stableEventMatchKey } from "@sentry/junior-plugin-api";
24
+ import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, not, notLike, or, sql } from "drizzle-orm";
25
+ import { EgressAuthRequired, EgressPolicyDenied, actorSchema, codeChangeInputSchema, conversationAnnotationInputSchema, defineConversationEvent, destinationSchema, eventDataSchema, eventInputSchema, eventMatchSchema, eventMatches, eventTypeSchema, isPluginModelCostEventName, missingToolAnnotationKeys, normalizeEventIdentifier, objectAnnotationSchema, objectIconPath, objectTypeSchema, pluginAuditAttributesSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, sourceSchema, stableEventMatchKey } from "@sentry/junior-plugin-api";
25
26
  import { alias } from "drizzle-orm/pg-core";
26
27
  import fs from "node:fs/promises";
27
28
  import pLimit from "p-limit";
@@ -418,6 +419,95 @@ function createPluginCache(plugin) {
418
419
  return await createCache(getStateAdapter(), `plugin:${plugin}`).getOrLoad(key, load, options);
419
420
  } };
420
421
  }
422
+ // src/chat/credentials/audit.ts
423
+ /**
424
+ * Facts that credential audit events name about the run and the credential.
425
+ *
426
+ * These values are telemetry only. They grant nothing.
427
+ */
428
+ const nonBlankStringSchema = z.string().min(1);
429
+ const credentialAuditSourceSchema = z.object({
430
+ kind: nonBlankStringSchema,
431
+ automationId: nonBlankStringSchema.optional(),
432
+ automationRunId: nonBlankStringSchema.optional()
433
+ }).strict();
434
+ /** Project a run Source to the facts that credential audit events name. */
435
+ function credentialAuditSource(source) {
436
+ if (source.kind !== "scheduled_automation" && source.kind !== "event_automation") return { kind: source.kind };
437
+ const result = { kind: source.kind };
438
+ if (source.automationId) result.automationId = source.automationId;
439
+ if (source.automationRunId) result.automationRunId = source.automationRunId;
440
+ return result;
441
+ }
442
+ /** Telemetry attributes for the run Source of a credential audit event. */
443
+ function credentialAuditAttributes(source) {
444
+ if (!source) return {};
445
+ const attributes = { "app.source.kind": source.kind };
446
+ if (source.automationId) attributes["app.task.id"] = source.automationId;
447
+ if (source.automationRunId) attributes["app.task.run.id"] = source.automationRunId;
448
+ return attributes;
449
+ }
450
+ /**
451
+ * Name whose credential a lease holds. An OAuth lease issued for a person
452
+ * holds that person's token: the Actor's own, or a delegated credential
453
+ * subject. Any other lease holds a credential that Junior owns, such as a
454
+ * GitHub App installation token or a deployment API key. An OAuth provider
455
+ * with no person falls back to its deployment token.
456
+ */
457
+ function credentialAccount(lease, credentials) {
458
+ return lease.authorization && credentialUserSubjectId(credentials) ? "actor" : "app";
459
+ }
460
+ // src/chat/egress/git-push.ts
461
+ const OBJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
462
+ const ZERO_OBJECT_ID = /^0+$/;
463
+ const PKT_LENGTH = /^[0-9a-f]{4}$/i;
464
+ /** Match a Git push request. */
465
+ function isGitReceivePack(method, upstreamUrl) {
466
+ return method.toUpperCase() === "POST" && upstreamUrl.pathname.toLowerCase().endsWith("/git-receive-pack");
467
+ }
468
+ function unreadable(reason) {
469
+ return {
470
+ kind: "unreadable",
471
+ reason
472
+ };
473
+ }
474
+ /**
475
+ * Read the ref update commands from a `git-receive-pack` body.
476
+ *
477
+ * The command list ends at the first flush packet, so push options and pack
478
+ * data after it do not matter. A signed push nests its commands in a
479
+ * certificate, so it is reported as unreadable.
480
+ */
481
+ function readGitPush(body) {
482
+ const bytes = new Uint8Array(body ?? /* @__PURE__ */ new ArrayBuffer(0));
483
+ if (bytes[0] === 31 && bytes[1] === 139) return unreadable("gzip");
484
+ const decoder = new TextDecoder();
485
+ const updates = [];
486
+ let offset = 0;
487
+ while (true) {
488
+ if (offset + 4 > bytes.length) return unreadable("unterminated");
489
+ const lengthText = String.fromCharCode(...bytes.subarray(offset, offset + 4));
490
+ if (!PKT_LENGTH.test(lengthText)) return unreadable("malformed");
491
+ const length = Number.parseInt(lengthText, 16);
492
+ if (length === 0) return {
493
+ kind: "commands",
494
+ updates
495
+ };
496
+ if (length < 4) return unreadable("malformed");
497
+ if (offset + length > bytes.length) return unreadable("unterminated");
498
+ const line = decoder.decode(bytes.subarray(offset + 4, offset + length)).replace(/\n$/, "");
499
+ offset += length;
500
+ if (line.startsWith("shallow ")) continue;
501
+ const command = line.split("\0", 1)[0];
502
+ if (command === "push-cert") return unreadable("signed");
503
+ const [oldId, newId, ref, ...rest] = command.split(" ");
504
+ if (!oldId || !newId || !ref || rest.length > 0 || !OBJECT_ID.test(oldId) || !OBJECT_ID.test(newId)) return unreadable("malformed");
505
+ updates.push({
506
+ deletes: ZERO_OBJECT_ID.test(newId),
507
+ ref
508
+ });
509
+ }
510
+ }
421
511
  // src/chat/slack/user.ts
422
512
  const slackUserInfoSchema = z.object({
423
513
  ok: z.literal(true),
@@ -3836,7 +3926,9 @@ const sandboxEgressCredentialContextSchema = z.object({
3836
3926
  conversationId: z.string().min(1).optional(),
3837
3927
  egressId: z.string().min(1),
3838
3928
  expiresAtMs: finiteNumberSchema,
3839
- contextId: z.string().min(1)
3929
+ contextId: z.string().min(1),
3930
+ /** Run Source that write audit events name. Telemetry only; it grants nothing. */
3931
+ source: credentialAuditSourceSchema.optional()
3840
3932
  }).strict();
3841
3933
  const sandboxEgressCredentialLeaseSchema = z.object({
3842
3934
  account: pluginProviderAccountSchema.optional(),
@@ -3860,7 +3952,7 @@ const sandboxEgressAuthRequiredSignalSchema = z.object({
3860
3952
  path: ["authorization", "provider"]
3861
3953
  });
3862
3954
  });
3863
- const sandboxEgressPermissionDeniedSignalSchema = z.object({
3955
+ const sandboxEgressUpstreamPermissionDeniedSignalSchema = z.object({
3864
3956
  account: pluginProviderAccountSchema.optional(),
3865
3957
  grant: sandboxEgressGrantSchema,
3866
3958
  message: z.string().min(1),
@@ -3871,6 +3963,17 @@ const sandboxEgressPermissionDeniedSignalSchema = z.object({
3871
3963
  upstreamPath: z.string().min(1),
3872
3964
  createdAtMs: finiteNumberSchema
3873
3965
  }).strict();
3966
+ /** A request that Junior's egress policy refused before it chose a credential. */
3967
+ const sandboxEgressPolicyDeniedSignalSchema = z.object({
3968
+ message: z.string().min(1),
3969
+ method: z.string().min(1),
3970
+ provider: providerNameSchema,
3971
+ source: z.literal("policy"),
3972
+ upstreamHost: z.string().min(1),
3973
+ upstreamPath: z.string().min(1),
3974
+ createdAtMs: finiteNumberSchema
3975
+ }).strict();
3976
+ const sandboxEgressPermissionDeniedSignalSchema = z.discriminatedUnion("source", [sandboxEgressUpstreamPermissionDeniedSignalSchema, sandboxEgressPolicyDeniedSignalSchema]);
3874
3977
  const sandboxEgressSignalsResponseSchema = z.object({
3875
3978
  auth_required: sandboxEgressAuthRequiredSignalSchema.optional(),
3876
3979
  permission_denied: sandboxEgressPermissionDeniedSignalSchema.optional()
@@ -3954,7 +4057,7 @@ function parseLease(value) {
3954
4057
  return result.data;
3955
4058
  }
3956
4059
  function getSandboxEgressSecret() {
3957
- const secret = process.env.JUNIOR_SECRET?.trim();
4060
+ const secret = readJuniorSecret();
3958
4061
  if (secret) return secret;
3959
4062
  throw new Error("Cannot determine sandbox egress secret (set JUNIOR_SECRET)");
3960
4063
  }
@@ -3973,7 +4076,8 @@ function createSandboxEgressCredentialToken(input) {
3973
4076
  credentials: input.credentials,
3974
4077
  egressId: input.egressId,
3975
4078
  expiresAtMs: now + ttlMs,
3976
- contextId: randomUUID()
4079
+ contextId: randomUUID(),
4080
+ ...input.source ? { source: input.source } : void 0
3977
4081
  };
3978
4082
  const payload = `${SANDBOX_EGRESS_TOKEN_VERSION}.${base64Url(JSON.stringify(context))}`;
3979
4083
  return `${payload}.${signPayload$1(payload)}`;
@@ -4012,14 +4116,15 @@ async function setSandboxEgressCredentialLease(_context, lease) {
4012
4116
  const ttlMs = Math.max(1, leaseExpiresAtMs - Date.now());
4013
4117
  const state = getStateAdapter();
4014
4118
  await state.connect();
4015
- await state.set(leaseKey(lease.provider, lease.grant), lease, ttlMs);
4119
+ await createEncryptedState(state).set(leaseKey(lease.provider, lease.grant), lease, ttlMs);
4016
4120
  }
4017
4121
  /** Load remembered auth headers for a shared installation grant. */
4018
4122
  async function getSandboxEgressCredentialLease(provider, grant, _context) {
4019
4123
  if (!isSharedInstallationGrant(grant)) return;
4020
4124
  const state = getStateAdapter();
4021
4125
  await state.connect();
4022
- return parseLease(await state.get(leaseKey(provider, grant)));
4126
+ const stored = await readEncryptedState(state, leaseKey(provider, grant));
4127
+ return stored?.stale ? void 0 : parseLease(stored?.value);
4023
4128
  }
4024
4129
  /** Drop remembered installation headers after the upstream rejects them. */
4025
4130
  async function clearSandboxEgressCredentialLease(provider, grant, _context) {
@@ -4045,13 +4150,14 @@ async function setSandboxEgressAuthRequiredSignal(context, signal) {
4045
4150
  }, ttlMs);
4046
4151
  }
4047
4152
  /**
4048
- * Record that the provider rejected an issued credential with permission denial.
4153
+ * Record that the provider rejected an issued credential, or that Junior's
4154
+ * egress policy refused the request before it chose a credential.
4049
4155
  */
4050
4156
  async function setSandboxEgressPermissionDeniedSignal(context, signal) {
4051
4157
  const ttlMs = Math.max(1, context.expiresAtMs - Date.now());
4052
4158
  const state = getStateAdapter();
4053
4159
  await state.connect();
4054
- await state.set(permissionSignalKey(context.egressId, signal.grant.access), {
4160
+ await state.set(permissionSignalKey(context.egressId, signal.source === "upstream" ? signal.grant.access : "write"), {
4055
4161
  ...signal,
4056
4162
  createdAtMs: Date.now()
4057
4163
  }, ttlMs);
@@ -4168,7 +4274,8 @@ async function executeSandboxEgressRequest(input, deps = {}) {
4168
4274
  path: upstreamUrl.pathname,
4169
4275
  status: 403
4170
4276
  }),
4171
- ...sandboxEgressRoutingAttributes(request, upstreamUrl)
4277
+ ...sandboxEgressRoutingAttributes(request, upstreamUrl),
4278
+ ...egressDecisionAttributes("denied", "no provider owns forwarded host")
4172
4279
  });
4173
4280
  return jsonError$1("No provider owns forwarded host", 403);
4174
4281
  }
@@ -4183,7 +4290,8 @@ async function executeSandboxEgressRequest(input, deps = {}) {
4183
4290
  provider,
4184
4291
  status: 403
4185
4292
  }),
4186
- ...sandboxEgressRoutingAttributes(request, upstreamUrl)
4293
+ ...sandboxEgressRoutingAttributes(request, upstreamUrl),
4294
+ ...egressDecisionAttributes("denied", "credential context is not authorized")
4187
4295
  });
4188
4296
  return jsonError$1("Sandbox egress credential context is not authorized", 403);
4189
4297
  }
@@ -7674,9 +7782,6 @@ async function updateTimerIndex(state, operation) {
7674
7782
  // src/chat/credentials/subject.ts
7675
7783
  const CREDENTIAL_SUBJECT_HMAC_CONTEXT = "junior.credential_subject.v1";
7676
7784
  const CREDENTIAL_SUBJECT_SIGNATURE_VERSION = "v1";
7677
- function getCredentialSubjectSecret() {
7678
- return process.env.JUNIOR_SECRET?.trim() || void 0;
7679
- }
7680
7785
  /** Encode ordered signing fields without allowing delimiter ambiguity. */
7681
7786
  function buildPayload(parts) {
7682
7787
  return [CREDENTIAL_SUBJECT_HMAC_CONTEXT, ...parts].join("\0");
@@ -7707,7 +7812,7 @@ function createSlackDirectCredentialSubject(input) {
7707
7812
  function bindSlackDirectCredentialSubject(input) {
7708
7813
  const channelId = normalizeSlackConversationId(input.channelId);
7709
7814
  const teamId = input.teamId.trim();
7710
- const secret = getCredentialSubjectSecret();
7815
+ const secret = readJuniorSecret();
7711
7816
  const { subject } = input;
7712
7817
  const userId = parseActorUserId(subject.userId);
7713
7818
  if (!channelId || !teamId || !secret || !isDmChannel(channelId) || subject.type !== "user" || !userId || subject.allowedWhen !== "private-direct-conversation") return;
@@ -7731,7 +7836,7 @@ function bindSlackDirectCredentialSubject(input) {
7731
7836
  /** Verify that a delegated subject was signed for the dispatch destination. */
7732
7837
  function verifySlackDirectCredentialSubject(input) {
7733
7838
  const channelId = normalizeSlackConversationId(input.channelId);
7734
- const secret = getCredentialSubjectSecret();
7839
+ const secret = readJuniorSecret();
7735
7840
  if (!channelId || !secret) return false;
7736
7841
  const { subject } = input;
7737
7842
  const binding = subject.binding;
@@ -7745,7 +7850,7 @@ function verifySlackDirectCredentialSubject(input) {
7745
7850
  }
7746
7851
  /** Bind a delegated user subject to one scheduler task dispatch. */
7747
7852
  function bindScheduledAutomationCredentialSubject(input) {
7748
- const secret = getCredentialSubjectSecret();
7853
+ const secret = readJuniorSecret();
7749
7854
  const plugin = input.plugin.trim();
7750
7855
  const userId = parseActorUserId(input.subject.userId);
7751
7856
  if (!secret || plugin !== "scheduler" || !userId || input.subject.allowedWhen !== "scheduled-automation") return;
@@ -7771,7 +7876,7 @@ function bindScheduledAutomationCredentialSubject(input) {
7771
7876
  }
7772
7877
  /** Verify that a delegated subject was signed for one scheduler task. */
7773
7878
  function verifyScheduledAutomationCredentialSubject(input) {
7774
- const secret = getCredentialSubjectSecret();
7879
+ const secret = readJuniorSecret();
7775
7880
  const { subject } = input;
7776
7881
  const binding = subject.binding;
7777
7882
  if (!secret || input.plugin !== "scheduler" || subject.type !== "user" || !isActorUserId(subject.userId) || subject.allowedWhen !== "scheduled-automation" || !subject.taskId || binding.type !== "scheduled-automation" || binding.plugin !== input.plugin || binding.taskId !== subject.taskId) return false;
@@ -7784,7 +7889,7 @@ function verifyScheduledAutomationCredentialSubject(input) {
7784
7889
  }
7785
7890
  /** Bind a delegated user subject to one event automation dispatch. */
7786
7891
  function bindEventAutomationCredentialSubject(input) {
7787
- const secret = getCredentialSubjectSecret();
7892
+ const secret = readJuniorSecret();
7788
7893
  const plugin = input.plugin.trim();
7789
7894
  const userId = parseActorUserId(input.subject.userId);
7790
7895
  if (!secret || plugin !== "junior" || !userId || input.subject.allowedWhen !== "event-automation") return;
@@ -7810,7 +7915,7 @@ function bindEventAutomationCredentialSubject(input) {
7810
7915
  }
7811
7916
  /** Verify that a delegated subject was signed for one event automation. */
7812
7917
  function verifyEventAutomationCredentialSubject(input) {
7813
- const secret = getCredentialSubjectSecret();
7918
+ const secret = readJuniorSecret();
7814
7919
  const { subject } = input;
7815
7920
  const binding = subject.binding;
7816
7921
  if (!secret || input.plugin !== "junior" || subject.type !== "user" || !isActorUserId(subject.userId) || subject.allowedWhen !== "event-automation" || !subject.taskId || binding.type !== "event-automation" || binding.plugin !== input.plugin || binding.taskId !== subject.taskId) return false;
@@ -7823,7 +7928,7 @@ function verifyEventAutomationCredentialSubject(input) {
7823
7928
  }
7824
7929
  /** Bind the user who set a timer Watch to that one Watch. */
7825
7930
  function bindTimerWatchCredentialSubject(input) {
7826
- const secret = getCredentialSubjectSecret();
7931
+ const secret = readJuniorSecret();
7827
7932
  const userId = parseActorUserId(input.userId);
7828
7933
  const { conversationId, watchId } = input;
7829
7934
  if (!secret || !userId || !conversationId || conversationId !== conversationId.trim() || !watchId || watchId !== watchId.trim()) return;
@@ -7846,7 +7951,7 @@ function bindTimerWatchCredentialSubject(input) {
7846
7951
  }
7847
7952
  /** Verify that a delegated subject was signed for one timer Watch. */
7848
7953
  function verifyTimerWatchCredentialSubject(input) {
7849
- const secret = getCredentialSubjectSecret();
7954
+ const secret = readJuniorSecret();
7850
7955
  const { subject } = input;
7851
7956
  const binding = subject.binding;
7852
7957
  if (!secret || subject.type !== "user" || !isActorUserId(subject.userId) || subject.allowedWhen !== "timer-watch" || binding.type !== "timer-watch" || binding.conversationId !== input.conversationId || binding.watchId !== input.watchId) return false;
@@ -8534,6 +8639,11 @@ async function readReviewItemAgentScope(context) {
8534
8639
  * the item, or a person, can change it. An agent cannot use the prefix.
8535
8640
  */
8536
8641
  const PLUGIN_REVIEW_ITEM_KEY_PREFIX = "plugin:";
8642
+ /** Return the plugin that owns a dedupe key, or undefined for an agent's key. */
8643
+ function reviewItemPlugin(dedupeKey) {
8644
+ if (!dedupeKey.startsWith("plugin:")) return void 0;
8645
+ return dedupeKey.slice(7).split(":", 1)[0] || void 0;
8646
+ }
8537
8647
  /**
8538
8648
  * Whether an agent can change an item. Only an agent in the tenant of the
8539
8649
  * item can change it. A public item changes only from a public
@@ -8688,10 +8798,12 @@ async function getReviewItem(db, id) {
8688
8798
  }
8689
8799
  /**
8690
8800
  * Read the action items that the agent added in one Conversation and that a
8691
- * reply can answer: the open items, and the items that a reply closed.
8801
+ * reply can answer: the open items, and the items that a reply closed. A
8802
+ * plugin's items are left out: the plugin closes them when its provider
8803
+ * state changes, such as when a pull request merges.
8692
8804
  */
8693
8805
  async function listReplyActionItems(db, conversationId) {
8694
- return await hydrate(db, await db.select().from(juniorReviewItems).where(and(eq(juniorReviewItems.addedByConversationId, conversationId), eq(juniorReviewItems.kind, "action"), or(eq(juniorReviewItems.status, "open"), eq(juniorReviewItems.closeReason, REVIEW_ITEM_REPLIED_REASON)))));
8806
+ return await hydrate(db, await db.select().from(juniorReviewItems).where(and(eq(juniorReviewItems.addedByConversationId, conversationId), eq(juniorReviewItems.kind, "action"), notLike(juniorReviewItems.dedupeKey, `${PLUGIN_REVIEW_ITEM_KEY_PREFIX}%`), or(eq(juniorReviewItems.status, "open"), eq(juniorReviewItems.closeReason, REVIEW_ITEM_REPLIED_REASON)))));
8695
8807
  }
8696
8808
  /**
8697
8809
  * Read the open Review item with one dedupe key in one provider tenant, if
@@ -8842,17 +8954,25 @@ async function listWaitingConversations(db, userId) {
8842
8954
  const rows = await db.selectDistinct({
8843
8955
  conversationId: sql`coalesce(${juniorConversations.rootConversationId}, ${juniorReviewItemConversations.conversationId})`,
8844
8956
  itemId: juniorReviewItems.id,
8957
+ dedupeKey: juniorReviewItems.dedupeKey,
8845
8958
  title: juniorReviewItems.title,
8846
8959
  createdAt: juniorReviewItems.createdAt
8847
8960
  }).from(juniorReviewItemConversations).innerJoin(juniorReviewItems, eq(juniorReviewItems.id, juniorReviewItemConversations.itemId)).leftJoin(juniorConversations, eq(juniorConversations.conversationId, juniorReviewItemConversations.conversationId)).where(reviewItemNeedsUser(userId)).orderBy(desc(juniorReviewItems.createdAt), desc(juniorReviewItems.id));
8848
8961
  const waiting = /* @__PURE__ */ new Map();
8849
8962
  for (const row of rows) {
8963
+ const plugin = reviewItemPlugin(row.dedupeKey);
8964
+ const item = {
8965
+ title: row.title,
8966
+ ...plugin ? { plugin } : void 0
8967
+ };
8850
8968
  const current = waiting.get(row.conversationId);
8851
- if (current) current.count += 1;
8852
- else waiting.set(row.conversationId, {
8969
+ if (current) {
8970
+ current.items.push(item);
8971
+ current.waitingSince = row.createdAt.toISOString();
8972
+ } else waiting.set(row.conversationId, {
8853
8973
  conversationId: row.conversationId,
8854
- title: row.title,
8855
- count: 1
8974
+ items: [item],
8975
+ waitingSince: row.createdAt.toISOString()
8856
8976
  });
8857
8977
  }
8858
8978
  return [...waiting.values()].sort((left, right) => left.conversationId.localeCompare(right.conversationId));
@@ -8899,7 +9019,7 @@ function createPluginReviewItems(args) {
8899
9019
  assigneeUserIds: await assigneeUserIds(db, notice.assigneeIdentityIds, conversationId),
8900
9020
  body: notice.body,
8901
9021
  conversationIds: [.../* @__PURE__ */ new Set([conversationId, ...existing?.conversationIds ?? []])],
8902
- kind: "notice",
9022
+ kind: notice.waitsOnAssignees ? "action" : "notice",
8903
9023
  title: notice.title,
8904
9024
  visibility: isPrivate ? "private" : "public",
8905
9025
  ...notice.subject ? { subject: notice.subject } : void 0
@@ -9161,7 +9281,7 @@ function isVapidSubject(subject) {
9161
9281
  */
9162
9282
  function readWebPushConfig() {
9163
9283
  const publicKey = process.env.JUNIOR_WEB_PUSH_PUBLIC_KEY?.trim();
9164
- const privateKey = process.env.JUNIOR_WEB_PUSH_PRIVATE_KEY?.trim();
9284
+ const privateKey = readWebPushPrivateKey();
9165
9285
  if (!publicKey || !privateKey) return void 0;
9166
9286
  const subject = process.env.JUNIOR_WEB_PUSH_SUBJECT?.trim() || subjectFromBaseUrl();
9167
9287
  if (!subject || !isVapidSubject(subject)) return void 0;
@@ -10411,6 +10531,7 @@ async function selectPluginGrant(input) {
10411
10531
  ...basePluginContext(plugin),
10412
10532
  request: {
10413
10533
  ...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
10534
+ ...input.gitPush ? { gitPush: input.gitPush } : void 0,
10414
10535
  method: input.method,
10415
10536
  ...input.operation ? { operation: input.operation } : void 0,
10416
10537
  url: input.upstreamUrl.toString()
@@ -10585,18 +10706,36 @@ function refreshLockKey(userId, provider) {
10585
10706
  }
10586
10707
  var StateAdapterTokenStore = class {
10587
10708
  state;
10709
+ secrets;
10588
10710
  constructor(stateAdapter) {
10589
10711
  this.state = stateAdapter;
10712
+ this.secrets = createEncryptedState(stateAdapter);
10590
10713
  }
10591
10714
  async get(userId, provider) {
10592
- const stored = await this.state.get(tokenKey(userId, provider));
10593
- return stored === null || stored === void 0 ? void 0 : storedTokensSchema.parse(stored);
10715
+ const stored = await readEncryptedState(this.state, tokenKey(userId, provider));
10716
+ if (!stored) return void 0;
10717
+ const tokens = storedTokensSchema.parse(stored.value);
10718
+ if (stored.stale) await this.saveStale(userId, provider);
10719
+ return tokens;
10720
+ }
10721
+ /**
10722
+ * Save stale tokens again with the active key. It runs only when the
10723
+ * refresh gate is free, so it cannot write back a refresh token that a
10724
+ * refresh replaced.
10725
+ */
10726
+ async saveStale(userId, provider) {
10727
+ await withLock(this.state, refreshLockKey(userId, provider), async () => {
10728
+ const key = tokenKey(userId, provider);
10729
+ const current = await readEncryptedState(this.state, key);
10730
+ if (!current?.stale) return;
10731
+ await this.set(userId, provider, storedTokensSchema.parse(current.value));
10732
+ }, { ttlMs: MUTATION_LOCK_TTL_MS });
10594
10733
  }
10595
10734
  async set(userId, provider, tokens) {
10596
10735
  const parsed = storedTokensSchema.parse(tokens);
10597
10736
  const expiresAt = parsed.refreshTokenExpiresAt ?? parsed.expiresAt;
10598
10737
  const ttlMs = expiresAt ? Math.max(expiresAt - Date.now() + BUFFER_MS, BUFFER_MS) : LONG_LIVED_TTL_MS;
10599
- await this.state.set(tokenKey(userId, provider), parsed, ttlMs);
10738
+ await this.secrets.set(tokenKey(userId, provider), parsed, ttlMs);
10600
10739
  }
10601
10740
  async delete(userId, provider) {
10602
10741
  await this.state.delete(tokenKey(userId, provider));
@@ -10715,6 +10854,7 @@ async function selectSandboxEgressGrant(input) {
10715
10854
  if (!hasEgressCredentialHooks(input.provider)) return defaultGrantForProvider(input);
10716
10855
  const pluginGrant = await selectPluginGrant({
10717
10856
  ...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
10857
+ ...input.gitPush ? { gitPush: input.gitPush } : void 0,
10718
10858
  ...input.operation ? { operation: input.operation } : void 0,
10719
10859
  provider: input.provider,
10720
10860
  method: input.method,
@@ -10864,8 +11004,15 @@ function policyDeniedResponse(error) {
10864
11004
  headers: { "cache-control": "no-store" }
10865
11005
  });
10866
11006
  }
10867
- function shouldLogSandboxEgressInfo() {
10868
- return (process.env.SENTRY_ENVIRONMENT ?? process.env.VERCEL_ENV ?? process.env.NODE_ENV ?? "").trim().toLowerCase() !== "production";
11007
+ /**
11008
+ * Name the egress decision on every outcome event, so one query over
11009
+ * `app.egress.policy.decision` gives the full trail for a request.
11010
+ */
11011
+ function egressDecisionAttributes(decision, reason) {
11012
+ return reason ? {
11013
+ "app.egress.policy.decision": decision,
11014
+ "app.sandbox.egress.policy.reason": reason
11015
+ } : { "app.egress.policy.decision": decision };
10869
11016
  }
10870
11017
  function egressAttributes(input) {
10871
11018
  return {
@@ -10905,19 +11052,17 @@ function isEgressPolicyDenied(error) {
10905
11052
  return error instanceof EgressPolicyDenied || error instanceof Error && error.name === "EgressPolicyDenied";
10906
11053
  }
10907
11054
  /**
10908
- * Record one forwarded provider request. Write-grant requests are audit
10909
- * events, so they reach Sentry in production. Other requests log only outside
10910
- * production.
11055
+ * Record one forwarded provider request as an audit event, so Sentry keeps
11056
+ * reads and writes in production.
10911
11057
  */
10912
11058
  function logSandboxEgressUpstreamRequest(input) {
10913
- const isWrite = input.grantAccess === "write";
10914
- if (!isWrite && !shouldLogSandboxEgressInfo()) return;
10915
- (isWrite ? logAudit : logInfo)("sandbox.egress.upstream.requested", {
11059
+ const { grant } = input.lease;
11060
+ logAudit("sandbox.egress.upstream.requested", {
10916
11061
  ...egressAttributes({
10917
11062
  egressId: input.egressId,
10918
- grantAccess: input.grantAccess,
10919
- grantName: input.grantName,
10920
- grantReason: input.grantReason,
11063
+ grantAccess: grant.access,
11064
+ grantName: grant.name,
11065
+ grantReason: grant.reason,
10921
11066
  host: input.upstreamUrl.hostname,
10922
11067
  method: input.request.method,
10923
11068
  path: input.upstreamUrl.pathname,
@@ -10925,6 +11070,10 @@ function logSandboxEgressUpstreamRequest(input) {
10925
11070
  status: input.upstream.status
10926
11071
  }),
10927
11072
  ...routingAttributes(input.request, input.upstreamUrl),
11073
+ ...credentialAuditAttributes(input.credentialContext.source),
11074
+ ...grant.auditAttributes,
11075
+ "app.credential.account": credentialAccount(input.lease, input.credentialContext.credentials),
11076
+ ...egressDecisionAttributes("allowed"),
10928
11077
  "app.sandbox.egress.upstream_ok": input.upstream.ok
10929
11078
  });
10930
11079
  }
@@ -11090,6 +11239,16 @@ async function recordSandboxPermissionDenied(input) {
11090
11239
  upstreamPath: displayedUpstreamPath(input.upstreamUrl)
11091
11240
  });
11092
11241
  }
11242
+ async function recordSandboxPolicyDenied(input) {
11243
+ await setSandboxEgressPermissionDeniedSignal(input.credentialContext, {
11244
+ message: input.message,
11245
+ method: input.request.method.toUpperCase(),
11246
+ provider: input.provider,
11247
+ source: "policy",
11248
+ upstreamHost: input.upstreamUrl.hostname,
11249
+ upstreamPath: displayedUpstreamPath(input.upstreamUrl)
11250
+ });
11251
+ }
11093
11252
  /**
11094
11253
  * Forward one verified sandbox egress request with host-managed credentials.
11095
11254
  *
@@ -11115,7 +11274,9 @@ async function executeCredentialedEgressRequest(input) {
11115
11274
  provider,
11116
11275
  status: 500
11117
11276
  }),
11118
- ...routingAttributes(request, upstreamUrl)
11277
+ ...routingAttributes(request, upstreamUrl),
11278
+ ...credentialAuditAttributes(credentialContext.source),
11279
+ ...egressDecisionAttributes("denied", "request body is unreadable")
11119
11280
  }));
11120
11281
  }
11121
11282
  const bodyForGrantSelection = githubBodyInspection({
@@ -11132,6 +11293,7 @@ async function executeCredentialedEgressRequest(input) {
11132
11293
  request,
11133
11294
  upstreamUrl
11134
11295
  }),
11296
+ ...isGitReceivePack(request.method, upstreamUrl) ? { gitPush: readGitPush(body) } : void 0,
11135
11297
  ...operation ? { operation } : void 0,
11136
11298
  provider,
11137
11299
  method: request.method,
@@ -11149,19 +11311,25 @@ async function executeCredentialedEgressRequest(input) {
11149
11311
  status: 403
11150
11312
  }),
11151
11313
  ...routingAttributes(request, upstreamUrl),
11152
- "app.sandbox.egress.policy.reason": error.message
11314
+ ...credentialAuditAttributes(credentialContext.source),
11315
+ ...pluginAuditAttributesSchema.safeParse(error.auditAttributes).data,
11316
+ ...egressDecisionAttributes("denied", error.message)
11317
+ });
11318
+ await recordSandboxPolicyDenied({
11319
+ credentialContext,
11320
+ message: error.message,
11321
+ provider,
11322
+ request,
11323
+ upstreamUrl
11153
11324
  });
11154
11325
  return policyDeniedResponse(error);
11155
11326
  }
11156
11327
  throw error;
11157
11328
  }
11158
- const issueCredentialLease = deps.issueCredentialLease ?? sandboxEgressCredentialLease;
11159
- const clearCredentialLease = deps.clearCredentialLease ?? clearSandboxEgressCredentialLease;
11160
11329
  const recordAuthRequired = deps.recordAuthRequired ?? recordSandboxAuthRequired;
11161
- const recordPermissionDenied = deps.recordPermissionDenied ?? recordSandboxPermissionDenied;
11162
11330
  async function resolveLease() {
11163
11331
  try {
11164
- return await issueCredentialLease(provider, grantSelection, credentialContext);
11332
+ return await sandboxEgressCredentialLease(provider, grantSelection, credentialContext);
11165
11333
  } catch (error) {
11166
11334
  if (!(error instanceof SandboxEgressCredentialError)) throw error;
11167
11335
  await recordAuthRequired({
@@ -11185,7 +11353,9 @@ async function executeCredentialedEgressRequest(input) {
11185
11353
  provider: error.provider,
11186
11354
  status: 401
11187
11355
  }),
11188
- ...routingAttributes(request, upstreamUrl)
11356
+ ...routingAttributes(request, upstreamUrl),
11357
+ ...credentialAuditAttributes(credentialContext.source),
11358
+ ...egressDecisionAttributes("denied", error.message)
11189
11359
  });
11190
11360
  return authRequiredResponse({
11191
11361
  provider: error.provider,
@@ -11208,6 +11378,8 @@ async function executeCredentialedEgressRequest(input) {
11208
11378
  if (!hasSandboxEgressLeaseTransformForHost(lease, upstreamUrl.hostname)) {
11209
11379
  logWarn("sandbox.egress.transform.missing", {
11210
11380
  ...attributes(lease, 403),
11381
+ ...credentialAuditAttributes(credentialContext.source),
11382
+ ...egressDecisionAttributes("denied", "credential lease does not cover forwarded host"),
11211
11383
  "app.sandbox.egress.transform_domains": lease.headerTransforms.map((transform) => transform.domain)
11212
11384
  });
11213
11385
  return Response.json({ error: "Credential lease does not cover forwarded host" }, { status: 403 });
@@ -11249,7 +11421,7 @@ async function executeCredentialedEgressRequest(input) {
11249
11421
  })).permissionDenied;
11250
11422
  } catch (error) {
11251
11423
  if (!isEgressAuthRequired(error)) throw error;
11252
- await clearCredentialLease(provider, lease.grant, credentialContext);
11424
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11253
11425
  await recordAuthRequired({
11254
11426
  credentialContext,
11255
11427
  provider,
@@ -11266,10 +11438,9 @@ async function executeCredentialedEgressRequest(input) {
11266
11438
  });
11267
11439
  }
11268
11440
  logSandboxEgressUpstreamRequest({
11441
+ credentialContext,
11269
11442
  egressId: activeEgressId,
11270
- grantAccess: lease.grant.access,
11271
- grantName: lease.grant.name,
11272
- grantReason: lease.grant.reason,
11443
+ lease,
11273
11444
  provider,
11274
11445
  request,
11275
11446
  upstream,
@@ -11284,7 +11455,7 @@ async function executeCredentialedEgressRequest(input) {
11284
11455
  ...attributes(lease, upstream.status),
11285
11456
  "app.sandbox.egress.www_authenticate": upstream.headers.get("www-authenticate") ?? void 0
11286
11457
  });
11287
- await clearCredentialLease(provider, lease.grant, credentialContext);
11458
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11288
11459
  await recordAuthRequired({
11289
11460
  credentialContext,
11290
11461
  provider,
@@ -11301,7 +11472,7 @@ async function executeCredentialedEgressRequest(input) {
11301
11472
  }
11302
11473
  if (upstream.status === UPSTREAM_PERMISSION_REJECTION_STATUS && !retriedAfter403) {
11303
11474
  logWarn("sandbox.egress.upstream_auth.rejected", { ...attributes(lease, upstream.status) });
11304
- await clearCredentialLease(provider, lease.grant, credentialContext);
11475
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11305
11476
  await upstream.body?.cancel().catch(() => void 0);
11306
11477
  logWarn("sandbox.egress.upstream_auth.retrying", { ...attributes(lease, upstream.status) });
11307
11478
  leaseOrResponse = await resolveLease();
@@ -11312,8 +11483,8 @@ async function executeCredentialedEgressRequest(input) {
11312
11483
  }
11313
11484
  if (upstream.status === UPSTREAM_PERMISSION_REJECTION_STATUS) {
11314
11485
  logWarn("sandbox.egress.upstream_auth.rejected", { ...attributes(lease, upstream.status) });
11315
- await clearCredentialLease(provider, lease.grant, credentialContext);
11316
- await recordPermissionDenied({
11486
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11487
+ await recordSandboxPermissionDenied({
11317
11488
  credentialContext,
11318
11489
  provider,
11319
11490
  lease,
@@ -11329,7 +11500,7 @@ async function executeCredentialedEgressRequest(input) {
11329
11500
  });
11330
11501
  }
11331
11502
  if (pluginPermissionDenied) {
11332
- await recordPermissionDenied({
11503
+ await recordSandboxPermissionDenied({
11333
11504
  credentialContext,
11334
11505
  provider,
11335
11506
  lease,
@@ -13980,17 +14151,18 @@ function createPluginAuthOrchestration(input) {
13980
14151
  };
13981
14152
  }
13982
14153
  // src/chat/egress/plugin.ts
13983
- function credentialContextForPluginEgress(credentialContext) {
14154
+ function credentialContextForPluginEgress(credentialContext, source) {
13984
14155
  return {
13985
14156
  credentials: credentialContext,
13986
14157
  contextId: randomUUID(),
13987
14158
  egressId: `plugin-egress:${randomUUID()}`,
13988
- expiresAtMs: Date.now() + 18e5
14159
+ expiresAtMs: Date.now() + 18e5,
14160
+ source
13989
14161
  };
13990
14162
  }
13991
14163
  /** Create host-owned provider egress for plugin runtime tools. */
13992
14164
  function createPluginEgress(deps) {
13993
- const credentialContext = deps.credentialContext ? credentialContextForPluginEgress(deps.credentialContext) : void 0;
14165
+ const credentialContext = deps.credentialContext ? credentialContextForPluginEgress(deps.credentialContext, deps.credentialAuditSource) : void 0;
13994
14166
  return { async fetch(input) {
13995
14167
  const operation = input.operation.trim();
13996
14168
  if (!operation) throw new Error("Plugin egress operation is required");
@@ -14012,7 +14184,6 @@ function createPluginEgress(deps) {
14012
14184
  provider: signal.provider
14013
14185
  });
14014
14186
  },
14015
- recordPermissionDenied: async () => {},
14016
14187
  tracePropagation: {}
14017
14188
  },
14018
14189
  operation,
@@ -15144,4 +15315,4 @@ async function recordGuardianActionReviewed(args) {
15144
15315
  createdAtMs: Date.now()
15145
15316
  }]);
15146
15317
  }
15147
- export { loadTurnCheckpoint as $, createConversationAccessReader as $a, uploadFilesToConversation as $i, savePushSubscription as $n, verifyScheduledAutomationCredentialSubject as $r, extractAssistantText as $t, latestConversationMessageSeq as A, normalizeSandboxEgressTracePropagationDomains as Aa, isVercelSandboxEgressRequest as Ai, resolvePluginOAuthAccount as An, lookupSlackUser as Ao, automationCreatorUserId as Ar, isInvalidConversationRecordError as At, getAgentContextInputLimitTokens as B, SANDBOX_REPOS_ROOT as Ba, normalizeSlackStatusText as Bi, getPlugins as Bn, cancelWatch as Br, requestConversationWork as Bt, settleConversationTitleWork as C, consumeSandboxEgressAuthRequiredSignal as Ca, setWorkspaceSnapshot as Ci, renderUntrustedTag as Cn, resolveRootVisibility as Co, requireReviewItemLinks as Cr, deadLetterAttempt as Ct, estimateConversationMessagesTokens as D, sandboxEgressSignalsResponseSchema as Da, isStale as Di, findLegacyWebActorUserId as Dn, listConversationAnnotationsById as Do, reviewItemReaderForUserInConversation as Dr, hasConversationStop as Dt, buildConversationContext as E, parseSandboxEgressCredentialToken as Ea, hash as Ei, createUserTokenStore as En, listConversationAnnotations as Eo, reviewItemReaderForUser as Er, getConversationWorkState as Et, turnHasReply as F, PluginToolDeniedError as Fa, resolveBaseUrl as Fi, getPluginRoutes as Fn, historyItemFromPiMessage as Fo, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as Fr, recordAttemptFailure as Ft, AuthPausePersistenceError as G, sandboxSkillPathResolution as Ga, getSlackMessagePermalink as Gi, setBriefsConfig as Gn, findMatchingWatches as Gr, TurnBudgetExceededError as Gt, PluginCredentialFailureError as H, SANDBOX_WORKSPACE_ROOT as Ha, truncateStatusText as Hi, validatePlugins as Hn, createTimerWatch as Hr, steerWebPendingMessages as Ht, upsertConversationMessage as I, createPluginEmbedder as Ia, startOAuthFlow as Ii, getPluginSlackConversationLink as In, piMessageFromHistoryItem as Io, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as Ir, recordConversationRetry as It, abandonReplacedPendingAuth as J, runNonInteractiveCommand as Ja, postSlackEphemeralMessage as Ji, resolveNotificationTimezone as Jn, takeDueTimerWatches as Jr, buildTurnErrorResponse as Jt, AuthorizationFlowDisabledError as K, buildCommandScript as Ka, openSlackDirectMessage as Ki, readWebPushConfig as Kn, getWatch as Kr, TurnSliceLimitExceededError as Kt, calculateContextCompactionTargetTokens as L, createPluginModel as La, escapeSlackMrkdwnText as Li, getPluginSystemPromptContributions as Ln, projectConversationEvents$1 as Lo, RESOURCE_WATCH_TOOL_SOURCE as Lr, releaseConversationWork as Lt, normalizeConversationText as M, sleep$2 as Ma, deliverOAuthAuthorization as Mi, createPluginEventPublisher as Mn, createPluginCache as Mo, resolveAssignees as Mr, markConversationWorkEnqueued as Mt, recordDeliveredAssistantMessage as N, tryWorkspaceRepoCheckoutPath as Na, formatProviderLabel as Ni, createPluginHookRunner as Nn, createDurableLocationConfigurationService as No, resolveChannelCapabilities as Nr, moveIdleConversationDestination as Nt, getConversationMessageSlackTs as O, buildSandboxEgressNetworkPolicy as Oa, ensureDockerDaemon as Oi, webActorUserIds as On, defaultTimezone as Oo, EVERYONE_ASSIGNEE as Or, hasRunnableConversationWork as Ot, trimConversationMessages as P, workspaceRepoCheckoutPath as Pa, parseOAuthStatePayload as Pi, getPluginApiRoutes as Pn, configValueSchema as Po, getSlackToolContext as Pr, pruneActiveConversation as Pt, continuableMessages as Q, canAddConversationMessages as Qa, updateSlackMessage as Qi, saveNotificationSchedule as Qn, verifyEventAutomationCredentialSubject as Qr, persistWithRetry as Qt, getAgentBackgroundCompactionMarkTokens as R, SANDBOX_COMMAND_PATH as Ra, formatSlackLink as Ri, getPluginTools as Rn, getConfigDefaults as Ro, STOP_WATCHING_TOOL_NAME as Rr, releaseInboundMessage as Rt, resolveConversationTitle as S, clearSandboxEgressSignals as Sa, loadSnapshotsForProfile as Si, renderTag as Sn, slackAttachmentsVersionQuery as So, requireReviewItemAssignees as Sr, countPendingConversationMessages as St, resolveTaskTitle as T, createSandboxEgressCredentialToken as Ta, create as Ti, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as Tn, createPluginAnnotations as To, reviewItemNeedsUser as Tr, getConversation as Tt, createPluginAuthOrchestration as U, sandboxSkillDir as Ua, addReactionToMessage as Ui, coreTaskRegistrations as Un, createWatch as Ur, stopConversationWork as Ut, createPluginEgress as V, SANDBOX_SKILLS_ROOT as Va, slackMention as Vi, setPlugins as Vn, collectEventMatchKeys as Vr, startConversationWork as Vt, authorizationId as W, sandboxSkillFile as Wa, deleteSlackMessage as Wi, registration_exports as Wn, deliverWatch as Wr, TURN_LIMIT_WRAP_UP_MESSAGE as Wt, clearPendingAuth as X, createPluginLogger as Xa, removeReactionFromMessage as Xi, listPushSubscriptions as Xn, bindScheduledAutomationCredentialSubject as Xr, isTurnExecutionLimitExceededError as Xt, canReusePendingAuthLink as Y, createPluginModelCostRecorder as Ya, postSlackMessage as Yi, deletePushSubscription as Yn, bindEventAutomationCredentialSubject as Yr, createTurnLimitGate as Yt, getConversationPendingAuth as Z, canAccessConversation as Za, unfurlSlackLinks as Zi, readNotificationSchedule as Zn, bindSlackDirectCredentialSubject as Zr, CODEMODE_TOOL_NAME as Zt, appendConversationMessages as _, wrapSandboxSetupError as _a, listWorkspaces as _i, TURN_CONTEXT_TAG as _n, notInheritedByForkChild as _o, canAgentChangeReviewItem as _r, claimInboundMessage as _t, loadProjection as a, getHeaderString as aa, getDashboardReviewItemLink as ai, instructionTextForProjection as an, conversationViewerMarks as ao, dismissOpenReviewItems as ar, failTurnRecord as at, persistConversationMessages as b, isWorkspaceSnapshotNotReadyError as ba, WorkspaceValidationError as bi, readParentAgentTask as bn, readAttachmentVisionSummary as bo, isOnlyAssignee as br, completeConversationStop as bt, recordAgentsInstructionsUpdated as c, isDmChannel as ca, parseDashboardConversationLink as ci, isStandaloneRuntimeContextMessage as cn, readConversationBriefThrough as co, insertReviewItem as cr, recordTurnSummary as ct, recordAuthorizationCompleted as d, withSlackRetries as da, createPluginState as di, normalizeToolNameFromResult as dn, readConversationEventPageAfter as do, reviewItemsNeedingUserVersionQuery as dr, ackMessages as dt, slackEntitySchema as ea, verifySlackDirectCredentialSubject as ei, getPiMessageRole as en, readConversationAccessFromSql as eo, isPausedBySlack as er, lostWorkerBeforeFirstSave as et, recordAuthorizationRequested as f, getWorkspaceTeamId as fa, renderToolResultNudge as fi, retainRuntimeTurnContext as fn, readConversationEventPageAround as fo, searchReviewItems as fr, appendExclusiveInboundMessage as ft, recordToolExecutionStarted as g, throwSandboxOperationError as ga, getWorkspaceByName as gi, SESSION_CONTEXT_SECTION_TAG as gn, loadForkHistory as go, canActOnReviewItem as gr, checkInConversationWork as gt, recordSubscribedReplyRoute as h, isAlreadyExistsError as ha, getWorkspace as hi, REQUEST_CONTEXT_SECTION_TAG as hn, buildSentryConversationUrl as ho, PLUGIN_REVIEW_ITEM_KEY_PREFIX as hr, cancelHumanFacingPendingMessages as ht, loadConversationProjection as i, getFilePermalink as ia, getDashboardObjectIconLink as ii, hasTurnInput as in, conversationPinnedForUser as io, countReviewItemsNeedingUser as ir, completeTurnRecord as it, markConversationMessage as j, SANDBOX_RUNTIME as ja, proxyVercelSandboxEgressRequest as ji, agent_hooks_exports as jn, lookupSlackUserNames as jo, resolveAssignee as jr, listActiveConversationIds as jt, isHumanConversationMessage as k, resolveSandboxCommandEnvironment as ka, getSandboxProvider as ki, getOAuthAccountProviders as kn, resolveUserTimezone as ko, activeParticipantUserIds as kr, isFinalAttempt as kt, recordAttachmentsDelivered as l, normalizeSlackConversationId as la, setDashboardConversationLinkOptions as li, isToolResultError as ln, readLatestConversationBrief as lo, listReplyActionItems as lr, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as lt, recordMcpProviderConnected as m, isAbortError as ma, deleteWorkspace as mi, trimTrailingAssistantMessages as mn, readConversationMessageEventSeq as mo, updateReviewItemContent as mr, beginConversationResume as mt, commitMessages as n, SlackActionError as na, JUNIOR_THREAD_STATE_TTL_MS as ni, getUserMessageInstructionText as nn, conversationIsMemberRoot as no, REVIEW_ITEM_REPLIED_REASON as nr, saveTurnCheckpoint as nt, loadTurnProjection as o, getSlackClient as oa, getDashboardSettingsLink as oi, isAssistantMessage as on, viewerMarksFromParticipant as oo, getOpenReviewItemByDedupeKey as or, getTurnRecord as ot, recordGuardianActionReviewed as p, runWithWorkspaceTeamId as pa, createWorkspace as pi, stripRuntimeTurnContext as pn, readConversationLastEventSeq as po, takeReviewItem as pr, appendInboundMessage as pt, AuthorizationPauseError as q, buildNonInteractiveShellScript as qa, openSlackModal as qi, sendPushNotificationToUser as qn, listWatches as qr, TurnToolCallLimitExceededError as qt, loadConnectedMcpProviders as r, downloadPrivateSlackFile as ra, getDashboardConversationLink as ri, hasRuntimeTurnContext as rn, conversationIsNotUnsubscribedRoot as ro, closeReviewItem as rr, abandonTurnRecord as rt, openConversationProjection as s, isConversationScopedChannel as sa, getDashboardTaskLink as si, isContinuablePiBoundary as sn, createPluginConversationEvents as so, getReviewItem as sr, listTurnSummaries as st, commitAcceptedReply as t, slackExternalRefIdSchema as ta, verifyTimerWatchCredentialSubject as ti, getTerminalAssistantMessages as tn, conversationHasParticipantUser as to, projectConversationMessages as tr, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, runWithSlackInstallationToken as ua, ToolInputError as ui, isToolResultMessage as un, readConversationEventPage as uo, listWaitingConversations as ur, CONVERSATION_WORK_STALE_ENQUEUE_MS as ut, hydrateConversationMessages as v, WorkspaceSnapshotNotReadyError as va, listWorkspacesByRepository as vi, escapeClosingTags as vn, getSlackFileId as vo, canReadReviewItem as vr, clearConsumedConversationWake as vt, fallbackShortTitle as w, consumeSandboxEgressPermissionDeniedSignal as wa, setWorkspaceSnapshotBuild as wi, tagJson as wn, saveObjectAnnotations as wo, reviewItemNeedsSomeone as wr, drainConversationMailbox as wt, toStoredConversationMessage as x, workspaceSnapshotNotReadyUserMessage as xa, invalidateReadySnapshot as xi, renderChildTag as xn, recordSlackAttachment as xo, readReviewItemAgentScope as xr, completeConversationWork as xt, persistConversationMessageWindow as y, getWorkspaceSnapshotNotReadyError as ya, updateWorkspace as yi, escapeTagText as yn, matchSlackAttachments as yo, canUserReadReviewItem as yr, clearExpiredConversationLease as yt, getAgentContextCompactionTriggerTokens as z, SANDBOX_DATA_ROOT as za, normalizeSlackReplyMarkdown as zi, getPluginUserPromptContributions as zn, setConfigDefaults as zo, cancelSubscriptions as zr, requestAnotherSlice as zt };
15318
+ export { loadTurnCheckpoint as $, createConversationAccessReader as $a, uploadFilesToConversation as $i, savePushSubscription as $n, verifyScheduledAutomationCredentialSubject as $r, extractAssistantText as $t, latestConversationMessageSeq as A, normalizeSandboxEgressTracePropagationDomains as Aa, isVercelSandboxEgressRequest as Ai, resolvePluginOAuthAccount as An, lookupSlackUser as Ao, automationCreatorUserId as Ar, isInvalidConversationRecordError as At, getAgentContextInputLimitTokens as B, SANDBOX_REPOS_ROOT as Ba, normalizeSlackStatusText as Bi, getPlugins as Bn, getConfigDefaults as Bo, cancelWatch as Br, requestConversationWork as Bt, settleConversationTitleWork as C, consumeSandboxEgressAuthRequiredSignal as Ca, setWorkspaceSnapshot as Ci, renderUntrustedTag as Cn, resolveRootVisibility as Co, requireReviewItemLinks as Cr, deadLetterAttempt as Ct, estimateConversationMessagesTokens as D, sandboxEgressSignalsResponseSchema as Da, isStale as Di, findLegacyWebActorUserId as Dn, listConversationAnnotationsById as Do, reviewItemReaderForUserInConversation as Dr, hasConversationStop as Dt, buildConversationContext as E, parseSandboxEgressCredentialToken as Ea, hash as Ei, createUserTokenStore as En, listConversationAnnotations as Eo, reviewItemReaderForUser as Er, getConversationWorkState as Et, turnHasReply as F, PluginToolDeniedError as Fa, resolveBaseUrl as Fi, getPluginRoutes as Fn, createDurableLocationConfigurationService as Fo, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as Fr, recordAttemptFailure as Ft, AuthPausePersistenceError as G, sandboxSkillPathResolution as Ga, getSlackMessagePermalink as Gi, setBriefsConfig as Gn, findMatchingWatches as Gr, TurnBudgetExceededError as Gt, PluginCredentialFailureError as H, SANDBOX_WORKSPACE_ROOT as Ha, truncateStatusText as Hi, validatePlugins as Hn, createTimerWatch as Hr, steerWebPendingMessages as Ht, upsertConversationMessage as I, createPluginEmbedder as Ia, startOAuthFlow as Ii, getPluginSlackConversationLink as In, configValueSchema as Io, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as Ir, recordConversationRetry as It, abandonReplacedPendingAuth as J, runNonInteractiveCommand as Ja, postSlackEphemeralMessage as Ji, resolveNotificationTimezone as Jn, takeDueTimerWatches as Jr, buildTurnErrorResponse as Jt, AuthorizationFlowDisabledError as K, buildCommandScript as Ka, openSlackDirectMessage as Ki, readWebPushConfig as Kn, getWatch as Kr, TurnSliceLimitExceededError as Kt, calculateContextCompactionTargetTokens as L, createPluginModel as La, escapeSlackMrkdwnText as Li, getPluginSystemPromptContributions as Ln, historyItemFromPiMessage as Lo, RESOURCE_WATCH_TOOL_SOURCE as Lr, releaseConversationWork as Lt, normalizeConversationText as M, sleep$2 as Ma, deliverOAuthAuthorization as Mi, createPluginEventPublisher as Mn, credentialAuditAttributes as Mo, resolveAssignees as Mr, markConversationWorkEnqueued as Mt, recordDeliveredAssistantMessage as N, tryWorkspaceRepoCheckoutPath as Na, formatProviderLabel as Ni, createPluginHookRunner as Nn, credentialAuditSource as No, resolveChannelCapabilities as Nr, moveIdleConversationDestination as Nt, getConversationMessageSlackTs as O, buildSandboxEgressNetworkPolicy as Oa, ensureDockerDaemon as Oi, webActorUserIds as On, defaultTimezone as Oo, EVERYONE_ASSIGNEE as Or, hasRunnableConversationWork as Ot, trimConversationMessages as P, workspaceRepoCheckoutPath as Pa, parseOAuthStatePayload as Pi, getPluginApiRoutes as Pn, createPluginCache as Po, getSlackToolContext as Pr, pruneActiveConversation as Pt, continuableMessages as Q, canAddConversationMessages as Qa, updateSlackMessage as Qi, saveNotificationSchedule as Qn, verifyEventAutomationCredentialSubject as Qr, persistWithRetry as Qt, getAgentBackgroundCompactionMarkTokens as R, SANDBOX_COMMAND_PATH as Ra, formatSlackLink as Ri, getPluginTools as Rn, piMessageFromHistoryItem as Ro, STOP_WATCHING_TOOL_NAME as Rr, releaseInboundMessage as Rt, resolveConversationTitle as S, clearSandboxEgressSignals as Sa, loadSnapshotsForProfile as Si, renderTag as Sn, slackAttachmentsVersionQuery as So, requireReviewItemAssignees as Sr, countPendingConversationMessages as St, resolveTaskTitle as T, createSandboxEgressCredentialToken as Ta, create as Ti, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as Tn, createPluginAnnotations as To, reviewItemNeedsUser as Tr, getConversation as Tt, createPluginAuthOrchestration as U, sandboxSkillDir as Ua, addReactionToMessage as Ui, coreTaskRegistrations as Un, createWatch as Ur, stopConversationWork as Ut, createPluginEgress as V, SANDBOX_SKILLS_ROOT as Va, slackMention as Vi, setPlugins as Vn, setConfigDefaults as Vo, collectEventMatchKeys as Vr, startConversationWork as Vt, authorizationId as W, sandboxSkillFile as Wa, deleteSlackMessage as Wi, registration_exports as Wn, deliverWatch as Wr, TURN_LIMIT_WRAP_UP_MESSAGE as Wt, clearPendingAuth as X, createPluginLogger as Xa, removeReactionFromMessage as Xi, listPushSubscriptions as Xn, bindScheduledAutomationCredentialSubject as Xr, isTurnExecutionLimitExceededError as Xt, canReusePendingAuthLink as Y, createPluginModelCostRecorder as Ya, postSlackMessage as Yi, deletePushSubscription as Yn, bindEventAutomationCredentialSubject as Yr, createTurnLimitGate as Yt, getConversationPendingAuth as Z, canAccessConversation as Za, unfurlSlackLinks as Zi, readNotificationSchedule as Zn, bindSlackDirectCredentialSubject as Zr, CODEMODE_TOOL_NAME as Zt, appendConversationMessages as _, wrapSandboxSetupError as _a, listWorkspaces as _i, TURN_CONTEXT_TAG as _n, notInheritedByForkChild as _o, canAgentChangeReviewItem as _r, claimInboundMessage as _t, loadProjection as a, getHeaderString as aa, getDashboardReviewItemLink as ai, instructionTextForProjection as an, conversationViewerMarks as ao, dismissOpenReviewItems as ar, failTurnRecord as at, persistConversationMessages as b, isWorkspaceSnapshotNotReadyError as ba, WorkspaceValidationError as bi, readParentAgentTask as bn, readAttachmentVisionSummary as bo, isOnlyAssignee as br, completeConversationStop as bt, recordAgentsInstructionsUpdated as c, isDmChannel as ca, parseDashboardConversationLink as ci, isStandaloneRuntimeContextMessage as cn, readConversationBriefThrough as co, insertReviewItem as cr, recordTurnSummary as ct, recordAuthorizationCompleted as d, withSlackRetries as da, createPluginState as di, normalizeToolNameFromResult as dn, readConversationEventPageAfter as do, reviewItemsNeedingUserVersionQuery as dr, ackMessages as dt, slackEntitySchema as ea, verifySlackDirectCredentialSubject as ei, getPiMessageRole as en, readConversationAccessFromSql as eo, isPausedBySlack as er, lostWorkerBeforeFirstSave as et, recordAuthorizationRequested as f, getWorkspaceTeamId as fa, renderToolResultNudge as fi, retainRuntimeTurnContext as fn, readConversationEventPageAround as fo, searchReviewItems as fr, appendExclusiveInboundMessage as ft, recordToolExecutionStarted as g, throwSandboxOperationError as ga, getWorkspaceByName as gi, SESSION_CONTEXT_SECTION_TAG as gn, loadForkHistory as go, canActOnReviewItem as gr, checkInConversationWork as gt, recordSubscribedReplyRoute as h, isAlreadyExistsError as ha, getWorkspace as hi, REQUEST_CONTEXT_SECTION_TAG as hn, buildSentryConversationUrl as ho, PLUGIN_REVIEW_ITEM_KEY_PREFIX as hr, cancelHumanFacingPendingMessages as ht, loadConversationProjection as i, getFilePermalink as ia, getDashboardObjectIconLink as ii, hasTurnInput as in, conversationPinnedForUser as io, countReviewItemsNeedingUser as ir, completeTurnRecord as it, markConversationMessage as j, SANDBOX_RUNTIME as ja, proxyVercelSandboxEgressRequest as ji, agent_hooks_exports as jn, lookupSlackUserNames as jo, resolveAssignee as jr, listActiveConversationIds as jt, isHumanConversationMessage as k, resolveSandboxCommandEnvironment as ka, getSandboxProvider as ki, getOAuthAccountProviders as kn, resolveUserTimezone as ko, activeParticipantUserIds as kr, isFinalAttempt as kt, recordAttachmentsDelivered as l, normalizeSlackConversationId as la, setDashboardConversationLinkOptions as li, isToolResultError as ln, readLatestConversationBrief as lo, listReplyActionItems as lr, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as lt, recordMcpProviderConnected as m, isAbortError as ma, deleteWorkspace as mi, trimTrailingAssistantMessages as mn, readConversationMessageEventSeq as mo, updateReviewItemContent as mr, beginConversationResume as mt, commitMessages as n, SlackActionError as na, JUNIOR_THREAD_STATE_TTL_MS as ni, getUserMessageInstructionText as nn, conversationIsMemberRoot as no, REVIEW_ITEM_REPLIED_REASON as nr, saveTurnCheckpoint as nt, loadTurnProjection as o, getSlackClient as oa, getDashboardSettingsLink as oi, isAssistantMessage as on, viewerMarksFromParticipant as oo, getOpenReviewItemByDedupeKey as or, getTurnRecord as ot, recordGuardianActionReviewed as p, runWithWorkspaceTeamId as pa, createWorkspace as pi, stripRuntimeTurnContext as pn, readConversationLastEventSeq as po, takeReviewItem as pr, appendInboundMessage as pt, AuthorizationPauseError as q, buildNonInteractiveShellScript as qa, openSlackModal as qi, sendPushNotificationToUser as qn, listWatches as qr, TurnToolCallLimitExceededError as qt, loadConnectedMcpProviders as r, downloadPrivateSlackFile as ra, getDashboardConversationLink as ri, hasRuntimeTurnContext as rn, conversationIsNotUnsubscribedRoot as ro, closeReviewItem as rr, abandonTurnRecord as rt, openConversationProjection as s, isConversationScopedChannel as sa, getDashboardTaskLink as si, isContinuablePiBoundary as sn, createPluginConversationEvents as so, getReviewItem as sr, listTurnSummaries as st, commitAcceptedReply as t, slackExternalRefIdSchema as ta, verifyTimerWatchCredentialSubject as ti, getTerminalAssistantMessages as tn, conversationHasParticipantUser as to, projectConversationMessages as tr, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, runWithSlackInstallationToken as ua, ToolInputError as ui, isToolResultMessage as un, readConversationEventPage as uo, listWaitingConversations as ur, CONVERSATION_WORK_STALE_ENQUEUE_MS as ut, hydrateConversationMessages as v, WorkspaceSnapshotNotReadyError as va, listWorkspacesByRepository as vi, escapeClosingTags as vn, getSlackFileId as vo, canReadReviewItem as vr, clearConsumedConversationWake as vt, fallbackShortTitle as w, consumeSandboxEgressPermissionDeniedSignal as wa, setWorkspaceSnapshotBuild as wi, tagJson as wn, saveObjectAnnotations as wo, reviewItemNeedsSomeone as wr, drainConversationMailbox as wt, toStoredConversationMessage as x, workspaceSnapshotNotReadyUserMessage as xa, invalidateReadySnapshot as xi, renderChildTag as xn, recordSlackAttachment as xo, readReviewItemAgentScope as xr, completeConversationWork as xt, persistConversationMessageWindow as y, getWorkspaceSnapshotNotReadyError as ya, updateWorkspace as yi, escapeTagText as yn, matchSlackAttachments as yo, canUserReadReviewItem as yr, clearExpiredConversationLease as yt, getAgentContextCompactionTriggerTokens as z, SANDBOX_DATA_ROOT as za, normalizeSlackReplyMarkdown as zi, getPluginUserPromptContributions as zn, projectConversationEvents$1 as zo, cancelSubscriptions as zr, requestAnotherSlice as zt };