@noetic-tools/core 5.19.1-next.1 → 5.19.2

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 (150) 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 +16 -1
  6. package/dist/builders/dynamic-workflow.js +222 -11
  7. package/dist/builders/every.d.ts +3 -3
  8. package/dist/builders/every.js +2 -1
  9. package/dist/builders/provide-builder.d.ts +3 -2
  10. package/dist/builders/provide-builder.js +2 -1
  11. package/dist/builders/sequence.d.ts +14 -0
  12. package/dist/builders/sequence.js +103 -0
  13. package/dist/builders/spawn-builder.d.ts +3 -2
  14. package/dist/builders/spawn-builder.js +3 -2
  15. package/dist/builders/step-builders.d.ts +80 -1
  16. package/dist/builders/step-builders.js +115 -1
  17. package/dist/builders/verify-builder.d.ts +79 -0
  18. package/dist/builders/verify-builder.js +69 -0
  19. package/dist/builders/workflow-child-nodes.d.ts +21 -0
  20. package/dist/builders/workflow-child-nodes.js +335 -0
  21. package/dist/builders/workflow-connection-nodes.d.ts +17 -0
  22. package/dist/builders/workflow-connection-nodes.js +160 -0
  23. package/dist/builders/workflow-connections.d.ts +90 -0
  24. package/dist/builders/workflow-connections.js +560 -0
  25. package/dist/builders/workflow-control-nodes.d.ts +13 -0
  26. package/dist/builders/workflow-control-nodes.js +213 -0
  27. package/dist/builders/workflow-hydrator.d.ts +44 -3
  28. package/dist/builders/workflow-hydrator.js +53 -495
  29. package/dist/builders/workflow-verify.d.ts +19 -0
  30. package/dist/builders/workflow-verify.js +194 -0
  31. package/dist/conditions/conditions.d.ts +7 -5
  32. package/dist/conditions/conditions.js +7 -4
  33. package/dist/connections/blobs.d.ts +33 -0
  34. package/dist/connections/blobs.js +77 -0
  35. package/dist/connections/cron-schedule.d.ts +32 -0
  36. package/dist/connections/cron-schedule.js +213 -0
  37. package/dist/connections/durability.d.ts +65 -0
  38. package/dist/connections/durability.js +54 -0
  39. package/dist/connections/errors.d.ts +30 -0
  40. package/dist/connections/errors.js +100 -0
  41. package/dist/connections/event-stream.d.ts +24 -0
  42. package/dist/connections/event-stream.js +176 -0
  43. package/dist/connections/gates.d.ts +94 -0
  44. package/dist/connections/gates.js +271 -0
  45. package/dist/connections/glob.d.ts +10 -0
  46. package/dist/connections/glob.js +46 -0
  47. package/dist/connections/handle.d.ts +22 -0
  48. package/dist/connections/handle.js +84 -0
  49. package/dist/connections/harness-wiring.d.ts +52 -0
  50. package/dist/connections/harness-wiring.js +143 -0
  51. package/dist/connections/in-memory-connection.d.ts +147 -0
  52. package/dist/connections/in-memory-connection.js +593 -0
  53. package/dist/connections/index.d.ts +34 -0
  54. package/dist/connections/index.js +23 -0
  55. package/dist/connections/json-schema.d.ts +28 -0
  56. package/dist/connections/json-schema.js +338 -0
  57. package/dist/connections/model-tools.d.ts +46 -0
  58. package/dist/connections/model-tools.js +466 -0
  59. package/dist/connections/negotiation.d.ts +30 -0
  60. package/dist/connections/negotiation.js +159 -0
  61. package/dist/connections/policy.d.ts +21 -0
  62. package/dist/connections/policy.js +34 -0
  63. package/dist/connections/pool.d.ts +111 -0
  64. package/dist/connections/pool.js +339 -0
  65. package/dist/connections/refs.d.ts +74 -0
  66. package/dist/connections/refs.js +316 -0
  67. package/dist/connections/registry-types.d.ts +141 -0
  68. package/dist/connections/registry-types.js +14 -0
  69. package/dist/connections/registry.d.ts +125 -0
  70. package/dist/connections/registry.js +775 -0
  71. package/dist/connections/secrets.d.ts +59 -0
  72. package/dist/connections/secrets.js +153 -0
  73. package/dist/connections/settle.d.ts +9 -0
  74. package/dist/connections/settle.js +26 -0
  75. package/dist/connections/sources.d.ts +27 -0
  76. package/dist/connections/sources.js +300 -0
  77. package/dist/connections/triggers.d.ts +78 -0
  78. package/dist/connections/triggers.js +310 -0
  79. package/dist/connections/values.d.ts +26 -0
  80. package/dist/connections/values.js +93 -0
  81. package/dist/connections/views.d.ts +31 -0
  82. package/dist/connections/views.js +176 -0
  83. package/dist/expression/check.js +80 -1
  84. package/dist/expression/jsonata.d.ts +14 -4
  85. package/dist/expression/jsonata.js +27 -9
  86. package/dist/expression/step-outputs.d.ts +25 -0
  87. package/dist/expression/step-outputs.js +78 -0
  88. package/dist/harness/agent-harness.d.ts +69 -166
  89. package/dist/harness/agent-harness.js +170 -262
  90. package/dist/harness/call-span-collector.d.ts +33 -0
  91. package/dist/harness/call-span-collector.js +83 -0
  92. package/dist/harness/call-spend.d.ts +2 -0
  93. package/dist/harness/call-spend.js +10 -14
  94. package/dist/harness/connection-gate.d.ts +78 -0
  95. package/dist/harness/connection-gate.js +169 -0
  96. package/dist/harness/deps/interpreter.d.ts +1 -0
  97. package/dist/harness/deps/interpreter.js +1 -0
  98. package/dist/harness/deps/runtime.d.ts +1 -1
  99. package/dist/harness/deps/types.d.ts +1 -1
  100. package/dist/harness/harness-options.d.ts +153 -0
  101. package/dist/harness/harness-options.js +36 -0
  102. package/dist/harness/harness-tracing.d.ts +16 -0
  103. package/dist/harness/harness-tracing.js +35 -0
  104. package/dist/harness/llm-client.d.ts +71 -0
  105. package/dist/harness/llm-client.js +218 -0
  106. package/dist/harness/model-call.d.ts +2 -7
  107. package/dist/harness/model-call.js +141 -558
  108. package/dist/harness/model-request.d.ts +42 -0
  109. package/dist/harness/model-request.js +159 -0
  110. package/dist/harness/model-rounds.d.ts +18 -2
  111. package/dist/harness/model-rounds.js +39 -8
  112. package/dist/harness/model-stream.d.ts +39 -0
  113. package/dist/harness/model-stream.js +131 -0
  114. package/dist/harness/model-tool-round.d.ts +37 -0
  115. package/dist/harness/model-tool-round.js +197 -0
  116. package/dist/harness/spend.d.ts +2 -0
  117. package/dist/harness/spend.js +5 -1
  118. package/dist/index.d.ts +31 -6
  119. package/dist/index.js +18 -1
  120. package/dist/interpreter/connection-steps.d.ts +194 -0
  121. package/dist/interpreter/connection-steps.js +537 -0
  122. package/dist/interpreter/execute-action.d.ts +2 -8
  123. package/dist/interpreter/execute-action.js +3 -178
  124. package/dist/interpreter/execute-call.d.ts +19 -0
  125. package/dist/interpreter/execute-call.js +99 -0
  126. package/dist/interpreter/execute-control.d.ts +6 -1
  127. package/dist/interpreter/execute-control.js +14 -0
  128. package/dist/interpreter/execute-invoke-tool.d.ts +11 -0
  129. package/dist/interpreter/execute-invoke-tool.js +183 -0
  130. package/dist/interpreter/execute-verify.d.ts +21 -0
  131. package/dist/interpreter/execute-verify.js +391 -0
  132. package/dist/interpreter/execute-wait.d.ts +21 -0
  133. package/dist/interpreter/execute-wait.js +233 -0
  134. package/dist/interpreter/execute.js +24 -133
  135. package/dist/interpreter/step-kind-dispatch.d.ts +24 -0
  136. package/dist/interpreter/step-kind-dispatch.js +157 -0
  137. package/dist/interpreter/step-walk.d.ts +2 -0
  138. package/dist/interpreter/step-walk.js +24 -0
  139. package/dist/interpreter/verify-host.d.ts +40 -0
  140. package/dist/interpreter/verify-host.js +245 -0
  141. package/dist/runtime/durable/step-ledger.d.ts +34 -2
  142. package/dist/runtime/durable/step-ledger.js +97 -3
  143. package/dist/runtime/in-memory-artifact-store.d.ts +24 -0
  144. package/dist/runtime/in-memory-artifact-store.js +240 -0
  145. package/dist/schemas/workflow.d.ts +2 -2
  146. package/dist/schemas/workflow.js +1 -1
  147. package/dist/util/harness-internals.d.ts +23 -0
  148. package/dist/util/harness-internals.js +35 -0
  149. package/package.json +3 -3
  150. package/schema/noetic-workflow.schema.json +1170 -92
