@sentry/junior 0.285.0 → 0.287.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 (78) hide show
  1. package/dist/{adapter-DN5AB4VU.js → adapter-CL-HUKgd.js} +1 -1
  2. package/dist/{admin-DOITMKnn.js → admin-C9urXVfi.js} +2 -1
  3. package/dist/{agent-runner-BsWhHe4N.js → agent-runner-Bfnw551N.js} +2174 -1323
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +73 -112
  8. package/dist/{app-DyMs9330.d.ts → app-DBY5TnfY.d.ts} +2 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +72 -42
  11. package/dist/{assistant-reply-9Jip5bsr.js → assistant-reply-u_PRYzuz.js} +1 -1
  12. package/dist/{automation-Mk8aaHzy.js → automation-DksGNDRO.js} +3 -6
  13. package/dist/{background-compaction-queue-DXkLsWoH.js → background-compaction-queue-CYI909P5.js} +137 -3
  14. package/dist/{briefs-Cl8-nK9B.js → briefs-DaXiMWzT.js} +6 -5
  15. package/dist/{catalog-runtime-Bte6jRB2.js → catalog-runtime-BCIuBe4d.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 +5 -6
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{client-DDbBucBw.js → config-CkHcUMN7.js} +580 -3
  24. package/dist/{connections-DA4LT9LL.js → connections-BnIj0wtx.js} +16 -50
  25. package/dist/{conversation-D8kVoCrP.js → conversation-E7ZPJx2H.js} +22 -6
  26. package/dist/{conversation-pending-messages-BvROq1bq.js → conversation-pending-messages-DVch6YQw.js} +2 -5
  27. package/dist/{conversation-privacy-D0j_h70R.js → conversation-privacy-DF1hW0ja.js} +1 -1
  28. package/dist/{credential-sync-hcsYatw-.js → credential-sync-CzMar9hq.js} +13 -13
  29. package/dist/{viewer-1Ea81s0b.js → db-DJ11eZqq.js} +64 -367
  30. package/dist/{db-BhHZSuFw.d.ts → db-YDKKDxlh.d.ts} +4 -4
  31. package/dist/{executor-BLEMIgIZ.js → executor-BY9TB31g.js} +20 -19
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BfORLKoq.js → logging-BO5zU6Mt.js} +1 -1
  34. package/dist/{media-Bu9C6lz0.js → media-Cz1ZiV1U.js} +16 -4
  35. package/dist/{message-DqjuKzUx.js → message-CsUbuEc8.js} +10 -10
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +2 -3
  38. package/dist/{oauth-callback-server-CFSRzu1n.js → oauth-callback-server-hiDKK0_n.js} +2 -2
  39. package/dist/{projection-DliWYrnT.js → projection-CL_YWeGf.js} +352 -356
  40. package/dist/{prompt-BvIUzY4y.js → prompt-BHOEQSmf.js} +182 -2
  41. package/dist/{registry-rC7MCxu8.js → registry-BriFLnaJ.js} +1 -1
  42. package/dist/{reporting-window-B4TwyuJo.js → reporting-window-B3Ze-Qnt.js} +4 -1
  43. package/dist/{resolve-Biu8Qw3u.js → resolve-Bt6GgAiA.js} +3 -3
  44. package/dist/{result-DxJMCX47.js → result-Bo1TZu0Q.js} +8 -8
  45. package/dist/{runner-BQJSFLKg.js → runner-D3YeCQgt.js} +16 -12
  46. package/dist/{sandbox-egress-signals-6aMxJSDn.js → sandbox-egress-signals-CcnSPP4S.js} +1 -1
  47. package/dist/{schema-BasXTvi2.js → schema-BWE3RJEB.js} +19 -7
  48. package/dist/{schema-BUviRAs8.d.ts → schema-C6fsEwjo.d.ts} +90 -8
  49. package/dist/{service-account-BI5Wgx22.js → service-account-DiQQuuw7.js} +3 -3
  50. package/dist/{service-account-CAE-_1dR.js → service-account-r6fl0b-9.js} +3 -3
  51. package/dist/{session-stop-CA-jOJ84.js → session-stop-B2Nut40V.js} +27 -25
  52. package/dist/{skills-B22duVJU.js → skills-CD5aJdzg.js} +2 -2
  53. package/dist/spawn-CalgZQiu.js +79 -0
  54. package/dist/{stop-DioIcEAu.js → stop-kujZLbi0.js} +233 -1127
  55. package/dist/{store-Dn4W7qgH.js → store-DdIEUL1q.js} +3 -3
  56. package/dist/{turn-session-routing-CGMKrYOj.js → task-runner-D_RDr2Hu.js} +1440 -993
  57. package/dist/{store-B26LV6UP.js → turn-failure-response-B5nV1Er-.js} +337 -6
  58. package/dist/{validation-TzhfQABF.js → validation-K4pqwoVZ.js} +1 -1
  59. package/dist/{version-DSk8CFvA.js → version-DBvhk1X9.js} +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/viewer-DrMmFUul.js +337 -0
  62. package/dist/{work-ybG4_q5C.js → work-ljRoODGu.js} +110 -94
  63. package/dist/{worker-ccSyZRNz.js → worker-CYO1Q0Js.js} +5 -6
  64. package/migrations/0086_shared_archive.sql +31 -0
  65. package/migrations/0087_child_location.sql +64 -0
  66. package/migrations/0088_conversation_unsubscribe.sql +1 -0
  67. package/migrations/meta/0086_snapshot.json +4366 -0
  68. package/migrations/meta/0087_snapshot.json +4366 -0
  69. package/migrations/meta/0088_snapshot.json +4372 -0
  70. package/migrations/meta/_journal.json +21 -0
  71. package/package.json +5 -4
  72. package/dist/config-DqFnykQT.js +0 -579
  73. package/dist/spawn-BB2_4VYn.js +0 -31
  74. package/dist/task-queue-Bt0IoR2i.js +0 -139
  75. package/dist/task-runner-D8lddjzp.js +0 -290
  76. package/dist/thread-state-CrFk3K_7.js +0 -173
  77. package/dist/turn-failure-response-DaJ04qVj.js +0 -224
  78. package/dist/turn-lifecycle-C2mXS7AZ.js +0 -58
