@sentry/junior 0.312.0 → 0.313.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 (82) hide show
  1. package/dist/{adapter-iIq7ihf7.js → adapter-CYAvJzZS.js} +1 -1
  2. package/dist/{adapter-context-BRjEWRy1.js → adapter-context-CVsHoVSf.js} +2 -2
  3. package/dist/{admin-DhInw5K9.js → admin-Cyhb4TwZ.js} +1 -1
  4. package/dist/{agent-runner-C9iDurwX.js → agent-runner-B5y9MsT-.js} +93 -45
  5. package/dist/api/schema.d.ts +1 -1
  6. package/dist/api/schema.js +4 -4
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +40 -40
  9. package/dist/{app-DRFrC8Mw.d.ts → app-DA8-hCMj.d.ts} +2 -2
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +31 -33
  12. package/dist/{background-compaction-queue-DrKi7w3d.js → background-compaction-queue-iZXadLV3.js} +56 -6
  13. package/dist/{catalog-runtime-D7xapBAX.js → catalog-runtime-kkE3hvCX.js} +1 -1
  14. package/dist/{channel-access-CJGfNTdn.js → channel-access-mt7K6dPh.js} +2 -2
  15. package/dist/cli/chat.js +16 -16
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +2 -2
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +5 -5
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-kXB2Y5tl.js → config-CWbwKj0j.js} +3 -3
  23. package/dist/{continue-in-slack-O6pV5004.js → continue-in-slack-CxyFzdlF.js} +6 -6
  24. package/dist/{conversation-feed-uNOv_x68.js → conversation-feed-BEXLD3Me.js} +13 -2
  25. package/dist/{conversation-privacy-L4ja1_W6.js → conversation-privacy-BrMiDN61.js} +1 -1
  26. package/dist/{conversation-turn-CeLbHqdw.js → conversation-turn-B35eu0uz.js} +63 -45
  27. package/dist/{credential-sync-I8VBGk05.js → credential-sync-DWTOEQrm.js} +15 -16
  28. package/dist/{credentialed-Cb6E2phL.js → credentialed-Dyv8b-lu.js} +12 -14
  29. package/dist/{db-BbC5stfa.d.ts → db-DYGcXYl3.d.ts} +1 -1
  30. package/dist/{db-LAyyX8tk.js → db-PwSRzWWn.js} +17 -19
  31. package/dist/{executor-SCub-fAq.js → executor-CgWyWfYz.js} +2 -4
  32. package/dist/{html-BCZ3Xtb_.js → html-DidUcRhI.js} +6 -6
  33. package/dist/ingest-B0AggUEC.js +7931 -0
  34. package/dist/{install-DCFJFkC0.js → install-2urLLXNt.js} +2 -2
  35. package/dist/instrumentation.js +2 -2
  36. package/dist/{lineage-B_m-4TJw.js → lineage-BXplQAVH.js} +2 -2
  37. package/dist/{list-CN2QA2R9.js → list-DyIyReSV.js} +82 -69
  38. package/dist/{logging-dQ9ZRGQ8.js → logging-DNt-qOIO.js} +1 -1
  39. package/dist/{media-CYm1QD8T.js → media-B0pZJ0bG.js} +9 -6
  40. package/dist/{message-DSXGj1hM.js → message-Z5YKC-Af.js} +23 -9
  41. package/dist/{model-input--TrP9hYV.js → model-input-BhPJYdSV.js} +3 -3
  42. package/dist/nitro.d.ts +1 -1
  43. package/dist/nitro.js +4 -4
  44. package/dist/{oauth-callback-server-DHCZC6B4.js → oauth-callback-server-ByvDdcdY.js} +2 -2
  45. package/dist/{oauth-relay-pPMGnDZt.js → oauth-relay-D-kK0yoN.js} +1 -1
  46. package/dist/{registry-CZOzddwu.js → registry-POH4bZC4.js} +1 -1
  47. package/dist/{statuses-_cRJHXK7.js → reporting-window-C4dbzDiR.js} +1 -27
  48. package/dist/request-deadline-BUiRYQYj.js +24 -0
  49. package/dist/{resolve-cKOQ14Dh.js → resolve-CWtBNSKP.js} +3 -3
  50. package/dist/{runner-DBfUW44l.js → runner-CsZ_VRxp.js} +8 -8
  51. package/dist/{sandbox-egress-signals-BVF_xAm1.js → sandbox-egress-signals-FbCk1FkN.js} +1 -1
  52. package/dist/{schema-BEHKxr4I.d.ts → schema-DBf18QPS.d.ts} +131 -912
  53. package/dist/{schema-Bk9Nm2E8.js → schema-DojR2uCL.js} +4 -4
  54. package/dist/{service-account-CVYsFjty.js → service-account-CDYb9hfX.js} +3 -3
  55. package/dist/{service-account-Ts4ulcrV.js → service-account-o15pZWcJ.js} +5 -5
  56. package/dist/{skills-VTnhAJWm.js → skills-B0jP4whm.js} +2 -2
  57. package/dist/{slack-conversation-unfurl-fuLnF1jE.js → slack-conversation-unfurl-D26t9kBC.js} +8 -8
  58. package/dist/{spawn-vxAarlX5.js → spawn-BjljgExZ.js} +14 -33
  59. package/dist/{start-conversation-CEn2KH1A.js → start-conversation-DbVujrwO.js} +10 -196
  60. package/dist/{state-C1P3_Ywk.js → state-BTawTCme.js} +4 -4
  61. package/dist/{result-event-type-BdIJuZxg.js → statuses-BKwqCPhj.js} +25 -4
  62. package/dist/{store-DFZaN-Ix.js → store-CjXrp-Up.js} +3 -3
  63. package/dist/{task-queue-Cx4Lmjyk.js → task-queue-Cwlatjz3.js} +4 -4
  64. package/dist/{task-runner-CbTwFA6k.js → task-runner--Ke8KSMf.js} +11 -11
  65. package/dist/{thread-context-BkAZDTX2.js → thread-context-B8exINEe.js} +6 -7
  66. package/dist/{thread-state-DhPndWi1.js → turn-membership-DTR3SaKD.js} +251 -17
  67. package/dist/{validation-nIzMtAVJ.js → validation-Ce0qbMlT.js} +1 -1
  68. package/dist/{vercel-queue-hW90XzbG.js → vercel-queue-q4z8w5QO.js} +2 -2
  69. package/dist/{version-Brbtz4Qf.js → version-DFh4n9nr.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{warmup-BDA5myRK.js → warmup-D5hzqTcp.js} +44 -2969
  72. package/dist/{worker-D63RcaVD.js → worker-CDg9Lbpg.js} +6 -6
  73. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  74. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
  75. package/migrations/meta/0158_snapshot.json +6515 -0
  76. package/migrations/meta/0159_snapshot.json +6515 -0
  77. package/migrations/meta/_journal.json +14 -0
  78. package/package.json +5 -5
  79. package/dist/callback-mFlTUWWx.js +0 -75
  80. package/dist/child-message-DcsritGf.js +0 -179
  81. package/dist/ingest-BDf3D50j.js +0 -3836
  82. package/dist/result-DcvEOe1r.js +0 -574
@@ -1,21 +1,22 @@
1
- import { En as resolveSandboxEgressProviderForHost, I as projectConversationMessages, Sn as parseSandboxEgressAuthRequiredSignal, _a as fallbackShortTitle, ao as publishConversationStatus, as as createPluginCache, cn as findInErrorChain, cs as completeText, dt as isAssistantMessage, ft as isContinuablePiBoundary, gt as normalizeToolNameFromResult, h as getPlugins, hs as authenticationLinkedEvent, ht as isToolResultMessage, it as extractAssistantText, ms as agentsInstructionsUpdatedEvent, mt as isToolResultError, ns as JUNIOR_THREAD_STATE_TTL_MS, on as startOAuthFlow, ps as JUNIOR_NATIVE_EVENT_NAMESPACE, rn as formatProviderLabel, t as executeCredentialedEgressRequest, ur as pluginConfigValues, va as generateShortTitle, vs as getConfigDefaults, wr as createPluginLogger, yt as trimTrailingAssistantMessages, zo as sleep$1 } from "./credentialed-Cb6E2phL.js";
2
- import { $ as authorAttrs, I as MUTATION_LOCK_TTL_MS, O as resolveGatewayModel, R as fenceLock, U as estimateTextTokens, ct as findProviderError, lt as getProviderErrorAttributes, n as botConfig, r as getChatConfig, rt as renderThreadContext, st as createProviderError, ut as getProviderErrorUserMessage, z as withLock } from "./config-kXB2Y5tl.js";
1
+ import { Ar as getDispatchConversationId, En as resolveSandboxEgressProviderForHost, I as projectConversationMessages, Nr as getDispatchRecord, Sn as parseSandboxEgressAuthRequiredSignal, _a as fallbackShortTitle, ao as publishConversationStatus, as as createPluginCache, cn as findInErrorChain, cs as completeText, dt as isAssistantMessage, ft as isContinuablePiBoundary, gt as normalizeToolNameFromResult, h as getPlugins, hs as authenticationLinkedEvent, ht as isToolResultMessage, it as extractAssistantText, ms as agentsInstructionsUpdatedEvent, mt as isToolResultError, ns as JUNIOR_THREAD_STATE_TTL_MS, on as startOAuthFlow, ps as JUNIOR_NATIVE_EVENT_NAMESPACE, rn as formatProviderLabel, t as executeCredentialedEgressRequest, ur as pluginConfigValues, va as generateShortTitle, vs as getConfigDefaults, wr as createPluginLogger, yt as trimTrailingAssistantMessages, zo as sleep$1 } from "./credentialed-Dyv8b-lu.js";
2
+ import { $ as authorAttrs, I as MUTATION_LOCK_TTL_MS, O as resolveGatewayModel, R as fenceLock, U as estimateTextTokens, ct as findProviderError, lt as getProviderErrorAttributes, n as botConfig, r as getChatConfig, rt as renderThreadContext, st as createProviderError, ut as getProviderErrorUserMessage, z as withLock } from "./config-CWbwKj0j.js";
3
3
  import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
4
- import { E as withSpan, W as formatSentryEventReference, Y as toOptionalString, b as setSpanAttributes, h as logWarn, o as getActiveTraceContext, p as logException, t as buildTurnFailureResponse } from "./logging-dQ9ZRGQ8.js";
4
+ import { E as withSpan, W as formatSentryEventReference, Y as toOptionalString, b as setSpanAttributes, h as logWarn, o as getActiveTraceContext, p as logException, t as buildTurnFailureResponse } from "./logging-DNt-qOIO.js";
5
5
  import { c as parseStoredSlackActor, l as toStoredSlackActor, o as isUserActor, v as parseSlackMessageTs } from "./actor-BsBdxDXQ.js";
6
- import { $t as resolveActorIdentityId, B as claimProviderConversation, O as isPersonInput, On as addAgentTurnUsage, Vn as sameDestination, a as getConversationStore, fn as ToolInputError, m as withConversationEventLock, o as getDb, r as getConversationEventStore, s as getSqlExecutor, u as createSqlConversationEventStore, z as startLocationThread, zn as parseDestination } from "./db-LAyyX8tk.js";
7
- import { q as juniorDestinations, y as juniorLocationConfigurations } from "./executor-SCub-fAq.js";
8
- import { d as contextProvenance, f as instructionActors, n as agentHistoryItemSchema, p as instructionProvenanceFor } from "./history-CYstOMKX.js";
9
- import { a as getStateValues, i as getStateAdapter, r as getDefaultRedisStateAdapterFor } from "./adapter-iIq7ihf7.js";
10
- import { g as credentialSubjectSchema, p as credentialContextForActor } from "./registry-CZOzddwu.js";
11
- import { n as pluginCatalogRuntime } from "./catalog-runtime-D7xapBAX.js";
12
- import { bt as messageCardRef, vt as inboxItemChangeRecordSchema } from "./media-CYm1QD8T.js";
13
- import { t as getVercelConversationWorkQueue } from "./vercel-queue-hW90XzbG.js";
6
+ import { B as claimProviderConversation, Bn as sameDestination, Dn as addAgentTurnUsage, O as isPersonInput, Qt as resolveActorIdentityId, Rn as parseDestination, a as getConversationStore, dn as ToolInputError, m as withConversationEventLock, o as getDb, r as getConversationEventStore, s as getSqlExecutor, u as createSqlConversationEventStore, z as startLocationThread } from "./db-PwSRzWWn.js";
7
+ import { M as juniorConversationEvents, q as juniorDestinations, y as juniorLocationConfigurations } from "./executor-CgWyWfYz.js";
8
+ import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, n as agentHistoryItemSchema, p as instructionProvenanceFor } from "./history-CYstOMKX.js";
9
+ import { a as getStateValues, i as getStateAdapter, r as getDefaultRedisStateAdapterFor } from "./adapter-CYAvJzZS.js";
10
+ import { g as credentialSubjectSchema, m as credentialContextSchema, p as credentialContextForActor } from "./registry-POH4bZC4.js";
11
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-kkE3hvCX.js";
12
+ import { bt as messageCardRef, vt as inboxItemChangeRecordSchema } from "./media-B0pZJ0bG.js";
13
+ import { t as getVercelConversationWorkQueue } from "./vercel-queue-q4z8w5QO.js";
14
14
  import * as z from "zod";
