@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
package/docs/api-reference.md
CHANGED
|
@@ -32,6 +32,7 @@ The page covers these classes, functions and types:
|
|
|
32
32
|
- [Context Methods](#context-methods)
|
|
33
33
|
- [Skill Methods](#skill-methods)
|
|
34
34
|
- [Per-Request Configuration Methods](#per-request-configuration-methods)
|
|
35
|
+
- [AI Event Methods](#ai-event-methods)
|
|
35
36
|
- [SIP Routing and MCP Methods](#sip-routing-and-mcp-methods)
|
|
36
37
|
- [URL and Proxy Methods](#url-and-proxy-methods)
|
|
37
38
|
- [Server Methods](#server-methods)
|
|
@@ -349,8 +350,8 @@ defineTool<P extends ToolParameters, R extends readonly PropertyKey[]>(
|
|
|
349
350
|
args: ToolArgs<P, R>,
|
|
350
351
|
rawData: SwaigRequest,
|
|
351
352
|
agent?: AgentBase,
|
|
352
|
-
) => FunctionResult | Record<string, unknown> | string
|
|
353
|
-
| Promise<FunctionResult | Record<string, unknown> | string>;
|
|
353
|
+
) => FunctionResult | Record<string, unknown> | string | null | undefined | void
|
|
354
|
+
| Promise<FunctionResult | Record<string, unknown> | string | null | undefined | void>;
|
|
354
355
|
},
|
|
355
356
|
): this
|
|
356
357
|
```
|
|
@@ -371,15 +372,50 @@ When `parameters` is a flat map of property definitions written inline, TypeScri
|
|
|
371
372
|
| `webhookUrl` | `string` | none | An external URL that runs the tool instead of this agent |
|
|
372
373
|
| `extraFields` | `Record<string, unknown>` | `{}` | Extra keys merged into the function definition |
|
|
373
374
|
| `onError` | `SwaigErrorHandler` | none | Called when the handler throws; may return a `FunctionResult` to use as the response |
|
|
374
|
-
| `errorMessage` | `string` |
|
|
375
|
+
| `errorMessage` | `string` | The unknown-outcome result | Response used when the handler throws and no error hook returns one |
|
|
375
376
|
| `isTypedHandler` | `boolean` | `false` | Marks a handler that takes named parameters; `defineTypedTool()` sets it |
|
|
376
377
|
| `gates` | `(SemanticGate \| Record<string, unknown>)[]` | none | Semantic gates, 1 to 8. See [Semantic gates](#semantic-gates) |
|
|
377
378
|
| `gateFillers` | `FillerPhrases` | none | What the AI says while the gates are checked, shaped like `fillers`. Only with `gates` |
|
|
379
|
+
| `vouched` | `boolean` | `false` | `true` for a tool whose arguments must come from the caller, not from the model's guesses. The tool gets a required boolean argument, `data_supplied_by_user` (`VOUCHED_PARAMETER`), in which the model says every other argument is what the caller said. Unless it's `true`, the handler doesn't run, and the model gets "<name> was not run." with the tool prompt "Get the answer from the user before using this tool." The handler never sees the argument |
|
|
380
|
+
| `nullableOptional` | `boolean` | the agent's | `true` to let the model send `null` for an optional argument, as providers with strict schemas require. Each argument that isn't required takes `null` as well as its type, and a `null` reaches the handler as an argument not given. Left out, it follows [`setNullableOptionalParameters()`](#setnullableoptionalparametersenabled) |
|
|
381
|
+
| `middleware` | `ToolMiddleware[]` | none | Middleware that runs around this tool's calls only, inside the agent's. See [`addToolMiddleware()`](#addtoolmiddlewaremiddleware) |
|
|
382
|
+
| `needsConversation` | `boolean` | `false` | `true` when the handler reads the conversation, as [`callerTurns(rawData)`](#post-prompt-helpers) does. It turns on the agent's `swaig_post_conversation` when the SWML is rendered, so every tool request carries the call log, unless that param was set to `false` |
|
|
378
383
|
|
|
379
384
|
**Throws:** `Error` for a gate the platform would refuse, or `gateFillers` without `gates`.
|
|
380
385
|
|
|
381
386
|
The handler's third argument is the agent the request was configured on. With a dynamic config callback or `addPerCallConfig()`, that's the per-request copy. The handler's return value is the tool's response: context for the model, which decides what to say. See [SwaigHandler](#swaighandler) for how each return type is serialized.
|
|
382
387
|
|
|
388
|
+
What the handler returns is what the model reads as the outcome, so the SDK keeps it honest:
|
|
389
|
+
|
|
390
|
+
- A `FunctionResult`, or an object with a `response` or an `action`, is sent as it is.
|
|
391
|
+
- Any other object is the handler's data, and the model gets it as JSON. An empty object tells the model the outcome is unknown.
|
|
392
|
+
- `undefined` or `null`, including a handler that returns nothing, gets "Function executed successfully".
|
|
393
|
+
- A handler that throws `new ToolRefusal(toolResult, toolPrompt?)` declines the call with an outcome it knows: the model gets that result and prompt. The `onError` hooks don't see a refusal.
|
|
394
|
+
- Any other error is logged, not sent. Unless an `onError` hook or `errorMessage` gives the response, the model is told the function failed before it finished, so whether it took effect is unknown, and not to tell the caller it worked or that it didn't (`toolErrorResult(name)`). The error's text could hold internals, and the model would read it as the outcome.
|
|
395
|
+
|
|
396
|
+
```ts
|
|
397
|
+
import { AgentBase, FunctionResult, ToolRefusal } from '@signalwire/sdk';
|
|
398
|
+
|
|
399
|
+
const shop = new AgentBase({ name: 'shop' });
|
|
400
|
+
const inStock = new Set(['tea', 'coffee']); // your inventory
|
|
401
|
+
|
|
402
|
+
shop.defineTool({
|
|
403
|
+
name: 'place_order',
|
|
404
|
+
description: 'Place an order for an item',
|
|
405
|
+
parameters: { item: { type: 'string', description: 'The item' } },
|
|
406
|
+
required: ['item'],
|
|
407
|
+
handler: (args) => {
|
|
408
|
+
if (!inStock.has(args.item)) {
|
|
409
|
+
throw new ToolRefusal(
|
|
410
|
+
`place_order was not run: ${args.item} is out of stock.`,
|
|
411
|
+
'Tell the caller, and offer the similar items in stock.',
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
return new FunctionResult().setToolResponse(`Order for ${args.item} is placed.`);
|
|
415
|
+
},
|
|
416
|
+
});
|
|
417
|
+
```
|
|
418
|
+
|
|
383
419
|
**Example:**
|
|
384
420
|
|
|
385
421
|
```ts
|
|
@@ -401,7 +437,7 @@ agent.defineTool({
|
|
|
401
437
|
|
|
402
438
|
A semantic gate is a yes/no question a decision model answers about the call right before the platform dispatches the function. Every gate on the function must pass for it to run. When one doesn't, the function isn't dispatched, and the model gets that gate's `on_fail` output instead, as if a data_map had returned it. The function's `fillers` and `wait_file` start only once its gates pass, so a blocked call never sounds as if the action were under way.
|
|
403
439
|
|
|
404
|
-
Semantic gates need a platform release that supports them. One that doesn't runs the function ungated, and may or may not log a warning about the unknown key, so don't rely on a gate to protect a function until your platform supports them.
|
|
440
|
+
Semantic gates need a platform release that supports them. One that doesn't runs the function ungated, and may or may not log a warning about the unknown key, so don't rely on a gate to protect a function until your platform supports them. The gate keys added later, `unclear`, `on_unclear`, `dialogue`, `history` and `since`, need a release that has them too: one that has gates but not a key refuses the whole function, since it treats an unknown gate key as an error.
|
|
405
441
|
|
|
406
442
|
The decision model sees three things, under these names: `conversation`, the recent dialogue; `semantic_state`, the call's `global_data.semantic_state`, which [`FunctionResult.setSemanticState()`](#data-actions) sets; and `proposed_function`, the function's name, description and arguments. Write each question as one proposition, and name what it's about with those names in backticks. The model reads literally: it doesn't do arithmetic or compare dates, so put a computed result in `semantic_state` instead of asking for it.
|
|
407
443
|
|
|
@@ -441,10 +477,17 @@ agent.defineTool({
|
|
|
441
477
|
|----------|------|-------------|
|
|
442
478
|
| `question` | `string` | The yes/no question, at most 8 KB. Its `${...}` variables are expanded from the call's global data when the gate is checked |
|
|
443
479
|
| `threshold` | `number` | The probability of yes, above 0 and at most 1, at or above which the gate passes |
|
|
444
|
-
| `onFail` | `string \| FunctionResult \| Record<string, unknown>` | What the model gets when this is the first gate that fails: the tool result text, a `FunctionResult`, whose response and actions are used, or a data_map output object. It needs a response, and in the `tool_result`/`tool_prompt` form a `tool_result`: a blocked call must never read as a success. The `tool_prompt` becomes a system message after the tool result; OpenAI Realtime agents don't use it, so put what they need in the `tool_result`. The
|
|
480
|
+
| `onFail` | `string \| FunctionResult \| Record<string, unknown>` | What the model gets when this is the first gate that fails: the tool result text, a `FunctionResult`, whose response and actions are used, or a data_map output object. It needs a response, and in the `tool_result`/`tool_prompt` form a `tool_result`: a blocked call must never read as a success. The `tool_prompt` becomes a system message after the tool result; OpenAI Realtime agents don't use it, so put what they need in the `tool_result`. The platform expands its `${...}` variables once, from the call's data as a data_map's output is, so it can quote what your code stored, such as `${global_data.semantic_state.proposal}`; a platform release from before that sends it as written |
|
|
445
481
|
| `opts.id` | `string` | 1 to 64 letters, digits or underscores, unique within the function. Default `gate_<n>`, 1-based |
|
|
446
482
|
| `opts.trueMeans`, `opts.falseMeans` | `string` | What yes and no mean, at most 2 KB each |
|
|
447
483
|
| `opts.visualInput` | `boolean \| number` | How many of the caller's newest video frames the decision model sees with this gate, as `visual_input`: `true` is 1, `false` or 0 none, or a whole number up to 5 (`MAX_VISUAL_INPUT`). Name it in the question, as in "Is the caller holding a photo ID up to the camera in `visual_input`?". All of a function's gates share one request, so each sees as many frames as the gate asking for the most. The gate provider must take images; one that doesn't makes the check a configuration error, which blocks the call. Left out by default. A function's own `visual_input`, frames sent to its webhook, is a separate field of the function, set through `extraFields` |
|
|
484
|
+
| `opts.unclear` | `boolean` | `true` to ask yes, no or unclear, where the gate's provider can (OpenAI). A yes under the threshold counts as unclear too, so such a gate wants a lower threshold than a yes/no one. Unclear doesn't run the function: the model gets `onUnclear`. Two unclear answers in a row for the same function and `semantic_state` ask again; the third is a fail, so the caller isn't asked the same thing forever. Default: yes or no |
|
|
485
|
+
| `opts.onUnclear` | `string \| FunctionResult \| Record<string, unknown>` | What the model gets when this is the first gate answered unclear and none failed, in the same forms as `onFail`. It should ask the caller again. Default: the platform's own, which does |
|
|
486
|
+
| `opts.dialogue` | `'window' \| 'proposal'` | The dialogue this gate judges, in place of the agent's ([`setSemanticGates({ dialogue })`](#setsemanticgatesopts)). A gate about something the caller asked before the proposal started, such as a request made before the account was found, wants `'window'` on an agent that judges its confirmations by the proposal |
|
|
487
|
+
| `opts.history` | `number` | How many of the newest dialogue entries this gate judges, a whole number from 1 to 100 (`MAX_GATE_HISTORY`), in place of the agent's `history` |
|
|
488
|
+
| `opts.since` | `string` | The name of a mark your code sets with [`FunctionResult.setSemanticGateMark(name)`](#data-actions). The gate judges the dialogue from the agent's first turn at or after the mark, at most `history` entries; until the mark is set, its `dialogue` as usual. Use it to anchor a confirmation to the moment your code chose, rather than to the last change of `semantic_state` |
|
|
489
|
+
|
|
490
|
+
Every gate on one function must have the same `dialogue`, `history` and `since`, set or not: they're asked together, about one dialogue. The SDK throws for gates that differ, as the platform refuses the function.
|
|
448
491
|
|
|
449
492
|
Gates are checked by the platform's rules when the tool is defined, and once more when the SWML is rendered. The platform refuses the whole function for an invalid gate, so the SDK throws instead. Gates aren't allowed on the hook names `startup_hook`, `hangup_hook` and `check_for_input`, on `end_call`, or on a built-in function's name. A gated function also needs a description, and a `web_hook_url` or `data_map`; tools the SDK builds always have them. A `gates` given as `null` is refused rather than dropped, since the platform refuses that function too.
|
|
450
493
|
|
|
@@ -472,10 +515,103 @@ defineTypedTool(opts: {
|
|
|
472
515
|
required?: string[];
|
|
473
516
|
gates?: ReadonlyArray<SemanticGate | Record<string, unknown>>;
|
|
474
517
|
gateFillers?: FillerPhrases;
|
|
518
|
+
vouched?: boolean;
|
|
519
|
+
nullableOptional?: boolean;
|
|
520
|
+
needsConversation?: boolean;
|
|
521
|
+
middleware?: readonly ToolMiddleware[];
|
|
475
522
|
}): this
|
|
476
523
|
```
|
|
477
524
|
|
|
478
|
-
`gates` and `gateFillers` work as they do on [`defineTool()`](#semantic-gates)
|
|
525
|
+
`gates` and `gateFillers` work as they do on [`defineTool()`](#semantic-gates), and so do `vouched`, `nullableOptional`, `needsConversation` and `middleware`.
|
|
526
|
+
|
|
527
|
+
#### `defineNativeTool(name, description, parameters?, fields?)`
|
|
528
|
+
|
|
529
|
+
Define a function the platform implements itself, under your own description and parameters. The platform runs its own implementation, by name, of a function whose `web_hook_url` is `'native'` (`NATIVE_WEBHOOK_URL`), and calls no webhook. A tool from `defineTool()` gets the agent's webhook URL, so it can't be one. Use it to describe a function the platform implements, such as `end_call`, in your own words, or to list it in a step's functions.
|
|
530
|
+
|
|
531
|
+
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
532
|
+
```ts
|
|
533
|
+
defineNativeTool(
|
|
534
|
+
name: string,
|
|
535
|
+
description: string,
|
|
536
|
+
parameters?: Record<string, unknown>,
|
|
537
|
+
fields?: Record<string, unknown>,
|
|
538
|
+
): this
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
```ts
|
|
542
|
+
agent.defineNativeTool(
|
|
543
|
+
'end_call',
|
|
544
|
+
'End the call once the order is placed and the caller has nothing else.',
|
|
545
|
+
{ type: 'object', properties: { reason: { type: 'string' } } },
|
|
546
|
+
);
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
#### `setUnavailableFunctionResponse(text)`
|
|
550
|
+
|
|
551
|
+
Set what the model is told when it calls a tool it can't use now: one the current step doesn't offer, or one the agent doesn't have. Without it, the platform says nothing ran, which steps offer the tool, and which tools are available now. `text` takes its place, with `${function}` for the tool's name, `${tools}` for the tools the request offered, comma-separated, and `${steps}` for the current context's steps whose functions include it, empty for a name the agent doesn't have. It's the `unavailable_function_response` param, which needs a platform release that has it. Throws for an empty string.
|
|
552
|
+
|
|
553
|
+
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
554
|
+
```ts
|
|
555
|
+
setUnavailableFunctionResponse(text: string): this
|
|
556
|
+
```
|
|
557
|
+
|
|
558
|
+
```ts
|
|
559
|
+
agent.setUnavailableFunctionResponse(
|
|
560
|
+
"Nothing ran: ${function} isn't offered now. Use one of: ${tools}.",
|
|
561
|
+
);
|
|
562
|
+
```
|
|
563
|
+
|
|
564
|
+
#### `setNullableOptionalParameters(enabled?)`
|
|
565
|
+
|
|
566
|
+
Let the model send `null` for every tool's optional arguments. Some providers' strict schemas make every argument required and refuse a call that leaves one out, so an optional argument must take `null` instead. With this on, each optional argument of a tool from `defineTool()` takes `null` as well as its type, and a `null` reaches the handler as an argument not given. A tool's own `nullableOptional` overrides it. It applies when the SWML is rendered, and to the MCP tool list, so it covers tools defined before and after it.
|
|
567
|
+
|
|
568
|
+
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
569
|
+
```ts
|
|
570
|
+
setNullableOptionalParameters(enabled?: boolean): this // default true
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
#### `addToolMiddleware(middleware)`
|
|
574
|
+
|
|
575
|
+
Run `middleware` around every tool call, after any added before it. A middleware is `(name, args, rawData, callNext) => result`. It runs before the handler, and calls `callNext(args, rawData)` for the rest of the chain and the handler, possibly with changed arguments. `callNext` returns a promise of the handler's result, so a middleware awaits it, or returns it as it is. What the middleware returns is the call's result: the handler's, a changed one, or its own without calling `callNext`. A middleware that throws `ToolRefusal` declines the call; any other error gives the model the unknown-outcome result. It covers tools from `defineTool()`, not DataMap or native tools, which run on the platform. The order around a call is the resend dedupe, the agent's middleware, then the tool's own.
|
|
576
|
+
|
|
577
|
+
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
578
|
+
```ts
|
|
579
|
+
type CallNext = (args: Record<string, unknown>, rawData: Record<string, unknown>) => Promise<unknown>;
|
|
580
|
+
type ToolMiddleware = (
|
|
581
|
+
name: string,
|
|
582
|
+
args: Record<string, unknown>,
|
|
583
|
+
rawData: Record<string, unknown>,
|
|
584
|
+
callNext: CallNext,
|
|
585
|
+
) => unknown;
|
|
586
|
+
|
|
587
|
+
addToolMiddleware(middleware: ToolMiddleware): this
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
```ts
|
|
591
|
+
import type { ToolMiddleware } from '@signalwire/sdk';
|
|
592
|
+
|
|
593
|
+
const logCalls: ToolMiddleware = async (name, args, rawData, callNext) => {
|
|
594
|
+
const started = performance.now();
|
|
595
|
+
const result = await callNext(args, rawData);
|
|
596
|
+
console.log(name, Math.round(performance.now() - started), 'ms');
|
|
597
|
+
return result;
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
agent.addToolMiddleware(logCalls);
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
`runChain(middleware, name, args, rawData, dispatch)` runs a list of middleware around a function of your own, and `resolve(value)` awaits a value that may be a promise, for code ported from the Python SDK.
|
|
604
|
+
|
|
605
|
+
#### `setToolResendDedupe(enabled?)`
|
|
606
|
+
|
|
607
|
+
Turn the dedupe of transport retries on or off; it's on by default. SignalWire sends a tool request again, with the same body, after a timeout, a failed connection or a 5xx, so a slow tool could run twice. The dedupe answers a retry with the first attempt's result, and one that arrives while the first is still running waits for it. A retry is a request with the same `call_id`, `tool_call_id` and function name. A call the model makes again has a new `tool_call_id` and runs, and a request without one always runs. It runs first, before any middleware. It's shared with the agent's per-request copies, and the record is kept in the agent's process, so with several processes or replicas a retry that reaches another one runs the tool again.
|
|
608
|
+
|
|
609
|
+
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
610
|
+
```ts
|
|
611
|
+
setToolResendDedupe(enabled?: boolean): this // default true
|
|
612
|
+
```
|
|
613
|
+
|
|
614
|
+
The dedupe is a `ResendDedupe(ttl = 600, maxEntries = 1024)`, exported for use in your own chains: its `middleware` property is the `ToolMiddleware`. Finished results are kept for `ttl` seconds, at most `maxEntries` of them; an attempt still running is never dropped.
|
|
479
615
|
|
|
480
616
|
#### `getTools()`
|
|
481
617
|
|
|
@@ -636,6 +772,8 @@ Add a pronunciation rule, emitted in `pronounce`. See [PronunciationRule](#pronu
|
|
|
636
772
|
addPronunciation(rule: PronunciationRule): this
|
|
637
773
|
```
|
|
638
774
|
|
|
775
|
+
The platform normalizes the text before these rules run, so a bare number is already words by then: a rule can't make "10001" read digit by digit. Tokens the normalizer treats as designations, such as IDs and codes, pass through unchanged, and rules do see those. To read digits, a ZIP code or an amount of money, give the words instead with the speech helpers: `sayDigits('10001')` is "one zero zero zero one". See [Conversation Patterns](conversation_patterns.md#numbers-the-way-a-voice-should-say-them).
|
|
776
|
+
|
|
639
777
|
#### `setPronunciations(rules)`
|
|
640
778
|
|
|
641
779
|
Replace every pronunciation rule.
|
|
@@ -671,7 +809,12 @@ Set how the call checks its functions' [semantic gates](#semantic-gates). Each o
|
|
|
671
809
|
|
|
672
810
|
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
673
811
|
```ts
|
|
674
|
-
setSemanticGates(opts?: {
|
|
812
|
+
setSemanticGates(opts?: {
|
|
813
|
+
enabled?: boolean;
|
|
814
|
+
timeoutMs?: number;
|
|
815
|
+
history?: number;
|
|
816
|
+
dialogue?: 'window' | 'proposal';
|
|
817
|
+
}): this
|
|
675
818
|
```
|
|
676
819
|
|
|
677
820
|
| Option | Type | Default | Description |
|
|
@@ -679,11 +822,14 @@ setSemanticGates(opts?: { enabled?: boolean; timeoutMs?: number; history?: numbe
|
|
|
679
822
|
| `enabled` | `boolean` | `true` | `false` dispatches gated functions without checking their gates. Sent as `semantic_gates_enabled` |
|
|
680
823
|
| `timeoutMs` | `number` | `2500` | The time one check may take, 500 to 10000 milliseconds. A check that runs out blocks the call. Sent as `semantic_gate_timeout_ms` |
|
|
681
824
|
| `history` | `number` | `20` | How many recent dialogue entries the decision model sees, 0 to 100. Sent as `semantic_gate_history` |
|
|
825
|
+
| `dialogue` | `'window' \| 'proposal'` | `'window'` | Which dialogue the decision model judges: `'window'`, the newest `history` entries, or `'proposal'`, the entries since `global_data.semantic_state` last changed, from the agent's first turn after it. With `'proposal'`, a gate that confirms a read-back sees the read-back and the caller's reply, not the requests before it. With no `semantic_state` set, the window. Sent as `semantic_gate_dialogue`, which needs a platform release that has it |
|
|
826
|
+
|
|
827
|
+
A gate's own `dialogue` and `history` take the place of these for its function.
|
|
682
828
|
|
|
683
829
|
**Throws:** `Error` for a value of the wrong type or out of range; a refused call changes nothing.
|
|
684
830
|
|
|
685
831
|
```ts
|
|
686
|
-
agent.setSemanticGates({ timeoutMs: 4000, history: 30 });
|
|
832
|
+
agent.setSemanticGates({ timeoutMs: 4000, history: 30, dialogue: 'proposal' });
|
|
687
833
|
```
|
|
688
834
|
|
|
689
835
|
#### `setGlobalData(data)`
|
|
@@ -1051,6 +1197,75 @@ Remove every SWAIG query parameter.
|
|
|
1051
1197
|
clearSwaigQueryParams(): this
|
|
1052
1198
|
```
|
|
1053
1199
|
|
|
1200
|
+
### AI Event Methods
|
|
1201
|
+
|
|
1202
|
+
The platform posts AI events, such as `ai.speech_detect` for each final of the caller's speech, to a call's `event_webhook_url` as they happen. These methods point that URL at the agent's own `/ai_events` endpoint when the SWML is rendered, unless you set `event_webhook_url` yourself (the agent then logs `event_webhook_url_already_set`, and its handlers get nothing). The endpoint takes a POST of JSON, within the agent's request size limit, behind the agent's basic auth and, with a `signingKey`, its signature check.
|
|
1203
|
+
|
|
1204
|
+
Set them on the agent, not in a dynamic config callback or `addPerCallConfig()`: the `/ai_events` endpoint runs on the agent itself, not on a per-request copy. The speech log is shared with the agent's per-request copies, so a tool handler reads it through its third argument too.
|
|
1205
|
+
|
|
1206
|
+
#### `onAiEvent(handler)`
|
|
1207
|
+
|
|
1208
|
+
Register a handler for the AI events the platform posts during calls. The handler is called with each event: `handler(eventType, params, event)`, where `params` is the event's `params` object and `event` the whole envelope `{ event_type, timestamp, project_id, space_id, params }`. `ai.speech_detect` (`SPEECH_DETECT`) comes for each final of the caller's speech, with its `text` and the recognizer's `words`, `[{ word, confidence }]`. The handlers run in turn and are awaited before the endpoint answers; one that throws is logged, and the others still run. A call with `redact_prompt` set sends no `ai.speech_detect` unless debug is on. Returns the handler.
|
|
1209
|
+
|
|
1210
|
+
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
1211
|
+
```ts
|
|
1212
|
+
type AiEventHandler = (
|
|
1213
|
+
eventType: string,
|
|
1214
|
+
params: Record<string, unknown>,
|
|
1215
|
+
event: Record<string, unknown>,
|
|
1216
|
+
) => unknown;
|
|
1217
|
+
|
|
1218
|
+
onAiEvent(handler: AiEventHandler): AiEventHandler
|
|
1219
|
+
```
|
|
1220
|
+
|
|
1221
|
+
#### `recordSpeechFinals(maxCalls?, maxFinals?)`
|
|
1222
|
+
|
|
1223
|
+
Keep each call's recognizer finals, from `ai.speech_detect`, for tool handlers to read with `speechFinals()`. It sets `event_webhook_url` as `onAiEvent()` does. It keeps up to `maxFinals` (default 200) finals for each of up to `maxCalls` (default 500) calls; the oldest call's finals go first. The finals live in the process: replicas of an agent each keep their own.
|
|
1224
|
+
|
|
1225
|
+
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
1226
|
+
```ts
|
|
1227
|
+
recordSpeechFinals(maxCalls?: number, maxFinals?: number): this
|
|
1228
|
+
```
|
|
1229
|
+
|
|
1230
|
+
#### `speechFinals(callId, since?)`
|
|
1231
|
+
|
|
1232
|
+
A call's recognizer finals, oldest first, as `{ text, words, timestamp }`, with `timestamp` in seconds since the epoch; `since` keeps the ones from that time on. The words are as the recognizer heard them, with their confidences, before hearing hints and number formatting change the text, so a handler can ask again about a word the recognizer wasn't sure of. Returns copies, and `[]` before `recordSpeechFinals()`.
|
|
1233
|
+
|
|
1234
|
+
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
1235
|
+
```ts
|
|
1236
|
+
speechFinals(callId: string, since?: number): SpeechFinal[]
|
|
1237
|
+
```
|
|
1238
|
+
|
|
1239
|
+
```ts
|
|
1240
|
+
import { AgentBase, FunctionResult } from '@signalwire/sdk';
|
|
1241
|
+
|
|
1242
|
+
const speller = new AgentBase({ name: 'speller' }).recordSpeechFinals();
|
|
1243
|
+
|
|
1244
|
+
speller.defineTool({
|
|
1245
|
+
name: 'spell_name',
|
|
1246
|
+
description: "Take the caller's spelled name",
|
|
1247
|
+
parameters: { name: { type: 'string', description: 'The name' } },
|
|
1248
|
+
required: ['name'],
|
|
1249
|
+
handler: (args, rawData) => {
|
|
1250
|
+
const finals = speller.speechFinals(String(rawData.call_id));
|
|
1251
|
+
const doubtful = finals
|
|
1252
|
+
.slice(-1)
|
|
1253
|
+
.flatMap((f) => f.words)
|
|
1254
|
+
.filter((w) => w.confidence < 0.85)
|
|
1255
|
+
.map((w) => w.word);
|
|
1256
|
+
if (doubtful.length > 0) {
|
|
1257
|
+
return new FunctionResult().setToolResponse(
|
|
1258
|
+
`Not sure of: ${doubtful.join(', ')}`,
|
|
1259
|
+
'Ask the caller to repeat those letters.',
|
|
1260
|
+
);
|
|
1261
|
+
}
|
|
1262
|
+
return new FunctionResult().setToolResponse(`Name: ${args.name}`);
|
|
1263
|
+
},
|
|
1264
|
+
});
|
|
1265
|
+
```
|
|
1266
|
+
|
|
1267
|
+
`SpeechLog`, the store behind it, is exported for use on its own: `add(event)`, `finals(callId, since?)` and `forget(callId)`.
|
|
1268
|
+
|
|
1054
1269
|
### SIP Routing and MCP Methods
|
|
1055
1270
|
|
|
1056
1271
|
#### `enableSipRouting(autoMap?, path?)`
|
|
@@ -1400,7 +1615,7 @@ Import the class from the package root:
|
|
|
1400
1615
|
import { AgentServer } from '@signalwire/sdk';
|
|
1401
1616
|
```
|
|
1402
1617
|
|
|
1403
|
-
`AgentServer` serves several agents from one HTTP server, each under its own route prefix.
|
|
1618
|
+
`AgentServer` serves several agents from one HTTP server, each under its own route prefix. `AgentServer<T extends SWMLService = AgentBase>` is generic over what it hosts: `new AgentServer<SWMLService>()` hosts plain `SWMLService` call flows next to agents, and its `getAgent()` and `getAgents()` then return `SWMLService`. A plain service answers at its route with or without a trailing slash, under its own basic auth, and serves its `/swaig` endpoint and routing callbacks; the agent endpoints (`/post_prompt`, `/check_for_input`, `/debug`) aren't served for it.
|
|
1404
1619
|
|
|
1405
1620
|
### Constructor
|
|
1406
1621
|
|
|
@@ -1421,10 +1636,10 @@ constructor(opts?: { host?: string; port?: number; logLevel?: string })
|
|
|
1421
1636
|
|
|
1422
1637
|
| Method | Signature | Description |
|
|
1423
1638
|
|--------|-----------|-------------|
|
|
1424
|
-
| `register` | `(agent:
|
|
1639
|
+
| `register` | `(agent: T, route?: string): void` | Mount the agent's (or service's) `asRouter()` at `route` (default its own route). Throws when the route is taken. |
|
|
1425
1640
|
| `unregister` | `(route: string): boolean` | Remove an agent and its routes; returns `false` when none was registered there. |
|
|
1426
|
-
| `getAgents` | `(): Map<string,
|
|
1427
|
-
| `getAgent` | `(route: string):
|
|
1641
|
+
| `getAgents` | `(): Map<string, T>` | Registered agents keyed by route |
|
|
1642
|
+
| `getAgent` | `(route: string): T \| undefined` | The agent at a route |
|
|
1428
1643
|
| `serveStaticFiles` | `(directory: string, route?: string): void` | Serve files from a directory, rejecting paths with `..` |
|
|
1429
1644
|
| `setupSipRouting` | `(route?: string, autoMap?: boolean): void` | Route SIP requests to agents by username at `route` (default `/sip`) |
|
|
1430
1645
|
| `registerSipUsername` | `(username: string, route: string): void` | Map a SIP username to an agent's route |
|
|
@@ -1577,6 +1792,7 @@ console.log(JSON.stringify(result.toDict()));
|
|
|
1577
1792
|
| `updateGlobalData` | `(data: Record<string, unknown>): this` | `{ set_global_data: data }` |
|
|
1578
1793
|
| `removeGlobalData` | `(keys: string \| string[]): this` | `{ unset_global_data: keys }` |
|
|
1579
1794
|
| `setSemanticState` | `(state: Record<string, unknown>): this` | `{ set_global_data: { semantic_state: state } }`. Replaces the state [semantic gates](#semantic-gates) judge, as a whole; send `{}` to reset it |
|
|
1795
|
+
| `setSemanticGateMark` | `(name: string): this` | `{ semantic_gate_mark: name }`. Sets a mark that gates with `since: name` judge the dialogue from. The name is 1 to 64 letters, digits or underscores; throws otherwise. Needs a platform release that has it |
|
|
1580
1796
|
| `setMetadata` | `(data: Record<string, unknown>): this` | `{ set_meta_data: data }` |
|
|
1581
1797
|
| `removeMetadata` | `(keys: string \| string[]): this` | `{ unset_meta_data: keys }` |
|
|
1582
1798
|
|
|
@@ -1586,6 +1802,7 @@ console.log(JSON.stringify(result.toDict()));
|
|
|
1586
1802
|
|--------|-----------|-------|
|
|
1587
1803
|
| `executeSwml` | `(swmlContent: string \| Record<string, unknown> \| { toDict(): Record<string, unknown> }, transfer?: boolean): this` | `{ SWML: document }`, with `transfer: 'true'` when `transfer` is `true`. A string that isn't JSON becomes `{ raw_swml: string }`; any other value throws. |
|
|
1588
1804
|
| `swmlChangeStep` | `(stepName: string): this` | `{ change_step: stepName }` |
|
|
1805
|
+
| `refreshStep` | `(stepName: string): this` | `{ change_step: stepName }`, the same action, for the current step: entering it again shows its text with new global data. See [Refreshing a step](swaig-reference.md#refreshstep) |
|
|
1589
1806
|
| `swmlChangeContext` | `(contextName: string): this` | `{ change_context: contextName }` |
|
|
1590
1807
|
| `swmlUserEvent` | `(eventData: Record<string, unknown>): this` | A `SWML` action with a `user_event` verb |
|
|
1591
1808
|
| `switchContext` | `(opts?: { systemPrompt?: string; userPrompt?: string; consolidate?: boolean; fullReset?: boolean }): this` | `{ context_switch: systemPrompt }` when only `systemPrompt` is set, otherwise an object with `system_prompt`, `user_prompt`, `consolidate` and `full_reset` |
|
|
@@ -1596,6 +1813,8 @@ console.log(JSON.stringify(result.toDict()));
|
|
|
1596
1813
|
|--------|-----------|-------|
|
|
1597
1814
|
| `toggleFunctions` | `(toggles: { function: string; active: boolean }[]): this` | `{ toggle_functions: toggles }` |
|
|
1598
1815
|
| `enableFunctionsOnTimeout` | `(enabled?: boolean): this` | `{ functions_on_speaker_timeout: enabled }` (default `true`) |
|
|
1816
|
+
| `noBargeNextResponse` | `(): this` | `{ no_barge_next_response: true }`. The next spoken reply plays whole: what the caller says during it is held until after it |
|
|
1817
|
+
| `backToBackFunctions` | `(value?: boolean \| 'forever'): this` | `{ back_to_back_functions: value }` (default `true`). Whether the model may call another function right after a function result. Throws for any other value |
|
|
1599
1818
|
| `updateSettings` | `(settings: Record<string, unknown>): this` | `{ settings: settings }` |
|
|
1600
1819
|
|
|
1601
1820
|
### Communication Actions
|
|
@@ -1737,6 +1956,10 @@ See [SwaigFunctionOptions](#swaigfunctionoptions) for the options.
|
|
|
1737
1956
|
| `isExternal` | `boolean` | Whether `webhookUrl` was given |
|
|
1738
1957
|
| `onError` | `SwaigErrorHandler \| undefined` | Per-tool error hook |
|
|
1739
1958
|
| `errorMessage` | `string \| undefined` | Per-tool error response |
|
|
1959
|
+
| `vouched` | `boolean` | Whether the model must vouch for the arguments |
|
|
1960
|
+
| `nullableOptional` | `boolean \| undefined` | Whether optional arguments take `null`; `undefined` follows the agent |
|
|
1961
|
+
| `needsConversation` | `boolean` | Whether the handler reads the conversation |
|
|
1962
|
+
| `middleware` | `readonly ToolMiddleware[]` | The tool's own middleware |
|
|
1740
1963
|
|
|
1741
1964
|
### Methods
|
|
1742
1965
|
|
|
@@ -1751,7 +1974,7 @@ validateArgs(args: Record<string, unknown>): [boolean, string[]]
|
|
|
1751
1974
|
|
|
1752
1975
|
#### `execute(args, rawData?, agentOnError?)`
|
|
1753
1976
|
|
|
1754
|
-
Run the handler and return the serialized result. The handler's third argument is `undefined` here. When the handler throws, the tool's `onError`, then `agentOnError`, may supply a `FunctionResult`; otherwise the result carries `errorMessage` or the
|
|
1977
|
+
Run the handler and return the serialized result. The handler's third argument is `undefined` here. When the handler throws, the tool's `onError`, then `agentOnError`, may supply a `FunctionResult`; otherwise the result carries `errorMessage` or the unknown-outcome result, `toolErrorResult(name)`. A thrown `ToolRefusal` gives its own result, without the hooks. The vouched check, the outcome rules and the tool's own middleware apply; the agent's middleware and resend dedupe apply only to calls the agent dispatches.
|
|
1755
1978
|
|
|
1756
1979
|
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
1757
1980
|
```ts
|
|
@@ -2055,6 +2278,17 @@ Check the contexts and throw on the first problem. It requires at least one cont
|
|
|
2055
2278
|
validate(): void
|
|
2056
2279
|
```
|
|
2057
2280
|
|
|
2281
|
+
#### `stepsOffering(name)`
|
|
2282
|
+
|
|
2283
|
+
The `[context, step]` pairs whose function list, or a gather question's, names a tool. The functions a step without `setFunctions()` inherits from the step before it aren't counted, since they depend on how the caller got there; its gather questions' own function lists are. When every step lists its functions and none lists a registered tool, rendering the SWML logs a `tool_offered_by_no_step` warning for it, once: the model never gets that tool unless a function result turns it on with `toggleFunctions()`.
|
|
2284
|
+
|
|
2285
|
+
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
2286
|
+
```ts
|
|
2287
|
+
stepsOffering(name: string): Array<[string, string]>
|
|
2288
|
+
```
|
|
2289
|
+
|
|
2290
|
+
Rendering also logs `tool_named_but_not_offered`, once each, for a registered tool named where a step that lists its functions doesn't offer it: its text, its criteria, its context's prompt, a gather question, or a gate's output on one of its tools. The exported `namedTools(text, tools)` finds the names: one with an underscore counts as a whole word anywhere, a one-word name only in backticks or before "(".
|
|
2291
|
+
|
|
2058
2292
|
#### `toDict()`
|
|
2059
2293
|
|
|
2060
2294
|
Validate, then serialize every context in the order it was added.
|
|
@@ -2110,7 +2344,7 @@ The `addStep()` options are shortcuts:
|
|
|
2110
2344
|
| `setUserPrompt` | `(userPrompt: string): this` | Emits `user_prompt` |
|
|
2111
2345
|
| `setIsolated` | `(isolated: boolean): this` | Emits `isolated: true` |
|
|
2112
2346
|
| `setPrompt` | `(prompt: string): this` | Raw `prompt`. Throws when prompt POM sections exist. |
|
|
2113
|
-
| `setHistory` | `(history: string): this` | Default history mode for the context's steps: `keep`, `default` or `
|
|
2347
|
+
| `setHistory` | `(history: string): this` | Default history mode for the context's steps: `keep`, `default`, `hide` or `isolate`. Throws on any other value. |
|
|
2114
2348
|
|
|
2115
2349
|
#### POM Sections
|
|
2116
2350
|
|
|
@@ -2172,14 +2406,15 @@ constructor(name: string)
|
|
|
2172
2406
|
| `setEnd` | `(end: boolean): this` | Emits `end: true`, which leaves step mode after this step. It doesn't end the call. |
|
|
2173
2407
|
| `setSkipUserTurn` | `(skip: boolean): this` | Emits `skip_user_turn: true` |
|
|
2174
2408
|
| `setSkipToNextStep` | `(skip: boolean): this` | Emits `skip_to_next_step: true` |
|
|
2175
|
-
| `setHistory` | `(history: string): this` | History mode when the step is entered: `keep`, `default` or `hide
|
|
2409
|
+
| `setHistory` | `(history: string): this` | History mode when the step is entered: `keep`, `default`, `hide` or `isolate` (like `hide`, but only while the agent is in the step). Throws on any other value. |
|
|
2410
|
+
| `setExpectedAnswer` | `(digits?: number, opts?: { minDigits?: number; maxDigits?: number }): this` | Emits `expected_answer`: how many digits the recognizer should expect before it ends its wait, `{ digits }` or `{ min_digits, max_digits }`, each from 1 to 64. Throws for any other shape. See [Expected Answers](contexts-guide.md#expected-answers) |
|
|
2176
2411
|
|
|
2177
2412
|
#### Gather Info Methods
|
|
2178
2413
|
|
|
2179
2414
|
| Method | Signature | Description |
|
|
2180
2415
|
|--------|-----------|-------------|
|
|
2181
2416
|
| `setGatherInfo` | `(opts?: { outputKey?: string; completionAction?: string; prompt?: string; isolated?: boolean }): this` | Start a `gather_info` for the step |
|
|
2182
|
-
| `addGatherQuestion` | `(opts: { key: string; question: string; type?: string; confirm?: boolean; prompt?: string; functions?: string[]; isolated?: boolean }): this` | Add a question. Throws when `setGatherInfo()` hasn't been called. |
|
|
2417
|
+
| `addGatherQuestion` | `(opts: { key: string; question: string; type?: string; confirm?: boolean; prompt?: string; functions?: string[]; isolated?: boolean; expectedAnswer?: ExpectedAnswer }): this` | Add a question. Throws when `setGatherInfo()` hasn't been called. |
|
|
2183
2418
|
|
|
2184
2419
|
`completionAction` is `'next_step'` or the name of a step in the same context. `isolated` on the gather is the default for its questions, and a question's own `isolated` overrides it. A question's `false` is emitted, so it can override an isolated gather.
|
|
2185
2420
|
|
|
@@ -2187,10 +2422,12 @@ constructor(name: string)
|
|
|
2187
2422
|
|
|
2188
2423
|
| Method | Signature | Description |
|
|
2189
2424
|
|--------|-----------|-------------|
|
|
2190
|
-
| `setResetSystemPrompt` | `(systemPrompt: string): this` |
|
|
2191
|
-
| `setResetUserPrompt` | `(userPrompt: string): this` |
|
|
2192
|
-
| `setResetConsolidate` | `(consolidate: boolean): this` |
|
|
2193
|
-
| `setResetFullReset` | `(fullReset: boolean): this` |
|
|
2425
|
+
| `setResetSystemPrompt` | `(systemPrompt: string): this` | The system prompt the reset loads (`reset.system_prompt`) |
|
|
2426
|
+
| `setResetUserPrompt` | `(userPrompt: string): this` | The user message the reset adds (`reset.user_prompt`) |
|
|
2427
|
+
| `setResetConsolidate` | `(consolidate: boolean): this` | Whether the reset summarizes the conversation into one message (`reset.consolidate`) |
|
|
2428
|
+
| `setResetFullReset` | `(fullReset: boolean): this` | Whether the reset replaces the system prompt, seeded with the summary (`reset.full_reset`) |
|
|
2429
|
+
|
|
2430
|
+
A step with any reset setting is terminal: when the call enters it, the platform runs the reset in place of the step's text, and step mode ends there. Rendering logs `step_reset_is_terminal` for such a step, once.
|
|
2194
2431
|
|
|
2195
2432
|
#### `toDict()`
|
|
2196
2433
|
|
|
@@ -2218,7 +2455,7 @@ constructor(opts?: { outputKey?: string; completionAction?: string; prompt?: str
|
|
|
2218
2455
|
|
|
2219
2456
|
| Method | Signature | Description |
|
|
2220
2457
|
|--------|-----------|-------------|
|
|
2221
|
-
| `addQuestion` | `(opts: { key; question; type?; confirm?; prompt?; functions?; isolated? }): this` | Add a question |
|
|
2458
|
+
| `addQuestion` | `(opts: { key; question; type?; confirm?; prompt?; functions?; isolated?; expectedAnswer? }): this` | Add a question |
|
|
2222
2459
|
| `getQuestions` | `(): GatherQuestion[]` | Get the questions |
|
|
2223
2460
|
| `toDict` | `(): GatherInfoDict` | Serialize. Throws when there are no questions. |
|
|
2224
2461
|
|
|
@@ -2240,6 +2477,7 @@ constructor(opts: {
|
|
|
2240
2477
|
prompt?: string;
|
|
2241
2478
|
functions?: string[];
|
|
2242
2479
|
isolated?: boolean;
|
|
2480
|
+
expectedAnswer?: ExpectedAnswer; // replaces the step's while this question is asked
|
|
2243
2481
|
})
|
|
2244
2482
|
```
|
|
2245
2483
|
|
|
@@ -2254,6 +2492,7 @@ constructor(opts: {
|
|
|
2254
2492
|
| `prompt` | `string \| undefined` | Extra prompt text for this question |
|
|
2255
2493
|
| `functions` | `string[] \| undefined` | Tools available while this question is asked |
|
|
2256
2494
|
| `isolated` | `boolean \| undefined` | Overrides the gather's `isolated` for this question |
|
|
2495
|
+
| `expectedAnswer` | `ExpectedAnswer \| undefined` | The digits the recognizer expects while this question is asked |
|
|
2257
2496
|
|
|
2258
2497
|
#### `toDict()`
|
|
2259
2498
|
|
|
@@ -2275,14 +2514,24 @@ Create a `Context` without a builder. The name defaults to `'default'`.
|
|
|
2275
2514
|
function createSimpleContext(name?: string): Context
|
|
2276
2515
|
```
|
|
2277
2516
|
|
|
2517
|
+
#### `expectedAnswer(digits?, opts?)`
|
|
2518
|
+
|
|
2519
|
+
Build an `expected_answer` and check it as the platform reads it: `expectedAnswer(5)` is `{ digits: 5 }`, and `expectedAnswer(undefined, { minDigits: 4, maxDigits: 6 })` is `{ min_digits: 4, max_digits: 6 }`. Each count is from 1 to 64 (`MAX_EXPECTED_DIGITS`), and the minimum is at most the maximum. Throws for anything else, which the platform would log and ignore.
|
|
2520
|
+
|
|
2521
|
+
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
2522
|
+
```ts
|
|
2523
|
+
type ExpectedAnswer = { digits: number } | { min_digits: number; max_digits: number };
|
|
2524
|
+
function expectedAnswer(digits?: number, opts?: { minDigits?: number; maxDigits?: number }): ExpectedAnswer
|
|
2525
|
+
```
|
|
2526
|
+
|
|
2278
2527
|
#### `HISTORY_MODES`
|
|
2279
2528
|
|
|
2280
2529
|
The accepted history modes:
|
|
2281
2530
|
|
|
2282
2531
|
<!-- snippet: no-compile API signature / type reference, not runnable code -->
|
|
2283
2532
|
```ts
|
|
2284
|
-
const HISTORY_MODES: readonly ['keep', 'default', 'hide']
|
|
2285
|
-
type HistoryMode = 'keep' | 'default' | 'hide'
|
|
2533
|
+
const HISTORY_MODES: readonly ['keep', 'default', 'hide', 'isolate']
|
|
2534
|
+
type HistoryMode = 'keep' | 'default' | 'hide' | 'isolate'
|
|
2286
2535
|
```
|
|
2287
2536
|
|
|
2288
2537
|
---
|
|
@@ -2905,6 +3154,7 @@ import {
|
|
|
2905
3154
|
| `parsePostPromptData` | `(data: unknown): Record<string, unknown>` | Read `post_prompt_data` in any shape: an object inside `parsed`, flat keys, or a `raw` string (with or without a code fence). Prose that isn't JSON becomes `{ summary: text }`. |
|
|
2906
3155
|
| `dialogueTurns` | `(callLog: unknown, opts?: { roles?: readonly string[]; dropEcho?: string \| null }): DialogueTurn[]` | The turns with the given roles (default `DIALOGUE_ROLES`) and non-empty content, without entries that carry `tool_calls`. A turn whose content equals `dropEcho` is dropped. |
|
|
2907
3156
|
| `stripJsonFence` | `(text: string): string` | Remove a surrounding code fence, such as one labeled `json` |
|
|
3157
|
+
| `callerTurns` | `(rawData: unknown, since?: number, opts?: { last?: number }): string[]` | What the caller said, oldest first, from a SWAIG request's `call_log` (or `raw_call_log` when that's empty), or from a call log given directly. `since` keeps the turns from that time on, in the call log's microseconds; `last` keeps the newest that many. A request carries the conversation only with `swaig_post_conversation` on, which a tool's `needsConversation` turns on |
|
|
2908
3158
|
| `DIALOGUE_ROLES` | `readonly string[]` | `['user', 'assistant']` |
|
|
2909
3159
|
|
|
2910
3160
|
`DialogueTurn` is `{ role: string; content: string }`. A `NormalizedPostPrompt` has these readonly properties:
|
|
@@ -3428,8 +3678,8 @@ type SwaigHandler = (
|
|
|
3428
3678
|
args: Record<string, unknown>,
|
|
3429
3679
|
rawData: SwaigRequest,
|
|
3430
3680
|
agent?: AgentBase,
|
|
3431
|
-
) => FunctionResult | Record<string, unknown> | string
|
|
3432
|
-
| Promise<FunctionResult | Record<string, unknown> | string>;
|
|
3681
|
+
) => FunctionResult | Record<string, unknown> | string | null | undefined | void
|
|
3682
|
+
| Promise<FunctionResult | Record<string, unknown> | string | null | undefined | void>;
|
|
3433
3683
|
```
|
|
3434
3684
|
|
|
3435
3685
|
`args` holds the arguments the model supplied. `rawData` is the whole SWAIG request, with `call_id`, `global_data` and the rest. `agent` is the agent the request was configured on: the per-request copy when per-request configuration is in use, and `undefined` when you call `SwaigFunction.execute()` yourself.
|
|
@@ -3437,10 +3687,13 @@ type SwaigHandler = (
|
|
|
3437
3687
|
The return value is serialized as follows:
|
|
3438
3688
|
|
|
3439
3689
|
- A `FunctionResult` is serialized with `toDict()`.
|
|
3440
|
-
- An object with a `response` key is sent as is.
|
|
3441
|
-
-
|
|
3690
|
+
- An object with a `response` or an `action` key is sent as is.
|
|
3691
|
+
- Any other object is the handler's data: it's sent as `{ response: JSON.stringify(data) }`, with a `bigint` as its digits. An empty object tells the model the outcome is unknown.
|
|
3692
|
+
- `undefined` or `null` is sent as `{ response: 'Function executed successfully' }`.
|
|
3442
3693
|
- Any other value is converted to a string and wrapped in a `FunctionResult`, and the SDK logs a warning.
|
|
3443
3694
|
|
|
3695
|
+
`settleResult(name, result)` applies these rules, and `toolErrorResult(name)` is the result for a handler that threw.
|
|
3696
|
+
|
|
3444
3697
|
A synchronous or CPU-bound handler blocks Node's event loop, and with it every other request, until it returns.
|
|
3445
3698
|
|
|
3446
3699
|
### SwaigFunctionOptions
|
|
@@ -3467,9 +3720,13 @@ interface SwaigFunctionOptions
|
|
|
3467
3720
|
| `extraFields` | `Record<string, unknown>` | `{}` | Extra keys merged into the definition |
|
|
3468
3721
|
| `isTypedHandler` | `boolean` | `false` | Whether the handler takes named parameters |
|
|
3469
3722
|
| `onError` | `SwaigErrorHandler` | none | Per-tool error hook |
|
|
3470
|
-
| `errorMessage` | `string` |
|
|
3723
|
+
| `errorMessage` | `string` | The unknown-outcome result | Response when the handler throws and no hook returns one |
|
|
3471
3724
|
| `gates` | `(SemanticGate \| Record<string, unknown>)[]` | none | [Semantic gates](#semantic-gates), 1 to 8 |
|
|
3472
3725
|
| `gateFillers` | `FillerPhrases` | none | Phrases said while the gates are checked. Only with `gates` |
|
|
3726
|
+
| `vouched` | `boolean` | `false` | Run only when the model vouches the arguments came from the caller. See [`defineTool()`](#definetoolopts) |
|
|
3727
|
+
| `nullableOptional` | `boolean` | the agent's | Optional arguments take `null` |
|
|
3728
|
+
| `needsConversation` | `boolean` | `false` | Turns on `swaig_post_conversation` |
|
|
3729
|
+
| `middleware` | `ToolMiddleware[]` | none | Middleware around this tool's calls only |
|
|
3473
3730
|
|
|
3474
3731
|
### AuthConfig
|
|
3475
3732
|
|
package/docs/architecture.md
CHANGED
|
@@ -534,14 +534,18 @@ The third argument is the agent the request was configured on: the per-request c
|
|
|
534
534
|
Handler returns:
|
|
535
535
|
|
|
|
536
536
|
|-- FunctionResult --> result.toDict()
|
|
537
|
-
|-- { response
|
|
538
|
-
|--
|
|
537
|
+
|-- { response } or { action } --> sent as it is
|
|
538
|
+
|-- any other object --> { response: JSON of the object }; {} -> the outcome is unknown
|
|
539
|
+
|-- undefined or null --> FunctionResult("Function executed successfully").toDict()
|
|
539
540
|
|-- anything else (a string) --> FunctionResult(String(value)).toDict()
|
|
540
|
-
|-- throws
|
|
541
|
+
|-- throws ToolRefusal --> its tool_result and tool_prompt
|
|
542
|
+
|-- throws anything else --> the tool's onError hook, then the agent's onError hook;
|
|
541
543
|
a FunctionResult either returns is sent. Otherwise
|
|
542
|
-
|
|
544
|
+
errorMessage, or toolErrorResult(name): the outcome is unknown
|
|
543
545
|
```
|
|
544
546
|
|
|
547
|
+
The tool middleware runs around this: the resend dedupe, the agent's middleware (`addToolMiddleware()`), then the tool's own, with the same rules for what a middleware returns.
|
|
548
|
+
|
|
545
549
|
`FunctionResult.toDict()` produces an object like this one:
|
|
546
550
|
|
|
547
551
|
```json
|
package/docs/cli-guide.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
`swaig-test` loads an agent file and lets you inspect its SWML, list its SWAIG functions, and call one, without a phone call or a deployment.
|
|
4
4
|
|
|
5
|
+
To test a whole call flow, such as a confirmation across steps, rather than one tool call, use `CallSimulator`; see [Conversation Patterns](conversation_patterns.md#testing-a-call-flow).
|
|
6
|
+
|
|
5
7
|
---
|
|
6
8
|
|
|
7
9
|
## Table of Contents
|