@@ -1,15 +1,15 @@
1
- import { $ as abandonTurnRecord, Gt as isTurnExecutionLimitExceededError, Q as saveTurnCheckpoint, U as AuthorizationFlowDisabledError, Xt as getTerminalAssistantMessages, gn as renderTag, go as loadForkHistory, nt as getTurnRecord, pn as escapeClosingTags, s as openConversationProjection, tt as failTurnRecord, z as PluginCredentialFailureError } from "./projection-DliWYrnT.js";
2
- import { n as botConfig } from "./config-DqFnykQT.js";
3
- import { C as getSqlExecutor, H as SYSTEM_IDENTITY_ID, x as getConversationStore, y as getConversationEventStore } from "./viewer-1Ea81s0b.js";
4
- import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-BLEMIgIZ.js";
5
- import { m as agentInstructionProvenance, v as sameActorIdentity } from "./media-Bu9C6lz0.js";
6
- import { Ct as recordSubagentEnded, Dt as AgentMessageQueueFullError, Lt as readConversationLineage, St as stopChildAgentsOf, Tt as AgentInvocationLimitError, kt as AgentNameInUseError, wt as recordSubagentStarted } from "./agent-runner-BsWhHe4N.js";
7
- import { D as agentTypeStartsWithParentHistory, E as agentTypeInstructions, F as getAgentInvocationTurnId, H as TurnInputCommitLostError, I as getChildAgentLockName, K as isTurnInputCommitLostError, L as getNamedAgentConversationId, N as getAgentInvocationMessageId, R as getUnnamedAgentConversationId, S as agentBindingSchema, W as getConversationTurnBoundaryError, _ as markAgentInvocationRunning, a as getAgentInvocation, d as listOpenAgentInvocations, g as markAgentInvocationPaused, i as getActiveAgentInvocationForConversation, k as getAgentInvocationId, l as isTerminalAgentInvocation, m as markAgentInvocationMailboxAppended, n as NON_TERMINAL_AGENT_INVOCATION_STATUSES, r as completeAgentInvocation, s as getLatestAgentInvocationForConversation, t as ACTIVE_AGENT_INVOCATION_STATUSES, u as listAgentInvocationsForConversation, v as markAgentInvocationSteered, w as createAgentInvocationSchema, y as reportReplacedAgentInvocation } from "./store-B26LV6UP.js";
8
- import { n as getAssistantReplyText } from "./assistant-reply-9Jip5bsr.js";
9
- import { G as resetAutomatedTurnLimit, J as buildSteeringPiMessage, R as maybePostAutomatedTurnLimitNotice, W as recordFinishedTurnForAutomatedLimit, Y as instructionForInputs, Z as withoutSavedSteeringMessages, i as resumeStoppedConversationTree, rt as readBlockedReport } from "./session-stop-CA-jOJ84.js";
10
- import { r as appendAndEnqueueInboundMessage } from "./store-Dn4W7qgH.js";
11
- import { t as ConversationTurnLifecycleService } from "./turn-lifecycle-C2mXS7AZ.js";
12
- import { a as persistThreadStateById, n as getPersistedSandboxState, r as getPersistedThreadState } from "./thread-state-CrFk3K_7.js";
1
+ import { $ as pauseLostWorkerTurn, Q as lostWorkerBeforeFirstSave, Qt as getTerminalAssistantMessages, U as AuthorizationFlowDisabledError, et as saveTurnCheckpoint, hn as escapeClosingTags, it as getTurnRecord, qt as isTurnExecutionLimitExceededError, rt as failTurnRecord, s as openConversationProjection, tt as abandonTurnRecord, v as hydrateConversationMessages, yn as renderTag, yo as loadForkHistory, z as PluginCredentialFailureError } from "./projection-CL_YWeGf.js";
2
+ import { n as botConfig } from "./config-CkHcUMN7.js";
3
+ import { T as SYSTEM_IDENTITY_ID, a as getConversationStore, r as getConversationEventStore, s as getSqlExecutor } from "./db-DJ11eZqq.js";
4
+ import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-BY9TB31g.js";
5
+ import { h as contextProvenance, m as agentInstructionProvenance, v as sameActorIdentity } from "./media-Cz1ZiV1U.js";
6
+ import { At as recordSubagentStarted, Ft as finishTurn, Ht as AgentInvocationLimitError, Kt as AgentNameInUseError, Mt as supersedeOpenMailboxTurns, Nt as AgentRunError, Ot as stopChildAgentsOf, Pt as executeTurn, Wt as AgentMessageQueueFullError, kt as recordSubagentEnded } from "./agent-runner-Bfnw551N.js";
7
+ 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-B5nV1Er-.js";
8
+ import { n as getAssistantReplyText } from "./assistant-reply-u_PRYzuz.js";
9
+ import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, K as recordFinishedTurnForAutomatedLimit, X as buildSteeringPiMessage, Z as instructionForInputs, at as readBlockedReport, h as parseWebMessages, i as resumeStoppedConversationTree, p as listActiveMailboxTurns, q as resetAutomatedTurnLimit, u as getActiveConversationTurnId } from "./session-stop-B2Nut40V.js";
10
+ import { S as getTurnRequestDeadline } from "./background-compaction-queue-CYI909P5.js";
11
+ import { r as appendAndEnqueueInboundMessage } from "./store-DdIEUL1q.js";
12
+ import { _t as getPersistedThreadState, bt as coerceThreadConversationState, gt as getPersistedSandboxState, yt as persistThreadStateById } from "./task-runner-D_RDr2Hu.js";
13
13
  import { isDeepStrictEqual } from "node:util";
