managed-deepagents 0.10.7 → 0.10.8-dev.10

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 (224) hide show
  1. package/README.md +463 -89
  2. package/dist/agent-auth.d.ts +4 -2
  3. package/dist/agent-auth.d.ts.map +1 -1
  4. package/dist/agent-auth.js +3 -1
  5. package/dist/agent-auth.js.map +1 -1
  6. package/dist/channels/address.d.ts +13 -0
  7. package/dist/channels/address.d.ts.map +1 -0
  8. package/dist/channels/address.js +67 -0
  9. package/dist/channels/address.js.map +1 -0
  10. package/dist/channels/assistant-text.d.ts +2 -0
  11. package/dist/channels/assistant-text.d.ts.map +1 -1
  12. package/dist/channels/assistant-text.js +47 -6
  13. package/dist/channels/assistant-text.js.map +1 -1
  14. package/dist/channels/binding.d.ts +7 -0
  15. package/dist/channels/binding.d.ts.map +1 -1
  16. package/dist/channels/binding.js +28 -4
  17. package/dist/channels/binding.js.map +1 -1
  18. package/dist/channels/delivery.d.ts.map +1 -1
  19. package/dist/channels/delivery.js +15 -18
  20. package/dist/channels/delivery.js.map +1 -1
  21. package/dist/channels/github/app-setup.d.ts.map +1 -1
  22. package/dist/channels/github/app-setup.js +86 -3
  23. package/dist/channels/github/app-setup.js.map +1 -1
  24. package/dist/channels/github/index.d.ts +1 -6
  25. package/dist/channels/github/index.d.ts.map +1 -1
  26. package/dist/channels/github/index.js +191 -38
  27. package/dist/channels/github/index.js.map +1 -1
  28. package/dist/channels/github/schema.d.ts +9280 -1622
  29. package/dist/channels/github/schema.d.ts.map +1 -1
  30. package/dist/channels/github/schema.js +164 -0
  31. package/dist/channels/github/schema.js.map +1 -1
  32. package/dist/channels/github/types.d.ts +98 -36
  33. package/dist/channels/github/types.d.ts.map +1 -1
  34. package/dist/channels/http/endpoint.d.ts +33 -9
  35. package/dist/channels/http/endpoint.d.ts.map +1 -1
  36. package/dist/channels/http/endpoint.js +72 -18
  37. package/dist/channels/http/endpoint.js.map +1 -1
  38. package/dist/channels/http/http.d.ts +7 -0
  39. package/dist/channels/http/http.d.ts.map +1 -1
  40. package/dist/channels/http/http.js +273 -27
  41. package/dist/channels/http/http.js.map +1 -1
  42. package/dist/channels/http/index.d.ts.map +1 -1
  43. package/dist/channels/http/index.js +4 -5
  44. package/dist/channels/http/index.js.map +1 -1
  45. package/dist/channels/http/ingress.d.ts +44 -1
  46. package/dist/channels/http/ingress.d.ts.map +1 -1
  47. package/dist/channels/http/ingress.js +63 -0
  48. package/dist/channels/http/ingress.js.map +1 -1
  49. package/dist/channels/http/input-state.d.ts +7 -0
  50. package/dist/channels/http/input-state.d.ts.map +1 -0
  51. package/dist/channels/http/input-state.js +16 -0
  52. package/dist/channels/http/input-state.js.map +1 -0
  53. package/dist/channels/http/provider.d.ts +36 -7
  54. package/dist/channels/http/provider.d.ts.map +1 -1
  55. package/dist/channels/http/provider.js +46 -7
  56. package/dist/channels/http/provider.js.map +1 -1
  57. package/dist/channels/http/types.d.ts +13 -5
  58. package/dist/channels/http/types.d.ts.map +1 -1
  59. package/dist/channels/linear/index.d.ts +0 -5
  60. package/dist/channels/linear/index.d.ts.map +1 -1
  61. package/dist/channels/linear/index.js +94 -21
  62. package/dist/channels/linear/index.js.map +1 -1
  63. package/dist/channels/linear/schema.d.ts +20 -20
  64. package/dist/channels/linear/schema.d.ts.map +1 -1
  65. package/dist/channels/linear/schema.js +20 -1
  66. package/dist/channels/linear/schema.js.map +1 -1
  67. package/dist/channels/linear/types.d.ts +58 -49
  68. package/dist/channels/linear/types.d.ts.map +1 -1
  69. package/dist/channels/reply.d.ts +28 -0
  70. package/dist/channels/reply.d.ts.map +1 -0
  71. package/dist/channels/reply.js +37 -0
  72. package/dist/channels/reply.js.map +1 -0
  73. package/dist/channels/resolve-user.d.ts +3 -2
  74. package/dist/channels/resolve-user.d.ts.map +1 -1
  75. package/dist/channels/resolve-user.js +5 -4
  76. package/dist/channels/resolve-user.js.map +1 -1
  77. package/dist/channels/run-input.d.ts +120 -10
  78. package/dist/channels/run-input.d.ts.map +1 -1
  79. package/dist/channels/run-input.js +233 -16
  80. package/dist/channels/run-input.js.map +1 -1
  81. package/dist/channels/runtime.d.ts +10 -3
  82. package/dist/channels/runtime.d.ts.map +1 -1
  83. package/dist/channels/runtime.js +15 -1
  84. package/dist/channels/runtime.js.map +1 -1
  85. package/dist/channels/schedule-delivery.d.ts +2 -2
  86. package/dist/channels/schedule-delivery.d.ts.map +1 -1
  87. package/dist/channels/slack/events.d.ts +176 -63
  88. package/dist/channels/slack/events.d.ts.map +1 -1
  89. package/dist/channels/slack/events.js +153 -4
  90. package/dist/channels/slack/events.js.map +1 -1
  91. package/dist/channels/slack/files.d.ts +6 -3
  92. package/dist/channels/slack/files.d.ts.map +1 -1
  93. package/dist/channels/slack/files.js +4 -1
  94. package/dist/channels/slack/files.js.map +1 -1
  95. package/dist/channels/slack/index.d.ts +60 -29
  96. package/dist/channels/slack/index.d.ts.map +1 -1
  97. package/dist/channels/slack/index.js +134 -56
  98. package/dist/channels/slack/index.js.map +1 -1
  99. package/dist/channels/trigger/conversation.d.ts +8 -3
  100. package/dist/channels/trigger/conversation.d.ts.map +1 -1
  101. package/dist/channels/trigger/conversation.js +101 -12
  102. package/dist/channels/trigger/conversation.js.map +1 -1
  103. package/dist/channels/trigger/http.d.ts +57 -8
  104. package/dist/channels/trigger/http.d.ts.map +1 -1
  105. package/dist/channels/trigger/http.js +405 -49
  106. package/dist/channels/trigger/http.js.map +1 -1
  107. package/dist/channels/trigger/ingress.d.ts +80 -2
  108. package/dist/channels/trigger/ingress.d.ts.map +1 -1
  109. package/dist/channels/trigger/ingress.js +143 -1
  110. package/dist/channels/trigger/ingress.js.map +1 -1
  111. package/dist/channels/trigger/transport.d.ts +2 -0
  112. package/dist/channels/trigger/transport.d.ts.map +1 -1
  113. package/dist/channels/trigger/transport.js +5 -1
  114. package/dist/channels/trigger/transport.js.map +1 -1
  115. package/dist/channels/trigger/types.d.ts +52 -3
  116. package/dist/channels/trigger/types.d.ts.map +1 -1
  117. package/dist/channels/trigger/types.js +21 -0
  118. package/dist/channels/trigger/types.js.map +1 -1
  119. package/dist/channels/types.d.ts +205 -1
  120. package/dist/channels/types.d.ts.map +1 -1
  121. package/dist/channels/types.js +27 -0
  122. package/dist/channels/types.js.map +1 -1
  123. package/dist/channels/warnings.d.ts +8 -0
  124. package/dist/channels/warnings.d.ts.map +1 -0
  125. package/dist/channels/warnings.js +17 -0
  126. package/dist/channels/warnings.js.map +1 -0
  127. package/dist/connectors/mcp/index.d.ts.map +1 -1
  128. package/dist/connectors/mcp/index.js +12 -4
  129. package/dist/connectors/mcp/index.js.map +1 -1
  130. package/dist/connectors/mcp/instructions.d.ts +30 -0
  131. package/dist/connectors/mcp/instructions.d.ts.map +1 -0
  132. package/dist/connectors/mcp/instructions.js +150 -0
  133. package/dist/connectors/mcp/instructions.js.map +1 -0
  134. package/dist/connectors/mcp/schema.d.ts.map +1 -1
  135. package/dist/connectors/mcp/schema.js +2 -1
  136. package/dist/connectors/mcp/schema.js.map +1 -1
  137. package/dist/connectors/mcp/types.d.ts +10 -0
  138. package/dist/connectors/mcp/types.d.ts.map +1 -1
  139. package/dist/index.d.ts +9 -6
  140. package/dist/index.d.ts.map +1 -1
  141. package/dist/index.js +2 -0
  142. package/dist/index.js.map +1 -1
  143. package/dist/ingress/runs.d.ts +3 -0
  144. package/dist/ingress/runs.d.ts.map +1 -1
  145. package/dist/ingress/runs.js +34 -16
  146. package/dist/ingress/runs.js.map +1 -1
  147. package/dist/memory/define-memory.d.ts +4 -2
  148. package/dist/memory/define-memory.d.ts.map +1 -1
  149. package/dist/memory/define-memory.js +4 -2
  150. package/dist/memory/define-memory.js.map +1 -1
  151. package/dist/namespaces.d.ts +2 -3
  152. package/dist/namespaces.d.ts.map +1 -1
  153. package/dist/namespaces.js +1 -1
  154. package/dist/namespaces.js.map +1 -1
  155. package/dist/run-context.d.ts +8 -0
  156. package/dist/run-context.d.ts.map +1 -1
  157. package/dist/run-context.js +5 -0
  158. package/dist/run-context.js.map +1 -1
  159. package/dist/run-ending-error.d.ts +16 -0
  160. package/dist/run-ending-error.d.ts.map +1 -0
  161. package/dist/run-ending-error.js +16 -0
  162. package/dist/run-ending-error.js.map +1 -0
  163. package/dist/runtime/auth.d.ts +5 -0
  164. package/dist/runtime/auth.d.ts.map +1 -1
  165. package/dist/runtime/auth.js +39 -6
  166. package/dist/runtime/auth.js.map +1 -1
  167. package/dist/runtime/backend.d.ts.map +1 -1
  168. package/dist/runtime/backend.js +7 -1
  169. package/dist/runtime/backend.js.map +1 -1
  170. package/dist/runtime/index.d.ts.map +1 -1
  171. package/dist/runtime/index.js +4 -1
  172. package/dist/runtime/index.js.map +1 -1
  173. package/dist/runtime/managed-thread.d.ts +6 -0
  174. package/dist/runtime/managed-thread.d.ts.map +1 -1
  175. package/dist/runtime/managed-thread.js +38 -2
  176. package/dist/runtime/managed-thread.js.map +1 -1
  177. package/dist/runtime/memory/policy.d.ts.map +1 -1
  178. package/dist/runtime/memory/policy.js +24 -5
  179. package/dist/runtime/memory/policy.js.map +1 -1
  180. package/dist/runtime/parent-run.d.ts +2 -1
  181. package/dist/runtime/parent-run.d.ts.map +1 -1
  182. package/dist/runtime/parent-run.js +9 -6
  183. package/dist/runtime/parent-run.js.map +1 -1
  184. package/dist/runtime/run-input.d.ts +1 -0
  185. package/dist/runtime/run-input.d.ts.map +1 -1
  186. package/dist/runtime/sandbox-manager.d.ts +27 -3
  187. package/dist/runtime/sandbox-manager.d.ts.map +1 -1
  188. package/dist/runtime/sandbox-manager.js +188 -22
  189. package/dist/runtime/sandbox-manager.js.map +1 -1
  190. package/dist/runtime/schedule-auth.d.ts +21 -5
  191. package/dist/runtime/schedule-auth.d.ts.map +1 -1
  192. package/dist/runtime/schedule-auth.js +58 -15
  193. package/dist/runtime/schedule-auth.js.map +1 -1
  194. package/dist/runtime/steering.d.ts +2 -2
  195. package/dist/runtime/steering.d.ts.map +1 -1
  196. package/dist/runtime/steering.js +83 -15
  197. package/dist/runtime/steering.js.map +1 -1
  198. package/dist/runtime/thread-handoff.d.ts +16 -0
  199. package/dist/runtime/thread-handoff.d.ts.map +1 -0
  200. package/dist/runtime/thread-handoff.js +24 -0
  201. package/dist/runtime/thread-handoff.js.map +1 -0
  202. package/dist/runtime/thread-record.d.ts +6 -0
  203. package/dist/runtime/thread-record.d.ts.map +1 -1
  204. package/dist/runtime/thread-record.js +6 -0
  205. package/dist/runtime/thread-record.js.map +1 -1
  206. package/dist/runtime-schedules.d.ts +2 -2
  207. package/dist/runtime-schedules.d.ts.map +1 -1
  208. package/dist/runtime-schedules.js +9 -3
  209. package/dist/runtime-schedules.js.map +1 -1
  210. package/dist/sandbox.d.ts +12 -0
  211. package/dist/sandbox.d.ts.map +1 -1
  212. package/dist/sandbox.js +5 -0
  213. package/dist/sandbox.js.map +1 -1
  214. package/dist/schedules.d.ts +33 -14
  215. package/dist/schedules.d.ts.map +1 -1
  216. package/dist/schedules.js +32 -1
  217. package/dist/schedules.js.map +1 -1
  218. package/dist/telemetry/run.d.ts +2 -1
  219. package/dist/telemetry/run.d.ts.map +1 -1
  220. package/dist/telemetry/run.js.map +1 -1
  221. package/dist/tool-errors.d.ts.map +1 -1
  222. package/dist/tool-errors.js +10 -5
  223. package/dist/tool-errors.js.map +1 -1
  224. package/package.json +7 -7
