@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.
Files changed (96) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -0
  3. package/dist/AgentBase.d.ts +120 -3
  4. package/dist/AgentBase.js +291 -18
  5. package/dist/AgentBase.js.map +1 -1
  6. package/dist/AgentServer.d.ts +30 -6
  7. package/dist/AgentServer.js +28 -2
  8. package/dist/AgentServer.js.map +1 -1
  9. package/dist/AiEvents.d.ts +70 -0
  10. package/dist/AiEvents.js +94 -0
  11. package/dist/AiEvents.js.map +1 -0
  12. package/dist/ContextBuilder.d.ts +197 -14
  13. package/dist/ContextBuilder.js +422 -13
  14. package/dist/ContextBuilder.js.map +1 -1
  15. package/dist/FunctionResult.d.ts +129 -0
  16. package/dist/FunctionResult.js +170 -0
  17. package/dist/FunctionResult.js.map +1 -1
  18. package/dist/Logger.d.ts +1 -1
  19. package/dist/PostPrompt.d.ts +19 -0
  20. package/dist/PostPrompt.js +43 -0
  21. package/dist/PostPrompt.js.map +1 -1
  22. package/dist/SWMLService.d.ts +151 -10
  23. package/dist/SWMLService.js +377 -61
  24. package/dist/SWMLService.js.map +1 -1
  25. package/dist/SchemaUtils.js +14 -1
  26. package/dist/SchemaUtils.js.map +1 -1
  27. package/dist/SemanticGate.d.ts +61 -1
  28. package/dist/SemanticGate.js +108 -15
  29. package/dist/SemanticGate.js.map +1 -1
  30. package/dist/SessionManager.d.ts +17 -6
  31. package/dist/SessionManager.js +16 -3
  32. package/dist/SessionManager.js.map +1 -1
  33. package/dist/SwaigFunction.d.ts +86 -9
  34. package/dist/SwaigFunction.js +215 -59
  35. package/dist/SwaigFunction.js.map +1 -1
  36. package/dist/ToolMiddleware.d.ts +82 -0
  37. package/dist/ToolMiddleware.js +131 -0
  38. package/dist/ToolMiddleware.js.map +1 -0
  39. package/dist/TypeInference.d.ts +2 -2
  40. package/dist/TypeInference.js +1 -1
  41. package/dist/TypeInference.js.map +1 -1
  42. package/dist/ai-chat/ChatGateway.d.ts +5 -5
  43. package/dist/ai-chat/HandoffRouter.d.ts +3 -3
  44. package/dist/cli/tsdocs/api-index.json +1 -1
  45. package/dist/cli/tsdocs/topics.js +24 -4
  46. package/dist/cli/tsdocs/topics.js.map +1 -1
  47. package/dist/index.d.ts +23 -8
  48. package/dist/index.js +16 -5
  49. package/dist/index.js.map +1 -1
  50. package/dist/livewire/index.d.ts +3 -0
  51. package/dist/livewire/index.js +3 -0
  52. package/dist/livewire/index.js.map +1 -1
  53. package/dist/llms.txt +1 -0
  54. package/dist/patterns/Proposal.d.ts +146 -0
  55. package/dist/patterns/Proposal.js +212 -0
  56. package/dist/patterns/Proposal.js.map +1 -0
  57. package/dist/patterns/RequestList.d.ts +136 -0
  58. package/dist/patterns/RequestList.js +169 -0
  59. package/dist/patterns/RequestList.js.map +1 -0
  60. package/dist/relay/Call.d.ts +1 -1
  61. package/dist/relay/Call.js +1 -1
  62. package/dist/relay/Message.d.ts +1 -1
  63. package/dist/relay/Message.js +1 -1
  64. package/dist/relay/RelayClient.d.ts +0 -2
  65. package/dist/relay/RelayClient.js.map +1 -1
  66. package/dist/relay/RelayEvent.d.ts +3 -3
  67. package/dist/relay/RelayEvent.js +3 -3
  68. package/dist/relay/closedSets.d.ts +10 -10
  69. package/dist/relay/closedSets.js +2 -2
  70. package/dist/relay/types.d.ts +1 -1
  71. package/dist/rest/base/CrudResource.d.ts +1 -1
  72. package/dist/rest/base/CrudResource.js +1 -1
  73. package/dist/skills/SkillBase.d.ts +26 -3
  74. package/dist/skills/SkillBase.js +14 -3
  75. package/dist/skills/SkillBase.js.map +1 -1
  76. package/dist/speech/numbers.d.ts +66 -0
  77. package/dist/speech/numbers.js +281 -0
  78. package/dist/speech/numbers.js.map +1 -0
  79. package/dist/speech/spelling.d.ts +71 -0
  80. package/dist/speech/spelling.js +294 -0
  81. package/dist/speech/spelling.js.map +1 -0
  82. package/dist/testing/CallSimulator.d.ts +281 -0
  83. package/dist/testing/CallSimulator.js +666 -0
  84. package/dist/testing/CallSimulator.js.map +1 -0
  85. package/docs/agent-guide.md +4 -4
  86. package/docs/api-reference.md +285 -28
  87. package/docs/architecture.md +8 -4
  88. package/docs/cli-guide.md +2 -0
  89. package/docs/contexts-guide.md +47 -4
  90. package/docs/conversation_patterns.md +257 -0
  91. package/docs/mcp_integration.md +1 -1
  92. package/docs/pgi_agent_guide.md +2 -1
  93. package/docs/programmatically_governed_inference.md +2 -2
  94. package/docs/swaig-reference.md +95 -3
  95. package/docs/swml_service_guide.md +31 -6
  96. package/package.json +3 -1
