@dudousxd/nestjs-agent 1.14.0 → 1.15.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.
@@ -30,10 +30,10 @@ __export(durable_exports, {
30
30
  module.exports = __toCommonJS(durable_exports);
31
31
 
32
32
  // src/durable/agent-run.workflow.ts
33
- var import_nestjs_agent_core2 = require("@dudousxd/nestjs-agent-core");
33
+ var import_nestjs_agent_core3 = require("@dudousxd/nestjs-agent-core");
34
34
  var import_nestjs_durable2 = require("@dudousxd/nestjs-durable");
35
35
  var import_nestjs_durable_core = require("@dudousxd/nestjs-durable-core");
36
- var import_common2 = require("@nestjs/common");
36
+ var import_common3 = require("@nestjs/common");
37
37
 
38
38
  // src/agent-deps.ts
39
39
  function utcDay(date = /* @__PURE__ */ new Date()) {
@@ -51,9 +51,8 @@ function childSinkWriter(writer) {
51
51
  }
52
52
  __name(childSinkWriter, "childSinkWriter");
53
53
 
54
- // src/durable/agent-run.steps.ts
54
+ // src/queue/chat-queue.service.ts
55
55
  var import_nestjs_agent_core = require("@dudousxd/nestjs-agent-core");
56
- var import_nestjs_durable = require("@dudousxd/nestjs-durable");
57
56
  var import_common = require("@nestjs/common");
58
57
  function _ts_decorate(decorators, target, key, desc) {
59
58
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -81,6 +80,434 @@ function _ts_param(paramIndex, decorator) {
81
80
  };
82
81
  }
83
82
  __name(_ts_param, "_ts_param");
83
+ var MAX_DRAIN_ATTEMPTS = 8;
84
+ var ChatQueueService = class _ChatQueueService {
85
+ static {
86
+ __name(this, "ChatQueueService");
87
+ }
88
+ store;
89
+ sink;
90
+ quotaProvider;
91
+ options;
92
+ staging;
93
+ logger = new import_common.Logger(_ChatQueueService.name);
94
+ /**
95
+ * Runs this process claimed a thread for and has not handed to a runner yet. A holder in here is
96
+ * alive whatever the runner says — it simply has not registered the run yet.
97
+ */
98
+ starting = /* @__PURE__ */ new Set();
99
+ constructor(store, sink, quotaProvider, options, staging) {
100
+ this.store = store;
101
+ this.sink = sink;
102
+ this.quotaProvider = quotaProvider;
103
+ this.options = options;
104
+ this.staging = staging;
105
+ }
106
+ /** Whether the bound store can hold a queue. Without one, a busy thread is not queued. */
107
+ get supported() {
108
+ return (0, import_nestjs_agent_core.isChatQueueStore)(this.store);
109
+ }
110
+ /** The bound store as a queue store, or a 501 naming what is missing. */
111
+ queueStore() {
112
+ if (!(0, import_nestjs_agent_core.isChatQueueStore)(this.store)) {
113
+ throw new import_common.NotImplementedException("Queueing messages requires an AgentStore that implements ChatQueueStore (enqueueMessage, listQueue, \u2026, claimActiveStream, releaseActiveStream); the bound store does not.");
114
+ }
115
+ return this.store;
116
+ }
117
+ async state(threadId) {
118
+ const store = this.queueStore();
119
+ const [items, paused] = await Promise.all([
120
+ store.listQueue(threadId),
121
+ store.queuePause(threadId)
122
+ ]);
123
+ return {
124
+ items: items.map(import_nestjs_agent_core.queuedMessageView),
125
+ paused
126
+ };
127
+ }
128
+ /**
129
+ * Whether `holder` is still running. A run this process is about to start is; otherwise the
130
+ * runner decides, and a runner that cannot tell says yes.
131
+ */
132
+ async isAlive(holder, runner) {
133
+ if (this.starting.has(holder)) {
134
+ return true;
135
+ }
136
+ if (typeof runner.isRunActive !== "function") {
137
+ return true;
138
+ }
139
+ try {
140
+ return await runner.isRunActive(holder);
141
+ } catch {
142
+ return true;
143
+ }
144
+ }
145
+ /**
146
+ * The run holding `threadId`, or `null` when it is free — a holder the runner reports dead counts
147
+ * as free, and is returned as `stale` so the caller can claim over it.
148
+ */
149
+ async holder(threadId, runner) {
150
+ const holder = await this.queueStore().activeRunForThread(threadId);
151
+ if (holder === null) {
152
+ return {
153
+ live: null,
154
+ stale: null
155
+ };
156
+ }
157
+ return await this.isAlive(holder, runner) ? {
158
+ live: holder,
159
+ stale: null
160
+ } : {
161
+ live: null,
162
+ stale: holder
163
+ };
164
+ }
165
+ /**
166
+ * Decide what follows a TOP-LEVEL run that is settling on `threadId`, and move the thread there:
167
+ * hand it to the next queued message (claimed and popped here, started by the caller), or pause
168
+ * the queue, or release the thread. Call it BEFORE the run's terminal frame, so a client reading
169
+ * the stream learns what comes next from the `queue` frame, and so the thread is already free
170
+ * when the client sees the run end.
171
+ *
172
+ * A no-op returning `{}` on a store without a queue.
173
+ */
174
+ async plan(args) {
175
+ if (!(0, import_nestjs_agent_core.isChatQueueStore)(this.store)) {
176
+ return {};
177
+ }
178
+ const store = this.store;
179
+ const { threadId, outcome } = args;
180
+ if (await store.activeRunForThread(threadId) !== args.runId) {
181
+ return {};
182
+ }
183
+ let holding = args.runId;
184
+ for (let attempt = 0; attempt < MAX_DRAIN_ATTEMPTS; attempt += 1) {
185
+ const items = await store.listQueue(threadId);
186
+ const head = items[0];
187
+ if (head === void 0) {
188
+ if (holding !== null) {
189
+ await store.releaseActiveStream(threadId, holding);
190
+ holding = null;
191
+ continue;
192
+ }
193
+ return {};
194
+ }
195
+ let pause = await store.queuePause(threadId);
196
+ if (pause === null) {
197
+ const reason = pauseReasonFor(outcome, head);
198
+ if (reason !== null) {
199
+ pause = {
200
+ reason,
201
+ ...outcome === "failed" && args.error !== void 0 ? {
202
+ message: args.error
203
+ } : {},
204
+ at: (/* @__PURE__ */ new Date()).toISOString()
205
+ };
206
+ await store.setQueuePause(threadId, pause);
207
+ }
208
+ }
209
+ if (pause === null) {
210
+ const blocked = await this.quotaBlock(head.actor);
211
+ if (blocked !== null) {
212
+ pause = {
213
+ reason: "quota_exceeded",
214
+ message: blocked,
215
+ at: (/* @__PURE__ */ new Date()).toISOString()
216
+ };
217
+ await store.setQueuePause(threadId, pause);
218
+ }
219
+ }
220
+ if (pause !== null) {
221
+ if (holding !== null) {
222
+ await store.releaseActiveStream(threadId, holding);
223
+ }
224
+ return {
225
+ frame: queueFrame(items, pause)
226
+ };
227
+ }
228
+ const claimed = await store.claimActiveStream(threadId, head.id, holding !== null ? {
229
+ replacing: holding
230
+ } : {});
231
+ if (!claimed) {
232
+ return {};
233
+ }
234
+ holding = head.id;
235
+ if (!await store.removeQueuedMessage(head.id)) {
236
+ await store.releaseActiveStream(threadId, head.id);
237
+ holding = null;
238
+ continue;
239
+ }
240
+ const next = {
241
+ runId: head.id,
242
+ messageId: head.id,
243
+ input: await this.inputFor(head)
244
+ };
245
+ return {
246
+ next,
247
+ frame: queueFrame(items.slice(1), null, {
248
+ messageId: head.id,
249
+ runId: head.id
250
+ })
251
+ };
252
+ }
253
+ if (holding !== null) {
254
+ await store.releaseActiveStream(threadId, holding);
255
+ }
256
+ return {};
257
+ }
258
+ /**
259
+ * {@link plan}, then start what it picked with `start`. What an in-process settle (the inline
260
+ * runner, a durable cancel issued outside a workflow) calls; answers the frame to write.
261
+ */
262
+ async handoff(args, start) {
263
+ const plan = await this.plan(args);
264
+ if (plan.next === void 0) {
265
+ return plan.frame;
266
+ }
267
+ return await this.launch(args.threadId, plan.next, start) ? plan.frame : this.pausedFrame(args.threadId);
268
+ }
269
+ /**
270
+ * Start the head of an IDLE thread's queue — after a send queued behind a run that turned out to
271
+ * be gone, after a resume, after a stale holder. Does nothing while a live run holds the thread
272
+ * (its settle drains) or while the queue is paused. Answers the started run's id, if any.
273
+ */
274
+ async kick(threadId, runner) {
275
+ if (!(0, import_nestjs_agent_core.isChatQueueStore)(this.store)) {
276
+ return void 0;
277
+ }
278
+ const { live, stale } = await this.holder(threadId, runner);
279
+ if (live !== null) {
280
+ return void 0;
281
+ }
282
+ if (stale !== null) {
283
+ this.logger.warn(`thread ${threadId} was held by run ${stale}, which is no longer running`);
284
+ }
285
+ const plan = await this.plan({
286
+ threadId,
287
+ runId: stale,
288
+ outcome: "completed"
289
+ });
290
+ if (plan.next === void 0) {
291
+ return void 0;
292
+ }
293
+ const started = await this.launch(threadId, plan.next, (input, runId) => runner.start(input, {
294
+ runId
295
+ }));
296
+ if (started && plan.frame !== void 0) {
297
+ await this.write(plan.next.runId, plan.frame);
298
+ }
299
+ return started ? plan.next.runId : void 0;
300
+ }
301
+ /**
302
+ * Start a turn the thread is already claimed for. On failure the message goes back to the head of
303
+ * the queue, the queue pauses (`start_failed`), and the claim is released — nothing is lost and
304
+ * nothing is left holding the thread.
305
+ */
306
+ async launch(threadId, next, start) {
307
+ this.starting.add(next.runId);
308
+ try {
309
+ await start(next.input, next.runId);
310
+ return true;
311
+ } catch (error) {
312
+ const message = error instanceof Error ? error.message : String(error);
313
+ this.logger.error(`queued message ${next.messageId} could not start: ${message}`);
314
+ await this.restore(threadId, next, "start_failed", message);
315
+ return false;
316
+ } finally {
317
+ this.starting.delete(next.runId);
318
+ }
319
+ }
320
+ /** Put a turn that never started back at the head of its queue, paused, and free the thread. */
321
+ async restore(threadId, next, reason, message) {
322
+ const store = this.queueStore();
323
+ const { input } = next;
324
+ await store.enqueueMessage({
325
+ threadId,
326
+ actor: input.actor,
327
+ content: input.userText,
328
+ at: "head",
329
+ ...input.attachments !== void 0 ? {
330
+ attachments: input.attachments
331
+ } : {},
332
+ ...input.agentName !== void 0 ? {
333
+ agentName: input.agentName
334
+ } : {},
335
+ ...input.model !== void 0 ? {
336
+ model: input.model
337
+ } : {},
338
+ ...input.pageContext !== void 0 ? {
339
+ pageContext: input.pageContext
340
+ } : {}
341
+ });
342
+ await store.setQueuePause(threadId, {
343
+ reason,
344
+ message,
345
+ at: (/* @__PURE__ */ new Date()).toISOString()
346
+ });
347
+ await store.releaseActiveStream(threadId, next.runId);
348
+ }
349
+ /** A `queue` frame with the thread's current state. */
350
+ async pausedFrame(threadId) {
351
+ return {
352
+ kind: "queue",
353
+ queue: await this.state(threadId)
354
+ };
355
+ }
356
+ /**
357
+ * Tell whoever is watching the thread that its queue changed: a `queue` frame into the stream of
358
+ * the run holding it. Best-effort — a thread nobody is streaming has no one to tell, and the next
359
+ * read of the thread carries the queue anyway.
360
+ */
361
+ async publish(threadId) {
362
+ const state = await this.state(threadId);
363
+ const holder = await this.queueStore().activeRunForThread(threadId);
364
+ if (holder !== null) {
365
+ await this.write(holder, {
366
+ kind: "queue",
367
+ queue: state
368
+ }).catch((error) => {
369
+ this.logger.warn(`could not publish the queue of thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`);
370
+ });
371
+ }
372
+ return state;
373
+ }
374
+ async write(runId, frame) {
375
+ const writer = await this.sink.open(runId);
376
+ await writer.write((0, import_nestjs_agent_core.encodeStreamEvent)(frame));
377
+ }
378
+ /** Why `actor` may not start a turn now (the quota message), or `null`. */
379
+ async quotaBlock(actor) {
380
+ if (this.options?.quota === void 0 || this.quotaProvider === void 0) {
381
+ return null;
382
+ }
383
+ try {
384
+ const { blocked } = await this.quotaProvider.report({
385
+ actor
386
+ });
387
+ if (blocked === void 0) {
388
+ return null;
389
+ }
390
+ return blocked.reason ?? `The ${blocked.period === "day" ? "daily" : "monthly"} quota is used up`;
391
+ } catch {
392
+ return null;
393
+ }
394
+ }
395
+ /**
396
+ * The turn a queued message starts: everything it was queued with, today's date, and its
397
+ * attachments' urls minted afresh — the ones stored at enqueue time may have expired while it
398
+ * waited. An attachment the staging store no longer resolves keeps its stored url.
399
+ */
400
+ async inputFor(message) {
401
+ const attachments = await this.freshAttachments(message.actor, message.attachments ?? []);
402
+ return {
403
+ threadId: message.threadId,
404
+ actor: message.actor,
405
+ userText: message.content,
406
+ day: utcDay(),
407
+ ...message.agentName !== void 0 ? {
408
+ agentName: message.agentName
409
+ } : {},
410
+ ...attachments.length > 0 ? {
411
+ attachments
412
+ } : {},
413
+ ...message.pageContext !== void 0 ? {
414
+ pageContext: message.pageContext
415
+ } : {},
416
+ ...message.model !== void 0 ? {
417
+ model: message.model
418
+ } : {}
419
+ };
420
+ }
421
+ async freshAttachments(actor, attachments) {
422
+ const staging = this.staging;
423
+ if (attachments.length === 0 || staging === void 0 || typeof staging.resolve !== "function") {
424
+ return attachments;
425
+ }
426
+ return Promise.all(attachments.map(async (attachment) => {
427
+ try {
428
+ return await staging.resolve({
429
+ mediaId: attachment.mediaId,
430
+ actor
431
+ }) ?? attachment;
432
+ } catch {
433
+ return attachment;
434
+ }
435
+ }));
436
+ }
437
+ };
438
+ ChatQueueService = _ts_decorate([
439
+ (0, import_common.Injectable)(),
440
+ _ts_param(0, (0, import_common.Inject)(import_nestjs_agent_core.AGENT_STORE)),
441
+ _ts_param(1, (0, import_common.Inject)(import_nestjs_agent_core.AGENT_SINK)),
442
+ _ts_param(2, (0, import_common.Optional)()),
443
+ _ts_param(2, (0, import_common.Inject)(import_nestjs_agent_core.AGENT_QUOTA_PROVIDER)),
444
+ _ts_param(3, (0, import_common.Optional)()),
445
+ _ts_param(3, (0, import_common.Inject)(import_nestjs_agent_core.AGENT_OPTIONS)),
446
+ _ts_param(4, (0, import_common.Optional)()),
447
+ _ts_param(4, (0, import_common.Inject)(import_nestjs_agent_core.AGENT_ATTACHMENT_STAGING)),
448
+ _ts_metadata("design:type", Function),
449
+ _ts_metadata("design:paramtypes", [
450
+ typeof AgentStore === "undefined" ? Object : AgentStore,
451
+ typeof TokenStreamSink === "undefined" ? Object : TokenStreamSink,
452
+ typeof QuotaProvider === "undefined" ? Object : QuotaProvider,
453
+ typeof Pick === "undefined" ? Object : Pick,
454
+ typeof AttachmentStagingStore === "undefined" ? Object : AttachmentStagingStore
455
+ ])
456
+ ], ChatQueueService);
457
+ function pauseReasonFor(outcome, head) {
458
+ if (outcome === "failed") {
459
+ return "run_failed";
460
+ }
461
+ if (outcome === "cancelled" && head.interrupt !== true) {
462
+ return "cancelled";
463
+ }
464
+ return null;
465
+ }
466
+ __name(pauseReasonFor, "pauseReasonFor");
467
+ function queueFrame(items, paused, started) {
468
+ return {
469
+ kind: "queue",
470
+ queue: {
471
+ items: items.map(import_nestjs_agent_core.queuedMessageView),
472
+ paused
473
+ },
474
+ ...started !== void 0 ? {
475
+ started
476
+ } : {}
477
+ };
478
+ }
479
+ __name(queueFrame, "queueFrame");
480
+
481
+ // src/durable/agent-run.steps.ts
482
+ var import_nestjs_agent_core2 = require("@dudousxd/nestjs-agent-core");
483
+ var import_nestjs_durable = require("@dudousxd/nestjs-durable");
484
+ var import_common2 = require("@nestjs/common");
485
+ function _ts_decorate2(decorators, target, key, desc) {
486
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
487
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
488
+ r = Reflect.decorate(decorators, target, key, desc);
489
+ } else {
490
+ for (var i = decorators.length - 1; i >= 0; i--) {
491
+ if (d = decorators[i]) {
492
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
493
+ }
494
+ }
495
+ }
496
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
497
+ }
498
+ __name(_ts_decorate2, "_ts_decorate");
499
+ function _ts_metadata2(metadataKey, metadataValue) {
500
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
501
+ return Reflect.metadata(metadataKey, metadataValue);
502
+ }
503
+ }
504
+ __name(_ts_metadata2, "_ts_metadata");
505
+ function _ts_param2(paramIndex, decorator) {
506
+ return function(target, key) {
507
+ decorator(target, key, paramIndex);
508
+ };
509
+ }
510
+ __name(_ts_param2, "_ts_param");
84
511
  var AgentRunSteps = class {
85
512
  static {
86
513
  __name(this, "AgentRunSteps");
@@ -97,9 +524,9 @@ var AgentRunSteps = class {
97
524
  */
98
525
  async llm(input) {
99
526
  const deps = this.factory.forAgent(input.agentName);
100
- const tools = (0, import_nestjs_agent_core.withMemoryTool)({
101
- tools: (0, import_nestjs_agent_core.withSkillTool)({
102
- tools: (0, import_nestjs_agent_core.withAskTool)({
527
+ const tools = (0, import_nestjs_agent_core2.withMemoryTool)({
528
+ tools: (0, import_nestjs_agent_core2.withSkillTool)({
529
+ tools: (0, import_nestjs_agent_core2.withAskTool)({
103
530
  tools: await deps.registry.definitionsFor(input.actor, deps.rolesPolicy, deps.toolAllowList, {
104
531
  ...input.threadId !== void 0 ? {
105
532
  threadId: input.threadId
@@ -114,7 +541,7 @@ var AgentRunSteps = class {
114
541
  }),
115
542
  enabled: deps.memory?.provider.write !== void 0
116
543
  });
117
- const buffer = input.bufferOutput === true ? (0, import_nestjs_agent_core.createFrameBuffer)() : void 0;
544
+ const buffer = input.bufferOutput === true ? (0, import_nestjs_agent_core2.createFrameBuffer)() : void 0;
118
545
  let writer;
119
546
  if (buffer !== void 0) {
120
547
  writer = buffer.writer;
@@ -122,8 +549,8 @@ var AgentRunSteps = class {
122
549
  const opened = await deps.sink.open(input.sinkRunId);
123
550
  writer = input.childSink ? childSinkWriter(opened) : opened;
124
551
  }
125
- const frames = (0, import_nestjs_agent_core.observeTurnFrames)(writer);
126
- const turn = (0, import_nestjs_agent_core.withTurnFrames)(await (0, import_nestjs_agent_core.traceLlmTurn)(input.runId, input.step, () => deps.model.runTurn({
552
+ const frames = (0, import_nestjs_agent_core2.observeTurnFrames)(writer);
553
+ const turn = (0, import_nestjs_agent_core2.withTurnFrames)(await (0, import_nestjs_agent_core2.traceLlmTurn)(input.runId, input.step, () => deps.model.runTurn({
127
554
  system: input.system,
128
555
  messages: input.messages,
129
556
  tools,
@@ -132,7 +559,7 @@ var AgentRunSteps = class {
132
559
  model: input.model
133
560
  } : {}
134
561
  })), frames.summary());
135
- const stamped = (0, import_nestjs_agent_core.stampToolKinds)(turn, deps);
562
+ const stamped = (0, import_nestjs_agent_core2.stampToolKinds)(turn, deps);
136
563
  return buffer === void 0 ? stamped : {
137
564
  ...stamped,
138
565
  bufferedFrames: buffer.frames()
@@ -155,9 +582,9 @@ var AgentRunSteps = class {
155
582
  }
156
583
  const sinkRunId = input.sinkRunId;
157
584
  let opened;
158
- const ui = (0, import_nestjs_agent_core.createUiCollector)(input.toolCallId, sinkRunId === void 0 ? void 0 : async (event) => {
585
+ const ui = (0, import_nestjs_agent_core2.createUiCollector)(input.toolCallId, sinkRunId === void 0 ? void 0 : async (event) => {
159
586
  opened ??= Promise.resolve(deps.sink.open(sinkRunId)).then((writer) => input.childSink === true ? childSinkWriter(writer) : writer);
160
- await (await opened).write((0, import_nestjs_agent_core.encodeStreamEvent)(event));
587
+ await (await opened).write((0, import_nestjs_agent_core2.encodeStreamEvent)(event));
161
588
  });
162
589
  const ctx = {
163
590
  ...input.ctx,
@@ -171,17 +598,17 @@ var AgentRunSteps = class {
171
598
  classify: localClassify
172
599
  } : {}
173
600
  };
174
- const output = await (0, import_nestjs_agent_core.traceToolExecution)(input.ctx.runId, {
601
+ const output = await (0, import_nestjs_agent_core2.traceToolExecution)(input.ctx.runId, {
175
602
  toolCallId: input.toolCallId,
176
603
  toolName: input.toolName,
177
604
  toolType: input.toolType
178
- }, () => (0, import_nestjs_agent_core.invokeWithTransientRetry)(() => {
605
+ }, () => (0, import_nestjs_agent_core2.invokeWithTransientRetry)(() => {
179
606
  ui.restart();
180
607
  const invocation = deps.registry.invoke(input.toolName, input.input, ctx, deps.rolesPolicy);
181
- return input.timeoutMs !== void 0 ? (0, import_nestjs_agent_core.withToolTimeout)(invocation, input.timeoutMs, input.toolName) : invocation;
608
+ return input.timeoutMs !== void 0 ? (0, import_nestjs_agent_core2.withToolTimeout)(invocation, input.timeoutMs, input.toolName) : invocation;
182
609
  }, transientRetry, {
183
610
  onRetry: /* @__PURE__ */ __name((attempt, error) => {
184
- (0, import_nestjs_agent_core.publishAgentToolRetry)({
611
+ (0, import_nestjs_agent_core2.publishAgentToolRetry)({
185
612
  toolName: input.toolName,
186
613
  toolCallId: input.toolCallId,
187
614
  attempt,
@@ -189,38 +616,38 @@ var AgentRunSteps = class {
189
616
  });
190
617
  }, "onRetry")
191
618
  }));
192
- return input.collectUi === true ? (0, import_nestjs_agent_core.wrapToolStepOutput)(output, ui.components()) : output;
619
+ return input.collectUi === true ? (0, import_nestjs_agent_core2.wrapToolStepOutput)(output, ui.components()) : output;
193
620
  }
194
621
  };
195
- _ts_decorate([
622
+ _ts_decorate2([
196
623
  (0, import_nestjs_durable.Step)({
197
624
  retries: 3
198
625
  }),
199
- _ts_metadata("design:type", Function),
200
- _ts_metadata("design:paramtypes", [
626
+ _ts_metadata2("design:type", Function),
627
+ _ts_metadata2("design:paramtypes", [
201
628
  typeof DispatchedLlmInput === "undefined" ? Object : DispatchedLlmInput
202
629
  ]),
203
- _ts_metadata("design:returntype", Promise)
630
+ _ts_metadata2("design:returntype", Promise)
204
631
  ], AgentRunSteps.prototype, "llm", null);
205
- _ts_decorate([
632
+ _ts_decorate2([
206
633
  (0, import_nestjs_durable.Step)(),
207
- _ts_metadata("design:type", Function),
208
- _ts_metadata("design:paramtypes", [
634
+ _ts_metadata2("design:type", Function),
635
+ _ts_metadata2("design:paramtypes", [
209
636
  typeof DispatchedToolInput === "undefined" ? Object : DispatchedToolInput
210
637
  ]),
211
- _ts_metadata("design:returntype", Promise)
638
+ _ts_metadata2("design:returntype", Promise)
212
639
  ], AgentRunSteps.prototype, "tool", null);
213
- AgentRunSteps = _ts_decorate([
214
- (0, import_common.Injectable)(),
215
- _ts_param(0, (0, import_common.Inject)(import_nestjs_agent_core.AGENT_DEPS_FACTORY)),
216
- _ts_metadata("design:type", Function),
217
- _ts_metadata("design:paramtypes", [
640
+ AgentRunSteps = _ts_decorate2([
641
+ (0, import_common2.Injectable)(),
642
+ _ts_param2(0, (0, import_common2.Inject)(import_nestjs_agent_core2.AGENT_DEPS_FACTORY)),
643
+ _ts_metadata2("design:type", Function),
644
+ _ts_metadata2("design:paramtypes", [
218
645
  typeof AgentDepsFactory === "undefined" ? Object : AgentDepsFactory
219
646
  ])
220
647
  ], AgentRunSteps);
221
648
 
222
649
  // src/durable/agent-run.workflow.ts
223
- function _ts_decorate2(decorators, target, key, desc) {
650
+ function _ts_decorate3(decorators, target, key, desc) {
224
651
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
225
652
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
226
653
  r = Reflect.decorate(decorators, target, key, desc);
@@ -233,19 +660,19 @@ function _ts_decorate2(decorators, target, key, desc) {
233
660
  }
234
661
  return c > 3 && r && Object.defineProperty(target, key, r), r;
235
662
  }
236
- __name(_ts_decorate2, "_ts_decorate");
237
- function _ts_metadata2(metadataKey, metadataValue) {
663
+ __name(_ts_decorate3, "_ts_decorate");
664
+ function _ts_metadata3(metadataKey, metadataValue) {
238
665
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
239
666
  return Reflect.metadata(metadataKey, metadataValue);
240
667
  }
241
668
  }
242
- __name(_ts_metadata2, "_ts_metadata");
243
- function _ts_param2(paramIndex, decorator) {
669
+ __name(_ts_metadata3, "_ts_metadata");
670
+ function _ts_param3(paramIndex, decorator) {
244
671
  return function(target, key) {
245
672
  decorator(target, key, paramIndex);
246
673
  };
247
674
  }
248
- __name(_ts_param2, "_ts_param");
675
+ __name(_ts_param3, "_ts_param");
249
676
  var AgentRunWorkflow = class _AgentRunWorkflow {
250
677
  static {
251
678
  __name(this, "AgentRunWorkflow");
@@ -253,10 +680,63 @@ var AgentRunWorkflow = class _AgentRunWorkflow {
253
680
  factory;
254
681
  store;
255
682
  runs;
256
- constructor(factory, store, runs) {
683
+ queue;
684
+ constructor(factory, store, runs, queue) {
257
685
  this.factory = factory;
258
686
  this.store = store;
259
687
  this.runs = runs;
688
+ this.queue = queue;
689
+ }
690
+ /**
691
+ * Move the thread past this settling turn — to the next queued message, started here as a
692
+ * fire-and-forget `ctx.startChild` under the message's own id, or to a paused/empty queue — and
693
+ * answer the `queue` frame to write before the turn's terminal.
694
+ *
695
+ * Journaled: the decision (which message, claimed and popped) is one `localStep`, so a replay
696
+ * reads it back instead of popping a second message, and the start is the runtime's own
697
+ * replay-safe spawn. Gated by `ctx.patched`, so a run recorded before the queue existed replays
698
+ * against the history it has. A no-op for a sub-agent's run and on a store without a queue.
699
+ */
700
+ async advanceQueue(ctx, input, outcome, error) {
701
+ const queue = this.queue;
702
+ if (queue === void 0 || !queue.supported || input.sinkRunId !== void 0 || input.deliverTo !== void 0) {
703
+ return void 0;
704
+ }
705
+ if (!await ctx.patched("agent:chat-queue")) {
706
+ return void 0;
707
+ }
708
+ const plan = await ctx.localStep(`queue:${outcome}`, async () => {
709
+ try {
710
+ const settled = outcome === "completed" && await this.isCancelled(ctx.runId) ? "cancelled" : outcome;
711
+ return await queue.plan({
712
+ threadId: input.threadId,
713
+ runId: ctx.runId,
714
+ outcome: settled,
715
+ ...error !== void 0 ? {
716
+ error
717
+ } : {}
718
+ });
719
+ } catch {
720
+ return {};
721
+ }
722
+ });
723
+ const next = plan.next;
724
+ if (next === void 0) {
725
+ return plan.frame;
726
+ }
727
+ try {
728
+ await ctx.startChild(_AgentRunWorkflow, next.input, next.runId);
729
+ return plan.frame;
730
+ } catch (failure) {
731
+ if ((0, import_nestjs_durable_core.isWorkflowControlFlowSignal)(failure)) {
732
+ throw failure;
733
+ }
734
+ const reason = failure instanceof Error ? failure.message : String(failure);
735
+ return ctx.localStep("queue:restore", async () => {
736
+ await queue.restore(input.threadId, next, "start_failed", reason);
737
+ return queue.pausedFrame(input.threadId);
738
+ });
739
+ }
260
740
  }
261
741
  /**
262
742
  * Has someone asked this run to stop? Read from the runtime's own run status, which is where
@@ -294,7 +774,7 @@ var AgentRunWorkflow = class _AgentRunWorkflow {
294
774
  if (delivery === void 0) {
295
775
  return;
296
776
  }
297
- await ctx.localStep("deliver:detached:unsettled", () => (0, import_nestjs_agent_core2.settleUnsettledDelegation)({
777
+ await ctx.localStep("deliver:detached:unsettled", () => (0, import_nestjs_agent_core3.settleUnsettledDelegation)({
298
778
  store: this.store,
299
779
  delivery,
300
780
  agent: input.agentName ?? "default",
@@ -322,7 +802,25 @@ var AgentRunWorkflow = class _AgentRunWorkflow {
322
802
  const hooks = {
323
803
  runId: ctx.runId,
324
804
  // A child forwards into the top-level sink but must not end/fail it (the top-level run owns it).
325
- openSink: /* @__PURE__ */ __name(async () => input.sinkRunId !== void 0 ? childSinkWriter(await deps.sink.open(sinkRunId)) : deps.sink.open(ctx.runId), "openSink"),
805
+ // A thread's own turn hands the thread to its queue just before the loop ends the stream, so
806
+ // the reader learns what runs next from the `queue` frame, before the end.
807
+ openSink: /* @__PURE__ */ __name(async () => {
808
+ if (input.sinkRunId !== void 0) {
809
+ return childSinkWriter(await deps.sink.open(sinkRunId));
810
+ }
811
+ const writer = await deps.sink.open(ctx.runId);
812
+ return {
813
+ write: /* @__PURE__ */ __name((chunk) => writer.write(chunk), "write"),
814
+ fail: /* @__PURE__ */ __name((failure) => writer.fail(failure), "fail"),
815
+ end: /* @__PURE__ */ __name(async () => {
816
+ const frame = await this.advanceQueue(ctx, input, "completed");
817
+ if (frame !== void 0) {
818
+ await writer.write((0, import_nestjs_agent_core3.encodeStreamEvent)(frame));
819
+ }
820
+ await writer.end();
821
+ }, "end")
822
+ };
823
+ }, "openSink"),
326
824
  // A policy's time to live becomes the signal wait's own timeout: the runtime journals the
327
825
  // deadline on the first call (a position of its own, reached only for a call the journal says
328
826
  // has a ttl) and wakes the run when it passes. The lapse comes back as a Decision rather than a
@@ -347,7 +845,7 @@ var AgentRunWorkflow = class _AgentRunWorkflow {
347
845
  // await, so launching a batch in one tick — what `settleAll` does — fixes the block of
348
846
  // positions in call order however the tools then settle. `ctx.patched` keeps a run that
349
847
  // recorded the one-call-at-a-time shape replaying against that shape.
350
- parallel: import_nestjs_agent_core2.settleAll,
848
+ parallel: import_nestjs_agent_core3.settleAll,
351
849
  cancelled: /* @__PURE__ */ __name(() => this.isCancelled(ctx.runId), "cancelled"),
352
850
  patched: /* @__PURE__ */ __name((id) => ctx.patched(id), "patched"),
353
851
  // Dispatched-step suspends must escape the loop's tool catch — control flow, not a tool
@@ -441,29 +939,29 @@ var AgentRunWorkflow = class _AgentRunWorkflow {
441
939
  } : {}
442
940
  };
443
941
  try {
444
- const result = await (0, import_nestjs_agent_core2.runAgentLoop)({
942
+ const result = await (0, import_nestjs_agent_core3.runAgentLoop)({
445
943
  ...deps,
446
944
  day
447
945
  }, input, hooks);
448
- await ctx.localStep("deactivate", () => this.store.setActiveStream(input.threadId, null));
946
+ await ctx.localStep("deactivate", () => (0, import_nestjs_agent_core3.releaseThreadRun)(this.store, input.threadId, ctx.runId));
449
947
  return result;
450
948
  } catch (error) {
451
949
  if ((0, import_nestjs_durable_core.isWorkflowControlFlowSignal)(error)) {
452
950
  throw error;
453
951
  }
454
- if (error instanceof import_nestjs_agent_core2.RunCancelledError) {
455
- await ctx.localStep("deactivate", () => this.store.setActiveStream(input.threadId, null));
952
+ if (error instanceof import_nestjs_agent_core3.RunCancelledError) {
953
+ await ctx.localStep("deactivate", () => (0, import_nestjs_agent_core3.releaseThreadRun)(this.store, input.threadId, ctx.runId));
456
954
  await this.settleDetachedParent(ctx, input, {
457
955
  status: "cancelled"
458
956
  });
459
957
  throw error;
460
958
  }
461
- if ((0, import_nestjs_agent_core2.isReplayIntegrityError)(error)) {
959
+ if ((0, import_nestjs_agent_core3.isReplayIntegrityError)(error)) {
462
960
  const failure = {
463
961
  code: "run_failed",
464
962
  message: error.message
465
963
  };
466
- (0, import_nestjs_agent_core2.publishAgentRunFailed)({
964
+ (0, import_nestjs_agent_core3.publishAgentRunFailed)({
467
965
  runId: ctx.runId,
468
966
  ...failure
469
967
  });
@@ -471,8 +969,8 @@ var AgentRunWorkflow = class _AgentRunWorkflow {
471
969
  throw error;
472
970
  }
473
971
  const message = error instanceof Error ? error.message : String(error);
474
- const code = (0, import_nestjs_agent_core2.agentFailureCode)(error);
475
- (0, import_nestjs_agent_core2.publishAgentRunFailed)({
972
+ const code = (0, import_nestjs_agent_core3.agentFailureCode)(error);
973
+ (0, import_nestjs_agent_core3.publishAgentRunFailed)({
476
974
  runId: ctx.runId,
477
975
  code,
478
976
  message
@@ -483,12 +981,16 @@ var AgentRunWorkflow = class _AgentRunWorkflow {
483
981
  errorCode: code,
484
982
  errorMessage: message
485
983
  }) ?? Promise.resolve());
486
- await ctx.localStep("deactivate", () => this.store.setActiveStream(input.threadId, null));
984
+ const queueFrame2 = await this.advanceQueue(ctx, input, "failed", message);
985
+ await ctx.localStep("deactivate", () => (0, import_nestjs_agent_core3.releaseThreadRun)(this.store, input.threadId, ctx.runId));
487
986
  await this.settleDetachedParent(ctx, input, {
488
987
  status: "failed",
489
988
  error: message
490
989
  });
491
990
  const writer = await hooks.openSink();
991
+ if (queueFrame2 !== void 0) {
992
+ await writer.write((0, import_nestjs_agent_core3.encodeStreamEvent)(queueFrame2));
993
+ }
492
994
  await writer.fail({
493
995
  code,
494
996
  message
@@ -497,21 +999,23 @@ var AgentRunWorkflow = class _AgentRunWorkflow {
497
999
  }
498
1000
  }
499
1001
  };
500
- AgentRunWorkflow = _ts_decorate2([
501
- (0, import_common2.Injectable)(),
1002
+ AgentRunWorkflow = _ts_decorate3([
1003
+ (0, import_common3.Injectable)(),
502
1004
  (0, import_nestjs_durable2.Workflow)({
503
1005
  name: "agent.run",
504
1006
  version: "1"
505
1007
  }),
506
- _ts_param2(0, (0, import_common2.Inject)(import_nestjs_agent_core2.AGENT_DEPS_FACTORY)),
507
- _ts_param2(1, (0, import_common2.Inject)(import_nestjs_agent_core2.AGENT_STORE)),
508
- _ts_param2(2, (0, import_common2.Optional)()),
509
- _ts_param2(2, (0, import_common2.Inject)(import_nestjs_durable2.RUN_GATEWAY)),
510
- _ts_metadata2("design:type", Function),
511
- _ts_metadata2("design:paramtypes", [
1008
+ _ts_param3(0, (0, import_common3.Inject)(import_nestjs_agent_core3.AGENT_DEPS_FACTORY)),
1009
+ _ts_param3(1, (0, import_common3.Inject)(import_nestjs_agent_core3.AGENT_STORE)),
1010
+ _ts_param3(2, (0, import_common3.Optional)()),
1011
+ _ts_param3(2, (0, import_common3.Inject)(import_nestjs_durable2.RUN_GATEWAY)),
1012
+ _ts_param3(3, (0, import_common3.Optional)()),
1013
+ _ts_metadata3("design:type", Function),
1014
+ _ts_metadata3("design:paramtypes", [
512
1015
  typeof AgentDepsFactory === "undefined" ? Object : AgentDepsFactory,
513
1016
  typeof AgentStore === "undefined" ? Object : AgentStore,
514
- typeof RunGateway === "undefined" ? Object : RunGateway
1017
+ typeof RunGateway === "undefined" ? Object : RunGateway,
1018
+ typeof ChatQueueService === "undefined" ? Object : ChatQueueService
515
1019
  ])
516
1020
  ], AgentRunWorkflow);
517
1021
  function isSignalTimeout(error) {
@@ -521,13 +1025,13 @@ __name(isSignalTimeout, "isSignalTimeout");
521
1025
 
522
1026
  // src/durable/durable-agent-runner.ts
523
1027
  var import_node_crypto = require("crypto");
524
- var import_nestjs_agent_core4 = require("@dudousxd/nestjs-agent-core");
1028
+ var import_nestjs_agent_core5 = require("@dudousxd/nestjs-agent-core");
525
1029
  var import_nestjs_durable3 = require("@dudousxd/nestjs-durable");
526
1030
  var import_nestjs_durable_core2 = require("@dudousxd/nestjs-durable-core");
527
- var import_common3 = require("@nestjs/common");
1031
+ var import_common4 = require("@nestjs/common");
528
1032
 
529
1033
  // src/in-process-sink.ts
530
- var import_nestjs_agent_core3 = require("@dudousxd/nestjs-agent-core");
1034
+ var import_nestjs_agent_core4 = require("@dudousxd/nestjs-agent-core");
531
1035
  var InProcessTokenStreamSink = class {
532
1036
  static {
533
1037
  __name(this, "InProcessTokenStreamSink");
@@ -582,7 +1086,7 @@ var InProcessTokenStreamSink = class {
582
1086
  }
583
1087
  if (buf.ended) {
584
1088
  if (buf.failure !== void 0) {
585
- throw new import_nestjs_agent_core3.AgentStreamError(buf.failure);
1089
+ throw new import_nestjs_agent_core4.AgentStreamError(buf.failure);
586
1090
  }
587
1091
  return;
588
1092
  }
@@ -595,7 +1099,7 @@ var InProcessTokenStreamSink = class {
595
1099
  };
596
1100
 
597
1101
  // src/durable/durable-agent-runner.ts
598
- function _ts_decorate3(decorators, target, key, desc) {
1102
+ function _ts_decorate4(decorators, target, key, desc) {
599
1103
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
600
1104
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
601
1105
  r = Reflect.decorate(decorators, target, key, desc);
@@ -608,19 +1112,19 @@ function _ts_decorate3(decorators, target, key, desc) {
608
1112
  }
609
1113
  return c > 3 && r && Object.defineProperty(target, key, r), r;
610
1114
  }
611
- __name(_ts_decorate3, "_ts_decorate");
612
- function _ts_metadata3(metadataKey, metadataValue) {
1115
+ __name(_ts_decorate4, "_ts_decorate");
1116
+ function _ts_metadata4(metadataKey, metadataValue) {
613
1117
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
614
1118
  return Reflect.metadata(metadataKey, metadataValue);
615
1119
  }
616
1120
  }
617
- __name(_ts_metadata3, "_ts_metadata");
618
- function _ts_param3(paramIndex, decorator) {
1121
+ __name(_ts_metadata4, "_ts_metadata");
1122
+ function _ts_param4(paramIndex, decorator) {
619
1123
  return function(target, key) {
620
1124
  decorator(target, key, paramIndex);
621
1125
  };
622
1126
  }
623
- __name(_ts_param3, "_ts_param");
1127
+ __name(_ts_param4, "_ts_param");
624
1128
  function threadOfRun(input) {
625
1129
  if (typeof input !== "object" || input === null || !("threadId" in input)) {
626
1130
  return void 0;
@@ -628,6 +1132,10 @@ function threadOfRun(input) {
628
1132
  return typeof input.threadId === "string" ? input.threadId : void 0;
629
1133
  }
630
1134
  __name(threadOfRun, "threadOfRun");
1135
+ function isThreadTurn(input) {
1136
+ return typeof input === "object" && input !== null && input.sinkRunId === void 0 && input.deliverTo === void 0;
1137
+ }
1138
+ __name(isThreadTurn, "isThreadTurn");
631
1139
  var DurableAgentRunner = class _DurableAgentRunner {
632
1140
  static {
633
1141
  __name(this, "DurableAgentRunner");
@@ -636,22 +1144,24 @@ var DurableAgentRunner = class _DurableAgentRunner {
636
1144
  runs;
637
1145
  store;
638
1146
  sink;
639
- logger = new import_common3.Logger(_DurableAgentRunner.name);
640
- constructor(workflows, runs, store, sink) {
1147
+ queue;
1148
+ logger = new import_common4.Logger(_DurableAgentRunner.name);
1149
+ constructor(workflows, runs, store, sink, queue) {
641
1150
  this.workflows = workflows;
642
1151
  this.runs = runs;
643
1152
  this.store = store;
644
1153
  this.sink = sink;
1154
+ this.queue = queue;
645
1155
  if (this.sink instanceof InProcessTokenStreamSink) {
646
1156
  this.logger.warn("durable: true with the default InProcessTokenStreamSink, which only buffers tokens in this process. The worker that runs the turn \u2014 and the one that serves its dispatched `llm` step \u2014 cannot stream into this buffer. Wire a cross-process TokenStreamSink (e.g. a Redis pub/sub sink) via AgentModule.forRoot({ sink }) before running multi-pod.");
647
1157
  }
648
1158
  }
649
- async start(input) {
1159
+ async start(input, options = {}) {
650
1160
  const stamped = {
651
1161
  ...input,
652
1162
  day: input.day ?? utcDay()
653
1163
  };
654
- const runId = (0, import_node_crypto.randomUUID)();
1164
+ const runId = options.runId ?? (0, import_node_crypto.randomUUID)();
655
1165
  try {
656
1166
  await this.workflows.start(AgentRunWorkflow, stamped, runId);
657
1167
  } catch (error) {
@@ -663,6 +1173,19 @@ var DurableAgentRunner = class _DurableAgentRunner {
663
1173
  runId
664
1174
  };
665
1175
  }
1176
+ /**
1177
+ * From the runtime's own run row. A run it does not know yet counts as running — a queued turn is
1178
+ * claimed before its `startChild` lands — and so does one it cannot be asked about: only a run the
1179
+ * runtime reports settled (`completed`/`failed`/`cancelled`/`dead`) is stale.
1180
+ */
1181
+ async isRunActive(runId) {
1182
+ try {
1183
+ const status = (await this.runs.getRunDetail(runId))?.run.status;
1184
+ return !(status === "completed" || status === "failed" || status === "cancelled" || status === "dead");
1185
+ } catch {
1186
+ return true;
1187
+ }
1188
+ }
666
1189
  async signal(runId, toolCallId2, reply) {
667
1190
  await this.workflows.signal(`tool:${runId}:${toolCallId2}`, reply);
668
1191
  }
@@ -692,15 +1215,32 @@ var DurableAgentRunner = class _DurableAgentRunner {
692
1215
  */
693
1216
  async cancel(runId) {
694
1217
  this.logger.log(`cancelling agent run ${runId}`);
695
- const threadId = await this.threadOf(runId);
1218
+ const input = await this.inputOf(runId);
1219
+ const threadId = threadOfRun(input);
696
1220
  await this.runs.cancel(runId, {
697
1221
  compensate: true
698
1222
  });
1223
+ const writer = await this.sink.open(runId);
699
1224
  if (threadId !== void 0) {
700
- await this.store.setActiveStream(threadId, null);
1225
+ if (this.queue?.supported === true && isThreadTurn(input)) {
1226
+ try {
1227
+ const frame = await this.queue.handoff({
1228
+ threadId,
1229
+ runId,
1230
+ outcome: "cancelled"
1231
+ }, (next, nextRunId) => this.start(next, {
1232
+ runId: nextRunId
1233
+ }));
1234
+ if (frame !== void 0) {
1235
+ await writer.write((0, import_nestjs_agent_core5.encodeStreamEvent)(frame));
1236
+ }
1237
+ } catch (error) {
1238
+ this.logger.error(`could not advance the queue of thread ${threadId} after cancelling ${runId}: ${error instanceof Error ? error.message : String(error)}`);
1239
+ }
1240
+ }
1241
+ await (0, import_nestjs_agent_core5.releaseThreadRun)(this.store, threadId, runId);
701
1242
  }
702
- const writer = await this.sink.open(runId);
703
- await writer.write((0, import_nestjs_agent_core4.encodeStreamEvent)({
1243
+ await writer.write((0, import_nestjs_agent_core5.encodeStreamEvent)({
704
1244
  kind: "cancelled"
705
1245
  }));
706
1246
  await writer.end();
@@ -710,7 +1250,7 @@ var DurableAgentRunner = class _DurableAgentRunner {
710
1250
  });
711
1251
  }
712
1252
  /**
713
- * Which thread a run was streaming, or `undefined` where the gateway cannot say.
1253
+ * The input a run was started with (which thread it was streaming), or `undefined` where the gateway cannot say.
714
1254
  *
715
1255
  * A read failure answers `undefined` instead of propagating, the same posture `AgentRunWorkflow`
716
1256
  * takes for its own cancel observation: failing to ask is not an answer worth failing a cancel
@@ -719,32 +1259,34 @@ var DurableAgentRunner = class _DurableAgentRunner {
719
1259
  * with a subscriber holding a stream that never settles, from the one call whose entire job is to
720
1260
  * make a run stop.
721
1261
  */
722
- async threadOf(runId) {
1262
+ async inputOf(runId) {
723
1263
  try {
724
- return threadOfRun((await this.runs.getRunDetail(runId))?.run.input);
1264
+ return (await this.runs.getRunDetail(runId))?.run.input;
725
1265
  } catch {
726
1266
  return void 0;
727
1267
  }
728
1268
  }
729
1269
  };
730
- DurableAgentRunner = _ts_decorate3([
731
- (0, import_common3.Injectable)(),
732
- _ts_param3(1, (0, import_common3.Inject)(import_nestjs_durable3.RUN_GATEWAY)),
733
- _ts_param3(2, (0, import_common3.Inject)(import_nestjs_agent_core4.AGENT_STORE)),
734
- _ts_param3(3, (0, import_common3.Inject)(import_nestjs_agent_core4.AGENT_SINK)),
735
- _ts_metadata3("design:type", Function),
736
- _ts_metadata3("design:paramtypes", [
1270
+ DurableAgentRunner = _ts_decorate4([
1271
+ (0, import_common4.Injectable)(),
1272
+ _ts_param4(1, (0, import_common4.Inject)(import_nestjs_durable3.RUN_GATEWAY)),
1273
+ _ts_param4(2, (0, import_common4.Inject)(import_nestjs_agent_core5.AGENT_STORE)),
1274
+ _ts_param4(3, (0, import_common4.Inject)(import_nestjs_agent_core5.AGENT_SINK)),
1275
+ _ts_param4(4, (0, import_common4.Optional)()),
1276
+ _ts_metadata4("design:type", Function),
1277
+ _ts_metadata4("design:paramtypes", [
737
1278
  typeof import_nestjs_durable3.WorkflowService === "undefined" ? Object : import_nestjs_durable3.WorkflowService,
738
1279
  typeof RunGateway === "undefined" ? Object : RunGateway,
739
1280
  typeof AgentStore === "undefined" ? Object : AgentStore,
740
- typeof TokenStreamSink === "undefined" ? Object : TokenStreamSink
1281
+ typeof TokenStreamSink === "undefined" ? Object : TokenStreamSink,
1282
+ typeof ChatQueueService === "undefined" ? Object : ChatQueueService
741
1283
  ])
742
1284
  ], DurableAgentRunner);
743
1285
 
744
1286
  // src/durable/agent-durable.module.ts
745
- var import_nestjs_agent_core5 = require("@dudousxd/nestjs-agent-core");
746
- var import_common4 = require("@nestjs/common");
747
- function _ts_decorate4(decorators, target, key, desc) {
1287
+ var import_nestjs_agent_core6 = require("@dudousxd/nestjs-agent-core");
1288
+ var import_common5 = require("@nestjs/common");
1289
+ function _ts_decorate5(decorators, target, key, desc) {
748
1290
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
749
1291
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
750
1292
  r = Reflect.decorate(decorators, target, key, desc);
@@ -757,12 +1299,12 @@ function _ts_decorate4(decorators, target, key, desc) {
757
1299
  }
758
1300
  return c > 3 && r && Object.defineProperty(target, key, r), r;
759
1301
  }
760
- __name(_ts_decorate4, "_ts_decorate");
1302
+ __name(_ts_decorate5, "_ts_decorate");
761
1303
  function runnerProviders() {
762
1304
  return [
763
1305
  DurableAgentRunner,
764
1306
  {
765
- provide: import_nestjs_agent_core5.AGENT_DURABLE_RUNNER,
1307
+ provide: import_nestjs_agent_core6.AGENT_DURABLE_RUNNER,
766
1308
  useExisting: DurableAgentRunner
767
1309
  }
768
1310
  ];
@@ -773,15 +1315,15 @@ var AgentDurableHttpModule = class AgentDurableHttpModule2 {
773
1315
  __name(this, "AgentDurableHttpModule");
774
1316
  }
775
1317
  };
776
- AgentDurableHttpModule = _ts_decorate4([
777
- (0, import_common4.Global)(),
778
- (0, import_common4.Module)({
1318
+ AgentDurableHttpModule = _ts_decorate5([
1319
+ (0, import_common5.Global)(),
1320
+ (0, import_common5.Module)({
779
1321
  providers: [
780
1322
  AgentRunWorkflow,
781
1323
  ...runnerProviders()
782
1324
  ],
783
1325
  exports: [
784
- import_nestjs_agent_core5.AGENT_DURABLE_RUNNER,
1326
+ import_nestjs_agent_core6.AGENT_DURABLE_RUNNER,
785
1327
  AgentRunWorkflow
786
1328
  ]
787
1329
  })
@@ -811,16 +1353,16 @@ var AgentDurableModule = class _AgentDurableModule {
811
1353
  };
812
1354
  }
813
1355
  };
814
- AgentDurableModule = _ts_decorate4([
815
- (0, import_common4.Global)(),
816
- (0, import_common4.Module)({
1356
+ AgentDurableModule = _ts_decorate5([
1357
+ (0, import_common5.Global)(),
1358
+ (0, import_common5.Module)({
817
1359
  providers: [
818
1360
  AgentRunWorkflow,
819
1361
  AgentRunSteps,
820
1362
  ...runnerProviders()
821
1363
  ],
822
1364
  exports: [
823
- import_nestjs_agent_core5.AGENT_DURABLE_RUNNER,
1365
+ import_nestjs_agent_core6.AGENT_DURABLE_RUNNER,
824
1366
  AgentRunWorkflow,
825
1367
  AgentRunSteps
826
1368
  ]
@@ -828,15 +1370,15 @@ AgentDurableModule = _ts_decorate4([
828
1370
  ], AgentDurableModule);
829
1371
 
830
1372
  // src/agent.module.ts
831
- var import_nestjs_agent_core28 = require("@dudousxd/nestjs-agent-core");
832
- var import_common24 = require("@nestjs/common");
1373
+ var import_nestjs_agent_core30 = require("@dudousxd/nestjs-agent-core");
1374
+ var import_common26 = require("@nestjs/common");
833
1375
  var import_core4 = require("@nestjs/core");
834
1376
 
835
1377
  // src/agent-deps.factory.ts
836
- var import_nestjs_agent_core6 = require("@dudousxd/nestjs-agent-core");
837
1378
  var import_nestjs_agent_core7 = require("@dudousxd/nestjs-agent-core");
838
- var import_common5 = require("@nestjs/common");
839
- function _ts_decorate5(decorators, target, key, desc) {
1379
+ var import_nestjs_agent_core8 = require("@dudousxd/nestjs-agent-core");
1380
+ var import_common6 = require("@nestjs/common");
1381
+ function _ts_decorate6(decorators, target, key, desc) {
840
1382
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
841
1383
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
842
1384
  r = Reflect.decorate(decorators, target, key, desc);
@@ -849,19 +1391,19 @@ function _ts_decorate5(decorators, target, key, desc) {
849
1391
  }
850
1392
  return c > 3 && r && Object.defineProperty(target, key, r), r;
851
1393
  }
852
- __name(_ts_decorate5, "_ts_decorate");
853
- function _ts_metadata4(metadataKey, metadataValue) {
1394
+ __name(_ts_decorate6, "_ts_decorate");
1395
+ function _ts_metadata5(metadataKey, metadataValue) {
854
1396
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
855
1397
  return Reflect.metadata(metadataKey, metadataValue);
856
1398
  }
857
1399
  }
858
- __name(_ts_metadata4, "_ts_metadata");
859
- function _ts_param4(paramIndex, decorator) {
1400
+ __name(_ts_metadata5, "_ts_metadata");
1401
+ function _ts_param5(paramIndex, decorator) {
860
1402
  return function(target, key) {
861
1403
  decorator(target, key, paramIndex);
862
1404
  };
863
1405
  }
864
- __name(_ts_param4, "_ts_param");
1406
+ __name(_ts_param5, "_ts_param");
865
1407
  function delegateToolName(args) {
866
1408
  const slug = args.target.replace(/[^a-zA-Z0-9]+/g, "_");
867
1409
  return args.detached === true ? `start_${slug}` : `ask_${slug}`;
@@ -919,7 +1461,7 @@ var AgentDepsFactory2 = class {
919
1461
  return void 0;
920
1462
  }
921
1463
  const delegated = (definition.delegatesTo ?? []).map((edge) => {
922
- const { agent, detached } = (0, import_nestjs_agent_core6.normalizeDelegation)(edge);
1464
+ const { agent, detached } = (0, import_nestjs_agent_core7.normalizeDelegation)(edge);
923
1465
  return delegateToolName({
924
1466
  target: agent,
925
1467
  detached
@@ -1032,7 +1574,7 @@ var AgentDepsFactory2 = class {
1032
1574
  }
1033
1575
  /** Build the built-in window policy from the declarative `{ maxMessages, maxTokens, summarize }`. */
1034
1576
  window(config) {
1035
- return (0, import_nestjs_agent_core6.windowHistory)({
1577
+ return (0, import_nestjs_agent_core7.windowHistory)({
1036
1578
  ...config.maxMessages !== void 0 ? {
1037
1579
  maxMessages: config.maxMessages
1038
1580
  } : {},
@@ -1042,7 +1584,7 @@ var AgentDepsFactory2 = class {
1042
1584
  // The shared module model, not a per-agent one: an agent's `modelId` is an accounting label,
1043
1585
  // and only one provider is ever bound.
1044
1586
  ...config.summarize === true ? {
1045
- summarize: (0, import_nestjs_agent_core6.summarizeWithModel)(this.model)
1587
+ summarize: (0, import_nestjs_agent_core7.summarizeWithModel)(this.model)
1046
1588
  } : {}
1047
1589
  });
1048
1590
  }
@@ -1058,31 +1600,31 @@ var AgentDepsFactory2 = class {
1058
1600
  return void 0;
1059
1601
  }
1060
1602
  };
1061
- AgentDepsFactory2 = _ts_decorate5([
1062
- (0, import_common5.Injectable)(),
1063
- _ts_param4(0, (0, import_common5.Inject)(import_nestjs_agent_core7.AGENT_OPTIONS)),
1064
- _ts_param4(1, (0, import_common5.Inject)(import_nestjs_agent_core6.AGENT_MODEL)),
1065
- _ts_param4(2, (0, import_common5.Inject)(import_nestjs_agent_core6.AGENT_STORE)),
1066
- _ts_param4(3, (0, import_common5.Inject)(import_nestjs_agent_core6.AGENT_SINK)),
1067
- _ts_param4(4, (0, import_common5.Inject)(import_nestjs_agent_core6.AGENT_ROLES_POLICY)),
1068
- _ts_param4(5, (0, import_common5.Inject)(import_nestjs_agent_core6.AGENT_TOOL_REGISTRY)),
1069
- _ts_param4(6, (0, import_common5.Inject)(import_nestjs_agent_core6.AGENT_REGISTRY)),
1070
- _ts_param4(7, (0, import_common5.Inject)(import_nestjs_agent_core6.AGENT_PROMPT_CONTRIBUTORS)),
1071
- _ts_param4(8, (0, import_common5.Optional)()),
1072
- _ts_param4(8, (0, import_common5.Inject)(import_nestjs_agent_core6.AGENT_PRICING_STORE)),
1073
- _ts_param4(9, (0, import_common5.Optional)()),
1074
- _ts_param4(9, (0, import_common5.Inject)(import_nestjs_agent_core6.AGENT_SKILLS)),
1075
- _ts_param4(10, (0, import_common5.Optional)()),
1076
- _ts_param4(10, (0, import_common5.Inject)(import_nestjs_agent_core6.AGENT_MEMORY)),
1077
- _ts_metadata4("design:type", Function),
1078
- _ts_metadata4("design:paramtypes", [
1603
+ AgentDepsFactory2 = _ts_decorate6([
1604
+ (0, import_common6.Injectable)(),
1605
+ _ts_param5(0, (0, import_common6.Inject)(import_nestjs_agent_core8.AGENT_OPTIONS)),
1606
+ _ts_param5(1, (0, import_common6.Inject)(import_nestjs_agent_core7.AGENT_MODEL)),
1607
+ _ts_param5(2, (0, import_common6.Inject)(import_nestjs_agent_core7.AGENT_STORE)),
1608
+ _ts_param5(3, (0, import_common6.Inject)(import_nestjs_agent_core7.AGENT_SINK)),
1609
+ _ts_param5(4, (0, import_common6.Inject)(import_nestjs_agent_core7.AGENT_ROLES_POLICY)),
1610
+ _ts_param5(5, (0, import_common6.Inject)(import_nestjs_agent_core7.AGENT_TOOL_REGISTRY)),
1611
+ _ts_param5(6, (0, import_common6.Inject)(import_nestjs_agent_core7.AGENT_REGISTRY)),
1612
+ _ts_param5(7, (0, import_common6.Inject)(import_nestjs_agent_core7.AGENT_PROMPT_CONTRIBUTORS)),
1613
+ _ts_param5(8, (0, import_common6.Optional)()),
1614
+ _ts_param5(8, (0, import_common6.Inject)(import_nestjs_agent_core7.AGENT_PRICING_STORE)),
1615
+ _ts_param5(9, (0, import_common6.Optional)()),
1616
+ _ts_param5(9, (0, import_common6.Inject)(import_nestjs_agent_core7.AGENT_SKILLS)),
1617
+ _ts_param5(10, (0, import_common6.Optional)()),
1618
+ _ts_param5(10, (0, import_common6.Inject)(import_nestjs_agent_core7.AGENT_MEMORY)),
1619
+ _ts_metadata5("design:type", Function),
1620
+ _ts_metadata5("design:paramtypes", [
1079
1621
  typeof AgentModuleOptions === "undefined" ? Object : AgentModuleOptions,
1080
1622
  typeof ModelProvider === "undefined" ? Object : ModelProvider,
1081
1623
  typeof AgentStore === "undefined" ? Object : AgentStore,
1082
1624
  typeof TokenStreamSink === "undefined" ? Object : TokenStreamSink,
1083
1625
  typeof RolesPolicy === "undefined" ? Object : RolesPolicy,
1084
- typeof import_nestjs_agent_core6.ToolRegistry === "undefined" ? Object : import_nestjs_agent_core6.ToolRegistry,
1085
- typeof import_nestjs_agent_core6.AgentRegistry === "undefined" ? Object : import_nestjs_agent_core6.AgentRegistry,
1626
+ typeof import_nestjs_agent_core7.ToolRegistry === "undefined" ? Object : import_nestjs_agent_core7.ToolRegistry,
1627
+ typeof import_nestjs_agent_core7.AgentRegistry === "undefined" ? Object : import_nestjs_agent_core7.AgentRegistry,
1086
1628
  Array,
1087
1629
  Object,
1088
1630
  Object,
@@ -1091,9 +1633,9 @@ AgentDepsFactory2 = _ts_decorate5([
1091
1633
  ], AgentDepsFactory2);
1092
1634
 
1093
1635
  // src/agent.service.ts
1094
- var import_nestjs_agent_core8 = require("@dudousxd/nestjs-agent-core");
1095
- var import_common6 = require("@nestjs/common");
1096
- function _ts_decorate6(decorators, target, key, desc) {
1636
+ var import_nestjs_agent_core9 = require("@dudousxd/nestjs-agent-core");
1637
+ var import_common7 = require("@nestjs/common");
1638
+ function _ts_decorate7(decorators, target, key, desc) {
1097
1639
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1098
1640
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1099
1641
  r = Reflect.decorate(decorators, target, key, desc);
@@ -1106,19 +1648,19 @@ function _ts_decorate6(decorators, target, key, desc) {
1106
1648
  }
1107
1649
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1108
1650
  }
1109
- __name(_ts_decorate6, "_ts_decorate");
1110
- function _ts_metadata5(metadataKey, metadataValue) {
1651
+ __name(_ts_decorate7, "_ts_decorate");
1652
+ function _ts_metadata6(metadataKey, metadataValue) {
1111
1653
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1112
1654
  return Reflect.metadata(metadataKey, metadataValue);
1113
1655
  }
1114
1656
  }
1115
- __name(_ts_metadata5, "_ts_metadata");
1116
- function _ts_param5(paramIndex, decorator) {
1657
+ __name(_ts_metadata6, "_ts_metadata");
1658
+ function _ts_param6(paramIndex, decorator) {
1117
1659
  return function(target, key) {
1118
1660
  decorator(target, key, paramIndex);
1119
1661
  };
1120
1662
  }
1121
- __name(_ts_param5, "_ts_param");
1663
+ __name(_ts_param6, "_ts_param");
1122
1664
  var AgentService = class {
1123
1665
  static {
1124
1666
  __name(this, "AgentService");
@@ -1130,7 +1672,8 @@ var AgentService = class {
1130
1672
  models;
1131
1673
  quotaProvider;
1132
1674
  options;
1133
- constructor(runner, store, deps, staging, models, quotaProvider, options) {
1675
+ queue;
1676
+ constructor(runner, store, deps, staging, models, quotaProvider, options, queue) {
1134
1677
  this.runner = runner;
1135
1678
  this.store = store;
1136
1679
  this.deps = deps;
@@ -1138,6 +1681,19 @@ var AgentService = class {
1138
1681
  this.models = models;
1139
1682
  this.quotaProvider = quotaProvider;
1140
1683
  this.options = options;
1684
+ this.queue = queue;
1685
+ }
1686
+ /** The queue service when the bound store can hold a queue, else `undefined`. */
1687
+ queueing() {
1688
+ return this.queue?.supported === true ? this.queue : void 0;
1689
+ }
1690
+ /** The queue service, or a 501 naming what is missing. */
1691
+ requireQueue() {
1692
+ const queue = this.queueing();
1693
+ if (queue === void 0) {
1694
+ throw new import_common7.NotImplementedException("Queueing messages requires an AgentStore that implements ChatQueueStore; the bound store does not.");
1695
+ }
1696
+ return queue;
1141
1697
  }
1142
1698
  /**
1143
1699
  * The actor's budget across windows (`GET <base>/quota`) — the bound {@link QuotaProvider}'s
@@ -1172,12 +1728,12 @@ var AgentService = class {
1172
1728
  actor
1173
1729
  });
1174
1730
  if (blocked !== void 0) {
1175
- throw new import_common6.HttpException({
1176
- statusCode: import_common6.HttpStatus.TOO_MANY_REQUESTS,
1731
+ throw new import_common7.HttpException({
1732
+ statusCode: import_common7.HttpStatus.TOO_MANY_REQUESTS,
1177
1733
  code: "quota_exceeded",
1178
1734
  period: blocked.period,
1179
1735
  message: blocked.reason ?? `The ${blocked.period === "day" ? "daily" : "monthly"} quota is used up`
1180
- }, import_common6.HttpStatus.TOO_MANY_REQUESTS);
1736
+ }, import_common7.HttpStatus.TOO_MANY_REQUESTS);
1181
1737
  }
1182
1738
  }
1183
1739
  /**
@@ -1205,17 +1761,17 @@ var AgentService = class {
1205
1761
  */
1206
1762
  async assertModelAllowed(actor, agent, model) {
1207
1763
  if (this.models === void 0) {
1208
- throw new import_common6.BadRequestException(`model "${model}" cannot be selected: no ModelCatalog is configured (AgentModule.forRoot({ models }))`);
1764
+ throw new import_common7.BadRequestException(`model "${model}" cannot be selected: no ModelCatalog is configured (AgentModule.forRoot({ models }))`);
1209
1765
  }
1210
- const entry = (0, import_nestjs_agent_core8.findCatalogModel)(await this.models.list({
1766
+ const entry = (0, import_nestjs_agent_core9.findCatalogModel)(await this.models.list({
1211
1767
  actor,
1212
1768
  agent
1213
1769
  }), model);
1214
1770
  if (entry === void 0) {
1215
- throw new import_common6.BadRequestException(`model "${model}" is not offered`);
1771
+ throw new import_common7.BadRequestException(`model "${model}" is not offered`);
1216
1772
  }
1217
1773
  if (!entry.available) {
1218
- throw new import_common6.BadRequestException(`model "${model}" is not available${entry.unavailableReason ? `: ${entry.unavailableReason}` : ""}`);
1774
+ throw new import_common7.BadRequestException(`model "${model}" is not available${entry.unavailableReason ? `: ${entry.unavailableReason}` : ""}`);
1219
1775
  }
1220
1776
  return entry.id;
1221
1777
  }
@@ -1231,7 +1787,7 @@ var AgentService = class {
1231
1787
  })).locked : void 0;
1232
1788
  if (locked !== void 0) {
1233
1789
  if (requested !== void 0 && requested !== locked.model) {
1234
- throw new import_common6.BadRequestException(`model "${requested}" cannot be selected: ${locked.reason ?? `this agent always uses "${locked.model}"`}`);
1790
+ throw new import_common7.BadRequestException(`model "${requested}" cannot be selected: ${locked.reason ?? `this agent always uses "${locked.model}"`}`);
1235
1791
  }
1236
1792
  return locked.model;
1237
1793
  }
@@ -1248,7 +1804,44 @@ var AgentService = class {
1248
1804
  }
1249
1805
  return (await this.store.getThread(threadId))?.model ?? null;
1250
1806
  }
1807
+ /**
1808
+ * Start a turn — for in-process callers that need a run id back. A send that would have to wait
1809
+ * (its thread already has a turn running) is refused with `409` instead; {@link send} is the form
1810
+ * that queues it.
1811
+ */
1251
1812
  async chat(params) {
1813
+ const result = await this.send({
1814
+ ...params,
1815
+ mode: "auto"
1816
+ });
1817
+ if (result.queued !== true) {
1818
+ return result;
1819
+ }
1820
+ if (result.runId !== void 0) {
1821
+ return {
1822
+ runId: result.runId,
1823
+ threadId: result.threadId
1824
+ };
1825
+ }
1826
+ const store = this.requireQueue().queueStore();
1827
+ if (!await store.removeQueuedMessage(result.messageId)) {
1828
+ return {
1829
+ runId: result.messageId,
1830
+ threadId: result.threadId
1831
+ };
1832
+ }
1833
+ await this.requireQueue().publish(result.threadId);
1834
+ throw new import_common7.ConflictException({
1835
+ statusCode: 409,
1836
+ code: "run_active",
1837
+ message: `thread ${result.threadId} already has a turn running`
1838
+ });
1839
+ }
1840
+ /**
1841
+ * Send a message: start a turn, or — when its thread already has one running — queue the message
1842
+ * to run after it (see {@link ChatSendMode}). What `POST <base>/chat` calls.
1843
+ */
1844
+ async send(params) {
1252
1845
  await this.assertWithinQuota(params.actor);
1253
1846
  const agentName = await this.resolveAgentName(params.agentName, params.threadId);
1254
1847
  const model = await this.resolveModel(params.actor, agentName, params.model, params.threadId);
@@ -1256,7 +1849,7 @@ var AgentService = class {
1256
1849
  let threadId = params.threadId;
1257
1850
  if (threadId === void 0) {
1258
1851
  if (params.regenerate === true) {
1259
- throw new import_common6.BadRequestException("regenerate requires an existing threadId");
1852
+ throw new import_common7.BadRequestException("regenerate requires an existing threadId");
1260
1853
  }
1261
1854
  const created = await this.store.createThread({
1262
1855
  actor: params.actor,
@@ -1265,7 +1858,7 @@ var AgentService = class {
1265
1858
  } : {}
1266
1859
  });
1267
1860
  threadId = created.id;
1268
- } else if (params.regenerate === true) {
1861
+ } else {
1269
1862
  await this.assertOwnsThread(params.actor, threadId);
1270
1863
  }
1271
1864
  const input = {
@@ -1287,13 +1880,195 @@ var AgentService = class {
1287
1880
  model
1288
1881
  } : {}
1289
1882
  };
1290
- const { runId } = await this.runner.start(input);
1291
- await this.store.setActiveStream(threadId, runId);
1883
+ const queue = this.queueing();
1884
+ if (queue === void 0) {
1885
+ const { runId } = await this.runner.start(input);
1886
+ await this.store.setActiveStream(threadId, runId);
1887
+ return {
1888
+ runId,
1889
+ threadId
1890
+ };
1891
+ }
1892
+ const mode = params.mode ?? "auto";
1893
+ const { live, stale } = await queue.holder(threadId, this.runner);
1894
+ if (live === null && mode !== "queue") {
1895
+ const runId = crypto.randomUUID();
1896
+ if (await queue.queueStore().claimActiveStream(threadId, runId, stale !== null ? {
1897
+ replacing: stale
1898
+ } : {})) {
1899
+ return {
1900
+ runId: await this.startClaimed(input, runId),
1901
+ threadId
1902
+ };
1903
+ }
1904
+ }
1905
+ if (params.regenerate === true) {
1906
+ throw new import_common7.ConflictException({
1907
+ statusCode: 409,
1908
+ code: "run_active",
1909
+ message: "cannot regenerate while a turn is running on this thread"
1910
+ });
1911
+ }
1912
+ return this.enqueue(queue, input, mode, live);
1913
+ }
1914
+ /**
1915
+ * Start a turn the thread is already claimed for, under the claimed id. A runner that minted an
1916
+ * id of its own anyway gets the thread re-pointed at it; one that fails to start frees the thread.
1917
+ */
1918
+ async startClaimed(input, runId) {
1919
+ const store = this.requireQueue().queueStore();
1920
+ let started;
1921
+ try {
1922
+ started = (await this.runner.start(input, {
1923
+ runId
1924
+ })).runId;
1925
+ } catch (error) {
1926
+ await store.releaseActiveStream(input.threadId, runId);
1927
+ throw error;
1928
+ }
1929
+ if (started !== runId) {
1930
+ await store.claimActiveStream(input.threadId, started, {
1931
+ replacing: runId
1932
+ });
1933
+ }
1934
+ return started;
1935
+ }
1936
+ /** Put a send in its thread's queue, then drain it if the thread turned out to be free. */
1937
+ async enqueue(queue, input, mode, live) {
1938
+ const store = queue.queueStore();
1939
+ const threadId = input.threadId;
1940
+ const interrupting = mode === "interrupt" && live !== null ? live : void 0;
1941
+ const queued = await store.enqueueMessage({
1942
+ threadId,
1943
+ actor: input.actor,
1944
+ content: input.userText,
1945
+ ...input.attachments !== void 0 ? {
1946
+ attachments: input.attachments
1947
+ } : {},
1948
+ ...input.agentName !== void 0 ? {
1949
+ agentName: input.agentName
1950
+ } : {},
1951
+ ...input.model !== void 0 ? {
1952
+ model: input.model
1953
+ } : {},
1954
+ ...input.pageContext !== void 0 ? {
1955
+ pageContext: input.pageContext
1956
+ } : {},
1957
+ ...interrupting !== void 0 ? {
1958
+ interrupt: true,
1959
+ at: "head"
1960
+ } : {}
1961
+ });
1962
+ let runId;
1963
+ if (interrupting !== void 0) {
1964
+ await store.setQueuePause(threadId, null);
1965
+ await queue.publish(threadId);
1966
+ await this.runner.cancel(interrupting);
1967
+ } else {
1968
+ runId = await queue.kick(threadId, this.runner);
1969
+ if (runId === void 0) {
1970
+ await queue.publish(threadId);
1971
+ }
1972
+ }
1973
+ const state = await queue.state(threadId);
1974
+ const position = state.items.findIndex((item) => item.id === queued.id);
1975
+ return {
1976
+ threadId,
1977
+ queued: true,
1978
+ messageId: queued.id,
1979
+ position: position === -1 ? 0 : position,
1980
+ queue: state,
1981
+ ...runId !== void 0 && runId === queued.id ? {
1982
+ runId
1983
+ } : {},
1984
+ ...interrupting !== void 0 ? {
1985
+ interrupting
1986
+ } : {}
1987
+ };
1988
+ }
1989
+ /** `GET <base>/threads/:id/queue` — the thread's waiting messages and whether it drains. */
1990
+ async getQueue(actor, threadId) {
1991
+ await this.assertOwnsThread(actor, threadId);
1992
+ return this.requireQueue().state(threadId);
1993
+ }
1994
+ /**
1995
+ * `PATCH <base>/queue/:messageId` — change a waiting message's text and/or attachments, and/or move
1996
+ * it to `position` in the queue. Answers the thread's queue.
1997
+ */
1998
+ async updateQueuedMessage(actor, messageId, patch) {
1999
+ const queue = this.requireQueue();
2000
+ const store = queue.queueStore();
2001
+ const threadId = await this.assertOwnsQueuedMessage(actor, messageId);
2002
+ if (patch.message !== void 0 && patch.message.trim().length === 0) {
2003
+ throw new import_common7.BadRequestException("message must not be empty");
2004
+ }
2005
+ const attachments = patch.attachments === void 0 || patch.attachments === null ? patch.attachments : await this.resolveAttachments(actor, patch.attachments);
2006
+ if (patch.message !== void 0 || attachments !== void 0) {
2007
+ const updated = await store.updateQueuedMessage(messageId, {
2008
+ ...patch.message !== void 0 ? {
2009
+ content: patch.message
2010
+ } : {},
2011
+ ...attachments !== void 0 ? {
2012
+ attachments
2013
+ } : {}
2014
+ });
2015
+ if (updated === null) {
2016
+ throw new import_common7.GoneException(`queued message ${messageId} already started or was removed`);
2017
+ }
2018
+ }
2019
+ if (patch.position !== void 0) {
2020
+ if (!Number.isInteger(patch.position) || patch.position < 0) {
2021
+ throw new import_common7.BadRequestException("position must be a non-negative integer");
2022
+ }
2023
+ if (!await store.moveQueuedMessage(messageId, patch.position)) {
2024
+ throw new import_common7.GoneException(`queued message ${messageId} already started or was removed`);
2025
+ }
2026
+ }
2027
+ return queue.publish(threadId);
2028
+ }
2029
+ /** `DELETE <base>/queue/:messageId` — drop a waiting message. Answers the thread's queue. */
2030
+ async removeQueuedMessage(actor, messageId) {
2031
+ const queue = this.requireQueue();
2032
+ const threadId = await this.assertOwnsQueuedMessage(actor, messageId);
2033
+ if (!await queue.queueStore().removeQueuedMessage(messageId)) {
2034
+ throw new import_common7.GoneException(`queued message ${messageId} already started or was removed`);
2035
+ }
2036
+ return queue.publish(threadId);
2037
+ }
2038
+ /** `DELETE <base>/threads/:id/queue` — drop every waiting message (and any pause). */
2039
+ async clearQueue(actor, threadId) {
2040
+ await this.assertOwnsThread(actor, threadId);
2041
+ const queue = this.requireQueue();
2042
+ await queue.queueStore().clearQueue(threadId);
2043
+ await queue.queueStore().setQueuePause(threadId, null);
2044
+ return queue.publish(threadId);
2045
+ }
2046
+ /**
2047
+ * `POST <base>/threads/:id/queue/resume` — lift a pause and start the head when nothing is
2048
+ * running. Answers the queue, and the run the head started under, if it did.
2049
+ */
2050
+ async resumeQueue(actor, threadId) {
2051
+ await this.assertOwnsThread(actor, threadId);
2052
+ const queue = this.requireQueue();
2053
+ await queue.queueStore().setQueuePause(threadId, null);
2054
+ const runId = await queue.kick(threadId, this.runner);
2055
+ const state = runId === void 0 ? await queue.publish(threadId) : await queue.state(threadId);
1292
2056
  return {
1293
- runId,
1294
- threadId
2057
+ ...state,
2058
+ ...runId !== void 0 ? {
2059
+ runId
2060
+ } : {}
1295
2061
  };
1296
2062
  }
2063
+ /** The thread a queued message waits on, once the caller is shown to own it. */
2064
+ async assertOwnsQueuedMessage(actor, messageId) {
2065
+ const message = await this.requireQueue().queueStore().getQueuedMessage(messageId);
2066
+ if (message === null) {
2067
+ throw new import_common7.NotFoundException(`queued message ${messageId} not found`);
2068
+ }
2069
+ await this.assertOwnsThread(actor, message.threadId);
2070
+ return message.threadId;
2071
+ }
1297
2072
  /**
1298
2073
  * Rebuild this turn's attachments from the staging store, keyed by the ids the caller claimed.
1299
2074
  * The model provider fetches {@link MessageAttachment.url} verbatim, so that url is only ever
@@ -1310,7 +2085,7 @@ var AgentService = class {
1310
2085
  }
1311
2086
  const staging = this.staging;
1312
2087
  if (staging === void 0 || typeof staging.resolve !== "function") {
1313
- throw new import_common6.NotImplementedException("Message attachments require an AGENT_ATTACHMENT_STAGING provider implementing resolve(); attachment urls are never taken from the request.");
2088
+ throw new import_common7.NotImplementedException("Message attachments require an AGENT_ATTACHMENT_STAGING provider implementing resolve(); attachment urls are never taken from the request.");
1314
2089
  }
1315
2090
  const resolved = [];
1316
2091
  for (const ref of refs) {
@@ -1319,7 +2094,7 @@ var AgentService = class {
1319
2094
  actor
1320
2095
  });
1321
2096
  if (attachment === null) {
1322
- throw new import_common6.ForbiddenException(`attachment ${ref.mediaId} is not available to this actor`);
2097
+ throw new import_common7.ForbiddenException(`attachment ${ref.mediaId} is not available to this actor`);
1323
2098
  }
1324
2099
  resolved.push(attachment);
1325
2100
  }
@@ -1468,7 +2243,7 @@ var AgentService = class {
1468
2243
  return;
1469
2244
  }
1470
2245
  if (this.store.updateThread === void 0) {
1471
- throw new import_common6.NotImplementedException("Setting a thread's defaultAgent or model requires an AgentStore that implements updateThread(); the bound store does not support it.");
2246
+ throw new import_common7.NotImplementedException("Setting a thread's defaultAgent or model requires an AgentStore that implements updateThread(); the bound store does not support it.");
1472
2247
  }
1473
2248
  const model = patch.model === void 0 || patch.model === null ? patch.model : await this.assertModelAllowed(actor, patch.defaultAgent ?? await this.resolveAgentName(void 0, threadId), patch.model);
1474
2249
  await this.store.updateThread(threadId, {
@@ -1486,10 +2261,10 @@ var AgentService = class {
1486
2261
  validateTitle(title) {
1487
2262
  const trimmed = title.trim();
1488
2263
  if (trimmed.length === 0) {
1489
- throw new import_common6.BadRequestException("title must not be empty");
2264
+ throw new import_common7.BadRequestException("title must not be empty");
1490
2265
  }
1491
2266
  if (trimmed.length > 200) {
1492
- throw new import_common6.BadRequestException("title must be at most 200 characters");
2267
+ throw new import_common7.BadRequestException("title must be at most 200 characters");
1493
2268
  }
1494
2269
  return trimmed;
1495
2270
  }
@@ -1533,9 +2308,13 @@ var AgentService = class {
1533
2308
  }
1534
2309
  async toDetailView(thread, actor) {
1535
2310
  const summary = await this.toSummaryView(thread);
2311
+ const queue = this.queueing();
1536
2312
  return {
1537
2313
  ...summary,
1538
- messages: await this.freshAttachmentUrls(thread.messages, actor)
2314
+ messages: await this.freshAttachmentUrls(thread.messages, actor),
2315
+ ...queue !== void 0 ? {
2316
+ queue: await queue.state(thread.id)
2317
+ } : {}
1539
2318
  };
1540
2319
  }
1541
2320
  /**
@@ -1588,21 +2367,21 @@ var AgentService = class {
1588
2367
  */
1589
2368
  async setMessageFeedback(actor, messageId, input) {
1590
2369
  if (input.value !== null && input.value !== "up" && input.value !== "down") {
1591
- throw new import_common6.BadRequestException("value must be 'up', 'down' or null");
2370
+ throw new import_common7.BadRequestException("value must be 'up', 'down' or null");
1592
2371
  }
1593
2372
  if (input.comment !== void 0 && typeof input.comment !== "string") {
1594
- throw new import_common6.BadRequestException("comment must be a string");
2373
+ throw new import_common7.BadRequestException("comment must be a string");
1595
2374
  }
1596
2375
  const comment = input.comment?.trim();
1597
2376
  if (comment !== void 0 && comment.length > 2e3) {
1598
- throw new import_common6.BadRequestException("comment must be at most 2000 characters");
2377
+ throw new import_common7.BadRequestException("comment must be at most 2000 characters");
1599
2378
  }
1600
2379
  if (this.store.threadOfMessage === void 0 || this.store.setMessageFeedback === void 0) {
1601
- throw new import_common6.NotImplementedException("Message feedback requires an AgentStore that implements threadOfMessage() and setMessageFeedback(); the bound store does not support it.");
2380
+ throw new import_common7.NotImplementedException("Message feedback requires an AgentStore that implements threadOfMessage() and setMessageFeedback(); the bound store does not support it.");
1602
2381
  }
1603
2382
  const threadId = await this.store.threadOfMessage(messageId);
1604
2383
  if (threadId === null) {
1605
- throw new import_common6.NotFoundException(`message ${messageId} not found`);
2384
+ throw new import_common7.NotFoundException(`message ${messageId} not found`);
1606
2385
  }
1607
2386
  await this.assertOwnsThread(actor, threadId);
1608
2387
  const feedback = input.value === null ? null : {
@@ -1650,7 +2429,7 @@ var AgentService = class {
1650
2429
  const list = this.attachmentInventory();
1651
2430
  const referencedMediaIds = this.store.referencedMediaIds?.bind(this.store);
1652
2431
  if (referencedMediaIds === void 0) {
1653
- throw new import_common6.NotImplementedException("Collecting attachments requires an AgentStore that implements referencedMediaIds(); the bound store cannot say which media a message still references, and guessing would delete files that are in use.");
2432
+ throw new import_common7.NotImplementedException("Collecting attachments requires an AgentStore that implements referencedMediaIds(); the bound store cannot say which media a message still references, and guessing would delete files that are in use.");
1654
2433
  }
1655
2434
  const stagedBefore = options.olderThan.toISOString();
1656
2435
  const inventory = await list({
@@ -1672,7 +2451,7 @@ var AgentService = class {
1672
2451
  attachmentInventory() {
1673
2452
  const list = this.staging?.list?.bind(this.staging);
1674
2453
  if (list === void 0) {
1675
- throw new import_common6.NotImplementedException("Listing attachments requires an AGENT_ATTACHMENT_STAGING provider implementing list(); the host owns the staged bytes, so only it can enumerate them.");
2454
+ throw new import_common7.NotImplementedException("Listing attachments requires an AGENT_ATTACHMENT_STAGING provider implementing list(); the host owns the staged bytes, so only it can enumerate them.");
1676
2455
  }
1677
2456
  return list;
1678
2457
  }
@@ -1683,10 +2462,10 @@ var AgentService = class {
1683
2462
  async assertOwnsThread(actor, threadId) {
1684
2463
  const owner = await this.store.ownerOfThread(threadId);
1685
2464
  if (owner === null) {
1686
- throw new import_common6.NotFoundException(`thread ${threadId} not found`);
2465
+ throw new import_common7.NotFoundException(`thread ${threadId} not found`);
1687
2466
  }
1688
2467
  if (owner !== actor.id) {
1689
- throw new import_common6.ForbiddenException("thread belongs to another actor");
2468
+ throw new import_common7.ForbiddenException("thread belongs to another actor");
1690
2469
  }
1691
2470
  }
1692
2471
  /**
@@ -1697,10 +2476,10 @@ var AgentService = class {
1697
2476
  async assertOwnsToolCall(actor, toolCallId2) {
1698
2477
  const owner = await this.store.ownerOfToolCall(toolCallId2);
1699
2478
  if (owner === null) {
1700
- throw new import_common6.NotFoundException(`tool call ${toolCallId2} not found`);
2479
+ throw new import_common7.NotFoundException(`tool call ${toolCallId2} not found`);
1701
2480
  }
1702
2481
  if (owner !== actor.id) {
1703
- throw new import_common6.ForbiddenException("tool call belongs to another actor");
2482
+ throw new import_common7.ForbiddenException("tool call belongs to another actor");
1704
2483
  }
1705
2484
  }
1706
2485
  /**
@@ -1715,12 +2494,12 @@ var AgentService = class {
1715
2494
  if (this.store.toolCallInput === void 0) {
1716
2495
  return;
1717
2496
  }
1718
- const questions = (0, import_nestjs_agent_core8.readElicitationQuestions)(await this.store.toolCallInput(toolCallId2));
2497
+ const questions = (0, import_nestjs_agent_core9.readElicitationQuestions)(await this.store.toolCallInput(toolCallId2));
1719
2498
  for (const question of questions) {
1720
2499
  const submitted = Object.hasOwn(answers2, question.id) ? answers2[question.id] : void 0;
1721
- const problem = (0, import_nestjs_agent_core8.validateElicitationAnswer)(question, submitted ?? question.defaults ?? []);
2500
+ const problem = (0, import_nestjs_agent_core9.validateElicitationAnswer)(question, submitted ?? question.defaults ?? []);
1722
2501
  if (problem !== null) {
1723
- throw new import_common6.BadRequestException(`answers["${question.id}"] ${problem}`);
2502
+ throw new import_common7.BadRequestException(`answers["${question.id}"] ${problem}`);
1724
2503
  }
1725
2504
  }
1726
2505
  }
@@ -1732,21 +2511,21 @@ var AgentService = class {
1732
2511
  */
1733
2512
  async assertMayDecide(actor, toolCallId2) {
1734
2513
  const approval = await this.store.toolCallApproval?.(toolCallId2);
1735
- const approver = approval?.approver ?? import_nestjs_agent_core8.REQUESTER_APPROVER;
1736
- if (approver === import_nestjs_agent_core8.REQUESTER_APPROVER) {
2514
+ const approver = approval?.approver ?? import_nestjs_agent_core9.REQUESTER_APPROVER;
2515
+ if (approver === import_nestjs_agent_core9.REQUESTER_APPROVER) {
1737
2516
  return this.assertOwnsToolCall(actor, toolCallId2);
1738
2517
  }
1739
2518
  const requesterRef = await this.store.ownerOfToolCall(toolCallId2);
1740
2519
  if (requesterRef === null) {
1741
- throw new import_common6.NotFoundException(`tool call ${toolCallId2} not found`);
2520
+ throw new import_common7.NotFoundException(`tool call ${toolCallId2} not found`);
1742
2521
  }
1743
- const allowed = await (0, import_nestjs_agent_core8.mayDecideApproval)(this.deps.forAgent().approvalPolicy, actor, {
2522
+ const allowed = await (0, import_nestjs_agent_core9.mayDecideApproval)(this.deps.forAgent().approvalPolicy, actor, {
1744
2523
  toolCallId: toolCallId2,
1745
2524
  approver,
1746
2525
  requesterRef
1747
2526
  });
1748
2527
  if (!allowed) {
1749
- throw new import_common6.ForbiddenException(`this approval is for ${approver}`);
2528
+ throw new import_common7.ForbiddenException(`this approval is for ${approver}`);
1750
2529
  }
1751
2530
  }
1752
2531
  /**
@@ -1762,7 +2541,7 @@ var AgentService = class {
1762
2541
  }
1763
2542
  const lapsed = approval.status === "expired" || approval.status === "pending_approval" && approval.expiresAt !== null && Date.parse(approval.expiresAt) <= Date.now();
1764
2543
  if (lapsed) {
1765
- throw new import_common6.GoneException(`the approval request for tool call ${toolCallId2} has expired`);
2544
+ throw new import_common7.GoneException(`the approval request for tool call ${toolCallId2} has expired`);
1766
2545
  }
1767
2546
  }
1768
2547
  /**
@@ -1775,7 +2554,7 @@ var AgentService = class {
1775
2554
  async resolveRunForToolCall(toolCallId2) {
1776
2555
  const runId = await this.store.runForToolCall(toolCallId2);
1777
2556
  if (runId === null) {
1778
- throw new import_common6.NotFoundException(`tool call ${toolCallId2} has no active run to signal`);
2557
+ throw new import_common7.NotFoundException(`tool call ${toolCallId2} has no active run to signal`);
1779
2558
  }
1780
2559
  return runId;
1781
2560
  }
@@ -1783,41 +2562,43 @@ var AgentService = class {
1783
2562
  async assertOwnsActiveStream(actor, runId) {
1784
2563
  const owner = await this.store.ownerOfActiveStream(runId);
1785
2564
  if (owner === null) {
1786
- throw new import_common6.NotFoundException(`no active run ${runId}`);
2565
+ throw new import_common7.NotFoundException(`no active run ${runId}`);
1787
2566
  }
1788
2567
  if (owner !== actor.id) {
1789
- throw new import_common6.ForbiddenException("run belongs to another actor");
2568
+ throw new import_common7.ForbiddenException("run belongs to another actor");
1790
2569
  }
1791
2570
  }
1792
2571
  };
1793
- AgentService = _ts_decorate6([
1794
- (0, import_common6.Injectable)(),
1795
- _ts_param5(0, (0, import_common6.Inject)(import_nestjs_agent_core8.AGENT_RUNNER)),
1796
- _ts_param5(1, (0, import_common6.Inject)(import_nestjs_agent_core8.AGENT_STORE)),
1797
- _ts_param5(2, (0, import_common6.Inject)(import_nestjs_agent_core8.AGENT_DEPS_FACTORY)),
1798
- _ts_param5(3, (0, import_common6.Optional)()),
1799
- _ts_param5(3, (0, import_common6.Inject)(import_nestjs_agent_core8.AGENT_ATTACHMENT_STAGING)),
1800
- _ts_param5(4, (0, import_common6.Optional)()),
1801
- _ts_param5(4, (0, import_common6.Inject)(import_nestjs_agent_core8.AGENT_MODEL_CATALOG)),
1802
- _ts_param5(5, (0, import_common6.Optional)()),
1803
- _ts_param5(5, (0, import_common6.Inject)(import_nestjs_agent_core8.AGENT_QUOTA_PROVIDER)),
1804
- _ts_param5(6, (0, import_common6.Optional)()),
1805
- _ts_param5(6, (0, import_common6.Inject)(import_nestjs_agent_core8.AGENT_OPTIONS)),
1806
- _ts_metadata5("design:type", Function),
1807
- _ts_metadata5("design:paramtypes", [
2572
+ AgentService = _ts_decorate7([
2573
+ (0, import_common7.Injectable)(),
2574
+ _ts_param6(0, (0, import_common7.Inject)(import_nestjs_agent_core9.AGENT_RUNNER)),
2575
+ _ts_param6(1, (0, import_common7.Inject)(import_nestjs_agent_core9.AGENT_STORE)),
2576
+ _ts_param6(2, (0, import_common7.Inject)(import_nestjs_agent_core9.AGENT_DEPS_FACTORY)),
2577
+ _ts_param6(3, (0, import_common7.Optional)()),
2578
+ _ts_param6(3, (0, import_common7.Inject)(import_nestjs_agent_core9.AGENT_ATTACHMENT_STAGING)),
2579
+ _ts_param6(4, (0, import_common7.Optional)()),
2580
+ _ts_param6(4, (0, import_common7.Inject)(import_nestjs_agent_core9.AGENT_MODEL_CATALOG)),
2581
+ _ts_param6(5, (0, import_common7.Optional)()),
2582
+ _ts_param6(5, (0, import_common7.Inject)(import_nestjs_agent_core9.AGENT_QUOTA_PROVIDER)),
2583
+ _ts_param6(6, (0, import_common7.Optional)()),
2584
+ _ts_param6(6, (0, import_common7.Inject)(import_nestjs_agent_core9.AGENT_OPTIONS)),
2585
+ _ts_param6(7, (0, import_common7.Optional)()),
2586
+ _ts_metadata6("design:type", Function),
2587
+ _ts_metadata6("design:paramtypes", [
1808
2588
  typeof AgentRunner === "undefined" ? Object : AgentRunner,
1809
2589
  typeof AgentStore === "undefined" ? Object : AgentStore,
1810
2590
  typeof AgentDepsFactory === "undefined" ? Object : AgentDepsFactory,
1811
2591
  typeof AttachmentStagingStore === "undefined" ? Object : AttachmentStagingStore,
1812
2592
  typeof ModelCatalog === "undefined" ? Object : ModelCatalog,
1813
2593
  typeof QuotaProvider === "undefined" ? Object : QuotaProvider,
1814
- typeof Pick === "undefined" ? Object : Pick
2594
+ typeof Pick === "undefined" ? Object : Pick,
2595
+ typeof ChatQueueService === "undefined" ? Object : ChatQueueService
1815
2596
  ])
1816
2597
  ], AgentService);
1817
2598
 
1818
2599
  // src/approval-port.adapter.ts
1819
- var import_common7 = require("@nestjs/common");
1820
- function _ts_decorate7(decorators, target, key, desc) {
2600
+ var import_common8 = require("@nestjs/common");
2601
+ function _ts_decorate8(decorators, target, key, desc) {
1821
2602
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1822
2603
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1823
2604
  r = Reflect.decorate(decorators, target, key, desc);
@@ -1830,13 +2611,13 @@ function _ts_decorate7(decorators, target, key, desc) {
1830
2611
  }
1831
2612
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1832
2613
  }
1833
- __name(_ts_decorate7, "_ts_decorate");
1834
- function _ts_metadata6(metadataKey, metadataValue) {
2614
+ __name(_ts_decorate8, "_ts_decorate");
2615
+ function _ts_metadata7(metadataKey, metadataValue) {
1835
2616
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1836
2617
  return Reflect.metadata(metadataKey, metadataValue);
1837
2618
  }
1838
2619
  }
1839
- __name(_ts_metadata6, "_ts_metadata");
2620
+ __name(_ts_metadata7, "_ts_metadata");
1840
2621
  var AgentApprovalPortAdapter = class {
1841
2622
  static {
1842
2623
  __name(this, "AgentApprovalPortAdapter");
@@ -1874,18 +2655,18 @@ var AgentApprovalPortAdapter = class {
1874
2655
  });
1875
2656
  }
1876
2657
  };
1877
- AgentApprovalPortAdapter = _ts_decorate7([
1878
- (0, import_common7.Injectable)(),
1879
- _ts_metadata6("design:type", Function),
1880
- _ts_metadata6("design:paramtypes", [
2658
+ AgentApprovalPortAdapter = _ts_decorate8([
2659
+ (0, import_common8.Injectable)(),
2660
+ _ts_metadata7("design:type", Function),
2661
+ _ts_metadata7("design:paramtypes", [
1881
2662
  typeof AgentService === "undefined" ? Object : AgentService
1882
2663
  ])
1883
2664
  ], AgentApprovalPortAdapter);
1884
2665
 
1885
2666
  // src/controller/agents.controller.ts
1886
- var import_nestjs_agent_core9 = require("@dudousxd/nestjs-agent-core");
1887
- var import_common8 = require("@nestjs/common");
1888
- function _ts_decorate8(decorators, target, key, desc) {
2667
+ var import_nestjs_agent_core10 = require("@dudousxd/nestjs-agent-core");
2668
+ var import_common9 = require("@nestjs/common");
2669
+ function _ts_decorate9(decorators, target, key, desc) {
1889
2670
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1890
2671
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1891
2672
  r = Reflect.decorate(decorators, target, key, desc);
@@ -1898,19 +2679,19 @@ function _ts_decorate8(decorators, target, key, desc) {
1898
2679
  }
1899
2680
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1900
2681
  }
1901
- __name(_ts_decorate8, "_ts_decorate");
1902
- function _ts_metadata7(metadataKey, metadataValue) {
2682
+ __name(_ts_decorate9, "_ts_decorate");
2683
+ function _ts_metadata8(metadataKey, metadataValue) {
1903
2684
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1904
2685
  return Reflect.metadata(metadataKey, metadataValue);
1905
2686
  }
1906
2687
  }
1907
- __name(_ts_metadata7, "_ts_metadata");
1908
- function _ts_param6(paramIndex, decorator) {
2688
+ __name(_ts_metadata8, "_ts_metadata");
2689
+ function _ts_param7(paramIndex, decorator) {
1909
2690
  return function(target, key) {
1910
2691
  decorator(target, key, paramIndex);
1911
2692
  };
1912
2693
  }
1913
- __name(_ts_param6, "_ts_param");
2694
+ __name(_ts_param7, "_ts_param");
1914
2695
  var AgentsController = class {
1915
2696
  static {
1916
2697
  __name(this, "AgentsController");
@@ -1932,26 +2713,26 @@ var AgentsController = class {
1932
2713
  }));
1933
2714
  }
1934
2715
  };
1935
- _ts_decorate8([
1936
- (0, import_common8.Get)(),
1937
- _ts_metadata7("design:type", Function),
1938
- _ts_metadata7("design:paramtypes", []),
1939
- _ts_metadata7("design:returntype", Array)
2716
+ _ts_decorate9([
2717
+ (0, import_common9.Get)(),
2718
+ _ts_metadata8("design:type", Function),
2719
+ _ts_metadata8("design:paramtypes", []),
2720
+ _ts_metadata8("design:returntype", Array)
1940
2721
  ], AgentsController.prototype, "list", null);
1941
- AgentsController = _ts_decorate8([
1942
- (0, import_common8.Controller)("agents"),
1943
- _ts_param6(0, (0, import_common8.Inject)(import_nestjs_agent_core9.AGENT_REGISTRY)),
1944
- _ts_param6(1, (0, import_common8.Inject)(import_nestjs_agent_core9.AGENT_DEPS_FACTORY)),
1945
- _ts_metadata7("design:type", Function),
1946
- _ts_metadata7("design:paramtypes", [
1947
- typeof import_nestjs_agent_core9.AgentRegistry === "undefined" ? Object : import_nestjs_agent_core9.AgentRegistry,
2722
+ AgentsController = _ts_decorate9([
2723
+ (0, import_common9.Controller)("agents"),
2724
+ _ts_param7(0, (0, import_common9.Inject)(import_nestjs_agent_core10.AGENT_REGISTRY)),
2725
+ _ts_param7(1, (0, import_common9.Inject)(import_nestjs_agent_core10.AGENT_DEPS_FACTORY)),
2726
+ _ts_metadata8("design:type", Function),
2727
+ _ts_metadata8("design:paramtypes", [
2728
+ typeof import_nestjs_agent_core10.AgentRegistry === "undefined" ? Object : import_nestjs_agent_core10.AgentRegistry,
1948
2729
  typeof AgentDepsFactory === "undefined" ? Object : AgentDepsFactory
1949
2730
  ])
1950
2731
  ], AgentsController);
1951
2732
 
1952
2733
  // src/controller/attachments.controller.ts
1953
- var import_nestjs_agent_core10 = require("@dudousxd/nestjs-agent-core");
1954
- var import_common9 = require("@nestjs/common");
2734
+ var import_nestjs_agent_core11 = require("@dudousxd/nestjs-agent-core");
2735
+ var import_common10 = require("@nestjs/common");
1955
2736
  var import_platform_express = require("@nestjs/platform-express");
1956
2737
 
1957
2738
  // src/attachment-limits.ts
@@ -1980,7 +2761,7 @@ function attachmentLimits(options, staging) {
1980
2761
  __name(attachmentLimits, "attachmentLimits");
1981
2762
 
1982
2763
  // src/controller/attachments.controller.ts
1983
- function _ts_decorate9(decorators, target, key, desc) {
2764
+ function _ts_decorate10(decorators, target, key, desc) {
1984
2765
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1985
2766
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1986
2767
  r = Reflect.decorate(decorators, target, key, desc);
@@ -1993,19 +2774,19 @@ function _ts_decorate9(decorators, target, key, desc) {
1993
2774
  }
1994
2775
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1995
2776
  }
1996
- __name(_ts_decorate9, "_ts_decorate");
1997
- function _ts_metadata8(metadataKey, metadataValue) {
2777
+ __name(_ts_decorate10, "_ts_decorate");
2778
+ function _ts_metadata9(metadataKey, metadataValue) {
1998
2779
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1999
2780
  return Reflect.metadata(metadataKey, metadataValue);
2000
2781
  }
2001
2782
  }
2002
- __name(_ts_metadata8, "_ts_metadata");
2003
- function _ts_param7(paramIndex, decorator) {
2783
+ __name(_ts_metadata9, "_ts_metadata");
2784
+ function _ts_param8(paramIndex, decorator) {
2004
2785
  return function(target, key) {
2005
2786
  decorator(target, key, paramIndex);
2006
2787
  };
2007
2788
  }
2008
- __name(_ts_param7, "_ts_param");
2789
+ __name(_ts_param8, "_ts_param");
2009
2790
  var HARD_MAX_ATTACHMENT_BYTES = 32 * 1024 * 1024;
2010
2791
  var ATTACHMENT_PAGE_SIZE = 50;
2011
2792
  var AttachmentsController = class {
@@ -2039,17 +2820,17 @@ var AttachmentsController = class {
2039
2820
  }
2040
2821
  async upload(req, file) {
2041
2822
  if (this.staging === void 0) {
2042
- throw new import_common9.NotImplementedException("Attachment upload is not configured on this server: bind AGENT_ATTACHMENT_STAGING (e.g. import AgentMediaAttachmentsModule).");
2823
+ throw new import_common10.NotImplementedException("Attachment upload is not configured on this server: bind AGENT_ATTACHMENT_STAGING (e.g. import AgentMediaAttachmentsModule).");
2043
2824
  }
2044
2825
  if (file === void 0) {
2045
- throw new import_common9.BadRequestException('multipart field "file" is required');
2826
+ throw new import_common10.BadRequestException('multipart field "file" is required');
2046
2827
  }
2047
2828
  const { allowedContentTypes, maxBytes } = attachmentLimits(this.options, this.staging);
2048
2829
  if (!allowedContentTypes.includes(file.mimetype)) {
2049
- throw new import_common9.UnsupportedMediaTypeException(`content type "${file.mimetype}" is not allowed (allowed: ${allowedContentTypes.join(", ")})`);
2830
+ throw new import_common10.UnsupportedMediaTypeException(`content type "${file.mimetype}" is not allowed (allowed: ${allowedContentTypes.join(", ")})`);
2050
2831
  }
2051
2832
  if (file.size > maxBytes) {
2052
- throw new import_common9.PayloadTooLargeException(`file exceeds the ${maxBytes}-byte limit`);
2833
+ throw new import_common10.PayloadTooLargeException(`file exceeds the ${maxBytes}-byte limit`);
2053
2834
  }
2054
2835
  const actor = await this.actorResolver.resolve(req);
2055
2836
  return this.staging.stage({
@@ -2061,39 +2842,39 @@ var AttachmentsController = class {
2061
2842
  });
2062
2843
  }
2063
2844
  };
2064
- _ts_decorate9([
2065
- (0, import_common9.Get)(),
2066
- _ts_param7(0, (0, import_common9.Req)()),
2067
- _ts_metadata8("design:type", Function),
2068
- _ts_metadata8("design:paramtypes", [
2845
+ _ts_decorate10([
2846
+ (0, import_common10.Get)(),
2847
+ _ts_param8(0, (0, import_common10.Req)()),
2848
+ _ts_metadata9("design:type", Function),
2849
+ _ts_metadata9("design:paramtypes", [
2069
2850
  typeof Request === "undefined" ? Object : Request
2070
2851
  ]),
2071
- _ts_metadata8("design:returntype", Promise)
2852
+ _ts_metadata9("design:returntype", Promise)
2072
2853
  ], AttachmentsController.prototype, "list", null);
2073
- _ts_decorate9([
2074
- (0, import_common9.Post)(),
2075
- (0, import_common9.UseInterceptors)((0, import_platform_express.FileInterceptor)("file", {
2854
+ _ts_decorate10([
2855
+ (0, import_common10.Post)(),
2856
+ (0, import_common10.UseInterceptors)((0, import_platform_express.FileInterceptor)("file", {
2076
2857
  limits: {
2077
2858
  fileSize: HARD_MAX_ATTACHMENT_BYTES
2078
2859
  }
2079
2860
  })),
2080
- _ts_param7(0, (0, import_common9.Req)()),
2081
- _ts_param7(1, (0, import_common9.UploadedFile)()),
2082
- _ts_metadata8("design:type", Function),
2083
- _ts_metadata8("design:paramtypes", [
2861
+ _ts_param8(0, (0, import_common10.Req)()),
2862
+ _ts_param8(1, (0, import_common10.UploadedFile)()),
2863
+ _ts_metadata9("design:type", Function),
2864
+ _ts_metadata9("design:paramtypes", [
2084
2865
  typeof Request === "undefined" ? Object : Request,
2085
2866
  Object
2086
2867
  ]),
2087
- _ts_metadata8("design:returntype", Promise)
2868
+ _ts_metadata9("design:returntype", Promise)
2088
2869
  ], AttachmentsController.prototype, "upload", null);
2089
- AttachmentsController = _ts_decorate9([
2090
- (0, import_common9.Controller)("attachments"),
2091
- _ts_param7(0, (0, import_common9.Inject)(import_nestjs_agent_core10.AGENT_OPTIONS)),
2092
- _ts_param7(1, (0, import_common9.Inject)(import_nestjs_agent_core10.AGENT_ACTOR_RESOLVER)),
2093
- _ts_param7(3, (0, import_common9.Optional)()),
2094
- _ts_param7(3, (0, import_common9.Inject)(import_nestjs_agent_core10.AGENT_ATTACHMENT_STAGING)),
2095
- _ts_metadata8("design:type", Function),
2096
- _ts_metadata8("design:paramtypes", [
2870
+ AttachmentsController = _ts_decorate10([
2871
+ (0, import_common10.Controller)("attachments"),
2872
+ _ts_param8(0, (0, import_common10.Inject)(import_nestjs_agent_core11.AGENT_OPTIONS)),
2873
+ _ts_param8(1, (0, import_common10.Inject)(import_nestjs_agent_core11.AGENT_ACTOR_RESOLVER)),
2874
+ _ts_param8(3, (0, import_common10.Optional)()),
2875
+ _ts_param8(3, (0, import_common10.Inject)(import_nestjs_agent_core11.AGENT_ATTACHMENT_STAGING)),
2876
+ _ts_metadata9("design:type", Function),
2877
+ _ts_metadata9("design:paramtypes", [
2097
2878
  typeof AgentModuleOptions === "undefined" ? Object : AgentModuleOptions,
2098
2879
  typeof ActorResolver === "undefined" ? Object : ActorResolver,
2099
2880
  typeof AgentService === "undefined" ? Object : AgentService,
@@ -2102,9 +2883,9 @@ AttachmentsController = _ts_decorate9([
2102
2883
  ], AttachmentsController);
2103
2884
 
2104
2885
  // src/controller/chat.controller.ts
2105
- var import_nestjs_agent_core11 = require("@dudousxd/nestjs-agent-core");
2106
- var import_common10 = require("@nestjs/common");
2107
- function _ts_decorate10(decorators, target, key, desc) {
2886
+ var import_nestjs_agent_core12 = require("@dudousxd/nestjs-agent-core");
2887
+ var import_common11 = require("@nestjs/common");
2888
+ function _ts_decorate11(decorators, target, key, desc) {
2108
2889
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2109
2890
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2110
2891
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2117,39 +2898,52 @@ function _ts_decorate10(decorators, target, key, desc) {
2117
2898
  }
2118
2899
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2119
2900
  }
2120
- __name(_ts_decorate10, "_ts_decorate");
2121
- function _ts_metadata9(metadataKey, metadataValue) {
2901
+ __name(_ts_decorate11, "_ts_decorate");
2902
+ function _ts_metadata10(metadataKey, metadataValue) {
2122
2903
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2123
2904
  return Reflect.metadata(metadataKey, metadataValue);
2124
2905
  }
2125
2906
  }
2126
- __name(_ts_metadata9, "_ts_metadata");
2127
- function _ts_param8(paramIndex, decorator) {
2907
+ __name(_ts_metadata10, "_ts_metadata");
2908
+ function _ts_param9(paramIndex, decorator) {
2128
2909
  return function(target, key) {
2129
2910
  decorator(target, key, paramIndex);
2130
2911
  };
2131
2912
  }
2132
- __name(_ts_param8, "_ts_param");
2913
+ __name(_ts_param9, "_ts_param");
2914
+ function sendMode(body) {
2915
+ if (body.interrupt === true) {
2916
+ return "interrupt";
2917
+ }
2918
+ if (body.mode === void 0 || body.mode === null) {
2919
+ return "auto";
2920
+ }
2921
+ if (body.mode === "auto" || body.mode === "queue" || body.mode === "interrupt") {
2922
+ return body.mode;
2923
+ }
2924
+ throw new import_common11.BadRequestException("mode must be 'auto', 'queue' or 'interrupt'");
2925
+ }
2926
+ __name(sendMode, "sendMode");
2133
2927
  function attachmentRefs(claimed) {
2134
2928
  if (claimed === void 0) {
2135
2929
  return [];
2136
2930
  }
2137
2931
  if (!Array.isArray(claimed)) {
2138
- throw new import_common10.BadRequestException("attachments must be an array of { mediaId }");
2932
+ throw new import_common11.BadRequestException("attachments must be an array of { mediaId }");
2139
2933
  }
2140
2934
  if (claimed.length > MAX_ATTACHMENTS_PER_MESSAGE) {
2141
- throw new import_common10.BadRequestException(`a message may carry at most ${MAX_ATTACHMENTS_PER_MESSAGE} attachments`);
2935
+ throw new import_common11.BadRequestException(`a message may carry at most ${MAX_ATTACHMENTS_PER_MESSAGE} attachments`);
2142
2936
  }
2143
2937
  return claimed.map((entry) => {
2144
2938
  if (typeof entry !== "object" || entry === null || !("mediaId" in entry)) {
2145
- throw new import_common10.BadRequestException("each attachment must be an object with a mediaId");
2939
+ throw new import_common11.BadRequestException("each attachment must be an object with a mediaId");
2146
2940
  }
2147
2941
  if (Object.keys(entry).some((key) => key !== "mediaId")) {
2148
- throw new import_common10.BadRequestException("attachments are { mediaId } refs \u2014 send nothing but the id");
2942
+ throw new import_common11.BadRequestException("attachments are { mediaId } refs \u2014 send nothing but the id");
2149
2943
  }
2150
2944
  const { mediaId } = entry;
2151
2945
  if (typeof mediaId !== "string" || mediaId.length === 0) {
2152
- throw new import_common10.BadRequestException("each attachment must carry a non-empty string mediaId");
2946
+ throw new import_common11.BadRequestException("each attachment must carry a non-empty string mediaId");
2153
2947
  }
2154
2948
  return {
2155
2949
  mediaId
@@ -2167,10 +2961,17 @@ var ChatController = class {
2167
2961
  this.agent = agent;
2168
2962
  this.actorResolver = actorResolver;
2169
2963
  }
2964
+ /**
2965
+ * Start a turn and stream it — or, when the thread already has one running, queue the message and
2966
+ * answer `202 { queued: true, messageId, position, queue, … }` (JSON, no stream): it runs when the
2967
+ * turn ahead of it settles, and the stream of the run holding the thread announces it with a
2968
+ * `queue` frame.
2969
+ */
2170
2970
  async chat(req, res, body) {
2171
2971
  const actor = await this.actorResolver.resolve(req);
2172
2972
  const attachments = attachmentRefs(body.attachments);
2173
- const { runId, threadId } = await this.agent.chat({
2973
+ const mode = sendMode(body);
2974
+ const result = await this.agent.send({
2174
2975
  actor,
2175
2976
  message: body.message,
2176
2977
  ...body.threadId !== void 0 ? {
@@ -2193,8 +2994,14 @@ var ChatController = class {
2193
2994
  } : {},
2194
2995
  ...typeof body.model === "string" && body.model.length > 0 ? {
2195
2996
  model: body.model
2196
- } : {}
2997
+ } : {},
2998
+ mode
2197
2999
  });
3000
+ if (result.queued === true) {
3001
+ res.status(202).json(result);
3002
+ return;
3003
+ }
3004
+ const { runId, threadId } = result;
2198
3005
  await this.pipe(res, runId, this.agent.subscribe(runId), threadId);
2199
3006
  }
2200
3007
  /**
@@ -2269,7 +3076,7 @@ data: ${line}
2269
3076
  }
2270
3077
  res.write("event: done\ndata: {}\n\n");
2271
3078
  } catch (error) {
2272
- const payload = error instanceof import_nestjs_agent_core11.AgentStreamError ? {
3079
+ const payload = error instanceof import_nestjs_agent_core12.AgentStreamError ? {
2273
3080
  code: error.code,
2274
3081
  message: error.message
2275
3082
  } : {
@@ -2284,50 +3091,50 @@ data: ${JSON.stringify(payload)}
2284
3091
  res.end();
2285
3092
  }
2286
3093
  };
2287
- _ts_decorate10([
2288
- (0, import_common10.Post)("chat"),
2289
- _ts_param8(0, (0, import_common10.Req)()),
2290
- _ts_param8(1, (0, import_common10.Res)()),
2291
- _ts_param8(2, (0, import_common10.Body)()),
2292
- _ts_metadata9("design:type", Function),
2293
- _ts_metadata9("design:paramtypes", [
3094
+ _ts_decorate11([
3095
+ (0, import_common11.Post)("chat"),
3096
+ _ts_param9(0, (0, import_common11.Req)()),
3097
+ _ts_param9(1, (0, import_common11.Res)()),
3098
+ _ts_param9(2, (0, import_common11.Body)()),
3099
+ _ts_metadata10("design:type", Function),
3100
+ _ts_metadata10("design:paramtypes", [
2294
3101
  typeof Request === "undefined" ? Object : Request,
2295
3102
  typeof Response === "undefined" ? Object : Response,
2296
3103
  typeof ChatBody === "undefined" ? Object : ChatBody
2297
3104
  ]),
2298
- _ts_metadata9("design:returntype", Promise)
3105
+ _ts_metadata10("design:returntype", Promise)
2299
3106
  ], ChatController.prototype, "chat", null);
2300
- _ts_decorate10([
2301
- (0, import_common10.Get)("chat/:runId/stream"),
2302
- _ts_param8(0, (0, import_common10.Req)()),
2303
- _ts_param8(1, (0, import_common10.Param)("runId")),
2304
- _ts_param8(2, (0, import_common10.Res)()),
2305
- _ts_param8(3, (0, import_common10.Query)("after")),
2306
- _ts_metadata9("design:type", Function),
2307
- _ts_metadata9("design:paramtypes", [
3107
+ _ts_decorate11([
3108
+ (0, import_common11.Get)("chat/:runId/stream"),
3109
+ _ts_param9(0, (0, import_common11.Req)()),
3110
+ _ts_param9(1, (0, import_common11.Param)("runId")),
3111
+ _ts_param9(2, (0, import_common11.Res)()),
3112
+ _ts_param9(3, (0, import_common11.Query)("after")),
3113
+ _ts_metadata10("design:type", Function),
3114
+ _ts_metadata10("design:paramtypes", [
2308
3115
  typeof Request === "undefined" ? Object : Request,
2309
3116
  String,
2310
3117
  typeof Response === "undefined" ? Object : Response,
2311
3118
  String
2312
3119
  ]),
2313
- _ts_metadata9("design:returntype", Promise)
3120
+ _ts_metadata10("design:returntype", Promise)
2314
3121
  ], ChatController.prototype, "stream", null);
2315
- _ts_decorate10([
2316
- (0, import_common10.Post)("chat/:runId/cancel"),
2317
- _ts_param8(0, (0, import_common10.Req)()),
2318
- _ts_param8(1, (0, import_common10.Param)("runId")),
2319
- _ts_metadata9("design:type", Function),
2320
- _ts_metadata9("design:paramtypes", [
3122
+ _ts_decorate11([
3123
+ (0, import_common11.Post)("chat/:runId/cancel"),
3124
+ _ts_param9(0, (0, import_common11.Req)()),
3125
+ _ts_param9(1, (0, import_common11.Param)("runId")),
3126
+ _ts_metadata10("design:type", Function),
3127
+ _ts_metadata10("design:paramtypes", [
2321
3128
  typeof Request === "undefined" ? Object : Request,
2322
3129
  String
2323
3130
  ]),
2324
- _ts_metadata9("design:returntype", Promise)
3131
+ _ts_metadata10("design:returntype", Promise)
2325
3132
  ], ChatController.prototype, "cancel", null);
2326
- ChatController = _ts_decorate10([
2327
- (0, import_common10.Controller)(),
2328
- _ts_param8(1, (0, import_common10.Inject)(import_nestjs_agent_core11.AGENT_ACTOR_RESOLVER)),
2329
- _ts_metadata9("design:type", Function),
2330
- _ts_metadata9("design:paramtypes", [
3133
+ ChatController = _ts_decorate11([
3134
+ (0, import_common11.Controller)(),
3135
+ _ts_param9(1, (0, import_common11.Inject)(import_nestjs_agent_core12.AGENT_ACTOR_RESOLVER)),
3136
+ _ts_metadata10("design:type", Function),
3137
+ _ts_metadata10("design:paramtypes", [
2331
3138
  typeof AgentService === "undefined" ? Object : AgentService,
2332
3139
  typeof ActorResolver === "undefined" ? Object : ActorResolver
2333
3140
  ])
@@ -2343,8 +3150,8 @@ function parseCursor(raw) {
2343
3150
  __name(parseCursor, "parseCursor");
2344
3151
 
2345
3152
  // src/controller/config.controller.ts
2346
- var import_nestjs_agent_core12 = require("@dudousxd/nestjs-agent-core");
2347
- var import_common11 = require("@nestjs/common");
3153
+ var import_nestjs_agent_core13 = require("@dudousxd/nestjs-agent-core");
3154
+ var import_common12 = require("@nestjs/common");
2348
3155
 
2349
3156
  // src/resolver/anonymous-actor-resolver.ts
2350
3157
  var import_node_crypto2 = require("crypto");
@@ -2434,7 +3241,7 @@ var AnonymousActorResolver = class {
2434
3241
  };
2435
3242
 
2436
3243
  // src/controller/config.controller.ts
2437
- function _ts_decorate11(decorators, target, key, desc) {
3244
+ function _ts_decorate12(decorators, target, key, desc) {
2438
3245
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2439
3246
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2440
3247
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2447,19 +3254,19 @@ function _ts_decorate11(decorators, target, key, desc) {
2447
3254
  }
2448
3255
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2449
3256
  }
2450
- __name(_ts_decorate11, "_ts_decorate");
2451
- function _ts_metadata10(metadataKey, metadataValue) {
3257
+ __name(_ts_decorate12, "_ts_decorate");
3258
+ function _ts_metadata11(metadataKey, metadataValue) {
2452
3259
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2453
3260
  return Reflect.metadata(metadataKey, metadataValue);
2454
3261
  }
2455
3262
  }
2456
- __name(_ts_metadata10, "_ts_metadata");
2457
- function _ts_param9(paramIndex, decorator) {
3263
+ __name(_ts_metadata11, "_ts_metadata");
3264
+ function _ts_param10(paramIndex, decorator) {
2458
3265
  return function(target, key) {
2459
3266
  decorator(target, key, paramIndex);
2460
3267
  };
2461
3268
  }
2462
- __name(_ts_param9, "_ts_param");
3269
+ __name(_ts_param10, "_ts_param");
2463
3270
  var ConfigController = class {
2464
3271
  static {
2465
3272
  __name(this, "ConfigController");
@@ -2490,25 +3297,25 @@ var ConfigController = class {
2490
3297
  };
2491
3298
  }
2492
3299
  };
2493
- _ts_decorate11([
2494
- (0, import_common11.Get)(),
2495
- _ts_param9(0, (0, import_common11.Req)()),
2496
- _ts_metadata10("design:type", Function),
2497
- _ts_metadata10("design:paramtypes", [
3300
+ _ts_decorate12([
3301
+ (0, import_common12.Get)(),
3302
+ _ts_param10(0, (0, import_common12.Req)()),
3303
+ _ts_metadata11("design:type", Function),
3304
+ _ts_metadata11("design:paramtypes", [
2498
3305
  typeof Request === "undefined" ? Object : Request
2499
3306
  ]),
2500
- _ts_metadata10("design:returntype", Promise)
3307
+ _ts_metadata11("design:returntype", Promise)
2501
3308
  ], ConfigController.prototype, "config", null);
2502
- ConfigController = _ts_decorate11([
2503
- (0, import_common11.Controller)("config"),
2504
- _ts_param9(0, (0, import_common11.Inject)(import_nestjs_agent_core12.AGENT_OPTIONS)),
2505
- _ts_param9(1, (0, import_common11.Inject)(import_nestjs_agent_core12.AGENT_ACTOR_RESOLVER)),
2506
- _ts_param9(2, (0, import_common11.Optional)()),
2507
- _ts_param9(2, (0, import_common11.Inject)(import_nestjs_agent_core12.AGENT_ATTACHMENT_STAGING)),
2508
- _ts_param9(3, (0, import_common11.Optional)()),
2509
- _ts_param9(3, (0, import_common11.Inject)(import_nestjs_agent_core12.AGENT_MODEL_CATALOG)),
2510
- _ts_metadata10("design:type", Function),
2511
- _ts_metadata10("design:paramtypes", [
3309
+ ConfigController = _ts_decorate12([
3310
+ (0, import_common12.Controller)("config"),
3311
+ _ts_param10(0, (0, import_common12.Inject)(import_nestjs_agent_core13.AGENT_OPTIONS)),
3312
+ _ts_param10(1, (0, import_common12.Inject)(import_nestjs_agent_core13.AGENT_ACTOR_RESOLVER)),
3313
+ _ts_param10(2, (0, import_common12.Optional)()),
3314
+ _ts_param10(2, (0, import_common12.Inject)(import_nestjs_agent_core13.AGENT_ATTACHMENT_STAGING)),
3315
+ _ts_param10(3, (0, import_common12.Optional)()),
3316
+ _ts_param10(3, (0, import_common12.Inject)(import_nestjs_agent_core13.AGENT_MODEL_CATALOG)),
3317
+ _ts_metadata11("design:type", Function),
3318
+ _ts_metadata11("design:paramtypes", [
2512
3319
  typeof AgentModuleOptions === "undefined" ? Object : AgentModuleOptions,
2513
3320
  typeof ActorResolver === "undefined" ? Object : ActorResolver,
2514
3321
  Object,
@@ -2517,9 +3324,9 @@ ConfigController = _ts_decorate11([
2517
3324
  ], ConfigController);
2518
3325
 
2519
3326
  // src/controller/memories.controller.ts
2520
- var import_nestjs_agent_core13 = require("@dudousxd/nestjs-agent-core");
2521
- var import_common12 = require("@nestjs/common");
2522
- function _ts_decorate12(decorators, target, key, desc) {
3327
+ var import_nestjs_agent_core14 = require("@dudousxd/nestjs-agent-core");
3328
+ var import_common13 = require("@nestjs/common");
3329
+ function _ts_decorate13(decorators, target, key, desc) {
2523
3330
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2524
3331
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2525
3332
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2532,19 +3339,19 @@ function _ts_decorate12(decorators, target, key, desc) {
2532
3339
  }
2533
3340
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2534
3341
  }
2535
- __name(_ts_decorate12, "_ts_decorate");
2536
- function _ts_metadata11(metadataKey, metadataValue) {
3342
+ __name(_ts_decorate13, "_ts_decorate");
3343
+ function _ts_metadata12(metadataKey, metadataValue) {
2537
3344
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2538
3345
  return Reflect.metadata(metadataKey, metadataValue);
2539
3346
  }
2540
3347
  }
2541
- __name(_ts_metadata11, "_ts_metadata");
2542
- function _ts_param10(paramIndex, decorator) {
3348
+ __name(_ts_metadata12, "_ts_metadata");
3349
+ function _ts_param11(paramIndex, decorator) {
2543
3350
  return function(target, key) {
2544
3351
  decorator(target, key, paramIndex);
2545
3352
  };
2546
3353
  }
2547
- __name(_ts_param10, "_ts_param");
3354
+ __name(_ts_param11, "_ts_param");
2548
3355
  var MemoriesController = class {
2549
3356
  static {
2550
3357
  __name(this, "MemoriesController");
@@ -2578,20 +3385,20 @@ var MemoriesController = class {
2578
3385
  */
2579
3386
  async forget(req, id) {
2580
3387
  if (this.memory === void 0) {
2581
- throw new import_common12.NotFoundException("No memory is configured in this deployment.");
3388
+ throw new import_common13.NotFoundException("No memory is configured in this deployment.");
2582
3389
  }
2583
3390
  const actor = await this.actorResolver.resolve(req);
2584
3391
  const digest = await this.unbounded("", actor);
2585
3392
  const entry = digest.entries.find((candidate) => candidate.id === id);
2586
3393
  if (entry === void 0) {
2587
- throw new import_common12.NotFoundException(`No memory with id "${id}".`);
3394
+ throw new import_common13.NotFoundException(`No memory with id "${id}".`);
2588
3395
  }
2589
- const verdict = (0, import_nestjs_agent_core13.memoryForgetVerdict)({
3396
+ const verdict = (0, import_nestjs_agent_core14.memoryForgetVerdict)({
2590
3397
  record: entry,
2591
3398
  actor
2592
3399
  });
2593
3400
  if (!verdict.allowed) {
2594
- throw new import_common12.ForbiddenException(verdict.reason);
3401
+ throw new import_common13.ForbiddenException(verdict.reason);
2595
3402
  }
2596
3403
  return {
2597
3404
  forgotten: await this.memory.provider.forget({
@@ -2605,7 +3412,7 @@ var MemoriesController = class {
2605
3412
  }
2606
3413
  async unbounded(threadId, actor) {
2607
3414
  const config = this.memory;
2608
- return await (0, import_nestjs_agent_core13.offerMemories)({
3415
+ return await (0, import_nestjs_agent_core14.offerMemories)({
2609
3416
  config: {
2610
3417
  ...config,
2611
3418
  maxMemories: Number.POSITIVE_INFINITY
@@ -2617,44 +3424,44 @@ var MemoriesController = class {
2617
3424
  });
2618
3425
  }
2619
3426
  };
2620
- _ts_decorate12([
2621
- (0, import_common12.Get)(),
2622
- _ts_param10(0, (0, import_common12.Req)()),
2623
- _ts_param10(1, (0, import_common12.Query)("threadId")),
2624
- _ts_metadata11("design:type", Function),
2625
- _ts_metadata11("design:paramtypes", [
3427
+ _ts_decorate13([
3428
+ (0, import_common13.Get)(),
3429
+ _ts_param11(0, (0, import_common13.Req)()),
3430
+ _ts_param11(1, (0, import_common13.Query)("threadId")),
3431
+ _ts_metadata12("design:type", Function),
3432
+ _ts_metadata12("design:paramtypes", [
2626
3433
  typeof Request === "undefined" ? Object : Request,
2627
3434
  String
2628
3435
  ]),
2629
- _ts_metadata11("design:returntype", Promise)
3436
+ _ts_metadata12("design:returntype", Promise)
2630
3437
  ], MemoriesController.prototype, "list", null);
2631
- _ts_decorate12([
2632
- (0, import_common12.Delete)(":id"),
2633
- _ts_param10(0, (0, import_common12.Req)()),
2634
- _ts_param10(1, (0, import_common12.Param)("id")),
2635
- _ts_metadata11("design:type", Function),
2636
- _ts_metadata11("design:paramtypes", [
3438
+ _ts_decorate13([
3439
+ (0, import_common13.Delete)(":id"),
3440
+ _ts_param11(0, (0, import_common13.Req)()),
3441
+ _ts_param11(1, (0, import_common13.Param)("id")),
3442
+ _ts_metadata12("design:type", Function),
3443
+ _ts_metadata12("design:paramtypes", [
2637
3444
  typeof Request === "undefined" ? Object : Request,
2638
3445
  String
2639
3446
  ]),
2640
- _ts_metadata11("design:returntype", Promise)
3447
+ _ts_metadata12("design:returntype", Promise)
2641
3448
  ], MemoriesController.prototype, "forget", null);
2642
- MemoriesController = _ts_decorate12([
2643
- (0, import_common12.Controller)("memories"),
2644
- _ts_param10(0, (0, import_common12.Inject)(import_nestjs_agent_core13.AGENT_ACTOR_RESOLVER)),
2645
- _ts_param10(1, (0, import_common12.Optional)()),
2646
- _ts_param10(1, (0, import_common12.Inject)(import_nestjs_agent_core13.AGENT_MEMORY)),
2647
- _ts_metadata11("design:type", Function),
2648
- _ts_metadata11("design:paramtypes", [
3449
+ MemoriesController = _ts_decorate13([
3450
+ (0, import_common13.Controller)("memories"),
3451
+ _ts_param11(0, (0, import_common13.Inject)(import_nestjs_agent_core14.AGENT_ACTOR_RESOLVER)),
3452
+ _ts_param11(1, (0, import_common13.Optional)()),
3453
+ _ts_param11(1, (0, import_common13.Inject)(import_nestjs_agent_core14.AGENT_MEMORY)),
3454
+ _ts_metadata12("design:type", Function),
3455
+ _ts_metadata12("design:paramtypes", [
2649
3456
  typeof ActorResolver === "undefined" ? Object : ActorResolver,
2650
3457
  Object
2651
3458
  ])
2652
3459
  ], MemoriesController);
2653
3460
 
2654
3461
  // src/controller/messages.controller.ts
2655
- var import_nestjs_agent_core14 = require("@dudousxd/nestjs-agent-core");
2656
- var import_common13 = require("@nestjs/common");
2657
- function _ts_decorate13(decorators, target, key, desc) {
3462
+ var import_nestjs_agent_core15 = require("@dudousxd/nestjs-agent-core");
3463
+ var import_common14 = require("@nestjs/common");
3464
+ function _ts_decorate14(decorators, target, key, desc) {
2658
3465
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2659
3466
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2660
3467
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2667,19 +3474,19 @@ function _ts_decorate13(decorators, target, key, desc) {
2667
3474
  }
2668
3475
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2669
3476
  }
2670
- __name(_ts_decorate13, "_ts_decorate");
2671
- function _ts_metadata12(metadataKey, metadataValue) {
3477
+ __name(_ts_decorate14, "_ts_decorate");
3478
+ function _ts_metadata13(metadataKey, metadataValue) {
2672
3479
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2673
3480
  return Reflect.metadata(metadataKey, metadataValue);
2674
3481
  }
2675
3482
  }
2676
- __name(_ts_metadata12, "_ts_metadata");
2677
- function _ts_param11(paramIndex, decorator) {
3483
+ __name(_ts_metadata13, "_ts_metadata");
3484
+ function _ts_param12(paramIndex, decorator) {
2678
3485
  return function(target, key) {
2679
3486
  decorator(target, key, paramIndex);
2680
3487
  };
2681
3488
  }
2682
- __name(_ts_param11, "_ts_param");
3489
+ __name(_ts_param12, "_ts_param");
2683
3490
  var MessagesController = class {
2684
3491
  static {
2685
3492
  __name(this, "MessagesController");
@@ -2707,34 +3514,34 @@ var MessagesController = class {
2707
3514
  };
2708
3515
  }
2709
3516
  };
2710
- _ts_decorate13([
2711
- (0, import_common13.Post)(":id/feedback"),
2712
- (0, import_common13.HttpCode)(200),
2713
- _ts_param11(0, (0, import_common13.Req)()),
2714
- _ts_param11(1, (0, import_common13.Param)("id")),
2715
- _ts_param11(2, (0, import_common13.Body)()),
2716
- _ts_metadata12("design:type", Function),
2717
- _ts_metadata12("design:paramtypes", [
3517
+ _ts_decorate14([
3518
+ (0, import_common14.Post)(":id/feedback"),
3519
+ (0, import_common14.HttpCode)(200),
3520
+ _ts_param12(0, (0, import_common14.Req)()),
3521
+ _ts_param12(1, (0, import_common14.Param)("id")),
3522
+ _ts_param12(2, (0, import_common14.Body)()),
3523
+ _ts_metadata13("design:type", Function),
3524
+ _ts_metadata13("design:paramtypes", [
2718
3525
  typeof Request === "undefined" ? Object : Request,
2719
3526
  String,
2720
3527
  typeof FeedbackBody === "undefined" ? Object : FeedbackBody
2721
3528
  ]),
2722
- _ts_metadata12("design:returntype", Promise)
3529
+ _ts_metadata13("design:returntype", Promise)
2723
3530
  ], MessagesController.prototype, "feedback", null);
2724
- MessagesController = _ts_decorate13([
2725
- (0, import_common13.Controller)("messages"),
2726
- _ts_param11(1, (0, import_common13.Inject)(import_nestjs_agent_core14.AGENT_ACTOR_RESOLVER)),
2727
- _ts_metadata12("design:type", Function),
2728
- _ts_metadata12("design:paramtypes", [
3531
+ MessagesController = _ts_decorate14([
3532
+ (0, import_common14.Controller)("messages"),
3533
+ _ts_param12(1, (0, import_common14.Inject)(import_nestjs_agent_core15.AGENT_ACTOR_RESOLVER)),
3534
+ _ts_metadata13("design:type", Function),
3535
+ _ts_metadata13("design:paramtypes", [
2729
3536
  typeof AgentService === "undefined" ? Object : AgentService,
2730
3537
  typeof ActorResolver === "undefined" ? Object : ActorResolver
2731
3538
  ])
2732
3539
  ], MessagesController);
2733
3540
 
2734
3541
  // src/controller/models.controller.ts
2735
- var import_nestjs_agent_core15 = require("@dudousxd/nestjs-agent-core");
2736
- var import_common14 = require("@nestjs/common");
2737
- function _ts_decorate14(decorators, target, key, desc) {
3542
+ var import_nestjs_agent_core16 = require("@dudousxd/nestjs-agent-core");
3543
+ var import_common15 = require("@nestjs/common");
3544
+ function _ts_decorate15(decorators, target, key, desc) {
2738
3545
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2739
3546
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2740
3547
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2747,19 +3554,19 @@ function _ts_decorate14(decorators, target, key, desc) {
2747
3554
  }
2748
3555
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2749
3556
  }
2750
- __name(_ts_decorate14, "_ts_decorate");
2751
- function _ts_metadata13(metadataKey, metadataValue) {
3557
+ __name(_ts_decorate15, "_ts_decorate");
3558
+ function _ts_metadata14(metadataKey, metadataValue) {
2752
3559
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2753
3560
  return Reflect.metadata(metadataKey, metadataValue);
2754
3561
  }
2755
3562
  }
2756
- __name(_ts_metadata13, "_ts_metadata");
2757
- function _ts_param12(paramIndex, decorator) {
3563
+ __name(_ts_metadata14, "_ts_metadata");
3564
+ function _ts_param13(paramIndex, decorator) {
2758
3565
  return function(target, key) {
2759
3566
  decorator(target, key, paramIndex);
2760
3567
  };
2761
3568
  }
2762
- __name(_ts_param12, "_ts_param");
3569
+ __name(_ts_param13, "_ts_param");
2763
3570
  var ModelsController = class {
2764
3571
  static {
2765
3572
  __name(this, "ModelsController");
@@ -2779,31 +3586,172 @@ var ModelsController = class {
2779
3586
  return this.agent.listModels(actor, agent);
2780
3587
  }
2781
3588
  };
2782
- _ts_decorate14([
2783
- (0, import_common14.Get)(),
2784
- _ts_param12(0, (0, import_common14.Req)()),
2785
- _ts_param12(1, (0, import_common14.Query)("agent")),
2786
- _ts_metadata13("design:type", Function),
2787
- _ts_metadata13("design:paramtypes", [
3589
+ _ts_decorate15([
3590
+ (0, import_common15.Get)(),
3591
+ _ts_param13(0, (0, import_common15.Req)()),
3592
+ _ts_param13(1, (0, import_common15.Query)("agent")),
3593
+ _ts_metadata14("design:type", Function),
3594
+ _ts_metadata14("design:paramtypes", [
2788
3595
  typeof Request === "undefined" ? Object : Request,
2789
3596
  String
2790
3597
  ]),
2791
- _ts_metadata13("design:returntype", Promise)
3598
+ _ts_metadata14("design:returntype", Promise)
2792
3599
  ], ModelsController.prototype, "list", null);
2793
- ModelsController = _ts_decorate14([
2794
- (0, import_common14.Controller)("models"),
2795
- _ts_param12(1, (0, import_common14.Inject)(import_nestjs_agent_core15.AGENT_ACTOR_RESOLVER)),
2796
- _ts_metadata13("design:type", Function),
2797
- _ts_metadata13("design:paramtypes", [
3600
+ ModelsController = _ts_decorate15([
3601
+ (0, import_common15.Controller)("models"),
3602
+ _ts_param13(1, (0, import_common15.Inject)(import_nestjs_agent_core16.AGENT_ACTOR_RESOLVER)),
3603
+ _ts_metadata14("design:type", Function),
3604
+ _ts_metadata14("design:paramtypes", [
2798
3605
  typeof AgentService === "undefined" ? Object : AgentService,
2799
3606
  typeof ActorResolver === "undefined" ? Object : ActorResolver
2800
3607
  ])
2801
3608
  ], ModelsController);
2802
3609
 
3610
+ // src/controller/queue.controller.ts
3611
+ var import_nestjs_agent_core17 = require("@dudousxd/nestjs-agent-core");
3612
+ var import_common16 = require("@nestjs/common");
3613
+ function _ts_decorate16(decorators, target, key, desc) {
3614
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3615
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
3616
+ r = Reflect.decorate(decorators, target, key, desc);
3617
+ } else {
3618
+ for (var i = decorators.length - 1; i >= 0; i--) {
3619
+ if (d = decorators[i]) {
3620
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3621
+ }
3622
+ }
3623
+ }
3624
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3625
+ }
3626
+ __name(_ts_decorate16, "_ts_decorate");
3627
+ function _ts_metadata15(metadataKey, metadataValue) {
3628
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
3629
+ return Reflect.metadata(metadataKey, metadataValue);
3630
+ }
3631
+ }
3632
+ __name(_ts_metadata15, "_ts_metadata");
3633
+ function _ts_param14(paramIndex, decorator) {
3634
+ return function(target, key) {
3635
+ decorator(target, key, paramIndex);
3636
+ };
3637
+ }
3638
+ __name(_ts_param14, "_ts_param");
3639
+ var QueueController = class {
3640
+ static {
3641
+ __name(this, "QueueController");
3642
+ }
3643
+ agent;
3644
+ actorResolver;
3645
+ constructor(agent, actorResolver) {
3646
+ this.agent = agent;
3647
+ this.actorResolver = actorResolver;
3648
+ }
3649
+ async list(req, id) {
3650
+ return this.agent.getQueue(await this.actorResolver.resolve(req), id);
3651
+ }
3652
+ async clear(req, id) {
3653
+ return this.agent.clearQueue(await this.actorResolver.resolve(req), id);
3654
+ }
3655
+ /** Lift a pause; the head starts when nothing is running. Carries `runId` when it started. */
3656
+ async resume(req, id) {
3657
+ return this.agent.resumeQueue(await this.actorResolver.resolve(req), id);
3658
+ }
3659
+ async update(req, messageId, body) {
3660
+ const actor = await this.actorResolver.resolve(req);
3661
+ if (body.message !== void 0 && typeof body.message !== "string") {
3662
+ throw new import_common16.BadRequestException("message must be a string");
3663
+ }
3664
+ if (body.position !== void 0 && typeof body.position !== "number") {
3665
+ throw new import_common16.BadRequestException("position must be a number");
3666
+ }
3667
+ const attachments = body.attachments === void 0 ? void 0 : body.attachments === null ? null : attachmentRefs(body.attachments);
3668
+ return this.agent.updateQueuedMessage(actor, messageId, {
3669
+ ...body.message !== void 0 ? {
3670
+ message: body.message
3671
+ } : {},
3672
+ ...attachments !== void 0 ? {
3673
+ attachments
3674
+ } : {},
3675
+ ...body.position !== void 0 ? {
3676
+ position: body.position
3677
+ } : {}
3678
+ });
3679
+ }
3680
+ async remove(req, messageId) {
3681
+ return this.agent.removeQueuedMessage(await this.actorResolver.resolve(req), messageId);
3682
+ }
3683
+ };
3684
+ _ts_decorate16([
3685
+ (0, import_common16.Get)("threads/:id/queue"),
3686
+ _ts_param14(0, (0, import_common16.Req)()),
3687
+ _ts_param14(1, (0, import_common16.Param)("id")),
3688
+ _ts_metadata15("design:type", Function),
3689
+ _ts_metadata15("design:paramtypes", [
3690
+ typeof Request === "undefined" ? Object : Request,
3691
+ String
3692
+ ]),
3693
+ _ts_metadata15("design:returntype", Promise)
3694
+ ], QueueController.prototype, "list", null);
3695
+ _ts_decorate16([
3696
+ (0, import_common16.Delete)("threads/:id/queue"),
3697
+ _ts_param14(0, (0, import_common16.Req)()),
3698
+ _ts_param14(1, (0, import_common16.Param)("id")),
3699
+ _ts_metadata15("design:type", Function),
3700
+ _ts_metadata15("design:paramtypes", [
3701
+ typeof Request === "undefined" ? Object : Request,
3702
+ String
3703
+ ]),
3704
+ _ts_metadata15("design:returntype", Promise)
3705
+ ], QueueController.prototype, "clear", null);
3706
+ _ts_decorate16([
3707
+ (0, import_common16.Post)("threads/:id/queue/resume"),
3708
+ _ts_param14(0, (0, import_common16.Req)()),
3709
+ _ts_param14(1, (0, import_common16.Param)("id")),
3710
+ _ts_metadata15("design:type", Function),
3711
+ _ts_metadata15("design:paramtypes", [
3712
+ typeof Request === "undefined" ? Object : Request,
3713
+ String
3714
+ ]),
3715
+ _ts_metadata15("design:returntype", Promise)
3716
+ ], QueueController.prototype, "resume", null);
3717
+ _ts_decorate16([
3718
+ (0, import_common16.Patch)("queue/:messageId"),
3719
+ _ts_param14(0, (0, import_common16.Req)()),
3720
+ _ts_param14(1, (0, import_common16.Param)("messageId")),
3721
+ _ts_param14(2, (0, import_common16.Body)()),
3722
+ _ts_metadata15("design:type", Function),
3723
+ _ts_metadata15("design:paramtypes", [
3724
+ typeof Request === "undefined" ? Object : Request,
3725
+ String,
3726
+ typeof UpdateQueuedMessageBody === "undefined" ? Object : UpdateQueuedMessageBody
3727
+ ]),
3728
+ _ts_metadata15("design:returntype", Promise)
3729
+ ], QueueController.prototype, "update", null);
3730
+ _ts_decorate16([
3731
+ (0, import_common16.Delete)("queue/:messageId"),
3732
+ _ts_param14(0, (0, import_common16.Req)()),
3733
+ _ts_param14(1, (0, import_common16.Param)("messageId")),
3734
+ _ts_metadata15("design:type", Function),
3735
+ _ts_metadata15("design:paramtypes", [
3736
+ typeof Request === "undefined" ? Object : Request,
3737
+ String
3738
+ ]),
3739
+ _ts_metadata15("design:returntype", Promise)
3740
+ ], QueueController.prototype, "remove", null);
3741
+ QueueController = _ts_decorate16([
3742
+ (0, import_common16.Controller)(),
3743
+ _ts_param14(1, (0, import_common16.Inject)(import_nestjs_agent_core17.AGENT_ACTOR_RESOLVER)),
3744
+ _ts_metadata15("design:type", Function),
3745
+ _ts_metadata15("design:paramtypes", [
3746
+ typeof AgentService === "undefined" ? Object : AgentService,
3747
+ typeof ActorResolver === "undefined" ? Object : ActorResolver
3748
+ ])
3749
+ ], QueueController);
3750
+
2803
3751
  // src/controller/quota.controller.ts
2804
- var import_nestjs_agent_core16 = require("@dudousxd/nestjs-agent-core");
2805
- var import_common15 = require("@nestjs/common");
2806
- function _ts_decorate15(decorators, target, key, desc) {
3752
+ var import_nestjs_agent_core18 = require("@dudousxd/nestjs-agent-core");
3753
+ var import_common17 = require("@nestjs/common");
3754
+ function _ts_decorate17(decorators, target, key, desc) {
2807
3755
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2808
3756
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2809
3757
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2816,19 +3764,19 @@ function _ts_decorate15(decorators, target, key, desc) {
2816
3764
  }
2817
3765
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2818
3766
  }
2819
- __name(_ts_decorate15, "_ts_decorate");
2820
- function _ts_metadata14(metadataKey, metadataValue) {
3767
+ __name(_ts_decorate17, "_ts_decorate");
3768
+ function _ts_metadata16(metadataKey, metadataValue) {
2821
3769
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2822
3770
  return Reflect.metadata(metadataKey, metadataValue);
2823
3771
  }
2824
3772
  }
2825
- __name(_ts_metadata14, "_ts_metadata");
2826
- function _ts_param13(paramIndex, decorator) {
3773
+ __name(_ts_metadata16, "_ts_metadata");
3774
+ function _ts_param15(paramIndex, decorator) {
2827
3775
  return function(target, key) {
2828
3776
  decorator(target, key, paramIndex);
2829
3777
  };
2830
3778
  }
2831
- __name(_ts_param13, "_ts_param");
3779
+ __name(_ts_param15, "_ts_param");
2832
3780
  var QuotaController = class {
2833
3781
  static {
2834
3782
  __name(this, "QuotaController");
@@ -2848,29 +3796,29 @@ var QuotaController = class {
2848
3796
  return this.agent.quotaReport(actor);
2849
3797
  }
2850
3798
  };
2851
- _ts_decorate15([
2852
- (0, import_common15.Get)(),
2853
- _ts_param13(0, (0, import_common15.Req)()),
2854
- _ts_metadata14("design:type", Function),
2855
- _ts_metadata14("design:paramtypes", [
3799
+ _ts_decorate17([
3800
+ (0, import_common17.Get)(),
3801
+ _ts_param15(0, (0, import_common17.Req)()),
3802
+ _ts_metadata16("design:type", Function),
3803
+ _ts_metadata16("design:paramtypes", [
2856
3804
  typeof Request === "undefined" ? Object : Request
2857
3805
  ]),
2858
- _ts_metadata14("design:returntype", Promise)
3806
+ _ts_metadata16("design:returntype", Promise)
2859
3807
  ], QuotaController.prototype, "report", null);
2860
- QuotaController = _ts_decorate15([
2861
- (0, import_common15.Controller)("quota"),
2862
- _ts_param13(1, (0, import_common15.Inject)(import_nestjs_agent_core16.AGENT_ACTOR_RESOLVER)),
2863
- _ts_metadata14("design:type", Function),
2864
- _ts_metadata14("design:paramtypes", [
3808
+ QuotaController = _ts_decorate17([
3809
+ (0, import_common17.Controller)("quota"),
3810
+ _ts_param15(1, (0, import_common17.Inject)(import_nestjs_agent_core18.AGENT_ACTOR_RESOLVER)),
3811
+ _ts_metadata16("design:type", Function),
3812
+ _ts_metadata16("design:paramtypes", [
2865
3813
  typeof AgentService === "undefined" ? Object : AgentService,
2866
3814
  typeof ActorResolver === "undefined" ? Object : ActorResolver
2867
3815
  ])
2868
3816
  ], QuotaController);
2869
3817
 
2870
3818
  // src/controller/skills.controller.ts
2871
- var import_nestjs_agent_core17 = require("@dudousxd/nestjs-agent-core");
2872
- var import_common16 = require("@nestjs/common");
2873
- function _ts_decorate16(decorators, target, key, desc) {
3819
+ var import_nestjs_agent_core19 = require("@dudousxd/nestjs-agent-core");
3820
+ var import_common18 = require("@nestjs/common");
3821
+ function _ts_decorate18(decorators, target, key, desc) {
2874
3822
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2875
3823
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2876
3824
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2883,19 +3831,19 @@ function _ts_decorate16(decorators, target, key, desc) {
2883
3831
  }
2884
3832
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2885
3833
  }
2886
- __name(_ts_decorate16, "_ts_decorate");
2887
- function _ts_metadata15(metadataKey, metadataValue) {
3834
+ __name(_ts_decorate18, "_ts_decorate");
3835
+ function _ts_metadata17(metadataKey, metadataValue) {
2888
3836
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2889
3837
  return Reflect.metadata(metadataKey, metadataValue);
2890
3838
  }
2891
3839
  }
2892
- __name(_ts_metadata15, "_ts_metadata");
2893
- function _ts_param14(paramIndex, decorator) {
3840
+ __name(_ts_metadata17, "_ts_metadata");
3841
+ function _ts_param16(paramIndex, decorator) {
2894
3842
  return function(target, key) {
2895
3843
  decorator(target, key, paramIndex);
2896
3844
  };
2897
3845
  }
2898
- __name(_ts_param14, "_ts_param");
3846
+ __name(_ts_param16, "_ts_param");
2899
3847
  var SkillsController = class {
2900
3848
  static {
2901
3849
  __name(this, "SkillsController");
@@ -2911,40 +3859,40 @@ var SkillsController = class {
2911
3859
  return [];
2912
3860
  }
2913
3861
  const actor = await this.actorResolver.resolve(req);
2914
- const offer = await (0, import_nestjs_agent_core17.offerSkills)(this.skills, {
3862
+ const offer = await (0, import_nestjs_agent_core19.offerSkills)(this.skills, {
2915
3863
  actor,
2916
3864
  threadId: threadId ?? ""
2917
3865
  });
2918
3866
  return offer.entries;
2919
3867
  }
2920
3868
  };
2921
- _ts_decorate16([
2922
- (0, import_common16.Get)(),
2923
- _ts_param14(0, (0, import_common16.Req)()),
2924
- _ts_param14(1, (0, import_common16.Query)("threadId")),
2925
- _ts_metadata15("design:type", Function),
2926
- _ts_metadata15("design:paramtypes", [
3869
+ _ts_decorate18([
3870
+ (0, import_common18.Get)(),
3871
+ _ts_param16(0, (0, import_common18.Req)()),
3872
+ _ts_param16(1, (0, import_common18.Query)("threadId")),
3873
+ _ts_metadata17("design:type", Function),
3874
+ _ts_metadata17("design:paramtypes", [
2927
3875
  typeof Request === "undefined" ? Object : Request,
2928
3876
  String
2929
3877
  ]),
2930
- _ts_metadata15("design:returntype", Promise)
3878
+ _ts_metadata17("design:returntype", Promise)
2931
3879
  ], SkillsController.prototype, "list", null);
2932
- SkillsController = _ts_decorate16([
2933
- (0, import_common16.Controller)("skills"),
2934
- _ts_param14(0, (0, import_common16.Inject)(import_nestjs_agent_core17.AGENT_ACTOR_RESOLVER)),
2935
- _ts_param14(1, (0, import_common16.Optional)()),
2936
- _ts_param14(1, (0, import_common16.Inject)(import_nestjs_agent_core17.AGENT_SKILLS)),
2937
- _ts_metadata15("design:type", Function),
2938
- _ts_metadata15("design:paramtypes", [
3880
+ SkillsController = _ts_decorate18([
3881
+ (0, import_common18.Controller)("skills"),
3882
+ _ts_param16(0, (0, import_common18.Inject)(import_nestjs_agent_core19.AGENT_ACTOR_RESOLVER)),
3883
+ _ts_param16(1, (0, import_common18.Optional)()),
3884
+ _ts_param16(1, (0, import_common18.Inject)(import_nestjs_agent_core19.AGENT_SKILLS)),
3885
+ _ts_metadata17("design:type", Function),
3886
+ _ts_metadata17("design:paramtypes", [
2939
3887
  typeof ActorResolver === "undefined" ? Object : ActorResolver,
2940
3888
  Object
2941
3889
  ])
2942
3890
  ], SkillsController);
2943
3891
 
2944
3892
  // src/controller/threads.controller.ts
2945
- var import_nestjs_agent_core18 = require("@dudousxd/nestjs-agent-core");
2946
- var import_common17 = require("@nestjs/common");
2947
- function _ts_decorate17(decorators, target, key, desc) {
3893
+ var import_nestjs_agent_core20 = require("@dudousxd/nestjs-agent-core");
3894
+ var import_common19 = require("@nestjs/common");
3895
+ function _ts_decorate19(decorators, target, key, desc) {
2948
3896
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2949
3897
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2950
3898
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2957,19 +3905,19 @@ function _ts_decorate17(decorators, target, key, desc) {
2957
3905
  }
2958
3906
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2959
3907
  }
2960
- __name(_ts_decorate17, "_ts_decorate");
2961
- function _ts_metadata16(metadataKey, metadataValue) {
3908
+ __name(_ts_decorate19, "_ts_decorate");
3909
+ function _ts_metadata18(metadataKey, metadataValue) {
2962
3910
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2963
3911
  return Reflect.metadata(metadataKey, metadataValue);
2964
3912
  }
2965
3913
  }
2966
- __name(_ts_metadata16, "_ts_metadata");
2967
- function _ts_param15(paramIndex, decorator) {
3914
+ __name(_ts_metadata18, "_ts_metadata");
3915
+ function _ts_param17(paramIndex, decorator) {
2968
3916
  return function(target, key) {
2969
3917
  decorator(target, key, paramIndex);
2970
3918
  };
2971
3919
  }
2972
- __name(_ts_param15, "_ts_param");
3920
+ __name(_ts_param17, "_ts_param");
2973
3921
  var ThreadsController = class {
2974
3922
  static {
2975
3923
  __name(this, "ThreadsController");
@@ -3036,101 +3984,101 @@ var ThreadsController = class {
3036
3984
  };
3037
3985
  }
3038
3986
  };
3039
- _ts_decorate17([
3040
- (0, import_common17.Get)(),
3041
- _ts_param15(0, (0, import_common17.Req)()),
3042
- _ts_metadata16("design:type", Function),
3043
- _ts_metadata16("design:paramtypes", [
3987
+ _ts_decorate19([
3988
+ (0, import_common19.Get)(),
3989
+ _ts_param17(0, (0, import_common19.Req)()),
3990
+ _ts_metadata18("design:type", Function),
3991
+ _ts_metadata18("design:paramtypes", [
3044
3992
  typeof Request === "undefined" ? Object : Request
3045
3993
  ]),
3046
- _ts_metadata16("design:returntype", Promise)
3994
+ _ts_metadata18("design:returntype", Promise)
3047
3995
  ], ThreadsController.prototype, "list", null);
3048
- _ts_decorate17([
3049
- (0, import_common17.Get)(":id"),
3050
- _ts_param15(0, (0, import_common17.Req)()),
3051
- _ts_param15(1, (0, import_common17.Param)("id")),
3052
- _ts_metadata16("design:type", Function),
3053
- _ts_metadata16("design:paramtypes", [
3996
+ _ts_decorate19([
3997
+ (0, import_common19.Get)(":id"),
3998
+ _ts_param17(0, (0, import_common19.Req)()),
3999
+ _ts_param17(1, (0, import_common19.Param)("id")),
4000
+ _ts_metadata18("design:type", Function),
4001
+ _ts_metadata18("design:paramtypes", [
3054
4002
  typeof Request === "undefined" ? Object : Request,
3055
4003
  String
3056
4004
  ]),
3057
- _ts_metadata16("design:returntype", Promise)
4005
+ _ts_metadata18("design:returntype", Promise)
3058
4006
  ], ThreadsController.prototype, "detail", null);
3059
- _ts_decorate17([
3060
- (0, import_common17.Delete)(":id"),
3061
- _ts_param15(0, (0, import_common17.Req)()),
3062
- _ts_param15(1, (0, import_common17.Param)("id")),
3063
- _ts_metadata16("design:type", Function),
3064
- _ts_metadata16("design:paramtypes", [
4007
+ _ts_decorate19([
4008
+ (0, import_common19.Delete)(":id"),
4009
+ _ts_param17(0, (0, import_common19.Req)()),
4010
+ _ts_param17(1, (0, import_common19.Param)("id")),
4011
+ _ts_metadata18("design:type", Function),
4012
+ _ts_metadata18("design:paramtypes", [
3065
4013
  typeof Request === "undefined" ? Object : Request,
3066
4014
  String
3067
4015
  ]),
3068
- _ts_metadata16("design:returntype", Promise)
4016
+ _ts_metadata18("design:returntype", Promise)
3069
4017
  ], ThreadsController.prototype, "remove", null);
3070
- _ts_decorate17([
3071
- (0, import_common17.Post)(":id/fork-from/:messageId"),
3072
- _ts_param15(0, (0, import_common17.Req)()),
3073
- _ts_param15(1, (0, import_common17.Param)("id")),
3074
- _ts_param15(2, (0, import_common17.Param)("messageId")),
3075
- _ts_metadata16("design:type", Function),
3076
- _ts_metadata16("design:paramtypes", [
4018
+ _ts_decorate19([
4019
+ (0, import_common19.Post)(":id/fork-from/:messageId"),
4020
+ _ts_param17(0, (0, import_common19.Req)()),
4021
+ _ts_param17(1, (0, import_common19.Param)("id")),
4022
+ _ts_param17(2, (0, import_common19.Param)("messageId")),
4023
+ _ts_metadata18("design:type", Function),
4024
+ _ts_metadata18("design:paramtypes", [
3077
4025
  typeof Request === "undefined" ? Object : Request,
3078
4026
  String,
3079
4027
  String
3080
4028
  ]),
3081
- _ts_metadata16("design:returntype", Promise)
4029
+ _ts_metadata18("design:returntype", Promise)
3082
4030
  ], ThreadsController.prototype, "fork", null);
3083
- _ts_decorate17([
3084
- (0, import_common17.Patch)(":id"),
3085
- _ts_param15(0, (0, import_common17.Req)()),
3086
- _ts_param15(1, (0, import_common17.Param)("id")),
3087
- _ts_param15(2, (0, import_common17.Body)()),
3088
- _ts_metadata16("design:type", Function),
3089
- _ts_metadata16("design:paramtypes", [
4031
+ _ts_decorate19([
4032
+ (0, import_common19.Patch)(":id"),
4033
+ _ts_param17(0, (0, import_common19.Req)()),
4034
+ _ts_param17(1, (0, import_common19.Param)("id")),
4035
+ _ts_param17(2, (0, import_common19.Body)()),
4036
+ _ts_metadata18("design:type", Function),
4037
+ _ts_metadata18("design:paramtypes", [
3090
4038
  typeof Request === "undefined" ? Object : Request,
3091
4039
  String,
3092
4040
  typeof UpdateThreadBody === "undefined" ? Object : UpdateThreadBody
3093
4041
  ]),
3094
- _ts_metadata16("design:returntype", Promise)
4042
+ _ts_metadata18("design:returntype", Promise)
3095
4043
  ], ThreadsController.prototype, "update", null);
3096
- _ts_decorate17([
3097
- (0, import_common17.Post)(":id/promote"),
3098
- _ts_param15(0, (0, import_common17.Req)()),
3099
- _ts_param15(1, (0, import_common17.Param)("id")),
3100
- _ts_metadata16("design:type", Function),
3101
- _ts_metadata16("design:paramtypes", [
4044
+ _ts_decorate19([
4045
+ (0, import_common19.Post)(":id/promote"),
4046
+ _ts_param17(0, (0, import_common19.Req)()),
4047
+ _ts_param17(1, (0, import_common19.Param)("id")),
4048
+ _ts_metadata18("design:type", Function),
4049
+ _ts_metadata18("design:paramtypes", [
3102
4050
  typeof Request === "undefined" ? Object : Request,
3103
4051
  String
3104
4052
  ]),
3105
- _ts_metadata16("design:returntype", Promise)
4053
+ _ts_metadata18("design:returntype", Promise)
3106
4054
  ], ThreadsController.prototype, "promote", null);
3107
- _ts_decorate17([
3108
- (0, import_common17.Delete)(":id/from/:messageId"),
3109
- _ts_param15(0, (0, import_common17.Req)()),
3110
- _ts_param15(1, (0, import_common17.Param)("id")),
3111
- _ts_param15(2, (0, import_common17.Param)("messageId")),
3112
- _ts_metadata16("design:type", Function),
3113
- _ts_metadata16("design:paramtypes", [
4055
+ _ts_decorate19([
4056
+ (0, import_common19.Delete)(":id/from/:messageId"),
4057
+ _ts_param17(0, (0, import_common19.Req)()),
4058
+ _ts_param17(1, (0, import_common19.Param)("id")),
4059
+ _ts_param17(2, (0, import_common19.Param)("messageId")),
4060
+ _ts_metadata18("design:type", Function),
4061
+ _ts_metadata18("design:paramtypes", [
3114
4062
  typeof Request === "undefined" ? Object : Request,
3115
4063
  String,
3116
4064
  String
3117
4065
  ]),
3118
- _ts_metadata16("design:returntype", Promise)
4066
+ _ts_metadata18("design:returntype", Promise)
3119
4067
  ], ThreadsController.prototype, "truncateFrom", null);
3120
- ThreadsController = _ts_decorate17([
3121
- (0, import_common17.Controller)("threads"),
3122
- _ts_param15(1, (0, import_common17.Inject)(import_nestjs_agent_core18.AGENT_ACTOR_RESOLVER)),
3123
- _ts_metadata16("design:type", Function),
3124
- _ts_metadata16("design:paramtypes", [
4068
+ ThreadsController = _ts_decorate19([
4069
+ (0, import_common19.Controller)("threads"),
4070
+ _ts_param17(1, (0, import_common19.Inject)(import_nestjs_agent_core20.AGENT_ACTOR_RESOLVER)),
4071
+ _ts_metadata18("design:type", Function),
4072
+ _ts_metadata18("design:paramtypes", [
3125
4073
  typeof AgentService === "undefined" ? Object : AgentService,
3126
4074
  typeof ActorResolver === "undefined" ? Object : ActorResolver
3127
4075
  ])
3128
4076
  ], ThreadsController);
3129
4077
 
3130
4078
  // src/controller/tool-call.controller.ts
3131
- var import_nestjs_agent_core19 = require("@dudousxd/nestjs-agent-core");
3132
- var import_common18 = require("@nestjs/common");
3133
- function _ts_decorate18(decorators, target, key, desc) {
4079
+ var import_nestjs_agent_core21 = require("@dudousxd/nestjs-agent-core");
4080
+ var import_common20 = require("@nestjs/common");
4081
+ function _ts_decorate20(decorators, target, key, desc) {
3134
4082
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3135
4083
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
3136
4084
  r = Reflect.decorate(decorators, target, key, desc);
@@ -3143,19 +4091,19 @@ function _ts_decorate18(decorators, target, key, desc) {
3143
4091
  }
3144
4092
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3145
4093
  }
3146
- __name(_ts_decorate18, "_ts_decorate");
3147
- function _ts_metadata17(metadataKey, metadataValue) {
4094
+ __name(_ts_decorate20, "_ts_decorate");
4095
+ function _ts_metadata19(metadataKey, metadataValue) {
3148
4096
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
3149
4097
  return Reflect.metadata(metadataKey, metadataValue);
3150
4098
  }
3151
4099
  }
3152
- __name(_ts_metadata17, "_ts_metadata");
3153
- function _ts_param16(paramIndex, decorator) {
4100
+ __name(_ts_metadata19, "_ts_metadata");
4101
+ function _ts_param18(paramIndex, decorator) {
3154
4102
  return function(target, key) {
3155
4103
  decorator(target, key, paramIndex);
3156
4104
  };
3157
4105
  }
3158
- __name(_ts_param16, "_ts_param");
4106
+ __name(_ts_param18, "_ts_param");
3159
4107
  var MAX_ANSWERED_QUESTIONS = 100;
3160
4108
  var MAX_VALUES_PER_QUESTION = 100;
3161
4109
  var MAX_ANSWER_VALUE_LENGTH = 4096;
@@ -3164,7 +4112,7 @@ var MAX_VIA_LENGTH = 64;
3164
4112
  var DEFAULT_VIA = "web";
3165
4113
  function toolCallId(claimed) {
3166
4114
  if (typeof claimed !== "string" || claimed.length === 0) {
3167
- throw new import_common18.BadRequestException("toolCallId must be a non-empty string");
4115
+ throw new import_common20.BadRequestException("toolCallId must be a non-empty string");
3168
4116
  }
3169
4117
  return claimed;
3170
4118
  }
@@ -3174,10 +4122,10 @@ function rejectReason(claimed) {
3174
4122
  return void 0;
3175
4123
  }
3176
4124
  if (typeof claimed !== "string") {
3177
- throw new import_common18.BadRequestException("reason must be a string");
4125
+ throw new import_common20.BadRequestException("reason must be a string");
3178
4126
  }
3179
4127
  if (claimed.length > MAX_REJECT_REASON_LENGTH) {
3180
- throw new import_common18.BadRequestException(`reason must be at most ${MAX_REJECT_REASON_LENGTH} characters`);
4128
+ throw new import_common20.BadRequestException(`reason must be at most ${MAX_REJECT_REASON_LENGTH} characters`);
3181
4129
  }
3182
4130
  return claimed;
3183
4131
  }
@@ -3187,7 +4135,7 @@ function remember(claimed) {
3187
4135
  return false;
3188
4136
  }
3189
4137
  if (typeof claimed !== "boolean") {
3190
- throw new import_common18.BadRequestException("remember must be a boolean");
4138
+ throw new import_common20.BadRequestException("remember must be a boolean");
3191
4139
  }
3192
4140
  return claimed;
3193
4141
  }
@@ -3197,7 +4145,7 @@ function via(claimed) {
3197
4145
  return DEFAULT_VIA;
3198
4146
  }
3199
4147
  if (typeof claimed !== "string" || claimed.length === 0 || claimed.length > MAX_VIA_LENGTH) {
3200
- throw new import_common18.BadRequestException(`via must be a string of 1-${MAX_VIA_LENGTH} characters`);
4148
+ throw new import_common20.BadRequestException(`via must be a string of 1-${MAX_VIA_LENGTH} characters`);
3201
4149
  }
3202
4150
  return claimed;
3203
4151
  }
@@ -3207,26 +4155,26 @@ function answers(claimed) {
3207
4155
  return void 0;
3208
4156
  }
3209
4157
  if (typeof claimed !== "object" || claimed === null || Array.isArray(claimed)) {
3210
- throw new import_common18.BadRequestException("answers must be an object of questionId \u2192 chosen values");
4158
+ throw new import_common20.BadRequestException("answers must be an object of questionId \u2192 chosen values");
3211
4159
  }
3212
4160
  const entries = Object.entries(claimed);
3213
4161
  if (entries.length > MAX_ANSWERED_QUESTIONS) {
3214
- throw new import_common18.BadRequestException(`answers may cover at most ${MAX_ANSWERED_QUESTIONS} questions`);
4162
+ throw new import_common20.BadRequestException(`answers may cover at most ${MAX_ANSWERED_QUESTIONS} questions`);
3215
4163
  }
3216
4164
  const validated = /* @__PURE__ */ Object.create(null);
3217
4165
  for (const [questionId, values] of entries) {
3218
4166
  if (!Array.isArray(values)) {
3219
- throw new import_common18.BadRequestException(`answers["${questionId}"] must be an array of chosen values`);
4167
+ throw new import_common20.BadRequestException(`answers["${questionId}"] must be an array of chosen values`);
3220
4168
  }
3221
4169
  if (values.length > MAX_VALUES_PER_QUESTION) {
3222
- throw new import_common18.BadRequestException(`answers["${questionId}"] may carry at most ${MAX_VALUES_PER_QUESTION} values`);
4170
+ throw new import_common20.BadRequestException(`answers["${questionId}"] may carry at most ${MAX_VALUES_PER_QUESTION} values`);
3223
4171
  }
3224
4172
  for (const value of values) {
3225
4173
  if (typeof value !== "string") {
3226
- throw new import_common18.BadRequestException(`answers["${questionId}"] must contain only strings`);
4174
+ throw new import_common20.BadRequestException(`answers["${questionId}"] must contain only strings`);
3227
4175
  }
3228
4176
  if (value.length > MAX_ANSWER_VALUE_LENGTH) {
3229
- throw new import_common18.BadRequestException(`answers["${questionId}"] values must be at most ${MAX_ANSWER_VALUE_LENGTH} characters`);
4177
+ throw new import_common20.BadRequestException(`answers["${questionId}"] values must be at most ${MAX_ANSWER_VALUE_LENGTH} characters`);
3230
4178
  }
3231
4179
  }
3232
4180
  validated[questionId] = values;
@@ -3288,64 +4236,64 @@ var ToolCallController = class {
3288
4236
  };
3289
4237
  }
3290
4238
  };
3291
- _ts_decorate18([
3292
- (0, import_common18.Post)("approve"),
3293
- _ts_param16(0, (0, import_common18.Req)()),
3294
- _ts_param16(1, (0, import_common18.Body)()),
3295
- _ts_metadata17("design:type", Function),
3296
- _ts_metadata17("design:paramtypes", [
4239
+ _ts_decorate20([
4240
+ (0, import_common20.Post)("approve"),
4241
+ _ts_param18(0, (0, import_common20.Req)()),
4242
+ _ts_param18(1, (0, import_common20.Body)()),
4243
+ _ts_metadata19("design:type", Function),
4244
+ _ts_metadata19("design:paramtypes", [
3297
4245
  typeof Request === "undefined" ? Object : Request,
3298
4246
  typeof ApproveBody === "undefined" ? Object : ApproveBody
3299
4247
  ]),
3300
- _ts_metadata17("design:returntype", Promise)
4248
+ _ts_metadata19("design:returntype", Promise)
3301
4249
  ], ToolCallController.prototype, "approve", null);
3302
- _ts_decorate18([
3303
- (0, import_common18.Post)("reject"),
3304
- _ts_param16(0, (0, import_common18.Req)()),
3305
- _ts_param16(1, (0, import_common18.Body)()),
3306
- _ts_metadata17("design:type", Function),
3307
- _ts_metadata17("design:paramtypes", [
4250
+ _ts_decorate20([
4251
+ (0, import_common20.Post)("reject"),
4252
+ _ts_param18(0, (0, import_common20.Req)()),
4253
+ _ts_param18(1, (0, import_common20.Body)()),
4254
+ _ts_metadata19("design:type", Function),
4255
+ _ts_metadata19("design:paramtypes", [
3308
4256
  typeof Request === "undefined" ? Object : Request,
3309
4257
  typeof RejectBody === "undefined" ? Object : RejectBody
3310
4258
  ]),
3311
- _ts_metadata17("design:returntype", Promise)
4259
+ _ts_metadata19("design:returntype", Promise)
3312
4260
  ], ToolCallController.prototype, "reject", null);
3313
- _ts_decorate18([
3314
- (0, import_common18.Post)("answer"),
3315
- _ts_param16(0, (0, import_common18.Req)()),
3316
- _ts_param16(1, (0, import_common18.Body)()),
3317
- _ts_metadata17("design:type", Function),
3318
- _ts_metadata17("design:paramtypes", [
4261
+ _ts_decorate20([
4262
+ (0, import_common20.Post)("answer"),
4263
+ _ts_param18(0, (0, import_common20.Req)()),
4264
+ _ts_param18(1, (0, import_common20.Body)()),
4265
+ _ts_metadata19("design:type", Function),
4266
+ _ts_metadata19("design:paramtypes", [
3319
4267
  typeof Request === "undefined" ? Object : Request,
3320
4268
  typeof AnswerBody === "undefined" ? Object : AnswerBody
3321
4269
  ]),
3322
- _ts_metadata17("design:returntype", Promise)
4270
+ _ts_metadata19("design:returntype", Promise)
3323
4271
  ], ToolCallController.prototype, "answer", null);
3324
- _ts_decorate18([
3325
- (0, import_common18.Post)("skip"),
3326
- _ts_param16(0, (0, import_common18.Req)()),
3327
- _ts_param16(1, (0, import_common18.Body)()),
3328
- _ts_metadata17("design:type", Function),
3329
- _ts_metadata17("design:paramtypes", [
4272
+ _ts_decorate20([
4273
+ (0, import_common20.Post)("skip"),
4274
+ _ts_param18(0, (0, import_common20.Req)()),
4275
+ _ts_param18(1, (0, import_common20.Body)()),
4276
+ _ts_metadata19("design:type", Function),
4277
+ _ts_metadata19("design:paramtypes", [
3330
4278
  typeof Request === "undefined" ? Object : Request,
3331
4279
  Object
3332
4280
  ]),
3333
- _ts_metadata17("design:returntype", Promise)
4281
+ _ts_metadata19("design:returntype", Promise)
3334
4282
  ], ToolCallController.prototype, "skip", null);
3335
- ToolCallController = _ts_decorate18([
3336
- (0, import_common18.Controller)("tool-call"),
3337
- _ts_param16(1, (0, import_common18.Inject)(import_nestjs_agent_core19.AGENT_ACTOR_RESOLVER)),
3338
- _ts_metadata17("design:type", Function),
3339
- _ts_metadata17("design:paramtypes", [
4283
+ ToolCallController = _ts_decorate20([
4284
+ (0, import_common20.Controller)("tool-call"),
4285
+ _ts_param18(1, (0, import_common20.Inject)(import_nestjs_agent_core21.AGENT_ACTOR_RESOLVER)),
4286
+ _ts_metadata19("design:type", Function),
4287
+ _ts_metadata19("design:paramtypes", [
3340
4288
  typeof AgentService === "undefined" ? Object : AgentService,
3341
4289
  typeof ActorResolver === "undefined" ? Object : ActorResolver
3342
4290
  ])
3343
4291
  ], ToolCallController);
3344
4292
 
3345
4293
  // src/controller/tools.controller.ts
3346
- var import_nestjs_agent_core20 = require("@dudousxd/nestjs-agent-core");
3347
- var import_common19 = require("@nestjs/common");
3348
- function _ts_decorate19(decorators, target, key, desc) {
4294
+ var import_nestjs_agent_core22 = require("@dudousxd/nestjs-agent-core");
4295
+ var import_common21 = require("@nestjs/common");
4296
+ function _ts_decorate21(decorators, target, key, desc) {
3349
4297
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3350
4298
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
3351
4299
  r = Reflect.decorate(decorators, target, key, desc);
@@ -3358,19 +4306,19 @@ function _ts_decorate19(decorators, target, key, desc) {
3358
4306
  }
3359
4307
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3360
4308
  }
3361
- __name(_ts_decorate19, "_ts_decorate");
3362
- function _ts_metadata18(metadataKey, metadataValue) {
4309
+ __name(_ts_decorate21, "_ts_decorate");
4310
+ function _ts_metadata20(metadataKey, metadataValue) {
3363
4311
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
3364
4312
  return Reflect.metadata(metadataKey, metadataValue);
3365
4313
  }
3366
4314
  }
3367
- __name(_ts_metadata18, "_ts_metadata");
3368
- function _ts_param17(paramIndex, decorator) {
4315
+ __name(_ts_metadata20, "_ts_metadata");
4316
+ function _ts_param19(paramIndex, decorator) {
3369
4317
  return function(target, key) {
3370
4318
  decorator(target, key, paramIndex);
3371
4319
  };
3372
4320
  }
3373
- __name(_ts_param17, "_ts_param");
4321
+ __name(_ts_param19, "_ts_param");
3374
4322
  var ToolsController = class {
3375
4323
  static {
3376
4324
  __name(this, "ToolsController");
@@ -3384,11 +4332,11 @@ var ToolsController = class {
3384
4332
  this.agents = agents;
3385
4333
  }
3386
4334
  async list(req, agent) {
3387
- if (agent !== void 0 && agent !== import_nestjs_agent_core20.ALL_AGENTS && this.agents.get(agent) === void 0) {
3388
- throw new import_common19.NotFoundException(`No agent named "${agent}"`);
4335
+ if (agent !== void 0 && agent !== import_nestjs_agent_core22.ALL_AGENTS && this.agents.get(agent) === void 0) {
4336
+ throw new import_common21.NotFoundException(`No agent named "${agent}"`);
3389
4337
  }
3390
4338
  const actor = await this.actorResolver.resolve(req);
3391
- const names = agent === import_nestjs_agent_core20.ALL_AGENTS ? [
4339
+ const names = agent === import_nestjs_agent_core22.ALL_AGENTS ? [
3392
4340
  void 0,
3393
4341
  ...this.agents.list().map((definition) => definition.name)
3394
4342
  ] : [
@@ -3414,33 +4362,33 @@ var ToolsController = class {
3414
4362
  ];
3415
4363
  }
3416
4364
  };
3417
- _ts_decorate19([
3418
- (0, import_common19.Get)(),
3419
- _ts_param17(0, (0, import_common19.Req)()),
3420
- _ts_param17(1, (0, import_common19.Query)("agent")),
3421
- _ts_metadata18("design:type", Function),
3422
- _ts_metadata18("design:paramtypes", [
4365
+ _ts_decorate21([
4366
+ (0, import_common21.Get)(),
4367
+ _ts_param19(0, (0, import_common21.Req)()),
4368
+ _ts_param19(1, (0, import_common21.Query)("agent")),
4369
+ _ts_metadata20("design:type", Function),
4370
+ _ts_metadata20("design:paramtypes", [
3423
4371
  typeof Request === "undefined" ? Object : Request,
3424
4372
  String
3425
4373
  ]),
3426
- _ts_metadata18("design:returntype", Promise)
4374
+ _ts_metadata20("design:returntype", Promise)
3427
4375
  ], ToolsController.prototype, "list", null);
3428
- ToolsController = _ts_decorate19([
3429
- (0, import_common19.Controller)("tools"),
3430
- _ts_param17(0, (0, import_common19.Inject)(import_nestjs_agent_core20.AGENT_ACTOR_RESOLVER)),
3431
- _ts_param17(1, (0, import_common19.Inject)(import_nestjs_agent_core20.AGENT_DEPS_FACTORY)),
3432
- _ts_param17(2, (0, import_common19.Inject)(import_nestjs_agent_core20.AGENT_REGISTRY)),
3433
- _ts_metadata18("design:type", Function),
3434
- _ts_metadata18("design:paramtypes", [
4376
+ ToolsController = _ts_decorate21([
4377
+ (0, import_common21.Controller)("tools"),
4378
+ _ts_param19(0, (0, import_common21.Inject)(import_nestjs_agent_core22.AGENT_ACTOR_RESOLVER)),
4379
+ _ts_param19(1, (0, import_common21.Inject)(import_nestjs_agent_core22.AGENT_DEPS_FACTORY)),
4380
+ _ts_param19(2, (0, import_common21.Inject)(import_nestjs_agent_core22.AGENT_REGISTRY)),
4381
+ _ts_metadata20("design:type", Function),
4382
+ _ts_metadata20("design:paramtypes", [
3435
4383
  typeof ActorResolver === "undefined" ? Object : ActorResolver,
3436
4384
  typeof AgentDepsFactory === "undefined" ? Object : AgentDepsFactory,
3437
- typeof import_nestjs_agent_core20.AgentRegistry === "undefined" ? Object : import_nestjs_agent_core20.AgentRegistry
4385
+ typeof import_nestjs_agent_core22.AgentRegistry === "undefined" ? Object : import_nestjs_agent_core22.AgentRegistry
3438
4386
  ])
3439
4387
  ], ToolsController);
3440
4388
 
3441
4389
  // src/discovery/agent-discovery.service.ts
3442
- var import_nestjs_agent_core21 = require("@dudousxd/nestjs-agent-core");
3443
- var import_common20 = require("@nestjs/common");
4390
+ var import_nestjs_agent_core23 = require("@dudousxd/nestjs-agent-core");
4391
+ var import_common22 = require("@nestjs/common");
3444
4392
  var import_core = require("@nestjs/core");
3445
4393
 
3446
4394
  // src/decorator/agent.decorator.ts
@@ -3457,7 +4405,7 @@ var SYSTEM_PROMPT_METADATA = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:
3457
4405
  var SYSTEM_PROMPT_CONTRIBUTOR_METADATA = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:system-prompt-contributor");
3458
4406
 
3459
4407
  // src/discovery/agent-discovery.service.ts
3460
- function _ts_decorate20(decorators, target, key, desc) {
4408
+ function _ts_decorate22(decorators, target, key, desc) {
3461
4409
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3462
4410
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
3463
4411
  r = Reflect.decorate(decorators, target, key, desc);
@@ -3470,19 +4418,19 @@ function _ts_decorate20(decorators, target, key, desc) {
3470
4418
  }
3471
4419
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3472
4420
  }
3473
- __name(_ts_decorate20, "_ts_decorate");
3474
- function _ts_metadata19(metadataKey, metadataValue) {
4421
+ __name(_ts_decorate22, "_ts_decorate");
4422
+ function _ts_metadata21(metadataKey, metadataValue) {
3475
4423
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
3476
4424
  return Reflect.metadata(metadataKey, metadataValue);
3477
4425
  }
3478
4426
  }
3479
- __name(_ts_metadata19, "_ts_metadata");
3480
- function _ts_param18(paramIndex, decorator) {
4427
+ __name(_ts_metadata21, "_ts_metadata");
4428
+ function _ts_param20(paramIndex, decorator) {
3481
4429
  return function(target, key) {
3482
4430
  decorator(target, key, paramIndex);
3483
4431
  };
3484
4432
  }
3485
- __name(_ts_param18, "_ts_param");
4433
+ __name(_ts_param20, "_ts_param");
3486
4434
  var AgentDiscoveryService = class _AgentDiscoveryService {
3487
4435
  static {
3488
4436
  __name(this, "AgentDiscoveryService");
@@ -3491,7 +4439,7 @@ var AgentDiscoveryService = class _AgentDiscoveryService {
3491
4439
  scanner;
3492
4440
  registry;
3493
4441
  contributors;
3494
- logger = new import_common20.Logger(_AgentDiscoveryService.name);
4442
+ logger = new import_common22.Logger(_AgentDiscoveryService.name);
3495
4443
  constructor(discovery, scanner, registry, contributors) {
3496
4444
  this.discovery = discovery;
3497
4445
  this.scanner = scanner;
@@ -3609,22 +4557,22 @@ var AgentDiscoveryService = class _AgentDiscoveryService {
3609
4557
  return (ctx) => candidate.call(instance, ctx);
3610
4558
  }
3611
4559
  };
3612
- AgentDiscoveryService = _ts_decorate20([
3613
- (0, import_common20.Injectable)(),
3614
- _ts_param18(2, (0, import_common20.Inject)(import_nestjs_agent_core21.AGENT_REGISTRY)),
3615
- _ts_param18(3, (0, import_common20.Inject)(import_nestjs_agent_core21.AGENT_PROMPT_CONTRIBUTORS)),
3616
- _ts_metadata19("design:type", Function),
3617
- _ts_metadata19("design:paramtypes", [
4560
+ AgentDiscoveryService = _ts_decorate22([
4561
+ (0, import_common22.Injectable)(),
4562
+ _ts_param20(2, (0, import_common22.Inject)(import_nestjs_agent_core23.AGENT_REGISTRY)),
4563
+ _ts_param20(3, (0, import_common22.Inject)(import_nestjs_agent_core23.AGENT_PROMPT_CONTRIBUTORS)),
4564
+ _ts_metadata21("design:type", Function),
4565
+ _ts_metadata21("design:paramtypes", [
3618
4566
  typeof import_core.DiscoveryService === "undefined" ? Object : import_core.DiscoveryService,
3619
4567
  typeof import_core.MetadataScanner === "undefined" ? Object : import_core.MetadataScanner,
3620
- typeof import_nestjs_agent_core21.AgentRegistry === "undefined" ? Object : import_nestjs_agent_core21.AgentRegistry,
4568
+ typeof import_nestjs_agent_core23.AgentRegistry === "undefined" ? Object : import_nestjs_agent_core23.AgentRegistry,
3621
4569
  Array
3622
4570
  ])
3623
4571
  ], AgentDiscoveryService);
3624
4572
 
3625
4573
  // src/discovery/ai-tool-discovery.service.ts
3626
- var import_nestjs_agent_core22 = require("@dudousxd/nestjs-agent-core");
3627
- var import_common21 = require("@nestjs/common");
4574
+ var import_nestjs_agent_core24 = require("@dudousxd/nestjs-agent-core");
4575
+ var import_common23 = require("@nestjs/common");
3628
4576
  var import_core2 = require("@nestjs/core");
3629
4577
  var import_zod = require("zod");
3630
4578
 
@@ -3644,7 +4592,7 @@ function isBrandedFunctionalTool(value) {
3644
4592
  __name(isBrandedFunctionalTool, "isBrandedFunctionalTool");
3645
4593
 
3646
4594
  // src/discovery/ai-tool-discovery.service.ts
3647
- function _ts_decorate21(decorators, target, key, desc) {
4595
+ function _ts_decorate23(decorators, target, key, desc) {
3648
4596
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3649
4597
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
3650
4598
  r = Reflect.decorate(decorators, target, key, desc);
@@ -3657,19 +4605,19 @@ function _ts_decorate21(decorators, target, key, desc) {
3657
4605
  }
3658
4606
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3659
4607
  }
3660
- __name(_ts_decorate21, "_ts_decorate");
3661
- function _ts_metadata20(metadataKey, metadataValue) {
4608
+ __name(_ts_decorate23, "_ts_decorate");
4609
+ function _ts_metadata22(metadataKey, metadataValue) {
3662
4610
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
3663
4611
  return Reflect.metadata(metadataKey, metadataValue);
3664
4612
  }
3665
4613
  }
3666
- __name(_ts_metadata20, "_ts_metadata");
3667
- function _ts_param19(paramIndex, decorator) {
4614
+ __name(_ts_metadata22, "_ts_metadata");
4615
+ function _ts_param21(paramIndex, decorator) {
3668
4616
  return function(target, key) {
3669
4617
  decorator(target, key, paramIndex);
3670
4618
  };
3671
4619
  }
3672
- __name(_ts_param19, "_ts_param");
4620
+ __name(_ts_param21, "_ts_param");
3673
4621
  var AiToolDiscoveryService = class _AiToolDiscoveryService {
3674
4622
  static {
3675
4623
  __name(this, "AiToolDiscoveryService");
@@ -3678,7 +4626,7 @@ var AiToolDiscoveryService = class _AiToolDiscoveryService {
3678
4626
  registry;
3679
4627
  agents;
3680
4628
  options;
3681
- logger = new import_common21.Logger(_AiToolDiscoveryService.name);
4629
+ logger = new import_common23.Logger(_AiToolDiscoveryService.name);
3682
4630
  constructor(discovery, registry, agents, options) {
3683
4631
  this.discovery = discovery;
3684
4632
  this.registry = registry;
@@ -3763,7 +4711,7 @@ var AiToolDiscoveryService = class _AiToolDiscoveryService {
3763
4711
  let delegates = 0;
3764
4712
  for (const definition of this.agents.list()) {
3765
4713
  for (const edge of definition.delegatesTo ?? []) {
3766
- const { agent: target, detached } = (0, import_nestjs_agent_core22.normalizeDelegation)(edge);
4714
+ const { agent: target, detached } = (0, import_nestjs_agent_core24.normalizeDelegation)(edge);
3767
4715
  const targetDefinition = this.agents.get(target);
3768
4716
  if (targetDefinition === void 0) {
3769
4717
  throw new Error(`Agent "${definition.name}" hands off to "${target}", which is not a registered @Agent. Declare it as an @Agent provider or fix the reference.`);
@@ -3813,13 +4761,13 @@ var AiToolDiscoveryService = class _AiToolDiscoveryService {
3813
4761
  return true;
3814
4762
  }
3815
4763
  };
3816
- AiToolDiscoveryService = _ts_decorate21([
3817
- (0, import_common21.Injectable)(),
3818
- _ts_param19(1, (0, import_common21.Inject)(import_nestjs_agent_core22.AGENT_TOOL_REGISTRY)),
3819
- _ts_param19(2, (0, import_common21.Inject)(import_nestjs_agent_core22.AGENT_REGISTRY)),
3820
- _ts_param19(3, (0, import_common21.Inject)(import_nestjs_agent_core22.AGENT_OPTIONS)),
3821
- _ts_metadata20("design:type", Function),
3822
- _ts_metadata20("design:paramtypes", [
4764
+ AiToolDiscoveryService = _ts_decorate23([
4765
+ (0, import_common23.Injectable)(),
4766
+ _ts_param21(1, (0, import_common23.Inject)(import_nestjs_agent_core24.AGENT_TOOL_REGISTRY)),
4767
+ _ts_param21(2, (0, import_common23.Inject)(import_nestjs_agent_core24.AGENT_REGISTRY)),
4768
+ _ts_param21(3, (0, import_common23.Inject)(import_nestjs_agent_core24.AGENT_OPTIONS)),
4769
+ _ts_metadata22("design:type", Function),
4770
+ _ts_metadata22("design:paramtypes", [
3823
4771
  typeof import_core2.DiscoveryService === "undefined" ? Object : import_core2.DiscoveryService,
3824
4772
  typeof ToolRegistry === "undefined" ? Object : ToolRegistry,
3825
4773
  typeof AgentRegistry === "undefined" ? Object : AgentRegistry,
@@ -3828,25 +4776,25 @@ AiToolDiscoveryService = _ts_decorate21([
3828
4776
  ], AiToolDiscoveryService);
3829
4777
 
3830
4778
  // src/discovery/skill-discovery.service.ts
3831
- var import_nestjs_agent_core24 = require("@dudousxd/nestjs-agent-core");
3832
- var import_common22 = require("@nestjs/common");
4779
+ var import_nestjs_agent_core26 = require("@dudousxd/nestjs-agent-core");
4780
+ var import_common24 = require("@nestjs/common");
3833
4781
  var import_core3 = require("@nestjs/core");
3834
4782
 
3835
4783
  // src/decorator/skill.decorator.ts
3836
4784
  var import_reflect_metadata4 = require("reflect-metadata");
3837
- var import_nestjs_agent_core23 = require("@dudousxd/nestjs-agent-core");
4785
+ var import_nestjs_agent_core25 = require("@dudousxd/nestjs-agent-core");
3838
4786
  var SKILL_METADATA = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:skill-metadata");
3839
4787
  function readSkillMetadata(target) {
3840
4788
  return Reflect.getMetadata(SKILL_METADATA, target);
3841
4789
  }
3842
4790
  __name(readSkillMetadata, "readSkillMetadata");
3843
4791
  function skillScope(options) {
3844
- return options.scope ?? import_nestjs_agent_core23.GLOBAL_SCOPE;
4792
+ return options.scope ?? import_nestjs_agent_core25.GLOBAL_SCOPE;
3845
4793
  }
3846
4794
  __name(skillScope, "skillScope");
3847
4795
 
3848
4796
  // src/discovery/skill-discovery.service.ts
3849
- function _ts_decorate22(decorators, target, key, desc) {
4797
+ function _ts_decorate24(decorators, target, key, desc) {
3850
4798
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3851
4799
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
3852
4800
  r = Reflect.decorate(decorators, target, key, desc);
@@ -3859,26 +4807,26 @@ function _ts_decorate22(decorators, target, key, desc) {
3859
4807
  }
3860
4808
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3861
4809
  }
3862
- __name(_ts_decorate22, "_ts_decorate");
3863
- function _ts_metadata21(metadataKey, metadataValue) {
4810
+ __name(_ts_decorate24, "_ts_decorate");
4811
+ function _ts_metadata23(metadataKey, metadataValue) {
3864
4812
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
3865
4813
  return Reflect.metadata(metadataKey, metadataValue);
3866
4814
  }
3867
4815
  }
3868
- __name(_ts_metadata21, "_ts_metadata");
3869
- function _ts_param20(paramIndex, decorator) {
4816
+ __name(_ts_metadata23, "_ts_metadata");
4817
+ function _ts_param22(paramIndex, decorator) {
3870
4818
  return function(target, key) {
3871
4819
  decorator(target, key, paramIndex);
3872
4820
  };
3873
4821
  }
3874
- __name(_ts_param20, "_ts_param");
4822
+ __name(_ts_param22, "_ts_param");
3875
4823
  var SkillDiscoveryService = class _SkillDiscoveryService {
3876
4824
  static {
3877
4825
  __name(this, "SkillDiscoveryService");
3878
4826
  }
3879
4827
  discovery;
3880
4828
  declared;
3881
- logger = new import_common22.Logger(_SkillDiscoveryService.name);
4829
+ logger = new import_common24.Logger(_SkillDiscoveryService.name);
3882
4830
  constructor(discovery, declared) {
3883
4831
  this.discovery = discovery;
3884
4832
  this.declared = declared;
@@ -3915,18 +4863,18 @@ var SkillDiscoveryService = class _SkillDiscoveryService {
3915
4863
  return flat === void 0 ? void 0 : () => flat;
3916
4864
  }
3917
4865
  };
3918
- SkillDiscoveryService = _ts_decorate22([
3919
- (0, import_common22.Injectable)(),
3920
- _ts_param20(1, (0, import_common22.Inject)(import_nestjs_agent_core24.AGENT_SKILL_SOURCES)),
3921
- _ts_metadata21("design:type", Function),
3922
- _ts_metadata21("design:paramtypes", [
4866
+ SkillDiscoveryService = _ts_decorate24([
4867
+ (0, import_common24.Injectable)(),
4868
+ _ts_param22(1, (0, import_common24.Inject)(import_nestjs_agent_core26.AGENT_SKILL_SOURCES)),
4869
+ _ts_metadata23("design:type", Function),
4870
+ _ts_metadata23("design:paramtypes", [
3923
4871
  typeof import_core3.DiscoveryService === "undefined" ? Object : import_core3.DiscoveryService,
3924
4872
  Array
3925
4873
  ])
3926
4874
  ], SkillDiscoveryService);
3927
4875
 
3928
4876
  // src/ledger-quota-provider.ts
3929
- var import_nestjs_agent_core25 = require("@dudousxd/nestjs-agent-core");
4877
+ var import_nestjs_agent_core27 = require("@dudousxd/nestjs-agent-core");
3930
4878
  var LedgerQuotaProvider = class {
3931
4879
  static {
3932
4880
  __name(this, "LedgerQuotaProvider");
@@ -3946,12 +4894,12 @@ var LedgerQuotaProvider = class {
3946
4894
  await this.dayWindow(actorRef, now)
3947
4895
  ];
3948
4896
  if (this.store.usageBetween !== void 0) {
3949
- const range = (0, import_nestjs_agent_core25.quotaPeriodRange)("month", now);
4897
+ const range = (0, import_nestjs_agent_core27.quotaPeriodRange)("month", now);
3950
4898
  const used = await this.store.usageBetween(actorRef, range.fromDay, range.toDay);
3951
4899
  windows.push(this.window("month", used.usedTokens, used.costUsd, range.resetsAt));
3952
4900
  }
3953
- const blocked = (0, import_nestjs_agent_core25.exhaustedWindow)(windows);
3954
- const warning = (0, import_nestjs_agent_core25.quotaWarning)(windows);
4901
+ const blocked = (0, import_nestjs_agent_core27.exhaustedWindow)(windows);
4902
+ const warning = (0, import_nestjs_agent_core27.quotaWarning)(windows);
3955
4903
  return {
3956
4904
  windows,
3957
4905
  ...blocked !== void 0 ? {
@@ -3963,7 +4911,7 @@ var LedgerQuotaProvider = class {
3963
4911
  };
3964
4912
  }
3965
4913
  async dayWindow(actorRef, now) {
3966
- const range = (0, import_nestjs_agent_core25.quotaPeriodRange)("day", now);
4914
+ const range = (0, import_nestjs_agent_core27.quotaPeriodRange)("day", now);
3967
4915
  const { usedTokens, costUsd } = await this.store.quotaToday(actorRef, range.fromDay);
3968
4916
  return this.window("day", usedTokens, costUsd, range.resetsAt);
3969
4917
  }
@@ -3988,9 +4936,9 @@ var LedgerQuotaProvider = class {
3988
4936
  };
3989
4937
 
3990
4938
  // src/runner/inline-agent-runner.ts
3991
- var import_nestjs_agent_core26 = require("@dudousxd/nestjs-agent-core");
3992
- var import_common23 = require("@nestjs/common");
3993
- function _ts_decorate23(decorators, target, key, desc) {
4939
+ var import_nestjs_agent_core28 = require("@dudousxd/nestjs-agent-core");
4940
+ var import_common25 = require("@nestjs/common");
4941
+ function _ts_decorate25(decorators, target, key, desc) {
3994
4942
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3995
4943
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
3996
4944
  r = Reflect.decorate(decorators, target, key, desc);
@@ -4003,26 +4951,27 @@ function _ts_decorate23(decorators, target, key, desc) {
4003
4951
  }
4004
4952
  return c > 3 && r && Object.defineProperty(target, key, r), r;
4005
4953
  }
4006
- __name(_ts_decorate23, "_ts_decorate");
4007
- function _ts_metadata22(metadataKey, metadataValue) {
4954
+ __name(_ts_decorate25, "_ts_decorate");
4955
+ function _ts_metadata24(metadataKey, metadataValue) {
4008
4956
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
4009
4957
  return Reflect.metadata(metadataKey, metadataValue);
4010
4958
  }
4011
4959
  }
4012
- __name(_ts_metadata22, "_ts_metadata");
4013
- function _ts_param21(paramIndex, decorator) {
4960
+ __name(_ts_metadata24, "_ts_metadata");
4961
+ function _ts_param23(paramIndex, decorator) {
4014
4962
  return function(target, key) {
4015
4963
  decorator(target, key, paramIndex);
4016
4964
  };
4017
4965
  }
4018
- __name(_ts_param21, "_ts_param");
4966
+ __name(_ts_param23, "_ts_param");
4019
4967
  var InlineAgentRunner = class _InlineAgentRunner {
4020
4968
  static {
4021
4969
  __name(this, "InlineAgentRunner");
4022
4970
  }
4023
4971
  factory;
4024
4972
  store;
4025
- logger = new import_common23.Logger(_InlineAgentRunner.name);
4973
+ queue;
4974
+ logger = new import_common25.Logger(_InlineAgentRunner.name);
4026
4975
  pending = /* @__PURE__ */ new Map();
4027
4976
  /**
4028
4977
  * Runs someone has asked to stop. In-process, like `pending`, and for the same reason: this runner
@@ -4030,14 +4979,25 @@ var InlineAgentRunner = class _InlineAgentRunner {
4030
4979
  * running it. A cancelled id is dropped once the run settles, so the set tracks live runs only.
4031
4980
  */
4032
4981
  cancelled = /* @__PURE__ */ new Set();
4033
- constructor(factory, store) {
4982
+ /** Top-level runs this process is running now — what {@link isRunActive} answers from. */
4983
+ live = /* @__PURE__ */ new Set();
4984
+ constructor(factory, store, queue) {
4034
4985
  this.factory = factory;
4035
4986
  this.store = store;
4987
+ this.queue = queue;
4036
4988
  }
4037
- async start(input) {
4038
- const runId = crypto.randomUUID();
4989
+ /**
4990
+ * In-process, so exact: a run this process is not running is not running anywhere — the process
4991
+ * that was running it is gone (a restart), and a thread it still holds is a stale claim.
4992
+ */
4993
+ async isRunActive(runId) {
4994
+ return this.live.has(runId);
4995
+ }
4996
+ async start(input, options = {}) {
4997
+ const runId = options.runId ?? crypto.randomUUID();
4039
4998
  const day = input.day ?? utcDay();
4040
4999
  const deps = this.factory.forAgent(input.agentName);
5000
+ this.live.add(runId);
4041
5001
  const hooks = this.topLevelHooks({
4042
5002
  runId,
4043
5003
  deps,
@@ -4049,20 +5009,21 @@ var InlineAgentRunner = class _InlineAgentRunner {
4049
5009
  ...input.agentName !== void 0 ? [
4050
5010
  input.agentName
4051
5011
  ] : []
4052
- ]
5012
+ ],
5013
+ input
4053
5014
  });
4054
- void (0, import_nestjs_agent_core26.runAgentLoop)({
5015
+ void (0, import_nestjs_agent_core28.runAgentLoop)({
4055
5016
  ...deps,
4056
5017
  day
4057
- }, input, hooks).then(() => this.store.setActiveStream(input.threadId, null)).catch(async (error) => {
4058
- if (error instanceof import_nestjs_agent_core26.RunCancelledError) {
4059
- await this.settleCancelled(runId, input.threadId, deps);
5018
+ }, input, hooks).then(() => (0, import_nestjs_agent_core28.releaseThreadRun)(this.store, input.threadId, runId)).catch(async (error) => {
5019
+ if (error instanceof import_nestjs_agent_core28.RunCancelledError) {
5020
+ await this.settleCancelled(runId, input, deps);
4060
5021
  return;
4061
5022
  }
4062
5023
  const message = error instanceof Error ? error.message : String(error);
4063
- const code = (0, import_nestjs_agent_core26.agentFailureCode)(error);
5024
+ const code = (0, import_nestjs_agent_core28.agentFailureCode)(error);
4064
5025
  this.logger.error(`agent run ${runId} failed (${code}): ${message}`);
4065
- (0, import_nestjs_agent_core26.publishAgentRunFailed)({
5026
+ (0, import_nestjs_agent_core28.publishAgentRunFailed)({
4066
5027
  runId,
4067
5028
  code,
4068
5029
  message
@@ -4073,13 +5034,17 @@ var InlineAgentRunner = class _InlineAgentRunner {
4073
5034
  errorCode: code,
4074
5035
  errorMessage: message
4075
5036
  });
4076
- await this.store.setActiveStream(input.threadId, null);
4077
5037
  const writer = await deps.sink.open(runId);
5038
+ await this.settleQueue(writer, input, runId, "failed", message);
5039
+ await (0, import_nestjs_agent_core28.releaseThreadRun)(this.store, input.threadId, runId);
4078
5040
  await writer.fail({
4079
5041
  code,
4080
5042
  message
4081
5043
  });
4082
- }).finally(() => this.cancelled.delete(runId));
5044
+ }).finally(() => {
5045
+ this.cancelled.delete(runId);
5046
+ this.live.delete(runId);
5047
+ });
4083
5048
  return {
4084
5049
  runId
4085
5050
  };
@@ -4111,7 +5076,7 @@ var InlineAgentRunner = class _InlineAgentRunner {
4111
5076
  for (const [key, waiter] of this.pending) {
4112
5077
  if (key.startsWith(`${runId}:`)) {
4113
5078
  this.pending.delete(key);
4114
- waiter.reject(new import_nestjs_agent_core26.RunCancelledError());
5079
+ waiter.reject(new import_nestjs_agent_core28.RunCancelledError());
4115
5080
  }
4116
5081
  }
4117
5082
  await Promise.resolve();
@@ -4122,11 +5087,12 @@ var InlineAgentRunner = class _InlineAgentRunner {
4122
5087
  * the stream ENDED after a `cancelled` frame rather than failed, so a client that retries failed
4123
5088
  * streams does not retry this one.
4124
5089
  */
4125
- async settleCancelled(runId, threadId, deps) {
5090
+ async settleCancelled(runId, input, deps) {
4126
5091
  this.logger.log(`agent run ${runId} cancelled`);
4127
- await this.store.setActiveStream(threadId, null);
4128
5092
  const writer = await deps.sink.open(runId);
4129
- await writer.write((0, import_nestjs_agent_core26.encodeStreamEvent)({
5093
+ await this.settleQueue(writer, input, runId, "cancelled");
5094
+ await (0, import_nestjs_agent_core28.releaseThreadRun)(this.store, input.threadId, runId);
5095
+ await writer.write((0, import_nestjs_agent_core28.encodeStreamEvent)({
4130
5096
  kind: "cancelled"
4131
5097
  }));
4132
5098
  await writer.end();
@@ -4136,6 +5102,38 @@ var InlineAgentRunner = class _InlineAgentRunner {
4136
5102
  });
4137
5103
  }
4138
5104
  /**
5105
+ * Move the thread past a settling TOP-LEVEL run — to the next queued message, which starts here,
5106
+ * or to a paused/empty queue — and write the resulting `queue` frame into this run's stream. A
5107
+ * no-op without a queue-capable store, and for a run that is not a thread's own turn.
5108
+ *
5109
+ * Never throws: the run is settling either way, and a queue that could not be advanced is picked
5110
+ * up by the next send or resume on the thread.
5111
+ */
5112
+ async settleQueue(writer, input, runId, outcome, error) {
5113
+ const queue = this.queue;
5114
+ if (queue === void 0 || !queue.supported || !isThreadTurn2(input)) {
5115
+ return;
5116
+ }
5117
+ const settled = outcome === "completed" && this.cancelled.has(runId) ? "cancelled" : outcome;
5118
+ try {
5119
+ const frame = await queue.handoff({
5120
+ threadId: input.threadId,
5121
+ runId,
5122
+ outcome: settled,
5123
+ ...error !== void 0 ? {
5124
+ error
5125
+ } : {}
5126
+ }, (next, nextRunId) => this.start(next, {
5127
+ runId: nextRunId
5128
+ }));
5129
+ if (frame !== void 0) {
5130
+ await writer.write((0, import_nestjs_agent_core28.encodeStreamEvent)(frame));
5131
+ }
5132
+ } catch (failure) {
5133
+ this.logger.error(`could not advance the queue of thread ${input.threadId} after run ${runId}: ${failure instanceof Error ? failure.message : String(failure)}`);
5134
+ }
5135
+ }
5136
+ /**
4139
5137
  * Park a run on a human, keyed by run + tool call. One map for approvals and for question-set
4140
5138
  * answers alike: both wait on the same key, and `signal` cannot tell (or need to tell) which
4141
5139
  * shape it is delivering — the loop asked for one and only ever gets what the caller sent. A
@@ -4180,14 +5178,27 @@ var InlineAgentRunner = class _InlineAgentRunner {
4180
5178
  });
4181
5179
  }
4182
5180
  topLevelHooks(args) {
4183
- const { runId, deps, actor, day, threadId, chainBelow } = args;
5181
+ const { runId, deps, actor, day, threadId, chainBelow, input } = args;
4184
5182
  return {
4185
5183
  runId,
4186
- openSink: /* @__PURE__ */ __name(() => deps.sink.open(runId), "openSink"),
5184
+ // The loop ends the stream when the turn completes. Just before, the thread passes to the next
5185
+ // queued message (or is released), and the reader is told which — so by the time a client
5186
+ // sees the run end, the thread is already free or already running what it queued.
5187
+ openSink: /* @__PURE__ */ __name(async () => {
5188
+ const writer = await deps.sink.open(runId);
5189
+ return this.queue === void 0 ? writer : {
5190
+ write: /* @__PURE__ */ __name((chunk) => writer.write(chunk), "write"),
5191
+ fail: /* @__PURE__ */ __name((error) => writer.fail(error), "fail"),
5192
+ end: /* @__PURE__ */ __name(async () => {
5193
+ await this.settleQueue(writer, input, runId, "completed");
5194
+ await writer.end();
5195
+ }, "end")
5196
+ };
5197
+ }, "openSink"),
4187
5198
  awaitApproval: /* @__PURE__ */ __name((call, _ctx, opts) => this.parkApproval(runId, call.id, opts?.timeoutMs), "awaitApproval"),
4188
5199
  awaitAnswers: /* @__PURE__ */ __name((request) => this.park(runId, request.id), "awaitAnswers"),
4189
5200
  step: /* @__PURE__ */ __name((_name, fn) => fn(), "step"),
4190
- parallel: import_nestjs_agent_core26.settleAll,
5201
+ parallel: import_nestjs_agent_core28.settleAll,
4191
5202
  cancelled: /* @__PURE__ */ __name(async () => this.cancelled.has(runId), "cancelled"),
4192
5203
  runAgent: /* @__PURE__ */ __name((agentName, task) => this.runNested({
4193
5204
  agentName,
@@ -4238,7 +5249,7 @@ var InlineAgentRunner = class _InlineAgentRunner {
4238
5249
  awaitApproval: /* @__PURE__ */ __name((call, _ctx, opts) => this.parkApproval(runId, call.id, opts?.timeoutMs), "awaitApproval"),
4239
5250
  awaitAnswers: /* @__PURE__ */ __name((request) => this.park(runId, request.id), "awaitAnswers"),
4240
5251
  step: /* @__PURE__ */ __name((_name, fn) => fn(), "step"),
4241
- parallel: import_nestjs_agent_core26.settleAll,
5252
+ parallel: import_nestjs_agent_core28.settleAll,
4242
5253
  cancelled: /* @__PURE__ */ __name(async () => this.cancelled.has(runId), "cancelled"),
4243
5254
  runAgent: /* @__PURE__ */ __name((childName, childTask) => this.runNested({
4244
5255
  agentName: childName,
@@ -4271,7 +5282,7 @@ var InlineAgentRunner = class _InlineAgentRunner {
4271
5282
  }
4272
5283
  }), "startAgent")
4273
5284
  };
4274
- void (0, import_nestjs_agent_core26.runAgentLoop)({
5285
+ void (0, import_nestjs_agent_core28.runAgentLoop)({
4275
5286
  ...deps,
4276
5287
  day
4277
5288
  }, {
@@ -4285,13 +5296,13 @@ var InlineAgentRunner = class _InlineAgentRunner {
4285
5296
  parentRunId,
4286
5297
  deliverTo
4287
5298
  }, hooks).catch(async (error) => {
4288
- const cancelled = error instanceof import_nestjs_agent_core26.RunCancelledError;
5299
+ const cancelled = error instanceof import_nestjs_agent_core28.RunCancelledError;
4289
5300
  const message = error instanceof Error ? error.message : String(error);
4290
5301
  if (!cancelled) {
4291
5302
  this.logger.error(`detached agent run ${runId} failed: ${message}`);
4292
- (0, import_nestjs_agent_core26.publishAgentRunFailed)({
5303
+ (0, import_nestjs_agent_core28.publishAgentRunFailed)({
4293
5304
  runId,
4294
- code: (0, import_nestjs_agent_core26.agentFailureCode)(error),
5305
+ code: (0, import_nestjs_agent_core28.agentFailureCode)(error),
4295
5306
  message
4296
5307
  });
4297
5308
  }
@@ -4299,11 +5310,11 @@ var InlineAgentRunner = class _InlineAgentRunner {
4299
5310
  runId,
4300
5311
  status: cancelled ? "cancelled" : "failed",
4301
5312
  ...cancelled ? {} : {
4302
- errorCode: (0, import_nestjs_agent_core26.agentFailureCode)(error),
5313
+ errorCode: (0, import_nestjs_agent_core28.agentFailureCode)(error),
4303
5314
  errorMessage: message
4304
5315
  }
4305
5316
  });
4306
- await (0, import_nestjs_agent_core26.settleUnsettledDelegation)({
5317
+ await (0, import_nestjs_agent_core28.settleUnsettledDelegation)({
4307
5318
  store: this.store,
4308
5319
  delivery: deliverTo,
4309
5320
  agent: agentName,
@@ -4342,7 +5353,7 @@ var InlineAgentRunner = class _InlineAgentRunner {
4342
5353
  awaitApproval: /* @__PURE__ */ __name((call, _ctx, opts) => this.parkApproval(runId, call.id, opts?.timeoutMs), "awaitApproval"),
4343
5354
  awaitAnswers: /* @__PURE__ */ __name((request) => this.park(runId, request.id), "awaitAnswers"),
4344
5355
  step: /* @__PURE__ */ __name((_name, fn) => fn(), "step"),
4345
- parallel: import_nestjs_agent_core26.settleAll,
5356
+ parallel: import_nestjs_agent_core28.settleAll,
4346
5357
  // A child stops when it is cancelled OR when the run a human is actually watching is: the
4347
5358
  // canceller names the top-level run, which is the only id that ever left the server.
4348
5359
  cancelled: /* @__PURE__ */ __name(async () => this.cancelled.has(runId) || this.cancelled.has(sinkRunId), "cancelled"),
@@ -4377,7 +5388,7 @@ var InlineAgentRunner = class _InlineAgentRunner {
4377
5388
  }), "startAgent")
4378
5389
  };
4379
5390
  try {
4380
- return await (0, import_nestjs_agent_core26.runAgentLoop)({
5391
+ return await (0, import_nestjs_agent_core28.runAgentLoop)({
4381
5392
  ...deps,
4382
5393
  day
4383
5394
  }, {
@@ -4396,19 +5407,25 @@ var InlineAgentRunner = class _InlineAgentRunner {
4396
5407
  }
4397
5408
  }
4398
5409
  };
4399
- InlineAgentRunner = _ts_decorate23([
4400
- (0, import_common23.Injectable)(),
4401
- _ts_param21(0, (0, import_common23.Inject)(import_nestjs_agent_core26.AGENT_DEPS_FACTORY)),
4402
- _ts_param21(1, (0, import_common23.Inject)(import_nestjs_agent_core26.AGENT_STORE)),
4403
- _ts_metadata22("design:type", Function),
4404
- _ts_metadata22("design:paramtypes", [
5410
+ InlineAgentRunner = _ts_decorate25([
5411
+ (0, import_common25.Injectable)(),
5412
+ _ts_param23(0, (0, import_common25.Inject)(import_nestjs_agent_core28.AGENT_DEPS_FACTORY)),
5413
+ _ts_param23(1, (0, import_common25.Inject)(import_nestjs_agent_core28.AGENT_STORE)),
5414
+ _ts_param23(2, (0, import_common25.Optional)()),
5415
+ _ts_metadata24("design:type", Function),
5416
+ _ts_metadata24("design:paramtypes", [
4405
5417
  typeof AgentDepsFactory === "undefined" ? Object : AgentDepsFactory,
4406
- typeof AgentStore === "undefined" ? Object : AgentStore
5418
+ typeof AgentStore === "undefined" ? Object : AgentStore,
5419
+ typeof ChatQueueService === "undefined" ? Object : ChatQueueService
4407
5420
  ])
4408
5421
  ], InlineAgentRunner);
5422
+ function isThreadTurn2(input) {
5423
+ return input.sinkRunId === void 0 && input.deliverTo === void 0;
5424
+ }
5425
+ __name(isThreadTurn2, "isThreadTurn");
4409
5426
 
4410
5427
  // src/skills-config.ts
4411
- var import_nestjs_agent_core27 = require("@dudousxd/nestjs-agent-core");
5428
+ var import_nestjs_agent_core29 = require("@dudousxd/nestjs-agent-core");
4412
5429
  function declaredSkillProvider(declared) {
4413
5430
  return {
4414
5431
  list: /* @__PURE__ */ __name(({ scopes }) => declared.filter((skill) => scopes.includes(skill.scope)).map(({ name, description, scope }) => ({
@@ -4434,7 +5451,7 @@ function resolveSkillsConfig(options, declared) {
4434
5451
  declaredSkillProvider(declared)
4435
5452
  ];
4436
5453
  return {
4437
- provider: providers.length === 1 ? providers[0] : (0, import_nestjs_agent_core27.compositeSkillProvider)(providers),
5454
+ provider: providers.length === 1 ? providers[0] : (0, import_nestjs_agent_core29.compositeSkillProvider)(providers),
4438
5455
  ...options.scopes !== void 0 ? {
4439
5456
  scopes: options.scopes
4440
5457
  } : {},
@@ -4446,7 +5463,7 @@ function resolveSkillsConfig(options, declared) {
4446
5463
  __name(resolveSkillsConfig, "resolveSkillsConfig");
4447
5464
 
4448
5465
  // src/agent.module.ts
4449
- function _ts_decorate24(decorators, target, key, desc) {
5466
+ function _ts_decorate26(decorators, target, key, desc) {
4450
5467
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4451
5468
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
4452
5469
  r = Reflect.decorate(decorators, target, key, desc);
@@ -4459,13 +5476,13 @@ function _ts_decorate24(decorators, target, key, desc) {
4459
5476
  }
4460
5477
  return c > 3 && r && Object.defineProperty(target, key, r), r;
4461
5478
  }
4462
- __name(_ts_decorate24, "_ts_decorate");
5479
+ __name(_ts_decorate26, "_ts_decorate");
4463
5480
  var DEFAULT_PATH = "agent";
4464
- var logger = new import_common24.Logger("AgentModule");
5481
+ var logger = new import_common26.Logger("AgentModule");
4465
5482
  function externalStoreWrapper(modules) {
4466
5483
  for (const module2 of modules.values()) {
4467
5484
  if (module2.metatype === AgentModule) continue;
4468
- const wrapper = module2.providers.get(import_nestjs_agent_core28.AGENT_STORE);
5485
+ const wrapper = module2.providers.get(import_nestjs_agent_core30.AGENT_STORE);
4469
5486
  if (wrapper !== void 0) return wrapper;
4470
5487
  }
4471
5488
  return void 0;
@@ -4496,7 +5513,7 @@ function resolveStore(options, modules) {
4496
5513
  const external = externalStoreWrapper(modules);
4497
5514
  if (external !== void 0) return forwardingStore(external);
4498
5515
  logger.warn("No `store` configured and no store module imported \u2014 using the in-memory store. Threads are lost on restart and not shared between processes: not for production. Pass `store`, or import a store module (e.g. MikroOrmAgentStoreModule.forFeature()).");
4499
- return new import_nestjs_agent_core28.InMemoryAgentStore();
5516
+ return new import_nestjs_agent_core30.InMemoryAgentStore();
4500
5517
  }
4501
5518
  __name(resolveStore, "resolveStore");
4502
5519
  function isQuotaProvider(quota) {
@@ -4512,99 +5529,99 @@ __name(resolveCatalog, "resolveCatalog");
4512
5529
  function sharedProviders(durable) {
4513
5530
  const providers = [
4514
5531
  {
4515
- provide: import_nestjs_agent_core28.AGENT_TOOL_REGISTRY,
4516
- useFactory: /* @__PURE__ */ __name(() => new import_nestjs_agent_core28.ToolRegistry(), "useFactory")
5532
+ provide: import_nestjs_agent_core30.AGENT_TOOL_REGISTRY,
5533
+ useFactory: /* @__PURE__ */ __name(() => new import_nestjs_agent_core30.ToolRegistry(), "useFactory")
4517
5534
  },
4518
5535
  // Starts empty; AgentDiscoveryService populates it from `@Agent`-decorated providers at boot.
4519
5536
  {
4520
- provide: import_nestjs_agent_core28.AGENT_REGISTRY,
4521
- useFactory: /* @__PURE__ */ __name(() => new import_nestjs_agent_core28.AgentRegistry(), "useFactory")
5537
+ provide: import_nestjs_agent_core30.AGENT_REGISTRY,
5538
+ useFactory: /* @__PURE__ */ __name(() => new import_nestjs_agent_core30.AgentRegistry(), "useFactory")
4522
5539
  },
4523
5540
  // A shared, mutable list AgentDiscoveryService fills with `@SystemPromptContributor()` methods.
4524
5541
  {
4525
- provide: import_nestjs_agent_core28.AGENT_PROMPT_CONTRIBUTORS,
5542
+ provide: import_nestjs_agent_core30.AGENT_PROMPT_CONTRIBUTORS,
4526
5543
  useFactory: /* @__PURE__ */ __name(() => [], "useFactory")
4527
5544
  },
4528
5545
  // Likewise for `@Skill`-decorated providers — filled by SkillDiscoveryService at onModuleInit,
4529
5546
  // read lazily by the AGENT_SKILLS provider below (which DI builds before discovery has run).
4530
5547
  {
4531
- provide: import_nestjs_agent_core28.AGENT_SKILL_SOURCES,
5548
+ provide: import_nestjs_agent_core30.AGENT_SKILL_SOURCES,
4532
5549
  useFactory: /* @__PURE__ */ __name(() => [], "useFactory")
4533
5550
  },
4534
5551
  {
4535
5552
  // One resolution, shared by the loop's deps and the listing endpoint: a second one would
4536
5553
  // drift, and a user would be offered a skill the agent cannot reach. `undefined` when the
4537
5554
  // host configured none — which is what keeps the turn's checkpoint sequence unchanged.
4538
- provide: import_nestjs_agent_core28.AGENT_SKILLS,
5555
+ provide: import_nestjs_agent_core30.AGENT_SKILLS,
4539
5556
  useFactory: /* @__PURE__ */ __name((options, declared) => resolveSkillsConfig(options.skills, declared), "useFactory"),
4540
5557
  inject: [
4541
- import_nestjs_agent_core28.AGENT_OPTIONS,
4542
- import_nestjs_agent_core28.AGENT_SKILL_SOURCES
5558
+ import_nestjs_agent_core30.AGENT_OPTIONS,
5559
+ import_nestjs_agent_core30.AGENT_SKILL_SOURCES
4543
5560
  ]
4544
5561
  },
4545
5562
  {
4546
5563
  // One resolution, shared by the loop's deps and the read-back endpoint: a person has to be
4547
5564
  // shown what the model was shown, and two resolutions would eventually disagree about that.
4548
- provide: import_nestjs_agent_core28.AGENT_MEMORY,
5565
+ provide: import_nestjs_agent_core30.AGENT_MEMORY,
4549
5566
  useFactory: /* @__PURE__ */ __name((options) => options.memory, "useFactory"),
4550
5567
  inject: [
4551
- import_nestjs_agent_core28.AGENT_OPTIONS
5568
+ import_nestjs_agent_core30.AGENT_OPTIONS
4552
5569
  ]
4553
5570
  },
4554
5571
  {
4555
- provide: import_nestjs_agent_core28.AGENT_SINK,
5572
+ provide: import_nestjs_agent_core30.AGENT_SINK,
4556
5573
  useFactory: /* @__PURE__ */ __name((options) => options.sink ?? new InProcessTokenStreamSink(), "useFactory"),
4557
5574
  inject: [
4558
- import_nestjs_agent_core28.AGENT_OPTIONS
5575
+ import_nestjs_agent_core30.AGENT_OPTIONS
4559
5576
  ]
4560
5577
  },
4561
5578
  {
4562
- provide: import_nestjs_agent_core28.AGENT_ROLES_POLICY,
4563
- useFactory: /* @__PURE__ */ __name((options) => options.rolesPolicy ?? new import_nestjs_agent_core28.DefaultRolesPolicy(options.defaultRoles), "useFactory"),
5579
+ provide: import_nestjs_agent_core30.AGENT_ROLES_POLICY,
5580
+ useFactory: /* @__PURE__ */ __name((options) => options.rolesPolicy ?? new import_nestjs_agent_core30.DefaultRolesPolicy(options.defaultRoles), "useFactory"),
4564
5581
  inject: [
4565
- import_nestjs_agent_core28.AGENT_OPTIONS
5582
+ import_nestjs_agent_core30.AGENT_OPTIONS
4566
5583
  ]
4567
5584
  },
4568
5585
  {
4569
- provide: import_nestjs_agent_core28.AGENT_ACTOR_RESOLVER,
5586
+ provide: import_nestjs_agent_core30.AGENT_ACTOR_RESOLVER,
4570
5587
  useFactory: /* @__PURE__ */ __name((options) => {
4571
5588
  if (options.actorResolver !== void 0) return options.actorResolver;
4572
5589
  logger.warn("No `actorResolver` configured \u2014 the agent endpoints are PUBLIC: every browser gets its own anonymous identity (an HttpOnly cookie). Set `actorResolver: requestUserActorResolver()` (or your own) to require login.");
4573
5590
  return new AnonymousActorResolver();
4574
5591
  }, "useFactory"),
4575
5592
  inject: [
4576
- import_nestjs_agent_core28.AGENT_OPTIONS
5593
+ import_nestjs_agent_core30.AGENT_OPTIONS
4577
5594
  ]
4578
5595
  },
4579
5596
  {
4580
- provide: import_nestjs_agent_core28.AGENT_MODEL,
5597
+ provide: import_nestjs_agent_core30.AGENT_MODEL,
4581
5598
  useFactory: /* @__PURE__ */ __name((o) => o.model, "useFactory"),
4582
5599
  inject: [
4583
- import_nestjs_agent_core28.AGENT_OPTIONS
5600
+ import_nestjs_agent_core30.AGENT_OPTIONS
4584
5601
  ]
4585
5602
  },
4586
5603
  {
4587
5604
  // `quota` is either a provider of the host's own or ceilings for the built-in ledger one;
4588
5605
  // omitted, the ledger provider still reports usage, with no ceiling to block on.
4589
- provide: import_nestjs_agent_core28.AGENT_QUOTA_PROVIDER,
5606
+ provide: import_nestjs_agent_core30.AGENT_QUOTA_PROVIDER,
4590
5607
  useFactory: /* @__PURE__ */ __name((o, store) => isQuotaProvider(o.quota) ? o.quota : new LedgerQuotaProvider(store, o.quota?.limits, o.quota?.warnAt !== void 0 ? {
4591
5608
  warnAt: o.quota.warnAt
4592
5609
  } : {}), "useFactory"),
4593
5610
  inject: [
4594
- import_nestjs_agent_core28.AGENT_OPTIONS,
4595
- import_nestjs_agent_core28.AGENT_STORE
5611
+ import_nestjs_agent_core30.AGENT_OPTIONS,
5612
+ import_nestjs_agent_core30.AGENT_STORE
4596
5613
  ]
4597
5614
  },
4598
5615
  {
4599
- provide: import_nestjs_agent_core28.AGENT_MODEL_CATALOG,
5616
+ provide: import_nestjs_agent_core30.AGENT_MODEL_CATALOG,
4600
5617
  useFactory: /* @__PURE__ */ __name((o) => resolveCatalog(o), "useFactory"),
4601
5618
  inject: [
4602
- import_nestjs_agent_core28.AGENT_OPTIONS
5619
+ import_nestjs_agent_core30.AGENT_OPTIONS
4603
5620
  ]
4604
5621
  },
4605
5622
  AgentDepsFactory2,
4606
5623
  {
4607
- provide: import_nestjs_agent_core28.AGENT_DEPS_FACTORY,
5624
+ provide: import_nestjs_agent_core30.AGENT_DEPS_FACTORY,
4608
5625
  useExisting: AgentDepsFactory2
4609
5626
  },
4610
5627
  // Populates the registry + contributors (onModuleInit) BEFORE AiToolDiscoveryService synthesizes
@@ -4612,27 +5629,30 @@ function sharedProviders(durable) {
4612
5629
  AgentDiscoveryService,
4613
5630
  AiToolDiscoveryService,
4614
5631
  SkillDiscoveryService,
5632
+ // The thread message queue — every surface, since both runners and the durable workflow settle
5633
+ // into it, and the chat routes enqueue into it.
5634
+ ChatQueueService,
4615
5635
  InlineAgentRunner,
4616
5636
  AgentService,
4617
5637
  // Bound ALWAYS (durable or inline) — the console's cross-thread approvals inbox routes decisions
4618
5638
  // through AgentService.signalToolCall, which reaches whichever AGENT_RUNNER is bound above.
4619
5639
  AgentApprovalPortAdapter,
4620
5640
  {
4621
- provide: import_nestjs_agent_core28.AGENT_APPROVAL_PORT,
5641
+ provide: import_nestjs_agent_core30.AGENT_APPROVAL_PORT,
4622
5642
  useExisting: AgentApprovalPortAdapter
4623
5643
  }
4624
5644
  ];
4625
5645
  providers.push({
4626
- provide: import_nestjs_agent_core28.AGENT_STORE,
5646
+ provide: import_nestjs_agent_core30.AGENT_STORE,
4627
5647
  useFactory: /* @__PURE__ */ __name((o, modules) => resolveStore(o, modules), "useFactory"),
4628
5648
  inject: [
4629
- import_nestjs_agent_core28.AGENT_OPTIONS,
5649
+ import_nestjs_agent_core30.AGENT_OPTIONS,
4630
5650
  import_core4.ModulesContainer
4631
5651
  ]
4632
5652
  });
4633
5653
  if (durable) {
4634
5654
  providers.push({
4635
- provide: import_nestjs_agent_core28.AGENT_RUNNER,
5655
+ provide: import_nestjs_agent_core30.AGENT_RUNNER,
4636
5656
  useFactory: /* @__PURE__ */ __name((durableRunner) => {
4637
5657
  if (durableRunner === void 0) {
4638
5658
  throw new Error("AgentModule.forRoot({ durable: true }) requires importing AgentDurableModule from '@dudousxd/nestjs-agent/durable' (alongside a configured DurableModule). It was not found.");
@@ -4641,14 +5661,14 @@ function sharedProviders(durable) {
4641
5661
  }, "useFactory"),
4642
5662
  inject: [
4643
5663
  {
4644
- token: import_nestjs_agent_core28.AGENT_DURABLE_RUNNER,
5664
+ token: import_nestjs_agent_core30.AGENT_DURABLE_RUNNER,
4645
5665
  optional: true
4646
5666
  }
4647
5667
  ]
4648
5668
  });
4649
5669
  } else {
4650
5670
  providers.push({
4651
- provide: import_nestjs_agent_core28.AGENT_RUNNER,
5671
+ provide: import_nestjs_agent_core30.AGENT_RUNNER,
4652
5672
  useExisting: InlineAgentRunner
4653
5673
  });
4654
5674
  }
@@ -4657,29 +5677,31 @@ function sharedProviders(durable) {
4657
5677
  __name(sharedProviders, "sharedProviders");
4658
5678
  function exportsFor() {
4659
5679
  return [
4660
- import_nestjs_agent_core28.AGENT_OPTIONS,
4661
- import_nestjs_agent_core28.AGENT_TOOL_REGISTRY,
4662
- import_nestjs_agent_core28.AGENT_REGISTRY,
4663
- import_nestjs_agent_core28.AGENT_SINK,
4664
- import_nestjs_agent_core28.AGENT_ROLES_POLICY,
4665
- import_nestjs_agent_core28.AGENT_ACTOR_RESOLVER,
4666
- import_nestjs_agent_core28.AGENT_MODEL,
4667
- import_nestjs_agent_core28.AGENT_STORE,
4668
- import_nestjs_agent_core28.AGENT_MODEL_CATALOG,
4669
- import_nestjs_agent_core28.AGENT_QUOTA_PROVIDER,
4670
- import_nestjs_agent_core28.AGENT_PROMPT_CONTRIBUTORS,
4671
- import_nestjs_agent_core28.AGENT_SKILLS,
4672
- import_nestjs_agent_core28.AGENT_MEMORY,
4673
- import_nestjs_agent_core28.AGENT_DEPS_FACTORY,
5680
+ import_nestjs_agent_core30.AGENT_OPTIONS,
5681
+ import_nestjs_agent_core30.AGENT_TOOL_REGISTRY,
5682
+ import_nestjs_agent_core30.AGENT_REGISTRY,
5683
+ import_nestjs_agent_core30.AGENT_SINK,
5684
+ import_nestjs_agent_core30.AGENT_ROLES_POLICY,
5685
+ import_nestjs_agent_core30.AGENT_ACTOR_RESOLVER,
5686
+ import_nestjs_agent_core30.AGENT_MODEL,
5687
+ import_nestjs_agent_core30.AGENT_STORE,
5688
+ import_nestjs_agent_core30.AGENT_MODEL_CATALOG,
5689
+ import_nestjs_agent_core30.AGENT_QUOTA_PROVIDER,
5690
+ import_nestjs_agent_core30.AGENT_PROMPT_CONTRIBUTORS,
5691
+ import_nestjs_agent_core30.AGENT_SKILLS,
5692
+ import_nestjs_agent_core30.AGENT_MEMORY,
5693
+ import_nestjs_agent_core30.AGENT_DEPS_FACTORY,
4674
5694
  AgentDepsFactory2,
4675
5695
  AgentService,
5696
+ ChatQueueService,
4676
5697
  InlineAgentRunner,
4677
- import_nestjs_agent_core28.AGENT_APPROVAL_PORT
5698
+ import_nestjs_agent_core30.AGENT_APPROVAL_PORT
4678
5699
  ];
4679
5700
  }
4680
5701
  __name(exportsFor, "exportsFor");
4681
5702
  var BASE_CONTROLLERS = [
4682
5703
  ChatController,
5704
+ QueueController,
4683
5705
  ThreadsController,
4684
5706
  ToolCallController,
4685
5707
  QuotaController,
@@ -4737,7 +5759,7 @@ var AgentModule = class _AgentModule {
4737
5759
  controllers: controllersForSurface(options.surface),
4738
5760
  providers: [
4739
5761
  {
4740
- provide: import_nestjs_agent_core28.AGENT_OPTIONS,
5762
+ provide: import_nestjs_agent_core30.AGENT_OPTIONS,
4741
5763
  useValue: options
4742
5764
  },
4743
5765
  ...sharedProviders(options.durable ?? false),
@@ -4760,7 +5782,7 @@ var AgentModule = class _AgentModule {
4760
5782
  controllers: controllersForSurface(options.surface),
4761
5783
  providers: [
4762
5784
  {
4763
- provide: import_nestjs_agent_core28.AGENT_OPTIONS,
5785
+ provide: import_nestjs_agent_core30.AGENT_OPTIONS,
4764
5786
  // Stamp the STATIC wiring flags onto the factory result: `durable`/`surface` are
4765
5787
  // authoritative on the async config object (they decided the actual wiring above), and
4766
5788
  // the durable module reads `durable` back off AGENT_OPTIONS. `surface` isn't read back by
@@ -4781,9 +5803,9 @@ var AgentModule = class _AgentModule {
4781
5803
  };
4782
5804
  }
4783
5805
  };
4784
- AgentModule = _ts_decorate24([
4785
- (0, import_common24.Global)(),
4786
- (0, import_common24.Module)({})
5806
+ AgentModule = _ts_decorate26([
5807
+ (0, import_common26.Global)(),
5808
+ (0, import_common26.Module)({})
4787
5809
  ], AgentModule);
4788
5810
 
4789
5811
  // src/durable/agent-durable.ts