@memberjunction/ai-agents 6.2.0-edge.4 → 6.2.0-edge.6

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 (161) hide show
  1. package/README.md +154 -7
  2. package/dist/AgentDataPreloader.d.ts +4 -2
  3. package/dist/AgentDataPreloader.d.ts.map +1 -1
  4. package/dist/AgentDataPreloader.js +21 -12
  5. package/dist/AgentDataPreloader.js.map +1 -1
  6. package/dist/AgentRunner.d.ts +61 -6
  7. package/dist/AgentRunner.d.ts.map +1 -1
  8. package/dist/AgentRunner.js +313 -68
  9. package/dist/AgentRunner.js.map +1 -1
  10. package/dist/AgentWakeTriggerService.d.ts +183 -0
  11. package/dist/AgentWakeTriggerService.d.ts.map +1 -0
  12. package/dist/AgentWakeTriggerService.js +478 -0
  13. package/dist/AgentWakeTriggerService.js.map +1 -0
  14. package/dist/ArtifactToolManager.d.ts +12 -3
  15. package/dist/ArtifactToolManager.d.ts.map +1 -1
  16. package/dist/ArtifactToolManager.js +77 -6
  17. package/dist/ArtifactToolManager.js.map +1 -1
  18. package/dist/ClientToolRequestManager.d.ts +11 -1
  19. package/dist/ClientToolRequestManager.d.ts.map +1 -1
  20. package/dist/ClientToolRequestManager.js +19 -6
  21. package/dist/ClientToolRequestManager.js.map +1 -1
  22. package/dist/ConversationToolManager.d.ts +1 -1
  23. package/dist/ConversationToolManager.d.ts.map +1 -1
  24. package/dist/ConversationToolManager.js +10 -4
  25. package/dist/ConversationToolManager.js.map +1 -1
  26. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  27. package/dist/MJAIAgentRequestEntityServer.js +20 -0
  28. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  29. package/dist/PayloadChangeAnalyzer.d.ts.map +1 -1
  30. package/dist/PayloadChangeAnalyzer.js +53 -30
  31. package/dist/PayloadChangeAnalyzer.js.map +1 -1
  32. package/dist/PayloadManager.d.ts +35 -2
  33. package/dist/PayloadManager.d.ts.map +1 -1
  34. package/dist/PayloadManager.js +250 -149
  35. package/dist/PayloadManager.js.map +1 -1
  36. package/dist/ScratchpadManager.d.ts +18 -0
  37. package/dist/ScratchpadManager.d.ts.map +1 -1
  38. package/dist/ScratchpadManager.js +61 -0
  39. package/dist/ScratchpadManager.js.map +1 -1
  40. package/dist/agent-audience.d.ts +38 -0
  41. package/dist/agent-audience.d.ts.map +1 -0
  42. package/dist/agent-audience.js +99 -0
  43. package/dist/agent-audience.js.map +1 -0
  44. package/dist/agent-context-injector.d.ts +38 -6
  45. package/dist/agent-context-injector.d.ts.map +1 -1
  46. package/dist/agent-context-injector.js +72 -20
  47. package/dist/agent-context-injector.js.map +1 -1
  48. package/dist/agent-memory-context-builder.d.ts +7 -2
  49. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  50. package/dist/agent-memory-context-builder.js +14 -5
  51. package/dist/agent-memory-context-builder.js.map +1 -1
  52. package/dist/agent-pre-execution-rag.d.ts +101 -9
  53. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  54. package/dist/agent-pre-execution-rag.js +227 -29
  55. package/dist/agent-pre-execution-rag.js.map +1 -1
  56. package/dist/agent-run-watchdog.d.ts +23 -8
  57. package/dist/agent-run-watchdog.d.ts.map +1 -1
  58. package/dist/agent-run-watchdog.js +141 -76
  59. package/dist/agent-run-watchdog.js.map +1 -1
  60. package/dist/agent-types/flow-agent-type.d.ts +15 -0
  61. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  62. package/dist/agent-types/flow-agent-type.js +129 -13
  63. package/dist/agent-types/flow-agent-type.js.map +1 -1
  64. package/dist/agent-types/loop-agent-prompt-params.d.ts +6 -2
  65. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  66. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  67. package/dist/agent-types/loop-agent-response-type.d.ts +8 -2
  68. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  69. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  70. package/dist/agent-types/loop-agent-type.d.ts +85 -7
  71. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  72. package/dist/agent-types/loop-agent-type.js +290 -66
  73. package/dist/agent-types/loop-agent-type.js.map +1 -1
  74. package/dist/base-agent.d.ts +809 -38
  75. package/dist/base-agent.d.ts.map +1 -1
  76. package/dist/base-agent.js +3308 -609
  77. package/dist/base-agent.js.map +1 -1
  78. package/dist/bound-action-params.d.ts +57 -0
  79. package/dist/bound-action-params.d.ts.map +1 -0
  80. package/dist/bound-action-params.js +91 -0
  81. package/dist/bound-action-params.js.map +1 -0
  82. package/dist/index.d.ts +9 -0
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +9 -0
  85. package/dist/index.js.map +1 -1
  86. package/dist/memory-cleanup-agent.d.ts.map +1 -1
  87. package/dist/memory-cleanup-agent.js +3 -0
  88. package/dist/memory-cleanup-agent.js.map +1 -1
  89. package/dist/memory-manager-agent.d.ts.map +1 -1
  90. package/dist/memory-manager-agent.js +52 -35
  91. package/dist/memory-manager-agent.js.map +1 -1
  92. package/dist/native-tools/action-param-schema.d.ts +57 -0
  93. package/dist/native-tools/action-param-schema.d.ts.map +1 -0
  94. package/dist/native-tools/action-param-schema.js +238 -0
  95. package/dist/native-tools/action-param-schema.js.map +1 -0
  96. package/dist/native-tools/action-tool-builder.d.ts +5 -4
  97. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  98. package/dist/native-tools/action-tool-builder.js +29 -71
  99. package/dist/native-tools/action-tool-builder.js.map +1 -1
  100. package/dist/native-tools/agent-tools.d.ts +64 -0
  101. package/dist/native-tools/agent-tools.d.ts.map +1 -0
  102. package/dist/native-tools/agent-tools.js +23 -0
  103. package/dist/native-tools/agent-tools.js.map +1 -0
  104. package/dist/native-tools/control-tools.d.ts +26 -4
  105. package/dist/native-tools/control-tools.d.ts.map +1 -1
  106. package/dist/native-tools/control-tools.js +114 -42
  107. package/dist/native-tools/control-tools.js.map +1 -1
  108. package/dist/native-tools/framework-tools.d.ts +47 -0
  109. package/dist/native-tools/framework-tools.d.ts.map +1 -0
  110. package/dist/native-tools/framework-tools.js +187 -0
  111. package/dist/native-tools/framework-tools.js.map +1 -0
  112. package/dist/native-tools/json-argument.d.ts +41 -0
  113. package/dist/native-tools/json-argument.d.ts.map +1 -0
  114. package/dist/native-tools/json-argument.js +79 -0
  115. package/dist/native-tools/json-argument.js.map +1 -0
  116. package/dist/native-tools/native-control-config.d.ts +93 -0
  117. package/dist/native-tools/native-control-config.d.ts.map +1 -0
  118. package/dist/native-tools/native-control-config.js +104 -0
  119. package/dist/native-tools/native-control-config.js.map +1 -0
  120. package/dist/native-tools/tool-result-turns.d.ts +41 -8
  121. package/dist/native-tools/tool-result-turns.d.ts.map +1 -1
  122. package/dist/native-tools/tool-result-turns.js +76 -2
  123. package/dist/native-tools/tool-result-turns.js.map +1 -1
  124. package/dist/native-tools/turn-mode.d.ts +8 -0
  125. package/dist/native-tools/turn-mode.d.ts.map +1 -0
  126. package/dist/native-tools/turn-mode.js +14 -0
  127. package/dist/native-tools/turn-mode.js.map +1 -0
  128. package/dist/query-builder-agent.d.ts +33 -5
  129. package/dist/query-builder-agent.d.ts.map +1 -1
  130. package/dist/query-builder-agent.js +137 -30
  131. package/dist/query-builder-agent.js.map +1 -1
  132. package/dist/realtime/bridge-room-transcript-sink.js +1 -0
  133. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  134. package/dist/realtime/bridge-session-transcript-sink.js +1 -0
  135. package/dist/realtime/bridge-session-transcript-sink.js.map +1 -1
  136. package/dist/realtime/realtime-client-session-service.d.ts +5 -4
  137. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  138. package/dist/realtime/realtime-client-session-service.js +42 -30
  139. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  140. package/dist/realtime/realtime-coagent-config.d.ts +8 -1
  141. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  142. package/dist/realtime/realtime-coagent-config.js +17 -1
  143. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  144. package/dist/realtime/realtime-recording-ledger.d.ts +150 -0
  145. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -0
  146. package/dist/realtime/realtime-recording-ledger.js +206 -0
  147. package/dist/realtime/realtime-recording-ledger.js.map +1 -0
  148. package/dist/realtime/realtime-recording-opus-assembly.d.ts +211 -0
  149. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -0
  150. package/dist/realtime/realtime-recording-opus-assembly.js +706 -0
  151. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -0
  152. package/dist/realtime/realtime-recording-store.d.ts +44 -6
  153. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  154. package/dist/realtime/realtime-recording-store.js +105 -51
  155. package/dist/realtime/realtime-recording-store.js.map +1 -1
  156. package/dist/realtime/realtime-turn-moderator.d.ts +2 -1
  157. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  158. package/dist/realtime/realtime-turn-moderator.js +7 -1
  159. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  160. package/dist/volatile-child-prompt.js +3 -3
  161. package/package.json +21 -19
