@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.
Files changed (67) hide show
  1. package/CHANGELOG.md +201 -0
  2. package/README.md +1 -0
  3. package/dist/AgentBase.d.ts +107 -2
  4. package/dist/AgentBase.js +259 -13
  5. package/dist/AgentBase.js.map +1 -1
  6. package/dist/AiEvents.d.ts +70 -0
  7. package/dist/AiEvents.js +94 -0
  8. package/dist/AiEvents.js.map +1 -0
  9. package/dist/ContextBuilder.d.ts +215 -14
  10. package/dist/ContextBuilder.js +441 -14
  11. package/dist/ContextBuilder.js.map +1 -1
  12. package/dist/FunctionResult.d.ts +146 -1
  13. package/dist/FunctionResult.js +188 -2
  14. package/dist/FunctionResult.js.map +1 -1
  15. package/dist/PostPrompt.d.ts +19 -0
  16. package/dist/PostPrompt.js +43 -0
  17. package/dist/PostPrompt.js.map +1 -1
  18. package/dist/SWMLService.d.ts +97 -1
  19. package/dist/SWMLService.js +129 -2
  20. package/dist/SWMLService.js.map +1 -1
  21. package/dist/SemanticGate.d.ts +61 -1
  22. package/dist/SemanticGate.js +108 -15
  23. package/dist/SemanticGate.js.map +1 -1
  24. package/dist/SwaigFunction.d.ts +85 -9
  25. package/dist/SwaigFunction.js +214 -58
  26. package/dist/SwaigFunction.js.map +1 -1
  27. package/dist/ToolMiddleware.d.ts +82 -0
  28. package/dist/ToolMiddleware.js +131 -0
  29. package/dist/ToolMiddleware.js.map +1 -0
  30. package/dist/TypeInference.d.ts +1 -1
  31. package/dist/TypeInference.js.map +1 -1
  32. package/dist/cli/tsdocs/api-index.json +1 -1
  33. package/dist/cli/tsdocs/topics.js +24 -4
  34. package/dist/cli/tsdocs/topics.js.map +1 -1
  35. package/dist/index.d.ts +22 -8
  36. package/dist/index.js +15 -5
  37. package/dist/index.js.map +1 -1
  38. package/dist/llms.txt +1 -0
  39. package/dist/patterns/Proposal.d.ts +148 -0
  40. package/dist/patterns/Proposal.js +214 -0
  41. package/dist/patterns/Proposal.js.map +1 -0
  42. package/dist/patterns/RequestList.d.ts +138 -0
  43. package/dist/patterns/RequestList.js +171 -0
  44. package/dist/patterns/RequestList.js.map +1 -0
  45. package/dist/skills/SkillBase.d.ts +24 -1
  46. package/dist/skills/SkillBase.js +12 -1
  47. package/dist/skills/SkillBase.js.map +1 -1
  48. package/dist/speech/numbers.d.ts +66 -0
  49. package/dist/speech/numbers.js +281 -0
  50. package/dist/speech/numbers.js.map +1 -0
  51. package/dist/speech/spelling.d.ts +71 -0
  52. package/dist/speech/spelling.js +294 -0
  53. package/dist/speech/spelling.js.map +1 -0
  54. package/dist/testing/CallSimulator.d.ts +391 -0
  55. package/dist/testing/CallSimulator.js +966 -0
  56. package/dist/testing/CallSimulator.js.map +1 -0
  57. package/docs/agent-guide.md +2 -2
  58. package/docs/api-reference.md +279 -22
  59. package/docs/architecture.md +8 -4
  60. package/docs/cli-guide.md +2 -0
  61. package/docs/contexts-guide.md +75 -4
  62. package/docs/conversation_patterns.md +257 -0
  63. package/docs/mcp_integration.md +1 -1
  64. package/docs/pgi_agent_guide.md +5 -0
  65. package/docs/programmatically_governed_inference.md +2 -2
  66. package/docs/swaig-reference.md +98 -6
  67. package/package.json +1 -1
@@ -4,8 +4,60 @@
4
4
  * Contexts contain ordered Steps, each with prompt text/POM sections,
5
5
  * completion criteria, function restrictions, and navigation rules.
6
6
  */