@@ -1,16 +1,17 @@
1
1
  import { INTERRUPT } from "@langchain/langgraph";
2
2
  import { bindingWithMessages } from "../binding.js";
3
3
  import { randomUUID } from "node:crypto";
4
+ import { v5 as uuidv5 } from "uuid";
4
5
  import { missingWorkspaceConnectionSlug, } from "../../agent-auth.js";
5
6
  import { resolveExternalPrincipalId } from "../../connections.js";
6
7
  import { DEFAULT_REACTION_EMOJI, resolveReactionEmoji, } from "../reactions.js";
7
8
  import { setLogAttributes } from "../../telemetry/otel/index.js";
8
9
  import { logger } from "../../runtime/log.js";
9
10
  import { INTERRUPT_CORRELATION_KEY } from "../../run-context.js";
10
- import { cancelIngressThreadRuns, conversationThreadId, ingressThreadExists, ingressResumeTarget, ingressThreadInterrupts, newerIngressRun, observeIngressAgent, resumeIngressAgent, startIngressAgent, } from "./ingress.js";
11
+ import { DELIVERS_METADATA, STARTED_FROM_METADATA, cancelHandlerThreadRuns, cancelIngressThreadRuns, conversationThreadId, deleteIngressThread, handlerThreadResumeTarget, handlerThreadsKey, ingressThreadExists, ingressRunReportsIn, getIngressThreadState, ingressResumeTarget, ingressThreadInterrupts, newerIngressRun, observeIngressAgent, resumeIngressAgent, startIngressAgent, } from "./ingress.js";
11
12
  import { scheduleIngressWork } from "../../ingress/index.js";
