@signalwire/sdk 3.5.0 → 3.7.1
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/CHANGELOG.md +71 -0
- package/dist/AgentBase.d.ts +101 -0
- package/dist/AgentBase.js +209 -22
- package/dist/AgentBase.js.map +1 -1
- package/dist/DataMap.d.ts +28 -0
- package/dist/DataMap.js +43 -0
- package/dist/DataMap.js.map +1 -1
- package/dist/FunctionResult.d.ts +32 -0
- package/dist/FunctionResult.js +39 -0
- package/dist/FunctionResult.js.map +1 -1
- package/dist/SWMLService.d.ts +11 -1
- package/dist/SWMLService.js +21 -2
- package/dist/SWMLService.js.map +1 -1
- package/dist/SemanticGate.d.ts +197 -0
- package/dist/SemanticGate.js +554 -0
- package/dist/SemanticGate.js.map +1 -0
- package/dist/SwaigFunction.d.ts +29 -3
- package/dist/SwaigFunction.js +19 -3
- package/dist/SwaigFunction.js.map +1 -1
- package/dist/cli/tsdocs/api-index.json +1 -1
- package/dist/cli/tsdocs/topics.js +21 -0
- package/dist/cli/tsdocs/topics.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/skills/SkillBase.d.ts +14 -1
- package/dist/skills/SkillBase.js.map +1 -1
- package/docs/agent-guide.md +122 -2
- package/docs/api-reference.md +142 -4
- package/docs/architecture.md +2 -1
- package/docs/datamap-guide.md +51 -4
- package/docs/swaig-reference.md +48 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,77 @@
|
|
|
3
3
|
All notable changes to `@signalwire/sdk` are documented here. This project
|
|
4
4
|
follows [Semantic Versioning](https://semver.org/).
|
|
5
5
|
|
|
6
|
+
## 3.7.1 (2026-10-14)
|
|
7
|
+
|
|
8
|
+
Parity with signalwire-python 3.7.1, and `onCallStart()` from its main branch (#118).
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Semantic gates take `visual_input`: how many of the caller's newest video
|
|
13
|
+
frames the decision model sees with the gate, `true` for 1 or a whole
|
|
14
|
+
number up to 5 (`MAX_VISUAL_INPUT`). `new SemanticGate(..., { visualInput })`
|
|
15
|
+
sets it, and gate objects are checked by the platform's rule. 3.6.0
|
|
16
|
+
refused the key, so a gate that looks at the caller's video could only be
|
|
17
|
+
written in raw SWML.
|
|
18
|
+
- `AgentBase.onCallStart()` registers handlers that run when the call
|
|
19
|
+
starts, before the AI's first turn: the counterpart of `onCallEnd()`. It
|
|
20
|
+
wraps the platform's reserved `startup_hook` function. A handler receives
|
|
21
|
+
the SWAIG request and may return a `FunctionResult`: its actions run at
|
|
22
|
+
once, and its response text is added to the conversation as a system
|
|
23
|
+
message the model reads before it speaks. Handlers run in registration
|
|
24
|
+
order, and an exception is logged, not raised.
|
|
25
|
+
|
|
26
|
+
### Documentation
|
|
27
|
+
|
|
28
|
+
- How to reject a call from the per-call configuration callback
|
|
29
|
+
(`addPerCallConfig()`): build the agent with `play` and `hangup`
|
|
30
|
+
post-answer verbs and no tools, and have the callback add the tools and
|
|
31
|
+
call `clearPostAnswerVerbs()` only for a call it accepts. A callback that
|
|
32
|
+
fails leaves the call rejected. See "Rejecting a Call" in
|
|
33
|
+
`docs/agent-guide.md`.
|
|
34
|
+
- The SWAIG function webhook timeout: the platform waits up to 30 seconds to
|
|
35
|
+
connect and 120 seconds for a tool's reply, and sends the request again, up
|
|
36
|
+
to 3 times, after a failed or timed-out request or a 5xx. The caller hears
|
|
37
|
+
nothing meanwhile, so tools should answer quickly and send late results into the call with
|
|
38
|
+
`calling.aiMessage()` on a `RestClient`. See "Slow tools and the webhook
|
|
39
|
+
timeout" in `docs/agent-guide.md`.
|
|
40
|
+
|
|
41
|
+
## 3.6.0 (2026-10-05)
|
|
42
|
+
|
|
43
|
+
Parity with signalwire-python 3.6.0: semantic gates, `changeVoice()`, and
|
|
44
|
+
the settings and state they use.
|
|
45
|
+
|
|
46
|
+
### Added
|
|
47
|
+
|
|
48
|
+
- Semantic gates: `SemanticGate`, and `gates` and `gateFillers` on
|
|
49
|
+
`defineTool()`, `defineTypedTool()`, `SwaigFunction`, a skill's tools and
|
|
50
|
+
raw function definitions, and `gate()` and `gateFillers()` on DataMap. A
|
|
51
|
+
gate is a yes/no question a decision model answers about the call before
|
|
52
|
+
the platform runs the function; when one fails, the function doesn't run
|
|
53
|
+
and the model gets the gate's `on_fail` output. Gates are checked by the
|
|
54
|
+
platform's rules when the tool is defined and again when the SWML is
|
|
55
|
+
rendered, since the platform refuses a function with an invalid gate. They
|
|
56
|
+
need a platform release with semantic gates: one without them runs the
|
|
57
|
+
function ungated.
|
|
58
|
+
- `AgentBase.setSemanticGates()` sets `semantic_gates_enabled`,
|
|
59
|
+
`semantic_gate_timeout_ms` and `semantic_gate_history`, and
|
|
60
|
+
`FunctionResult.setSemanticState()` sets the state gates judge.
|
|
61
|
+
- `FunctionResult.changeVoice()` changes the AI's voice for the rest of the
|
|
62
|
+
call (`change_voice`), from the next batch of speech on. It throws on an
|
|
63
|
+
empty or whitespace-only voice, which the platform would ignore.
|
|
64
|
+
- Function fillers are documented with the `auto` key, translated into the
|
|
65
|
+
call's language on first use, and wait scripts, lists of phrases spoken one
|
|
66
|
+
at a time while the call waits. `gateFillers` is typed for both (the
|
|
67
|
+
exported `FillerPhrases`); `fillers` keeps its type, so a wait script there
|
|
68
|
+
needs a cast.
|
|
69
|
+
|
|
70
|
+
### Changed
|
|
71
|
+
|
|
72
|
+
- `addSkill()` merges a skill's `swaig_fields` and each tool's own fields
|
|
73
|
+
before it builds the tool, so the merged definition is what gets checked;
|
|
74
|
+
a tool's own fields still win. It used to copy `swaig_fields` onto the
|
|
75
|
+
tool afterwards.
|
|
76
|
+
|
|
6
77
|
## 3.5.0 (2026-09-29)
|
|
7
78
|
|
|
8
79
|
Brings the TypeScript SDK to parity with signalwire-python 3.5.1: the
|
package/dist/AgentBase.d.ts
CHANGED
|
@@ -11,7 +11,9 @@ import { PromptManager } from './PromptManager.js';
|
|
|
11
11
|
import { PromptObjectModel } from './POM/PromptObjectModel.js';
|
|
12
12
|
import { SWMLService } from './SWMLService.js';
|
|
13
13
|
import { SwaigFunction, type SwaigErrorHandler } from './SwaigFunction.js';
|
|
14
|
+
import { type FillerPhrases, type SemanticGate } from './SemanticGate.js';
|
|
14
15
|
import { type TypedToolHandler } from './TypeInference.js';
|
|
16
|
+
import { FunctionResult } from './FunctionResult.js';
|
|
15
17
|
import { ContextBuilder } from './ContextBuilder.js';
|
|
16
18
|
import { type Logger } from './Logger.js';
|
|
17
19
|
import { SkillManager } from './skills/SkillManager.js';
|
|
@@ -124,6 +126,8 @@ export declare class AgentBase extends SWMLService {
|
|
|
124
126
|
private perCallConfigs;
|
|
125
127
|
/** Set once serve() runs an HTTP server; getFullUrl then ignores serverless environments. */
|
|
126
128
|
private _serving;
|
|
129
|
+
/** Handlers registered with {@link onCallStart}. */
|
|
130
|
+
private callStartHandlers;
|
|
127
131
|
/** Handlers registered with {@link onCallEnd}. */
|
|
128
132
|
private callEndHandlers;
|
|
129
133
|
/** Apps and routers added with {@link mount}, replayed on every app build. */
|
|
@@ -530,6 +534,29 @@ export declare class AgentBase extends SWMLService {
|
|
|
530
534
|
* @returns This agent instance for chaining.
|
|
531
535
|
*/
|
|
532
536
|
setParams(params: Record<string, unknown>): this;
|
|
537
|
+
/**
|
|
538
|
+
* Set how the call checks its functions' semantic gates (see
|
|
539
|
+
* {@link SemanticGate}).
|
|
540
|
+
*
|
|
541
|
+
* Each option left out leaves its current setting as it is; the platform's
|
|
542
|
+
* default applies to a setting that was never set.
|
|
543
|
+
* @param opts - The gate settings.
|
|
544
|
+
* @param opts.enabled - `false` dispatches gated functions without checking
|
|
545
|
+
* their gates. Default `true`. Sent as `semantic_gates_enabled`.
|
|
546
|
+
* @param opts.timeoutMs - The time one check may take, 500 to 10000
|
|
547
|
+
* milliseconds, preparing the request and any retry included. A check that
|
|
548
|
+
* runs out blocks the call. Default 2500. Sent as
|
|
549
|
+
* `semantic_gate_timeout_ms`.
|
|
550
|
+
* @param opts.history - How many recent dialogue entries the decision model
|
|
551
|
+
* sees, 0 to 100. Default 20. Sent as `semantic_gate_history`.
|
|
552
|
+
* @returns This agent instance for chaining.
|
|
553
|
+
* @throws {Error} When a value has the wrong type or is out of range.
|
|
554
|
+
*/
|
|
555
|
+
setSemanticGates(opts?: {
|
|
556
|
+
enabled?: boolean;
|
|
557
|
+
timeoutMs?: number;
|
|
558
|
+
history?: number;
|
|
559
|
+
}): this;
|
|
533
560
|
/**
|
|
534
561
|
* **MERGES** `data` into the global_data object passed into the AI
|
|
535
562
|
* configuration. **Despite the name, this does NOT replace** the existing
|
|
@@ -790,10 +817,15 @@ export declare class AgentBase extends SWMLService {
|
|
|
790
817
|
*/
|
|
791
818
|
handler: TypedToolHandler;
|
|
792
819
|
secure?: boolean;
|
|
820
|
+
/** Phrases the AI says while the function runs (see `SwaigFunctionOptions.fillers`). */
|
|
793
821
|
fillers?: Record<string, string[]>;
|
|
794
822
|
waitFile?: string;
|
|
795
823
|
waitFileLoops?: number;
|
|
796
824
|
required?: string[];
|
|
825
|
+
/** Semantic gates (see `SwaigFunctionOptions.gates`). */
|
|
826
|
+
gates?: ReadonlyArray<SemanticGate | Record<string, unknown>>;
|
|
827
|
+
/** Phrases said while the gates are checked (see `SwaigFunctionOptions.gateFillers`). */
|
|
828
|
+
gateFillers?: FillerPhrases;
|
|
797
829
|
}): this;
|
|
798
830
|
/**
|
|
799
831
|
* Validate a tool-call token for the given function.
|
|
@@ -996,12 +1028,81 @@ export declare class AgentBase extends SWMLService {
|
|
|
996
1028
|
* without knowing about each other. `setDynamicConfigCallback` replaces
|
|
997
1029
|
* every callback registered so far.
|
|
998
1030
|
*
|
|
1031
|
+
* Rejecting a call: a callback can't refuse the request, but it can decide
|
|
1032
|
+
* what the call does. Build the agent to fail closed, with
|
|
1033
|
+
* `addPostAnswerVerb('play', { url: 'say:...' })` and
|
|
1034
|
+
* `addPostAnswerVerb('hangup', {})` and no tools, so the call hears the
|
|
1035
|
+
* message and hangs up before the `ai` verb runs. For a call the callback
|
|
1036
|
+
* accepts, add the tools to `agent` and call `agent.clearPostAnswerVerbs()`
|
|
1037
|
+
* last. A callback that throws is logged and the copy is rendered as it
|
|
1038
|
+
* stands, so a failure before that last step leaves the goodbye in place.
|
|
1039
|
+
* A callback that throws stops the ones after it but doesn't restore verbs
|
|
1040
|
+
* an earlier one cleared, so the callback that clears them must run last.
|
|
1041
|
+
* Callbacks run for every request of the call (the SWML fetch, each tool
|
|
1042
|
+
* call, the summary), and only the SWML fetch carries the caller's data
|
|
1043
|
+
* (such as `userVariables`): verify there, remember the `call_id`, and check
|
|
1044
|
+
* it on later requests. See "Rejecting a Call" in docs/agent-guide.md.
|
|
1045
|
+
*
|
|
999
1046
|
* @param cb - Callback receiving `(queryParams, bodyParams, headers, agent)`,
|
|
1000
1047
|
* where `agent` is the per-request copy. Configure that, never the agent
|
|
1001
1048
|
* itself, or the configuration leaks across callers. May be async.
|
|
1002
1049
|
* @returns This agent instance for chaining.
|
|
1003
1050
|
*/
|
|
1004
1051
|
addPerCallConfig(cb: DynamicConfigCallback): this;
|
|
1052
|
+
/**
|
|
1053
|
+
* Register a handler that runs when the call starts, before the AI speaks.
|
|
1054
|
+
*
|
|
1055
|
+
* Handlers run in registration order with `rawData`, the whole SWAIG request
|
|
1056
|
+
* (`call_id`, `global_data`, the caller's details). This wraps the
|
|
1057
|
+
* platform's reserved `startup_hook` function, the counterpart of the
|
|
1058
|
+
* `hangup_hook` behind {@link onCallEnd}. The platform calls it once, after
|
|
1059
|
+
* the call is answered and before the AI's first turn, and never offers it to
|
|
1060
|
+
* the model.
|
|
1061
|
+
*
|
|
1062
|
+
* The platform waits for the hook before the AI starts, so a slow handler
|
|
1063
|
+
* delays the greeting; it waits up to 120 seconds for a function's reply
|
|
1064
|
+
* and sends the request again after a timeout or a 5xx. Keep handlers
|
|
1065
|
+
* short; start long work without awaiting
|
|
1066
|
+
* it and send its result into the call later (`calling.aiMessage()` on the
|
|
1067
|
+
* REST client). Like any function request, the hook's request can be sent
|
|
1068
|
+
* again after a timeout or an error, so make handlers safe to run twice.
|
|
1069
|
+
*
|
|
1070
|
+
* A handler may return a `FunctionResult`, or nothing. What the platform
|
|
1071
|
+
* does with the hook's reply:
|
|
1072
|
+
* - its actions run at once, in registration order across handlers (for
|
|
1073
|
+
* example `updateGlobalData()` to give the call data before the
|
|
1074
|
+
* conversation starts);
|
|
1075
|
+
* - its response text is added to the conversation as a system message the
|
|
1076
|
+
* model reads before its first turn. The texts of several handlers are
|
|
1077
|
+
* joined, one per line. Only a plain string response is used. OpenAI
|
|
1078
|
+
* Realtime agents run the actions but don't add the text.
|
|
1079
|
+
*
|
|
1080
|
+
* `postProcess` isn't used: the combined result runs its actions at once.
|
|
1081
|
+
* The platform adds every hook reply to the conversation, so a hook whose
|
|
1082
|
+
* handlers return no text still adds a short placeholder line, as any
|
|
1083
|
+
* function with an empty reply does.
|
|
1084
|
+
*
|
|
1085
|
+
* An exception is logged, not raised, and that handler's result is dropped,
|
|
1086
|
+
* so a failing handler can't stop the call from starting or the other
|
|
1087
|
+
* handlers from running.
|
|
1088
|
+
*
|
|
1089
|
+
* @param handler - Called with `(rawData)`; may be async. Returns a
|
|
1090
|
+
* `FunctionResult`, or nothing.
|
|
1091
|
+
* @returns The handler.
|
|
1092
|
+
*
|
|
1093
|
+
* @example
|
|
1094
|
+
* ```ts
|
|
1095
|
+
* agent.onCallStart(async (rawData) => {
|
|
1096
|
+
* const caller = await lookupCaller(rawData.caller_id_num);
|
|
1097
|
+
* return new FunctionResult(`The caller's name is ${caller.name}.`).updateGlobalData({
|
|
1098
|
+
* customer_id: caller.id,
|
|
1099
|
+
* });
|
|
1100
|
+
* });
|
|
1101
|
+
* ```
|
|
1102
|
+
*/
|
|
1103
|
+
onCallStart(handler: (rawData: SwaigRequest) => FunctionResult | null | undefined | void | Promise<FunctionResult | null | undefined | void>): (rawData: SwaigRequest) => FunctionResult | null | undefined | void | Promise<FunctionResult | null | undefined | void>;
|
|
1104
|
+
/** Register the reserved startup_hook tool once. */
|
|
1105
|
+
private ensureCallStartHook;
|
|
1005
1106
|
/**
|
|
1006
1107
|
* Register a handler that runs when the call ends, with the transcript.
|
|
1007
1108
|
*
|
package/dist/AgentBase.js
CHANGED
|
@@ -17,6 +17,7 @@ import { SwmlBuilder } from './SwmlBuilder.js';
|
|
|
17
17
|
import { SWMLService } from './SWMLService.js';
|
|
18
18
|
import { ConfigLoader } from './ConfigLoader.js';
|
|
19
19
|
import { SwaigFunction, normalizeParameters, } from './SwaigFunction.js';
|
|
20
|
+
import { _checkGatedFunction } from './SemanticGate.js';
|
|
20
21
|
import { inferSchema, createTypedHandlerWrapper } from './TypeInference.js';
|
|
21
22
|
import { FunctionResult } from './FunctionResult.js';
|
|
22
23
|
import { Context as ConversationContext, ContextBuilder, GatherInfo, GatherQuestion, Step, } from './ContextBuilder.js';
|
|
@@ -299,6 +300,8 @@ export class AgentBase extends SWMLService {
|
|
|
299
300
|
perCallConfigs = [];
|
|
300
301
|
/** Set once serve() runs an HTTP server; getFullUrl then ignores serverless environments. */
|
|
301
302
|
_serving = false;
|
|
303
|
+
/** Handlers registered with {@link onCallStart}. */
|
|
304
|
+
callStartHandlers = [];
|
|
302
305
|
/** Handlers registered with {@link onCallEnd}. */
|
|
303
306
|
callEndHandlers = [];
|
|
304
307
|
/** Apps and routers added with {@link mount}, replayed on every app build. */
|
|
@@ -1021,6 +1024,49 @@ export class AgentBase extends SWMLService {
|
|
|
1021
1024
|
safeAssign(this.params, params);
|
|
1022
1025
|
return this;
|
|
1023
1026
|
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Set how the call checks its functions' semantic gates (see
|
|
1029
|
+
* {@link SemanticGate}).
|
|
1030
|
+
*
|
|
1031
|
+
* Each option left out leaves its current setting as it is; the platform's
|
|
1032
|
+
* default applies to a setting that was never set.
|
|
1033
|
+
* @param opts - The gate settings.
|
|
1034
|
+
* @param opts.enabled - `false` dispatches gated functions without checking
|
|
1035
|
+
* their gates. Default `true`. Sent as `semantic_gates_enabled`.
|
|
1036
|
+
* @param opts.timeoutMs - The time one check may take, 500 to 10000
|
|
1037
|
+
* milliseconds, preparing the request and any retry included. A check that
|
|
1038
|
+
* runs out blocks the call. Default 2500. Sent as
|
|
1039
|
+
* `semantic_gate_timeout_ms`.
|
|
1040
|
+
* @param opts.history - How many recent dialogue entries the decision model
|
|
1041
|
+
* sees, 0 to 100. Default 20. Sent as `semantic_gate_history`.
|
|
1042
|
+
* @returns This agent instance for chaining.
|
|
1043
|
+
* @throws {Error} When a value has the wrong type or is out of range.
|
|
1044
|
+
*/
|
|
1045
|
+
setSemanticGates(opts = {}) {
|
|
1046
|
+
// Check every value before setting any, so a refused call changes nothing
|
|
1047
|
+
const { enabled, timeoutMs, history } = opts;
|
|
1048
|
+
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
|
1049
|
+
throw new Error(`enabled must be a boolean, got ${JSON.stringify(enabled)}`);
|
|
1050
|
+
}
|
|
1051
|
+
const ranges = [
|
|
1052
|
+
['semantic_gate_timeout_ms', 'timeout_ms', timeoutMs, 500, 10000],
|
|
1053
|
+
['semantic_gate_history', 'history', history, 0, 100],
|
|
1054
|
+
];
|
|
1055
|
+
for (const [, name, value, low, high] of ranges) {
|
|
1056
|
+
if (value === undefined)
|
|
1057
|
+
continue;
|
|
1058
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < low || value > high) {
|
|
1059
|
+
throw new Error(`${name} must be an integer from ${low} to ${high}, got ${JSON.stringify(value)}`);
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
if (enabled !== undefined)
|
|
1063
|
+
this.params['semantic_gates_enabled'] = enabled;
|
|
1064
|
+
for (const [param, , value] of ranges) {
|
|
1065
|
+
if (value !== undefined)
|
|
1066
|
+
this.params[param] = value;
|
|
1067
|
+
}
|
|
1068
|
+
return this;
|
|
1069
|
+
}
|
|
1024
1070
|
/**
|
|
1025
1071
|
* **MERGES** `data` into the global_data object passed into the AI
|
|
1026
1072
|
* configuration. **Despite the name, this does NOT replace** the existing
|
|
@@ -1577,6 +1623,8 @@ export class AgentBase extends SWMLService {
|
|
|
1577
1623
|
waitFileLoops: opts.waitFileLoops,
|
|
1578
1624
|
required,
|
|
1579
1625
|
isTypedHandler: true,
|
|
1626
|
+
gates: opts.gates,
|
|
1627
|
+
gateFillers: opts.gateFillers,
|
|
1580
1628
|
});
|
|
1581
1629
|
this.toolRegistry.set(opts.name, fn);
|
|
1582
1630
|
return this;
|
|
@@ -1727,29 +1775,40 @@ export class AgentBase extends SWMLService {
|
|
|
1727
1775
|
// and the other keys go into the SWAIG definition.
|
|
1728
1776
|
const { secure: skillSecure, ...skillExtraFields } = skill.swaigFields;
|
|
1729
1777
|
for (const toolDef of skill.getTools()) {
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
if (toolDef.skip_fillers !== undefined) {
|
|
1745
|
-
fn.extraFields['skip_fillers'] = toolDef.skip_fillers;
|
|
1746
|
-
}
|
|
1747
|
-
// Propagate is_hangup_hook so the SignalWire platform auto-fires this
|
|
1748
|
-
// tool on call hangup (Python equivalent: is_hangup_hook=True in define_tool).
|
|
1749
|
-
if (toolDef.isHangupHook) {
|
|
1750
|
-
fn.extraFields['is_hangup_hook'] = true;
|
|
1751
|
-
}
|
|
1778
|
+
// Skill-level swaigFields are the base and the tool's own fields win —
|
|
1779
|
+
// Python skill_base.py:70-73 (swaig_fields base, explicit kwargs win) and
|
|
1780
|
+
// SkillBase.defineTool() ({...swaigDefaults, ...toolDef}). They are merged
|
|
1781
|
+
// before the function is built, so the result is what's checked: a
|
|
1782
|
+
// skill's default gates never replace a tool's own.
|
|
1783
|
+
const extraFields = {};
|
|
1784
|
+
safeAssign(extraFields, skillExtraFields);
|
|
1785
|
+
// A tool may carry its own extra fields (getTools() can return
|
|
1786
|
+
// SwaigFunctionOptions); they win over the skill's defaults.
|
|
1787
|
+
const ownExtraFields = toolDef.extraFields;
|
|
1788
|
+
if (ownExtraFields)
|
|
1789
|
+
safeAssign(extraFields, ownExtraFields);
|
|
1790
|
+
if (toolDef.wait_for_fillers !== undefined) {
|
|
1791
|
+
extraFields['wait_for_fillers'] = toolDef.wait_for_fillers;
|
|
1752
1792
|
}
|
|
1793
|
+
if (toolDef.skip_fillers !== undefined) {
|
|
1794
|
+
extraFields['skip_fillers'] = toolDef.skip_fillers;
|
|
1795
|
+
}
|
|
1796
|
+
// Propagate is_hangup_hook so the SignalWire platform auto-fires this
|
|
1797
|
+
// tool on call hangup (Python equivalent: is_hangup_hook=True in define_tool).
|
|
1798
|
+
if (toolDef.isHangupHook) {
|
|
1799
|
+
extraFields['is_hangup_hook'] = true;
|
|
1800
|
+
}
|
|
1801
|
+
if (toolDef.gates !== undefined)
|
|
1802
|
+
extraFields['gates'] = toolDef.gates;
|
|
1803
|
+
if (toolDef.gate_fillers !== undefined)
|
|
1804
|
+
extraFields['gate_fillers'] = toolDef.gate_fillers;
|
|
1805
|
+
this.defineTool({
|
|
1806
|
+
...toolDef,
|
|
1807
|
+
...(toolDef.secure === undefined && typeof skillSecure === 'boolean'
|
|
1808
|
+
? { secure: skillSecure }
|
|
1809
|
+
: {}),
|
|
1810
|
+
extraFields,
|
|
1811
|
+
});
|
|
1753
1812
|
}
|
|
1754
1813
|
// Register DataMap-style tools — skills that build their own SWAIG JSON
|
|
1755
1814
|
// (e.g. DataSphereServerless) return them via getDataMapTools().
|
|
@@ -1912,6 +1971,21 @@ export class AgentBase extends SWMLService {
|
|
|
1912
1971
|
* without knowing about each other. `setDynamicConfigCallback` replaces
|
|
1913
1972
|
* every callback registered so far.
|
|
1914
1973
|
*
|
|
1974
|
+
* Rejecting a call: a callback can't refuse the request, but it can decide
|
|
1975
|
+
* what the call does. Build the agent to fail closed, with
|
|
1976
|
+
* `addPostAnswerVerb('play', { url: 'say:...' })` and
|
|
1977
|
+
* `addPostAnswerVerb('hangup', {})` and no tools, so the call hears the
|
|
1978
|
+
* message and hangs up before the `ai` verb runs. For a call the callback
|
|
1979
|
+
* accepts, add the tools to `agent` and call `agent.clearPostAnswerVerbs()`
|
|
1980
|
+
* last. A callback that throws is logged and the copy is rendered as it
|
|
1981
|
+
* stands, so a failure before that last step leaves the goodbye in place.
|
|
1982
|
+
* A callback that throws stops the ones after it but doesn't restore verbs
|
|
1983
|
+
* an earlier one cleared, so the callback that clears them must run last.
|
|
1984
|
+
* Callbacks run for every request of the call (the SWML fetch, each tool
|
|
1985
|
+
* call, the summary), and only the SWML fetch carries the caller's data
|
|
1986
|
+
* (such as `userVariables`): verify there, remember the `call_id`, and check
|
|
1987
|
+
* it on later requests. See "Rejecting a Call" in docs/agent-guide.md.
|
|
1988
|
+
*
|
|
1915
1989
|
* @param cb - Callback receiving `(queryParams, bodyParams, headers, agent)`,
|
|
1916
1990
|
* where `agent` is the per-request copy. Configure that, never the agent
|
|
1917
1991
|
* itself, or the configuration leaks across callers. May be async.
|
|
@@ -1922,6 +1996,114 @@ export class AgentBase extends SWMLService {
|
|
|
1922
1996
|
this.perCallConfigs = [...this.perCallConfigs, cb];
|
|
1923
1997
|
return this;
|
|
1924
1998
|
}
|
|
1999
|
+
/**
|
|
2000
|
+
* Register a handler that runs when the call starts, before the AI speaks.
|
|
2001
|
+
*
|
|
2002
|
+
* Handlers run in registration order with `rawData`, the whole SWAIG request
|
|
2003
|
+
* (`call_id`, `global_data`, the caller's details). This wraps the
|
|
2004
|
+
* platform's reserved `startup_hook` function, the counterpart of the
|
|
2005
|
+
* `hangup_hook` behind {@link onCallEnd}. The platform calls it once, after
|
|
2006
|
+
* the call is answered and before the AI's first turn, and never offers it to
|
|
2007
|
+
* the model.
|
|
2008
|
+
*
|
|
2009
|
+
* The platform waits for the hook before the AI starts, so a slow handler
|
|
2010
|
+
* delays the greeting; it waits up to 120 seconds for a function's reply
|
|
2011
|
+
* and sends the request again after a timeout or a 5xx. Keep handlers
|
|
2012
|
+
* short; start long work without awaiting
|
|
2013
|
+
* it and send its result into the call later (`calling.aiMessage()` on the
|
|
2014
|
+
* REST client). Like any function request, the hook's request can be sent
|
|
2015
|
+
* again after a timeout or an error, so make handlers safe to run twice.
|
|
2016
|
+
*
|
|
2017
|
+
* A handler may return a `FunctionResult`, or nothing. What the platform
|
|
2018
|
+
* does with the hook's reply:
|
|
2019
|
+
* - its actions run at once, in registration order across handlers (for
|
|
2020
|
+
* example `updateGlobalData()` to give the call data before the
|
|
2021
|
+
* conversation starts);
|
|
2022
|
+
* - its response text is added to the conversation as a system message the
|
|
2023
|
+
* model reads before its first turn. The texts of several handlers are
|
|
2024
|
+
* joined, one per line. Only a plain string response is used. OpenAI
|
|
2025
|
+
* Realtime agents run the actions but don't add the text.
|
|
2026
|
+
*
|
|
2027
|
+
* `postProcess` isn't used: the combined result runs its actions at once.
|
|
2028
|
+
* The platform adds every hook reply to the conversation, so a hook whose
|
|
2029
|
+
* handlers return no text still adds a short placeholder line, as any
|
|
2030
|
+
* function with an empty reply does.
|
|
2031
|
+
*
|
|
2032
|
+
* An exception is logged, not raised, and that handler's result is dropped,
|
|
2033
|
+
* so a failing handler can't stop the call from starting or the other
|
|
2034
|
+
* handlers from running.
|
|
2035
|
+
*
|
|
2036
|
+
* @param handler - Called with `(rawData)`; may be async. Returns a
|
|
2037
|
+
* `FunctionResult`, or nothing.
|
|
2038
|
+
* @returns The handler.
|
|
2039
|
+
*
|
|
2040
|
+
* @example
|
|
2041
|
+
* ```ts
|
|
2042
|
+
* agent.onCallStart(async (rawData) => {
|
|
2043
|
+
* const caller = await lookupCaller(rawData.caller_id_num);
|
|
2044
|
+
* return new FunctionResult(`The caller's name is ${caller.name}.`).updateGlobalData({
|
|
2045
|
+
* customer_id: caller.id,
|
|
2046
|
+
* });
|
|
2047
|
+
* });
|
|
2048
|
+
* ```
|
|
2049
|
+
*/
|
|
2050
|
+
onCallStart(handler) {
|
|
2051
|
+
const first = this.callStartHandlers.length === 0;
|
|
2052
|
+
// Rebind rather than push: a per-request copy shares this array.
|
|
2053
|
+
this.callStartHandlers = [...this.callStartHandlers, handler];
|
|
2054
|
+
if (first)
|
|
2055
|
+
this.ensureCallStartHook();
|
|
2056
|
+
return handler;
|
|
2057
|
+
}
|
|
2058
|
+
/** Register the reserved startup_hook tool once. */
|
|
2059
|
+
ensureCallStartHook() {
|
|
2060
|
+
this.defineTool({
|
|
2061
|
+
name: 'startup_hook',
|
|
2062
|
+
description: 'Internal: fires when the call starts.',
|
|
2063
|
+
parameters: {},
|
|
2064
|
+
handler: async (_args, rawData, running) => {
|
|
2065
|
+
const raw = (rawData ?? {});
|
|
2066
|
+
const combined = new FunctionResult();
|
|
2067
|
+
const texts = [];
|
|
2068
|
+
// The handlers of the agent running the call: a per-call copy may
|
|
2069
|
+
// have added its own.
|
|
2070
|
+
const agent = running instanceof AgentBase ? running : this;
|
|
2071
|
+
for (const callback of agent.callStartHandlers) {
|
|
2072
|
+
const name = callback.name || 'anonymous';
|
|
2073
|
+
let result;
|
|
2074
|
+
// Each handler is isolated, so one failure doesn't stop the others.
|
|
2075
|
+
try {
|
|
2076
|
+
result = await callback(raw);
|
|
2077
|
+
}
|
|
2078
|
+
catch (err) {
|
|
2079
|
+
this.log.error('call_start_handler_failed', {
|
|
2080
|
+
error: err instanceof Error ? err.message : String(err),
|
|
2081
|
+
handler: name,
|
|
2082
|
+
});
|
|
2083
|
+
continue;
|
|
2084
|
+
}
|
|
2085
|
+
if (result === undefined || result === null)
|
|
2086
|
+
continue;
|
|
2087
|
+
if (!(result instanceof FunctionResult)) {
|
|
2088
|
+
this.log.warn('call_start_handler_result_ignored', {
|
|
2089
|
+
handler: name,
|
|
2090
|
+
result_type: typeof result,
|
|
2091
|
+
});
|
|
2092
|
+
continue;
|
|
2093
|
+
}
|
|
2094
|
+
const response = result.toDict().response;
|
|
2095
|
+
if (typeof response === 'object') {
|
|
2096
|
+
this.log.warn('call_start_handler_structured_response_ignored', { handler: name });
|
|
2097
|
+
}
|
|
2098
|
+
else if (result.response) {
|
|
2099
|
+
texts.push(result.response);
|
|
2100
|
+
}
|
|
2101
|
+
combined.addActions(result.action);
|
|
2102
|
+
}
|
|
2103
|
+
return combined.setResponse(texts.join('\n'));
|
|
2104
|
+
},
|
|
2105
|
+
});
|
|
2106
|
+
}
|
|
1925
2107
|
/**
|
|
1926
2108
|
* Register a handler that runs when the call ends, with the transcript.
|
|
1927
2109
|
*
|
|
@@ -2587,11 +2769,16 @@ export class AgentBase extends SWMLService {
|
|
|
2587
2769
|
entry['web_hook_url'] = this.buildWebhookUrl('swaig', urlParams);
|
|
2588
2770
|
}
|
|
2589
2771
|
safeAssign(entry, fn.extraFields);
|
|
2772
|
+
// Gates are checked once more as sent: under the name the entry carries,
|
|
2773
|
+
// with its URL or the defaults' URL (the platform drops a gated
|
|
2774
|
+
// function it can't register).
|
|
2775
|
+
_checkGatedFunction(entry, defaultWebhookUrl);
|
|
2590
2776
|
functions.push(entry);
|
|
2591
2777
|
}
|
|
2592
2778
|
else {
|
|
2593
2779
|
// Raw dict (DataMap) - use as-is
|
|
2594
2780
|
const entry = { ...fn, function: name };
|
|
2781
|
+
_checkGatedFunction(entry, defaultWebhookUrl);
|
|
2595
2782
|
functions.push(entry);
|
|
2596
2783
|
}
|
|
2597
2784
|
}
|