@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
@@ -1,19 +1,18 @@
1
- import { frameworkCast, ItemSchemaRegistry, NoeticConfigError } from '@noetic-tools/types';
2
- import { NoeticEvent } from '../observability/genai-attributes.js';
3
- import { SpanImpl } from '../observability/span-impl.js';
4
- import { NoopExporter } from '../observability/trace-exporter.js';
1
+ import { CONNECTION_EVENT_ITEM_TYPE, frameworkCast, ItemSchemaRegistry, NoeticConfigError, } from '@noetic-tools/types';
2
+ import { toStep } from '../builders/sequence.js';
3
+ import { runEvery } from '../connections/settle.js';
5
4
  import { AcpSessionStore } from '../runtime/acp-session-store.js';
6
- import { callDecide } from './decide-call.js';
7
- import { createInMemoryFsAdapter, createInMemoryShellAdapter, createInMemorySubprocessAdapter, HTTPClient, OpenRouter, OpenRouterSdk, } from './deps/adapters.js';
5
+ import { ConnectionGate } from './connection-gate.js';
8
6
  import { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, initLayers, notifyDecision, onSteerLayers, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from './deps/context.js';
9
- import { collectAllTools, collectCustomItems, deduplicateTools, dispatchStepThroughAdapter, execute, prepareBandedView, someStep, } from './deps/interpreter.js';
10
- import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createCheckpointStore, createInMemoryStorage, createSessionStore, createSpendLog, createStepLedgerStore, customItemGates, Drains, filterReasoningStream, filterTextStream, INTERRUPT_REASON, isSteer, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, warnToConsole, } from './deps/runtime.js';
7
+ import { clearPendingEntries, collectAllTools, collectCustomItems, deduplicateTools, dispatchStepThroughAdapter, execute, prepareBandedView, } from './deps/interpreter.js';
8
+ import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createInMemoryStorage, createSessionStore, createSpendLog, createStepLedgerStore, customItemGates, Drains, filterReasoningStream, filterTextStream, INTERRUPT_REASON, isSteer, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, } from './deps/runtime.js';
11
9
  import { SteeringAction } from './deps/types.js';
12
- import { AgentHarnessModelCaller, noLlmProviderError } from './model-call.js';
13
- import { DISPATCH_HEADER, GENERATION_HEADER, Spend } from './spend.js';
14
- import { ThreadRecord } from './thread-record.js';
15
- export { createStreamIdleWatchdog } from './model-call.js';
10
+ import { resolveCheckpointStore, resolveEnvironmentAdapters } from './harness-options.js';
11
+ import { createHarnessSpan, recordChannelWarning, resolveTraceExporter } from './harness-tracing.js';
12
+ import { LlmGateway } from './llm-client.js';
16
13
  import { buildItemSchemaRegistry } from './model-schema.js';
14
+ import { Spend } from './spend.js';
15
+ import { ThreadRecord } from './thread-record.js';
17
16
  //#endregion
18
17
  const DEFAULT_THREAD_ID = '__default__';
