@memberjunction/ai-agents 6.2.0-edge.5 → 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 (106) hide show
  1. package/README.md +60 -0
  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 +55 -3
  7. package/dist/AgentRunner.d.ts.map +1 -1
  8. package/dist/AgentRunner.js +150 -30
  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 +1 -0
  15. package/dist/ArtifactToolManager.d.ts.map +1 -1
  16. package/dist/ArtifactToolManager.js +5 -0
  17. package/dist/ArtifactToolManager.js.map +1 -1
  18. package/dist/ConversationToolManager.d.ts +1 -1
  19. package/dist/ConversationToolManager.d.ts.map +1 -1
  20. package/dist/ConversationToolManager.js +10 -4
  21. package/dist/ConversationToolManager.js.map +1 -1
  22. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  23. package/dist/MJAIAgentRequestEntityServer.js +20 -0
  24. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  25. package/dist/agent-context-injector.d.ts +21 -4
  26. package/dist/agent-context-injector.d.ts.map +1 -1
  27. package/dist/agent-context-injector.js +49 -13
  28. package/dist/agent-context-injector.js.map +1 -1
  29. package/dist/agent-memory-context-builder.js +2 -2
  30. package/dist/agent-memory-context-builder.js.map +1 -1
  31. package/dist/agent-pre-execution-rag.js +5 -8
  32. package/dist/agent-pre-execution-rag.js.map +1 -1
  33. package/dist/agent-run-watchdog.d.ts +23 -8
  34. package/dist/agent-run-watchdog.d.ts.map +1 -1
  35. package/dist/agent-run-watchdog.js +141 -76
  36. package/dist/agent-run-watchdog.js.map +1 -1
  37. package/dist/agent-types/flow-agent-type.d.ts +7 -0
  38. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  39. package/dist/agent-types/flow-agent-type.js +95 -21
  40. package/dist/agent-types/flow-agent-type.js.map +1 -1
  41. package/dist/agent-types/loop-agent-prompt-params.d.ts +6 -2
  42. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  43. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  44. package/dist/agent-types/loop-agent-type.d.ts +76 -5
  45. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  46. package/dist/agent-types/loop-agent-type.js +230 -50
  47. package/dist/agent-types/loop-agent-type.js.map +1 -1
  48. package/dist/base-agent.d.ts +244 -10
  49. package/dist/base-agent.d.ts.map +1 -1
  50. package/dist/base-agent.js +1019 -193
  51. package/dist/base-agent.js.map +1 -1
  52. package/dist/bound-action-params.d.ts +57 -0
  53. package/dist/bound-action-params.d.ts.map +1 -0
  54. package/dist/bound-action-params.js +91 -0
  55. package/dist/bound-action-params.js.map +1 -0
  56. package/dist/index.d.ts +5 -0
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +5 -0
  59. package/dist/index.js.map +1 -1
  60. package/dist/memory-cleanup-agent.d.ts.map +1 -1
  61. package/dist/memory-cleanup-agent.js +3 -0
  62. package/dist/memory-cleanup-agent.js.map +1 -1
  63. package/dist/memory-manager-agent.d.ts.map +1 -1
  64. package/dist/memory-manager-agent.js +6 -1
  65. package/dist/memory-manager-agent.js.map +1 -1
  66. package/dist/native-tools/agent-tools.d.ts +64 -0
  67. package/dist/native-tools/agent-tools.d.ts.map +1 -0
  68. package/dist/native-tools/agent-tools.js +23 -0
  69. package/dist/native-tools/agent-tools.js.map +1 -0
  70. package/dist/native-tools/control-tools.d.ts +26 -4
  71. package/dist/native-tools/control-tools.d.ts.map +1 -1
  72. package/dist/native-tools/control-tools.js +114 -42
  73. package/dist/native-tools/control-tools.js.map +1 -1
  74. package/dist/native-tools/framework-tools.d.ts +47 -0
  75. package/dist/native-tools/framework-tools.d.ts.map +1 -0
  76. package/dist/native-tools/framework-tools.js +187 -0
  77. package/dist/native-tools/framework-tools.js.map +1 -0
  78. package/dist/native-tools/native-control-config.d.ts +93 -0
  79. package/dist/native-tools/native-control-config.d.ts.map +1 -0
  80. package/dist/native-tools/native-control-config.js +104 -0
  81. package/dist/native-tools/native-control-config.js.map +1 -0
  82. package/dist/native-tools/tool-result-turns.d.ts +41 -8
  83. package/dist/native-tools/tool-result-turns.d.ts.map +1 -1
  84. package/dist/native-tools/tool-result-turns.js +76 -2
  85. package/dist/native-tools/tool-result-turns.js.map +1 -1
  86. package/dist/native-tools/turn-mode.d.ts +8 -0
  87. package/dist/native-tools/turn-mode.d.ts.map +1 -0
  88. package/dist/native-tools/turn-mode.js +14 -0
  89. package/dist/native-tools/turn-mode.js.map +1 -0
  90. package/dist/query-builder-agent.d.ts +20 -1
  91. package/dist/query-builder-agent.d.ts.map +1 -1
  92. package/dist/query-builder-agent.js +35 -3
  93. package/dist/query-builder-agent.js.map +1 -1
  94. package/dist/realtime/bridge-room-transcript-sink.js +1 -0
  95. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  96. package/dist/realtime/bridge-session-transcript-sink.js +1 -0
  97. package/dist/realtime/bridge-session-transcript-sink.js.map +1 -1
  98. package/dist/realtime/realtime-recording-ledger.d.ts +20 -0
  99. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -1
  100. package/dist/realtime/realtime-recording-ledger.js +16 -0
  101. package/dist/realtime/realtime-recording-ledger.js.map +1 -1
  102. package/dist/realtime/realtime-recording-store.d.ts +6 -5
  103. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  104. package/dist/realtime/realtime-recording-store.js +47 -21
  105. package/dist/realtime/realtime-recording-store.js.map +1 -1
  106. package/package.json +20 -20
