@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
@@ -0,0 +1,159 @@
1
+ import { frameworkCast, NoeticConfigError, ToolChoiceMode } from '@noetic-tools/types';
2
+ import { serverTool } from '@openrouter/agent';
3
+ import { convertTools, extractSystemInstruction, resolveWireJsonSchema, sanitizeToolNameForWire, } from '../adapters/openrouter.js';
4
+ import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.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
+ //#region Model request preparation
10
+ export function buildTextFormat(schema, explicitJsonSchema) {
11
+ const jsonSchema = resolveWireJsonSchema({
12
+ schema,
13
+ explicitJsonSchema,
14
+ what: 'structured output schema',
15
+ });
16
+ return {
17
+ format: {
18
+ type: 'json_schema',
19
+ name: 'output',
20
+ schema: jsonSchema,
21
+ },
22
+ };
23
+ }
24
+ export function prepareModelRequest(request, agentName) {
25
+ const { instructions: extractedInstructions, remaining } = extractSystemInstruction(request.items);
26
+ const instructions = [
27
+ request.instructions,
28
+ extractedInstructions,
29
+ ]
30
+ .filter(Boolean)
31
+ .join('\n\n') || undefined;
32
+ const broadcaster = getBroadcaster(request.ctx);
33
+ const allowedTools = filterAllowedTools(request) ?? [];
34
+ // Every request carries the full tool list, so the prompt-cache prefix is the
35
+ // same for every step in the tree; `toolChoice` does the narrowing. A call
36
+ // that may use no client tool sends none.
37
+ // Client (function) tools convert to SDK tool definitions; OpenRouter server
38
+ // tools (web_search/web_fetch) are wrapped via the SDK's `serverTool()` so
39
+ // its convertToolsToAPIFormat accepts them — a raw `{type}` entry crashes it.
40
+ // `parameters` keys stay camelCase: the SDK's outbound zod schema strips
41
+ // unknown keys, so snake_case would be silently dropped.
42
+ const clientSdkTools = request.tools && allowedTools.length > 0
43
+ ? convertTools({
44
+ tools: request.tools,
45
+ })
46
+ : [];
47
+ const serverSdkTools = (request._serverTools ?? []).map((s) => serverTool(frameworkCast({
48
+ type: s.type,
49
+ parameters: s.parameters,
50
+ })));
51
+ const sdkTools = [
52
+ ...clientSdkTools,
53
+ ...frameworkCast(serverSdkTools),
54
+ ];
55
+ return {
56
+ instructions,
57
+ remaining,
58
+ broadcaster,
59
+ sdkTools: sdkTools.length > 0 ? sdkTools : undefined,
60
+ toolChoice: roundToolChoices({
61
+ request,
62
+ allowedTools,
63
+ sendsClientTools: clientSdkTools.length > 0,
64
+ sendsTools: sdkTools.length > 0,
65
+ }),
66
+ allowedTools,
67
+ emitIfAllowed(eventType, data) {
68
+ if (!shouldEmit(request.emit, eventType, data)) {
69
+ return;
70
+ }
71
+ emitFrameworkEvent({
72
+ broadcaster,
73
+ agentName,
74
+ eventType,
75
+ data,
76
+ });
77
+ },
78
+ };
79
+ }
80
+ function roundToolChoices(scope) {
81
+ const choice = scope.request.toolChoice ?? ToolChoiceMode.Auto;
82
+ return {
83
+ first: wireToolChoice(scope, choice),
84
+ rest: wireToolChoice(scope, choice === ToolChoiceMode.None ? choice : ToolChoiceMode.Auto),
85
+ };
86
+ }
87
+ /**
88
+ * Map a `toolChoice` onto the wire, inside the step's restriction.
89
+ * A restricted call narrows with an `allowed_tools` choice (plus the step's
90
+ * server tools) rather than by trimming `tools`, so the request keeps the
91
+ * shared cache prefix. `none` keeps the tools too, for the same reason. A call
92
+ * that sends no tools sends no choice.
93
+ *
94
+ * @throws NoeticConfigError `UNKNOWN_TOOL_CHOICE` when `{ tool }` names a tool
95
+ * this call cannot run.
96
+ */
97
+ function wireToolChoice(scope, choice) {
98
+ const { request, allowedTools } = scope;
99
+ if (typeof choice === 'object') {
100
+ return forcedToolChoice(choice.tool, allowedTools);
101
+ }
102
+ if (!scope.sendsTools) {
103
+ return undefined;
104
+ }
105
+ if (choice === ToolChoiceMode.None) {
106
+ return 'none';
107
+ }
108
+ if (request.allowedToolNames && scope.sendsClientTools) {
109
+ return allowedToolsChoice(request, allowedTools, choice);
110
+ }
111
+ return choice === ToolChoiceMode.Required ? 'required' : undefined;
112
+ }
113
+ /** Force one function tool. It must be one the call may run. */
114
+ function forcedToolChoice(name, allowedTools) {
115
+ const tool = allowedTools.find((candidate) => candidate.name === name);
116
+ if (!tool) {
117
+ const offered = allowedTools.map((t) => t.name).join(', ') || 'none';
118
+ throw new NoeticConfigError({
119
+ code: 'UNKNOWN_TOOL_CHOICE',
120
+ message: `toolChoice forces tool ${JSON.stringify(name)}, which this model call cannot run.`,
121
+ hint: `Force a tool the call offers (offered: ${offered}), or give '${name}' to the step or a context layer.`,
122
+ });
123
+ }
124
+ return {
125
+ type: 'function',
126
+ name: sanitizeToolNameForWire(tool.name),
127
+ };
128
+ }
129
+ /** Restrict the model to `allowedTools` (plus the step's server tools). */
130
+ function allowedToolsChoice(request, allowedTools, mode) {
131
+ return {
132
+ type: 'allowed_tools',
133
+ mode,
134
+ tools: [
135
+ ...allowedTools.map((tool) => ({
136
+ type: 'function',
137
+ name: sanitizeToolNameForWire(tool.name),
138
+ })),
139
+ ...(request._serverTools ?? []).map((spec) => ({
140
+ type: spec.type,
141
+ })),
142
+ ],
143
+ };
144
+ }
145
+ /** Match a wire tool name against both the original and the sanitised name. */
146
+ export function findTool(tools, wireName) {
147
+ return tools.find((tool) => tool.name === wireName || sanitizeToolNameForWire(tool.name) === wireName);
148
+ }
149
+ function filterAllowedTools(request) {
150
+ if (!request.tools) {
151
+ return undefined;
152
+ }
153
+ if (!('allowedToolNames' in request) || !request.allowedToolNames) {
154
+ return request.tools;
155
+ }
156
+ const allowedNames = new Set(request.allowedToolNames);
157
+ return request.tools.filter((tool) => allowedNames.has(tool.name));
158
+ }
159
+ //#endregion
@@ -0,0 +1,39 @@
1
+ import type { Item } from '@noetic-tools/types';
2
+ import type { EventBroadcaster } from '../runtime/event-broadcaster.js';
3
+ import type { Dispatch } from './spend.js';
4
+ /**
5
+ * Reading a model response stream: piping SDK events to the broadcaster,
6
+ * spotting the generation id and terminal errors, and racing awaits against abort.
7
+ */
8
+ export declare function isStreamRecord(value: unknown): value is Record<string, unknown>;
9
+ interface ProviderTerminalError {
10
+ status: string;
11
+ message: string;
12
+ }
13
+ export declare function providerTerminalError(response: unknown): ProviderTerminalError | null;
14
+ /**
15
+ * Save the generation id a stream's `response.created` event carries, for a response
16
+ * whose headers did not. OpenRouter's ids start `gen-`; other ids price nothing.
17
+ */
18
+ export declare function noteStreamGeneration(dispatch: Dispatch | undefined, event: unknown): void;
19
+ export declare function hasUsableResponseOutput(response: unknown, items: ReadonlyArray<Item>): boolean;
20
+ /** Race a promise against an AbortSignal so callers (e.g. `SessionRunner.abort`)
21
+ * can break out of a long `await` without waiting for the underlying call to
22
+ * settle. When the signal fires, the returned promise rejects with
23
+ * `signal.reason` (an `Error`) or a generic `Error('aborted')` fallback. */
24
+ export declare function awaitWithAbort<T>(p: Promise<T>, signal: AbortSignal | undefined): Promise<T>;
25
+ interface PipeStreamOpts {
26
+ stream: AsyncIterable<unknown>;
27
+ /** Optional: when provided, each SDK event is emitted into it. Absent in
28
+ * headless/test harness runs that still need the idle watchdog to reset. */
29
+ broadcaster?: EventBroadcaster;
30
+ agentName: string;
31
+ signal?: AbortSignal;
32
+ /** Invoked once per SDK event received — used by the idle watchdog to bump
33
+ * its deadline so a still-streaming response isn't aborted. */
34
+ onEvent?: (event: unknown) => void;
35
+ /** Awaited with each finished output item before the next event is read. */
36
+ onItemDone?: (item: unknown) => Promise<void>;
37
+ }
38
+ export declare function pipeStreamEventsToBroadcaster(opts: PipeStreamOpts): Promise<void>;
39
+ export {};
@@ -0,0 +1,131 @@
1
+ import { emitFrameworkEvent } from '../runtime/broadcaster-utils.js';
2
+ /**
3
+ * Reading a model response stream: piping SDK events to the broadcaster,
4
+ * spotting the generation id and terminal errors, and racing awaits against abort.
5
+ */
6
+ //#region Model stream helpers
7
+ export function isStreamRecord(value) {
8
+ return typeof value === 'object' && value !== null;
9
+ }
10
+ export function providerTerminalError(response) {
11
+ if (!isStreamRecord(response) || response.status === undefined) {
12
+ return null;
13
+ }
14
+ const status = String(response.status);
15
+ if (status === 'completed') {
16
+ return null;
17
+ }
18
+ if (status === 'incomplete') {
19
+ const details = response.incompleteDetails;
20
+ const reason = isStreamRecord(details) && typeof details.reason === 'string' ? `: ${details.reason}` : '';
21
+ return {
22
+ status,
23
+ message: `LLM response incomplete${reason}`,
24
+ };
25
+ }
26
+ if (status === 'failed') {
27
+ const error = response.error;
28
+ const message = isStreamRecord(error) && typeof error.message === 'string' ? `: ${error.message}` : '';
29
+ return {
30
+ status,
31
+ message: `LLM response failed${message}`,
32
+ };
33
+ }
34
+ return {
35
+ status,
36
+ message: `LLM response ended with status '${status}'`,
37
+ };
38
+ }
39
+ /**
40
+ * Save the generation id a stream's `response.created` event carries, for a response
41
+ * whose headers did not. OpenRouter's ids start `gen-`; other ids price nothing.
42
+ */
43
+ export function noteStreamGeneration(dispatch, event) {
44
+ if (!dispatch || !isStreamRecord(event) || event.type !== 'response.created') {
45
+ return;
46
+ }
47
+ const response = event.response;
48
+ if (!isStreamRecord(response) || typeof response.id !== 'string') {
49
+ return;
50
+ }
51
+ if (response.id.startsWith('gen-')) {
52
+ void dispatch.noteGeneration(response.id);
53
+ }
54
+ }
55
+ export function hasUsableResponseOutput(response, items) {
56
+ if (items.length > 0) {
57
+ return true;
58
+ }
59
+ return (isStreamRecord(response) &&
60
+ typeof response.outputText === 'string' &&
61
+ response.outputText.length > 0);
62
+ }
63
+ /** Race a promise against an AbortSignal so callers (e.g. `SessionRunner.abort`)
64
+ * can break out of a long `await` without waiting for the underlying call to
65
+ * settle. When the signal fires, the returned promise rejects with
66
+ * `signal.reason` (an `Error`) or a generic `Error('aborted')` fallback. */
67
+ export function awaitWithAbort(p, signal) {
68
+ if (!signal) {
69
+ return p;
70
+ }
71
+ if (signal.aborted) {
72
+ return Promise.reject(signal.reason instanceof Error ? signal.reason : new Error('aborted'));
73
+ }
74
+ return new Promise((resolve, reject) => {
75
+ const onAbort = () => {
76
+ reject(signal.reason instanceof Error ? signal.reason : new Error('aborted'));
77
+ };
78
+ signal.addEventListener('abort', onAbort, {
79
+ once: true,
80
+ });
81
+ p.then((v) => {
82
+ signal.removeEventListener('abort', onAbort);
83
+ resolve(v);
84
+ }, (e) => {
85
+ signal.removeEventListener('abort', onAbort);
86
+ reject(e);
87
+ });
88
+ });
89
+ }
90
+ export async function pipeStreamEventsToBroadcaster(opts) {
91
+ const { stream, broadcaster, agentName, signal, onEvent, onItemDone } = opts;
92
+ try {
93
+ for await (const event of stream) {
94
+ if (signal?.aborted) {
95
+ return;
96
+ }
97
+ onEvent?.(event);
98
+ if (!isStreamRecord(event)) {
99
+ continue;
100
+ }
101
+ broadcaster?.emit({
102
+ source: 'sdk',
103
+ type: typeof event.type === 'string' ? event.type : 'unknown',
104
+ data: event,
105
+ outputIndex: typeof event.outputIndex === 'number' ? event.outputIndex : undefined,
106
+ contentIndex: typeof event.contentIndex === 'number' ? event.contentIndex : undefined,
107
+ });
108
+ if (event.type === 'response.output_item.done' && onItemDone) {
109
+ await onItemDone(event.item);
110
+ }
111
+ }
112
+ }
113
+ catch (err) {
114
+ // The stream ends badly when the round is aborted; that is not a pipe fault.
115
+ if (signal?.aborted) {
116
+ return;
117
+ }
118
+ if (broadcaster) {
119
+ emitFrameworkEvent({
120
+ broadcaster,
121
+ agentName,
122
+ eventType: 'stream_pipe_error',
123
+ data: {
124
+ error: err instanceof Error ? err.message : String(err),
125
+ },
126
+ });
127
+ }
128
+ throw err;
129
+ }
130
+ }
131
+ //#endregion
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The tool round of a model call: run each function call the model made (or
3
+ * answer it unrun when a steer arrives first), append its result item to the
4
+ * conversation, and record the tool span.
5
+ */
6
+ import type { AgentHarnessContract, CallModelRequest, Context, Item, ItemSchemaRegistry, Span } from '@noetic-tools/types';
7
+ import { itemsToInput } from '../adapters/openrouter.js';
8
+ import type { CallSpanCollector } from './call-span-collector.js';
9
+ import type { PreparedModelRequest } from './model-request.js';
10
+ import type { SteerInbox } from './steer-inbox.js';
11
+ /** What the tool round needs from the model caller that runs it. */
12
+ export interface ToolRoundScope {
13
+ harness: AgentHarnessContract;
14
+ itemSchemas: ItemSchemaRegistry;
15
+ /** Broadcast a framework-authored item so the item stream carries it. */
16
+ emitItemAppended: (ctx: Context | undefined, item: Item) => void;
17
+ }
18
+ /**
19
+ * Tool rounds replay only their function calls. A round a steer follows must
20
+ * also replay what the model said, or the next round starts without it.
21
+ * Function calls are left to the tool round, which adds each with its output.
22
+ */
23
+ export declare function replayOutput(input: ReturnType<typeof itemsToInput>, roundItems: ReadonlyArray<Item>): void;
24
+ /** Whether a round asked for any tool calls. */
25
+ export declare function hasFunctionCalls(roundItems: ReadonlyArray<Item>): boolean;
26
+ /** Run the round's function calls. Returns `false` when there were none to run. */
27
+ export declare function runToolRound(scope: ToolRoundScope, params: {
28
+ roundItems: Item[];
29
+ request: CallModelRequest;
30
+ prepared: PreparedModelRequest;
31
+ allItems: Item[];
32
+ conversationInput: ReturnType<typeof itemsToInput>;
33
+ round: number;
34
+ spans: CallSpanCollector;
35
+ modelSpan: Span | null;
36
+ steers: SteerInbox | undefined;
37
+ }): Promise<boolean>;
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The tool round of a model call: run each function call the model made (or
3
+ * answer it unrun when a steer arrives first), append its result item to the
4
+ * conversation, and record the tool span.
5
+ */
6
+ import { SteerPoint } from '@noetic-tools/types';
7
+ import { executeToolCall, itemsToInput } from '../adapters/openrouter.js';
8
+ import { isFunctionCall } from '../interpreter/typeguards.js';
9
+ import { drainsOf } from '../runtime/drain.js';
10
+ import { findTool } from './model-request.js';
11
+ import { createToolResultItem } from './model-schema.js';
12
+ //#endregion
13
+ //#region Tool Round
14
+ const SKIPPED_FOR_STEER_OUTPUT = 'Skipped: a new message arrived before this tool call ran.';
15
+ /**
16
+ * Tool rounds replay only their function calls. A round a steer follows must
17
+ * also replay what the model said, or the next round starts without it.
18
+ * Function calls are left to the tool round, which adds each with its output.
19
+ */
20
+ export function replayOutput(input, roundItems) {
21
+ input.push(...itemsToInput(roundItems.filter((item) => !isFunctionCall(item))));
22
+ }
23
+ /** Whether a round asked for any tool calls. */
24
+ export function hasFunctionCalls(roundItems) {
25
+ return roundItems.some(isFunctionCall);
26
+ }
27
+ /** Run the round's function calls. Returns `false` when there were none to run. */
28
+ export async function runToolRound(scope, params) {
29
+ const functionCalls = params.roundItems.filter(isFunctionCall);
30
+ if (functionCalls.length === 0 || !params.request.tools) {
31
+ return false;
32
+ }
33
+ await executeToolRound(scope, {
34
+ functionCalls,
35
+ request: params.request,
36
+ allowedTools: params.prepared.allowedTools,
37
+ allItems: params.allItems,
38
+ conversationInput: params.conversationInput,
39
+ round: params.round,
40
+ emitIfAllowed: params.prepared.emitIfAllowed,
41
+ spans: params.spans,
42
+ modelSpan: params.modelSpan,
43
+ steers: params.steers,
44
+ });
45
+ return true;
46
+ }
47
+ async function executeToolRound(scope, params) {
48
+ const { functionCalls, request, allowedTools, allItems, conversationInput, spans, modelSpan, steers, } = params;
49
+ params.emitIfAllowed('tool_round_started', {
50
+ round: params.round,
51
+ toolCount: functionCalls.length,
52
+ });
53
+ for (const fc of functionCalls) {
54
+ conversationInput.push({
55
+ type: 'function_call',
56
+ callId: fc.callId,
57
+ id: fc.id ?? crypto.randomUUID(),
58
+ name: fc.name,
59
+ arguments: fc.arguments,
60
+ });
61
+ }
62
+ for (const [index, fc] of functionCalls.entries()) {
63
+ await drainsOf(request.ctx)?.hold(request.ctx);
64
+ if (request.signal?.aborted) {
65
+ break;
66
+ }
67
+ const remaining = functionCalls.slice(index);
68
+ if (steers?.hasQueued() && (await steers.offer(SteerPoint.BeforeToolCall, remaining))) {
69
+ for (const skipped of remaining) {
70
+ recordSkippedToolCall(scope, {
71
+ fc: skipped,
72
+ request,
73
+ allowedTools,
74
+ allItems,
75
+ conversationInput,
76
+ emitIfAllowed: params.emitIfAllowed,
77
+ });
78
+ }
79
+ break;
80
+ }
81
+ const toolForCall = findTool(allowedTools, fc.name);
82
+ const approval = await executeFunctionCall(scope, {
83
+ fc,
84
+ request,
85
+ allowedTools,
86
+ allItems,
87
+ conversationInput,
88
+ emitIfAllowed: params.emitIfAllowed,
89
+ });
90
+ spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false, approval);
91
+ }
92
+ params.emitIfAllowed('tool_round_completed', {
93
+ round: params.round,
94
+ toolCount: functionCalls.length,
95
+ });
96
+ }
97
+ async function executeFunctionCall(scope, params) {
98
+ const { fc, request, allowedTools, allItems, conversationInput } = params;
99
+ params.emitIfAllowed('tool_call_started', {
100
+ name: fc.name,
101
+ callId: fc.callId,
102
+ });
103
+ let parsedArgs;
104
+ try {
105
+ parsedArgs = JSON.parse(fc.arguments);
106
+ }
107
+ catch {
108
+ recordUnrunToolCall(scope, {
109
+ fc,
110
+ output: `Error: malformed JSON in tool arguments: ${fc.arguments}`,
111
+ request,
112
+ allowedTools,
113
+ allItems,
114
+ conversationInput,
115
+ emitIfAllowed: params.emitIfAllowed,
116
+ });
117
+ return undefined;
118
+ }
119
+ if (!request.tools) {
120
+ throw new Error(`executeFunctionCall invoked without tools on CallModelRequest (tool name: ${fc.name}).`);
121
+ }
122
+ const toolForCall = findTool(allowedTools, fc.name);
123
+ const toolResult = await executeToolCall({
124
+ toolName: fc.name,
125
+ args: parsedArgs,
126
+ tools: allowedTools,
127
+ context: request.ctx,
128
+ harness: scope.harness,
129
+ layers: request.layers,
130
+ callId: fc.callId,
131
+ });
132
+ // Owner-scoped result validation: a tool's `toolResults` schemas apply
133
+ // only to that tool's own result items. Harness-level `opts.itemSchemas`
134
+ // stay global by design; sibling tools' schemas never reject this item.
135
+ const outputItem = createToolResultItem({
136
+ output: toolResult.output,
137
+ callId: fc.callId,
138
+ roundItemSchemas: scope.itemSchemas.extend(toolForCall?.itemSchemas),
139
+ tool: toolForCall,
140
+ callItem: fc,
141
+ args: parsedArgs,
142
+ result: toolResult.result,
143
+ error: toolResult.error,
144
+ });
145
+ allItems.push(outputItem);
146
+ conversationInput.push({
147
+ type: 'function_call_output',
148
+ callId: fc.callId,
149
+ output: toolResult.output,
150
+ });
151
+ scope.emitItemAppended(request.ctx, outputItem);
152
+ params.emitIfAllowed('tool_call_completed', {
153
+ name: fc.name,
154
+ callId: fc.callId,
155
+ error: toolResult.error === true,
156
+ output: toolResult.output,
157
+ });
158
+ return toolResult.approval;
159
+ }
160
+ function recordSkippedToolCall(scope, params) {
161
+ params.emitIfAllowed('tool_call_started', {
162
+ name: params.fc.name,
163
+ callId: params.fc.callId,
164
+ });
165
+ recordUnrunToolCall(scope, {
166
+ ...params,
167
+ output: SKIPPED_FOR_STEER_OUTPUT,
168
+ });
169
+ }
170
+ /** Answer a call that never ran, so every call in the history has an output. */
171
+ function recordUnrunToolCall(scope, params) {
172
+ const { fc, request, allowedTools, allItems, conversationInput } = params;
173
+ const toolForCall = findTool(allowedTools, fc.name);
174
+ // Owner-scoped result validation (see executeFunctionCall).
175
+ const outputItem = createToolResultItem({
176
+ output: params.output,
177
+ callId: fc.callId,
178
+ roundItemSchemas: scope.itemSchemas.extend(toolForCall?.itemSchemas),
179
+ tool: toolForCall,
180
+ callItem: fc,
181
+ error: true,
182
+ });
183
+ allItems.push(outputItem);
184
+ conversationInput.push({
185
+ type: 'function_call_output',
186
+ callId: fc.callId,
187
+ output: params.output,
188
+ });
189
+ scope.emitItemAppended(request.ctx, outputItem);
190
+ params.emitIfAllowed('tool_call_completed', {
191
+ name: fc.name,
192
+ callId: fc.callId,
193
+ error: true,
194
+ output: params.output,
195
+ });
196
+ }
197
+ //#endregion
@@ -136,6 +136,8 @@ export declare class Dispatch {
136
136
  /** Request headers that tie the response back to this dispatch. */
137
137
  get headers(): Record<string, string>;
138
138
  noteGeneration(generationId: string): Promise<void>;
139
+ /** The provider refused the call before generating anything, so nothing was billed. */
140
+ wasRefused(err: unknown): boolean;
139
141
  /** The call's bill reached the run, or the provider refused it: drop the record. */
140
142
  settle(): Promise<void>;
141
143
  /** The call is over. Without a settled bill its record stays, pending. */
@@ -12,7 +12,7 @@ import { recordUsage, SpendKind } from '@noetic-tools/types';
12
12
  import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
13
13
  import { isUnreadable } from '../runtime/durable/spend-log.js';
14
14
  import { hashText } from '../runtime/durable/step-ledger.js';
15
- import { statusOf } from '../util/status-code.js';
15
+ import { isErrorStatus, statusOf } from '../util/status-code.js';
16
16
  import { ContextImpl, laneBase } from './deps/runtime.js';
17
17
  import { ceilingOf, createPriceBook, LOOKUP_TIMEOUT_MS, measureRequest } from './model-price.js';
18
18
  import { roundPath } from './model-rounds.js';
@@ -437,6 +437,10 @@ export class Dispatch {
437
437
  this.record.generationId = generationId;
438
438
  return this.queue('write', () => this.log.put(this.record));
439
439
  }
440
+ /** The provider refused the call before generating anything, so nothing was billed. */
441
+ wasRefused(err) {
442
+ return isErrorStatus(err) && this.record.generationId === undefined;
443
+ }
440
444
  /** The call's bill reached the run, or the provider refused it: drop the record. */
441
445
  settle() {
442
446
  if (this.ended) {