@sentry/junior 0.309.0 → 0.311.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 (117) hide show
  1. package/dist/adapter-B1wujchl.js +259 -0
  2. package/dist/{adapter-context-1YUbMpD3.js → adapter-context-G2M0y6rP.js} +2 -2
  3. package/dist/{admin-u30A8TcD.js → admin-DCiBhUT1.js} +1 -2
  4. package/dist/{agent-runner-sJLhgPQV.js → agent-runner-BVHPUIc8.js} +695 -1817
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +8 -7
  7. package/dist/api.d.ts +21 -3
  8. package/dist/api.js +1479 -372
  9. package/dist/{app-B_7Wn0en.d.ts → app-Cw5Vy6H6.d.ts} +14 -3
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +233 -506
  12. package/dist/{background-compaction-queue-CUJXVKG3.js → background-compaction-queue-CJDnWVOJ.js} +4 -4
  13. package/dist/{briefs-BHi70IR5.js → briefs-BDjnug6Y.js} +3 -3
  14. package/dist/{catalog-runtime-Chc_IP2o.js → catalog-runtime-DMY3VV-D.js} +1 -1
  15. package/dist/cli/chat.js +16 -16
  16. package/dist/cli/check.js +23 -29
  17. package/dist/cli/init.js +1 -6
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +8 -7
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{config-BIyIdTtA.js → config-BrXDQefC.js} +239 -5
  24. package/dist/{continue-in-slack-BQJBfiQh.js → continue-in-slack-DNXSC9So.js} +6 -5
  25. package/dist/{conversation-CzrLhdHG.js → conversation-ca__NDQW.js} +48 -9
  26. package/dist/{conversation-feed-B9e3_gxz.js → conversation-feed-DkinDu5o.js} +15 -6
  27. package/dist/{conversation-privacy-CkTW29hd.js → conversation-privacy-DxttrKb9.js} +1 -1
  28. package/dist/{conversation-turn-CZaYQUum.js → conversation-turn-DWw7Xhdr.js} +42 -39
  29. package/dist/{credential-sync-58m_CyIJ.js → credential-sync-Bk8wGb8Y.js} +15 -16
  30. package/dist/{db-B4Hjxr-u.d.ts → db-7ETESH44.d.ts} +3 -1
  31. package/dist/{db-CFUpEZi9.js → db-DTxzH7u5.js} +1618 -1041
  32. package/dist/{executor-DXL0O0MV.js → executor-DqTiYj9S.js} +454 -96
  33. package/dist/{history-N7IVbUom.js → history-CYstOMKX.js} +6 -0
  34. package/dist/{html-CaBu2VbT.js → html-B9Sl4Axb.js} +6 -6
  35. package/dist/{install-DhTBUUov.js → install-Sg4ePfLl.js} +2 -2
  36. package/dist/instrumentation.js +3 -3
  37. package/dist/{lineage-CxtOI2_p.js → lineage-BHAMpNKr.js} +2 -2
  38. package/dist/{logging-BNUovdcX.js → logging-FjclQsXu.js} +47 -9
  39. package/dist/{message-DcUsS2vg.js → message-CJ7_RL50.js} +5 -8
  40. package/dist/{model-input-o3rEqgwM.js → model-input-CMLh4Cwq.js} +3 -3
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +3 -3
  43. package/dist/{oauth-callback-server-1Fizd1EM.js → oauth-callback-server-RVcbiDjL.js} +2 -2
  44. package/dist/{oauth-relay-DOwngqdM.js → oauth-relay-Bu9kkaQu.js} +1 -1
  45. package/dist/{projection-Ce4pmhKP.js → projection-Cns7XwWa.js} +9206 -5318
  46. package/dist/{prompt-DEqjDVMs.js → prompt-CDqcsDYC.js} +4 -4
  47. package/dist/{registry-CNE4ZBnG.js → registry-BPwuOP2O.js} +5 -8
  48. package/dist/{resolve-qbPg-aC-.js → resolve-BK29bBry.js} +3 -3
  49. package/dist/rule-DAxQY-1h.js +20 -0
  50. package/dist/{runner-eGIxpAMf.js → runner-BcAE-cJm.js} +10 -10
  51. package/dist/{sandbox-egress-signals-DMFB1kCp.js → sandbox-egress-signals-C-q0go5b.js} +1 -1
  52. package/dist/{schedule-Cire6NU7.js → schedule-BLJ476XQ.js} +209 -43
  53. package/dist/{schema-CfIey9Ao.js → schema-BLgSZXcL.js} +255 -49
  54. package/dist/{schema-DriSvB40.d.ts → schema-DYcJeV7d.d.ts} +701 -62
  55. package/dist/{service-account-Cw_LWZ4-.js → service-account-gN0zqf0S.js} +68 -68
  56. package/dist/{service-account-B1VXCTqg.js → service-account-iJoCtkHR.js} +3 -3
  57. package/dist/{skills-Zg8-vrje.js → skills-BoZ80epJ.js} +77 -31
  58. package/dist/{slack-conversation-unfurl-DA51qH0c.js → slack-conversation-unfurl-CogYrITA.js} +8 -10
  59. package/dist/{spawn-DBi4-zD8.js → spawn-Dk92r7mX.js} +5 -6
  60. package/dist/{state-C-Ftk23K.js → state-DH3Cmgp3.js} +4 -4
  61. package/dist/{stop-D9xideLM.js → stop-CYsfc0Ed.js} +1064 -314
  62. package/dist/{store-BjIXA0Al.js → store-DmmMIrQi.js} +5 -5
  63. package/dist/{task-queue-D0_qbnpo.js → task-queue-C_zldF5J.js} +3 -3
  64. package/dist/{task-runner-DQMq4XY0.js → task-runner-C7oCJQIx.js} +21 -14
  65. package/dist/{thread-context-D0i1e-5O.js → thread-context-BW2BsQbH.js} +13 -11
  66. package/dist/{turn-session-routing-C0l68I_O.js → turn-session-routing-Xh_2nSQe.js} +52 -54
  67. package/dist/{validation-CRbvRPvu.js → validation-DrJd0nnq.js} +1 -1
  68. package/dist/{version-BYdVs12p.js → version-CNKZ8owc.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{warmup-DN9OHN1-.js → warmup-BWdHew2H.js} +14289 -7197
  71. package/dist/{web-message-id-BT8Mg8LL.js → web-message-id-Ch5dPq-a.js} +32 -144
  72. package/dist/{worker-C9ZfJXmV.js → worker-t9qpu_Zx.js} +7 -8
  73. package/migrations/0124_artifact_visibility.sql +9 -0
  74. package/migrations/0125_artifact_public_sha_index.sql +1 -0
  75. package/migrations/0126_artifact_drop_public.sql +8 -0
  76. package/migrations/0127_artifact_path.sql +4 -0
  77. package/migrations/0128_artifact_path_index.sql +1 -0
  78. package/migrations/0129_review_item_answered_index.sql +1 -0
  79. package/migrations/0130_review_item_status_index.sql +1 -0
  80. package/migrations/0131_brief_outcome_status.sql +1 -0
  81. package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
  82. package/migrations/0133_brief_created_at_index.sql +1 -0
  83. package/migrations/0134_slack_person_search_index.sql +1 -0
  84. package/migrations/0135_code_change_size.sql +3 -0
  85. package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
  86. package/migrations/0137_inbox_snoozes.sql +27 -0
  87. package/migrations/0138_code_change_search_index.sql +2 -0
  88. package/migrations/0139_review_item_owner.sql +22 -0
  89. package/migrations/0140_review_item_owner_index.sql +1 -0
  90. package/migrations/0141_memory_core_adoption.sql +89 -0
  91. package/migrations/0142_memory_core_indexes.sql +17 -0
  92. package/migrations/meta/0124_snapshot.json +5516 -0
  93. package/migrations/meta/0125_snapshot.json +5516 -0
  94. package/migrations/meta/0126_snapshot.json +5488 -0
  95. package/migrations/meta/0127_snapshot.json +5519 -0
  96. package/migrations/meta/0128_snapshot.json +5519 -0
  97. package/migrations/meta/0129_snapshot.json +5547 -0
  98. package/migrations/meta/0130_snapshot.json +5563 -0
  99. package/migrations/meta/0131_snapshot.json +5569 -0
  100. package/migrations/meta/0132_snapshot.json +5569 -0
  101. package/migrations/meta/0133_snapshot.json +5590 -0
  102. package/migrations/meta/0134_snapshot.json +5606 -0
  103. package/migrations/meta/0135_snapshot.json +5624 -0
  104. package/migrations/meta/0136_snapshot.json +5624 -0
  105. package/migrations/meta/0137_snapshot.json +5864 -0
  106. package/migrations/meta/0138_snapshot.json +5894 -0
  107. package/migrations/meta/0139_snapshot.json +5898 -0
  108. package/migrations/meta/0140_snapshot.json +5919 -0
  109. package/migrations/meta/0141_snapshot.json +6429 -0
  110. package/migrations/meta/0142_snapshot.json +6457 -0
  111. package/migrations/meta/_journal.json +134 -1
  112. package/package.json +6 -7
  113. package/dist/result-ZGnDzcsb.js +0 -548
  114. package/dist/session-stop-P2XdTiwr.js +0 -4252
  115. package/dist/turn-user-message-nBVvOXjs.js +0 -364
  116. package/dist/users-DdjMjbmM.js +0 -181
  117. package/dist/viewer-DudYrQGj.js +0 -212
@@ -1,364 +0,0 @@
1
- import { qt as readInboundMessageSender } from "./projection-Ce4pmhKP.js";
2
- import { v as parseSlackMessageTs } from "./actor-BsBdxDXQ.js";
3
- import { r as getConversationEventStore, s as getSqlExecutor } from "./db-CFUpEZi9.js";
4
- import { y as juniorAgentInvocations } from "./executor-DXL0O0MV.js";
5
- import { createHash } from "node:crypto";
6
- import { inArray } from "drizzle-orm";
7
- // src/chat/state/turn-id.ts
8
- /** Build a stable turn identifier from a message ID. */
9
- function buildDeterministicTurnId(messageId) {
10
- return `turn_${messageId.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
11
- }
12
- /** Build the stable visible assistant-message identity for one logical turn. */
13
- function buildDeterministicAssistantMessageId(turnId) {
14
- return `${turnId}:assistant:1`;
15
- }
16
- // src/chat/agent-invocations/ids.ts
17
- const CREATE_LOCK_PREFIX = "junior:agent_invocation:create";
18
- /**
19
- * Return the SQL lock that one parent Conversation takes to start, message,
20
- * or stop its child agents.
21
- */
22
- function getChildAgentLockName(parentConversationId) {
23
- return `${CREATE_LOCK_PREFIX}:${parentConversationId}`;
24
- }
25
- function stableId(prefix, ...parts) {
26
- return `${prefix}:${createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32)}`;
27
- }
28
- /** Return the stable identity for one retry-safe delegated task. */
29
- function getAgentInvocationId(parentConversationId, idempotencyKey) {
30
- return stableId("agent-invocation", parentConversationId, idempotencyKey);
31
- }
32
- /** Return the stable child identity for one invocation without a named binding. */
33
- function getUnnamedAgentConversationId(invocationId) {
34
- return stableId("agent", invocationId);
35
- }
36
- /** Return the stable child identity for one named binding. */
37
- function getNamedAgentConversationId(parentConversationId, name) {
38
- return stableId("agent", parentConversationId, name);
39
- }
40
- /**
41
- * Return the stable identity of the agent invocation that gives one child
42
- * agent result to the child Conversation that started that child agent.
43
- */
44
- function getAgentInvocationIdForResult(resultInvocationId) {
45
- return stableId("agent-invocation", "result", resultInvocationId);
46
- }
47
- /**
48
- * Return the stable identity of the agent invocation that gives one message
49
- * from a child agent to the child Conversation that started that child agent.
50
- */
51
- function getAgentInvocationIdForMessage(messageId) {
52
- return stableId("agent-invocation", "message", messageId);
53
- }
54
- /**
55
- * Return the stable identity of the agent invocation that gives one batch of
56
- * watch events to a child Conversation. The first message of the batch names
57
- * it.
58
- */
59
- function getAgentInvocationIdForEvents(messageId) {
60
- return stableId("agent-invocation", "events", messageId);
61
- }
62
- /** Return the stable turn identity advanced by one agent invocation. */
63
- function getAgentInvocationTurnId(invocationId) {
64
- return `agent-invocation:${invocationId}`;
65
- }
66
- /** Return the stable mailbox identity for one agent invocation. */
67
- function getAgentInvocationMessageId(invocationId) {
68
- return `agent-invocation:${invocationId}:input`;
69
- }
70
- const REPLY_MESSAGE_PREFIX = "agent-reply:";
71
- /**
72
- * Return the parent mailbox identity of one child agent `reply` call.
73
- * `senderId` is the Agent invocation that sent it, or the child Conversation
74
- * when no Agent invocation names the child.
75
- */
76
- function getAgentReplyMessageId(senderId, toolCallId) {
77
- return `${REPLY_MESSAGE_PREFIX}${senderId}:${toolCallId}`;
78
- }
79
- /**
80
- * Return the key of the `reply` of one Turn on a child's Conversation loop.
81
- * Readers take the sender from the message's sender fields, not this key.
82
- */
83
- function getTurnReplyKey(turnId, toolCallId) {
84
- return `${turnId}:${toolCallId}`;
85
- }
86
- /** Return the stable parent mailbox identity for one terminal result. */
87
- function getAgentInvocationResultMessageId(invocationId) {
88
- return `agent-invocation:${invocationId}:result`;
89
- }
90
- // src/chat/agent-invocations/child-message.ts
91
- /** Mailbox metadata that stores who sent one child reply or result. */
92
- function childMessageSenderMetadata(sender) {
93
- return { sender };
94
- }
95
- /** Read who sent one child reply or result in a parent's mailbox. */
96
- async function readChildMessageSender(message) {
97
- return readInboundMessageSender(message) ?? (await readLegacyChildMessageSenders([message.inboundMessageId])).get(message.inboundMessageId);
98
- }
99
- /**
100
- * Read who sent each child reply or result, in message order. Messages
101
- * without stored sender fields share one legacy read.
102
- */
103
- async function readChildMessageSenders(messages) {
104
- const stored = messages.map((message) => readInboundMessageSender(message));
105
- const legacy = await readLegacyChildMessageSenders(messages.flatMap((message, index) => stored[index] ? [] : [message.inboundMessageId]));
106
- return messages.map((message, index) => stored[index] ?? legacy.get(message.inboundMessageId));
107
- }
108
- /**
109
- * List the child replies and results among the ids that reached one
110
- * mailbox, oldest first, with the sender fields that the mailbox keeps.
111
- */
112
- async function listChildMessages(inboundMessageIds, messageSenders) {
113
- const legacy = await readLegacyChildMessageSenders(inboundMessageIds.filter((id) => !messageSenders[id]));
114
- return inboundMessageIds.flatMap((inboundMessageId) => {
115
- const sender = messageSenders[inboundMessageId] ?? legacy.get(inboundMessageId);
116
- return sender ? [{
117
- inboundMessageId,
118
- sender
119
- }] : [];
120
- });
121
- }
122
- /**
123
- * Return the Agent invocation whose own Turn sent the message. A Turn on the
124
- * child's Conversation loop has none, even when the message names the
125
- * child's newest Agent invocation.
126
- *
127
- * TODO(dcramer): Remove with Agent invocation rows (#3060 step 7).
128
- */
129
- function ownAgentInvocation(sender) {
130
- const { agentInvocationId } = sender;
131
- return agentInvocationId && sender.turnId === getAgentInvocationTurnId(agentInvocationId) ? agentInvocationId : void 0;
132
- }
133
- /** Return whether the message is the result of an Agent invocation. */
134
- function isAgentInvocationResult(message) {
135
- const agentInvocationId = ownAgentInvocation(message.sender);
136
- return agentInvocationId !== void 0 && message.inboundMessageId === getAgentInvocationResultMessageId(agentInvocationId);
137
- }
138
- /**
139
- * Return whether one Agent invocation sent a reply to its parent: a message
140
- * names it as sender and is not its own result.
141
- */
142
- function hasAgentInvocationReply(messages, agentInvocationId) {
143
- return messages.some((message) => message.sender.agentInvocationId === agentInvocationId && !isAgentInvocationResult(message));
144
- }
145
- const LEGACY_REPLY_ID = /^agent-reply:(agent(?:-invocation)?:[0-9a-f]{32}):(?:(turn_[A-Za-z0-9_-]+)(?::|$))?/;
146
- const LEGACY_RESULT_ID = /^agent-invocation:(agent-invocation:[0-9a-f]{32}):result$/;
147
- /**
148
- * Read the sender of child messages that reached a mailbox before senders
149
- * stored their fields, from their ids.
150
- *
151
- * TODO: remove one release after this ships. Step 7 of #3060 deletes it and
152
- * makes the id a plain generated key.
153
- */
154
- async function readLegacyChildMessageSenders(inboundMessageIds) {
155
- const senders = /* @__PURE__ */ new Map();
156
- const byAgentInvocation = /* @__PURE__ */ new Map();
157
- for (const id of inboundMessageIds) {
158
- const result = LEGACY_RESULT_ID.exec(id);
159
- const reply = result ? void 0 : LEGACY_REPLY_ID.exec(id);
160
- const senderId = result?.[1] ?? reply?.[1];
161
- if (!senderId) continue;
162
- const turnId = reply?.[2];
163
- if (senderId.startsWith("agent-invocation:")) byAgentInvocation.set(id, {
164
- agentInvocationId: senderId,
165
- turnId
166
- });
167
- else if (turnId) senders.set(id, {
168
- conversationId: senderId,
169
- turnId
170
- });
171
- }
172
- if (byAgentInvocation.size === 0) return senders;
173
- const rows = await getSqlExecutor().db().select({
174
- childConversationId: juniorAgentInvocations.childConversationId,
175
- invocationId: juniorAgentInvocations.invocationId
176
- }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.invocationId, [...new Set([...byAgentInvocation.values()].map((s) => s.agentInvocationId))]));
177
- const childOf = new Map(rows.map((row) => [row.invocationId, row.childConversationId]));
178
- for (const [id, { agentInvocationId, turnId }] of byAgentInvocation) {
179
- const conversationId = childOf.get(agentInvocationId);
180
- if (!conversationId) continue;
181
- senders.set(id, {
182
- agentInvocationId,
183
- conversationId,
184
- turnId: turnId ?? getAgentInvocationTurnId(agentInvocationId)
185
- });
186
- }
187
- return senders;
188
- }
189
- // src/chat/conversations/turn-lifecycle.ts
190
- /** Persist correlated turn lifecycle facts with retry-safe terminal exclusion. */
191
- var ConversationTurnLifecycleService = class {
192
- events;
193
- constructor(events) {
194
- this.events = events;
195
- }
196
- /** Record the turn start once after every input message is durable. */
197
- async start(input) {
198
- await this.events.append(input.conversationId, [{
199
- idempotencyKey: `turn:${input.turnId}:started`,
200
- createdAtMs: input.createdAtMs,
201
- data: {
202
- type: "turn_started",
203
- turnId: input.turnId,
204
- inputMessageIds: input.inputMessageIds,
205
- surface: input.surface,
206
- ...input.threadContextThroughSeq === void 0 ? void 0 : { threadContextThroughSeq: input.threadContextThroughSeq }
207
- }
208
- }]);
209
- }
210
- /** Return the input message ids that started a Turn, when it started. */
211
- async loadInputMessageIds(conversationId, turnId) {
212
- const event = await this.events.loadByIdempotencyKey(conversationId, `turn:${turnId}:started`);
213
- return event?.data.type === "turn_started" ? event.data.inputMessageIds : void 0;
214
- }
215
- /** Record a completion that is not a failure once. */
216
- async complete(input) {
217
- await this.events.append(input.conversationId, [{
218
- idempotencyKey: `turn:${input.turnId}:terminal`,
219
- createdAtMs: input.createdAtMs,
220
- data: {
221
- type: "turn_completed",
222
- turnId: input.turnId,
223
- outcome: input.outcome
224
- }
225
- }]);
226
- }
227
- /** Record a classified failure once. Do not store raw error text. */
228
- async fail(input) {
229
- await this.events.append(input.conversationId, [{
230
- idempotencyKey: `turn:${input.turnId}:terminal`,
231
- createdAtMs: input.createdAtMs,
232
- data: {
233
- type: "turn_failed",
234
- turnId: input.turnId,
235
- failureCode: input.failureCode,
236
- ...input.failureReason ? { failureReason: input.failureReason } : void 0,
237
- ...input.eventId ? { eventId: input.eventId } : void 0
238
- }
239
- }]);
240
- }
241
- };
242
- /** Return the Turn lifecycle that records Conversation events. */
243
- function getTurnLifecycle() {
244
- return new ConversationTurnLifecycleService(getConversationEventStore());
245
- }
246
- // src/chat/runtime/turn.ts
247
- /** Classified Slack turn failure carrying the owning Sentry capture outward. */
248
- var ConversationTurnBoundaryError = class extends Error {
249
- eventId;
250
- failureCode;
251
- constructor(args) {
252
- super(args.cause instanceof Error ? args.cause.message : String(args.cause), { cause: args.cause });
253
- this.name = "ConversationTurnBoundaryError";
254
- this.eventId = args.eventId;
255
- this.failureCode = args.failureCode;
256
- }
257
- };
258
- /** Return a classified Slack boundary failure without erasing its cause. */
259
- function getConversationTurnBoundaryError(error) {
260
- return error instanceof ConversationTurnBoundaryError ? error : void 0;
261
- }
262
- /**
263
- * Queue-worker yield routing: respond.ts returns a suspended AgentRunOutcome
264
- * and the Slack executor raises this at the worker boundary so the lease owner
265
- * requeues the conversation.
266
- */
267
- var CooperativeTurnYieldError = class extends Error {
268
- code = "cooperative_turn_yield";
269
- constructor(message = "Agent turn yielded at a safe boundary") {
270
- super(message);
271
- this.name = "CooperativeTurnYieldError";
272
- }
273
- };
274
- function isCooperativeTurnYieldError(error) {
275
- return error instanceof CooperativeTurnYieldError;
276
- }
277
- /** Error indicating durable turn input could not be committed by the worker owner. */
278
- var TurnInputCommitLostError = class extends Error {
279
- code = "turn_input_commit_lost";
280
- constructor(message = "Turn input commit lost its durable owner") {
281
- super(message);
282
- this.name = "TurnInputCommitLostError";
283
- }
284
- };
285
- /** Return whether an error means the durable worker lost input ownership. */
286
- function isTurnInputCommitLostError(error) {
287
- return error instanceof TurnInputCommitLostError;
288
- }
289
- /** Error indicating durable turn input should stay pending for a later worker. */
290
- var TurnInputDeferredError = class extends Error {
291
- code = "turn_input_deferred";
292
- constructor(message = "Turn input is deferred until the active resume ends") {
293
- super(message);
294
- this.name = "TurnInputDeferredError";
295
- }
296
- };
297
- /** Return whether an error means the durable worker should redeliver input later. */
298
- function isTurnInputDeferredError(error) {
299
- return error instanceof TurnInputDeferredError;
300
- }
301
- /** Mark a turn as the active turn in conversation state. */
302
- function startActiveTurn(args) {
303
- args.conversation.processing.activeTurnId = args.nextTurnId;
304
- }
305
- function clearActiveTurn(conversation, sessionId) {
306
- if (!sessionId || conversation.processing.activeTurnId === sessionId) conversation.processing.activeTurnId = void 0;
307
- }
308
- /**
309
- * Close the active turn without marking a Pi session reusable for future
310
- * history. Use this for auth handoffs and recovery replies that end the live
311
- * turn but do not produce a completed Pi session.
312
- */
313
- function markTurnClosed(args) {
314
- clearActiveTurn(args.conversation, args.sessionId);
315
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
316
- }
317
- /**
318
- * Mark a turn as completed after its assistant output has been handled.
319
- */
320
- function markTurnCompleted(args) {
321
- clearActiveTurn(args.conversation, args.sessionId);
322
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
323
- }
324
- /**
325
- * Mark a turn as failed when execution or final user-visible reply delivery
326
- * cannot be completed. If `sessionId` is provided, `activeTurnId` is only
327
- * cleared when it still matches the failing turn.
328
- */
329
- function markTurnFailed(args) {
330
- clearActiveTurn(args.conversation, args.sessionId);
331
- args.conversation.processing.lastCompletedAtMs = args.nowMs;
332
- args.markConversationMessage(args.conversation, args.userMessageId, {
333
- replied: false,
334
- skippedReason: "reply failed"
335
- });
336
- }
337
- // src/chat/runtime/turn-user-message.ts
338
- /** Return the user message for a persisted turn/session, if one exists. */
339
- function getTurnUserMessage(conversation, sessionId) {
340
- for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
341
- const message = conversation.messages[index];
342
- if (message?.role !== "user") continue;
343
- if (buildDeterministicTurnId(message.id) === sessionId) return message;
344
- }
345
- }
346
- /** Return the persisted user-message id for a turn/session, if one exists. */
347
- function getTurnUserMessageId(conversation, sessionId) {
348
- return getTurnUserMessage(conversation, sessionId)?.id;
349
- }
350
- /** Return the Slack timestamp for the user message that a resumed turn acts on. */
351
- function getTurnUserSlackMessageTs(message) {
352
- return parseSlackMessageTs(message?.meta?.slackTs);
353
- }
354
- /** Rebuild attachment context for a resumed turn from the persisted user message. */
355
- function getTurnUserReplyAttachmentContext(message) {
356
- const inboundAttachmentCount = message?.meta?.attachmentCount ?? 0;
357
- const imageAttachmentCount = message?.meta?.imageAttachmentCount ?? 0;
358
- const imagesHydrated = message?.meta?.imagesHydrated === true;
359
- return {
360
- ...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
361
- ...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
362
- };
363
- }
364
- export { getAgentInvocationMessageId as A, ownAgentInvocation as C, getAgentInvocationIdForEvents as D, getAgentInvocationId as E, getNamedAgentConversationId as F, getTurnReplyKey as I, getUnnamedAgentConversationId as L, getAgentInvocationTurnId as M, getAgentReplyMessageId as N, getAgentInvocationIdForMessage as O, getChildAgentLockName as P, buildDeterministicAssistantMessageId as R, listChildMessages as S, readChildMessageSenders as T, ConversationTurnLifecycleService as _, ConversationTurnBoundaryError as a, hasAgentInvocationReply as b, TurnInputDeferredError as c, isTurnInputCommitLostError as d, isTurnInputDeferredError as f, startActiveTurn as g, markTurnFailed as h, getTurnUserSlackMessageTs as i, getAgentInvocationResultMessageId as j, getAgentInvocationIdForResult as k, getConversationTurnBoundaryError as l, markTurnCompleted as m, getTurnUserMessageId as n, CooperativeTurnYieldError as o, markTurnClosed as p, getTurnUserReplyAttachmentContext as r, TurnInputCommitLostError as s, getTurnUserMessage as t, isCooperativeTurnYieldError as u, getTurnLifecycle as v, readChildMessageSender as w, isAgentInvocationResult as x, childMessageSenderMetadata as y, buildDeterministicTurnId as z };
@@ -1,181 +0,0 @@
1
- import { Ms as withSlackRetries, Ts as getSlackClient, xs as SlackActionError } from "./projection-Ce4pmhKP.js";
2
- import * as z from "zod";
3
- // src/chat/slack/users.ts
4
- const profileFieldsSchema = z.object({ fields: z.record(z.string(), z.object({
5
- value: z.string().optional(),
6
- alt: z.string().optional(),
7
- label: z.string().optional()
8
- }).nullable()).nullish() });
9
- function normalizeUser(raw) {
10
- const rawFields = profileFieldsSchema.parse(raw.profile ?? {}).fields;
11
- const profileFields = [];
12
- if (rawFields) for (const [id, field] of Object.entries(rawFields)) {
13
- if (!field) continue;
14
- profileFields.push({
15
- id,
16
- label: field.label || void 0,
17
- value: field.value || void 0,
18
- alt: field.alt || void 0
19
- });
20
- }
21
- return {
22
- id: raw.id ?? "",
23
- team_id: raw.team_id || void 0,
24
- name: raw.name || void 0,
25
- real_name: raw.real_name || raw.profile?.real_name || void 0,
26
- display_name: raw.profile?.display_name || void 0,
27
- title: raw.profile?.title || void 0,
28
- email: raw.profile?.email || void 0,
29
- status_text: raw.profile?.status_text ?? void 0,
30
- status_emoji: raw.profile?.status_emoji ?? void 0,
31
- avatar_url: raw.profile?.image_512 || void 0,
32
- is_bot: raw.is_bot ?? false,
33
- is_deleted: raw.deleted ?? false,
34
- timezone: raw.tz || void 0,
35
- ...profileFields.length > 0 ? { profile_fields: profileFields } : void 0
36
- };
37
- }
38
- function normalizeNameTokens(value) {
39
- return value.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
40
- }
41
- function nameFields(user) {
42
- return [
43
- user.name ?? "",
44
- user.profile?.display_name ?? "",
45
- user.real_name ?? user.profile?.real_name ?? ""
46
- ].map((value) => value.toLowerCase().trim()).filter(Boolean);
47
- }
48
- /** Look up a Slack user by ID, returning the full profile including custom fields. */
49
- async function lookupSlackUserProfile(userId) {
50
- const client = getSlackClient();
51
- const user = (await withSlackRetries(() => client.users.info({ user: userId }), 3, { action: "users.info" })).user;
52
- if (!user) throw new Error(`Slack users.info returned no user for ${userId}`);
53
- return normalizeUser(user);
54
- }
55
- /**
56
- * Look up one Slack user who is a current human member of a workspace.
57
- *
58
- * Returns undefined for a user that Slack cannot find, a deleted user, a bot,
59
- * or a user of another workspace. Other lookup errors propagate.
60
- */
61
- async function lookupActiveSlackWorkspaceMember(userId, teamId) {
62
- let user;
63
- try {
64
- user = await lookupSlackUserProfile(userId);
65
- } catch (error) {
66
- if (error instanceof SlackActionError && error.apiError === "user_not_found") return;
67
- throw error;
68
- }
69
- return user.id === userId && user.team_id === teamId && !user.is_deleted && !user.is_bot ? user : void 0;
70
- }
71
- /** Look up a Slack bot by ID. Returns undefined when Slack has no such bot. */
72
- async function lookupSlackBot(botId) {
73
- try {
74
- return (await withSlackRetries(() => getSlackClient().bots.info({ bot: botId }), 3, { action: "bots.info" })).bot;
75
- } catch (error) {
76
- if (error instanceof SlackActionError && error.apiError === "bot_not_found") return;
77
- throw error;
78
- }
79
- }
80
- /** Look up a Slack user by email. Returns null when no user matches. */
81
- async function lookupSlackUserByEmail(email) {
82
- const client = getSlackClient();
83
- let result;
84
- try {
85
- result = await withSlackRetries(() => client.users.lookupByEmail({ email }), 3, { action: "users.lookupByEmail" });
86
- } catch (error) {
87
- if (error instanceof SlackActionError && error.apiError === "users_not_found") return null;
88
- throw error;
89
- }
90
- const user = result.user;
91
- if (!user) return null;
92
- return normalizeUser(user);
93
- }
94
- /**
95
- * Rank Slack name-search quality for one candidate.
96
- * Exact field and token matches beat field prefixes so a display-name prefix
97
- * cannot outrank a real-name first-name hit.
98
- */
99
- function scoreNameMatch(user, query) {
100
- const queryLower = query.toLowerCase().trim();
101
- if (!queryLower) return 0;
102
- const fields = nameFields(user);
103
- if (fields.length === 0) return 0;
104
- let best = 0;
105
- const queryTokens = normalizeNameTokens(queryLower);
106
- for (const field of fields) {
107
- if (field === queryLower) {
108
- best = Math.max(best, 100);
109
- continue;
110
- }
111
- if (field.startsWith(queryLower)) best = Math.max(best, 70);
112
- else if (field.includes(queryLower)) best = Math.max(best, 25);
113
- const tokens = normalizeNameTokens(field);
114
- for (const token of tokens) if (token === queryLower) best = Math.max(best, 85);
115
- else if (token.startsWith(queryLower)) best = Math.max(best, 60);
116
- if (queryTokens.length > 1 && queryTokens.every((queryToken) => tokens.some((token) => token === queryToken || token.startsWith(queryToken)))) best = Math.max(best, 95);
117
- }
118
- return best;
119
- }
120
- function compareNameMatches(left, right) {
121
- if (right.score !== left.score) return right.score - left.score;
122
- return (left.user.name ?? "").localeCompare(right.user.name ?? "");
123
- }
124
- async function listWorkspaceUsers(options) {
125
- const client = getSlackClient();
126
- const matches = [];
127
- let cursor;
128
- let pages = 0;
129
- let totalScanned = 0;
130
- while (pages < options.maxPages) {
131
- pages++;
132
- const result = await withSlackRetries(() => client.users.list({
133
- limit: 200,
134
- ...cursor ? { cursor } : void 0
135
- }), 3, { action: "users.list" });
136
- const members = result.members ?? [];
137
- totalScanned += members.length;
138
- for (const member of members) {
139
- if (!options.includeDeleted && member.deleted) continue;
140
- if (!options.includeBots && member.is_bot) continue;
141
- if (member.id === "USLACKBOT") continue;
142
- const score = options.score(member);
143
- if (score <= 0) continue;
144
- matches.push({
145
- user: member,
146
- score
147
- });
148
- }
149
- const nextCursor = result.response_metadata?.next_cursor;
150
- if (!nextCursor) {
151
- cursor = void 0;
152
- break;
153
- }
154
- cursor = nextCursor;
155
- }
156
- return {
157
- matches,
158
- searched_pages: pages,
159
- searched_user_count: totalScanned,
160
- truncated: pages >= options.maxPages && Boolean(cursor)
161
- };
162
- }
163
- /** Search workspace users by name with bounded pagination through `users.list`. */
164
- async function searchSlackUsers(options) {
165
- const { query, limit = 10, maxPages = 3, includeDeleted = false, includeBots = false } = options;
166
- const queryLower = query.toLowerCase().trim();
167
- const listed = await listWorkspaceUsers({
168
- maxPages,
169
- includeDeleted,
170
- includeBots,
171
- score: (member) => scoreNameMatch(member, queryLower)
172
- });
173
- listed.matches.sort(compareNameMatches);
174
- return {
175
- users: listed.matches.slice(0, limit).map((m) => normalizeUser(m.user)),
176
- searched_pages: listed.searched_pages,
177
- searched_user_count: listed.searched_user_count,
178
- truncated: listed.truncated
179
- };
180
- }
181
- export { searchSlackUsers as a, lookupSlackUserProfile as i, lookupSlackBot as n, lookupSlackUserByEmail as r, lookupActiveSlackWorkspaceMember as t };