@@ -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 {};
@@ -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
@@ -14,6 +14,11 @@
14
14
  * belongs to the conversation the earlier recorded rounds built. When the step
15
15
  * finishes and records, the ledger prunes its rounds.
16
16
  *
17
+ * While a round streams, each output item it finishes is recorded at the same key as
18
+ * a `cut` round, so a host killed mid-stream resumes from those items rather than
19
+ * making them again. The round's own record replaces it. A cut round with neither a
20
+ * function call nor an answer has nothing to go on from, so replay stops there.
21
+ *
17
22
  * A call that fails charges its context with the rounds it recorded, so a failed run
18
23
  * reports what it paid. A retry in place replays those rounds on the same context,
19
24
  * so the ledger remembers which rounds were charged and the replay counts them no
@@ -28,6 +33,8 @@ export interface RoundRecord {
28
33
  input: unknown[];
29
34
  usage: RoundUsage;
30
35
  cost: number;
36
+ /** The stream had not finished: `items` holds the output items it had, tools not yet run. */
37
+ cut?: boolean;
31
38
  }
32
39
  /** A replayed round: its record plus the items it appended to the item log. */
33
40
  export interface ReplayedRound extends RoundRecord {
@@ -55,8 +62,17 @@ export declare class RoundLedger {
55
62
  take(round: number, schemas: ItemSchemaRegistry): ReplayedRound | undefined;
56
63
  /** Mark where the log stood when a round began, so its appends can be recorded. */
57
64
  mark(): number;
58
- /** Record a finished round. `logMark` is what `mark()` returned when it began. */
59
- record(round: number, logMark: number, record: RoundRecord): Promise<void>;
65
+ /**
66
+ * Record a round, finished or `cut`. `logMark` is what `mark()` returned when it
67
+ * began. Resolves whether the record was stored.
68
+ *
69
+ * Also drops the record of the round after it, left by an earlier attempt of the
70
+ * same step (a steering retry calls the model again at the same path). Replay
71
+ * stops at the first missing round, so the stale rounds past it are never read.
72
+ */
73
+ record(round: number, logMark: number, record: RoundRecord): Promise<boolean>;
74
+ /** Drop the record of round `round`: the loop threw that round away. */
75
+ drop(round: number): Promise<void>;
60
76
  /** Note that the rounds this loop recorded were charged to its context. */
61
77
  charged(): void;
62
78
  private key;
@@ -14,13 +14,19 @@
14
14
  * belongs to the conversation the earlier recorded rounds built. When the step
15
15
  * finishes and records, the ledger prunes its rounds.
16
16
  *
17
+ * While a round streams, each output item it finishes is recorded at the same key as
18
+ * a `cut` round, so a host killed mid-stream resumes from those items rather than
19
+ * making them again. The round's own record replaces it. A cut round with neither a
20
+ * function call nor an answer has nothing to go on from, so replay stops there.
21
+ *
17
22
  * A call that fails charges its context with the rounds it recorded, so a failed run
18
23
  * reports what it paid. A retry in place replays those rounds on the same context,
19
24
  * so the ledger remembers which rounds were charged and the replay counts them no
20
25
  * more.
21
26
  */
22
- import { frameworkCast } from '@noetic-tools/types';
27
+ import { frameworkCast, isAssistantMessage } from '@noetic-tools/types';
23
28
  import { z } from 'zod';
29
+ import { isFunctionCall } from '../interpreter/typeguards.js';
24
30
  import { ContextImpl } from './deps/runtime.js';
25
31
  //#region Types
26
32
  const ROUND_KIND = 'callModel:round';
@@ -34,6 +40,7 @@ const RoundOutputSchema = z.object({
34
40
  cacheWriteTokens: z.number().optional(),
35
41
  }),
36
42
  cost: z.number(),
43
+ cut: z.boolean().optional(),
37
44
  });