12
13
  import { lookupStatus, rejectedAsBusy, } from "../../ingress/runs.js";
13
- import { runStartOptions } from "../run-input.js";
14
+ import { runStartOptions, } from "../run-input.js";
14
15
  import { createTriggerClient, LANGSMITH_MDA_TRIGGER_SERVER_URL_ENV, TriggerClientError, } from "./client.js";
15
16
  import { IdentityContextUnavailableError, InvalidIdentityContextError, principalIdFromIdentityContext, } from "./identity-context.js";
16
17
  import { resolveTracerSessionId } from "./tracing-project.js";
@@ -20,6 +21,14 @@ import { createTriggerTransport } from "./transport.js";
20
21
  import { parseTriggerChannelEvent, triggerChannelBinding, TRIGGER_SERVICE_KEY_HEADER, normalizedUserPromptResponse, triggerEventActor, } from "./types.js";
21
22
  import { isRecord, nonblankString } from "../../values.js";
22
23
  export { TRIGGER_SERVICE_KEY_HEADER } from "./types.js";
24
+ /**
25
+ * What a message in a thread whose conversation moved to a new thread hears
26
+ * instead of a run (`post(message, { newThread: true, handOff: true })`).
27
+ */
28
+ export const MOVED_AWAY = {
29
+ type: "content",
30
+ content: "This conversation moved to a new thread.",
31
+ };
23
32
  export const ASSISTANT_ID_ENV = "MDA_ASSISTANT_ID";
