@sentry/junior 0.294.0 → 0.296.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 (79) hide show
  1. package/dist/{admin-vt8aSiCD.js → admin-z_lgDi-z.js} +2 -2
  2. package/dist/{agent-runner-DJu7w6mI.js → agent-runner-HoQiUKLL.js} +318 -199
  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 +321 -331
  7. package/dist/{app--a5RLOrr.d.ts → app-C75Ft-A_.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-Cre1wFt9.js} +7 -9
  12. package/dist/{briefs-JOAoCb6d.js → briefs-BXECHduJ.js} +3 -3
  13. package/dist/{catalog-runtime-CLMA9AXd.js → catalog-runtime-CpCmlD9L.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-CCPHvTqx.js} +59 -2
  25. package/dist/{connections-XhdVg7OR.js → connections-B5pWh8e2.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-CZD5soDW.js} +1 -1
  29. package/dist/{credential-sync-zigBlXS3.js → credential-sync-DwLkIvXI.js} +16 -15
  30. package/dist/{db-DV5AbcGM.d.ts → db-B3iyr_Or.d.ts} +6 -1
  31. package/dist/{db--xuNV7g6.js → db-C1M1y-bh.js} +64 -26
  32. package/dist/{executor-BItuRqAR.js → executor-DUSEwXaO.js} +16 -5
  33. package/dist/instrumentation.js +19 -2
  34. package/dist/{logging-Cb6MGvdt.js → logging-D0svFM8r.js} +2 -1
  35. package/dist/{message-BTGgSmaH.js → message-BFnIwKpx.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-BXRtD6Fk.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-B6VS7kbo.js} +386 -108
  42. package/dist/{prompt-qp_LdxLX.js → prompt-CD11tfG8.js} +4 -4
  43. package/dist/{registry-MtwokaqW.js → registry-CHewwYEo.js} +3 -13
  44. package/dist/{resolve-BnJA0UNE.js → resolve-1owMH4qo.js} +3 -3
  45. package/dist/{result-ChL-1KyW.js → result-CEqQFrEf.js} +8 -8
  46. package/dist/{runner-BONN7Dp2.js → runner-BtWvJslp.js} +8 -8
  47. package/dist/{sandbox-egress-signals-nmlmI5Ab.js → sandbox-egress-signals-ByftwJVt.js} +1 -1
  48. package/dist/{schema-DgvcyJ1y.d.ts → schema-Ct1Zf2xy.d.ts} +66 -14
  49. package/dist/{schema-yr0ccDni.js → schema-D2iGyYIp.js} +24 -6
  50. package/dist/secrets-DebYU866.js +18 -0
  51. package/dist/{service-account-Bd0lBaGr.js → service-account-BZEuMKdo.js} +3 -3
  52. package/dist/{service-account-kio5nXSD.js → service-account-DLoeoHww.js} +42 -26
  53. package/dist/{session-stop-CeCXL3j9.js → session-stop-hYNTNpVf.js} +23 -778
  54. package/dist/{skills-e3DDNlKO.js → skills-DXgd5Inh.js} +3 -3
  55. package/dist/{spawn--cRxITWQ.js → spawn-YeqlNDv8.js} +5 -5
  56. package/dist/{adapter-DxLhJEnO.js → state-C3CbtD_m.js} +132 -2
  57. package/dist/{stop-Iai5N2PU.js → stop-Cze_pEL8.js} +351 -255
  58. package/dist/{store-C8LsaJwS.js → store-CZ9vqR4P.js} +3 -3
  59. package/dist/{task-runner-Dw7exu0-.js → task-runner-CMiNGsER.js} +275 -251
  60. package/dist/{turn-failure-response-BqTTx3XG.js → turn-failure-response-pXhZ2wMK.js} +12 -9
  61. package/dist/{validation-BrGahtnv.js → validation-Du7NdkOR.js} +1 -1
  62. package/dist/{version-Bdqhx8Qh.js → version-EN3Wnq-R.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/{viewer-CjRFHR5U.js → viewer-Agxi_o5c.js} +3 -3
  65. package/dist/warmup-CY2ArYag.js +2017 -0
  66. package/dist/{work-BWBG1EGV.js → work-EA98F0ia.js} +11 -11
  67. package/dist/{worker-DAnBIVMs.js → worker-BALVdWbv.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/0101_drop_legacy_columns.sql +12 -0
  72. package/migrations/meta/0098_snapshot.json +4490 -0
  73. package/migrations/meta/0099_snapshot.json +4720 -0
  74. package/migrations/meta/0100_snapshot.json +4496 -0
  75. package/migrations/meta/0101_snapshot.json +4496 -0
  76. package/migrations/meta/_journal.json +28 -0
  77. package/package.json +6 -5
  78. package/dist/assistant-reply-iTtEdDyc.js +0 -58
  79. 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-CCPHvTqx.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-D0svFM8r.js";
4
+ import { t as canExposeConversationPayload } from "./conversation-privacy-CZD5soDW.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-C1M1y-bh.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-DUSEwXaO.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-CHewwYEo.js";
10
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-CpCmlD9L.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-CD11tfG8.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-Agxi_o5c.js";
14
+ import { a as getStateAdapter, i as getDefaultRedisStateAdapterFor, n as readEncryptedState, o as getStateValues, s as setStateValues, t as createEncryptedState } from "./state-C3CbtD_m.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,219 @@ 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$1(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$1("gzip");
484
+ const decoder = new TextDecoder();
485
+ const updates = [];
486
+ let offset = 0;
487
+ while (true) {
488
+ if (offset + 4 > bytes.length) return unreadable$1("unterminated");
489
+ const lengthText = String.fromCharCode(...bytes.subarray(offset, offset + 4));
490
+ if (!PKT_LENGTH.test(lengthText)) return unreadable$1("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$1("malformed");
497
+ if (offset + length > bytes.length) return unreadable$1("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$1("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$1("malformed");
505
+ updates.push({
506
+ deletes: ZERO_OBJECT_ID.test(newId),
507
+ ref
508
+ });
509
+ }
510
+ }
511
+ // src/chat/egress/graphql.ts
512
+ /** Largest GraphQL body that the host reads before it issues credentials. */
513
+ const GRAPHQL_BODY_LIMIT_BYTES = 65536;
514
+ /** Match a GraphQL request whose body names the operation. */
515
+ function isGraphqlPost(method, upstreamUrl) {
516
+ return method.toUpperCase() === "POST" && upstreamUrl.pathname.toLowerCase().endsWith("/graphql");
517
+ }
518
+ function unreadable(reason) {
519
+ return {
520
+ kind: "unreadable",
521
+ reason
522
+ };
523
+ }
524
+ /**
525
+ * Read the operations of a GraphQL POST body.
526
+ *
527
+ * A JSON array is a batch. One unreadable entry makes the whole batch
528
+ * unreadable.
529
+ */
530
+ async function readGraphqlRequest(body) {
531
+ const bytes = new Uint8Array(body ?? /* @__PURE__ */ new ArrayBuffer(0));
532
+ if (bytes[0] === 31 && bytes[1] === 139) return unreadable("gzip");
533
+ if (bytes.byteLength > GRAPHQL_BODY_LIMIT_BYTES) return unreadable("too-large");
534
+ let parsed;
535
+ try {
536
+ parsed = JSON.parse(new TextDecoder().decode(bytes));
537
+ } catch {
538
+ return unreadable("json");
539
+ }
540
+ if (!Array.isArray(parsed)) {
541
+ const operation = await readOperation(parsed);
542
+ return typeof operation === "string" ? unreadable(operation) : {
543
+ kind: "operation",
544
+ operation
545
+ };
546
+ }
547
+ const operations = [];
548
+ for (const entry of parsed) {
549
+ const operation = await readOperation(entry);
550
+ if (typeof operation === "string") return unreadable(operation);
551
+ operations.push(operation);
552
+ }
553
+ return {
554
+ kind: "batch",
555
+ operations
556
+ };
557
+ }
558
+ async function readOperation(entry) {
559
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return "json";
560
+ const { operationName, query } = entry;
561
+ if (typeof query !== "string") return "query";
562
+ if (operationName !== void 0 && operationName !== null && typeof operationName !== "string") return "operation";
563
+ const { parse } = await import("graphql");
564
+ let document;
565
+ try {
566
+ document = parse(query, { noLocation: true });
567
+ } catch {
568
+ return "document";
569
+ }
570
+ const fragments = /* @__PURE__ */ new Map();
571
+ const operations = [];
572
+ for (const definition of document.definitions) if (definition.kind === "OperationDefinition") operations.push(definition);
573
+ else if (definition.kind === "FragmentDefinition") {
574
+ if (fragments.has(definition.name.value)) return "document";
575
+ fragments.set(definition.name.value, definition);
576
+ }
577
+ const operation = operationName ? operations.find((candidate) => candidate.name?.value === operationName) : operations.length === 1 ? operations[0] : void 0;
578
+ if (!operation) return "operation";
579
+ const fields = /* @__PURE__ */ new Map();
580
+ const rootFields = [];
581
+ if (!collectFields(operation.selectionSet, fragments, /* @__PURE__ */ new Set(), fields) || !collectRootFields(operation.selectionSet, fragments, /* @__PURE__ */ new Set(), rootFields)) return "document";
582
+ return {
583
+ fields: [...fields.values()],
584
+ ...operation.name ? { name: operation.name.value } : void 0,
585
+ rootFields,
586
+ type: operation.operation
587
+ };
588
+ }
589
+ /** Add each distinct field at any depth. Each fragment is read once. */
590
+ function collectFields(selectionSet, fragments, seen, fields) {
591
+ for (const selection of selectionSet.selections) {
592
+ if (selection.kind === "Field") {
593
+ const name = selection.name.value;
594
+ const args = (selection.arguments ?? []).map((arg) => arg.name.value);
595
+ const key = [name, ...args].join("\0");
596
+ if (!fields.has(key)) fields.set(key, {
597
+ arguments: args,
598
+ name
599
+ });
600
+ if (selection.selectionSet && !collectFields(selection.selectionSet, fragments, seen, fields)) return false;
601
+ continue;
602
+ }
603
+ const inner = fragmentSelectionSet(selection, fragments, seen);
604
+ if (inner === false) return false;
605
+ if (inner && !collectFields(inner, fragments, seen, fields)) return false;
606
+ }
607
+ return true;
608
+ }
609
+ /** Add the operation root fields, through fragments. */
610
+ function collectRootFields(selectionSet, fragments, seen, rootFields) {
611
+ for (const selection of selectionSet.selections) {
612
+ if (selection.kind === "Field") {
613
+ rootFields.push(selection.name.value);
614
+ continue;
615
+ }
616
+ const inner = fragmentSelectionSet(selection, fragments, seen);
617
+ if (inner === false) return false;
618
+ if (inner && !collectRootFields(inner, fragments, seen, rootFields)) return false;
619
+ }
620
+ return true;
621
+ }
622
+ /**
623
+ * Return the selections of an inline fragment or a fragment spread.
624
+ *
625
+ * Returns undefined for a fragment already read, which also stops cycles, and
626
+ * false for a spread of an undefined fragment.
627
+ */
628
+ function fragmentSelectionSet(selection, fragments, seen) {
629
+ if (selection.kind === "InlineFragment") return selection.selectionSet;
630
+ const name = selection.name.value;
631
+ if (seen.has(name)) return;
632
+ seen.add(name);
633
+ return fragments.get(name)?.selectionSet ?? false;
634
+ }
421
635
  // src/chat/slack/user.ts
422
636
  const slackUserInfoSchema = z.object({
423
637
  ok: z.literal(true),
@@ -3836,7 +4050,9 @@ const sandboxEgressCredentialContextSchema = z.object({
3836
4050
  conversationId: z.string().min(1).optional(),
3837
4051
  egressId: z.string().min(1),
3838
4052
  expiresAtMs: finiteNumberSchema,
3839
- contextId: z.string().min(1)
4053
+ contextId: z.string().min(1),
4054
+ /** Run Source that write audit events name. Telemetry only; it grants nothing. */
4055
+ source: credentialAuditSourceSchema.optional()
3840
4056
  }).strict();
3841
4057
  const sandboxEgressCredentialLeaseSchema = z.object({
3842
4058
  account: pluginProviderAccountSchema.optional(),
@@ -3860,7 +4076,7 @@ const sandboxEgressAuthRequiredSignalSchema = z.object({
3860
4076
  path: ["authorization", "provider"]
3861
4077
  });
3862
4078
  });
3863
- const sandboxEgressPermissionDeniedSignalSchema = z.object({
4079
+ const sandboxEgressUpstreamPermissionDeniedSignalSchema = z.object({
3864
4080
  account: pluginProviderAccountSchema.optional(),
3865
4081
  grant: sandboxEgressGrantSchema,
3866
4082
  message: z.string().min(1),
@@ -3871,6 +4087,17 @@ const sandboxEgressPermissionDeniedSignalSchema = z.object({
3871
4087
  upstreamPath: z.string().min(1),
3872
4088
  createdAtMs: finiteNumberSchema
3873
4089
  }).strict();
4090
+ /** A request that Junior's egress policy refused before it chose a credential. */
4091
+ const sandboxEgressPolicyDeniedSignalSchema = z.object({
4092
+ message: z.string().min(1),
4093
+ method: z.string().min(1),
4094
+ provider: providerNameSchema,
4095
+ source: z.literal("policy"),
4096
+ upstreamHost: z.string().min(1),
4097
+ upstreamPath: z.string().min(1),
4098
+ createdAtMs: finiteNumberSchema
4099
+ }).strict();
4100
+ const sandboxEgressPermissionDeniedSignalSchema = z.discriminatedUnion("source", [sandboxEgressUpstreamPermissionDeniedSignalSchema, sandboxEgressPolicyDeniedSignalSchema]);
3874
4101
  const sandboxEgressSignalsResponseSchema = z.object({
3875
4102
  auth_required: sandboxEgressAuthRequiredSignalSchema.optional(),
3876
4103
  permission_denied: sandboxEgressPermissionDeniedSignalSchema.optional()
@@ -3954,7 +4181,7 @@ function parseLease(value) {
3954
4181
  return result.data;
3955
4182
  }
3956
4183
  function getSandboxEgressSecret() {
3957
- const secret = process.env.JUNIOR_SECRET?.trim();
4184
+ const secret = readJuniorSecret();
3958
4185
  if (secret) return secret;
3959
4186
  throw new Error("Cannot determine sandbox egress secret (set JUNIOR_SECRET)");
3960
4187
  }
@@ -3973,7 +4200,8 @@ function createSandboxEgressCredentialToken(input) {
3973
4200
  credentials: input.credentials,
3974
4201
  egressId: input.egressId,
3975
4202
  expiresAtMs: now + ttlMs,
3976
- contextId: randomUUID()
4203
+ contextId: randomUUID(),
4204
+ ...input.source ? { source: input.source } : void 0
3977
4205
  };
3978
4206
  const payload = `${SANDBOX_EGRESS_TOKEN_VERSION}.${base64Url(JSON.stringify(context))}`;
3979
4207
  return `${payload}.${signPayload$1(payload)}`;
@@ -4012,14 +4240,15 @@ async function setSandboxEgressCredentialLease(_context, lease) {
4012
4240
  const ttlMs = Math.max(1, leaseExpiresAtMs - Date.now());
4013
4241
  const state = getStateAdapter();
4014
4242
  await state.connect();
4015
- await state.set(leaseKey(lease.provider, lease.grant), lease, ttlMs);
4243
+ await createEncryptedState(state).set(leaseKey(lease.provider, lease.grant), lease, ttlMs);
4016
4244
  }
4017
4245
  /** Load remembered auth headers for a shared installation grant. */
4018
4246
  async function getSandboxEgressCredentialLease(provider, grant, _context) {
4019
4247
  if (!isSharedInstallationGrant(grant)) return;
4020
4248
  const state = getStateAdapter();
4021
4249
  await state.connect();
4022
- return parseLease(await state.get(leaseKey(provider, grant)));
4250
+ const stored = await readEncryptedState(state, leaseKey(provider, grant));
4251
+ return stored?.stale ? void 0 : parseLease(stored?.value);
4023
4252
  }
4024
4253
  /** Drop remembered installation headers after the upstream rejects them. */
4025
4254
  async function clearSandboxEgressCredentialLease(provider, grant, _context) {
@@ -4045,13 +4274,14 @@ async function setSandboxEgressAuthRequiredSignal(context, signal) {
4045
4274
  }, ttlMs);
4046
4275
  }
4047
4276
  /**
4048
- * Record that the provider rejected an issued credential with permission denial.
4277
+ * Record that the provider rejected an issued credential, or that Junior's
4278
+ * egress policy refused the request before it chose a credential.
4049
4279
  */
4050
4280
  async function setSandboxEgressPermissionDeniedSignal(context, signal) {
4051
4281
  const ttlMs = Math.max(1, context.expiresAtMs - Date.now());
4052
4282
  const state = getStateAdapter();
4053
4283
  await state.connect();
4054
- await state.set(permissionSignalKey(context.egressId, signal.grant.access), {
4284
+ await state.set(permissionSignalKey(context.egressId, signal.source === "upstream" ? signal.grant.access : "write"), {
4055
4285
  ...signal,
4056
4286
  createdAtMs: Date.now()
4057
4287
  }, ttlMs);
@@ -4168,7 +4398,8 @@ async function executeSandboxEgressRequest(input, deps = {}) {
4168
4398
  path: upstreamUrl.pathname,
4169
4399
  status: 403
4170
4400
  }),
4171
- ...sandboxEgressRoutingAttributes(request, upstreamUrl)
4401
+ ...sandboxEgressRoutingAttributes(request, upstreamUrl),
4402
+ ...egressDecisionAttributes("denied", "no provider owns forwarded host")
4172
4403
  });
4173
4404
  return jsonError$1("No provider owns forwarded host", 403);
4174
4405
  }
@@ -4183,7 +4414,8 @@ async function executeSandboxEgressRequest(input, deps = {}) {
4183
4414
  provider,
4184
4415
  status: 403
4185
4416
  }),
4186
- ...sandboxEgressRoutingAttributes(request, upstreamUrl)
4417
+ ...sandboxEgressRoutingAttributes(request, upstreamUrl),
4418
+ ...egressDecisionAttributes("denied", "credential context is not authorized")
4187
4419
  });
4188
4420
  return jsonError$1("Sandbox egress credential context is not authorized", 403);
4189
4421
  }
@@ -7674,9 +7906,6 @@ async function updateTimerIndex(state, operation) {
7674
7906
  // src/chat/credentials/subject.ts
7675
7907
  const CREDENTIAL_SUBJECT_HMAC_CONTEXT = "junior.credential_subject.v1";
7676
7908
  const CREDENTIAL_SUBJECT_SIGNATURE_VERSION = "v1";
7677
- function getCredentialSubjectSecret() {
7678
- return process.env.JUNIOR_SECRET?.trim() || void 0;
7679
- }
7680
7909
  /** Encode ordered signing fields without allowing delimiter ambiguity. */
7681
7910
  function buildPayload(parts) {
7682
7911
  return [CREDENTIAL_SUBJECT_HMAC_CONTEXT, ...parts].join("\0");
@@ -7707,7 +7936,7 @@ function createSlackDirectCredentialSubject(input) {
7707
7936
  function bindSlackDirectCredentialSubject(input) {
7708
7937
  const channelId = normalizeSlackConversationId(input.channelId);
7709
7938
  const teamId = input.teamId.trim();
7710
- const secret = getCredentialSubjectSecret();
7939
+ const secret = readJuniorSecret();
7711
7940
  const { subject } = input;
7712
7941
  const userId = parseActorUserId(subject.userId);
7713
7942
  if (!channelId || !teamId || !secret || !isDmChannel(channelId) || subject.type !== "user" || !userId || subject.allowedWhen !== "private-direct-conversation") return;
@@ -7731,7 +7960,7 @@ function bindSlackDirectCredentialSubject(input) {
7731
7960
  /** Verify that a delegated subject was signed for the dispatch destination. */
7732
7961
  function verifySlackDirectCredentialSubject(input) {
7733
7962
  const channelId = normalizeSlackConversationId(input.channelId);
7734
- const secret = getCredentialSubjectSecret();
7963
+ const secret = readJuniorSecret();
7735
7964
  if (!channelId || !secret) return false;
7736
7965
  const { subject } = input;
7737
7966
  const binding = subject.binding;
@@ -7745,7 +7974,7 @@ function verifySlackDirectCredentialSubject(input) {
7745
7974
  }
7746
7975
  /** Bind a delegated user subject to one scheduler task dispatch. */
7747
7976
  function bindScheduledAutomationCredentialSubject(input) {
7748
- const secret = getCredentialSubjectSecret();
7977
+ const secret = readJuniorSecret();
7749
7978
  const plugin = input.plugin.trim();
7750
7979
  const userId = parseActorUserId(input.subject.userId);
7751
7980
  if (!secret || plugin !== "scheduler" || !userId || input.subject.allowedWhen !== "scheduled-automation") return;
@@ -7771,7 +8000,7 @@ function bindScheduledAutomationCredentialSubject(input) {
7771
8000
  }
7772
8001
  /** Verify that a delegated subject was signed for one scheduler task. */
7773
8002
  function verifyScheduledAutomationCredentialSubject(input) {
7774
- const secret = getCredentialSubjectSecret();
8003
+ const secret = readJuniorSecret();
7775
8004
  const { subject } = input;
7776
8005
  const binding = subject.binding;
7777
8006
  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 +8013,7 @@ function verifyScheduledAutomationCredentialSubject(input) {
7784
8013
  }
7785
8014
  /** Bind a delegated user subject to one event automation dispatch. */
7786
8015
  function bindEventAutomationCredentialSubject(input) {
7787
- const secret = getCredentialSubjectSecret();
8016
+ const secret = readJuniorSecret();
7788
8017
  const plugin = input.plugin.trim();
7789
8018
  const userId = parseActorUserId(input.subject.userId);
7790
8019
  if (!secret || plugin !== "junior" || !userId || input.subject.allowedWhen !== "event-automation") return;
@@ -7810,7 +8039,7 @@ function bindEventAutomationCredentialSubject(input) {
7810
8039
  }
7811
8040
  /** Verify that a delegated subject was signed for one event automation. */
7812
8041
  function verifyEventAutomationCredentialSubject(input) {
7813
- const secret = getCredentialSubjectSecret();
8042
+ const secret = readJuniorSecret();
7814
8043
  const { subject } = input;
7815
8044
  const binding = subject.binding;
7816
8045
  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 +8052,7 @@ function verifyEventAutomationCredentialSubject(input) {
7823
8052
  }
7824
8053
  /** Bind the user who set a timer Watch to that one Watch. */
7825
8054
  function bindTimerWatchCredentialSubject(input) {
7826
- const secret = getCredentialSubjectSecret();
8055
+ const secret = readJuniorSecret();
7827
8056
  const userId = parseActorUserId(input.userId);
7828
8057
  const { conversationId, watchId } = input;
7829
8058
  if (!secret || !userId || !conversationId || conversationId !== conversationId.trim() || !watchId || watchId !== watchId.trim()) return;
@@ -7846,7 +8075,7 @@ function bindTimerWatchCredentialSubject(input) {
7846
8075
  }
7847
8076
  /** Verify that a delegated subject was signed for one timer Watch. */
7848
8077
  function verifyTimerWatchCredentialSubject(input) {
7849
- const secret = getCredentialSubjectSecret();
8078
+ const secret = readJuniorSecret();
7850
8079
  const { subject } = input;
7851
8080
  const binding = subject.binding;
7852
8081
  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 +8763,11 @@ async function readReviewItemAgentScope(context) {
8534
8763
  * the item, or a person, can change it. An agent cannot use the prefix.
8535
8764
  */
8536
8765
  const PLUGIN_REVIEW_ITEM_KEY_PREFIX = "plugin:";
8766
+ /** Return the plugin that owns a dedupe key, or undefined for an agent's key. */
8767
+ function reviewItemPlugin(dedupeKey) {
8768
+ if (!dedupeKey.startsWith("plugin:")) return void 0;
8769
+ return dedupeKey.slice(7).split(":", 1)[0] || void 0;
8770
+ }
8537
8771
  /**
8538
8772
  * Whether an agent can change an item. Only an agent in the tenant of the
8539
8773
  * item can change it. A public item changes only from a public
@@ -8688,10 +8922,12 @@ async function getReviewItem(db, id) {
8688
8922
  }
8689
8923
  /**
8690
8924
  * 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.
8925
+ * reply can answer: the open items, and the items that a reply closed. A
8926
+ * plugin's items are left out: the plugin closes them when its provider
8927
+ * state changes, such as when a pull request merges.
8692
8928
  */
8693
8929
  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)))));
8930
+ 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
8931
  }
8696
8932
  /**
8697
8933
  * Read the open Review item with one dedupe key in one provider tenant, if
@@ -8842,17 +9078,25 @@ async function listWaitingConversations(db, userId) {
8842
9078
  const rows = await db.selectDistinct({
8843
9079
  conversationId: sql`coalesce(${juniorConversations.rootConversationId}, ${juniorReviewItemConversations.conversationId})`,
8844
9080
  itemId: juniorReviewItems.id,
9081
+ dedupeKey: juniorReviewItems.dedupeKey,
8845
9082
  title: juniorReviewItems.title,
8846
9083
  createdAt: juniorReviewItems.createdAt
8847
9084
  }).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
9085
  const waiting = /* @__PURE__ */ new Map();
8849
9086
  for (const row of rows) {
9087
+ const plugin = reviewItemPlugin(row.dedupeKey);
9088
+ const item = {
9089
+ title: row.title,
9090
+ ...plugin ? { plugin } : void 0
9091
+ };
8850
9092
  const current = waiting.get(row.conversationId);
8851
- if (current) current.count += 1;
8852
- else waiting.set(row.conversationId, {
9093
+ if (current) {
9094
+ current.items.push(item);
9095
+ current.waitingSince = row.createdAt.toISOString();
9096
+ } else waiting.set(row.conversationId, {
8853
9097
  conversationId: row.conversationId,
8854
- title: row.title,
8855
- count: 1
9098
+ items: [item],
9099
+ waitingSince: row.createdAt.toISOString()
8856
9100
  });
8857
9101
  }
8858
9102
  return [...waiting.values()].sort((left, right) => left.conversationId.localeCompare(right.conversationId));
@@ -8899,7 +9143,7 @@ function createPluginReviewItems(args) {
8899
9143
  assigneeUserIds: await assigneeUserIds(db, notice.assigneeIdentityIds, conversationId),
8900
9144
  body: notice.body,
8901
9145
  conversationIds: [.../* @__PURE__ */ new Set([conversationId, ...existing?.conversationIds ?? []])],
8902
- kind: "notice",
9146
+ kind: notice.waitsOnAssignees ? "action" : "notice",
8903
9147
  title: notice.title,
8904
9148
  visibility: isPrivate ? "private" : "public",
8905
9149
  ...notice.subject ? { subject: notice.subject } : void 0
@@ -9161,7 +9405,7 @@ function isVapidSubject(subject) {
9161
9405
  */
9162
9406
  function readWebPushConfig() {
9163
9407
  const publicKey = process.env.JUNIOR_WEB_PUSH_PUBLIC_KEY?.trim();
9164
- const privateKey = process.env.JUNIOR_WEB_PUSH_PRIVATE_KEY?.trim();
9408
+ const privateKey = readWebPushPrivateKey();
9165
9409
  if (!publicKey || !privateKey) return void 0;
9166
9410
  const subject = process.env.JUNIOR_WEB_PUSH_SUBJECT?.trim() || subjectFromBaseUrl();
9167
9411
  if (!subject || !isVapidSubject(subject)) return void 0;
@@ -10411,6 +10655,8 @@ async function selectPluginGrant(input) {
10411
10655
  ...basePluginContext(plugin),
10412
10656
  request: {
10413
10657
  ...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
10658
+ ...input.gitPush ? { gitPush: input.gitPush } : void 0,
10659
+ ...input.graphql ? { graphql: input.graphql } : void 0,
10414
10660
  method: input.method,
10415
10661
  ...input.operation ? { operation: input.operation } : void 0,
10416
10662
  url: input.upstreamUrl.toString()
@@ -10585,18 +10831,36 @@ function refreshLockKey(userId, provider) {
10585
10831
  }
10586
10832
  var StateAdapterTokenStore = class {
10587
10833
  state;
10834
+ secrets;
10588
10835
  constructor(stateAdapter) {
10589
10836
  this.state = stateAdapter;
10837
+ this.secrets = createEncryptedState(stateAdapter);
10590
10838
  }
10591
10839
  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);
10840
+ const stored = await readEncryptedState(this.state, tokenKey(userId, provider));
10841
+ if (!stored) return void 0;
10842
+ const tokens = storedTokensSchema.parse(stored.value);
10843
+ if (stored.stale) await this.saveStale(userId, provider);
10844
+ return tokens;
10845
+ }
10846
+ /**
10847
+ * Save stale tokens again with the active key. It runs only when the
10848
+ * refresh gate is free, so it cannot write back a refresh token that a
10849
+ * refresh replaced.
10850
+ */
10851
+ async saveStale(userId, provider) {
10852
+ await withLock(this.state, refreshLockKey(userId, provider), async () => {
10853
+ const key = tokenKey(userId, provider);
10854
+ const current = await readEncryptedState(this.state, key);
10855
+ if (!current?.stale) return;
10856
+ await this.set(userId, provider, storedTokensSchema.parse(current.value));
10857
+ }, { ttlMs: MUTATION_LOCK_TTL_MS });
10594
10858
  }
10595
10859
  async set(userId, provider, tokens) {
10596
10860
  const parsed = storedTokensSchema.parse(tokens);
10597
10861
  const expiresAt = parsed.refreshTokenExpiresAt ?? parsed.expiresAt;
10598
10862
  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);
10863
+ await this.secrets.set(tokenKey(userId, provider), parsed, ttlMs);
10600
10864
  }
10601
10865
  async delete(userId, provider) {
10602
10866
  await this.state.delete(tokenKey(userId, provider));
@@ -10715,6 +10979,8 @@ async function selectSandboxEgressGrant(input) {
10715
10979
  if (!hasEgressCredentialHooks(input.provider)) return defaultGrantForProvider(input);
10716
10980
  const pluginGrant = await selectPluginGrant({
10717
10981
  ...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
10982
+ ...input.gitPush ? { gitPush: input.gitPush } : void 0,
10983
+ ...input.graphql ? { graphql: input.graphql } : void 0,
10718
10984
  ...input.operation ? { operation: input.operation } : void 0,
10719
10985
  provider: input.provider,
10720
10986
  method: input.method,
@@ -10864,8 +11130,15 @@ function policyDeniedResponse(error) {
10864
11130
  headers: { "cache-control": "no-store" }
10865
11131
  });
10866
11132
  }
10867
- function shouldLogSandboxEgressInfo() {
10868
- return (process.env.SENTRY_ENVIRONMENT ?? process.env.VERCEL_ENV ?? process.env.NODE_ENV ?? "").trim().toLowerCase() !== "production";
11133
+ /**
11134
+ * Name the egress decision on every outcome event, so one query over
11135
+ * `app.egress.policy.decision` gives the full trail for a request.
11136
+ */
11137
+ function egressDecisionAttributes(decision, reason) {
11138
+ return reason ? {
11139
+ "app.egress.policy.decision": decision,
11140
+ "app.sandbox.egress.policy.reason": reason
11141
+ } : { "app.egress.policy.decision": decision };
10869
11142
  }
10870
11143
  function egressAttributes(input) {
10871
11144
  return {
@@ -10905,19 +11178,17 @@ function isEgressPolicyDenied(error) {
10905
11178
  return error instanceof EgressPolicyDenied || error instanceof Error && error.name === "EgressPolicyDenied";
10906
11179
  }
10907
11180
  /**
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.
11181
+ * Record one forwarded provider request as an audit event, so Sentry keeps
11182
+ * reads and writes in production.
10911
11183
  */
10912
11184
  function logSandboxEgressUpstreamRequest(input) {
10913
- const isWrite = input.grantAccess === "write";
10914
- if (!isWrite && !shouldLogSandboxEgressInfo()) return;
10915
- (isWrite ? logAudit : logInfo)("sandbox.egress.upstream.requested", {
11185
+ const { grant } = input.lease;
11186
+ logAudit("sandbox.egress.upstream.requested", {
10916
11187
  ...egressAttributes({
10917
11188
  egressId: input.egressId,
10918
- grantAccess: input.grantAccess,
10919
- grantName: input.grantName,
10920
- grantReason: input.grantReason,
11189
+ grantAccess: grant.access,
11190
+ grantName: grant.name,
11191
+ grantReason: grant.reason,
10921
11192
  host: input.upstreamUrl.hostname,
10922
11193
  method: input.request.method,
10923
11194
  path: input.upstreamUrl.pathname,
@@ -10925,6 +11196,10 @@ function logSandboxEgressUpstreamRequest(input) {
10925
11196
  status: input.upstream.status
10926
11197
  }),
10927
11198
  ...routingAttributes(input.request, input.upstreamUrl),
11199
+ ...credentialAuditAttributes(input.credentialContext.source),
11200
+ ...grant.auditAttributes,
11201
+ "app.credential.account": credentialAccount(input.lease, input.credentialContext.credentials),
11202
+ ...egressDecisionAttributes("allowed"),
10928
11203
  "app.sandbox.egress.upstream_ok": input.upstream.ok
10929
11204
  });
10930
11205
  }
@@ -10948,28 +11223,14 @@ function unreadableBodyResponse(eventId) {
10948
11223
  headers: { "cache-control": "no-store" }
10949
11224
  });
10950
11225
  }
10951
- /** Identify GitHub writes whose body determines whether a grant is safe. */
10952
- function githubBodyInspection(input) {
10953
- if (input.provider !== "github" || input.requestMethod.toUpperCase() !== "POST" || input.upstreamUrl.hostname.toLowerCase() !== "api.github.com") return;
10954
- const pathname = input.upstreamUrl.pathname.toLowerCase();
10955
- if (pathname.endsWith("/graphql")) return "graphql";
10956
- return /^\/repos\/[^/]+\/[^/]+\/pulls\/[^/]+\/reviews(?:\/[^/]+\/events)?$/.test(pathname) ? "pull-request-review" : void 0;
11226
+ /** Identify GitHub review writes whose body decides whether a grant is safe. */
11227
+ function isGitHubPullRequestReviewPost(input) {
11228
+ return input.provider === "github" && input.requestMethod.toUpperCase() === "POST" && input.upstreamUrl.hostname.toLowerCase() === "api.github.com" && /^\/repos\/[^/]+\/[^/]+\/pulls\/[^/]+\/reviews(?:\/[^/]+\/events)?$/.test(input.upstreamUrl.pathname.toLowerCase());
10957
11229
  }
10958
- function grantSelectionBodyTooLargeMessage(inspection) {
10959
- return inspection === "graphql" ? "GitHub GraphQL request body is too large to inspect before issuing credentials." : "GitHub pull request review request body is too large to inspect before issuing credentials.";
10960
- }
10961
- function grantSelectionBodyText(input) {
10962
- if (input.body === void 0) return;
10963
- if (input.body.byteLength > GRANT_SELECTION_BODY_TEXT_LIMIT_BYTES) {
10964
- const inspection = githubBodyInspection({
10965
- provider: input.provider,
10966
- requestMethod: input.request.method,
10967
- upstreamUrl: input.upstreamUrl
10968
- });
10969
- if (inspection) throw new EgressPolicyDenied(grantSelectionBodyTooLargeMessage(inspection));
10970
- return;
10971
- }
10972
- return new TextDecoder().decode(input.body);
11230
+ function grantSelectionBodyText(body) {
11231
+ if (body === void 0) return;
11232
+ if (body.byteLength > GRANT_SELECTION_BODY_TEXT_LIMIT_BYTES) throw new EgressPolicyDenied("GitHub pull request review request body is too large to inspect before issuing credentials.");
11233
+ return new TextDecoder().decode(body);
10973
11234
  }
10974
11235
  function responseContentLength(upstream) {
10975
11236
  const raw = upstream.headers.get("content-length");
@@ -11090,6 +11351,16 @@ async function recordSandboxPermissionDenied(input) {
11090
11351
  upstreamPath: displayedUpstreamPath(input.upstreamUrl)
11091
11352
  });
11092
11353
  }
11354
+ async function recordSandboxPolicyDenied(input) {
11355
+ await setSandboxEgressPermissionDeniedSignal(input.credentialContext, {
11356
+ message: input.message,
11357
+ method: input.request.method.toUpperCase(),
11358
+ provider: input.provider,
11359
+ source: "policy",
11360
+ upstreamHost: input.upstreamUrl.hostname,
11361
+ upstreamPath: displayedUpstreamPath(input.upstreamUrl)
11362
+ });
11363
+ }
11093
11364
  /**
11094
11365
  * Forward one verified sandbox egress request with host-managed credentials.
11095
11366
  *
@@ -11115,23 +11386,21 @@ async function executeCredentialedEgressRequest(input) {
11115
11386
  provider,
11116
11387
  status: 500
11117
11388
  }),
11118
- ...routingAttributes(request, upstreamUrl)
11389
+ ...routingAttributes(request, upstreamUrl),
11390
+ ...credentialAuditAttributes(credentialContext.source),
11391
+ ...egressDecisionAttributes("denied", "request body is unreadable")
11119
11392
  }));
11120
11393
  }
11121
- const bodyForGrantSelection = githubBodyInspection({
11122
- provider,
11123
- requestMethod: request.method,
11124
- upstreamUrl
11125
- }) ? body : void 0;
11126
11394
  let grantSelection;
11127
11395
  try {
11128
11396
  grantSelection = await selectSandboxEgressGrant({
11129
- bodyText: grantSelectionBodyText({
11130
- body: bodyForGrantSelection,
11397
+ ...isGitHubPullRequestReviewPost({
11131
11398
  provider,
11132
- request,
11399
+ requestMethod: request.method,
11133
11400
  upstreamUrl
11134
- }),
11401
+ }) ? { bodyText: grantSelectionBodyText(body) } : void 0,
11402
+ ...isGitReceivePack(request.method, upstreamUrl) ? { gitPush: readGitPush(body) } : void 0,
11403
+ ...isGraphqlPost(request.method, upstreamUrl) ? { graphql: await readGraphqlRequest(body) } : void 0,
11135
11404
  ...operation ? { operation } : void 0,
11136
11405
  provider,
11137
11406
  method: request.method,
@@ -11149,19 +11418,25 @@ async function executeCredentialedEgressRequest(input) {
11149
11418
  status: 403
11150
11419
  }),
11151
11420
  ...routingAttributes(request, upstreamUrl),
11152
- "app.sandbox.egress.policy.reason": error.message
11421
+ ...credentialAuditAttributes(credentialContext.source),
11422
+ ...pluginAuditAttributesSchema.safeParse(error.auditAttributes).data,
11423
+ ...egressDecisionAttributes("denied", error.message)
11424
+ });
11425
+ await recordSandboxPolicyDenied({
11426
+ credentialContext,
11427
+ message: error.message,
11428
+ provider,
11429
+ request,
11430
+ upstreamUrl
11153
11431
  });
11154
11432
  return policyDeniedResponse(error);
11155
11433
  }
11156
11434
  throw error;
11157
11435
  }
11158
- const issueCredentialLease = deps.issueCredentialLease ?? sandboxEgressCredentialLease;
11159
- const clearCredentialLease = deps.clearCredentialLease ?? clearSandboxEgressCredentialLease;
11160
11436
  const recordAuthRequired = deps.recordAuthRequired ?? recordSandboxAuthRequired;
11161
- const recordPermissionDenied = deps.recordPermissionDenied ?? recordSandboxPermissionDenied;
11162
11437
  async function resolveLease() {
11163
11438
  try {
11164
- return await issueCredentialLease(provider, grantSelection, credentialContext);
11439
+ return await sandboxEgressCredentialLease(provider, grantSelection, credentialContext);
11165
11440
  } catch (error) {
11166
11441
  if (!(error instanceof SandboxEgressCredentialError)) throw error;
11167
11442
  await recordAuthRequired({
@@ -11185,7 +11460,9 @@ async function executeCredentialedEgressRequest(input) {
11185
11460
  provider: error.provider,
11186
11461
  status: 401
11187
11462
  }),
11188
- ...routingAttributes(request, upstreamUrl)
11463
+ ...routingAttributes(request, upstreamUrl),
11464
+ ...credentialAuditAttributes(credentialContext.source),
11465
+ ...egressDecisionAttributes("denied", error.message)
11189
11466
  });
11190
11467
  return authRequiredResponse({
11191
11468
  provider: error.provider,
@@ -11208,6 +11485,8 @@ async function executeCredentialedEgressRequest(input) {
11208
11485
  if (!hasSandboxEgressLeaseTransformForHost(lease, upstreamUrl.hostname)) {
11209
11486
  logWarn("sandbox.egress.transform.missing", {
11210
11487
  ...attributes(lease, 403),
11488
+ ...credentialAuditAttributes(credentialContext.source),
11489
+ ...egressDecisionAttributes("denied", "credential lease does not cover forwarded host"),
11211
11490
  "app.sandbox.egress.transform_domains": lease.headerTransforms.map((transform) => transform.domain)
11212
11491
  });
11213
11492
  return Response.json({ error: "Credential lease does not cover forwarded host" }, { status: 403 });
@@ -11249,7 +11528,7 @@ async function executeCredentialedEgressRequest(input) {
11249
11528
  })).permissionDenied;
11250
11529
  } catch (error) {
11251
11530
  if (!isEgressAuthRequired(error)) throw error;
11252
- await clearCredentialLease(provider, lease.grant, credentialContext);
11531
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11253
11532
  await recordAuthRequired({
11254
11533
  credentialContext,
11255
11534
  provider,
@@ -11266,10 +11545,9 @@ async function executeCredentialedEgressRequest(input) {
11266
11545
  });
11267
11546
  }
11268
11547
  logSandboxEgressUpstreamRequest({
11548
+ credentialContext,
11269
11549
  egressId: activeEgressId,
11270
- grantAccess: lease.grant.access,
11271
- grantName: lease.grant.name,
11272
- grantReason: lease.grant.reason,
11550
+ lease,
11273
11551
  provider,
11274
11552
  request,
11275
11553
  upstream,
@@ -11284,7 +11562,7 @@ async function executeCredentialedEgressRequest(input) {
11284
11562
  ...attributes(lease, upstream.status),
11285
11563
  "app.sandbox.egress.www_authenticate": upstream.headers.get("www-authenticate") ?? void 0
11286
11564
  });
11287
- await clearCredentialLease(provider, lease.grant, credentialContext);
11565
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11288
11566
  await recordAuthRequired({
11289
11567
  credentialContext,
11290
11568
  provider,
@@ -11301,7 +11579,7 @@ async function executeCredentialedEgressRequest(input) {
11301
11579
  }
11302
11580
  if (upstream.status === UPSTREAM_PERMISSION_REJECTION_STATUS && !retriedAfter403) {
11303
11581
  logWarn("sandbox.egress.upstream_auth.rejected", { ...attributes(lease, upstream.status) });
11304
- await clearCredentialLease(provider, lease.grant, credentialContext);
11582
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11305
11583
  await upstream.body?.cancel().catch(() => void 0);
11306
11584
  logWarn("sandbox.egress.upstream_auth.retrying", { ...attributes(lease, upstream.status) });
11307
11585
  leaseOrResponse = await resolveLease();
@@ -11312,8 +11590,8 @@ async function executeCredentialedEgressRequest(input) {
11312
11590
  }
11313
11591
  if (upstream.status === UPSTREAM_PERMISSION_REJECTION_STATUS) {
11314
11592
  logWarn("sandbox.egress.upstream_auth.rejected", { ...attributes(lease, upstream.status) });
11315
- await clearCredentialLease(provider, lease.grant, credentialContext);
11316
- await recordPermissionDenied({
11593
+ await clearSandboxEgressCredentialLease(provider, lease.grant, credentialContext);
11594
+ await recordSandboxPermissionDenied({
11317
11595
  credentialContext,
11318
11596
  provider,
11319
11597
  lease,
@@ -11329,7 +11607,7 @@ async function executeCredentialedEgressRequest(input) {
11329
11607
  });
11330
11608
  }
11331
11609
  if (pluginPermissionDenied) {
11332
- await recordPermissionDenied({
11610
+ await recordSandboxPermissionDenied({
11333
11611
  credentialContext,
11334
11612
  provider,
11335
11613
  lease,
@@ -13980,17 +14258,18 @@ function createPluginAuthOrchestration(input) {
13980
14258
  };
13981
14259
  }
13982
14260
  // src/chat/egress/plugin.ts
13983
- function credentialContextForPluginEgress(credentialContext) {
14261
+ function credentialContextForPluginEgress(credentialContext, source) {
13984
14262
  return {
13985
14263
  credentials: credentialContext,
13986
14264
  contextId: randomUUID(),
13987
14265
  egressId: `plugin-egress:${randomUUID()}`,
13988
- expiresAtMs: Date.now() + 18e5
14266
+ expiresAtMs: Date.now() + 18e5,
14267
+ source
13989
14268
  };
13990
14269
  }
13991
14270
  /** Create host-owned provider egress for plugin runtime tools. */
13992
14271
  function createPluginEgress(deps) {
13993
- const credentialContext = deps.credentialContext ? credentialContextForPluginEgress(deps.credentialContext) : void 0;
14272
+ const credentialContext = deps.credentialContext ? credentialContextForPluginEgress(deps.credentialContext, deps.credentialAuditSource) : void 0;
13994
14273
  return { async fetch(input) {
13995
14274
  const operation = input.operation.trim();
13996
14275
  if (!operation) throw new Error("Plugin egress operation is required");
@@ -14012,7 +14291,6 @@ function createPluginEgress(deps) {
14012
14291
  provider: signal.provider
14013
14292
  });
14014
14293
  },
14015
- recordPermissionDenied: async () => {},
14016
14294
  tracePropagation: {}
14017
14295
  },
14018
14296
  operation,
@@ -14078,7 +14356,7 @@ async function getPluginConversationTitleContext(args) {
14078
14356
  const COMPACTION_TRIGGER_RATIO = .9;
14079
14357
  const CONTEXT_INPUT_LIMIT_RATIO = .95;
14080
14358
  const COMPACTION_TARGET_RATIO = .8;
14081
- const BACKGROUND_COMPACTION_MARK_RATIO = .7;
14359
+ const BACKGROUND_COMPACTION_MARK_RATIO = .85;
14082
14360
  const FALLBACK_CONTEXT_WINDOW_TOKENS = 4e5;
14083
14361
  function positiveInteger(value, fallback) {
14084
14362
  return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
@@ -15144,4 +15422,4 @@ async function recordGuardianActionReviewed(args) {
15144
15422
  createdAtMs: Date.now()
15145
15423
  }]);
15146
15424
  }
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 };
15425
+ 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 };