@signalwire/sdk 3.7.2 → 3.10.3
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 +201 -0
- package/README.md +1 -0
- package/dist/AgentBase.d.ts +107 -2
- package/dist/AgentBase.js +259 -13
- package/dist/AgentBase.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 +215 -14
- package/dist/ContextBuilder.js +441 -14
- package/dist/ContextBuilder.js.map +1 -1
- package/dist/FunctionResult.d.ts +146 -1
- package/dist/FunctionResult.js +188 -2
- package/dist/FunctionResult.js.map +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 +97 -1
- package/dist/SWMLService.js +129 -2
- package/dist/SWMLService.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/SwaigFunction.d.ts +85 -9
- package/dist/SwaigFunction.js +214 -58
- 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 +1 -1
- package/dist/TypeInference.js.map +1 -1
- 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 +22 -8
- package/dist/index.js +15 -5
- package/dist/index.js.map +1 -1
- package/dist/llms.txt +1 -0
- package/dist/patterns/Proposal.d.ts +148 -0
- package/dist/patterns/Proposal.js +214 -0
- package/dist/patterns/Proposal.js.map +1 -0
- package/dist/patterns/RequestList.d.ts +138 -0
- package/dist/patterns/RequestList.js +171 -0
- package/dist/patterns/RequestList.js.map +1 -0
- package/dist/skills/SkillBase.d.ts +24 -1
- package/dist/skills/SkillBase.js +12 -1
- 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 +391 -0
- package/dist/testing/CallSimulator.js +966 -0
- package/dist/testing/CallSimulator.js.map +1 -0
- package/docs/agent-guide.md +2 -2
- package/docs/api-reference.md +279 -22
- package/docs/architecture.md +8 -4
- package/docs/cli-guide.md +2 -0
- package/docs/contexts-guide.md +75 -4
- package/docs/conversation_patterns.md +257 -0
- package/docs/mcp_integration.md +1 -1
- package/docs/pgi_agent_guide.md +5 -0
- package/docs/programmatically_governed_inference.md +2 -2
- package/docs/swaig-reference.md +98 -6
- package/package.json +1 -1
|
@@ -0,0 +1,966 @@
|
|
|
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,
|
|
15
|
+
* consolidation, the sliding window, or the gates' decision model (give a
|
|
16
|
+
* callback). {@link CallSimulator.modelView} shows what the model gets after
|
|
17
|
+
* the steps' history modes, and {@link CallSimulator.gateConversation} the
|
|
18
|
+
* dialogue a gate judges. It renders and runs tools on the
|
|
19
|
+
* agent itself: a dynamic config callback's per-request copy isn't made.
|
|
20
|
+
*
|
|
21
|
+
* {@link RequestRecorder} records real tool requests for
|
|
22
|
+
* {@link CallSimulator.replay}.
|
|
23
|
+
*/
|
|
24
|
+
import { appendFile } from 'node:fs/promises';
|
|
25
|
+
import { readFileSync } from 'node:fs';
|
|
26
|
+
import { namedTools } from '../ContextBuilder.js';
|
|
27
|
+
import { FunctionResult } from '../FunctionResult.js';
|
|
28
|
+
import { RESERVED_FUNCTION_NAMES } from '../SemanticGate.js';
|
|
29
|
+
import { SwaigFunction } from '../SwaigFunction.js';
|
|
30
|
+
const NAVIGATION = ['next_step', 'change_context'];
|
|
31
|
+
// The most gate marks the platform keeps for a call
|
|
32
|
+
const MAX_MARKS = 16;
|
|
33
|
+
const VARIABLE = /\$\{([A-Za-z0-9_.]+)\}/g;
|
|
34
|
+
/** A tool result named a tool the step it left the call in doesn't offer. */
|
|
35
|
+
export class ToolMentionError extends Error {
|
|
36
|
+
name = 'ToolMentionError';
|
|
37
|
+
}
|
|
38
|
+
/** What one tool call came to in the simulation. */
|
|
39
|
+
export class SimulatedCall {
|
|
40
|
+
/** The tool's name. */
|
|
41
|
+
name;
|
|
42
|
+
/** The arguments the model sent. */
|
|
43
|
+
args;
|
|
44
|
+
/** The result, as the platform gets it. */
|
|
45
|
+
result;
|
|
46
|
+
/** Whether the tool's handler (or stub) ran. */
|
|
47
|
+
ran;
|
|
48
|
+
/**
|
|
49
|
+
* Why it didn't: "step" for a tool the step doesn't offer, or the id of the
|
|
50
|
+
* gate that blocked it.
|
|
51
|
+
*/
|
|
52
|
+
blockedBy;
|
|
53
|
+
/**
|
|
54
|
+
* @param name - The tool's name.
|
|
55
|
+
* @param args - The arguments the model sent.
|
|
56
|
+
* @param result - The result, as the platform gets it.
|
|
57
|
+
* @param opts - `ran`, and `blockedBy` for a call that didn't run.
|
|
58
|
+
*/
|
|
59
|
+
constructor(name, args, result, opts) {
|
|
60
|
+
this.name = name;
|
|
61
|
+
this.args = args;
|
|
62
|
+
this.result = result;
|
|
63
|
+
this.ran = opts.ran;
|
|
64
|
+
this.blockedBy = opts.blockedBy ?? null;
|
|
65
|
+
}
|
|
66
|
+
/** The result's text: its response, or its tool_result. */
|
|
67
|
+
get response() {
|
|
68
|
+
const response = this.result['response'] ?? '';
|
|
69
|
+
if (isRecord(response))
|
|
70
|
+
return String(response['tool_result'] ?? '');
|
|
71
|
+
return String(response);
|
|
72
|
+
}
|
|
73
|
+
/** The result's tool_prompt, or null when it has none. */
|
|
74
|
+
get toolPrompt() {
|
|
75
|
+
const response = this.result['response'];
|
|
76
|
+
if (!isRecord(response) || response['tool_prompt'] === undefined)
|
|
77
|
+
return null;
|
|
78
|
+
return response['tool_prompt'];
|
|
79
|
+
}
|
|
80
|
+
/** The result's actions. */
|
|
81
|
+
get actions() {
|
|
82
|
+
const action = this.result['action'] ?? [];
|
|
83
|
+
return (Array.isArray(action) ? action : [action]);
|
|
84
|
+
}
|
|
85
|
+
/** The call, for a test's failure message. */
|
|
86
|
+
toString() {
|
|
87
|
+
const state = this.ran ? 'ran' : `blocked by ${this.blockedBy}`;
|
|
88
|
+
return `<SimulatedCall ${this.name} ${state}: ${JSON.stringify(this.response)}>`;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* A simulated call to an agent, for tests.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* ```ts
|
|
96
|
+
* import assert from 'node:assert';
|
|
97
|
+
* import { AgentBase, CallSimulator } from '@signalwire/sdk';
|
|
98
|
+
*
|
|
99
|
+
* declare const agent: AgentBase; // an agent with review_order and place_order steps
|
|
100
|
+
* const sim = new CallSimulator(agent, { gates: () => true });
|
|
101
|
+
* sim.caller("I'd like a large tea");
|
|
102
|
+
* assert.equal((await sim.call('place_order', { item: 'tea' })).ran, false); // not offered yet
|
|
103
|
+
* await sim.call('review_order', { item: 'large tea' });
|
|
104
|
+
* sim.caller('yes');
|
|
105
|
+
* assert.equal((await sim.call('place_order')).ran, true);
|
|
106
|
+
* assert.equal(sim.step, 'done');
|
|
107
|
+
* ```
|
|
108
|
+
*/
|
|
109
|
+
export class CallSimulator {
|
|
110
|
+
/** The agent. */
|
|
111
|
+
agent;
|
|
112
|
+
/** The call's id, as the agent's tools see it. */
|
|
113
|
+
callId;
|
|
114
|
+
/** The AI verb's params, as rendered. */
|
|
115
|
+
params;
|
|
116
|
+
/** The call's global data. */
|
|
117
|
+
globalData;
|
|
118
|
+
/** The agent's functions, as rendered, by name. */
|
|
119
|
+
functions;
|
|
120
|
+
/** The conversation so far, as call log entries. */
|
|
121
|
+
callLog = [];
|
|
122
|
+
/** Whether a result ended the call. */
|
|
123
|
+
ended = false;
|
|
124
|
+
/** The back_to_back_functions setting, as the last result left it. */
|
|
125
|
+
chaining = 'forever';
|
|
126
|
+
/** Whether a result asked the model to wait for the caller. */
|
|
127
|
+
waitingForUser = false;
|
|
128
|
+
/** Every tool call so far. */
|
|
129
|
+
calls = [];
|
|
130
|
+
/**
|
|
131
|
+
* The semantic gate marks set, by name: the call log position where the
|
|
132
|
+
* action list that set each began, so `callLog.slice(marks.get(name))` is
|
|
133
|
+
* since it.
|
|
134
|
+
*/
|
|
135
|
+
marks = new Map();
|
|
136
|
+
/** The current context, null without contexts. */
|
|
137
|
+
context = null;
|
|
138
|
+
/** The current step, null without contexts. */
|
|
139
|
+
step = null;
|
|
140
|
+
gates;
|
|
141
|
+
stubs;
|
|
142
|
+
checkToolMentions;
|
|
143
|
+
contexts;
|
|
144
|
+
toggled = new Map();
|
|
145
|
+
toolCalls = 0;
|
|
146
|
+
stepFunctions;
|
|
147
|
+
// What the model sees: each call log entry's kind, and which are out of its
|
|
148
|
+
// view (see modelView)
|
|
149
|
+
kinds = new Map();
|
|
150
|
+
hidden = new Set();
|
|
151
|
+
isolatedEntries = new Set();
|
|
152
|
+
cleared = new Set();
|
|
153
|
+
// The entries that are a result's say
|
|
154
|
+
says = new Set();
|
|
155
|
+
injectPending = false;
|
|
156
|
+
// Where the call whose actions are running started, and where the exchange
|
|
157
|
+
// that entered the current step starts: spoken, hide and isolate keep it.
|
|
158
|
+
// Null when nothing is kept: a change by next_step
|
|
159
|
+
callStart = null;
|
|
160
|
+
enteredAt = 0;
|
|
161
|
+
// A post_process result's actions, waiting for the model's reply, and where
|
|
162
|
+
// their call started
|
|
163
|
+
deferred = null;
|
|
164
|
+
// The current step's instruction entry and its text before expansion, and
|
|
165
|
+
// each instruction's text as the model gets it now, when the platform
|
|
166
|
+
// expanded it again
|
|
167
|
+
instruction = null;
|
|
168
|
+
shown = new Map();
|
|
169
|
+
// Where the proposal (semantic_state's last change) starts in the call log
|
|
170
|
+
proposalAt = null;
|
|
171
|
+
actionStart = 0;
|
|
172
|
+
// A reset step the call entered: past it, the model's view isn't simulated
|
|
173
|
+
resetStep = null;
|
|
174
|
+
/**
|
|
175
|
+
* @param agent - The agent.
|
|
176
|
+
* @param opts - `callId`, `gates`, `stubs` and `globalData`.
|
|
177
|
+
*/
|
|
178
|
+
constructor(agent, opts = {}) {
|
|
179
|
+
this.agent = agent;
|
|
180
|
+
this.callId = opts.callId ?? 'simulated-call';
|
|
181
|
+
this.gates = opts.gates;
|
|
182
|
+
this.stubs = { ...(opts.stubs ?? {}) };
|
|
183
|
+
this.checkToolMentions = opts.checkToolMentions ?? false;
|
|
184
|
+
const ai = aiVerb(JSON.parse(agent.renderSwml(this.callId)));
|
|
185
|
+
this.params = structuredClone(asRecord(ai['params']));
|
|
186
|
+
this.globalData = {
|
|
187
|
+
...structuredClone(asRecord(ai['global_data'])),
|
|
188
|
+
...structuredClone(opts.globalData ?? {}),
|
|
189
|
+
};
|
|
190
|
+
const swaig = asRecord(ai['SWAIG']);
|
|
191
|
+
const functions = Array.isArray(swaig['functions']) ? swaig['functions'] : [];
|
|
192
|
+
// No prototype, so a tool named __proto__ is a tool like any other
|
|
193
|
+
this.functions = Object.create(null);
|
|
194
|
+
for (const f of functions) {
|
|
195
|
+
if (isRecord(f) && 'function' in f)
|
|
196
|
+
this.functions[String(f['function'])] = f;
|
|
197
|
+
}
|
|
198
|
+
const prompt = ai['prompt'];
|
|
199
|
+
this.contexts = isRecord(prompt) ? asRecord(prompt['contexts']) : {};
|
|
200
|
+
this.stepFunctions = new Set(this.tools());
|
|
201
|
+
const names = Object.keys(this.contexts);
|
|
202
|
+
if (names.length > 0)
|
|
203
|
+
this.enterContext(names.includes('default') ? 'default' : names[0]);
|
|
204
|
+
this.inject();
|
|
205
|
+
}
|
|
206
|
+
// ── The conversation ────────────────────────────────────────────────
|
|
207
|
+
/**
|
|
208
|
+
* The caller says `text`.
|
|
209
|
+
* @param text - What they say.
|
|
210
|
+
* @returns This simulator, for chaining.
|
|
211
|
+
*/
|
|
212
|
+
caller(text) {
|
|
213
|
+
// Stored before the next request, which is when a pending step is injected
|
|
214
|
+
this.log({ role: 'user', content: text }, 'spoken');
|
|
215
|
+
this.waitingForUser = false;
|
|
216
|
+
return this;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The agent says `text`, as the model's reply. The actions of a
|
|
220
|
+
* `post_process` result waiting for it run after it.
|
|
221
|
+
* @param text - What it says.
|
|
222
|
+
* @returns This simulator, for chaining.
|
|
223
|
+
*/
|
|
224
|
+
agentSays(text) {
|
|
225
|
+
this.inject();
|
|
226
|
+
this.log({ role: 'assistant', content: text }, 'spoken');
|
|
227
|
+
if (this.deferred !== null) {
|
|
228
|
+
const { actions, callStart } = this.deferred;
|
|
229
|
+
this.deferred = null;
|
|
230
|
+
this.callStart = callStart;
|
|
231
|
+
this.runActions(actions);
|
|
232
|
+
this.callStart = null;
|
|
233
|
+
}
|
|
234
|
+
return this;
|
|
235
|
+
}
|
|
236
|
+
/** `globalData.semantic_state`, or undefined. */
|
|
237
|
+
get semanticState() {
|
|
238
|
+
return this.globalData['semantic_state'];
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* The tools the model is offered now, as the current step allows, in the
|
|
242
|
+
* agent's order, with the navigation tools after them.
|
|
243
|
+
* @returns Their names.
|
|
244
|
+
*/
|
|
245
|
+
offered() {
|
|
246
|
+
const offered = Object.keys(this.functions).filter((name) => this.toggled.get(name) ?? this.stepFunctions.has(name));
|
|
247
|
+
const step = this.currentStep();
|
|
248
|
+
if (step && isNonEmpty(step['valid_steps']))
|
|
249
|
+
offered.push('next_step');
|
|
250
|
+
if (this.validContexts().length > 0)
|
|
251
|
+
offered.push('change_context');
|
|
252
|
+
return offered;
|
|
253
|
+
}
|
|
254
|
+
// ── Tool calls ──────────────────────────────────────────────────────
|
|
255
|
+
/**
|
|
256
|
+
* The model calls `name` with `args`.
|
|
257
|
+
*
|
|
258
|
+
* The call is checked as the platform checks it: a tool the current step
|
|
259
|
+
* doesn't offer, or one the platform doesn't know, doesn't run, and the model
|
|
260
|
+
* gets the platform's reply naming the tools it has. A gated tool runs only
|
|
261
|
+
* when every gate passes. Otherwise the tool runs as the `/swaig` route runs
|
|
262
|
+
* it, with a request like the platform's, and its result's actions change
|
|
263
|
+
* the call. A result with `post_process` runs its actions after the model's
|
|
264
|
+
* reply to it, as the platform does: give the reply with {@link agentSays}. A
|
|
265
|
+
* newer such result replaces actions still waiting.
|
|
266
|
+
*
|
|
267
|
+
* @param name - The tool.
|
|
268
|
+
* @param args - Its arguments.
|
|
269
|
+
* @returns What the call came to.
|
|
270
|
+
* @throws Error when the call has ended, or for a DataMap tool without a stub.
|
|
271
|
+
* @throws {ToolMentionError} With `checkToolMentions`, for a result that names a
|
|
272
|
+
* tool the step it leaves the call in doesn't offer.
|
|
273
|
+
*/
|
|
274
|
+
async call(name, args = {}) {
|
|
275
|
+
if (this.ended)
|
|
276
|
+
throw new Error('the call has ended');
|
|
277
|
+
const callArgs = { ...args };
|
|
278
|
+
this.inject();
|
|
279
|
+
this.callStart = this.callLog.length;
|
|
280
|
+
this.log({
|
|
281
|
+
role: 'assistant',
|
|
282
|
+
content: '',
|
|
283
|
+
tool_calls: [{ function: { name, arguments: JSON.stringify(callArgs) } }],
|
|
284
|
+
}, 'tool_call');
|
|
285
|
+
let outcome;
|
|
286
|
+
if (!this.offered().includes(name)) {
|
|
287
|
+
outcome = new SimulatedCall(name, callArgs, { response: this.unavailable(name) }, { ran: false, blockedBy: 'step' });
|
|
288
|
+
}
|
|
289
|
+
else if (NAVIGATION.includes(name)) {
|
|
290
|
+
outcome = this.navigate(name, callArgs);
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
outcome = await this.dispatch(name, callArgs);
|
|
294
|
+
}
|
|
295
|
+
this.log({ role: 'tool', content: outcome.response }, 'tool_result');
|
|
296
|
+
if (outcome.toolPrompt) {
|
|
297
|
+
// The platform adds a result's tool_prompt as a system note
|
|
298
|
+
this.log({ role: 'system', content: outcome.toolPrompt }, 'note');
|
|
299
|
+
}
|
|
300
|
+
this.calls.push(outcome);
|
|
301
|
+
this.callStart = null;
|
|
302
|
+
// A call whose result changed the step gets its follow-up request right
|
|
303
|
+
// away, and the new step is injected before it
|
|
304
|
+
this.inject();
|
|
305
|
+
if (this.checkToolMentions && outcome.blockedBy !== 'step')
|
|
306
|
+
this.checkMentions(outcome);
|
|
307
|
+
return outcome;
|
|
308
|
+
}
|
|
309
|
+
checkMentions(outcome) {
|
|
310
|
+
const text = `${outcome.response} ${outcome.toolPrompt ?? ''}`;
|
|
311
|
+
const offered = new Set(this.offered());
|
|
312
|
+
const named = [...namedTools(text, this.tools())].filter((t) => !offered.has(t)).sort();
|
|
313
|
+
if (named.length > 0) {
|
|
314
|
+
const where = this.step ? `step '${this.step}'` : 'the call';
|
|
315
|
+
throw new ToolMentionError(`${outcome.name}'s result names ${named.join(', ')}, which ${where} doesn't offer: ` +
|
|
316
|
+
JSON.stringify(text.trim()));
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Run recorded tool requests against the agent again, as they came.
|
|
321
|
+
*
|
|
322
|
+
* Each request is a SWAIG request body, as {@link RequestRecorder} records
|
|
323
|
+
* it, with its own call data; the simulated call's state isn't used or
|
|
324
|
+
* changed. Use it to check that changed code still gives the results it gave
|
|
325
|
+
* on real calls.
|
|
326
|
+
*
|
|
327
|
+
* @param requests - The requests.
|
|
328
|
+
* @returns What each request came to, in order.
|
|
329
|
+
*/
|
|
330
|
+
async replay(requests) {
|
|
331
|
+
const outcomes = [];
|
|
332
|
+
for (const body of requests) {
|
|
333
|
+
const name = String(body['function'] ?? '');
|
|
334
|
+
const args = { ...this.agent._extractSwaigArgs(body) };
|
|
335
|
+
const result = await this.run(name, args, structuredClone(body));
|
|
336
|
+
outcomes.push(new SimulatedCall(name, args, result, { ran: true }));
|
|
337
|
+
}
|
|
338
|
+
return outcomes;
|
|
339
|
+
}
|
|
340
|
+
// ── Internals ───────────────────────────────────────────────────────
|
|
341
|
+
/** The agent's answer to a call, as the `/swaig` route gives it. */
|
|
342
|
+
async run(name, args, rawData) {
|
|
343
|
+
const hookResult = await this.agent.onFunctionCall(name, args, rawData);
|
|
344
|
+
if (hookResult !== undefined && hookResult !== null)
|
|
345
|
+
return asResult(hookResult);
|
|
346
|
+
const fn = this.agent.getTool(name);
|
|
347
|
+
// A function the SWML has that isn't a local tool was registered as a dict
|
|
348
|
+
if (fn === undefined && !Object.hasOwn(this.functions, name)) {
|
|
349
|
+
return { response: `Function '${name}' not found` };
|
|
350
|
+
}
|
|
351
|
+
if (!(fn instanceof SwaigFunction)) {
|
|
352
|
+
return {
|
|
353
|
+
response: `Data map function '${name}' should be executed by SignalWire server, not locally`,
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
if (fn.webhookUrl) {
|
|
357
|
+
return {
|
|
358
|
+
response: `External webhook function '${name}' should be executed by SignalWire at ${fn.webhookUrl}, not locally`,
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
return asResult(await this.agent._executeFunction(fn, args, rawData));
|
|
362
|
+
}
|
|
363
|
+
async dispatch(name, args) {
|
|
364
|
+
const definition = this.functions[name];
|
|
365
|
+
const blocked = await this.checkGates(name, definition, args);
|
|
366
|
+
if (blocked !== null)
|
|
367
|
+
return blocked;
|
|
368
|
+
let result;
|
|
369
|
+
const stub = Object.hasOwn(this.stubs, name) ? this.stubs[name] : undefined;
|
|
370
|
+
if (stub) {
|
|
371
|
+
result = asResult(await stub(args));
|
|
372
|
+
}
|
|
373
|
+
else if ('data_map' in definition) {
|
|
374
|
+
throw new Error(`${name} is a DataMap tool, which runs on the platform; give a stub for it: ` +
|
|
375
|
+
'new CallSimulator(agent, { stubs: {...} })');
|
|
376
|
+
}
|
|
377
|
+
else {
|
|
378
|
+
result = await this.run(name, args, this.request(name, args));
|
|
379
|
+
}
|
|
380
|
+
this.apply(result);
|
|
381
|
+
return new SimulatedCall(name, args, result, { ran: true });
|
|
382
|
+
}
|
|
383
|
+
async checkGates(name, definition, args) {
|
|
384
|
+
const gates = Array.isArray(definition['gates']) ? definition['gates'] : [];
|
|
385
|
+
let unclear = null;
|
|
386
|
+
for (const [index, gate] of gates.entries()) {
|
|
387
|
+
const answer = this.gates === undefined ? true : await this.gates(gate, this, args);
|
|
388
|
+
const gateId = String(gate['id'] ?? `gate_${index + 1}`);
|
|
389
|
+
if (answer === 'unclear') {
|
|
390
|
+
unclear ??= { ...gate, id: gateId };
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
const passed = typeof answer === 'number' ? answer >= Number(gate['threshold'] ?? 1) : Boolean(answer);
|
|
394
|
+
if (!passed)
|
|
395
|
+
return this.blocked(name, args, asRecord(gate['on_fail']), gateId);
|
|
396
|
+
}
|
|
397
|
+
if (unclear !== null) {
|
|
398
|
+
const onUnclear = isRecord(unclear['on_unclear'])
|
|
399
|
+
? unclear['on_unclear']
|
|
400
|
+
: { response: `${name} was not run. Ask the caller again.` };
|
|
401
|
+
return this.blocked(name, args, onUnclear, String(unclear['id']));
|
|
402
|
+
}
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
blocked(name, args, output, gateId) {
|
|
406
|
+
const result = expand(structuredClone(output), {
|
|
407
|
+
global_data: this.globalData,
|
|
408
|
+
args,
|
|
409
|
+
});
|
|
410
|
+
this.apply(result);
|
|
411
|
+
return new SimulatedCall(name, args, result, { ran: false, blockedBy: gateId });
|
|
412
|
+
}
|
|
413
|
+
navigate(name, args) {
|
|
414
|
+
if (name === 'next_step') {
|
|
415
|
+
const requested = String(args['step'] ?? '');
|
|
416
|
+
const valid = this.currentStep()?.['valid_steps'];
|
|
417
|
+
const target = requested === 'next' ? this.followingStep() : requested;
|
|
418
|
+
if (!Array.isArray(valid) || !valid.includes(requested) || target === null) {
|
|
419
|
+
return new SimulatedCall(name, args, { response: `${requested} is not a step you can go to.` }, { ran: false, blockedBy: 'step' });
|
|
420
|
+
}
|
|
421
|
+
this.enterStep(target);
|
|
422
|
+
this.enteredAt = null; // next_step keeps nothing of its own
|
|
423
|
+
return new SimulatedCall(name, args, { response: `Moved to step ${target}.` }, { ran: true });
|
|
424
|
+
}
|
|
425
|
+
const target = String(args['context'] ?? '');
|
|
426
|
+
if (!this.validContexts().includes(target) || !Object.hasOwn(this.contexts, target)) {
|
|
427
|
+
return new SimulatedCall(name, args, { response: `${target} is not a context you can go to.` }, { ran: false, blockedBy: 'step' });
|
|
428
|
+
}
|
|
429
|
+
this.enterContext(target);
|
|
430
|
+
return new SimulatedCall(name, args, { response: `Moved to context ${target}.` }, { ran: true });
|
|
431
|
+
}
|
|
432
|
+
request(name, args) {
|
|
433
|
+
this.toolCalls += 1;
|
|
434
|
+
const request = {
|
|
435
|
+
function: name,
|
|
436
|
+
argument: { parsed: [args], raw: JSON.stringify(args) },
|
|
437
|
+
call_id: this.callId,
|
|
438
|
+
tool_call_id: `${this.callId}-tool-${this.toolCalls}`,
|
|
439
|
+
global_data: structuredClone(this.globalData),
|
|
440
|
+
content_type: 'text/swaig',
|
|
441
|
+
version: '2.0',
|
|
442
|
+
};
|
|
443
|
+
if (this.params['swaig_post_conversation']) {
|
|
444
|
+
request['call_log'] = structuredClone(this.callLog);
|
|
445
|
+
request['raw_call_log'] = structuredClone(this.callLog);
|
|
446
|
+
}
|
|
447
|
+
return request;
|
|
448
|
+
}
|
|
449
|
+
apply(result) {
|
|
450
|
+
const given = result['action'] ?? [];
|
|
451
|
+
const actions = Array.isArray(given) ? given : [given];
|
|
452
|
+
if (result['post_process'] && actions.length > 0) {
|
|
453
|
+
this.deferred = { actions, callStart: this.callStart };
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
this.runActions(actions);
|
|
457
|
+
}
|
|
458
|
+
runActions(actions) {
|
|
459
|
+
// A proposal or mark is set as of the start of the result's action list,
|
|
460
|
+
// so a say anywhere in the list is after it
|
|
461
|
+
this.actionStart = this.callLog.length;
|
|
462
|
+
for (const action of actions) {
|
|
463
|
+
if (!isRecord(action))
|
|
464
|
+
continue;
|
|
465
|
+
for (const [key, value] of Object.entries(action))
|
|
466
|
+
this.applyOne(key, value);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
applyOne(key, value) {
|
|
470
|
+
if (key === 'say') {
|
|
471
|
+
this.says.add(this.callLog.length);
|
|
472
|
+
this.log({ role: 'assistant', content: String(value) }, 'spoken');
|
|
473
|
+
}
|
|
474
|
+
else if (key === 'set_global_data' && isRecord(value)) {
|
|
475
|
+
if ('semantic_state' in value)
|
|
476
|
+
this.noteState(value['semantic_state']);
|
|
477
|
+
Object.assign(this.globalData, structuredClone(value));
|
|
478
|
+
}
|
|
479
|
+
else if (key === 'unset_global_data') {
|
|
480
|
+
const names = typeof value === 'string' ? [value] : Array.isArray(value) ? value : [];
|
|
481
|
+
for (const name of names)
|
|
482
|
+
delete this.globalData[String(name)];
|
|
483
|
+
// With the state gone, there's no proposal: gates judge the window
|
|
484
|
+
if (names.map(String).includes('semantic_state'))
|
|
485
|
+
this.proposalAt = null;
|
|
486
|
+
}
|
|
487
|
+
else if (key === 'change_step') {
|
|
488
|
+
this.enterStep(String(value));
|
|
489
|
+
}
|
|
490
|
+
else if (key === 'change_context') {
|
|
491
|
+
this.enterContext(String(value));
|
|
492
|
+
}
|
|
493
|
+
else if (key === 'toggle_functions' && Array.isArray(value)) {
|
|
494
|
+
for (const toggle of value) {
|
|
495
|
+
if (isRecord(toggle) && 'function' in toggle) {
|
|
496
|
+
this.toggled.set(String(toggle['function']), Boolean(toggle['active'] ?? true));
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
else if (key === 'back_to_back_functions') {
|
|
501
|
+
this.chaining = value;
|
|
502
|
+
}
|
|
503
|
+
else if (key === 'semantic_gate_mark') {
|
|
504
|
+
// The platform keeps a call's 16 newest names; setting one moves it
|
|
505
|
+
this.marks.delete(String(value));
|
|
506
|
+
this.marks.set(String(value), this.actionStart);
|
|
507
|
+
while (this.marks.size > MAX_MARKS)
|
|
508
|
+
this.marks.delete(this.marks.keys().next().value);
|
|
509
|
+
}
|
|
510
|
+
else if (key === 'wait_for_user') {
|
|
511
|
+
this.waitingForUser = Boolean(value);
|
|
512
|
+
}
|
|
513
|
+
else if (key === 'hangup' || key === 'stop') {
|
|
514
|
+
this.ended = true;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
enterContext(name) {
|
|
518
|
+
if (!Object.hasOwn(this.contexts, name)) {
|
|
519
|
+
throw new Error(`the agent has no context ${JSON.stringify(name)}`);
|
|
520
|
+
}
|
|
521
|
+
const steps = this.stepsOf(name);
|
|
522
|
+
this.context = name;
|
|
523
|
+
this.stepFunctions = new Set(this.tools());
|
|
524
|
+
const initial = this.contexts[name]['initial_step'] || (steps[0]?.['name'] ?? null);
|
|
525
|
+
if (initial)
|
|
526
|
+
this.enterStep(String(initial));
|
|
527
|
+
}
|
|
528
|
+
enterStep(name) {
|
|
529
|
+
if (this.context === null)
|
|
530
|
+
return;
|
|
531
|
+
const step = this.findStep(name);
|
|
532
|
+
if (step === null) {
|
|
533
|
+
throw new Error(`context ${JSON.stringify(this.context)} has no step ${JSON.stringify(name)}`);
|
|
534
|
+
}
|
|
535
|
+
this.step = name;
|
|
536
|
+
// The platform injects the step's instructions, and applies its history
|
|
537
|
+
// mode, before the next request to the model: for a tool that changed the
|
|
538
|
+
// step, the follow-up right after its result. The call is the new step's
|
|
539
|
+
// start, with everything stored from it on: for a post_process change, the
|
|
540
|
+
// reply and the caller's words too
|
|
541
|
+
this.injectPending = true;
|
|
542
|
+
this.enteredAt = this.callStart ?? this.callLog.length;
|
|
543
|
+
const functions = step['functions'];
|
|
544
|
+
if (functions === 'none' || (Array.isArray(functions) && functions.length === 0)) {
|
|
545
|
+
this.stepFunctions = new Set();
|
|
546
|
+
}
|
|
547
|
+
else if (Array.isArray(functions)) {
|
|
548
|
+
this.stepFunctions = new Set(functions.map(String));
|
|
549
|
+
}
|
|
550
|
+
// A step without a function list keeps the set before it
|
|
551
|
+
}
|
|
552
|
+
stepsOf(context) {
|
|
553
|
+
if (context === null)
|
|
554
|
+
return [];
|
|
555
|
+
const steps = this.contexts[context]?.['steps'];
|
|
556
|
+
return Array.isArray(steps) ? steps.filter(isRecord) : [];
|
|
557
|
+
}
|
|
558
|
+
currentStep() {
|
|
559
|
+
return this.step === null ? null : this.findStep(this.step);
|
|
560
|
+
}
|
|
561
|
+
findStep(name) {
|
|
562
|
+
const step = this.stepsOf(this.context).find((s) => s['name'] === name);
|
|
563
|
+
return step ? { ...step } : null;
|
|
564
|
+
}
|
|
565
|
+
followingStep() {
|
|
566
|
+
const names = this.stepsOf(this.context).map((s) => s['name']);
|
|
567
|
+
const at = names.indexOf(this.step);
|
|
568
|
+
return at >= 0 && at + 1 < names.length ? String(names[at + 1]) : null;
|
|
569
|
+
}
|
|
570
|
+
validContexts() {
|
|
571
|
+
const step = this.currentStep() ?? {};
|
|
572
|
+
if (step['valid_contexts'] !== undefined && step['valid_contexts'] !== null) {
|
|
573
|
+
return step['valid_contexts'].map(String);
|
|
574
|
+
}
|
|
575
|
+
if (this.context !== null) {
|
|
576
|
+
const valid = this.contexts[this.context]['valid_contexts'];
|
|
577
|
+
return Array.isArray(valid) ? valid.map(String) : [];
|
|
578
|
+
}
|
|
579
|
+
return [];
|
|
580
|
+
}
|
|
581
|
+
tools() {
|
|
582
|
+
return Object.keys(this.functions).filter((name) => !RESERVED_FUNCTION_NAMES.has(name));
|
|
583
|
+
}
|
|
584
|
+
/** The current context's other steps whose functions include `name`, in step order. */
|
|
585
|
+
stepsOffering(name) {
|
|
586
|
+
return this.stepsOf(this.context)
|
|
587
|
+
.filter((step) => step['name'] !== this.step &&
|
|
588
|
+
Array.isArray(step['functions']) &&
|
|
589
|
+
step['functions'].includes(name))
|
|
590
|
+
.map((step) => String(step['name']));
|
|
591
|
+
}
|
|
592
|
+
/** The platform's reply to a call of a tool it won't run now. */
|
|
593
|
+
unavailable(name) {
|
|
594
|
+
const offered = this.offered();
|
|
595
|
+
const tools = offered.join(', ');
|
|
596
|
+
const known = Object.hasOwn(this.functions, name);
|
|
597
|
+
const steps = known ? this.stepsOffering(name).join(', ') : '';
|
|
598
|
+
const template = this.params['unavailable_function_response'];
|
|
599
|
+
if (typeof template === 'string' && template) {
|
|
600
|
+
return template
|
|
601
|
+
.replaceAll('${function}', () => name)
|
|
602
|
+
.replaceAll('${tools}', () => tools)
|
|
603
|
+
.replaceAll('${steps}', () => steps);
|
|
604
|
+
}
|
|
605
|
+
let text;
|
|
606
|
+
if (known) {
|
|
607
|
+
text = `Nothing ran: ${name} isn't available at this point in the call.`;
|
|
608
|
+
if (steps)
|
|
609
|
+
text += ` The steps that offer it: ${steps}.`;
|
|
610
|
+
}
|
|
611
|
+
else {
|
|
612
|
+
text = `Nothing ran: there is no tool named ${name}.`;
|
|
613
|
+
}
|
|
614
|
+
if (offered.length > 0)
|
|
615
|
+
return `${text} The tools available now are: ${tools}.\n`;
|
|
616
|
+
return `${text} No tools are available now.\n`;
|
|
617
|
+
}
|
|
618
|
+
log(entry, kind = 'spoken') {
|
|
619
|
+
this.kinds.set(this.callLog.length, kind);
|
|
620
|
+
this.callLog.push({ ...entry, timestamp: Date.now() * 1000 });
|
|
621
|
+
}
|
|
622
|
+
// ── What the model sees ─────────────────────────────────────────────
|
|
623
|
+
/**
|
|
624
|
+
* The current step's history mode: its own, its context's, or "default".
|
|
625
|
+
* @returns The mode.
|
|
626
|
+
*/
|
|
627
|
+
historyMode() {
|
|
628
|
+
const step = this.currentStep() ?? {};
|
|
629
|
+
const context = this.context !== null ? (this.contexts[this.context] ?? {}) : {};
|
|
630
|
+
return String(step['history'] || context['history'] || 'default');
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* The conversation entries the model gets now, oldest first, after the
|
|
634
|
+
* history modes of the steps entered so far.
|
|
635
|
+
*
|
|
636
|
+
* At each step's injection, the platform first restores what an isolate
|
|
637
|
+
* step hid, then applies the new step's mode to everything before it:
|
|
638
|
+
*
|
|
639
|
+
* - `keep`: nothing leaves.
|
|
640
|
+
* - `default`: earlier step instructions leave.
|
|
641
|
+
* - `hide`: earlier instructions, and every earlier spoken turn, tool call,
|
|
642
|
+
* tool result and system note, leave for the rest of the call.
|
|
643
|
+
* - `isolate`: as `hide`, until the call leaves the step.
|
|
644
|
+
* - `spoken`: earlier instructions, and every earlier tool call, tool result
|
|
645
|
+
* and system note, leave for the rest of the call; every spoken turn stays.
|
|
646
|
+
*
|
|
647
|
+
* `hide`, `isolate` and `spoken` keep the exchange that entered the step, as
|
|
648
|
+
* its start: the call whose action changed it, its result, notes and say,
|
|
649
|
+
* and caller words stored before the step was injected. For a `post_process`
|
|
650
|
+
* action's change, which runs after the model's reply, that's the call and
|
|
651
|
+
* everything stored from it on, the reply included. A change by `next_step`
|
|
652
|
+
* keeps nothing. After that they're ordinary entries, which each later
|
|
653
|
+
* step's mode treats like the rest.
|
|
654
|
+
*
|
|
655
|
+
* It's the view for the model's next request: a step entered by a `say` or
|
|
656
|
+
* another action outside a tool call is injected before it, as the platform
|
|
657
|
+
* injects a step before the next request. A result's `say` is the agent's
|
|
658
|
+
* turn after the call's result and notes: the platform holds it until the
|
|
659
|
+
* next caller or agent turn, past system entries such as a step's
|
|
660
|
+
* instructions, or to the end. The current step's instructions are its text
|
|
661
|
+
* expanded with the global data now, as the platform expands it again when a
|
|
662
|
+
* value it reads changes; `callLog` keeps the text as it went in. An end
|
|
663
|
+
* step keeps the text it went in with. An end step takes no pass: steps end
|
|
664
|
+
* there, so what an `isolate` step hid is back, and earlier instructions
|
|
665
|
+
* stay. The base prompt isn't included.
|
|
666
|
+
*
|
|
667
|
+
* @returns The entries, without their timestamps.
|
|
668
|
+
* @throws Error once the call has entered a step with a reset, which starts a
|
|
669
|
+
* new context or consolidates the conversation in place of the step's
|
|
670
|
+
* text: the simulation doesn't follow it.
|
|
671
|
+
*/
|
|
672
|
+
modelView() {
|
|
673
|
+
this.inject();
|
|
674
|
+
this.checkModelled();
|
|
675
|
+
const view = [];
|
|
676
|
+
const held = [];
|
|
677
|
+
this.callLog.forEach((entry, index) => {
|
|
678
|
+
if (this.hidden.has(index) || this.isolatedEntries.has(index) || this.cleared.has(index)) {
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
const shown = { ...entry };
|
|
682
|
+
delete shown['timestamp'];
|
|
683
|
+
if (this.shown.has(index))
|
|
684
|
+
shown['content'] = this.shown.get(index);
|
|
685
|
+
if (this.says.has(index)) {
|
|
686
|
+
held.push(shown);
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
if ((shown['role'] === 'user' || shown['role'] === 'assistant') && !shown['tool_calls']) {
|
|
690
|
+
view.push(...held);
|
|
691
|
+
held.length = 0;
|
|
692
|
+
}
|
|
693
|
+
view.push(shown);
|
|
694
|
+
});
|
|
695
|
+
return [...view, ...held];
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* The dialogue a semantic gate judges now, as `"role: text"` lines, oldest
|
|
699
|
+
* first: the spoken turns the model sees ({@link modelView}), chosen as the
|
|
700
|
+
* platform chooses them.
|
|
701
|
+
*
|
|
702
|
+
* With the gate's `since` mark set, the turns from the agent's first turn at
|
|
703
|
+
* or after the mark. Otherwise, with `dialogue` "proposal" (the gate's, or
|
|
704
|
+
* the agent's `semantic_gate_dialogue`) and a proposal marked, the turns
|
|
705
|
+
* from the agent's first turn after `semantic_state` last changed. Otherwise
|
|
706
|
+
* the window. Then at most `history` of the newest (the gate's, the agent's
|
|
707
|
+
* `semantic_gate_history`, or 20).
|
|
708
|
+
*
|
|
709
|
+
* Give it to a gate callback: `gates: (gate, sim) =>
|
|
710
|
+
* judge(gate['question'], sim.gateConversation(gate))`.
|
|
711
|
+
*
|
|
712
|
+
* @param gate - The gate, as rendered; default none.
|
|
713
|
+
* @returns The lines.
|
|
714
|
+
* @throws Error once the call has entered a step with a reset, as for
|
|
715
|
+
* {@link modelView}.
|
|
716
|
+
*/
|
|
717
|
+
gateConversation(gate = {}) {
|
|
718
|
+
this.inject();
|
|
719
|
+
this.checkModelled();
|
|
720
|
+
let spoken = this.callLog
|
|
721
|
+
.map((_, i) => i)
|
|
722
|
+
.filter((i) => !this.hidden.has(i) &&
|
|
723
|
+
!this.isolatedEntries.has(i) &&
|
|
724
|
+
this.kinds.get(i) === 'spoken' &&
|
|
725
|
+
Boolean(this.callLog[i]['content']));
|
|
726
|
+
let start = null;
|
|
727
|
+
const since = gate['since'];
|
|
728
|
+
const dialogue = gate['dialogue'] || this.params['semantic_gate_dialogue'];
|
|
729
|
+
if (typeof since === 'string' && this.marks.has(since)) {
|
|
730
|
+
start = this.marks.get(since);
|
|
731
|
+
}
|
|
732
|
+
else if (String(dialogue ?? '').toLowerCase() === 'proposal' && this.proposalAt !== null) {
|
|
733
|
+
start = this.proposalAt;
|
|
734
|
+
}
|
|
735
|
+
if (start !== null) {
|
|
736
|
+
const from = start;
|
|
737
|
+
const firstAgent = spoken.find((i) => i >= from && this.callLog[i]['role'] === 'assistant');
|
|
738
|
+
spoken = firstAgent === undefined ? [] : spoken.filter((i) => i >= firstAgent);
|
|
739
|
+
}
|
|
740
|
+
const history = Math.trunc(Number(gate['history'] || this.params['semantic_gate_history'] || 20));
|
|
741
|
+
const newest = history > 0 ? spoken.slice(-history) : [];
|
|
742
|
+
return newest.map((i) => `${this.callLog[i]['role']}: ${this.callLog[i]['content']}`);
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Before a request to the model: inject the current step's instructions,
|
|
746
|
+
* applying its history mode to what came before, once a step change is
|
|
747
|
+
* pending; otherwise expand the current step's text again.
|
|
748
|
+
*/
|
|
749
|
+
inject() {
|
|
750
|
+
if (!this.injectPending) {
|
|
751
|
+
this.refresh();
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
this.injectPending = false;
|
|
755
|
+
this.isolatedEntries.clear();
|
|
756
|
+
const step = this.currentStep() ?? {};
|
|
757
|
+
const context = this.context !== null ? (this.contexts[this.context] ?? {}) : {};
|
|
758
|
+
// An end step, or one with a reset, ends steps mode once it's in: it takes
|
|
759
|
+
// no history pass, its text isn't expanded again, and what an isolate step
|
|
760
|
+
// hid is back (step_management.c)
|
|
761
|
+
const hasReset = isRecord(step['reset']);
|
|
762
|
+
const terminal = Boolean(step['end']) || hasReset;
|
|
763
|
+
if (!terminal)
|
|
764
|
+
this.historyPass();
|
|
765
|
+
this.instruction = null;
|
|
766
|
+
if (hasReset) {
|
|
767
|
+
// The platform runs the reset (process_reset) in place of the step's text
|
|
768
|
+
this.resetStep = this.step;
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
// The context's prompt first, then the step's text, end steps included
|
|
772
|
+
// (mod_openai dc20c53)
|
|
773
|
+
const text = [String(context['prompt'] || ''), String(step['text'] || '')]
|
|
774
|
+
.filter((part) => part)
|
|
775
|
+
.join('\n\n');
|
|
776
|
+
if (!terminal)
|
|
777
|
+
this.instruction = { index: this.callLog.length, text };
|
|
778
|
+
this.log({
|
|
779
|
+
role: 'system',
|
|
780
|
+
content: expand(text, { global_data: this.globalData }, ''),
|
|
781
|
+
}, 'instruction');
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* A semantic_state being set: `{}` leaves no proposal, and any other state
|
|
785
|
+
* that differs from the current one, compared as serialized as the engine
|
|
786
|
+
* compares it (so a reordered state is a change), starts one.
|
|
787
|
+
*/
|
|
788
|
+
noteState(state) {
|
|
789
|
+
if (isRecord(state) && Object.keys(state).length === 0) {
|
|
790
|
+
this.proposalAt = null;
|
|
791
|
+
}
|
|
792
|
+
else if (!Object.hasOwn(this.globalData, 'semantic_state') ||
|
|
793
|
+
JSON.stringify(state) !== JSON.stringify(this.globalData['semantic_state'])) {
|
|
794
|
+
this.proposalAt = this.actionStart;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
/** The current step's history mode, applied to everything before its start. */
|
|
798
|
+
historyPass() {
|
|
799
|
+
const mode = this.historyMode();
|
|
800
|
+
const before = this.callLog.length;
|
|
801
|
+
if (mode !== 'keep') {
|
|
802
|
+
for (let i = 0; i < before; i++) {
|
|
803
|
+
if (this.kinds.get(i) === 'instruction')
|
|
804
|
+
this.cleared.add(i);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
if (mode === 'hide' || mode === 'isolate' || mode === 'spoken') {
|
|
808
|
+
// The exchange that entered the step stays: it's the step's start
|
|
809
|
+
const keptFrom = this.enteredAt ?? before;
|
|
810
|
+
const target = mode === 'isolate' ? this.isolatedEntries : this.hidden;
|
|
811
|
+
for (let i = 0; i < keptFrom; i++) {
|
|
812
|
+
const kind = this.kinds.get(i);
|
|
813
|
+
if (kind === 'instruction' || this.hidden.has(i))
|
|
814
|
+
continue;
|
|
815
|
+
if (mode === 'spoken' && kind === 'spoken')
|
|
816
|
+
continue;
|
|
817
|
+
target.add(i);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
/** Throw for a view the simulator can't give: after a reset step. */
|
|
822
|
+
checkModelled() {
|
|
823
|
+
if (this.resetStep !== null) {
|
|
824
|
+
throw new Error(`step '${this.resetStep}' has a reset, which the simulator doesn't model: the ` +
|
|
825
|
+
"platform replaces the model's context in place of the step's text");
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* The platform rewrites the step's instruction entry in place when its
|
|
830
|
+
* expansion changes; the call log keeps the text as it went in.
|
|
831
|
+
*/
|
|
832
|
+
refresh() {
|
|
833
|
+
if (this.instruction === null)
|
|
834
|
+
return;
|
|
835
|
+
const { index, text } = this.instruction;
|
|
836
|
+
const expanded = expand(text, { global_data: this.globalData }, '');
|
|
837
|
+
if (expanded === this.callLog[index]['content'])
|
|
838
|
+
this.shown.delete(index);
|
|
839
|
+
else
|
|
840
|
+
this.shown.set(index, expanded);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Tool middleware that records each tool request, for
|
|
845
|
+
* {@link CallSimulator.replay}.
|
|
846
|
+
*
|
|
847
|
+
* @example
|
|
848
|
+
* ```ts
|
|
849
|
+
* import { AgentBase, CallSimulator, RequestRecorder } from '@signalwire/sdk';
|
|
850
|
+
*
|
|
851
|
+
* declare const agent: AgentBase;
|
|
852
|
+
* const recorder = new RequestRecorder('tool_requests.jsonl');
|
|
853
|
+
* agent.addToolMiddleware(recorder.middleware);
|
|
854
|
+
* // ...
|
|
855
|
+
* await new CallSimulator(agent).replay(RequestRecorder.load('tool_requests.jsonl'));
|
|
856
|
+
* ```
|
|
857
|
+
*
|
|
858
|
+
* The requests carry what the caller said and the call's data: keep the file
|
|
859
|
+
* where you'd keep call recordings.
|
|
860
|
+
*/
|
|
861
|
+
export class RequestRecorder {
|
|
862
|
+
/** A file each request is appended to, one JSON object a line. */
|
|
863
|
+
path;
|
|
864
|
+
/** The most requests kept in `requests`. */
|
|
865
|
+
limit;
|
|
866
|
+
/** The requests recorded, oldest first. */
|
|
867
|
+
requests = [];
|
|
868
|
+
/** The file's writes, in the order the requests came. */
|
|
869
|
+
writes = Promise.resolve();
|
|
870
|
+
/**
|
|
871
|
+
* @param path - A file to append each request to, one JSON object a line.
|
|
872
|
+
* @param opts - `limit`.
|
|
873
|
+
*/
|
|
874
|
+
constructor(path, opts = {}) {
|
|
875
|
+
this.path = path ?? null;
|
|
876
|
+
this.limit = opts.limit ?? 1000;
|
|
877
|
+
}
|
|
878
|
+
/** This recorder as a {@link ToolMiddleware}. */
|
|
879
|
+
middleware = (name, args, rawData, callNext) => this.handle(name, args, rawData, callNext);
|
|
880
|
+
/**
|
|
881
|
+
* Record a request, then run the rest of the chain.
|
|
882
|
+
* @param name - The tool's name.
|
|
883
|
+
* @param args - The arguments.
|
|
884
|
+
* @param rawData - The SWAIG request.
|
|
885
|
+
* @param callNext - The rest of the chain.
|
|
886
|
+
* @returns The call's result.
|
|
887
|
+
*/
|
|
888
|
+
async handle(name, args, rawData, callNext) {
|
|
889
|
+
const request = structuredClone(rawData);
|
|
890
|
+
if (!('function' in request))
|
|
891
|
+
request['function'] = name;
|
|
892
|
+
if (!('argument' in request)) {
|
|
893
|
+
request['argument'] = { parsed: [args], raw: JSON.stringify(args) };
|
|
894
|
+
}
|
|
895
|
+
this.requests.push(request);
|
|
896
|
+
this.requests.splice(0, Math.max(0, this.requests.length - this.limit));
|
|
897
|
+
if (this.path !== null) {
|
|
898
|
+
const line = JSON.stringify(request, (_key, value) => typeof value === 'bigint' ? value.toString() : value);
|
|
899
|
+
const path = this.path;
|
|
900
|
+
const write = this.writes.then(() => appendFile(path, `${line}\n`, 'utf-8'));
|
|
901
|
+
// A failed write doesn't stop the writes after it
|
|
902
|
+
this.writes = write.catch(() => undefined);
|
|
903
|
+
await write;
|
|
904
|
+
}
|
|
905
|
+
return await callNext(args, rawData);
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* The requests a recorder wrote to `path`.
|
|
909
|
+
* @param path - The file.
|
|
910
|
+
* @returns The requests, in order.
|
|
911
|
+
*/
|
|
912
|
+
static load(path) {
|
|
913
|
+
return readFileSync(path, 'utf-8')
|
|
914
|
+
.split(/\r?\n/)
|
|
915
|
+
.filter((line) => line.trim())
|
|
916
|
+
.map((line) => JSON.parse(line));
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
function aiVerb(swml) {
|
|
920
|
+
const main = asRecord(swml['sections'])['main'];
|
|
921
|
+
for (const verb of Array.isArray(main) ? main : []) {
|
|
922
|
+
if (isRecord(verb) && isRecord(verb['ai']))
|
|
923
|
+
return verb['ai'];
|
|
924
|
+
}
|
|
925
|
+
throw new Error("the agent's SWML has no ai verb");
|
|
926
|
+
}
|
|
927
|
+
function asResult(result) {
|
|
928
|
+
if (result instanceof FunctionResult)
|
|
929
|
+
return result.toDict();
|
|
930
|
+
if (isRecord(result))
|
|
931
|
+
return result;
|
|
932
|
+
return { response: String(result) };
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* `${...}` variables from the call's data, as the platform expands them once. A
|
|
936
|
+
* variable it can't find becomes `missing`, or is left as it is without one.
|
|
937
|
+
*/
|
|
938
|
+
function expand(value, data, missing) {
|
|
939
|
+
if (typeof value === 'string') {
|
|
940
|
+
return value.replace(VARIABLE, (match, path) => {
|
|
941
|
+
let found = data;
|
|
942
|
+
for (const part of path.split('.')) {
|
|
943
|
+
if (!isRecord(found) || !Object.hasOwn(found, part))
|
|
944
|
+
return missing ?? match;
|
|
945
|
+
found = found[part];
|
|
946
|
+
}
|
|
947
|
+
return typeof found === 'string' ? found : JSON.stringify(found);
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
if (Array.isArray(value))
|
|
951
|
+
return value.map((v) => expand(v, data, missing));
|
|
952
|
+
if (isRecord(value)) {
|
|
953
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, expand(v, data, missing)]));
|
|
954
|
+
}
|
|
955
|
+
return value;
|
|
956
|
+
}
|
|
957
|
+
function isRecord(value) {
|
|
958
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
959
|
+
}
|
|
960
|
+
function asRecord(value) {
|
|
961
|
+
return isRecord(value) ? value : {};
|
|
962
|
+
}
|
|
963
|
+
function isNonEmpty(value) {
|
|
964
|
+
return Array.isArray(value) ? value.length > 0 : Boolean(value);
|
|
965
|
+
}
|
|
966
|
+
//# sourceMappingURL=CallSimulator.js.map
|