@falai/agent 2.5.0 → 2.6.1

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 (51) hide show
  1. package/dist/cjs/core/Agent.d.ts.map +1 -1
  2. package/dist/cjs/core/Agent.js +3 -1
  3. package/dist/cjs/core/Agent.js.map +1 -1
  4. package/dist/cjs/core/FlowRouter.d.ts.map +1 -1
  5. package/dist/cjs/core/FlowRouter.js +0 -11
  6. package/dist/cjs/core/FlowRouter.js.map +1 -1
  7. package/dist/cjs/core/ResponseModal.d.ts +51 -2
  8. package/dist/cjs/core/ResponseModal.d.ts.map +1 -1
  9. package/dist/cjs/core/ResponseModal.js +272 -269
  10. package/dist/cjs/core/ResponseModal.js.map +1 -1
  11. package/dist/cjs/core/ToolLoopExecutor.js +1 -1
  12. package/dist/cjs/core/ToolLoopExecutor.js.map +1 -1
  13. package/dist/cjs/providers/GeminiProvider.d.ts.map +1 -1
  14. package/dist/cjs/providers/GeminiProvider.js +3 -1
  15. package/dist/cjs/providers/GeminiProvider.js.map +1 -1
  16. package/dist/cjs/types/agent.d.ts +9 -0
  17. package/dist/cjs/types/agent.d.ts.map +1 -1
  18. package/dist/cjs/utils/streamingMessage.d.ts +48 -0
  19. package/dist/cjs/utils/streamingMessage.d.ts.map +1 -0
  20. package/dist/cjs/utils/streamingMessage.js +210 -0
  21. package/dist/cjs/utils/streamingMessage.js.map +1 -0
  22. package/dist/core/Agent.d.ts.map +1 -1
  23. package/dist/core/Agent.js +3 -1
  24. package/dist/core/Agent.js.map +1 -1
  25. package/dist/core/FlowRouter.d.ts.map +1 -1
  26. package/dist/core/FlowRouter.js +0 -11
  27. package/dist/core/FlowRouter.js.map +1 -1
  28. package/dist/core/ResponseModal.d.ts +51 -2
  29. package/dist/core/ResponseModal.d.ts.map +1 -1
  30. package/dist/core/ResponseModal.js +272 -269
  31. package/dist/core/ResponseModal.js.map +1 -1
  32. package/dist/core/ToolLoopExecutor.js +1 -1
  33. package/dist/core/ToolLoopExecutor.js.map +1 -1
  34. package/dist/providers/GeminiProvider.d.ts.map +1 -1
  35. package/dist/providers/GeminiProvider.js +3 -1
  36. package/dist/providers/GeminiProvider.js.map +1 -1
  37. package/dist/types/agent.d.ts +9 -0
  38. package/dist/types/agent.d.ts.map +1 -1
  39. package/dist/utils/streamingMessage.d.ts +48 -0
  40. package/dist/utils/streamingMessage.d.ts.map +1 -0
  41. package/dist/utils/streamingMessage.js +205 -0
  42. package/dist/utils/streamingMessage.js.map +1 -0
  43. package/docs/reference/create-agent.md +2 -0
  44. package/package.json +1 -1
  45. package/src/core/Agent.ts +3 -1
  46. package/src/core/FlowRouter.ts +0 -14
  47. package/src/core/ResponseModal.ts +332 -299
  48. package/src/core/ToolLoopExecutor.ts +1 -1
  49. package/src/providers/GeminiProvider.ts +4 -2
  50. package/src/types/agent.ts +9 -0
  51. package/src/utils/streamingMessage.ts +220 -0
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Incremental extraction of the `message` field from a streamed structured
3
+ * JSON response.
4
+ *
5
+ * Providers that enforce a JSON schema stream the raw wrapper object
6
+ * (`{"message":"Hel` → `{"message":"Hello"}`), not the message text. Without
7
+ * this, every streaming consumer has to re-implement partial-JSON unwrapping to
8
+ * recover the user-facing tokens. These helpers do it once, at the framework
9
+ * boundary, so `delta`/`accumulated` carry clean message text and the parsed
10
+ * object is surfaced only when complete.
11
+ *
12
+ * The extractor targets the top-level `message` string field specifically
13
+ * (tracking object depth and string context, so a nested decoy `"message"` key
14
+ * or a `"message"` substring inside another value is never mistaken for it),
15
+ * and is tolerant of truncation at any byte — a dangling escape sequence is
16
+ * held back rather than emitted half-decoded. Input that is not a JSON object
17
+ * (e.g. a provider streaming plain text) is passed through verbatim.
18
+ */
19
+ const WHITESPACE = " \t\n\r";
20
+ const ESCAPE_CHARS = {
21
+ '"': '"',
22
+ "\\": "\\",
23
+ "/": "/",
24
+ b: "\b",
25
+ f: "\f",
26
+ n: "\n",
27
+ r: "\r",
28
+ t: "\t",
29
+ };
30
+ /**
31
+ * Read a JSON string token whose opening quote is at `s[start]`. Decodes
32
+ * escapes. When the closing quote has not arrived, returns the decoded prefix
33
+ * with any trailing incomplete escape (`\` or a partial `\uXXXX`) held back, so
34
+ * a half-decoded character is never produced.
35
+ */
36
+ function readJsonString(s, start) {
37
+ let out = "";
38
+ const n = s.length;
39
+ let i = start + 1; // skip opening quote
40
+ while (i < n) {
41
+ const ch = s[i];
42
+ if (ch === '"') {
43
+ return { value: out, end: i + 1, complete: true };
44
+ }
45
+ if (ch === "\\") {
46
+ const esc = s[i + 1];
47
+ if (esc === undefined) {
48
+ // Dangling backslash — wait for the rest of the escape.
49
+ return { value: out, end: n, complete: false };
50
+ }
51
+ if (esc === "u") {
52
+ if (i + 6 > n) {
53
+ // Incomplete \uXXXX — hold it back.
54
+ return { value: out, end: n, complete: false };
55
+ }
56
+ const code = parseInt(s.slice(i + 2, i + 6), 16);
57
+ if (Number.isNaN(code)) {
58
+ return { value: out, end: n, complete: false };
59
+ }
60
+ out += String.fromCharCode(code);
61
+ i += 6;
62
+ }
63
+ else if (esc in ESCAPE_CHARS) {
64
+ out += ESCAPE_CHARS[esc];
65
+ i += 2;
66
+ }
67
+ else {
68
+ // Not a valid JSON escape; pass the character through leniently.
69
+ out += esc;
70
+ i += 2;
71
+ }
72
+ continue;
73
+ }
74
+ out += ch;
75
+ i++;
76
+ }
77
+ return { value: out, end: n, complete: false };
78
+ }
79
+ /**
80
+ * Skip one JSON value (string, object, array, or primitive) starting at `s[i]`.
81
+ * Tolerant of truncation: an unfinished value reports `complete: false`.
82
+ */
83
+ function skipJsonValue(s, i) {
84
+ const n = s.length;
85
+ if (i >= n)
86
+ return { end: n, complete: false };
87
+ const ch = s[i];
88
+ if (ch === '"') {
89
+ const r = readJsonString(s, i);
90
+ return { end: r.end, complete: r.complete };
91
+ }
92
+ if (ch === "{" || ch === "[") {
93
+ let depth = 0;
94
+ let j = i;
95
+ while (j < n) {
96
+ const c = s[j];
97
+ if (c === '"') {
98
+ const r = readJsonString(s, j);
99
+ if (!r.complete)
100
+ return { end: n, complete: false };
101
+ j = r.end;
102
+ continue;
103
+ }
104
+ if (c === "{" || c === "[")
105
+ depth++;
106
+ else if (c === "}" || c === "]") {
107
+ depth--;
108
+ if (depth === 0)
109
+ return { end: j + 1, complete: true };
110
+ }
111
+ j++;
112
+ }
113
+ return { end: n, complete: false };
114
+ }
115
+ // Primitive (number, true, false, null): runs until a structural delimiter.
116
+ // Hitting end-of-input first means it may still be streaming.
117
+ let j = i;
118
+ while (j < n && !`,}]${WHITESPACE}`.includes(s[j]))
119
+ j++;
120
+ return j < n ? { end: j, complete: true } : { end: n, complete: false };
121
+ }
122
+ /**
123
+ * Extract the decoded value of the top-level `message` string field from a
124
+ * (possibly partial) JSON object string, returning the text available so far.
125
+ *
126
+ * Returns `""` while the `message` value has not begun streaming, and passes
127
+ * `accumulated` through unchanged when it is not a JSON object.
128
+ */
129
+ export function extractMessageSoFar(accumulated) {
130
+ const s = accumulated;
131
+ const n = s.length;
132
+ let i = 0;
133
+ while (i < n && WHITESPACE.includes(s[i]))
134
+ i++;
135
+ // Not a JSON object — a plain-text stream; emit verbatim.
136
+ if (i >= n || s[i] !== "{")
137
+ return accumulated;
138
+ i++; // skip '{'
139
+ while (i < n) {
140
+ while (i < n && (WHITESPACE.includes(s[i]) || s[i] === ","))
141
+ i++;
142
+ if (i >= n)
143
+ return "";
144
+ if (s[i] === "}")
145
+ return ""; // object closed without a message
146
+ if (s[i] !== '"')
147
+ return ""; // key not (fully) arrived
148
+ const key = readJsonString(s, i);
149
+ if (!key.complete)
150
+ return ""; // key still streaming
151
+ i = key.end;
152
+ while (i < n && WHITESPACE.includes(s[i]))
153
+ i++;
154
+ if (i >= n || s[i] !== ":")
155
+ return ""; // colon not arrived
156
+ i++;
157
+ while (i < n && WHITESPACE.includes(s[i]))
158
+ i++;
159
+ if (i >= n)
160
+ return "";
161
+ if (key.value === "message") {
162
+ // Found it. Only a string value yields text; null/other → no message yet.
163
+ if (s[i] !== '"')
164
+ return "";
165
+ return readJsonString(s, i).value;
166
+ }
167
+ // A field before `message`: skip its value. If it is still streaming we
168
+ // cannot have reached `message` yet.
169
+ const skipped = skipJsonValue(s, i);
170
+ if (!skipped.complete)
171
+ return "";
172
+ i = skipped.end;
173
+ }
174
+ return "";
175
+ }
176
+ /**
177
+ * Stateful wrapper over {@link extractMessageSoFar} for a single stream: feed
178
+ * each chunk's accumulated JSON and get back the clean message-so-far plus the
179
+ * newly revealed delta.
180
+ *
181
+ * Each push re-scans the full accumulated buffer (O(n) per chunk, O(n²) over a
182
+ * stream) — deliberately kept simple and stateless: at LLM response sizes (KBs)
183
+ * the cost is negligible, and it avoids carrying cross-chunk parser/escape state.
184
+ */
185
+ export class StreamingMessageDecoder {
186
+ constructor() {
187
+ this.previous = "";
188
+ }
189
+ /**
190
+ * @param accumulated The provider chunk's full accumulated output so far.
191
+ * @returns `message` (clean text so far) and `delta` (the new text since the
192
+ * previous push).
193
+ */
194
+ push(accumulated) {
195
+ const message = extractMessageSoFar(accumulated);
196
+ // Decoding is monotonic (each push extends the prefix); the guard is a
197
+ // belt-and-braces reset for any non-prefix anomaly.
198
+ const delta = message.startsWith(this.previous)
199
+ ? message.slice(this.previous.length)
200
+ : message;
201
+ this.previous = message;
202
+ return { message, delta };
203
+ }
204
+ }
205
+ //# sourceMappingURL=streamingMessage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streamingMessage.js","sourceRoot":"","sources":["../../src/utils/streamingMessage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,MAAM,UAAU,GAAG,SAAS,CAAC;AAE7B,MAAM,YAAY,GAA2B;IAC3C,GAAG,EAAE,GAAG;IACR,IAAI,EAAE,IAAI;IACV,GAAG,EAAE,GAAG;IACR,CAAC,EAAE,IAAI;IACP,CAAC,EAAE,IAAI;IACP,CAAC,EAAE,IAAI;IACP,CAAC,EAAE,IAAI;I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known, TData = unknown> {
44
44
  flowSwitchMargin?: number;
