@signalwire/sdk 3.7.1 → 3.9.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/CHANGELOG.md +214 -0
- package/README.md +1 -0
- package/dist/AgentBase.d.ts +120 -3
- package/dist/AgentBase.js +291 -18
- 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/AiEvents.d.ts +70 -0
- package/dist/AiEvents.js +94 -0
- package/dist/AiEvents.js.map +1 -0
- package/dist/ContextBuilder.d.ts +197 -14
- package/dist/ContextBuilder.js +422 -13
- package/dist/ContextBuilder.js.map +1 -1
- package/dist/FunctionResult.d.ts +129 -0
- package/dist/FunctionResult.js +170 -0
- package/dist/FunctionResult.js.map +1 -1
- package/dist/Logger.d.ts +1 -1
- package/dist/PostPrompt.d.ts +19 -0
- package/dist/PostPrompt.js +43 -0
- package/dist/PostPrompt.js.map +1 -1
- package/dist/SWMLService.d.ts +151 -10
- package/dist/SWMLService.js +377 -61
- 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 +61 -1
- package/dist/SemanticGate.js +108 -15
- 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 +86 -9
- package/dist/SwaigFunction.js +215 -59
- package/dist/SwaigFunction.js.map +1 -1
- package/dist/ToolMiddleware.d.ts +82 -0
- package/dist/ToolMiddleware.js +131 -0
- package/dist/ToolMiddleware.js.map +1 -0
- package/dist/TypeInference.d.ts +2 -2
- package/dist/TypeInference.js +1 -1
- package/dist/TypeInference.js.map +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 +24 -4
- package/dist/cli/tsdocs/topics.js.map +1 -1
- package/dist/index.d.ts +23 -8
- package/dist/index.js +16 -5
- 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/llms.txt +1 -0
- package/dist/patterns/Proposal.d.ts +146 -0
- package/dist/patterns/Proposal.js +212 -0
- package/dist/patterns/Proposal.js.map +1 -0
- package/dist/patterns/RequestList.d.ts +136 -0
- package/dist/patterns/RequestList.js +169 -0
- package/dist/patterns/RequestList.js.map +1 -0
- 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 +26 -3
- package/dist/skills/SkillBase.js +14 -3
- package/dist/skills/SkillBase.js.map +1 -1
- package/dist/speech/numbers.d.ts +66 -0
- package/dist/speech/numbers.js +281 -0
- package/dist/speech/numbers.js.map +1 -0
- package/dist/speech/spelling.d.ts +71 -0
- package/dist/speech/spelling.js +294 -0
- package/dist/speech/spelling.js.map +1 -0
- package/dist/testing/CallSimulator.d.ts +281 -0
- package/dist/testing/CallSimulator.js +666 -0
- package/dist/testing/CallSimulator.js.map +1 -0
- package/docs/agent-guide.md +4 -4
- package/docs/api-reference.md +285 -28
- package/docs/architecture.md +8 -4
- package/docs/cli-guide.md +2 -0
- package/docs/contexts-guide.md +47 -4
- package/docs/conversation_patterns.md +257 -0
- package/docs/mcp_integration.md +1 -1
- package/docs/pgi_agent_guide.md +2 -1
- package/docs/programmatically_governed_inference.md +2 -2
- package/docs/swaig-reference.md +95 -3
- package/docs/swml_service_guide.md +31 -6
- package/package.json +3 -1
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A call, simulated in a test: the agent's tools, steps and state, without the
|
|
3
|
+
* platform or a model.
|
|
4
|
+
*
|
|
5
|
+
* {@link CallSimulator} reads the agent's rendered SWML, as the platform would,
|
|
6
|
+
* and plays the model's side: the test says what the caller says and which
|
|
7
|
+
* tools the model calls. Each call is checked as the platform checks it: a tool
|
|
8
|
+
* the current step doesn't offer doesn't run, and a gated tool runs only when
|
|
9
|
+
* the test's gate callback lets it. A result's actions change the simulated
|
|
10
|
+
* call: global data and `semantic_state`, the step and context, which functions
|
|
11
|
+
* are on, `say`, and the end of the call.
|
|
12
|
+
*
|
|
13
|
+
* It's an approximation of the platform, for testing your code's decisions. It
|
|
14
|
+
* doesn't run a model, DataMap tools (give a stub), gather questions, or the
|
|
15
|
+
* gates' decision model (give a callback). It renders and runs tools on the
|
|
16
|
+
* agent itself: a dynamic config callback's per-request copy isn't made.
|
|
17
|
+
*
|
|
18
|
+
* {@link RequestRecorder} records real tool requests for
|
|
19
|
+
* {@link CallSimulator.replay}.
|
|
20
|
+
*/
|
|
21
|
+
import { appendFile } from 'node:fs/promises';
|
|
22
|
+
import { readFileSync } from 'node:fs';
|
|
23
|
+
import { namedTools } from '../ContextBuilder.js';
|
|
24
|
+
import { FunctionResult } from '../FunctionResult.js';
|
|
25
|
+
import { RESERVED_FUNCTION_NAMES } from '../SemanticGate.js';
|
|
26
|
+
import { SwaigFunction } from '../SwaigFunction.js';
|
|
27
|
+
const NAVIGATION = ['next_step', 'change_context'];
|
|
28
|
+
// The most gate marks the platform keeps for a call
|
|
29
|
+
const MAX_MARKS = 16;
|
|
30
|
+
const VARIABLE = /\$\{([A-Za-z0-9_.]+)\}/g;
|
|
31
|
+
/** A tool result named a tool the step it left the call in doesn't offer. */
|
|
32
|
+
export class ToolMentionError extends Error {
|
|
33
|
+
name = 'ToolMentionError';
|
|
34
|
+
}
|
|
35
|
+
/** What one tool call came to in the simulation. */
|
|
36
|
+
export class SimulatedCall {
|
|
37
|
+
/** The tool's name. */
|
|
38
|
+
name;
|
|
39
|
+
/** The arguments the model sent. */
|
|
40
|
+
args;
|
|
41
|
+
/** The result, as the platform gets it. */
|
|
42
|
+
result;
|
|
43
|
+
/** Whether the tool's handler (or stub) ran. */
|
|
44
|
+
ran;
|
|
45
|
+
/**
|
|
46
|
+
* Why it didn't: "step" for a tool the step doesn't offer, or the id of the
|
|
47
|
+
* gate that blocked it.
|
|
48
|
+
*/
|
|
49
|
+
blockedBy;
|
|
50
|
+
/**
|
|
51
|
+
* @param name - The tool's name.
|
|
52
|
+
* @param args - The arguments the model sent.
|
|
53
|
+
* @param result - The result, as the platform gets it.
|
|
54
|
+
* @param opts - `ran`, and `blockedBy` for a call that didn't run.
|
|
55
|
+
*/
|
|
56
|
+
constructor(name, args, result, opts) {
|
|
57
|
+
this.name = name;
|
|
58
|
+
this.args = args;
|
|
59
|
+
this.result = result;
|
|
60
|
+
this.ran = opts.ran;
|
|
61
|
+
this.blockedBy = opts.blockedBy ?? null;
|
|
62
|
+
}
|
|
63
|
+
/** The result's text: its response, or its tool_result. */
|
|
64
|
+
get response() {
|
|
65
|
+
const response = this.result['response'] ?? '';
|
|
66
|
+
if (isRecord(response))
|
|
67
|
+
return String(response['tool_result'] ?? '');
|
|
68
|
+
return String(response);
|
|
69
|
+
}
|
|
70
|
+
/** The result's tool_prompt, or null when it has none. */
|
|
71
|
+
get toolPrompt() {
|
|
72
|
+
const response = this.result['response'];
|
|
73
|
+
if (!isRecord(response) || response['tool_prompt'] === undefined)
|
|
74
|
+
return null;
|
|
75
|
+
return response['tool_prompt'];
|
|
76
|
+
}
|
|
77
|
+
/** The result's actions. */
|
|
78
|
+
get actions() {
|
|
79
|
+
const action = this.result['action'] ?? [];
|
|
80
|
+
return (Array.isArray(action) ? action : [action]);
|
|
81
|
+
}
|
|
82
|
+
/** The call, for a test's failure message. */
|
|
83
|
+
toString() {
|
|
84
|
+
const state = this.ran ? 'ran' : `blocked by ${this.blockedBy}`;
|
|
85
|
+
return `<SimulatedCall ${this.name} ${state}: ${JSON.stringify(this.response)}>`;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* A simulated call to an agent, for tests.
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* ```ts
|
|
93
|
+
* import assert from 'node:assert';
|
|
94
|
+
* import { AgentBase, CallSimulator } from '@signalwire/sdk';
|
|
95
|
+
*
|
|
96
|
+
* declare const agent: AgentBase; // an agent with review_order and place_order steps
|
|
97
|
+
* const sim = new CallSimulator(agent, { gates: () => true });
|
|
98
|
+
* sim.caller("I'd like a large tea");
|
|
99
|
+
* assert.equal((await sim.call('place_order', { item: 'tea' })).ran, false); // not offered yet
|
|
100
|
+
* await sim.call('review_order', { item: 'large tea' });
|
|
101
|
+
* sim.caller('yes');
|
|
102
|
+
* assert.equal((await sim.call('place_order')).ran, true);
|
|
103
|
+
* assert.equal(sim.step, 'done');
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
export class CallSimulator {
|
|
107
|
+
/** The agent. */
|
|
108
|
+
agent;
|
|
109
|
+
/** The call's id, as the agent's tools see it. */
|
|
110
|
+
callId;
|
|
111
|
+
/** The AI verb's params, as rendered. */
|
|
112
|
+
params;
|
|
113
|
+
/** The call's global data. */
|
|
114
|
+
globalData;
|
|
115
|
+
/** The agent's functions, as rendered, by name. */
|
|
116
|
+
functions;
|
|
117
|
+
/** The conversation so far, as call log entries. */
|
|
118
|
+
callLog = [];
|
|
119
|
+
/** Whether a result ended the call. */
|
|
120
|
+
ended = false;
|
|
121
|
+
/** The back_to_back_functions setting, as the last result left it. */
|
|
122
|
+
chaining = 'forever';
|
|
123
|
+
/** Whether a result asked the model to wait for the caller. */
|
|
124
|
+
waitingForUser = false;
|
|
125
|
+
/** Every tool call so far. */
|
|
126
|
+
calls = [];
|
|
127
|
+
/**
|
|
128
|
+
* The semantic gate marks set, by name: the length of the call log when each
|
|
129
|
+
* was set, so `callLog.slice(marks.get(name))` is since it.
|
|
130
|
+
*/
|
|
131
|
+
marks = new Map();
|
|
132
|
+
/** The current context, null without contexts. */
|
|
133
|
+
context = null;
|
|
134
|
+
/** The current step, null without contexts. */
|
|
135
|
+
step = null;
|
|
136
|
+
gates;
|
|
137
|
+
stubs;
|
|
138
|
+
checkToolMentions;
|
|
139
|
+
contexts;
|
|
140
|
+
toggled = new Map();
|
|
141
|
+
toolCalls = 0;
|
|
142
|
+
stepFunctions;
|
|
143
|
+
/**
|
|
144
|
+
* @param agent - The agent.
|
|
145
|
+
* @param opts - `callId`, `gates`, `stubs` and `globalData`.
|
|
146
|
+
*/
|
|
147
|
+
constructor(agent, opts = {}) {
|
|
148
|
+
this.agent = agent;
|
|
149
|
+
this.callId = opts.callId ?? 'simulated-call';
|
|
150
|
+
this.gates = opts.gates;
|
|
151
|
+
this.stubs = { ...(opts.stubs ?? {}) };
|
|
152
|
+
this.checkToolMentions = opts.checkToolMentions ?? false;
|
|
153
|
+
const ai = aiVerb(JSON.parse(agent.renderSwml(this.callId)));
|
|
154
|
+
this.params = structuredClone(asRecord(ai['params']));
|
|
155
|
+
this.globalData = {
|
|
156
|
+
...structuredClone(asRecord(ai['global_data'])),
|
|
157
|
+
...structuredClone(opts.globalData ?? {}),
|
|
158
|
+
};
|
|
159
|
+
const swaig = asRecord(ai['SWAIG']);
|
|
160
|
+
const functions = Array.isArray(swaig['functions']) ? swaig['functions'] : [];
|
|
161
|
+
// No prototype, so a tool named __proto__ is a tool like any other
|
|
162
|
+
this.functions = Object.create(null);
|
|
163
|
+
for (const f of functions) {
|
|
164
|
+
if (isRecord(f) && 'function' in f)
|
|
165
|
+
this.functions[String(f['function'])] = f;
|
|
166
|
+
}
|
|
167
|
+
const prompt = ai['prompt'];
|
|
168
|
+
this.contexts = isRecord(prompt) ? asRecord(prompt['contexts']) : {};
|
|
169
|
+
this.stepFunctions = new Set(this.tools());
|
|
170
|
+
const names = Object.keys(this.contexts);
|
|
171
|
+
if (names.length > 0)
|
|
172
|
+
this.enterContext(names.includes('default') ? 'default' : names[0]);
|
|
173
|
+
}
|
|
174
|
+
// ── The conversation ────────────────────────────────────────────────
|
|
175
|
+
/**
|
|
176
|
+
* The caller says `text`.
|
|
177
|
+
* @param text - What they say.
|
|
178
|
+
* @returns This simulator, for chaining.
|
|
179
|
+
*/
|
|
180
|
+
caller(text) {
|
|
181
|
+
this.log({ role: 'user', content: text });
|
|
182
|
+
this.waitingForUser = false;
|
|
183
|
+
return this;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The agent says `text`, as the model's reply.
|
|
187
|
+
* @param text - What it says.
|
|
188
|
+
* @returns This simulator, for chaining.
|
|
189
|
+
*/
|
|
190
|
+
agentSays(text) {
|
|
191
|
+
this.log({ role: 'assistant', content: text });
|
|
192
|
+
return this;
|
|
193
|
+
}
|
|
194
|
+
/** `globalData.semantic_state`, or undefined. */
|
|
195
|
+
get semanticState() {
|
|
196
|
+
return this.globalData['semantic_state'];
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* The tools the model is offered now, as the current step allows, in the
|
|
200
|
+
* agent's order, with the navigation tools after them.
|
|
201
|
+
* @returns Their names.
|
|
202
|
+
*/
|
|
203
|
+
offered() {
|
|
204
|
+
const offered = Object.keys(this.functions).filter((name) => this.toggled.get(name) ?? this.stepFunctions.has(name));
|
|
205
|
+
const step = this.currentStep();
|
|
206
|
+
if (step && isNonEmpty(step['valid_steps']))
|
|
207
|
+
offered.push('next_step');
|
|
208
|
+
if (this.validContexts().length > 0)
|
|
209
|
+
offered.push('change_context');
|
|
210
|
+
return offered;
|
|
211
|
+
}
|
|
212
|
+
// ── Tool calls ──────────────────────────────────────────────────────
|
|
213
|
+
/**
|
|
214
|
+
* The model calls `name` with `args`.
|
|
215
|
+
*
|
|
216
|
+
* The call is checked as the platform checks it: a tool the current step
|
|
217
|
+
* doesn't offer, or one the platform doesn't know, doesn't run, and the model
|
|
218
|
+
* gets the platform's reply naming the tools it has. A gated tool runs only
|
|
219
|
+
* when every gate passes. Otherwise the tool runs as the `/swaig` route runs
|
|
220
|
+
* it, with a request like the platform's, and its result's actions change
|
|
221
|
+
* the call.
|
|
222
|
+
*
|
|
223
|
+
* @param name - The tool.
|
|
224
|
+
* @param args - Its arguments.
|
|
225
|
+
* @returns What the call came to.
|
|
226
|
+
* @throws Error when the call has ended, or for a DataMap tool without a stub.
|
|
227
|
+
* @throws {ToolMentionError} With `checkToolMentions`, for a result that names a
|
|
228
|
+
* tool the step it leaves the call in doesn't offer.
|
|
229
|
+
*/
|
|
230
|
+
async call(name, args = {}) {
|
|
231
|
+
if (this.ended)
|
|
232
|
+
throw new Error('the call has ended');
|
|
233
|
+
const callArgs = { ...args };
|
|
234
|
+
this.log({
|
|
235
|
+
role: 'assistant',
|
|
236
|
+
content: '',
|
|
237
|
+
tool_calls: [{ function: { name, arguments: JSON.stringify(callArgs) } }],
|
|
238
|
+
});
|
|
239
|
+
let outcome;
|
|
240
|
+
if (!this.offered().includes(name)) {
|
|
241
|
+
outcome = new SimulatedCall(name, callArgs, { response: this.unavailable(name) }, { ran: false, blockedBy: 'step' });
|
|
242
|
+
}
|
|
243
|
+
else if (NAVIGATION.includes(name)) {
|
|
244
|
+
outcome = this.navigate(name, callArgs);
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
outcome = await this.dispatch(name, callArgs);
|
|
248
|
+
}
|
|
249
|
+
this.log({ role: 'tool', content: outcome.response });
|
|
250
|
+
this.calls.push(outcome);
|
|
251
|
+
if (this.checkToolMentions && outcome.blockedBy !== 'step')
|
|
252
|
+
this.checkMentions(outcome);
|
|
253
|
+
return outcome;
|
|
254
|
+
}
|
|
255
|
+
checkMentions(outcome) {
|
|
256
|
+
const text = `${outcome.response} ${outcome.toolPrompt ?? ''}`;
|
|
257
|
+
const offered = new Set(this.offered());
|
|
258
|
+
const named = [...namedTools(text, this.tools())].filter((t) => !offered.has(t)).sort();
|
|
259
|
+
if (named.length > 0) {
|
|
260
|
+
const where = this.step ? `step '${this.step}'` : 'the call';
|
|
261
|
+
throw new ToolMentionError(`${outcome.name}'s result names ${named.join(', ')}, which ${where} doesn't offer: ` +
|
|
262
|
+
JSON.stringify(text.trim()));
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Run recorded tool requests against the agent again, as they came.
|
|
267
|
+
*
|
|
268
|
+
* Each request is a SWAIG request body, as {@link RequestRecorder} records
|
|
269
|
+
* it, with its own call data; the simulated call's state isn't used or
|
|
270
|
+
* changed. Use it to check that changed code still gives the results it gave
|
|
271
|
+
* on real calls.
|
|
272
|
+
*
|
|
273
|
+
* @param requests - The requests.
|
|
274
|
+
* @returns What each request came to, in order.
|
|
275
|
+
*/
|
|
276
|
+
async replay(requests) {
|
|
277
|
+
const outcomes = [];
|
|
278
|
+
for (const body of requests) {
|
|
279
|
+
const name = String(body['function'] ?? '');
|
|
280
|
+
const args = { ...this.agent._extractSwaigArgs(body) };
|
|
281
|
+
const result = await this.run(name, args, structuredClone(body));
|
|
282
|
+
outcomes.push(new SimulatedCall(name, args, result, { ran: true }));
|
|
283
|
+
}
|
|
284
|
+
return outcomes;
|
|
285
|
+
}
|
|
286
|
+
// ── Internals ───────────────────────────────────────────────────────
|
|
287
|
+
/** The agent's answer to a call, as the `/swaig` route gives it. */
|
|
288
|
+
async run(name, args, rawData) {
|
|
289
|
+
const hookResult = await this.agent.onFunctionCall(name, args, rawData);
|
|
290
|
+
if (hookResult !== undefined && hookResult !== null)
|
|
291
|
+
return asResult(hookResult);
|
|
292
|
+
const fn = this.agent.getTool(name);
|
|
293
|
+
// A function the SWML has that isn't a local tool was registered as a dict
|
|
294
|
+
if (fn === undefined && !Object.hasOwn(this.functions, name)) {
|
|
295
|
+
return { response: `Function '${name}' not found` };
|
|
296
|
+
}
|
|
297
|
+
if (!(fn instanceof SwaigFunction)) {
|
|
298
|
+
return {
|
|
299
|
+
response: `Data map function '${name}' should be executed by SignalWire server, not locally`,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
if (fn.webhookUrl) {
|
|
303
|
+
return {
|
|
304
|
+
response: `External webhook function '${name}' should be executed by SignalWire at ${fn.webhookUrl}, not locally`,
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
return asResult(await this.agent._executeFunction(fn, args, rawData));
|
|
308
|
+
}
|
|
309
|
+
async dispatch(name, args) {
|
|
310
|
+
const definition = this.functions[name];
|
|
311
|
+
const blocked = await this.checkGates(name, definition, args);
|
|
312
|
+
if (blocked !== null)
|
|
313
|
+
return blocked;
|
|
314
|
+
let result;
|
|
315
|
+
const stub = Object.hasOwn(this.stubs, name) ? this.stubs[name] : undefined;
|
|
316
|
+
if (stub) {
|
|
317
|
+
result = asResult(await stub(args));
|
|
318
|
+
}
|
|
319
|
+
else if ('data_map' in definition) {
|
|
320
|
+
throw new Error(`${name} is a DataMap tool, which runs on the platform; give a stub for it: ` +
|
|
321
|
+
'new CallSimulator(agent, { stubs: {...} })');
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
result = await this.run(name, args, this.request(name, args));
|
|
325
|
+
}
|
|
326
|
+
this.apply(result);
|
|
327
|
+
return new SimulatedCall(name, args, result, { ran: true });
|
|
328
|
+
}
|
|
329
|
+
async checkGates(name, definition, args) {
|
|
330
|
+
const gates = Array.isArray(definition['gates']) ? definition['gates'] : [];
|
|
331
|
+
let unclear = null;
|
|
332
|
+
for (const [index, gate] of gates.entries()) {
|
|
333
|
+
const answer = this.gates === undefined ? true : await this.gates(gate, this, args);
|
|
334
|
+
const gateId = String(gate['id'] ?? `gate_${index + 1}`);
|
|
335
|
+
if (answer === 'unclear') {
|
|
336
|
+
unclear ??= { ...gate, id: gateId };
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
const passed = typeof answer === 'number' ? answer >= Number(gate['threshold'] ?? 1) : Boolean(answer);
|
|
340
|
+
if (!passed)
|
|
341
|
+
return this.blocked(name, args, asRecord(gate['on_fail']), gateId);
|
|
342
|
+
}
|
|
343
|
+
if (unclear !== null) {
|
|
344
|
+
const onUnclear = isRecord(unclear['on_unclear'])
|
|
345
|
+
? unclear['on_unclear']
|
|
346
|
+
: { response: `${name} was not run. Ask the caller again.` };
|
|
347
|
+
return this.blocked(name, args, onUnclear, String(unclear['id']));
|
|
348
|
+
}
|
|
349
|
+
return null;
|
|
350
|
+
}
|
|
351
|
+
blocked(name, args, output, gateId) {
|
|
352
|
+
const result = expand(structuredClone(output), {
|
|
353
|
+
global_data: this.globalData,
|
|
354
|
+
args,
|
|
355
|
+
});
|
|
356
|
+
this.apply(result);
|
|
357
|
+
return new SimulatedCall(name, args, result, { ran: false, blockedBy: gateId });
|
|
358
|
+
}
|
|
359
|
+
navigate(name, args) {
|
|
360
|
+
if (name === 'next_step') {
|
|
361
|
+
const requested = String(args['step'] ?? '');
|
|
362
|
+
const valid = this.currentStep()?.['valid_steps'];
|
|
363
|
+
const target = requested === 'next' ? this.followingStep() : requested;
|
|
364
|
+
if (!Array.isArray(valid) || !valid.includes(requested) || target === null) {
|
|
365
|
+
return new SimulatedCall(name, args, { response: `${requested} is not a step you can go to.` }, { ran: false, blockedBy: 'step' });
|
|
366
|
+
}
|
|
367
|
+
this.enterStep(target);
|
|
368
|
+
return new SimulatedCall(name, args, { response: `Moved to step ${target}.` }, { ran: true });
|
|
369
|
+
}
|
|
370
|
+
const target = String(args['context'] ?? '');
|
|
371
|
+
if (!this.validContexts().includes(target) || !Object.hasOwn(this.contexts, target)) {
|
|
372
|
+
return new SimulatedCall(name, args, { response: `${target} is not a context you can go to.` }, { ran: false, blockedBy: 'step' });
|
|
373
|
+
}
|
|
374
|
+
this.enterContext(target);
|
|
375
|
+
return new SimulatedCall(name, args, { response: `Moved to context ${target}.` }, { ran: true });
|
|
376
|
+
}
|
|
377
|
+
request(name, args) {
|
|
378
|
+
this.toolCalls += 1;
|
|
379
|
+
const request = {
|
|
380
|
+
function: name,
|
|
381
|
+
argument: { parsed: [args], raw: JSON.stringify(args) },
|
|
382
|
+
call_id: this.callId,
|
|
383
|
+
tool_call_id: `${this.callId}-tool-${this.toolCalls}`,
|
|
384
|
+
global_data: structuredClone(this.globalData),
|
|
385
|
+
content_type: 'text/swaig',
|
|
386
|
+
version: '2.0',
|
|
387
|
+
};
|
|
388
|
+
if (this.params['swaig_post_conversation']) {
|
|
389
|
+
request['call_log'] = structuredClone(this.callLog);
|
|
390
|
+
request['raw_call_log'] = structuredClone(this.callLog);
|
|
391
|
+
}
|
|
392
|
+
return request;
|
|
393
|
+
}
|
|
394
|
+
apply(result) {
|
|
395
|
+
const actions = result['action'] ?? [];
|
|
396
|
+
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
397
|
+
if (!isRecord(action))
|
|
398
|
+
continue;
|
|
399
|
+
for (const [key, value] of Object.entries(action))
|
|
400
|
+
this.applyOne(key, value);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
applyOne(key, value) {
|
|
404
|
+
if (key === 'say') {
|
|
405
|
+
this.log({ role: 'assistant', content: String(value) });
|
|
406
|
+
}
|
|
407
|
+
else if (key === 'set_global_data' && isRecord(value)) {
|
|
408
|
+
Object.assign(this.globalData, structuredClone(value));
|
|
409
|
+
}
|
|
410
|
+
else if (key === 'unset_global_data') {
|
|
411
|
+
const names = typeof value === 'string' ? [value] : Array.isArray(value) ? value : [];
|
|
412
|
+
for (const name of names)
|
|
413
|
+
delete this.globalData[String(name)];
|
|
414
|
+
}
|
|
415
|
+
else if (key === 'change_step') {
|
|
416
|
+
this.enterStep(String(value));
|
|
417
|
+
}
|
|
418
|
+
else if (key === 'change_context') {
|
|
419
|
+
this.enterContext(String(value));
|
|
420
|
+
}
|
|
421
|
+
else if (key === 'toggle_functions' && Array.isArray(value)) {
|
|
422
|
+
for (const toggle of value) {
|
|
423
|
+
if (isRecord(toggle) && 'function' in toggle) {
|
|
424
|
+
this.toggled.set(String(toggle['function']), Boolean(toggle['active'] ?? true));
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
else if (key === 'back_to_back_functions') {
|
|
429
|
+
this.chaining = value;
|
|
430
|
+
}
|
|
431
|
+
else if (key === 'semantic_gate_mark') {
|
|
432
|
+
// The platform keeps a call's 16 newest names; setting one moves it
|
|
433
|
+
this.marks.delete(String(value));
|
|
434
|
+
this.marks.set(String(value), this.callLog.length);
|
|
435
|
+
while (this.marks.size > MAX_MARKS)
|
|
436
|
+
this.marks.delete(this.marks.keys().next().value);
|
|
437
|
+
}
|
|
438
|
+
else if (key === 'wait_for_user') {
|
|
439
|
+
this.waitingForUser = Boolean(value);
|
|
440
|
+
}
|
|
441
|
+
else if (key === 'hangup' || key === 'stop') {
|
|
442
|
+
this.ended = true;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
enterContext(name) {
|
|
446
|
+
if (!Object.hasOwn(this.contexts, name)) {
|
|
447
|
+
throw new Error(`the agent has no context ${JSON.stringify(name)}`);
|
|
448
|
+
}
|
|
449
|
+
const steps = this.stepsOf(name);
|
|
450
|
+
this.context = name;
|
|
451
|
+
this.stepFunctions = new Set(this.tools());
|
|
452
|
+
const initial = this.contexts[name]['initial_step'] || (steps[0]?.['name'] ?? null);
|
|
453
|
+
if (initial)
|
|
454
|
+
this.enterStep(String(initial));
|
|
455
|
+
}
|
|
456
|
+
enterStep(name) {
|
|
457
|
+
if (this.context === null)
|
|
458
|
+
return;
|
|
459
|
+
const step = this.findStep(name);
|
|
460
|
+
if (step === null) {
|
|
461
|
+
throw new Error(`context ${JSON.stringify(this.context)} has no step ${JSON.stringify(name)}`);
|
|
462
|
+
}
|
|
463
|
+
this.step = name;
|
|
464
|
+
const functions = step['functions'];
|
|
465
|
+
if (functions === 'none' || (Array.isArray(functions) && functions.length === 0)) {
|
|
466
|
+
this.stepFunctions = new Set();
|
|
467
|
+
}
|
|
468
|
+
else if (Array.isArray(functions)) {
|
|
469
|
+
this.stepFunctions = new Set(functions.map(String));
|
|
470
|
+
}
|
|
471
|
+
// A step without a function list keeps the set before it
|
|
472
|
+
}
|
|
473
|
+
stepsOf(context) {
|
|
474
|
+
if (context === null)
|
|
475
|
+
return [];
|
|
476
|
+
const steps = this.contexts[context]?.['steps'];
|
|
477
|
+
return Array.isArray(steps) ? steps.filter(isRecord) : [];
|
|
478
|
+
}
|
|
479
|
+
currentStep() {
|
|
480
|
+
return this.step === null ? null : this.findStep(this.step);
|
|
481
|
+
}
|
|
482
|
+
findStep(name) {
|
|
483
|
+
const step = this.stepsOf(this.context).find((s) => s['name'] === name);
|
|
484
|
+
return step ? { ...step } : null;
|
|
485
|
+
}
|
|
486
|
+
followingStep() {
|
|
487
|
+
const names = this.stepsOf(this.context).map((s) => s['name']);
|
|
488
|
+
const at = names.indexOf(this.step);
|
|
489
|
+
return at >= 0 && at + 1 < names.length ? String(names[at + 1]) : null;
|
|
490
|
+
}
|
|
491
|
+
validContexts() {
|
|
492
|
+
const step = this.currentStep() ?? {};
|
|
493
|
+
if (step['valid_contexts'] !== undefined && step['valid_contexts'] !== null) {
|
|
494
|
+
return step['valid_contexts'].map(String);
|
|
495
|
+
}
|
|
496
|
+
if (this.context !== null) {
|
|
497
|
+
const valid = this.contexts[this.context]['valid_contexts'];
|
|
498
|
+
return Array.isArray(valid) ? valid.map(String) : [];
|
|
499
|
+
}
|
|
500
|
+
return [];
|
|
501
|
+
}
|
|
502
|
+
tools() {
|
|
503
|
+
return Object.keys(this.functions).filter((name) => !RESERVED_FUNCTION_NAMES.has(name));
|
|
504
|
+
}
|
|
505
|
+
/** The current context's other steps whose functions include `name`, in step order. */
|
|
506
|
+
stepsOffering(name) {
|
|
507
|
+
return this.stepsOf(this.context)
|
|
508
|
+
.filter((step) => step['name'] !== this.step &&
|
|
509
|
+
Array.isArray(step['functions']) &&
|
|
510
|
+
step['functions'].includes(name))
|
|
511
|
+
.map((step) => String(step['name']));
|
|
512
|
+
}
|
|
513
|
+
/** The platform's reply to a call of a tool it won't run now. */
|
|
514
|
+
unavailable(name) {
|
|
515
|
+
const offered = this.offered();
|
|
516
|
+
const tools = offered.join(', ');
|
|
517
|
+
const known = Object.hasOwn(this.functions, name);
|
|
518
|
+
const steps = known ? this.stepsOffering(name).join(', ') : '';
|
|
519
|
+
const template = this.params['unavailable_function_response'];
|
|
520
|
+
if (typeof template === 'string' && template) {
|
|
521
|
+
return template
|
|
522
|
+
.replaceAll('${function}', () => name)
|
|
523
|
+
.replaceAll('${tools}', () => tools)
|
|
524
|
+
.replaceAll('${steps}', () => steps);
|
|
525
|
+
}
|
|
526
|
+
let text;
|
|
527
|
+
if (known) {
|
|
528
|
+
text = `Nothing ran: ${name} isn't available at this point in the call.`;
|
|
529
|
+
if (steps)
|
|
530
|
+
text += ` The steps that offer it: ${steps}.`;
|
|
531
|
+
}
|
|
532
|
+
else {
|
|
533
|
+
text = `Nothing ran: there is no tool named ${name}.`;
|
|
534
|
+
}
|
|
535
|
+
if (offered.length > 0)
|
|
536
|
+
return `${text} The tools available now are: ${tools}.\n`;
|
|
537
|
+
return `${text} No tools are available now.\n`;
|
|
538
|
+
}
|
|
539
|
+
log(entry) {
|
|
540
|
+
this.callLog.push({ ...entry, timestamp: Date.now() * 1000 });
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Tool middleware that records each tool request, for
|
|
545
|
+
* {@link CallSimulator.replay}.
|
|
546
|
+
*
|
|
547
|
+
* @example
|
|
548
|
+
* ```ts
|
|
549
|
+
* import { AgentBase, CallSimulator, RequestRecorder } from '@signalwire/sdk';
|
|
550
|
+
*
|
|
551
|
+
* declare const agent: AgentBase;
|
|
552
|
+
* const recorder = new RequestRecorder('tool_requests.jsonl');
|
|
553
|
+
* agent.addToolMiddleware(recorder.middleware);
|
|
554
|
+
* // ...
|
|
555
|
+
* await new CallSimulator(agent).replay(RequestRecorder.load('tool_requests.jsonl'));
|
|
556
|
+
* ```
|
|
557
|
+
*
|
|
558
|
+
* The requests carry what the caller said and the call's data: keep the file
|
|
559
|
+
* where you'd keep call recordings.
|
|
560
|
+
*/
|
|
561
|
+
export class RequestRecorder {
|
|
562
|
+
/** A file each request is appended to, one JSON object a line. */
|
|
563
|
+
path;
|
|
564
|
+
/** The most requests kept in `requests`. */
|
|
565
|
+
limit;
|
|
566
|
+
/** The requests recorded, oldest first. */
|
|
567
|
+
requests = [];
|
|
568
|
+
/** The file's writes, in the order the requests came. */
|
|
569
|
+
writes = Promise.resolve();
|
|
570
|
+
/**
|
|
571
|
+
* @param path - A file to append each request to, one JSON object a line.
|
|
572
|
+
* @param opts - `limit`.
|
|
573
|
+
*/
|
|
574
|
+
constructor(path, opts = {}) {
|
|
575
|
+
this.path = path ?? null;
|
|
576
|
+
this.limit = opts.limit ?? 1000;
|
|
577
|
+
}
|
|
578
|
+
/** This recorder as a {@link ToolMiddleware}. */
|
|
579
|
+
middleware = (name, args, rawData, callNext) => this.handle(name, args, rawData, callNext);
|
|
580
|
+
/**
|
|
581
|
+
* Record a request, then run the rest of the chain.
|
|
582
|
+
* @param name - The tool's name.
|
|
583
|
+
* @param args - The arguments.
|
|
584
|
+
* @param rawData - The SWAIG request.
|
|
585
|
+
* @param callNext - The rest of the chain.
|
|
586
|
+
* @returns The call's result.
|
|
587
|
+
*/
|
|
588
|
+
async handle(name, args, rawData, callNext) {
|
|
589
|
+
const request = structuredClone(rawData);
|
|
590
|
+
if (!('function' in request))
|
|
591
|
+
request['function'] = name;
|
|
592
|
+
if (!('argument' in request)) {
|
|
593
|
+
request['argument'] = { parsed: [args], raw: JSON.stringify(args) };
|
|
594
|
+
}
|
|
595
|
+
this.requests.push(request);
|
|
596
|
+
this.requests.splice(0, Math.max(0, this.requests.length - this.limit));
|
|
597
|
+
if (this.path !== null) {
|
|
598
|
+
const line = JSON.stringify(request, (_key, value) => typeof value === 'bigint' ? value.toString() : value);
|
|
599
|
+
const path = this.path;
|
|
600
|
+
const write = this.writes.then(() => appendFile(path, `${line}\n`, 'utf-8'));
|
|
601
|
+
// A failed write doesn't stop the writes after it
|
|
602
|
+
this.writes = write.catch(() => undefined);
|
|
603
|
+
await write;
|
|
604
|
+
}
|
|
605
|
+
return await callNext(args, rawData);
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* The requests a recorder wrote to `path`.
|
|
609
|
+
* @param path - The file.
|
|
610
|
+
* @returns The requests, in order.
|
|
611
|
+
*/
|
|
612
|
+
static load(path) {
|
|
613
|
+
return readFileSync(path, 'utf-8')
|
|
614
|
+
.split(/\r?\n/)
|
|
615
|
+
.filter((line) => line.trim())
|
|
616
|
+
.map((line) => JSON.parse(line));
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
function aiVerb(swml) {
|
|
620
|
+
const main = asRecord(swml['sections'])['main'];
|
|
621
|
+
for (const verb of Array.isArray(main) ? main : []) {
|
|
622
|
+
if (isRecord(verb) && isRecord(verb['ai']))
|
|
623
|
+
return verb['ai'];
|
|
624
|
+
}
|
|
625
|
+
throw new Error("the agent's SWML has no ai verb");
|
|
626
|
+
}
|
|
627
|
+
function asResult(result) {
|
|
628
|
+
if (result instanceof FunctionResult)
|
|
629
|
+
return result.toDict();
|
|
630
|
+
if (isRecord(result))
|
|
631
|
+
return result;
|
|
632
|
+
return { response: String(result) };
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* `${...}` variables in a gate's output, from the call's data, as the platform
|
|
636
|
+
* expands them once; a variable it can't find is left as it is.
|
|
637
|
+
*/
|
|
638
|
+
function expand(value, data) {
|
|
639
|
+
if (typeof value === 'string') {
|
|
640
|
+
return value.replace(VARIABLE, (match, path) => {
|
|
641
|
+
let found = data;
|
|
642
|
+
for (const part of path.split('.')) {
|
|
643
|
+
if (!isRecord(found) || !Object.hasOwn(found, part))
|
|
644
|
+
return match;
|
|
645
|
+
found = found[part];
|
|
646
|
+
}
|
|
647
|
+
return typeof found === 'string' ? found : JSON.stringify(found);
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
if (Array.isArray(value))
|
|
651
|
+
return value.map((v) => expand(v, data));
|
|
652
|
+
if (isRecord(value)) {
|
|
653
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, expand(v, data)]));
|
|
654
|
+
}
|
|
655
|
+
return value;
|
|
656
|
+
}
|
|
657
|
+
function isRecord(value) {
|
|
658
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
659
|
+
}
|
|
660
|
+
function asRecord(value) {
|
|
661
|
+
return isRecord(value) ? value : {};
|
|
662
|
+
}
|
|
663
|
+
function isNonEmpty(value) {
|
|
664
|
+
return Array.isArray(value) ? value.length > 0 : Boolean(value);
|
|
665
|
+
}
|
|
666
|
+
//# sourceMappingURL=CallSimulator.js.map
|