7
+ import { getLogger } from './Logger.js';
8
+ import { RESERVED_FUNCTION_NAMES } from './SemanticGate.js';
7
9
  const MAX_CONTEXTS = 50;
8
10
  const MAX_STEPS_PER_CONTEXT = 100;
11
+ const log = getLogger('contexts');
12
+ /** The most digits an expected answer can name. */
13
+ export const MAX_EXPECTED_DIGITS = 64;
14
+ /**
15
+ * An `expected_answer` as the platform reads it: `{ digits: N }`, or
16
+ * `{ min_digits: a, max_digits: b }` with a at most b, each count from 1 to
17
+ * 64. The platform logs and ignores any other shape.
18
+ * @param digits - The exact number of digits.
19
+ * @param opts - Or, without `digits`, the fewest and most digits.
20
+ * @returns The expected answer.
21
+ * @throws {Error} For a shape or count the platform would ignore.
22
+ */
23
+ export function expectedAnswer(digits, opts = {}) {
24
+ const count = (name, value) => {
25
+ if (!Number.isInteger(value) ||
26
+ value < 1 ||
27
+ value > MAX_EXPECTED_DIGITS) {
28
+ throw new Error(`${name} must be a whole number from 1 to ${MAX_EXPECTED_DIGITS}, got ${JSON.stringify(value)}`);
29
+ }
30
+ return value;
31
+ };
32
+ const { minDigits, maxDigits } = opts;
33
+ if (digits !== undefined && digits !== null) {
34
+ if (minDigits !== undefined || maxDigits !== undefined) {
35
+ throw new Error('expected_answer takes digits, or min_digits and max_digits, not both');
36
+ }
37
+ return { digits: count('digits', digits) };
38
+ }
39
+ if (minDigits === undefined || maxDigits === undefined) {
40
+ throw new Error('expected_answer needs digits, or both min_digits and max_digits');
41
+ }
42
+ const low = count('min_digits', minDigits);
43
+ const high = count('max_digits', maxDigits);
44
+ if (low > high)
45
+ throw new Error(`min_digits (${low}) must be at most max_digits (${high})`);
46
+ return { min_digits: low, max_digits: high };
47
+ }
48
+ /** A given expected_answer object, checked by the platform's rules. */
49
+ function checkExpectedAnswer(value) {
50
+ const keys = new Set(['digits', 'min_digits', 'max_digits']);
51
+ if (typeof value !== 'object' ||
52
+ value === null ||
53
+ Array.isArray(value) ||
54
+ Object.keys(value).length === 0 ||
55
+ Object.keys(value).some((k) => !keys.has(k))) {
56
+ throw new Error('expected_answer must be {"digits": N} or {"min_digits": a, "max_digits": b}');
57
+ }
58
+ const v = value;
59
+ return expectedAnswer(v['digits'], { minDigits: v['min_digits'], maxDigits: v['max_digits'] });
60
+ }
9
61
  /**
10
62
  * Valid values for a step's or context's `history` visibility mode.
11
63
  *
@@ -19,8 +71,12 @@ const MAX_STEPS_PER_CONTEXT = 100;
19
71
  * - `isolate`: like `hide`, but only while the agent is in this step: the
20
72
  * earlier dialogue returns when the step is left, and the earlier step
21
73
  * instructions stay cleared.
74
+ * - `spoken`: prior instructions hidden, and every earlier tool call, tool
75
+ * result and turn-scoped system note (tool prompts and the like) pulled out
76
+ * for the rest of the call; every spoken turn, the caller's and the
77
+ * agent's, stays.
22
78
  */
