@noetic-tools/core 5.22.0-next.1 → 5.22.0-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/adapters/in-memory-subprocess-adapter.js +4 -2
  2. package/dist/adapters/openrouter.d.ts +6 -1
  3. package/dist/adapters/openrouter.js +10 -0
  4. package/dist/builders/custom-item.d.ts +1 -1
  5. package/dist/builders/custom-item.js +14 -3
  6. package/dist/builders/decide-builders.d.ts +7 -0
  7. package/dist/builders/tool-builder.d.ts +5 -1
  8. package/dist/builders/tool-builder.js +2 -0
  9. package/dist/builders/workflow-control-nodes.js +1 -0
  10. package/dist/connections/pool.d.ts +18 -0
  11. package/dist/connections/pool.js +54 -9
  12. package/dist/connections/registry.js +11 -0
  13. package/dist/harness/agent-harness.d.ts +130 -3
  14. package/dist/harness/agent-harness.js +337 -22
  15. package/dist/harness/decide-call.d.ts +15 -0
  16. package/dist/harness/decide-call.js +57 -7
  17. package/dist/harness/deps/types.d.ts +1 -1
  18. package/dist/harness/forget.d.ts +57 -0
  19. package/dist/harness/forget.js +496 -0
  20. package/dist/harness/harness-options.d.ts +24 -1
  21. package/dist/harness/llm-client.d.ts +2 -0
  22. package/dist/harness/llm-client.js +9 -5
  23. package/dist/harness/model-rounds.d.ts +6 -0
  24. package/dist/harness/model-rounds.js +7 -3
  25. package/dist/harness/model-tool-round.js +67 -8
  26. package/dist/harness/recorded-tool-calls.d.ts +16 -0
  27. package/dist/harness/recorded-tool-calls.js +106 -0
  28. package/dist/harness/spend.d.ts +13 -1
  29. package/dist/harness/spend.js +82 -1
  30. package/dist/harness/steer-inbox.js +9 -5
  31. package/dist/harness/thread-record.d.ts +12 -1
  32. package/dist/harness/thread-record.js +63 -19
  33. package/dist/index.d.ts +9 -6
  34. package/dist/index.js +4 -3
  35. package/dist/interpreter/acp-tools.js +21 -4
  36. package/dist/interpreter/execute-action.js +7 -1
  37. package/dist/interpreter/execute-decide.js +5 -0
  38. package/dist/interpreter/execute.js +55 -3
  39. package/dist/interpreter/step-dispatcher.js +17 -1
  40. package/dist/interpreter/step-kind-dispatch.js +9 -1
  41. package/dist/portable/runtime.d.ts +4 -0
  42. package/dist/portable/runtime.js +2 -0
  43. package/dist/runtime/durable/child-links.d.ts +61 -0
  44. package/dist/runtime/durable/child-links.js +127 -0
  45. package/dist/runtime/durable/session-store.d.ts +6 -0
  46. package/dist/runtime/durable/session-store.js +16 -2
  47. package/dist/runtime/durable/turn-lease.d.ts +10 -0
  48. package/dist/runtime/durable/turn-lease.js +10 -2
  49. package/dist/runtime/event-broadcaster.d.ts +9 -1
  50. package/dist/runtime/event-broadcaster.js +16 -1
  51. package/dist/runtime/held-calls.d.ts +65 -6
  52. package/dist/runtime/held-calls.js +257 -5
  53. package/dist/runtime/output-store.d.ts +90 -0
  54. package/dist/runtime/output-store.js +243 -0
  55. package/dist/runtime/session-streams.d.ts +28 -7
  56. package/dist/runtime/session-streams.js +112 -67
  57. package/dist/runtime/tool-approval.d.ts +1 -3
  58. package/dist/runtime/tool-approval.js +1 -1
  59. package/package.json +2 -2
  60. package/schema/noetic-workflow.schema.json +27 -0
@@ -4,9 +4,9 @@ import { runEvery } from '../connections/settle.js';
4
4
  import { pendingTasksOf, resumableWaitsOf } from '../interpreter/connection-steps.js';
5
5
  import { turnEndingIn } from '../interpreter/turn-ending.js';
6
6
  import { AcpSessionStore } from '../runtime/acp-session-store.js';
7
- import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
8
7
  import { stubOf } from '../runtime/durable/step-ledger.js';
9
8
  import { heldCallsOf, toHeldCall } from '../runtime/held-calls.js';
9
+ import { OutputStore } from '../runtime/output-store.js';
10
10
  import { awaitApproval } from '../runtime/tool-approval.js';
11
11
  import { ConnectionGate } from './connection-gate.js';
12
12
  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';
