@noetic-tools/core 5.19.1 → 5.19.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/dist/adapters/openrouter.js +5 -0
  2. package/dist/builders/control-flow-builders.d.ts +15 -6
  3. package/dist/builders/control-flow-builders.js +8 -0
  4. package/dist/builders/decide-builders.d.ts +2 -5
  5. package/dist/builders/dynamic-workflow.d.ts +54 -2
  6. package/dist/builders/dynamic-workflow.js +247 -12
  7. package/dist/builders/every.d.ts +3 -3
  8. package/dist/builders/every.js +2 -1
  9. package/dist/builders/mcp-url-pattern.d.ts +13 -0
  10. package/dist/builders/mcp-url-pattern.js +85 -0
  11. package/dist/builders/provide-builder.d.ts +3 -2
  12. package/dist/builders/provide-builder.js +2 -1
  13. package/dist/builders/sequence.d.ts +14 -0
  14. package/dist/builders/sequence.js +103 -0
  15. package/dist/builders/spawn-builder.d.ts +3 -2
  16. package/dist/builders/spawn-builder.js +3 -2
  17. package/dist/builders/step-builders.d.ts +80 -1
  18. package/dist/builders/step-builders.js +115 -1
  19. package/dist/builders/verify-builder.d.ts +79 -0
  20. package/dist/builders/verify-builder.js +69 -0
  21. package/dist/builders/workflow-acp-grants.d.ts +42 -0
  22. package/dist/builders/workflow-acp-grants.js +224 -0
  23. package/dist/builders/workflow-child-nodes.d.ts +21 -0
  24. package/dist/builders/workflow-child-nodes.js +336 -0
  25. package/dist/builders/workflow-connection-nodes.d.ts +25 -0
  26. package/dist/builders/workflow-connection-nodes.js +198 -0
  27. package/dist/builders/workflow-connections.d.ts +90 -0
  28. package/dist/builders/workflow-connections.js +560 -0
  29. package/dist/builders/workflow-control-nodes.d.ts +13 -0
  30. package/dist/builders/workflow-control-nodes.js +213 -0
  31. package/dist/builders/workflow-hydrator.d.ts +56 -3
  32. package/dist/builders/workflow-hydrator.js +53 -520
  33. package/dist/builders/workflow-mcp-servers.d.ts +24 -0
  34. package/dist/builders/workflow-mcp-servers.js +220 -0
  35. package/dist/builders/workflow-verify.d.ts +19 -0
  36. package/dist/builders/workflow-verify.js +194 -0
  37. package/dist/conditions/conditions.d.ts +7 -5
  38. package/dist/conditions/conditions.js +7 -4
  39. package/dist/connections/blobs.d.ts +33 -0
  40. package/dist/connections/blobs.js +77 -0
  41. package/dist/connections/cron-schedule.d.ts +32 -0
  42. package/dist/connections/cron-schedule.js +213 -0
  43. package/dist/connections/durability.d.ts +65 -0
  44. package/dist/connections/durability.js +54 -0
  45. package/dist/connections/errors.d.ts +30 -0
  46. package/dist/connections/errors.js +100 -0
  47. package/dist/connections/event-stream.d.ts +24 -0
  48. package/dist/connections/event-stream.js +176 -0
  49. package/dist/connections/gates.d.ts +94 -0
  50. package/dist/connections/gates.js +271 -0
  51. package/dist/connections/glob.d.ts +10 -0
  52. package/dist/connections/glob.js +46 -0
  53. package/dist/connections/handle.d.ts +22 -0
  54. package/dist/connections/handle.js +84 -0
  55. package/dist/connections/harness-wiring.d.ts +52 -0
  56. package/dist/connections/harness-wiring.js +143 -0
  57. package/dist/connections/in-memory-connection.d.ts +147 -0
  58. package/dist/connections/in-memory-connection.js +593 -0
  59. package/dist/connections/index.d.ts +34 -0
  60. package/dist/connections/index.js +23 -0
  61. package/dist/connections/json-schema.d.ts +28 -0
  62. package/dist/connections/json-schema.js +338 -0
  63. package/dist/connections/model-tools.d.ts +46 -0
  64. package/dist/connections/model-tools.js +466 -0
  65. package/dist/connections/negotiation.d.ts +30 -0
  66. package/dist/connections/negotiation.js +159 -0
  67. package/dist/connections/policy.d.ts +21 -0
  68. package/dist/connections/policy.js +34 -0
  69. package/dist/connections/pool.d.ts +111 -0
  70. package/dist/connections/pool.js +339 -0
  71. package/dist/connections/refs.d.ts +74 -0
  72. package/dist/connections/refs.js +316 -0
  73. package/dist/connections/registry-types.d.ts +141 -0
  74. package/dist/connections/registry-types.js +14 -0
  75. package/dist/connections/registry.d.ts +125 -0
  76. package/dist/connections/registry.js +775 -0
  77. package/dist/connections/secrets.d.ts +59 -0
  78. package/dist/connections/secrets.js +153 -0
  79. package/dist/connections/settle.d.ts +9 -0
  80. package/dist/connections/settle.js +26 -0
  81. package/dist/connections/sources.d.ts +27 -0
  82. package/dist/connections/sources.js +300 -0
  83. package/dist/connections/triggers.d.ts +78 -0
  84. package/dist/connections/triggers.js +310 -0
  85. package/dist/connections/values.d.ts +26 -0
  86. package/dist/connections/values.js +93 -0
  87. package/dist/connections/views.d.ts +31 -0
  88. package/dist/connections/views.js +176 -0
  89. package/dist/expression/check.js +80 -1
  90. package/dist/expression/jsonata.d.ts +14 -4
  91. package/dist/expression/jsonata.js +27 -9
  92. package/dist/expression/step-outputs.d.ts +25 -0
  93. package/dist/expression/step-outputs.js +78 -0
  94. package/dist/harness/agent-harness.d.ts +69 -166
  95. package/dist/harness/agent-harness.js +170 -262
  96. package/dist/harness/call-span-collector.d.ts +33 -0
  97. package/dist/harness/call-span-collector.js +83 -0
  98. package/dist/harness/connection-gate.d.ts +78 -0
  99. package/dist/harness/connection-gate.js +170 -0
  100. package/dist/harness/deps/interpreter.d.ts +1 -0
  101. package/dist/harness/deps/interpreter.js +1 -0
  102. package/dist/harness/deps/runtime.d.ts +1 -1
  103. package/dist/harness/deps/types.d.ts +1 -1
  104. package/dist/harness/harness-options.d.ts +153 -0
  105. package/dist/harness/harness-options.js +36 -0
  106. package/dist/harness/harness-tracing.d.ts +16 -0
  107. package/dist/harness/harness-tracing.js +35 -0
  108. package/dist/harness/llm-client.d.ts +71 -0
  109. package/dist/harness/llm-client.js +218 -0
  110. package/dist/harness/model-call.d.ts +2 -7
  111. package/dist/harness/model-call.js +21 -549
  112. package/dist/harness/model-request.d.ts +42 -0
  113. package/dist/harness/model-request.js +159 -0
  114. package/dist/harness/model-stream.d.ts +39 -0
  115. package/dist/harness/model-stream.js +131 -0
  116. package/dist/harness/model-tool-round.d.ts +37 -0
  117. package/dist/harness/model-tool-round.js +197 -0
  118. package/dist/harness/spend.d.ts +2 -0
  119. package/dist/harness/spend.js +5 -1
  120. package/dist/index.d.ts +33 -8
  121. package/dist/index.js +18 -1
  122. package/dist/interpreter/connection-steps.d.ts +194 -0
  123. package/dist/interpreter/connection-steps.js +537 -0
  124. package/dist/interpreter/execute-action.d.ts +2 -8
  125. package/dist/interpreter/execute-action.js +3 -178
  126. package/dist/interpreter/execute-call.d.ts +19 -0
  127. package/dist/interpreter/execute-call.js +99 -0
  128. package/dist/interpreter/execute-control.d.ts +6 -1
  129. package/dist/interpreter/execute-control.js +14 -0
  130. package/dist/interpreter/execute-invoke-tool.d.ts +11 -0
  131. package/dist/interpreter/execute-invoke-tool.js +183 -0
  132. package/dist/interpreter/execute-verify.d.ts +21 -0
  133. package/dist/interpreter/execute-verify.js +391 -0
  134. package/dist/interpreter/execute-wait.d.ts +21 -0
  135. package/dist/interpreter/execute-wait.js +233 -0
  136. package/dist/interpreter/execute.js +24 -133
  137. package/dist/interpreter/step-kind-dispatch.d.ts +24 -0
  138. package/dist/interpreter/step-kind-dispatch.js +157 -0
  139. package/dist/interpreter/step-walk.d.ts +2 -0
  140. package/dist/interpreter/step-walk.js +24 -0
  141. package/dist/interpreter/verify-host.d.ts +40 -0
  142. package/dist/interpreter/verify-host.js +245 -0
  143. package/dist/runtime/durable/step-ledger.d.ts +31 -1
  144. package/dist/runtime/durable/step-ledger.js +87 -1
  145. package/dist/runtime/in-memory-artifact-store.d.ts +24 -0
  146. package/dist/runtime/in-memory-artifact-store.js +240 -0
  147. package/dist/schemas/workflow.d.ts +2 -2
  148. package/dist/schemas/workflow.js +1 -1
  149. package/dist/util/harness-internals.d.ts +25 -0
  150. package/dist/util/harness-internals.js +35 -0
  151. package/package.json +3 -3
  152. package/schema/noetic-workflow.schema.json +1309 -180
