@sentry/junior 0.288.0 → 0.290.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 (76) hide show
  1. package/dist/{adapter-Cikcqdty.js → adapter-CHMVy-j0.js} +1 -1
  2. package/dist/{admin-BcSxHuTB.js → admin-C45Ap5Tn.js} +2 -2
  3. package/dist/{agent-runner-9MXyWUL8.js → agent-runner-CZjf6MOQ.js} +343 -103
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +6 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +281 -254
  8. package/dist/{app-BUklJVBe.d.ts → app-BB1j2krL.d.ts} +2 -4
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +92 -64
  11. package/dist/assistant-reply-BtIV0hq6.js +58 -0
  12. package/dist/{automation-DDXwHQs5.js → automation-DWbjJltM.js} +1 -1
  13. package/dist/{background-compaction-queue-CjllSPir.js → background-compaction-queue-2gKhjRD3.js} +4 -4
  14. package/dist/{briefs-DW9iuolG.js → briefs-BGke_Cz5.js} +3 -4
  15. package/dist/{catalog-runtime-B3gfH58M.js → catalog-runtime-BSOlVfXi.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  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 +4 -4
  23. package/dist/{config-CLJcyYEF.js → config-DHDub41t.js} +4 -41
  24. package/dist/{connections-BtdJftow.js → connections-BAb0fedk.js} +7 -129
  25. package/dist/{conversation-DhoqHtQ7.js → conversation-CwC8K3RZ.js} +8 -8
  26. package/dist/{conversation-pending-messages-DHV0S4uF.js → conversation-pending-messages-B0cuLReP.js} +1 -1
  27. package/dist/{conversation-privacy-BPirIVlX.js → conversation-privacy-QRdLPH-9.js} +1 -1
  28. package/dist/{credential-sync-Co8Q2xRW.js → credential-sync-YIMGiRk7.js} +13 -13
  29. package/dist/{db-Co7DTYYh.js → db-DBHig2sI.js} +56 -31
  30. package/dist/{db-zIs8-Ba3.d.ts → db-DCSmv9tz.d.ts} +6 -2
  31. package/dist/{executor-m0kIN71Q.js → executor-DKrtH0k_.js} +62 -13
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-DbD-dErY.js → logging-f24cZPEj.js} +2 -2
  34. package/dist/{history-IjdmO_r6.js → media-BepyEUNm.js} +85 -1
  35. package/dist/{message-DKTdTYm-.js → message-BbBOajiX.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +2 -2
  38. package/dist/{oauth-callback-server-CpbepSbp.js → oauth-callback-server-rHJYjFoz.js} +2 -2
  39. package/dist/{projection-BViECfYu.js → projection-D-9aVaHj.js} +153 -119
  40. package/dist/{prompt-KT6MaDHN.js → prompt-C7SZhNDy.js} +183 -3
  41. package/dist/{registry-D-Acyjhh.js → registry-CwA-kSjW.js} +1 -1
  42. package/dist/{resolve-gkT2R66z.js → resolve-B5WJgt9k.js} +3 -3
  43. package/dist/{result-DHmCFEt8.js → result-B2sCVIwl.js} +16 -10
  44. package/dist/{runner-DBKjGjH-.js → runner-CZq7wyIh.js} +8 -8
  45. package/dist/{sandbox-egress-signals-9n8hqx29.js → sandbox-egress-signals-C4d6Pa9a.js} +1 -1
  46. package/dist/{schema-DxicIQbc.js → schema-Bptz19Ja.js} +14 -9
  47. package/dist/{schema-B_6aOcx5.d.ts → schema-DQaFSkZZ.d.ts} +13 -5
  48. package/dist/{service-account-CDlC9ssy.js → service-account-B6OJtplS.js} +3 -3
  49. package/dist/{service-account-Bi0HsY6w.js → service-account-BC73M8rj.js} +3 -3
  50. package/dist/{session-stop-BWOsuo8p.js → session-stop-1cku9Vm3.js} +41 -30
  51. package/dist/{skills-DO5K68Rq.js → skills-BFopj5ID.js} +2 -2
  52. package/dist/{spawn-BBqZDcPa.js → spawn-B-1JlJwH.js} +5 -5
  53. package/dist/{stop-WC97cmHz.js → stop-CJweYiOH.js} +123 -213
  54. package/dist/{store-ByR1Lr7e.js → store-CK869JpC.js} +3 -3
  55. package/dist/{task-runner-B-Ewf8TX.js → task-runner-XmXL9E-k.js} +13 -17
  56. package/dist/{turn-failure-response-CpdPoZSl.js → turn-failure-response-hhpek6Fn.js} +8 -8
  57. package/dist/{validation-B4sbIoES.js → validation-DHQjCRFx.js} +1 -1
  58. package/dist/{version-D6lpuAgL.js → version-DQgCf4FE.js} +1 -1
  59. package/dist/version.js +1 -1
  60. package/dist/{viewer-CeP27tC3.js → viewer-DG97nzP4.js} +4 -4
  61. package/dist/{warmup-P_GJCL1c.js → warmup-C00-jOoN.js} +272 -78
  62. package/dist/{work-DI7x1Slm.js → work-Ch3EWO6u.js} +14 -14
  63. package/dist/{worker-CYPTOT4j.js → worker-B8kyM1fB.js} +6 -30
  64. package/migrations/0091_conversation_participant_unsubscribed_index.sql +20 -0
  65. package/migrations/0092_turn_metric_actor.sql +12 -0
  66. package/migrations/0093_participant_root_actor_backfill.sql +18 -0
  67. package/migrations/0094_conversation_delivery_paused_at.sql +1 -0
  68. package/migrations/meta/0091_snapshot.json +4410 -0
  69. package/migrations/meta/0092_snapshot.json +4446 -0
  70. package/migrations/meta/0093_snapshot.json +4446 -0
  71. package/migrations/meta/0094_snapshot.json +4452 -0
  72. package/migrations/meta/_journal.json +28 -0
  73. package/package.json +5 -5
  74. package/dist/assistant-reply-mj47jMRV.js +0 -65
  75. package/dist/core-model-BTt5E5b0.js +0 -182
  76. package/dist/media-BAHvgkok.js +0 -85
@@ -1,12 +1,16 @@
1
1
  import { n as captureMessage, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { E as resolveGatewayModel, G as isProviderRetryError, i as getChatConfig } from "./config-CLJcyYEF.js";
3
- import { H as runWithLogContext, h as logWarn, m as logInfo } from "./logging-DbD-dErY.js";
4
- import { r as completeText } from "./core-model-BTt5E5b0.js";
5
- import { r as getStateAdapter } from "./adapter-Cikcqdty.js";
6
- import { E as sendCacheWarmup } from "./background-compaction-queue-CjllSPir.js";
2
+ import { Ya as createPluginLogger, jo as createPluginCache, zn as getPlugins } from "./projection-D-9aVaHj.js";
3
+ import { E as resolveGatewayModel, W as isProviderRetryError, i as getChatConfig } from "./config-DHDub41t.js";
4
+ import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-f24cZPEj.js";
5
+ import { K as rootConversationIsArchived, a as getConversationStore, o as getDb, s as getSqlExecutor } from "./db-DBHig2sI.js";
6
+ import { A as juniorConversations, C as isUserInstruction, j as juniorIdentities, w as juniorConversationEvents } from "./executor-DKrtH0k_.js";
7
+ import { u as completeText } from "./prompt-C7SZhNDy.js";
8
+ import { r as getStateAdapter } from "./adapter-CHMVy-j0.js";
9
+ import { E as sendCacheWarmup } from "./background-compaction-queue-2gKhjRD3.js";
7
10
  import { streamSimple } from "@earendil-works/pi-ai/compat";
8
11
  import { promisify } from "node:util";
9
12
  import { randomUUID } from "node:crypto";
13
+ import { and, desc, eq, inArray, sql } from "drizzle-orm";
10
14
  import { constants, zstdCompress, zstdDecompress } from "node:zlib";
11
15
  // src/chat/cache-warming/model.ts
12
16
  /**
@@ -77,9 +81,6 @@ function warmupFailureCountsAsMiss(error) {
77
81
  }
78
82
  /** Gap that Junior records for an idle period with no reply in the horizon. */
79
83
  const NO_REPLY_GAP_MS = 1440 * MINUTE_MS;
80
- const BASE_WARMUP_MARGIN_MS = 45e3;
81
- const MARGIN_PER_PREFIX_TOKEN_MS = .27;
82
- const MAX_SIZE_MARGIN_MS = 9e4;
83
84
  function binIndex(gapMs) {
84
85
  return GAP_BIN_EDGES_MS.findIndex((edge) => gapMs < edge);
85
86
  }
@@ -115,24 +116,28 @@ function returnProbability(histogram, idleMs, windowMs) {
115
116
  return Math.max(0, (now - survival(histogram, idleMs + windowMs)) / now);
116
117
  }
117
118
  /**
118
- * Return how long before cache expiry to send a warmup. The warmup refreshes
119
- * the cache only if the provider reads the whole prefix before it expires. A
120
- * larger prefix takes longer to send and read, and its cache blocks were
121
- * written at slightly different times. So the margin grows with the prefix up
122
- * to a fixed cap.
119
+ * How long before cache expiry Junior sends a warmup. A warmup reads each
120
+ * cache block of the prefix in one request, so the provider refreshes all
121
+ * blocks together. A margin that grows with the prefix size gains nothing.
122
+ * The margin covers only the queue delay and the time of the warmup request.
123
123
  */
124
- function warmupMarginMs(prefixTokens) {
125
- return BASE_WARMUP_MARGIN_MS + Math.min(Math.max(0, prefixTokens) * MARGIN_PER_PREFIX_TOKEN_MS, MAX_SIZE_MARGIN_MS);
126
- }
124
+ const WARMUP_MARGIN_MS = 45e3;
127
125
  /**
128
126
  * Pick the gap histogram for an idle period. Return chances differ most by
129
127
  * who started the Turn and by how many Turns the Conversation had before it.
130
128
  * Turns that no person started rarely get a quick reply. In 30 days of
131
129
  * production data, segments by these two keys saved more than one histogram.
132
130
  * Local time of day did not improve the result, so it is not a key.
131
+ *
132
+ * The work state lets the histograms learn how often anything returns after
133
+ * the work is done. An event does not restore an archived Conversation, so
134
+ * most returns to one are events, not people. Its segment has only the work
135
+ * state, which keeps the number of segments small.
133
136
  */
134
- function gapSegment(userActor, endedTurns) {
135
- return `${userActor ? "user" : "system"}:${endedTurns === 0 ? "1" : endedTurns < 3 ? "2-3" : "4+"}`;
137
+ function gapSegment(input) {
138
+ if (input.archived) return `archived:${input.workState}`;
139
+ const depth = input.endedTurns === 0 ? "1" : input.endedTurns < 3 ? "2-3" : "4+";
140
+ return `${input.userActor ? "user" : "system"}:${depth}:${input.workState}`;
136
141
  }
137
142
  /**
138
143
  * Decide whether to send the next warmup.
@@ -155,7 +160,7 @@ function decideWarmup(input) {
155
160
  const global = histogramOf(input.globalGapsMs);
156
161
  const histogram = blendHistograms(conversation, global);
157
162
  const probability = returnProbability(histogram, input.idleMs, Math.min(input.cacheTtlMs, IDLE_HORIZON_MS - input.idleMs));
158
- const perWarmup = returnsPerWarmup(histogram, input.idleMs, input.cacheExpiryIdleMs, input.cacheTtlMs, input.prefixTokens);
163
+ const perWarmup = returnsPerWarmup(histogram, input.idleMs, input.cacheExpiryIdleMs, input.cacheTtlMs);
159
164
  const decision = (reason) => ({
160
165
  warm: reason === "warm",
161
166
  reason,
@@ -169,9 +174,9 @@ function decideWarmup(input) {
169
174
  if (conversation.total + global.total < MIN_GAP_SAMPLES) return decision("few_gaps");
170
175
  return decision(perWarmup >= threshold ? "warm" : "unlikely_return");
171
176
  }
172
- function returnsPerWarmup(histogram, idleMs, cacheExpiryIdleMs, ttlMs, prefixTokens) {
177
+ function returnsPerWarmup(histogram, idleMs, cacheExpiryIdleMs, ttlMs) {
173
178
  const now = survival(histogram, idleMs);
174
- const intervalMs = ttlMs - warmupMarginMs(prefixTokens);
179
+ const intervalMs = ttlMs - WARMUP_MARGIN_MS;
175
180
  if (now < .001 || intervalMs <= 0) return 0;
176
181
  const leftAtExpiry = survival(histogram, Math.min(cacheExpiryIdleMs, IDLE_HORIZON_MS));
177
182
  let best = 0;
@@ -230,11 +235,11 @@ function cachedPrefixTokens(message) {
230
235
  * Return when the cache that a request at `requestStartedAtMs` read or wrote
231
236
  * expires, and the delay until the warmup that refreshes it.
232
237
  */
233
- function warmupTiming(requestStartedAtMs, prefixTokens, ttlMs) {
238
+ function warmupTiming(requestStartedAtMs, ttlMs) {
234
239
  const cacheExpiresAtMs = requestStartedAtMs + ttlMs;
235
240
  return {
236
241
  cacheExpiresAtMs,
237
- delayMs: cacheExpiresAtMs - warmupMarginMs(prefixTokens) - Date.now()
242
+ delayMs: cacheExpiresAtMs - WARMUP_MARGIN_MS - Date.now()
238
243
  };
239
244
  }
240
245
  const LATE_WARMUP_MS = 1e4;
@@ -327,7 +332,7 @@ function createToolWaitWarmer(conversationId) {
327
332
  let generation = 0;
328
333
  const schedule = (cache, refreshedAtMs, cycle) => {
329
334
  const current = generation;
330
- const { cacheExpiresAtMs, delayMs } = warmupTiming(refreshedAtMs, cache.prefixTokens, cache.ttlMs);
335
+ const { cacheExpiresAtMs, delayMs } = warmupTiming(refreshedAtMs, cache.ttlMs);
331
336
  timer = setTimeout(() => {
332
337
  timer = void 0;
333
338
  warm(cache, cacheExpiresAtMs, cycle, current);
@@ -336,29 +341,36 @@ function createToolWaitWarmer(conversationId) {
336
341
  };
337
342
  const warm = (cache, cacheExpiresAtMs, cycle, current) => {
338
343
  const { request, prefixTokens } = cache;
339
- return runWithLogContext({
344
+ const attributes = {
345
+ "app.cache_warming.cycle": cycle,
346
+ "app.cache_warming.prefix_tokens": prefixTokens,
347
+ "app.cache_warming.trigger": "tool_wait"
348
+ };
349
+ return withSpan("cache_warming.warmup", "cache_warming.warmup", {
340
350
  conversationId,
341
351
  modelId: request.model.id
342
- }, {}, async () => {
343
- const attributes = {
344
- "app.cache_warming.cycle": cycle,
345
- "app.cache_warming.prefix_tokens": prefixTokens,
346
- "app.cache_warming.trigger": "tool_wait"
347
- };
348
- if (warmupTooLate(cacheExpiresAtMs)) {
352
+ }, async (setSpanAttributes) => {
353
+ const setOutcome = (outcome, extra = {}) => setSpanAttributes({
354
+ ...attributes,
355
+ ...extra,
356
+ "app.cache_warming.outcome": outcome
357
+ });
358
+ const skip = (reason) => {
359
+ const skipReason = { "app.cache_warming.skip_reason": reason };
349
360
  logInfo("cache_warming.warmup.skipped", {
350
361
  ...attributes,
351
- "app.cache_warming.skip_reason": "cache_expired"
362
+ ...skipReason
352
363
  });
364
+ setOutcome("skipped", skipReason);
365
+ };
366
+ if (warmupTooLate(cacheExpiresAtMs)) {
367
+ skip("cache_expired");
353
368
  return;
354
369
  }
355
370
  try {
356
371
  const state = await connectedState();
357
372
  if (await breakerOpen(state, request.model.id)) {
358
- logInfo("cache_warming.warmup.skipped", {
359
- ...attributes,
360
- "app.cache_warming.skip_reason": "breaker_open"
361
- });
373
+ skip("breaker_open");
362
374
  return;
363
375
  }
364
376
  const decision = decideWarmup({
@@ -374,12 +386,12 @@ function createToolWaitWarmer(conversationId) {
374
386
  attributes["app.cache_warming.return_probability"] = decision.returnProbability;
375
387
  attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
376
388
  attributes["app.cache_warming.threshold"] = decision.threshold;
377
- if (current !== generation) return;
389
+ if (current !== generation) {
390
+ setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
391
+ return;
392
+ }
378
393
  if (!decision.warm) {
379
- logInfo("cache_warming.warmup.skipped", {
380
- ...attributes,
381
- "app.cache_warming.skip_reason": decision.reason
382
- });
394
+ skip(decision.reason);
383
395
  return;
384
396
  }
385
397
  const startedAtMs = Date.now();
@@ -393,17 +405,21 @@ function createToolWaitWarmer(conversationId) {
393
405
  Object.assign(attributes, warmup.attributes);
394
406
  if (!warmup.refreshed) {
395
407
  logWarn("cache_warming.warmup.failed", attributes);
408
+ setOutcome("missed");
396
409
  return;
397
410
  }
398
411
  logInfo("cache_warming.warmup.completed", attributes);
412
+ setOutcome("completed");
399
413
  if (current === generation) schedule(cache, startedAtMs, cycle + 1);
400
414
  } catch (error) {
401
415
  logWarn("cache_warming.warmup.failed", {
402
416
  ...attributes,
403
417
  "exception.message": error instanceof Error ? error.message : String(error)
404
418
  });
419
+ setOutcome("failed", { "error.type": error instanceof Error ? error.name : typeof error });
420
+ setSpanStatus("error");
405
421
  }
406
- });
422
+ }, attributes);
407
423
  };
408
424
  const stop = () => {
409
425
  generation += 1;
@@ -452,6 +468,162 @@ function createToolWaitWarmer(conversationId) {
452
468
  }
453
469
  };
454
470
  }
471
+ // src/api/conversations/user-message-activity.ts
472
+ /**
473
+ * The newest event of one type in the outer Conversation that matches the
474
+ * filter. It walks the message role or user message time index from the
475
+ * newest event. The user message index has only matching entries, so that
476
+ * read stops at the first one.
477
+ */
478
+ function latestEventAt(db, type, filter) {
479
+ return db.select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, type), filter)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1).as(`latest_${type}`);
480
+ }
481
+ /** Read the latest true user message time for each selected conversation. */
482
+ async function readLastUserMessageAtByConversation(db, conversationIds) {
483
+ if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
484
+ const payload = juniorConversationEvents.payload;
485
+ const instruction = latestEventAt(db, "user_message", isUserInstruction(payload));
486
+ const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
487
+ const message = latestEventAt(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`);
488
+ const rows = await db.select({
489
+ conversationId: juniorConversations.conversationId,
490
+ instructionAt: instruction.createdAt,
491
+ messageAt: message.createdAt
492
+ }).from(juniorConversations).leftJoinLateral(instruction, sql`true`).leftJoinLateral(message, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
493
+ const result = /* @__PURE__ */ new Map();
494
+ for (const { conversationId, instructionAt, messageAt } of rows) {
495
+ const times = [instructionAt, messageAt].flatMap((at) => at ? [at.getTime()] : []);
496
+ if (times.length > 0) result.set(conversationId, new Date(Math.max(...times)).toISOString());
497
+ }
498
+ return result;
499
+ }
500
+ // src/chat/plugins/unfinished-work.ts
501
+ /**
502
+ * Decide whether a conversation's work finished at or before the cutoff,
503
+ * with no person's message after it finished. Auto-archive passes now minus
504
+ * the grace period. A conversation without plugin-reported work has nothing
505
+ * to wait for, so it counts as done here; cache warming needs reported work
506
+ * and checks `assignedWork` itself.
507
+ */
508
+ function isConversationWorkDone(conversation, cutoffMs) {
509
+ if (conversation.unfinishedWork) return false;
510
+ if (!conversation.assignedWork) return true;
511
+ const finishedAt = Date.parse(conversation.finishedWorkAt ?? "");
512
+ if (!Number.isFinite(finishedAt) || finishedAt > cutoffMs) return false;
513
+ const lastUserMessageAt = Date.parse(conversation.lastUserMessageAt ?? "");
514
+ return !(Number.isFinite(lastUserMessageAt) && lastUserMessageAt > finishedAt);
515
+ }
516
+ /**
517
+ * Map each candidate and each child of a candidate root to the candidate it
518
+ * counts for. A child agent runs under its own conversation id, so a plugin
519
+ * links the work that the child does, such as a pull request, to the child.
520
+ */
521
+ async function readWorkOwners(conversationIds) {
522
+ const owners = new Map(conversationIds.map((id) => [id, id]));
523
+ const children = await getDb().select({
524
+ conversationId: juniorConversations.conversationId,
525
+ rootConversationId: juniorConversations.rootConversationId
526
+ }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, conversationIds));
527
+ for (const child of children) if (child.rootConversationId && !owners.has(child.conversationId)) owners.set(child.conversationId, child.rootConversationId);
528
+ return owners;
529
+ }
530
+ /**
531
+ * Return assigned and unfinished plugin work for the candidate conversations.
532
+ * Work in a child conversation counts for its root candidate. Feed Priority
533
+ * combines these signals with conversation activity on the host.
534
+ */
535
+ async function listConversationWork(conversationIds) {
536
+ if (conversationIds.length === 0) return {
537
+ assignedIds: [],
538
+ failed: false,
539
+ finishedAtById: {},
540
+ unfinishedIds: []
541
+ };
542
+ const owners = await readWorkOwners(conversationIds);
543
+ const queriedIds = [...owners.keys()];
544
+ const assigned = /* @__PURE__ */ new Set();
545
+ const finishedAtById = /* @__PURE__ */ new Map();
546
+ const unfinished = /* @__PURE__ */ new Set();
547
+ let failed = false;
548
+ for (const plugin of getPlugins()) {
549
+ const hook = plugin.hooks?.unfinishedWork;
550
+ if (!hook) continue;
551
+ try {
552
+ const result = await hook({
553
+ conversationIds: queriedIds,
554
+ db: getDb(),
555
+ log: createPluginLogger(plugin.manifest.name),
556
+ plugin: { name: plugin.manifest.name },
557
+ cache: createPluginCache(plugin.manifest.name)
558
+ });
559
+ for (const workId of result.conversationIds) {
560
+ const conversationId = owners.get(workId);
561
+ if (!conversationId) continue;
562
+ unfinished.add(conversationId);
563
+ assigned.add(conversationId);
564
+ }
565
+ for (const workId of result.assignedConversationIds ?? []) {
566
+ const conversationId = owners.get(workId);
567
+ if (conversationId) assigned.add(conversationId);
568
+ }
569
+ for (const [workId, finishedAt] of Object.entries(result.finishedWorkAtByConversationId ?? {})) {
570
+ const conversationId = owners.get(workId);
571
+ if (!conversationId) continue;
572
+ const time = Date.parse(finishedAt);
573
+ if (!Number.isFinite(time)) continue;
574
+ const current = finishedAtById.get(conversationId);
575
+ if (!current || time > Date.parse(current)) finishedAtById.set(conversationId, finishedAt);
576
+ }
577
+ } catch (error) {
578
+ failed = true;
579
+ logWarn("plugin.unfinished_work.hook.failed", {
580
+ "app.plugin.name": plugin.manifest.name,
581
+ "exception.message": error instanceof Error ? error.message : String(error)
582
+ });
583
+ }
584
+ }
585
+ return {
586
+ assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
587
+ failed,
588
+ finishedAtById: Object.fromEntries(conversationIds.flatMap((conversationId) => {
589
+ const finishedAt = finishedAtById.get(conversationId);
590
+ return finishedAt ? [[conversationId, finishedAt]] : [];
591
+ })),
592
+ unfinishedIds: conversationIds.filter((conversationId) => unfinished.has(conversationId))
593
+ };
594
+ }
595
+ // src/chat/cache-warming/work-state.ts
596
+ /**
597
+ * Read the plugin work state and the archive state of a Conversation when an
598
+ * idle period starts that Junior can warm. Work of child Conversations counts
599
+ * for their root. A child counts as archived when it or its root is: a manual
600
+ * archive also archives the children, but auto-archive sets only the root.
601
+ */
602
+ async function readSegmentState(conversationId, nowMs) {
603
+ const [work, conversation, rootArchived] = await Promise.all([
604
+ listConversationWork([conversationId]),
605
+ getConversationStore().get({ conversationId }),
606
+ rootConversationIsArchived(getSqlExecutor(), conversationId)
607
+ ]);
608
+ const archived = rootArchived || conversation?.archivedAtMs !== void 0;
609
+ if (work.failed || !work.assignedIds.includes(conversationId)) return {
610
+ workState: "none",
611
+ archived
612
+ };
613
+ if (work.unfinishedIds.includes(conversationId)) return {
614
+ workState: "open",
615
+ archived
616
+ };
617
+ const lastUserMessageAt = (await readLastUserMessageAtByConversation(getDb(), [conversationId])).get(conversationId);
618
+ return {
619
+ workState: isConversationWorkDone({
620
+ assignedWork: true,
621
+ finishedWorkAt: work.finishedAtById[conversationId],
622
+ lastUserMessageAt
623
+ }, nowMs) ? "done" : "none",
624
+ archived
625
+ };
626
+ }
455
627
  // src/chat/cache-warming/warmup.ts
456
628
  /**
457
629
  * Prompt cache warming for idle Conversations.
@@ -504,8 +676,12 @@ const snapshotKey = (conversationId, generation) => `${KEY_PREFIX}:snapshot:${co
504
676
  const warmupsKey = (conversationId, generation) => `${KEY_PREFIX}:warmups:${conversationId}:${generation}`;
505
677
  /** Set by the first of the reply and the horizon to record the gap. */
506
678
  const gapClaimKey = (conversationId, generation) => `${KEY_PREFIX}:gap_claim:${conversationId}:${generation}`;
679
+ const segmentAttributes = (warm) => ({
680
+ "app.cache_warming.work_state": warm.workState,
681
+ "app.cache_warming.archived": warm.archived
682
+ });
507
683
  async function scheduleWarmup(message, requestStartedAtMs, warm) {
508
- const { cacheExpiresAtMs, delayMs } = warmupTiming(requestStartedAtMs, warm.prefixTokens, warm.cacheTtlMs);
684
+ const { cacheExpiresAtMs, delayMs } = warmupTiming(requestStartedAtMs, warm.cacheTtlMs);
509
685
  await sendCacheWarmup({
510
686
  ...message,
511
687
  cacheExpiresAtMs
@@ -523,21 +699,20 @@ function snapshotContext(context) {
523
699
  })) } : void 0
524
700
  };
525
701
  }
526
- async function recordGap(state, conversationId, idle, gapMs) {
527
- if (!await state.setIfNotExists(gapClaimKey(conversationId, idle.generation), true, CONVERSATION_STATE_TTL_MS)) return;
528
- await state.appendToList(segmentGapsKey(idle.segment), gapMs, {
702
+ async function recordGap(state, conversationId, generation, warm, gapMs) {
703
+ if (!await state.setIfNotExists(gapClaimKey(conversationId, generation), true, CONVERSATION_STATE_TTL_MS)) return;
704
+ await state.appendToList(segmentGapsKey(warm.segment), gapMs, {
529
705
  maxLength: GLOBAL_GAPS_MAX,
530
706
  ttlMs: GLOBAL_GAPS_TTL_MS
531
707
  });
532
- await state.appendToList(conversationGapsKey(conversationId, idle.segment), gapMs, {
708
+ await state.appendToList(conversationGapsKey(conversationId, warm.segment), gapMs, {
533
709
  maxLength: CONVERSATION_GAPS_MAX,
534
710
  ttlMs: CONVERSATION_STATE_TTL_MS
535
711
  });
536
712
  }
537
- async function startIdlePeriod(state, conversationId, request, message, segment) {
713
+ async function startIdlePeriod(state, conversationId, request, message, turn) {
538
714
  const idle = {
539
715
  generation: randomUUID(),
540
- segment,
541
716
  sinceMs: request.startedAtMs
542
717
  };
543
718
  const prefixTokens = cachedPrefixTokens(message);
@@ -551,10 +726,16 @@ async function startIdlePeriod(state, conversationId, request, message, segment)
551
726
  });
552
727
  return idle;
553
728
  }
729
+ const segmentState = await readSegmentState(conversationId, Date.now());
554
730
  await state.set(snapshotKey(conversationId, idle.generation), snapshot, IDLE_HORIZON_MS);
555
731
  return {
556
732
  ...idle,
557
733
  warm: {
734
+ segment: gapSegment({
735
+ ...turn,
736
+ ...segmentState
737
+ }),
738
+ ...segmentState,
558
739
  modelId: request.model.id,
559
740
  prefixTokens,
560
741
  cacheTtlMs: ttlMs,
@@ -568,13 +749,14 @@ async function recordModelCall(conversationId, userActor, request, message) {
568
749
  const idle = previous?.idle;
569
750
  if (idle?.warm) {
570
751
  const gapMs = request.startedAtMs - idle.sinceMs;
571
- if (gapMs > 0) await recordGap(state, conversationId, idle, gapMs);
752
+ if (gapMs > 0) await recordGap(state, conversationId, idle.generation, idle.warm, gapMs);
572
753
  await state.delete(snapshotKey(conversationId, idle.generation));
573
754
  const warmups = await state.get(warmupsKey(conversationId, idle.generation)) ?? 0;
574
755
  if (warmups > 0) logInfo("cache_warming.conversation.returned", {
575
756
  "app.cache_warming.gap_ms": gapMs,
576
757
  "app.cache_warming.prefix_tokens": idle.warm.prefixTokens,
577
758
  "app.cache_warming.warmup_count": warmups,
759
+ ...segmentAttributes(idle.warm),
578
760
  "gen_ai.usage.cache_read.input_tokens": message.usage.cacheRead,
579
761
  "gen_ai.usage.cache_creation.input_tokens": message.usage.cacheWrite
580
762
  });
@@ -582,7 +764,10 @@ async function recordModelCall(conversationId, userActor, request, message) {
582
764
  const endedTurns = previous?.endedTurns ?? 0;
583
765
  const next = message.stopReason === "stop" ? {
584
766
  endedTurns: endedTurns + 1,
585
- idle: await startIdlePeriod(state, conversationId, request, message, gapSegment(userActor, endedTurns))
767
+ idle: await startIdlePeriod(state, conversationId, request, message, {
768
+ userActor,
769
+ endedTurns
770
+ })
586
771
  } : { endedTurns };
587
772
  if (!idle && !next.idle) return;
588
773
  await state.set(conversationKey(conversationId), next, CONVERSATION_STATE_TTL_MS);
@@ -682,40 +867,47 @@ async function runCacheWarmup(message) {
682
867
  const stop = () => state.delete(snapshotKey(conversationId, generation));
683
868
  if (message.kind === "horizon") {
684
869
  await stop();
685
- await recordGap(state, conversationId, idle, NO_REPLY_GAP_MS);
870
+ await recordGap(state, conversationId, generation, warm, NO_REPLY_GAP_MS);
686
871
  return;
687
872
  }
688
873
  if ((await state.get(warmupsKey(conversationId, generation)) ?? 0) !== message.cycle - 1) return;
689
- await runWithLogContext({
874
+ const attributes = {
875
+ "app.cache_warming.cycle": message.cycle,
876
+ "app.cache_warming.prefix_tokens": warm.prefixTokens,
877
+ "app.cache_warming.trigger": "idle",
878
+ ...segmentAttributes(warm),
879
+ "app.cache_warming.cache_ttl_left_ms": message.cacheExpiresAtMs - Date.now()
880
+ };
881
+ await withSpan("cache_warming.warmup", "cache_warming.warmup", {
690
882
  conversationId,
691
883
  modelId: warm.modelId
692
- }, {}, async () => {
693
- const attributes = {
694
- "app.cache_warming.cycle": message.cycle,
695
- "app.cache_warming.prefix_tokens": warm.prefixTokens,
696
- "app.cache_warming.trigger": "idle",
697
- "app.cache_warming.cache_ttl_left_ms": message.cacheExpiresAtMs - Date.now()
698
- };
699
- if (warmupTooLate(message.cacheExpiresAtMs)) {
884
+ }, async (setSpanAttributes) => {
885
+ const setOutcome = (outcome, extra = {}) => setSpanAttributes({
886
+ ...attributes,
887
+ ...extra,
888
+ "app.cache_warming.outcome": outcome
889
+ });
890
+ const skip = async (reason) => {
891
+ const skipReason = { "app.cache_warming.skip_reason": reason };
700
892
  logInfo("cache_warming.warmup.skipped", {
701
893
  ...attributes,
702
- "app.cache_warming.skip_reason": "cache_expired"
894
+ ...skipReason
703
895
  });
896
+ setOutcome("skipped", skipReason);
704
897
  await stop();
898
+ };
899
+ if (warmupTooLate(message.cacheExpiresAtMs)) {
900
+ await skip("cache_expired");
705
901
  return;
706
902
  }
707
903
  if (await breakerOpen(state, warm.modelId)) {
708
- logInfo("cache_warming.warmup.skipped", {
709
- ...attributes,
710
- "app.cache_warming.skip_reason": "breaker_open"
711
- });
712
- await stop();
904
+ await skip("breaker_open");
713
905
  return;
714
906
  }
715
907
  const model = resolveGatewayModel(warm.modelId);
716
908
  const decision = decideWarmup({
717
- conversationGapsMs: await state.getList(conversationGapsKey(conversationId, idle.segment)),
718
- globalGapsMs: await state.getList(segmentGapsKey(idle.segment)),
909
+ conversationGapsMs: await state.getList(conversationGapsKey(conversationId, warm.segment)),
910
+ globalGapsMs: await state.getList(segmentGapsKey(warm.segment)),
719
911
  idleMs: Date.now() - idle.sinceMs,
720
912
  cacheExpiryIdleMs: message.cacheExpiresAtMs - idle.sinceMs,
721
913
  cacheTtlMs: warm.cacheTtlMs,
@@ -727,15 +919,14 @@ async function runCacheWarmup(message) {
727
919
  attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
728
920
  attributes["app.cache_warming.threshold"] = decision.threshold;
729
921
  if (!decision.warm) {
730
- logInfo("cache_warming.warmup.skipped", {
731
- ...attributes,
732
- "app.cache_warming.skip_reason": decision.reason
733
- });
734
- await stop();
922
+ await skip(decision.reason);
735
923
  return;
736
924
  }
737
925
  const snapshot = await state.get(snapshotKey(conversationId, generation));
738
- if (!snapshot) return;
926
+ if (!snapshot) {
927
+ setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
928
+ return;
929
+ }
739
930
  const context = JSON.parse((await zstdDecompress$1(Buffer.from(snapshot, "base64"))).toString("utf8"));
740
931
  const startedAtMs = Date.now();
741
932
  const warmup = await sendWarmup(state, {
@@ -745,16 +936,19 @@ async function runCacheWarmup(message) {
745
936
  ...warm.reasoning ? { reasoning: warm.reasoning } : void 0,
746
937
  prefixTokens: warm.prefixTokens
747
938
  }).catch(async (error) => {
939
+ setOutcome("failed");
748
940
  await stop();
749
941
  throw error;
750
942
  });
751
943
  Object.assign(attributes, warmup.attributes);
752
944
  if (!warmup.refreshed) {
753
945
  logWarn("cache_warming.warmup.failed", attributes);
946
+ setOutcome("missed");
754
947
  await stop();
755
948
  return;
756
949
  }
757
950
  logInfo("cache_warming.warmup.completed", attributes);
951
+ setOutcome("completed");
758
952
  await state.set(warmupsKey(conversationId, generation), message.cycle, IDLE_HORIZON_MS);
759
953
  if (await state.get(snapshotKey(conversationId, generation))) await scheduleWarmup({
760
954
  kind: "warmup",
@@ -762,6 +956,6 @@ async function runCacheWarmup(message) {
762
956
  cycle: message.cycle + 1,
763
957
  generation
764
958
  }, startedAtMs, warm);
765
- });
959
+ }, attributes);
766
960
  }
767
- export { segmentGapsKey as a, MINUTE_MS as c, gapSegment as d, createCacheWarmingRecorder as i, MIN_WARMUP_PREFIX_TOKENS as l, GLOBAL_GAPS_MAX as n, warmup_exports as o, GLOBAL_GAPS_TTL_MS as r, IDLE_HORIZON_MS as s, CONVERSATION_STATE_TTL_MS as t, NO_REPLY_GAP_MS as u };
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 };
@@ -1,15 +1,15 @@
1
- import { Cn as renderTag, U as PluginCredentialFailureError, Zt as isTurnExecutionLimitExceededError, fo as loadForkHistory, it as abandonTurnRecord, nn as getTerminalAssistantMessages, nt as pauseLostWorkerTurn, ot as failTurnRecord, q as AuthorizationFlowDisabledError, rt as saveTurnCheckpoint, s as openConversationProjection, st as getTurnRecord, tt as lostWorkerBeforeFirstSave, v as hydrateConversationMessages, yn as escapeClosingTags } from "./projection-BViECfYu.js";
2
- import { n as botConfig } from "./config-CLJcyYEF.js";
3
- import { T as SYSTEM_IDENTITY_ID, a as getConversationStore, r as getConversationEventStore, s as getSqlExecutor } from "./db-Co7DTYYh.js";
4
- import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-m0kIN71Q.js";
5
- import { d as contextProvenance, m as sameActorIdentity, u as agentInstructionProvenance } from "./history-IjdmO_r6.js";
6
- import { At as recordSubagentStarted, Ft as executeTurn, Gt as AgentMessageQueueFullError, It as finishTurn, Nt as supersedeOpenMailboxTurns, Ot as stopChildAgentsOf, Pt as AgentRunError, Ut as AgentInvocationLimitError, kt as recordSubagentEnded, qt as AgentNameInUseError } from "./agent-runner-9MXyWUL8.js";
7
- import { k as getTurnRequestDeadline } from "./background-compaction-queue-CjllSPir.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-CpdPoZSl.js";
9
- import { n as getAssistantReplyText } from "./assistant-reply-mj47jMRV.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-BWOsuo8p.js";
11
- import { r as appendAndEnqueueInboundMessage } from "./store-ByR1Lr7e.js";
12
- import { _t as getPersistedThreadState, bt as coerceThreadConversationState, gt as getPersistedSandboxState, yt as persistThreadStateById } from "./task-runner-B-Ewf8TX.js";
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-D-9aVaHj.js";
2
+ import { n as botConfig } from "./config-DHDub41t.js";
3
+ import { T as SYSTEM_IDENTITY_ID, a as getConversationStore, r as getConversationEventStore, s as getSqlExecutor } from "./db-DBHig2sI.js";
4
+ import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-DKrtH0k_.js";
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-CZjf6MOQ.js";
7
+ import { k as getTurnRequestDeadline } from "./background-compaction-queue-2gKhjRD3.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-hhpek6Fn.js";
9
+ import { n as getAssistantReplyText } from "./assistant-reply-BtIV0hq6.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-1cku9Vm3.js";
11
+ import { r as appendAndEnqueueInboundMessage } from "./store-CK869JpC.js";
12
+ import { _t as persistThreadStateById, ht as getPersistedThreadState, mt as getPersistedSandboxState, vt as coerceThreadConversationState } from "./task-runner-XmXL9E-k.js";
13
13
  import { isDeepStrictEqual } from "node:util";
14
14
  import * as z from "zod";
15
15
  import { and, eq } from "drizzle-orm";
@@ -303,7 +303,7 @@ function buildAgentInvocationInboundMessage(invocation, nowMs = Date.now()) {
303
303
  /** Append one invocation to its child mailbox and send the normal queue wake. */
304
304
  async function enqueueAgentInvocation(invocation, options) {
305
305
  if (invocation.mailboxStatus === "appended" || isTerminalAgentInvocation(invocation)) return;
306
- await recordSubagentStarted(invocation);
306
+ await recordSubagentStarted(invocation, options.eventMeta);
307
307
  if (invocation.parentToolCallId !== void 0) await resumeStoppedConversationTree(invocation.childConversationId, invocation.createdAtMs);
308
308
  const nowMs = options.nowMs ?? Date.now();
309
309
  await appendAndEnqueueInboundMessage({
@@ -570,7 +570,7 @@ async function saveAgentInvocationResult(args) {
570
570
  errorMessage: args.result.blocked.missing,
571
571
  status: "blocked"
572
572
  } : {
573
- result: args.result.text,
573
+ result: args.result.text || (args.result.noReply?.note ?? ""),
574
574
  status: "completed"
575
575
  }
576
576
  });