@sentry/junior 0.298.0 → 0.300.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 (95) hide show
  1. package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
  2. package/dist/{state-CSuA2J1V.js → adapter-S5UkjNK3.js} +53 -136
  3. package/dist/{admin-BF3DbYGf.js → admin-UrTniSPO.js} +2 -2
  4. package/dist/{agent-runner-Q9GkoerG.js → agent-runner-bY4_0UPm.js} +1444 -1478
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +7 -7
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +382 -68
  9. package/dist/{app-DOg_mCtV.d.ts → app-D-AcIcCV.d.ts} +17 -4
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +148 -483
  12. package/dist/{automation-Cn8qmbdr.js → automation-Dw82oQ-h.js} +2 -2
  13. package/dist/{background-compaction-queue-BZhGFOK6.js → background-compaction-queue-B6U3060-.js} +9 -5
  14. package/dist/{briefs-CQrCRF6-.js → briefs-DqiwWu-n.js} +4 -4
  15. package/dist/{catalog-runtime-DZeD2WbL.js → catalog-runtime-D1oYNv04.js} +1 -1
  16. package/dist/cli/chat.js +17 -17
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +5 -5
  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-BOByVnxe.js → config-9nHoFiJP.js} +117 -12
  24. package/dist/{connections-BNN5cJam.js → connections-DZjTN3JC.js} +6 -6
  25. package/dist/continue-in-slack-Dtv7_U42.js +176 -0
  26. package/dist/{conversation-DCkzvxqB.js → conversation-Dyjq2CZ8.js} +36 -13
  27. package/dist/{conversation-feed-CMA12Rjs.js → conversation-feed-CcDxlrlQ.js} +109 -3
  28. package/dist/{conversation-privacy-C0eRxsgb.js → conversation-privacy-D-5HTXjS.js} +1 -1
  29. package/dist/{conversation-turn-D9qvcDX6.js → conversation-turn-Cxl8WZD7.js} +85 -68
  30. package/dist/{credential-sync-B_iUpxGL.js → credential-sync-C49ClwDX.js} +18 -18
  31. package/dist/{db-DoMcnYol.d.ts → db-2resqBh1.d.ts} +1 -1
  32. package/dist/{db-CoMNr2Zm.js → db-BJNo6fK5.js} +176 -12
  33. package/dist/{executor-C-m8VrzX.js → executor-DBIaOeJ_.js} +47 -13
  34. package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
  35. package/dist/instrumentation.js +14 -5
  36. package/dist/lineage-0dereG7H.js +37 -0
  37. package/dist/{logging-CJTi5niy.js → logging-BIclibct.js} +1 -1
  38. package/dist/{message-Q6_5DAWR.js → message-dkOl-Iii.js} +9 -10
  39. package/dist/model-input-CLo9TaUd.js +82 -0
  40. package/dist/nitro.d.ts +1 -1
  41. package/dist/nitro.js +17 -9
  42. package/dist/{oauth-callback-server-CH5XAyo-.js → oauth-callback-server-WmpjfJgQ.js} +2 -2
  43. package/dist/{plugins-HYh_JOdw.js → plugins-BBX07Jzt.js} +1 -1
  44. package/dist/{projection-BgwEE36_.js → projection-w_X-zi7v.js} +1035 -692
  45. package/dist/{prompt-DXc9DYT9.js → prompt-B1Xw46-S.js} +4 -4
  46. package/dist/{registry-9XwqSnM-.js → registry-BmP5vnlj.js} +4 -4
  47. package/dist/{resolve-DUIAbcRL.js → resolve-goo34bJK.js} +3 -3
  48. package/dist/{result-C2Vn8QGn.js → result-PVBeU0Wf.js} +158 -69
  49. package/dist/{runner-CXGtw-Mc.js → runner-DKrfvNV6.js} +9 -9
  50. package/dist/{sandbox-egress-signals-Di3S_dO7.js → sandbox-egress-signals-DsUcqrI0.js} +1 -1
  51. package/dist/{schema-Dyp7racy.js → schema-C9iNFz5n.js} +51 -7
  52. package/dist/{schema-BnbZ-rKv.d.ts → schema-Dns-sTas.d.ts} +1285 -761
  53. package/dist/{service-account-DM3KBBeG.js → service-account-CMAAloAL.js} +3 -3
  54. package/dist/{service-account-GzAMUQ8a.js → service-account-CmowamcB.js} +4 -4
  55. package/dist/session-stop-BcAXze8a.js +3330 -0
  56. package/dist/{skills-DCK9SD_l.js → skills-DfsazET6.js} +3 -3
  57. package/dist/slack-conversation-unfurl-CzQonuWz.js +370 -0
  58. package/dist/spawn-C7o0FDDp.js +73 -0
  59. package/dist/state-zSilNpbi.js +132 -0
  60. package/dist/{user-input-request-CXNIov9n.js → statuses-Hn-HsOph.js} +115 -26
  61. package/dist/{stop-Dh2DfwpK.js → stop-CFOujp8C.js} +9105 -6007
  62. package/dist/{store-DrA17Fbz.js → store-Dkeis_8o.js} +10 -10
  63. package/dist/{store-B1zepKG8.js → store-E3x2Fg_F.js} +24 -4
  64. package/dist/{task-queue-D1rXWfFN.js → task-queue-D-hCqdZW.js} +4 -4
  65. package/dist/{task-runner-CT4M8oDz.js → task-runner-vohUPLHe.js} +10 -10
  66. package/dist/{thread-context-DnqUkbzN.js → thread-context-BzvdkgI9.js} +18 -18
  67. package/dist/{turn-session-routing-VXDVXLRl.js → turn-session-routing-Bo_LxFum.js} +5 -5
  68. package/dist/turn-user-message-D5RnVmxQ.js +355 -0
  69. package/dist/users-2bggndVg.js +424 -0
  70. package/dist/{validation-zxAJBDDy.js → validation-BbWikeSa.js} +1 -1
  71. package/dist/{version-DcZ40a0g.js → version-GVBMW2jA.js} +1 -1
  72. package/dist/version.js +1 -1
  73. package/dist/{viewer-CgiGjW10.js → viewer-BpxRliyO.js} +36 -163
  74. package/dist/{warmup-CwKbxQLl.js → warmup-BW2qwnal.js} +1140 -145
  75. package/dist/{worker-CbDUzaBA.js → worker-Cbd-iuwZ.js} +25 -20
  76. package/migrations/0104_code_change_draft.sql +1 -0
  77. package/migrations/0105_attachment_uploads.sql +14 -0
  78. package/migrations/0106_conversation_agent_config.sql +1 -0
  79. package/migrations/0107_attachment_deferred_download.sql +2 -0
  80. package/migrations/meta/0104_snapshot.json +4516 -0
  81. package/migrations/meta/0105_snapshot.json +4611 -0
  82. package/migrations/meta/0106_snapshot.json +4617 -0
  83. package/migrations/meta/0107_snapshot.json +4617 -0
  84. package/migrations/meta/_journal.json +28 -0
  85. package/package.json +10 -8
  86. package/dist/attempt-selection-ClP3MMPr.js +0 -61
  87. package/dist/locks-D-0h111u.js +0 -48
  88. package/dist/notification-Bv25xbj0.js +0 -1284
  89. package/dist/prompt-input-BUr4J9RO.js +0 -1424
  90. package/dist/session-stop-D4i7e6iT.js +0 -181
  91. package/dist/spawn-6cX6xE9G.js +0 -80
  92. package/dist/turn-cancel-l460pfGW.js +0 -201
  93. package/dist/turn-user-message-BSPmkm7X.js +0 -608
  94. package/dist/turn-wake-DVFVXyhX.js +0 -161
  95. package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