@@ -1,95 +1,19 @@
1
- import { frameworkCast, NoeticConfigError, SpendKind, SteerPoint, ToolChoiceMode, } from '@noetic-tools/types';
2
- import { serverTool } from '@openrouter/agent';
3
- import { convertTools, executeToolCall, extractOutputItems, extractSystemInstruction, extractUsage, itemsToInput, resolveWireJsonSchema, sanitizeToolNameForWire, toolsOnWire, } from '../adapters/openrouter.js';
4
- import { isFunctionCall } from '../interpreter/typeguards.js';
5
- import { GenAI, NoeticAttr, ToolAttr } from '../observability/genai-attributes.js';
6
- import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
1
+ import { frameworkCast, NoeticConfigError, SpendKind, SteerPoint } from '@noetic-tools/types';
2
+ import { extractOutputItems, extractUsage, itemsToInput, toolsOnWire, } from '../adapters/openrouter.js';
3
+ import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
7
4
  import { drainsOf } from '../runtime/drain.js';
8
5
  import { markSpent } from '../util/spent.js';
9
- import { isErrorStatus } from '../util/status-code.js';
6
+ import { CallSpanCollector } from './call-span-collector.js';
10
7
  import { CallSpend, noBill } from './call-spend.js';
11
- import { exportSpans } from './deps/context.js';
8
+ import { buildTextFormat, prepareModelRequest } from './model-request.js';
12
9
  import { RoundLedger } from './model-rounds.js';