@@ -10,7 +10,7 @@
10
10
  * @since 2.49.0
11
11
  */
12
12
  import { BaseAgentType } from './base-agent-type.js';
13
- import type { NativeToolBinding } from '../native-tools/control-tools.js';
13
+ import { type NativeToolBinding } from '../native-tools/control-tools.js';
14
14
  import { AIPromptRunResult, BaseAgentNextStep, AIPromptParams, ExecuteAgentParams, AgentConfiguration, AgentAction } from '@memberjunction/ai-core-plus';
15
15
  import { MJAIPromptEntityExtended } from '@memberjunction/ai-core-plus';
16
16
  export declare class LoopAgentType extends BaseAgentType {
@@ -95,12 +95,71 @@ export declare class LoopAgentType extends BaseAgentType {
95
95
  * documented to do this, measured at roughly one forced call in six, so the loop
96
96
  * has to be able to say "that tool does not exist" rather than appear to hang.
97
97
  */
98
- protected nextStepFromNativeToolCalls(promptResult: AIPromptRunResult, bindings?: ReadonlyMap<string, NativeToolBinding>): BaseAgentNextStep | null;
98
+ protected nextStepFromNativeToolCalls(promptResult: AIPromptRunResult, bindings?: ReadonlyMap<string, NativeToolBinding>, relaxedTurnShapes?: boolean): BaseAgentNextStep | null;
99
+ /**
100
+ * Whether a binding runs on a hybrid turn. Actions and the agent's own tools run in every native
101
+ * mode; control tools — and the framework tools, which are declared as control tools — are
102
+ * stripped from a hybrid request, so a call to one there is a call to an undeclared tool.
103
+ */
104
+ private dispatchableOnHybrid;
105
+ /** What to do instead, after a call to a tool that does not exist on this turn. */
106
+ private unknownToolAdvice;
99
107
  /** Pairs each call with its binding; a control-tool binding counts only under implicit control flow. */
100
108
  private resolveNativeCalls;
101
- /** The turn-reading table of spec §2.1, one row per branch. */
102
- private routeResolvedCalls;
103
- /** `ask_user` ends the run as Chat / AwaitingFeedback; it must travel alone and carry a message. */
109
+ /**
110
+ * The turn-reading table of spec §2.1, with each control call alone on its turn — the default.
111
+ *
112
+ * `ask_user` and `complete_task` must be the only call on their turn, at most one
113
+ * `payload_change_request` is allowed, and acting and delegating cannot share a turn; each of
114
+ * these is a Retry that runs nothing. The agent's own tools ride along with Actions or a
115
+ * delegation, and alone are a turn of their own.
116
+ *
117
+ * @param completeTaskDeclared Whether the agent declares `complete_task`; a text-terminal agent
118
+ * does not, and is told to finish in plain text instead.
119
+ */
120
+ private routeStrict;
121
+ /**
122
+ * The turn-reading table with relaxed turn shapes (`NativeControl.RelaxedTurnShapes`): every
123
+ * call on the turn is honoured where the loop can do so without skipping a check.
124
+ * - Writes — the agent's own tools and `payload_change_request` — run inline, in call order,
125
+ * and are answered one by one. A single payload change keeps the step's own payload channel.
126
+ * - `ask_user` or `complete_task` after writes: the writes run, then the turn asks or completes
127
+ * through the normal Chat or Success validation. A failed write declines it (see BaseAgent).
128
+ * - Actions with a delegation, `ask_user` or `complete_task`: the Actions run, and the other
129
+ * calls are answered as not run — they were made before the Actions' results existed, and
130
+ * running them afterwards would skip the validation a turn's own decision gets.
131
+ *
132
+ * @param completeTaskDeclared Whether the agent declares `complete_task`; a text-terminal agent
133
+ * does not, and is told to finish in plain text instead.
134
+ */
135
+ private routeRelaxed;
136
+ /** The turn's calls by kind; `writes` holds agent-tool and payload calls in the order the model made them. */
137
+ private groupResolvedCalls;
138
+ /**
139
+ * The step for every non-terminal call on the turn, or undefined when there are none.
140
+ *
141
+ * One `payload_change_request` on a turn with no terminal call rides on the step's own payload
142
+ * channel, as it always has. Several — or one beside `ask_user` / `complete_task`, whose step
143
+ * cannot answer it — run with the agent's tools as ordered writes, each answered by its result.
144
+ */
145
+ private workStep;
146
+ /** Whether a step only writes — runs inline in the prompt step, with nothing executed after it. */
147
+ private isWritesOnly;
148
+ /** `ask_user` with the turn's other calls: after writes it asks; beside Actions or delegations it is declined. */
149
+ private withAskUser;
150
+ /** Adds one declined call to a step's list. */
151
+ private withDeclined;
152
+ /** `complete_task` with the turn's other calls — see {@link routeRelaxed} for when it runs. */
153
+ private withCompleteTask;
154
+ /** The turn's write calls, in call order, as the step carries them — or nothing when there are none. */
155
+ private agentToolCallRequests;
156
+ /**
157
+ * Agent-tool calls with no Action or delegation: the loop runs them, answers each call with its
158
+ * result, and goes again. A Retry with no instructions, so nothing but the results is added —
159
+ * the same non-terminal "go again" the payload-only turn uses.
160
+ */
161
+ private agentToolsStep;
162
+ /** `ask_user` ends the run as Chat / AwaitingFeedback; it must carry a message. */
104
163
  private askUserStep;
105
164
  /**
106
165
  * `complete_task` → Success, carrying its payload change — the native twin of the envelope's
@@ -133,6 +192,18 @@ export declare class LoopAgentType extends BaseAgentType {
133
192
  * (Pipeline uses it the same way); the instructions are what the loop shows the model.
134
193
  */
135
194
  private payloadOnlyStep;
195
+ /**
196
+ * What the model is told after a tool call the provider rejected — one it could not read, or one
197
+ * to a tool this turn did not offer — with the provider's description of the call, when it gave
198
+ * one, so the model can see what it sent.
199
+ */
200
+ private rejectedToolCallInstructions;
201
+ /**
202
+ * What a model on implicit control flow is told after writing JSON that could not be read. It
203
+ * names `complete_task` only when the agent declares it, and the envelope's step types only
204
+ * when the agent still has an envelope.
205
+ */
206
+ private envelopeAttemptInstructions;
136
207
  DetermineNextStep<P = any, ATS = any>(promptResult: AIPromptRunResult | null, params: ExecuteAgentParams<any, P>, payload: P, agentTypeState: ATS, nativeToolBindings?: ReadonlyMap<string, NativeToolBinding>): Promise<BaseAgentNextStep<P>>;
137
208
  /** Whether the response requests an Actions or Sub-Agent step that carries a valid finishIf. */
138
209
  private isGatedStep;
@@ -1 +1 @@
1
- {"version":3,"file":"loop-agent-type.d.ts","sourceRoot":"","sources":["../../src/agent-types/loop-agent-type.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAMvE,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,cAAc,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,WAAW,EAElE,MAAM,8BAA8B,CAAC;AAErF,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAqDxE,qBACa,aAAc,S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CAAC,iBAAiB,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAK/G;;;;;;;;;;;OAWG;IACU,kBAAkB,CAAC,CAAC,GAAG,GAAG,EAAE,GAAG,GAAG,GAAG,EAC9C,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAAC,EAC7B,IAAI,EAAE,iBAAiB,CAAC,CAAC,CAAC,EAC1B,OAAO,EAAE,CAAC,EACV,cAAc,EAAE,GAAG,GACpB,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAKvC;;;;;;;;;;;OAWG;IACU,gBAAgB,CAAC,CAAC,GAAG,GAAG,EAAE,GAAG,GAAG,GAAG,EAC5C,MAAM,EAAE,kBAAkB,EAC1B,MAAM,EAAE,kBAAkB,EAC1B,OAAO,EAAE,CAAC,EACV,cAAc,EAAE,GAAG,EACnB,gBAAgB,CAAC,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,IAAI,GAC/C,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC;IAK3C;;;;;;;;;;;;;;;;;OAiBG;IACU,oBAAoB,CAAC,CAAC,GAAG,GAAG,EAAE,GAAG,GAAG,GAAG,EAChD,OAAO,EAAE,WAAW,EAAE,EACtB,cAAc,EAAE,CAAC,EACjB,cAAc,EAAE,GAAG,EACnB,WAAW,EAAE,iBAAiB,CAAC,CAAC,CAAC,EACjC,MAAM,CAAC,EAAE,kBAAkB,CAAC,CAAC,CAAC,GAC/B,OAAO,CAAC,IAAI,CAAC;IAShB;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,6BAA6B;CAyBxC"}
@@ -15,11 +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';
22
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';
23
27
  import { GetToolCallingDecision } from '@memberjunction/ai-prompts';
24
28
  import { FormatValidationErrors, ValidateTaskGraphSpec, ConfigOf } from '@memberjunction/ai-core-plus';
25
29
  import { LogError, LogStatusEx } from '@memberjunction/core';
@@ -294,7 +298,7 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
294
298
  * documented to do this, measured at roughly one forced call in six, so the loop
295
299
  * has to be able to say "that tool does not exist" rather than appear to hang.
296
300
  */
297
- nextStepFromNativeToolCalls(promptResult, bindings) {
301
+ nextStepFromNativeToolCalls(promptResult, bindings, relaxedTurnShapes = false) {
298
302
  const calls = promptResult.chatResult?.data?.choices?.[0]?.message?.toolCalls;
299
303
  if (!calls?.length) {
300
304
  return null;
@@ -307,21 +311,41 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
307
311
  // Control tools are dispatchable ONLY on a turn the runner recorded as NativeImplicit
308
312
  // under the hybrid they are stripped from the request, so a call to one
309
313
  // is a call to an undeclared tool, whatever the binding map says.
310
- const implicit = promptResult.promptRun?.ToolCallingMode === 'NativeImplicit';
314
+ const implicit = TurnToolCallingMode(promptResult) === 'NativeImplicit';
311
315
  // The model's own turn travels on the step so the loop can replay it into history and
312
316
  // answer each call natively when the runner's decision says so.
313
317
  const message = promptResult.chatResult?.data?.choices?.[0]?.message;
314
318
  const nativeTurn = {
315
319
  text: typeof message?.content === 'string' ? message.content : '',
316
320
  toolCalls: calls,
317
- sendResultsNatively: GetToolCallingDecision(promptResult.chatResult)?.toolResults === true
321
+ sendResultsNatively: GetToolCallingDecision(promptResult.chatResult)?.toolResults === true,
322
+ ...(message?.reasoning?.length ? { reasoning: message.reasoning } : {})
318
323
  };
319
324
  const { resolved, unknown } = this.resolveNativeCalls(calls, bindings, implicit);
320
325
  if (unknown.length > 0) {
321
326
  return this.createRetryStep(`You called ${unknown.map((c) => `'${c.name}'`).join(', ')}, which ${unknown.length === 1 ? 'is not a tool' : 'are not tools'} `
322
- + `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 });
323
328
  }
324
- return { ...this.routeResolvedCalls(resolved), nativeTurn };
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.';
345
+ }
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.';
325
349
  }
326
350
  /** Pairs each call with its binding; a control-tool binding counts only under implicit control flow. */
327
351
  resolveNativeCalls(calls, bindings, implicit) {
@@ -329,7 +353,7 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
329
353
  const unknown = [];
330
354
  for (const call of calls) {
331
355
  const binding = bindings.get(call.name);
332
- if (binding && (binding.kind === 'action' || implicit)) {
356
+ if (binding && (implicit || this.dispatchableOnHybrid(binding))) {
333
357
  resolved.push({ call, binding });
334
358
  }
335
359
  else {
@@ -338,44 +362,167 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
338
362
  }
339
363
  return { resolved, unknown };
340
364
  }
341
- /** The turn-reading table of spec §2.1, one row per branch. */
342
- routeResolvedCalls(resolved) {
343
- const ofKind = (kind) => resolved.filter((r) => r.binding.kind === kind);
344
- const askUser = ofKind('askUser');
345
- const subAgents = ofKind('subAgent');
346
- const actions = ofKind('action');
347
- const payloads = ofKind('payloadChange');
348
- if (askUser.length > 0) {
349
- 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]);
350
382
  }
351
- const completes = ofKind('complete');
352
- if (completes.length > 0) {
353
- 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]);
354
387
  }
355
- if (payloads.length > 1) {
388
+ if (calls.payloads.length > 1) {
356
389
  return this.createRetryStep('Call payload_change_request at most once per turn; combine your changes into one call.');
357
390
  }
358
- const payloadChangeRequest = payloads[0]?.call.arguments;
359
- // The payload call's id has to travel with every step that carries the change, not just the
360
- // payload-only one: whichever branch applies it also has to answer that call, or the model
361
- // is left with a tool_use nothing responded to.
362
- const payloadToolCallId = payloads[0]?.call.id;
363
- if (subAgents.length > 0 && actions.length > 0) {
391
+ if (calls.subAgents.length > 0 && calls.actions.length > 0) {
364
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.');
365
393
  }
366
- if (subAgents.length > 0) {
367
- 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);
419
+ }
420
+ if (calls.complete.length > 0) {
421
+ return this.withCompleteTask(calls.complete[0], work);
422
+ }
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
+ };
437
+ }
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 };
368
462
  }
369
- if (actions.length > 0) {
370
- return this.actionsStep(actions, payloadChangeRequest, payloadToolCallId);
463
+ if (writes.agentToolCalls) {
464
+ return this.agentToolsStep(writes.agentToolCalls, payloadChangeRequest, payloadToolCallId);
371
465
  }
372
- return this.payloadOnlyStep(payloadChangeRequest, payloadToolCallId);
466
+ return payloadChangeRequest ? this.payloadOnlyStep(payloadChangeRequest, payloadToolCallId, completeTaskDeclared) : undefined;
373
467
  }
374
- /** `ask_user` ends the run as Chat / AwaitingFeedback; it must travel alone and carry a message. */
375
- askUserStep(ask, totalCalls) {
376
- if (totalCalls > 1) {
377
- 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.');
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 };
378
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 {};
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) {
379
526
  const message = typeof ask.call.arguments?.message === 'string' ? ask.call.arguments.message.trim() : '';
380
527
  if (!message) {
381
528
  return this.createRetryStep('ask_user requires a message — the question or request for the user.');
@@ -399,10 +546,7 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
399
546
  * the loop answers this call with the validation feedback, exactly as it answers a
400
547
  * payload-only turn.
401
548
  */
402
- completeTaskStep(complete, totalCalls) {
403
- if (totalCalls > 1) {
404
- 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.');
405
- }
549
+ completeTaskStep(complete) {
406
550
  const message = typeof complete.call.arguments?.message === 'string' ? complete.call.arguments.message.trim() : '';
407
551
  const decoded = this.decodePayloadChangeArgument(complete.call.arguments?.payloadChangeRequest);
408
552
  if ('error' in decoded) {
@@ -490,25 +634,62 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
490
634
  * `payload_change_request` alone: apply and continue. Retry is the non-terminal "go again" step
491
635
  * (Pipeline uses it the same way); the instructions are what the loop shows the model.
492
636
  */
493
- payloadOnlyStep(payloadChangeRequest, payloadToolCallId) {
637
+ payloadOnlyStep(payloadChangeRequest, payloadToolCallId, completeTaskDeclared) {
638
+ const finish = completeTaskDeclared ? 'call complete_task' : 'reply in plain text';
494
639
  return this.createNextStep('Retry', {
495
640
  terminate: false,
496
641
  payloadChangeRequest,
497
642
  payloadToolCallId,
498
643
  retryReason: 'Payload change applied',
499
- 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.`
500
645
  });
501
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
+ }
502
683
  async DetermineNextStep(promptResult, params, payload, agentTypeState, nativeToolBindings) {
503
684
  try {
504
685
  // A tool call the provider could not read (Gemini's MALFORMED_FUNCTION_CALL — usually an oversized
505
686
  // or broken argument object) comes back with NO toolCalls and only the narration that preceded
506
687
  // the call. Left alone, under implicit control flow that narration reads as a completion and
507
688
  // under the envelope as unparseable JSON; neither tells the model what went wrong. Say so.
508
- if (promptResult?.chatResult?.data?.choices?.[0]?.finish_reason === CHAT_FINISH_REASON_MALFORMED_TOOL_CALL) {
509
- return this.createRetryStep('Your tool call could not be read by the provider (malformed function call). Call the tool again ' +
510
- 'with valid JSON arguments, and keep them compact — write a large result to the payload in pieces ' +
511
- '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));
512
693
  }
513
694
  // Ensure we have a successful result
514
695
  if (!promptResult.success || !promptResult.result) {
@@ -522,7 +703,8 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
522
703
  // it reaches zero — the model answers through whichever channel it was given. So the
523
704
  // loop adopts the industry convention: a tool call means "continue", and anything else
524
705
  // means the model owes us an envelope.
525
- const nativeStep = this.nextStepFromNativeToolCalls(promptResult, nativeToolBindings);
706
+ const control = ResolveNativeControlConfig(params.agent?.TypeConfiguration).Config;
707
+ const nativeStep = this.nextStepFromNativeToolCalls(promptResult, nativeToolBindings, control.RelaxedTurnShapes);
526
708
  if (nativeStep) {
527
709
  return nativeStep;
528
710
  }
@@ -532,16 +714,14 @@ let LoopAgentType = class LoopAgentType extends BaseAgentType {
532
714
  // Implicit control flow: plain text with no tool call IS the terminal
533
715
  // form. Only a turn the runner recorded as NativeImplicit reads this way — under the
534
716
  // hybrid and the envelope, prose is still the JSON-only Retry below.
535
- if (promptResult.promptRun?.ToolCallingMode === 'NativeImplicit') {
717
+ if (TurnToolCallingMode(promptResult) === 'NativeImplicit') {
536
718
  const text = typeof promptResult.result === 'string' ? promptResult.result.trim()
537
719
  : typeof promptResult.rawResult === 'string' ? promptResult.rawResult.trim() : '';
538
720
  if (this.looksLikeEnvelopeAttempt(text)) {
539
721
  // JSON the envelope parser could not read is an attempted structured answer, not
540
722
  // prose. Accepting it as the final answer would end the run with any payload it
541
723
  // carried silently dropped.
542
- return this.createRetryStep('Your reply looks like a JSON response, but it could not be read and plain text ends the task. ' +
543
- 'To finish, call complete_task with your answer in message and any payload writes in payloadChangeRequest. ' +
544
- '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));
545
725
  }
546
726
  if (text.length > 0) {
547
727
  LogStatusEx({ message: '✅ Loop Agent (implicit): plain-text completion. ' + text.slice(0, 120), verboseOnly: true });