@dudousxd/nestjs-agent-core 0.31.0 → 0.32.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.
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
- import { M as ModelMessage, c as ToolDefinition, d as ToolCallRequest, e as MessageUsage, f as AgentUiComponent, A as Actor, g as AiToolCtx, h as AgentStreamEvent, i as ThreadSummary, j as ThreadDetail, S as StoredMessage, k as ToolResult, l as MessageAttachment, m as MessageFeedback, n as ToolCallStatus, U as UsagePurpose, T as ToolSpec, Q as QuotaState, o as AgentRunInput, H as HumanReply, p as ToolKind, q as ToolCallApproval, a as ToolHandler, r as HistoryPolicy, P as PageContext, s as AgentDefinition, t as AgentDelegation, D as DetachedDelivery, u as ToolDescribeScope, v as PromptBuilder, w as PromptContributor, x as ToolTransientRetrySetting, y as AgentIntake, z as Decision, E as ElicitationRequest, L as LlmStepEnvelope, B as ToolStepEnvelope } from './tool-B0J4Fjyd.cjs';
2
- export { C as ALL_AGENTS, F as ASK_TOOL_DESCRIPTION, G as ASK_TOOL_NAME, I as AgentApprovalRequest, J as AgentApprovalSettlement, K as AgentAttachmentConfig, N as AgentCatalogEntry, O as AgentClientConfig, R as AgentHistoryWindow, V as AskToolInput, W as DEFAULT_INTAKE_PREAMBLE, X as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, Y as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, Z as ELICITATION_INPUT_TYPES, _ as ElicitationInput, $ as ElicitationInputType, a0 as ElicitationOption, a1 as ElicitationOutcome, a2 as ElicitationQuestion, a3 as ElicitationReply, a4 as ElicitationResult, a5 as HistoryPolicyContext, a6 as HistorySelection, a7 as HistorySummary, a8 as InvokeWithTransientRetryOptions, a9 as MAX_ASK_QUESTIONS, aa as MessageFeedbackValue, ab as MessageRole, ac as PromptContext, ad as QuotaView, ae as ToolCallApprovalStatus, af as ToolCatalogEntry, ag as ToolConfirmation, ah as ToolDescription, b as ToolPresentation, ai as ToolPresentationTone, aj as ToolResultField, ak as ToolResultView, al as ToolStepCtx, am as ToolTransientRetryNumbers, an as ToolTransientRetryOptions, ao as askInputSchema, ap as askToolDefinition, aq as decodeStreamEvent, ar as encodeStreamEvent, as as invokeWithTransientRetry, at as isTransientToolError, au as isTypedQuestion, av as normalizeElicitationReply, aw as questionOptions, ax as readElicitationInput, ay as readElicitationQuestions, az as renderElicitationAnswers, aA as resolveElicitation, aB as resolveToolTransientRetryNumbers, aC as settleElicitation, aD as validateElicitationAnswer, aE as validateElicitationValue } from './tool-B0J4Fjyd.cjs';
1
+ import { M as ModelMessage, c as ToolDefinition, d as ToolCallRequest, e as MessageUsage, f as AgentUiComponent, A as Actor, g as AiToolCtx, h as AgentStreamEvent, T as ToolSpec, Q as QuotaState, i as AgentRunInput, H as HumanReply, j as MessageAttachment, k as ToolKind, l as ToolCallStatus, m as ToolCallApproval, a as ToolHandler, n as HistoryPolicy, P as PageContext, o as AgentDefinition, p as AgentDelegation, q as AgentStore, D as DetachedDelivery, r as ToolDescribeScope, s as PromptBuilder, t as PromptContributor, u as ToolTransientRetrySetting, v as AgentIntake, w as Decision, E as ElicitationRequest, L as LlmStepEnvelope, x as ToolStepEnvelope, C as ChatQueueStore, y as CreateThreadInput, z as ThreadSummary, B as ThreadDetail, F as ToolCallApprovalState, U as UpdateThreadInput, R as RecordRunStartInput, G as EnqueueMessageInput, I as QueuedMessage, J as QueuedMessagePatch, K as QueuePause, N as AppendMessageInput, S as StoredMessage, O as ToolResult, V as MessageFeedback, W as RecordToolCallInput, X as UpdateToolCallInput, Y as RecordUsageInput } from './tool-BhhzEI40.cjs';
2
+ export { Z as ALL_AGENTS, _ as ASK_TOOL_DESCRIPTION, $ as ASK_TOOL_NAME, a0 as AgentApprovalRequest, a1 as AgentApprovalSettlement, a2 as AgentAttachmentConfig, a3 as AgentCatalogEntry, a4 as AgentClientConfig, a5 as AgentHistoryWindow, a6 as AskToolInput, a7 as ChatQueueState, a8 as DEFAULT_INTAKE_PREAMBLE, a9 as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, aa as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, ab as ELICITATION_INPUT_TYPES, ac as ElicitationInput, ad as ElicitationInputType, ae as ElicitationOption, af as ElicitationOutcome, ag as ElicitationQuestion, ah as ElicitationReply, ai as ElicitationResult, aj as HistoryPolicyContext, ak as HistorySelection, al as HistorySummary, am as InvokeWithTransientRetryOptions, an as MAX_ASK_QUESTIONS, ao as MessageFeedbackValue, ap as MessageRole, aq as PromptContext, ar as QueuePauseReason, as as QueuedMessageView, at as QuotaView, au as RecordRunEndInput, av as ThreadTurnPage, aw as ThreadTurnQuery, ax as ThreadTurnReader, ay as ToolCallApprovalStatus, az as ToolCatalogEntry, aA as ToolConfirmation, aB as ToolDescription, b as ToolPresentation, aC as ToolPresentationTone, aD as ToolResultField, aE as ToolResultView, aF as ToolStepCtx, aG as ToolTransientRetryNumbers, aH as ToolTransientRetryOptions, aI as UsagePurpose, aJ as askInputSchema, aK as askToolDefinition, aL as decodeStreamEvent, aM as encodeStreamEvent, aN as invokeWithTransientRetry, aO as isChatQueueStore, aP as isTransientToolError, aQ as isTypedQuestion, aR as normalizeElicitationReply, aS as questionOptions, aT as queuedMessageView, aU as readElicitationInput, aV as readElicitationQuestions, aW as releaseThreadRun, aX as renderElicitationAnswers, aY as resolveElicitation, aZ as resolveToolTransientRetryNumbers, a_ as settleElicitation, a$ as validateElicitationAnswer, b0 as validateElicitationValue } from './tool-BhhzEI40.cjs';
3
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
4
- import { O as OutputProcessor, P as ProcessorContext, I as InputProcessor, a as ProcessedPrompt, M as ModelAnswer } from './processors-DdnRmmlq.cjs';
5
- export { D as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, b as IncrementalGating, c as OutputRejectedError, d as OutputVerdict, e as ProcessorFailedError } from './processors-DdnRmmlq.cjs';
4
+ import { O as OutputProcessor, P as ProcessorContext, I as InputProcessor, a as ProcessedPrompt, M as ModelAnswer } from './processors-DQJ5sWw7.cjs';
5
+ export { D as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, b as IncrementalGating, c as OutputRejectedError, d as OutputVerdict, e as ProcessorFailedError } from './processors-DQJ5sWw7.cjs';
6
6
  import { ChannelRegistry } from '@dudousxd/nestjs-diagnostics';
