@dudousxd/nestjs-agent-core 0.4.0 → 0.6.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,4 +1,5 @@
1
1
  import { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import { ChannelRegistry } from '@dudousxd/nestjs-diagnostics';
2
3
 
3
4
  /** Who is driving the turn. Roles + tenant come from the host app (nestjs-context/authz). */
4
5
  interface Actor {
@@ -119,6 +120,11 @@ interface QuotaView {
119
120
  interface Decision {
120
121
  approved: boolean;
121
122
  reason?: string;
123
+ /**
124
+ * Opaque ref of WHO decided (e.g. a console admin). When absent, the run's own actor decided
125
+ * (the chat flow).
126
+ */
127
+ executedByRef?: string;
122
128
  }
123
129
  type MessageRole = 'user' | 'assistant' | 'system';
124
130
  /**
@@ -275,6 +281,38 @@ interface ThreadDetail extends ThreadSummary {
275
281
  activeStreamId?: string;
276
282
  }
277
283
  type ToolCallStatus = 'auto_executed' | 'pending_approval' | 'executed' | 'rejected' | 'failed';
284
+ /**
285
+ * Serializable input for a dispatched model-turn step. Carries only data — the serving worker
286
+ * re-resolves the model/sink/registry from its own DI via AGENT_DEPS_FACTORY.forAgent(agentName).
287
+ */
288
+ interface LlmStepEnvelope {
289
+ /** Undefined = default agent (same semantics as {@link AgentRunInput.agentName}). */
290
+ agentName?: string;
291
+ system: string;
292
+ messages: ModelMessage[];
293
+ /** The turn's actor — the handler re-derives tool definitions from it (definitionsFor). */
294
+ actor: Actor;
295
+ }
296
+ /**
297
+ * The serializable subset of `AiToolCtx` — everything except `host` (re-attached handler-side
298
+ * from DI).
299
+ */
300
+ interface ToolStepCtx {
301
+ actor: Actor;
302
+ threadId: string;
303
+ runId: string;
304
+ requestId: string;
305
+ agentName?: string;
306
+ pageContext?: PageContext;
307
+ }
308
+ /** Serializable input for a dispatched tool-execution step. */
309
+ interface ToolStepEnvelope {
310
+ toolName: string;
311
+ input: unknown;
312
+ ctx: ToolStepCtx;
313
+ /** Applied INSIDE the handler (`withToolTimeout`) — never as a durable step `timeoutMs`. */
314
+ timeoutMs?: number;
315
+ }
278
316
 
279
317
  /**
280
318
  * Public, cross-lib-discoverable DI tokens.
@@ -325,6 +363,11 @@ declare const AGENT_ACTOR_DIRECTORY: unique symbol;
325
363
  * {@link import('./spi/attachment-staging.js').AttachmentStagingStore}.
326
364
  */
327
365
  declare const AGENT_ATTACHMENT_STAGING: unique symbol;
366
+ /**
367
+ * Console-side HITL approve/reject for the cross-thread approvals inbox. Optional — see
368
+ * {@link import('./spi/approval-port.js').AgentApprovalPort}.
369
+ */
370
+ declare const AGENT_APPROVAL_PORT: unique symbol;
328
371
 
329
372
  /**
330
373
  * Per-invocation context handed to a tool handler. Host-supplied bits are optional. Identity lives
@@ -541,6 +584,21 @@ interface RecordUsageInput {
541
584
  /** Provider-reported actual USD cost for this turn, when known (gateways report it). */
542
585
  costUsd?: number;
543
586
  }
587
+ interface RecordRunStartInput {
588
+ runId: string;
589
+ threadId: string;
590
+ actorRef: string;
591
+ agentName?: string;
592
+ /** sha256 hex of the run's resolved (pre-RAG) system prompt — identifies the prompt VERSION. */
593
+ promptHash?: string;
594
+ }
595
+ interface RecordRunEndInput {
596
+ runId: string;
597
+ status: 'completed' | 'failed';
598
+ durationMs?: number;
599
+ errorCode?: string;
600
+ errorMessage?: string;
601
+ }
544
602
  /** ORM-agnostic persistence. Refs are string ids; adapters may add real relations. */
545
603
  interface AgentStore {
546
604
  createThread(input: CreateThreadInput): Promise<ThreadSummary>;
@@ -570,6 +628,15 @@ interface AgentStore {
570
628
  * Absent on a store that predates this — thread read/list payloads report `activeRunId: null`.
571
629
  */
572
630
  activeRunForThread?(threadId: string): Promise<string | null>;
631
+ /**
632
+ * OPTIONAL: persist the start of a run (turn). Replay-safe: called under a durable localStep.
633
+ * Absent on a store that predates run recording — reliability metrics degrade to zeros/empty.
634
+ */
635
+ recordRunStart?(run: RecordRunStartInput): Promise<void>;
636
+ /** OPTIONAL: settle a run's outcome. `errorCode`/`errorMessage` only when status is 'failed'. */
637
+ recordRunEnd?(end: RecordRunEndInput): Promise<void>;
638
+ /** OPTIONAL: bump the run's llm-step retry counter (dispatched-step attempt > 1). */
639
+ bumpRunRetries?(runId: string): Promise<void>;
573
640
  /**
574
641
  * The `actorRef` that owns a thread, or `null` if no such thread exists. The authorization seam
575
642
  * for thread-scoped endpoints (detail / delete / fork): the service compares this against the
@@ -822,6 +889,77 @@ interface ThreadActivityRow {
822
889
  totalTokens: number;
823
890
  lastActivityAt: string;
824
891
  }
892
+ /** Aggregated run reliability over a range. */
893
+ interface RunMetrics {
894
+ runs: number;
895
+ completed: number;
896
+ failed: number;
897
+ /** completed / runs, 0 when runs = 0. */
898
+ successRate: number;
899
+ /** Total llm-step retries across the range's runs. */
900
+ retries: number;
901
+ durationP50Ms: number | null;
902
+ durationP95Ms: number | null;
903
+ }
904
+ /** Run/failure/retry rollup for one agent over a range. */
905
+ interface RunAgentBreakdownRow {
906
+ /** '(default)' when the run had none. */
907
+ agentName: string;
908
+ runs: number;
909
+ failed: number;
910
+ retries: number;
911
+ }
912
+ /** Failed-run count for one error code over a range. */
913
+ interface RunErrorBreakdownRow {
914
+ errorCode: string;
915
+ count: number;
916
+ }
917
+ /** One point on the daily run/failure trend. */
918
+ interface RunTrendPoint {
919
+ day: string;
920
+ runs: number;
921
+ failed: number;
922
+ }
923
+ /** A recent run for the reliability feed. */
924
+ interface RecentRunRow {
925
+ runId: string;
926
+ threadId: string;
927
+ actorRef: string;
928
+ agentName: string | null;
929
+ /** 'running' | 'completed' | 'failed'. */
930
+ status: string;
931
+ durationMs: number | null;
932
+ errorCode: string | null;
933
+ errorMessage: string | null;
934
+ retries: number;
935
+ /** ISO timestamp. */
936
+ startedAt: string;
937
+ /** sha256 hex of the run's resolved (pre-RAG) system prompt; `null` for a run recorded before this shipped. */
938
+ promptHash: string | null;
939
+ }
940
+ /** One tool call awaiting a HITL decision, for the cross-thread approvals inbox. */
941
+ interface PendingApprovalRow {
942
+ toolCallId: string;
943
+ toolName: string;
944
+ input: unknown;
945
+ threadId: string;
946
+ threadTitle: string;
947
+ /** Who asked — the run's actor. */
948
+ actorRef: string;
949
+ agentName: string | null;
950
+ /** ISO timestamp. */
951
+ requestedAt: string;
952
+ }
953
+ /** Governance rollup for one tool over a range. */
954
+ interface ToolStatRow {
955
+ toolName: string;
956
+ toolType: string;
957
+ calls: number;
958
+ failed: number;
959
+ rejected: number;
960
+ /** p95 of executionMs across executed calls; null when none carry it. */
961
+ p95ExecutionMs: number | null;
962
+ }
825
963
  /**
826
964
  * The governance read-model. Cost is `inputTokens/1e6 * inputPricePer1m + outputTokens/1e6 *
827
965
  * outputPricePer1m` against the current pricing row per model; an unpriced model contributes 0 cost
@@ -835,6 +973,15 @@ interface AgentGovernanceQueries {
835
973
  usageTrend(range: GovernanceRange): Promise<UsageTrendPoint[]>;
836
974
  recentToolCalls(limit: number): Promise<ToolCallActivityRow[]>;
837
975
  recentThreads(limit: number): Promise<ThreadActivityRow[]>;
976
+ runMetrics(range: GovernanceRange): Promise<RunMetrics>;
977
+ runsByAgent(range: GovernanceRange): Promise<RunAgentBreakdownRow[]>;
978
+ runErrors(range: GovernanceRange): Promise<RunErrorBreakdownRow[]>;
979
+ runTrend(range: GovernanceRange): Promise<RunTrendPoint[]>;
980
+ recentRuns(limit: number): Promise<RecentRunRow[]>;
981
+ /** Tool calls sitting `pending_approval`, oldest first — an inbox drains from the back. Capped at `limit`. */
982
+ pendingApprovals(limit: number): Promise<PendingApprovalRow[]>;
983
+ /** Per-tool call/failure/rejection/latency rollup over the range, highest call count first. */
984
+ toolStats(range: GovernanceRange): Promise<ToolStatRow[]>;
838
985
  }
839
986
 
840
987
  /**
@@ -876,6 +1023,21 @@ interface AttachmentStagingStore {
876
1023
  stage(input: StageAttachmentInput): Promise<MessageAttachment>;
877
1024
  }
878
1025
 
1026
+ /**
1027
+ * Console-side HITL decisions. Implemented by the agent runtime (the nestjs package binds it to
1028
+ * the same signal path chat approvals use); the dashboard injects it OPTIONALLY — absent = the
1029
+ * approvals inbox renders read-only.
1030
+ */
1031
+ interface AgentApprovalPort {
1032
+ approve(toolCallId: string, opts?: {
1033
+ executedByRef?: string;
1034
+ }): Promise<void>;
1035
+ reject(toolCallId: string, opts?: {
1036
+ executedByRef?: string;
1037
+ reason?: string;
1038
+ }): Promise<void>;
1039
+ }
1040
+
879
1041
  /**
880
1042
  * The pure aggregation core shared by every {@link import('../spi/governance-queries.js').AgentGovernanceQueries}
881
1043
  * adapter (MikroORM, Drizzle, in-memory). An adapter's only job is the DB-specific row fetch; the
@@ -1066,15 +1228,36 @@ interface AgentLoopHooks {
1066
1228
  text: string;
1067
1229
  }>;
1068
1230
  /**
1069
- * Checkpoint wrapper. Inline = call fn directly; durable = ctx.step(name, fn).
1231
+ * Checkpoint wrapper. Inline = call fn directly; durable = ctx.localStep(name, fn) — the
1232
+ * in-process checkpointed primitive (`name` is a checkpoint identity, not a worker group).
1070
1233
  * EVERY side-effect and control-flow read goes through this so durable replay returns
1071
1234
  * cached results (stable ids, no double-write, no re-streaming).
1072
1235
  */
1073
1236
  step<T>(name: string, fn: () => Promise<T>): Promise<T>;
1237
+ /**
1238
+ * Dispatch the model turn as a routed remote step. When present the loop uses it INSTEAD of
1239
+ * running the model inline under hooks.step. Must resolve to exactly what deps.model.runTurn
1240
+ * resolves. The durable runner enriches the envelope with sink routing (sinkRunId/childSink)
1241
+ * on its side — core stays sink-topology-agnostic.
1242
+ */
1243
+ dispatchLlm?(index: number, envelope: LlmStepEnvelope): Promise<ModelTurnResult>;
1244
+ /**
1245
+ * Dispatch one tool execution as a routed remote step. Replaces ONLY the registry.invoke call
1246
+ * (+ its timeout, applied handler-side); all persist steps around it stay local.
1247
+ */
1248
+ dispatchTool?(call: ToolCallRequest, envelope: ToolStepEnvelope): Promise<unknown>;
1249
+ /**
1250
+ * Recognizes the runner's control-flow signals (durable suspend / continue-as-new) so the loop
1251
+ * rethrows them untouched instead of recording a failure. Inline runners omit it — they have no
1252
+ * control-flow exceptions.
1253
+ */
1254
+ isControlFlowError?(error: unknown): boolean;
1074
1255
  }
1075
1256
  declare class QuotaExceededError extends Error {
1076
1257
  constructor();
1077
1258
  }
1259
+ /** Reject if `work` doesn't settle within `ms`. The underlying work is left to finish on its own. */
1260
+ declare function withToolTimeout<T>(work: Promise<T>, ms: number, toolName: string): Promise<T>;
1078
1261
  /**
1079
1262
  * The provider-agnostic agent turn, reused by both the inline and durable runners.
1080
1263
  * It drives the model→tools→model iteration; the runner supplies the `step`/`awaitApproval`
@@ -1157,5 +1340,28 @@ declare function publishAgentRunFinished(payload: AgentRunFinished): void;
1157
1340
  declare function publishAgentRunFailed(payload: AgentRunFailed): void;
1158
1341
  declare function publishAgentDelegated(payload: AgentDelegated): void;
1159
1342
  declare function publishAgentRetrieved(payload: AgentRetrieved): void;
1343
+ /** Every event key declared on `ChannelRegistry['agent']` above — derived, not hand-copied. */
1344
+ type AgentDiagnosticEvent = keyof ChannelRegistry['agent'];
1345
+ /**
1346
+ * All 8 events on `ChannelRegistry['agent']`, in a stable order — handy for wiring subscribers
1347
+ * (mirrors nestjs-media's `MEDIA_DIAGNOSTIC_EVENTS`). A drift between this list and the registry is
1348
+ * a compile error in both directions: an extra/misspelled entry fails this array's own
1349
+ * `readonly AgentDiagnosticEvent[]` annotation immediately; a missing entry fails the
1350
+ * {@link AgentDiagnosticEventsCoverAllKeys} check below.
1351
+ */
1352
+ declare const AGENT_DIAGNOSTIC_EVENTS: readonly AgentDiagnosticEvent[];
1353
+ /**
1354
+ * The telescope key for an agent diagnostics channel — `agent:<event>`. This is the key the
1355
+ * `@dudousxd/nestjs-diagnostics-telescope` generic bridge matches its `exclude` option against,
1356
+ * and the label its "Busiest events" panel shows. Distinct from the `aviary:agent:<event>` channel
1357
+ * name used on the wire. Mirrors `mediaDiagnosticKey`.
1358
+ */
1359
+ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
1360
+ /**
1361
+ * Compose the telescope key for an agent event, typed against {@link AgentDiagnosticEvent} so a
1362
+ * misspelled event is a compile error. Feed the result to `nestjsDiagnosticsTelescope({ exclude:
1363
+ * [...] })` to mute a noisy channel, e.g. `agentDiagnosticKey('message')`.
1364
+ */
1365
+ declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
1160
1366
 
1161
- export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MODEL, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_STORE, AGENT_TOOL_REGISTRY, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentGovernanceQueries, type AgentLoopDeps, type AgentLoopHooks, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentToolCallEvent, type AiToolCtx, type AppendMessageInput, type AttachmentStagingStore, type CostUsage, type CreateThreadInput, type CurrentModelPrice, type Decision, DefaultRolesPolicy, type EmbeddingProvider, type GovernanceRange, type GovernanceUsageInput, type MessageAttachment, type MessageRole, type MessageUsage, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type PageContext, type Passage, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, type RecordToolCallInput, type RecordUsageInput, type RerankOptions, type Reranker, type RetrieveOptions, type Retriever, type RolesPolicy, type SinkWriter, type StageAttachmentInput, type StoredMessage, type StreamError, type ThreadActivityRow, type ThreadDetail, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolDefinition, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, dayBoundsUtc, encodeStreamEvent, estimateCost, filterToolsByAllowList, filterToolsByRole, publishAgentDelegated, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentToolCall, runAgentLoop, seedModelPrices };
1367
+ 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_MODEL, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_STORE, AGENT_TOOL_REGISTRY, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentGovernanceQueries, type AgentLoopDeps, type AgentLoopHooks, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentToolCallEvent, type AiToolCtx, type AppendMessageInput, type AttachmentStagingStore, type CostUsage, type CreateThreadInput, type CurrentModelPrice, type Decision, DefaultRolesPolicy, type EmbeddingProvider, type GovernanceRange, type GovernanceUsageInput, type LlmStepEnvelope, type MessageAttachment, type MessageRole, type MessageUsage, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type PageContext, type Passage, type PendingApprovalRow, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RerankOptions, type Reranker, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, type RunErrorBreakdownRow, type RunMetrics, type RunTrendPoint, type SinkWriter, type StageAttachmentInput, type StoredMessage, type StreamError, type ThreadActivityRow, type ThreadDetail, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolDefinition, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type ToolStatRow, type ToolStepCtx, type ToolStepEnvelope, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, agentDiagnosticKey, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, dayBoundsUtc, encodeStreamEvent, estimateCost, filterToolsByAllowList, filterToolsByRole, publishAgentDelegated, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentToolCall, runAgentLoop, seedModelPrices, withToolTimeout };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import { ChannelRegistry } from '@dudousxd/nestjs-diagnostics';
2
3
 
