@noetic-tools/core 5.22.0-next.2 → 5.22.0-next.4

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 (47) hide show
  1. package/dist/adapters/in-memory-subprocess-adapter.js +4 -2
  2. package/dist/builders/custom-item.d.ts +1 -1
  3. package/dist/builders/custom-item.js +14 -3
  4. package/dist/connections/pool.d.ts +18 -0
  5. package/dist/connections/pool.js +54 -9
  6. package/dist/connections/registry.js +11 -0
  7. package/dist/harness/agent-harness.d.ts +110 -4
  8. package/dist/harness/agent-harness.js +394 -40
  9. package/dist/harness/deps/types.d.ts +1 -1
  10. package/dist/harness/forget.d.ts +57 -0
  11. package/dist/harness/forget.js +496 -0
  12. package/dist/harness/harness-options.d.ts +40 -1
  13. package/dist/harness/model-rounds.d.ts +6 -0
  14. package/dist/harness/model-rounds.js +7 -3
  15. package/dist/harness/model-tool-round.js +19 -5
  16. package/dist/harness/park-watchers.d.ts +3 -2
  17. package/dist/harness/recorded-tool-calls.d.ts +16 -0
  18. package/dist/harness/recorded-tool-calls.js +106 -0
  19. package/dist/harness/spend.d.ts +13 -1
  20. package/dist/harness/spend.js +82 -1
  21. package/dist/harness/steer-inbox.js +9 -5
  22. package/dist/harness/thread-record.d.ts +23 -1
  23. package/dist/harness/thread-record.js +98 -21
  24. package/dist/harness/turn-cuts.d.ts +50 -0
  25. package/dist/harness/turn-cuts.js +108 -0
  26. package/dist/index.d.ts +6 -7
  27. package/dist/index.js +2 -3
  28. package/dist/interpreter/acp-tools.js +21 -4
  29. package/dist/interpreter/execute-action.js +7 -1
  30. package/dist/interpreter/execute.js +55 -3
  31. package/dist/interpreter/step-dispatcher.js +17 -1
  32. package/dist/interpreter/step-kind-dispatch.js +9 -1
  33. package/dist/runtime/durable/child-links.d.ts +61 -0
  34. package/dist/runtime/durable/child-links.js +127 -0
  35. package/dist/runtime/durable/session-store.d.ts +11 -0
  36. package/dist/runtime/durable/session-store.js +28 -2
  37. package/dist/runtime/durable/turn-lease.d.ts +10 -0
  38. package/dist/runtime/durable/turn-lease.js +10 -2
  39. package/dist/runtime/held-calls.d.ts +65 -6
  40. package/dist/runtime/held-calls.js +257 -5
  41. package/dist/runtime/output-store.d.ts +2 -0
  42. package/dist/runtime/output-store.js +3 -1
  43. package/dist/runtime/session-runner.d.ts +9 -1
  44. package/dist/runtime/session-runner.js +34 -0
  45. package/dist/runtime/tool-approval.d.ts +1 -3
  46. package/dist/runtime/tool-approval.js +1 -1
  47. package/package.json +2 -2
@@ -70,6 +70,18 @@ const SessionRecordSchema = z.object({
70
70
  z.string(),
71
71
  ])
72
72
  .optional(),
73
+ /**
74
+ * Set while the turn is cut (spec 23 § Cut turns): its lease was lost or a
75
+ * durable write failed, and a wake runs it again once its back-off is over.
76
+ * `count` is how many times it has been cut.
77
+ */
78
+ cut: z
79
+ .object({
80
+ reason: z.string(),
81
+ count: z.number(),
82
+ at: z.number(),
83
+ })
84
+ .optional(),
73
85
  /** Set while the turn is parked: every part of it waits, and no harness holds it. */
74
86
  parked: z
