@signalwire/sdk 3.6.0 → 3.7.2
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 +95 -0
- package/dist/AgentBase.d.ts +85 -1
- package/dist/AgentBase.js +157 -5
- package/dist/AgentBase.js.map +1 -1
- package/dist/AgentServer.d.ts +30 -6
- package/dist/AgentServer.js +28 -2
- package/dist/AgentServer.js.map +1 -1
- package/dist/ContextBuilder.d.ts +16 -5
- package/dist/ContextBuilder.js +15 -4
- package/dist/ContextBuilder.js.map +1 -1
- package/dist/Logger.d.ts +1 -1
- package/dist/SWMLService.d.ts +54 -9
- package/dist/SWMLService.js +248 -59
- package/dist/SWMLService.js.map +1 -1
- package/dist/SchemaUtils.js +14 -1
- package/dist/SchemaUtils.js.map +1 -1
- package/dist/SemanticGate.d.ts +16 -2
- package/dist/SemanticGate.js +23 -2
- package/dist/SemanticGate.js.map +1 -1
- package/dist/SessionManager.d.ts +17 -6
- package/dist/SessionManager.js +16 -3
- package/dist/SessionManager.js.map +1 -1
- package/dist/SwaigFunction.d.ts +4 -3
- package/dist/SwaigFunction.js +1 -1
- package/dist/SwaigFunction.js.map +1 -1
- package/dist/TypeInference.d.ts +1 -1
- package/dist/TypeInference.js +1 -1
- package/dist/ai-chat/ChatGateway.d.ts +5 -5
- package/dist/ai-chat/HandoffRouter.d.ts +3 -3
- package/dist/cli/tsdocs/api-index.json +1 -1
- package/dist/cli/tsdocs/topics.js +17 -0
- package/dist/cli/tsdocs/topics.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/livewire/index.d.ts +3 -0
- package/dist/livewire/index.js +3 -0
- package/dist/livewire/index.js.map +1 -1
- package/dist/relay/Call.d.ts +1 -1
- package/dist/relay/Call.js +1 -1
- package/dist/relay/Message.d.ts +1 -1
- package/dist/relay/Message.js +1 -1
- package/dist/relay/RelayClient.d.ts +0 -2
- package/dist/relay/RelayClient.js.map +1 -1
- package/dist/relay/RelayEvent.d.ts +3 -3
- package/dist/relay/RelayEvent.js +3 -3
- package/dist/relay/closedSets.d.ts +10 -10
- package/dist/relay/closedSets.js +2 -2
- package/dist/relay/types.d.ts +1 -1
- package/dist/rest/base/CrudResource.d.ts +1 -1
- package/dist/rest/base/CrudResource.js +1 -1
- package/dist/skills/SkillBase.d.ts +2 -2
- package/dist/skills/SkillBase.js +2 -2
- package/docs/agent-guide.md +124 -4
- package/docs/api-reference.md +40 -9
- package/docs/architecture.md +2 -1
- package/docs/contexts-guide.md +2 -1
- package/docs/pgi_agent_guide.md +2 -1
- package/docs/programmatically_governed_inference.md +1 -1
- package/docs/swml_service_guide.md +31 -6
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,101 @@
|
|
|
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.2 (2026-11-12)
|
|
7
|
+
|
|
8
|
+
Parity with signalwire-python 3.7.7: the chat-session token fix, a plain
|
|
9
|
+
`SWMLService` on an `AgentServer`, the `isolate` history mode and the schema
|
|
10
|
+
validator warning.
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- A step's or context's history mode can be `"isolate"`:
|
|
15
|
+
`step.setHistory('isolate')`. While the agent is in the step, the model
|
|
16
|
+
sees none of the earlier dialogue and none of the earlier step
|
|
17
|
+
instructions, as with `"hide"`. When the agent leaves the step, the
|
|
18
|
+
earlier dialogue comes back, and the step's own turns stay; the earlier
|
|
19
|
+
instructions stay cleared, and what an earlier `"hide"` step hid stays
|
|
20
|
+
hidden. Entering the step again isolates it again. On a context, it
|
|
21
|
+
applies to every step that doesn't set its own mode. A platform without
|
|
22
|
+
isolate treats it as `"default"`. Parity with signalwire-python 3.7.7.
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- A chat session's post-prompt summary was refused with `403`, so its
|
|
27
|
+
transcript never saved. The chat service fetches an agent's SWML under the
|
|
28
|
+
conversation's id, so the SDK mints that SWML's tokens for the
|
|
29
|
+
conversation, but the summary can arrive under the chat service's own call
|
|
30
|
+
id, with the conversation's id as `conversation_id`. A token is now
|
|
31
|
+
accepted when it names the request's `call_id` or its `conversation_id`,
|
|
32
|
+
for post-prompt summaries and secure functions alike. A voice call, where
|
|
33
|
+
the two are the same, is unchanged, and the token still has to name this
|
|
34
|
+
call or conversation. A `call_id` that isn't a non-empty string is
|
|
35
|
+
refused, and an accepted chat request logs no token mismatch. Parity with
|
|
36
|
+
signalwire-python 3.7.4 (#166).
|
|
37
|
+
- `AgentServer` hosts a plain `SWMLService` next to its agents, as
|
|
38
|
+
signalwire-python 3.7.6 does. Registering one made every request under its
|
|
39
|
+
route answer with 500. Use `new AgentServer<SWMLService>()`:
|
|
40
|
+
`AgentServer<T extends SWMLService = AgentBase>` is now generic over what
|
|
41
|
+
it hosts, so `getAgent()` and `getAgents()` keep returning agents on a
|
|
42
|
+
plain `new AgentServer()`. The service answers at its route with or
|
|
43
|
+
without a trailing slash, under its own basic auth, and serves its
|
|
44
|
+
`/swaig` endpoint and routing callbacks; the agent endpoints
|
|
45
|
+
(`/post_prompt`, `/check_for_input`, `/debug`) aren't served for it.
|
|
46
|
+
- `SWMLService.asRouter()` returns a router whose routes are relative to
|
|
47
|
+
the service's route, as the reference's `as_router()` does, so a host can
|
|
48
|
+
mount it at any prefix. It returned the service's own app, so a service at
|
|
49
|
+
`/menu` mounted at `/menu` served `/menu/menu`. The router's own routes
|
|
50
|
+
and callbacks carry the service's security headers, CORS and basic auth,
|
|
51
|
+
and it has no middleware for every path, so it leaves a host's other
|
|
52
|
+
routes alone; a route you add to the router checks auth itself, as with
|
|
53
|
+
`AgentBase.asRouter()`. A `SWMLService` route
|
|
54
|
+
drops a trailing slash (`/menu/` is stored as `/menu`), as the reference
|
|
55
|
+
does, so it's served the same mounted or on its own.
|
|
56
|
+
- A plain `SWMLService` serves its routing callbacks under its route
|
|
57
|
+
(`/menu/sip`), as the reference does, and still at the bare path
|
|
58
|
+
(`/sip`), where earlier releases served them. A callback registered after
|
|
59
|
+
the service has served a request now answers; it used to throw.
|
|
60
|
+
- Where the SWML schema can't be compiled, as on a runtime that blocks code
|
|
61
|
+
generation from strings (Cloudflare Workers), verb validation falls back
|
|
62
|
+
to checking verb names and required fields, and now logs
|
|
63
|
+
`schema_validator_unavailable` once instead of falling back silently, as
|
|
64
|
+
signalwire-python 3.7.2 does.
|
|
65
|
+
|
|
66
|
+
## 3.7.1 (2026-10-14)
|
|
67
|
+
|
|
68
|
+
Parity with signalwire-python 3.7.1, and `onCallStart()` from its main branch (#118).
|
|
69
|
+
|
|
70
|
+
### Added
|
|
71
|
+
|
|
72
|
+
- Semantic gates take `visual_input`: how many of the caller's newest video
|
|
73
|
+
frames the decision model sees with the gate, `true` for 1 or a whole
|
|
74
|
+
number up to 5 (`MAX_VISUAL_INPUT`). `new SemanticGate(..., { visualInput })`
|
|
75
|
+
sets it, and gate objects are checked by the platform's rule. 3.6.0
|
|
76
|
+
refused the key, so a gate that looks at the caller's video could only be
|
|
77
|
+
written in raw SWML.
|
|
78
|
+
- `AgentBase.onCallStart()` registers handlers that run when the call
|
|
79
|
+
starts, before the AI's first turn: the counterpart of `onCallEnd()`. It
|
|
80
|
+
wraps the platform's reserved `startup_hook` function. A handler receives
|
|
81
|
+
the SWAIG request and may return a `FunctionResult`: its actions run at
|
|
82
|
+
once, and its response text is added to the conversation as a system
|
|
83
|
+
message the model reads before it speaks. Handlers run in registration
|
|
84
|
+
order, and an exception is logged, not raised.
|
|
85
|
+
|
|
86
|
+
### Documentation
|
|
87
|
+
|
|
88
|
+
- How to reject a call from the per-call configuration callback
|
|
89
|
+
(`addPerCallConfig()`): build the agent with `play` and `hangup`
|
|
90
|
+
post-answer verbs and no tools, and have the callback add the tools and
|
|
91
|
+
call `clearPostAnswerVerbs()` only for a call it accepts. A callback that
|
|
92
|
+
fails leaves the call rejected. See "Rejecting a Call" in
|
|
93
|
+
`docs/agent-guide.md`.
|
|
94
|
+
- The SWAIG function webhook timeout: the platform waits up to 30 seconds to
|
|
95
|
+
connect and 120 seconds for a tool's reply, and sends the request again, up
|
|
96
|
+
to 3 times, after a failed or timed-out request or a 5xx. The caller hears
|
|
97
|
+
nothing meanwhile, so tools should answer quickly and send late results into the call with
|
|
98
|
+
`calling.aiMessage()` on a `RestClient`. See "Slow tools and the webhook
|
|
99
|
+
timeout" in `docs/agent-guide.md`.
|
|
100
|
+
|
|
6
101
|
## 3.6.0 (2026-10-05)
|
|
7
102
|
|
|
8
103
|
Parity with signalwire-python 3.6.0: semantic gates, `changeVoice()`, and
|
package/dist/AgentBase.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { SWMLService } from './SWMLService.js';
|
|
|
13
13
|
import { SwaigFunction, type SwaigErrorHandler } from './SwaigFunction.js';
|
|
14
14
|
import { type FillerPhrases, type SemanticGate } from './SemanticGate.js';
|
|
15
15
|
import { type TypedToolHandler } from './TypeInference.js';
|
|
16
|
+
import { FunctionResult } from './FunctionResult.js';
|
|
16
17
|
import { ContextBuilder } from './ContextBuilder.js';
|
|
17
18
|
import { type Logger } from './Logger.js';
|
|
18
19
|
import { SkillManager } from './skills/SkillManager.js';
|
|
@@ -44,7 +45,7 @@ export type RoutingCallback = (body: SwmlRequestData, headers?: Record<string, s
|
|
|
44
45
|
* - `POST /post_prompt` receives the end-of-call summary and invokes {@link onSummary}
|
|
45
46
|
*
|
|
46
47
|
* Most user agents either (a) subclass `AgentBase` and override `defineTools()` / `onSummary()`
|
|
47
|
-
* or (b) use one of the
|
|
48
|
+
* or (b) use one of the prefab agents (e.g. {@link ReceptionistAgent}).
|
|
48
49
|
*
|
|
49
50
|
* @example Subclass with a custom tool
|
|
50
51
|
* ```ts
|
|
@@ -125,6 +126,8 @@ export declare class AgentBase extends SWMLService {
|
|
|
125
126
|
private perCallConfigs;
|
|
126
127
|
/** Set once serve() runs an HTTP server; getFullUrl then ignores serverless environments. */
|
|
127
128
|
private _serving;
|
|
129
|
+
/** Handlers registered with {@link onCallStart}. */
|
|
130
|
+
private callStartHandlers;
|
|
128
131
|
/** Handlers registered with {@link onCallEnd}. */
|
|
129
132
|
private callEndHandlers;
|
|
130
133
|
/** Apps and routers added with {@link mount}, replayed on every app build. */
|
|
@@ -1025,12 +1028,81 @@ export declare class AgentBase extends SWMLService {
|
|
|
1025
1028
|
* without knowing about each other. `setDynamicConfigCallback` replaces
|
|
1026
1029
|
* every callback registered so far.
|
|
1027
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
|
+
*
|
|
1028
1046
|
* @param cb - Callback receiving `(queryParams, bodyParams, headers, agent)`,
|
|
1029
1047
|
* where `agent` is the per-request copy. Configure that, never the agent
|
|
1030
1048
|
* itself, or the configuration leaks across callers. May be async.
|
|
1031
1049
|
* @returns This agent instance for chaining.
|
|
1032
1050
|
*/
|
|
1033
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;
|
|
1034
1106
|
/**
|
|
1035
1107
|
* Register a handler that runs when the call ends, with the transcript.
|
|
1036
1108
|
*
|
|
@@ -1299,10 +1371,22 @@ export declare class AgentBase extends SWMLService {
|
|
|
1299
1371
|
* missing `call_id`, is refused like a wrong token. A non-secure function
|
|
1300
1372
|
* runs without a token.
|
|
1301
1373
|
*
|
|
1374
|
+
* The token may name the request's `call_id` or its `conversation_id`. A
|
|
1375
|
+
* chat session fetches its SWML, and so gets its tokens, under the
|
|
1376
|
+
* conversation's id, then sends every request under the chat service's own
|
|
1377
|
+
* call id, with the conversation's id beside it.
|
|
1378
|
+
*
|
|
1302
1379
|
* @returns The SWAIG response to send instead of running the function, or
|
|
1303
1380
|
* `null` when the function may run.
|
|
1304
1381
|
*/
|
|
1305
1382
|
private swaigTokenRefusal;
|
|
1383
|
+
/**
|
|
1384
|
+
* Whether `token` was minted for `functionName` and the request's call:
|
|
1385
|
+
* its `call_id`, or its `conversation_id` when it names a different one.
|
|
1386
|
+
* The request must name a call: a `call_id` that isn't a non-empty string
|
|
1387
|
+
* is refused, so the conversation can't stand in for a malformed one.
|
|
1388
|
+
*/
|
|
1389
|
+
private tokenNamesCall;
|
|
1306
1390
|
private extractSwaigArgs;
|
|
1307
1391
|
/**
|
|
1308
1392
|
* Render the complete SWML document by assembling all 5 phases: pre-answer, answer,
|
package/dist/AgentBase.js
CHANGED
|
@@ -49,6 +49,13 @@ function headersOf(c) {
|
|
|
49
49
|
});
|
|
50
50
|
return headers;
|
|
51
51
|
}
|
|
52
|
+
/** A request body's `conversation_id`, if it names one. */
|
|
53
|
+
function conversationIdOf(body) {
|
|
54
|
+
if (body === null || typeof body !== 'object')
|
|
55
|
+
return undefined;
|
|
56
|
+
const value = body['conversation_id'];
|
|
57
|
+
return typeof value === 'string' && value ? value : undefined;
|
|
58
|
+
}
|
|
52
59
|
/** The Hono context of the served request being handled, for onSwmlRequest. */
|
|
53
60
|
const servedRequestContext = new AsyncLocalStorage();
|
|
54
61
|
/** Compare two strings in constant time, whatever their lengths. */
|
|
@@ -209,7 +216,7 @@ function relativePath(path, routePath) {
|
|
|
209
216
|
* - `POST /post_prompt` receives the end-of-call summary and invokes {@link onSummary}
|
|
210
217
|
*
|
|
211
218
|
* Most user agents either (a) subclass `AgentBase` and override `defineTools()` / `onSummary()`
|
|
212
|
-
* or (b) use one of the
|
|
219
|
+
* or (b) use one of the prefab agents (e.g. {@link ReceptionistAgent}).
|
|
213
220
|
*
|
|
214
221
|
* @example Subclass with a custom tool
|
|
215
222
|
* ```ts
|
|
@@ -300,6 +307,8 @@ export class AgentBase extends SWMLService {
|
|
|
300
307
|
perCallConfigs = [];
|
|
301
308
|
/** Set once serve() runs an HTTP server; getFullUrl then ignores serverless environments. */
|
|
302
309
|
_serving = false;
|
|
310
|
+
/** Handlers registered with {@link onCallStart}. */
|
|
311
|
+
callStartHandlers = [];
|
|
303
312
|
/** Handlers registered with {@link onCallEnd}. */
|
|
304
313
|
callEndHandlers = [];
|
|
305
314
|
/** Apps and routers added with {@link mount}, replayed on every app build. */
|
|
@@ -1969,6 +1978,21 @@ export class AgentBase extends SWMLService {
|
|
|
1969
1978
|
* without knowing about each other. `setDynamicConfigCallback` replaces
|
|
1970
1979
|
* every callback registered so far.
|
|
1971
1980
|
*
|
|
1981
|
+
* Rejecting a call: a callback can't refuse the request, but it can decide
|
|
1982
|
+
* what the call does. Build the agent to fail closed, with
|
|
1983
|
+
* `addPostAnswerVerb('play', { url: 'say:...' })` and
|
|
1984
|
+
* `addPostAnswerVerb('hangup', {})` and no tools, so the call hears the
|
|
1985
|
+
* message and hangs up before the `ai` verb runs. For a call the callback
|
|
1986
|
+
* accepts, add the tools to `agent` and call `agent.clearPostAnswerVerbs()`
|
|
1987
|
+
* last. A callback that throws is logged and the copy is rendered as it
|
|
1988
|
+
* stands, so a failure before that last step leaves the goodbye in place.
|
|
1989
|
+
* A callback that throws stops the ones after it but doesn't restore verbs
|
|
1990
|
+
* an earlier one cleared, so the callback that clears them must run last.
|
|
1991
|
+
* Callbacks run for every request of the call (the SWML fetch, each tool
|
|
1992
|
+
* call, the summary), and only the SWML fetch carries the caller's data
|
|
1993
|
+
* (such as `userVariables`): verify there, remember the `call_id`, and check
|
|
1994
|
+
* it on later requests. See "Rejecting a Call" in docs/agent-guide.md.
|
|
1995
|
+
*
|
|
1972
1996
|
* @param cb - Callback receiving `(queryParams, bodyParams, headers, agent)`,
|
|
1973
1997
|
* where `agent` is the per-request copy. Configure that, never the agent
|
|
1974
1998
|
* itself, or the configuration leaks across callers. May be async.
|
|
@@ -1979,6 +2003,114 @@ export class AgentBase extends SWMLService {
|
|
|
1979
2003
|
this.perCallConfigs = [...this.perCallConfigs, cb];
|
|
1980
2004
|
return this;
|
|
1981
2005
|
}
|
|
2006
|
+
/**
|
|
2007
|
+
* Register a handler that runs when the call starts, before the AI speaks.
|
|
2008
|
+
*
|
|
2009
|
+
* Handlers run in registration order with `rawData`, the whole SWAIG request
|
|
2010
|
+
* (`call_id`, `global_data`, the caller's details). This wraps the
|
|
2011
|
+
* platform's reserved `startup_hook` function, the counterpart of the
|
|
2012
|
+
* `hangup_hook` behind {@link onCallEnd}. The platform calls it once, after
|
|
2013
|
+
* the call is answered and before the AI's first turn, and never offers it to
|
|
2014
|
+
* the model.
|
|
2015
|
+
*
|
|
2016
|
+
* The platform waits for the hook before the AI starts, so a slow handler
|
|
2017
|
+
* delays the greeting; it waits up to 120 seconds for a function's reply
|
|
2018
|
+
* and sends the request again after a timeout or a 5xx. Keep handlers
|
|
2019
|
+
* short; start long work without awaiting
|
|
2020
|
+
* it and send its result into the call later (`calling.aiMessage()` on the
|
|
2021
|
+
* REST client). Like any function request, the hook's request can be sent
|
|
2022
|
+
* again after a timeout or an error, so make handlers safe to run twice.
|
|
2023
|
+
*
|
|
2024
|
+
* A handler may return a `FunctionResult`, or nothing. What the platform
|
|
2025
|
+
* does with the hook's reply:
|
|
2026
|
+
* - its actions run at once, in registration order across handlers (for
|
|
2027
|
+
* example `updateGlobalData()` to give the call data before the
|
|
2028
|
+
* conversation starts);
|
|
2029
|
+
* - its response text is added to the conversation as a system message the
|
|
2030
|
+
* model reads before its first turn. The texts of several handlers are
|
|
2031
|
+
* joined, one per line. Only a plain string response is used. OpenAI
|
|
2032
|
+
* Realtime agents run the actions but don't add the text.
|
|
2033
|
+
*
|
|
2034
|
+
* `postProcess` isn't used: the combined result runs its actions at once.
|
|
2035
|
+
* The platform adds every hook reply to the conversation, so a hook whose
|
|
2036
|
+
* handlers return no text still adds a short placeholder line, as any
|
|
2037
|
+
* function with an empty reply does.
|
|
2038
|
+
*
|
|
2039
|
+
* An exception is logged, not raised, and that handler's result is dropped,
|
|
2040
|
+
* so a failing handler can't stop the call from starting or the other
|
|
2041
|
+
* handlers from running.
|
|
2042
|
+
*
|
|
2043
|
+
* @param handler - Called with `(rawData)`; may be async. Returns a
|
|
2044
|
+
* `FunctionResult`, or nothing.
|
|
2045
|
+
* @returns The handler.
|
|
2046
|
+
*
|
|
2047
|
+
* @example
|
|
2048
|
+
* ```ts
|
|
2049
|
+
* agent.onCallStart(async (rawData) => {
|
|
2050
|
+
* const caller = await lookupCaller(rawData.caller_id_num);
|
|
2051
|
+
* return new FunctionResult(`The caller's name is ${caller.name}.`).updateGlobalData({
|
|
2052
|
+
* customer_id: caller.id,
|
|
2053
|
+
* });
|
|
2054
|
+
* });
|
|
2055
|
+
* ```
|
|
2056
|
+
*/
|
|
2057
|
+
onCallStart(handler) {
|
|
2058
|
+
const first = this.callStartHandlers.length === 0;
|
|
2059
|
+
// Rebind rather than push: a per-request copy shares this array.
|
|
2060
|
+
this.callStartHandlers = [...this.callStartHandlers, handler];
|
|
2061
|
+
if (first)
|
|
2062
|
+
this.ensureCallStartHook();
|
|
2063
|
+
return handler;
|
|
2064
|
+
}
|
|
2065
|
+
/** Register the reserved startup_hook tool once. */
|
|
2066
|
+
ensureCallStartHook() {
|
|
2067
|
+
this.defineTool({
|
|
2068
|
+
name: 'startup_hook',
|
|
2069
|
+
description: 'Internal: fires when the call starts.',
|
|
2070
|
+
parameters: {},
|
|
2071
|
+
handler: async (_args, rawData, running) => {
|
|
2072
|
+
const raw = (rawData ?? {});
|
|
2073
|
+
const combined = new FunctionResult();
|
|
2074
|
+
const texts = [];
|
|
2075
|
+
// The handlers of the agent running the call: a per-call copy may
|
|
2076
|
+
// have added its own.
|
|
2077
|
+
const agent = running instanceof AgentBase ? running : this;
|
|
2078
|
+
for (const callback of agent.callStartHandlers) {
|
|
2079
|
+
const name = callback.name || 'anonymous';
|
|
2080
|
+
let result;
|
|
2081
|
+
// Each handler is isolated, so one failure doesn't stop the others.
|
|
2082
|
+
try {
|
|
2083
|
+
result = await callback(raw);
|
|
2084
|
+
}
|
|
2085
|
+
catch (err) {
|
|
2086
|
+
this.log.error('call_start_handler_failed', {
|
|
2087
|
+
error: err instanceof Error ? err.message : String(err),
|
|
2088
|
+
handler: name,
|
|
2089
|
+
});
|
|
2090
|
+
continue;
|
|
2091
|
+
}
|
|
2092
|
+
if (result === undefined || result === null)
|
|
2093
|
+
continue;
|
|
2094
|
+
if (!(result instanceof FunctionResult)) {
|
|
2095
|
+
this.log.warn('call_start_handler_result_ignored', {
|
|
2096
|
+
handler: name,
|
|
2097
|
+
result_type: typeof result,
|
|
2098
|
+
});
|
|
2099
|
+
continue;
|
|
2100
|
+
}
|
|
2101
|
+
const response = result.toDict().response;
|
|
2102
|
+
if (typeof response === 'object') {
|
|
2103
|
+
this.log.warn('call_start_handler_structured_response_ignored', { handler: name });
|
|
2104
|
+
}
|
|
2105
|
+
else if (result.response) {
|
|
2106
|
+
texts.push(result.response);
|
|
2107
|
+
}
|
|
2108
|
+
combined.addActions(result.action);
|
|
2109
|
+
}
|
|
2110
|
+
return combined.setResponse(texts.join('\n'));
|
|
2111
|
+
},
|
|
2112
|
+
});
|
|
2113
|
+
}
|
|
1982
2114
|
/**
|
|
1983
2115
|
* Register a handler that runs when the call ends, with the transcript.
|
|
1984
2116
|
*
|
|
@@ -2531,10 +2663,15 @@ export class AgentBase extends SWMLService {
|
|
|
2531
2663
|
* missing `call_id`, is refused like a wrong token. A non-secure function
|
|
2532
2664
|
* runs without a token.
|
|
2533
2665
|
*
|
|
2666
|
+
* The token may name the request's `call_id` or its `conversation_id`. A
|
|
2667
|
+
* chat session fetches its SWML, and so gets its tokens, under the
|
|
2668
|
+
* conversation's id, then sends every request under the chat service's own
|
|
2669
|
+
* call id, with the conversation's id beside it.
|
|
2670
|
+
*
|
|
2534
2671
|
* @returns The SWAIG response to send instead of running the function, or
|
|
2535
2672
|
* `null` when the function may run.
|
|
2536
2673
|
*/
|
|
2537
|
-
swaigTokenRefusal(fn, token, callId, reqLog) {
|
|
2674
|
+
swaigTokenRefusal(fn, token, callId, reqLog, conversationId) {
|
|
2538
2675
|
if (!fn.secure)
|
|
2539
2676
|
return null;
|
|
2540
2677
|
if (!token) {
|
|
@@ -2543,7 +2680,7 @@ export class AgentBase extends SWMLService {
|
|
|
2543
2680
|
else if (!callId) {
|
|
2544
2681
|
reqLog.warn('token_rejected_no_call_id');
|
|
2545
2682
|
}
|
|
2546
|
-
else if (this.
|
|
2683
|
+
else if (this.tokenNamesCall(fn.name, token, callId, conversationId)) {
|
|
2547
2684
|
reqLog.debug('token_valid');
|
|
2548
2685
|
return null;
|
|
2549
2686
|
}
|
|
@@ -2553,6 +2690,18 @@ export class AgentBase extends SWMLService {
|
|
|
2553
2690
|
// The reference's exact wording: the refusal is part of the SWAIG wire contract.
|
|
2554
2691
|
return new FunctionResult("I'm sorry, the security token for this function is invalid or expired. I cannot execute this action.").toDict();
|
|
2555
2692
|
}
|
|
2693
|
+
/**
|
|
2694
|
+
* Whether `token` was minted for `functionName` and the request's call:
|
|
2695
|
+
* its `call_id`, or its `conversation_id` when it names a different one.
|
|
2696
|
+
* The request must name a call: a `call_id` that isn't a non-empty string
|
|
2697
|
+
* is refused, so the conversation can't stand in for a malformed one.
|
|
2698
|
+
*/
|
|
2699
|
+
tokenNamesCall(functionName, token, callId, conversationId) {
|
|
2700
|
+
if (typeof callId !== 'string' || !callId)
|
|
2701
|
+
return false;
|
|
2702
|
+
const ids = conversationId && conversationId !== callId ? [callId, conversationId] : [callId];
|
|
2703
|
+
return this.sessionManager._validateTokenFor(ids, functionName, token);
|
|
2704
|
+
}
|
|
2556
2705
|
extractSwaigArgs(body, reqLog) {
|
|
2557
2706
|
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
2558
2707
|
const argument = body['argument'];
|
|
@@ -3114,7 +3263,7 @@ export class AgentBase extends SWMLService {
|
|
|
3114
3263
|
}
|
|
3115
3264
|
const url = new URL(c.req.url);
|
|
3116
3265
|
const token = url.searchParams.get('__token') ?? url.searchParams.get('token');
|
|
3117
|
-
const refusal = target.swaigTokenRefusal(fn, token, callIdStr, reqLog);
|
|
3266
|
+
const refusal = target.swaigTokenRefusal(fn, token, callIdStr, reqLog, conversationIdOf(body));
|
|
3118
3267
|
if (refusal)
|
|
3119
3268
|
return c.json(refusal);
|
|
3120
3269
|
const args = this.extractSwaigArgs(body, reqLog);
|
|
@@ -3183,7 +3332,10 @@ export class AgentBase extends SWMLService {
|
|
|
3183
3332
|
reqLog.warn('token_missing');
|
|
3184
3333
|
return c.json({ error: 'Invalid or missing token' }, 403);
|
|
3185
3334
|
}
|
|
3186
|
-
|
|
3335
|
+
// A chat session's summary arrives under the chat service's own call id,
|
|
3336
|
+
// with the conversation its SWML, and so its token, was made for beside it.
|
|
3337
|
+
const conversationId = conversationIdOf(body);
|
|
3338
|
+
if (!callId || !this.tokenNamesCall('post_prompt', token, callId, conversationId)) {
|
|
3187
3339
|
reqLog.warn('invalid_token');
|
|
3188
3340
|
return c.json({ error: 'Invalid or missing token' }, 403);
|
|
3189
3341
|
}
|