14
14
  import * as z from "zod";
15
15
  import { and, eq } from "drizzle-orm";
@@ -105,7 +105,8 @@ async function createAgentInvocation(rawInput, nowMs = Date.now()) {
105
105
  return await getSqlExecutor().withLock(lockName, async () => {
106
106
  const existing = await getAgentInvocation(invocationId);
107
107
  if (existing) {
108
- if (!sameCreateInput(existing, input)) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
108
+ const child = await getConversationStore().get({ conversationId: existing.childConversationId });
109
+ if (!sameCreateInput(existing, input) || child?.kind !== input.kind) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
109
110
  return existing;
110
111
  }
111
112
  const open = await listOpenAgentInvocations(input.parentConversationId);
@@ -120,7 +121,7 @@ async function createAgentInvocation(rawInput, nowMs = Date.now()) {
120
121
  });
121
122
  await getConversationStore().createChild({
122
123
  childConversationId,
123
- kind: "task",
124
+ kind: input.kind,
124
125
  parentConversationId: input.parentConversationId,
125
126
  nowMs,
126
127
  source: "internal"
@@ -222,50 +223,49 @@ async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
222
223
  };
223
224
  });
224
225
  }
225
- // src/chat/runtime/turn-execution.ts
226
- /** An error thrown while the agent advances a Run. */
227
- var AgentRunError = class extends Error {
228
- constructor(cause) {
229
- super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
230
- this.name = "AgentRunError";
231
- }
232
- };
226
+ // src/chat/agent-invocations/thread-turn.ts
233
227
  /**
234
- * Run the agent and finish the Turn after the caller saves its result.
235
- *
236
- * A paused Run, or a Run waiting for authorization, leaves the Turn open. A
237
- * save error also leaves the Turn open so the worker can retry or recover it.
228
+ * A person's Turn in a Thread. People message a Thread like a root, but it
229
+ * stays a child: only a root delivers to its Location, so replies stay in
230
+ * Junior. Agent invocation input and watch Events keep the child worker. A
231
+ * person's Turn and an Agent invocation Turn are never open at the same time.
238
232
  */