@@ -15,10 +15,15 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
15
15
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16
16
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17
17
  };
18
- import { CHAT_FINISH_REASON_MALFORMED_TOOL_CALL } from '@memberjunction/ai';
18
+ import { CHAT_FINISH_REASON_MALFORMED_TOOL_CALL, CHAT_FINISH_REASON_UNEXPECTED_TOOL_CALL } from '@memberjunction/ai';
19
19
  import { RegisterClass, SafeExpressionEvaluator } from '@memberjunction/global';
20
20
  import { BaseAgentType } from './base-agent-type.js';
21
+ import { COMPLETE_TASK_TOOL, PAYLOAD_CHANGE_TOOL } from '../native-tools/control-tools.js';
21
22
  import { CoerceActionArguments } from '../native-tools/action-tool-builder.js';
23
+ import { DecodeJSONArgument } from '../native-tools/json-argument.js';
24
+ import { ResolveNativeControlConfig } from '../native-tools/native-control-config.js';
25
+ import { TurnToolCallingMode } from '../native-tools/turn-mode.js';
26
+ import { FRAMEWORK_TOOL_NAMES } from '../native-tools/framework-tools.js';
22
27
  import { GetToolCallingDecision } from '@memberjunction/ai-prompts';
23
28
  import { FormatValidationErrors, ValidateTaskGraphSpec, ConfigOf } from '@memberjunction/ai-core-plus';