@@ -1,181 +0,0 @@
1
- import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { M as normalizeConversationText, ti as cancelSubscriptions, x as toStoredConversationMessage } from "./projection-BgwEE36_.js";
3
- import { et as nextDetailVersion, r as getConversationEventStore, s as getSqlExecutor, w as isPersonInput } from "./db-CoMNr2Zm.js";
4
- import { A as juniorConversations } from "./executor-C-m8VrzX.js";
5
- import { _ as getEventBatchDelayMs, s as instructionForInputs, t as eventReviewItemInputs } from "./prompt-input-BUr4J9RO.js";
6
- import { a as renderEventBatchInputs, i as isEventMailboxMetadata, r as eventBatchMessageMeta } from "./notification-Bv25xbj0.js";
7
- import { and, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
8
- // src/chat/conversations/sql/subtree.ts
9
- /** Columns of the `conversation_subtree` table that `conversationSubtree` returns. */
10
- const conversationSubtreeColumns = {
11
- conversationId: sql`conversation_subtree.conversation_id`,
12
- scopeConversationId: sql`conversation_subtree.scope_conversation_id`
13
- };
14
- /**
15
- * Return a joinable `conversation_subtree` table. It maps each selected
16
- * Conversation to itself and to each descendant child Conversation at any
17
- * depth. Reports use it so that a total for a Conversation always includes the
18
- * work of all its child agents.
19
- *
20
- * A descendant must have the same root as the selected Conversation. Thus a
21
- * Conversation that has no valid root gets only its own work.
22
- */
23
- function conversationSubtree(conversationIds) {
24
- const selectedIds = sql.join(conversationIds.map((conversationId) => sql`${conversationId}`), sql`, `);
25
- return sql`(
26
- with recursive tree(scope_conversation_id, conversation_id, root_conversation_id) as (
27
- select selected.conversation_id, selected.conversation_id, selected.root_conversation_id
28
- from junior_conversations selected
29
- where selected.conversation_id in (${selectedIds})
30
- union
31
- select tree.scope_conversation_id, child.conversation_id, child.root_conversation_id
32
- from junior_conversations child
33
- join tree
34
- on child.parent_conversation_id = tree.conversation_id
35
- and (child.root_conversation_id || '') = tree.root_conversation_id
36
- )
37
- select scope_conversation_id, conversation_id from tree
38
- ) conversation_subtree`;
39
- }
40
- // src/chat/conversations/session-stop.ts
41
- var session_stop_exports = /* @__PURE__ */ __exportAll({
42
- getConversationStoppedAtMs: () => getConversationStoppedAtMs,
43
- isSkippedAfterConversationStop: () => isSkippedAfterConversationStop,
44
- isWatchEvent: () => isWatchEvent,
45
- markConversationsStopped: () => markConversationsStopped,
46
- resumeStoppedConversationTree: () => resumeStoppedConversationTree,
47
- skipInputAfterConversationStop: () => skipInputAfterConversationStop
48
- });
49
- /** Skip reason on the Message that saves Events for a stopped Conversation. */
50
- const STOPPED_CONVERSATION_SKIP_REASON = "stopped conversation";
51
- /**
52
- * Stop each Conversation until a person sends it input or its parent gives
53
- * it new work. With `cancelWatches`, an agent stopped them, so their Watches
54
- * end first: a Watch delivers under its lock, so every Event of a cancelled
55
- * Watch was received before the stop. A Conversation that already stopped
56
- * later keeps that stop, so a retried or cascaded stop does not move it back.
57
- */
58
- async function markConversationsStopped(conversationIds, options) {
59
- if (conversationIds.length === 0) return;
60
- if (options.cancelWatches) for (const conversationId of conversationIds) await cancelSubscriptions({
61
- conversationId,
62
- state: options.state
63
- });
64
- const stoppedAt = new Date(options.nowMs ?? Date.now());
65
- await getSqlExecutor().db().update(juniorConversations).set({
66
- stoppedAt,
67
- detailVersion: nextDetailVersion
68
- }).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), or(isNull(juniorConversations.stoppedAt), lt(juniorConversations.stoppedAt, stoppedAt))));
69
- }
70
- /** Return when a Conversation stopped, or undefined when it is not stopped. */
71
- async function getConversationStoppedAtMs(conversationId) {
72
- const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
73
- return row?.stoppedAt?.getTime();
74
- }
75
- /**
76
- * End the stop of a Conversation and of the child agents below it, for new
77
- * work sent at `sentAtMs`. Nothing changes for work sent at or before the
78
- * stop, so the input that a stop drops does not undo it.
79
- * Only Conversations that stopped no later than this Conversation change, so
80
- * a later stop of one child agent stays in effect.
81
- */
82
- async function resumeStoppedConversationTree(conversationId, sentAtMs) {
83
- const stoppedAtMs = await getConversationStoppedAtMs(conversationId);
84
- if (stoppedAtMs === void 0 || sentAtMs <= stoppedAtMs) return;
85
- await getSqlExecutor().db().update(juniorConversations).set({
86
- stoppedAt: null,
87
- detailVersion: nextDetailVersion
88
- }).where(and(inArray(juniorConversations.conversationId, sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`), lte(juniorConversations.stoppedAt, new Date(stoppedAtMs))));
89
- }
90
- /**
91
- * Apply a session stop to automated input. Input from a person always runs.
92
- * When a person sent it after the stop, the Conversation and its child agents
93
- * stop no more. Input from a parent tool call also runs. While the
94
- * Conversation is stopped, its Watch Events are saved as one Message and
95
- * start no Turn, and other Events received at or before the stop are
96
- * dropped. Returns the work to run, with only the Events that are left, or
97
- * the finished result when nothing is left.
98
- */
99
- async function skipInputAfterConversationStop(context) {
100
- const messages = context.attempt.messages;
101
- const personInput = messages.filter((message) => isPersonInput(message.source));
102
- if (personInput.length > 0) {
103
- await resumeStoppedConversationTree(context.conversationId, Math.max(...personInput.map((message) => message.createdAtMs)));
104
- return { context };
105
- }
106
- if (messages.length === 0 || !messages.every(isEventInput)) return { context };
107
- const stoppedAtMs = await getConversationStoppedAtMs(context.conversationId);
108
- if (stoppedAtMs === void 0) return { context };
109
- const saved = messages.filter(isWatchEvent);
110
- const live = messages.filter((message) => !isSkippedAfterConversationStop(message, stoppedAtMs));
111
- if (live.length > 0 && saved.length > 0) {
112
- const delayMs = Math.max(getEventBatchDelayMs(messages), getEventBatchDelayMs(live));
113
- if (delayMs > 0) return { skipped: {
114
- status: "deferred",
115
- delayMs
116
- } };
117
- }
118
- if (saved.length > 0) await saveStoppedConversationEvents(context.conversationId, saved);
119
- if (live.length === messages.length) return { context };
120
- if (live.length > 0) return { context: {
121
- ...context,
122
- attempt: {
123
- ...context.attempt,
124
- messages: live
125
- }
126
- } };
127
- await context.attempt.ack();
128
- return { skipped: { status: "completed" } };
129
- }
130
- /**
131
- * Return whether a session stop at `stoppedAtMs` keeps one Event from
132
- * starting a Turn: a Watch Event is saved, and another Event received at or
133
- * before the stop is dropped. Input from a person is never skipped.
134
- */
135
- function isSkippedAfterConversationStop(message, stoppedAtMs) {
136
- return stoppedAtMs !== void 0 && isEventInput(message) && (isWatchEvent(message) || message.receivedAtMs <= stoppedAtMs);
137
- }
138
- function isEventInput(message) {
139
- return message.source === "event" && isEventMailboxMetadata(message.input.metadata);
140
- }
141
- /** Return whether a Watch delivered this input. Agent input has none. */
142
- function isWatchEvent(message) {
143
- const metadata = message.input.metadata;
144
- return isEventMailboxMetadata(metadata) && metadata.event.subscriptionId !== void 0;
145
- }
146
- /**
147
- * Save Events as the one Message that a Turn would save for them. The append
148
- * is idempotent by Message id, so a retried batch saves nothing new. The
149
- * Message takes the id of the first saved Event, so when an ack is lost and
150
- * the retry carries more Events to save, the extra Events are deduplicated
151
- * away.
152
- */
153
- async function saveStoppedConversationEvents(conversationId, messages) {
154
- const first = messages[0];
155
- const { text } = instructionForInputs(renderEventBatchInputs(messages, await eventReviewItemInputs(messages)).map((input) => ({
156
- kind: "runtime",
157
- text: input
158
- })));
159
- const stored = toStoredConversationMessage({
160
- id: first.inboundMessageId,
161
- role: "user",
162
- text: normalizeConversationText(text),
163
- createdAtMs: first.createdAtMs,
164
- ...first.input.authorIdentityId ? { authorIdentityId: first.input.authorIdentityId } : void 0,
165
- meta: {
166
- replied: false,
167
- skippedReason: STOPPED_CONVERSATION_SKIP_REASON,
168
- ...eventBatchMessageMeta(messages)
169
- }
170
- });
171
- const { createdAtMs, ...data } = stored;
172
- await getConversationEventStore().append(conversationId, [{
173
- idempotencyKey: `message:${stored.messageId}`,
174
- createdAtMs,
175
- data: {
176
- type: "message",
177
- ...data
178
- }
179
- }]);
180
- }
181
- export { session_stop_exports as a, conversationSubtreeColumns as c, resumeStoppedConversationTree as i, isSkippedAfterConversationStop as n, skipInputAfterConversationStop as o, markConversationsStopped as r, conversationSubtree as s, getConversationStoppedAtMs as t };
@@ -1,80 +0,0 @@
1
- import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { n as botConfig } from "./config-BOByVnxe.js";
3
- import { O as conversationKindFromRow, o as getDb } from "./db-CoMNr2Zm.js";
4
- import { A as juniorConversations } from "./executor-C-m8VrzX.js";
5
- import { Ft as actorFromRun, It as toolInvocationDestination } from "./agent-runner-Q9GkoerG.js";
6
- import { A as AgentDepthLimitError, v as createAndEnqueueAgentInvocation } from "./warmup-CwKbxQLl.js";
7
- import { desc, eq, sql } from "drizzle-orm";
8
- // src/chat/conversations/lineage.ts
9
- /**
10
- * Read the parent chain of a Conversation in one query, root first, with the
11
- * Conversation last. Returns an empty list when the Conversation is missing.
12
- *
13
- * The chain stops at a parent that is missing or that is already in the
14
- * chain. Then the first entry still has a `parentConversationId`, so callers
15
- * can tell a broken chain from one that ends at a root.
16
- */
17
- async function readConversationLineage(conversationId) {
18
- const lineage = sql`(
19
- with recursive lineage(conversation_id, parent_conversation_id, depth, path) as (
20
- select selected.conversation_id, selected.parent_conversation_id, 0, array[selected.conversation_id]
21
- from junior_conversations selected
22
- where selected.conversation_id = ${conversationId}
23
- union all
24
- select parent.conversation_id, parent.parent_conversation_id, lineage.depth + 1, lineage.path || parent.conversation_id
25
- from junior_conversations parent
26
- join lineage on parent.conversation_id = lineage.parent_conversation_id
27
- where parent.conversation_id <> all(lineage.path)
28
- )
29
- select conversation_id, depth from lineage
30
- ) conversation_lineage`;
31
- return (await getDb().select({
32
- conversationId: juniorConversations.conversationId,
33
- kind: juniorConversations.kind,
34
- parentConversationId: juniorConversations.parentConversationId
35
- }).from(juniorConversations).innerJoin(lineage, eq(sql`conversation_lineage.conversation_id`, juniorConversations.conversationId)).orderBy(desc(sql`conversation_lineage.depth`))).map((row) => ({
36
- conversationId: row.conversationId,
37
- kind: conversationKindFromRow(row),
38
- ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0
39
- }));
40
- }
41
- // src/chat/agent-invocations/spawn.ts
42
- var spawn_exports = /* @__PURE__ */ __exportAll({ bindSpawnAgent: () => bindSpawnAgent });
43
- /**
44
- * Count the parents of the Conversation that starts a child agent. A chain
45
- * that does not end at a root, such as a cycle, cannot start one.
46
- */
47
- async function assertCanStartChildAgent(conversationId, maxAgentDepth) {
48
- const lineage = await readConversationLineage(conversationId);
49
- const root = lineage[0];
50
- if (!root || root.parentConversationId || lineage.length - 1 > maxAgentDepth) throw new AgentDepthLimitError(maxAgentDepth);
51
- }
52
- /** Bind a Run's Actor and credentials to new Agent invocations. */
53
- function bindSpawnAgent(run, options) {
54
- const actor = actorFromRun(run);
55
- if (!actor) return;
56
- return async (input, call) => {
57
- call.signal?.throwIfAborted();
58
- await assertCanStartChildAgent(run.conversationId, options.maxAgentDepth ?? botConfig.maxAgentDepth);
59
- const queue = typeof options.queue === "function" ? options.queue() : options.queue;
60
- return { childConversationId: (await createAndEnqueueAgentInvocation({
61
- actor,
62
- ...input.name ? { agentName: input.name } : void 0,
63
- ...input.agentType ? { agentType: input.agentType } : void 0,
64
- ...input.fork ? { fork: true } : void 0,
65
- ...run.credentialContext ? { credentialContext: run.credentialContext } : void 0,
66
- destination: toolInvocationDestination(run),
67
- idempotencyKey: `${run.turnId}:${call.toolCallId}`,
68
- input: input.task,
69
- ...input.kind ? { kind: input.kind } : void 0,
70
- parentConversationId: run.conversationId,
71
- parentToolCallId: call.toolCallId,
72
- ...input.reasoningLevel ? { reasoningLevel: input.reasoningLevel } : void 0,
73
- ...input.title ? { title: input.title } : void 0
74
- }, {
75
- ...options,
76
- queue
77
- })).childConversationId };
78
- };
79
- }
80
- export { spawn_exports as n, readConversationLineage as r, bindSpawnAgent as t };
@@ -1,201 +0,0 @@
1
- import { X as clearPendingAuth, j as markConversationMessage, ot as getTurnRecord, rt as abandonTurnRecord, v as hydrateConversationMessages } from "./projection-BgwEE36_.js";
2
- import { r as getConversationEventStore } from "./db-CoMNr2Zm.js";
3
- import { g as getAuthPausedConversationTurnId, v as listActiveMailboxTurns } from "./prompt-input-BUr4J9RO.js";
4
- import { _ as ConversationTurnLifecycleService, p as markTurnClosed, t as getTurnUserMessage } from "./turn-user-message-BSPmkm7X.js";
5
- import { a as getPersistedThreadState, c as coerceThreadConversationState, s as persistThreadStateById } from "./turn-session-routing-VXDVXLRl.js";
6
- import { n as getPausedTurnRequest, s as deleteWebAuthorization } from "./turn-wake-DVFVXyhX.js";
7
- import { t as canJoinTurn } from "./attempt-selection-ClP3MMPr.js";
8
- // src/chat/runtime/turn-execution.ts
9
- /** An error thrown while the agent advances a Run. */
10
- var AgentRunError = class extends Error {
11
- constructor(cause) {
12
- super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
13
- this.name = "AgentRunError";
14
- }
15
- };
16
- /**
17
- * Run the agent and finish the Turn after the caller saves its result.
18
- *
19
- * A paused Run, or a Run waiting for authorization, leaves the Turn open. A
20
- * save error also leaves the Turn open so the worker can retry or recover it.
21
- */
22
- async function executeTurn(agentRunner, run, saveResult) {
23
- let outcome;
24
- try {
25
- outcome = await agentRunner.run(run);
26
- } catch (error) {
27
- throw new AgentRunError(error);
28
- }
29
- if (outcome.status !== "completed") return outcome;
30
- const saved = await saveResult(outcome.result);
31
- await finishTurn(run.conversationId, run.turnId, saved);
32
- return { status: "completed" };
33
- }
34
- /** Record the terminal lifecycle event of a Turn from its saved result. */
35
- async function finishTurn(conversationId, turnId, saved) {
36
- const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
37
- const common = {
38
- conversationId,
39
- createdAtMs: saved.finishedAtMs ?? Date.now(),
40
- turnId
41
- };
42
- if (saved.outcome === "failed") await lifecycle.fail({
43
- ...common,
44
- ...saved.eventId ? { eventId: saved.eventId } : void 0,
45
- failureCode: saved.failureCode,
46
- ...saved.failureReason ? { failureReason: saved.failureReason } : void 0
47
- });
48
- else await lifecycle.complete({
49
- ...common,
50
- outcome: saved.outcome
51
- });
52
- }
53
- // src/chat/task-execution/supersede-turns.ts
54
- /**
55
- * End every open mailbox Turn other than `keepTurnId`, so new input runs in
56
- * the only open Turn. New input starts only when no yielded Turn waits, so an
57
- * open Turn here waits for OAuth or was left open by a failed or stopped Run.
58
- * The caller persists `conversation`. Returns false when `isStopped` turns
59
- * true first.
60
- */
61
- async function supersedeOpenMailboxTurns(args) {
62
- return await supersedeTurns({
63
- ...args,
64
- turns: (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId)
65
- });
66
- }
67
- /**
68
- * End open Turns that new input replaces. A late resume or OAuth callback
69
- * for an ended Turn is a no-op. The caller persists `conversation`. Returns
70
- * false when `isStopped` turns true first.
71
- */
72
- async function supersedeTurns(args) {
73
- const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
74
- for (const stale of args.turns) {
75
- if (args.isStopped?.()) return false;
76
- await abandonTurnRecord({
77
- conversationId: args.conversationId,
78
- turnId: stale.turnId,
79
- errorMessage: "Turn superseded by new input"
80
- });
81
- await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
82
- conversationId: args.conversationId,
83
- createdAtMs: Date.now(),
84
- outcome: "cancelled",
85
- turnId: stale.turnId
86
- });
87
- markTurnClosed({
88
- conversation: args.conversation,
89
- nowMs: Date.now(),
90
- sessionId: stale.turnId
91
- });
92
- }
93
- if (args.turns.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
94
- actorId: pendingAuthorizationActorId,
95
- conversationId: args.conversationId
96
- });
97
- return true;
98
- }
99
- /**
100
- * End the Turn that waits for its next Run when `message` cannot join it, so
101
- * the message starts its own Turn instead of running with that Turn's Actor.
102
- * A stored legacy Turn without an Actor keeps taking the input.
103
- */
104
- async function supersedeTurnForInput(args) {
105
- const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
106
- const turnId = conversation.processing.activeTurnId;
107
- if (!turnId || !await getPausedTurnRequest({
108
- conversationId: args.conversationId,
109
- turnId
110
- })) return;
111
- const turn = await getTurnRecord(args.conversationId, turnId);
112
- if (!turn?.actor || canJoinTurn(turn, args.message)) return;
113
- await hydrateConversationMessages({
114
- conversation,
115
- conversationId: args.conversationId
116
- });
117
- await supersedeTurns({
118
- conversation,
119
- conversationId: args.conversationId,
120
- turns: [turn]
121
- });
122
- await persistThreadStateById(args.conversationId, { conversation });
123
- }
124
- // src/chat/task-execution/turn-cancel.ts
125
- /**
126
- * End a cancelled Turn: a stop that a worker saw, or a stop of a Turn that
127
- * waits for sign-in with no worker.
128
- */
129
- /** Close a cancelled Turn, save it, and acknowledge its input. */
130
- async function completeCancelledConversationTurn(args) {
131
- const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
132
- await abandonTurnRecord({
133
- conversationId: args.conversationId,
134
- turnId: args.turnId,
135
- errorMessage: "Turn cancelled"
136
- });
137
- clearPendingAuth(args.conversation, args.turnId);
138
- markConversationMessage(args.conversation, args.userMessageId, {
139
- replied: false,
140
- skippedReason: "turn cancelled"
141
- });
142
- markTurnClosed({
143
- conversation: args.conversation,
144
- nowMs: Date.now(),
145
- sessionId: args.turnId
146
- });
147
- if (pendingAuthorization) await deleteWebAuthorization({
148
- actorId: pendingAuthorization.actorId,
149
- conversationId: args.conversationId
150
- });
151
- await persistThreadStateById(args.conversationId, {
152
- conversation: args.conversation,
153
- sandboxRef: args.sandboxRef
154
- });
155
- await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
156
- conversationId: args.conversationId,
157
- createdAtMs: Date.now(),
158
- outcome: "cancelled",
159
- turnId: args.turnId
160
- });
161
- await args.acknowledge();
162
- }
163
- /**
164
- * End the Turn of a stopped Conversation that waits for sign-in, so a later
165
- * sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
166
- * Slack request waits as the thread's pending sign-in. Every stop path calls
167
- * this, because no worker holds a waiting Turn and the stop wake can go to
168
- * queued input first.
169
- */
170
- async function cancelSignInWait(conversationId) {
171
- const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
172
- if (turnId) await cancelSignInPausedTurn({
173
- conversationId,
174
- turnId
175
- });
176
- }
177
- /**
178
- * Cancel a Turn that waits for sign-in outside its worker, with the same
179
- * cleanup as a stopped resume.
180
- */
181
- async function cancelSignInPausedTurn(args) {
182
- if (!await abandonTurnRecord({
183
- conversationId: args.conversationId,
184
- errorMessage: "Turn cancelled",
185
- onlyIfAuthPaused: true,
186
- turnId: args.turnId
187
- })) return;
188
- const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
189
- await hydrateConversationMessages({
190
- conversation,
191
- conversationId: args.conversationId
192
- });
193
- await completeCancelledConversationTurn({
194
- acknowledge: async () => {},
195
- conversation,
196
- conversationId: args.conversationId,
197
- turnId: args.turnId,
198
- userMessageId: getTurnUserMessage(conversation, args.turnId)?.id
199
- });
200
- }
201
- export { AgentRunError as a, supersedeTurnForInput as i, completeCancelledConversationTurn as n, executeTurn as o, supersedeOpenMailboxTurns as r, finishTurn as s, cancelSignInWait as t };