@noetic-tools/core 5.16.1 → 5.18.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 (45) hide show
  1. package/dist/conditions/conditions.js +1 -0
  2. package/dist/harness/agent-harness.d.ts +54 -9
  3. package/dist/harness/agent-harness.js +192 -23
  4. package/dist/harness/decide-call.d.ts +3 -0
  5. package/dist/harness/decide-call.js +45 -12
  6. package/dist/harness/deps/adapters.d.ts +1 -1
  7. package/dist/harness/deps/adapters.js +1 -1
  8. package/dist/harness/deps/runtime.d.ts +4 -2
  9. package/dist/harness/deps/runtime.js +4 -2
  10. package/dist/harness/deps/types.d.ts +1 -1
  11. package/dist/harness/model-call.d.ts +5 -1
  12. package/dist/harness/model-call.js +107 -21
  13. package/dist/harness/model-price.d.ts +35 -0
  14. package/dist/harness/model-price.js +81 -0
  15. package/dist/harness/model-rounds.d.ts +2 -0
  16. package/dist/harness/model-rounds.js +5 -1
  17. package/dist/harness/spend.d.ts +138 -0
  18. package/dist/harness/spend.js +494 -0
  19. package/dist/harness/steer-inbox.d.ts +5 -0
  20. package/dist/harness/steer-inbox.js +45 -5
  21. package/dist/harness/thread-record.d.ts +17 -5
  22. package/dist/harness/thread-record.js +54 -4
  23. package/dist/index.d.ts +5 -1
  24. package/dist/index.js +2 -0
  25. package/dist/interpreter/execute-action.js +60 -11
  26. package/dist/interpreter/execute-control.js +1 -0
  27. package/dist/interpreter/execute-decide.js +18 -0
  28. package/dist/interpreter/execute.js +9 -0
  29. package/dist/runtime/context-impl.d.ts +1 -0
  30. package/dist/runtime/context-impl.js +1 -0
  31. package/dist/runtime/drain.d.ts +77 -0
  32. package/dist/runtime/drain.js +268 -0
  33. package/dist/runtime/durable/session-store.d.ts +12 -0
  34. package/dist/runtime/durable/session-store.js +16 -0
  35. package/dist/runtime/durable/spend-log.d.ts +38 -0
  36. package/dist/runtime/durable/spend-log.js +65 -0
  37. package/dist/runtime/durable/step-ledger.d.ts +6 -0
  38. package/dist/runtime/durable/step-ledger.js +3 -2
  39. package/dist/runtime/session-runner.d.ts +5 -3
  40. package/dist/runtime/session-runner.js +9 -4
  41. package/dist/until/predicates.d.ts +5 -1
  42. package/dist/until/predicates.js +12 -7
  43. package/dist/util/status-code.d.ts +5 -0
  44. package/dist/util/status-code.js +8 -0
  45. package/package.json +3 -3