13
- import { buildItemSchemaRegistry, createToolResultItem } from './model-schema.js';
10
+ import { buildItemSchemaRegistry } from './model-schema.js';
11
+ import { awaitWithAbort, hasUsableResponseOutput, noteStreamGeneration, pipeStreamEventsToBroadcaster, providerTerminalError, } from './model-stream.js';
12
+ import { hasFunctionCalls, replayOutput, runToolRound } from './model-tool-round.js';
14
13
  import { openSteerInbox } from './steer-inbox.js';
15
14
  const MAX_TOOL_ROUNDS = 32;
16
15
  const MAX_RECOVERY_CONTINUATIONS = 3;
17
16
  const EPHEMERAL_CONTINUE_INPUT = 'continue';
18
- const SKIPPED_FOR_STEER_OUTPUT = 'Skipped: a new message arrived before this tool call ran.';
19
- function buildTextFormat(schema, explicitJsonSchema) {
20
- const jsonSchema = resolveWireJsonSchema({
21
- schema,
22
- explicitJsonSchema,
23
- what: 'structured output schema',
24
- });
25
- return {
26
- format: {
27
- type: 'json_schema',
28
- name: 'output',
29
- schema: jsonSchema,
30
- },
31
- };
32
- }
33
- function isStreamRecord(value) {
34
- return typeof value === 'object' && value !== null;
35
- }
36
- function providerTerminalError(response) {
37
- if (!isStreamRecord(response) || response.status === undefined) {
38
- return null;
39
- }
40
- const status = String(response.status);
41
- if (status === 'completed') {
42
- return null;
43
- }
44
- if (status === 'incomplete') {
45
- const details = response.incompleteDetails;
46
- const reason = isStreamRecord(details) && typeof details.reason === 'string' ? `: ${details.reason}` : '';
47
- return {
48
- status,
49
- message: `LLM response incomplete${reason}`,
50
- };
51
- }
52
- if (status === 'failed') {
53
- const error = response.error;
54
- const message = isStreamRecord(error) && typeof error.message === 'string' ? `: ${error.message}` : '';
55
- return {
56
- status,
57
- message: `LLM response failed${message}`,
58
- };
59
- }
60
- return {
61
- status,
62
- message: `LLM response ended with status '${status}'`,
63
- };
64
- }
65
- /**
66
- * Tool rounds replay only their function calls. A round a steer follows must
67
- * also replay what the model said, or the next round starts without it.
68
- * Function calls are left to the tool round, which adds each with its output.
69
- */
70
- function replayOutput(input, roundItems) {
71
- input.push(...itemsToInput(roundItems.filter((item) => !isFunctionCall(item))));
72
- }
73
- /**
74
- * Save the generation id a stream's `response.created` event carries, for a response
75
- * whose headers did not. OpenRouter's ids start `gen-`; other ids price nothing.
76
- */
77
- function noteStreamGeneration(dispatch, event) {
78
- if (!dispatch || !isStreamRecord(event) || event.type !== 'response.created') {
79
- return;
80
- }
81
- const response = event.response;
82
- if (!isStreamRecord(response) || typeof response.id !== 'string') {
83
- return;
84
- }
85
- if (response.id.startsWith('gen-')) {
86
- void dispatch.noteGeneration(response.id);
87
- }
88
- }
89
- /** The provider refused the call before generating anything, so nothing was billed. */
90
- function wasRefused(err, dispatch) {
91
- return isErrorStatus(err) && dispatch.record.generationId === undefined;
92
- }
93
17
  function itemIds(items) {
94
18
  return items.flatMap((item) => 'id' in item && typeof item.id === 'string'
95
19
  ? [
@@ -100,14 +24,6 @@ function itemIds(items) {
100
24
  function hasItem(items, id) {
101
25
  return items.some((item) => 'id' in item && item.id === id);
102
26
  }
103
- function hasUsableResponseOutput(response, items) {
104
- if (items.length > 0) {
105
- return true;
106
- }
107
- return (isStreamRecord(response) &&
108
- typeof response.outputText === 'string' &&
109
- response.outputText.length > 0);
110
- }
111
27
  function withEphemeralContinueInput(input) {
112
28
  return [
113
29
  ...frameworkCast(input),
@@ -118,74 +34,6 @@ function withEphemeralContinueInput(input) {
118
34
  }),
119
35
  ];
120
36
  }
121
- /** Race a promise against an AbortSignal so callers (e.g. `SessionRunner.abort`)
122
- * can break out of a long `await` without waiting for the underlying call to
123
- * settle. When the signal fires, the returned promise rejects with
124
- * `signal.reason` (an `Error`) or a generic `Error('aborted')` fallback. */
125
- function awaitWithAbort(p, signal) {
126
- if (!signal) {
127
- return p;
128
- }
129
- if (signal.aborted) {
130
- return Promise.reject(signal.reason instanceof Error ? signal.reason : new Error('aborted'));
131
- }
132
- return new Promise((resolve, reject) => {
133
- const onAbort = () => {
134
- reject(signal.reason instanceof Error ? signal.reason : new Error('aborted'));
135
- };
136
- signal.addEventListener('abort', onAbort, {
137
- once: true,
138
- });
139
- p.then((v) => {
140
- signal.removeEventListener('abort', onAbort);
141
- resolve(v);
142
- }, (e) => {
143
- signal.removeEventListener('abort', onAbort);
144
- reject(e);
145
- });
146
- });
147
- }
148
- async function pipeStreamEventsToBroadcaster(opts) {
149
- const { stream, broadcaster, agentName, signal, onEvent, onItemDone } = opts;
150
- try {
151
- for await (const event of stream) {
152
- if (signal?.aborted) {
153
- return;
154
- }
155
- onEvent?.(event);
156
- if (!isStreamRecord(event)) {
157
- continue;
158
- }
159
- broadcaster?.emit({
160
- source: 'sdk',
161
- type: typeof event.type === 'string' ? event.type : 'unknown',
162
- data: event,
163
- outputIndex: typeof event.outputIndex === 'number' ? event.outputIndex : undefined,
164
- contentIndex: typeof event.contentIndex === 'number' ? event.contentIndex : undefined,
165
- });
166
- if (event.type === 'response.output_item.done' && onItemDone) {
167
- await onItemDone(event.item);
168
- }
169
- }
170
- }
171
- catch (err) {
172
- // The stream ends badly when the round is aborted; that is not a pipe fault.
173
- if (signal?.aborted) {
174
- return;
175
- }
176
- if (broadcaster) {
177
- emitFrameworkEvent({
178
- broadcaster,
179
- agentName,
180
- eventType: 'stream_pipe_error',
181
- data: {
182
- error: err instanceof Error ? err.message : String(err),
183
- },
184
- });
185
- }
186
- throw err;
187
- }
188
- }
189
37
  /** @internal The error for a model call on a harness with no LLM credentials. */
190
38
  export function noLlmProviderError() {
191
39
  return new NoeticConfigError({
@@ -237,220 +85,6 @@ export function createStreamIdleWatchdog(timeoutMs, controller, onTimeout) {
237
85
  },
238
86
  };
239
87
  }
240
- function prepareModelRequest(request, agentName) {
241
- const { instructions: extractedInstructions, remaining } = extractSystemInstruction(request.items);
242
- const instructions = [
243
- request.instructions,
244
- extractedInstructions,
245
- ]
246
- .filter(Boolean)
247
- .join('\n\n') || undefined;
248
- const broadcaster = getBroadcaster(request.ctx);
249
- const allowedTools = filterAllowedTools(request) ?? [];
250
- // Every request carries the full tool list, so the prompt-cache prefix is the
251
- // same for every step in the tree; `toolChoice` does the narrowing. A call
252
- // that may use no client tool sends none.
253
- // Client (function) tools convert to SDK tool definitions; OpenRouter server
254
- // tools (web_search/web_fetch) are wrapped via the SDK's `serverTool()` so
255
- // its convertToolsToAPIFormat accepts them — a raw `{type}` entry crashes it.
256
- // `parameters` keys stay camelCase: the SDK's outbound zod schema strips
257
- // unknown keys, so snake_case would be silently dropped.
258
- const clientSdkTools = request.tools && allowedTools.length > 0
259
- ? convertTools({
260
- tools: request.tools,
261
- })
262
- : [];
263
- const serverSdkTools = (request._serverTools ?? []).map((s) => serverTool(frameworkCast({
264
- type: s.type,
265
- parameters: s.parameters,
266
- })));
267
- const sdkTools = [
268
- ...clientSdkTools,
269
- ...frameworkCast(serverSdkTools),
270
- ];
271
- return {
272
- instructions,
273
- remaining,
274
- broadcaster,
275
- sdkTools: sdkTools.length > 0 ? sdkTools : undefined,
276
- toolChoice: roundToolChoices({
277
- request,
278
- allowedTools,
279
- sendsClientTools: clientSdkTools.length > 0,
280
- sendsTools: sdkTools.length > 0,
281
- }),
282
- allowedTools,
283
- emitIfAllowed(eventType, data) {
284
- if (!shouldEmit(request.emit, eventType, data)) {
285
- return;
286
- }
287
- emitFrameworkEvent({
288
- broadcaster,
289
- agentName,
290
- eventType,
291
- data,
292
- });
293
- },
294
- };
295
- }
296
- function roundToolChoices(scope) {
297
- const choice = scope.request.toolChoice ?? ToolChoiceMode.Auto;
298
- return {
299
- first: wireToolChoice(scope, choice),
300
- rest: wireToolChoice(scope, choice === ToolChoiceMode.None ? choice : ToolChoiceMode.Auto),
301
- };
302
- }
303
- /**
304
- * Map a `toolChoice` onto the wire, inside the step's restriction.
305
- * A restricted call narrows with an `allowed_tools` choice (plus the step's
306
- * server tools) rather than by trimming `tools`, so the request keeps the
307
- * shared cache prefix. `none` keeps the tools too, for the same reason. A call
308
- * that sends no tools sends no choice.
309
- *
310
- * @throws NoeticConfigError `UNKNOWN_TOOL_CHOICE` when `{ tool }` names a tool
311
- * this call cannot run.
312
- */
313
- function wireToolChoice(scope, choice) {
314
- const { request, allowedTools } = scope;
315
- if (typeof choice === 'object') {
316
- return forcedToolChoice(choice.tool, allowedTools);
317
- }
318
- if (!scope.sendsTools) {
319
- return undefined;
320
- }
321
- if (choice === ToolChoiceMode.None) {
322
- return 'none';
323
- }
324
- if (request.allowedToolNames && scope.sendsClientTools) {
325
- return allowedToolsChoice(request, allowedTools, choice);
326
- }
327
- return choice === ToolChoiceMode.Required ? 'required' : undefined;
328
- }
329
- /** Force one function tool. It must be one the call may run. */
330
- function forcedToolChoice(name, allowedTools) {
331
- const tool = allowedTools.find((candidate) => candidate.name === name);
332
- if (!tool) {
333
- const offered = allowedTools.map((t) => t.name).join(', ') || 'none';
334
- throw new NoeticConfigError({
335
- code: 'UNKNOWN_TOOL_CHOICE',
336
- message: `toolChoice forces tool ${JSON.stringify(name)}, which this model call cannot run.`,
337
- hint: `Force a tool the call offers (offered: ${offered}), or give '${name}' to the step or a context layer.`,
338
- });
339
- }
340
- return {
341
- type: 'function',
342
- name: sanitizeToolNameForWire(tool.name),
343
- };
344
- }
345
- /** Restrict the model to `allowedTools` (plus the step's server tools). */
346
- function allowedToolsChoice(request, allowedTools, mode) {
347
- return {
348
- type: 'allowed_tools',
349
- mode,
350
- tools: [
351
- ...allowedTools.map((tool) => ({
352
- type: 'function',
353
- name: sanitizeToolNameForWire(tool.name),
354
- })),
355
- ...(request._serverTools ?? []).map((spec) => ({
356
- type: spec.type,
357
- })),
358
- ],
359
- };
360
- }
361
- /** Match a wire tool name against both the original and the sanitised name. */
362
- function findTool(tools, wireName) {
363
- return tools.find((tool) => tool.name === wireName || sanitizeToolNameForWire(tool.name) === wireName);
364
- }
365
- function filterAllowedTools(request) {
366
- if (!request.tools) {
367
- return undefined;
368
- }
369
- if (!('allowedToolNames' in request) || !request.allowedToolNames) {
370
- return request.tools;
371
- }
372
- const allowedNames = new Set(request.allowedToolNames);
373
- return request.tools.filter((tool) => allowedNames.has(tool.name));
374
- }
375
- /**
376
- * Per-`callModel` span accumulator. Spans are created lazily from the calling
377
- * context's span (so the trace tree mirrors the execution tree) and flushed to
378
- * the harness `traceExporter` once the call settles — see issue #50, where the
379
- * exporter was stored but never invoked.
380
- */
381
- class CallSpanCollector {
382
- harness;
383
- exporter;
384
- parent;
385
- nodeId;
386
- firstSpanAttributes;
387
- spans = [];
388
- constructor(harness, exporter, parent, nodeId,
389
- /** Stamped on the first model span only, then dropped. */
390
- firstSpanAttributes) {
391
- this.harness = harness;
392
- this.exporter = exporter;
393
- this.parent = parent;
394
- this.nodeId = nodeId;
395
- this.firstSpanAttributes = firstSpanAttributes;
396
- }
397
- /** Link a span back to its declared workflow node, when the call carries one. */
398
- stampNode(span) {
399
- if (this.nodeId !== undefined) {
400
- span.setAttribute(NoeticAttr.NODE_ID, this.nodeId);
401
- }
402
- }
403
- /** Open a model-call span stamped with GenAI semantic-convention attributes. */
404
- startModelSpan(model) {
405
- const span = this.harness.createSpan('llm.call', this.parent);
406
- span.setAttribute(GenAI.SYSTEM, 'openrouter');
407
- span.setAttribute(GenAI.REQUEST_MODEL, model);
408
- this.stampNode(span);
409
- for (const [key, value] of Object.entries(this.firstSpanAttributes ?? {})) {
410
- span.setAttribute(key, value);
411
- }
412
- this.firstSpanAttributes = undefined;
413
- this.spans.push(span);
414
- return span;
415
- }
416
- /** Record usage + cost on a model-call span. */
417
- finishModelSpan(span, usage, cost) {
418
- span.setAttribute(GenAI.USAGE_INPUT_TOKENS, usage.inputTokens);
419
- span.setAttribute(GenAI.USAGE_OUTPUT_TOKENS, usage.outputTokens);
420
- if (usage.cachedTokens !== undefined) {
421
- span.setAttribute(GenAI.USAGE_CACHED_INPUT_TOKENS, usage.cachedTokens);
422
- }
423
- if (usage.cacheWriteTokens !== undefined) {
424
- span.setAttribute(GenAI.USAGE_CACHE_WRITE_TOKENS, usage.cacheWriteTokens);
425
- }
426
- if (cost !== undefined) {
427
- span.setAttribute(GenAI.COST, cost);
428
- }
429
- span.end();
430
- }
431
- /**
432
- * Open and immediately close a tool-call span under the given model span, or under
433
- * the call's parent when the round's model call ran in an earlier attempt.
434
- */
435
- recordToolSpan(parent, toolName, needsApproval, approval) {
436
- const span = this.harness.createSpan('tool.call', parent ?? this.parent);
437
- span.setAttribute(ToolAttr.NAME, toolName);
438
- span.setAttribute(ToolAttr.NEEDS_APPROVAL, needsApproval);
439
- if (approval !== undefined) {
440
- span.setAttribute(ToolAttr.APPROVAL, approval);
441
- }
442
- this.stampNode(span);
443
- span.end();
444
- this.spans.push(span);
445
- }
446
- /** Flush all accumulated spans to the exporter. */
447
- async flush() {
448
- if (this.spans.length === 0) {
449
- return;
450
- }
451
- await exportSpans(this.exporter, this.spans);
452
- }
453
- }
454
88
  export class AgentHarnessModelCaller {
455
89
  opts;
456
90
  constructor(opts) {
@@ -475,6 +109,14 @@ export class AgentHarnessModelCaller {
475
109
  },
476
110
  });
477
111
  }
112
+ /** What the tool-round functions need from this caller. */
113
+ toolRoundScope() {
114
+ return {
115
+ harness: this.opts.harness,
116
+ itemSchemas: this.opts.itemSchemas,
117
+ emitItemAppended: (ctx, item) => this.emitItemAppended(ctx, item),
118
+ };
119
+ }
478
120
  async callOverriddenModel(request) {
479
121
  if (!this.opts.callModelOverride) {
480
122
  throw new Error('No callModel override configured.');
@@ -660,14 +302,14 @@ export class AgentHarnessModelCaller {
660
302
  prepared.emitIfAllowed('model_round_replayed', {
661
303
  round,
662
304
  });
663
- if (replayed.cut && !replayed.items.some(isFunctionCall)) {
305
+ if (replayed.cut && !hasFunctionCalls(replayed.items)) {
664
306
  // The stream was cut after the answer finished: it ends the loop.
665
307
  break;
666
308
  }
667
309
  if (replayed.cut) {
668
310
  // Go on from the function calls the stream finished: run them, then ask
669
311
  // the model again with their results in the conversation.
670
- await this.runToolRound({
312
+ await runToolRound(this.toolRoundScope(), {
671
313
  roundItems: replayed.items,
672
314
  request,
673
315
  prepared,
@@ -863,7 +505,7 @@ export class AgentHarnessModelCaller {
863
505
  catch (err) {
864
506
  streaming = false;
865
507
  await checkpoints;
866
- if (dispatch && wasRefused(err, dispatch)) {
508
+ if (dispatch?.wasRefused(err)) {
867
509
  await dispatch.settle();
868
510
  }
869
511
  if (idleStalled) {
@@ -897,7 +539,7 @@ export class AgentHarnessModelCaller {
897
539
  });
898
540
  allItems.push(...roundItems);
899
541
  replayOutput(conversationInput, roundItems);
900
- await this.runToolRound({
542
+ await runToolRound(this.toolRoundScope(), {
901
543
  roundItems,
902
544
  request,
903
545
  prepared,
@@ -953,7 +595,7 @@ export class AgentHarnessModelCaller {
953
595
  });
954
596
  servedTier = sdkResponse.serviceTier ?? undefined;
955
597
  allItems.push(...roundItems);
956
- const ranTools = await this.runToolRound({
598
+ const ranTools = await runToolRound(this.toolRoundScope(), {
957
599
  roundItems,
958
600
  request,
959
601
  prepared,
@@ -1035,26 +677,6 @@ export class AgentHarnessModelCaller {
1035
677
  });
1036
678
  return roundItemSchemas.parseMany(items);
1037
679
  }
1038
- /** Run the round's function calls. Returns `false` when there were none to run. */
1039
- async runToolRound(params) {
1040
- const functionCalls = params.roundItems.filter(isFunctionCall);
1041
- if (functionCalls.length === 0 || !params.request.tools) {
1042
- return false;
1043
- }
1044
- await this.executeToolRound({
1045
- functionCalls,
1046
- request: params.request,
1047
- allowedTools: params.prepared.allowedTools,
1048
- allItems: params.allItems,
1049
- conversationInput: params.conversationInput,
1050
- round: params.round,
1051
- emitIfAllowed: params.prepared.emitIfAllowed,
1052
- spans: params.spans,
1053
- modelSpan: params.modelSpan,
1054
- steers: params.steers,
1055
- });
1056
- return true;
1057
- }
1058
680
  handleModelRecovery(params) {
1059
681
  const terminalError = providerTerminalError(params.sdkResponse);
1060
682
  if (!terminalError) {
@@ -1111,156 +733,6 @@ export class AgentHarnessModelCaller {
1111
733
  invalidRecoveryContinuations: next,
1112
734
  };
1113
735
  }
1114
- async executeToolRound(params) {
1115
- const { functionCalls, request, allowedTools, allItems, conversationInput, spans, modelSpan, steers, } = params;
1116
- params.emitIfAllowed('tool_round_started', {
1117
- round: params.round,
1118
- toolCount: functionCalls.length,
1119
- });
1120
- for (const fc of functionCalls) {
1121
- conversationInput.push({
1122
- type: 'function_call',
1123
- callId: fc.callId,
1124
- id: fc.id ?? crypto.randomUUID(),
1125
- name: fc.name,
1126
- arguments: fc.arguments,
1127
- });
1128
- }
1129
- for (const [index, fc] of functionCalls.entries()) {
1130
- await drainsOf(request.ctx)?.hold(request.ctx);
1131
- if (request.signal?.aborted) {
1132
- break;
1133
- }
1134
- const remaining = functionCalls.slice(index);
1135
- if (steers?.hasQueued() && (await steers.offer(SteerPoint.BeforeToolCall, remaining))) {
1136
- for (const skipped of remaining) {
1137
- this.recordSkippedToolCall({
1138
- fc: skipped,
1139
- request,
1140
- allowedTools,
1141
- allItems,
1142
- conversationInput,
1143
- emitIfAllowed: params.emitIfAllowed,
1144
- });
1145
- }
1146
- break;
1147
- }
1148
- const toolForCall = findTool(allowedTools, fc.name);
1149
- const approval = await this.executeFunctionCall({
1150
- fc,
1151
- request,
1152
- allowedTools,
1153
- allItems,
1154
- conversationInput,
1155
- emitIfAllowed: params.emitIfAllowed,
1156
- });
1157
- spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false, approval);
1158
- }
1159
- params.emitIfAllowed('tool_round_completed', {
1160
- round: params.round,
1161
- toolCount: functionCalls.length,
1162
- });
1163
- }
1164
- async executeFunctionCall(params) {
1165
- const { fc, request, allowedTools, allItems, conversationInput } = params;
1166
- params.emitIfAllowed('tool_call_started', {
1167
- name: fc.name,
1168
- callId: fc.callId,
1169
- });
1170
- let parsedArgs;
1171
- try {
1172
- parsedArgs = JSON.parse(fc.arguments);
1173
- }
1174
- catch {
1175
- this.recordUnrunToolCall({
1176
- fc,
1177
- output: `Error: malformed JSON in tool arguments: ${fc.arguments}`,
1178
- request,
1179
- allowedTools,
1180
- allItems,
1181
- conversationInput,
1182
- emitIfAllowed: params.emitIfAllowed,
1183
- });
1184
- return undefined;
1185
- }
1186
- if (!request.tools) {
1187
- throw new Error(`executeFunctionCall invoked without tools on CallModelRequest (tool name: ${fc.name}).`);
1188
- }
1189
- const toolForCall = findTool(allowedTools, fc.name);
1190
- const toolResult = await executeToolCall({
1191
- toolName: fc.name,
1192
- args: parsedArgs,
1193
- tools: allowedTools,
1194
- context: request.ctx,
1195
- harness: this.opts.harness,
1196
- layers: request.layers,
1197
- callId: fc.callId,
1198
- });
1199
- // Owner-scoped result validation: a tool's `toolResults` schemas apply
1200
- // only to that tool's own result items. Harness-level `opts.itemSchemas`
1201
- // stay global by design; sibling tools' schemas never reject this item.
1202
- const outputItem = createToolResultItem({
1203
- output: toolResult.output,
1204
- callId: fc.callId,
1205
- roundItemSchemas: this.opts.itemSchemas.extend(toolForCall?.itemSchemas),
1206
- tool: toolForCall,
1207
- callItem: fc,
1208
- args: parsedArgs,
1209
- result: toolResult.result,
1210
- error: toolResult.error,
1211
- });
1212
- allItems.push(outputItem);
1213
- conversationInput.push({
1214
- type: 'function_call_output',
1215
- callId: fc.callId,
1216
- output: toolResult.output,
1217
- });
1218
- this.emitItemAppended(request.ctx, outputItem);
1219
- params.emitIfAllowed('tool_call_completed', {
1220
- name: fc.name,
1221
- callId: fc.callId,
1222
- error: toolResult.error === true,
1223
- output: toolResult.output,
1224
- });
1225
- return toolResult.approval;
1226
- }
1227
- recordSkippedToolCall(params) {
1228
- params.emitIfAllowed('tool_call_started', {
1229
- name: params.fc.name,
1230
- callId: params.fc.callId,
1231
- });
1232
- this.recordUnrunToolCall({
1233
- ...params,
1234
- output: SKIPPED_FOR_STEER_OUTPUT,
1235
- });
1236
- }
1237
- /** Answer a call that never ran, so every call in the history has an output. */
1238
- recordUnrunToolCall(params) {
1239
- const { fc, request, allowedTools, allItems, conversationInput } = params;
1240
- const toolForCall = findTool(allowedTools, fc.name);
1241
- // Owner-scoped result validation (see executeFunctionCall).
1242
- const outputItem = createToolResultItem({
1243
- output: params.output,
1244
- callId: fc.callId,
1245
- roundItemSchemas: this.opts.itemSchemas.extend(toolForCall?.itemSchemas),
1246
- tool: toolForCall,
1247
- callItem: fc,
1248
- error: true,
1249
- });
1250
- allItems.push(outputItem);
1251
- conversationInput.push({
1252
- type: 'function_call_output',
1253
- callId: fc.callId,
1254
- output: params.output,
1255
- });
1256
- this.emitItemAppended(request.ctx, outputItem);
1257
- params.emitIfAllowed('tool_call_completed', {
1258
- name: fc.name,
1259
- callId: fc.callId,
1260
- error: true,
1261
- output: params.output,
1262
- });
1263
- }
1264
736
  handleToolRoundLimit(params) {
1265
737
  if (params.round < MAX_TOOL_ROUNDS) {
1266
738
  return {
@@ -0,0 +1,42 @@
1
+ import type { CallModelRequest, Item, StandardSchemaV1, Tool } from '@noetic-tools/types';
2
+ import type * as OpenRouterAgent from '@openrouter/agent';
3
+ import { convertTools } from '../adapters/openrouter.js';
4
+ import type { EventBroadcaster } from '../runtime/event-broadcaster.js';
5
+ /**
6
+ * Shapes a `callModel` request for the wire: system instructions, the SDK tool
7
+ * list, the per-round tool choice, and the structured-output text format.
8
+ */
9
+ export declare function buildTextFormat(schema: StandardSchemaV1, explicitJsonSchema?: Record<string, unknown>): {
10
+ format: {
11
+ type: 'json_schema';
12
+ name: string;
13
+ schema: Record<string, unknown>;
14
+ };
15
+ };
16
+ export interface PreparedModelRequest {
17
+ instructions?: string;
18
+ remaining: ReadonlyArray<Item>;
19
+ broadcaster?: EventBroadcaster;
20
+ sdkTools?: ReturnType<typeof convertTools>;
21
+ /**
22
+ * The wire tool choice, by round. A forcing choice (`required`, `{ tool }`)
23
+ * holds only until the model has called a tool; later rounds fall back to
24
+ * `auto`, or every round would force another call until the round limit.
25
+ */
26
+ toolChoice: {
27
+ first: WireToolChoice;
28
+ rest: WireToolChoice;
29
+ };
30
+ /**
31
+ * The tools this call may run: the request's tools narrowed to
32
+ * `allowedToolNames`. A call to any other tool is answered as unknown, so a
33
+ * model that names a tool it was never offered cannot run it.
34
+ */
35
+ allowedTools: Tool[];
36
+ emitIfAllowed: (eventType: string, data: Record<string, unknown>) => void;
37
+ }
38
+ export declare function prepareModelRequest(request: CallModelRequest, agentName: string): PreparedModelRequest;
39
+ type WireToolChoice = OpenRouterAgent.CallModelInput['toolChoice'];
40
+ /** Match a wire tool name against both the original and the sanitised name. */
41
+ export declare function findTool(tools: ReadonlyArray<Tool>, wireName: string): Tool | undefined;
42
+ export {};