45
45
  maxAutoStepsPerTurn?: number;
46
46
  maxDirectiveChain?: number;
47
+ maxToolLoops?: number;
47
48
  compaction?: AgentCompactionConfig;
48
49
  promptCache?: PromptCacheConfig;
49
50
  routerMode?: 'ai';
@@ -76,6 +77,7 @@ interface AgentOptions<TContext = unknown, TData = unknown> {
76
77
  | `flowSwitchMargin` | `number` | no | `15` | Margin (0–100) the best alternative flow must exceed the current flow's score by before switching. Higher values make the agent stickier. |
77
78
  | `maxAutoStepsPerTurn` | `number` | no | `10` | Cap on consecutive `auto: true` steps per turn. Throws `FlowConfigurationError` when exceeded. |
78
79
  | `maxDirectiveChain` | `number` | no | `10` | Cap on chained directives per turn (e.g., `goTo` → `onEnter` emits `goTo` → …). Throws `FlowConfigurationError` when exceeded. |
80
+ | `maxToolLoops` | `number` | no | `5` | Cap on tool-call follow-up rounds per turn, after the initial tool batch. Stops executing further tool calls when reached. Applies to both `respond()` and streaming. An explicit `0` disables tool loops. |
79
81
  | `compaction` | `AgentCompactionConfig` | no | — | History compaction config: `maxTokens`, `compactionThreshold`, `preserveRecentCount`, `maxToolResultChars`. |
80
82
  | `promptCache` | `PromptCacheConfig` | no | `{ enabled: true }` | Controls prompt-section memoization across turns. |
81
83
  | `debug` | `boolean` | no | `false` | Enables `loglevel` debug output. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@falai/agent",
3
- "version": "2.5.0",
3
+ "version": "2.6.1",
4
4
  "description": "Conversational state engine for TypeScript where the AI understands, but the code is in control",
5
5
  "type": "module",
6
6
  "main": "./dist/cjs/index.js",
package/src/core/Agent.ts CHANGED
@@ -255,7 +255,9 @@ export class Agent<TContext = unknown, TData = unknown> implements ResponseModal
255
255
  this.tool = new ToolManager<TContext, TData>(this);
256
256
 
257
257
  // Initialize ResponseModal for handling all response generation
258
- this._responseModal = new ResponseModal<TContext, TData>(this);
258
+ this._responseModal = new ResponseModal<TContext, TData>(this, {
259
+ maxToolLoops: options.maxToolLoops,
260
+ });
259
261
 
260
262
  // Initialize persistence if configured
261
263
  if (options.persistence) {
@@ -366,20 +366,6 @@ export class FlowRouter<TContext = unknown, TData = unknown> {
366
366
  }
367
367
  }
368
368
 
369
- // No candidates means flow has no valid next steps (edge case)
370
- if (candidates.length === 0) {
371
- logger.debug(
372
- `[FlowRouter] Single-flow: No valid candidate steps found`
373
- );
374
- return {
375
- selectedFlow,
376
- selectedStep: undefined,
377
- session: updatedSession,
378
- isFlowComplete: false,
379
- completedFlows,
380
- };
381
- }
382
-
383
369
  // Multiple candidates - use AI to select best step
384
370
  const lastUserMessage = getLastMessageFromHistory(history);
385
371