23
- export const HISTORY_MODES = ['keep', 'default', 'hide', 'isolate'];
79
+ export const HISTORY_MODES = ['keep', 'default', 'hide', 'isolate', 'spoken'];
24
80
  function validateHistory(mode) {
25
81
  if (!HISTORY_MODES.includes(mode)) {
26
82
  throw new Error(`history must be one of ${JSON.stringify(HISTORY_MODES)}, got ${JSON.stringify(mode)}`);
@@ -68,9 +124,15 @@ export class GatherQuestion {
68
124
  * unset — it is emitted to SWML so it can override an isolated gather.
69
125
  */
70
126
  isolated;
127
+ /**
128
+ * The number of digits the answer has, for the recognizer: while this
129
+ * question is asked, it replaces the step's expected answer.
130
+ */
131
+ expectedAnswer;
71
132
  /**
72
133
  * Creates a new GatherQuestion.
73
- * @param opts - Question configuration including key, question text, and optional type/confirm/prompt/functions/isolated.
134
+ * @param opts - Question configuration including key, question text, and optional type/confirm/prompt/functions/isolated/expectedAnswer.
135
+ * @throws {Error} For an `expectedAnswer` the platform would ignore.
74
136
  */
75
137
  constructor(opts) {
76
138
  this.key = opts.key;
@@ -82,6 +144,9 @@ export class GatherQuestion {
82
144
  // Tri-state: undefined means "inherit the gather_info default". Do NOT
83
145
  // collapse to a boolean — `false` must survive to the wire.
84
146
  this.isolated = opts.isolated;
147
+ if (opts.expectedAnswer !== undefined) {
148
+ this.expectedAnswer = checkExpectedAnswer(opts.expectedAnswer);
149
+ }
85
150
  }
86
151
  /**
87
152
  * Serializes this question to a plain object for SWML output.
@@ -100,6 +165,8 @@ export class GatherQuestion {
100
165
  // Emitted even when false, so it can override an isolated gather.
101
166
  if (this.isolated !== undefined && this.isolated !== null)
102
167
  d['isolated'] = this.isolated;
168
+ if (this.expectedAnswer !== undefined)
169
+ d['expected_answer'] = { ...this.expectedAnswer };
103
170
  return d;
104
171
  }
105
172
  /**
@@ -184,6 +251,8 @@ export class Step {
184
251
  text = null;
185
252
  stepCriteria = null;
186
253
  functions = null;
254
+ /** The recognizer's hint for a number the caller is asked for. */
255
+ _expectedAnswer = null;
187
256
  validSteps = null;
188
257
  validContexts = null;
189
258
  sections = [];
@@ -205,6 +274,13 @@ export class Step {
205
274
  }
206
275
  /**
207
276
  * Sets raw text content for this step, mutually exclusive with POM sections.
277
+ *
278
+ * The platform expands its variables, such as `${global_data.order_total}`,
279
+ * when the step is entered, and current releases expand it again before a
280
+ * request whenever a value it reads has changed. Earlier releases, and a
281
+ * realtime model, keep the values from entry: there, return
282
+ * `FunctionResult.refreshStep(name)` after a later `updateGlobalData()` to
283
+ * enter the step again with the new values.
208
284
  * @param text - The raw prompt text.
209
285
  * @returns This step for chaining.
210
286
  */
@@ -411,6 +487,78 @@ export class Step {
411
487
  getStepValidContexts() {
412
488
  return this.validContexts;
413
489
  }
490
+ /**
491
+ * Tell the recognizer how many digits the caller's answer in this step has,
492
+ * such as a ZIP code or a PIN.
493
+ *
494
+ * The recognizer ends its wait for a number once the caller has said that
495
+ * many digits. A gather question's own expected answer replaces this while
496
+ * that question is asked. Pass `digits` for an exact count, or `minDigits`
497
+ * and `maxDigits` for a range, each from 1 to 64. Sent as `expected_answer`;
498
+ * it needs a platform release that has it.
499
+ * @param digits - The exact number of digits.
500
+ * @param opts - Or, without `digits`, the fewest and most digits.
501
+ * @returns This step for chaining.
502
+ * @throws {Error} For a count or combination the platform would ignore.
503
+ */
504
+ setExpectedAnswer(digits, opts = {}) {
505
+ this._expectedAnswer = expectedAnswer(digits, opts);
506
+ return this;
507
+ }
508
+ /**
509
+ * Whether this step sets its own function list (an array or a string
510
+ * sentinel such as `'none'`), rather than keeping the one before it.
511
+ * @internal
512
+ */
513
+ _hasFunctionList() {
514
+ return this.functions !== null;
515
+ }
516
+ /**
517
+ * The step's own function list: null when it inherits the list before it,
518
+ * empty for `'none'`.
519
+ * @internal
520
+ */
521
+ _offeredFunctions() {
522
+ if (Array.isArray(this.functions))
523
+ return [...this.functions];
524
+ return this.functions === 'none' ? [] : null;
525
+ }
526
+ /**
527
+ * Whether the step has a reset, which makes it terminal.
528
+ * @internal
529
+ */
530
+ _hasReset() {
531
+ return (this.resetSystemPrompt !== null ||
532
+ this.resetUserPrompt !== null ||
533
+ this.resetConsolidate ||
534
+ this.resetFullReset);
535
+ }
536
+ /**
537
+ * What the model reads in this step, as `[where, text, tools also offered
538
+ * there]`: its text, its criteria, and its gather questions.
539
+ * @internal
540
+ */
541
+ _modelTexts() {
542
+ let text = '';
543
+ try {
544
+ text = this.renderText();
545
+ }
546
+ catch {
547
+ // A step without text fails validation on its own
548
+ }
549
+ const texts = [
550
+ ['text', text, []],
551
+ ['criteria', this.stepCriteria ?? '', []],
552
+ ];
553
+ for (const q of this.gatherInfo?.getQuestions() ?? []) {
554
+ texts.push([
555
+ `gather question ${q.key}`,
556
+ `${q.question} ${q.prompt ?? ''}`,
557
+ q.functions ?? [],
558
+ ]);
559
+ }
560
+ return texts;
561
+ }
414
562
  /**
415
563
  * Returns this step's function whitelist as an array of tool NAMES to
416
564
  * validate, or null when there is nothing to validate. A string value
@@ -433,7 +581,11 @@ export class Step {
433
581
  return this;
434
582
  }
435
583
  /**
436
- * Sets the system prompt to use when resetting context at this step.
584
+ * Set the system prompt this step's reset loads.
585
+ *
586
+ * A step with any reset setting is terminal: when the call enters it, the
587
+ * platform runs the reset in place of the step's text, and step mode ends
588
+ * there. Use it for a step that hands the call over to a new prompt.
437
589
  * @param systemPrompt - The replacement system prompt text.
438
590
  * @returns This step for chaining.
439
591
  */
@@ -442,7 +594,11 @@ export class Step {
442
594
  return this;
443
595
  }
444
596
  /**
445
- * Sets the user prompt to use when resetting context at this step.
597
+ * Set the user message this step's reset adds.
598
+ *
599
+ * A step with any reset setting is terminal: when the call enters it, the
600
+ * platform runs the reset in place of the step's text, and step mode ends
601
+ * there. Use it for a step that hands the call over to a new prompt.
446
602
  * @param userPrompt - The replacement user prompt text.
447
603
  * @returns This step for chaining.
448
604
  */
@@ -451,7 +607,11 @@ export class Step {
451
607
  return this;
452
608
  }
453
609
  /**
454
- * Sets whether to consolidate conversation history when resetting at this step.
610
+ * Set whether this step's reset consolidates the conversation into a summary.
611
+ *
612
+ * A step with any reset setting is terminal: when the call enters it, the
613
+ * platform runs the reset in place of the step's text, and step mode ends
614
+ * there. Use it for a step that hands the call over to a new prompt.
455
615
  * @param consolidate - Whether to consolidate.
456
616
  * @returns This step for chaining.
457
617
  */
@@ -460,7 +620,12 @@ export class Step {
460
620
  return this;
461
621
  }
462
622
  /**
463
- * Sets whether to perform a full conversation reset at this step.
623
+ * Set whether this step's reset replaces the system prompt, seeded with the
624
+ * consolidated summary, rather than adding to it.
625
+ *
626
+ * A step with any reset setting is terminal: when the call enters it, the
627
+ * platform runs the reset in place of the step's text, and step mode ends
628
+ * there. Use it for a step that hands the call over to a new prompt.
464
629
  * @param fullReset - Whether to fully reset.
465
630
  * @returns This step for chaining.
466
631
  */
@@ -471,9 +636,16 @@ export class Step {
471
636
  /**
472
637
  * Control what the model still sees when this step is entered.
473
638
  *
474
- * The mode applies at the moment this step is entered and governs
475
- * everything that came before it. It does not affect this step's own
476
- * turns, which accumulate fresh. Nothing is deleted from the call log.
639
+ * The mode applies when the step's instructions are injected, before the
640
+ * next request to the model, and governs everything before it. The exchange
641
+ * that entered the step stays under `"hide"`, `"isolate"` and `"spoken"`, as
642
+ * the step's start: the call whose action changed the step, its result,
643
+ * notes and say. A post_process action's change, which runs after the
644
+ * model's reply, keeps its call and everything stored from it on, the reply
645
+ * included. A change by next_step keeps nothing. Platform releases before
646
+ * this keep nothing under `"hide"` and `"isolate"`. An end step, or one with
647
+ * a reset, takes no history pass. The mode doesn't affect this step's own turns, which
648
+ * accumulate fresh. Nothing is deleted from the call log.
477
649
  *
478
650
  * @param history - One of:
479
651
  * - `"keep"`: clear nothing. Every prior step's instructions and
@@ -491,6 +663,16 @@ export class Step {
491
663
  * hid stays hidden. Entering the step again isolates it again. Use it
492
664
  * for a step that must see nothing else, such as one that reads back a
493
665
  * confirmation. A platform without isolate treats it as `"default"`.
666
+ * - `"spoken"`: keep the conversation, drop the work. Earlier step
667
+ * instructions are cleared, and every earlier tool call, tool result and
668
+ * turn-scoped system note (tool prompts, ai-msg injections, a gather's
669
+ * preamble) leaves the model's context for the rest of the call. Every
670
+ * spoken turn stays: the caller's, the agent's replies and `say`
671
+ * actions. An assistant turn that spoke and called a tool keeps its
672
+ * words. Use it at a stage boundary where the caller's earlier requests
673
+ * must stay but the finished stage's tool results shouldn't. A platform
674
+ * without spoken treats it as `"default"`, which keeps the tool
675
+ * exchanges.
494
676
  * @returns This step for chaining.
495
677
  * @throws {Error} If `history` is not one of these modes.
496
678
  */
@@ -539,6 +721,8 @@ export class Step {
539
721
  d.skip_to_next_step = true;
540
722
  if (this._history !== null)
541
723
  d.history = this._history;
724
+ if (this._expectedAnswer !== null)
725
+ d.expected_answer = { ...this._expectedAnswer };
542
726
  const reset = {};
543
727
  if (this.resetSystemPrompt !== null)
544
728
  reset.system_prompt = this.resetSystemPrompt;
@@ -731,8 +915,9 @@ export class Context {
731
915
  * Mark this context as isolated — entering it wipes conversation history.
732
916
  *
733
917
  * When `isolated=true` and the context is entered via change_context, the
734
- * runtime wipes the conversation array. The model starts fresh with only
735
- * the new context's systemPrompt + step instructions, with no memory of
918
+ * runtime calls ai_conversation_restart(), which drops every conversation
919
+ * entry but the first, the base system prompt. The model starts fresh with
920
+ * the base prompt and the new context's step instructions, with no memory of
736
921
  * prior turns.
737
922
  *
738
923
  * EXCEPTION — `reset` overrides the wipe:
@@ -862,7 +1047,8 @@ export class Context {
862
1047
  * A step's own `setHistory()` overrides this. See {@link Step.setHistory}
863
1048
  * for what each mode does.
864
1049
  *
865
- * @param history - One of `"keep"`, `"default"`, `"hide"`, or `"isolate"`.
1050
+ * @param history - One of `"keep"`, `"default"`, `"hide"`, `"isolate"`, or
1051
+ * `"spoken"`.
866
1052
  * @returns This context for chaining.
867
1053
  * @throws {Error} If `history` is not one of these modes.
868
1054
  */
@@ -900,6 +1086,28 @@ export class Context {
900
1086
  return null;
901
1087
  return this.renderSections(this.systemPromptSections);
902
1088
  }
1089
+ /**
1090
+ * The context's prompt, which goes before every step's text.
1091
+ * @internal
1092
+ */
1093
+ _modelPrompt() {
1094
+ return this.renderPrompt();
1095
+ }
1096
+ /**
1097
+ * The reset settings that do nothing because the context has no system
1098
+ * prompt: the platform runs a context's reset only with one.
1099
+ * @internal
1100
+ */
1101
+ _inertResetSettings() {
1102
+ if (this.renderSystemPrompt() !== null)
1103
+ return [];
1104
+ const settings = [
1105
+ ['consolidate', this._consolidate],
1106
+ ['full_reset', this._fullReset],
1107
+ ['user_prompt', this._userPrompt],
1108
+ ];
1109
+ return settings.filter(([, value]) => value).map(([name]) => name);
1110
+ }
903
1111
  renderSections(sections) {
904
1112
  const parts = [];
905
1113
  for (const s of sections) {
@@ -982,8 +1190,8 @@ export class Context {
982
1190
  * - `next_step(step: enum)` — present when validSteps is set
983
1191
  * - `change_context(context: enum)` — present when validContexts is set
984
1192
  *
985
- * Their `enum` schemas are rewritten on every turn to match whatever
986
- * validSteps / validContexts apply to the current step. You do NOT need
1193
+ * Their `enum` schemas are rewritten when a step loads, to match whatever
1194
+ * validSteps / validContexts apply to that step. You do NOT need
987
1195
  * to define these tools yourself; they appear automatically.
988
1196
  *
989
1197
  * A third native tool — `gather_submit` — is injected during gather_info
@@ -1043,6 +1251,12 @@ export class Context {
1043
1251
  export class ContextBuilder {
1044
1252
  contexts = new Map();
1045
1253
  contextOrder = [];
1254
+ /**
1255
+ * Tools already reported as offered by no step, so a render on every request
1256
+ * doesn't repeat it. The agent shares its own set, so its per-request copies
1257
+ * don't repeat it either.
1258
+ */
1259
+ unofferedWarned = new Set();
1046
1260
  agent = null;
1047
1261
  /**
1048
1262
  * Attach an agent reference so validate() can check user tool names
@@ -1054,6 +1268,15 @@ export class ContextBuilder {
1054
1268
  this.agent = agent;
1055
1269
  return this;
1056
1270
  }
1271
+ /**
1272
+ * Record the tools reported as offered by no step in `warned`, a set the
1273
+ * agent keeps for itself and its per-request copies.
1274
+ * @internal
1275
+ */
1276
+ _shareUnofferedWarnings(warned) {
1277
+ this.unofferedWarned = warned;
1278
+ return this;
1279
+ }
1057
1280
  /**
1058
1281
  * Removes all contexts, returning the builder to its initial state.
1059
1282
  * Use this in a dynamic config callback when you need to rebuild
@@ -1275,6 +1498,148 @@ export class ContextBuilder {
1275
1498
  `Registered tools: [${knownNames.map((n) => `'${n}'`).join(', ')}]. ` +
1276
1499
  `Fix the tool name or register the missing tool.`);
1277
1500
  }
1501
+ const names = registered
1502
+ .map((t) => t?.name)
1503
+ .filter((n) => typeof n === 'string');
1504
+ this.warnUnofferedTools(names);
1505
+ const getFunction = this.agent.getFunction;
1506
+ this.warnToolMentions(names, (name) => typeof getFunction === 'function' ? getFunction.call(this.agent, name) : undefined);
1507
+ }
1508
+ this.warnInertResets();
1509
+ }
1510
+ /**
1511
+ * The steps whose function list offers `functionName`, as
1512
+ * `[context, step]` pairs in order, including a gather question's functions.
1513
+ *
1514
+ * A step without `setFunctions()` keeps whatever was active before it, so it
1515
+ * isn't counted: what it offers depends on the step the call came from. The
1516
+ * platform's reply to a call of a tool the current step doesn't offer names
1517
+ * the same steps.
1518
+ * @param functionName - The function's name.
1519
+ * @returns The `[context name, step name]` pairs, empty when no step lists it.
1520
+ */
1521
+ stepsOffering(functionName) {
1522
+ const found = [];
1523
+ for (const contextName of this.contextOrder) {
1524
+ const ctx = this.contexts.get(contextName);
1525
+ if (!ctx)
1526
+ continue;
1527
+ for (const [stepName, step] of ctx.getSteps()) {
1528
+ if (stepOffers(step, functionName))
1529
+ found.push([contextName, stepName]);
1530
+ }
1531
+ }
1532
+ return found;
1533
+ }
1534
+ /**
1535
+ * Log, once each, reset settings that don't do what they read as: a step
1536
+ * with a reset is terminal, so its text never runs; and a context's
1537
+ * consolidate, full_reset and user_prompt act only with a system prompt,
1538
+ * whose presence runs the context's reset.
1539
+ */
1540
+ warnInertResets() {
1541
+ for (const contextName of this.contextOrder) {
1542
+ const ctx = this.contexts.get(contextName);
1543
+ if (!ctx)
1544
+ continue;
1545
+ const inert = ctx._inertResetSettings();
1546
+ const contextKey = JSON.stringify(['context', contextName]);
1547
+ if (inert.length > 0 && !this.unofferedWarned.has(contextKey)) {
1548
+ this.unofferedWarned.add(contextKey);
1549
+ log.warn('context_reset_without_system_prompt', {
1550
+ context: contextName,
1551
+ settings: inert,
1552
+ hint: "The platform runs a context's reset only when it has a system_prompt, " +
1553
+ 'so these do nothing; add setSystemPrompt().',
1554
+ });
1555
+ }
1556
+ for (const [stepName, step] of ctx.getSteps()) {
1557
+ const key = JSON.stringify(['step', contextName, stepName]);
1558
+ if (this.unofferedWarned.has(key) || !step._hasReset())
1559
+ continue;
1560
+ this.unofferedWarned.add(key);
1561
+ log.warn('step_reset_is_terminal', {
1562
+ context: contextName,
1563
+ step: stepName,
1564
+ hint: 'A step with a reset is terminal: the platform runs the reset in place ' +
1565
+ 'of its text and step mode ends there.',
1566
+ });
1567
+ }
1568
+ }
1569
+ }
1570
+ /**
1571
+ * Log, once each, a registered tool named where the step doesn't offer it:
1572
+ * in its text, its criteria, its context's prompt (which goes before every
1573
+ * step's text), a gather question, or a gate's output on one of its tools.
1574
+ * The model reads the name and may call a tool it doesn't have. A step
1575
+ * without a function list is skipped: what it offers depends on the step
1576
+ * before it.
1577
+ */
1578
+ warnToolMentions(registered, definitionOf) {
1579
+ const tools = registered.filter((name) => !RESERVED_FUNCTION_NAMES.has(name) && !RESERVED_NATIVE_TOOL_NAMES.has(name));
1580
+ if (tools.length === 0)
1581
+ return;
1582
+ for (const contextName of this.contextOrder) {
1583
+ const ctx = this.contexts.get(contextName);
1584
+ if (!ctx)
1585
+ continue;
1586
+ const prompt = ctx._modelPrompt() ?? '';
1587
+ for (const [stepName, step] of ctx.getSteps()) {
1588
+ const list = step._offeredFunctions();
1589
+ if (list === null)
1590
+ continue;
1591
+ const offered = new Set(list);
1592
+ const texts = step._modelTexts();
1593
+ texts.splice(2, 0, ['context prompt', prompt, []]);
1594
+ for (const tool of [...offered].sort()) {
1595
+ for (const [gate, output] of gateTexts(definitionOf(tool))) {
1596
+ texts.push([`${tool} gate ${gate}`, output, []]);
1597
+ }
1598
+ }
1599
+ for (const [where, text, also] of texts) {
1600
+ const named = [...namedTools(text, tools)]
1601
+ .filter((t) => !offered.has(t) && !also.includes(t))
1602
+ .sort();
1603
+ for (const tool of named) {
1604
+ const key = JSON.stringify([contextName, stepName, where, tool]);
1605
+ if (this.unofferedWarned.has(key))
1606
+ continue;
1607
+ this.unofferedWarned.add(key);
1608
+ log.warn('tool_named_but_not_offered', {
1609
+ context: contextName,
1610
+ step: stepName,
1611
+ where,
1612
+ function: tool,
1613
+ hint: "The model reads this name in a step that doesn't offer the tool. " +
1614
+ "Name only the step's own tools; move the work to the step that offers it.",
1615
+ });
1616
+ }
1617
+ }
1618
+ }
1619
+ }
1620
+ }
1621
+ /**
1622
+ * Log, once per tool, a tool no step can offer: when every step lists its
1623
+ * functions and none lists it, the model never gets it, unless a function
1624
+ * result turns it on.
1625
+ */
1626
+ warnUnofferedTools(registered) {
1627
+ const steps = [...this.contexts.values()].flatMap((c) => [...c.getSteps().values()]);
1628
+ if (steps.length === 0 || steps.some((step) => !step._hasFunctionList()))
1629
+ return;
1630
+ for (const name of registered) {
1631
+ if (this.unofferedWarned.has(name) ||
1632
+ RESERVED_FUNCTION_NAMES.has(name) ||
1633
+ RESERVED_NATIVE_TOOL_NAMES.has(name) ||
1634
+ this.stepsOffering(name).length > 0) {
1635
+ continue;
1636
+ }
1637
+ this.unofferedWarned.add(name);
1638
+ log.warn('tool_offered_by_no_step', {
1639
+ function: name,
1640
+ hint: 'Every step lists its functions and none lists this one, so the model never gets it ' +
1641
+ 'unless a function result turns it on (toggle_functions). Add it to the steps that need it.',
1642
+ });
1278
1643
  }
1279
1644
  }
1280
1645
  /**
@@ -1306,4 +1671,66 @@ export class ContextBuilder {
1306
1671
  export function createSimpleContext(name = 'default') {
1307
1672
  return new Context(name);
1308
1673
  }
1674
+ /**
1675
+ * The tool names `text` names.
1676
+ *
1677
+ * A name with an underscore, such as `place_order`, counts as a whole word
1678
+ * anywhere. A one-word name, such as `help`, counts only in backticks or before
1679
+ * "(", since it's also an ordinary word.
1680
+ *
1681
+ * @param text - The text: a step's, a prompt's or a tool result's.
1682
+ * @param tools - The tool names to look for.
1683
+ * @returns The names it finds.
1684
+ */
1685
+ export function namedTools(text, tools) {
1686
+ const found = new Set();
1687
+ if (!text)
1688
+ return found;
1689
+ for (const name of tools) {
1690
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1691
+ const pattern = name.includes('_')
1692
+ ? new RegExp(`(?<![A-Za-z0-9_])${escaped}(?![A-Za-z0-9_])`)
1693
+ : new RegExp(`\`${escaped}\`|(?<![A-Za-z0-9_])${escaped}\\(`);
1694
+ if (pattern.test(text))
1695
+ found.add(name);
1696
+ }
1697
+ return found;
1698
+ }
1699
+ /** Each gate's output text on a tool, as `[gate id, text]`. */
1700
+ function gateTexts(definition) {
1701
+ let gates;
1702
+ if (definition && typeof definition === 'object') {
1703
+ const fields = definition.extraFields;
1704
+ gates = fields ? fields['gates'] : definition['gates'];
1705
+ }
1706
+ if (!Array.isArray(gates))
1707
+ return [];
1708
+ const texts = [];
1709
+ gates.forEach((gate, index) => {
1710
+ if (!gate || typeof gate !== 'object' || Array.isArray(gate))
1711
+ return;
1712
+ const g = gate;
1713
+ const gateId = String(g['id'] ?? `gate_${index + 1}`);
1714
+ for (const key of ['on_fail', 'on_unclear']) {
1715
+ const output = g[key];
1716
+ let response = output && typeof output === 'object'
1717
+ ? output['response']
1718
+ : undefined;
1719
+ if (response && typeof response === 'object') {
1720
+ const r = response;
1721
+ response = ['tool_result', 'tool_prompt'].map((k) => String(r[k] ?? '')).join(' ');
1722
+ }
1723
+ if (typeof response === 'string' && response)
1724
+ texts.push([`${gateId} ${key}`, response]);
1725
+ }
1726
+ });
1727
+ return texts;
1728
+ }
1729
+ /** Whether a step's own function list, or one of its gather questions', names `functionName`. */
1730
+ function stepOffers(step, functionName) {
1731
+ if (step.getFunctions()?.includes(functionName))
1732
+ return true;
1733
+ const gather = step.getGatherInfo();
1734
+ return !!gather && gather.getQuestions().some((q) => q.functions?.includes(functionName));
1735
+ }
1309
1736
  //# sourceMappingURL=ContextBuilder.js.map