@sentry/junior 0.295.0 → 0.297.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 (84) hide show
  1. package/dist/{admin-ifgjyfpF.js → admin-tmGIw4KS.js} +2 -2
  2. package/dist/{agent-runner-DjMTPWEO.js → agent-runner-CneTquAE.js} +468 -1947
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +7 -7
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +306 -569
  7. package/dist/{app-uiTzRbvq.d.ts → app-BJojZ7HL.d.ts} +7 -2
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +64 -44
  10. package/dist/attempt-selection-ClP3MMPr.js +61 -0
  11. package/dist/{automation-yJX3C7i3.js → automation-BrP6ImrC.js} +1 -1
  12. package/dist/{background-compaction-queue-DUkHZjmL.js → background-compaction-queue-CwfJy3Cd.js} +4 -88
  13. package/dist/{briefs-CbNYM-q2.js → briefs-uFTuhMqA.js} +3 -3
  14. package/dist/{catalog-runtime-DgouZKZm.js → catalog-runtime-0kuQqYL4.js} +1 -1
  15. package/dist/cli/chat.js +19 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-DvnTPCfp.js → config-Dj9M_nqB.js} +18 -2
  23. package/dist/{connections-CWaIVl_1.js → connections-B96JUM5o.js} +6 -6
  24. package/dist/{conversation-CMkSmi02.js → conversation-CvcBU1z2.js} +2 -16
  25. package/dist/{conversation-feed-BVAOga0H.js → conversation-feed-BSMlGZnS.js} +1 -1
  26. package/dist/{conversation-privacy-DPjv4SnA.js → conversation-privacy-DI29jbZV.js} +1 -1
  27. package/dist/conversation-turn-CZWBr091.js +805 -0
  28. package/dist/{credential-sync-BhbaZfmO.js → credential-sync-Blhx4_xf.js} +14 -13
  29. package/dist/{db-Dts2XvLu.js → db-Br0tfAo7.js} +54 -32
  30. package/dist/{db-CCUqQe0E.d.ts → db-CrtyFRz7.d.ts} +13 -1
  31. package/dist/{executor-Ck73J0wP.js → executor-BMPipFVA.js} +19 -5
  32. package/dist/instrumentation.js +19 -2
  33. package/dist/{logging-9OAq-fdg.js → logging-CQjlDQYX.js} +1 -1
  34. package/dist/{message-CtaPzC7m.js → message-BOZEIuxy.js} +15 -13
  35. package/dist/nitro.d.ts +1 -1
  36. package/dist/nitro.js +3 -2
  37. package/dist/{session-stop-DkxI5vc3.js → notification-gusCgdQ6.js} +14 -933
  38. package/dist/{oauth-callback-server-C_LXY1d4.js → oauth-callback-server-V_DuMuNX.js} +2 -2
  39. package/dist/{projection-BzJQncZV.js → projection-B08mfi0u.js} +479 -145
  40. package/dist/{prompt-Cbq5b4SO.js → prompt-BlutWLNt.js} +4 -4
  41. package/dist/prompt-input-Dxn8cDC0.js +1424 -0
  42. package/dist/{registry-cbpOxO4M.js → registry-BDWgCJDf.js} +1 -1
  43. package/dist/reporting-window-DopzcOHh.js +137 -0
  44. package/dist/{resolve-t-pmRdwS.js → resolve-2Z_o_SsI.js} +3 -3
  45. package/dist/result-CAujiaci.js +463 -0
  46. package/dist/{runner-CHv9X9TH.js → runner-D2Chc02N.js} +9 -8
  47. package/dist/{sandbox-egress-signals-Yy3fSCbg.js → sandbox-egress-signals-CFoJduFj.js} +1 -1
  48. package/dist/{schema-BhneuGYv.js → schema-Bqa5NbcP.js} +22 -48
  49. package/dist/{schema-TSEisVJR.d.ts → schema-Ce2XCS7O.d.ts} +24 -107
  50. package/dist/{service-account-DjPIwCMj.js → service-account-C9kRQEb_.js} +3 -3
  51. package/dist/{service-account-C4rBP8ne.js → service-account-CERfXEVU.js} +3 -3
  52. package/dist/session-stop-B-I1rAS1.js +181 -0
  53. package/dist/{skills-BZE2DP8I.js → skills-B0m1nZ_j.js} +3 -3
  54. package/dist/{spawn-BvULxIiu.js → spawn-CwMjRRtn.js} +6 -5
  55. package/dist/{state-CO9ETDzk.js → state-DFnmLmfn.js} +2 -2
  56. package/dist/{stop-CL-rdtQb.js → stop-BCH9VNGf.js} +329 -382
  57. package/dist/{store-DgD78_NK.js → store-B59rOYbS.js} +11 -4
  58. package/dist/{task-runner-CKOj6xla.js → store-m5bmdmsP.js} +929 -1559
  59. package/dist/task-queue-N0kuCknH.js +89 -0
  60. package/dist/task-runner-COOwR8qm.js +291 -0
  61. package/dist/thread-context-Cd44z_W5.js +248 -0
  62. package/dist/turn-cancel-DDu8TOwt.js +201 -0
  63. package/dist/turn-session-routing-BlCtVFRN.js +380 -0
  64. package/dist/{turn-failure-response-BTSo6SMJ.js → turn-user-message-ygLG3ylQ.js} +183 -358
  65. package/dist/turn-wake-DmQec4AG.js +161 -0
  66. package/dist/{reporting-window-B3Ze-Qnt.js → user-input-request-CXNIov9n.js} +24 -143
  67. package/dist/{validation-CXeYgBzq.js → validation-Ba2OcUse.js} +1 -1
  68. package/dist/{version-AQa7Fr2H.js → version-KNDzIAh6.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{viewer-Bqkb678l.js → viewer-BPpuN2f9.js} +3 -3
  71. package/dist/warmup-Bskrwmk1.js +2697 -0
  72. package/dist/{worker-Hl7N292I.js → worker-B1skZlit.js} +20 -8
  73. package/migrations/0101_drop_legacy_columns.sql +12 -0
  74. package/migrations/0102_code_change_last_activity.sql +1 -0
  75. package/migrations/0103_agent_invocation_fork.sql +8 -0
  76. package/migrations/meta/0101_snapshot.json +4496 -0
  77. package/migrations/meta/0102_snapshot.json +4502 -0
  78. package/migrations/meta/0103_snapshot.json +4509 -0
  79. package/migrations/meta/_journal.json +21 -0
  80. package/package.json +5 -4
  81. package/dist/result-DhgjR3nQ.js +0 -305
  82. package/dist/result-event-type-DD6BAgT7.js +0 -11
  83. package/dist/warmup-h6u1e9n0.js +0 -1869
  84. package/dist/work-yN_GAuXY.js +0 -768
@@ -1,19 +1,19 @@
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-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";
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-Dj9M_nqB.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-CQjlDQYX.js";
4
+ import { t as canExposeConversationPayload } from "./conversation-privacy-DI29jbZV.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 { 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";
6
+ import { $ as conversationDetailTouch, K as addAgentTurnUsage, P as resolveActorIdentityId, U as claimProviderConversation, V as saveUserTimezone, X as hasAgentTurnUsage, a as getConversationStore, at as sameDestination, d as createSqlConversationEventStore, f as eventFromRow, j as startLocationThread, o as getDb, p as withConversationEventLock, r as getConversationEventStore, rt as parseDestination, s as getSqlExecutor, w as isPersonInput, x as createSqlStore, z as readUserTimezone } from "./db-Br0tfAo7.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-BMPipFVA.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, 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";
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-BDWgCJDf.js";
10
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-0kuQqYL4.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-BlutWLNt.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-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";
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-BPpuN2f9.js";
14
+ import { a as getStateAdapter, i as getDefaultRedisStateAdapterFor, n as readEncryptedState, o as getStateValues, s as setStateValues, t as createEncryptedState } from "./state-DFnmLmfn.js";
15
15
  import { n as isWithinNotificationSchedule, r as notificationScheduleSchema, s as isValidTimeZone, t as DEFAULT_NOTIFICATION_SCHEDULE } from "./schedule-cP0AACm1.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";
16
+ import { H as readMessageAttachments, I as readMessageCardRefs, J as parseBriefInput, K as briefResourceLabel, M as reviewItemChangeRecordSchema, P as messageCardRef, Y as parseStoredBrief, _ as conversationReportMessageEventSchema, g as conversationReportEventSchema, q as conversationBriefSchema } from "./conversation-CvcBU1z2.js";
17
17
  import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
18
18
  import { i as readWebPushPrivateKey, t as readJuniorSecret } from "./secrets-DebYU866.js";
19
19
  import path from "node:path";
@@ -465,7 +465,7 @@ const PKT_LENGTH = /^[0-9a-f]{4}$/i;
465
465
  function isGitReceivePack(method, upstreamUrl) {
466
466
  return method.toUpperCase() === "POST" && upstreamUrl.pathname.toLowerCase().endsWith("/git-receive-pack");
467
467
  }
468
- function unreadable(reason) {
468
+ function unreadable$1(reason) {
469
469
  return {
470
470
  kind: "unreadable",
471
471
  reason
@@ -480,34 +480,158 @@ function unreadable(reason) {
480
480
  */
481
481
  function readGitPush(body) {
482
482
  const bytes = new Uint8Array(body ?? /* @__PURE__ */ new ArrayBuffer(0));
483
- if (bytes[0] === 31 && bytes[1] === 139) return unreadable("gzip");
483
+ if (bytes[0] === 31 && bytes[1] === 139) return unreadable$1("gzip");
484
484
  const decoder = new TextDecoder();
485
485
  const updates = [];
486
486
  let offset = 0;
487
487
  while (true) {
488
- if (offset + 4 > bytes.length) return unreadable("unterminated");
488
+ if (offset + 4 > bytes.length) return unreadable$1("unterminated");
489
489
  const lengthText = String.fromCharCode(...bytes.subarray(offset, offset + 4));
490
- if (!PKT_LENGTH.test(lengthText)) return unreadable("malformed");
490
+ if (!PKT_LENGTH.test(lengthText)) return unreadable$1("malformed");
491
491
  const length = Number.parseInt(lengthText, 16);
492
492
  if (length === 0) return {
493
493
  kind: "commands",
494
494
  updates
495
495
  };
496
- if (length < 4) return unreadable("malformed");
497
- if (offset + length > bytes.length) return unreadable("unterminated");
496
+ if (length < 4) return unreadable$1("malformed");
497
+ if (offset + length > bytes.length) return unreadable$1("unterminated");
498
498
  const line = decoder.decode(bytes.subarray(offset + 4, offset + length)).replace(/\n$/, "");
499
499
  offset += length;
500
500
  if (line.startsWith("shallow ")) continue;
501
501
  const command = line.split("\0", 1)[0];
502
- if (command === "push-cert") return unreadable("signed");
502
+ if (command === "push-cert") return unreadable$1("signed");
503
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");
504
+ if (!oldId || !newId || !ref || rest.length > 0 || !OBJECT_ID.test(oldId) || !OBJECT_ID.test(newId)) return unreadable$1("malformed");
505
505
  updates.push({
506
506
  deletes: ZERO_OBJECT_ID.test(newId),
507
507
  ref
508
508
  });
509
509
  }
510
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
+ }
511
635
  // src/chat/slack/user.ts
512
636
  const slackUserInfoSchema = z.object({
513
637
  ok: z.literal(true),
@@ -938,6 +1062,8 @@ function slackFileIds(meta) {
938
1062
  return Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [];
939
1063
  }
940
1064
  // src/chat/agent-invocations/fork-history.ts
1065
+ /** Instructions that a fork child reads with its first task. */
1066
+ const FORK_INSTRUCTIONS = "You are a fork of your parent agent. The messages before your first parent task are copied from the parent's conversation so you have its context. They are not your job: your job is the parent task below. Sandbox files, approvals, and credentials of the parent were not copied, and your sandbox is separate. Verify files in your own sandbox before you use them.";
941
1067
  /**
942
1068
  * Cut parent history for a fork: everything before the parent's message that
943
1069
  * started the fork, through the last point where every tool call has its
@@ -1796,7 +1922,7 @@ const WINDOWS = [
1796
1922
  30,
1797
1923
  90
1798
1924
  ];
1799
- function startOfUtcDay$1(value) {
1925
+ function startOfUtcDay(value) {
1800
1926
  const date = new Date(value);
1801
1927
  date.setUTCHours(0, 0, 0, 0);
1802
1928
  return date;
@@ -1819,7 +1945,7 @@ function formatUsd(value) {
1819
1945
  * Conversations leaves the report with them; the labels say so.
1820
1946
  */
1821
1947
  async function buildBriefsOperationalReport(args) {
1822
- const newestDay = startOfUtcDay$1(args.nowMs);
1948
+ const newestDay = startOfUtcDay(args.nowMs);
1823
1949
  const windowStart = /* @__PURE__ */ new Date(newestDay.getTime() - 29 * DAY_MS$2);
1824
1950
  const windowEnd = new Date(newestDay.getTime() + DAY_MS$2);
1825
1951
  const [[counts], recentCounts] = await Promise.all([args.db.select({
@@ -2175,6 +2301,7 @@ async function readConversationAccessFromSql(db, conversationIds, viewer) {
2175
2301
  rootConversationId: rootConversation.conversationId,
2176
2302
  rootParentConversationId: rootConversation.parentConversationId,
2177
2303
  rootRootConversationId: rootConversation.rootConversationId,
2304
+ destinationId: rootDestination.id,
2178
2305
  visibility: rootDestination.visibility,
2179
2306
  provider: rootDestination.provider,
2180
2307
  providerTenantId: rootDestination.providerTenantId
@@ -2192,6 +2319,7 @@ async function readConversationAccessFromSql(db, conversationIds, viewer) {
2192
2319
  const canViewPrivateContent = isParticipant || validRootConversationId !== void 0 && canExposeConversationPayload({ visibility: visibility ?? void 0 });
2193
2320
  return [row.conversationId, {
2194
2321
  canViewPrivateContent,
2322
+ ...validRootConversationId !== void 0 && row.destinationId ? { destinationId: row.destinationId } : void 0,
2195
2323
  isParticipant,
2196
2324
  ...validRootConversationId !== void 0 ? { rootConversationId: validRootConversationId } : void 0,
2197
2325
  visibility,
@@ -2232,11 +2360,13 @@ function createConversationAccessReader(db, viewer) {
2232
2360
  * Conversation may read or find the data of the `target` Conversation. The
2233
2361
  * person of the Turn does not change the result. A public Conversation is
2234
2362
  * reachable from any Conversation, on any surface and in any provider tenant.
2235
- * A private Conversation is reachable only from its own tree.
2363
+ * A private Conversation is reachable only from its own tree and from
2364
+ * Conversations at the same Destination, which have the same audience.
2236
2365
  */
2237
2366
  function canAccessConversation(args) {
2238
2367
  const { requester, target } = args;
2239
2368
  if (requester.rootConversationId !== void 0 && requester.rootConversationId === target.rootConversationId) return true;
2369
+ if (requester.destinationId !== void 0 && requester.destinationId === target.destinationId) return true;
2240
2370
  return target.visibility === "public";
2241
2371
  }
2242
2372
  // src/chat/plugins/conversation-event-reader.ts
@@ -2266,16 +2396,75 @@ function createPluginConversationEventReader(plugin) {
2266
2396
  } };
2267
2397
  }
2268
2398
  // src/chat/plugins/conversation-event-stats.ts
2269
- const DAY_MS$1 = 864e5;
2399
+ const HOUR_MS = 36e5;
2400
+ const DAY_MS$1 = 24 * HOUR_MS;
2270
2401
  const costRowSchema = z.object({
2271
2402
  costUsd: z.number().finite().nonnegative(),
2272
2403
  date: z.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),
2273
2404
  events: z.number().int().nonnegative()
2274
2405
  }).strict();
2275
- function startOfUtcDay(value) {
2276
- const date = new Date(value);
2277
- date.setUTCHours(0, 0, 0, 0);
2278
- return date;
2406
+ const cachedBucketSchema = costRowSchema.omit({ date: true });
2407
+ const DAY = {
2408
+ ms: DAY_MS$1,
2409
+ sqlFormat: "YYYY-MM-DD",
2410
+ keyLength: 10
2411
+ };
2412
+ const HOUR = {
2413
+ ms: HOUR_MS,
2414
+ sqlFormat: "YYYY-MM-DD\"T\"HH24",
2415
+ keyLength: 13
2416
+ };
2417
+ const BUCKET_SETTLE_MS = 3e5;
2418
+ const BUCKET_CACHE_TTL_MS = 91 * DAY_MS$1;
2419
+ function bucketCacheKey(namespace, eventName, bucket) {
2420
+ return `plugin-event-costs:v1:${namespace}:${eventName}:${bucket}`;
2421
+ }
2422
+ async function queryCostBuckets(args) {
2423
+ const date = sql`TO_CHAR(
2424
+ ${juniorConversationEvents.createdAt} AT TIME ZONE 'UTC',
2425
+ ${sql.raw(`'${args.unit.sqlFormat}'`)}
2426
+ )`;
2427
+ const cost = sql`CASE
2428
+ WHEN jsonb_typeof(${juniorConversationEvents.payload}->'content'->'costUsd') = 'number'
2429
+ THEN (${juniorConversationEvents.payload}->'content'->>'costUsd')::double precision
2430
+ ELSE 0
2431
+ END`;
2432
+ const rows = await getDb().select({
2433
+ costUsd: sql`SUM(${cost})::double precision`.mapWith(Number),
2434
+ date,
2435
+ events: sql`COUNT(*)::integer`.mapWith(Number)
2436
+ }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.type, "structured_event"), sql`${juniorConversationEvents.payload}->>'namespace' = ${args.namespace}`, sql`${juniorConversationEvents.payload}->>'name' = ${args.eventName}`, gte(juniorConversationEvents.createdAt, args.start), lt(juniorConversationEvents.createdAt, args.end))).groupBy(date);
2437
+ return new Map(z.array(costRowSchema).parse(rows).map((row) => [row.date, row]));
2438
+ }
2439
+ async function readCostBuckets(args) {
2440
+ const { count, eventName, namespace, unit } = args;
2441
+ const startMs = args.start.getTime();
2442
+ const buckets = Array.from({ length: count }, (_, index) => new Date(startMs + index * unit.ms).toISOString().slice(0, unit.keyLength));
2443
+ const settledCount = Math.min(count, Math.max(0, Math.floor((args.nowMs - BUCKET_SETTLE_MS - startMs) / unit.ms)));
2444
+ const state = getStateAdapter();
2445
+ const cached = (await getStateValues(state, buckets.slice(0, settledCount).map((bucket) => bucketCacheKey(namespace, eventName, bucket)))).map((value) => cachedBucketSchema.safeParse(value).data);
2446
+ const firstMissing = cached.findIndex((value) => value === void 0);
2447
+ const queryFrom = firstMissing === -1 ? settledCount : firstMissing;
2448
+ const queried = queryFrom < count ? await queryCostBuckets({
2449
+ end: new Date(startMs + count * unit.ms),
2450
+ eventName,
2451
+ namespace,
2452
+ start: new Date(startMs + queryFrom * unit.ms),
2453
+ unit
2454
+ }) : /* @__PURE__ */ new Map();
2455
+ const result = buckets.map((date, index) => {
2456
+ const value = index < queryFrom ? cached[index] : queried.get(date);
2457
+ return {
2458
+ costUsd: value?.costUsd ?? 0,
2459
+ date,
2460
+ events: value?.events ?? 0
2461
+ };
2462
+ });
2463
+ await setStateValues(state, result.slice(queryFrom, settledCount).map(({ date, ...value }) => ({
2464
+ key: bucketCacheKey(namespace, eventName, date),
2465
+ value
2466
+ })), BUCKET_CACHE_TTL_MS);
2467
+ return result;
2279
2468
  }
2280
2469
  function registeredEventName(plugin, eventName) {
2281
2470
  if (!isPluginModelCostEventName(eventName) && !plugin.conversationEvents?.some((definition) => definition.eventName === eventName)) throw new TypeError(`Plugin "${plugin.manifest.name}" did not register event "${eventName}"`);
@@ -2285,63 +2474,30 @@ function registeredEventName(plugin, eventName) {
2285
2474
  function createPluginConversationEventStats(plugin, now = Date.now) {
2286
2475
  return {
2287
2476
  async costsByHour(input) {
2288
- const eventName = registeredEventName(plugin, input.eventName);
2289
- const hourCount = input.hours ?? 24;
2290
- const end = new Date(now());
2477
+ const nowMs = now();
2478
+ const count = input.hours ?? 24;
2479
+ const end = new Date(nowMs);
2291
2480
  end.setUTCMinutes(0, 0, 0);
2292
- const start = /* @__PURE__ */ new Date(end.getTime() - (hourCount - 1) * 60 * 60 * 1e3);
2293
- const endExclusive = new Date(end.getTime() + 36e5);
2294
- const date = sql`TO_CHAR(
2295
- ${juniorConversationEvents.createdAt} AT TIME ZONE 'UTC',
2296
- 'YYYY-MM-DD"T"HH24'
2297
- )`;
2298
- const cost = sql`CASE
2299
- WHEN jsonb_typeof(${juniorConversationEvents.payload}->'content'->'costUsd') = 'number'
2300
- THEN (${juniorConversationEvents.payload}->'content'->>'costUsd')::double precision
2301
- ELSE 0
2302
- END`;
2303
- const rows = await getDb().select({
2304
- costUsd: sql`SUM(${cost})::double precision`.mapWith(Number),
2305
- date,
2306
- events: sql`COUNT(*)::integer`.mapWith(Number)
2307
- }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.type, "structured_event"), sql`${juniorConversationEvents.payload}->>'namespace' = ${plugin.manifest.name}`, sql`${juniorConversationEvents.payload}->>'name' = ${eventName}`, gte(juniorConversationEvents.createdAt, start), lt(juniorConversationEvents.createdAt, endExclusive))).groupBy(date);
2308
- const byHour = new Map(z.array(costRowSchema).parse(rows).map((row) => [row.date, row]));
2309
- return Array.from({ length: hourCount }, (_, index) => {
2310
- const key = new Date(start.getTime() + index * 60 * 60 * 1e3).toISOString().slice(0, 13);
2311
- return byHour.get(key) ?? {
2312
- costUsd: 0,
2313
- date: key,
2314
- events: 0
2315
- };
2481
+ return await readCostBuckets({
2482
+ count,
2483
+ eventName: registeredEventName(plugin, input.eventName),
2484
+ namespace: plugin.manifest.name,
2485
+ nowMs,
2486
+ start: /* @__PURE__ */ new Date(end.getTime() - (count - 1) * HOUR_MS),
2487
+ unit: HOUR
2316
2488
  });
2317
2489
  },
2318
2490
  async costsByDay(input) {
2319
- const eventName = registeredEventName(plugin, input.eventName);
2320
- const end = startOfUtcDay(now());
2321
- const start = /* @__PURE__ */ new Date(end.getTime() - (input.days - 1) * DAY_MS$1);
2322
- const endExclusive = new Date(end.getTime() + DAY_MS$1);
2323
- const date = sql`TO_CHAR(
2324
- ${juniorConversationEvents.createdAt} AT TIME ZONE 'UTC',
2325
- 'YYYY-MM-DD'
2326
- )`;
2327
- const cost = sql`CASE
2328
- WHEN jsonb_typeof(${juniorConversationEvents.payload}->'content'->'costUsd') = 'number'
2329
- THEN (${juniorConversationEvents.payload}->'content'->>'costUsd')::double precision
2330
- ELSE 0
2331
- END`;
2332
- const rows = await getDb().select({
2333
- costUsd: sql`SUM(${cost})::double precision`.mapWith(Number),
2334
- date,
2335
- events: sql`COUNT(*)::integer`.mapWith(Number)
2336
- }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.type, "structured_event"), sql`${juniorConversationEvents.payload}->>'namespace' = ${plugin.manifest.name}`, sql`${juniorConversationEvents.payload}->>'name' = ${eventName}`, gte(juniorConversationEvents.createdAt, start), lt(juniorConversationEvents.createdAt, endExclusive))).groupBy(date);
2337
- const byDate = new Map(z.array(costRowSchema).parse(rows).map((row) => [row.date, row]));
2338
- return Array.from({ length: input.days }, (_, index) => {
2339
- const date = new Date(start.getTime() + index * DAY_MS$1).toISOString().slice(0, 10);
2340
- return byDate.get(date) ?? {
2341
- costUsd: 0,
2342
- date,
2343
- events: 0
2344
- };
2491
+ const nowMs = now();
2492
+ const end = new Date(nowMs);
2493
+ end.setUTCHours(0, 0, 0, 0);
2494
+ return await readCostBuckets({
2495
+ count: input.days,
2496
+ eventName: registeredEventName(plugin, input.eventName),
2497
+ namespace: plugin.manifest.name,
2498
+ nowMs,
2499
+ start: /* @__PURE__ */ new Date(end.getTime() - (input.days - 1) * DAY_MS$1),
2500
+ unit: DAY
2345
2501
  });
2346
2502
  }
2347
2503
  };
@@ -8449,6 +8605,11 @@ async function recordCodeChange(db, provider, input) {
8449
8605
  where: lte(juniorCodeChanges.updatedAt, change.updatedAt)
8450
8606
  });
8451
8607
  }
8608
+ /** Move a code change's last activity forward. Older activity is a no-op. */
8609
+ async function recordCodeChangeActivity(db, provider, input) {
8610
+ const repository = db.select({ id: juniorCodeRepositories.id }).from(juniorCodeRepositories).where(and(eq(juniorCodeRepositories.provider, provider), eq(juniorCodeRepositories.providerId, input.repositoryProviderId)));
8611
+ await db.update(juniorCodeChanges).set({ lastActivityAt: sql`GREATEST(${juniorCodeChanges.lastActivityAt}, ${input.at.toISOString()}::timestamptz)` }).where(and(eq(juniorCodeChanges.provider, provider), inArray(juniorCodeChanges.repositoryId, repository), eq(juniorCodeChanges.number, input.number)));
8612
+ }
8452
8613
  /** Add conversation links to an existing code change. */
8453
8614
  async function associateCodeChangeConversations(db, provider, input) {
8454
8615
  if (input.conversationIds.length === 0) return;
@@ -8471,6 +8632,9 @@ function createCodeChangePublisher(provider) {
8471
8632
  },
8472
8633
  async record(input) {
8473
8634
  await recordCodeChange(getDb(), provider, input);
8635
+ },
8636
+ async recordActivity(input) {
8637
+ await recordCodeChangeActivity(getDb(), provider, input);
8474
8638
  }
8475
8639
  };
8476
8640
  }
@@ -9834,7 +9998,6 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
9834
9998
  const dashboardConversationUrl = getDashboardConversationLink(context.conversationId);
9835
9999
  const slackContext = slackToolContext ? {
9836
10000
  channelCapabilities: resolveChannelCapabilities(slackToolContext.locationChannelId),
9837
- ...dashboardConversationUrl ? { conversationLink: { url: dashboardConversationUrl } } : void 0,
9838
10001
  ...credentialSubject ? { credentialSubject } : void 0
9839
10002
  } : void 0;
9840
10003
  const annotations = createPluginAnnotations({
@@ -9880,6 +10043,7 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
9880
10043
  ...basePluginContext$1(plugin),
9881
10044
  annotations,
9882
10045
  ...automationUrl ? { automationLink: { url: automationUrl } } : void 0,
10046
+ ...dashboardConversationUrl ? { conversationLink: { url: dashboardConversationUrl } } : void 0,
9883
10047
  conversationId: context.conversationId,
9884
10048
  locationId: context.locationId,
9885
10049
  ...slackContext ? { slack: slackContext } : void 0,
@@ -10532,6 +10696,7 @@ async function selectPluginGrant(input) {
10532
10696
  request: {
10533
10697
  ...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
10534
10698
  ...input.gitPush ? { gitPush: input.gitPush } : void 0,
10699
+ ...input.graphql ? { graphql: input.graphql } : void 0,
10535
10700
  method: input.method,
10536
10701
  ...input.operation ? { operation: input.operation } : void 0,
10537
10702
  url: input.upstreamUrl.toString()
@@ -10855,6 +11020,7 @@ async function selectSandboxEgressGrant(input) {
10855
11020
  const pluginGrant = await selectPluginGrant({
10856
11021
  ...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
10857
11022
  ...input.gitPush ? { gitPush: input.gitPush } : void 0,
11023
+ ...input.graphql ? { graphql: input.graphql } : void 0,
10858
11024
  ...input.operation ? { operation: input.operation } : void 0,
10859
11025
  provider: input.provider,
10860
11026
  method: input.method,
@@ -11097,28 +11263,14 @@ function unreadableBodyResponse(eventId) {
11097
11263
  headers: { "cache-control": "no-store" }
11098
11264
  });
11099
11265
  }
11100
- /** Identify GitHub writes whose body determines whether a grant is safe. */
11101
- function githubBodyInspection(input) {
11102
- if (input.provider !== "github" || input.requestMethod.toUpperCase() !== "POST" || input.upstreamUrl.hostname.toLowerCase() !== "api.github.com") return;
11103
- const pathname = input.upstreamUrl.pathname.toLowerCase();
11104
- if (pathname.endsWith("/graphql")) return "graphql";
11105
- return /^\/repos\/[^/]+\/[^/]+\/pulls\/[^/]+\/reviews(?:\/[^/]+\/events)?$/.test(pathname) ? "pull-request-review" : void 0;
11106
- }
11107
- function grantSelectionBodyTooLargeMessage(inspection) {
11108
- 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.";
11266
+ /** Identify GitHub review writes whose body decides whether a grant is safe. */
11267
+ function isGitHubPullRequestReviewPost(input) {
11268
+ return input.provider === "github" && input.requestMethod.toUpperCase() === "POST" && input.upstreamUrl.hostname.toLowerCase() === "api.github.com" && /^\/repos\/[^/]+\/[^/]+\/pulls\/[^/]+\/reviews(?:\/[^/]+\/events)?$/.test(input.upstreamUrl.pathname.toLowerCase());
11109
11269
  }
11110
- function grantSelectionBodyText(input) {
11111
- if (input.body === void 0) return;
11112
- if (input.body.byteLength > GRANT_SELECTION_BODY_TEXT_LIMIT_BYTES) {
11113
- const inspection = githubBodyInspection({
11114
- provider: input.provider,
11115
- requestMethod: input.request.method,
11116
- upstreamUrl: input.upstreamUrl
11117
- });
11118
- if (inspection) throw new EgressPolicyDenied(grantSelectionBodyTooLargeMessage(inspection));
11119
- return;
11120
- }
11121
- return new TextDecoder().decode(input.body);
11270
+ function grantSelectionBodyText(body) {
11271
+ if (body === void 0) return;
11272
+ 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.");
11273
+ return new TextDecoder().decode(body);
11122
11274
  }
11123
11275
  function responseContentLength(upstream) {
11124
11276
  const raw = upstream.headers.get("content-length");
@@ -11279,21 +11431,16 @@ async function executeCredentialedEgressRequest(input) {
11279
11431
  ...egressDecisionAttributes("denied", "request body is unreadable")
11280
11432
  }));
11281
11433
  }
11282
- const bodyForGrantSelection = githubBodyInspection({
11283
- provider,
11284
- requestMethod: request.method,
11285
- upstreamUrl
11286
- }) ? body : void 0;
11287
11434
  let grantSelection;
11288
11435
  try {
11289
11436
  grantSelection = await selectSandboxEgressGrant({
11290
- bodyText: grantSelectionBodyText({
11291
- body: bodyForGrantSelection,
11437
+ ...isGitHubPullRequestReviewPost({
11292
11438
  provider,
11293
- request,
11439
+ requestMethod: request.method,
11294
11440
  upstreamUrl
11295
- }),
11441
+ }) ? { bodyText: grantSelectionBodyText(body) } : void 0,
11296
11442
  ...isGitReceivePack(request.method, upstreamUrl) ? { gitPush: readGitPush(body) } : void 0,
11443
+ ...isGraphqlPost(request.method, upstreamUrl) ? { graphql: await readGraphqlRequest(body) } : void 0,
11297
11444
  ...operation ? { operation } : void 0,
11298
11445
  provider,
11299
11446
  method: request.method,
@@ -11806,12 +11953,185 @@ async function persistWithRetry(persist) {
11806
11953
  }
11807
11954
  throw lastError;
11808
11955
  }
11956
+ // src/chat/agent-invocations/blocked-report.ts
11957
+ /** Blocked report of a child agent. */
11958
+ /** Model-facing tool that ends a child agent run as blocked. */
11959
+ const REPORT_BLOCKED_TOOL_NAME = "reportBlocked";
11960
+ const blockedReportSchema = z.object({ missing: z.string().trim().min(1) });
11961
+ /**
11962
+ * Read the last successful blocked report from the new messages of one run.
11963
+ *
11964
+ * Do not pass the whole history. A named child keeps its history, so a report
11965
+ * from an earlier agent invocation must not end the current one.
11966
+ */
11967
+ function readBlockedReport(messages) {
11968
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
11969
+ const message = messages[index];
11970
+ if (!isToolResultMessage(message) || isToolResultError(message) || normalizeToolNameFromResult(message) !== "reportBlocked") continue;
11971
+ const parsed = blockedReportSchema.safeParse(message.details);
11972
+ if (parsed.success) return parsed.data;
11973
+ }
11974
+ }
11809
11975
  // src/chat/codemode/result.ts
11810
11976
  /**
11811
11977
  * Name of the tool that runs a Code Mode script. Nested calls use it as
11812
11978
  * their dispatcher name.
11813
11979
  */
11814
11980
  const CODEMODE_TOOL_NAME = "codemode";
11981
+ // src/chat/no-reply.ts
11982
+ /** No-reply result of a Turn. */
11983
+ /** Model-facing tool that ends a Turn with no reply. */
11984
+ const NO_REPLY_TOOL_NAME = "noReply";
11985
+ const noReplySchema$1 = z.object({ note: z.string().trim().min(1).optional() });
11986
+ /**
11987
+ * Read the last successful no-reply result from the new messages of one run.
11988
+ * Do not pass the whole history: a call from an earlier Turn must not end
11989
+ * this one.
11990
+ */
11991
+ function readNoReply(messages) {
11992
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
11993
+ const message = messages[index];
11994
+ if (!isToolResultMessage(message) || isToolResultError(message) || normalizeToolNameFromResult(message) !== "noReply") continue;
11995
+ const parsed = noReplySchema$1.safeParse(message.details);
11996
+ if (parsed.success) return parsed.data;
11997
+ }
11998
+ }
11999
+ const LEGACY_NO_REPLY_MARKERS = ["[[NO_REPLY]]", "[[QUIET]]"];
12000
+ /** True when the text is only a legacy no-reply marker from old history. */
12001
+ function isLegacyNoReplyMarker(text) {
12002
+ return LEGACY_NO_REPLY_MARKERS.includes(text.trim());
12003
+ }
12004
+ /** Return the first legacy no-reply marker that the text contains. */
12005
+ function findLegacyNoReplyMarker(text) {
12006
+ return LEGACY_NO_REPLY_MARKERS.find((marker) => text.includes(marker));
12007
+ }
12008
+ // src/chat/services/assistant-reply.ts
12009
+ const THINKING_XML_BLOCK_PATTERN = /[ \t]*<thinking\b[^>]*>[\s\S]*?<\/thinking>[ \t]*(?:\r?\n)?/gi;
12010
+ const FENCED_CODE_BLOCK_PATTERN = /```[\s\S]*?```/g;
12011
+ /** Remove provider reasoning wrappers while preserving fenced code examples. */
12012
+ function sanitizeAssistantText(text) {
12013
+ let result = "";
12014
+ let cursor = 0;
12015
+ for (const match of text.matchAll(FENCED_CODE_BLOCK_PATTERN)) {
12016
+ const start = match.index;
12017
+ if (start === void 0) continue;
12018
+ result += text.slice(cursor, start).replace(THINKING_XML_BLOCK_PATTERN, "");
12019
+ result += match[0];
12020
+ cursor = start + match[0].length;
12021
+ }
12022
+ return (result + text.slice(cursor).replace(THINKING_XML_BLOCK_PATTERN, "")).trim();
12023
+ }
12024
+ /** Decide whether one completed assistant message becomes a reply. */
12025
+ function decideReply(message) {
12026
+ if (message.content.some((part) => part.type === "toolCall")) return { kind: "suppress" };
12027
+ const text = sanitizeAssistantText(extractAssistantText(message));
12028
+ if (!text) return { kind: "empty" };
12029
+ if (isLegacyNoReplyMarker(text)) return { kind: "suppress" };
12030
+ return {
12031
+ kind: "deliver",
12032
+ text
12033
+ };
12034
+ }
12035
+ /** Return destination-visible reply text when the message is deliverable. */
12036
+ function getAssistantReplyText(message) {
12037
+ const decision = decideReply(message);
12038
+ return decision.kind === "deliver" ? decision.text : void 0;
12039
+ }
12040
+ // src/chat/turn-answer.ts
12041
+ /**
12042
+ * Answer of a gated Turn.
12043
+ *
12044
+ * A gated Turn ends with one answer tool: `reply`, `noReply`, or
12045
+ * `reportBlocked`. Its final response is not delivered. The runtime reads the
12046
+ * answer and decides what to post.
12047
+ */
12048
+ /** Model-facing tool that sets the reply of a gated Turn. */
12049
+ const REPLY_TOOL_NAME = "reply";
12050
+ /** Return whether a tool ends a gated Turn with its answer. */
12051
+ function isAnswerToolName(name) {
12052
+ return name === "reply" || name === "noReply" || name === "reportBlocked";
12053
+ }
12054
+ /** The `reply` text gets the same cleanup as a chat reply. */
12055
+ const replyTextSchema = z.string().transform(sanitizeAssistantText).pipe(z.string().min(1));
12056
+ const replySchema = z.object({ text: replyTextSchema });
12057
+ const noReplySchema = z.object({ note: z.string().trim().min(1).optional() });
12058
+ const blockedSchema = z.object({ missing: z.string().trim().min(1) });
12059
+ const LEGACY_FINISH_AUTOMATION_RUN_TOOL_NAME = "finishAutomationRun";
12060
+ const legacyResultSchema = z.discriminatedUnion("result", [
12061
+ z.object({
12062
+ result: z.literal("send_message"),
12063
+ message: replyTextSchema
12064
+ }),
12065
+ z.object({
12066
+ result: z.literal("no_action"),
12067
+ reason: z.string()
12068
+ }),
12069
+ z.object({
12070
+ result: z.literal("misconfigured"),
12071
+ reason: z.string().min(1)
12072
+ })
12073
+ ]);
12074
+ function parseAnswer(toolName, details, toolCallId) {
12075
+ switch (toolName) {
12076
+ case REPLY_TOOL_NAME: {
12077
+ const parsed = replySchema.safeParse(details);
12078
+ return parsed.success ? { reply: {
12079
+ text: parsed.data.text,
12080
+ toolCallId
12081
+ } } : void 0;
12082
+ }
12083
+ case NO_REPLY_TOOL_NAME: {
12084
+ const parsed = noReplySchema.safeParse(details);
12085
+ return parsed.success ? { noReply: parsed.data } : void 0;
12086
+ }
12087
+ case REPORT_BLOCKED_TOOL_NAME: {
12088
+ const parsed = blockedSchema.safeParse(details);
12089
+ return parsed.success ? { blocked: parsed.data } : void 0;
12090
+ }
12091
+ case LEGACY_FINISH_AUTOMATION_RUN_TOOL_NAME: {
12092
+ const parsed = legacyResultSchema.safeParse(details);
12093
+ if (!parsed.success) return void 0;
12094
+ switch (parsed.data.result) {
12095
+ case "send_message": return { reply: {
12096
+ text: parsed.data.message,
12097
+ toolCallId
12098
+ } };
12099
+ case "no_action": return { noReply: {} };
12100
+ case "misconfigured": return { blocked: { missing: parsed.data.reason } };
12101
+ }
12102
+ }
12103
+ }
12104
+ }
12105
+ /**
12106
+ * Read the last successful answer from the messages of one Turn. Do not pass
12107
+ * the whole history: an answer from an earlier Turn must not end this one.
12108
+ */
12109
+ function readTurnAnswer(messages) {
12110
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
12111
+ const message = messages[index];
12112
+ if (!isToolResultMessage(message) || isToolResultError(message)) continue;
12113
+ const answer = parseAnswer(normalizeToolNameFromResult(message), message.details, message.toolCallId);
12114
+ if (answer) return answer;
12115
+ }
12116
+ }
12117
+ const MISSING_ANSWER_REMINDER = `This Turn has not ended. Your text was not delivered. Call \`${REPLY_TOOL_NAME}\`, \`${NO_REPLY_TOOL_NAME}\`, or \`${REPORT_BLOCKED_TOOL_NAME}\` now.`;
12118
+ /**
12119
+ * Return agent history plus a reminder when the model stopped without an
12120
+ * answer, or undefined when the Turn already has one. `turnStart` is the
12121
+ * index of the Turn's first message in `messages`.
12122
+ */
12123
+ function remindMissingAnswer(messages, turnStart) {
12124
+ const last = messages.at(-1);
12125
+ if (!isAssistantMessage(last) || last.stopReason !== "stop" || readTurnAnswer(messages.slice(turnStart))) return;
12126
+ return [...messages, {
12127
+ role: "user",
12128
+ content: [{
12129
+ type: "text",
12130
+ text: MISSING_ANSWER_REMINDER
12131
+ }],
12132
+ timestamp: Date.now()
12133
+ }];
12134
+ }
11815
12135
  // src/chat/services/turn-limit.ts
11816
12136
  /** Terminal failure when one turn uses too many execution slices. */
11817
12137
  var TurnSliceLimitExceededError = class extends Error {
@@ -11850,6 +12170,11 @@ function isTurnExecutionLimitExceededError(error) {
11850
12170
  */
11851
12171
  const TURN_LIMIT_WRAP_UP_MESSAGE = `This Turn used its execution budget, so all tools are disabled, also in ${CODEMODE_TOOL_NAME} scripts. Do not call a tool again in this Turn. Reply now with what you finished, what is left, and how to continue.`;
11852
12172
  /**
12173
+ * The wrap-up result in a gated Turn. Its answer tools still run, so it can
12174
+ * end with its progress.
12175
+ */
12176
+ const GATED_TURN_LIMIT_WRAP_UP_MESSAGE = `This Turn used its execution budget, so every other tool is disabled, also in ${CODEMODE_TOOL_NAME} scripts. Call \`${REPLY_TOOL_NAME}\` now with what you finished, what is left, and how to continue, or \`${REPORT_BLOCKED_TOOL_NAME}\` when the work cannot continue.`;
12177
+ /**
11853
12178
  * Check tool calls against the turn limits for one slice.
11854
12179
  *
11855
12180
  * The first model step past a limit gets `wrap_up`: its tool calls are blocked
@@ -12510,6 +12835,21 @@ async function appendInboundMessageWithAdmission(args) {
12510
12835
  return { status: "duplicate" };
12511
12836
  }
12512
12837
  if (args.exclusive && hasRunnableWork(current)) return { status: "active" };
12838
+ const text = args.renderText ? await args.renderText(current.execution.inboundMessageIds) : args.message.input.text;
12839
+ if (text === void 0) {
12840
+ await writeConversation(state, lock, withExecutionUpdate(current, {
12841
+ ...current.execution,
12842
+ inboundMessageIds: [...current.execution.inboundMessageIds, args.message.inboundMessageId]
12843
+ }, nowMs));
12844
+ return { status: "duplicate" };
12845
+ }
12846
+ const message = {
12847
+ ...args.message,
12848
+ input: {
12849
+ ...args.message.input,
12850
+ text
12851
+ }
12852
+ };
12513
12853
  let status;
12514
12854
  if (current.execution.lease) status = current.execution.status === "running" ? "running" : "paused";
12515
12855
  else if (current.execution.status === "paused" && args.message.delivery === "defer") status = "paused";
@@ -12523,7 +12863,7 @@ async function appendInboundMessageWithAdmission(args) {
12523
12863
  ...current.execution,
12524
12864
  status,
12525
12865
  inboundMessageIds: [...current.execution.inboundMessageIds, args.message.inboundMessageId],
12526
- pendingMessages: [...current.execution.pendingMessages, args.message].sort(compareMessages)
12866
+ pendingMessages: [...current.execution.pendingMessages, message].sort(compareMessages)
12527
12867
  }, nowMs));
12528
12868
  return { status: "appended" };
12529
12869
  });
@@ -12865,31 +13205,29 @@ async function completeConversationStop(args) {
12865
13205
  }
12866
13206
  /** Cancel human-facing pending mailbox rows without requiring a worker lease. */
12867
13207
  async function cancelHumanFacingPendingMessages(args) {
12868
- const nowMs = args.nowMs ?? now();
12869
13208
  const requestedIds = args.inboundMessageIds === void 0 ? void 0 : new Set(args.inboundMessageIds);
13209
+ const cancelledMessages = await removePendingMessages(args, (message) => isPersonInput(message.source) && (requestedIds === void 0 || requestedIds.has(message.inboundMessageId)) && (args.receivedBeforeMs === void 0 || message.receivedAtMs <= args.receivedBeforeMs));
13210
+ return {
13211
+ cancelledInboundMessageIds: cancelledMessages.map((message) => message.inboundMessageId),
13212
+ cancelledMessages
13213
+ };
13214
+ }
13215
+ /**
13216
+ * Drop pending mailbox rows by id without a worker lease, such as unread
13217
+ * input that a stop skips. Returns the ids that were dropped.
13218
+ */
13219
+ async function dropPendingMessages(args) {
13220
+ const ids = new Set(args.inboundMessageIds);
13221
+ return (await removePendingMessages(args, (message) => ids.has(message.inboundMessageId))).map((message) => message.inboundMessageId);
13222
+ }
13223
+ async function removePendingMessages(args, shouldRemove) {
13224
+ const nowMs = args.nowMs ?? now();
12870
13225
  return await withConversationMutation(args, async (state, lock) => {
12871
13226
  const current = await readConversation(state, args.conversationId);
12872
- if (!current) return {
12873
- cancelledInboundMessageIds: [],
12874
- cancelledMessages: []
12875
- };
12876
- const cancelledInboundMessageIds = [];
12877
- const cancelledMessages = [];
12878
- const pendingMessages = [];
12879
- for (const message of current.execution.pendingMessages) {
12880
- const isRequested = requestedIds === void 0 || requestedIds.has(message.inboundMessageId);
12881
- const isInSnapshot = args.receivedBeforeMs === void 0 || message.receivedAtMs <= args.receivedBeforeMs;
12882
- if (isPersonInput(message.source) && isRequested && isInSnapshot) {
12883
- cancelledInboundMessageIds.push(message.inboundMessageId);
12884
- cancelledMessages.push(message);
12885
- continue;
12886
- }
12887
- pendingMessages.push(message);
12888
- }
12889
- if (cancelledInboundMessageIds.length === 0) return {
12890
- cancelledInboundMessageIds,
12891
- cancelledMessages
12892
- };
13227
+ if (!current) return [];
13228
+ const removed = current.execution.pendingMessages.filter(shouldRemove);
13229
+ if (removed.length === 0) return removed;
13230
+ const pendingMessages = current.execution.pendingMessages.filter((message) => !removed.includes(message));
12893
13231
  const becomesIdle = current.execution.status === "pending" && pendingMessages.length === 0;
12894
13232
  await writeConversation(state, lock, withExecutionUpdate(current, {
12895
13233
  ...current.execution,
@@ -12899,10 +13237,7 @@ async function cancelHumanFacingPendingMessages(args) {
12899
13237
  runId: becomesIdle ? void 0 : current.execution.runId,
12900
13238
  status: becomesIdle ? "idle" : current.execution.status
12901
13239
  }, nowMs));
12902
- return {
12903
- cancelledInboundMessageIds,
12904
- cancelledMessages
12905
- };
13240
+ return removed;
12906
13241
  });
12907
13242
  }
12908
13243
  /**
@@ -14249,7 +14584,7 @@ async function getPluginConversationTitleContext(args) {
14249
14584
  const COMPACTION_TRIGGER_RATIO = .9;
14250
14585
  const CONTEXT_INPUT_LIMIT_RATIO = .95;
14251
14586
  const COMPACTION_TARGET_RATIO = .8;
14252
- const BACKGROUND_COMPACTION_MARK_RATIO = .7;
14587
+ const BACKGROUND_COMPACTION_MARK_RATIO = .85;
14253
14588
  const FALLBACK_CONTEXT_WINDOW_TOKENS = 4e5;
14254
14589
  function positiveInteger(value, fallback) {
14255
14590
  return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
@@ -14398,9 +14733,9 @@ function markConversationMessage(conversation, messageId, patch) {
14398
14733
  }
14399
14734
  };
14400
14735
  }
14401
- function isTakeOnly(message) {
14736
+ function isTakeOrDismissOnly(message) {
14402
14737
  const changes = message.meta?.reviewItemChanges;
14403
- return Boolean(changes?.length && changes.every((change) => change.kind === "taken"));
14738
+ return Boolean(changes?.length && changes.every((change) => change.kind === "taken" || change.kind === "dismissed"));
14404
14739
  }
14405
14740
  function renderThreadContextMessage(message, conversation, index) {
14406
14741
  const author = escapeXml(conversationAuthorDisplayName(message));
@@ -14433,7 +14768,7 @@ function latestConversationMessageSeq(conversation) {
14433
14768
  */
14434
14769
  function buildConversationContext(conversation, options = {}) {
14435
14770
  const { history } = options;
14436
- const candidates = conversation.messages.filter((entry) => !options.excludeMessageIds?.includes(entry.id) && !isTakeOnly(entry) && (!history || isUntaggedThreadMessage(entry) && (history.afterSeq === void 0 || entry.seq === void 0 || entry.seq > history.afterSeq)));
14771
+ const candidates = conversation.messages.filter((entry) => !options.excludeMessageIds?.includes(entry.id) && !isTakeOrDismissOnly(entry) && (!history || isUntaggedThreadMessage(entry) && (history.afterSeq === void 0 || entry.seq === void 0 || entry.seq > history.afterSeq)));
14437
14772
  let first = candidates.length;
14438
14773
  let chars = 0;
14439
14774
  while (first > 0) {
@@ -15026,8 +15361,7 @@ async function commitAcceptedReply(args) {
15026
15361
  conversationId: args.conversationId,
15027
15362
  ...reference
15028
15363
  };
15029
- await bindProviderConversation(executor, binding);
15030
- await startLocationThread(executor, binding);
15364
+ if (await claimProviderConversation(executor, binding)) await startLocationThread(executor, binding);
15031
15365
  }
15032
15366
  }));
15033
15367
  }
@@ -15315,4 +15649,4 @@ async function recordGuardianActionReviewed(args) {
15315
15649
  createdAtMs: Date.now()
15316
15650
  }]);
15317
15651
  }
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 };
15652
+ export { loadTurnCheckpoint as $, createPluginModel as $a, escapeSlackMrkdwnText as $i, getPluginSystemPromptContributions as $n, configValueSchema as $o, RESOURCE_WATCH_TOOL_SOURCE as $r, REPLY_TOOL_NAME as $t, latestConversationMessageSeq as A, isAbortError as Aa, deleteWorkspace as Ai, trimTrailingAssistantMessages as An, readConversationMessageEventSeq as Ao, updateReviewItemContent as Ar, isFinalAttempt as At, getAgentContextInputLimitTokens as B, consumeSandboxEgressPermissionDeniedSignal as Ba, setWorkspaceSnapshotBuild as Bi, tagJson as Bn, resolveRootVisibility as Bo, reviewItemNeedsSomeone as Br, requestAnotherSlice as Bt, settleConversationTitleWork as C, isConversationScopedChannel as Ca, getDashboardTaskLink as Ci, isContinuablePiBoundary as Cn, createPluginConversationEvents as Co, getReviewItem as Cr, deadLetterAttempt as Ct, estimateConversationMessagesTokens as D, withSlackRetries as Da, createPluginState as Di, normalizeToolNameFromResult as Dn, readConversationEventPageAfter as Do, reviewItemsNeedingUserVersionQuery as Dr, getConversationWorkState as Dt, buildConversationContext as E, runWithSlackInstallationToken as Ea, ToolInputError as Ei, isToolResultMessage as En, readConversationEventPage as Eo, listWaitingConversations as Er, getConversation as Et, turnHasReply as F, getWorkspaceSnapshotNotReadyError as Fa, updateWorkspace as Fi, escapeTagText as Fn, getSlackFileId as Fo, canUserReadReviewItem as Fr, pruneActiveConversation as Ft, AuthPausePersistenceError as G, resolveSandboxCommandEnvironment as Ga, getSandboxProvider as Gi, getOAuthAccountProviders as Gn, defaultTimezone as Go, automationCreatorUserId as Gr, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Gt, PluginCredentialFailureError as H, parseSandboxEgressCredentialToken as Ha, hash as Hi, createUserTokenStore as Hn, createPluginAnnotations as Ho, reviewItemReaderForUserInConversation as Hr, startConversationWork as Ht, upsertConversationMessage as I, isWorkspaceSnapshotNotReadyError as Ia, WorkspaceValidationError as Ii, readParentAgentTask as In, matchSlackAttachments as Io, isOnlyAssignee as Ir, recordAttemptFailure as It, abandonReplacedPendingAuth as J, sleep$2 as Ja, deliverOAuthAuthorization as Ji, createPluginEventPublisher as Jn, lookupSlackUserNames as Jo, createCodeChangePublisher as Jr, TurnSliceLimitExceededError as Jt, AuthorizationFlowDisabledError as K, normalizeSandboxEgressTracePropagationDomains as Ka, isVercelSandboxEgressRequest as Ki, resolvePluginOAuthAccount as Kn, resolveUserTimezone as Ko, resolveAssignee as Kr, TURN_LIMIT_WRAP_UP_MESSAGE as Kt, calculateContextCompactionTargetTokens as L, workspaceSnapshotNotReadyUserMessage as La, invalidateReadySnapshot as Li, renderChildTag as Ln, readAttachmentVisionSummary as Lo, readReviewItemAgentScope as Lr, recordConversationRetry as Lt, normalizeConversationText as M, throwSandboxOperationError as Ma, getWorkspaceByName as Mi, SESSION_CONTEXT_SECTION_TAG as Mn, FORK_INSTRUCTIONS as Mo, canActOnReviewItem as Mr, listActiveConversationIds as Mt, recordDeliveredAssistantMessage as N, wrapSandboxSetupError as Na, listWorkspaces as Ni, TURN_CONTEXT_TAG as Nn, loadForkHistory as No, canAgentChangeReviewItem as Nr, markConversationWorkEnqueued as Nt, getConversationMessageSlackTs as O, getWorkspaceTeamId as Oa, renderToolResultNudge as Oi, retainRuntimeTurnContext as On, readConversationEventPageAround as Oo, searchReviewItems as Or, hasConversationStop as Ot, trimConversationMessages as P, WorkspaceSnapshotNotReadyError as Pa, listWorkspacesByRepository as Pi, escapeClosingTags as Pn, notInheritedByForkChild as Po, canReadReviewItem as Pr, moveIdleConversationDestination as Pt, continuableMessages as Q, createPluginEmbedder as Qa, startOAuthFlow as Qi, getPluginSlackConversationLink as Qn, createDurableLocationConfigurationService as Qo, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as Qr, isTurnExecutionLimitExceededError as Qt, getAgentBackgroundCompactionMarkTokens as R, clearSandboxEgressSignals as Ra, loadSnapshotsForProfile as Ri, renderTag as Rn, recordSlackAttachment as Ro, requireReviewItemAssignees as Rr, releaseConversationWork as Rt, resolveConversationTitle as S, getSlackClient as Sa, getDashboardSettingsLink as Si, isAssistantMessage as Sn, viewerMarksFromParticipant as So, getOpenReviewItemByDedupeKey as Sr, countPendingConversationMessages as St, resolveTaskTitle as T, normalizeSlackConversationId as Ta, setDashboardConversationLinkOptions as Ti, isToolResultError as Tn, readLatestConversationBrief as To, listReplyActionItems as Tr, dropPendingMessages as Tt, createPluginAuthOrchestration as U, sandboxEgressSignalsResponseSchema as Ua, isStale as Ui, findLegacyWebActorUserId as Un, listConversationAnnotations as Uo, EVERYONE_ASSIGNEE as Ur, steerWebPendingMessages as Ut, createPluginEgress as V, createSandboxEgressCredentialToken as Va, create as Vi, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as Vn, saveObjectAnnotations as Vo, reviewItemReaderForUser as Vr, requestConversationWork as Vt, authorizationId as W, buildSandboxEgressNetworkPolicy as Wa, ensureDockerDaemon as Wi, webActorUserIds as Wn, listConversationAnnotationsById as Wo, activeParticipantUserIds as Wr, stopConversationWork as Wt, clearPendingAuth as X, workspaceRepoCheckoutPath as Xa, parseOAuthStatePayload as Xi, getPluginApiRoutes as Xn, credentialAuditSource as Xo, getSlackToolContext as Xr, buildTurnErrorResponse as Xt, canReusePendingAuthLink as Y, tryWorkspaceRepoCheckoutPath as Ya, formatProviderLabel as Yi, createPluginHookRunner as Yn, credentialAuditAttributes as Yo, resolveChannelCapabilities as Yr, TurnToolCallLimitExceededError as Yt, getConversationPendingAuth as Z, PluginToolDeniedError as Za, resolveBaseUrl as Zi, getPluginRoutes as Zn, createPluginCache as Zo, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as Zr, createTurnLimitGate as Zt, appendConversationMessages as _, slackExternalRefIdSchema as _a, verifyTimerWatchCredentialSubject as _i, getTerminalAssistantMessages as _n, conversationHasParticipantUser as _o, projectConversationMessages as _r, claimInboundMessage as _t, loadProjection as a, addReactionToMessage as aa, createWatch as ai, getAssistantReplyText as an, sandboxSkillDir as ao, coreTaskRegistrations as ar, failTurnRecord as at, persistConversationMessages as b, getFilePermalink as ba, getDashboardObjectIconLink as bi, hasTurnInput as bn, conversationPinnedForUser as bo, countReviewItemsNeedingUser as br, completeConversationStop as bt, recordAgentsInstructionsUpdated as c, openSlackDirectMessage as ca, getWatch as ci, findLegacyNoReplyMarker as cn, buildCommandScript as co, readWebPushConfig as cr, recordTurnSummary as ct, recordAuthorizationCompleted as d, postSlackMessage as da, bindEventAutomationCredentialSubject as di, CODEMODE_TOOL_NAME as dn, createPluginModelCostRecorder as do, deletePushSubscription as dr, ackMessages as dt, formatSlackLink as ea, STOP_WATCHING_TOOL_NAME as ei, isAnswerToolName as en, SANDBOX_COMMAND_PATH as eo, getPluginTools as er, historyItemFromPiMessage as es, lostWorkerBeforeFirstSave as et, recordAuthorizationRequested as f, removeReactionFromMessage as fa, bindScheduledAutomationCredentialSubject as fi, REPORT_BLOCKED_TOOL_NAME as fn, createPluginLogger as fo, listPushSubscriptions as fr, appendExclusiveInboundMessage as ft, recordToolExecutionStarted as g, slackEntitySchema as ga, verifySlackDirectCredentialSubject as gi, getPiMessageRole as gn, readConversationAccessFromSql as go, isPausedBySlack as gr, checkInConversationWork as gt, recordSubscribedReplyRoute as h, uploadFilesToConversation as ha, verifyScheduledAutomationCredentialSubject as hi, extractAssistantText as hn, createConversationAccessReader as ho, savePushSubscription as hr, cancelHumanFacingPendingMessages as ht, loadConversationProjection as i, truncateStatusText as ia, createTimerWatch as ii, decideReply as in, SANDBOX_WORKSPACE_ROOT as io, validatePlugins as ir, setConfigDefaults as is, completeTurnRecord as it, markConversationMessage as j, isAlreadyExistsError as ja, getWorkspace as ji, REQUEST_CONTEXT_SECTION_TAG as jn, buildSentryConversationUrl as jo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as jr, isInvalidConversationRecordError as jt, isHumanConversationMessage as k, runWithWorkspaceTeamId as ka, createWorkspace as ki, stripRuntimeTurnContext as kn, readConversationLastEventSeq as ko, takeReviewItem as kr, hasRunnableConversationWork as kt, recordAttachmentsDelivered as l, openSlackModal as la, listWatches as li, isLegacyNoReplyMarker as ln, buildNonInteractiveShellScript as lo, sendPushNotificationToUser as lr, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as lt, recordMcpProviderConnected as m, updateSlackMessage as ma, verifyEventAutomationCredentialSubject as mi, persistWithRetry as mn, canAddConversationMessages as mo, saveNotificationSchedule as mr, beginConversationResume as mt, commitMessages as n, normalizeSlackStatusText as na, cancelWatch as ni, remindMissingAnswer as nn, SANDBOX_REPOS_ROOT as no, getPlugins as nr, projectConversationEvents$1 as ns, saveTurnCheckpoint as nt, loadTurnProjection as o, deleteSlackMessage as oa, deliverWatch as oi, sanitizeAssistantText as on, sandboxSkillFile as oo, registration_exports as or, getTurnRecord as ot, recordGuardianActionReviewed as p, unfurlSlackLinks as pa, bindSlackDirectCredentialSubject as pi, readBlockedReport as pn, canAccessConversation as po, readNotificationSchedule as pr, appendInboundMessage as pt, AuthorizationPauseError as q, SANDBOX_RUNTIME as qa, proxyVercelSandboxEgressRequest as qi, agent_hooks_exports as qn, lookupSlackUser as qo, resolveAssignees as qr, TurnBudgetExceededError as qt, loadConnectedMcpProviders as r, slackMention as ra, collectEventMatchKeys as ri, replyTextSchema as rn, SANDBOX_SKILLS_ROOT as ro, setPlugins as rr, getConfigDefaults as rs, abandonTurnRecord as rt, openConversationProjection as s, getSlackMessagePermalink as sa, findMatchingWatches as si, NO_REPLY_TOOL_NAME as sn, sandboxSkillPathResolution as so, setBriefsConfig as sr, listTurnSummaries as st, commitAcceptedReply as t, normalizeSlackReplyMarkdown as ta, cancelSubscriptions as ti, readTurnAnswer as tn, SANDBOX_DATA_ROOT as to, getPluginUserPromptContributions as tr, piMessageFromHistoryItem as ts, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, postSlackEphemeralMessage as ua, takeDueTimerWatches as ui, readNoReply as un, runNonInteractiveCommand as uo, resolveNotificationTimezone as ur, CONVERSATION_WORK_STALE_ENQUEUE_MS as ut, hydrateConversationMessages as v, SlackActionError as va, JUNIOR_THREAD_STATE_TTL_MS as vi, getUserMessageInstructionText as vn, conversationIsMemberRoot as vo, REVIEW_ITEM_REPLIED_REASON as vr, clearConsumedConversationWake as vt, fallbackShortTitle as w, isDmChannel as wa, parseDashboardConversationLink as wi, isStandaloneRuntimeContextMessage as wn, readConversationBriefThrough as wo, insertReviewItem as wr, drainConversationMailbox as wt, toStoredConversationMessage as x, getHeaderString as xa, getDashboardReviewItemLink as xi, instructionTextForProjection as xn, conversationViewerMarks as xo, dismissOpenReviewItems as xr, completeConversationWork as xt, persistConversationMessageWindow as y, downloadPrivateSlackFile as ya, getDashboardConversationLink as yi, hasRuntimeTurnContext as yn, conversationIsNotUnsubscribedRoot as yo, closeReviewItem as yr, clearExpiredConversationLease as yt, getAgentContextCompactionTriggerTokens as z, consumeSandboxEgressAuthRequiredSignal as za, setWorkspaceSnapshot as zi, renderUntrustedTag as zn, slackAttachmentsVersionQuery as zo, requireReviewItemLinks as zr, releaseInboundMessage as zt };