75
87
  .object({
@@ -92,6 +104,18 @@ const SessionRecordSchema = z.object({
92
104
  executionId: z.string().optional(),
93
105
  }))
94
106
  .optional(),
107
+ /**
108
+ * Every execution the thread began a turn on, oldest first. `done` keeps only the
109
+ * last few turns; this is how a forget (spec 23 § Forgetting) and the thread's trail
110
+ * find the older ones. Absent in records written before it was kept.
111
+ */
112
+ executions: z.array(z.string()).optional(),
113
+ /**
114
+ * Ids of the context layers whose state may be kept at the thread's scope key, so a
115
+ * forget on a harness that never ran the thread still finds it. Absent in records
116
+ * written before it was kept.
117
+ */
118
+ layers: z.array(z.string()).optional(),
95
119
  /** Steers sent into the turn in flight, in arrival order. */
96
120
  steers: z
97
121
  .array(z.object({
@@ -145,8 +169,10 @@ export function createSessionStore(storage) {
145
169
  threads: async () => (await storage.list(SESSION_PREFIX)).map((key) => key.slice(SESSION_PREFIX.length)),
146
170
  };
147
171
  }
148
- const SESSION_PREFIX = 'session:';
149
- function sessionKey(threadId) {
172
+ /** @internal The prefix every thread's record key starts with. */
173
+ export const SESSION_PREFIX = 'session:';
174
+ /** @internal The key a thread's record is stored under. */
175
+ export function sessionKey(threadId) {
150
176
  return `${SESSION_PREFIX}${threadId}`;
151
177
  }
152
178
  //#endregion
@@ -58,6 +58,14 @@ export interface LedgerFence {
58
58
  }
59
59
  /** @internal True when `storage` can compare-and-set. */
60
60
  export declare function canSwap(storage: StorageAdapter | undefined): storage is SwapStorage;
61
+ /**
62
+ * @internal
63
+ * A prefix of its own. Under `session:`, the lease of thread `a` and the session
64
+ * of a thread named `a:lease` would be one key.
65
+ */
66
+ export declare function leaseKey(threadId: string): string;
67
+ /** @internal The prefix every thread's lease key starts with. */
68
+ export declare const LEASE_PREFIX = "turn-lease:";
61
69
  /** @internal True when a harness other than `opts.holder` holds the thread's lease now. */
62
70
  /**
63
71
  * @internal
@@ -119,6 +127,8 @@ export declare class TurnLease implements LedgerFence {
119
127
  renew(): Promise<void>;
120
128
  private renewOnce;
121
129
  verify(): Promise<void>;
130
+ /** Stop renewing, and wait for a renewal in flight, keeping the lease as it stands. */
131
+ stop(): Promise<void>;
122
132
  /** Hand the lease back so the next turn need not wait for it to run out. */
123
133
  release(): Promise<void>;
124
134
  private markLost;
@@ -52,12 +52,15 @@ function isHeldBy(record, holder, now) {
52
52
  return record !== null && record.holder !== holder && record.heldUntil > now;
53
53
  }
54
54
  /**
55
+ * @internal
55
56
  * A prefix of its own. Under `session:`, the lease of thread `a` and the session
56
57
  * of a thread named `a:lease` would be one key.
57
58
  */
58
- function leaseKey(threadId) {
59
- return `turn-lease:${threadId}`;
59
+ export function leaseKey(threadId) {
60
+ return `${LEASE_PREFIX}${threadId}`;
60
61
  }
62
+ /** @internal The prefix every thread's lease key starts with. */
63
+ export const LEASE_PREFIX = 'turn-lease:';
61
64
  /**
62
65
  * The term to take the lease at. It only ever goes up: a lease that went back to
63
66
  * term 1 would lose every write to the entries a higher term left in the ledger,
@@ -261,6 +264,11 @@ export class TurnLease {
261
264
  }
262
265
  this.assert();
263
266
  }
267
+ /** Stop renewing, and wait for a renewal in flight, keeping the lease as it stands. */
268
+ async stop() {
269
+ this.stopTimer();
270
+ await this.renewing;
271
+ }
264
272
  /** Hand the lease back so the next turn need not wait for it to run out. */
265
273
  async release() {
266
274
  this.stopTimer();
@@ -11,7 +11,7 @@
11
11
  * turn resumed on another harness finds the same record and the same answer.
12
12
  */
13
13
  import type { StorageAdapter } from '@noetic-tools/context';
14
- import type { Context, HeldCall, HeldResolution, ToolApprover } from '@noetic-tools/types';
14
+ import type { Context, HeldCall, HeldCallHandler, HeldCallSettled, HeldResolution, ToolApprover } from '@noetic-tools/types';
15
15
  import { z } from 'zod';
16
16
  declare const HeldRecordSchema: z.ZodObject<{
17
17
  callId: z.ZodString;
@@ -49,7 +49,24 @@ export interface HoldHost {
49
49
  readonly storage?: StorageAdapter;
50
50
  readonly now?: () => number;
51
51
  readonly approveToolCall?: ToolApprover;
52
+ readonly onHeld?: HeldCallHandler;
52
53
  };
54
+ /** The thread a context's held calls belong to, when it is a thread's turn. */
55
+ heldThreadOf?(ctx: Context): string | undefined;
56
+ /**
57
+ * Answer a call held under `executionId`, as a decision item does, and wake its
58
+ * thread's turn when that turn is this execution and parked.
59
+ */
60
+ answerHeld?(answer: HeldAnswerRequest): Promise<void>;
61
+ }
62
+ /** @internal An answer to a held call, for the execution that holds it. */
63
+ export interface HeldAnswerRequest {
64
+ readonly executionId: string;
65
+ /** The thread whose turn held the call, when it was a thread's turn. */
66
+ readonly threadId?: string;
67
+ readonly callId: string;
68
+ readonly argsHash: string;
69
+ readonly resolution: HeldResolution;
53
70
  }
54
71
  /** @internal How long a hold lasts and what happens when that runs out. */
55
72
  export interface HoldDue {
@@ -74,6 +91,12 @@ export declare class HeldCalls {
74
91
  private readonly storage;
75
92
  private readonly clock;
76
93
  private readonly waiters;
94
+ /** Calls announced held in this process, by execution and call. */
95
+ private readonly watches;
96
+ /** Watched calls this process is closing: a sweep leaves them to `close`. */
97
+ private readonly closing;
98
+ /** Re-reads watched calls on shared storage, which another harness may settle. */
99
+ private sweeper;
77
100
  constructor(storage: StorageAdapter, clock: () => number);
78
101
  now(): number;
79
102
  /** The record of `callId`, when the call is held. */
@@ -100,8 +123,32 @@ export declare class HeldCalls {
100
123
  wasStarted(executionId: string, callId: string, argsHash: string): Promise<boolean>;
101
124
  /** The call finished and its result is on record. */
102
125
  disarm(executionId: string, callId: string): Promise<void>;
103
- /** The call was settled and its result recorded: drop its record. */
104
- close(executionId: string, callId: string): Promise<void>;
126
+ /**
127
+ * The call was settled and its result recorded, or it is being dropped: drop its
128
+ * record. `by` says why, for a call this process announced; without it the record
129
+ * says: answered, overdue, or else cancelled.
130
+ */
131
+ close(executionId: string, callId: string, by?: HeldCallSettled['by']): Promise<void>;
132
+ /**
133
+ * Note that this process announced `held`. Resolves the signal a handler waits on,
134
+ * or `undefined` when the same question is already being watched here. A different
135
+ * question under the same id replaces the old one: a call held for a new reason
136
+ * moved on because the old question was answered; one held for other arguments
137
+ * voided it.
138
+ */
139
+ watch(executionId: string, held: HeldCall, emit: (settled: HeldCallSettled) => void): AbortSignal | undefined;
140
+ /**
141
+ * On shared storage another harness may answer, skip or drop a call this process
142
+ * announced, and finish its turn, so nothing here would ever close it. Watched
143
+ * calls are read again every so often while any are watched.
144
+ */
145
+ private armSweep;
146
+ private stopSweep;
147
+ /** Settle every watched call whose record says it is no longer the question shown. */
148
+ sweep(): Promise<void>;
149
+ /** The harness is closing: every handler still waiting is let go, with no event. */
150
+ releaseWatches(): void;
151
+ private settleWatch;
105
152
  /**
106
153
  * Answer a held call. The first answer wins: the same answer again is a no-op, a
107
154
  * different one is refused.
@@ -178,15 +225,27 @@ export declare function holdAndWait(opts: {
178
225
  harness: HoldHost;
179
226
  ctx: Context;
180
227
  record: HeldRecord;
181
- /** Called once per process, when the call is first seen held. */
182
- onHeld?: (held: HeldCall) => void;
183
228
  }): Promise<HeldAnswer>;
184
229
  /**
185
230
  * @internal
186
231
  * Says on the stream that a call is held: `{name}:tool_call_held`, with the fields
187
- * `harness.pending()` returns. What a hold does when its caller gives no `onHeld`.
232
+ * `harness.pending()` returns, and puts it to the harness's `onHeld` handler.
188
233
  */
189
234
  export declare function announcerOf(harness: HoldHost, ctx: Context): (held: HeldCall) => void;
235
+ /**
236
+ * @internal
237
+ * A call was announced held in this process (spec 08 § Held tool calls): watch it, so
238
+ * `tool_call_settled` follows when it stops being held, and put it to the harness's
239
+ * `onHeld` handler, once per question. Never waits on the handler.
240
+ *
241
+ * @param emit - How the settling is said, when not on `ctx`'s stream as is.
242
+ */
243
+ export declare function noticeHeld(opts: {
244
+ harness: HoldHost;
245
+ ctx: Context;
246
+ held: HeldCall;
247
+ emit?: (settled: HeldCallSettled) => void;
248
+ }): void;
190
249
  /** True once a hold with a `deny` deadline has run out. */
191
250
  export declare function isOverdue(record: HeldRecord, now: number): boolean;
192
251
  export {};
@@ -113,6 +113,38 @@ function toResolutionRecord(resolution) {
113
113
  hasOutput: true,
114
114
  };
115
115
  }
116
+ function watchKey(executionId, callId) {
117
+ return `${executionId}\u0000${callId}`;
118
+ }
119
+ function settledOf(held, by) {
120
+ return {
121
+ callId: held.callId,
122
+ name: held.name,
123
+ argsHash: held.argsHash,
124
+ reason: held.reason,
125
+ by,
126
+ };
127
+ }
128
+ /** Why a record that is being closed stopped being held, as the record says. */
129
+ function settledByOf(record, now) {
130
+ if (record?.resolution !== undefined) {
131
+ return 'answer';
132
+ }
133
+ if (record && isOverdue(record, now)) {
134
+ return 'due';
135
+ }
136
+ return 'cancelled';
137
+ }
138
+ /**
139
+ * Whether a watched call is still the question shown: held, unanswered, for the same
140
+ * arguments and reason. Anything else means another harness settled it.
141
+ */
142
+ function stillShown(record, held) {
143
+ return (record !== undefined &&
144
+ record.resolution === undefined &&
145
+ record.argsHash === held.argsHash &&
146
+ record.reason === held.reason);
147
+ }
116
148
  /** A held record as hosts see it. */
117
149
  export function toHeldCall(record) {
118
150
  return {
@@ -145,6 +177,12 @@ export class HeldCalls {
145
177
  storage;
146
178
  clock;
147
179
  waiters = new Map();
180
+ /** Calls announced held in this process, by execution and call. */
181
+ watches = new Map();
182
+ /** Watched calls this process is closing: a sweep leaves them to `close`. */
183
+ closing = new Set();
184
+ /** Re-reads watched calls on shared storage, which another harness may settle. */
185
+ sweeper;
148
186
  constructor(storage, clock) {
149
187
  this.storage = storage;
150
188
  this.clock = clock;
@@ -190,6 +228,13 @@ export class HeldCalls {
190
228
  }
191
229
  /** Drop every held call and intent of an execution that is over or was abandoned. */
192
230
  async clear(executionId) {
231
+ for (const key of [
232
+ ...this.watches.keys(),
233
+ ]) {
234
+ if (key.startsWith(`${executionId}\u0000`)) {
235
+ this.settleWatch(key, 'cancelled');
236
+ }
237
+ }
193
238
  for (const prefix of [
194
239
  heldPrefix(executionId),
195
240
  intentPrefix(executionId),
@@ -218,9 +263,118 @@ export class HeldCalls {
218
263
  async disarm(executionId, callId) {
219
264
  await this.storage.delete(`${intentPrefix(executionId)}${callId}`);
220
265
  }
221
- /** The call was settled and its result recorded: drop its record. */
222
- async close(executionId, callId) {
223
- await this.storage.delete(`${heldPrefix(executionId)}${callId}`);
266
+ /**
267
+ * The call was settled and its result recorded, or it is being dropped: drop its
268
+ * record. `by` says why, for a call this process announced; without it the record
269
+ * says: answered, overdue, or else cancelled.
270
+ */
271
+ async close(executionId, callId, by) {
272
+ const key = watchKey(executionId, callId);
273
+ const watched = this.watches.has(key);
274
+ if (watched) {
275
+ this.closing.add(key);
276
+ }
277
+ try {
278
+ const settledBy = watched && by === undefined
279
+ ? settledByOf(await this.load(executionId, callId), this.now())
280
+ : by;
281
+ await this.storage.delete(`${heldPrefix(executionId)}${callId}`);
282
+ if (settledBy !== undefined) {
283
+ this.settleWatch(key, settledBy);
284
+ }
285
+ }
286
+ finally {
287
+ this.closing.delete(key);
288
+ }
289
+ }
290
+ /**
291
+ * Note that this process announced `held`. Resolves the signal a handler waits on,
292
+ * or `undefined` when the same question is already being watched here. A different
293
+ * question under the same id replaces the old one: a call held for a new reason
294
+ * moved on because the old question was answered; one held for other arguments
295
+ * voided it.
296
+ */
297
+ watch(executionId, held, emit) {
298
+ const key = watchKey(executionId, held.callId);
299
+ const existing = this.watches.get(key);
300
+ if (existing?.held.argsHash === held.argsHash && existing.held.reason === held.reason) {
301
+ return undefined;
302
+ }
303
+ if (existing) {
304
+ this.settleWatch(key, existing.held.reason === held.reason ? 'cancelled' : 'answer');
305
+ }
306
+ const controller = new AbortController();
307
+ this.watches.set(key, {
308
+ executionId,
309
+ held,
310
+ controller,
311
+ emit,
312
+ });
313
+ this.armSweep();
314
+ return controller.signal;
315
+ }
316
+ /**
317
+ * On shared storage another harness may answer, skip or drop a call this process
318
+ * announced, and finish its turn, so nothing here would ever close it. Watched
319
+ * calls are read again every so often while any are watched.
320
+ */
321
+ armSweep() {
322
+ if (!this.shared || this.sweeper !== undefined) {
323
+ return;
324
+ }
325
+ const sweeper = setInterval(() => {
326
+ void this.sweep().catch(() => undefined);
327
+ }, HELD_POLL_MS);
328
+ if (typeof sweeper === 'object' && 'unref' in sweeper) {
329
+ sweeper.unref();
330
+ }
331
+ this.sweeper = sweeper;
332
+ }
333
+ stopSweep() {
334
+ clearInterval(this.sweeper);
335
+ this.sweeper = undefined;
336
+ }
337
+ /** Settle every watched call whose record says it is no longer the question shown. */
338
+ async sweep() {
339
+ for (const [key, watch] of [
340
+ ...this.watches,
341
+ ]) {
342
+ const record = await this.load(watch.executionId, watch.held.callId);
343
+ if (this.watches.get(key) !== watch || this.closing.has(key)) {
344
+ continue;
345
+ }
346
+ // Settled by another harness, which cannot say how: reported as answered.
347
+ if (!stillShown(record, watch.held)) {
348
+ this.settleWatch(key, 'answer');
349
+ }
350
+ }
351
+ }
352
+ /** The harness is closing: every handler still waiting is let go, with no event. */
353
+ releaseWatches() {
354
+ this.stopSweep();
355
+ for (const [key, watch] of [
356
+ ...this.watches,
357
+ ]) {
358
+ this.watches.delete(key);
359
+ watch.controller.abort(settledOf(watch.held, 'cancelled'));
360
+ }
361
+ }
362
+ settleWatch(key, by) {
363
+ const watch = this.watches.get(key);
364
+ if (!watch) {
365
+ return;
366
+ }
367
+ this.watches.delete(key);
368
+ if (this.watches.size === 0) {
369
+ this.stopSweep();
370
+ }
371
+ const settled = settledOf(watch.held, by);
372
+ try {
373
+ watch.emit(settled);
374
+ }
375
+ finally {
376
+ watch.controller.abort(settled);
377
+ }
224
378
  }
225
379
  /**
226
380
  * Answer a held call. The first answer wins: the same answer again is a no-op, a
@@ -288,6 +442,7 @@ export class HeldCalls {
288
442
  }
289
443
  throw refused(callId, 'the call was already answered differently');
290
444
  }
445
+ this.settleWatch(watchKey(executionId, callId), 'answer');
291
446
  this.notify(executionId);
292
447
  }
293
448
  /** True when other processes may share this storage, and so may answer a call. */
@@ -450,7 +605,7 @@ export async function holdAndWait(opts) {
450
605
  const { callId } = opts.record;
451
606
  const opened = mayWriteHolds(opts.ctx) ? await holds.open(executionId, opts.record) : opts.record;
452
607
  if (opened.resolution === undefined) {
453
- (opts.onHeld ?? announcerOf(opts.harness, opts.ctx))(toHeldCall(opened));
608
+ announcerOf(opts.harness, opts.ctx)(toHeldCall(opened));
454
609
  }
455
610
  for (;;) {
456
611
  const current = await holds.load(executionId, callId);
@@ -475,7 +630,7 @@ export async function holdAndWait(opts) {
475
630
  /**
476
631
  * @internal
477
632
  * Says on the stream that a call is held: `{name}:tool_call_held`, with the fields
478
- * `harness.pending()` returns. What a hold does when its caller gives no `onHeld`.
633
+ * `harness.pending()` returns, and puts it to the harness's `onHeld` handler.
479
634
  */
480
635
  export function announcerOf(harness, ctx) {
481
636
  return (held) => {
@@ -487,8 +642,105 @@ export function announcerOf(harness, ctx) {
487
642
  ...held,
488
643
  },
489
644
  });
645
+ noticeHeld({
646
+ harness,
647
+ ctx,
648
+ held,
649
+ });
650
+ };
651
+ }
652
+ /** Emits `{name}:tool_call_settled` on the context's stream. */
653
+ function settledAnnouncerOf(harness, ctx) {
654
+ return (settled) => {
655
+ emitFrameworkEvent({
656
+ broadcaster: getBroadcaster(ctx),
657
+ agentName: harness.config.name,
658
+ eventType: 'tool_call_settled',
659
+ data: {
660
+ ...settled,
661
+ },
662
+ });
490
663
  };
491
664
  }
665
+ /**
666
+ * @internal
667
+ * A call was announced held in this process (spec 08 § Held tool calls): watch it, so
668
+ * `tool_call_settled` follows when it stops being held, and put it to the harness's
669
+ * `onHeld` handler, once per question. Never waits on the handler.
670
+ *
671
+ * @param emit - How the settling is said, when not on `ctx`'s stream as is.
672
+ */
673
+ export function noticeHeld(opts) {
674
+ const { harness, ctx, held } = opts;
675
+ const executionId = heldScopeOf(ctx);
676
+ const signal = heldCallsOf(harness).watch(executionId, held, opts.emit ?? settledAnnouncerOf(harness, ctx));
677
+ const handler = harness.config.onHeld;
678
+ if (!signal || !handler) {
679
+ return;
680
+ }
681
+ void askHandler({
682
+ harness,
683
+ handler,
684
+ held,
685
+ signal,
686
+ executionId,
687
+ threadId: harness.heldThreadOf?.(ctx),
688
+ });
689
+ }
690
+ /** Put a held call to the host's handler and take its answer as a decision. */
691
+ async function askHandler(opts) {
692
+ const { harness, held, signal, executionId, threadId } = opts;
693
+ let answer;
694
+ try {
695
+ answer = await opts.handler(held, {
696
+ signal,
697
+ executionId,
698
+ ...(threadId === undefined
699
+ ? {}
700
+ : {
701
+ threadId,
702
+ }),
703
+ });
704
+ }
705
+ catch (e) {
706
+ console.warn(`[noetic] ${harness.config.name}: the onHeld handler failed for '${held.name}' (${held.callId}); the call stays held: ${messageOf(e)}`);
707
+ return;
708
+ }
709
+ // Settled some other way first: there is nothing left to answer.
710
+ if (answer === undefined || signal.aborted) {
711
+ return;
712
+ }
713
+ try {
714
+ if (harness.answerHeld) {
715
+ await harness.answerHeld({
716
+ executionId,
717
+ ...(threadId === undefined
718
+ ? {}
719
+ : {
720
+ threadId,
721
+ }),
722
+ callId: held.callId,
723
+ argsHash: held.argsHash,
724
+ resolution: answer,
725
+ });
726
+ return;
727
+ }
728
+ await heldCallsOf(harness).resolve(executionId, {
729
+ callId: held.callId,
730
+ argsHash: held.argsHash,
731
+ resolution: answer,
732
+ });
733
+ }
734
+ catch (e) {
735
+ if (signal.aborted) {
736
+ return;
737
+ }
738
+ console.warn(`[noetic] ${harness.config.name}: the onHeld answer for '${held.name}' (${held.callId}) was refused; the call stays held: ${messageOf(e)}`);
739
+ }
740
+ }
741
+ function messageOf(e) {
742
+ return e instanceof Error ? e.message : String(e);
743
+ }
492
744
  /** True once a hold with a `deny` deadline has run out. */
493
745
  export function isOverdue(record, now) {
494
746
  return record.dueAt !== undefined && record.onDue !== 'keep' && record.dueAt <= now;
@@ -23,6 +23,8 @@ export declare class OutputStoreError extends Error {
23
23
  cause: unknown;
24
24
  });
25
25
  }
26
+ /** @internal The prefix every thread's display output key starts with. */
27
+ export declare const OUTPUT_PREFIX = "output:";
26
28
  /** @internal The storage key a thread's display output is kept under. */
27
29
  export declare function outputKey(scope: string): string;
28
30
  /**
@@ -29,9 +29,11 @@ const WRITE_ATTEMPTS = 3;
29
29
  /** How many times a write may lose to another writer before it is a failure. */
30
30
  const SWAP_ATTEMPTS = 20;
31
31
  const WRITE_RETRY_MS = 10;
32
+ /** @internal The prefix every thread's display output key starts with. */
33
+ export const OUTPUT_PREFIX = 'output:';
32
34
  /** @internal The storage key a thread's display output is kept under. */
33
35
  export function outputKey(scope) {
34
- return `output:${scope}`;
36
+ return `${OUTPUT_PREFIX}${scope}`;
35
37
  }
36
38
  /** What makes two snapshots the same item: its id, else its call, else its content. */
37
39
  function keyOf(item) {
@@ -1,4 +1,4 @@
1
- import type { Context, HarnessResponse, HarnessStatus, HeldCall, Item, SessionUsage } from '@noetic-tools/types';
1
+ import type { Context, HarnessResponse, HarnessStatus, HeldCall, Item, SessionUsage, TurnCut } from '@noetic-tools/types';
2
2
  import { EventBroadcaster } from './event-broadcaster.js';
3
3
  import type { QueuedMessage } from './message-queue.js';
4
4
  import { MessageQueue } from './message-queue.js';
@@ -38,6 +38,8 @@ export interface SessionRunnerOpts {
38
38
  readonly onTurnUsage?: (usage: TurnUsage) => Promise<void>;
39
39
  /** The tool calls the turn on `ctx` holds for a person, for a parked response. */
40
40
  readonly heldCalls?: (ctx: Context) => Promise<ReadonlyArray<HeldCall>>;
41
+ /** The cut the turn on `ctx` ended with, when it was cut rather than failed (spec 23 § Cut turns). */
42
+ readonly cutOf?: (ctx: Context) => TurnCut | undefined;
41
43
  }
42
44
  /**
43
45
  * @internal
@@ -73,6 +75,7 @@ export declare class SessionRunner {
73
75
  private totalBilledCost;
74
76
  private readonly onTurnUsage?;
75
77
  private readonly heldCalls?;
78
+ private readonly cutOf?;
76
79
  private currentController?;
77
80
  private currentCtx?;
78
81
  private loopPromise?;
@@ -123,6 +126,11 @@ export declare class SessionRunner {
123
126
  * hears it settled — so `getUsage()` after `getAgentResponse()` includes it.
124
127
  */
125
128
  private settleUsage;
129
+ /**
130
+ * The turn was cut: it has not ended, and a later wake runs it again. Its response
131
+ * says so, with the items so far, and `turn_cut` stands in for `turn_aborted`.
132
+ */
133
+ private answerCut;
126
134
  /** A turn whose context could not be built: report it like any other failed turn. */
127
135
  private failBeforeStart;
128
136
  private resolveWaiters;
@@ -50,6 +50,7 @@ export class SessionRunner {
50
50
  totalBilledCost = 0;
51
51
  onTurnUsage;
52
52
  heldCalls;
53
+ cutOf;
53
54
  currentController;
54
55
  currentCtx;
55
56
  loopPromise;
@@ -65,6 +66,7 @@ export class SessionRunner {
65
66
  this.createContext = opts.createContext;
66
67
  this.onTurnUsage = opts.onTurnUsage;
67
68
  this.heldCalls = opts.heldCalls;
69
+ this.cutOf = opts.cutOf;
68
70
  this.queue.subscribe(() => {
69
71
  this.kick();
70
72
  });
@@ -281,6 +283,11 @@ export class SessionRunner {
281
283
  try {
282
284
  const text = await this.runTurn(ctx, turn, controller.signal);
283
285
  await this.settleUsage(start, ctx);
286
+ const cut = this.cutOf?.(ctx);
287
+ if (cut) {
288
+ this.answerCut(turnId, startedAt, ctx, cut);
289
+ return;
290
+ }
284
291
  const wakeAt = parkedUntilOf(ctx);
285
292
  const held = wakeAt === undefined ? [] : ((await this.heldCalls?.(ctx)) ?? []);
286
293
  const response = wakeAt === undefined
@@ -372,6 +379,33 @@ export class SessionRunner {
372
379
  this.totalBilledCost += spent.billedCost;
373
380
  await this.onTurnUsage?.(spent);
374
381
  }
382
+ /**
383
+ * The turn was cut: it has not ended, and a later wake runs it again. Its response
384
+ * says so, with the items so far, and `turn_cut` stands in for `turn_aborted`.
385
+ */
386
+ answerCut(turnId, startedAt, ctx, cut) {
387
+ const response = {
388
+ ...buildResponse('', ctx),
389
+ cut,
390
+ };
391
+ this.lastResponse = response;
392
+ this.lastError = undefined;
393
+ emitFrameworkEvent({
394
+ broadcaster: this.broadcaster,
395
+ agentName: this.agentName,
396
+ eventType: 'turn_cut',
397
+ data: {
398
+ turnId,
399
+ durationMs: Date.now() - startedAt,
400
+ reason: cut.reason,
401
+ attempt: cut.attempt,
402
+ wakeAt: cut.wakeAt,
403
+ },
404
+ });
405
+ if (this.queue.size === 0) {
406
+ this.resolveWaiters(response);
407
+ }
408
+ }
375
409
  /** A turn whose context could not be built: report it like any other failed turn. */
376
410
  failBeforeStart(turnId, err) {
377
411
  const error = err instanceof Error ? err : new Error(String(err));
@@ -1,4 +1,4 @@
1
- import type { Context, HeldCall, SteeringDecision } from '@noetic-tools/types';
1
+ import type { Context, SteeringDecision } from '@noetic-tools/types';
2
2
  import type { HoldHost } from './held-calls.js';
3
3
  /** How the approval stage settled a call, as recorded on its `tool.call` span. */
4
4
  export declare const ApprovalOutcome: {
@@ -58,8 +58,6 @@ export declare function awaitApproval(params: {
58
58
  */
59
59
  recordId?: string;
60
60
  ctx: Context;
61
- /** Called once, when the call is first held. */
62
- onHeld?: (held: HeldCall) => void;
63
61
  /** False when the turn must stay live while the call is held. Default true. */
64
62
  park?: boolean;
65
63
  }): Promise<ToolApproval>;
@@ -173,7 +173,7 @@ export async function awaitApproval(params) {
173
173
  });
174
174
  if (!announced) {
175
175
  announced = true;
176
- (params.onHeld ?? announcerOf(params.harness, params.ctx))(toHeldCall(record));
176
+ announcerOf(params.harness, params.ctx)(toHeldCall(record));
177
177
  }
178
178
  await waitOnHeldCalls({
179
179
  harness: params.harness,