@sentry/junior 0.292.0 → 0.294.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 (74) hide show
  1. package/dist/{adapter-Cigb1MTr.js → adapter-DxLhJEnO.js} +1 -1
  2. package/dist/{admin-BO9V7vnn.js → admin-vt8aSiCD.js} +2 -2
  3. package/dist/{agent-runner-BuH7EHrX.js → agent-runner-DJu7w6mI.js} +318 -162
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +5 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +65 -40
  8. package/dist/{app-C47PT68y.d.ts → app--a5RLOrr.d.ts} +4 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +454 -435
  11. package/dist/{assistant-reply-ZjLRGHm2.js → assistant-reply-iTtEdDyc.js} +1 -1
  12. package/dist/{automation-CrsYnvdV.js → automation-BM-OBsKW.js} +72 -23
  13. package/dist/{background-compaction-queue-CqZBPe9g.js → background-compaction-queue-D2j-0XkH.js} +4 -4
  14. package/dist/{briefs-DZrhXJss.js → briefs-JOAoCb6d.js} +3 -3
  15. package/dist/{catalog-runtime-Cj9I0dco.js → catalog-runtime-CLMA9AXd.js} +1 -1
  16. package/dist/cli/chat.js +15 -15
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +7 -74
  23. package/dist/{config-BerMjSVL.js → config-mIZeGEWv.js} +17 -7
  24. package/dist/{connections-BWmTOVPB.js → connections-XhdVg7OR.js} +6 -6
  25. package/dist/{conversation-CtjR1Zcx.js → conversation-CDWejM4R.js} +1 -0
  26. package/dist/{conversation-pending-messages-Cd7ShwBs.js → conversation-pending-messages-Dh2tfbaw.js} +5 -2
  27. package/dist/{conversation-privacy-BMfbOUCo.js → conversation-privacy-C6h-X2cZ.js} +1 -1
  28. package/dist/{credential-sync-DZDij2CU.js → credential-sync-zigBlXS3.js} +13 -13
  29. package/dist/{db-BlfjuqzW.js → db--xuNV7g6.js} +99 -6
  30. package/dist/{db-7glZCI18.d.ts → db-DV5AbcGM.d.ts} +8 -6
  31. package/dist/{executor-ikZvFaMD.js → executor-BItuRqAR.js} +87 -21
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-CTCH5jOy.js → logging-Cb6MGvdt.js} +1 -1
  34. package/dist/{message-C1ID1tKi.js → message-BTGgSmaH.js} +9 -9
  35. package/dist/nitro.d.ts +1 -1
  36. package/dist/nitro.js +2 -2
  37. package/dist/{oauth-callback-server-CStBgDU7.js → oauth-callback-server-Dvh1aOIi.js} +2 -2
  38. package/dist/{projection-DY93nCfX.js → projection-DLQgfO5N.js} +61 -52
  39. package/dist/{prompt-exicBZeb.js → prompt-qp_LdxLX.js} +5 -6
  40. package/dist/{registry-X_xdFY9L.js → registry-MtwokaqW.js} +1 -1
  41. package/dist/{resolve-B9dYN-nS.js → resolve-BnJA0UNE.js} +3 -3
  42. package/dist/{result-CC8bV8Fl.js → result-ChL-1KyW.js} +8 -8
  43. package/dist/{runner-D44qp4rc.js → runner-BONN7Dp2.js} +8 -8
  44. package/dist/{sandbox-egress-signals-BrH6DWkt.js → sandbox-egress-signals-nmlmI5Ab.js} +1 -1
  45. package/dist/{schema-CC2RxDAV.d.ts → schema-DgvcyJ1y.d.ts} +283 -45
  46. package/dist/{schema-CVV5r-qP.js → schema-yr0ccDni.js} +29 -4
  47. package/dist/{service-account-DoNZuJb-.js → service-account-Bd0lBaGr.js} +3 -3
  48. package/dist/{service-account-89JZHWCE.js → service-account-kio5nXSD.js} +3 -3
  49. package/dist/{session-stop-DNucbmPf.js → session-stop-CeCXL3j9.js} +20 -41
  50. package/dist/{skills-BeUfmYXL.js → skills-e3DDNlKO.js} +10 -9
  51. package/dist/{spawn-CIAcfcvZ.js → spawn--cRxITWQ.js} +5 -5
  52. package/dist/{stop-Ckd3735h.js → stop-Iai5N2PU.js} +34 -29
  53. package/dist/{store-CS0xoqXW.js → store-C8LsaJwS.js} +3 -3
  54. package/dist/{task-runner-DjjHCX_m.js → task-runner-Dw7exu0-.js} +65 -90
  55. package/dist/{turn-failure-response-D0bwI462.js → turn-failure-response-BqTTx3XG.js} +8 -8
  56. package/dist/{validation-Cvx_AupF.js → validation-BrGahtnv.js} +1 -1
  57. package/dist/{version-BrDx4Fzc.js → version-Bdqhx8Qh.js} +1 -1
  58. package/dist/version.js +1 -1
  59. package/dist/{viewer-4CxdwLLQ.js → viewer-CjRFHR5U.js} +3 -3
  60. package/dist/{warmup-B62hd4lD.js → warmup-DuxCtzKC.js} +104 -26
  61. package/dist/{work-Cu315oJl.js → work-BWBG1EGV.js} +11 -11
  62. package/dist/{worker-4ClZu6ry.js → worker-DAnBIVMs.js} +6 -6
  63. package/migrations/0062_plugin_report_index.sql +1 -20
  64. package/migrations/0078_plugin_conversation_index.sql +1 -20
  65. package/migrations/0079_conversation_event_author_index.sql +1 -20
  66. package/migrations/0080_conversation_event_latest_message_indexes.sql +2 -27
  67. package/migrations/0090_guardian_review_time_index.sql +1 -20
  68. package/migrations/0091_conversation_participant_unsubscribed_index.sql +1 -20
  69. package/migrations/0096_automation_task_kind.sql +75 -0
  70. package/migrations/0097_conversation_kind_automation.sql +6 -0
  71. package/migrations/meta/0096_snapshot.json +4490 -0
  72. package/migrations/meta/0097_snapshot.json +4490 -0
  73. package/migrations/meta/_journal.json +14 -0
  74. package/package.json +5 -5
