@noetic-tools/core 5.20.0-next.1 → 5.21.0

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 (92) hide show
  1. package/dist/adapters/openrouter.d.ts +1 -48
  2. package/dist/adapters/openrouter.js +3 -204
  3. package/dist/builders/acp-agent-checks.d.ts +20 -0
  4. package/dist/builders/acp-agent-checks.js +68 -0
  5. package/dist/builders/acp-agent-tool.d.ts +4 -3
  6. package/dist/builders/acp-agent-tool.js +5 -2
  7. package/dist/builders/connection-ceiling.d.ts +13 -0
  8. package/dist/builders/connection-ceiling.js +17 -0
  9. package/dist/builders/document-entries.d.ts +13 -0
  10. package/dist/builders/document-entries.js +18 -0
  11. package/dist/builders/dynamic-workflow.d.ts +53 -8
  12. package/dist/builders/dynamic-workflow.js +53 -25
  13. package/dist/builders/mcp-url-pattern.d.ts +13 -0
  14. package/dist/builders/mcp-url-pattern.js +85 -0
  15. package/dist/builders/step-builders.d.ts +14 -6
  16. package/dist/builders/step-builders.js +25 -2
  17. package/dist/builders/workflow-acp-grants.d.ts +42 -0
  18. package/dist/builders/workflow-acp-grants.js +224 -0
  19. package/dist/builders/workflow-child-nodes.js +8 -0
  20. package/dist/builders/workflow-connection-nodes.d.ts +13 -3
  21. package/dist/builders/workflow-connection-nodes.js +129 -3
  22. package/dist/builders/workflow-connections.js +2 -1
  23. package/dist/builders/workflow-hydrator.d.ts +24 -1
  24. package/dist/builders/workflow-hydrator.js +8 -167
  25. package/dist/builders/workflow-mcp-servers.d.ts +44 -0
  26. package/dist/builders/workflow-mcp-servers.js +327 -0
  27. package/dist/builders/workflow-tool-entries.d.ts +84 -0
  28. package/dist/builders/workflow-tool-entries.js +216 -0
  29. package/dist/connections/durability.d.ts +11 -1
  30. package/dist/connections/durability.js +34 -0
  31. package/dist/connections/entries.d.ts +33 -0
  32. package/dist/connections/entries.js +118 -0
  33. package/dist/connections/errors.d.ts +6 -0
  34. package/dist/connections/errors.js +12 -0
  35. package/dist/connections/harness-wiring.d.ts +4 -4
  36. package/dist/connections/harness-wiring.js +1 -1
  37. package/dist/connections/in-memory-connection.d.ts +2 -0
  38. package/dist/connections/in-memory-connection.js +5 -0
  39. package/dist/connections/model-tools.d.ts +35 -12
  40. package/dist/connections/model-tools.js +348 -202
  41. package/dist/connections/registry-types.d.ts +7 -0
  42. package/dist/connections/registry.d.ts +35 -6
  43. package/dist/connections/registry.js +183 -39
  44. package/dist/connections/step-tools.d.ts +64 -0
  45. package/dist/connections/step-tools.js +154 -0
  46. package/dist/connections/views.d.ts +3 -2
  47. package/dist/connections/views.js +15 -6
  48. package/dist/harness/agent-harness.d.ts +11 -1
  49. package/dist/harness/agent-harness.js +69 -8
  50. package/dist/harness/connection-gate.d.ts +49 -8
  51. package/dist/harness/connection-gate.js +137 -26
  52. package/dist/harness/deps/interpreter.d.ts +3 -3
  53. package/dist/harness/deps/interpreter.js +3 -3
  54. package/dist/harness/harness-options.d.ts +4 -3
  55. package/dist/harness/model-call.d.ts +0 -1
  56. package/dist/harness/model-call.js +0 -48
  57. package/dist/harness/model-request.js +3 -1
  58. package/dist/harness/model-schema.d.ts +1 -19
  59. package/dist/harness/model-schema.js +0 -28
  60. package/dist/harness/model-tool-round.js +2 -2
  61. package/dist/index.d.ts +5 -5
  62. package/dist/index.js +1 -1
  63. package/dist/interpreter/acp-events.d.ts +25 -1
  64. package/dist/interpreter/acp-events.js +53 -1
  65. package/dist/interpreter/acp-layers.d.ts +20 -0
  66. package/dist/interpreter/acp-layers.js +55 -0
  67. package/dist/interpreter/acp-tools.d.ts +108 -0
  68. package/dist/interpreter/acp-tools.js +462 -0
  69. package/dist/interpreter/collect-tools.d.ts +28 -0
  70. package/dist/interpreter/collect-tools.js +112 -15
  71. package/dist/interpreter/connection-steps.d.ts +0 -2
  72. package/dist/interpreter/connection-steps.js +30 -8
  73. package/dist/interpreter/execute-acp-agent.js +263 -72
  74. package/dist/interpreter/execute-action.d.ts +76 -1
  75. package/dist/interpreter/execute-action.js +35 -42
  76. package/dist/interpreter/execute.d.ts +2 -0
  77. package/dist/interpreter/execute.js +24 -1
  78. package/dist/interpreter/verify-host.js +2 -1
  79. package/dist/runtime/tool-call.d.ts +67 -0
  80. package/dist/runtime/tool-call.js +244 -0
  81. package/dist/runtime/tool-context.d.ts +1 -2
  82. package/dist/runtime/tool-context.js +6 -2
  83. package/dist/schemas/workflow.d.ts +1 -1
  84. package/dist/types/connection-entry.d.ts +22 -0
  85. package/dist/types/connection-entry.js +8 -0
  86. package/dist/util/harness-internals.d.ts +2 -0
  87. package/dist/util/root-context.d.ts +3 -0
  88. package/dist/util/root-context.js +8 -0
  89. package/dist/util/tool-name.d.ts +8 -0
  90. package/dist/util/tool-name.js +10 -0
  91. package/package.json +3 -3
  92. package/schema/noetic-workflow.schema.json +498 -128