24
33
  // Raised when the thread cannot say which interrupt an answer belongs to. An
25
34
  // app opts out of this by carrying a correlation id; see INTERRUPT_CORRELATION_KEY.
@@ -156,33 +165,33 @@ export async function handleTriggerChannelEventRequest(request, options) {
156
165
  });
157
166
  /** `resolveUser`'s answer when it holds back the run the delivery would start. */
158
167
  const withheld = user?.type === "principal" ? undefined : user;
168
+ /** Post a reply instead of the run, where the delivery came from. */
169
+ const replyTo = (message) => postReply(message, {
170
+ name: options.channelName,
171
+ provider: options.sourceProvider,
172
+ target: triggerTarget(event),
173
+ transport: createTriggerTransport(client, {
174
+ actionId: event.delivery_id,
175
+ }),
176
+ });
159
177
  /** Post `resolveUser`'s reply, if any, instead of that run. */
160
178
  const withhold = async () => {
161
179
  if (withheld?.type === "reply")
162
- await postReply(withheld.message, {
163
- name: options.channelName,
164
- provider: options.sourceProvider,
165
- target: triggerTarget(event),
166
- transport: createTriggerTransport(client, {
167
- actionId: event.delivery_id,
168
- }),
169
- });
180
+ await replyTo(withheld.message);
170
181
  logNoRun(event, { type: "skipped" });
171
182
  };
172
- const observe = (started) => observeAcceptedRun({
173
- event,
174
- started,
175
- client,
176
- observeAgent: options.observeAgent,
177
- sourceProvider: options.sourceProvider,
178
- sourceThreadKey: event.source_thread_key,
179
- userId,
180
- reactions: options.reactions ?? DEFAULT_REACTION_EMOJI,
181
- ...(options.startedStatus && { startedStatus: options.startedStatus }),
182
- ...(options.showProgress === false && { showProgress: false }),
183
- multitaskStrategy: options.multitaskStrategy,
184
- newerRun: options.newerRun,
185
- });
183
+ /**
184
+ * Post a handler's reply instead of the run. When `resolveUser` held the
185
+ * delivery back, its answer stands instead, as for a run.
186
+ */
187
+ const replyInstead = async (message) => {
188
+ if (withheld)
189
+ return withhold();
190
+ await replyTo(message);
191
+ logNoRun(event, { type: "skipped" });
192
+ };
193
+ /** Only a channel with handlers starts runs on threads they chose. */
194
+ const handlerThreads = options.decideMessage !== undefined;
186
195
  let threadId;