239
- async function executeTurn(agentRunner, run, saveResult) {
240
- let outcome;
241
- try {
242
- outcome = await agentRunner.run(run);
243
- } catch (error) {
244
- throw new AgentRunError(error);
245
- }
246
- if (outcome.status !== "completed") return outcome;
247
- const saved = await saveResult(outcome.result);
248
- await finishTurn(run.conversationId, run.turnId, saved);
249
- return { status: "completed" };
250
- }
251
- /** Record the terminal lifecycle event of a Turn from its saved result. */
252
- async function finishTurn(conversationId, turnId, saved) {
253
- const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
254
- const common = {
255
- conversationId,
256
- createdAtMs: saved.finishedAtMs ?? Date.now(),
257
- turnId
233
+ /**
234
+ * Select the person's Turn work of a Thread, or undefined for Agent
235
+ * invocation work. A Thread has one open Turn at a time, like a root. Web
236
+ * Messages start a person's Turn, and an empty wake resumes the open person's
237
+ * Turn. Every other input and wake goes to the child worker.
238
+ */
239
+ async function resolveThreadTurnWork(context) {
240
+ const batch = parseWebMessages(context.attempt.messages);
241
+ if (batch.length > 0) return {
242
+ kind: "mailbox",
243
+ batch
258
244
  };
259
- if (saved.outcome === "failed") await lifecycle.fail({
260
- ...common,
261
- ...saved.eventId ? { eventId: saved.eventId } : void 0,
262
- failureCode: saved.failureCode,
263
- ...saved.failureReason ? { failureReason: saved.failureReason } : void 0
245
+ if (context.attempt.messages.length > 0) return;
246
+ const turnId = await getActiveConversationTurnId(context.conversationId);
247
+ return turnId ? {
248
+ kind: "resume",
249
+ turnId
250
+ } : void 0;
251
+ }
252
+ /**
253
+ * End a person's open Turn in a Thread before an agent invocation starts, as
254
+ * new input does on a root. Only a Turn that waits for sign-in or lost its
255
+ * worker can be open here: a yielded Turn resumes before new input.
256
+ */
257
+ async function supersedeOpenPersonTurn(conversationId) {
258
+ if ((await listActiveMailboxTurns(conversationId)).length === 0) return;
259
+ const conversation = coerceThreadConversationState(await getPersistedThreadState(conversationId));
260
+ await hydrateConversationMessages({
261
+ conversation,
262
+ conversationId
264
263
  });
265
- else await lifecycle.complete({
266
- ...common,
267
- outcome: saved.outcome
264
+ await supersedeOpenMailboxTurns({
265
+ conversation,
266
+ conversationId
268
267
  });
268
+ await persistThreadStateById(conversationId, { conversation });
269
269
  }
270
270
  // src/chat/agent-invocations/work.ts
271
271
  const agentInvocationMailboxMetadataSchema = z.object({
@@ -343,6 +343,13 @@ function agentInvocationInputText(invocation) {
343
343
  const typeInstructions = agentTypeInstructions(invocation.agentType);
344
344
  return renderTag("parent-agent-task", {}, [...typeInstructions ? [escapeClosingTags(typeInstructions), ""] : [], escapeClosingTags(invocation.input)]);
345
345
  }
346
+ /**
347
+ * A parent agent task or message is the child's instruction. Another input,
348
+ * such as a result of the child's own child agent or an Event, is context.
349
+ */
350
+ function agentInvocationProvenance(invocation) {
351
+ return invocation.parentToolCallId ? agentInstructionProvenance : contextProvenance;
352
+ }
346
353
  /** Resolve invocation execution from mailbox input or durable active state. */
347
354
  async function resolveAgentInvocationId(context) {
348
355
  const mailboxInvocationId = invocationIdFromMessages(context.attempt.messages);
@@ -383,7 +390,7 @@ function createAgentMessageSteeringDrain(context, running) {
383
390
  const saved = (await getTurnRecord(running.childConversationId, turnId))?.piMessages ?? [];
384
391
  const messages = withoutSavedSteeringMessages(saved, joining.map((candidate) => ({
385
392
  kind: "runtime",
386
- provenance: agentInstructionProvenance,
393
+ provenance: agentInvocationProvenance(candidate),
387
394
  text: agentInvocationInputText(candidate),
388
395
  timestampMs: candidate.createdAtMs
389
396
  })), buildSteeringPiMessage);
@@ -436,11 +443,17 @@ async function persistTerminalLifecycle(terminal) {
436
443
  });
437
444
  await finishTurn(terminal.childConversationId, turnId, agentInvocationTurnEnd(terminal));
438
445
  }
439
- /** Stop an invocation whose worker died, or project its terminal turn result. */
446
+ /**
447
+ * Stop an invocation whose worker died, or project its terminal turn result.
448
+ * With `resumeLostWorker`, a Turn whose worker died resumes once from its last
449
+ * save, as a root Turn does. A second loss stops it.
450
+ */
440
451
  async function projectTerminalTurn(invocation, options = {}) {
452
+ const { resumeLostWorker, ...completeOptions } = options;
441
453
  let turn = await getTurnRecord(invocation.childConversationId, getAgentInvocationTurnId(invocation.invocationId));
442
454
  if (!turn) return;
443
- if (turn.state === "running") {
455
+ if (resumeLostWorker && turn.state === "running" && await pauseLostWorkerTurn(turn)) return;
456
+ if (turn.state === "running" || resumeLostWorker && turn.state === "paused" && lostWorkerBeforeFirstSave(turn)) {
444
457
  turn = await failTurnRecord({
445
458
  conversationId: turn.conversationId,
446
459
  expectedVersion: turn.version,
@@ -454,7 +467,7 @@ async function projectTerminalTurn(invocation, options = {}) {
454
467
  const failed = turn.state !== "completed" || Boolean(turn.errorMessage);
455
468
  const blocked = turn.turnStartMessageIndex === void 0 ? void 0 : readBlockedReport(turn.piMessages.slice(turn.turnStartMessageIndex));
456
469
  return await completeAgentInvocation({
457
- ...options,
470
+ ...completeOptions,
458
471
  invocationId: invocation.invocationId,
459
472
  ...failed ? {
460
473
  errorMessage: turn.errorMessage ?? "Agent invocation failed",
@@ -469,18 +482,26 @@ async function projectTerminalTurn(invocation, options = {}) {
469
482
  });
470
483
  }
471
484
  /**
472
- * End an agent invocation that is still running or paused while other work
473
- * of its child starts. A saved finished Turn gives its result. Otherwise it
474
- * fails. The newer work does not continue this task, so the result goes to
475
- * the parent on its own.
485
+ * End every running or paused agent invocation of a child before other work
486
+ * opens a Turn there, so the child has one open Turn. A saved finished Turn
487
+ * gives its result. Every other one fails with `errorMessage`, because the
488
+ * newer work does not continue its task. Each reports on its own.
476
489
  */
477
- async function endOtherActiveAgentInvocation(invocation) {
478
- return await projectTerminalTurn(invocation, { reportNow: true }) ?? await completeAgentInvocation({
479
- invocationId: invocation.invocationId,
480
- errorMessage: "This task was not resumed. Newer work for this child agent started, so this task ended without a result.",
481
- reportNow: true,
482
- status: "failed"
483
- });
490
+ async function endActiveAgentInvocations(conversationId, options) {
491
+ for (const active of await listAgentInvocationsForConversation(conversationId, ACTIVE_AGENT_INVOCATION_STATUSES)) {
492
+ if (active.invocationId === options.exceptInvocationId) continue;
493
+ const terminal = await projectTerminalTurn(active, { reportNow: true }) ?? await completeAgentInvocation({
494
+ invocationId: active.invocationId,
495
+ errorMessage: options.errorMessage,
496
+ reportNow: true,
497
+ status: "failed"
498
+ });
499
+ if (terminal && isTerminalAgentInvocation(terminal)) {
500
+ await persistTerminalLifecycle(terminal);
501
+ await recordSubagentEnded(terminal);
502
+ await options.enqueueResult?.(terminal);
503
+ }
504
+ }
484
505
  }
485
506
  /**
486
507
  * End every agent invocation of a child whose last attempt lost its worker and
@@ -556,19 +577,6 @@ async function saveAgentInvocationResult(args) {
556
577
  return agentInvocationTurnEnd(terminal);
557
578
  }
558
579
  /**
559
- * Read how many parents a child Conversation has and the root Conversation's
560
- * Location. A child of the root has depth 1.
561
- */
562
- async function readChildDepthAndRootLocation(conversationId) {
563
- const lineage = await readConversationLineage(conversationId);
564
- const root = lineage[0];
565
- if (!root) return { depth: 0 };
566
- return root.parentConversationId ? { depth: lineage.length } : {
567
- depth: lineage.length - 1,
568
- location: root.location
569
- };
570
- }
571
- /**
572
580
  * Build the invocation consumer that advances work through the shared runner.
573
581
  * `enqueueResult` sends each terminal result to the parent mailbox. Omit it
574
582
  * only where the parent has no mailbox, such as the local CLI.
@@ -576,7 +584,7 @@ async function readChildDepthAndRootLocation(conversationId) {
576
584
  * own child agents. The default, 0, lets only the root start child agents.
577
585
  */
578
586
  function createAgentInvocationWorker(agentRunner, options = {}) {
579
- const maxAgentDepth = options.maxAgentDepth ?? 0;
587
+ const canSpawn = (options.maxAgentDepth ?? 0) > 0;
580
588
  return async (context, invocationId) => {
581
589
  let invocation = await getAgentInvocation(invocationId);
582
590
  if (!invocation) throw new Error(`Agent invocation is missing for ${invocationId}`);
@@ -615,7 +623,6 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
615
623
  let sandboxRef;
616
624
  let history;
617
625
  let location;
618
- let canSpawn = false;
619
626
  try {
620
627
  if (invocation.childConversationId !== context.conversationId) throw new Error(`Agent invocation ${invocationId} belongs to ${invocation.childConversationId}, not ${context.conversationId}`);
621
628
  if (context.destination) throw new Error(`Agent invocation conversation ${context.conversationId} must not own a provider destination`);
@@ -624,13 +631,18 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
624
631
  await acknowledge();
625
632
  return { status: "completed" };
626
633
  }
627
- const projected = await projectTerminalTurn(invocation);
634
+ const projected = await projectTerminalTurn(invocation, { resumeLostWorker: true });
628
635
  if (projected && isTerminalAgentInvocation(projected)) {
629
636
  await finish(projected);
630
637
  await acknowledge();
631
638
  return { status: "completed" };
632
639
  }
633
- for (const active of await listAgentInvocationsForConversation(invocation.childConversationId, ACTIVE_AGENT_INVOCATION_STATUSES)) if (active.invocationId !== invocation.invocationId) await finish(await endOtherActiveAgentInvocation(active));
640
+ await endActiveAgentInvocations(invocation.childConversationId, {
641
+ enqueueResult: options.enqueueResult,
642
+ errorMessage: "This task was not resumed. Newer work for this child agent started, so this task ended without a result.",
643
+ exceptInvocationId: invocation.invocationId
644
+ });
645
+ await supersedeOpenPersonTurn(invocation.childConversationId);
634
646
  invocation = await markAgentInvocationRunning(invocation.invocationId) ?? invocation;
635
647
  if (isTerminalAgentInvocation(invocation)) {
636
648
  await finish(invocation);
@@ -644,15 +656,14 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
644
656
  surface: "internal",
645
657
  turnId
646
658
  });
647
- const [persisted, projection, tree] = await Promise.all([
659
+ const [persisted, projection, child] = await Promise.all([
648
660
  getPersistedThreadState(invocation.childConversationId),
649
661
  openConversationProjection({ conversationId: invocation.childConversationId }),
650
- readChildDepthAndRootLocation(invocation.childConversationId)
662
+ getConversationStore().get({ conversationId: invocation.childConversationId })
651
663
  ]);
652
664
  sandboxRef = getPersistedSandboxState(persisted);
653
665
  history = agentTypeStartsWithParentHistory(invocation.agentType) && projection.messages.length === 0 ? await loadForkHistory(invocation) : projection.messages;
654
- location = tree.location;
655
- canSpawn = tree.depth <= maxAgentDepth;
666
+ location = child?.location;
656
667
  } catch (error) {
657
668
  if (isInvocationInputCommitLost(error)) return { status: "lost_lease" };
658
669
  if (!context.attempt.isFinalAttempt) throw error;
@@ -672,10 +683,13 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
672
683
  parentConversationId: invocation.parentConversationId,
673
684
  turnId,
674
685
  runId: invocation.invocationId,
675
- instruction: instructionForInputs([{
676
- kind: "runtime",
677
- text: agentInvocationInputText(invocation)
678
- }]),
686
+ instruction: {
687
+ ...instructionForInputs([{
688
+ kind: "runtime",
689
+ text: agentInvocationInputText(invocation)
690
+ }]),
691
+ provenance: agentInvocationProvenance(invocation)
692
+ },
679
693
  history,
680
694
  actor: invocation.actor,
681
695
  credentialContext: invocation.credentialContext,
@@ -683,6 +697,7 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
683
697
  source: invocation.source,
684
698
  ...location ? { location } : void 0,
685
699
  surface: "internal",
700
+ deadlineAtMs: getTurnRequestDeadline()?.deadlineAtMs,
686
701
  ...stopSignal ? { signal: stopSignal } : void 0,
687
702
  ...agentInvocationRunPolicy(invocation, canSpawn),
688
703
  state: { sandboxRef },
@@ -690,6 +705,7 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
690
705
  drainSteeringMessages: createAgentMessageSteeringDrain(context, invocation),
691
706
  onInputCommitted: acknowledge,
692
707
  shouldYield: context.shouldYield,
708
+ checkIn: context.checkIn,
693
709
  onSandboxRefChanged: async (nextSandboxRef) => {
694
710
  sandboxRef = nextSandboxRef;
695
711
  await persistThreadStateById(invocation.childConversationId, { sandboxRef });
@@ -748,4 +764,4 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
748
764
  return { status: "completed" };
749
765
  };
750
766
  }
751
- export { resolveAgentInvocationId as a, createAgentInvocationForMessage as c, enqueueAgentInvocation as i, createAgentInvocationFromLatest as l, createAndEnqueueAgentInvocation as n, AgentRunError as o, endAgentInvocationsOfStoppedWork as r, executeTurn as s, createAgentInvocationWorker as t, findChildAgentConversationId as u };
767
+ export { enqueueAgentInvocation as a, createAgentInvocationForMessage as c, endAgentInvocationsOfStoppedWork as i, createAgentInvocationFromLatest as l, createAndEnqueueAgentInvocation as n, resolveAgentInvocationId as o, endActiveAgentInvocations as r, resolveThreadTurnWork as s, createAgentInvocationWorker as t, findChildAgentConversationId as u };
@@ -1,10 +1,9 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { St as hasConversationStop, Tt as isInvalidConversationRecordError, wt as isFinalAttempt } from "./projection-DliWYrnT.js";
3
- import { x as isProviderRetryError } from "./client-DDbBucBw.js";
4
- import { i as getChatConfig } from "./config-DqFnykQT.js";
5
- import { T as withLogContext, b as setSpanAttributes, h as logWarn, m as logInfo, p as logException } from "./logging-BfORLKoq.js";
6
- import { g as getTurnRequestDeadline, v as ConversationQueueMessageRejectedError } from "./background-compaction-queue-DXkLsWoH.js";
7
- import { E as startConversationWork, S as releaseConversationWork, _ as getConversationWorkState, b as recordAttemptFailure, c as clearConsumedConversationWake, d as completeConversationWork, f as countPendingConversationMessages, h as ensureConversationWake, i as beginConversationResume, m as drainConversationMailbox, o as checkInConversationWork, p as deadLetterAttempt, t as ackMessages, u as completeConversationStop, w as requestAnotherSlice, x as recordConversationRetry } from "./store-Dn4W7qgH.js";
2
+ import { Dt as isInvalidConversationRecordError, Et as isFinalAttempt, wt as hasConversationStop } from "./projection-CL_YWeGf.js";
3
+ import { i as getChatConfig, z as isProviderRetryError } from "./config-CkHcUMN7.js";
4
+ import { T as withLogContext, b as setSpanAttributes, h as logWarn, m as logInfo, p as logException } from "./logging-BO5zU6Mt.js";
5
+ import { C as ConversationQueueMessageRejectedError, S as getTurnRequestDeadline } from "./background-compaction-queue-CYI909P5.js";
6
+ import { E as startConversationWork, S as releaseConversationWork, _ as getConversationWorkState, b as recordAttemptFailure, c as clearConsumedConversationWake, d as completeConversationWork, f as countPendingConversationMessages, h as ensureConversationWake, i as beginConversationResume, m as drainConversationMailbox, o as checkInConversationWork, p as deadLetterAttempt, t as ackMessages, u as completeConversationStop, w as requestAnotherSlice, x as recordConversationRetry } from "./store-DdIEUL1q.js";
8
7
  // src/chat/task-execution/attempt-selection.ts
9
8
  function selectContiguousTurnBatch(messages) {
10
9
  const first = messages[0];
@@ -0,0 +1,31 @@
1
+ -- Archive now applies to everyone and lives on junior_conversations. Its
2
+ -- legacy archived_at values are stale, so clear them first.
3
+ UPDATE "junior_conversations" SET "archived_at" = NULL WHERE "archived_at" IS NOT NULL;--> statement-breakpoint
4
+ -- A root stays archived only when every member archived it. The root actor
5
+ -- is a member without a participant row, and an archive always wrote one, so
6
+ -- an actor with no row did not archive it.
7
+ UPDATE "junior_conversations" AS "c"
8
+ SET "archived_at" = "p"."archived_at"
9
+ FROM (
10
+ SELECT "root_conversation_id", max("archived_at") AS "archived_at"
11
+ FROM "junior_conversation_participants"
12
+ GROUP BY "root_conversation_id"
13
+ HAVING count(*) = count("archived_at")
14
+ ) AS "p"
15
+ WHERE "c"."conversation_id" = "p"."root_conversation_id"
16
+ AND "c"."parent_conversation_id" IS NULL
17
+ AND NOT EXISTS (
18
+ SELECT 1 FROM "junior_identities" AS "i"
19
+ WHERE "i"."id" = "c"."actor_identity_id"
20
+ AND "i"."user_id" IS NOT NULL
21
+ AND NOT EXISTS (
22
+ SELECT 1 FROM "junior_conversation_participants" AS "ap"
23
+ WHERE "ap"."root_conversation_id" = "c"."conversation_id"
24
+ AND "ap"."user_id" = "i"."user_id"
25
+ )
26
+ );--> statement-breakpoint
27
+ -- A child archive was already shared.
28
+ UPDATE "junior_conversations" SET "archived_at" = "child_archived_at" WHERE "child_archived_at" IS NOT NULL;--> statement-breakpoint
29
+ DROP INDEX "junior_conversation_participants_unarchived_activity_idx";--> statement-breakpoint
30
+ DROP INDEX "junior_conversation_participants_auto_archive_idx";--> statement-breakpoint
31
+ CREATE INDEX "junior_conversation_participants_auto_archive_idx" ON "junior_conversation_participants" USING btree ("user_id") WHERE "junior_conversation_participants"."auto_archive";
@@ -0,0 +1,64 @@
1
+ -- Give each existing child the Destination row and Location of its root, as
2
+ -- createChild now does for a new child. A child Run then reads visibility and
3
+ -- Location from its own row. A child whose chain is broken or has a cycle
4
+ -- never joins a root here, so it keeps no Destination row and its Runs are
5
+ -- private with no Location. The Location follows locationFromRow:
6
+ -- location_json, else a Slack destination row, with the session Source
7
+ -- threadTs when the Location has none.
8
+ WITH RECURSIVE "tree" ("conversation_id", "root_id", "depth", "path") AS (
9
+ SELECT "conversation_id", "conversation_id", 0, ARRAY["conversation_id"]
10
+ FROM "junior_conversations"
11
+ WHERE "parent_conversation_id" IS NULL
12
+ UNION ALL
13
+ SELECT "child"."conversation_id", "tree"."root_id", "tree"."depth" + 1, "tree"."path" || "child"."conversation_id"
14
+ FROM "junior_conversations" "child"
15
+ JOIN "tree" ON "child"."parent_conversation_id" = "tree"."conversation_id"
16
+ WHERE "child"."conversation_id" <> ALL ("tree"."path")
17
+ ),
18
+ "root_place" AS (
19
+ SELECT
20
+ "root"."conversation_id" AS "root_id",
21
+ "root"."destination_id",
22
+ CASE
23
+ WHEN "root"."location_json" IS NOT NULL THEN "root"."location_json"
24
+ WHEN "destination"."provider" = 'slack' THEN jsonb_build_object(
25
+ 'id', "destination"."id",
26
+ 'provider', 'slack',
27
+ 'teamId', "destination"."provider_tenant_id",
28
+ 'channelId', "destination"."provider_destination_id"
29
+ )
30
+ END AS "location",
31
+ nullif(btrim("root"."source_json"->>'threadTs'), '') AS "source_thread_ts",
32
+ "root"."source_json"->>'kind' AS "source_kind",
33
+ "root"."source_json"->>'teamId' AS "source_team_id",
34
+ "root"."source_json"->>'channelId' AS "source_channel_id"
35
+ FROM "junior_conversations" "root"
36
+ LEFT JOIN "junior_destinations" "destination" ON "destination"."id" = "root"."destination_id"
37
+ WHERE "root"."parent_conversation_id" IS NULL
38
+ ),
39
+ "root_facts" AS (
40
+ SELECT
41
+ "root_id",
42
+ "destination_id",
43
+ CASE
44
+ WHEN "location" IS NOT NULL
45
+ AND "location"->>'threadTs' IS NULL
46
+ AND "source_kind" = 'slack'
47
+ AND "source_team_id" = "location"->>'teamId'
48
+ AND "source_channel_id" = "location"->>'channelId'
49
+ AND "source_thread_ts" IS NOT NULL
50
+ THEN "location" || jsonb_build_object('threadTs', "source_thread_ts")
51
+ ELSE "location"
52
+ END AS "location"
53
+ FROM "root_place"
54
+ )
55
+ UPDATE "junior_conversations" "child"
56
+ SET
57
+ "destination_id" = "root_facts"."destination_id",
58
+ "location_json" = "root_facts"."location"
59
+ FROM "tree"
60
+ JOIN "root_facts" ON "root_facts"."root_id" = "tree"."root_id"
61
+ WHERE "child"."conversation_id" = "tree"."conversation_id"
62
+ AND "tree"."depth" > 0
63
+ AND "child"."destination_id" IS NULL
64
+ AND "child"."location_json" IS NULL;
@@ -0,0 +1 @@
1
+ ALTER TABLE "junior_conversation_participants" ADD COLUMN "unsubscribed_at" timestamp with time zone;