@voicelayer/sdk 0.4.1 → 0.5.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.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { A as AgentDTO, a as AgentStatus, b as AgentEnvironment, c as AgentContext, P as Participant, C as CallInfo, d as ProcessSchemaDTO } from './text-session-BB0dLLH2.js';
2
- export { e as AgentTurnEvent, f as AudioProfile, g as AudioSurface, h as ChannelKind, D as DtmfEvent, i as DtmfHandler, E as EndCallControllerHandle, j as EndCallOutcome, F as FakeSessionAdapter, k as FloorControlConfig, I as InboundOptions, L as LK_AGENT_STATE_MAP, M as MemoryHandle, l as MetricsEvent, N as NON_BUSY_STATES, m as ParticipantId, n as ParticipantKind, o as ParticipantSet, p as ProcessSnapshot, R as RespondOptions, q as Room, r as RouteEntry, s as RoutingRule, t as RoutingSnapshot, u as RunTextSessionOptions, v as RunTextTranscriptOptions, S as SayOptions, w as SendDtmfOptions, x as SessionAdapter, y as SessionCapabilities, z as SessionErrorEvent, B as SessionEvent, G as SessionEventMap, H as SessionFactory, J as SessionFactoryInput, K as SessionOutbound, O as SessionState, Q as SpeechResult, T as SpeechTarget, U as StateChangeEvent, V as TextSession, W as TextTranscriptResult, X as TtsVoiceConfig, Y as TurnEvent, Z as Unsubscribe, _ as UserInputEvent, $ as UserStateEvent, a0 as UserTurn, a1 as applySpeechTurnHandling, a2 as dtmfCodeToDigit, a3 as dtmfDigitToCode, a4 as duck, a5 as mute, a6 as normalizeState, m as participantId, a7 as passthrough, a8 as runTextSession, a9 as runTextTranscript, aa as transform } from './text-session-BB0dLLH2.js';
1
+ import { A as AgentEnvironment, P as ProcessSchemaDTO, R as ReadinessProbe, a as AgentLifecycleEvent, b as AgentDTO, c as AgentEventEmitter, d as AgentContext, e as AgentConfig$1, f as ProcessField, M as ModelConfig, C as ConnectorInstance, g as ProviderFactory, S as STTProvider, T as TTSProvider, L as LLMProvider, h as RealtimeProvider, i as TurnDetectorProvider, V as VADProvider, j as ProcessDefinition, k as TriggerDefinition, H as HandoffConfig, l as MemoryConfig, m as ToolDefinition$1, n as SpeechConfig, o as ToolExecutor, p as HostLookup } from './text-session-Bf4Jni7H.js';
2
+ export { q as AgentEventListener, r as AgentTurnEvent, s as AudioProfile, t as AudioSurface, u as CallInfo, v as CallOutcomeSummary, w as ChannelKind, x as CompletionStrategy, y as ComplianceTag, z as ConsultationPolicy, D as DtmfEvent, B as DtmfHandler, E as EndCallControllerHandle, F as EndCallInfo, G as EndCallOutcome, I as EndCallPolicy, J as EndCallTrigger, K as EndpointingConfig, N as FakeSessionAdapter, O as FloorControlConfig, Q as InboundOptions, U as InferProcessData, W as InterruptionConfig, X as LK_AGENT_STATE_MAP, Y as MemoryHandle, Z as MemoryScope, _ as MetricsEvent, $ as NON_BUSY_STATES, a0 as Participant, a1 as ParticipantId, a2 as ParticipantKind, a3 as ParticipantSet, a4 as ParticipantsConfig, a5 as ProcessBackendAck, a6 as ProcessFieldType, a7 as ProcessSnapshot, a8 as ReadinessReport, a9 as ReadinessResult, aa as RespondOptions, ab as Room, ac as RouteEntry, ad as RoutingRule, ae as RoutingSnapshot, af as RunTextSessionOptions, ag as RunTextTranscriptOptions, ah as SayOptions, ai as SecurityConfig, aj as SendDtmfOptions, ak as SessionAdapter, al as SessionCapabilities, am as SessionErrorEvent, an as SessionEvent, ao as SessionEventMap, ap as SessionFactory, aq as SessionFactoryInput, ar as SessionOutbound, as as SessionState, at as ShorthandPrimitive, au as SpeechResult, av as SpeechTarget, aw as StateChangeEvent, ax as TextSession, ay as TextTranscriptResult, az as ToolInputShape, aA as TriggerAction, aB as TriggerCondition, aC as TtsVoiceConfig, aD as TurnEvent, aE as Unsubscribe, aF as UserInputEvent, aG as UserStateEvent, aH as UserTurn, aI as VoiceLayerAuthError, aJ as VoiceLayerError, aK as VoiceLayerHttpError, aL as VoiceLayerNetworkError, aM as VoiceLayerValidationError, aN as applySpeechTurnHandling, aO as asyncProbe, aP as defineProcess, aQ as dtmfCodeToDigit, aR as dtmfDigitToCode, aS as duck, aT as envProbe, aU as mute, aV as normalizeState, a1 as participantId, aW as passthrough, aX as runProbes, aY as runTextSession, aZ as runTextTranscript, a_ as transform, a$ as urlProbe } from './text-session-Bf4Jni7H.js';
3
3
  import { z, ZodType } from 'zod';
4
- import { OnQuery, BrainTransport } from './brain/index.js';
5
- export { BrainCallMetadata, BrainCapabilities, BrainChunk, BrainConfigError, BrainEndpointConfig, BrainMessage, BrainPubSub, BrainRequest, BrainRequestError, ConnectorChatModel, ConnectorChatModelOptions, ConnectorLLMOptions, IncomingBrainRequest, OnQueryContext, OnQueryResult, RedisBrainPubSub, SseDelta, TunnelBrainTransportOptions, assertPublicHttpsUrl, buildRedisBrainPubSub, callbackTransport, createConnectorLLM, httpBrainTransport, parseChatCompletionSse, runBrainRequest, tunnelBrainTransport } from './brain/index.js';
4
+ import { O as OnQuery, B as BrainTransport } from './types-KqrAfY85.js';
5
+ export { a as BrainCallMetadata, b as BrainCapabilities, c as BrainChunk, d as BrainMessage, e as BrainRequest, f as OnQueryContext, g as OnQueryResult } from './types-KqrAfY85.js';
6
+ export { BrainConfigError, BrainEndpointConfig, BrainPubSub, BrainRequestError, ConnectorChatModel, ConnectorChatModelOptions, ConnectorLLMOptions, IncomingBrainRequest, RedisBrainPubSub, SseDelta, TunnelBrainTransportOptions, assertPublicHttpsUrl, buildRedisBrainPubSub, callbackTransport, createConnectorLLM, httpBrainTransport, parseChatCompletionSse, runBrainRequest, tunnelBrainTransport } from './brain/index.js';
6
7
  import '@livekit/agents';
7
8
  import 'openai';
8
9
  import 'ioredis';
@@ -141,12 +142,12 @@ declare const CallPlan: z.ZodObject<{
141
142
  description: z.ZodOptional<z.ZodString>;
142
143
  }, "strip", z.ZodTypeAny, {
143
144
  description?: string | undefined;
144
- e164?: string | undefined;
145
145
  displayName?: string | undefined;
146
+ e164?: string | undefined;
146
147
  }, {
147
148
  description?: string | undefined;
148
- e164?: string | undefined;
149
149
  displayName?: string | undefined;
150
+ e164?: string | undefined;
150
151
  }>;