3
4
  /** Who is driving the turn. Roles + tenant come from the host app (nestjs-context/authz). */
4
5
  interface Actor {
@@ -119,6 +120,11 @@ interface QuotaView {
119
120
  interface Decision {
120
121
  approved: boolean;
121
122
  reason?: string;
123
+ /**
124
+ * Opaque ref of WHO decided (e.g. a console admin). When absent, the run's own actor decided
125
+ * (the chat flow).
126
+ */
127
+ executedByRef?: string;
122
128
  }
123
129
  type MessageRole = 'user' | 'assistant' | 'system';
124
130
  /**
@@ -275,6 +281,38 @@ interface ThreadDetail extends ThreadSummary {
275
281
  activeStreamId?: string;
276
282
  }
277
283
  type ToolCallStatus = 'auto_executed' | 'pending_approval' | 'executed' | 'rejected' | 'failed';
284
+ /**
285
+ * Serializable input for a dispatched model-turn step. Carries only data — the serving worker
286
+ * re-resolves the model/sink/registry from its own DI via AGENT_DEPS_FACTORY.forAgent(agentName).
287
+ */
288
+ interface LlmStepEnvelope {
289
+ /** Undefined = default agent (same semantics as {@link AgentRunInput.agentName}). */
290
+ agentName?: string;
291
+ system: string;
292
+ messages: ModelMessage[];
293
+ /** The turn's actor — the handler re-derives tool definitions from it (definitionsFor). */
294
+ actor: Actor;
295
+ }
296
+ /**
297
+ * The serializable subset of `AiToolCtx` — everything except `host` (re-attached handler-side
298
+ * from DI).
299
+ */
300
+ interface ToolStepCtx {
301
+ actor: Actor;
302
+ threadId: string;
303
+ runId: string;
304
+ requestId: string;
305
+ agentName?: string;
306
+ pageContext?: PageContext;
307
+ }
308
+ /** Serializable input for a dispatched tool-execution step. */
309
+ interface ToolStepEnvelope {
310
+ toolName: string;
311
+ input: unknown;
312
+ ctx: ToolStepCtx;
313
+ /** Applied INSIDE the handler (`withToolTimeout`) — never as a durable step `timeoutMs`. */
314
+ timeoutMs?: number;
315
+ }
278
316
 
279
317
  /**
280
318
  * Public, cross-lib-discoverable DI tokens.
@@ -325,6 +363,11 @@ declare const AGENT_ACTOR_DIRECTORY: unique symbol;
325
363
  * {@link import('./spi/attachment-staging.js').AttachmentStagingStore}.
326
364
  */
327
365
  declare const AGENT_ATTACHMENT_STAGING: unique symbol;
366
+ /**
367
+ * Console-side HITL approve/reject for the cross-thread approvals inbox. Optional — see
368
+ * {@link import('./spi/approval-port.js').AgentApprovalPort}.
369
+ */
370
+ declare const AGENT_APPROVAL_PORT: unique symbol;
328
371
 
329
372
  /**
330
373
  * Per-invocation context handed to a tool handler. Host-supplied bits are optional. Identity lives
@@ -541,6 +584,21 @@ interface RecordUsageInput {
541
584
  /** Provider-reported actual USD cost for this turn, when known (gateways report it). */
542
585
  costUsd?: number;
543
586
  }
587
+ interface RecordRunStartInput {
588
+ runId: string;
589
+ threadId: string;
590
+ actorRef: string;
591
+ agentName?: string;
592
+ /** sha256 hex of the run's resolved (pre-RAG) system prompt — identifies the prompt VERSION. */
593
+ promptHash?: string;
594
+ }
595
+ interface RecordRunEndInput {
596
+ runId: string;
597
+ status: 'completed' | 'failed';
598
+ durationMs?: number;
599
+ errorCode?: string;
600
+ errorMessage?: string;
601
+ }
544
602
  /** ORM-agnostic persistence. Refs are string ids; adapters may add real relations. */
545
603
  interface AgentStore {
546
604
  createThread(input: CreateThreadInput): Promise<ThreadSummary>;
@@ -570,6 +628,15 @@ interface AgentStore {
570
628
  * Absent on a store that predates this — thread read/list payloads report `activeRunId: null`.
571
629
  */
572
630
  activeRunForThread?(threadId: string): Promise<string | null>;
631
+ /**
632
+ * OPTIONAL: persist the start of a run (turn). Replay-safe: called under a durable localStep.
633
+ * Absent on a store that predates run recording — reliability metrics degrade to zeros/empty.
634
+ */
635
+ recordRunStart?(run: RecordRunStartInput): Promise<void>;
636
+ /** OPTIONAL: settle a run's outcome. `errorCode`/`errorMessage` only when status is 'failed'. */
637
+ recordRunEnd?(end: RecordRunEndInput): Promise<void>;
638
+ /** OPTIONAL: bump the run's llm-step retry counter (dispatched-step attempt > 1). */
639
+ bumpRunRetries?(runId: string): Promise<void>;
573
640
  /**
574
641
  * The `actorRef` that owns a thread, or `null` if no such thread exists. The authorization seam
575
642
  * for thread-scoped endpoints (detail / delete / fork): the service compares this against the
@@ -822,6 +889,77 @@ interface ThreadActivityRow {
822
889
  totalTokens: number;
823
890
  lastActivityAt: string;
824
891
  }
892
+ /** Aggregated run reliability over a range. */
893
+ interface RunMetrics {
894
+ runs: number;
895
+ completed: number;
896
+ failed: number;
897
+ /** completed / runs, 0 when runs = 0. */
898
+ successRate: number;
899
+ /** Total llm-step retries across the range's runs. */
900
+ retries: number;
901
+ durationP50Ms: number | null;
902
+ durationP95Ms: number | null;
903
+ }
904
+ /** Run/failure/retry rollup for one agent over a range. */
905
+ interface RunAgentBreakdownRow {
906
+ /** '(default)' when the run had none. */
907
+ agentName: string;
908
+ runs: number;
909
+ failed: number;
910
+ retries: number;
911
+ }
912
+ /** Failed-run count for one error code over a range. */
913
+ interface RunErrorBreakdownRow {
914
+ errorCode: string;
915
+ count: number;
916
+ }
917
+ /** One point on the daily run/failure trend. */
918
+ interface RunTrendPoint {
919
+ day: string;
920
+ runs: number;
921
+ failed: number;
922
+ }
923
+ /** A recent run for the reliability feed. */
924
+ interface RecentRunRow {
925
+ runId: string;
926
+ threadId: string;
927
+ actorRef: string;
928
+ agentName: string | null;
929
+ /** 'running' | 'completed' | 'failed'. */
930
+ status: string;
931
+ durationMs: number | null;
932
+ errorCode: string | null;
933
+ errorMessage: string | null;
934
+ retries: number;
935
+ /** ISO timestamp. */
936
+ startedAt: string;
937
+ /** sha256 hex of the run's resolved (pre-RAG) system prompt; `null` for a run recorded before this shipped. */
938
+ promptHash: string | null;
939
+ }
940
+ /** One tool call awaiting a HITL decision, for the cross-thread approvals inbox. */
941
+ interface PendingApprovalRow {
942
+ toolCallId: string;
943
+ toolName: string;
944
+ input: unknown;
945
+ threadId: string;
946
+ threadTitle: string;
947
+ /** Who asked — the run's actor. */
948
+ actorRef: string;
949
+ agentName: string | null;
950
+ /** ISO timestamp. */
951
+ requestedAt: string;
952
+ }
953
+ /** Governance rollup for one tool over a range. */
954
+ interface ToolStatRow {
955
+ toolName: string;
956
+ toolType: string;
957
+ calls: number;
958
+ failed: number;
959
+ rejected: number;
960
+ /** p95 of executionMs across executed calls; null when none carry it. */
961
+ p95ExecutionMs: number | null;
962
+ }
825
963
  /**
826
964
  * The governance read-model. Cost is `inputTokens/1e6 * inputPricePer1m + outputTokens/1e6 *
827
965
  * outputPricePer1m` against the current pricing row per model; an unpriced model contributes 0 cost
@@ -835,6 +973,15 @@ interface AgentGovernanceQueries {
835
973
  usageTrend(range: GovernanceRange): Promise<UsageTrendPoint[]>;
836
974
  recentToolCalls(limit: number): Promise<ToolCallActivityRow[]>;
837
975
  recentThreads(limit: number): Promise<ThreadActivityRow[]>;
976
+ runMetrics(range: GovernanceRange): Promise<RunMetrics>;
977
+ runsByAgent(range: GovernanceRange): Promise<RunAgentBreakdownRow[]>;
978
+ runErrors(range: GovernanceRange): Promise<RunErrorBreakdownRow[]>;
979
+ runTrend(range: GovernanceRange): Promise<RunTrendPoint[]>;
980
+ recentRuns(limit: number): Promise<RecentRunRow[]>;
981
+ /** Tool calls sitting `pending_approval`, oldest first — an inbox drains from the back. Capped at `limit`. */
982
+ pendingApprovals(limit: number): Promise<PendingApprovalRow[]>;
983
+ /** Per-tool call/failure/rejection/latency rollup over the range, highest call count first. */
984
+ toolStats(range: GovernanceRange): Promise<ToolStatRow[]>;
838
985
  }
839
986
 
840
987
  /**
@@ -876,6 +1023,21 @@ interface AttachmentStagingStore {
876
1023
  stage(input: StageAttachmentInput): Promise<MessageAttachment>;
877
1024
  }
878
1025
 
1026
+ /**
1027
+ * Console-side HITL decisions. Implemented by the agent runtime (the nestjs package binds it to
1028
+ * the same signal path chat approvals use); the dashboard injects it OPTIONALLY — absent = the
1029
+ * approvals inbox renders read-only.
1030
+ */
1031
+ interface AgentApprovalPort {
1032
+ approve(toolCallId: string, opts?: {
1033
+ executedByRef?: string;
1034
+ }): Promise<void>;
1035
+ reject(toolCallId: string, opts?: {
1036
+ executedByRef?: string;
1037
+ reason?: string;
1038
+ }): Promise<void>;
1039
+ }
1040
+
879
1041
  /**
880
1042
  * The pure aggregation core shared by every {@link import('../spi/governance-queries.js').AgentGovernanceQueries}
881
1043
  * adapter (MikroORM, Drizzle, in-memory). An adapter's only job is the DB-specific row fetch; the
@@ -1066,15 +1228,36 @@ interface AgentLoopHooks {
1066
1228
  text: string;
1067
1229
  }>;
1068
1230
  /**
1069
- * Checkpoint wrapper. Inline = call fn directly; durable = ctx.step(name, fn).
1231
+ * Checkpoint wrapper. Inline = call fn directly; durable = ctx.localStep(name, fn) — the
1232
+ * in-process checkpointed primitive (`name` is a checkpoint identity, not a worker group).
1070
1233
  * EVERY side-effect and control-flow read goes through this so durable replay returns
1071
1234
  * cached results (stable ids, no double-write, no re-streaming).
1072
1235
  */
1073
1236
  step<T>(name: string, fn: () => Promise<T>): Promise<T>;
1237
+ /**
1238
+ * Dispatch the model turn as a routed remote step. When present the loop uses it INSTEAD of
1239
+ * running the model inline under hooks.step. Must resolve to exactly what deps.model.runTurn
1240
+ * resolves. The durable runner enriches the envelope with sink routing (sinkRunId/childSink)
1241
+ * on its side — core stays sink-topology-agnostic.
1242
+ */
1243
+ dispatchLlm?(index: number, envelope: LlmStepEnvelope): Promise<ModelTurnResult>;
1244
+ /**
1245
+ * Dispatch one tool execution as a routed remote step. Replaces ONLY the registry.invoke call
1246
+ * (+ its timeout, applied handler-side); all persist steps around it stay local.
1247
+ */
1248
+ dispatchTool?(call: ToolCallRequest, envelope: ToolStepEnvelope): Promise<unknown>;
1249
+ /**
1250
+ * Recognizes the runner's control-flow signals (durable suspend / continue-as-new) so the loop
1251
+ * rethrows them untouched instead of recording a failure. Inline runners omit it — they have no
1252
+ * control-flow exceptions.
1253
+ */
1254
+ isControlFlowError?(error: unknown): boolean;
1074
1255
  }
1075
1256
  declare class QuotaExceededError extends Error {
1076
1257
  constructor();
1077
1258
  }
1259
+ /** Reject if `work` doesn't settle within `ms`. The underlying work is left to finish on its own. */
1260
+ declare function withToolTimeout<T>(work: Promise<T>, ms: number, toolName: string): Promise<T>;
1078
1261
  /**
1079
1262
  * The provider-agnostic agent turn, reused by both the inline and durable runners.
1080
1263
  * It drives the model→tools→model iteration; the runner supplies the `step`/`awaitApproval`
@@ -1157,5 +1340,28 @@ declare function publishAgentRunFinished(payload: AgentRunFinished): void;
1157
1340
  declare function publishAgentRunFailed(payload: AgentRunFailed): void;
1158
1341
  declare function publishAgentDelegated(payload: AgentDelegated): void;
1159
1342
  declare function publishAgentRetrieved(payload: AgentRetrieved): void;
1343
+ /** Every event key declared on `ChannelRegistry['agent']` above — derived, not hand-copied. */
1344
+ type AgentDiagnosticEvent = keyof ChannelRegistry['agent'];
1345
+ /**
1346
+ * All 8 events on `ChannelRegistry['agent']`, in a stable order — handy for wiring subscribers
1347
+ * (mirrors nestjs-media's `MEDIA_DIAGNOSTIC_EVENTS`). A drift between this list and the registry is
1348
+ * a compile error in both directions: an extra/misspelled entry fails this array's own
1349
+ * `readonly AgentDiagnosticEvent[]` annotation immediately; a missing entry fails the
1350
+ * {@link AgentDiagnosticEventsCoverAllKeys} check below.
1351
+ */
1352
+ declare const AGENT_DIAGNOSTIC_EVENTS: readonly AgentDiagnosticEvent[];
1353
+ /**
1354
+ * The telescope key for an agent diagnostics channel — `agent:<event>`. This is the key the
1355
+ * `@dudousxd/nestjs-diagnostics-telescope` generic bridge matches its `exclude` option against,
1356
+ * and the label its "Busiest events" panel shows. Distinct from the `aviary:agent:<event>` channel
1357
+ * name used on the wire. Mirrors `mediaDiagnosticKey`.
1358
+ */
1359
+ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
1360
+ /**
1361
+ * Compose the telescope key for an agent event, typed against {@link AgentDiagnosticEvent} so a
1362
+ * misspelled event is a compile error. Feed the result to `nestjsDiagnosticsTelescope({ exclude:
1363
+ * [...] })` to mute a noisy channel, e.g. `agentDiagnosticKey('message')`.
1364
+ */
1365
+ declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
1160
1366
 
1161
- export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MODEL, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_STORE, AGENT_TOOL_REGISTRY, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentGovernanceQueries, type AgentLoopDeps, type AgentLoopHooks, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentToolCallEvent, type AiToolCtx, type AppendMessageInput, type AttachmentStagingStore, type CostUsage, type CreateThreadInput, type CurrentModelPrice, type Decision, DefaultRolesPolicy, type EmbeddingProvider, type GovernanceRange, type GovernanceUsageInput, type MessageAttachment, type MessageRole, type MessageUsage, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type PageContext, type Passage, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, type RecordToolCallInput, type RecordUsageInput, type RerankOptions, type Reranker, type RetrieveOptions, type Retriever, type RolesPolicy, type SinkWriter, type StageAttachmentInput, type StoredMessage, type StreamError, type ThreadActivityRow, type ThreadDetail, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolDefinition, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, dayBoundsUtc, encodeStreamEvent, estimateCost, filterToolsByAllowList, filterToolsByRole, publishAgentDelegated, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentToolCall, runAgentLoop, seedModelPrices };
1367
+ 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_MODEL, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_STORE, AGENT_TOOL_REGISTRY, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentGovernanceQueries, type AgentLoopDeps, type AgentLoopHooks, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentToolCallEvent, type AiToolCtx, type AppendMessageInput, type AttachmentStagingStore, type CostUsage, type CreateThreadInput, type CurrentModelPrice, type Decision, DefaultRolesPolicy, type EmbeddingProvider, type GovernanceRange, type GovernanceUsageInput, type LlmStepEnvelope, type MessageAttachment, type MessageRole, type MessageUsage, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type PageContext, type Passage, type PendingApprovalRow, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RerankOptions, type Reranker, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, type RunErrorBreakdownRow, type RunMetrics, type RunTrendPoint, type SinkWriter, type StageAttachmentInput, type StoredMessage, type StreamError, type ThreadActivityRow, type ThreadDetail, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolDefinition, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type ToolStatRow, type ToolStepCtx, type ToolStepEnvelope, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, agentDiagnosticKey, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, dayBoundsUtc, encodeStreamEvent, estimateCost, filterToolsByAllowList, filterToolsByRole, publishAgentDelegated, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentToolCall, runAgentLoop, seedModelPrices, withToolTimeout };