@@ -1,16 +1,16 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Fa as createPluginEmbedder, Gi as openSlackDirectMessage, Hn as coreTaskRegistrations, Ia as createPluginModel, Ii as escapeSlackMrkdwnText, Ja as createPluginModelCostRecorder, Ji as postSlackMessage, Li as formatSlackLink, Mo as createDurableLocationConfigurationService, Ya as createPluginLogger, an as instructionTextForProjection, b as persistConversationMessages, dn as normalizeToolNameFromResult, en as getPiMessageRole, jo as createPluginCache, li as ToolInputError, ln as isToolResultError, oi as getDashboardTaskLink, oo as createPluginConversationEvents, ot as getTurnRecord, pn as stripRuntimeTurnContext, ti as JUNIOR_THREAD_STATE_TTL_MS, ui as createPluginState, un as isToolResultMessage, v as hydrateConversationMessages, w as fallbackShortTitle, zn as getPlugins } from "./projection-DY93nCfX.js";
3
- import { n as botConfig } from "./config-BerMjSVL.js";
4
- import { E as withSpan, G as isRecord$1, K as toOptionalNumber, _ as runBestEffort, h as logWarn, q as toOptionalString } from "./logging-CTCH5jOy.js";
2
+ import { Bn as getPlugins, Ia as createPluginEmbedder, Ki as openSlackDirectMessage, La as createPluginModel, Li as escapeSlackMrkdwnText, Mo as createPluginCache, No as createDurableLocationConfigurationService, Ri as formatSlackLink, Un as coreTaskRegistrations, Xa as createPluginLogger, Ya as createPluginModelCostRecorder, Yi as postSlackMessage, an as instructionTextForProjection, b as persistConversationMessages, di as createPluginState, dn as normalizeToolNameFromResult, en as getPiMessageRole, ln as isToolResultError, ni as JUNIOR_THREAD_STATE_TTL_MS, ot as getTurnRecord, pn as stripRuntimeTurnContext, si as getDashboardTaskLink, so as createPluginConversationEvents, ui as ToolInputError, un as isToolResultMessage, v as hydrateConversationMessages, w as fallbackShortTitle } from "./projection-DLQgfO5N.js";
3
+ import { n as botConfig } from "./config-mIZeGEWv.js";
4
+ import { E as withSpan, G as isRecord$1, K as toOptionalNumber, _ as runBestEffort, h as logWarn, q as toOptionalString } from "./logging-Cb6MGvdt.js";
5
5
  import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
6
- import { H as agentTurnTotalTokens, V as agentTurnCostUsd, a as getConversationStore, o as getDb } from "./db-BlfjuqzW.js";
7
- import { A as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-ikZvFaMD.js";
6
+ import { K as agentTurnCostUsd, a as getConversationStore, o as getDb, q as agentTurnTotalTokens } from "./db--xuNV7g6.js";
7
+ import { A as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-BItuRqAR.js";
8
8
  import { v as sameActorIdentity } from "./media-BepyEUNm.js";
9
- import { h as credentialSubjectSchema } from "./registry-X_xdFY9L.js";
10
- import { i as readActorIdentity } from "./viewer-4CxdwLLQ.js";
11
- import { r as getStateAdapter } from "./adapter-Cigb1MTr.js";
12
- import { c as pluginTaskParamsSchema, d as sendVercelPluginTask, s as pluginTaskId } from "./background-compaction-queue-CqZBPe9g.js";
13
- import { O as eventAutomationSchema, S as automationVersionSchema, j as scheduledAutomationSchema } from "./automation-CrsYnvdV.js";
9
+ import { h as credentialSubjectSchema } from "./registry-MtwokaqW.js";
10
+ import { i as readActorIdentity } from "./viewer-CjRFHR5U.js";
11
+ import { r as getStateAdapter } from "./adapter-DxLhJEnO.js";
12
+ import { c as pluginTaskParamsSchema, d as sendVercelPluginTask, s as pluginTaskId } from "./background-compaction-queue-D2j-0XkH.js";
13
+ import { B as automationTaskColumns, H as automationTaskSchema, M as scheduledAutomationSchema, S as automationVersionSchema, V as automationTaskDescription, k as eventAutomationSchema, z as automationSkillNameSchema } from "./automation-BM-OBsKW.js";
14
14
  import { createHash } from "node:crypto";
15
15
  import * as z from "zod";
16
16
  import { and, asc, count, desc, eq, gte, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
@@ -349,7 +349,7 @@ function slackSourceForDestination(args) {
349
349
  * Reads parent Conversations when this Conversation has no Destination.
350
350
  */
351
351
  async function resolveConversationRouting(args) {
352
- const conversationStore = args.conversationStore ?? (await import("./db-BlfjuqzW.js").then((n) => n.n)).getConversationStore();
352
+ const conversationStore = args.conversationStore ?? (await import("./db--xuNV7g6.js").then((n) => n.n)).getConversationStore();
353
353
  const chain = await loadConversationChain(args.conversationId, conversationStore);
354
354
  let destination;
355
355
  let source;
@@ -492,18 +492,11 @@ function emptyAutomationRunWindows() {
492
492
  function utcDate(nowMs) {
493
493
  return new Date(nowMs).toISOString().slice(0, 10);
494
494
  }
495
- function emptyDay(date) {
496
- return {
497
- costUsd: 0,
498
- date,
499
- event: 0,
500
- scheduled: 0
501
- };
502
- }
503
495
  function emptyStatusDay(date) {
504
496
  return {
505
497
  blocked: 0,
506
498
  completed: 0,
499
+ costUsd: 0,
507
500
  date,
508
501
  failed: 0
509
502
  };
@@ -569,7 +562,7 @@ async function readAutomationExecutionSummaries(automationIds, options = {}) {
569
562
  }).from(juniorAutomationRuns).where(selected).orderBy(juniorAutomationRuns.automationId, desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).as("latest_task_execution");
570
563
  const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
571
564
  const costSince = (sinceMs) => sql`coalesce(sum(${conversationCost}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::double precision`;
572
- const rows = await db.select({
565
+ const summaryRows = db.select({
573
566
  costLast1Day: costSince(oneDayAgoMs),
574
567
  costLast7Days: costSince(sevenDaysAgoMs),
575
568
  costLast30Days: costSince(thirtyDaysAgoMs),
@@ -582,8 +575,10 @@ async function readAutomationExecutionSummaries(automationIds, options = {}) {
582
575
  runsLast30Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${thirtyDaysAgoMs})::int`,
583
576
  runsLast90Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${ninetyDaysAgoMs})::int`,
584
577
  automationId: juniorAutomationRuns.automationId,
578
+ totalCostUsd: sql`coalesce(sum(${conversationCost}), 0)::double precision`,
585
579
  totalRuns: sql`count(*)::int`
586
580
  }).from(juniorAutomationRuns).innerJoin(latest, eq(latest.automationId, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, executionConversation()).where(selected).groupBy(juniorAutomationRuns.automationId, latest.conversationId, latest.status);
581
+ const [rows, recentRuns] = await Promise.all([summaryRows, readAutomationRecentRuns(automationIds)]);
587
582
  return new Map(rows.map((row) => [row.automationId, {
588
583
  costUsd: {
589
584
  1: addUsd(0, row.costLast1Day),
@@ -594,78 +589,52 @@ async function readAutomationExecutionSummaries(automationIds, options = {}) {
594
589
  lastRunStatus: row.lastRunStatus,
595
590
  ...row.lastConversationId ? { lastConversationId: row.lastConversationId } : void 0,
596
591
  ...row.lastExecutedAtMs !== null ? { lastExecutedAtMs: row.lastExecutedAtMs } : void 0,
592
+ recentRuns: recentRuns.get(row.automationId) ?? [],
597
593
  runs: {
598
594
  1: row.runsLast1Day,
599
595
  7: row.runsLast7Days,
600
596
  30: row.runsLast30Days,
601
597
  90: row.runsLast90Days
602
598
  },
599
+ totalCostUsd: addUsd(0, row.totalCostUsd),
603
600
  totalRuns: row.totalRuns
604
601
  }]));
605
602
  }
606
- /** Load a fixed trailing window of completed executions stacked by task type. */
607
- async function readAutomationExecutionDays(dayCount = 90, options = {}) {
608
- const end = utcDate(options.nowMs ?? Date.now());
609
- const endMs = Date.parse(`${end}T23:59:59.999Z`);
610
- const startMs = Date.parse(`${end}T00:00:00.000Z`) - (dayCount - 1) * 864e5;
611
- const executionDate = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD')`;
612
- const rows = await readCompletedExecutionBuckets({
613
- access: options.access,
614
- bucket: executionDate,
615
- endMs,
616
- startMs
617
- });
618
- const byDate = /* @__PURE__ */ new Map();
619
- for (let offset = 0; offset < dayCount; offset += 1) {
620
- const date = utcDate(startMs + offset * 864e5);
621
- byDate.set(date, emptyDay(date));
622
- }
623
- for (const row of rows) {
624
- const day = byDate.get(row.date);
625
- if (!day) continue;
626
- if (row.kind === "scheduled") day.scheduled = row.count;
627
- else if (row.kind === "event") day.event = row.count;
628
- if (row.costUsd !== null && row.costUsd > 0) day.costUsd = addUsd(day.costUsd, row.costUsd);
629
- }
630
- return [...byDate.values()];
631
- }
632
- /** Load a fixed trailing window of completed executions stacked by hour. */
633
- async function readAutomationExecutionHours(hourCount = 168, options = {}) {
634
- const nowMs = options.nowMs ?? Date.now();
635
- const end = new Date(nowMs);
636
- end.setUTCMinutes(0, 0, 0);
637
- const endMs = end.getTime() + 3599999;
638
- const startMs = end.getTime() - (hourCount - 1) * 36e5;
639
- const executionHour = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD"T"HH24')`;
640
- const rows = await readCompletedExecutionBuckets({
641
- access: options.access,
642
- bucket: executionHour,
643
- endMs,
644
- startMs
645
- });
646
- const byHour = /* @__PURE__ */ new Map();
647
- for (let offset = 0; offset < hourCount; offset += 1) {
648
- const date = new Date(startMs + offset * 36e5).toISOString().slice(0, 13);
649
- byHour.set(date, emptyDay(date));
650
- }
603
+ /**
604
+ * Load the newest runs of each Automation, oldest first. A lateral limit
605
+ * reads at most `AUTOMATION_RECENT_RUN_LIMIT` rows per Automation from the
606
+ * (automation, completed) index, so long histories do not slow the list.
607
+ */
608
+ async function readAutomationRecentRuns(automationIds) {
609
+ const db = getDb();
610
+ const recent = db.select({
611
+ durationMs: juniorConversations.durationMs,
612
+ executedAtMs: juniorAutomationRuns.completedAtMs,
613
+ executionId: juniorAutomationRuns.id,
614
+ status: juniorAutomationRuns.status
615
+ }).from(juniorAutomationRuns).leftJoin(juniorConversations, executionConversation()).where(and(isExecution(), eq(juniorAutomationRuns.automationId, juniorAutomations.id))).orderBy(desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).limit(20).as("recent_run");
616
+ const rows = await db.select({
617
+ automationId: juniorAutomations.id,
618
+ durationMs: recent.durationMs,
619
+ executedAtMs: recent.executedAtMs,
620
+ status: recent.status
621
+ }).from(juniorAutomations).innerJoinLateral(recent, sql`true`).where(inArray(juniorAutomations.id, automationIds)).orderBy(juniorAutomations.id, asc(recent.executedAtMs), asc(recent.executionId));
622
+ const byAutomation = /* @__PURE__ */ new Map();
651
623
  for (const row of rows) {
652
- const hour = byHour.get(row.date);
653
- if (!hour) continue;
654
- if (row.kind === "scheduled") hour.scheduled = row.count;
655
- else if (row.kind === "event") hour.event = row.count;
656
- if (row.costUsd !== null && row.costUsd > 0) hour.costUsd = addUsd(hour.costUsd, row.costUsd);
624
+ const durationMs = positiveDuration(row.durationMs);
625
+ const runs = byAutomation.get(row.automationId) ?? [];
626
+ runs.push({
627
+ ...durationMs !== void 0 ? { durationMs } : void 0,
628
+ executedAt: new Date(row.executedAtMs).toISOString(),
629
+ status: row.status
630
+ });
631
+ byAutomation.set(row.automationId, runs);
657
632
  }
658
- return [...byHour.values()];
633
+ return byAutomation;
659
634
  }
660
- /** Count completed executions and their cost per time bucket and kind. */
661
- async function readCompletedExecutionBuckets(args) {
662
- const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
663
- return await getDb().select({
664
- count: count(),
665
- costUsd: sql`SUM(${conversationCost})::double precision`,
666
- date: args.bucket,
667
- kind: juniorAutomations.kind
668
- }).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, eq(juniorConversations.conversationId, juniorAutomationRuns.conversationId)).where(and(gte(juniorAutomationRuns.completedAtMs, args.startMs), lte(juniorAutomationRuns.completedAtMs, args.endMs), eq(juniorAutomationRuns.status, "completed"), args.access)).groupBy(args.bucket, juniorAutomations.kind).orderBy(asc(args.bucket), asc(juniorAutomations.kind));
635
+ /** Keep a recorded runtime only when it is a real duration. */
636
+ function positiveDuration(value) {
637
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
669
638
  }
670
639
  /** Load the Automation run linked to one conversation, if any. */
671
640
  async function readAutomationExecutionByConversationId(args) {
@@ -687,11 +656,11 @@ async function readAutomationTitlesByConversationId(conversations) {
687
656
  if (untitledIds.length === 0) return titles;
688
657
  const rows = await getDb().select({
689
658
  conversationId: juniorAutomationRuns.conversationId,
690
- instruction: juniorAutomations.instruction,
659
+ task: sql`${juniorAutomations.record}->'task'`,
691
660
  title: juniorAutomations.title
692
661
  }).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(inArray(juniorAutomationRuns.conversationId, untitledIds));
693
662
  for (const row of rows) {
694
- const title = row.title?.trim() || fallbackShortTitle(row.instruction, "");
663
+ const title = row.title?.trim() || fallbackShortTitle(automationTaskDescription(automationTaskSchema.parse(row.task)), "");
695
664
  if (row.conversationId && title) titles.set(row.conversationId, title);
696
665
  }
697
666
  return titles;
@@ -741,7 +710,7 @@ function mapAutomationExecutionRecord(row) {
741
710
  const title = row.title?.trim();
742
711
  const costUsd = agentTurnCostUsd(row.usage ?? void 0);
743
712
  const totalTokens = agentTurnTotalTokens(row.usage ?? void 0);
744
- const durationMs = typeof row.durationMs === "number" && Number.isFinite(row.durationMs) && row.durationMs > 0 ? row.durationMs : void 0;
713
+ const durationMs = positiveDuration(row.durationMs);
745
714
  const error = row.errorMessage?.trim();
746
715
  const scheduledFor = isoTime(row.scheduledForMs);
747
716
  const startedAt = isoTime(row.startedAtMs);
@@ -785,6 +754,7 @@ async function readAutomationExecutionStatusDays(args) {
785
754
  if (row.status === "completed") day.completed = row.count;
786
755
  else if (row.status === "failed") day.failed = row.count;
787
756
  else if (row.status === "blocked") day.blocked = row.count;
757
+ if (row.costUsd !== null && row.costUsd > 0) day.costUsd = addUsd(day.costUsd, row.costUsd);
788
758
  }
789
759
  return [...byDate.values()];
790
760
  }
@@ -814,16 +784,19 @@ async function readAutomationExecutionStatusHours(args) {
814
784
  if (row.status === "completed") hour.completed = row.count;
815
785
  else if (row.status === "failed") hour.failed = row.count;
816
786
  else if (row.status === "blocked") hour.blocked = row.count;
787
+ if (row.costUsd !== null && row.costUsd > 0) hour.costUsd = addUsd(hour.costUsd, row.costUsd);
817
788
  }
818
789
  return [...byHour.values()];
819
790
  }
820
- /** Count one automation's executions per time bucket and status. */
791
+ /** Count one automation's executions and their cost per time bucket and status. */
821
792
  async function readExecutionStatusBuckets(args) {
793
+ const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
822
794
  return await getDb().select({
823
795
  count: count(),
796
+ costUsd: sql`SUM(${conversationCost})::double precision`,
824
797
  date: args.bucket,
825
798
  status: juniorAutomationRuns.status
826
- }).from(juniorAutomationRuns).where(and(isExecution(), eq(juniorAutomationRuns.automationId, args.automationId), gte(juniorAutomationRuns.completedAtMs, args.startMs), lte(juniorAutomationRuns.completedAtMs, args.endMs))).groupBy(args.bucket, juniorAutomationRuns.status).orderBy(asc(args.bucket), asc(juniorAutomationRuns.status));
799
+ }).from(juniorAutomationRuns).leftJoin(juniorConversations, executionConversation()).where(and(isExecution(), eq(juniorAutomationRuns.automationId, args.automationId), gte(juniorAutomationRuns.completedAtMs, args.startMs), lte(juniorAutomationRuns.completedAtMs, args.endMs))).groupBy(args.bucket, juniorAutomationRuns.status).orderBy(asc(args.bucket), asc(juniorAutomationRuns.status));
827
800
  }
828
801
  // src/chat/automations/revision.ts
829
802
  /** Storage revisions prevent stale edits from replacing newer values. */
@@ -853,7 +826,7 @@ function requireAutomationRevision(task, revision) {
853
826
  function automationDefinition(task) {
854
827
  const common = {
855
828
  title: task.title?.trim() || null,
856
- instruction: task.task.text,
829
+ task: task.task,
857
830
  credentialMode: task.credentialMode,
858
831
  destination: task.destination,
859
832
  outcomes: task.outcomes
@@ -1037,7 +1010,7 @@ function eventAutomationColumns(task) {
1037
1010
  creatorIdentityId,
1038
1011
  creatorSlackUserId: record.createdBy.slackUserId,
1039
1012
  identifier: record.trigger.identifier ?? null,
1040
- instruction: record.task.text,
1013
+ ...automationTaskColumns(record.task),
1041
1014
  namespace: record.trigger.namespace,
1042
1015
  record,
1043
1016
  teamId: record.destination.teamId,
@@ -1352,7 +1325,7 @@ async function upsertScheduledAutomation(db, task) {
1352
1325
  createdAtMs,
1353
1326
  creatorIdentityId,
1354
1327
  creatorSlackUserId: record.createdBy.slackUserId,
1355
- instruction: record.task.text,
1328
+ ...automationTaskColumns(record.task),
1356
1329
  nextRunAtMs: nextRunAtMs ?? null,
1357
1330
  record,
1358
1331
  runNowAtMs: runNowAtMs ?? null,
@@ -1457,7 +1430,7 @@ async function notifyAutomationBlocked(ref) {
1457
1430
  await runBestEffort(async () => {
1458
1431
  const task = ref.kind === "scheduled" ? await readScheduledAutomation(getDb(), ref.automationId) : await getEventAutomation(getDb(), ref.automationId);
1459
1432
  if (!task) return;
1460
- const title = task.title ?? fallbackShortTitle(task.task.text, ref.kind === "scheduled" ? "Scheduled automation" : "Event automation");
1433
+ const title = task.title ?? fallbackShortTitle(automationTaskDescription(task.task), ref.kind === "scheduled" ? "Scheduled automation" : "Event automation");
1461
1434
  await postSlackMessage({
1462
1435
  channelId: await openSlackDirectMessage(task.createdBy.slackUserId),
1463
1436
  text: buildBlockedNoticeText(ref.automationId, title, ref.reason)
@@ -1501,6 +1474,7 @@ const dispatchRecordSchema = z.object({
1501
1474
  resultMessageTs: z.string().optional(),
1502
1475
  source: sourceSchema,
1503
1476
  outcomes: z.array(taskOutcomeSchema).max(5).optional(),
1477
+ skill: automationSkillNameSchema.optional(),
1504
1478
  status: dispatchStatusSchema,
1505
1479
  title: z.string().min(1).optional(),
1506
1480
  updatedAtMs: z.number().finite()
@@ -1668,6 +1642,7 @@ async function createOrGetDispatch(args) {
1668
1642
  plugin: args.plugin,
1669
1643
  ...args.options.replyAttribution ? { replyAttribution: args.options.replyAttribution } : void 0,
1670
1644
  ...args.options.outcomes ? { outcomes: args.options.outcomes } : void 0,
1645
+ ...args.options.skill ? { skill: args.options.skill } : void 0,
1671
1646
  status: "pending",
1672
1647
  source: args.options.source,
1673
1648
  ...args.options.title?.trim() ? { title: args.options.title.trim() } : void 0,
@@ -2073,4 +2048,4 @@ async function processPluginTask(message, options = {}) {
2073
2048
  "app.plugin.task": message.name
2074
2049
  });
2075
2050
  }
2076
- export { readAutomationExecutionByConversationId as $, withScheduledAutomationLock as A, registeredResourceTypeSchema as At, setEventAutomationStatus as B, deleteScheduledAutomation as C, eventGuidance as Ct, saveScheduledAutomation as D, registeredEventMatchSchema as Dt, readScheduledAutomation as E, hasEventCatalogEntries as Et, findMatchingEventAutomations as F, listAutomationVersions as G, eventAutomationRunLimitReason as H, getEventAutomation as I, AutomationConflictError as J, readAutomationVersion as K, listDeletedEventAutomationsCreatedBy as L, collectEventAutomationMatchKeys as M, requireValidEventTrigger as Mt, createEventAutomation as N, saveScheduledAutomationInLock as O, registeredEventTriggerProblems as Ot, deleteEventAutomation as P, existingConversationId as Q, parseEventAutomationRow as R, createScheduledAutomation as S, eventCatalogEntry as St, parseScheduledAutomationRow as T, eventWatchUnavailable as Tt, automationDefinition as U, admitEventAutomationRun as V, automationVersionOf as W, requireAutomationRevision as X, automationRevision as Y, emptyAutomationRunWindows as Z, markDispatchBlocked as _, persistThreadStateById as _t, claimDispatchMailboxAppend as a, readAutomationExecutions as at, markDispatchRunning as b, automationEventCatalog as bt, getDispatchConversationId as c, recordAutomationExecution as ct, getDispatchRecord as d, resolveConversationRouting as dt, readAutomationExecutionDays as et, getDispatchTurnId as f, resolveTurnSessionRouting as ft, markDispatchAwaitingResume as g, persistThreadRuntimeState as gt, listPendingDispatchMailboxAppends as h, getPersistedThreadState as ht, buildDispatchId as i, readAutomationExecutionSummaries as it, blockEventAutomation as j, requireEventIdentifier as jt, scheduledRunId as k, registeredEventTypeSchema as kt, getDispatchIdForConversation as l, conversationAggregateColumns as lt, isTerminalDispatchStatus as m, getPersistedSandboxState as mt, scheduleSessionCompletedPluginTasks as n, readAutomationExecutionStatusDays as nt, confirmDispatchMailboxAppend as o, readAutomationRuns as ot, getPluginDispatchProjection as p, getLocationConfigurationService as pt, sameDefinitionValue as q, task_runner_exports as r, readAutomationExecutionStatusHours as rt, createOrGetDispatch as s, readAutomationTitlesByConversationId as st, processPluginTask as t, readAutomationExecutionHours as tt, getDispatchInputMessageId as u, conversationRangeColumns as ut, markDispatchCompleted as v, coerceThreadConversationState as vt, listScheduledAutomationsForTeam as w, eventNamespaceSchema as wt, notifyAutomationBlocked as x, describeRegisteredEventTrigger as xt, markDispatchFailed as y, CORE_EVENT_NAMESPACE as yt, saveEventAutomation as z };
2051
+ export { readAutomationExecutionByConversationId as $, withScheduledAutomationLock as A, requireValidEventTrigger as At, setEventAutomationStatus as B, deleteScheduledAutomation as C, eventWatchUnavailable as Ct, saveScheduledAutomation as D, registeredEventTypeSchema as Dt, readScheduledAutomation as E, registeredEventTriggerProblems as Et, findMatchingEventAutomations as F, listAutomationVersions as G, eventAutomationRunLimitReason as H, getEventAutomation as I, AutomationConflictError as J, readAutomationVersion as K, listDeletedEventAutomationsCreatedBy as L, collectEventAutomationMatchKeys as M, createEventAutomation as N, saveScheduledAutomationInLock as O, registeredResourceTypeSchema as Ot, deleteEventAutomation as P, existingConversationId as Q, parseEventAutomationRow as R, createScheduledAutomation as S, eventNamespaceSchema as St, parseScheduledAutomationRow as T, registeredEventMatchSchema as Tt, automationDefinition as U, admitEventAutomationRun as V, automationVersionOf as W, requireAutomationRevision as X, automationRevision as Y, emptyAutomationRunWindows as Z, markDispatchBlocked as _, CORE_EVENT_NAMESPACE as _t, claimDispatchMailboxAppend as a, readAutomationTitlesByConversationId as at, markDispatchRunning as b, eventCatalogEntry as bt, getDispatchConversationId as c, conversationRangeColumns as ct, getDispatchRecord as d, getLocationConfigurationService as dt, readAutomationExecutionStatusDays as et, getDispatchTurnId as f, getPersistedSandboxState as ft, markDispatchAwaitingResume as g, coerceThreadConversationState as gt, listPendingDispatchMailboxAppends as h, persistThreadStateById as ht, buildDispatchId as i, readAutomationRuns as it, blockEventAutomation as j, scheduledRunId as k, requireEventIdentifier as kt, getDispatchIdForConversation as l, resolveConversationRouting as lt, isTerminalDispatchStatus as m, persistThreadRuntimeState as mt, scheduleSessionCompletedPluginTasks as n, readAutomationExecutionSummaries as nt, confirmDispatchMailboxAppend as o, recordAutomationExecution as ot, getPluginDispatchProjection as p, getPersistedThreadState as pt, sameDefinitionValue as q, task_runner_exports as r, readAutomationExecutions as rt, createOrGetDispatch as s, conversationAggregateColumns as st, processPluginTask as t, readAutomationExecutionStatusHours as tt, getDispatchInputMessageId as u, resolveTurnSessionRouting as ut, markDispatchCompleted as v, automationEventCatalog as vt, listScheduledAutomationsForTeam as w, hasEventCatalogEntries as wt, notifyAutomationBlocked as x, eventGuidance as xt, markDispatchFailed as y, describeRegisteredEventTrigger as yt, saveEventAutomation as z };
@@ -1,13 +1,13 @@
1
- import { E as buildConversationContext, To as listConversationAnnotations, X as clearPendingAuth, j as markConversationMessage, v as hydrateConversationMessages } from "./projection-DY93nCfX.js";
2
- import { H as getProviderErrorAttributes, U as getProviderErrorUserMessage, V as findProviderError, g as TURN_REASONING_LEVELS, z as ProviderError } from "./config-BerMjSVL.js";
3
- import { G as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-CTCH5jOy.js";
1
+ import { E as buildConversationContext, Eo as listConversationAnnotations, X as clearPendingAuth, j as markConversationMessage, v as hydrateConversationMessages } from "./projection-DLQgfO5N.js";
2
+ import { H as findProviderError, U as getProviderErrorAttributes, W as getProviderErrorUserMessage, g as TURN_REASONING_LEVELS, z as ProviderError } from "./config-mIZeGEWv.js";
3
+ import { G as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-Cb6MGvdt.js";
4
4
  import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
5
- import { o as getDb, r as getConversationEventStore, s as getSqlExecutor } from "./db-BlfjuqzW.js";
6
- import { g as juniorAgentInvocations } from "./executor-ikZvFaMD.js";
7
- import { p as credentialContextSchema } from "./registry-X_xdFY9L.js";
8
- import { B as resolveMessageCards, R as readMessageCardRefs, z as removedCardSchema } from "./conversation-CtjR1Zcx.js";
5
+ import { o as getDb, r as getConversationEventStore, s as getSqlExecutor } from "./db--xuNV7g6.js";
6
+ import { g as juniorAgentInvocations } from "./executor-BItuRqAR.js";
7
+ import { p as credentialContextSchema } from "./registry-MtwokaqW.js";
8
+ import { B as resolveMessageCards, R as readMessageCardRefs, z as removedCardSchema } from "./conversation-CDWejM4R.js";
9
9
  import { C as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, S as AGENT_INVOCATION_MAILBOX_STATUSES } from "./reporting-window-B3Ze-Qnt.js";
10
- import { _t as persistThreadStateById, ht as getPersistedThreadState, vt as coerceThreadConversationState } from "./task-runner-DjjHCX_m.js";
10
+ import { gt as coerceThreadConversationState, ht as persistThreadStateById, pt as getPersistedThreadState } from "./task-runner-Dw7exu0-.js";
11
11
  import { createHash } from "node:crypto";
12
12
  import * as z from "zod";
13
13
  import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
@@ -1,5 +1,5 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-Cj9I0dco.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-CLMA9AXd.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
1
  // package.json
2
- var version = "0.292.0";
2
+ var version = "0.294.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-BrDx4Fzc.js";
1
+ export { t as JUNIOR_VERSION } from "./version-Bdqhx8Qh.js";
@@ -1,6 +1,6 @@
1
- import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-CTCH5jOy.js";
2
- import { E as findActorIdentityId, o as getDb } from "./db-BlfjuqzW.js";
3
- import { M as juniorUsers, j as juniorIdentities } from "./executor-ikZvFaMD.js";
1
+ import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-Cb6MGvdt.js";
2
+ import { j as findActorIdentityId, o as getDb } from "./db--xuNV7g6.js";
3
+ import { M as juniorUsers, j as juniorIdentities } from "./executor-BItuRqAR.js";
4
4
  import { r as detectImageMediaType } from "./media-BepyEUNm.js";
5
5
  import { a as withLock } from "./locks-D-0h111u.js";
6
6
  import { createHash, randomUUID } from "node:crypto";
@@ -1,12 +1,12 @@
1
1
  import { n as captureMessage, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Ya as createPluginLogger, jo as createPluginCache, zn as getPlugins } from "./projection-DY93nCfX.js";
3
- import { E as resolveGatewayModel, W as isProviderRetryError, i as getChatConfig } from "./config-BerMjSVL.js";
4
- import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-CTCH5jOy.js";
5
- import { K as rootConversationIsArchived, a as getConversationStore, o as getDb, s as getSqlExecutor } from "./db-BlfjuqzW.js";
6
- import { A as juniorConversations, C as isUserInstruction, j as juniorIdentities, w as juniorConversationEvents } from "./executor-ikZvFaMD.js";
7
- import { u as completeText } from "./prompt-exicBZeb.js";
8
- import { r as getStateAdapter } from "./adapter-Cigb1MTr.js";
9
- import { E as sendCacheWarmup } from "./background-compaction-queue-CqZBPe9g.js";
2
+ import { Bn as getPlugins, Mo as createPluginCache, Xa as createPluginLogger } from "./projection-DLQgfO5N.js";
3
+ import { E as resolveGatewayModel, K as isProviderRetryError, i as getChatConfig } from "./config-mIZeGEWv.js";
4
+ import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-Cb6MGvdt.js";
5
+ import { Z as rootConversationIsArchived, a as getConversationStore, o as getDb, s as getSqlExecutor } from "./db--xuNV7g6.js";
6
+ import { A as juniorConversations, C as isUserInstruction, j as juniorIdentities, w as juniorConversationEvents } from "./executor-BItuRqAR.js";
7
+ import { u as completeText } from "./prompt-qp_LdxLX.js";
8
+ import { r as getStateAdapter } from "./adapter-DxLhJEnO.js";
9
+ import { E as sendCacheWarmup } from "./background-compaction-queue-D2j-0XkH.js";
10
10
  import { streamSimple } from "@earendil-works/pi-ai/compat";
11
11
  import { promisify } from "node:util";
12
12
  import { randomUUID } from "node:crypto";
@@ -48,14 +48,20 @@ const GAP_BIN_EDGES_MS = [
48
48
  Infinity
49
49
  ];
50
50
  const GAP_BIN_COUNT = GAP_BIN_EDGES_MS.length;
51
- /** Gaps a conversation needs before its own gaps replace the global gaps. */
51
+ /**
52
+ * Gaps that a segment needs before its gaps replace its parent segment's
53
+ * gaps (`parentGapSegment`). A new or rare segment starts with its parent's
54
+ * return chances, so it can warm before it has gaps of its own.
55
+ */
52
56
  const BLEND_PSEUDOCOUNT = 20;
53
57
  /**
54
- * Gaps that a decision needs in total. With fewer, one gap sets the return
55
- * chance for each Conversation of the segment, such as at launch or after
56
- * the gap lists expire.
58
+ * Gaps that a Conversation needs before its gaps replace its segment's gaps.
59
+ * One Conversation has few gaps, and a few unusual replies say little about
60
+ * its next one. A backtest of time-ordered decisions showed that a weight
61
+ * this slow predicts returns better than both a faster weight and no
62
+ * Conversation weight at all.
57
63
  */
58
- const MIN_GAP_SAMPLES = 20;
64
+ const CONVERSATION_BLEND_PSEUDOCOUNT = 100;
59
65
  /** Below this prefix size, one cache miss costs too little to warm for. */
60
66
  const MIN_WARMUP_PREFIX_TOKENS = 5e4;
61
67
  /**
@@ -92,11 +98,11 @@ function histogramOf(gapsMs) {
92
98
  total: gapsMs.length
93
99
  };
94
100
  }
95
- function blendHistograms(conversation, global) {
96
- if (conversation.total === 0 || global.total === 0) return conversation.total === 0 ? global : conversation;
97
- const weight = Math.min(conversation.total / BLEND_PSEUDOCOUNT, 1);
101
+ function blendHistograms(own, prior, pseudocount) {
102
+ if (own.total === 0 || prior.total === 0) return own.total === 0 ? prior : own;
103
+ const weight = Math.min(own.total / pseudocount, 1);
98
104
  return {
99
- counts: conversation.counts.map((count, index) => weight * count / conversation.total + (1 - weight) * global.counts[index] / global.total),
105
+ counts: own.counts.map((count, index) => weight * count / own.total + (1 - weight) * prior.counts[index] / prior.total),
100
106
  total: 1
101
107
  };
102
108
  }
@@ -139,6 +145,70 @@ function gapSegment(input) {
139
145
  const depth = input.endedTurns === 0 ? "1" : input.endedTurns < 3 ? "2-3" : "4+";
140
146
  return `${input.userActor ? "user" : "system"}:${depth}:${input.workState}`;
141
147
  }
148
+ /** Each segment that `gapSegment` returns, in display order. */
149
+ const GAP_SEGMENTS = [...[true, false].flatMap((userActor) => [
150
+ 0,
151
+ 1,
152
+ 3
153
+ ].flatMap((endedTurns) => [
154
+ "open",
155
+ "done",
156
+ "none"
157
+ ].map((workState) => gapSegment({
158
+ userActor,
159
+ endedTurns,
160
+ workState,
161
+ archived: false
162
+ })))), ...[
163
+ "open",
164
+ "done",
165
+ "none"
166
+ ].map((workState) => gapSegment({
167
+ userActor: false,
168
+ endedTurns: 0,
169
+ workState,
170
+ archived: true
171
+ }))];
172
+ /**
173
+ * Count gaps in the bins that `decideWarmup` uses, for reports. A gap at or
174
+ * after `IDLE_HORIZON_MS` is a no-reply gap, as the recorder stores it. The
175
+ * bins after the horizon never get a gap, so they are left out.
176
+ */
177
+ function gapHistogramReport(gapsMs) {
178
+ const { counts } = histogramOf(gapsMs.filter((gapMs) => gapMs < IDLE_HORIZON_MS));
179
+ const bins = [];
180
+ for (const [index, endMs] of GAP_BIN_EDGES_MS.entries()) {
181
+ const startMs = index > 0 ? GAP_BIN_EDGES_MS[index - 1] : 0;
182
+ if (startMs >= 33e5) break;
183
+ bins.push({
184
+ startMs,
185
+ endMs: Math.min(endMs, IDLE_HORIZON_MS),
186
+ count: counts[index]
187
+ });
188
+ }
189
+ return {
190
+ bins,
191
+ noReply: gapsMs.filter((gapMs) => gapMs >= IDLE_HORIZON_MS).length,
192
+ total: gapsMs.length
193
+ };
194
+ }
195
+ /**
196
+ * Segment whose gaps a thin segment leans on: the `none` segment with the
197
+ * same Actor and Turn depth. The backfill and most traffic keep the `none`
198
+ * segments full. A `none` segment that is not archived has no parent.
199
+ */
200
+ function parentGapSegment(input) {
201
+ if (!input.archived && input.workState === "none") return void 0;
202
+ return gapSegment({
203
+ ...input,
204
+ workState: "none",
205
+ archived: false
206
+ });
207
+ }
208
+ /** Whether a segment has too few gaps to stand without its parent. */
209
+ function segmentNeedsParent(segmentGaps) {
210
+ return segmentGaps < BLEND_PSEUDOCOUNT;
211
+ }
142
212
  /**
143
213
  * Decide whether to send the next warmup.
144
214
  *
@@ -158,7 +228,8 @@ function decideWarmup(input) {
158
228
  const threshold = savedPerReturn > 0 ? Math.min(input.cacheReadPrice / savedPerReturn, 1) : 1;
159
229
  const conversation = histogramOf(input.conversationGapsMs);
160
230
  const global = histogramOf(input.globalGapsMs);
161
- const histogram = blendHistograms(conversation, global);
231
+ const parent = input.parentGapsMs && segmentNeedsParent(global.total) ? histogramOf(input.parentGapsMs) : void 0;
232
+ const histogram = blendHistograms(conversation, parent ? blendHistograms(global, parent, BLEND_PSEUDOCOUNT) : global, CONVERSATION_BLEND_PSEUDOCOUNT);
162
233
  const probability = returnProbability(histogram, input.idleMs, Math.min(input.cacheTtlMs, IDLE_HORIZON_MS - input.idleMs));
163
234
  const perWarmup = returnsPerWarmup(histogram, input.idleMs, input.cacheExpiryIdleMs, input.cacheTtlMs);
164
235
  const decision = (reason) => ({
@@ -166,12 +237,13 @@ function decideWarmup(input) {
166
237
  reason,
167
238
  returnProbability: probability,
168
239
  returnsPerWarmup: perWarmup,
169
- threshold
240
+ threshold,
241
+ parentPrior: (parent?.total ?? 0) > 0
170
242
  });
171
243
  if (input.prefixTokens < 5e4) return decision("prefix_too_small");
172
244
  if (threshold >= 1) return decision("no_savings");
173
245
  if (input.idleMs >= 33e5) return decision("horizon");
174
- if (conversation.total + global.total < MIN_GAP_SAMPLES) return decision("few_gaps");
246
+ if (conversation.total + global.total + (parent?.total ?? 0) < 20) return decision("few_gaps");
175
247
  return decision(perWarmup >= threshold ? "warm" : "unlikely_return");
176
248
  }
177
249
  function returnsPerWarmup(histogram, idleMs, cacheExpiryIdleMs, ttlMs) {
@@ -728,13 +800,16 @@ async function startIdlePeriod(state, conversationId, request, message, turn) {
728
800
  }
729
801
  const segmentState = await readSegmentState(conversationId, Date.now());
730
802
  await state.set(snapshotKey(conversationId, idle.generation), snapshot, IDLE_HORIZON_MS);
803
+ const segmentInput = {
804
+ ...turn,
805
+ ...segmentState
806
+ };
807
+ const parentSegment = parentGapSegment(segmentInput);
731
808
  return {
732
809
  ...idle,
733
810
  warm: {
734
- segment: gapSegment({
735
- ...turn,
736
- ...segmentState
737
- }),
811
+ segment: gapSegment(segmentInput),
812
+ ...parentSegment ? { parentSegment } : void 0,
738
813
  ...segmentState,
739
814
  modelId: request.model.id,
740
815
  prefixTokens,
@@ -905,9 +980,11 @@ async function runCacheWarmup(message) {
905
980
  return;
906
981
  }
907
982
  const model = resolveGatewayModel(warm.modelId);
983
+ const globalGapsMs = await state.getList(segmentGapsKey(warm.segment));
908
984
  const decision = decideWarmup({
909
985
  conversationGapsMs: await state.getList(conversationGapsKey(conversationId, warm.segment)),
910
- globalGapsMs: await state.getList(segmentGapsKey(warm.segment)),
986
+ globalGapsMs,
987
+ ...warm.parentSegment && segmentNeedsParent(globalGapsMs.length) ? { parentGapsMs: await state.getList(segmentGapsKey(warm.parentSegment)) } : void 0,
911
988
  idleMs: Date.now() - idle.sinceMs,
912
989
  cacheExpiryIdleMs: message.cacheExpiresAtMs - idle.sinceMs,
913
990
  cacheTtlMs: warm.cacheTtlMs,
@@ -918,6 +995,7 @@ async function runCacheWarmup(message) {
918
995
  attributes["app.cache_warming.return_probability"] = decision.returnProbability;
919
996
  attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
920
997
  attributes["app.cache_warming.threshold"] = decision.threshold;
998
+ attributes["app.cache_warming.parent_prior"] = decision.parentPrior;
921
999
  if (!decision.warm) {
922
1000
  await skip(decision.reason);
923
1001
  return;
@@ -958,4 +1036,4 @@ async function runCacheWarmup(message) {
958
1036
  }, startedAtMs, warm);
959
1037
  }, attributes);
960
1038
  }
961
- export { segmentGapsKey as a, listConversationWork as c, MINUTE_MS as d, MIN_WARMUP_PREFIX_TOKENS as f, createCacheWarmingRecorder as i, readLastUserMessageAtByConversation as l, gapSegment as m, GLOBAL_GAPS_MAX as n, warmup_exports as o, NO_REPLY_GAP_MS as p, GLOBAL_GAPS_TTL_MS as r, isConversationWorkDone as s, CONVERSATION_STATE_TTL_MS as t, IDLE_HORIZON_MS as u };
1039
+ export { segmentGapsKey as a, listConversationWork as c, IDLE_HORIZON_MS as d, MINUTE_MS as f, gapSegment as g, gapHistogramReport as h, createCacheWarmingRecorder as i, readLastUserMessageAtByConversation as l, NO_REPLY_GAP_MS as m, GLOBAL_GAPS_MAX as n, warmup_exports as o, MIN_WARMUP_PREFIX_TOKENS as p, GLOBAL_GAPS_TTL_MS as r, isConversationWorkDone as s, CONVERSATION_STATE_TTL_MS as t, GAP_SEGMENTS as u };
@@ -1,15 +1,15 @@
1
- import { H as PluginCredentialFailureError, K as AuthorizationFlowDisabledError, Sn as renderTag, Xt as isTurnExecutionLimitExceededError, at as failTurnRecord, et as lostWorkerBeforeFirstSave, ho as loadForkHistory, nt as saveTurnCheckpoint, ot as getTurnRecord, rt as abandonTurnRecord, s as openConversationProjection, tn as getTerminalAssistantMessages, tt as pauseLostWorkerTurn, v as hydrateConversationMessages, vn as escapeClosingTags } from "./projection-DY93nCfX.js";
2
- import { n as botConfig } from "./config-BerMjSVL.js";
3
- import { T as SYSTEM_IDENTITY_ID, a as getConversationStore, r as getConversationEventStore, s as getSqlExecutor } from "./db-BlfjuqzW.js";
4
- import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-ikZvFaMD.js";
1
+ import { H as PluginCredentialFailureError, K as AuthorizationFlowDisabledError, Sn as renderTag, Xt as isTurnExecutionLimitExceededError, at as failTurnRecord, et as lostWorkerBeforeFirstSave, go as loadForkHistory, nt as saveTurnCheckpoint, ot as getTurnRecord, rt as abandonTurnRecord, s as openConversationProjection, tn as getTerminalAssistantMessages, tt as pauseLostWorkerTurn, v as hydrateConversationMessages, vn as escapeClosingTags } from "./projection-DLQgfO5N.js";
2
+ import { n as botConfig } from "./config-mIZeGEWv.js";
3
+ import { A as SYSTEM_IDENTITY_ID, a as getConversationStore, r as getConversationEventStore, s as getSqlExecutor } from "./db--xuNV7g6.js";
4
+ import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-BItuRqAR.js";
5
5
  import { h as contextProvenance, m as agentInstructionProvenance, v as sameActorIdentity } from "./media-BepyEUNm.js";
6
- import { Dt as stopChildAgentsOf, Gt as finishTurn, Mt as supersedeOpenMailboxTurns, Ot as recordSubagentEnded, Ut as AgentRunError, Wt as executeTurn, an as AgentNameInUseError, kt as recordSubagentStarted, rn as AgentMessageQueueFullError, tn as AgentInvocationLimitError } from "./agent-runner-BuH7EHrX.js";
7
- import { k as getTurnRequestDeadline } from "./background-compaction-queue-CqZBPe9g.js";
8
- import { $ as getUnnamedAgentConversationId, A as markAgentInvocationPaused, C as isTerminalAgentInvocation, H as agentTypeStartsWithParentHistory, J as getAgentInvocationMessageId, L as agentBindingSchema, M as markAgentInvocationSteered, N as reportReplacedAgentInvocation, O as markAgentInvocationMailboxAppended, Q as getNamedAgentConversationId, T as listOpenAgentInvocations, V as agentTypeInstructions, W as getAgentInvocationId, X as getAgentInvocationTurnId, Z as getChildAgentLockName, _ as completeAgentInvocation, at as getConversationTurnBoundaryError, f as ConversationTurnLifecycleService, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, h as ACTIVE_AGENT_INVOCATION_STATUSES, j as markAgentInvocationRunning, rt as TurnInputCommitLostError, st as isTurnInputCommitLostError, v as getActiveAgentInvocationForConversation, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation, y as getAgentInvocation, z as createAgentInvocationSchema } from "./turn-failure-response-D0bwI462.js";
9
- import { n as getAssistantReplyText } from "./assistant-reply-ZjLRGHm2.js";
10
- import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, K as recordFinishedTurnForAutomatedLimit, X as buildSteeringPiMessage, Z as instructionForInputs, ct as readBlockedReport, h as parseWebMessages, i as resumeStoppedConversationTree, p as listActiveMailboxTurns, q as resetAutomatedTurnLimit, u as getActiveConversationTurnId } from "./session-stop-DNucbmPf.js";
11
- import { r as appendAndEnqueueInboundMessage } from "./store-CS0xoqXW.js";
12
- import { _t as persistThreadStateById, ht as getPersistedThreadState, mt as getPersistedSandboxState, vt as coerceThreadConversationState } from "./task-runner-DjjHCX_m.js";
6
+ import { Dt as stopChildAgentsOf, Gt as finishTurn, Mt as supersedeOpenMailboxTurns, Ot as recordSubagentEnded, Ut as AgentRunError, Wt as executeTurn, an as AgentNameInUseError, kt as recordSubagentStarted, rn as AgentMessageQueueFullError, tn as AgentInvocationLimitError } from "./agent-runner-DJu7w6mI.js";
7
+ import { k as getTurnRequestDeadline } from "./background-compaction-queue-D2j-0XkH.js";
8
+ import { $ as getUnnamedAgentConversationId, A as markAgentInvocationPaused, C as isTerminalAgentInvocation, H as agentTypeStartsWithParentHistory, J as getAgentInvocationMessageId, L as agentBindingSchema, M as markAgentInvocationSteered, N as reportReplacedAgentInvocation, O as markAgentInvocationMailboxAppended, Q as getNamedAgentConversationId, T as listOpenAgentInvocations, V as agentTypeInstructions, W as getAgentInvocationId, X as getAgentInvocationTurnId, Z as getChildAgentLockName, _ as completeAgentInvocation, at as getConversationTurnBoundaryError, f as ConversationTurnLifecycleService, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, h as ACTIVE_AGENT_INVOCATION_STATUSES, j as markAgentInvocationRunning, rt as TurnInputCommitLostError, st as isTurnInputCommitLostError, v as getActiveAgentInvocationForConversation, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation, y as getAgentInvocation, z as createAgentInvocationSchema } from "./turn-failure-response-BqTTx3XG.js";
9
+ import { n as getAssistantReplyText } from "./assistant-reply-iTtEdDyc.js";
10
+ import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, K as recordFinishedTurnForAutomatedLimit, X as buildSteeringPiMessage, Z as instructionForInputs, ct as readBlockedReport, h as parseWebMessages, i as resumeStoppedConversationTree, p as listActiveMailboxTurns, q as resetAutomatedTurnLimit, u as getActiveConversationTurnId } from "./session-stop-CeCXL3j9.js";
11
+ import { r as appendAndEnqueueInboundMessage } from "./store-C8LsaJwS.js";
12
+ import { ft as getPersistedSandboxState, gt as coerceThreadConversationState, ht as persistThreadStateById, pt as getPersistedThreadState } from "./task-runner-Dw7exu0-.js";
13
13
  import { isDeepStrictEqual } from "node:util";
14
14
  import * as z from "zod";
15
15
  import { and, eq } from "drizzle-orm";