15
15
  import { isDeepStrictEqual } from "node:util";
16
16
  import { createHash, randomUUID } from "node:crypto";
17
17
  import { actorSchema, destinationSchema, escapeTagTextAndQuotes, indentTagLines, renderTag, sourceSchema } from "@sentry/junior-plugin-api";
18
18
  import { and, eq, sql } from "drizzle-orm";
19
+ import { alias } from "drizzle-orm/pg-core";
19
20
  // src/chat/pi/messages.ts
20
21
  /** Permissive schema for durable Pi SDK messages whose content shape may evolve. */
21
22
  const piMessageSchema = z.object({ role: z.string() }).passthrough().transform((value) => value);
@@ -1297,7 +1298,10 @@ function turnStartedKey(turnId) {
1297
1298
  /** Load the `turn_started` event of a Turn, when it started. */
1298
1299
  async function loadTurnStart(conversationId, turnId) {
1299
1300
  const event = await getConversationEventStore().loadByIdempotencyKey(conversationId, turnStartedKey(turnId));
1300
- return event?.data.type === "turn_started" ? { seq: event.seq } : void 0;
1301
+ return event?.data.type === "turn_started" ? {
1302
+ seq: event.seq,
1303
+ startedAtMs: event.createdAtMs
1304
+ } : void 0;
1301
1305
  }
1302
1306
  /** Persist correlated turn lifecycle facts with retry-safe terminal exclusion. */
1303
1307
  var ConversationTurnLifecycleService = class {
@@ -1392,10 +1396,40 @@ var ConversationTurnLifecycleService = class {
1392
1396
  function getTurnLifecycle() {
1393
1397
  return new ConversationTurnLifecycleService(getConversationEventStore(), { watchQueue: getVercelConversationWorkQueue });
1394
1398
  }
1399
+ // src/chat/agent-invocations/parent-message-input.ts
1400
+ /**
1401
+ * A parent agent task or message to a child that no Agent invocation names:
1402
+ * who sent it and the instruction. It names the parent Conversation, the
1403
+ * Actor and grants of the parent's Turn, and the `spawnAgent` or
1404
+ * `messageAgent` tool call that sent it. Its text is the raw task. `fork`
1405
+ * marks the task of a fork spawn.
1406
+ */
1407
+ const parentMessageSchema = z.object({
1408
+ actor: actorSchema,
1409
+ credentialContext: credentialContextSchema.optional(),
1410
+ fork: z.literal(true).optional(),
1411
+ kind: z.literal("parent_message"),
1412
+ parentConversationId: z.string().min(1),
1413
+ parentToolCallId: z.string().min(1)
1414
+ }).strict();
1415
+ /**
1416
+ * Read the parent message that one mailbox input is, if it is one. Check its
1417
+ * sender with `isFromStoredParent` before it gets any authority.
1418
+ */
1419
+ function readParentMessage(message) {
1420
+ if (message.source !== "internal") return;
1421
+ const parsed = parentMessageSchema.safeParse(message.input.metadata);
1422
+ return parsed.success ? parsed.data : void 0;
1423
+ }
1395
1424
  // src/chat/task-execution/attempt-selection.ts
1396
1425
  function inputOwner(message) {
1426
+ const parentMessage = readParentMessage(message);
1397
1427
  return {
1398
1428
  authorId: message.input.authorId,
1429
+ ...parentMessage ? { credentials: {
1430
+ actor: parentMessage.actor,
1431
+ credentialContext: parentMessage.credentialContext
1432
+ } } : void 0,
1399
1433
  identityId: message.input.authorIdentityId,
1400
1434
  source: message.source
1401
1435
  };
@@ -1415,10 +1449,14 @@ function turnOwner(turn) {
1415
1449
  */
1416
1450
  function hasSameOwner(a, b) {
1417
1451
  if (a.source && b.source && a.source !== b.source) return false;
1452
+ if (a.credentials && b.credentials && !hasSameCredentials(a.credentials, b.credentials)) return false;
1418
1453
  const sameIdentity = a.identityId && b.identityId ? a.identityId === b.identityId : void 0;
1419
1454
  const sameAuthor = a.authorId && b.authorId ? a.authorId === b.authorId : void 0;
1420
1455
  return sameIdentity !== false && sameAuthor !== false && (sameIdentity ?? sameAuthor) === true;
1421
1456
  }
1457
+ function hasSameCredentials(a, b) {
1458
+ return sameActorIdentity(a.actor, b.actor) && isDeepStrictEqual(a.credentialContext, b.credentialContext);
1459
+ }
1422
1460
  /** True when two Inbound messages may share one Turn. */
1423
1461
  function canShareTurn(a, b) {
1424
1462
  return hasSameOwner(inputOwner(a), inputOwner(b));
@@ -2112,7 +2150,8 @@ function conversationWorkState(conversation) {
2112
2150
  leaseToken: lease.token
2113
2151
  } } : void 0,
2114
2152
  messages: pendingMessages(conversation),
2115
- needsRun: hasRunnableWork(conversation)
2153
+ needsRun: hasRunnableWork(conversation),
2154
+ runningInboundMessageIds: isLeaseActive(lease, now$1()) ? [...lease?.attemptInboundMessageIds ?? []] : []
2116
2155
  };
2117
2156
  }
2118
2157
  /** Return a persisted conversation record, if one exists. */
@@ -2216,7 +2255,7 @@ async function appendInboundMessageWithAdmission(args) {
2216
2255
  });
2217
2256
  }
2218
2257
  /** Persist one inbound message idempotently in its conversation mailbox. */
2219
- async function appendInboundMessage(args) {
2258
+ async function appendInboundMessage$1(args) {
2220
2259
  const result = await appendInboundMessageWithAdmission({
2221
2260
  ...args,
2222
2261
  exclusive: false
@@ -5204,6 +5243,16 @@ async function ensureConversationWake(args) {
5204
5243
  queueMessageId: queueResult?.messageId
5205
5244
  };
5206
5245
  }
5246
+ /** Persist one inbound message idempotently in its conversation mailbox. */
5247
+ async function appendInboundMessage(args) {
5248
+ const result = await appendInboundMessage$1(args);
5249
+ await recordExecutionMetadata({
5250
+ conversationId: args.message.conversationId,
5251
+ conversationStore: args.conversationStore,
5252
+ state: args.state
5253
+ });
5254
+ return result;
5255
+ }
5207
5256
  /**
5208
5257
  * Record an inbound message id that skips the mailbox. When the claim is
5209
5258
  * saved but its metadata write fails, this releases the claim, so a
@@ -5281,7 +5330,7 @@ async function appendAndEnqueueInboundMessage(args) {
5281
5330
  const nowMs = args.nowMs ?? now();
5282
5331
  const result = await enqueueAfterAppend({
5283
5332
  ...args,
5284
- appendResult: await appendInboundMessage({
5333
+ appendResult: await appendInboundMessage$1({
5285
5334
  message: args.message,
5286
5335
  nowMs,
5287
5336
  renderText: args.renderText,
@@ -5424,7 +5473,7 @@ async function runDeferredMove(args) {
5424
5473
  const move = await takeDeferredConversationMove(args);
5425
5474
  if (move === void 0) return;
5426
5475
  try {
5427
- const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-fuLnF1jE.js").then((n) => n.r);
5476
+ const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-D26t9kBC.js").then((n) => n.r);
5428
5477
  await continueDeferredSlackClick(move, args.getSlackAdapter);
5429
5478
  } catch (error) {
5430
5479
  logException(error, "slack.continue_here.deferred.failed", { "gen_ai.conversation.id": args.conversationId });
@@ -5622,4 +5671,189 @@ function getLocationConfigurationService(destination) {
5622
5671
  loadLegacy: async () => await getLegacyChannelState(destination.channelId)
5623
5672
  });
5624
5673
  }
5625
- export { recordSubscribedReplyRoute as $, CODE_MODE_CALL_STATUS_TEXT as $n, CONVERSATION_WORK_STALE_ENQUEUE_MS as $t, requestAnotherSlice as A, ToolActionRejectedError as An, PluginCredentialFailureError as At, loadConnectedMcpProviders as B, REPLY_TOOL_NAME as Bn, continuableMessages as Bt, getConversation as C, buildTurnErrorResponse as Cn, isEventAuthorId as Ct, recordAttemptFailure as D, finalizeFailedTurnReplyWithEvent as Dn, getAgentContextCompactionTriggerTokens as Dt, listActiveConversationIds as E, captureTurnFailure as En, getAgentBackgroundCompactionMarkTokens as Et, takePendingEventMessages as F, getToolActionRejectionMarker as Fn, AuthorizationPauseError as Ft, recordAgentsInstructionsUpdated as G, decideReply as Gn, abandonTurnRecord as Gt, loadConversationSkillNames as H, readTurnAnswer as Hn, lostWorkerBeforeFirstSave as Ht, buildDeterministicAssistantMessageId as I, restoreToolActionRejections as In, abandonReplacedPendingAuth as It, recordAuthorizationCompleted as J, NO_REPLY_TOOL_NAME as Jn, getStoredTurnFields as Jt, recordAttachmentsDelivered as K, getAssistantReplyText as Kn, completeTurnRecord as Kt, buildDeterministicTurnId as L, RISK_LEVELS as Ln, canReusePendingAuthLink as Lt, startConversationWork as M, ToolActionReviewUnavailableError as Mn, authorizationId as Mt, steerWebPendingMessages as N, createToolActionReview as Nn, AuthPausePersistenceError as Nt, recordConversationRetry as O, getAgentTurnDiagnosticsAttributes as On, getAgentContextInputLimitTokens as Ot, stopConversationWork as P, reviewToolActions as Pn, AuthorizationFlowDisabledError as Pt, recordSkillLoaded as Q, CODEMODE_TOOL_NAME as Qn, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as Qt, commitAcceptedReply as R, ROOT_LINE_BREAK as Rn, clearPendingAuth as Rt, ensureConversationWake as S, TurnToolCallLimitExceededError as Sn, eventBotAuthorId as St, getConversationWorkStates as T, isTurnExecutionLimitExceededError as Tn, calculateContextCompactionTargetTokens as Tt, loadTurnProjection as U, remindMissingAnswer as Un, pauseLostWorkerTurn as Ut, loadConversationProjection as V, isAnswerToolName as Vn, loadTurnCheckpoint as Vt, openConversationProjection as W, replyTextSchema as Wn, saveTurnCheckpoint as Wt, recordGuardianActionReviewed as X, isLegacyNoReplyMarker as Xn, listTurnSummaries as Xt, recordAuthorizationRequested as Y, findLegacyNoReplyMarker as Yn, getTurnRecord as Yt, recordMcpProviderConnected as Z, readNoReply as Zn, recordTurnSummary as Zt, completeConversationStop as _, eventInboundMessageId as _n, turnHasReply as _t, persistThreadStateById as a, isInvalidConversationRecordError as an, piMessageFromHistoryItem as ar, toStoredConversationMessage as at, drainConversationMailbox as b, TurnBudgetExceededError as bn, EVENT_MESSAGE_AUTHOR as bt, appendAndEnqueueExclusiveInboundMessage as c, releaseInboundMessage as cn, buildConversationContext as ct, cancelHumanFacingPendingMessages as d, canJoinTurn as dn, isHumanConversationMessage as dt, countPendingConversationMessages as en, REPORT_BLOCKED_TOOL_NAME as er, recordToolExecutionStarted as et, checkInConversationWork as f, canShareTurn as fn, latestConversationMessageSeq as ft, clearExpiredConversationLease as g, loadTurnStart as gn, trimConversationMessages as gt, clearConsumedConversationWake as h, getTurnLifecycle as hn, recordDeliveredAssistantMessage as ht, persistThreadRuntimeState as i, isFinalAttempt as in, historyItemFromPiMessage as ir, persistConversationMessages as it, requestConversationWork as j, ToolActionReviewLimitError as jn, createPluginAuthOrchestration as jt, releaseConversationWork as k, requireTurnFailureEventId as kn, createPluginEgress as kt, appendAndEnqueueInboundMessage as l, withIdleConversation as ln, estimateConversationMessagesTokens as lt, claimInboundMessage as m, selectAttemptMessages as mn, normalizeConversationText as mt, getPersistedSandboxState as n, hasConversationStop as nn, persistWithRetry as nr, hydrateConversationMessages as nt, coerceThreadConversationState as o, moveIdleConversationDestination as on, projectConversationEvents as or, resolveConversationTitle as ot, claimConversationAttempt as p, isAttemptInterrupt as pn, markConversationMessage as pt, recordAuthenticationLinked as q, sanitizeAssistantText as qn, failTurnRecord as qt, getPersistedThreadState as r, hasRunnableConversationWork as rn, configValueSchema as rr, persistConversationMessageWindow as rt, ackMessages as s, pruneActiveConversation as sn, settleConversationTitleWork as st, getLocationConfigurationService as t, deferConversationMove as tn, readBlockedReport as tr, appendConversationMessages as tt, beginConversationResume as u, readInboundMessageSender as un, getConversationMessageSlackTs as ut, completeConversationWork as v, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as vn, upsertConversationMessage as vt, getConversationWorkState as w, createTurnLimitGate as wn, isEventConversationMessage as wt, dropPendingMessages as x, TurnSliceLimitExceededError as xn, EVENT_SYSTEM_ACTOR as xt, deadLetterAttempt as y, TURN_LIMIT_WRAP_UP_MESSAGE as yn, EVENT_AUTHOR_ID as yt, commitMessages as z, USER_AUTHORIZATION_LEVELS as zn, getConversationPendingAuth as zt };
5674
+ // src/chat/agent-invocations/fork-history.ts
5675
+ /** Instructions that a fork child reads with its first task. */
5676
+ 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.";
5677
+ /**
5678
+ * Cut parent history for a fork: everything before the parent's message that
5679
+ * started the fork, through the last point where every tool call has its
5680
+ * result. A model request with an unanswered tool call fails, and the parent
5681
+ * can commit its history in the middle of a tool round.
5682
+ */
5683
+ function forkHistoryFrom(messages, parentToolCallId) {
5684
+ const spawnIndex = parentToolCallId ? messages.findIndex((message) => message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && part.id === parentToolCallId)) : -1;
5685
+ const before = spawnIndex >= 0 ? messages.slice(0, spawnIndex) : messages;
5686
+ const pending = /* @__PURE__ */ new Set();
5687
+ let end = 0;
5688
+ for (const [index, message] of before.entries()) {
5689
+ if (message.role === "assistant") {
5690
+ for (const part of message.content) if (part.type === "toolCall") pending.add(part.id);
5691
+ } else if (message.role === "toolResult") pending.delete(message.toolCallId);
5692
+ if (pending.size === 0) end = index + 1;
5693
+ }
5694
+ return before.slice(0, end);
5695
+ }
5696
+ /**
5697
+ * Load the start history of a fork child from its parent Conversation.
5698
+ */
5699
+ async function loadForkHistory(invocation) {
5700
+ return forkHistoryFrom((await openConversationProjection({ conversationId: invocation.parentConversationId })).messages, invocation.parentToolCallId);
5701
+ }
5702
+ async function hasTurnStarted(conversationId) {
5703
+ const [row] = await getSqlExecutor().db().select({ seq: juniorConversationEvents.seq }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "turn_started"))).limit(1);
5704
+ return row !== void 0;
5705
+ }
5706
+ /**
5707
+ * Commit the start history of a fork child before its first Turn starts, so
5708
+ * the history is below the Turn start. A child that already has agent
5709
+ * history, such as on a retry, commits nothing. A child whose Turn already
5710
+ * started commits nothing too: the history would be Turn messages, and a
5711
+ * parent `reply` in it would read as the Turn's answer. Only a worker that
5712
+ * committed fork history after the Turn start leaves such a child.
5713
+ */
5714
+ async function commitForkHistory(args) {
5715
+ if ((await openConversationProjection({ conversationId: args.childConversationId })).messages.length > 0 || await hasTurnStarted(args.childConversationId)) return;
5716
+ const messages = await loadForkHistory(args);
5717
+ if (messages.length === 0) return;
5718
+ await commitMessages({
5719
+ conversationId: args.childConversationId,
5720
+ messages,
5721
+ provenance: messages.map(() => contextProvenance)
5722
+ });
5723
+ }
5724
+ /** True for agent history that a fork child inherited from its parent. */
5725
+ function isInheritedForkHistory(event, firstEvent) {
5726
+ return firstEvent !== void 0 && event.seq > firstEvent.seq && event.createdAtMs < firstEvent.createdAtMs && (event.data.type === "assistant_message" || event.data.type === "tool_result");
5727
+ }
5728
+ const firstRow = alias(juniorConversationEvents, "first_event");
5729
+ /**
5730
+ * SQL filter for event rows that a fork child did not inherit from its
5731
+ * parent. Usage reports use it, so inherited model calls count only in the
5732
+ * parent. It reads only a lower seq, the Conversation's first event, so a
5733
+ * counted row never changes whether it counts.
5734
+ */
5735
+ function notInheritedByForkChild() {
5736
+ return sql`not coalesce(${juniorConversationEvents.createdAt} < (
5737
+ select ${firstRow.createdAt}
5738
+ from ${juniorConversationEvents} as ${sql.identifier("first_event")}
5739
+ where ${firstRow.conversationId} = ${juniorConversationEvents.conversationId}
5740
+ and ${firstRow.seq} < ${juniorConversationEvents.seq}
5741
+ order by ${firstRow.seq}
5742
+ limit 1
5743
+ ), false)`;
5744
+ }
5745
+ // src/chat/services/turn-session-routing.ts
5746
+ async function loadConversationChain(conversationId, conversationStore) {
5747
+ const chain = [];
5748
+ const seen = /* @__PURE__ */ new Set();
5749
+ let cursor = conversationId;
5750
+ while (cursor && !seen.has(cursor)) {
5751
+ seen.add(cursor);
5752
+ const conversation = await conversationStore.get({ conversationId: cursor });
5753
+ if (!conversation) break;
5754
+ chain.push(conversation);
5755
+ cursor = conversation.parentConversationId;
5756
+ }
5757
+ return chain;
5758
+ }
5759
+ /**
5760
+ * Normalize a stored Slack session source against the conversation destination.
5761
+ *
5762
+ * Does not create channel or thread values from the conversation id.
5763
+ */
5764
+ function slackSourceForDestination(args) {
5765
+ if (args.source?.kind !== "slack" || args.source.channelId !== args.destination.channelId) return;
5766
+ const threadTs = args.source.threadTs?.trim();
5767
+ return {
5768
+ kind: "slack",
5769
+ visibility: args.source.visibility ?? "public",
5770
+ teamId: args.source.teamId?.trim() || args.destination.teamId,
5771
+ channelId: args.source.channelId,
5772
+ ...threadTs ? { threadTs } : void 0
5773
+ };
5774
+ }
5775
+ /**
5776
+ * Resolve the Conversation Location, Destination, and session Source.
5777
+ *
5778
+ * Reads parent Conversations when this Conversation has no Destination.
5779
+ */
5780
+ async function resolveConversationRouting(args) {
5781
+ const conversationStore = args.conversationStore ?? (await import("./db-PwSRzWWn.js").then((n) => n.n)).getConversationStore();
5782
+ const chain = await loadConversationChain(args.conversationId, conversationStore);
5783
+ let destination;
5784
+ let source;
5785
+ let location;
5786
+ for (const conversation of chain) {
5787
+ destination ??= conversation.destination;
5788
+ source ??= conversation.sessionSource;
5789
+ location ??= conversation.location;
5790
+ if (destination && source) break;
5791
+ }
5792
+ if (!destination) return;
5793
+ if (destination.platform === "slack") {
5794
+ const slackSource = slackSourceForDestination({
5795
+ destination,
5796
+ source
5797
+ });
5798
+ return {
5799
+ destination,
5800
+ ...location ? { location } : void 0,
5801
+ ...slackSource ? { source: slackSource } : void 0
5802
+ };
5803
+ }
5804
+ return {
5805
+ destination,
5806
+ ...location ? { location } : void 0,
5807
+ ...source ? { source } : void 0
5808
+ };
5809
+ }
5810
+ /** Require the Conversation Destination and Source from SQL. */
5811
+ async function resolveTurnSessionRouting(args) {
5812
+ const routing = await resolveConversationRouting(args);
5813
+ if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
5814
+ return {
5815
+ destination: routing.destination,
5816
+ ...routing.location ? { location: routing.location } : void 0,
5817
+ source: routing.source
5818
+ };
5819
+ }
5820
+ /**
5821
+ * Require the Destination and Source to resume a Turn.
5822
+ *
5823
+ * A dispatch Conversation stores the dispatch Source, which has no session
5824
+ * Source. Its dispatch record owns the Destination and Source.
5825
+ */
5826
+ async function resolveTurnResumeRouting(args) {
5827
+ if (!args.dispatchId) return await resolveTurnSessionRouting(args);
5828
+ const dispatch = await getDispatchRecord(args.dispatchId);
5829
+ if (!dispatch) throw new Error(`Dispatch record is missing for ${args.dispatchId}`);
5830
+ const dispatchConversationId = getDispatchConversationId(dispatch);
5831
+ if (dispatchConversationId !== args.conversationId) throw new Error(`Dispatch ${dispatch.id} belongs to ${dispatchConversationId}, not ${args.conversationId}`);
5832
+ const location = (await resolveConversationRouting(args))?.location;
5833
+ return {
5834
+ destination: dispatch.destination,
5835
+ ...location ? { location } : void 0,
5836
+ source: dispatch.source
5837
+ };
5838
+ }
5839
+ // src/chat/task-execution/turn-membership.ts
5840
+ /** True when the committed message at `seq` belongs to the Turn. */
5841
+ function isTurnMessage(start, seq, message) {
5842
+ return seq > start.seq && message.role !== "system";
5843
+ }
5844
+ /**
5845
+ * The messages of a saved Turn with their provenance. Without a
5846
+ * `turn_started` event, nothing tells this Turn from earlier history, so it
5847
+ * has no messages.
5848
+ */
5849
+ function savedTurnMessages(record, start) {
5850
+ if (!start) return [];
5851
+ return record.piMessages.flatMap((message, index) => {
5852
+ const seq = record.piMessageSeqs[index];
5853
+ return seq !== void 0 && isTurnMessage(start, seq, message) ? [{
5854
+ message,
5855
+ provenance: record.piMessageProvenance[index] ?? { authority: "context" }
5856
+ }] : [];
5857
+ });
5858
+ }
5859
+ export { recordAgentsInstructionsUpdated as $, replyTextSchema as $n, abandonTurnRecord as $t, dropPendingMessages as A, TurnSliceLimitExceededError as An, eventBotAuthorId as At, requestConversationWork as B, ToolActionReviewLimitError as Bn, authorizationId as Bt, claimInboundMessage as C, readParentMessage as Cn, recordDeliveredAssistantMessage as Ct, completeConversationWork as D, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Dn, EVENT_AUTHOR_ID as Dt, completeConversationStop as E, eventInboundMessageId as En, upsertConversationMessage as Et, listActiveConversationIds as F, captureTurnFailure as Fn, getAgentContextCompactionTriggerTokens as Ft, buildDeterministicAssistantMessageId as G, restoreToolActionRejections as Gn, canReusePendingAuthLink as Gt, steerWebPendingMessages as H, createToolActionReview as Hn, AuthorizationFlowDisabledError as Ht, recordAttemptFailure as I, finalizeFailedTurnReplyWithEvent as In, getAgentContextInputLimitTokens as It, commitMessages as J, USER_AUTHORIZATION_LEVELS as Jn, continuableMessages as Jt, buildDeterministicTurnId as K, RISK_LEVELS as Kn, clearPendingAuth as Kt, recordConversationRetry as L, getAgentTurnDiagnosticsAttributes as Ln, createPluginEgress as Lt, getConversation as M, buildTurnErrorResponse as Mn, isEventConversationMessage as Mt, getConversationWorkState as N, createTurnLimitGate as Nn, calculateContextCompactionTargetTokens as Nt, deadLetterAttempt as O, TURN_LIMIT_WRAP_UP_MESSAGE as On, EVENT_MESSAGE_AUTHOR as Ot, getConversationWorkStates as P, isTurnExecutionLimitExceededError as Pn, getAgentBackgroundCompactionMarkTokens as Pt, loadTurnProjection as Q, remindMissingAnswer as Qn, saveTurnCheckpoint as Qt, releaseConversationWork as R, requireTurnFailureEventId as Rn, PluginCredentialFailureError as Rt, claimConversationAttempt as S, selectAttemptMessages as Sn, normalizeConversationText as St, clearExpiredConversationLease as T, loadTurnStart as Tn, turnHasReply as Tt, stopConversationWork as U, reviewToolActions as Un, AuthorizationPauseError as Ut, startConversationWork as V, ToolActionReviewUnavailableError as Vn, AuthPausePersistenceError as Vt, takePendingEventMessages as W, getToolActionRejectionMarker as Wn, abandonReplacedPendingAuth as Wt, loadConversationProjection as X, isAnswerToolName as Xn, lostWorkerBeforeFirstSave as Xt, loadConnectedMcpProviders as Y, REPLY_TOOL_NAME as Yn, loadTurnCheckpoint as Yt, loadConversationSkillNames as Z, readTurnAnswer as Zn, pauseLostWorkerTurn as Zt, appendAndEnqueueInboundMessage as _, withIdleConversation as _n, estimateConversationMessagesTokens as _t, FORK_INSTRUCTIONS as a, recordTurnSummary as an, isLegacyNoReplyMarker as ar, recordMcpProviderConnected as at, cancelHumanFacingPendingMessages as b, canShareTurn as bn, latestConversationMessageSeq as bt, notInheritedByForkChild as c, countPendingConversationMessages as cn, CODE_MODE_CALL_STATUS_TEXT as cr, recordToolExecutionStarted as ct, getPersistedThreadState as d, hasRunnableConversationWork as dn, persistWithRetry as dr, persistConversationMessageWindow as dt, completeTurnRecord as en, decideReply as er, recordAttachmentsDelivered as et, persistThreadRuntimeState as f, isFinalAttempt as fn, configValueSchema as fr, persistConversationMessages as ft, appendAndEnqueueExclusiveInboundMessage as g, releaseInboundMessage as gn, buildConversationContext as gt, ackMessages as h, pruneActiveConversation as hn, projectConversationEvents as hr, settleConversationTitleWork as ht, resolveTurnResumeRouting as i, listTurnSummaries as in, findLegacyNoReplyMarker as ir, recordGuardianActionReviewed as it, ensureConversationWake as j, TurnToolCallLimitExceededError as jn, isEventAuthorId as jt, drainConversationMailbox as k, TurnBudgetExceededError as kn, EVENT_SYSTEM_ACTOR as kt, getLocationConfigurationService as l, deferConversationMove as ln, REPORT_BLOCKED_TOOL_NAME as lr, appendConversationMessages as lt, coerceThreadConversationState as m, moveIdleConversationDestination as mn, piMessageFromHistoryItem as mr, resolveConversationTitle as mt, savedTurnMessages as n, getStoredTurnFields as nn, sanitizeAssistantText as nr, recordAuthorizationCompleted as nt, commitForkHistory as o, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as on, readNoReply as or, recordSkillLoaded as ot, persistThreadStateById as p, isInvalidConversationRecordError as pn, historyItemFromPiMessage as pr, toStoredConversationMessage as pt, commitAcceptedReply as q, ROOT_LINE_BREAK as qn, getConversationPendingAuth as qt, resolveConversationRouting as r, getTurnRecord as rn, NO_REPLY_TOOL_NAME as rr, recordAuthorizationRequested as rt, isInheritedForkHistory as s, CONVERSATION_WORK_STALE_ENQUEUE_MS as sn, CODEMODE_TOOL_NAME as sr, recordSubscribedReplyRoute as st, isTurnMessage as t, failTurnRecord as tn, getAssistantReplyText as tr, recordAuthenticationLinked as tt, getPersistedSandboxState as u, hasConversationStop as un, readBlockedReport as ur, hydrateConversationMessages as ut, appendInboundMessage as v, readInboundMessageSender as vn, getConversationMessageSlackTs as vt, clearConsumedConversationWake as w, getTurnLifecycle as wn, trimConversationMessages as wt, checkInConversationWork as x, isAttemptInterrupt as xn, markConversationMessage as xt, beginConversationResume as y, canJoinTurn as yn, isHumanConversationMessage as yt, requestAnotherSlice as z, ToolActionRejectedError as zn, createPluginAuthOrchestration as zt };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-D7xapBAX.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-kkE3hvCX.js";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  // src/chat/plugins/validation.ts
5
5
  var validation_exports = /* @__PURE__ */ __exportAll({
@@ -1,5 +1,5 @@
1
- import { E as withSpan, m as logInfo, p as logException } from "./logging-dQ9ZRGQ8.js";
2
- import { r as getChatConfig } from "./config-kXB2Y5tl.js";
1
+ import { E as withSpan, m as logInfo, p as logException } from "./logging-DNt-qOIO.js";
2
+ import { r as getChatConfig } from "./config-CWbwKj0j.js";
3
3
  import "./fan-out-Cod-yEHG.js";
4
4
  import * as z from "zod";
5
5
  import pLimit from "p-limit";
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.312.0";
2
+ var version = "0.313.0";
3
3
  // src/version.ts
4
4
  /** Installed Junior package version, or `unknown` when package metadata is unavailable. */
5
5
  const JUNIOR_VERSION = typeof version === "string" && version.trim() ? version : "unknown";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export { t as JUNIOR_VERSION } from "./version-Brbtz4Qf.js";
1
+ export { t as JUNIOR_VERSION } from "./version-DFh4n9nr.js";