@@ -14,12 +14,14 @@ import { clearPendingEntries, collectAllTools, collectCustomItems, deduplicateTo
14
14
  import { buildItemStream, ChannelStore, ContextImpl, canSwap, captureCheckpoint, clearCheckpoint, collectContextTree, createInMemoryStorage, createSessionStore, createSpendLog, createStepLedgerStore, customItemGates, DEFAULT_LEASE_TTL_MS, DEFAULT_PARK_GRACE_MS, Drains, filterReasoningStream, filterTextStream, heldElsewhere, heldElsewhereUntil, INTERRUPT_REASON, isSteer, PARK_REASON, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, TurnLease, } from './deps/runtime.js';
15
15
  import { SteeringAction } from './deps/types.js';
16
16
  import { flowVersionOf } from './flow-version.js';
17
+ import { forgetExecution, forgetThread, listStoredExecutions, listStoredThreads } from './forget.js';
17
18
  import { resolveCheckpointStore, resolveEnvironmentAdapters } from './harness-options.js';
18
19
  import { createHarnessSpan, recordChannelWarning, resolveTraceExporter } from './harness-tracing.js';
19
20
  import { LlmGateway } from './llm-client.js';
20
21
  import { buildItemSchemaRegistry } from './model-schema.js';
21
22
  import { DEFAULT_TASK_POLL_MS, DEFAULT_WAKE_DEBOUNCE_MS, ParkWatchers } from './park-watchers.js';
22
23
  import { readDecision } from './read-decision.js';
24
+ import { recordedToolCalls } from './recorded-tool-calls.js';
23
25
  import { Spend } from './spend.js';
24
26
  import { ThreadRecord } from './thread-record.js';
25
27
  /** Keep `message` in storage for after the thread's parked turn, with its options. */
@@ -29,6 +31,28 @@ function keepForLater(session, record, message) {
29
31
  }
30
32
  //#endregion
31
33
  const DEFAULT_THREAD_ID = '__default__';
34
+ /**
35
+ * `store`, noting in `ids` the id of every layer it keeps durable state for, so a
36
+ * forget knows which layers' storage to look in (spec 23 § Forgetting).
37
+ */
38
+ function noteDurableLayers(store, ids) {
39
+ const register = store.registerDurable;
40
+ if (!register) {
41
+ return store;
42
+ }
43
+ return new Proxy(store, {
44
+ get(target, property) {
45
+ if (property === 'registerDurable') {
46
+ return (executionId, layerId, storage) => {
47
+ ids.add(layerId);
48
+ register.call(target, executionId, layerId, storage);
49
+ };
50
+ }
51
+ const value = Reflect.get(target, property, target);
52
+ return typeof value === 'function' ? value.bind(target) : value;
53
+ },
54
+ });
55
+ }
32
56
  /** What a `turn_stuck` error says about where the turn stopped, or undefined for any other error. */
33
57
  function stuckOf(error) {
34
58
  const ending = turnEndingIn(error)?.noeticError;
@@ -195,6 +219,20 @@ export class AgentHarness {
195
219
  pendingCheckpoints = new Map();
196
220
  defaultDeliveryMode;
197
221
  sessions = new Map();
222
+ /** Whether threads keep their streamed output for display (`opts.interactive`). */
223
+ interactive;
224
+ /** Where display output is kept: the harness's storage, or memory without one. */
225
+ outputStorage;
226
+ /** The display output each thread of an interactive harness records, by thread id. */
227
+ outputs = new Map();
228
+ /** Forgets in progress, by thread id: a turn of the thread waits for its forget. */
229
+ forgetting = new Map();
230
+ /** Ids of the context layers whose state this harness has kept durably. */
231
+ durableLayerIds = new Set();
232
+ /** Thread id → what stops recording it. */
233
+ stopRecording = new Map();
234
+ /** Threads named by a host-built context's own id, dropped when its run ends. */
235
+ ownThreads = new Set();
198
236
  /**
199
237
  * @internal Live ACP connections. Reached by the interpreter via
200
238
  * `frameworkCast`; use {@link listAcpSessions}, {@link getAcpSession},
@@ -283,6 +321,7 @@ export class AgentHarness {
283
321
  * access from outside core. */
284
322
  itemSchemas;
285
323
  constructor(opts) {
324
+ this.interactive = opts.interactive ?? false;
286
325
  const validatedParams = opts.paramsSchema ? opts.paramsSchema.parse(opts.params) : opts.params;
287
326
  const environment = opts.environment;
288
327
  const storageEnv = environment?.storage;
@@ -298,8 +337,11 @@ export class AgentHarness {
298
337
  decisionModel: opts.decisionModel,
299
338
  emitItemsOnReplay: opts.emitItemsOnReplay,
300
339
  approveToolCall: opts.approveToolCall,
340
+ onHeld: opts.onHeld,
341
+ steerWhileHeld: opts.steerWhileHeld,
301
342
  now: opts.now,
302
343
  };
344
+ this.outputStorage = this.config.storage ?? createInMemoryStorage();
303
345
  const adapters = resolveEnvironmentAdapters(environment);
304
346
  this.fs = adapters.fs;
305
347
  this.shell = adapters.shell;
@@ -340,11 +382,10 @@ export class AgentHarness {
340
382
  onWarning: (warning) => this.recordChannelWarning(warning),
341
383
  });
342
384
  this.traceExporter = resolveTraceExporter(opts.traceExporter);
343
- this.layerStateStore =
344
- storageEnv?.layerStateStore ??
345
- createLayerStateStore((layerId, hook, error) => {
346
- console.warn(`[noetic] context layer '${layerId}' ${hook} error:`, error);
347
- });
385
+ this.layerStateStore = noteDurableLayers(storageEnv?.layerStateStore ??
386
+ createLayerStateStore((layerId, hook, error) => {
387
+ console.warn(`[noetic] context layer '${layerId}' ${hook} error:`, error);
388
+ }), this.durableLayerIds);
348
389
  this.recallCache = createRecallCache();
349
390
  this.contextCache = createContextCacheStore();
350
391
  this.defaultDeliveryMode = opts.defaultDeliveryMode ?? 'next-turn';
@@ -479,7 +520,11 @@ export class AgentHarness {
479
520
  */
480
521
  async close() {
481
522
  this.parkWatchers?.stopAll();
523
+ heldCallsOf(this).releaseWatches();
482
524
  await runEvery([
525
+ ...[
526
+ ...this.outputs.values(),
527
+ ].map((output) => () => output.flush()),
483
528
  () => this.#connections.close(),
484
529
  () => this.closeAcpSessions(),
485
530
  ]);
@@ -614,6 +659,11 @@ export class AgentHarness {
614
659
  return Promise.reject(missingModel);
615
660
  }
616
661
  const threadId = options?.threadId ?? DEFAULT_THREAD_ID;
662
+ const forgetting = this.forgetting.get(threadId);
663
+ if (forgetting) {
664
+ // A message for a thread being forgotten starts the thread afresh once the forget is done.
665
+ return forgetting.then(() => this.deliverInput(input, options));
666
+ }
617
667
  const deliveryMode = options?.deliveryMode ?? this.defaultDeliveryMode;
618
668
  const session = this.getOrCreateSession(threadId);
619
669
  const message = {
@@ -637,9 +687,13 @@ export class AgentHarness {
637
687
  * deliveries doing that at once would each miss the other.
638
688
  */
639
689
  deliver(session, message) {
690
+ session.arriving = (session.arriving ?? 0) + 1;
640
691
  const turn = (session.delivering ?? Promise.resolve())
641
692
  .catch(() => undefined)
642
- .then(() => this.deliverOne(session, message));
693
+ .then(() => this.deliverOne(session, message))
694
+ .finally(() => {
695
+ session.arriving = (session.arriving ?? 1) - 1;
696
+ });
643
697
  session.delivering = turn;
644
698
  return turn;
645
699
  }
@@ -677,6 +731,43 @@ export class AgentHarness {
677
731
  const session = this.requireSession(scope);
678
732
  return frameworkCast(buildItemStream(session.runner.broadcaster, this.itemSchemas));
679
733
  }
734
+ /**
735
+ * A thread's display output (spec 08 § Display output): the latest snapshot of
736
+ * every item it streamed, unfinished ones included, read from storage. An
737
+ * `interactive` harness records it; any harness over the same storage reads it.
738
+ * For showing a thread again, never for resuming one.
739
+ *
740
+ * @throws OutputStoreError when storage fails, or holds something else under the key.
741
+ * @public
742
+ */
743
+ getSessionOutput(scope) {
744
+ return this.outputOf(scope?.threadId ?? DEFAULT_THREAD_ID).read();
745
+ }
746
+ /**
747
+ * Save display snapshots for a thread, each replacing the stored one with its
748
+ * id, and resolve the thread's whole display output. For a protocol adapter
749
+ * that shows a thread in its own item shapes. Model history is untouched.
750
+ *
751
+ * @throws OutputStoreError when `items` are not snapshots (objects with a string
752
+ * `type`), or storage fails.
753
+ * @public
754
+ */
755
+ saveSessionOutput(items, scope) {
756
+ return this.outputOf(scope.threadId ?? DEFAULT_THREAD_ID).write(items);
757
+ }
758
+ /**
759
+ * The thread's one output store: every write for a thread goes through it, so
760
+ * this harness's writes queue behind each other instead of racing.
761
+ */
762
+ outputOf(threadId) {
763
+ const known = this.outputs.get(threadId);
764
+ if (known) {
765
+ return known;
766
+ }
767
+ const output = new OutputStore(this.outputStorage, threadId, this.itemSchemas);
768
+ this.outputs.set(threadId, output);
769
+ return output;
770
+ }
680
771
  getTextStream(scope) {
681
772
  const session = this.requireSession(scope);
682
773
  return filterTextStream(session.runner.broadcaster);
@@ -1054,7 +1145,9 @@ export class AgentHarness {
1054
1145
  // A harness that was replaced says nothing about the turn: it is the new
1055
1146
  // holder's now, and marking it stopped would keep a wake from resuming it.
1056
1147
  const replaced = isLeaseLost(error) || session.lease?.lost === true;
1057
- if (ctx.aborted && !replaced && ctx.abortReason !== INTERRUPT_REASON) {
1148
+ // An interrupted turn answers its held calls "Cancelled before it ran." in
1149
+ // the history it restarts from: no answer could reach them any more.
1150
+ if (ctx.aborted && !replaced) {
1058
1151
  await heldCallsOf(this).clear(ctx.id);
1059
1152
  }
1060
1153
  if (record && !replaced && ctx.abortReason !== INTERRUPT_REASON) {
@@ -1073,6 +1166,10 @@ export class AgentHarness {
1073
1166
  await this.announceWakeTimeQuietly();
1074
1167
  return result;
1075
1168
  };
1169
+ if (this.interactive) {
1170
+ const output = this.outputOf(threadId);
1171
+ this.stopRecording.set(threadId, session.runner.broadcaster.observe((event) => output.record(event)));
1172
+ }
1076
1173
  this.sessions.set(threadId, session);
1077
1174
  if (record) {
1078
1175
  void record.usage().then((usage) => session.runner.seedUsage(usage));
@@ -1106,6 +1203,10 @@ export class AgentHarness {
1106
1203
  : await this.sessionStore.threads();
1107
1204
  const woken = [];
1108
1205
  for (const threadId of threadIds) {
1206
+ // A thread being forgotten has no turn left to wake.
1207
+ if (this.forgetting.has(threadId)) {
1208
+ continue;
1209
+ }
1109
1210
  // A turn asked for by name may be closing out its park this instant: its
1110
1211
  // runner is busy, though nothing is running. Wait for it rather than skip.
1111
1212
  const closing = scope?.threadId ? this.sessions.get(threadId)?.runner : undefined;
@@ -1263,7 +1364,29 @@ export class AgentHarness {
1263
1364
  if (scope && 'executionId' in scope) {
1264
1365
  return;
1265
1366
  }
1266
- const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
1367
+ await this.wakeAnswered(scope?.threadId ?? DEFAULT_THREAD_ID, options);
1368
+ }
1369
+ /**
1370
+ * An `onHeld` handler's answer: for the execution that held the call, never for a
1371
+ * later turn on the same thread. Wakes the thread's turn when it is that execution.
1372
+ * @internal
1373
+ */
1374
+ async answerHeld(answer) {
1375
+ await heldCallsOf(this).resolve(answer.executionId, {
1376
+ callId: answer.callId,
1377
+ argsHash: answer.argsHash,
1378
+ resolution: answer.resolution,
1379
+ });
1380
+ if (answer.threadId === undefined) {
1381
+ return;
1382
+ }
1383
+ if ((await this.turnExecutionId(answer.threadId)) !== answer.executionId) {
1384
+ return;
1385
+ }
1386
+ await this.wakeAnswered(answer.threadId);
1387
+ }
1388
+ /** A thread's turn was answered: resume it if parked, now or once it comes to rest. */
1389
+ async wakeAnswered(threadId, options) {
1267
1390
  const runner = this.sessions.get(threadId)?.runner;
1268
1391
  if (runner?.context === undefined) {
1269
1392
  await this.wake({
@@ -1355,13 +1478,27 @@ export class AgentHarness {
1355
1478
  });
1356
1479
  return true;
1357
1480
  }
1481
+ /**
1482
+ * The tool calls a resume of `executionId` goes on from rather than having the
1483
+ * model ask for them again: every call whose request its step ledger holds, in a
1484
+ * completed step or a recorded round, read from storage. `settled` says whether
1485
+ * the call's result is on record too; an unsettled call runs again on resume (spec
1486
+ * 23a § Tool calls in a round). A host that journals tool traffic of its own adds
1487
+ * none of these to a restored context, or the model sees them twice. Empty without
1488
+ * durable storage.
1489
+ * @public
1490
+ */
1491
+ async recordedToolCalls(executionId) {
1492
+ const window = await this.stepLedgerStore?.load(executionId);
1493
+ return window ? recordedToolCalls(window) : [];
1494
+ }
1358
1495
  /**
1359
1496
  * What a run did, step by step: who ran each step, under which flow version, and
1360
1497
  * the receipt of a step with a lasting effect (spec 23 § The trail). Marks outlive
1361
1498
  * the ledger entries they came from, so the trail of a finished run stays readable.
1362
1499
  *
1363
- * `scope` names an execution, or a thread, whose recent turns are then listed in
1364
- * order.
1500
+ * `scope` names an execution, or a thread, whose turns are then listed in order:
1501
+ * every turn it began, two reads per turn.
1365
1502
  * @public
1366
1503
  */
1367
1504
  async getAuditTrail(scope) {
@@ -1393,6 +1530,128 @@ export class AgentHarness {
1393
1530
  return marks;
1394
1531
  }
1395
1532
  //#endregion
1533
+ //#region Forgetting
1534
+ /**
1535
+ * Delete everything the harness keeps for a thread or an execution, so a host never
1536
+ * builds a storage key itself (spec 23 § Forgetting).
1537
+ *
1538
+ * A thread's forget covers every execution the thread ran, its context-layer state,
1539
+ * display output, record and turn lease. An execution's forget covers what is stored
1540
+ * under it and its layer state, and leaves any thread's record alone. Pending spend
1541
+ * is settled first: priced through the provider, waiting up to `patienceMs`, else
1542
+ * written off at its ceiling (at 0, flagged `unbounded`, when it has none). The trail
1543
+ * goes too unless `keepTrail`.
1544
+ *
1545
+ * A thread's forget holds and renews the thread's lease until it is done, and a
1546
+ * message sent to the thread on this harness meanwhile waits for it, then starts
1547
+ * the thread afresh.
1548
+ *
1549
+ * @throws NoeticError `lease_lost` when the thread has a turn running, queued or
1550
+ * being delivered in this harness, is already being forgotten, or the execution
1551
+ * has a run in flight; when another harness still holds the thread's lease after
1552
+ * `waitMs`; or when the lease is lost part way.
1553
+ * @throws NoeticError `ledger_write_failed` when a spend record could not be
1554
+ * settled; nothing was deleted.
1555
+ * @throws NoeticConfigError `INVALID_FORGET_SCOPE` for a scope with neither id.
1556
+ * @public
1557
+ */
1558
+ async forget(scope, options) {
1559
+ if ('executionId' in scope) {
1560
+ return forgetExecution(this.forgetHost(), scope.executionId, options);
1561
+ }
1562
+ const threadId = scope.threadId;
1563
+ if (typeof threadId !== 'string' || threadId === '') {
1564
+ throw new NoeticConfigError({
1565
+ code: 'INVALID_FORGET_SCOPE',
1566
+ message: 'harness.forget() needs a threadId or an executionId.',
1567
+ hint: 'Pass { threadId } to forget a thread, or { executionId } to forget one execution.',
1568
+ });
1569
+ }
1570
+ const running = this.forgetting.get(threadId);
1571
+ if (running) {
1572
+ throw new NoeticErrorImpl({
1573
+ kind: 'lease_lost',
1574
+ executionId: threadId,
1575
+ term: 0,
1576
+ reason: `thread "${threadId}" is already being forgotten`,
1577
+ });
1578
+ }
1579
+ const forgetting = forgetThread(this.forgetHost(), threadId, options);
1580
+ this.forgetting.set(threadId, forgetting.catch(() => undefined));
1581
+ try {
1582
+ return await forgetting;
1583
+ }
1584
+ finally {
1585
+ this.forgetting.delete(threadId);
1586
+ await this.announceWakeTimeQuietly();
1587
+ }
1588
+ }
1589
+ /**
1590
+ * Every thread with a record, a turn lease, or display output stored: what
1591
+ * `forget({ threadId })` deletes. Sorted; `prefix` narrows to ids that start with it.
1592
+ * @public
1593
+ */
1594
+ async listStoredThreads(options) {
1595
+ return listStoredThreads(this.forgetHost(), options);
1596
+ }
1597
+ /**
1598
+ * Every execution with anything stored, with what is stored for it. `resumable` is
1599
+ * set when a snapshot or ledger entries are: a trail alone is not a checkpoint.
1600
+ * Sorted; `prefix` narrows to ids that start with it.
1601
+ * @public
1602
+ */
1603
+ async listStoredExecutions(options) {
1604
+ return listStoredExecutions(this.forgetHost(), options);
1605
+ }
1606
+ forgetHost() {
1607
+ return {
1608
+ storage: this.config.storage,
1609
+ outputStorage: this.outputStorage,
1610
+ checkpointStore: this.checkpointStore,
1611
+ sessionStore: this.sessionStore,
1612
+ leaseOptions: this.leaseOptions,
1613
+ threadBusy: (threadId) => {
1614
+ const session = this.sessions.get(threadId);
1615
+ if (!session) {
1616
+ return false;
1617
+ }
1618
+ return (session.lease !== undefined ||
1619
+ session.runner.context !== undefined ||
1620
+ session.runner.getStatus().kind !== 'idle' ||
1621
+ session.runner.queue.size > 0 ||
1622
+ (session.arriving ?? 0) > 0);
1623
+ },
1624
+ executionBusy: (executionId) => this.liveRoots.has(executionId),
1625
+ closeSpend: async (owns, patienceMs) => (await this.spend?.close(owns, patienceMs)) ?? [],
1626
+ clearCheckpoint: (executionId) => this.clearCheckpoint(executionId),
1627
+ settleOutput: async (threadId) => {
1628
+ const output = this.outputs.get(threadId);
1629
+ this.outputs.delete(threadId);
1630
+ await output?.flush().catch(() => undefined);
1631
+ },
1632
+ dropThread: (threadId) => {
1633
+ this.parkWatchers?.stop(threadId);
1634
+ this.sessions.delete(threadId);
1635
+ },
1636
+ layerIds: () => this.layerIds(),
1637
+ releaseConnections: (executionId) => this.#connections.registry.releaseRun(executionId),
1638
+ subprocess: this.subprocess,
1639
+ harness: this,
1640
+ };
1641
+ }
1642
+ /** Ids of the layers that may keep durable state: this harness's thread-wide layers, and any it has kept state for. */
1643
+ layerIds() {
1644
+ const ids = new Set(this.durableLayerIds);
1645
+ for (const layer of this._contextLayers ?? []) {
1646
+ if (layer.scope !== 'execution') {
1647
+ ids.add(layer.id);
1648
+ }
1649
+ }
1650
+ return [
1651
+ ...ids,
1652
+ ];
1653
+ }
1654
+ //#endregion
1396
1655
  //#region Triggers
1397
1656
  /**
1398
1657
  * Add a trigger while the harness runs (spec 35 § Triggers). A trigger written
@@ -1607,6 +1866,21 @@ export class AgentHarness {
1607
1866
  }
1608
1867
  return true;
1609
1868
  }
1869
+ /**
1870
+ * The thread whose turn `ctx` runs in, or `undefined` for a run the host started
1871
+ * itself. Where an `onHeld` answer goes.
1872
+ * @internal
1873
+ */
1874
+ heldThreadOf(ctx) {
1875
+ const executionId = rootIdOf(ctx);
1876
+ for (const [threadId, session] of this.sessions) {
1877
+ const running = session.runner.context;
1878
+ if (running && rootIdOf(running) === executionId) {
1879
+ return threadId;
1880
+ }
1881
+ }
1882
+ return undefined;
1883
+ }
1610
1884
  /** The execution whose held calls `scope` names. */
1611
1885
  heldExecutionId(scope) {
1612
1886
  if (scope && 'executionId' in scope) {
@@ -1644,6 +1918,7 @@ export class AgentHarness {
1644
1918
  restore: (executionId, opts) => this.restore(executionId, opts),
1645
1919
  clearCheckpoint: (executionId) => this.clearCheckpoint(executionId),
1646
1920
  parseItems: (raw) => this.itemSchemas.parseMany(raw),
1921
+ layerIds: () => this.layerIds(),
1647
1922
  }, threadId);
1648
1923
  }
1649
1924
  requireSession(scope) {
@@ -1684,16 +1959,6 @@ export class AgentHarness {
1684
1959
  callId: request.callId,
1685
1960
  ctx: request.ctx,
1686
1961
  park: request.park,
1687
- onHeld: (held) => {
1688
- emitFrameworkEvent({
1689
- broadcaster: getBroadcaster(request.ctx),
1690
- agentName: this.config.name,
1691
- eventType: 'tool_call_held',
1692
- data: {
1693
- ...held,
1694
- },
1695
- });
1696
- },
1697
1962
  });
1698
1963
  return approval.decision;
1699
1964
  }
@@ -1838,7 +2103,8 @@ export class AgentHarness {
1838
2103
  }
1839
2104
  try {
1840
2105
  await entry.ready;
1841
- return await execute(s, input, ctx);
2106
+ const result = await execute(s, input, ctx);
2107
+ return result;
1842
2108
  }
1843
2109
  catch (error) {
1844
2110
  entry.failed = true;
@@ -1862,9 +2128,39 @@ export class AgentHarness {
1862
2128
  }
1863
2129
  // The turn's own connections end with it; a resume attaches them again.
1864
2130
  await this.#connections.release(ctx.id);
2131
+ await this.saveOutputOfRun(ctx.threadId);
2132
+ this.forgetOwnThread(ctx.threadId);
1865
2133
  }
1866
2134
  }
1867
2135
  }
2136
+ /**
2137
+ * Wait for what a run streamed to be saved. Display output never decides a run:
2138
+ * a save that failed is logged, stays queued for the next flush, and the run's
2139
+ * own result or error stands.
2140
+ */
2141
+ async saveOutputOfRun(threadId) {
2142
+ try {
2143
+ await this.outputs.get(threadId)?.flush();
2144
+ }
2145
+ catch (error) {
2146
+ console.warn('[noetic] could not save the display output of a run:', error);
2147
+ }
2148
+ }
2149
+ /**
2150
+ * A thread named by a host-built context's own id has no later turns: once its
2151
+ * run ends, the harness drops its session and output store. What was saved stays
2152
+ * in storage under `output:<ctx.id>`.
2153
+ */
2154
+ forgetOwnThread(threadId) {
2155
+ // The thread is named by its context's id, so that context's root run is its only one.
2156
+ if (!this.ownThreads.delete(threadId) || this.liveRoots.has(threadId)) {
2157
+ return;
2158
+ }
2159
+ this.stopRecording.get(threadId)?.();
2160
+ this.stopRecording.delete(threadId);
2161
+ this.outputs.delete(threadId);
2162
+ this.sessions.delete(threadId);
2163
+ }
1868
2164
  /**
1869
2165
  * Fix the point a resume of this run starts from, and queue it for saving — so even
1870
2166
  * a run whose first step dies leaves a snapshot to restore. The save is not awaited:
@@ -2007,6 +2303,7 @@ export class AgentHarness {
2007
2303
  return new ContextImpl({
2008
2304
  ...rest,
2009
2305
  id: executionId,
2306
+ ...this.interactiveThread(resolved, executionId),
2010
2307
  harness: this,
2011
2308
  channelStore: this.channelStore,
2012
2309
  layers: effectiveLayers,
@@ -2018,6 +2315,24 @@ export class AgentHarness {
2018
2315
  ledger,
2019
2316
  });
2020
2317
  }
2318
+ /**
2319
+ * On an interactive harness, a root context a host builds joins its thread: it
2320
+ * gets the thread's broadcaster, so `run()` on it streams, and is recorded, like
2321
+ * a session turn. A context with no `threadId` is its own thread, named by its id.
2322
+ */
2323
+ interactiveThread(opts, executionId) {
2324
+ if (!this.interactive || opts.parent || opts._broadcaster) {
2325
+ return {};
2326
+ }
2327
+ const threadId = opts.threadId ?? executionId;
2328
+ if (opts.threadId === undefined) {
2329
+ this.ownThreads.add(threadId);
2330
+ }
2331
+ return {
2332
+ threadId,
2333
+ _broadcaster: this.getOrCreateSession(threadId).runner.broadcaster,
2334
+ };
2335
+ }
2021
2336
  send(channel, value, ctx) {
2022
2337
  // Internal sender: back-pressured on full queue channels. The calling
2023
2338
  // context's abort signal rejects a parked send with 'cancelled'.
@@ -6,12 +6,27 @@ export type DecisionsClient = Pick<OpenRouter, 'alpha' | 'models'>;
6
6
  /** @internal */
7
7
  export interface DecideCallerDeps {
8
8
  client?: DecisionsClient;
9
+ /**
10
+ * Where native decisions are sent, when not to OpenRouter: the client's own base
11
+ * URL (see `decisionsServerUrl`). The SDK sends them to openrouter.ai whatever the
12
+ * client was built with, so without this a credential for another route would go there.
13
+ */
14
+ serverUrl?: string;
9
15
  callModel: (request: CallModelRequest) => Promise<LLMResponse>;
10
16
  /** Per-harness cache: model id → whether it is a decision model (`undefined` while unknown). */
11
17
  nativeModels: Map<string, Promise<boolean | undefined>>;
12
18
  /** Records each native call before it is sent. Absent without durable storage. */
13
19
  spend?: Spend;
14
20
  }
21
+ /**
22
+ * The base URL native decisions are sent to, given the one the client was built
23
+ * with: that URL without trailing slashes, or undefined for OpenRouter's own (or
24
+ * none), whose decisions endpoint the SDK already knows. Any other base must
25
+ * serve `api/alpha/decisions` under its own path.
26
+ *
27
+ * @internal
28
+ */
29
+ export declare function decisionsServerUrl(clientServerUrl: string | undefined): string | undefined;
15
30
  /**
16
31
  * Answer a decide request. Decision models (those whose OpenRouter output
17
32
  * modality is `decisions`) answer natively with their own distributions; any
@@ -3,6 +3,33 @@ import { z } from 'zod';
3
3
  import { isErrorStatus, statusOf } from '../util/status-code.js';
4
4
  //#endregion
5
5
  //#region Public API
6
+ const OPENROUTER_HOST = 'openrouter.ai';
7
+ /** Whether `url` is OpenRouter's own API, however its host and port are spelled. */
8
+ function isOpenRouter(url) {
9
+ let parsed;
10
+ try {
11
+ parsed = new URL(url);
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ // `URL` lower-cases the host and drops a scheme's default port.
17
+ return parsed.protocol === 'https:' && parsed.host === OPENROUTER_HOST;
18
+ }
19
+ /**
20
+ * The base URL native decisions are sent to, given the one the client was built
21
+ * with: that URL without trailing slashes, or undefined for OpenRouter's own (or
22
+ * none), whose decisions endpoint the SDK already knows. Any other base must
23
+ * serve `api/alpha/decisions` under its own path.
24
+ *
25
+ * @internal
26
+ */
27
+ export function decisionsServerUrl(clientServerUrl) {
28
+ if (!clientServerUrl || isOpenRouter(clientServerUrl)) {
29
+ return undefined;
30
+ }
31
+ return clientServerUrl.replace(/\/+$/, '');
32
+ }
6
33
  /**
7
34
  * Answer a decide request. Decision models (those whose OpenRouter output
8
35
  * modality is `decisions`) answer natively with their own distributions; any
@@ -12,7 +39,11 @@ import { isErrorStatus, statusOf } from '../util/status-code.js';
12
39
  */
13
40
  export async function callDecide(request, deps) {
14
41
  if (deps.client && (await isDecisionModel(request.model, deps))) {
15
- return callNative(request, deps.client, deps.spend);
42
+ return callNative(request, {
43
+ client: deps.client,
44
+ serverUrl: deps.serverUrl,
45
+ spend: deps.spend,
46
+ });
16
47
  }
17
48
  return callEstimated(request, deps);
18
49
  }
@@ -54,7 +85,7 @@ async function lookupDecisionModel(model, client) {
54
85
  }
55
86
  //#endregion
56
87
  //#region Native path
57
- async function callNative(request, client, spend) {
88
+ async function callNative(request, route) {
58
89
  const questions = {};
59
90
  for (const [id, question] of Object.entries(request.questions)) {
60
91
  questions[id] = toNativeQuestion(question);
@@ -65,10 +96,9 @@ async function callNative(request, client, spend) {
65
96
  questions,
66
97
  };
67
98
  const response = await sendNative({
68
- client,
99
+ ...route,
69
100
  decisionsRequest,
70
101
  request,
71
- spend,
72
102
  });
73
103
  const answers = {};
74
104
  for (const [id, question] of Object.entries(request.questions)) {
@@ -93,7 +123,7 @@ async function callNative(request, client, spend) {
93
123
  * response hook save the generation id when the headers arrive, so a call cut off
94
124
  * before its body finishes can still be priced.
95
125
  */
96
- async function sendNative({ client, decisionsRequest, request, spend, }) {
126
+ async function sendNative({ client, serverUrl, decisionsRequest, request, spend, }) {
97
127
  const dispatch = await spend?.open({
98
128
  ctx: request._billTo,
99
129
  kind: SpendKind.Decide,
@@ -105,11 +135,12 @@ async function sendNative({ client, decisionsRequest, request, spend, }) {
105
135
  decisionsRequest,
106
136
  }, {
107
137
  signal: request.signal,
108
- ...(dispatch
138
+ ...(serverUrl
109
139
  ? {
110
- headers: dispatch.headers,
140
+ serverURL: serverUrl,
111
141
  }
112
142
  : {}),
143
+ ...nativeHeaders(dispatch?.headers, request),
113
144
  });
114
145
  await dispatch?.settle();
115
146
  return response;
@@ -124,6 +155,25 @@ async function sendNative({ client, decisionsRequest, request, spend, }) {
124
155
  dispatch?.end();
125
156
  }
126
157
  }
158
+ /**
159
+ * The request headers of a native call: the request's own, then the dispatch
160
+ * record's. Header names are not case-sensitive, so a request header that names a
161
+ * dispatch header in any case is dropped: sent beside it, the two values would be
162
+ * joined into one that names no record.
163
+ */
164
+ function nativeHeaders(dispatchHeaders, request) {
165
+ if (!dispatchHeaders && !request.headers) {
166
+ return {};
167
+ }
168
+ const reserved = new Set(Object.keys(dispatchHeaders ?? {}).map((name) => name.toLowerCase()));
169
+ const own = Object.entries(request.headers ?? {}).filter(([name]) => !reserved.has(name.toLowerCase()));
170
+ return {
171
+ headers: {
172
+ ...Object.fromEntries(own),
173
+ ...dispatchHeaders,
174
+ },
175
+ };
176
+ }
127
177
  /**
128
178
  * The native APIs require `instructions` on every question, while Noetic lets a
129
179
  * boolean question carry its meaning in `criteria` alone; and TypeSafe needs