187
196
  try {
188
197
  threadId = await (options.conversationThread ?? conversationThreadId)({
@@ -195,14 +204,75 @@ export async function handleTriggerChannelEventRequest(request, options) {
195
204
  logger.error(`channel thread could not be found (${logger.safeErrorLabel(error)})`);
196
205
  return Response.json({ error: "channel run could not be started" }, { status: 500 });
197
206
  }
198
- const thread = { id: threadId, sourceThreadKey: event.source_thread_key };
207
+ const thread = {
208
+ id: threadId,
209
+ sourceThreadKey: event.source_thread_key,
210
+ getState: () => (options.getThreadState ?? getIngressThreadState)({
211
+ threadId,
212
+ sourceProvider: options.sourceProvider,
213
+ sourceThreadKey: event.source_thread_key,
214
+ userId,
215
+ }),
216
+ };
217
+ /** Whether the run was refused because this conversation handed its thread on. */
218
+ const movedAway = (error) => handedOff(error, options, {
219
+ threadId,
220
+ sourceProvider: options.sourceProvider,
221
+ sourceThreadKey: event.source_thread_key,
222
+ userId,
223
+ });
224
+ const runReportsHere = (runThreadId, sourceThreadKey) => (options.runReportsIn ?? ingressRunReportsIn)({
225
+ threadId: runThreadId,
226
+ sourceProvider: options.sourceProvider,
227
+ sourceThreadKey,
228
+ userId,
229
+ reportsIn: event.source_thread_key,
230
+ }).catch(() => false);
231
+ const pending = options.showProgress !== false &&
232
+ event.type === "message" &&
233
+ asksAgent(options.sourceProvider, event)
234
+ ? pendingStatus(event, client, options.startedStatus, options.schedule, () => runReportsHere(threadId, event.source_thread_key))
235
+ : undefined;
236
+ /** Whether the handler's runs show the status here, and how many of them have not failed to start. */
237
+ let handedHere = false;
238
+ let unstartedHere = 0;
239
+ const observe = async (started, as) => {
240
+ await pending?.posted;
241
+ return observeAcceptedRun({
242
+ event,
243
+ ...(as.reportedFor && { reportedFor: as.reportedFor }),
244
+ started,
245
+ client,
246
+ observeAgent: options.observeAgent,
247
+ sourceProvider: options.sourceProvider,
248
+ sourceThreadKey: as.sourceThreadKey,
249
+ userId,
250
+ reactions: as.react === false
251
+ ? false
252
+ : (options.reactions ?? DEFAULT_REACTION_EMOJI),
253
+ ...(options.startedStatus && { startedStatus: options.startedStatus }),
254
+ ...(options.showProgress === false && { showProgress: false }),
255
+ multitaskStrategy: as.multitaskStrategy,
256
+ newerRun: options.newerRun,
257
+ // Only the conversation's own thread can be handed on.
258
+ ...(started.threadId === threadId &&
259
+ as.sourceThreadKey === event.source_thread_key && {
260
+ handedOff: movedAway,
261
+ }),
262
+ });
263
+ };
199
264
  /**
200
265
  * Whether the delivery starts a turn of its own, which finishes: a message,
201
266
  * or a prompt response that answers no interrupt. Resumes don't.
202
267
  */
203
- let startsTurn = event.type === "message";
268
+ let startsTurn = event.type === "message" || event.type === "provider_event";
204
269
  /** Tell the provider a turn is done, once; a failure is logged. */
205
270
  const finish = async (finished) => {
271
+ if (pending &&
272
+ !handedHere &&
273
+ finished.type !== "run" &&
274
+ (finished.reason === "ignored" || finished.reason === "start"))
275
+ await pending.skip();
206
276
  if (!startsTurn || !options.onFinish)
207
277
  return;
208
278
  const { identity_context: _token, ...message } = event;
@@ -222,14 +292,115 @@ export async function handleTriggerChannelEventRequest(request, options) {
222
292
  logger.error(`channel finish notice failed (${logger.safeErrorLabel(error)})`);
223
293
  }
224
294
  };
295
+ const skipPending = () => {
296
+ if (pending)
297
+ scheduleIngressWork(pending.skip, {
298
+ label: "Channel skipped status",
299
+ schedule: options.schedule,
300
+ });
301
+ };
225
302
  const finishLater = (finished) => {
226
- if (options.onFinish)
303
+ if (options.onFinish || pending)
227
304
  scheduleIngressWork(() => finish(finished), {
228
305
  label: "Channel finish notice",
229
306
  schedule: options.schedule,
230
307
  });
231
308
  };
232
309
  let started;
310
+ let observedAs = {
311
+ sourceThreadKey: event.source_thread_key,
312
+ multitaskStrategy: options.multitaskStrategy,
313
+ };
314
+ /**
315
+ * Start a run on a thread the handler chose, and see it through. Every such
316
+ * thread of the channel's is owned by one key, so Stop and the buttons in
317
+ * the conversation that started a run reach it there. Its status shows in
318
+ * that conversation; it answers there only with `autoPost`. An ephemeral
319
+ * thread is deleted once its run ends, unless the run waits on a decision.
320
+ */
321
+ const runOnThread = async (run, index, react, showsStatus = false) => {
322
+ const owner = handlerThreadsKey(options.channelName);
323
+ const chosen = run.thread;
324
+ const threadId = chosen.mode === "persistent"
325
+ ? chosen.id
326
+ : triggerEphemeralThreadId(options.channelName, event.delivery_id, index);
327
+ const strategy = run.multitaskStrategy ?? options.multitaskStrategy;
328
+ // A run that belongs to another Slack thread reports there, and Stop there stops it.
329
+ const reported = run.conversation
330
+ ? inConversation(event, run.conversation)
331
+ : event;
332
+ const binding = {
333
+ ...bindingWithMessages(triggerChannelBinding(reported, options.sourceProvider, options.channelName), run.messages),
334
+ reply: run.deliverToConversation ? "auto" : "none",
335
+ };
336
+ let threadRun;
337
+ try {
338
+ threadRun = await (options.startAgent ?? startIngressAgent)({
339
+ threadId,
340
+ assistantId,
341
+ sourceProvider: options.sourceProvider,
342
+ sourceThreadKey: owner,
343
+ userId,
344
+ ...runStartOptions(run, {
345
+ [STARTED_FROM_METADATA]: reported.source_thread_key,
346
+ ...(run.deliverToConversation && { [DELIVERS_METADATA]: true }),
347
+ }),
348
+ context: run.context ?? {},
349
+ binding,
350
+ ...(strategy && { multitaskStrategy: strategy }),
351
+ });
352
+ }
353
+ catch (error) {
354
+ const busy = rejectedAsBusy(strategy, error);
355
+ if (busy) {
356
+ logger.info(`channel run rejected: its thread is busy (delivery_id=${logger.logIdentifier(event.delivery_id)})`);
357
+ }
358
+ else {
359
+ logger.error(`channel run could not be started (${logger.safeErrorLabel(error)})`);
360
+ }
361
+ if (showsStatus && !(busy && (await runReportsHere(threadId, owner)))) {
362
+ unstartedHere -= 1;
363
+ if (unstartedHere === 0)
364
+ await pending?.skip();
365
+ }
366
+ return;
367
+ }
368
+ const finished = await observe(threadRun, {
369
+ sourceThreadKey: owner,
370
+ multitaskStrategy: strategy,
371
+ react,
372
+ reportedFor: reported,
373
+ });
374
+ if (chosen.mode === "persistent" ||
375
+ finished.type !== "run" ||
376
+ finished.interrupts.length)
377
+ return;
378
+ try {
379
+ await (options.deleteThread ?? deleteIngressThread)({
380
+ threadId,
381
+ sourceProvider: options.sourceProvider,
382
+ sourceThreadKey: owner,
383
+ userId,
384
+ });
385
+ }
386
+ catch (error) {
387
+ logger.error(`ephemeral channel thread could not be deleted (${logger.safeErrorLabel(error)})`);
388
+ }
389
+ };
390
+ /** Start the handler's runs on its threads; the message's own reaction goes with its conversation's run, else the first. */
391
+ const startOnThreads = (decided) => {
392
+ (decided.runs ?? []).forEach((run, index) => {
393
+ const react = decided.input === undefined && index === 0;
394
+ const showsStatus = decided.input === undefined && !run.conversation;
395
+ handedHere ||= showsStatus;
396
+ if (showsStatus)
397
+ unstartedHere += 1;
398
+ scheduleIngressWork(() => runOnThread(run, index, react, showsStatus), {
399
+ label: "Channel run on a handler's thread",
400
+ schedule: options.schedule,
401
+ });
402
+ });
403
+ };
233
404
  try {
234
405
  const common = {
235
406
  threadId: thread.id,
@@ -248,7 +419,11 @@ export async function handleTriggerChannelEventRequest(request, options) {
248
419
  const decideAndStart = async (route, undecided) => {
249
420
  /** Start the run; `undefined` when `reject` left the thread to its run. */
250
421
  const startRun = async (input) => {
251
- const strategy = options.multitaskStrategy;
422
+ const strategy = input?.multitaskStrategy ?? options.multitaskStrategy;
423
+ observedAs = {
424
+ sourceThreadKey: event.source_thread_key,
425
+ multitaskStrategy: strategy,
426
+ };
252
427
  try {
253
428
  return await (options.startAgent ?? startIngressAgent)({
254
429
  ...common,
@@ -273,18 +448,29 @@ export async function handleTriggerChannelEventRequest(request, options) {
273
448
  scheduleIngressWork(async () => {
274
449
  const decided = await route.decide();
275
450
  if (decided.type !== "input") {
276
- logNoRun(event, decided);
451
+ if (decided.type === "reply")
452
+ await replyInstead(decided.message);
453
+ else
454
+ logNoRun(event, decided);
277
455
  return finish(skipped("ignored"));
278
456
  }
279
457
  if (withheld) {
280
458
  await withhold();
281
459
  return finish(skipped("ignored"));
282
460
  }
461
+ startOnThreads(decided);
462
+ // The handler's runs all went to threads of its choosing.
463
+ if (!decided.input && decided.runs?.length)
464
+ return finish(skipped("ignored"));
283
465
  let run;
284
466
  try {
285
467
  run = await startRun(decided.input);
286
468
  }
287
469
  catch (error) {
470
+ if (await movedAway(error)) {
471
+ await replyInstead(MOVED_AWAY);
472
+ return finish(skipped("ignored"));
473
+ }
288
474
  logger.error(`channel run could not be started (${logger.safeErrorLabel(error)})`, error);
289
475
  return finish({
290
476
  type: "failed",
@@ -292,23 +478,36 @@ export async function handleTriggerChannelEventRequest(request, options) {
292
478
  interrupts: [],
293
479
  });
294
480
  }
295
- await finish(run ? await observe(run) : skipped("rejected"));
481
+ await finish(run ? await observe(run, observedAs) : skipped("rejected"));
296
482
  }, { label: "Channel event decision", schedule: options.schedule });
297
483
  return acceptedResponse(event);
298
484
  }
299
- if (route?.type === "skipped") {
300
- logNoRun(event, route);
485
+ if (route?.type === "skipped" || route?.type === "reply") {
486
+ if (route.type === "reply")
487
+ await replyInstead(route.message);
488
+ else
489
+ logNoRun(event, route);
301
490
  finishLater(skipped("ignored"));
302
491
  return acceptedResponse(event);
303
492
  }
304
493
  // Trigger Server may deliver it again, which finishes on its own.
305
- if (route?.type === "failed")
494
+ if (route?.type === "failed") {
495
+ skipPending();
306
496
  return startFailedResponse();
497
+ }
307
498
  if (withheld) {
308
499
  await withhold();
309
500
  finishLater(skipped("ignored"));
310
501
  return acceptedResponse(event);
311
502
  }
503
+ if (route?.type === "input") {
504
+ startOnThreads(route);
505
+ if (!route.input && route.runs?.length) {
506
+ // The handler's runs all went to threads of its choosing.
507
+ finishLater(skipped("ignored"));
508
+ return acceptedResponse(event);
509
+ }
510
+ }
312
511
  const run = await startRun(route?.input);
313
512
  if (!run) {
314
513
  finishLater(skipped("rejected"));
@@ -330,21 +529,36 @@ export async function handleTriggerChannelEventRequest(request, options) {
330
529
  started = outcome;
331
530
  break;
332
531
  }
532
+ case "provider_event": {
533
+ // Only a handler starts a run for a provider event.
534
+ const route = await options.decideProviderEvent?.(event, thread, actor);
535
+ const outcome = await decideAndStart(route ?? { type: "skipped" }, () => []);
536
+ if (outcome instanceof Response)
537
+ return outcome;
538
+ started = outcome;
539
+ break;
540
+ }
333
541
  case "interrupt_resume": {
334
542
  if (withheld) {
335
543
  await withhold();
336
544
  return acceptedResponse(event);
337
545
  }
338
- // The answer may belong to a paused async subagent.
339
- const target = await (options.resumeTarget ?? ingressResumeTarget)({
340
- ...common,
341
- interruptIds: Object.keys(event.interaction.resume),
342
- });
546
+ // The answer may belong to a paused async subagent, or to a run this
547
+ // conversation's message started on a thread its handler chose.
548
+ const answered = await answeredThread(common, Object.keys(event.interaction.resume), handlerThreads, options);
343
549
  started = await (options.resumeAgent ?? resumeIngressAgent)({
344
550
  ...common,
345
- ...target,
551
+ ...answered.target,
552
+ // The resumed run is the one Stop and the next answer look for.
553
+ ...(answered.handler && {
554
+ sourceThreadKey: answered.handler.sourceThreadKey,
555
+ binding: { ...common.binding, reply: answered.handler.reply },
556
+ metadata: answered.handler.runMetadata,
557
+ }),
346
558
  resume: event.interaction.resume,
347
559
  });
560
+ if (answered.handler)
561
+ observedAs = { sourceThreadKey: answered.handler.sourceThreadKey };
348
562
  break;
349
563
  }
350
564
  case "user_prompt_response": {
@@ -388,10 +602,16 @@ export async function handleTriggerChannelEventRequest(request, options) {
388
602
  logger.warn(`channel user prompt response could not be matched to an interrupt (${error.message}, delivery_id=${logger.logIdentifier(event.delivery_id)}, event_id=${logger.logIdentifier(event.event_id)})`);
389
603
  return acceptedResponse(event);
390
604
  }
605
+ if (await movedAway(error)) {
606
+ await replyInstead(MOVED_AWAY);
607
+ finishLater(skipped("ignored"));
608
+ return acceptedResponse(event);
609
+ }
391
610
  logger.error(`channel run could not be started (${logger.safeErrorLabel(error)})`, error);
611
+ skipPending();
392
612
  return startFailedResponse();
393
613
  }
394
- scheduleIngressWork(async () => finish(await observe(started)), {
614
+ scheduleIngressWork(async () => finish(await observe(started, observedAs)), {
395
615
  label: "Channel run observation",
396
616
  schedule: options.schedule,
397
617
  });
@@ -419,10 +639,64 @@ function logNoRun(event, decision) {
419
639
  function decidedRun(input, binding) {
420
640
  return {
421
641
  ...runStartOptions(input),
422
- binding: bindingWithMessages(binding, input.messages),
642
+ binding: {
643
+ ...bindingWithMessages(binding, input.messages),
644
+ ...(input.reply && { reply: input.reply }),
645
+ },
423
646
  context: input.context ?? {},
424
647
  };
425
648
  }
649
+ function triggerEphemeralThreadId(channelName, deliveryId, index) {
650
+ return uuidv5(`mda-thread:v1:trigger-ephemeral:${JSON.stringify([channelName, deliveryId, index])}`, uuidv5.URL);
651
+ }
652
+ /**
653
+ * The thread an answer resumes: the conversation's, one of its subagents', or
654
+ * else the handler thread a run this conversation's message started waits on.
655
+ * A failed search of the handler threads resumes the conversation, as before.
656
+ */
657
+ async function answeredThread(common, interruptIds, handlerThreads, options) {
658
+ const target = await (options.resumeTarget ?? ingressResumeTarget)({
659
+ ...common,
660
+ interruptIds,
661
+ });
662
+ if (!handlerThreads || target.threadId !== common.threadId)
663
+ return { target };
664
+ try {
665
+ const parked = await (options.threadInterrupts ?? ingressThreadInterrupts)(common);
666
+ if (parked.some(({ id }) => id !== undefined && interruptIds.includes(id)))
667
+ return { target };
668
+ const handler = await (options.handlerResumeTarget ?? handlerThreadResumeTarget)({
669
+ channelName: options.channelName,
670
+ sourceProvider: common.sourceProvider,
671
+ startedFrom: common.sourceThreadKey,
672
+ interruptIds,
673
+ userId: common.userId,
674
+ });
675
+ return handler ? { target: handler, handler } : { target };
676
+ }
677
+ catch (error) {
678
+ logger.warn(`channel handler threads could not be searched; the answer resumes the conversation (${logger.safeErrorLabel(error)})`);
679
+ return { target };
680
+ }
681
+ }
682
+ /**
683
+ * Whether a refused run is a conversation that handed its thread to a new
684
+ * one. Ingress creates a conversation's thread before its first run, so its
685
+ * own thread refuses a run with a not-found or conflict only once another
686
+ * conversation owns it, and then this one can no longer see it. Any other
687
+ * failure, or a failed lookup, is not a move.
688
+ */
689
+ async function handedOff(error, options, common) {
690
+ const status = lookupStatus(error);
691
+ if (status !== 404 && status !== 409)
692
+ return false;
693
+ try {
694
+ return !(await (options.threadExists ?? ingressThreadExists)(common));
695
+ }
696
+ catch {
697
+ return false;
698
+ }
699
+ }
426
700
  function startFailedResponse() {
427
701
  return Response.json({ error: "channel run could not be started" }, { status: 500 });
428
702
  }
@@ -430,7 +704,9 @@ function startFailedResponse() {
430
704
  * Stop the source thread's runs; each run's observer reports `run.cancelled`.
431
705
  *
432
706
  * Runs are cancelled as the thread's channel principal, so the managed owner
433
- * filter confines the cancel to this source conversation.
707
+ * filter confines the cancel to this source conversation. On threads the
708
+ * channel's handlers chose, only the runs this conversation's messages
709
+ * started are cancelled; another conversation's run there goes on.
434
710
  */
435
711
  async function cancelEventRuns(event, userId, options) {
436
712
  let cancelled;
@@ -450,6 +726,21 @@ async function cancelEventRuns(event, userId, options) {
450
726
  logger.error(`channel runs could not be cancelled (${logger.safeErrorLabel(error)})`);
451
727
  return Response.json({ error: "channel runs could not be cancelled" }, { status: 500 });
452
728
  }
729
+ // Only a channel with handlers starts runs on threads they chose.
730
+ if (options.decideMessage) {
731
+ try {
732
+ cancelled += await (options.cancelHandlerRuns ?? cancelHandlerThreadRuns)({
733
+ channelName: options.channelName,
734
+ sourceProvider: options.sourceProvider,
735
+ startedFrom: event.source_thread_key,
736
+ userId,
737
+ });
738
+ }
739
+ catch (error) {
740
+ // The conversation's own runs are cancelled; only a handler thread's may go on.
741
+ logger.error(`channel runs on handler threads could not be cancelled (${logger.safeErrorLabel(error)})`);
742
+ }
743
+ }
453
744
  logger.info(`Channel runs cancelled (count=${cancelled}, delivery_id=${logger.logIdentifier(event.delivery_id)})`);
454
745
  return acceptedResponse(event);
455
746
  }
@@ -519,6 +810,66 @@ function interruptCorrelationId(value) {
519
810
  return undefined;
520
811
  return nonblankString(value[INTERRUPT_CORRELATION_KEY]);
521
812
  }
813
+ /**
814
+ * The event as the Slack thread a run belongs to sees it: that thread's
815
+ * address and key, in the event's Slack app and workspace. The event as it
816
+ * is when its key isn't a Slack thread's.
817
+ */
818
+ function inConversation(event, conversation) {
819
+ const parts = event.source_thread_key.split(":");
820
+ if (parts.length !== 6 || parts[0] !== "slack" || parts[1] !== "v1") {
821
+ logger.error(`channel run conversation ignored: the event is not from a Slack thread (delivery_id=${logger.logIdentifier(event.delivery_id)})`);
822
+ return event;
823
+ }
824
+ return {
825
+ ...event,
826
+ address: {
827
+ conversation_id: conversation.conversation_id,
828
+ thread_id: conversation.thread_id,
829
+ },
830
+ source_thread_key: [
831
+ ...parts.slice(0, 4),
832
+ conversation.conversation_id,
833
+ conversation.thread_id,
834
+ ].join(":"),
835
+ };
836
+ }
837
+ /**
838
+ * Posts `run.pending` as the message arrives, and `run.skipped` if it starts
839
+ * no run, unless a run active in the conversation still shows the status.
840
+ */
841
+ function pendingStatus(event, client, status, schedule, runActive) {
842
+ const post = async (type, message) => {
843
+ logger.info(`Channel outgoing event (type=${type}, delivery_id=${logger.logIdentifier(event.delivery_id)}, channel_id=${logger.logIdentifier(event.channel_id)})`);
844
+ await bestEffort(client.postRuntimeEvent(event.channel_id, {
845
+ id: randomUUID(),
846
+ type,
847
+ delivery_id: event.delivery_id,
848
+ source_thread_key: event.source_thread_key,
849
+ address: event.address,
850
+ ...(message && { message }),
851
+ }));
852
+ };
853
+ const posted = new Promise((resolve) => scheduleIngressWork(() => post("run.pending", status?.message).finally(resolve), { label: "Channel pending status", schedule }));
854
+ return {
855
+ posted,
856
+ skip: async () => {
857
+ await posted;
858
+ if (!(await runActive()))
859
+ await post("run.skipped");
860
+ },
861
+ };
862
+ }
863
+ /**
864
+ * A Slack `app_mention` or DM. A mention's channel `message` copy doesn't count,
865
+ * so it can't clear the status its `app_mention` shows.
866
+ */
867
+ function asksAgent(sourceProvider, event) {
868
+ const rawEvent = event.raw_event;
869
+ return (sourceProvider === "slack" &&
870
+ isRecord(rawEvent) &&
871
+ (rawEvent.type === "app_mention" || rawEvent.channel_type === "im"));
872
+ }
522
873
  async function observeAcceptedRun(input) {
523
874
  const { event, started, client } = input;
524
875
  const run = {
@@ -532,12 +883,13 @@ async function observeAcceptedRun(input) {
532
883
  const replaceable = input.multitaskStrategy === "interrupt" ||
533
884
  input.multitaskStrategy === "rollback";
534
885
  /**
535
- * A newer message's run took the thread over; it reports to Slack, so this
536
- * run says nothing that would stop or fail the thread's status. It ended
537
- * `interrupted`, as the HTTP channel reports a replaced run.
886
+ * A newer message's run, or the conversation the run handed its thread to,
887
+ * took the thread over and reports to Slack, so this run says nothing that
888
+ * would stop or fail the thread's status. It ended `interrupted`, as the
889
+ * HTTP channel reports a replaced run.
538
890
  */
539
- const replaced = () => {
540
- logger.info(`channel run was replaced by a newer message (delivery_id=${logger.logIdentifier(event.delivery_id)}, run_id=${logger.logIdentifier(started.runId)})`);
891
+ const replaced = (why = "was replaced by a newer message") => {
892
+ logger.info(`channel run ${why} (delivery_id=${logger.logIdentifier(event.delivery_id)}, run_id=${logger.logIdentifier(started.runId)})`);
541
893
  return {
542
894
  type: "run",
543
895
  run: { id: started.runId, status: "interrupted" },
@@ -547,7 +899,7 @@ async function observeAcceptedRun(input) {
547
899
  const lifecycle = async (type, message, status) => {
548
900
  logger.info(`Channel outgoing event (type=${type}, delivery_id=${logger.logIdentifier(event.delivery_id)}, channel_id=${logger.logIdentifier(event.channel_id)}, run_id=${logger.logIdentifier(started.runId)})`);
549
901
  const request = {
550
- ...runtimeEvent(type, event, started, message, await resolveTracerSessionId()),
902
+ ...runtimeEvent(type, input.reportedFor ?? event, started, message, await resolveTracerSessionId()),
551
903
  ...status,
552
904
  ...(input.showProgress === false && { show_progress: false }),
553
905
  };
@@ -568,8 +920,12 @@ async function observeAcceptedRun(input) {
568
920
  observed = await (input.observeAgent ?? observeIngressAgent)(run);
569
921
  }
570
922
  catch (error) {
923
+ const notFound = lookupStatus(error) === 404;
924
+ // The run handed its thread to a new conversation, which reports it now.
925
+ if (notFound && (await input.handedOff?.(error)))
926
+ return replaced("handed its thread to a new conversation");
571
927
  // `rollback` cancels, then deletes, the run a newer message replaced.
572
- if (replaceable && lookupStatus(error) === 404)
928
+ if (replaceable && notFound)
573
929
  return replaced();
574
930
  await lifecycle("run.failed", missingConnectionFailureMessage(error));
575
931
  return { type: "failed", reason: "observe", interrupts: [] };