19
18
  /** Default idle-timeout for a single model call's streaming response. Chosen to be
@@ -41,167 +40,6 @@ function resolveContextCwdState(rootCwdState, parent, cwdInit) {
41
40
  }
42
41
  return rootCwdState;
43
42
  }
44
- /** The Noetic platform's OpenAI-Responses-compatible inference base URL. */
45
- const NOETIC_DEFAULT_BASE_URL = 'https://platform.noetic.tools/v1';
46
- function readLlmEnv() {
47
- const processValue = 'process' in globalThis ? globalThis.process : undefined;
48
- const env = typeof processValue === 'object' && processValue !== null && 'env' in processValue
49
- ? processValue.env
50
- : undefined;
51
- if (typeof env !== 'object' || env === null) {
52
- return {};
53
- }
54
- const str = (value) => typeof value === 'string' ? value : undefined;
55
- return {
56
- noeticApiKey: 'NOETIC_API_KEY' in env ? str(env.NOETIC_API_KEY) : undefined,
57
- noeticBaseUrl: 'NOETIC_BASE_URL' in env ? str(env.NOETIC_BASE_URL) : undefined,
58
- openrouterApiKey: 'OPENROUTER_API_KEY' in env ? str(env.OPENROUTER_API_KEY) : undefined,
59
- };
60
- }
61
- /**
62
- * Resolve the effective LLM client options from the provider config + environment.
63
- * Defaults to the Noetic platform (`provider: 'noetic'`): the `'noetic'` provider
64
- * authenticates with `NOETIC_API_KEY` and targets the Noetic platform base URL,
65
- * while `'openrouter'` authenticates with `OPENROUTER_API_KEY` and uses the SDK's
66
- * default OpenRouter endpoint. Returns undefined when no API key is available.
67
- * Exported for testing.
68
- */
69
- export function resolveLlmClient(config, env) {
70
- const provider = config?.provider ?? 'noetic';
71
- const apiKey = config?.apiKey ?? (provider === 'noetic' ? env.noeticApiKey : env.openrouterApiKey);
72
- if (!apiKey) {
73
- return undefined;
74
- }
75
- const serverURL = provider === 'noetic'
76
- ? (config?.baseUrl ?? env.noeticBaseUrl ?? NOETIC_DEFAULT_BASE_URL)
77
- : config?.baseUrl;
78
- return {
79
- apiKey,
80
- serverURL,
81
- cache: config?.cache ?? false,
82
- };
83
- }
84
- /**
85
- * Ask the provider to cache the prompt prefix.
86
- *
87
- * Anthropic caching is opt-in — without a breakpoint it caches nothing however
88
- * stable the prefix is, measured against live models. OpenRouter accepts a
89
- * `cache_control` directive on the request and places the breakpoints itself;
90
- * providers that cache on their own (OpenAI, Gemini) ignore it.
91
- *
92
- * It has to be injected here rather than passed with the other request fields:
93
- * the SDK validates the request against a generated schema that drops keys it
94
- * does not know, and `cache_control` is one of them.
95
- */
96
- async function addCacheBreakpoint(request) {
97
- const body = await request.clone().text();
98
- if (!body) {
99
- return request;
100
- }
101
- let payload;
102
- try {
103
- payload = JSON.parse(body);
104
- }
105
- catch {
106
- return request;
107
- }
108
- if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
109
- return request;
110
- }
111
- return new Request(request, {
112
- body: JSON.stringify({
113
- ...payload,
114
- cache_control: {
115
- type: 'ephemeral',
116
- },
117
- }),
118
- });
119
- }
120
- function createClient(config, contextCache, http) {
121
- const resolved = resolveLlmClient(config, readLlmEnv());
122
- if (!resolved) {
123
- return undefined;
124
- }
125
- const options = {
126
- apiKey: resolved.apiKey,
127
- };
128
- if (resolved.serverURL) {
129
- options.serverURL = resolved.serverURL;
130
- }
131
- if (http) {
132
- // The agent bundles an older SDK whose `HTTPClient` class is nominally different;
133
- // the agent calls only `request()` on it, which both versions share.
134
- options.httpClient = frameworkCast(http);
135
- }
136
- // A cache write costs more than a plain read, so the breakpoint only pays off
137
- // when something is holding the prefix still — which is what anchoring does.
138
- const wantsBreakpoint = contextCache?.enabled !== false;
139
- if (!resolved.cache && !wantsBreakpoint) {
140
- return new OpenRouter(options);
141
- }
142
- return new OpenRouter({
143
- ...options,
144
- hooks: {
145
- beforeRequest: async (_ctx, request) => {
146
- if (resolved.cache) {
147
- // Serve identical model calls from OpenRouter's own response cache
148
- // without re-billing (deterministic re-runs).
149
- request.headers.set('X-OpenRouter-Cache', 'true');
150
- }
151
- return wantsBreakpoint ? addCacheBreakpoint(request) : request;
152
- },
153
- },
154
- });
155
- }
156
- /**
157
- * An HTTP client that saves a paid call's generation id the moment its headers
158
- * arrive. The SDK awaits the hook before it reads the body, so a call cut off after
159
- * its headers can still be priced. Both the model client and the decisions client
160
- * send through it; requests without a dispatch header pass untouched.
161
- */
162
- function generationHook(spend) {
163
- return new HTTPClient().addHook('response', async (res, req) => {
164
- const dispatchId = req.headers.get(DISPATCH_HEADER);
165
- const generationId = res.headers.get(GENERATION_HEADER);
166
- // An error response is retried or refused; only a success carries the call's id.
167
- if (res.ok && dispatchId && generationId) {
168
- await spend.noteGeneration(dispatchId, generationId);
169
- }
170
- });
171
- }
172
- function createSdkClient(config, http) {
173
- const resolved = resolveLlmClient(config, readLlmEnv());
174
- if (!resolved) {
175
- return undefined;
176
- }
177
- return new OpenRouterSdk({
178
- apiKey: resolved.apiKey,
179
- serverURL: resolved.serverURL,
180
- ...(http
181
- ? {
182
- httpClient: http,
183
- }
184
- : {}),
185
- });
186
- }
187
- /**
188
- * The checkpoint store a harness runs with: the one given, else a store over the
189
- * configured storage adapter, so durable storage alone turns resume on. None when
190
- * the harness sets `durability: false`.
191
- */
192
- function resolveCheckpointStore(storage, durability) {
193
- if (durability === false) {
194
- return undefined;
195
- }
196
- if (storage?.checkpointStore) {
197
- return storage.checkpointStore;
198
- }
199
- return storage?.adapter
200
- ? createCheckpointStore({
201
- storage: storage.adapter,
202
- })
203
- : undefined;
204
- }
205
43
  //#region AgentHarness