@@ -0,0 +1,494 @@
1
+ /**
2
+ * Paid dispatches: a record before every paid provider call, and the bill settled
3
+ * afterwards even when the call was cut off (spec 23 § Paid dispatches).
4
+ *
5
+ * A call's record is written before it is sent, gains the provider's generation id
6
+ * when its response headers arrive, and is deleted when its bill reaches the run.
7
+ * A call that ends any other way — cancelled, steered, timed out, its host killed —
8
+ * leaves the record behind. It is then *pending*: held at its ceiling, and priced
9
+ * through the provider's generation lookup once the provider has billed it.
10
+ */
11
+ import { estimateTokens, recordUsage } from '@noetic-tools/types';
12
+ import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
13
+ import { hashText } from '../runtime/durable/step-ledger.js';
14
+ import { statusOf } from '../util/status-code.js';
15
+ import { ContextImpl, laneBase } from './deps/runtime.js';
16
+ import { ceilingOf, createPriceBook, LOOKUP_TIMEOUT_MS } from './model-price.js';
17
+ import { roundPath } from './model-rounds.js';
18
+ //#region Types
19
+ /** @internal Request header that ties a response back to its dispatch. */
20
+ export const DISPATCH_HEADER = 'x-noetic-dispatch';
21
+ /** @internal Response header carrying OpenRouter's id for the call. */
22
+ export const GENERATION_HEADER = 'x-generation-id';
23
+ const DEFAULT_PATIENCE_MS = 60e3;
24
+ const FIRST_POLL_MS = 1e3;
25
+ const MAX_POLL_MS = 10e3;
26
+ //#endregion
27
+ //#region Spend
28
+ /**
29
+ * @internal
30
+ * One harness's paid dispatches: the live ones it is sending and the pending ones it
31
+ * holds. Pending records come from storage, so any harness over the same storage can
32
+ * settle a call another harness made.
33
+ */
34
+ export class Spend {
35
+ host;
36
+ live = new Map();
37
+ holds = new Map();
38
+ /**
39
+ * Generation lookups in flight, so two callers never settle one dispatch twice and
40
+ * a reconcile waits for the ones already running.
41
+ */
42
+ lookups = new Map();
43
+ price;
44
+ constructor(host) {
45
+ this.host = host;
46
+ this.price = createPriceBook(() => host.client());
47
+ }
48
+ /** Write the record for a call about to be sent. A failed write never blocks the call. */
49
+ async open(params) {
50
+ const root = rootOf(params.ctx);
51
+ const path = pathOf(params.ctx);
52
+ const json = JSON.stringify(params.body) ?? '';
53
+ const record = {
54
+ id: crypto.randomUUID(),
55
+ kind: params.kind,
56
+ model: params.model,
57
+ requestHash: hashText(json),
58
+ inputTokens: estimateTokens(json),
59
+ ...(params.maxOutputTokens !== undefined
60
+ ? {
61
+ maxOutputTokens: params.maxOutputTokens,
62
+ }
63
+ : {}),
64
+ ...(root
65
+ ? {
66
+ executionId: root.id,
67
+ threadId: root.threadId,
68
+ }
69
+ : {}),
70
+ ...(path !== undefined
71
+ ? {
72
+ path: params.round === undefined ? path : roundPath(path, params.round),
73
+ }
74
+ : {}),
75
+ sentAt: new Date().toISOString(),
76
+ };
77
+ const dispatch = new Dispatch(this, this.host.log, record, root);
78
+ this.live.set(record.id, dispatch);
79
+ await quietly('write', () => this.host.log.put(record));
80
+ return dispatch;
81
+ }
82
+ /** Save a live dispatch's generation id. The client's response hook awaits it. */
83
+ noteGeneration(dispatchId, generationId) {
84
+ return this.live.get(dispatchId)?.noteGeneration(generationId) ?? Promise.resolve();
85
+ }
86
+ /** Unsettled dispatches, each with its ceiling. */
87
+ async pending(executionId) {
88
+ const records = await this.unsettled(executionId);
89
+ return Promise.all(records.map(async (record) => {
90
+ const ceiling = await this.ceilingOf(record);
91
+ return ceiling === undefined
92
+ ? record
93
+ : {
94
+ ...record,
95
+ ceiling,
96
+ };
97
+ }));
98
+ }
99
+ /**
100
+ * Hold the restored root context's pending dispatches on it, then reconcile them in
101
+ * the background. `ctx.heldCost` is set when this resolves.
102
+ */
103
+ async adopt(ctx) {
104
+ const root = rootOf(ctx);
105
+ const records = await this.unsettled(ctx.id);
106
+ await Promise.all(records.map((record) => this.hold(record, root)));
107
+ void this.reconcile({
108
+ executionId: ctx.id,
109
+ }).catch((error) => warn('reconcile', error));
110
+ }
111
+ /**
112
+ * Price every pending dispatch that has a generation id, polling until the provider
113
+ * has, and wait for lookups already running for the same dispatches.
114
+ */
115
+ async reconcile(opts = {}) {
116
+ const { executionId } = opts;
117
+ const running = [
118
+ ...this.lookups.values(),
119
+ ]
120
+ .filter((lookup) => executionId === undefined || lookup.executionId === executionId)
121
+ .map((lookup) => lookup.settled);
122
+ const records = await this.unsettled(executionId);
123
+ await Promise.all(records.map((record) => this.hold(record)));
124
+ const patienceMs = opts.patienceMs ?? DEFAULT_PATIENCE_MS;
125
+ const settled = await Promise.all([
126
+ ...running,
127
+ ...records.map((record) => this.lookup(record, patienceMs)),
128
+ ]);
129
+ const unique = new Map();
130
+ for (const settlement of settled) {
131
+ if (settlement) {
132
+ unique.set(settlement.id, settlement);
133
+ }
134
+ }
135
+ return [
136
+ ...unique.values(),
137
+ ];
138
+ }
139
+ /** Settle one pending dispatch at an amount the host asserts. */
140
+ async writeOff(id, opts) {
141
+ if (this.live.has(id)) {
142
+ return undefined;
143
+ }
144
+ const record = this.holds.get(id)?.record ?? (await this.host.log.get(id));
145
+ if (!record) {
146
+ return undefined;
147
+ }
148
+ await this.hold(record);
149
+ return this.settle(id, {
150
+ cost: opts.assumedCost,
151
+ inputTokens: 0,
152
+ outputTokens: 0,
153
+ }, true);
154
+ }
155
+ /** USD held for a thread's pending dispatches. */
156
+ heldFor(threadId) {
157
+ let held = 0;
158
+ for (const hold of this.holds.values()) {
159
+ if (hold.record.threadId === threadId) {
160
+ held += hold.ceiling ?? 0;
161
+ }
162
+ }
163
+ return held;
164
+ }
165
+ /** A live dispatch ended. Called by `Dispatch` only. */
166
+ release(id) {
167
+ this.live.delete(id);
168
+ }
169
+ /** A dispatch ended without a bill: hold it and start looking for one. Called by `Dispatch` only. */
170
+ leave(record, root) {
171
+ void this.hold(record, root)
172
+ .then(() => this.lookup(record, DEFAULT_PATIENCE_MS))
173
+ .catch((error) => warn('reconcile', error));
174
+ }
175
+ async unsettled(executionId) {
176
+ const records = await this.host.log.list();
177
+ return records.filter((record) => !this.live.has(record.id) &&
178
+ (executionId === undefined || record.executionId === executionId));
179
+ }
180
+ /**
181
+ * Hold `record` at its ceiling, on `ctx` when given. A dispatch already held moves to
182
+ * `ctx`, so an execution restored in this process takes over its cut-off calls.
183
+ */
184
+ hold(record, ctx) {
185
+ const known = this.holds.get(record.id);
186
+ if (known) {
187
+ if (ctx && known.ctx !== ctx) {
188
+ if (known.ctx && known.ceiling !== undefined) {
189
+ known.ctx.heldCost = Math.max(0, known.ctx.heldCost - known.ceiling);
190
+ }
191
+ known.ctx = ctx;
192
+ ctx.heldCost += known.ceiling ?? 0;
193
+ }
194
+ return known.ready;
195
+ }
196
+ const hold = {
197
+ record,
198
+ ctx,
199
+ ready: Promise.resolve(),
200
+ };
201
+ this.holds.set(record.id, hold);
202
+ hold.ready = this.ceilingOf(record).then((ceiling) => {
203
+ if (this.holds.get(record.id) !== hold) {
204
+ return;
205
+ }
206
+ hold.ceiling = ceiling;
207
+ if (hold.ctx && ceiling !== undefined) {
208
+ hold.ctx.heldCost += ceiling;
209
+ }
210
+ this.emit(hold, 'spend_pending', {
211
+ id: record.id,
212
+ kind: record.kind,
213
+ model: record.model,
214
+ generationId: record.generationId,
215
+ ceiling,
216
+ ...(ceiling === undefined
217
+ ? {
218
+ unbounded: true,
219
+ }
220
+ : {}),
221
+ });
222
+ });
223
+ return hold.ready;
224
+ }
225
+ async ceilingOf(record) {
226
+ const price = await this.price(record.model);
227
+ return price ? ceilingOf(record, price) : undefined;
228
+ }
229
+ lookup(record, patienceMs) {
230
+ const generationId = record.generationId;
231
+ if (!generationId) {
232
+ return Promise.resolve(undefined);
233
+ }
234
+ const running = this.lookups.get(record.id);
235
+ if (running) {
236
+ return running.settled;
237
+ }
238
+ const settled = this.poll(record.id, generationId, patienceMs).finally(() => {
239
+ this.lookups.delete(record.id);
240
+ });
241
+ this.lookups.set(record.id, {
242
+ executionId: record.executionId,
243
+ settled,
244
+ });
245
+ return settled;
246
+ }
247
+ /**
248
+ * Ask the provider for the call's bill until it has one. The provider prices a call
249
+ * some seconds after it ends — 7 to 32 s observed — so a lookup that gave up after a
250
+ * few seconds would leave ordinary calls unknown.
251
+ */
252
+ async poll(id, generationId, patienceMs) {
253
+ const client = this.host.client();
254
+ if (!client) {
255
+ return undefined;
256
+ }
257
+ const deadline = Date.now() + patienceMs;
258
+ for (let wait = FIRST_POLL_MS; this.holds.has(id); wait = Math.min(wait * 2, MAX_POLL_MS)) {
259
+ const bill = await fetchBill(client, generationId);
260
+ if (bill === 'stop') {
261
+ return undefined;
262
+ }
263
+ if (bill) {
264
+ return this.settle(id, bill);
265
+ }
266
+ if (Date.now() + wait > deadline) {
267
+ return undefined;
268
+ }
269
+ await sleep(wait);
270
+ }
271
+ return undefined;
272
+ }
273
+ /**
274
+ * Settle a held dispatch: drop its record, release its hold, and charge its bill
275
+ * once. The record goes first, so a crash part-way loses a settlement rather than
276
+ * counting one twice. A record already gone was settled by another harness over the
277
+ * same storage, which charged it; one that could not be deleted stays held, to be
278
+ * settled by a later reconcile.
279
+ */
280
+ async settle(id, bill, writtenOff = false) {
281
+ const hold = this.holds.get(id);
282
+ if (!hold || hold.settling) {
283
+ return undefined;
284
+ }
285
+ // The hold stays in place until the record is gone, so a reconcile listing storage
286
+ // meanwhile joins this settlement instead of holding the dispatch again.
287
+ hold.settling = true;
288
+ const taken = await this.take(id);
289
+ if (taken === 'failed') {
290
+ hold.settling = false;
291
+ return undefined;
292
+ }
293
+ this.holds.delete(id);
294
+ if (hold.ctx && hold.ceiling !== undefined) {
295
+ hold.ctx.heldCost = Math.max(0, hold.ctx.heldCost - hold.ceiling);
296
+ }
297
+ if (taken === 'gone') {
298
+ return undefined;
299
+ }
300
+ await this.charge(hold, bill);
301
+ const { executionId, threadId } = hold.record;
302
+ this.emit(hold, 'spend_settled', {
303
+ id,
304
+ cost: bill.cost,
305
+ ...(writtenOff
306
+ ? {
307
+ writtenOff,
308
+ }
309
+ : {}),
310
+ });
311
+ return {
312
+ id,
313
+ ...(executionId !== undefined
314
+ ? {
315
+ executionId,
316
+ }
317
+ : {}),
318
+ ...(threadId !== undefined
319
+ ? {
320
+ threadId,
321
+ }
322
+ : {}),
323
+ ...bill,
324
+ ...(writtenOff
325
+ ? {
326
+ writtenOff: true,
327
+ }
328
+ : {}),
329
+ };
330
+ }
331
+ /**
332
+ * Charge a bill to one place: the run in flight on its execution, else its thread's
333
+ * session, else the context this harness held it on. A run in flight passes the
334
+ * charge on to its turn's usage, so charging the session too would count it twice.
335
+ */
336
+ async charge(hold, bill) {
337
+ const charge = {
338
+ inputTokens: bill.inputTokens,
339
+ outputTokens: bill.outputTokens,
340
+ cost: bill.cost,
341
+ billedCost: bill.cost,
342
+ };
343
+ const { executionId, threadId } = hold.record;
344
+ const live = executionId !== undefined ? this.host.liveRoot(executionId) : undefined;
345
+ if (live) {
346
+ recordUsage(live, charge);
347
+ return;
348
+ }
349
+ if (threadId !== undefined && (await this.host.chargeSession(threadId, charge))) {
350
+ return;
351
+ }
352
+ if (hold.ctx) {
353
+ recordUsage(hold.ctx, charge);
354
+ }
355
+ }
356
+ /** Delete a held dispatch's record, unless it is already gone. */
357
+ async take(id) {
358
+ try {
359
+ if (!(await this.host.log.get(id))) {
360
+ return 'gone';
361
+ }
362
+ await this.host.log.remove(id);
363
+ return 'taken';
364
+ }
365
+ catch (error) {
366
+ warn('delete', error);
367
+ return 'failed';
368
+ }
369
+ }
370
+ emit(hold, eventType, data) {
371
+ const threadId = hold.record.threadId;
372
+ emitFrameworkEvent({
373
+ broadcaster: getBroadcaster(hold.ctx) ??
374
+ (threadId !== undefined ? this.host.sessionBroadcaster(threadId) : undefined),
375
+ agentName: this.host.agentName,
376
+ eventType,
377
+ data,
378
+ });
379
+ }
380
+ }
381
+ //#endregion
382
+ //#region Dispatch
383
+ /**
384
+ * @internal
385
+ * One paid call in flight. Record writes run one at a time, so a generation id saved
386
+ * late never brings back a record that was already deleted.
387
+ */
388
+ export class Dispatch {
389
+ spend;
390
+ log;
391
+ record;
392
+ root;
393
+ writes = Promise.resolve();
394
+ ended = false;
395
+ constructor(spend, log, record, root) {
396
+ this.spend = spend;
397
+ this.log = log;
398
+ this.record = record;
399
+ this.root = root;
400
+ }
401
+ /** Request headers that tie the response back to this dispatch. */
402
+ get headers() {
403
+ return {
404
+ [DISPATCH_HEADER]: this.record.id,
405
+ };
406
+ }
407
+ noteGeneration(generationId) {
408
+ if (this.ended || this.record.generationId) {
409
+ return this.writes;
410
+ }
411
+ this.record.generationId = generationId;
412
+ return this.queue('write', () => this.log.put(this.record));
413
+ }
414
+ /** The call's bill reached the run, or the provider refused it: drop the record. */
415
+ settle() {
416
+ if (this.ended) {
417
+ return this.writes;
418
+ }
419
+ this.ended = true;
420
+ this.spend.release(this.record.id);
421
+ return this.queue('delete', () => this.log.remove(this.record.id));
422
+ }
423
+ /** The call is over. Without a settled bill its record stays, pending. */
424
+ end() {
425
+ if (this.ended) {
426
+ return;
427
+ }
428
+ this.ended = true;
429
+ this.spend.release(this.record.id);
430
+ void this.writes.then(() => this.spend.leave(this.record, this.root));
431
+ }
432
+ queue(what, write) {
433
+ this.writes = this.writes.then(() => quietly(what, write));
434
+ return this.writes;
435
+ }
436
+ }
437
+ //#endregion
438
+ //#region Helpers
439
+ function rootOf(ctx) {
440
+ let node = ctx;
441
+ while (node?.parent) {
442
+ node = node.parent;
443
+ }
444
+ const root = node ? laneBase(node) : undefined;
445
+ return root instanceof ContextImpl ? root : undefined;
446
+ }
447
+ function pathOf(ctx) {
448
+ return ctx instanceof ContextImpl ? ctx.currentDispatch()?.path : undefined;
449
+ }
450
+ /**
451
+ * The provider's bill for a call: undefined while it has not priced it yet, 'stop'
452
+ * when asking again cannot help.
453
+ */
454
+ async function fetchBill(client, generationId) {
455
+ try {
456
+ const { data } = await client.generations.getGeneration({
457
+ id: generationId,
458
+ }, {
459
+ timeoutMs: LOOKUP_TIMEOUT_MS,
460
+ });
461
+ return {
462
+ cost: data.totalCost,
463
+ inputTokens: data.tokensPrompt ?? 0,
464
+ outputTokens: data.tokensCompletion ?? 0,
465
+ };
466
+ }
467
+ catch (e) {
468
+ const status = statusOf(e);
469
+ const transient = status === undefined || status === 404 || status === 429 || status >= 500;
470
+ return transient ? undefined : 'stop';
471
+ }
472
+ }
473
+ /** Storage is best-effort here, as for checkpoints: a failed write never fails the call. */
474
+ async function quietly(what, write) {
475
+ try {
476
+ await write();
477
+ }
478
+ catch (error) {
479
+ warn(what, error);
480
+ }
481
+ }
482
+ function warn(what, error) {
483
+ console.warn(`Spend: dispatch ${what} failed:`, error instanceof Error ? error.message : String(error));
484
+ }
485
+ /** A wait that does not keep the host process alive. */
486
+ function sleep(ms) {
487
+ return new Promise((resolve) => {
488
+ const timer = setTimeout(resolve, ms);
489
+ if (typeof timer === 'object' && 'unref' in timer) {
490
+ timer.unref();
491
+ }
492
+ });
493
+ }
494
+ //#endregion
@@ -5,6 +5,8 @@ import type { MessageQueue } from '../runtime/message-queue.js';
5
5
  export interface StagedSteers {
6
6
  messageIds: string[];
7
7
  items: Item[];
8
+ /** A layer asked for recall to run again once these are applied. */
9
+ recall: boolean;
8
10
  }