24
29
  import { LogError, LogStatusEx } from '@memberjunction/core';
@@ -171,6 +176,11 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
171
176
  retVal.errorMessage = 'Task graph not specified for Tasks type';
172
177
  return;
173
178
  }
179
+ // Backward-compatibility normalization: if a prompt or model emits the legacy v1 flat
180
+ // `"agentName": "..."` field on a task node without `kind` / `configuration`, normalize it
181
+ // in place to the v2 `kind: "Agent"` + `configuration: { agentName }` shape before running
182
+ // ValidateTaskGraphSpec so single-agent and multi-agent delegations do not needlessly fail.
183
+ this.normalizeLegacyTaskNodes(spec);
174
184
  // The same validator the server runs at submission (D16), so a graph that passes here
175
185
  // cannot fail a different check later. Every failure is reported at once — a model fixing a
176
186
  // malformed graph should not discover the problems one round-trip at a time.
@@ -207,6 +217,34 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
207
217
  retVal.taskGraph = { spec, folded: true, foldReason: fold.reason };
208
218
  }
209
219
  }
220
+ /**
221
+ * Normalizes legacy v1 flat `agentName` task nodes into the v2 `{ kind: 'Agent', configuration: { agentName } }`
222
+ * shape in place before validation.
223
+ */
224
+ normalizeLegacyTaskNodes(spec) {
225
+ if (!spec || !Array.isArray(spec.tasks)) {
226
+ return;
227
+ }
228
+ for (const rawNode of spec.tasks) {
229
+ if (!rawNode || typeof rawNode !== 'object') {
230
+ continue;
231
+ }
232
+ const record = rawNode;
233
+ const legacyAgentName = typeof record.agentName === 'string' ? record.agentName.trim() : '';
234
+ if (!record.kind && legacyAgentName.length > 0) {
235
+ record.kind = 'Agent';
236
+ if (!record.configuration || typeof record.configuration !== 'object') {
237
+ record.configuration = { agentName: legacyAgentName };
238
+ }
239
+ else {
240
+ const configRecord = record.configuration;
241
+ if (typeof configRecord.agentName !== 'string' || configRecord.agentName.trim().length === 0) {
242
+ configRecord.agentName = legacyAgentName;
243
+ }
244
+ }
245
+ }
246
+ }
247
+ }
210
248
  /**
211
249
  * Decides whether a graph folds to an in-run sub-agent call, and says why when it does not.
212
250
  *
@@ -226,10 +264,10 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
226
264
  return { folded: false, reason: `the single node is a ${node.kind} step, which has no in-run equivalent` };
227
265
  if (spec.durable === true)
228
266
  return { folded: false, reason: 'the graph requested durable execution' };
229
- if (spec.continuation && spec.continuation !== 'message') {
230
- return { folded: false, reason: `continuation is '${spec.continuation}', not the default` };
267
+ if (spec.continuation && spec.continuation !== 'message' && spec.continuation !== 'reinvoke') {
268
+ return { folded: false, reason: `continuation is '${spec.continuation}', not foldable in-run` };
231
269
  }
232
- return { folded: true, reason: 'single agent node, no dependencies, default continuation' };
270
+ return { folded: true, reason: 'single agent node, no dependencies, foldable continuation' };
233
271
  }
234
272
  async InitializeAgentTypeState(params) {
235
273
  // Loop agents do not require agent-type specific state initialization
@@ -260,7 +298,7 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
260
298
  * documented to do this, measured at roughly one forced call in six, so the loop
261
299
  * has to be able to say "that tool does not exist" rather than appear to hang.
262
300
  */