38
45
  /**
39
46
  * Keys of recorded rounds a failed call charged, per execution ledger. Kept in memory
@@ -52,7 +59,7 @@ export class RoundLedger {
52
59
  dispatch;
53
60
  replaying = true;
54
61
  /** Rounds this loop recorded. */
55
- recorded = [];
62
+ recorded = new Set();
56
63
  constructor(ctx, dispatch) {
57
64
  this.ctx = ctx;
58
65
  this.dispatch = dispatch;
@@ -85,12 +92,14 @@ export class RoundLedger {
85
92
  this.replaying = false;
86
93
  return undefined;
87
94
  }
95
+ let replayed;
88
96
  try {
89
- return {
97
+ replayed = {
90
98
  items: schemas.parseMany(parsed.data.items),
91
99
  input: parsed.data.input,
92
100
  usage: parsed.data.usage,
93
101
  cost: parsed.data.cost,
102
+ cut: parsed.data.cut,
94
103
  appended: schemas.parseMany(entry.items ?? []),
95
104
  charged: chargedRounds.get(ledger)?.has(this.key(round)) ?? false,
96
105
  };
@@ -99,17 +108,29 @@ export class RoundLedger {
99
108
  this.replaying = false;
100
109
  return undefined;
101
110
  }
111
+ if (replayed.cut && !replayed.items.some(goesOn)) {
112
+ this.replaying = false;
113
+ return undefined;
114
+ }
115
+ return replayed;
102
116
  }
103
117
  /** Mark where the log stood when a round began, so its appends can be recorded. */
104
118
  mark() {
105
119
  return this.ctx.appendedItems().length;
106
120
  }
107
- /** Record a finished round. `logMark` is what `mark()` returned when it began. */
121
+ /**
122
+ * Record a round, finished or `cut`. `logMark` is what `mark()` returned when it
123
+ * began. Resolves whether the record was stored.
124
+ *
125
+ * Also drops the record of the round after it, left by an earlier attempt of the
126
+ * same step (a steering retry calls the model again at the same path). Replay
127
+ * stops at the first missing round, so the stale rounds past it are never read.
128
+ */
108
129
  async record(round, logMark, record) {
109
130
  this.replaying = false;
110
131
  const ledger = this.ctx.ledger;
111
132
  if (!ledger) {
112
- return;
133
+ return false;
113
134
  }
114
135
  const appended = this.ctx.appendedItems().slice(logMark);
115
136
  const stored = await ledger.record({
@@ -126,16 +147,22 @@ export class RoundLedger {
126
147
  completedAt: new Date().toISOString(),
127
148
  });
128
149
  if (!stored) {
129
- return;
150
+ return false;
130
151
  }
131
- this.recorded.push(round);
152
+ this.recorded.add(round);
132
153
  // A new record holds a bill no context has been charged with yet.
133
154
  chargedRounds.get(ledger)?.delete(this.key(round));
155
+ await ledger.drop(this.key(round + 1));
156
+ return true;
157
+ }
158
+ /** Drop the record of round `round`: the loop threw that round away. */
159
+ async drop(round) {
160
+ await this.ctx.ledger?.drop(this.key(round));
134
161
  }
135
162
  /** Note that the rounds this loop recorded were charged to its context. */
136
163
  charged() {
137
164
  const ledger = this.ctx.ledger;
138
- if (!ledger || this.recorded.length === 0) {
165
+ if (!ledger || this.recorded.size === 0) {
139
166
  return;
140
167
  }
141
168
  const keys = chargedRounds.get(ledger) ?? new Set();
@@ -148,6 +175,10 @@ export class RoundLedger {
148
175
  return roundPath(this.dispatch.path, round);
149
176
  }
150
177
  }
178
+ /** A cut round holding a function call or an answer has something to go on from. */
179
+ function goesOn(item) {
180
+ return isFunctionCall(item) || isAssistantMessage(item);
181
+ }
151
182
  /** @internal The ledger key of round `round` of the model loop at step path `path`. */
152
183
  export function roundPath(path, round) {
153
184
  return `${path}/round#${round}`;
@@ -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>;