151
152
  draftConfig: z.ZodDefault<z.ZodObject<{
152
153
  name: z.ZodOptional<z.ZodString>;
@@ -735,8 +736,8 @@ declare const CallPlan: z.ZodObject<{
735
736
  objective: string;
736
737
  callee: {
737
738
  description?: string | undefined;
738
- e164?: string | undefined;
739
739
  displayName?: string | undefined;
740
+ e164?: string | undefined;
740
741
  };
741
742
  draftConfig: {
742
743
  name?: string | undefined;
@@ -869,8 +870,8 @@ declare const CallPlan: z.ZodObject<{
869
870
  objective: string;
870
871
  callee: {
871
872
  description?: string | undefined;
872
- e164?: string | undefined;
873
873
  displayName?: string | undefined;
874
+ e164?: string | undefined;
874
875
  };
875
876
  escalation: {
876
877
  onUncertainty?: "consult_host" | "ask_callee" | "fallback_phrase" | undefined;
@@ -997,8 +998,8 @@ declare const CallPlan: z.ZodObject<{
997
998
  }>;
998
999
  type CallPlan = z.infer<typeof CallPlan>;
999
1000
 
1000
- declare const MemoryScope$1: z.ZodEnum<["call", "caller", "account", "platform"]>;
1001
- type MemoryScope$1 = z.infer<typeof MemoryScope$1>;
1001
+ declare const MemoryScope: z.ZodEnum<["call", "caller", "account", "platform"]>;
1002
+ type MemoryScope = z.infer<typeof MemoryScope>;
1002
1003
  declare const RelevantContext: z.ZodObject<{
1003
1004
  call: z.ZodRecord<z.ZodString, z.ZodUnknown>;
1004
1005
  caller: z.ZodRecord<z.ZodString, z.ZodUnknown>;
@@ -1027,39 +1028,39 @@ declare const ResolveCallerResponse: z.ZodObject<{
1027
1028
  updatedAt: z.ZodString;
1028
1029
  }, "strip", z.ZodTypeAny, {
1029
1030
  id: string;
1031
+ displayName: string | null;
1030
1032
  projectId: string;
1031
1033
  createdAt: string;
1032
1034
  updatedAt: string;
1033
1035
  metadata: Record<string, unknown>;
1034
- displayName: string | null;
1035
1036
  externalKey: string;
1036
1037
  }, {
1037
1038
  id: string;
1039
+ displayName: string | null;
1038
1040
  projectId: string;
1039
1041
  createdAt: string;
1040
1042
  updatedAt: string;
1041
1043
  metadata: Record<string, unknown>;
1042
- displayName: string | null;
1043
1044
  externalKey: string;
1044
1045
  }>;
1045
1046
  }, "strip", z.ZodTypeAny, {
1046
1047
  caller: {
1047
1048
  id: string;
1049
+ displayName: string | null;
1048
1050
  projectId: string;
1049
1051
  createdAt: string;
1050
1052
  updatedAt: string;
1051
1053
  metadata: Record<string, unknown>;
1052
- displayName: string | null;
1053
1054
  externalKey: string;
1054
1055
  };
1055
1056
  }, {
1056
1057
  caller: {
1057
1058
  id: string;
1059
+ displayName: string | null;
1058
1060
  projectId: string;
1059
1061
  createdAt: string;
1060
1062
  updatedAt: string;
1061
1063
  metadata: Record<string, unknown>;
1062
- displayName: string | null;
1063
1064
  externalKey: string;
1064
1065
  };
1065
1066
  }>;
@@ -1076,58 +1077,7 @@ declare const DeleteCallerResponse: z.ZodObject<{
1076
1077
  }>;
1077
1078
  type DeleteCallerResponse = z.infer<typeof DeleteCallerResponse>;
1078
1079
 
1079
- /** Policy embedded in AgentConfig — caps + UX wording. */
1080
- declare const ConsultationPolicy: z.ZodObject<{
1081
- enabled: z.ZodDefault<z.ZodBoolean>;
1082
- defaultTimeoutMs: z.ZodDefault<z.ZodNumber>;
1083
- maxTimeoutMs: z.ZodDefault<z.ZodNumber>;
1084
- maxCumulativeHoldMs: z.ZodDefault<z.ZodNumber>;
1085
- holdPhrase: z.ZodDefault<z.ZodString>;
1086
- fallbackPhrase: z.ZodDefault<z.ZodString>;
1087
- callEndFallback: z.ZodDefault<z.ZodString>;
1088
- urgencyOverrides: z.ZodOptional<z.ZodObject<{
1089
- low: z.ZodOptional<z.ZodNumber>;
1090
- normal: z.ZodOptional<z.ZodNumber>;
1091
- high: z.ZodOptional<z.ZodNumber>;
1092
- }, "strip", z.ZodTypeAny, {
1093
- low?: number | undefined;
1094
- high?: number | undefined;
1095
- normal?: number | undefined;
1096
- }, {
1097
- low?: number | undefined;
1098
- high?: number | undefined;
1099
- normal?: number | undefined;
1100
- }>>;
1101
- }, "strip", z.ZodTypeAny, {
1102
- enabled: boolean;
1103
- defaultTimeoutMs: number;
1104
- maxTimeoutMs: number;
1105
- maxCumulativeHoldMs: number;
1106
- holdPhrase: string;
1107
- fallbackPhrase: string;
1108
- callEndFallback: string;
1109
- urgencyOverrides?: {
1110
- low?: number | undefined;
1111
- high?: number | undefined;
1112
- normal?: number | undefined;
1113
- } | undefined;
1114
- }, {
1115
- enabled?: boolean | undefined;
1116
- defaultTimeoutMs?: number | undefined;
1117
- maxTimeoutMs?: number | undefined;
1118
- maxCumulativeHoldMs?: number | undefined;
1119
- holdPhrase?: string | undefined;
1120
- fallbackPhrase?: string | undefined;
1121
- callEndFallback?: string | undefined;
1122
- urgencyOverrides?: {
1123
- low?: number | undefined;
1124
- high?: number | undefined;
1125
- normal?: number | undefined;
1126
- } | undefined;
1127
- }>;
1128
- type ConsultationPolicy = z.infer<typeof ConsultationPolicy>;
1129
-
1130
- declare const AgentConfig$1: z.ZodObject<{
1080
+ declare const AgentConfig: z.ZodObject<{
1131
1081
  id: z.ZodString;
1132
1082
  projectId: z.ZodString;
1133
1083
  name: z.ZodString;
@@ -1659,673 +1609,17 @@ declare const AgentConfig$1: z.ZodObject<{
1659
1609
  description?: string | undefined;
1660
1610
  }[] | undefined;
1661
1611
  }>;
1662
- type AgentConfig$1 = z.infer<typeof AgentConfig$1>;
1612
+ type AgentConfig = z.infer<typeof AgentConfig>;
1663
1613
 
1664
- declare const AgentEndReason: z.ZodEnum<["flow_boot:schema_fetch_failed" | "flow_boot:no_process_schema" | "flow_boot:missing_agent_id" | "flow_boot:no_api_key", ...("flow_boot:schema_fetch_failed" | "flow_boot:no_process_schema" | "flow_boot:missing_agent_id" | "flow_boot:no_api_key")[]]>;
1614
+ declare const AgentEndReason: z.ZodEnum<["flow_boot:schema_fetch_failed" | "flow_boot:no_process_schema" | "flow_boot:missing_agent_id" | "flow_boot:no_api_key" | "flow_boot:worker_identity_refused", ...("flow_boot:schema_fetch_failed" | "flow_boot:no_process_schema" | "flow_boot:missing_agent_id" | "flow_boot:no_api_key" | "flow_boot:worker_identity_refused")[]]>;
1665
1615
  type AgentEndReason = z.infer<typeof AgentEndReason>;
1666
1616
 
1667
- interface ReadinessResult {
1668
- readonly ok: boolean;
1669
- /** Human-readable explanation when ok=false. Surfaced in metadata. */
1670
- readonly detail?: string;
1671
- }
1672
- interface ReadinessProbe {
1673
- readonly name: string;
1674
- check(): Promise<ReadinessResult>;
1675
- }
1676
- /** Aggregate result the SDK records in metadata.readiness. */
1677
- interface ReadinessReport {
1678
- readonly probe: string;
1679
- readonly ok: boolean;
1680
- readonly detail?: string;
1681
- }
1682
- /**
1683
- * Run all probes in parallel. A probe that throws is reported as not-ok with
1684
- * the error message as detail; one bad probe never sinks the others.
1685
- */
1686
- declare function runProbes(probes: readonly ReadinessProbe[]): Promise<ReadinessReport[]>;
1687
- /** Probe that passes iff process.env[name] is non-empty after trimming. */
1688
- declare function envProbe(name: string): ReadinessProbe;
1689
- /**
1690
- * Probe wrapping an arbitrary async function. Returning a value (or void)
1691
- * means ok; throwing means not-ok. Compact escape hatch — promote to a real
1692
- * probe class when reuse appears.
1693
- */
1694
- declare function asyncProbe(name: string, fn: () => Promise<unknown>): ReadinessProbe;
1695
- /**
1696
- * Probe that fetches a URL and considers any 2xx/3xx response ok. Useful for
1697
- * upstream health-checks (e.g. an LLM gateway's /healthz). Default 3s timeout.
1698
- */
1699
- declare function urlProbe(name: string, url: string, opts?: {
1700
- timeoutMs?: number;
1701
- method?: 'GET' | 'HEAD';
1702
- }): ReadinessProbe;
1703
-
1704
- declare class VoiceLayerError extends Error {
1705
- readonly name: string;
1706
- }
1707
- declare class VoiceLayerAuthError extends VoiceLayerError {
1708
- readonly status: number;
1709
- readonly name: string;
1710
- constructor(message: string, status: number);
1711
- }
1712
- declare class VoiceLayerNetworkError extends VoiceLayerError {
1713
- readonly name: string;
1714
- readonly cause?: unknown;
1715
- constructor(message: string, cause?: unknown);
1716
- }
1717
- declare class VoiceLayerValidationError extends VoiceLayerError {
1718
- readonly issues: unknown;
1719
- readonly name: string;
1720
- constructor(message: string, issues: unknown);
1721
- }
1722
- declare class VoiceLayerHttpError extends VoiceLayerError {
1723
- readonly status: number;
1724
- readonly body: unknown;
1725
- readonly name: string;
1726
- constructor(message: string, status: number, body: unknown);
1727
- }
1728
-
1729
- type AgentLifecycleEvent = {
1730
- type: 'registered';
1731
- agent: AgentDTO;
1732
- } | {
1733
- type: 'readiness';
1734
- report: readonly ReadinessReport[];
1735
- allOk: boolean;
1736
- } | {
1737
- type: 'heartbeat';
1738
- agent: AgentDTO;
1739
- } | {
1740
- type: 'heartbeat_error';
1741
- error: VoiceLayerError | Error;
1742
- consecutiveFailures: number;
1743
- willRetry: boolean;
1744
- } | {
1745
- type: 'heartbeat_recovered';
1746
- afterFailures: number;
1747
- } | {
1748
- type: 're_registered';
1749
- agent: AgentDTO;
1750
- reason: 'agent_not_found';
1751
- } | {
1752
- type: 'status_changed';
1753
- status: AgentStatus;
1754
- detail?: string;
1755
- } | {
1756
- type: 'metadata_updated';
1757
- } | {
1758
- type: 'deregistered';
1759
- reason: 'manual' | 'signal';
1760
- };
1761
- type AgentEventListener = (event: AgentLifecycleEvent) => void;
1762
- interface AgentEventEmitter {
1763
- on(listener: AgentEventListener): () => void;
1764
- /** @internal — used by the lifecycle to publish events. */
1765
- emit(event: AgentLifecycleEvent): void;
1766
- }
1767
-
1768
- /** Primitive field types accepted in a process definition. */
1769
- type ProcessFieldType = 'string' | 'string[]' | 'number' | 'boolean' | 'datetime' | 'email' | 'phone';
1770
- interface ProcessField {
1771
- readonly type: ProcessFieldType;
1772
- readonly required?: boolean;
1773
- /** Regex pattern for `string` / `string[]` items. */
1774
- readonly pattern?: RegExp;
1775
- /** Inclusive lower bound on a number or array length. */
1776
- readonly min?: number;
1777
- /** Inclusive upper bound on a number or array length. */
1778
- readonly max?: number;
1779
- /** One of N — restricts the captured value to this set. */
1780
- readonly enum?: readonly string[];
1781
- /** Override the auto-generated prompt for capturing this field. */
1782
- readonly ask?: string;
1783
- /** Override the field-extraction hint shown to the LLM. */
1784
- readonly extract?: string;
1785
- }
1786
- type CompletionStrategy = 'all-required-captured' | 'all-captured' | {
1787
- custom: (data: Record<string, unknown>, ctx: AgentContext) => boolean | Promise<boolean>;
1788
- };
1789
- interface ProcessBackendAck {
1790
- /** URL to POST captured data to. The call cannot complete until this 2xx's. */
1791
- readonly url: string;
1792
- readonly timeoutMs?: number;
1793
- readonly headers?: Readonly<Record<string, string>>;
1794
- }
1795
- interface ProcessDefinition<T extends Record<string, ProcessField> = Record<string, ProcessField>> {
1796
- /** Field schema. Order is preserved when the SDK auto-asks for fields. */
1797
- readonly collect: T;
1798
- /** When the call can end. Defaults to 'all-required-captured'. */
1799
- readonly completeWhen?: CompletionStrategy;
1800
- /** Optional external system that must ACK before completion. */
1801
- readonly backendAck?: ProcessBackendAck;
1802
- /** Fires once all completion conditions are met. */
1803
- readonly onComplete?: (data: InferProcessData<T>, ctx: AgentContext) => Promise<void> | void;
1804
- /** Fires whenever a field is captured (good for live CRM updates). */
1805
- readonly onField?: <K extends keyof T>(field: K, value: InferFieldValue<T[K]>, ctx: AgentContext) => Promise<void> | void;
1806
- }
1807
- /** Inferred TS type for the data bag a process produces. */
1808
- type InferProcessData<T extends Record<string, ProcessField>> = {
1809
- [K in keyof T]: T[K]['required'] extends true ? InferFieldValue<T[K]> : InferFieldValue<T[K]> | undefined;
1810
- };
1811
- type InferFieldValue<F extends ProcessField> = F['type'] extends 'string' ? string : F['type'] extends 'string[]' ? string[] : F['type'] extends 'number' ? number : F['type'] extends 'boolean' ? boolean : F['type'] extends 'datetime' ? Date : F['type'] extends 'email' ? string : F['type'] extends 'phone' ? string : never;
1812
- type TriggerCondition = RegExp | `signal:${string}` | ((text: string, ctx: AgentContext) => boolean | Promise<boolean>);
1813
- type TriggerAction = 'handoff' | 'endCall' | {
1814
- say: string;
1815
- } | {
1816
- run: (ctx: AgentContext) => Promise<void> | void;
1817
- }
1818
- /** Jump the flow-graph cursor to a node id. Only meaningful under the graph
1819
- * interpreter (the flat goals+rails path has no cursor and ignores it). */
1820
- | {
1821
- goto: string;
1822
- };
1823
- interface TriggerDefinition {
1824
- readonly on: TriggerCondition;
1825
- readonly then: TriggerAction;
1826
- /** If set, the trigger only fires while the named field is uncaptured. */
1827
- readonly onlyWhile?: string;
1828
- }
1829
- interface HandoffConfig {
1830
- /** Default human number when a trigger says { then: 'handoff' }. */
1831
- readonly fallback: string;
1832
- /** Map signal/trigger names to specific destinations. */
1833
- readonly routes?: Readonly<Record<string, string>>;
1834
- /** Build the briefing text passed to the human agent (or PSTN whisper). */
1835
- readonly briefing?: (args: {
1836
- readonly data: Record<string, unknown>;
1837
- readonly transcript: TranscriptHandle;
1838
- readonly call: AgentContext['call'];
1839
- }) => string | Promise<string>;
1840
- /**
1841
- * 'warm' (default) dials the human into the room as a conference, lets the
1842
- * agent brief them live, then drops the agent — caller + human stay
1843
- * connected. 'cold' is a blind SIP REFER: the caller is transferred away
1844
- * immediately. Warm falls back to cold when no outbound trunk is configured.
1845
- */
1846
- readonly mode?: 'warm' | 'cold';
1847
- }
1848
- interface TranscriptHandle {
1849
- /** Last N turns as `speaker: text` lines. */
1850
- tail(n: number): string;
1851
- full(): string;
1852
- }
1853
- /**
1854
- * Memory scope. `'participant'` and `'caller'` are synonyms — `'caller'`
1855
- * is the historical name from the 1:1 era; new code should prefer
1856
- * `'participant'`, which makes the multi-party semantics explicit.
1857
- */
1858
- type MemoryScope = 'call' | 'caller' | 'participant' | 'account' | 'platform';
1859
- interface MemoryConfig {
1860
- /** Which scope to persist to. Defaults to 'caller'. */
1861
- readonly scope?: MemoryScope;
1862
- readonly retentionDays?: number;
1863
- /** Fields auto-redacted on write. Recognized: ssn, dob, email, phone, ccn. */
1864
- readonly piiFields?: readonly string[];
1865
- /** Opt in to cross-tenant aggregate memory (anonymized). */
1866
- readonly platformOptIn?: boolean;
1867
- }
1868
- /**
1869
- * Multi-participant configuration. Optional — when omitted, the agent runs
1870
- * in 1:1 mode (one human + one agent) and the SDK still populates
1871
- * `ctx.room.participants` so participant-aware code paths work.
1872
- */
1873
- interface ParticipantsConfig {
1874
- /**
1875
- * Fires when a human participant joins the room. In 1:1 calls this
1876
- * fires once at session start for the caller. In multi-party calls it
1877
- * fires per join.
1878
- */
1879
- readonly onJoin?: (participant: Participant, ctx: AgentContext) => Promise<void> | void;
1880
- /** Fires when a participant disconnects (hangup, transfer, kick). */
1881
- readonly onLeave?: (participant: Participant, ctx: AgentContext) => Promise<void> | void;
1882
- /**
1883
- * Synchronously enrich a participant's attribute bag before `onJoin`
1884
- * fires. Useful for phone-number → language lookups, etc. The returned
1885
- * map is merged into `participant.attributes`.
1886
- */
1887
- readonly attributes?: (participant: Participant) => Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>;
1888
- /**
1889
- * Reject participants beyond this count. Default: unlimited. The cap
1890
- * is enforced by the worker when wiring participant lifecycle.
1891
- */
1892
- readonly max?: number;
1893
- }
1894
- /**
1895
- * A connector instance. Created by per-system factories like `salesforce()`,
1896
- * `twilio()`, etc. The factory returns an opaque handle that the SDK wires
1897
- * into `ctx.connectors` and (when `expose: true`) into the LLM tool list.
1898
- */
1899
- interface ConnectorInstance<TName extends string = string, TApi = unknown> {
1900
- readonly __connector: true;
1901
- readonly name: TName;
1902
- readonly api: TApi;
1903
- /** If true, every method on `api` becomes an LLM-callable tool. */
1904
- readonly expose?: boolean;
1905
- }
1906
- type ComplianceTag = 'tcpa' | 'hipaa' | 'pci' | 'gdpr' | 'soc2';
1907
- /**
1908
- * Duck-typed pipeline component markers. The SDK never inspects these — they
1909
- * are passed through to LiveKit's AgentSession as-is. Three ways to satisfy:
1910
- *
1911
- * 1. SDK factory: `deepgram.tts({ model: 'aura-2' })`
1912
- * 2. Wrapped LK: `wrap(new TTS({...}), { trace: true })`
1913
- * 3. User-built: class MyTTS extends BaseTTS { ... } // BaseTTS
1914
- * // re-exported
1915
- * // from the SDK
1916
- *
1917
- * Anything implementing the duck-type — even a plain object — is accepted.
1918
- */
1919
- interface STTProvider {
1920
- readonly __vlPipeline?: 'stt';
1921
- }
1922
- interface LLMProvider {
1923
- readonly __vlPipeline?: 'llm';
1924
- }
1925
- interface TTSProvider {
1926
- readonly __vlPipeline?: 'tts';
1927
- }
1928
- interface VADProvider {
1929
- readonly __vlPipeline?: 'vad';
1930
- }
1931
- interface TurnDetectorProvider {
1932
- readonly __vlPipeline?: 'turn';
1933
- }
1934
- /**
1935
- * Speech-to-speech / realtime model marker (OpenAI Realtime, Gemini Live).
1936
- * A realtime model handles STT + LLM + TTS + turn-taking server-side, so when
1937
- * `models.realtime` is set the SDK builds the AgentSession around it and
1938
- * ignores the stt/llm/tts slots.
1939
- */
1940
- interface RealtimeProvider {
1941
- readonly __vlPipeline?: 'realtime';
1942
- }
1943
- /**
1944
- * Lazy form so users can pick a provider per call (e.g. by caller locale).
1945
- * The factory runs once per call, before AgentSession is constructed, so it
1946
- * receives the call envelope (callerId, to, metadata) rather than the full
1947
- * AgentContext (which depends on AgentSession existing).
1948
- */
1949
- type ProviderFactory<T> = (call: CallInfo) => T | Promise<T>;
1950
- interface ModelConfig {
1951
- /**
1952
- * String form: 'openai/gpt-4o' (resolves via SDK defaults).
1953
- * Instance form: any LLMProvider (LK plugin, wrap()-ed, or user-built).
1954
- * Factory form: `(ctx) => provider` for per-call selection.
1955
- */
1956
- readonly llm?: string | LLMProvider | ProviderFactory<LLMProvider>;
1957
- readonly stt?: string | STTProvider | ProviderFactory<STTProvider>;
1958
- readonly tts?: string | TTSProvider | ProviderFactory<TTSProvider>;
1959
- /** VAD has no string form — always pass an instance or factory. */
1960
- readonly vad?: VADProvider | ProviderFactory<VADProvider>;
1961
- readonly turnDetector?: TurnDetectorProvider | ProviderFactory<TurnDetectorProvider>;
1962
- /**
1963
- * Speech-to-speech / realtime model. When set, the STT→LLM→TTS pipeline is
1964
- * bypassed: the realtime model drives the whole turn. No string form — pass
1965
- * an instance (`openai.realtime({ voice: 'alloy' })`) or a per-call factory.
1966
- */
1967
- readonly realtime?: RealtimeProvider | ProviderFactory<RealtimeProvider>;
1968
- /** Spoken language; defaults to 'en-US'. Used by string-form defaults. */
1969
- readonly language?: string;
1970
- }
1971
- /**
1972
- * Answering-machine detection mode for outbound calls. Mirrors
1973
- * `OutboundConfig.amd` in @voicelayer/agent-spec.
1974
- *
1975
- * 'off' — never run AMD; treat every answer as a human.
1976
- * 'detect' — leave the voicemail message (or hang up) the moment
1977
- * a machine greeting is recognised.
1978
- * 'detectMessageEnd' — recognise the machine, then wait for the greeting to
1979
- * finish (an explicit "after the tone"-style cue or the
1980
- * greeting going quiet) before leaving the message.
1981
- */
1982
- type AmdMode = 'off' | 'detect' | 'detectMessageEnd';
1983
- /**
1984
- * Outbound-only behavior. AMD never runs on inbound calls (the runtime gates
1985
- * on the dispatch-metadata `direction`), so these knobs are inert unless the
1986
- * call was placed via the outbound path.
1987
- */
1988
- interface OutboundCallConfig {
1989
- /** Answering-machine detection mode. Defaults to 'off'. */
1990
- readonly amd?: AmdMode;
1991
- /**
1992
- * Spoken (via TTS) when a machine is detected. When unset, the agent hangs
1993
- * up on detection instead of leaving a message.
1994
- */
1995
- readonly voicemailScript?: string;
1996
- }
1997
- /**
1998
- * Barge-in tuning. The pipeline allows interruptions by default (LK defaults:
1999
- * any speech ≥500ms cuts the agent off). These knobs tune that behavior per
2000
- * agent WITHOUT switching to puppet/hostControlled mode — e.g. a senior-living
2001
- * help desk wants `minWords: 2` so backchannels ("mm-hm", "okay") don't
2002
- * truncate the agent mid-sentence, while a fast-paced escalation desk keeps
2003
- * the zero-word default. Set `enabled: false` to make the agent
2004
- * non-interruptible (kiosk / broadcast announcements).
2005
- */
2006
- interface InterruptionConfig {
2007
- /** Allow the caller to barge in over agent speech. Default true. */
2008
- readonly enabled?: boolean;
2009
- /** Words the caller must say before it counts as an interruption. Default 0
2010
- * (any speech interrupts). 2–3 filters out backchannels. */
2011
- readonly minWords?: number;
2012
- /** Minimum caller speech duration (ms) to count as an interruption. Default 500. */
2013
- readonly minDuration?: number;
2014
- }
2015
- /**
2016
- * End-of-turn detection tuning: how long the pipeline waits after the caller
2017
- * stops speaking before treating the turn as finished. Raise `minDelay` for
2018
- * callers who pause mid-thought (e.g. elderly speakers); lower it for
2019
- * fast-paced lines.
2020
- */
2021
- interface EndpointingConfig {
2022
- /** Minimum silence (ms) before the caller's turn is considered done. Default 500. */
2023
- readonly minDelay?: number;
2024
- /** Hard ceiling (ms) after which the turn ends regardless. Default 3000. */
2025
- readonly maxDelay?: number;
2026
- }
2027
- /**
2028
- * Speech polish. `pronunciations` rewrites brand names / acronyms / jargon to
2029
- * a spoken form before TTS (e.g. `{ VoiceLayer: 'Voice Layer', API: 'A P I' }`)
2030
- * via applyPronunciations(). `backgroundAudio` plays ambient room tone under
2031
- * the agent so silence feels less dead (a URL or a named preset).
2032
- * `interruption` + `endpointing` tune barge-in and turn-taking per agent.
2033
- */
2034
- interface SpeechConfig {
2035
- readonly pronunciations?: Readonly<Record<string, string>>;
2036
- readonly backgroundAudio?: string | {
2037
- readonly url?: string;
2038
- readonly volume?: number;
2039
- };
2040
- readonly interruption?: InterruptionConfig;
2041
- readonly endpointing?: EndpointingConfig;
2042
- }
2043
- /** What caused the call to end. Surfaced to `endCall.onEnd` + logs. */
2044
- type EndCallTrigger =
2045
- /** The LLM invoked the built-in `end_call` tool. */
2046
- 'tool'
2047
- /** An external controller (MCP host) sent a `hangup` command. */
2048
- | 'host'
2049
- /** The dead-air backstop fired (`idleHangupMs` of silence while idle). */
2050
- | 'idle'
2051
- /** The hard per-call ceiling fired (`maxCallDurationMs` elapsed). */
2052
- | 'max_duration'
2053
- /** The last non-agent participant left the room. */
2054
- | 'participant-left'
2055
- /** A flow/graph run finished and asked to hang up. */
2056
- | 'flow'
2057
- /** The realtime engine closed / disconnected under the session. */
2058
- | 'engine-closed'
2059
- /** `ctx.endCall()` called directly from user code. */
2060
- | 'user';
2061
- /** Passed to `endCall.onEnd` describing the teardown about to happen. */
2062
- interface EndCallInfo {
2063
- /** Why the call is ending (e.g. the `end_call` tool's `reason`). */
2064
- readonly reason?: string;
2065
- /** What triggered the hang-up. */
2066
- readonly trigger: EndCallTrigger;
2067
- /** The teardown strategy that will run (after the policy is resolved). */
2068
- readonly teardown: 'room' | 'agent';
2069
- }
2070
- /**
2071
- * Controls how the agent ENDS a call. The SDK — not the agent prompt or an
2072
- * external puppet driver — owns teardown, so a hang-up is reliable even when
2073
- * the realtime transport has died mid-wrap.
2074
- *
2075
- * Defaults are "best case" and active without opt-in: the whole LiveKit room
2076
- * is deleted (which drops the SIP/PSTN leg too, so the carrier gets a BYE),
2077
- * a guarantee-watchdog re-attempts teardown if the first try doesn't land, and
2078
- * a dead-air backstop hangs up after the line has been silent too long. Every
2079
- * knob is overridable; set a field to `false` to disable that guard.
2080
- */
2081
- interface EndCallPolicy {
2082
- /**
2083
- * Teardown strategy. `'room'` (default) deletes the LiveKit room via the
2084
- * room service — this removes the SIP participant too, so the call actually
2085
- * disconnects on the carrier side. `'agent'` only drops the agent's own
2086
- * participant (leaves any SIP leg up); use it only when something else owns
2087
- * the room lifecycle.
2088
- */
2089
- readonly teardown?: 'room' | 'agent';
2090
- /**
2091
- * After a hang-up is requested, keep re-attempting teardown until the room
2092
- * is actually gone or this many ms elapse. Guards against a teardown call
2093
- * that silently doesn't land (transport race, transient room-service error).
2094
- * Default 4000. `false` disables (single best-effort attempt).
2095
- */
2096
- readonly guaranteeMs?: number | false;
2097
- /**
2098
- * Dead-air backstop: when the agent is idle (waiting on the caller) and the
2099
- * line stays silent — no agent turn, no caller speech — for this many ms,
2100
- * end the call. Catches a wedged session whose normal `end_call` never ran.
2101
- * Only armed while the agent is idle, so it never interrupts agent speech or
2102
- * a long tool call. Default 20000. `false` disables.
2103
- */
2104
- readonly idleHangupMs?: number | false;
2105
- /**
2106
- * Hard call ceiling: hang up once the call has run this many ms from when
2107
- * the session becomes ready, regardless of activity. Catches runaway calls
2108
- * that never end naturally (stuck loops, hijacked keys dialing premium
2109
- * numbers). Fires with trigger `'max_duration'`. Default 3600000 (60
2110
- * minutes). `false` disables.
2111
- */
2112
- readonly maxCallDurationMs?: number | false;
2113
- /**
2114
- * Hook fired the moment a hang-up is decided, just before teardown — for
2115
- * every trigger (tool, host, idle, max_duration, engine-closed, …). Return
2116
- * `false` to take over teardown yourself (the SDK then does nothing — the
2117
- * call will NOT end unless you end it). Returning anything else (or nothing)
2118
- * runs the default teardown. Throwing is caught + logged, then the default
2119
- * teardown still runs (safe by default).
2120
- *
2121
- * EXCEPT a host hangup (`trigger: 'host'` — MCP `call_hangup`): the host is
2122
- * the operator, so the hook is told (with the host's reason) and given 2
2123
- * seconds, but can't keep the call open; the room is always deleted, even
2124
- * after an earlier hang-up was vetoed and whatever `teardown` says (0.2.0).
2125
- */
2126
- readonly onEnd?: (ctx: AgentContext, info: EndCallInfo) => boolean | void | Promise<boolean | void>;
2127
- }
2128
- type ShorthandPrimitive$1 = 'string' | 'number' | 'boolean';
2129
- type ToolInputShape$1 = Record<string, ShorthandPrimitive$1> | z.ZodTypeAny;
2130
- interface ToolDefinition$1<I = unknown, R = unknown> {
2131
- readonly description: string;
2132
- readonly input: ToolInputShape$1;
2133
- readonly run: (input: I, ctx: AgentContext) => Promise<R> | R;
2134
- /**
2135
- * Capability this tool requires. Action Guard hard-blocks the call if not
2136
- * declared (PRD §B.5 — "no soft failures, ever"). Defaults to
2137
- * `tool.<name>` when omitted; passing a domain-scoped string
2138
- * (`crm.write`, `payment.refund`) lets multiple tools share a capability
2139
- * for centralised policy.
2140
- */
2141
- readonly capability?: string;
2142
- }
2143
- /**
2144
- * Optional security adapters. The SDK always enforces the local-only synchronous
2145
- * guards (PRD §B.2 input regex, §B.3 system seal + PII tokenisation, §B.4
2146
- * markdown strip + PII partial-mask, §B.5 capability check). Setting any of
2147
- * these augments the local floor with external services. Each is independently
2148
- * optional — none has to be live for the floor guards to function.
2149
- *
2150
- * URLs can also come from env (`SECURITY_LLM_GUARD_URL`,
2151
- * `SECURITY_PRESIDIO_ANALYZER_URL`, `SECURITY_PRESIDIO_ANONYMIZER_URL`,
2152
- * `SECURITY_OPA_URL`, `SECURITY_OPA_DECISION_PATH`); explicit config wins.
2153
- */
2154
- interface SecurityConfig {
2155
- /** Disable the primitive entirely. Use only for tests. Production code MUST NOT set this. */
2156
- readonly disabled?: boolean;
2157
- /** External LLM-Guard adapter for richer injection detection. */
2158
- readonly llmGuardUrl?: string;
2159
- /** Presidio analyzer URL for PII detection beyond local regex. */
2160
- readonly presidioAnalyzerUrl?: string;
2161
- /** Presidio anonymizer URL — if set, output is redacted before TTS. */
2162
- readonly presidioAnonymizerUrl?: string;
2163
- /** OPA decision API base URL (e.g. `http://opa:8181`). */
2164
- readonly opaUrl?: string;
2165
- /** OPA decision path (e.g. `voicelayer/security/decision`). */
2166
- readonly opaDecisionPath?: string;
2167
- /** Per-request timeout for security adapter calls. */
2168
- readonly adapterTimeoutMs?: number;
2169
- }
2170
- /**
2171
- * Marks an agent as a *flow-runtime* worker: instead of a fixed process it
2172
- * resolves the deployed flow from the dispatch metadata (`agentId`) at call
2173
- * time, fetches that agent's compiled process_schema, and boots from it. One
2174
- * process serves many flows (the shared pool). See defineFlowRuntime().
2175
- */
2176
- interface FlowRuntimeConfig {
2177
- /** Prepended to the flow's compiled say/confirm prompt fragments. */
2178
- readonly basePrompt?: string;
2179
- /** Spoken (verbatim) before hanging up when a flow call's schema cannot be
2180
- * loaded. A failed flow boot NEVER silently answers as a generic assistant. */
2181
- readonly bootFailureMessage?: string;
2182
- }
2183
- /** Output content-moderation guard config (P5). Mirrors @voicelayer/plugin-guard's
2184
- * GuardConfig; the pure inspector lives in runtime/guard.ts. */
2185
- interface GuardConfig {
2186
- /** Flag content longer than this many characters. Default 8000. */
2187
- readonly maxLength?: number;
2188
- /** Substrings that flag content (case-insensitive). Default none. */
2189
- readonly bannedSubstrings?: readonly string[];
2190
- }
2191
- interface AgentConfig<TProcess extends Record<string, ProcessField> = Record<string, ProcessField>> {
2192
- /** Lowercase, kebab-case identifier. Used for LiveKit dispatch + presence. */
2193
- readonly name: string;
2194
- /** System prompt the LLM sees. */
2195
- readonly prompt: string;
2196
- /** Fixed opening line, spoken instantly via TTS at the start of the default
2197
- * conversation flow — NO LLM. Eliminates the dead air of an LLM-generated
2198
- * greeting (the first generateReply must process the whole system prompt).
2199
- * Absent → the SDK falls back to an LLM-generated greeting. */
2200
- readonly greeting?: string;
2201
- /** Agent-level Instructions (the routing/decision layer): plain-language guidance
2202
- * for WHEN the agent acts, appended below the persona under a `# Routing` header.
2203
- * Interpolated with {{ }} by the process runtime. Optional. */
2204
- readonly routingInstructions?: string;
2205
- /** Capability tags surfaced in the dashboard. */
2206
- readonly capabilities?: readonly string[];
2207
- /** Semantic version. Defaults to AGENT_VERSION env or '0.0.0'. */
2208
- readonly version?: string;
2209
- /** dev / stg / prd. Defaults to AGENT_ENVIRONMENT env or 'dev'. */
2210
- readonly environment?: AgentEnvironment;
2211
- readonly process?: ProcessDefinition<TProcess>;
2212
- readonly triggers?: Readonly<Record<string, TriggerDefinition>>;
2213
- readonly handoff?: HandoffConfig;
2214
- readonly memory?: MemoryConfig;
2215
- readonly participants?: ParticipantsConfig;
2216
- readonly connectors?: Readonly<Record<string, ConnectorInstance>>;
2217
- readonly compliance?: readonly ComplianceTag[];
2218
- readonly models?: ModelConfig;
2219
- readonly outbound?: OutboundCallConfig;
2220
- readonly speech?: SpeechConfig;
2221
- readonly endCall?: EndCallPolicy;
2222
- readonly tools?: Readonly<Record<string, ToolDefinition$1>>;
2223
- /** Per-agent registry-tool scoping (stored ToolBinding names, applied at
2224
- * boot). Non-empty → only these dashboard HTTP tools attach; absent/[] →
2225
- * every enabled registry tool attaches (the historical default). */
2226
- readonly toolBindings?: readonly string[];
2227
- readonly security?: SecurityConfig;
2228
- /** Output content-moderation guard (P5). When set, each assistant turn is
2229
- * inspected and a violation is recorded as an engine.guard.blocked event on
2230
- * the call timeline. OBSERVE-ONLY on voice — it audits, it does not unsay a
2231
- * spoken turn. Absent → no guard. */
2232
- readonly guard?: GuardConfig;
2233
- /**
2234
- * Per-call ConsultationPolicy used by the built-in `ask_host` tool. When
2235
- * omitted the SDK uses the contract defaults (30s per-consult, 120s
2236
- * cumulative). Plan-first calls override this at boot from
2237
- * `plan.draftConfig.consultation`. See
2238
- * packages/contracts/src/consultation.ts for the schema + semantics.
2239
- */
2240
- readonly consultation?: ConsultationPolicy;
2241
- /**
2242
- * Use your existing text agent as the LLM. When set (and `models.llm` is
2243
- * unset), defineAgent wires the pipeline's LLM slot to this function: the
2244
- * caller's STT transcript is passed to `onQuery`, and its returned text (or
2245
- * streamed pieces) is spoken by TTS. The "two lines, keep your stack" path.
2246
- *
2247
- * Equivalent to `models: { llm: connector.llm({ onQuery }) }`. For a remote
2248
- * brain instead, use `connector.llm({ url })` (direct) or a tunnel transport.
2249
- * See docs/specs/voice-brain-connector/.
2250
- */
2251
- readonly onQuery?: OnQuery;
2252
- readonly onUtterance?: (text: string, ctx: AgentContext) => Promise<void> | void;
2253
- readonly onFieldCaptured?: (field: string, value: unknown, ctx: AgentContext) => Promise<void> | void;
2254
- readonly onCallEnd?: (outcome: CallOutcomeSummary, ctx: AgentContext) => Promise<void> | void;
2255
- readonly onEvent?: (event: AgentLifecycleEvent) => void;
2256
- /** Replace the default conversation loop. The SDK does NOT auto-greet. */
2257
- readonly onCall?: (ctx: AgentContext) => Promise<void>;
2258
- readonly readiness?: readonly ReadinessProbe[];
2259
- /**
2260
- * Run as a remote-controlled (puppet) agent: no autonomous LLM loop, no
2261
- * process/triggers pipeline. STT utterances are still published to
2262
- * `call-events:{callId}` via the existing transcript-segments sync, and
2263
- * the SDK subscribes to `call-control:{room}` to receive `say`,
2264
- * `hangup`, `dtmf` commands from an external driver (typically the MCP
2265
- * server invoked by a coding agent).
2266
- *
2267
- * When this is on, `process`, `triggers`, `onUtterance`, `onCall` are
2268
- * ignored. `tools`, `connectors`, `memory` still work.
2269
- */
2270
- readonly puppetMode?: boolean;
2271
- /**
2272
- * Host-controlled autonomous agent (the "smart puppet"). UNLIKE puppetMode,
2273
- * the agent keeps its REAL LLM and drives the conversation itself from its
2274
- * prompt (the per-call `intent` is appended at boot). Since 0.2.0 EVERY
2275
- * agent listens on its call's control channel (the MCP host can interject
2276
- * with `say`, `hangup` or send `dtmf`, and answer `ask_host`), so this flag
2277
- * now only shapes turn handling for a host-driven call. Use this for an agent that takes a customer's
2278
- * intent and runs the call like a human secretary, asking the host for any
2279
- * info it's missing. Mutually exclusive in spirit with puppetMode (which is
2280
- * the older NoOp "dumb mouth").
2281
- */
2282
- readonly hostControlled?: boolean;
2283
- /** When set, this agent boots each call from a deployed flow's process_schema. */
2284
- readonly flowRuntime?: FlowRuntimeConfig;
2285
- /**
2286
- * Opt a hand-coded (non-flow) agent into the dashboard-driven pipeline: on
2287
- * each call the SDK fetches this agent's PUBLISHED configuration (a saved
2288
- * dashboard draft applies only once the owner publishes it) and applies
2289
- * the operator-selected voice / model / STT over the coded defaults. The
2290
- * pipeline *mode* (cascade vs realtime) stays pinned to what the code
2291
- * declares — a stale `mode=realtime` in the dashboard can't flip a
2292
- * cascade-only worker. Flow agents (`flowRuntime`) get this implicitly and
2293
- * may additionally switch mode; this flag is the SDK opt-in. The agent id is
2294
- * read from dispatch metadata (the inbound router injects it from
2295
- * phone_numbers.agentId), so it's a no-op for calls without one.
2296
- */
2297
- readonly pipelineFromConfig?: boolean;
2298
- /**
2299
- * Opt this agent into MCP-layer visibility. When true, on register the API
2300
- * also writes an `agent_config` row keyed by (project_id, name,
2301
- * environment) so MCP / dashboard / REST can list and inspect this agent
2302
- * (and, post-step-7, drive call_say / call_send_guidance / etc against
2303
- * its live calls).
2304
- *
2305
- * Defaults to true so newly-registered agents show up in dashboards and
2306
- * MCP-host listings without opt-in. Pass `false` for autonomous-only
2307
- * agents that should stay invisible to MCP. See
2308
- * docs/architecture/contracts-design.md §2b.
2309
- */
2310
- readonly mcpExposed?: boolean;
2311
- }
2312
- interface CallOutcomeSummary {
2313
- readonly reason: 'completed' | 'handoff' | 'caller_hung_up' | 'agent_hung_up' | 'error';
2314
- readonly durationMs: number;
2315
- readonly processCompleted: boolean;
2316
- readonly fieldsCaptured: number;
2317
- readonly handoffOccurred: boolean;
1617
+ interface ApiCredential {
1618
+ readonly apiKey: string;
1619
+ readonly baseUrl: string;
1620
+ /** `worker-token`: minted for this call's project. `env-key`: the process's own VOICELAYER_API_KEY. */
1621
+ readonly source: 'worker-token' | 'env-key';
2318
1622
  }
2319
- /**
2320
- * Identity helper that gives users a typed `defineProcess` entry point with
2321
- * full inference on `onComplete`'s `data` argument.
2322
- *
2323
- * defineProcess({
2324
- * collect: { name: { type: 'string', required: true } },
2325
- * onComplete: (data) => { data.name // string },
2326
- * })
2327
- */
2328
- declare function defineProcess<T extends Record<string, ProcessField>>(def: ProcessDefinition<T>): ProcessDefinition<T>;
2329
1623
 
2330
1624
  interface TransportOptions {
2331
1625
  readonly apiKey: string;
@@ -2476,7 +1770,7 @@ declare class AgentsClient {
2476
1770
  * published; a saved-but-unpublished dashboard draft is never returned here
2477
1771
  * (docs/specs/agents/draft-publish.md). Returns null on 404 (agent absent).
2478
1772
  */
2479
- getConfig(agentId: string): Promise<AgentConfig$1 | null>;
1773
+ getConfig(agentId: string): Promise<AgentConfig | null>;
2480
1774
  register(input: RegisterInput, opts?: RegisterOptions): Promise<RegisteredAgent>;
2481
1775
  list(query?: {
2482
1776
  environment?: AgentEnvironment;
@@ -2506,6 +1800,7 @@ declare class AgentsClient {
2506
1800
  backendAck?: {
2507
1801
  url: string;
2508
1802
  timeoutMs: number;
1803
+ allowPrivateNetwork?: boolean | undefined;
2509
1804
  } | undefined;
2510
1805
  };
2511
1806
  fields: {
@@ -2517,6 +1812,7 @@ declare class AgentsClient {
2517
1812
  min?: number | undefined;
2518
1813
  max?: number | undefined;
2519
1814
  enum?: string[] | undefined;
1815
+ fromCaller?: boolean | undefined;
2520
1816
  }[];
2521
1817
  handoff?: {
2522
1818
  fallback?: string | undefined;
@@ -2555,9 +1851,11 @@ declare class AgentsClient {
2555
1851
  input: Record<string, "string" | "number" | "boolean">;
2556
1852
  method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
2557
1853
  auth: "none" | "connection";
1854
+ allowPrivateNetwork?: boolean | undefined;
2558
1855
  headers?: Record<string, string> | undefined;
2559
1856
  connectionRef?: string | undefined;
2560
1857
  }[] | undefined;
1858
+ displayName?: string | undefined;
2561
1859
  program?: {
2562
1860
  v: 1;
2563
1861
  id: string;
@@ -2594,10 +1892,10 @@ declare class AgentsClient {
2594
1892
 
2595
1893
  interface ContextInput {
2596
1894
  readonly callerId: string;
2597
- readonly scopes?: readonly MemoryScope$1[];
1895
+ readonly scopes?: readonly MemoryScope[];
2598
1896
  }
2599
1897
  interface WriteInput {
2600
- readonly scope: MemoryScope$1;
1898
+ readonly scope: MemoryScope;
2601
1899
  readonly callerId: string;
2602
1900
  readonly delta: Record<string, unknown>;
2603
1901
  readonly callId?: string;
@@ -3036,7 +2334,7 @@ declare class Agent {
3036
2334
  /** Whether this process registered `<name>::text` and takes text turns (said so at registration). */
3037
2335
  private textTurns;
3038
2336
  private processStatePublisher;
3039
- constructor(config: AgentConfig);
2337
+ constructor(config: AgentConfig$1);
3040
2338
  /**
3041
2339
  * Boot the LiveKit worker and register presence. Idempotent. Returns the
3042
2340
  * LiveKit agent definition so the caller can `export default` it; LK's
@@ -3056,7 +2354,7 @@ declare class Agent {
3056
2354
  private registerPresence;
3057
2355
  }
3058
2356
 
3059
- declare function defineAgent<TProcess extends Record<string, ProcessField> = Record<string, ProcessField>>(config: AgentConfig<TProcess>): Agent;
2357
+ declare function defineAgent<TProcess extends Record<string, ProcessField> = Record<string, ProcessField>>(config: AgentConfig$1<TProcess>): Agent;
3060
2358
  /**
3061
2359
  * defineFlowRuntime — a worker that serves many visually-built flows from one
3062
2360
  * process (the shared pool). It registers under a single LiveKit agent name;
@@ -3267,26 +2565,132 @@ interface CompiledAgentParts {
3267
2565
  /**
3268
2566
  * Turn a compiled ProcessSchemaDTO into the full set of `defineAgent` parts a
3269
2567
  * flow-runtime worker boots a visually-built conversation with: the composed
3270
- * prompt (say/confirm fragments), the process (slots + gate), the deterministic
2568
+ * prompt (say/confirm fragments on the flat path; the persona alone in graph
2569
+ * mode, `graphNodeIds` given), the process (slots + gate), the deterministic
3271
2570
  * triggers (rails), and the handoff destination. Pure.
3272
2571
  */
3273
2572
  declare function processSchemaToAgentParts(schema: ProcessSchemaDTO, opts?: {
3274
2573
  readonly basePrompt?: string;
3275
2574
  readonly graphNodeIds?: ReadonlySet<string>;
2575
+ /**
2576
+ * The worker's server-side tool executor (the platform's pools): every schema tool runs through it — the API's
2577
+ * SSRF guard, its connection resolution — instead of a fetch from this worker. Absent → the local guarded fetch.
2578
+ */
2579
+ readonly toolExecutor?: ToolExecutor;
3276
2580
  }): CompiledAgentParts;
3277
2581
 
3278
2582
  interface ExchangeWorkerTokenInput {
3279
2583
  readonly projectId: string;
3280
2584
  readonly callId?: string;
2585
+ /**
2586
+ * The LiveKit room the job was dispatched into — from the JOB (LiveKit's own record), never from dispatch metadata.
2587
+ * The API mints only when the platform's record of that room names `projectId` (a caller who sets `projectId` in
2588
+ * its metadata can't borrow another workspace's identity).
2589
+ */
2590
+ readonly roomName: string;
2591
+ /** The dispatched agent: the API's audit line, and (with `route`) what a number's inbound rule is judged against. */
2592
+ readonly agentId?: string;
2593
+ /** The number a number's dispatch rule stamped on the job — the API refuses a leftover route. */
2594
+ readonly phoneNumberId?: string;
2595
+ /** 'inbound_number' when the job came from a number's inbound rule — the only jobs the API judges. */
2596
+ readonly route?: string;
3281
2597
  readonly fetchImpl?: typeof fetch;
2598
+ /** Waits between attempts on a transient failure (network / 5xx / timeout). A 4xx is final. */
2599
+ readonly retryDelaysMs?: readonly number[];
2600
+ /** One attempt's ceiling. Default 3 s (above the API's 2.5 s room lookup). */
2601
+ readonly attemptTimeoutMs?: number;
2602
+ /** The whole exchange's ceiling, retries included — a caller is on the line in silence. Default 5 s. */
2603
+ readonly budgetMs?: number;
2604
+ }
2605
+ /**
2606
+ * The API refused this job's identity: it was dispatched by a leftover route for a number its workspace no longer
2607
+ * answers with this agent (moved to another workspace, released, re-assigned — burn-down G-28). The job must not act
2608
+ * at all: no env-key fallback, no session.
2609
+ */
2610
+ declare class StaleRouteError extends Error {
2611
+ readonly reason: string;
2612
+ constructor(reason: string);
3282
2613
  }
3283
2614
  /** One mint per call (cheap in-cluster HMAC mint, ~ms) so every token is
3284
- * attributable to a specific call in the API's audit log. Returns null when
3285
- * the exchange isn't configured or fails — callers fall back to the env key. */
2615
+ * attributable to a specific call in the API's audit log. A transient failure
2616
+ * (network, 5xx, 429, a hung attempt) is retried with a short backoff, all
2617
+ * inside the budget — the ONE timing every caller (resolveWorkerIdentity,
2618
+ * admitCallIdentity) inherits; null when the exchange isn't configured, the API
2619
+ * refuses, or the budget ran out. Throws StaleRouteError when the API refuses a
2620
+ * leftover route (never null: a refusal must not degrade into acting under
2621
+ * another key). */
3286
2622
  declare function exchangeWorkerToken(input: ExchangeWorkerTokenInput): Promise<string | null>;
3287
- /** Build the per-call SDK client under the calling project's identity, with
3288
- * the env-key fallback chain above. `md` is the parsed dispatch metadata. */
3289
- declare function resolveWorkerClient(md: Record<string, unknown>, fetchImpl?: typeof fetch): Promise<VoiceLayerClient | null>;
2623
+ /** The identity a call acts as: its SDK client and the credential behind it (for the call's resolvers). */
2624
+ interface WorkerIdentity {
2625
+ readonly client: VoiceLayerClient;
2626
+ readonly credential: ApiCredential;
2627
+ }
2628
+ type WorkerIdentityResolution = {
2629
+ readonly kind: 'ok';
2630
+ readonly identity: WorkerIdentity;
2631
+ }
2632
+ /** No credentials configured at all — the degraded no-API mode. */
2633
+ | {
2634
+ readonly kind: 'none';
2635
+ }
2636
+ /** A pool worker could not act as the calling project; it must not act as anyone else. */
2637
+ | {
2638
+ readonly kind: 'refused';
2639
+ readonly reason: 'worker_token_exchange_failed' | 'no_project_in_dispatch';
2640
+ }
2641
+ /** A number's leftover inbound rule dispatched it (G-28); `detail` says why the API refused it. */
2642
+ | {
2643
+ readonly kind: 'refused';
2644
+ readonly reason: 'stale_route';
2645
+ readonly detail: string;
2646
+ };
2647
+ interface ResolveWorkerIdentityOptions {
2648
+ /** The job's room as LiveKit reports it (never from metadata) — the mint is bound to it. */
2649
+ readonly roomName?: string | undefined;
2650
+ /**
2651
+ * A worker that only ever serves a customer's project (the flow-runtime and puppet pools, a text turn): on a pool,
2652
+ * a dispatch without a usable projectId is refused instead of falling back to the worker's own (platform) key.
2653
+ */
2654
+ readonly requireProject?: boolean;
2655
+ readonly fetchImpl?: typeof fetch;
2656
+ readonly retryDelaysMs?: readonly number[];
2657
+ readonly attemptTimeoutMs?: number;
2658
+ readonly budgetMs?: number;
2659
+ }
2660
+ /** Resolve the identity a call (or text turn) acts as, per the order above. `md` is the parsed dispatch metadata. */
2661
+ declare function resolveWorkerIdentity(md: Record<string, unknown>, opts?: ResolveWorkerIdentityOptions): Promise<WorkerIdentityResolution>;
2662
+ /** The per-call SDK client under the calling project's identity (resolveWorkerIdentity), or null when there is none
2663
+ * — including when a pool worker's token exchange failed (never the env key in its place). */
2664
+ declare function resolveWorkerClient(md: Record<string, unknown>, opts?: ResolveWorkerIdentityOptions): Promise<VoiceLayerClient | null>;
2665
+ /** The minimum of a LiveKit JobContext the admission needs (so it is testable without a worker). */
2666
+ interface AdmissibleJob {
2667
+ shutdown(reason?: string): void;
2668
+ /** Ends the call for the caller too (deletes the room): a refused job must not leave a SIP caller in dead air. */
2669
+ endRoom?(): Promise<void>;
2670
+ }
2671
+ type CallAdmission = {
2672
+ readonly admitted: true;
2673
+ readonly resolution: WorkerIdentityResolution;
2674
+ } | {
2675
+ readonly admitted: false;
2676
+ readonly reason: string;
2677
+ };
2678
+ /**
2679
+ * Per-call admission for a worker (burn-down G-28): decide whether this job may act at all, and as whom. On a POOL
2680
+ * worker (the internal exchange is configured: it serves many workspaces) the call is ended — room deleted, job shut
2681
+ * down, never answered under the env key — when
2682
+ * - a SIP call's dispatch names no workspace: no rule of ours dispatches that way (the retired provision:twilio rule
2683
+ * did), and the env key would answer it as whichever workspace the pool's key belongs to;
2684
+ * - a number's INBOUND rule dispatched it and the identity exchange does not succeed: refused as a stale route (its
2685
+ * workspace no longer answers the number with this agent), or failed for any other reason — a marked inbound job
2686
+ * only ever acts as the workspace the API confirmed.
2687
+ * Every other job gets its identity resolution (resolveWorkerIdentity) back to act on — the agent decides what a
2688
+ * refusal means for it (a flow apologises and ends; a coded agent runs with no workspace credential).
2689
+ */
2690
+ declare function admitCallIdentity(job: AdmissibleJob, md: Record<string, unknown>, participant: {
2691
+ readonly identity?: string;
2692
+ readonly attributes?: Record<string, string> | undefined;
2693
+ }, opts?: ResolveWorkerIdentityOptions): Promise<CallAdmission>;
3290
2694
 
3291
2695
  /**
3292
2696
  * Extend this to author a tool with the least ceremony. `run` receives the
@@ -3329,14 +2733,30 @@ interface HttpToolSpec {
3329
2733
  /** Build the request body from input (non-GET). Defaults to the input bag. */
3330
2734
  readonly body?: (input: Record<string, unknown>) => unknown;
3331
2735
  readonly capability?: string;
3332
- /** Injectable for tests. Defaults to global fetch. */
2736
+ /** Injectable for tests. Defaults to global fetch (always guarded, never following a redirect itself). */
3333
2737
  readonly fetchImpl?: typeof fetch;
2738
+ /** Injectable for tests. Defaults to node:dns. */
2739
+ readonly lookup?: HostLookup;
2740
+ /** Abort the request after this long. Default 15s. */
2741
+ readonly timeoutMs?: number;
2742
+ /**
2743
+ * A self-hosted worker calling its OWN private network (an intranet API, a service on localhost). Off by default:
2744
+ * without it a private / loopback / link-local / metadata address is refused. Lifts only that refusal — the request
2745
+ * is still http(s), still pinned to the checked address, still never follows a blind redirect. The platform never
2746
+ * sets it, and its server-side executor has no such switch.
2747
+ */
2748
+ readonly allowPrivateNetwork?: boolean;
3334
2749
  }
3335
2750
  /**
3336
2751
  * A config-only HTTP tool — no subclass needed for the common "call an API"
3337
2752
  * case. Use this for public/no-auth endpoints (e.g. an n8n webhook). Secrets
3338
2753
  * should NOT be inlined here; vault-backed credentials resolve server-side.
2754
+ *
2755
+ * Safe by default (runtime/safe-fetch.ts): http(s) only, never a private /
2756
+ * loopback / link-local / metadata address (checked again after DNS and on every
2757
+ * redirect hop), a timeout, and a capped body. A refused request is a failed
2758
+ * result `{ ok: false, status: 0, data: { kind: 'blocked', reason } }`, never a throw.
3339
2759
  */
3340
2760
  declare function httpTool(spec: HttpToolSpec): Record<string, ToolDefinition>;
3341
2761
 
3342
- export { Agent, type AgentConfig, AgentContext, type AgentEventEmitter, type AgentEventListener, type AgentLifecycleEvent, type AppendDtmfEventInput, type AppendTranscriptInput, BaseTool, BrainTransport, type CallAttributeValue, CallInfo, type CallLegInput, type CallOutcomeSummary, type CallParticipantInput, type CallStatus, type CallSummary, CallsClient, type CompiledAgentParts, type CompletionStrategy, type ComplianceTag, type ConnectorInstance, type ConnectorLLMConfig, ConsultationPolicy, type CreateClientOptions, type CreatedFormSession, type DefaultMetadata, type DtmfDirection, EmailClient, type SendEmailInput as EmailSendInput, type EndCallInfo, type EndCallPolicy, type EndCallTrigger, type EndpointingConfig, type EnsureCallByRoomInput, type ExchangeWorkerTokenInput, type CreateFormSessionInput as FormCreateInput, type FormToolsOptions, FormsClient, type HandoffConfig, type HttpToolResult, type HttpToolSpec, type InferProcessData, type InterruptionConfig, type LLMProvider, type MemoryConfig, type MemoryScope, type ModelConfig, OnQuery, Participant, type ParticipantsConfig, type PipelineConfig, PlansClient, type ProcessBackendAck, type ProcessDefinition, type ProcessField, type ProcessFieldType, type PronunciationDict, type ProviderFactory, type PublicFormSessionView, type ReadinessProbe, type ReadinessReport, type ReadinessResult, type RealtimeProvider, type RegisterInput, type RegisterOptions, type RegisteredAgent, type ResendCredentials, type ResendEmailToolOptions, type STTProvider, type SecurityConfig, type SentEmail, type ShorthandPrimitive$1 as ShorthandPrimitive, type SpeechConfig, type SyncCallStateInput, type TTSProvider, type ToolDefinition$1 as ToolDefinition, type ToolInputShape$1 as ToolInputShape, type TriggerAction, type TriggerCondition, type TriggerDefinition, type TurnDetectorProvider, type VADProvider, VoiceLayerAuthError, type VoiceLayerClient, VoiceLayerError, VoiceLayerHttpError, VoiceLayerNetworkError, VoiceLayerValidationError, type WebhookApi, type WebhookConfig, type WrapOptions, applyPronunciations, assemblyai, asyncProbe, cartesia, collectDefaultMetadata, connector, createClient, createNoOpLLM, deepgram, defineAgent, defineFlowRuntime, defineProcess, defineTool, elevenlabs, envProbe, exchangeWorkerToken, formTools, google, httpTool, livekitTurn, mergeMetadata, openai, processSchemaToAgentParts, processSchemaToDefinition, resendEmailTool, resolveWorkerClient, runProbes, silero, urlProbe, webhook, wrap };
2762
+ export { Agent, AgentConfig$1 as AgentConfig, AgentContext, AgentEventEmitter, AgentLifecycleEvent, type ApiCredential, type AppendDtmfEventInput, type AppendTranscriptInput, BaseTool, BrainTransport, type CallAttributeValue, type CallLegInput, type CallParticipantInput, type CallStatus, type CallSummary, CallsClient, type CompiledAgentParts, ConnectorInstance, type ConnectorLLMConfig, type CreateClientOptions, type CreatedFormSession, type DefaultMetadata, type DtmfDirection, EmailClient, type SendEmailInput as EmailSendInput, type EnsureCallByRoomInput, type ExchangeWorkerTokenInput, type CreateFormSessionInput as FormCreateInput, type FormToolsOptions, FormsClient, HandoffConfig, type HttpToolResult, type HttpToolSpec, LLMProvider, MemoryConfig, ModelConfig, OnQuery, type PipelineConfig, PlansClient, ProcessDefinition, ProcessField, type PronunciationDict, ProviderFactory, type PublicFormSessionView, ReadinessProbe, RealtimeProvider, type RegisterInput, type RegisterOptions, type RegisteredAgent, type ResendCredentials, type ResendEmailToolOptions, STTProvider, type SentEmail, SpeechConfig, StaleRouteError, type SyncCallStateInput, TTSProvider, ToolDefinition$1 as ToolDefinition, TriggerDefinition, TurnDetectorProvider, VADProvider, type VoiceLayerClient, type WebhookApi, type WebhookConfig, type WorkerIdentity, type WorkerIdentityResolution, type WrapOptions, admitCallIdentity, applyPronunciations, assemblyai, cartesia, collectDefaultMetadata, connector, createClient, createNoOpLLM, deepgram, defineAgent, defineFlowRuntime, defineTool, elevenlabs, exchangeWorkerToken, formTools, google, httpTool, livekitTurn, mergeMetadata, openai, processSchemaToAgentParts, processSchemaToDefinition, resendEmailTool, resolveWorkerClient, resolveWorkerIdentity, silero, webhook, wrap };