9
11
  interface SteerInboxOpts {
10
12
  queue: MessageQueue;
@@ -12,6 +14,8 @@ interface SteerInboxOpts {
12
14
  layers: ContextLayer[];
13
15
  harness: AgentHarnessContract;
14
16
  emit: (eventType: string, data: Record<string, unknown>) => void;
17
+ /** Whether an item with this id is already in the conversation. */
18
+ inConversation: (itemId: string) => boolean;
15
19
  }
16
20
  /**
17
21
  * @internal Open the steer inbox for a model call, or `undefined` when the call
@@ -42,6 +46,7 @@ export declare class SteerInbox {
42
46
  offer(point: SteerPoint, pendingCalls?: ReadonlyArray<FunctionCallItem>): Promise<boolean>;
43
47
  /** Hand over the staged steers and clear them. */
44
48
  takeStaged(): StagedSteers;
49
+ private alreadyApplied;
45
50
  private judge;
46
51
  /** Steers are user input, so they pass through `onItemAppend` like any other.
47
52
  * Re-render requests are ignored: recall does not run again mid-call. */
@@ -33,6 +33,7 @@ export class SteerInbox {
33
33
  staged = {
34
34
  messageIds: [],
35
35
  items: [],
36
+ recall: false,
36
37
  };
37
38
  /** Steers already reported as waiting on tool calls, so each is reported once. */
38
39
  reportedPending = new Set();
@@ -52,7 +53,14 @@ export class SteerInbox {
52
53
  async offer(point, pendingCalls = []) {
53
54
  let stagedAny = false;
54
55
  for (const message of this.opts.queue.peekAll().filter(isSteer)) {
55
- const verdict = await this.judge(message, point, pendingCalls);
56
+ const items = steerItems(message);
57
+ // A resumed turn re-queues the steers its last run kept; the ones that run
58
+ // already applied come back with the replayed rounds and steps.
59
+ if (this.alreadyApplied(items)) {
60
+ this.opts.queue.take((queued) => queued === message);
61
+ continue;
62
+ }
63
+ const verdict = await this.judge(message, items, point, pendingCalls);
56
64
  if (verdict.action === SteerAction.Defer) {
57
65
  this.reportPending(message, point, pendingCalls);
58
66
  continue;
@@ -68,7 +76,7 @@ export class SteerInbox {
68
76
  });
69
77
  continue;
70
78
  }
71
- await this.stage(message.id, verdict.items);
79
+ await this.stage(message.id, verdict.items, verdict.recall === true);
72
80
  stagedAny = true;
73
81
  }
74
82
  return stagedAny;
@@ -79,12 +87,16 @@ export class SteerInbox {
79
87
  this.staged = {
80
88
  messageIds: [],
81
89
  items: [],
90
+ recall: false,
82
91
  };
83
92
  return staged;
84
93
  }
85
- async judge(message, point, pendingCalls) {
94
+ alreadyApplied(items) {
95
+ return (items.length > 0 &&
96
+ items.every((item) => 'id' in item && item.id !== undefined && this.opts.inConversation(item.id)));
97
+ }
98
+ async judge(message, items, point, pendingCalls) {
86
99
  const action = defaultAction(point, message.deliveryMode);
87
- const items = inputToItems(message.input);
88
100
  const { harness, layers } = this.opts;
89
101
  if (!harness.onSteer || !layers.some((layer) => layer.hooks.onSteer)) {
90
102
  return {
@@ -104,12 +116,13 @@ export class SteerInbox {
104
116
  }
105
117
  /** Steers are user input, so they pass through `onItemAppend` like any other.
106
118
  * Re-render requests are ignored: recall does not run again mid-call. */
107
- async stage(messageId, items) {
119
+ async stage(messageId, items, recall) {
108
120
  const piped = this.opts.layers.length > 0
109
121
  ? (await this.opts.harness.runAppendPipeline(this.opts.layers, items, this.opts.ctx)).items
110
122
  : items;
111
123
  this.staged.messageIds.push(messageId);
112
124
  this.staged.items.push(...piped);
125
+ this.staged.recall ||= recall;
113
126
  }
114
127
  reportPending(message, point, pendingCalls) {
115
128
  if (point !== SteerPoint.BeforeToolCall || this.reportedPending.has(message.id)) {
@@ -124,6 +137,33 @@ export class SteerInbox {
124
137
  }
125
138
  //#endregion
126
139
  //#region Helpers
140
+ /**
141
+ * A steer's items. Text gets an id from the message id rather than a random one,
142
+ * so a resumed turn can tell the steer is already in the conversation.
143
+ */
144
+ function steerItems(message) {
145
+ if (typeof message.input !== 'string') {
146
+ return inputToItems(message.input);
147
+ }
148
+ if (message.input.length === 0) {
149
+ return [];
150
+ }
151
+ const item = {
152
+ id: `steer-${message.id}`,
153
+ type: 'message',
154
+ role: 'user',
155
+ status: 'completed',
156
+ content: [
157
+ {
158
+ type: 'input_text',
159
+ text: message.input,
160
+ },
161
+ ],
162
+ };
163
+ return [
164
+ item,
165
+ ];
166
+ }
127
167
  function findSessionQueue(ctx) {
128
168
  for (let current = ctx; current; current = current.parent) {
129
169
  const ext = frameworkCast(current);
@@ -8,7 +8,7 @@
8
8
  * a harness built a moment ago behave the same.
9
9
  */
10
10
  import type { Context, Item, SessionUsage } from '@noetic-tools/types';
11
- import type { RestoreCheckpointOptions, SessionStore, TurnUsage } from './deps/runtime.js';
11
+ import type { QueuedMessage, RestoreCheckpointOptions, SessionStore, TurnUsage } from './deps/runtime.js';
12
12
  /** @internal The harness surface a thread record needs. */
13
13
  export interface ThreadRecordHost {
14
14
  readonly store: SessionStore;
@@ -20,7 +20,8 @@ export interface ThreadRecordHost {
20
20
  * @internal
21
21
  * One thread's stored session. Turns call `history` → `resume` → `begin` → `end`; a
22
22
  * turn that throws never reaches `end`, so its record stays for a re-delivery of the
23
- * same messages to resume. Operations run one at a time, in call order, so a read
23
+ * same messages to resume. Steers sent into a running turn are kept with `keepSteer`
24
+ * until `end`. Operations run one at a time, in call order, so a read
24
25
  * never overtakes a write issued before it.
25
26
  */
26
27
  export declare class ThreadRecord {
@@ -38,10 +39,20 @@ export declare class ThreadRecord {
38
39
  * dropped, its checkpoint cleared, and the new messages start a fresh turn.
39
40
  */
40
41
  resume(messageIds: ReadonlyArray<string>, opts: RestoreCheckpointOptions): Promise<Context | undefined>;
41
- /** Record the turn about to run on `ctx`, before any of it runs. */
42
+ /** Keep a steer sent into the running turn, so a resumed turn still applies it. */
43
+ keepSteer(message: QueuedMessage): Promise<void>;
44
+ /** The steers kept for the turn in flight, as queue messages. */
45
+ steers(): Promise<QueuedMessage[]>;
46
+ /**
47
+ * Record the turn about to run on `ctx`, before any of it runs. Kept steers it
48
+ * delivers as input stop being steers: re-delivering the turn re-sends them.
49
+ */
42
50
  begin(ctx: Context, messageIds: ReadonlyArray<string>): Promise<void>;
43
- /** The turn on `ctx` finished: store the history it left and drop its checkpoint. */
44
- end(ctx: Context, history: ReadonlyArray<Item>): Promise<void>;
51
+ /**
52
+ * The turn on `ctx` finished: store the history it left and drop its checkpoint.
53
+ * Only steers still queued are kept; the rest were applied or dropped.
54
+ */
55
+ end(ctx: Context, history: ReadonlyArray<Item>, queuedIds: ReadonlyArray<string>): Promise<void>;
45
56
  /** Add one turn's spend to the stored totals, and return the totals now stored. */
46
57
  addUsage(spent: TurnUsage): Promise<SessionUsage>;
47
58
  /** The stored totals. */
@@ -49,6 +60,7 @@ export declare class ThreadRecord {
49
60
  private update;
50
61
  /** Read-modify-write the stored record. Call only from inside `run`. */
51
62
  private write;
63
+ private parseInput;
52
64
  private load;
53
65
  private run;
54
66
  }