206
44
  /**
207
45
  * Default agent harness for executing agent steps with built-in channel, context, and trace support.
@@ -244,20 +82,13 @@ export class AgentHarness {
244
82
  * so free functions in `runtime/durable/` (checkpoint/restore) can read it
245
83
  * without friend-class gymnastics. Do not access from outside core. */
246
84
  _contextLayers;
247
- client;
248
- /**
249
- * SDK 1.x client for the endpoints the agent's client predates: decisions, model
250
- * prices, and generation lookups.
251
- */
252
- sdkClient;
85
+ /** Provider clients and the model / decision calls made through them. */
86
+ llm;
253
87
  /**
254
88
  * Paid dispatch records, present exactly when durability is on.
255
89
  * @internal
256
90
  */
257
91
  spend;
258
- decideOverride;
259
- /** Model id → whether it answers natively as a decision model. */
260
- decisionModels = new Map();
261
92
  /** @internal Channel state; read by the checkpoint functions. */
262
93
  channelStore;
263
94
  /**
@@ -269,7 +100,6 @@ export class AgentHarness {
269
100
  sessionStore;
270
101
  /** Checkpoint capture in flight per execution id — see `saveCheckpoint`. */
271
102
  pendingCheckpoints = new Map();
272
- callModelOverride;
273
103
  defaultDeliveryMode;
274
104
  sessions = new Map();
275
105
  /**
@@ -280,6 +110,12 @@ export class AgentHarness {
280
110
  acpSessions = new AcpSessionStore();
281
111
  /** @internal Graceful stops in progress; the interpreter and model loop hold on them. */
282
112
  drains = new Drains();
