@sentry/junior 0.293.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 (85) hide show
  1. package/dist/{admin-uuecrKuD.js → admin-ifgjyfpF.js} +2 -2
  2. package/dist/{agent-runner-DHq1pjUg.js → agent-runner-DjMTPWEO.js} +192 -100
  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 +73 -29
  7. package/dist/{app-fWzCHFIb.d.ts → app-uiTzRbvq.d.ts} +5 -3
  8. package/dist/app.d.ts +2 -2
  9. package/dist/app.js +64 -74
  10. package/dist/{automation-BE3z19VN.js → automation-yJX3C7i3.js} +3 -3
  11. package/dist/{background-compaction-queue-D7ncdEa6.js → background-compaction-queue-DUkHZjmL.js} +7 -9
  12. package/dist/{briefs-NpgMEFh1.js → briefs-CbNYM-q2.js} +3 -3
  13. package/dist/{catalog-runtime-DwbTyNRD.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 +7 -74
  24. package/dist/{config-B4b-NXH5.js → config-DvnTPCfp.js} +58 -7
  25. package/dist/{connections-Dz_AQg5p.js → connections-CWaIVl_1.js} +6 -6
  26. package/dist/{conversation-CtjR1Zcx.js → conversation-CMkSmi02.js} +3 -11
  27. package/dist/{conversation-pending-messages-1Kad1Mif.js → conversation-feed-BVAOga0H.js} +27 -2
  28. package/dist/{conversation-privacy-DRsSgLGO.js → conversation-privacy-DPjv4SnA.js} +1 -1
  29. package/dist/{credential-sync-ClCnnGVj.js → credential-sync-BhbaZfmO.js} +16 -15
  30. package/dist/{db-BbpttyKH.d.ts → db-CCUqQe0E.d.ts} +13 -6
  31. package/dist/{db-CoA7_Xqu.js → db-Dts2XvLu.js} +144 -7
  32. package/dist/{executor-SWyHhit0.js → executor-Ck73J0wP.js} +64 -10
  33. package/dist/instrumentation.js +2 -2
  34. package/dist/{logging-BN5drSEZ.js → logging-9OAq-fdg.js} +2 -1
  35. package/dist/{message-D4qjpW1C.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-Xi-mTLOV.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-DXl4ftyL.js → projection-BzJQncZV.js} +251 -161
  42. package/dist/{prompt-Dmx6IfWZ.js → prompt-Cbq5b4SO.js} +5 -6
  43. package/dist/{registry-DosVt9f9.js → registry-cbpOxO4M.js} +3 -13
  44. package/dist/{resolve-BDjWJC9s.js → resolve-t-pmRdwS.js} +3 -3
  45. package/dist/{result-CaAFpf4B.js → result-DhgjR3nQ.js} +8 -8
  46. package/dist/{runner-h96Mkss6.js → runner-CHv9X9TH.js} +8 -8
  47. package/dist/{sandbox-egress-signals-rK91BW7i.js → sandbox-egress-signals-Yy3fSCbg.js} +1 -1
  48. package/dist/{schema-C_v8wb80.js → schema-BhneuGYv.js} +39 -7
  49. package/dist/{schema-CHsBmXIj.d.ts → schema-TSEisVJR.d.ts} +87 -14
  50. package/dist/secrets-DebYU866.js +18 -0
  51. package/dist/{service-account-WUMVuqVL.js → service-account-C4rBP8ne.js} +3 -3
  52. package/dist/{service-account-BpGpScaT.js → service-account-DjPIwCMj.js} +42 -26
  53. package/dist/{session-stop-xYK15HUu.js → session-stop-DkxI5vc3.js} +20 -775
  54. package/dist/{skills-DHApyCjj.js → skills-BZE2DP8I.js} +2 -2
  55. package/dist/{spawn-BQQrwGNe.js → spawn-BvULxIiu.js} +5 -5
  56. package/dist/{adapter-CMJfmHso.js → state-CO9ETDzk.js} +132 -2
  57. package/dist/{stop-CBeD6_Gs.js → stop-CL-rdtQb.js} +85 -32
  58. package/dist/{store-xtibD98L.js → store-DgD78_NK.js} +3 -3
  59. package/dist/{task-runner-BYPN4BEO.js → task-runner-CKOj6xla.js} +11 -11
  60. package/dist/{turn-failure-response-jNVl00MD.js → turn-failure-response-BTSo6SMJ.js} +8 -8
  61. package/dist/{validation-DGeB_moV.js → validation-CXeYgBzq.js} +1 -1
  62. package/dist/{version-C6nqU3Qc.js → version-AQa7Fr2H.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/{viewer-9KLQibjn.js → viewer-Bqkb678l.js} +3 -3
  65. package/dist/warmup-h6u1e9n0.js +1869 -0
  66. package/dist/{work-xwX6unUE.js → work-yN_GAuXY.js} +11 -11
  67. package/dist/{worker-CiCCfwd4.js → worker-Hl7N292I.js} +6 -6
  68. package/migrations/0062_plugin_report_index.sql +1 -20
  69. package/migrations/0078_plugin_conversation_index.sql +1 -20
  70. package/migrations/0079_conversation_event_author_index.sql +1 -20
  71. package/migrations/0080_conversation_event_latest_message_indexes.sql +2 -27
  72. package/migrations/0090_guardian_review_time_index.sql +1 -20
  73. package/migrations/0091_conversation_participant_unsubscribed_index.sql +1 -20
  74. package/migrations/0097_conversation_kind_automation.sql +6 -0
  75. package/migrations/0098_review_item_plugin_actions.sql +5 -0
  76. package/migrations/0099_conversation_last_message_at.sql +1 -0
  77. package/migrations/0100_automation_task_kind_repair.sql +48 -0
  78. package/migrations/meta/0097_snapshot.json +4490 -0
  79. package/migrations/meta/0098_snapshot.json +4490 -0
  80. package/migrations/meta/0099_snapshot.json +4720 -0
  81. package/migrations/meta/0100_snapshot.json +4496 -0
  82. package/migrations/meta/_journal.json +28 -0
  83. package/package.json +5 -5
  84. package/dist/assistant-reply-CIApSfor.js +0 -58
  85. package/dist/warmup-7S6z068f.js +0 -993
@@ -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, J as toOptionalTrimmed, L as escapeXml, S as completeObject, T as rerankTexts, 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-B4b-NXH5.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-BN5drSEZ.js";
4
- import { t as canExposeConversationPayload } from "./conversation-privacy-DRsSgLGO.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 { $ as sameDestination, B as addAgentTurnUsage, D as resolveActorIdentityId, I as bindProviderConversation, M as readUserTimezone, P as saveUserTimezone, W as hasAgentTurnUsage, Z as parseDestination, a as getConversationStore, d as createSqlConversationEventStore, f as eventFromRow, o as getDb, p as withConversationEventLock, q as conversationDetailTouch, r as getConversationEventStore, s as getSqlExecutor, w as startLocationThread, y as createSqlStore } from "./db-CoA7_Xqu.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-SWyHhit0.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-DosVt9f9.js";
10
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DwbTyNRD.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-Dmx6IfWZ.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-9KLQibjn.js";
14
- import { a as setStateValues, i as getStateValues, n as getDefaultRedisStateAdapterFor, r as getStateAdapter } from "./adapter-CMJfmHso.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-CtjR1Zcx.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
  }
@@ -5374,6 +5482,7 @@ async function withSlackRetries(task, maxAttempts = 3, context = {}) {
5374
5482
  ...context.attributes ?? {}
5375
5483
  };
5376
5484
  if (!isRetryable || attempt >= maxAttempts || remainingDelayBudgetMs <= 0) {
5485
+ if (context.expectedErrorCodes?.includes(mapped.code)) throw mapped;
5377
5486
  logWarn("slack.action.failed", {
5378
5487
  ...baseLogAttributes,
5379
5488
  ...mapped.errorData ? { "app.slack.error_data": mapped.errorData } : void 0
@@ -5817,6 +5926,7 @@ async function addReactionToMessage(input) {
5817
5926
  name: emoji
5818
5927
  }), input.timeoutMs === void 0 ? 3 : 1, {
5819
5928
  action: "reactions.add",
5929
+ expectedErrorCodes: ["already_reacted"],
5820
5930
  idempotent: true,
5821
5931
  spanAttributes: {
5822
5932
  "app.slack.channel_id": channelId,
@@ -5843,6 +5953,7 @@ async function removeReactionFromMessage(input) {
5843
5953
  name: emoji
5844
5954
  }), 3, {
5845
5955
  action: "reactions.remove",
5956
+ expectedErrorCodes: ["no_reaction"],
5846
5957
  idempotent: true,
5847
5958
  spanAttributes: {
5848
5959
  "app.slack.channel_id": channelId,
@@ -7671,9 +7782,6 @@ async function updateTimerIndex(state, operation) {
7671
7782
  // src/chat/credentials/subject.ts
7672
7783
  const CREDENTIAL_SUBJECT_HMAC_CONTEXT = "junior.credential_subject.v1";
7673
7784
  const CREDENTIAL_SUBJECT_SIGNATURE_VERSION = "v1";
7674
- function getCredentialSubjectSecret() {
7675
- return process.env.JUNIOR_SECRET?.trim() || void 0;
7676
- }
7677
7785
  /** Encode ordered signing fields without allowing delimiter ambiguity. */
7678
7786
  function buildPayload(parts) {
7679
7787
  return [CREDENTIAL_SUBJECT_HMAC_CONTEXT, ...parts].join("\0");
@@ -7704,7 +7812,7 @@ function createSlackDirectCredentialSubject(input) {
7704
7812
  function bindSlackDirectCredentialSubject(input) {
7705
7813
  const channelId = normalizeSlackConversationId(input.channelId);
7706
7814
  const teamId = input.teamId.trim();
7707
- const secret = getCredentialSubjectSecret();
7815
+ const secret = readJuniorSecret();
7708
7816
  const { subject } = input;
7709
7817
  const userId = parseActorUserId(subject.userId);
7710
7818
  if (!channelId || !teamId || !secret || !isDmChannel(channelId) || subject.type !== "user" || !userId || subject.allowedWhen !== "private-direct-conversation") return;
@@ -7728,7 +7836,7 @@ function bindSlackDirectCredentialSubject(input) {
7728
7836
  /** Verify that a delegated subject was signed for the dispatch destination. */
7729
7837
  function verifySlackDirectCredentialSubject(input) {
7730
7838
  const channelId = normalizeSlackConversationId(input.channelId);
7731
- const secret = getCredentialSubjectSecret();
7839
+ const secret = readJuniorSecret();
7732
7840
  if (!channelId || !secret) return false;
7733
7841
  const { subject } = input;
7734
7842
  const binding = subject.binding;
@@ -7742,7 +7850,7 @@ function verifySlackDirectCredentialSubject(input) {
7742
7850
  }
7743
7851
  /** Bind a delegated user subject to one scheduler task dispatch. */
7744
7852
  function bindScheduledAutomationCredentialSubject(input) {
7745
- const secret = getCredentialSubjectSecret();
7853
+ const secret = readJuniorSecret();
7746
7854
  const plugin = input.plugin.trim();
7747
7855
  const userId = parseActorUserId(input.subject.userId);
7748
7856
  if (!secret || plugin !== "scheduler" || !userId || input.subject.allowedWhen !== "scheduled-automation") return;
@@ -7768,7 +7876,7 @@ function bindScheduledAutomationCredentialSubject(input) {
7768
7876
  }
7769
7877
  /** Verify that a delegated subject was signed for one scheduler task. */
7770
7878
  function verifyScheduledAutomationCredentialSubject(input) {
7771
- const secret = getCredentialSubjectSecret();
7879
+ const secret = readJuniorSecret();
7772
7880
  const { subject } = input;
7773
7881
  const binding = subject.binding;
7774
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;
@@ -7781,7 +7889,7 @@ function verifyScheduledAutomationCredentialSubject(input) {
7781
7889
  }
7782
7890
  /** Bind a delegated user subject to one event automation dispatch. */
7783
7891
  function bindEventAutomationCredentialSubject(input) {
7784
- const secret = getCredentialSubjectSecret();
7892
+ const secret = readJuniorSecret();
7785
7893
  const plugin = input.plugin.trim();
7786
7894
  const userId = parseActorUserId(input.subject.userId);
7787
7895
  if (!secret || plugin !== "junior" || !userId || input.subject.allowedWhen !== "event-automation") return;
@@ -7807,7 +7915,7 @@ function bindEventAutomationCredentialSubject(input) {
7807
7915
  }
7808
7916
  /** Verify that a delegated subject was signed for one event automation. */
7809
7917
  function verifyEventAutomationCredentialSubject(input) {
7810
- const secret = getCredentialSubjectSecret();
7918
+ const secret = readJuniorSecret();
7811
7919
  const { subject } = input;
7812
7920
  const binding = subject.binding;
7813
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;
@@ -7820,7 +7928,7 @@ function verifyEventAutomationCredentialSubject(input) {
7820
7928
  }
7821
7929
  /** Bind the user who set a timer Watch to that one Watch. */
7822
7930
  function bindTimerWatchCredentialSubject(input) {
7823
- const secret = getCredentialSubjectSecret();
7931
+ const secret = readJuniorSecret();
7824
7932
  const userId = parseActorUserId(input.userId);
7825
7933
  const { conversationId, watchId } = input;
7826
7934
  if (!secret || !userId || !conversationId || conversationId !== conversationId.trim() || !watchId || watchId !== watchId.trim()) return;
@@ -7843,7 +7951,7 @@ function bindTimerWatchCredentialSubject(input) {
7843
7951
  }
7844
7952
  /** Verify that a delegated subject was signed for one timer Watch. */
7845
7953
  function verifyTimerWatchCredentialSubject(input) {
7846
- const secret = getCredentialSubjectSecret();
7954
+ const secret = readJuniorSecret();
7847
7955
  const { subject } = input;
7848
7956
  const binding = subject.binding;
7849
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;
@@ -8531,6 +8639,11 @@ async function readReviewItemAgentScope(context) {
8531
8639
  * the item, or a person, can change it. An agent cannot use the prefix.
8532
8640
  */
8533
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
+ }
8534
8647
  /**
8535
8648
  * Whether an agent can change an item. Only an agent in the tenant of the
8536
8649
  * item can change it. A public item changes only from a public
@@ -8685,10 +8798,12 @@ async function getReviewItem(db, id) {
8685
8798
  }
8686
8799
  /**
8687
8800
  * Read the action items that the agent added in one Conversation and that a
8688
- * 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.
8689
8804
  */
8690
8805
  async function listReplyActionItems(db, conversationId) {
8691
- 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)))));
8692
8807
  }
8693
8808
  /**
8694
8809
  * Read the open Review item with one dedupe key in one provider tenant, if
@@ -8839,17 +8954,25 @@ async function listWaitingConversations(db, userId) {
8839
8954
  const rows = await db.selectDistinct({
8840
8955
  conversationId: sql`coalesce(${juniorConversations.rootConversationId}, ${juniorReviewItemConversations.conversationId})`,
8841
8956
  itemId: juniorReviewItems.id,
8957
+ dedupeKey: juniorReviewItems.dedupeKey,
8842
8958
  title: juniorReviewItems.title,
8843
8959
  createdAt: juniorReviewItems.createdAt
8844
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));
8845
8961
  const waiting = /* @__PURE__ */ new Map();
8846
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
+ };
8847
8968
  const current = waiting.get(row.conversationId);
8848
- if (current) current.count += 1;
8849
- 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, {
8850
8973
  conversationId: row.conversationId,
8851
- title: row.title,
8852
- count: 1
8974
+ items: [item],
8975
+ waitingSince: row.createdAt.toISOString()
8853
8976
  });
8854
8977
  }
8855
8978
  return [...waiting.values()].sort((left, right) => left.conversationId.localeCompare(right.conversationId));
@@ -8896,7 +9019,7 @@ function createPluginReviewItems(args) {
8896
9019
  assigneeUserIds: await assigneeUserIds(db, notice.assigneeIdentityIds, conversationId),
8897
9020
  body: notice.body,
8898
9021
  conversationIds: [.../* @__PURE__ */ new Set([conversationId, ...existing?.conversationIds ?? []])],
8899
- kind: "notice",
9022
+ kind: notice.waitsOnAssignees ? "action" : "notice",
8900
9023
  title: notice.title,
8901
9024
  visibility: isPrivate ? "private" : "public",
8902
9025
  ...notice.subject ? { subject: notice.subject } : void 0
@@ -9158,7 +9281,7 @@ function isVapidSubject(subject) {
9158
9281
  */
9159
9282
  function readWebPushConfig() {
9160
9283
  const publicKey = process.env.JUNIOR_WEB_PUSH_PUBLIC_KEY?.trim();
9161
- const privateKey = process.env.JUNIOR_WEB_PUSH_PRIVATE_KEY?.trim();
9284
+ const privateKey = readWebPushPrivateKey();
9162
9285
  if (!publicKey || !privateKey) return void 0;
9163
9286
  const subject = process.env.JUNIOR_WEB_PUSH_SUBJECT?.trim() || subjectFromBaseUrl();
9164
9287
  if (!subject || !isVapidSubject(subject)) return void 0;
@@ -10408,6 +10531,7 @@ async function selectPluginGrant(input) {
10408
10531
  ...basePluginContext(plugin),
10409
10532
  request: {
10410
10533
  ...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
10534
+ ...input.gitPush ? { gitPush: input.gitPush } : void 0,
10411
10535
  method: input.method,
10412
10536
  ...input.operation ? { operation: input.operation } : void 0,
10413
10537
  url: input.upstreamUrl.toString()
@@ -10582,18 +10706,36 @@ function refreshLockKey(userId, provider) {
10582
10706
  }
10583
10707
  var StateAdapterTokenStore = class {
10584
10708
  state;
10709
+ secrets;
10585
10710
  constructor(stateAdapter) {
10586
10711
  this.state = stateAdapter;
10712
+ this.secrets = createEncryptedState(stateAdapter);
10587
10713
  }
10588
10714
  async get(userId, provider) {
10589
- const stored = await this.state.get(tokenKey(userId, provider));
10590
- 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 });
10591
10733
  }
10592
10734
  async set(userId, provider, tokens) {
10593
10735
  const parsed = storedTokensSchema.parse(tokens);
10594
10736
  const expiresAt = parsed.refreshTokenExpiresAt ?? parsed.expiresAt;
10595
10737
  const ttlMs = expiresAt ? Math.max(expiresAt - Date.now() + BUFFER_MS, BUFFER_MS) : LONG_LIVED_TTL_MS;
10596
- await this.state.set(tokenKey(userId, provider), parsed, ttlMs);
10738
+ await this.secrets.set(tokenKey(userId, provider), parsed, ttlMs);
10597
10739
  }
10598
10740
  async delete(userId, provider) {
10599
10741
  await this.state.delete(tokenKey(userId, provider));
@@ -10712,6 +10854,7 @@ async function selectSandboxEgressGrant(input) {
10712
10854
  if (!hasEgressCredentialHooks(input.provider)) return defaultGrantForProvider(input);
10713
10855
  const pluginGrant = await selectPluginGrant({
10714
10856
  ...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
10857
+ ...input.gitPush ? { gitPush: input.gitPush } : void 0,
10715
10858
  ...input.operation ? { operation: input.operation } : void 0,
10716
10859
  provider: input.provider,
10717
10860
  method: input.method,
@@ -10861,8 +11004,15 @@ function policyDeniedResponse(error) {
10861
11004
  headers: { "cache-control": "no-store" }
10862
11005
  });
10863
11006
  }
10864
- function shouldLogSandboxEgressInfo() {
10865
- 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 };
10866
11016
  }
10867
11017
  function egressAttributes(input) {
10868
11018
  return {
@@ -10902,19 +11052,17 @@ function isEgressPolicyDenied(error) {
10902
11052
  return error instanceof EgressPolicyDenied || error instanceof Error && error.name === "EgressPolicyDenied";
10903
11053
  }
10904
11054
  /**
10905
- * Record one forwarded provider request. Write-grant requests are audit
10906
- * events, so they reach Sentry in production. Other requests log only outside
10907
- * production.
11055
+ * Record one forwarded provider request as an audit event, so Sentry keeps
11056
+ * reads and writes in production.
10908
11057
  */
10909
11058
  function logSandboxEgressUpstreamRequest(input) {
10910
- const isWrite = input.grantAccess === "write";
10911
- if (!isWrite && !shouldLogSandboxEgressInfo()) return;
10912
- (isWrite ? logAudit : logInfo)("sandbox.egress.upstream.requested", {
11059
+ const { grant } = input.lease;
11060
+ logAudit("sandbox.egress.upstream.requested", {
10913
11061
  ...egressAttributes({
10914
11062
  egressId: input.egressId,
10915
- grantAccess: input.grantAccess,
10916
- grantName: input.grantName,
10917
- grantReason: input.grantReason,
11063
+ grantAccess: grant.access,
11064
+ grantName: grant.name,
11065
+ grantReason: grant.reason,
10918
11066
  host: input.upstreamUrl.hostname,
10919
11067
  method: input.request.method,
10920
11068
  path: input.upstreamUrl.pathname,
@@ -10922,6 +11070,10 @@ function logSandboxEgressUpstreamRequest(input) {
10922
11070
  status: input.upstream.status
10923
11071
  }),
10924
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"),
10925
11077
  "app.sandbox.egress.upstream_ok": input.upstream.ok
10926
11078
  });
10927
11079
  }
@@ -11087,6 +11239,16 @@ async function recordSandboxPermissionDenied(input) {
11087
11239
  upstreamPath: displayedUpstreamPath(input.upstreamUrl)
11088
11240
  });
11089
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
+ }
11090
11252
  /**
11091
11253
  * Forward one verified sandbox egress request with host-managed credentials.
11092
11254
  *
@@ -11112,7 +11274,9 @@ async function executeCredentialedEgressRequest(input) {
11112
11274
  provider,
11113
11275
  status: 500
11114
11276
  }),
11115
- ...routingAttributes(request, upstreamUrl)
11277
+ ...routingAttributes(request, upstreamUrl),
11278
+ ...credentialAuditAttributes(credentialContext.source),
11279
+ ...egressDecisionAttributes("denied", "request body is unreadable")
11116
11280
  }));
11117
11281
  }
11118
11282
  const bodyForGrantSelection = githubBodyInspection({
@@ -11129,6 +11293,7 @@ async function executeCredentialedEgressRequest(input) {
11129
11293
  request,
11130
11294
  upstreamUrl
11131
11295
  }),
11296
+ ...isGitReceivePack(request.method, upstreamUrl) ? { gitPush: readGitPush(body) } : void 0,
11132
11297
  ...operation ? { operation } : void 0,
11133
11298
  provider,
11134
11299
  method: request.method,
@@ -11146,19 +11311,25 @@ async function executeCredentialedEgressRequest(input) {
11146
11311
  status: 403
11147
11312
  }),
11148
11313
  ...routingAttributes(request, upstreamUrl),
11149
- "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
11150
11324
  });
11151
11325
  return policyDeniedResponse(error);
11152
11326
  }
11153
11327
  throw error;
11154
11328
  }
11155
- const issueCredentialLease = deps.issueCredentialLease ?? sandboxEgressCredentialLease;
11156
- const clearCredentialLease = deps.clearCredentialLease ?? clearSandboxEgressCredentialLease;
11157
11329
  const recordAuthRequired = deps.recordAuthRequired ?? recordSandboxAuthRequired;
11158
- const recordPermissionDenied = deps.recordPermissionDenied ?? recordSandboxPermissionDenied;
11159
11330
  async function resolveLease() {
11160
11331
  try {
11161
- return await issueCredentialLease(provider, grantSelection, credentialContext);
11332
+ return await sandboxEgressCredentialLease(provider, grantSelection, credentialContext);
11162
11333
  } catch (error) {
11163
11334
  if (!(error instanceof SandboxEgressCredentialError)) throw error;
11164
11335
  await recordAuthRequired({
@@ -11182,7 +11353,9 @@ async function executeCredentialedEgressRequest(input) {
11182
11353
  provider: error.provider,
11183
11354
  status: 401
11184
11355
  }),
11185
- ...routingAttributes(request, upstreamUrl)
11356
+ ...routingAttributes(request, upstreamUrl),
11357
+ ...credentialAuditAttributes(credentialContext.source),
11358
+ ...egressDecisionAttributes("denied", error.message)
11186
11359
  });
11187
11360
  return authRequiredResponse({
11188
11361
  provider: error.provider,
@@ -11205,6 +11378,8 @@ async function executeCredentialedEgressRequest(input) {
11205
11378
  if (!hasSandboxEgressLeaseTransformForHost(lease, upstreamUrl.hostname)) {
11206
11379
  logWarn("sandbox.egress.transform.missing", {
11207
11380
  ...attributes(lease, 403),
11381
+ ...credentialAuditAttributes(credentialContext.source),
11382
+ ...egressDecisionAttributes("denied", "credential lease does not cover forwarded host"),
11208
11383
  "app.sandbox.egress.transform_domains": lease.headerTransforms.map((transform) => transform.domain)
11209
11384
  });
11210
11385
  return Response.json({ error: "Credential lease does not cover forwarded host" }, { status: 403 });
@@ -11246,7 +11421,7 @@ async function executeCredentialedEgressRequest(input) {
11246
11421
  })).permissionDenied;
11247
11422
  } catch (error) {
11248
11423
  if (!isEgressAuthRequired(error)) throw error;
11249
- await clearCredentialLease(provider, lease.grant, credentialContext);
11424
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11250
11425
  await recordAuthRequired({
11251
11426
  credentialContext,
11252
11427
  provider,
@@ -11263,10 +11438,9 @@ async function executeCredentialedEgressRequest(input) {
11263
11438
  });
11264
11439
  }
11265
11440
  logSandboxEgressUpstreamRequest({
11441
+ credentialContext,
11266
11442
  egressId: activeEgressId,
11267
- grantAccess: lease.grant.access,
11268
- grantName: lease.grant.name,
11269
- grantReason: lease.grant.reason,
11443
+ lease,
11270
11444
  provider,
11271
11445
  request,
11272
11446
  upstream,
@@ -11281,7 +11455,7 @@ async function executeCredentialedEgressRequest(input) {
11281
11455
  ...attributes(lease, upstream.status),
11282
11456
  "app.sandbox.egress.www_authenticate": upstream.headers.get("www-authenticate") ?? void 0
11283
11457
  });
11284
- await clearCredentialLease(provider, lease.grant, credentialContext);
11458
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11285
11459
  await recordAuthRequired({
11286
11460
  credentialContext,
11287
11461
  provider,
@@ -11298,7 +11472,7 @@ async function executeCredentialedEgressRequest(input) {
11298
11472
  }
11299
11473
  if (upstream.status === UPSTREAM_PERMISSION_REJECTION_STATUS && !retriedAfter403) {
11300
11474
  logWarn("sandbox.egress.upstream_auth.rejected", { ...attributes(lease, upstream.status) });
11301
- await clearCredentialLease(provider, lease.grant, credentialContext);
11475
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11302
11476
  await upstream.body?.cancel().catch(() => void 0);
11303
11477
  logWarn("sandbox.egress.upstream_auth.retrying", { ...attributes(lease, upstream.status) });
11304
11478
  leaseOrResponse = await resolveLease();
@@ -11309,8 +11483,8 @@ async function executeCredentialedEgressRequest(input) {
11309
11483
  }
11310
11484
  if (upstream.status === UPSTREAM_PERMISSION_REJECTION_STATUS) {
11311
11485
  logWarn("sandbox.egress.upstream_auth.rejected", { ...attributes(lease, upstream.status) });
11312
- await clearCredentialLease(provider, lease.grant, credentialContext);
11313
- await recordPermissionDenied({
11486
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11487
+ await recordSandboxPermissionDenied({
11314
11488
  credentialContext,
11315
11489
  provider,
11316
11490
  lease,
@@ -11326,7 +11500,7 @@ async function executeCredentialedEgressRequest(input) {
11326
11500
  });
11327
11501
  }
11328
11502
  if (pluginPermissionDenied) {
11329
- await recordPermissionDenied({
11503
+ await recordSandboxPermissionDenied({
11330
11504
  credentialContext,
11331
11505
  provider,
11332
11506
  lease,
@@ -11702,89 +11876,6 @@ function buildTurnLimitResponse(eventId) {
11702
11876
  function buildTurnErrorResponse(error, eventId) {
11703
11877
  return isTurnExecutionLimitExceededError(error) ? buildTurnLimitResponse(eventId) : buildTurnFailureResponse(eventId);
11704
11878
  }
11705
- // src/chat/conversations/kind-behavior.ts
11706
- const ROOT = {
11707
- delivery: "location",
11708
- promptMode: "conversation",
11709
- gated: false,
11710
- tools: {
11711
- agents: "children",
11712
- reviewDesk: true,
11713
- subscriptions: true,
11714
- userCustomization: true,
11715
- reportBlocked: false,
11716
- noReply: true,
11717
- finishAutomationRun: false
11718
- }
11719
- };
11720
- const PERSON_IN_THREAD = {
11721
- ...ROOT,
11722
- tools: {
11723
- ...ROOT.tools,
11724
- agents: "none"
11725
- }
11726
- };
11727
- const AGENT_IN_CHILD = {
11728
- delivery: "conversation",
11729
- promptMode: "child_agent",
11730
- gated: false,
11731
- tools: {
11732
- agents: "children_and_parent",
11733
- reviewDesk: false,
11734
- subscriptions: false,
11735
- userCustomization: false,
11736
- reportBlocked: true,
11737
- noReply: true,
11738
- finishAutomationRun: false
11739
- }
11740
- };
11741
- const AUTOMATION_RUN = {
11742
- delivery: "conversation",
11743
- promptMode: "automation",
11744
- gated: true,
11745
- tools: {
11746
- ...ROOT.tools,
11747
- noReply: false,
11748
- finishAutomationRun: true
11749
- }
11750
- };
11751
- /**
11752
- * Return the behavior of one Turn. `automationRun` marks a Scheduled or Event
11753
- * automation run. It is a temporary bridge until Conversation kind
11754
- * `automation` replaces it.
11755
- *
11756
- * TODO(dcramer): Remove `automationRun` when kind `automation` ships.
11757
- */
11758
- function turnBehavior(args) {
11759
- if (args.automationRun) return AUTOMATION_RUN;
11760
- if (args.kind === "root") return ROOT;
11761
- if (!args.personInput) return AGENT_IN_CHILD;
11762
- if (args.kind === "thread") return PERSON_IN_THREAD;
11763
- throw new Error("A task Conversation cannot have a person's input");
11764
- }
11765
- /** Return whether a person sent input from this Source. */
11766
- function isPersonInput(source) {
11767
- return source === "web" || source === "slack";
11768
- }
11769
- /**
11770
- * Return whether the runtime delivers the final response of a Slack or
11771
- * dispatch run. Only root Conversations reach these paths, so only an
11772
- * Automation run keeps its final response in the Conversation. A dispatch
11773
- * with no outcomes delivers nothing.
11774
- */
11775
- function deliversFinalText(dispatch) {
11776
- return dispatch?.outcomes?.length !== 0 && !dispatch?.declaresResult;
11777
- }
11778
- /**
11779
- * Return whether the runtime may post a failure reply or a status notice,
11780
- * such as an auth prompt, for a run outside `finishedRunReply`. The rule is
11781
- * the same as for a final response. A chat Turn may post, also in a thread
11782
- * that an Automation Conversation owns. An Automation run posts only a
11783
- * declared message; its failed execution shows on the Automation.
11784
- */
11785
- function postsRunNotices(dispatch) {
11786
- return deliversFinalText(dispatch);
11787
- }
11788
11879
  // src/chat/task-execution/state.ts
11789
11880
  /**
11790
11881
  * Expiring conversation mailbox and execution index store.
@@ -14060,17 +14151,18 @@ function createPluginAuthOrchestration(input) {
14060
14151
  };
14061
14152
  }
14062
14153
  // src/chat/egress/plugin.ts
14063
- function credentialContextForPluginEgress(credentialContext) {
14154
+ function credentialContextForPluginEgress(credentialContext, source) {
14064
14155
  return {
14065
14156
  credentials: credentialContext,
14066
14157
  contextId: randomUUID(),
14067
14158
  egressId: `plugin-egress:${randomUUID()}`,
14068
- expiresAtMs: Date.now() + 18e5
14159
+ expiresAtMs: Date.now() + 18e5,
14160
+ source
14069
14161
  };
14070
14162
  }
14071
14163
  /** Create host-owned provider egress for plugin runtime tools. */
14072
14164
  function createPluginEgress(deps) {
14073
- const credentialContext = deps.credentialContext ? credentialContextForPluginEgress(deps.credentialContext) : void 0;
14165
+ const credentialContext = deps.credentialContext ? credentialContextForPluginEgress(deps.credentialContext, deps.credentialAuditSource) : void 0;
14074
14166
  return { async fetch(input) {
14075
14167
  const operation = input.operation.trim();
14076
14168
  if (!operation) throw new Error("Plugin egress operation is required");
@@ -14092,7 +14184,6 @@ function createPluginEgress(deps) {
14092
14184
  provider: signal.provider
14093
14185
  });
14094
14186
  },
14095
- recordPermissionDenied: async () => {},
14096
14187
  tracePropagation: {}
14097
14188
  },
14098
14189
  operation,
@@ -14473,7 +14564,6 @@ async function generateShortTitle(args) {
14473
14564
  const result = await args.completeText({
14474
14565
  signal: args.signal,
14475
14566
  modelId: botConfig.fastModelId,
14476
- temperature: 0,
14477
14567
  operation: `${args.kind}_title`,
14478
14568
  cost: args.cost,
14479
14569
  messages: [{
@@ -15225,4 +15315,4 @@ async function recordGuardianActionReviewed(args) {
15225
15315
  createdAtMs: Date.now()
15226
15316
  }]);
15227
15317
  }
15228
- export { loadTurnCheckpoint as $, createPluginModelCostRecorder as $a, postSlackMessage as $i, deletePushSubscription as $n, bindEventAutomationCredentialSubject as $r, createTurnLimitGate as $t, latestConversationMessageSeq as A, parseSandboxEgressCredentialToken as Aa, hash as Ai, createUserTokenStore as An, listConversationAnnotations as Ao, reviewItemReaderForUser as Ar, isInvalidConversationRecordError as At, getAgentContextInputLimitTokens as B, createPluginEmbedder as Ba, startOAuthFlow as Bi, getPluginSlackConversationLink as Bn, piMessageFromHistoryItem as Bo, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as Br, requestConversationWork as Bt, settleConversationTitleWork as C, getWorkspaceSnapshotNotReadyError as Ca, updateWorkspace as Ci, escapeTagText as Cn, matchSlackAttachments as Co, canUserReadReviewItem as Cr, deadLetterAttempt as Ct, estimateConversationMessagesTokens as D, consumeSandboxEgressAuthRequiredSignal as Da, setWorkspaceSnapshot as Di, renderUntrustedTag as Dn, resolveRootVisibility as Do, requireReviewItemLinks as Dr, hasConversationStop as Dt, buildConversationContext as E, clearSandboxEgressSignals as Ea, loadSnapshotsForProfile as Ei, renderTag as En, slackAttachmentsVersionQuery as Eo, requireReviewItemAssignees as Er, getConversationWorkState as Et, turnHasReply as F, SANDBOX_RUNTIME as Fa, proxyVercelSandboxEgressRequest as Fi, agent_hooks_exports as Fn, lookupSlackUserNames as Fo, resolveAssignee as Fr, recordAttemptFailure as Ft, AuthPausePersistenceError as G, SANDBOX_SKILLS_ROOT as Ga, slackMention as Gi, setPlugins as Gn, collectEventMatchKeys as Gr, isPersonInput as Gt, PluginCredentialFailureError as H, SANDBOX_COMMAND_PATH as Ha, formatSlackLink as Hi, getPluginTools as Hn, getConfigDefaults as Ho, STOP_WATCHING_TOOL_NAME as Hr, steerWebPendingMessages as Ht, upsertConversationMessage as I, sleep$2 as Ia, deliverOAuthAuthorization as Ii, createPluginEventPublisher as In, createPluginCache as Io, resolveAssignees as Ir, recordConversationRetry as It, abandonReplacedPendingAuth as J, sandboxSkillFile as Ja, deleteSlackMessage as Ji, registration_exports as Jn, deliverWatch as Jr, TURN_LIMIT_WRAP_UP_MESSAGE as Jt, AuthorizationFlowDisabledError as K, SANDBOX_WORKSPACE_ROOT as Ka, truncateStatusText as Ki, validatePlugins as Kn, createTimerWatch as Kr, postsRunNotices as Kt, calculateContextCompactionTargetTokens as L, tryWorkspaceRepoCheckoutPath as La, formatProviderLabel as Li, createPluginHookRunner as Ln, createDurableLocationConfigurationService as Lo, resolveChannelCapabilities as Lr, releaseConversationWork as Lt, normalizeConversationText as M, buildSandboxEgressNetworkPolicy as Ma, ensureDockerDaemon as Mi, webActorUserIds as Mn, defaultTimezone as Mo, EVERYONE_ASSIGNEE as Mr, markConversationWorkEnqueued as Mt, recordDeliveredAssistantMessage as N, resolveSandboxCommandEnvironment as Na, getSandboxProvider as Ni, getOAuthAccountProviders as Nn, resolveUserTimezone as No, activeParticipantUserIds as Nr, moveIdleConversationDestination as Nt, getConversationMessageSlackTs as O, consumeSandboxEgressPermissionDeniedSignal as Oa, setWorkspaceSnapshotBuild as Oi, tagJson as On, saveObjectAnnotations as Oo, reviewItemNeedsSomeone as Or, hasRunnableConversationWork as Ot, trimConversationMessages as P, normalizeSandboxEgressTracePropagationDomains as Pa, isVercelSandboxEgressRequest as Pi, resolvePluginOAuthAccount as Pn, lookupSlackUser as Po, automationCreatorUserId as Pr, pruneActiveConversation as Pt, continuableMessages as Q, runNonInteractiveCommand as Qa, postSlackEphemeralMessage as Qi, resolveNotificationTimezone as Qn, takeDueTimerWatches as Qr, buildTurnErrorResponse as Qt, getAgentBackgroundCompactionMarkTokens as R, workspaceRepoCheckoutPath as Ra, parseOAuthStatePayload as Ri, getPluginApiRoutes as Rn, configValueSchema as Ro, getSlackToolContext as Rr, releaseInboundMessage as Rt, resolveConversationTitle as S, WorkspaceSnapshotNotReadyError as Sa, listWorkspacesByRepository as Si, escapeClosingTags as Sn, getSlackFileId as So, canReadReviewItem as Sr, countPendingConversationMessages as St, resolveTaskTitle as T, workspaceSnapshotNotReadyUserMessage as Ta, invalidateReadySnapshot as Ti, renderChildTag as Tn, recordSlackAttachment as To, readReviewItemAgentScope as Tr, getConversation as Tt, createPluginAuthOrchestration as U, SANDBOX_DATA_ROOT as Ua, normalizeSlackReplyMarkdown as Ui, getPluginUserPromptContributions as Un, setConfigDefaults as Uo, cancelSubscriptions as Ur, stopConversationWork as Ut, createPluginEgress as V, createPluginModel as Va, escapeSlackMrkdwnText as Vi, getPluginSystemPromptContributions as Vn, projectConversationEvents$1 as Vo, RESOURCE_WATCH_TOOL_SOURCE as Vr, startConversationWork as Vt, authorizationId as W, SANDBOX_REPOS_ROOT as Wa, normalizeSlackStatusText as Wi, getPlugins as Wn, cancelWatch as Wr, deliversFinalText as Wt, clearPendingAuth as X, buildCommandScript as Xa, openSlackDirectMessage as Xi, readWebPushConfig as Xn, getWatch as Xr, TurnSliceLimitExceededError as Xt, canReusePendingAuthLink as Y, sandboxSkillPathResolution as Ya, getSlackMessagePermalink as Yi, setBriefsConfig as Yn, findMatchingWatches as Yr, TurnBudgetExceededError as Yt, getConversationPendingAuth as Z, buildNonInteractiveShellScript as Za, openSlackModal as Zi, sendPushNotificationToUser as Zn, listWatches as Zr, TurnToolCallLimitExceededError as Zt, appendConversationMessages as _, runWithWorkspaceTeamId as _a, createWorkspace as _i, stripRuntimeTurnContext as _n, readConversationLastEventSeq as _o, takeReviewItem as _r, claimInboundMessage as _t, loadProjection as a, slackExternalRefIdSchema as aa, verifyTimerWatchCredentialSubject as ai, getTerminalAssistantMessages as an, conversationHasParticipantUser as ao, projectConversationMessages as ar, failTurnRecord as at, persistConversationMessages as b, throwSandboxOperationError as ba, getWorkspaceByName as bi, SESSION_CONTEXT_SECTION_TAG as bn, loadForkHistory as bo, canActOnReviewItem as br, completeConversationStop as bt, recordAgentsInstructionsUpdated as c, getFilePermalink as ca, getDashboardObjectIconLink as ci, hasTurnInput as cn, conversationPinnedForUser as co, countReviewItemsNeedingUser as cr, recordTurnSummary as ct, recordAuthorizationCompleted as d, isConversationScopedChannel as da, getDashboardTaskLink as di, isContinuablePiBoundary as dn, createPluginConversationEvents as do, getReviewItem as dr, ackMessages as dt, removeReactionFromMessage as ea, bindScheduledAutomationCredentialSubject as ei, isTurnExecutionLimitExceededError as en, createPluginLogger as eo, listPushSubscriptions as er, lostWorkerBeforeFirstSave as et, recordAuthorizationRequested as f, isDmChannel as fa, parseDashboardConversationLink as fi, isStandaloneRuntimeContextMessage as fn, readConversationBriefThrough as fo, insertReviewItem as fr, appendExclusiveInboundMessage as ft, recordToolExecutionStarted as g, getWorkspaceTeamId as ga, renderToolResultNudge as gi, retainRuntimeTurnContext as gn, readConversationEventPageAround as go, searchReviewItems as gr, checkInConversationWork as gt, recordSubscribedReplyRoute as h, withSlackRetries as ha, createPluginState as hi, normalizeToolNameFromResult as hn, readConversationEventPageAfter as ho, reviewItemsNeedingUserVersionQuery as hr, cancelHumanFacingPendingMessages as ht, loadConversationProjection as i, slackEntitySchema as ia, verifySlackDirectCredentialSubject as ii, getPiMessageRole as in, readConversationAccessFromSql as io, isPausedBySlack as ir, completeTurnRecord as it, markConversationMessage as j, sandboxEgressSignalsResponseSchema as ja, isStale as ji, findLegacyWebActorUserId as jn, listConversationAnnotationsById as jo, reviewItemReaderForUserInConversation as jr, listActiveConversationIds as jt, isHumanConversationMessage as k, createSandboxEgressCredentialToken as ka, create as ki, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as kn, createPluginAnnotations as ko, reviewItemNeedsUser as kr, isFinalAttempt as kt, recordAttachmentsDelivered as l, getHeaderString as la, getDashboardReviewItemLink as li, instructionTextForProjection as ln, conversationViewerMarks as lo, dismissOpenReviewItems as lr, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as lt, recordMcpProviderConnected as m, runWithSlackInstallationToken as ma, ToolInputError as mi, isToolResultMessage as mn, readConversationEventPage as mo, listWaitingConversations as mr, beginConversationResume as mt, commitMessages as n, updateSlackMessage as na, verifyEventAutomationCredentialSubject as ni, persistWithRetry as nn, canAddConversationMessages as no, saveNotificationSchedule as nr, saveTurnCheckpoint as nt, loadTurnProjection as o, SlackActionError as oa, JUNIOR_THREAD_STATE_TTL_MS as oi, getUserMessageInstructionText as on, conversationIsMemberRoot as oo, REVIEW_ITEM_REPLIED_REASON as or, getTurnRecord as ot, recordGuardianActionReviewed as p, normalizeSlackConversationId as pa, setDashboardConversationLinkOptions as pi, isToolResultError as pn, readLatestConversationBrief as po, listReplyActionItems as pr, appendInboundMessage as pt, AuthorizationPauseError as q, sandboxSkillDir as qa, addReactionToMessage as qi, coreTaskRegistrations as qn, createWatch as qr, turnBehavior as qt, loadConnectedMcpProviders as r, uploadFilesToConversation as ra, verifyScheduledAutomationCredentialSubject as ri, extractAssistantText as rn, createConversationAccessReader as ro, savePushSubscription as rr, abandonTurnRecord as rt, openConversationProjection as s, downloadPrivateSlackFile as sa, getDashboardConversationLink as si, hasRuntimeTurnContext as sn, conversationIsNotUnsubscribedRoot as so, closeReviewItem as sr, listTurnSummaries as st, commitAcceptedReply as t, unfurlSlackLinks as ta, bindSlackDirectCredentialSubject as ti, CODEMODE_TOOL_NAME as tn, canAccessConversation as to, readNotificationSchedule as tr, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, getSlackClient as ua, getDashboardSettingsLink as ui, isAssistantMessage as un, viewerMarksFromParticipant as uo, getOpenReviewItemByDedupeKey as ur, CONVERSATION_WORK_STALE_ENQUEUE_MS as ut, hydrateConversationMessages as v, isAbortError as va, deleteWorkspace as vi, trimTrailingAssistantMessages as vn, readConversationMessageEventSeq as vo, updateReviewItemContent as vr, clearConsumedConversationWake as vt, fallbackShortTitle as w, isWorkspaceSnapshotNotReadyError as wa, WorkspaceValidationError as wi, readParentAgentTask as wn, readAttachmentVisionSummary as wo, isOnlyAssignee as wr, drainConversationMailbox as wt, toStoredConversationMessage as x, wrapSandboxSetupError as xa, listWorkspaces as xi, TURN_CONTEXT_TAG as xn, notInheritedByForkChild as xo, canAgentChangeReviewItem as xr, completeConversationWork as xt, persistConversationMessageWindow as y, isAlreadyExistsError as ya, getWorkspace as yi, REQUEST_CONTEXT_SECTION_TAG as yn, buildSentryConversationUrl as yo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as yr, clearExpiredConversationLease as yt, getAgentContextCompactionTriggerTokens as z, PluginToolDeniedError as za, resolveBaseUrl as zi, getPluginRoutes as zn, historyItemFromPiMessage as zo, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS 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 };