@@ -0,0 +1,212 @@
1
+ /**
2
+ * A change the caller says yes to before a tool carries it out.
3
+ *
4
+ * This is the platform's confirm pattern. A function proposes the change: it
5
+ * reads it back and records it in `semantic_state`, in one action object, so
6
+ * the proposal's dialogue starts with the read-back. The confirm tool's
7
+ * semantic gates, judged on that dialogue (`dialogue: 'proposal'`), check three
8
+ * things: that the caller's latest turn is an answer, that the answer is a yes,
9
+ * and that what they answered was a read-back of this change. The gates'
10
+ * questions are the platform's, as replayed against logged calls.
11
+ */
12
+ import { FunctionResult } from '../FunctionResult.js';
13
+ import { SemanticGate } from '../SemanticGate.js';
14
+ /** Where the proposal is recorded in `semantic_state`. */
15
+ export const PROPOSAL_KEY = 'proposal';
16
+ /**
17
+ * A read-back the caller confirms before `confirmTool` runs.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { AgentBase, Proposal } from '@signalwire/sdk';
22
+ *
23
+ * const agent = new AgentBase({ name: 'shop' });
24
+ * const order = new Proposal('place_order', { declineTool: 'change_order' });
25
+ *
26
+ * agent.defineTool({
27
+ * name: 'review_order',
28
+ * description: 'Read the order back',
29
+ * parameters: {
30
+ * type: 'object',
31
+ * properties: { item: { type: 'string' }, time: { type: 'string' } },
32
+ * required: ['item', 'time'],
33
+ * },
34
+ * handler: (args, rawData) =>
35
+ * order.propose(`That's ${args.item} for pickup at ${args.time}. Is that right?`, {
36
+ * rawData,
37
+ * details: { item: args.item },
38
+ * }),
39
+ * });
40
+ * agent.defineTool({
41
+ * name: 'place_order',
42
+ * description: 'Place the order the caller said yes to',
43
+ * handler: () => order.complete('The order is placed.'),
44
+ * gates: order.confirmGates(),
45
+ * });
46
+ * ```
47
+ */
48
+ export class Proposal {
49
+ /** The tool that carries out the change. */
50
+ confirmTool;
51
+ /** The tool the caller's no or change goes to. */
52
+ declineTool;
53
+ /** Each gate's threshold. */
54
+ threshold;
55
+ /** Whether the gates may answer unclear. */
56
+ unclear;
57
+ /**
58
+ * @param confirmTool - The tool that carries out the change.
59
+ * @param opts - `declineTool`, `threshold` and `unclear`.
60
+ */
61
+ constructor(confirmTool, opts = {}) {
62
+ this.confirmTool = confirmTool;
63
+ this.declineTool = opts.declineTool;
64
+ this.threshold = opts.threshold ?? 0.8;
65
+ this.unclear = opts.unclear ?? false;
66
+ }
67
+ /**
68
+ * The result of the function that proposes the change.
69
+ *
70
+ * The agent says `readBack` word for word, and the proposal is recorded as
71
+ * `semantic_state` `{ proposal: readBack, revision: n, ...details }`, in the
72
+ * same action object, so the gates' proposal dialogue starts with the
73
+ * read-back. The model then waits for the caller's answer (`wait_for_user`).
74
+ *
75
+ * @param readBack - The words to read back, ending with the question, such as
76
+ * "That's a large tea for pickup at five. Is that right?". Name everything
77
+ * the change covers, the way the caller would say it.
78
+ * @param opts - `rawData`, `details` and `result`.
79
+ * @returns The result.
80
+ */
81
+ propose(readBack, opts = {}) {
82
+ const state = {
83
+ ...(opts.details ?? {}),
84
+ [PROPOSAL_KEY]: readBack,
85
+ revision: revisionOf(opts.rawData) + 1,
86
+ };
87
+ const result = opts.result ?? new FunctionResult();
88
+ result.setToolResponse(`Read back to the caller: ${readBack}`, `Wait for the caller's answer. Call ${this.confirmTool} only when ` +
89
+ 'they say yes to this read-back.' +
90
+ (this.declineTool ? ` If they say no or want a change, call ${this.declineTool}.` : ''));
91
+ // One object: its say runs before its set_global_data, so the read-back
92
+ // is the first turn of the proposal it records
93
+ result.addAction('say', readBack);
94
+ result.action[result.action.length - 1]['set_global_data'] = { semantic_state: state };
95
+ result.waitForUser({ enabled: true });
96
+ return result;
97
+ }
98
+ /**
99
+ * Read the current proposal back again, as a new revision, so the gates'
100
+ * proposal dialogue starts over with it.
101
+ *
102
+ * @param rawData - The request of the call asking again, which carries the
103
+ * proposal in its `global_data`.
104
+ * @param result - A result to add to.
105
+ * @returns The result.
106
+ * @throws Error when the request carries no proposal.
107
+ */
108
+ askAgain(rawData, result) {
109
+ const state = current(rawData);
110
+ if (state === null) {
111
+ throw new Error('there is no proposal in semantic_state to ask about again');
112
+ }
113
+ const details = Object.fromEntries(Object.entries(state).filter(([k]) => k !== PROPOSAL_KEY && k !== 'revision'));
114
+ return this.propose(String(state[PROPOSAL_KEY]), { rawData, details, result });
115
+ }
116
+ /**
117
+ * The confirm tool's gates: the caller answered, the answer is a yes, and it
118
+ * was a yes to a read-back of this change. Each is judged on the proposal's
119
+ * dialogue. When one fails, the model is told why, with the proposal quoted
120
+ * from `semantic_state` (the platform expands `${global_data...}` in a gate's
121
+ * output; one that doesn't sends it as written), and chaining is turned off
122
+ * for the call (`backToBackFunctions(false)`), so the model answers in words
123
+ * before it calls a tool again.
124
+ *
125
+ * @returns The gates, for the confirm tool's `gates`.
126
+ */
127
+ confirmGates() {
128
+ const tool = this.confirmTool;
129
+ const quoted = '${global_data.semantic_state.proposal}';
130
+ const decline = this.declineTool
131
+ ? `, or call ${this.declineTool} if they no longer want it`
132
+ : '';
133
+ const blocked = (why, then) => new FunctionResult(undefined, false, `${tool} was not run. ${why}`, then).backToBackFunctions(false);
134
+ const gate = { dialogue: 'proposal' };
135
+ if (this.unclear) {
136
+ gate.unclear = true;
137
+ gate.onUnclear = blocked("The caller's answer didn't settle it.", `Read the change back as it stands, "${quoted}", and ask for a plain yes or no.`);
138
+ }
139
+ return [
140
+ new SemanticGate("Is the caller's latest turn in `conversation` an answer, rather than " +
141
+ 'only a sound that shows they are listening, made while the agent was ' +
142
+ 'still talking? A caller turn began while the agent was still talking ' +
143
+ 'if it is marked `while_agent_talking`, or if the agent turn just ' +
144
+ 'before it is marked `interrupted`, which means the caller cut it off. ' +
145
+ 'Any other caller turn began after the agent had finished.', this.threshold, blocked('The caller was only showing they were listening.', 'Finish reading the change back and ask for a plain yes or no.'), {
146
+ ...gate,
147
+ id: 'answered',
148
+ trueMeans: 'Their latest turn answers, with a yes, a no, or more than a sound ' +
149
+ 'that shows they are listening, or it began after the agent had ' +
150
+ 'finished.',
151
+ falseMeans: 'Their latest turn is only a sound that shows they are listening, ' +
152
+ 'and it began while the agent was still talking.',
153
+ }),
154
+ new SemanticGate("Is the caller's latest answer in `conversation` to the agent's request " +
155
+ 'to confirm a yes to the change described in `semantic_state`? The ' +
156
+ 'read-back may be cut off by their answer: a yes once they have heard ' +
157
+ 'what the change is counts. A yes that comes with another request still ' +
158
+ 'counts as a yes to this change.', this.threshold, blocked('The caller has not said yes to this change.', `Read it back, "${quoted}", and ask for a plain yes or no${decline}.`), {
159
+ ...gate,
160
+ id: 'agreed',
161
+ trueMeans: 'Their latest answer says yes to this change, even with another ' +
162
+ 'request or a cut-off read-back.',
163
+ falseMeans: 'Their latest answer says no, hesitates, or only asks a question or ' +
164
+ 'for something else.',
165
+ }),
166
+ new SemanticGate("Did the agent read back the change in `semantic_state` before the caller's " +
167
+ 'latest answer in `conversation`?', this.threshold, blocked('What the caller answered was not a read-back of this change.', `Read the proposal back as it stands, "${quoted}", and only it, then ` +
168
+ `ask for a yes or no${decline}.`), {
169
+ ...gate,
170
+ id: 'read_back',
171
+ trueMeans: "The agent's read-back, even if cut off by the answer, described this change.",
172
+ falseMeans: 'The read-back described a different change, or none was given.',
173
+ }),
174
+ ];
175
+ }
176
+ /**
177
+ * Record that the change was carried out, in place of the proposal.
178
+ *
179
+ * Write what was done rather than clearing the state with `{}`: a state that
180
+ * changes starts the next proposal dialogue there, and the model and the
181
+ * gates see what's settled.
182
+ *
183
+ * @param summary - What was done, such as "Order 4471 is placed".
184
+ * @param result - The confirm tool's result, to add to.
185
+ * @returns The result.
186
+ */
187
+ complete(summary, result) {
188
+ return (result ?? new FunctionResult(undefined, false, summary)).setSemanticState({
189
+ done: summary,
190
+ });
191
+ }
192
+ }
193
+ /**
194
+ * The proposal a request's `global_data.semantic_state` holds, or null.
195
+ * @param rawData - The SWAIG request.
196
+ * @returns The state, as the request carries it.
197
+ */
198
+ export function current(rawData) {
199
+ if (!isRecord(rawData))
200
+ return null;
201
+ const globalData = rawData['global_data'];
202
+ const state = isRecord(globalData) ? globalData['semantic_state'] : undefined;
203
+ return isRecord(state) && PROPOSAL_KEY in state ? state : null;
204
+ }
205
+ function revisionOf(rawData) {
206
+ const revision = current(rawData)?.['revision'];
207
+ return typeof revision === 'number' && Number.isInteger(revision) ? revision : 0;
208
+ }
209
+ function isRecord(value) {
210
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
211
+ }
212
+ //# sourceMappingURL=Proposal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Proposal.js","sourceRoot":"","sources":["../../src/patterns/Proposal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,YAAY,EAA4B,MAAM,oBAAoB,CAAC;AAE5E,0DAA0D;AAC1D,MAAM,CAAC,MAAM,YAAY,GAAG,UAAU,CAAC;AAgCvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,OAAO,QAAQ;IACnB,4CAA4C;IAC5C,WAAW,CAAS;IACpB,kDAAkD;IAClD,WAAW,CAAU;IACrB,6BAA6B;IAC7B,SAAS,CAAS;IAClB,4CAA4C;IAC5C,OAAO,CAAU;IAEjB;;;OAGG;IACH,YAAY,WAAmB,EAAE,OAAwB,EAAE;QACzD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,WAAW,GA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Aa,CAAC,CAAC;IAC1C,MAAM,KAAK,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC9E,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,YAAY,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACjE,CAAC;AAED,SAAS,UAAU,CAAC,OAAmD;IACrE,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC;IAChD,OAAO,OAAO,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC"}
@@ -0,0 +1,136 @@
1
+ /**
2
+ * What the caller asked for while the agent was busy with something else.
3
+ *
4
+ * A caller in the middle of one task often asks for another: "and can you also
5
+ * check my balance?" Taking it up at once loses the first task; ignoring it
6
+ * loses the second. A tool notes the request, and the agent tells the caller
7
+ * it's noted for right after this. When the first task is done, the step's
8
+ * text, which shows the list, has the agent take up the next one.
9
+ *
10
+ * The list lives in the call's `global_data`, so it lasts for the call and a
11
+ * step's text can show it, as `${global_data.<key>_text}`.
12
+ */
13
+ import { FunctionResult } from '../FunctionResult.js';
14
+ /** One request the caller made. */
15
+ export interface NotedRequest {
16
+ /** The kind of request, one of the app's (it picks the opener). */
17
+ kind: string;
18
+ /** What it's about, in a few words. */
19
+ about: string;
20
+ }
21
+ /** Options for a {@link RequestList}. */
22
+ export interface RequestListOptions {
23
+ /**
24
+ * How the agent opens each kind of request when it takes it up, keyed by
25
+ * kind, with `{about}` for what it's about. A kind without one opens with
26
+ * what it's about.
27
+ */
28
+ openers?: Record<string, string>;
29
+ /** The first line of the list's text. Default "Noted for right after this:". */
30
+ heading?: string;
31
+ }
32
+ /**
33
+ * The caller's requests to come back to, in the order they asked.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * import { AgentBase, RequestList } from '@signalwire/sdk';
38
+ *
39
+ * const agent = new AgentBase({ name: 'bank' });
40
+ * const later = new RequestList('later', {
41
+ * openers: {
42
+ * balance: 'You also asked about your balance.',
43
+ * question: 'You had a question: {about}.',
44
+ * },
45
+ * });
46
+ *
47
+ * agent.setGlobalData(later.defaults());
48
+ * agent.defineTool({
49
+ * name: 'note_request',
50
+ * description: 'Note a request to come back to',
51
+ * parameters: {
52
+ * type: 'object',
53
+ * properties: { kind: { type: 'string' }, about: { type: 'string' } },
54
+ * required: ['kind', 'about'],
55
+ * },
56
+ * handler: (args, rawData) => later.note(rawData, String(args.kind), String(args.about)),
57
+ * });
58
+ * const ctx = agent.defineContexts().addContext('default');
59
+ * ctx.addStep('take_order').setText("Take the caller's order.\n\n${global_data.later_text}");
60
+ * ```
61
+ *
62
+ * A step's text is expanded when the step is entered, so the list it shows is
63
+ * the one from then; the model hears of each new request in the tool result.
64
+ * Return `refreshStep()` with the note to show it at once.
65
+ */
66
+ export declare class RequestList {
67
+ /** The `global_data` key the list is kept under. */
68
+ globalKey: string;
69
+ /** The `global_data` key its text for step text is kept under: `<globalKey>_text`. */
70
+ textKey: string;
71
+ /** How the agent opens each kind of request. */
72
+ openers: Record<string, string>;
73
+ /** The first line of the list's text. */
74
+ heading: string;
75
+ /**
76
+ * @param globalKey - The `global_data` key the list is kept under. Its text
77
+ * for step text is kept under `<globalKey>_text`.
78
+ * @param opts - `openers` and `heading`.
79
+ */
80
+ constructor(globalKey: string, opts?: RequestListOptions);
81
+ /**
82
+ * The `global_data` to start a call with, an empty list, so step text that
83
+ * shows it has a value before anything is noted.
84
+ * @returns The global data.
85
+ */
86
+ defaults(): Record<string, unknown>;
87
+ /**
88
+ * The requests a call has noted, oldest first, from its request's `global_data`.
89
+ * @param rawData - The call's request.
90
+ * @returns The requests.
91
+ */
92
+ pending(rawData: Record<string, unknown> | null | undefined): NotedRequest[];
93
+ /**
94
+ * Note a request to come back to, and tell the model so.
95
+ *
96
+ * The model gets "Noted for right after this: <about>.", with a tool prompt to
97
+ * tell the caller and carry on with what it was doing. The same request noted
98
+ * twice is kept once.
99
+ *
100
+ * @param rawData - The noting call's request.
101
+ * @param kind - The kind of request, one of the app's (it picks the opener).
102
+ * @param about - What it's about, in a few words.
103
+ * @param result - A result to add to.
104
+ * @returns The result.
105
+ */
106
+ note(rawData: Record<string, unknown> | null | undefined, kind: string, about: string, result?: FunctionResult): FunctionResult;
107
+ /**
108
+ * The oldest request not yet taken up, with its `opener`, or null.
109
+ * @param rawData - The call's request.
110
+ * @returns The request.
111
+ */
112
+ next(rawData: Record<string, unknown> | null | undefined): (NotedRequest & {
113
+ opener: string;
114
+ }) | null;
115
+ /**
116
+ * Remove the oldest request, once it has been taken up.
117
+ * @param rawData - The call's request.
118
+ * @param result - A result to add to.
119
+ * @returns The result.
120
+ */
121
+ done(rawData: Record<string, unknown> | null | undefined, result?: FunctionResult): FunctionResult;
122
+ /**
123
+ * How the agent opens a request when it takes it up.
124
+ * @param request - The request.
125
+ * @returns The opener.
126
+ */
127
+ opener(request: Partial<NotedRequest>): string;
128
+ /**
129
+ * The list as step text: the heading and one numbered line a request, or ""
130
+ * when there are none.
131
+ * @param requests - The requests.
132
+ * @returns The text.
133
+ */
134
+ asText(requests: readonly NotedRequest[]): string;
135
+ private store;
136
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * What the caller asked for while the agent was busy with something else.
3
+ *
4
+ * A caller in the middle of one task often asks for another: "and can you also
5
+ * check my balance?" Taking it up at once loses the first task; ignoring it
6
+ * loses the second. A tool notes the request, and the agent tells the caller
7
+ * it's noted for right after this. When the first task is done, the step's
8
+ * text, which shows the list, has the agent take up the next one.
9
+ *
10
+ * The list lives in the call's `global_data`, so it lasts for the call and a
11
+ * step's text can show it, as `${global_data.<key>_text}`.
12
+ */
13
+ import { FunctionResult } from '../FunctionResult.js';
14
+ /**
15
+ * The caller's requests to come back to, in the order they asked.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { AgentBase, RequestList } from '@signalwire/sdk';
20
+ *
21
+ * const agent = new AgentBase({ name: 'bank' });
22
+ * const later = new RequestList('later', {
23
+ * openers: {
24
+ * balance: 'You also asked about your balance.',
25
+ * question: 'You had a question: {about}.',
26
+ * },
27
+ * });
28
+ *
29
+ * agent.setGlobalData(later.defaults());
30
+ * agent.defineTool({
31
+ * name: 'note_request',
32
+ * description: 'Note a request to come back to',
33
+ * parameters: {
34
+ * type: 'object',
35
+ * properties: { kind: { type: 'string' }, about: { type: 'string' } },
36
+ * required: ['kind', 'about'],
37
+ * },
38
+ * handler: (args, rawData) => later.note(rawData, String(args.kind), String(args.about)),
39
+ * });
40
+ * const ctx = agent.defineContexts().addContext('default');
41
+ * ctx.addStep('take_order').setText("Take the caller's order.\n\n${global_data.later_text}");
42
+ * ```
43
+ *
44
+ * A step's text is expanded when the step is entered, so the list it shows is
45
+ * the one from then; the model hears of each new request in the tool result.
46
+ * Return `refreshStep()` with the note to show it at once.
47
+ */
48
+ export class RequestList {
49
+ /** The `global_data` key the list is kept under. */
50
+ globalKey;
51
+ /** The `global_data` key its text for step text is kept under: `<globalKey>_text`. */
52
+ textKey;
53
+ /** How the agent opens each kind of request. */
54
+ openers;
55
+ /** The first line of the list's text. */
56
+ heading;
57
+ /**
58
+ * @param globalKey - The `global_data` key the list is kept under. Its text
59
+ * for step text is kept under `<globalKey>_text`.
60
+ * @param opts - `openers` and `heading`.
61
+ */
62
+ constructor(globalKey, opts = {}) {
63
+ this.globalKey = globalKey;
64
+ this.textKey = `${globalKey}_text`;
65
+ this.openers = { ...(opts.openers ?? {}) };
66
+ this.heading = opts.heading ?? 'Noted for right after this:';
67
+ }
68
+ /**
69
+ * The `global_data` to start a call with, an empty list, so step text that
70
+ * shows it has a value before anything is noted.
71
+ * @returns The global data.
72
+ */
73
+ defaults() {
74
+ return { [this.globalKey]: [], [this.textKey]: '' };
75
+ }
76
+ /**
77
+ * The requests a call has noted, oldest first, from its request's `global_data`.
78
+ * @param rawData - The call's request.
79
+ * @returns The requests.
80
+ */
81
+ pending(rawData) {
82
+ if (!isRecord(rawData))
83
+ return [];
84
+ const globalData = rawData['global_data'];
85
+ const stored = isRecord(globalData) ? globalData[this.globalKey] : undefined;
86
+ if (!Array.isArray(stored))
87
+ return [];
88
+ return stored.filter(isRecord).map((r) => ({
89
+ kind: String(r['kind'] ?? ''),
90
+ about: String(r['about'] ?? ''),
91
+ }));
92
+ }
93
+ /**
94
+ * Note a request to come back to, and tell the model so.
95
+ *
96
+ * The model gets "Noted for right after this: <about>.", with a tool prompt to
97
+ * tell the caller and carry on with what it was doing. The same request noted
98
+ * twice is kept once.
99
+ *
100
+ * @param rawData - The noting call's request.
101
+ * @param kind - The kind of request, one of the app's (it picks the opener).
102
+ * @param about - What it's about, in a few words.
103
+ * @param result - A result to add to.
104
+ * @returns The result.
105
+ */
106
+ note(rawData, kind, about, result) {
107
+ const requests = this.pending(rawData);
108
+ if (!requests.some((r) => r.kind === kind && r.about === about)) {
109
+ requests.push({ kind, about });
110
+ }
111
+ const out = (result ?? new FunctionResult()).setToolResponse(`Noted for right after this: ${about}.`, "Tell the caller you've noted it for right after this, and carry on " +
112
+ 'with what you were doing.');
113
+ return this.store(out, requests);
114
+ }
115
+ /**
116
+ * The oldest request not yet taken up, with its `opener`, or null.
117
+ * @param rawData - The call's request.
118
+ * @returns The request.
119
+ */
120
+ next(rawData) {
121
+ const first = this.pending(rawData)[0];
122
+ return first ? { ...first, opener: this.opener(first) } : null;
123
+ }
124
+ /**
125
+ * Remove the oldest request, once it has been taken up.
126
+ * @param rawData - The call's request.
127
+ * @param result - A result to add to.
128
+ * @returns The result.
129
+ */
130
+ done(rawData, result) {
131
+ return this.store(result ?? new FunctionResult(), this.pending(rawData).slice(1));
132
+ }
133
+ /**
134
+ * How the agent opens a request when it takes it up.
135
+ * @param request - The request.
136
+ * @returns The opener.
137
+ */
138
+ opener(request) {
139
+ const about = String(request.about ?? '');
140
+ const kind = String(request.kind ?? '');
141
+ const template = Object.hasOwn(this.openers, kind) ? this.openers[kind] : undefined;
142
+ return template ? template.replaceAll('{about}', () => about) : about;
143
+ }
144
+ /**
145
+ * The list as step text: the heading and one numbered line a request, or ""
146
+ * when there are none.
147
+ * @param requests - The requests.
148
+ * @returns The text.
149
+ */
150
+ asText(requests) {
151
+ if (requests.length === 0)
152
+ return '';
153
+ return [
154
+ this.heading,
155
+ ...requests.map((r, n) => `${n + 1}. ${this.opener(r)}`),
156
+ "When the current task is done, take these up in order, then ask if there's anything else.",
157
+ ].join('\n');
158
+ }
159
+ store(result, requests) {
160
+ return result.updateGlobalData({
161
+ [this.globalKey]: requests,
162
+ [this.textKey]: this.asText(requests),
163
+ });
164
+ }
165
+ }
166
+ function isRecord(value) {
167
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
168
+ }
169
+ //# sourceMappingURL=RequestList.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RequestList.js","sourceRoot":"","sources":["../../src/patterns/RequestList.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAsBtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,OAAO,WAAW;IACtB,oDAAoD;IACpD,SAAS,CAAS;IAClB,sFAAsF;IACtF,OAAO,CAAS;IAChB,gDAAgD;IAChD,OAAO,CAAyB;IAChC,yCAAyC;IACzC,OAAO,CAAS;IAEhB;;;;OAIG;IACH,YAAY,SAAiB,EAAE,OAA2B,EAAE;QAC1D,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CA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O,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACpF,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IACxE,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,QAAiC;QACtC,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,CAAC;QACrC,OAAO;YACL,IAAI,CAAC,OAAO;YACZ,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;YACxD,2FAA2F;SAC5F,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACf,CAAC;IAEO,KAAK,CAAC,MAAsB,EAAE,QAAwB;QAC5D,OAAO,MAAM,CAAC,gBAAgB,CAAC;YAC7B,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,QAAQ;YAC1B,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC;SACtC,CAAC,CAAC;IACL,CAAC;CACF;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC"}
@@ -82,7 +82,7 @@ export declare class Call {
82
82
  *
83
83
  * Idiomatic shortcut for `isCallStateTerminal(call.state)` — prefer it over
84
84
  * a hand-written `call.state === 'ended'` comparison so the terminal-set
85
- * definition lives in one place ({@link ../relay/closedSets.CallState}).
85
+ * definition lives in one place ({@link CallState}).
86
86
  */
87
87
  get isTerminal(): boolean;
88
88
  /**
@@ -87,7 +87,7 @@ export class Call {
87
87
  *
88
88
  * Idiomatic shortcut for `isCallStateTerminal(call.state)` — prefer it over
89
89
  * a hand-written `call.state === 'ended'` comparison so the terminal-set
90
- * definition lives in one place ({@link ../relay/closedSets.CallState}).
90
+ * definition lives in one place ({@link CallState}).
91
91
  */
92
92
  get isTerminal() {
93
93
  return isCallStateTerminal(this.state);
@@ -84,7 +84,7 @@ export declare class Message {
84
84
  * Distinct from {@link Message.isDone}: `isDone` reflects whether the
85
85
  * internal completion promise has settled (driven by event dispatch),
86
86
  * whereas `isTerminal` is a pure test of the state *value*
87
- * ({@link ../relay/closedSets.MessageState}) and is meaningful even on a
87
+ * ({@link MessageState}) and is meaningful even on a
88
88
  * freshly-constructed inbound message.
89
89
  */
90
90
  get isTerminal(): boolean;
@@ -91,7 +91,7 @@ export class Message {
91
91
  * Distinct from {@link Message.isDone}: `isDone` reflects whether the
92
92
  * internal completion promise has settled (driven by event dispatch),
93
93
  * whereas `isTerminal` is a pure test of the state *value*
94
- * ({@link ../relay/closedSets.MessageState}) and is meaningful even on a
94
+ * ({@link MessageState}) and is meaningful even on a
95
95
  * freshly-constructed inbound message.
96
96
  */
97
97
  get isTerminal() {
@@ -277,9 +277,7 @@ export declare class RelayClient {
277
277
  */
278
278
  dial(devices: Record<string, unknown>[][], options?: {
279
279
  tag?: string;
280
- /** Maximum call duration in minutes. */
281
280
  maxDuration?: number;
282
- /** Dial timeout in seconds (default 120). */
283
281
  dialTimeout?: number;
284
282
  }): Promise<Call>;
285
283
  /**