113
+ /** Where binary content is stored: `environment.artifacts`, else an in-memory store. */
114
+ artifacts;
115
+ // Connection state lives in a true private field: anything holding `ctx.harness`
116
+ // must not reach the registry or the secret resolver (spec 35 § Gates, § Secrets).
117
+ // Core modules read the registry and verifier through `harnessInternal`.
118
+ #connections;
283
119
  /**
284
120
  * Snapshot of every live ACP sub-agent, for a UI that wants to show what is
285
121
  * running and let a user act on it. Read-only: a session's turns are driven
@@ -370,9 +206,10 @@ export class AgentHarness {
370
206
  emitItemsOnReplay: opts.emitItemsOnReplay,
371
207
  approveToolCall: opts.approveToolCall,
372
208
  };
373
- this.fs = environment?.fs ?? createInMemoryFsAdapter();
374
- this.shell = environment?.shell ?? createInMemoryShellAdapter();
375
- this.subprocess = environment?.subprocess ?? createInMemorySubprocessAdapter();
209
+ const adapters = resolveEnvironmentAdapters(environment);
210
+ this.fs = adapters.fs;
211
+ this.shell = adapters.shell;
212
+ this.subprocess = adapters.subprocess;
376
213
  this.checkpointStore = resolveCheckpointStore(storageEnv, opts.durability);
377
214
  this.stepLedgerStore = this.checkpointStore
378
215
  ? createStepLedgerStore({
@@ -386,22 +223,22 @@ export class AgentHarness {
386
223
  this.spend = this.checkpointStore
387
224
  ? this.createSpend(this.config.storage ?? createInMemoryStorage())
388
225
  : undefined;
389
- this.agentGraph = opts.agentGraph;
226
+ this.agentGraph = opts.agentGraph ? toStep(opts.agentGraph) : undefined;
390
227
  this.harnessTools = opts.tools ?? [];
391
228
  this._contextLayers = opts.contextLayers;
392
- this.callModelOverride = opts._testCallModel;
393
- const http = this.spend ? generationHook(this.spend) : undefined;
394
- this.client = opts._testCallModel
395
- ? undefined
396
- : createClient(opts.callModelDefaults, opts.contextCache, http);
397
- this.decideOverride = opts._testDecide;
398
- this.sdkClient = opts._testCallModel
399
- ? undefined
400
- : createSdkClient(opts.callModelDefaults, http);
229
+ this.llm = new LlmGateway({
230
+ agentName: opts.name,
231
+ providerConfig: opts.callModelDefaults,
232
+ contextCache: opts.contextCache,
233
+ spend: this.spend,
234
+ callModelOverride: opts._testCallModel,
235
+ decideOverride: opts._testDecide,
236
+ streamIdleTimeoutMs: DEFAULT_STREAM_IDLE_TIMEOUT_MS,
237
+ });
401
238
  this.channelStore = new ChannelStore({
402
239
  onWarning: (warning) => this.recordChannelWarning(warning),
403
240
  });
404
- this.traceExporter = opts.traceExporter ?? new NoopExporter();
241
+ this.traceExporter = resolveTraceExporter(opts.traceExporter);
405
242
  this.layerStateStore =
406
243
  storageEnv?.layerStateStore ??
407
244
  createLayerStateStore((layerId, hook, error) => {
@@ -414,13 +251,64 @@ export class AgentHarness {
414
251
  this.itemSchemas = new ItemSchemaRegistry(opts.itemSchemas?.schemas, {
415
252
  strictUnknownExtensions: opts.itemSchemas?.strict ?? true,
416
253
  }).extend({
417
- items: opts.agentGraph
418
- ? customItemGates(collectCustomItems(frameworkCast(opts.agentGraph)).map((item) => item.type))
419
- : [],
254
+ items: customItemGates([
255
+ ...(this.agentGraph
256
+ ? collectCustomItems(frameworkCast(this.agentGraph)).map((item) => item.type)
257
+ : []),
258
+ ...(opts.triggers && opts.triggers.length > 0
259
+ ? [
260
+ CONNECTION_EVENT_ITEM_TYPE,
261
+ ]
262
+ : []),
263
+ ]),
420
264
  });
421
265
  this.rootCwdState = {
422
266
  cwd: opts.initialCwd ?? '/',
423
267
  };
268
+ this.artifacts = adapters.artifacts;
269
+ this.#connections = new ConnectionGate({
270
+ harness: this,
271
+ connections: opts.connections,
272
+ triggers: opts.triggers,
273
+ storage: this.config.storage ?? createInMemoryStorage(),
274
+ artifacts: this.artifacts,
275
+ secrets: environment?.secrets,
276
+ verifier: opts.verification,
277
+ broadcasters: () => [
278
+ ...this.sessions.values(),
279
+ ].map((session) => session.runner.broadcaster),
280
+ });
281
+ this.#connections.registerGraphNeeds(this.agentGraph ? frameworkCast(this.agentGraph) : undefined);
282
+ }
283
+ /**
284
+ * Connects every connection provider and starts triggers. The first `execute()`
285
+ * or `run()` calls it; call it yourself for a harness that only reacts to
286
+ * triggers. Idempotent.
287
+ * @public
288
+ */
289
+ async start() {
290
+ await this.#connections.start();
291
+ }
292
+ /**
293
+ * Each connection's state, identity and pool usage; one entry for `name`, or all.
294
+ * @public
295
+ */
296
+ getConnectionStatus(name) {
297
+ return this.#connections.status(name);
298
+ }
299
+ /**
300
+ * Shuts down everything the harness holds open: stops triggers, releases
301
+ * every connection and pool lease, and closes every ACP session. Call it when
302
+ * the host is done with the harness; anything left open can keep the process
303
+ * alive. Everything is closed even when one part throws; the first failure is
304
+ * then rethrown. Idempotent.
305
+ * @public
306
+ */
307
+ async close() {
308
+ await runEvery([
309
+ () => this.#connections.close(),
310
+ () => this.closeAcpSessions(),
311
+ ]);
424
312
  }
425
313
  /**
426
314
  * Update the harness-wide root cwd. The TUI calls this in response to a
@@ -444,8 +332,9 @@ export class AgentHarness {
444
332
  hint: 'Pass `agentGraph` in constructor options, or use run() directly.',
445
333
  }));
446
334
  }
447
- if (this.lacksModelFor(this.agentGraph)) {
448
- return Promise.reject(noLlmProviderError());
335
+ const missingModel = this.llm.missingModelFor(this.agentGraph);
336
+ if (missingModel) {
337
+ return Promise.reject(missingModel);
449
338
  }
450
339
  const threadId = options?.threadId ?? DEFAULT_THREAD_ID;
451
340
  const deliveryMode = options?.deliveryMode ?? this.defaultDeliveryMode;
@@ -656,11 +545,14 @@ export class AgentHarness {
656
545
  _broadcaster: session.runner.broadcaster,
657
546
  });
658
547
  frameworkCast(ctx)._sessionQueue = session.runner.queue;
659
- if (this.agentGraph || this.harnessTools.length > 0) {
548
+ await this.start();
549
+ const connectionTools = this.#connections.tools();
550
+ if (this.agentGraph || this.harnessTools.length > 0 || connectionTools.length > 0) {
660
551
  const stepTools = this.agentGraph ? collectAllTools(this.agentGraph) : [];
661
552
  this.setUnifiedTools(ctx, [
662
553
  ...stepTools,
663
554
  ...this.harnessTools,
555
+ ...connectionTools,
664
556
  ]);
665
557
  }
666
558
  // Steers the last harness accepted but never applied go back in the queue;
@@ -743,29 +635,16 @@ export class AgentHarness {
743
635
  //#endregion
744
636
  //#region callModel
745
637
  async callModel(request) {
746
- return new AgentHarnessModelCaller({
747
- agentName: this.config.name,
638
+ return this.llm.callModel(request, {
748
639
  itemSchemas: this.itemSchemas,
749
- client: this.client,
750
- callModelOverride: this.callModelOverride,
751
- streamIdleTimeoutMs: DEFAULT_STREAM_IDLE_TIMEOUT_MS,
752
640
  harness: this,
753
641
  traceExporter: this.traceExporter,
754
- spend: this.spend,
755
- }).callModel(request);
642
+ });
756
643
  }
757
644
  //#endregion
758
645
  //#region decide
759
646
  async decide(request) {
760
- if (this.decideOverride) {
761
- return this.decideOverride(request);
762
- }
763
- return callDecide(request, {
764
- client: this.sdkClient,
765
- callModel: (r) => this.callModel(r),
766
- nativeModels: this.decisionModels,
767
- spend: this.spend,
768
- });
647
+ return this.llm.decide(request, (r) => this.callModel(r));
769
648
  }
770
649
  async notifyDecision(layers, record, ctx) {
771
650
  await this.trackHook(ctx, notifyDecision({
@@ -776,43 +655,57 @@ export class AgentHarness {
776
655
  recallCache: this.recallCache,
777
656
  }));
778
657
  }
779
- //#endregion
780
658
  async run(s, input, ctx) {
781
- if (this.lacksModelFor(s)) {
782
- throw noLlmProviderError();
659
+ const root = toStep(s);
660
+ await this.dropRerunsOnFailure(ctx, () => this.prepareRun(root, ctx));
661
+ return this.executeClosingChannels(root, input, ctx);
662
+ }
663
+ /**
664
+ * Everything `run()` does before the root executes: fail fast on a missing
665
+ * model provider, connect, negotiate the root, wire the tool pool and run the
666
+ * layers' `init` hooks.
667
+ */
668
+ async prepareRun(root, ctx) {
669
+ const missingModel = this.llm.missingModelFor(root);
670
+ if (missingModel) {
671
+ throw missingModel;
783
672
  }
784
673
  // Populate the unified tool pool when an embedder drives a step directly on
785
674
  // a bare `createContext()` context (the turn pipeline does this per turn).
786
675
  // Without it, steps that resolve tools dynamically from `ctx.unifiedTools`
787
676
  // — and any sub-agents spawned from them — would see no tools.
788
- if (!ctx.unifiedTools && (s !== undefined || this.harnessTools.length > 0)) {
677
+ await this.start();
678
+ this.#connections.negotiateRoot(frameworkCast(root));
679
+ if (!ctx.unifiedTools) {
789
680
  this.setUnifiedTools(ctx, [
790
- ...collectAllTools(s),
681
+ ...collectAllTools(root),
791
682
  ...this.harnessTools,
683
+ ...this.#connections.tools(),
792
684
  ]);
793
685
  }
794
686
  // Hydrate/recall/persist context on the bare `run()` path too (issue #48):
795
687
  // configuring `context` + `storage` must "just work" without going through
796
688
  // `execute()`/`seedSessionHistory`. Idempotent — see `ensureLayersInit`.
797
689
  await this.ensureLayersInit(ctx);
798
- return this.executeClosingChannels(s, input, ctx);
799
690
  }
800
691
  /**
801
- * Whether `step` calls a model this harness has no credentials for. Checked
802
- * before any step runs so a missing provider fails fast instead of after
803
- * earlier steps' side effects. Steps the walk cannot see (dynamic branches)
804
- * still hit the same error lazily at their model call.
692
+ * Runs `prepare`, ending any rerun allowance `ctx` carries from its restore
693
+ * when it throws: a run that fails before executing still ends the restore's
694
+ * allowance, as one that executes does.
805
695
  */
806
- lacksModelFor(step) {
807
- if (this.client || this.callModelOverride) {
808
- return false;
696
+ async dropRerunsOnFailure(ctx, prepare) {
697
+ try {
698
+ await prepare();
699
+ }
700
+ catch (error) {
701
+ this.#connections.dropReruns(ctx);
702
+ throw error;
809
703
  }
810
- return someStep(frameworkCast(step), (s) => s.kind === 'callModel' || (s.kind === 'decide' && !this.decideOverride));
811
704
  }
812
705
  /** Run all layer `init` hooks before the first step executes. Per spec 11,
813
706
  * init MUST complete before any recall fires so layer state is populated. */
814
707
  async initAndRun(s, input, ctx) {
815
- await this.ensureLayersInit(ctx);
708
+ await this.dropRerunsOnFailure(ctx, () => this.ensureLayersInit(ctx));
816
709
  return this.executeClosingChannels(s, input, ctx);
817
710
  }
818
711
  /**
@@ -841,7 +734,8 @@ export class AgentHarness {
841
734
  // A restored or sequentially re-run root context reuses its id — clear
842
735
  // any closure from a previous completion so its channels work again.
843
736
  this.channelStore.openExecution(ctx.id);
844
- entry.ready = this.beginDurableRun(ctx);
737
+ this.#connections.grantReruns(ctx);
738
+ entry.ready = this.beginDurableRun(ctx).then(() => this.reconcileConnections(ctx));
845
739
  }
846
740
  try {
847
741
  await entry.ready;
@@ -857,7 +751,14 @@ export class AgentHarness {
857
751
  this.liveRoots.delete(ctx.id);
858
752
  this.channelStore.closeExecution(ctx.id);
859
753
  await this.acpSessions.closeOwnedBy(ctx.id);
860
- if (!entry.failed) {
754
+ if (entry.failed) {
755
+ // A failed run keeps its pool leases, unrenewed, so a resume within the
756
+ // reclaim window gets the same connections back and an abandoned one
757
+ // frees them (spec 35 § Pools and leases).
758
+ this.#connections.orphanRun(ctx.id);
759
+ }
760
+ else {
761
+ await this.#connections.releaseRun(ctx.id);
861
762
  await this.endDurableRun(ctx);
862
763
  }
863
764
  }
@@ -882,6 +783,16 @@ export class AgentHarness {
882
783
  ctx.beginRun();
883
784
  void this.saveCheckpoint(ctx);
884
785
  }
786
+ /**
787
+ * Before a resumed run replays anything, checks the connections its ledger and
788
+ * pending entries were recorded against, discarding the ledger from the first
789
+ * entry whose connection was replaced (spec 35 § Durability).
790
+ *
791
+ * @throws NoeticErrorImpl `connection_resume_refused` when a replaced connection is unsafe to drive again.
792
+ */
793
+ async reconcileConnections(ctx) {
794
+ await this.#connections.reconcile(ctx, this.config.storage);
795
+ }
885
796
  /**
886
797
  * Stand `ctx` at its stored baseline and give it the stored ledger. Without a
887
798
  * snapshot (its save failed), the baseline the context fixed in memory when the run
@@ -917,6 +828,9 @@ export class AgentHarness {
917
828
  if (await this.saveCheckpoint(ctx)) {
918
829
  await ctx.ledger?.dropPaths();
919
830
  }
831
+ if (this.config.storage) {
832
+ await clearPendingEntries(this.config.storage, ctx.id);
833
+ }
920
834
  }
921
835
  /**
922
836
  * Idempotently run layer `init` hooks for `ctx` (keyed by `ctx.id`). Init
@@ -949,14 +863,21 @@ export class AgentHarness {
949
863
  * settle is only observable via `await()`, and calling it internally would consume
950
864
  * the result the caller is holding. The handle manifest is the adapter's own
951
865
  * durability surface (`listLive`/`reattach`), so nothing is lost. */
952
- return dispatchStepThroughAdapter(this, s, input, parentCtx, overrides);
866
+ return dispatchStepThroughAdapter(this, toStep(s), input, parentCtx, overrides);
953
867
  }
954
868
  createContext(opts) {
955
869
  const resolved = opts ?? {};
956
870
  // `ContextImpl` takes the layers as `layers`, so the option spelling is
957
871
  // dropped from `rest` rather than spread through under the wrong name.
958
872
  const { contextLayers, extraContextLayers, cwdInit, ...rest } = resolved;
959
- const baseLayers = contextLayers ?? this._contextLayers;
873
+ const configuredLayers = contextLayers ?? this._contextLayers;
874
+ const views = this.#connections.views;
875
+ const baseLayers = views.length > 0
876
+ ? [
877
+ ...(configuredLayers ?? []),
878
+ ...views,
879
+ ]
880
+ : configuredLayers;
960
881
  const effectiveLayers = extraContextLayers && extraContextLayers.length > 0
961
882
  ? [
962
883
  ...(baseLayers ?? []),
@@ -1255,7 +1176,8 @@ export class AgentHarness {
1255
1176
  * returned context (`heldCost`) and reconciled in the background.
1256
1177
  */
1257
1178
  async restore(executionId, opts) {
1258
- const restored = await restoreFromCheckpoint(this, executionId, opts);
1179
+ const { rerun, ...restoreOptions } = opts ?? {};
1180
+ const restored = await restoreFromCheckpoint(this, executionId, restoreOptions);
1259
1181
  if (!restored) {
1260
1182
  return null;
1261
1183
  }
@@ -1263,6 +1185,11 @@ export class AgentHarness {
1263
1185
  this.restoredExecutions.add(executionId);
1264
1186
  }
1265
1187
  await this.spend?.adopt(restored.ctx);
1188
+ // Granted only to the context this restore returns: a restore that fails, or a
1189
+ // later plain restore of the same id, never inherits it (spec 35 § Durability).
1190
+ if (rerun && rerun.length > 0) {
1191
+ this.#connections.holdReruns(restored.ctx, rerun);
1192
+ }
1266
1193
  return restored.ctx;
1267
1194
  }
1268
1195
  /**
@@ -1317,7 +1244,7 @@ export class AgentHarness {
1317
1244
  return new Spend({
1318
1245
  agentName: this.config.name,
1319
1246
  log: createSpendLog(storage),
1320
- client: () => this.sdkClient,
1247
+ client: () => this.llm?.sdkClient,
1321
1248
  liveRoot: (executionId) => this.liveRoots.get(executionId)?.ctx,
1322
1249
  chargeSession: (threadId, charge) => this.chargeSession(threadId, charge),
1323
1250
  sessionBroadcaster: (threadId) => this.sessions.get(threadId)?.runner.broadcaster,
@@ -1431,31 +1358,12 @@ export class AgentHarness {
1431
1358
  ...layers,
1432
1359
  ], ctx);
1433
1360
  }
1434
- /**
1435
- * Channel state is shared by every root on this harness, so a channel
1436
- * warning is recorded as a `channel.warning` event on each live root's
1437
- * span (spec 10). A root span counts only if it will reach the trace
1438
- * exporter — a harness span (`SpanImpl`) with a real exporter configured.
1439
- * With no such span the warning goes to the console, so it is never lost.
1440
- */
1361
+ /** Records a channel warning on every live root's span (see `recordChannelWarning`). */
1441
1362
  recordChannelWarning(warning) {
1442
- const traced = this.traceExporter instanceof NoopExporter
1443
- ? []
1444
- : [
1445
- ...this.liveRoots.values(),
1446
- ].filter(({ ctx }) => ctx.span instanceof SpanImpl);
1447
- if (traced.length === 0) {
1448
- warnToConsole(warning);
1449
- return;
1450
- }
1451
- for (const { ctx } of traced) {
1452
- ctx.span.addEvent(NoeticEvent.CHANNEL_WARNING, {
1453
- ...warning,
1454
- });
1455
- }
1363
+ recordChannelWarning(warning, this.traceExporter, this.liveRoots.values());
1456
1364
  }
1457
1365
  createSpan(name, parent) {
1458
- return new SpanImpl(name, parent);
1366
+ return createHarnessSpan(name, parent);
1459
1367
  }
1460
1368
  getLayerState(executionId, layerId) {
1461
1369
  return this.layerStateStore.get(executionId, layerId);
@@ -0,0 +1,33 @@
1
+ import type { AgentHarnessContract, RoundUsage, Span, TraceExporter } from '@noetic-tools/types';
2
+ import type { ApprovalOutcome } from '../runtime/tool-approval.js';
3
+ /**
4
+ * Per-`callModel` span accumulator. Spans are created lazily from the calling
5
+ * context's span (so the trace tree mirrors the execution tree) and flushed to
6
+ * the harness `traceExporter` once the call settles — see issue #50, where the
7
+ * exporter was stored but never invoked.
8
+ */
9
+ export declare class CallSpanCollector {
10
+ private readonly harness;
11
+ private readonly exporter;
12
+ private readonly parent;
13
+ private readonly nodeId;
14
+ /** Stamped on the first model span only, then dropped. */
15
+ private firstSpanAttributes;
16
+ private readonly spans;
17
+ constructor(harness: AgentHarnessContract, exporter: TraceExporter, parent: Span | null, nodeId: string | undefined,
18
+ /** Stamped on the first model span only, then dropped. */
19
+ firstSpanAttributes: Record<string, string | number | boolean> | undefined);
20
+ /** Link a span back to its declared workflow node, when the call carries one. */
21
+ private stampNode;
22
+ /** Open a model-call span stamped with GenAI semantic-convention attributes. */
23
+ startModelSpan(model: string): Span;
24
+ /** Record usage + cost on a model-call span. */
25
+ finishModelSpan(span: Span, usage: RoundUsage, cost: number | undefined): void;
26
+ /**
27
+ * Open and immediately close a tool-call span under the given model span, or under
28
+ * the call's parent when the round's model call ran in an earlier attempt.
29
+ */
30
+ recordToolSpan(parent: Span | null, toolName: string, needsApproval: boolean, approval: ApprovalOutcome | undefined): void;
31
+ /** Flush all accumulated spans to the exporter. */
32
+ flush(): Promise<void>;
33
+ }