7
7
 
8
8
  /**
@@ -352,332 +352,6 @@ declare function createUiCollector(toolCallId: string, write?: (event: AgentStre
352
352
  /** Merge component lists: first-seen order, the last props for each id. */
353
353
  declare function mergeUi(...lists: readonly (readonly AgentUiComponent[] | undefined)[]): AgentUiComponent[];
354
354
 
355
- interface CreateThreadInput {
356
- actor: Actor;
357
- transient?: boolean;
358
- title?: string;
359
- }
360
- interface AppendMessageInput {
361
- threadId: string;
362
- role: StoredMessage['role'];
363
- content: string;
364
- /** Which agent produced this message (assistant messages) — provenance. */
365
- agentName?: string;
366
- toolCalls?: ToolCallRequest[];
367
- toolResults?: ToolResult[];
368
- /** Files the user attached to this message (image/PDF). Persisted verbatim. */
369
- attachments?: MessageAttachment[];
370
- followUps?: string[];
371
- usage?: MessageUsage;
372
- /**
373
- * The run (turn) that produced this message. Without it a consumer can only guess which turn a
374
- * message belongs to by comparing timestamps against the run's `startedAt`, and that guess breaks
375
- * the moment a turn is regenerated — the replaced answer is truncated away, so the times no longer
376
- * line up 1:1. Optional so a caller predating this (and a host that appends messages outside a
377
- * run) can omit it; the store persists it as `null` when absent.
378
- */
379
- runId?: string;
380
- /** The step's streamed thinking. See {@link StoredMessage.reasoning}. */
381
- reasoning?: string;
382
- /** Time spent thinking in this step, in ms. See {@link StoredMessage.reasoningMs}. */
383
- reasoningMs?: number;
384
- /** Components pushed during this step. See {@link StoredMessage.ui}. */
385
- ui?: AgentUiComponent[];
386
- }
387
- interface RecordToolCallInput {
388
- toolCallId: string;
389
- messageId: string;
390
- toolName: string;
391
- toolType: 'read' | 'action';
392
- input: unknown;
393
- status: ToolCallStatus;
394
- /**
395
- * The run (turn) this tool call belongs to — enables a governance surface to deep-link a tool
396
- * call out to its trace waterfall. Optional so a caller predating this (or a store's own
397
- * synthetic tool calls) can omit it; the store persists it as `null` when absent.
398
- */
399
- runId?: string;
400
- /**
401
- * Who has to approve this call (`'requester'` or a role), from the turn's `ApprovalPolicy`. Set on
402
- * an action call that was put to a person — or approved by a remembered decision — and never
403
- * otherwise; persisted as `null` when absent.
404
- */
405
- approver?: string;
406
- /** ISO-8601 instant the approval request lapses. Absent → it never does. */
407
- expiresAt?: string;
408
- }
409
- interface UpdateToolCallInput {
410
- toolCallId: string;
411
- status: ToolCallStatus;
412
- output?: unknown;
413
- error?: string;
414
- executionMs?: number;
415
- executedByRef?: string;
416
- /** The approval asked for later calls of this tool in this thread to run without asking. */
417
- remember?: boolean;
418
- /** The surface the decision came through. See {@link import('../types.js').Decision.decidedVia}. */
419
- decidedVia?: string;
420
- }
421
- /** What the approve/reject routes need to know about a call before they signal a decision on it. */
422
- interface ToolCallApprovalState {
423
- status: ToolCallStatus;
424
- /** `null` for a call no policy put to anyone (an `ask`, or a row written before approvers existed). */
425
- approver: string | null;
426
- expiresAt: string | null;
427
- }
428
- /** Patch applied by {@link AgentStore.updateThread}. An omitted key leaves that field untouched. */
429
- interface UpdateThreadInput {
430
- title?: string;
431
- /** `null` clears the thread's default agent (falls back to the module default). */
432
- defaultAgent?: string | null;
433
- /** `null` unpins the thread's model (turns run on the provider default). */
434
- model?: string | null;
435
- }
436
- interface RecordUsageInput {
437
- threadId: string;
438
- actorRef: string;
439
- messageId?: string;
440
- modelId: string;
441
- purpose: UsagePurpose;
442
- usage: MessageUsage;
443
- /** Provider-reported actual USD cost for this turn, when known (gateways report it). */
444
- costUsd?: number;
445
- }
446
- interface RecordRunStartInput {
447
- runId: string;
448
- threadId: string;
449
- actorRef: string;
450
- agentName?: string;
451
- /**
452
- * The run that started this one, for a delegation's child run. The parent->child edge exists in
453
- * the durable runtime's own journal, but only there: a governance surface reading run rows alone
454
- * cannot roll a delegation's cost up to the turn that asked for it, and a DETACHED child outlives
455
- * its parent's turn entirely, so nothing in the transcript pairs them either.
456
- *
457
- * Optional, and a store that persists nothing for it still works — it loses the tree, not the run.
458
- */
459
- parentRunId?: string;
460
- /** sha256 hex of the run's resolved (pre-RAG) system prompt — identifies the prompt VERSION. */
461
- promptHash?: string;
462
- }
463
- interface RecordRunEndInput {
464
- runId: string;
465
- /**
466
- * `cancelled` is a THIRD terminal, not a flavour of `failed`: someone asked the run to stop and it
467
- * did, which is the control working. A consumer computing a failure rate over these rows has to be
468
- * able to leave it out — counting a user pressing Stop as an error pages whoever is on call for
469
- * model failures. It carries no `errorCode`/`errorMessage`, since there is nothing to diagnose.
470
- */
471
- status: 'completed' | 'failed' | 'cancelled';
472
- durationMs?: number;
473
- errorCode?: string;
474
- errorMessage?: string;
475
- }
476
- /** Which thread, and how many of its newest messages, {@link ThreadTurnReader.loadThreadForTurn} reads. */
477
- interface ThreadTurnQuery {
478
- threadId: string;
479
- /** Omitted reads every message; `0` reads none. */
480
- messageLimit?: number;
481
- }
482
- /** What a turn reads off a thread — a bounded window, not the transcript. */
483
- interface ThreadTurnPage {
484
- title: string;
485
- defaultAgent: string | null;
486
- /** Whether the THREAD has ever been answered, not whether {@link messages} holds an answer. */
487
- hasAssistantMessage: boolean;
488
- /** Oldest first, carrying only the fields a model turn reads. */
489
- messages: StoredMessage[];
490
- }
491
- /**
492
- * A store that can hand a turn the WINDOW it is about to send, instead of the thread's transcript.
493
- *
494
- * {@link AgentStore.getThread} materializes every message row, every attachment and every tool
495
- * output a thread ever recorded, and the run then journals what it loaded — so a long thread pays
496
- * for its whole history on every turn and again on every replay, to send a prompt bounded to its
497
- * last few messages. This read is bounded by the database (`order by created_at desc limit ?`),
498
- * projected to the columns a model turn actually reads.
499
- *
500
- * `hasAssistantMessage` is answered over the WHOLE thread, never the page: it answers "has this
501
- * conversation been answered before?" — what a `thread-start` intake asks — and a thread whose window
502
- * happens to hold only the user's last questions has still been answered. `null` for a thread that is
503
- * unknown or soft-deleted, matching `getThread`.
504
- *
505
- * Probed STRUCTURALLY rather than declared on {@link AgentStore}, the same way `defaultAgentForThread`
506
- * is: it is an optimization a store either offers or does not, and one that predates it still answers
507
- * correctly through the full read.
508
- */
509
- interface ThreadTurnReader {
510
- loadThreadForTurn(query: ThreadTurnQuery): Promise<ThreadTurnPage | null>;
511
- }
512
- /** ORM-agnostic persistence. Refs are string ids; adapters may add real relations. */
513
- interface AgentStore {
514
- createThread(input: CreateThreadInput): Promise<ThreadSummary>;
515
- getThread(threadId: string): Promise<ThreadDetail | null>;
516
- listThreads(actorRef: string, limit?: number): Promise<ThreadSummary[]>;
517
- softDeleteThread(threadId: string): Promise<void>;
518
- forkThread(threadId: string, fromMessageId: string): Promise<ThreadSummary>;
519
- setTitle(threadId: string, title: string): Promise<void>;
520
- /**
521
- * Promote a transient thread to a persistent one so it shows up in {@link listThreads}. A
522
- * transient thread is a scratch conversation the caller has not chosen to keep; "saving" it
523
- * clears the flag. Idempotent — promoting an already-persistent thread is a no-op.
524
- */
525
- promoteThread(threadId: string): Promise<void>;
526
- setActiveStream(threadId: string, runId: string | null): Promise<void>;
527
- /**
528
- * OPTIONAL: rename a thread and/or set its default agent in one write. Absent on a store that
529
- * predates this — `setTitle` still covers title-only edits, so nothing else in the lib requires
530
- * this method; the REST `PATCH /threads/:id` endpoint responds 501 for a `defaultAgent` change
531
- * against a store that lacks it.
532
- */
533
- updateThread?(threadId: string, patch: UpdateThreadInput): Promise<void>;
534
- /**
535
- * OPTIONAL: the runId of a currently-running turn on this thread, or `null` if none is running.
536
- * Lets a client that reconnects (page refresh) discover a run to reattach to via the existing
537
- * `GET /chat/:runId/stream`, instead of only being told about a run right after starting it.
538
- * Absent on a store that predates this — thread read/list payloads report `activeRunId: null`.
539
- */
540
- activeRunForThread?(threadId: string): Promise<string | null>;
541
- /**
542
- * OPTIONAL: persist the start of a run (turn). Replay-safe: called under a durable localStep.
543
- * Absent on a store that predates run recording — reliability metrics degrade to zeros/empty.
544
- */
545
- recordRunStart?(run: RecordRunStartInput): Promise<void>;
546
- /** OPTIONAL: settle a run's outcome. `errorCode`/`errorMessage` only when status is 'failed'. */
547
- recordRunEnd?(end: RecordRunEndInput): Promise<void>;
548
- /** OPTIONAL: bump the run's llm-step retry counter (dispatched-step attempt > 1). */
549
- bumpRunRetries?(runId: string): Promise<void>;
550
- /**
551
- * The `actorRef` that owns a thread, or `null` if no such thread exists. The authorization seam
552
- * for thread-scoped endpoints (detail / delete / fork): the service compares this against the
553
- * resolved caller before acting, so one actor can never read or mutate another's thread.
554
- */
555
- ownerOfThread(threadId: string): Promise<string | null>;
556
- /**
557
- * The `actorRef` that owns the thread a tool call belongs to, or `null` if the call is unknown.
558
- * The authorization seam for HITL approve / reject: the caller must own the run they approve.
559
- */
560
- ownerOfToolCall(toolCallId: string): Promise<string | null>;
561
- /**
562
- * The run awaiting a decision on `toolCallId`: the call's OWN `runId` when the row carries one,
563
- * else the thread's `activeStreamId`. Both HITL approve/reject and an elicitation answer route
564
- * through this, derived server-side from the tool call alone — so a decision reaches the exact run
565
- * awaiting it, including a sub-agent's own child run, which the client never sees and could not
566
- * name. No client-supplied runId is trusted (or needed).
567
- *
568
- * The row's own runId comes FIRST because `activeStreamId` names whichever run is streaming the
569
- * thread right now, and that is only the same run while a thread holds exactly one. The fallback
570
- * is for rows written before tool calls recorded a runId, which have nothing else to answer with.
571
- */
572
- runForToolCall(toolCallId: string): Promise<string | null>;
573
- /**
574
- * The `actorRef` that owns the thread currently streaming `runId` (its `activeStreamId`), or
575
- * `null` if no thread is streaming it. The authorization seam for `cancel`: the caller must own
576
- * the run they abort. Resolvable during the live window (a run cancel only matters while active).
577
- */
578
- ownerOfActiveStream(runId: string): Promise<string | null>;
579
- appendMessage(input: AppendMessageInput): Promise<StoredMessage>;
580
- /**
581
- * Attach a turn's settled tool RESULTS to a message that was already appended, replacing whatever
582
- * it held. A message's tool calls are known when it is written and their outputs are not, but a
583
- * thread reader pairs the two off THAT MESSAGE — so an output that only ever reaches the tool-call
584
- * table leaves every call on a reopened thread looking like a tool still running.
585
- *
586
- * Required rather than optional: a store that silently declines this renders a finished turn as a
587
- * permanently in-flight one, with nothing logged and nothing to notice. A missing method should
588
- * fail to compile instead.
589
- */
590
- setMessageToolResults(messageId: string, results: ToolResult[]): Promise<void>;
591
- /**
592
- * Replace the components persisted on an already-appended message (see {@link StoredMessage.ui}).
593
- * The loop calls it once per step, after the step's tools ran, with every component the step
594
- * showed — the model turn's own `ui` frames first, then what its tools pushed through
595
- * `ctx.emitUi`, in call order, deduplicated by `id`. A full replacement, never an append, so a
596
- * repeated call writes the same value.
597
- *
598
- * OPTIONAL: a store without it still streams tool-pushed components live; a reload then shows
599
- * only the ones the model turn itself produced.
600
- */
601
- setMessageUi?(messageId: string, ui: AgentUiComponent[]): Promise<void>;
602
- truncateFrom(threadId: string, messageId: string): Promise<void>;
603
- /**
604
- * OPTIONAL: the thread a message belongs to, or `null` when there is no such message. The
605
- * authorization seam for message-scoped routes (feedback): the service resolves the thread's owner
606
- * from it. Implement it together with {@link setMessageFeedback}.
607
- */
608
- threadOfMessage?(messageId: string): Promise<string | null>;
609
- /**
610
- * OPTIONAL: set (or, with `null`, clear) the rating on a message — see
611
- * {@link import('../types.js').StoredMessage.feedback}. Absent → `POST /messages/:id/feedback`
612
- * answers `501`.
613
- */
614
- setMessageFeedback?(messageId: string, feedback: MessageFeedback | null): Promise<void>;
615
- recordToolCall(input: RecordToolCallInput): Promise<void>;
616
- updateToolCall(input: UpdateToolCallInput): Promise<void>;
617
- /**
618
- * OPTIONAL: the names of the tools whose approval someone asked to REMEMBER in this thread — an
619
- * approved call persisted with `remember: true`. The loop approves a later call of one of them
620
- * without asking, inside that call's own `persist:toolcall` checkpoint. Absent → nothing is ever
621
- * remembered, and every call asks.
622
- */
623
- rememberedApprovals?(threadId: string): Promise<string[]>;
624
- /**
625
- * OPTIONAL: a call's approval state, or `null` when the call is unknown. Read by the approve/reject
626
- * routes to enforce the recorded approver and refuse a decision on a request that already
627
- * expired. Absent → every call is treated as the requester's, with no expiry (the old behaviour).
628
- */
629
- toolCallApproval?(toolCallId: string): Promise<ToolCallApprovalState | null>;
630
- /**
631
- * OPTIONAL: the input a call was recorded with, or `null` when the call is unknown. Read by the
632
- * answer route to check a reply against the questions it answers (a typed question's rules, a
633
- * `required` one left empty) before it is signalled. Absent → answers are checked for shape only,
634
- * and the loop drops what it cannot settle.
635
- */
636
- toolCallInput?(toolCallId: string): Promise<unknown>;
637
- /**
638
- * OPTIONAL: of `mediaIds`, the ones a message that still exists — in a thread owned by
639
- * `actorRef` — still carries as an attachment. The inverse of
640
- * {@link import('./attachment-staging.js').AttachmentStagingStore.list}: the host can enumerate
641
- * the media it staged but cannot see a transcript, and this side sees every transcript but never
642
- * holds the bytes, so neither can decide alone what is safe to delete.
643
- *
644
- * DERIVED, not tracked. A reference is not permanent: `truncateFrom` deletes messages — which is
645
- * exactly what regenerating a turn does — so media that was referenced becomes unreferenced
646
- * again. A flag set when a message is sent would never be unset by that delete, and the bytes
647
- * would be pinned for ever with nothing pointing at them. Answering from the surviving message
648
- * rows on every call is the only form of this that stays true after a truncation.
649
- *
650
- * Scoped to one actor, like every other read on this surface: media referenced only by ANOTHER
651
- * actor's thread is reported unreferenced here, so this can never be turned into a probe for what
652
- * exists in someone else's conversation. A host pairs it with its own per-actor inventory, so the
653
- * candidate ids are already the caller's own.
654
- *
655
- * Returns each id at most once, in the order asked. Absent on a store that predates this — a
656
- * caller must treat the absence as "cannot answer" and collect NOTHING, never as "nothing is
657
- * referenced", which would delete every attachment the actor ever sent.
658
- */
659
- referencedMediaIds?(actorRef: string, mediaIds: readonly string[]): Promise<string[]>;
660
- recordUsage(input: RecordUsageInput): Promise<void>;
661
- /**
662
- * The actor's spend for `day` (UTC): total tokens plus the summed provider-reported USD cost.
663
- * `costUsd` is `0` when no turn on that day reported a cost (token-only providers). Feeds both
664
- * quota enforcement (via {@link QuotaStore}) and the quota-today view.
665
- */
666
- quotaToday(actorRef: string, day: string): Promise<{
667
- usedTokens: number;
668
- costUsd: number;
669
- }>;
670
- /**
671
- * OPTIONAL: the actor's spend over the UTC days `fromDay`..`toDay` (`YYYY-MM-DD`, inclusive) —
672
- * {@link quotaToday} over a range. Feeds the monthly window of `GET <base>/quota`; absent → that
673
- * window is left out.
674
- */
675
- usageBetween?(actorRef: string, fromDay: string, toDay: string): Promise<{
676
- usedTokens: number;
677
- costUsd: number;
678
- }>;
679
- }
680
-
681
355
  /**
682
356
  * Decides whether an actor may invoke a tool. The default impl checks the actor's role
683
357
  * against `spec.roles` (defaulting to an ADMIN-only set). Apps can plug `nestjs-authz`
@@ -875,10 +549,29 @@ interface Reranker {
875
549
  * `start` ENQUEUES and returns immediately with the runId — the live tokens flow on the
876
550
  * TokenStreamSink, not through this call.
877
551
  */