@@ -7,9 +7,9 @@
7
7
  * Steps never hold a provider's `Connection`: everything goes through the
8
8
  * registry contract in `connections/registry-types.ts`.
9
9
  */
10
- import { frameworkCast, NoeticConfigError, NoeticErrorImpl } from '@noetic-tools/types';
10
+ import { frameworkCast, isConnectionPick, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
11
11
  import { z } from 'zod';
12
- import { resumeDecision } from '../connections/durability.js';
12
+ import { resumeDecision, stepPathOf } from '../connections/durability.js';
13
13
  import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
14
14
  import { ContextImpl } from '../runtime/context-impl.js';
15
15
  import { harnessInternal } from '../util/harness-internals.js';
@@ -53,7 +53,7 @@ export function connectionRegistryOf(ctx, name) {
53
53
  throw new NoeticConfigError({
54
54
  code: 'CONNECTION_UNKNOWN',
55
55
  message: `Connection '${name}' is used, but the harness has no connections.`,
56
- hint: `Add it to the harness: new AgentHarness({ connections: { ${name}: mcp('…') } }).`,
56
+ hint: `Add it to the harness: new AgentHarness({ connections: [mcp({ name: '${name}', type: 'http', url: '…' })] }).`,
57
57
  });
58
58
  }
59
59
  /** The topmost ancestor of `ctx`: the run's root context, whose id names the run. */
@@ -101,11 +101,6 @@ export async function releasePathLeases(paths) {
101
101
  await registry.releaseScope(pathScopeKey(path)).catch(() => undefined);
102
102
  }
103
103
  }
104
- /** The ledger path of the step running on `ctx`, when it runs on a lane. */
105
- export function stepPathOf(ctx) {
106
- const path = ctx instanceof ContextImpl ? ctx.currentPath() : '';
107
- return path.length > 0 ? path : undefined;
108
- }
109
104
  /** The run-and-step key a call carries, stable across a resume of the same run (spec 35 § Durability). */
110
105
  export function idempotencyKeyFor(ctx, stepId, ledgerKey) {
111
106
  return `${runRootOf(ctx).id}:${ledgerKey ?? stepPathOf(ctx) ?? stepId}`;
@@ -199,6 +194,29 @@ export function requirementFor(target, use) {
199
194
  : {}),
200
195
  };
201
196
  }
197
+ /** What the picks in a model step's eager `tools` need: a picked handle's profile range. */
198
+ function pickNeeds(tools) {
199
+ if (!Array.isArray(tools)) {
200
+ return [];
201
+ }
202
+ return tools.flatMap((entry) => {
203
+ if (!isConnectionPick(entry) || !entry.requirement) {
204
+ return [];
205
+ }
206
+ return [
207
+ {
208
+ name: entry.connection,
209
+ ...(entry.profile
210
+ ? {
211
+ profile: entry.profile,
212
+ }
213
+ : {}),
214
+ requirement: entry.requirement,
215
+ setup: false,
216
+ },
217
+ ];
218
+ });
219
+ }
202
220
  /**
203
221
  * Every connection need a graph states up front: each `call` and `wait` whose
204
222
  * connection is a static handle, with its profile and requirement. The harness
@@ -208,6 +226,10 @@ export function requirementFor(target, use) {
208
226
  export function graphConnectionNeeds(graph) {
209
227
  const needs = [];
210
228
  someStep(graph, (step) => {
229
+ if (step.kind === 'callModel') {
230
+ needs.push(...pickNeeds(step.tools));
231
+ return false;
232
+ }
211
233
  if (step.kind !== 'call' && step.kind !== 'wait') {
212
234
  return false;
213
235
  }
@@ -7,9 +7,13 @@
7
7
  * protocol library or agent SDK enters its dependency graph.
8
8
  */
9
9
  import { createMessage, extractAssistantText, frameworkCast, NoeticConfigError, NoeticErrorImpl, SteeringAction, } from '@noetic-tools/types';
10
+ import { assertAgentTakesTools } from '../builders/acp-agent-checks.js';
11
+ import { runtimeOf } from '../connections/model-tools.js';
10
12
  import { AcpEventBridge } from './acp-events.js';
11
13
  import { withHistoryPrompt } from './acp-history.js';
12
- import { resolveLazy } from './execute-action.js';
14
+ import { renderLayerContext } from './acp-layers.js';
15
+ import { AcpToolRunner, mergeBridgedItems, resolveAcpTools } from './acp-tools.js';
16
+ import { appendUserInput, MAX_STEERING_RETRIES, resolveLazy } from './execute-action.js';
13
17
  import { trackUsage } from './message-helpers.js';
14
18
  import { parseStructuredOutput } from './structured-output.js';
15
19
  import { isContextImpl, isFunctionCall, isMutableContext } from './typeguards.js';
@@ -165,6 +169,24 @@ function bindHostToStep(host, opts) {
165
169
  : undefined;
166
170
  host.onSessionUpdate = opts.onUpdate;
167
171
  host.onClientActivity = opts.onActivity;
172
+ // A step that gives no tools gets none, even on a session another step
173
+ // opened with tools. The session's runner stays listed, so the agent's
174
+ // permission requests are still recognized, but its calls answer as unknown
175
+ // tools.
176
+ if (!opts.tools) {
177
+ if (host.tools instanceof AcpToolRunner) {
178
+ host.tools.unbind();
179
+ }
180
+ return;
181
+ }
182
+ host.tools = opts.tools;
183
+ opts.tools.bind({
184
+ stepId: opts.step.id,
185
+ ctx: opts.ctx,
186
+ layers: opts.layers,
187
+ events: opts.events,
188
+ fail: opts.failTurn,
189
+ });
168
190
  }
169
191
  function buildHost(opts) {
170
192
  const host = {
@@ -199,14 +221,11 @@ function normalizedCapabilities(config) {
199
221
  });
200
222
  }
201
223
  /**
202
- * `cwd` and `mcpServers` are fixed when the session is created, so a step
203
- * joining an existing one cannot change them either.
204
- *
205
- * These used to be dropped in silence while a mismatched `clientCapabilities`
206
- * threw — so a step that named different MCP servers simply got none of them,
207
- * with no diagnostic. Connection-scoped settings should all fail the same way.
224
+ * `cwd` and the served tools are fixed when the session is created, so a step
225
+ * joining an existing one cannot change them either. Connection-scoped
226
+ * settings all fail the same way: a mismatch throws rather than being dropped.
208
227
  */
209
- function assertSessionScopedSettingsMatch(step, live, cwd, servers) {
228
+ function assertSessionScopedSettingsMatch(step, live, cwd, tools) {
210
229
  const conflict = (setting, hint) => new NoeticConfigError({
211
230
  code: 'ACP_SESSION_SETTING_CONFLICT',
212
231
  message: `step.acpAgent(${JSON.stringify(step.id)}) reuses session '${step.session?.reuse}' but requests a different ${setting} than the session was created with.`,
@@ -215,10 +234,18 @@ function assertSessionScopedSettingsMatch(step, live, cwd, servers) {
215
234
  if (cwd !== live.cwd) {
216
235
  throw conflict('cwd', 'A session is created in one working directory. Give every step sharing a `session.reuse` key the same `cwd`, or use a separate session.');
217
236
  }
218
- // Only a step that asks for servers can conflict; omitting them means
219
- // "whatever the session already has".
220
- if (servers && JSON.stringify(servers) !== JSON.stringify(live.mcpServers ?? [])) {
221
- throw conflict('set of MCP servers', 'MCP servers are attached when the session is created. Give every step sharing a `session.reuse` key the same `mcpServers`, or use a separate session.');
237
+ // The agent reads its tool list once, so a step may serve any part of it —
238
+ // a call to a tool outside its part answers as unknown, as on `callModel` —
239
+ // but nothing the list lacks.
240
+ const listed = new Map((live.tools ?? []).map((tool) => [
241
+ tool.name,
242
+ JSON.stringify(tool),
243
+ ]));
244
+ const unlisted = (tools?.tools ?? [])
245
+ .filter((tool) => listed.get(tool.name) !== JSON.stringify(tool))
246
+ .map((tool) => tool.name);
247
+ if (unlisted.length > 0) {
248
+ throw conflict(`set of tools (${unlisted.join(', ')} ${unlisted.length === 1 ? 'is' : 'are'} not in the session's tool list, or differ)`, 'The agent reads its tool list once, when the session is created. Give the step that opens a `session.reuse` session every tool a later step will serve, or use a separate session.');
222
249
  }
223
250
  }
224
251
  /**
@@ -279,10 +306,10 @@ async function openSession(opts) {
279
306
  // its step has to be reachable, or nothing can ever close it.
280
307
  const key = store.keyFor(parts);
281
308
  const { live, fresh } = await store.acquire(key, parts, async () => {
282
- const connection = await opts.agent.connect({
309
+ const connection = holdingConnections(await opts.agent.connect({
283
310
  host: opts.host,
284
311
  signal: abortSignalOf(opts.baseCtx),
285
- });
312
+ }), opts.baseCtx, keepAlive);
286
313
  // From here on the connection owns a live agent (usually a child process).
287
314
  // Anything that throws before the caller can take responsibility for it
288
315
  // must close it first — otherwise the agent outlives the step and, because
@@ -293,11 +320,9 @@ async function openSession(opts) {
293
320
  ? await connection.loadSession({
294
321
  sessionId: loadId,
295
322
  cwd: opts.cwd,
296
- mcpServers: opts.servers,
297
323
  })
298
324
  : await connection.newSession({
299
325
  cwd: opts.cwd,
300
- mcpServers: opts.servers,
301
326
  });
302
327
  return {
303
328
  connection,
@@ -306,7 +331,7 @@ async function openSession(opts) {
306
331
  agentId: opts.agent.agentId,
307
332
  keepAlive,
308
333
  cwd: opts.cwd,
309
- mcpServers: opts.servers,
334
+ tools: opts.tools?.tools,
310
335
  };
311
336
  }
312
337
  catch (e) {
@@ -315,7 +340,7 @@ async function openSession(opts) {
315
340
  }
316
341
  });
317
342
  if (!fresh) {
318
- assertSessionScopedSettingsMatch(opts.step, live, opts.cwd, opts.servers);
343
+ assertSessionScopedSettingsMatch(opts.step, live, opts.cwd, opts.tools);
319
344
  if (live.agentId !== opts.agent.agentId) {
320
345
  throw new NoeticConfigError({
321
346
  code: 'ACP_SESSION_AGENT_CONFLICT',
@@ -334,6 +359,29 @@ async function openSession(opts) {
334
359
  fresh,
335
360
  };
336
361
  }
362
+ /**
363
+ * A connection kept past its step holds the turn's connections until it
364
+ * closes: its agent may still call tools of entries the turn attached, which
365
+ * would otherwise be released when the turn ends.
366
+ */
367
+ function holdingConnections(connection, ctx, keepAlive) {
368
+ const registry = runtimeOf(ctx.harness);
369
+ if (keepAlive === 'step' || !registry) {
370
+ return connection;
371
+ }
372
+ const release = registry.hold(rootContextId(ctx));
373
+ const close = connection.close.bind(connection);
374
+ return Object.assign(connection, {
375
+ async close() {
376
+ try {
377
+ await close();
378
+ }
379
+ finally {
380
+ release();
381
+ }
382
+ },
383
+ });
384
+ }
337
385
  /**
338
386
  * Tear the connection down per policy. Nothing is kept unless the step asked
339
387
  * for it: only `keepAlive: 'run' | 'harness'` survives the step, and the run
@@ -395,10 +443,105 @@ function turnFailure(step, cause, baseCtx) {
395
443
  return new NoeticErrorImpl({
396
444
  kind: 'step_failed',
397
445
  stepId: step.id,
398
- cause: cause instanceof Error ? cause : new Error(String(cause)),
446
+ cause: cause instanceof Error ? cause : new Error(describeCause(cause)),
399
447
  retriesExhausted: false,
400
448
  });
401
449
  }
450
+ /** A readable message for a thrown non-Error, such as a JSON-RPC error object. */
451
+ function describeCause(cause) {
452
+ if (typeof cause !== 'object' || cause === null) {
453
+ return String(cause);
454
+ }
455
+ const message = Reflect.get(cause, 'message');
456
+ const data = Reflect.get(cause, 'data');
457
+ const head = typeof message === 'string' ? message : JSON.stringify(cause);
458
+ return data === undefined ? head : `${head}: ${JSON.stringify(data)}`;
459
+ }
460
+ /**
461
+ * The tools the agent is served. No `tools` offers every tool the run has,
462
+ * as on `callModel`, and an agent that cannot take tools then simply gets
463
+ * none; tools given explicitly to such an agent are a configuration error.
464
+ */
465
+ async function resolveServedTools(step, ctx, layers, agent) {
466
+ const given = gives(step.tools);
467
+ if (given) {
468
+ assertAgentTakesTools(step.id, agent);
469
+ }
470
+ const tools = await resolveAcpTools(step, ctx, layers);
471
+ if (given || agent.refusesTools === undefined) {
472
+ return tools;
473
+ }
474
+ return undefined;
475
+ }
476
+ /** Whether a step setting may name anything: a getter, or a non-empty array. */
477
+ function gives(setting) {
478
+ return typeof setting === 'function' || (Array.isArray(setting) && setting.length > 0);
479
+ }
480
+ /**
481
+ * One agent turn: prompt, wait for every bridged call the turn started, and
482
+ * fold the bridge's records into the turn's items.
483
+ */
484
+ async function runTurn(params) {
485
+ const { step, baseCtx, resolution, bridge, tools, turnError } = params;
486
+ if (tools) {
487
+ bridge.nameToolCalls((title) => tools.wireNameOf(title));
488
+ }
489
+ bridge.begin();
490
+ let result;
491
+ try {
492
+ result = await resolution.live.session.prompt({
493
+ content: params.content,
494
+ // Per-turn signal, so a session reused across turns is cancelled by the
495
+ // context running the CURRENT turn rather than the one that opened it.
496
+ signal: abortSignalOf(baseCtx),
497
+ });
498
+ }
499
+ catch (e) {
500
+ await settle(tools);
501
+ // Close the turn on the event surface before rethrowing. A consumer driving
502
+ // a UI off `getFullStream()` saw `response.created` and would otherwise
503
+ // wait forever for a completion that never comes — the stream just stops.
504
+ bridge.abort(e);
505
+ await discardIfFresh(resolution, baseCtx);
506
+ throw turnFailure(step, turnError.error ?? e, baseCtx);
507
+ }
508
+ await settle(tools);
509
+ if (turnError.error !== undefined) {
510
+ bridge.abort(turnError.error);
511
+ await discardIfFresh(resolution, baseCtx);
512
+ throw turnFailure(step, turnError.error, baseCtx);
513
+ }
514
+ if (tools) {
515
+ const merged = mergeBridgedItems(result.items, tools.takeFinished());
516
+ bridge.adoptToolCalls(merged.adopted);
517
+ result = {
518
+ ...result,
519
+ items: merged.items,
520
+ };
521
+ }
522
+ bridge.finalize(result);
523
+ return result;
524
+ }
525
+ /** Let every bridged call the turn started finish, then stop taking calls. */
526
+ async function settle(tools) {
527
+ if (!tools) {
528
+ return;
529
+ }
530
+ await tools.idle();
531
+ tools.unbind();
532
+ }
533
+ async function stepOutput(step, result) {
534
+ const lastText = result.text.trim().length > 0 ? result.text : extractAssistantText(result.items);
535
+ if (step.output) {
536
+ return await parseStructuredOutput({
537
+ schema: step.output,
538
+ rawText: lastText,
539
+ stepId: step.id,
540
+ });
541
+ }
542
+ return frameworkCast(lastText);
543
+ }
544
+ //#endregion
402
545
  //#region Public API
403
546
  export async function executeAcpAgent(step, input, ctx, layers) {
404
547
  const baseCtx = frameworkCast(ctx);
@@ -419,31 +562,48 @@ export async function executeAcpAgent(step, input, ctx, layers) {
419
562
  });
420
563
  }
421
564
  const cwd = (await resolveLazy(step.cwd, ctx)) ?? baseCtx.cwdState.cwd;
422
- const servers = await resolveLazy(step.mcpServers, ctx);
565
+ const tools = await resolveServedTools(step, ctx, layers, agent);
423
566
  // Capture the conversation so far BEFORE appending this turn's prompt, so a
424
567
  // fresh session can be seeded with it and the agent is not left guessing at
425
568
  // what earlier steps established.
426
569
  const priorHistory = [
427
570
  ...baseCtx.itemLog.items,
428
571
  ];
429
- if (promptText.length > 0) {
430
- baseCtx.itemLog.append(createMessage(promptText, 'user'));
431
- }
432
- const bridge = new AcpEventBridge(step, agent.agentId, baseCtx);
433
- const binding = {
572
+ // Through the layers' append pipeline, as `callModel` adds its input.
573
+ let rerenderRequests = await appendUserInput({
574
+ ctx: baseCtx,
575
+ layers,
576
+ input: promptText,
577
+ });
578
+ let bridge = new AcpEventBridge(step, agent.agentId, baseCtx);
579
+ // A tool pipeline error fails the step, as it does in `callModel`: it is
580
+ // kept, the agent's turn is cancelled, and the error is thrown once the
581
+ // turn has unwound.
582
+ const turnError = {};
583
+ const bindingFor = (events) => ({
434
584
  step,
435
585
  ctx: baseCtx,
436
586
  agentId: agent.agentId,
437
587
  layers,
438
588
  onUpdate: (notification) => {
439
- bridge.forward(notification);
589
+ tools?.observe(notification.update);
590
+ events.forward(notification);
440
591
  },
441
592
  onActivity: (activity) => {
442
- bridge.forwardActivity(activity);
593
+ events.forwardActivity(activity);
443
594
  },
444
- };
595
+ tools,
596
+ events,
597
+ failTurn: (error) => {
598
+ if (turnError.error !== undefined) {
599
+ return;
600
+ }
601
+ turnError.error = error;
602
+ void turnError.cancel?.().catch(() => undefined);
603
+ },
604
+ });
445
605
  const host = buildHost({
446
- ...binding,
606
+ ...bindingFor(bridge),
447
607
  cwd,
448
608
  });
449
609
  const resolution = await openSession({
@@ -452,54 +612,85 @@ export async function executeAcpAgent(step, input, ctx, layers) {
452
612
  baseCtx,
453
613
  cwd,
454
614
  host,
455
- binding,
456
- servers: servers
457
- ? [
458
- ...servers,
459
- ]
460
- : undefined,
615
+ binding: bindingFor(bridge),
616
+ tools,
461
617
  });
462
618
  await applySessionSelection(step, ctx, resolution, baseCtx);
463
- bridge.begin();
464
- let result;
465
- try {
466
- result = await resolution.live.session.prompt({
619
+ turnError.cancel = () => resolution.live.session.cancel();
620
+ // History seeds only a freshly opened session; a reused one already owns
621
+ // its conversation on the agent side.
622
+ let turnPrompt = resolution.fresh
623
+ ? withHistoryPrompt({
624
+ prompt: promptText,
625
+ history: priorHistory,
626
+ })
627
+ : promptText;
628
+ let turnBlocks = blocks;
629
+ let retries = 0;
630
+ for (;;) {
631
+ // Recall runs before every turn, as before every model call; its output
632
+ // leads the prompt.
633
+ const context = await renderLayerContext({
634
+ ctx: baseCtx,
635
+ layers,
636
+ query: promptText,
637
+ rerenderRequests,
638
+ });
639
+ rerenderRequests = [];
640
+ const result = await runTurn({
641
+ step,
642
+ baseCtx,
643
+ resolution,
644
+ bridge,
645
+ tools,
646
+ turnError,
467
647
  content: buildContent({
468
- // History seeds only a freshly opened session; a reused one already
469
- // owns its conversation on the agent side.
470
- text: resolution.fresh
471
- ? withHistoryPrompt({
472
- prompt: promptText,
473
- history: priorHistory,
474
- })
475
- : promptText,
476
- blocks,
648
+ text: [
649
+ context,
650
+ turnPrompt,
651
+ ]
652
+ .filter((part) => part.length > 0)
653
+ .join('\n\n'),
654
+ blocks: turnBlocks,
477
655
  }),
478
- // Per-turn signal, so a session reused across turns is cancelled by the
479
- // context running the CURRENT turn rather than the one that opened it.
480
- signal: abortSignalOf(baseCtx),
481
- });
482
- }
483
- catch (e) {
484
- // Close the turn on the event surface before rethrowing. A consumer driving
485
- // a UI off `getFullStream()` saw `response.created` and would otherwise
486
- // wait forever for a completion that never comes — the stream just stops.
487
- bridge.abort(e);
488
- await discardIfFresh(resolution, baseCtx);
489
- throw turnFailure(step, e, baseCtx);
490
- }
491
- bridge.finalize(result);
492
- applyTurnResult(baseCtx, result);
493
- await finalizeSession(resolution, baseCtx);
494
- assertTurnSucceeded(step.id, result, baseCtx);
495
- const lastText = result.text.length > 0 ? result.text : extractAssistantText(result.items);
496
- if (step.output) {
497
- return parseStructuredOutput({
498
- schema: step.output,
499
- rawText: lastText,
500
- stepId: step.id,
501
656
  });
657
+ applyTurnResult(baseCtx, result);
658
+ try {
659
+ assertTurnSucceeded(step.id, result, baseCtx);
660
+ }
661
+ catch (e) {
662
+ await finalizeSession(resolution, baseCtx);
663
+ throw e;
664
+ }
665
+ const response = toLlmResponse(result);
666
+ const decision = layers && layers.length > 0
667
+ ? await baseCtx.harness.afterModelCall(layers, response, baseCtx)
668
+ : undefined;
669
+ if (decision?.action === SteeringAction.Deny) {
670
+ await finalizeSession(resolution, baseCtx);
671
+ throw new NoeticErrorImpl({
672
+ kind: 'steering_denied',
673
+ guidance: decision.guidance,
674
+ });
675
+ }
676
+ // A layer asking for a better answer gets another turn carrying its
677
+ // guidance, as a `callModel` step retries its call. The agent keeps its
678
+ // first answer in its own history, so it stays in the log as well.
679
+ if (decision?.action === SteeringAction.Guide && retries < MAX_STEERING_RETRIES) {
680
+ const guidance = decision.guidance ?? 'Please adjust your response.';
681
+ baseCtx.itemLog.append(createMessage(guidance, 'developer'));
682
+ turnPrompt = guidance;
683
+ turnBlocks = undefined;
684
+ retries += 1;
685
+ bridge = new AcpEventBridge(step, agent.agentId, baseCtx);
686
+ bindHostToStep(resolution.live.host, bindingFor(bridge));
687
+ continue;
688
+ }
689
+ if (layers && layers.length > 0) {
690
+ await baseCtx.harness.storeLayers(layers, response, baseCtx);
691
+ }
692
+ await finalizeSession(resolution, baseCtx);
693
+ return await stepOutput(step, result);
502
694
  }
503
- return frameworkCast(lastText);
504
695
  }
505
696
  //#endregion
@@ -1,9 +1,16 @@
1
1
  /**
2
2
  * Action step handlers: run, llm, spawn, provide.
3
3
  */
4
+ import type { StepToolEntry } from '@noetic-tools/types';
5
+ import type { SplitStepTools } from '../connections/step-tools.js';
4
6
  import type { ItemSchemaRegistry, LayerStateStore } from './action-deps.js';
5
- import type { Context, ContextLayer, ExecuteStepFn, StepCallModel, StepRunCode, StepSpawn, StepWithContext, StorageAdapter } from './action-types.js';
7
+ import type { Context, ContextData, ContextLayer, ContextRerenderRequest, ExecuteStepFn, ProjectionPolicy, RecallLayerOutput, StepCallModel, StepRunCode, StepSpawn, StepWithContext, StorageAdapter, Tool } from './action-types.js';
6
8
  export declare function executeRunCode<TContext, I, O>(step: StepRunCode<TContext, I, O>, input: I, ctx: Context<TContext>): Promise<O>;
9
+ export declare const MAX_STEERING_RETRIES = 3;
10
+ interface ResolvedTools {
11
+ tools: Tool[] | undefined;
12
+ allowedToolNames: string[] | undefined;
13
+ }
7
14
  /**
8
15
  * Resolves a `Lazy<T>` step field. If the value is a function, it is invoked
9
16
  * with the current context; otherwise the value is returned as-is. Supports
@@ -14,6 +21,73 @@ export declare function executeRunCode<TContext, I, O>(step: StepRunCode<TContex
14
21
  * tools) without baking them in at build time.
15
22
  */
16
23
  export declare function resolveLazy<T, TContext>(value: T | ((ctx: Context<TContext>) => T | Promise<T>), ctx: Context<TContext>): Promise<T>;
24
+ /**
25
+ * Resolves which tools to send and what restrictions to apply.
26
+ *
27
+ * When a unified tool set exists on the context (collected before execution),
28
+ * every LLM call sends the full set and step.tools narrows via allowedToolNames.
29
+ *
30
+ * Semantics:
31
+ * step.tools = undefined → unrestricted (all tools, no allowedToolNames),
32
+ * except the tools of connections only some step lists
33
+ * (a document node's ceiling narrows its connections)
34
+ * step.tools = [] → no tools at all
35
+ * step.tools = [a, b] → full set sent, restrict to a and b (a connection
36
+ * entry or pick restricts to its connection's tools,
37
+ * each cut to what it picks and sent in place)
38
+ *
39
+ * Fallback: when no unified set exists (e.g. harness.run() called directly),
40
+ * merge step tools with layer tools as before.
41
+ */
42
+ export declare function resolveToolsAndRestrictions(listed: SplitStepTools | undefined, layers: ContextLayer[] | undefined, ctx: Context): ResolvedTools;
43
+ /**
44
+ * Splits a step's resolved `tools`. Client tools and connection picks flow
45
+ * through the unified-tool / allowedToolNames / steering machinery; server-tool
46
+ * specs bypass it and are stamped onto the model request (`_serverTools`) for
47
+ * the model caller to wrap via the SDK's `serverTool()`. `undefined`
48
+ * (unrestricted) is preserved, so the `[] = opt-out` semantics stay intact.
49
+ *
50
+ * @throws NoeticConfigError `CONNECTION_INVALID` when function-form tools return
51
+ * a connection the turn never attached.
52
+ */
53
+ export declare function splitResolvedTools(step: {
54
+ readonly id: string;
55
+ readonly tools?: unknown;
56
+ }, resolved: ReadonlyArray<StepToolEntry> | undefined, ctx: Context): SplitStepTools | undefined;
57
+ /**
58
+ * Append user input — through layer pipeline if layers exist, otherwise direct.
59
+ * The append pipeline may request a context re-render (e.g. a layer that
60
+ * expanded an input reference into new content); applied after recall.
61
+ */
62
+ export declare function appendUserInput<I>(params: {
63
+ ctx: Context<ContextData>;
64
+ layers: ContextLayer[] | undefined;
65
+ input: I;
66
+ }): Promise<ContextRerenderRequest[]>;
67
+ /**
68
+ * Splits the context budget across layers via `allocateBudgets`. An empty map
69
+ * when the step runs without layers.
70
+ */
71
+ export declare function computeBudgetMap(params: {
72
+ layers: ContextLayer[] | undefined;
73
+ policy: ProjectionPolicy;
74
+ systemPromptTokens: number;
75
+ }): Map<string, number>;
76
+ /**
77
+ * Recall once per LLM step: atomic layers run in the hot path; eventual layers
78
+ * are served from cache. Results drive both the assembled context window and
79
+ * the per-layer usage breakdown (ctx.lastLayerUsage). Recall fires before the
80
+ * steering retry loop because retries replay the same context. Re-render
81
+ * requests collected from the input-append pipeline are applied on top.
82
+ */
83
+ export declare function gatherRecallResults(params: {
84
+ ctx: Context<ContextData>;
85
+ layers: ContextLayer[] | undefined;
86
+ recallQuery: string;
87
+ budgetMap: Map<string, number>;
88
+ slotOf: Map<string, number>;
89
+ rerenderRequests: ContextRerenderRequest[];
90
+ }): Promise<ReadonlyArray<RecallLayerOutput>>;
17
91
  export declare function executeCallModel<TContext, I, O>(step: StepCallModel<TContext, I, O>, input: I, ctx: Context<TContext>, layers?: ContextLayer[]): Promise<O>;
18
92
  export interface ExecuteSpawnOpts {
19
93
  layerStore?: LayerStateStore;
@@ -44,3 +118,4 @@ export interface ExecuteWithContextOpts {
44
118
  * is neither initialized nor disposed here.
45
119
  */
46
120
  export declare function executeWithContext<TContext, I, O>(step: StepWithContext<TContext, I, O>, input: I, ctx: Context<TContext>, executeStep: ExecuteStepFn, opts?: ExecuteWithContextOpts): Promise<O>;
121
+ export {};