263
- nextStepFromNativeToolCalls(promptResult, bindings) {
301
+ nextStepFromNativeToolCalls(promptResult, bindings, relaxedTurnShapes = false) {
264
302
  const calls = promptResult.chatResult?.data?.choices?.[0]?.message?.toolCalls;
265
303
  if (!calls?.length) {
266
304
  return null;
@@ -273,21 +311,41 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
273
311
  // Control tools are dispatchable ONLY on a turn the runner recorded as NativeImplicit
274
312
  // under the hybrid they are stripped from the request, so a call to one
275
313
  // is a call to an undeclared tool, whatever the binding map says.
276
- const implicit = promptResult.promptRun?.ToolCallingMode === 'NativeImplicit';
314
+ const implicit = TurnToolCallingMode(promptResult) === 'NativeImplicit';
277
315
  // The model's own turn travels on the step so the loop can replay it into history and
278
316
  // answer each call natively when the runner's decision says so.
279
317
  const message = promptResult.chatResult?.data?.choices?.[0]?.message;
280
318
  const nativeTurn = {
281
319
  text: typeof message?.content === 'string' ? message.content : '',
282
320
  toolCalls: calls,
283
- sendResultsNatively: GetToolCallingDecision(promptResult.chatResult)?.toolResults === true
321
+ sendResultsNatively: GetToolCallingDecision(promptResult.chatResult)?.toolResults === true,
322
+ ...(message?.reasoning?.length ? { reasoning: message.reasoning } : {})
284
323
  };
285
324
  const { resolved, unknown } = this.resolveNativeCalls(calls, bindings, implicit);
286
325
  if (unknown.length > 0) {
287
326
  return this.createRetryStep(`You called ${unknown.map((c) => `'${c.name}'`).join(', ')}, which ${unknown.length === 1 ? 'is not a tool' : 'are not tools'} `
288
- + `available to you. Call one of the declared tools, or respond with the JSON envelope if no tool applies.`, { nativeTurn });
327
+ + `available to you. ${this.unknownToolAdvice(implicit, bindings)}`, { nativeTurn });
328
+ }
329
+ const completeTaskDeclared = bindings.has(COMPLETE_TASK_TOOL);
330
+ const step = relaxedTurnShapes ? this.routeRelaxed(resolved, completeTaskDeclared) : this.routeStrict(resolved, completeTaskDeclared);
331
+ return { ...step, nativeTurn };
332
+ }
333
+ /**
334
+ * Whether a binding runs on a hybrid turn. Actions and the agent's own tools run in every native
335
+ * mode; control tools — and the framework tools, which are declared as control tools — are
336
+ * stripped from a hybrid request, so a call to one there is a call to an undeclared tool.
337
+ */
338
+ dispatchableOnHybrid(binding) {
339
+ return binding.kind === 'action' || (binding.kind === 'agentTool' && !FRAMEWORK_TOOL_NAMES.includes(binding.toolName));
340
+ }
341
+ /** What to do instead, after a call to a tool that does not exist on this turn. */
342
+ unknownToolAdvice(implicit, bindings) {
343
+ if (!implicit) {
344
+ return 'Call one of the declared tools, or respond with the JSON envelope if no tool applies.';
289
345
  }
290
- return { ...this.routeResolvedCalls(resolved), nativeTurn };
346
+ return bindings.has(COMPLETE_TASK_TOOL)
347
+ ? 'Call one of the declared tools, or call complete_task when the task is done.'
348
+ : 'Call one of the declared tools, or reply in plain text when the task is done.';
291
349
  }
292
350
  /** Pairs each call with its binding; a control-tool binding counts only under implicit control flow. */
293
351
  resolveNativeCalls(calls, bindings, implicit) {
@@ -295,7 +353,7 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
295
353
  const unknown = [];
296
354
  for (const call of calls) {
297
355
  const binding = bindings.get(call.name);
298
- if (binding && (binding.kind === 'action' || implicit)) {
356
+ if (binding && (implicit || this.dispatchableOnHybrid(binding))) {
299
357
  resolved.push({ call, binding });
300
358
  }
301
359
  else {
@@ -304,44 +362,167 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
304
362
  }
305
363
  return { resolved, unknown };
306
364
  }
307
- /** The turn-reading table of spec §2.1, one row per branch. */
308
- routeResolvedCalls(resolved) {
309
- const ofKind = (kind) => resolved.filter((r) => r.binding.kind === kind);
310
- const askUser = ofKind('askUser');
311
- const subAgents = ofKind('subAgent');
312
- const actions = ofKind('action');
313
- const payloads = ofKind('payloadChange');
314
- if (askUser.length > 0) {
315
- return this.askUserStep(askUser[0], resolved.length);
365
+ /**
366
+ * The turn-reading table of spec §2.1, with each control call alone on its turn — the default.
367
+ *
368
+ * `ask_user` and `complete_task` must be the only call on their turn, at most one
369
+ * `payload_change_request` is allowed, and acting and delegating cannot share a turn; each of
370
+ * these is a Retry that runs nothing. The agent's own tools ride along with Actions or a
371
+ * delegation, and alone are a turn of their own.
372
+ *
373
+ * @param completeTaskDeclared Whether the agent declares `complete_task`; a text-terminal agent
374
+ * does not, and is told to finish in plain text instead.
375
+ */
376
+ routeStrict(resolved, completeTaskDeclared) {
377
+ const calls = this.groupResolvedCalls(resolved);
378
+ if (calls.askUser.length > 0) {
379
+ return resolved.length > 1
380
+ ? this.createRetryStep('ask_user must be the only call on its turn: either ask the user, or do the work — not both at once.')
381
+ : this.askUserStep(calls.askUser[0]);
316
382
  }
317
- const completes = ofKind('complete');
318
- if (completes.length > 0) {
319
- return this.completeTaskStep(completes[0], resolved.length);
383
+ if (calls.complete.length > 0) {
384
+ return resolved.length > 1
385
+ ? this.createRetryStep('complete_task must be the only call on its turn. Finish any other tool calls first, then call complete_task on its own.')
386
+ : this.completeTaskStep(calls.complete[0]);
320
387
  }
321
- if (payloads.length > 1) {
388
+ if (calls.payloads.length > 1) {
322
389
  return this.createRetryStep('Call payload_change_request at most once per turn; combine your changes into one call.');
323
390
  }
324
- const payloadChangeRequest = payloads[0]?.call.arguments;
325
- // The payload call's id has to travel with every step that carries the change, not just the
326
- // payload-only one: whichever branch applies it also has to answer that call, or the model
327
- // is left with a tool_use nothing responded to.
328
- const payloadToolCallId = payloads[0]?.call.id;
329
- if (subAgents.length > 0 && actions.length > 0) {
391
+ if (calls.subAgents.length > 0 && calls.actions.length > 0) {
330
392
  return this.createRetryStep('Delegate or act — not both in one turn. Call the sub-agent tool(s) on their own, or the action tool(s) on their own.');
331
393
  }
332
- if (subAgents.length > 0) {
333
- return this.subAgentStep(subAgents, payloadChangeRequest, payloadToolCallId);
394
+ return this.workStep(calls, false, completeTaskDeclared) ?? this.payloadOnlyStep(undefined, undefined, completeTaskDeclared);
395
+ }
396
+ /**
397
+ * The turn-reading table with relaxed turn shapes (`NativeControl.RelaxedTurnShapes`): every
398
+ * call on the turn is honoured where the loop can do so without skipping a check.
399
+ * - Writes — the agent's own tools and `payload_change_request` — run inline, in call order,
400
+ * and are answered one by one. A single payload change keeps the step's own payload channel.
401
+ * - `ask_user` or `complete_task` after writes: the writes run, then the turn asks or completes
402
+ * through the normal Chat or Success validation. A failed write declines it (see BaseAgent).
403
+ * - Actions with a delegation, `ask_user` or `complete_task`: the Actions run, and the other
404
+ * calls are answered as not run — they were made before the Actions' results existed, and
405
+ * running them afterwards would skip the validation a turn's own decision gets.
406
+ *
407
+ * @param completeTaskDeclared Whether the agent declares `complete_task`; a text-terminal agent
408
+ * does not, and is told to finish in plain text instead.
409
+ */
410
+ routeRelaxed(resolved, completeTaskDeclared) {
411
+ const calls = this.groupResolvedCalls(resolved);
412
+ if (calls.askUser.length > 1 || calls.complete.length > 1) {
413
+ return this.createRetryStep('Call ask_user or complete_task at most once per turn.');
414
+ }
415
+ const terminal = calls.askUser.length > 0 || calls.complete.length > 0;
416
+ const work = this.workStep(calls, terminal, completeTaskDeclared);
417
+ if (calls.askUser.length > 0) {
418
+ return this.withAskUser(calls.askUser[0], work);
334
419
  }
335
- if (actions.length > 0) {
336
- return this.actionsStep(actions, payloadChangeRequest, payloadToolCallId);
420
+ if (calls.complete.length > 0) {
421
+ return this.withCompleteTask(calls.complete[0], work);
337
422
  }
338
- return this.payloadOnlyStep(payloadChangeRequest, payloadToolCallId);
423
+ // A resolved turn always holds at least one call, so a non-terminal turn always has work.
424
+ return work ?? this.payloadOnlyStep(undefined, undefined, completeTaskDeclared);
425
+ }
426
+ /** The turn's calls by kind; `writes` holds agent-tool and payload calls in the order the model made them. */
427
+ groupResolvedCalls(resolved) {
428
+ const ofKind = (kind) => resolved.filter((r) => r.binding.kind === kind);
429
+ return {
430
+ askUser: ofKind('askUser'),
431
+ complete: ofKind('complete'),
432
+ subAgents: ofKind('subAgent'),
433
+ actions: ofKind('action'),
434
+ payloads: ofKind('payloadChange'),
435
+ writes: resolved.filter((r) => r.binding.kind === 'agentTool' || r.binding.kind === 'payloadChange')
436
+ };
339
437
  }
340
- /** `ask_user` ends the run as Chat / AwaitingFeedback; it must travel alone and carry a message. */
341
- askUserStep(ask, totalCalls) {
342
- if (totalCalls > 1) {
343
- return this.createRetryStep('ask_user must be the only call on its turn: either ask the user, or do the work — not both at once.');
438
+ /**
439
+ * The step for every non-terminal call on the turn, or undefined when there are none.
440
+ *
441
+ * One `payload_change_request` on a turn with no terminal call rides on the step's own payload
442
+ * channel, as it always has. Several — or one beside `ask_user` / `complete_task`, whose step
443
+ * cannot answer it — run with the agent's tools as ordered writes, each answered by its result.
444
+ */
445
+ workStep(calls, terminal, completeTaskDeclared) {
446
+ const ordered = calls.payloads.length > 1 || terminal;
447
+ const payloadChangeRequest = ordered ? undefined : calls.payloads[0]?.call.arguments;
448
+ // Whichever branch applies the change also answers its call, so the id travels with the step.
449
+ const payloadToolCallId = ordered ? undefined : calls.payloads[0]?.call.id;
450
+ const writes = this.agentToolCallRequests(ordered ? calls.writes : calls.writes.filter((w) => w.binding.kind === 'agentTool'));
451
+ if (calls.actions.length > 0) {
452
+ // Strict routing never reaches here with both; relaxed routing runs the Actions and
453
+ // declines the delegations, which are made again once the Actions' results are read.
454
+ const declined = calls.subAgents.map(({ call }) => ({
455
+ toolCallId: call.id, toolName: call.name,
456
+ reason: 'Delegations are not run on a turn that also calls Actions. The Actions ran; read their results, then delegate on a turn of its own.'
457
+ }));
458
+ return { ...this.actionsStep(calls.actions, payloadChangeRequest, payloadToolCallId), ...writes, ...(declined.length ? { declinedToolCalls: declined } : {}) };
459
+ }
460
+ if (calls.subAgents.length > 0) {
461
+ return { ...this.subAgentStep(calls.subAgents, payloadChangeRequest, payloadToolCallId), ...writes };
462
+ }
463
+ if (writes.agentToolCalls) {
464
+ return this.agentToolsStep(writes.agentToolCalls, payloadChangeRequest, payloadToolCallId);
465
+ }
466
+ return payloadChangeRequest ? this.payloadOnlyStep(payloadChangeRequest, payloadToolCallId, completeTaskDeclared) : undefined;
467
+ }
468
+ /** Whether a step only writes — runs inline in the prompt step, with nothing executed after it. */
469
+ isWritesOnly(step) {
470
+ return step.step === 'Retry' && !step.actions?.length && !step.subAgent && !step.subAgents?.length;
471
+ }
472
+ /** `ask_user` with the turn's other calls: after writes it asks; beside Actions or delegations it is declined. */
473
+ withAskUser(ask, work) {
474
+ const chat = this.askUserStep(ask);
475
+ if (!work || chat.step !== 'Chat') {
476
+ return chat;
477
+ }
478
+ if (this.isWritesOnly(work)) {
479
+ return { ...chat, agentToolCalls: work.agentToolCalls };
480
+ }
481
+ const reason = 'ask_user was called with other tools on the same turn. They ran first; read their results, then ask on a turn of its own if you still need to.';
482
+ return this.withDeclined(work, { toolCallId: ask.call.id, toolName: ask.call.name, reason });
483
+ }
484
+ /** Adds one declined call to a step's list. */
485
+ withDeclined(step, declined) {
486
+ return { ...step, declinedToolCalls: [...(step.declinedToolCalls ?? []), declined] };
487
+ }
488
+ /** `complete_task` with the turn's other calls — see {@link routeRelaxed} for when it runs. */
489
+ withCompleteTask(complete, work) {
490
+ const success = this.completeTaskStep(complete);
491
+ if (!work || success.step !== 'Success') {
492
+ return success;
493
+ }
494
+ // Its own payload change would land ahead of writes the model made before it, so it waits.
495
+ if (this.isWritesOnly(work) && !success.payloadChangeRequest) {
496
+ return { ...success, agentToolCalls: work.agentToolCalls };
497
+ }
498
+ const reason = this.isWritesOnly(work)
499
+ ? 'complete_task was called with other writes on the same turn. They ran; call complete_task again, on its own, with its final payload change.'
500
+ : 'complete_task was called with other tools on the same turn. They ran first; read their results, then call complete_task on its own if the task is done.';
501
+ return this.withDeclined(work, { toolCallId: complete.call.id, toolName: complete.call.name, reason });
502
+ }
503
+ /** The turn's write calls, in call order, as the step carries them — or nothing when there are none. */
504
+ agentToolCallRequests(calls) {
505
+ if (calls.length === 0) {
506
+ return {};
344
507
  }
508
+ return { agentToolCalls: calls.map(({ call }) => ({ toolCallId: call.id, toolName: call.name, arguments: call.arguments ?? {} })) };
509
+ }
510
+ /**
511
+ * Agent-tool calls with no Action or delegation: the loop runs them, answers each call with its
512
+ * result, and goes again. A Retry with no instructions, so nothing but the results is added —
513
+ * the same non-terminal "go again" the payload-only turn uses.
514
+ */
515
+ agentToolsStep(agentToolCalls, payloadChangeRequest, payloadToolCallId) {
516
+ return this.createNextStep('Retry', {
517
+ terminate: false,
518
+ agentToolCalls,
519
+ payloadChangeRequest,
520
+ payloadToolCallId,
521
+ retryReason: 'Agent tools ran'
522
+ });
523
+ }
524
+ /** `ask_user` ends the run as Chat / AwaitingFeedback; it must carry a message. */
525
+ askUserStep(ask) {
345
526
  const message = typeof ask.call.arguments?.message === 'string' ? ask.call.arguments.message.trim() : '';
346
527
  if (!message) {
347
528
  return this.createRetryStep('ask_user requires a message — the question or request for the user.');
@@ -365,15 +546,14 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
365
546
  * the loop answers this call with the validation feedback, exactly as it answers a
366
547
  * payload-only turn.
367
548
  */
368
- completeTaskStep(complete, totalCalls) {
369
- if (totalCalls > 1) {
370
- return this.createRetryStep('complete_task must be the only call on its turn. Finish any other tool calls first, then call complete_task on its own.');
371
- }
549
+ completeTaskStep(complete) {
372
550
  const message = typeof complete.call.arguments?.message === 'string' ? complete.call.arguments.message.trim() : '';
373
- const payloadChangeRequest = this.decodePayloadChangeArgument(complete.call.arguments?.payloadChangeRequest);
374
- if (payloadChangeRequest === null) {
375
- return this.createRetryStep('complete_task.payloadChangeRequest must be an object (newElements / updateElements / replaceElements / removeElements), or be omitted.');
551
+ const decoded = this.decodePayloadChangeArgument(complete.call.arguments?.payloadChangeRequest);
552
+ if ('error' in decoded) {
553
+ return this.createRetryStep('complete_task.payloadChangeRequest must be an object (newElements / updateElements / replaceElements / removeElements), or be omitted.'
554
+ + ` Problem: ${decoded.error}`);
376
555
  }
556
+ const payloadChangeRequest = decoded.payloadChangeRequest;
377
557
  return this.createSuccessStep({
378
558
  ...(message ? { message } : {}),
379
559
  payloadChangeRequest,
@@ -389,29 +569,33 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
389
569
  return /^(?:```(?:json)?\s*)?\{\s*(?:"|$)/i.test(text);
390
570
  }
391
571
  /**
392
- * Reads `complete_task.payloadChangeRequest`: undefined when absent, null when unusable. Models
393
- * occasionally JSON-encode a nested object argument, so a string that parses to one is accepted.
572
+ * Reads `complete_task.payloadChangeRequest`: no change when absent, an error when unusable. The
573
+ * argument is declared as a JSON string (see `BuildCompleteTaskTool`); an object is accepted too,
574
+ * since some providers send one anyway. A string whose layout the model wrote as escape sequences
575
+ * is repaired rather than rejected — see `DecodeJSONArgument`.
394
576
  */
395
577
  decodePayloadChangeArgument(value) {
396
578
  if (value === undefined || value === null) {
397
- return undefined;
579
+ return {};
398
580
  }
399
581
  // An empty or "null" string is the argument left out, not a malformed one.
400
582
  if (typeof value === 'string' && (value.trim() === '' || value.trim() === 'null')) {
401
- return undefined;
583
+ return {};
402
584
  }
403
585
  let candidate = value;
404
586
  if (typeof value === 'string') {
405
- try {
406
- candidate = JSON.parse(value);
587
+ const decoded = DecodeJSONArgument(value);
588
+ if ('Error' in decoded) {
589
+ return { error: decoded.Error };
407
590
  }
408
- catch {
409
- return null;
591
+ if (decoded.Repaired) {
592
+ LogStatusEx({ message: '🩹 Loop Agent: complete_task.payloadChangeRequest had layout escapes outside its strings — repaired' });
410
593
  }
594
+ candidate = decoded.Value;
411
595
  }
412
596
  return candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate)
413
- ? candidate
414
- : null;
597
+ ? { payloadChangeRequest: candidate }
598
+ : { error: 'the value is not a JSON object' };
415
599
  }
416
600
  /** One sub-agent tool → `subAgent`; several → the parallel `subAgents[]` form. */
417
601
  subAgentStep(subAgents, payloadChangeRequest, payloadToolCallId) {
@@ -450,25 +634,62 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
450
634
  * `payload_change_request` alone: apply and continue. Retry is the non-terminal "go again" step
451
635
  * (Pipeline uses it the same way); the instructions are what the loop shows the model.
452
636
  */
453
- payloadOnlyStep(payloadChangeRequest, payloadToolCallId) {
637
+ payloadOnlyStep(payloadChangeRequest, payloadToolCallId, completeTaskDeclared) {
638
+ const finish = completeTaskDeclared ? 'call complete_task' : 'reply in plain text';
454
639
  return this.createNextStep('Retry', {
455
640
  terminate: false,
456
641
  payloadChangeRequest,
457
642
  payloadToolCallId,
458
643
  retryReason: 'Payload change applied',
459
- retryInstructions: 'Your payload change was applied. Continue: call another tool if there is more to do, or call complete_task when the task is complete.'
644
+ retryInstructions: `Your payload change was applied. Continue: call another tool if there is more to do, or ${finish} when the task is complete.`
460
645
  });
461
646
  }
647
+ /**
648
+ * What the model is told after a tool call the provider rejected — one it could not read, or one
649
+ * to a tool this turn did not offer — with the provider's description of the call, when it gave
650
+ * one, so the model can see what it sent.
651
+ */
652
+ rejectedToolCallInstructions(reason, finishMessage, bindings, implicit) {
653
+ const sent = finishMessage ? ` What the provider received: ${finishMessage.length > 400 ? `${finishMessage.slice(0, 400)}…` : finishMessage}` : '';
654
+ if (reason === CHAT_FINISH_REASON_UNEXPECTED_TOOL_CALL) {
655
+ // Only the tools this turn's request carried: a hybrid request has the control and
656
+ // framework tools stripped, and naming one would send the model straight back to it.
657
+ const declared = bindings ? [...bindings.values()].filter((b) => implicit || this.dispatchableOnHybrid(b)).map((b) => b.toolName) : [];
658
+ const offered = declared.length ? ` The tools available on this turn are: ${declared.join(', ')}.` : ' No tools are available on this turn.';
659
+ const otherwise = implicit ? 'reply in plain text' : 'respond with the JSON envelope';
660
+ return `You called a tool that was not available on this turn.${offered} Call one of those, or ${otherwise}.${sent}`;
661
+ }
662
+ // An agent with no payload tool writes through its own tools, so the advice names no tool.
663
+ const split = bindings?.has(PAYLOAD_CHANGE_TOOL) === false
664
+ ? 'split a large result into several smaller tool calls rather than one enormous call.'
665
+ : 'write a large result to the payload in pieces across several payload_change_request calls rather than one enormous call.';
666
+ return 'Your tool call could not be read by the provider (malformed function call). Call the tool again '
667
+ + `with valid JSON arguments, and keep them compact — ${split}${sent}`;
668
+ }
669
+ /**
670
+ * What a model on implicit control flow is told after writing JSON that could not be read. It
671
+ * names `complete_task` only when the agent declares it, and the envelope's step types only
672
+ * when the agent still has an envelope.
673
+ */
674
+ envelopeAttemptInstructions(completeTaskDeclared, nativeOnly) {
675
+ const finish = completeTaskDeclared
676
+ ? 'To finish, call complete_task with your answer in message and any payload writes in payloadChangeRequest.'
677
+ : 'To finish, reply with your answer in plain text, with no JSON around it.';
678
+ const json = nativeOnly
679
+ ? 'Act only through your tools; do not write JSON.'
680
+ : 'Write JSON only for the nextStep types listed in the response format.';
681
+ return `Your reply looks like a JSON response, but it could not be read and plain text ends the task. ${finish} ${json}`;
682
+ }
462
683
  async DetermineNextStep(promptResult, params, payload, agentTypeState, nativeToolBindings) {
463
684
  try {
464
685
  // A tool call the provider could not read (Gemini's MALFORMED_FUNCTION_CALL — usually an oversized
465
686
  // or broken argument object) comes back with NO toolCalls and only the narration that preceded
466
687
  // the call. Left alone, under implicit control flow that narration reads as a completion and
467
688
  // under the envelope as unparseable JSON; neither tells the model what went wrong. Say so.
468
- if (promptResult?.chatResult?.data?.choices?.[0]?.finish_reason === CHAT_FINISH_REASON_MALFORMED_TOOL_CALL) {
469
- return this.createRetryStep('Your tool call could not be read by the provider (malformed function call). Call the tool again ' +
470
- 'with valid JSON arguments, and keep them compact — write a large result to the payload in pieces ' +
471
- 'across several payload_change_request calls rather than one enormous call.');
689
+ const choice = promptResult?.chatResult?.data?.choices?.[0];
690
+ if (choice?.finish_reason === CHAT_FINISH_REASON_MALFORMED_TOOL_CALL || choice?.finish_reason === CHAT_FINISH_REASON_UNEXPECTED_TOOL_CALL) {
691
+ const implicit = TurnToolCallingMode(promptResult) === 'NativeImplicit';
692
+ return this.createRetryStep(this.rejectedToolCallInstructions(choice.finish_reason, choice.finishMessage, nativeToolBindings, implicit));
472
693
  }
473
694
  // Ensure we have a successful result
474
695
  if (!promptResult.success || !promptResult.result) {
@@ -482,7 +703,8 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
482
703
  // it reaches zero — the model answers through whichever channel it was given. So the
483
704
  // loop adopts the industry convention: a tool call means "continue", and anything else
484
705
  // means the model owes us an envelope.
485
- const nativeStep = this.nextStepFromNativeToolCalls(promptResult, nativeToolBindings);
706
+ const control = ResolveNativeControlConfig(params.agent?.TypeConfiguration).Config;
707
+ const nativeStep = this.nextStepFromNativeToolCalls(promptResult, nativeToolBindings, control.RelaxedTurnShapes);
486
708
  if (nativeStep) {
487
709
  return nativeStep;
488
710
  }
@@ -492,16 +714,14 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
492
714
  // Implicit control flow: plain text with no tool call IS the terminal
493
715
  // form. Only a turn the runner recorded as NativeImplicit reads this way — under the
494
716
  // hybrid and the envelope, prose is still the JSON-only Retry below.
495
- if (promptResult.promptRun?.ToolCallingMode === 'NativeImplicit') {
717
+ if (TurnToolCallingMode(promptResult) === 'NativeImplicit') {
496
718
  const text = typeof promptResult.result === 'string' ? promptResult.result.trim()
497
719
  : typeof promptResult.rawResult === 'string' ? promptResult.rawResult.trim() : '';
498
720
  if (this.looksLikeEnvelopeAttempt(text)) {
499
721
  // JSON the envelope parser could not read is an attempted structured answer, not
500
722
  // prose. Accepting it as the final answer would end the run with any payload it
501
723
  // carried silently dropped.
502
- return this.createRetryStep('Your reply looks like a JSON response, but it could not be read and plain text ends the task. ' +
503
- 'To finish, call complete_task with your answer in message and any payload writes in payloadChangeRequest. ' +
504
- 'Write JSON only for the nextStep types listed in the response format.');
724
+ return this.createRetryStep(this.envelopeAttemptInstructions(nativeToolBindings?.has(COMPLETE_TASK_TOOL) === true, control.NativeOnly));
505
725
  }
506
726
  if (text.length > 0) {
507
727
  LogStatusEx({ message: '✅ Loop Agent (implicit): plain-text completion. ' + text.slice(0, 120), verboseOnly: true });
@@ -571,6 +791,7 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
571
791
  terminate: true, // Chat always terminates to return to user
572
792
  decisions: response.decisions,
573
793
  payloadChangeRequest: response.payloadChangeRequest,
794
+ artifactDirective: response.artifactDirective,
574
795
  scratchpad: response.scratchpad,
575
796
  artifactToolCalls: response.artifactToolCalls,
576
797
  conversationToolCalls: response.conversationToolCalls,
@@ -602,6 +823,7 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
602
823
  confidence: response.confidence,
603
824
  decisions: response.decisions,
604
825
  payloadChangeRequest: response.payloadChangeRequest,
826
+ artifactDirective: response.artifactDirective,
605
827
  scratchpad: response.scratchpad,
606
828
  artifactToolCalls: response.artifactToolCalls,
607
829
  conversationToolCalls: response.conversationToolCalls,
@@ -619,6 +841,7 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
619
841
  const retVal = {
620
842
  decisions: response.decisions,
621
843
  payloadChangeRequest: response.payloadChangeRequest,
844
+ artifactDirective: response.artifactDirective,
622
845
  scratchpad: response.scratchpad,
623
846
  artifactToolCalls: response.artifactToolCalls,
624
847
  conversationToolCalls: response.conversationToolCalls,
@@ -830,6 +1053,7 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
830
1053
  }
831
1054
  else if (response.payloadChangeRequest?.newElements ||
832
1055
  response.payloadChangeRequest?.updateElements ||
1056
+ response.payloadChangeRequest?.replaceElements ||
833
1057
  response.payloadChangeRequest?.removeElements) {
834
1058
  // the AI forgot to mark taskComplete as true but provided a payloadChangeRequest
835
1059
  // with changes to the elements, so we can consider this a valid response