552
+ /** How {@link AgentRunner.start} starts a run. */
553
+ interface AgentRunStartOptions {
554
+ /**
555
+ * Use this id for the run instead of minting one. The chat queue claims the thread for a run
556
+ * BEFORE starting it (so no second turn can slip in between), which needs the id up front; a
557
+ * queued message's run id is the message's own id, which also makes a retried start idempotent.
558
+ * A runner that ignores it still works — the service then re-points the thread at the id it
559
+ * returned.
560
+ */
561
+ runId?: string;
562
+ }
878
563
  interface AgentRunner {
879
- start(input: AgentRunInput): Promise<{
564
+ start(input: AgentRunInput, options?: AgentRunStartOptions): Promise<{
880
565
  runId: string;
881
566
  }>;
567
+ /**
568
+ * OPTIONAL: whether `runId` is still running (or parked, or about to start) as far as this runner
569
+ * can tell. Asked when a thread's admission is held by a run, to tell a live holder from a stale
570
+ * one a crashed process left behind — a stale holder is replaced instead of queueing behind it
571
+ * for ever. Answer `true` when unsure: a wrong `false` starts a second turn on the thread. Absent
572
+ * → every holder is treated as live.
573
+ */
574
+ isRunActive?(runId: string): Promise<boolean>;
882
575
  /**
883
576
  * Deliver a human's reply to a parked tool call — a {@link import('../types.js').Decision} on an
884
577
  * action tool, or an `ElicitationReply` answering a question set. One channel for both, because
@@ -3630,8 +3323,11 @@ interface GovernanceRunRow {
3630
3323
  parentRunId?: string;
3631
3324
  }
3632
3325
  /** A fully in-memory `AgentStore` for tests and the offline demo. */
3633
- declare class InMemoryAgentStore implements AgentStore {
3326
+ declare class InMemoryAgentStore implements AgentStore, ChatQueueStore {
3634
3327
  private readonly threads;
3328
+ /** Each thread's waiting messages, in run order. */
3329
+ private readonly queues;
3330
+ private readonly pauses;
3635
3331
  private readonly toolCalls;
3636
3332
  private readonly usage;
3637
3333
  private readonly runs;
@@ -3680,6 +3376,20 @@ declare class InMemoryAgentStore implements AgentStore {
3680
3376
  bumpRunRetries(runId: string): Promise<void>;
3681
3377
  promoteThread(threadId: string): Promise<void>;
3682
3378
  setActiveStream(threadId: string, runId: string | null): Promise<void>;
3379
+ claimActiveStream(threadId: string, runId: string, options?: {
3380
+ replacing?: string;
3381
+ }): Promise<boolean>;
3382
+ releaseActiveStream(threadId: string, runId: string): Promise<boolean>;
3383
+ enqueueMessage(input: EnqueueMessageInput): Promise<QueuedMessage>;
3384
+ listQueue(threadId: string): Promise<QueuedMessage[]>;
3385
+ getQueuedMessage(id: string): Promise<QueuedMessage | null>;
3386
+ updateQueuedMessage(id: string, patch: QueuedMessagePatch): Promise<QueuedMessage | null>;
3387
+ moveQueuedMessage(id: string, index: number): Promise<boolean>;
3388
+ removeQueuedMessage(id: string): Promise<boolean>;
3389
+ clearQueue(threadId: string): Promise<number>;
3390
+ queuePause(threadId: string): Promise<QueuePause | null>;
3391
+ setQueuePause(threadId: string, pause: QueuePause | null): Promise<void>;
3392
+ private findQueued;
3683
3393
  appendMessage(input: AppendMessageInput): Promise<StoredMessage>;
3684
3394
  setMessageToolResults(messageId: string, results: ToolResult[]): Promise<void>;
3685
3395
  setMessageUi(messageId: string, ui: AgentUiComponent[]): Promise<void>;
@@ -3744,4 +3454,4 @@ declare class InMemoryAgentStore implements AgentStore {
3744
3454
  private toSummary;
3745
3455
  }
3746
3456
 
3747
- export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MEMORY, AGENT_MODEL, AGENT_MODEL_CATALOG, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_PROVIDER, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, type AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingDescription, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernanceMessageRow, type GovernancePage, type GovernancePageQuery, type GovernancePendingApprovalRow, type GovernanceRange, type GovernanceRunDetail, type GovernanceRunRow, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceThreadRow, type GovernanceToolCallRow, type GovernanceUsageInput, type GovernanceUsageRow, HistoryPolicy, HumanReply, InMemoryAgentStore, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageFeedback, MessageUsage, ModelAnswer, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogLock, type ModelCatalogProviderGroup, type ModelCatalogQuery, type ModelCatalogView, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, type QuotaBlock, QuotaExceededError, type QuotaPeriod, type QuotaProvider, type QuotaQuery, type QuotaReport, QuotaState, type QuotaStore, type QuotaWarning, type QuotaWindow, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, type ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDescribeScope, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, type UpdateThreadInput, type UpdateToolCallInput, UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, exhaustedWindow, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, quotaPeriodRange, quotaUsedRatio, quotaWarning, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
3457
+ export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MEMORY, AGENT_MODEL, AGENT_MODEL_CATALOG, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_PROVIDER, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStartOptions, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingDescription, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, ChatQueueStore, type CostUsage, CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, EnqueueMessageInput, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernanceMessageRow, type GovernancePage, type GovernancePageQuery, type GovernancePendingApprovalRow, type GovernanceRange, type GovernanceRunDetail, type GovernanceRunRow, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceThreadRow, type GovernanceToolCallRow, type GovernanceUsageInput, type GovernanceUsageRow, HistoryPolicy, HumanReply, InMemoryAgentStore, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageFeedback, MessageUsage, ModelAnswer, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogLock, type ModelCatalogProviderGroup, type ModelCatalogQuery, type ModelCatalogView, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QueuePause, QueuedMessage, QueuedMessagePatch, type QuotaBlock, QuotaExceededError, type QuotaPeriod, type QuotaProvider, type QuotaQuery, type QuotaReport, QuotaState, type QuotaStore, type QuotaWarning, type QuotaWindow, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, RecordRunStartInput, RecordToolCallInput, RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDescribeScope, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, UpdateThreadInput, UpdateToolCallInput, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, exhaustedWindow, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, quotaPeriodRange, quotaUsedRatio, quotaWarning, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };