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

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 (83) hide show
  1. package/dist/builders/tool-builder.d.ts +20 -0
  2. package/dist/builders/tool-builder.js +23 -1
  3. package/dist/builders/workflow-hydrator.d.ts +19 -0
  4. package/dist/builders/workflow-hydrator.js +19 -0
  5. package/dist/builders/workflow-step.js +7 -1
  6. package/dist/connections/cron-schedule.js +12 -3
  7. package/dist/connections/durability.d.ts +1 -2
  8. package/dist/connections/durability.js +1 -4
  9. package/dist/connections/gates.js +6 -2
  10. package/dist/connections/harness-wiring.d.ts +5 -0
  11. package/dist/connections/harness-wiring.js +76 -10
  12. package/dist/connections/in-memory-connection.d.ts +4 -0
  13. package/dist/connections/in-memory-connection.js +10 -0
  14. package/dist/connections/model-tools.js +5 -1
  15. package/dist/connections/registry.d.ts +6 -2
  16. package/dist/connections/registry.js +10 -0
  17. package/dist/connections/sources.js +261 -20
  18. package/dist/connections/triggers.d.ts +62 -2
  19. package/dist/connections/triggers.js +375 -35
  20. package/dist/harness/agent-harness.d.ts +263 -4
  21. package/dist/harness/agent-harness.js +1156 -95
  22. package/dist/harness/connection-gate.d.ts +3 -0
  23. package/dist/harness/connection-gate.js +4 -0
  24. package/dist/harness/deps/runtime.d.ts +3 -0
  25. package/dist/harness/deps/runtime.js +2 -0
  26. package/dist/harness/flow-version.d.ts +13 -0
  27. package/dist/harness/flow-version.js +66 -0
  28. package/dist/harness/harness-options.d.ts +82 -0
  29. package/dist/harness/model-call.js +8 -0
  30. package/dist/harness/model-rounds.d.ts +30 -0
  31. package/dist/harness/model-rounds.js +146 -1
  32. package/dist/harness/model-tool-round.d.ts +3 -0
  33. package/dist/harness/model-tool-round.js +201 -19
  34. package/dist/harness/park-watchers.d.ts +93 -0
  35. package/dist/harness/park-watchers.js +217 -0
  36. package/dist/harness/read-decision.d.ts +23 -0
  37. package/dist/harness/read-decision.js +100 -0
  38. package/dist/harness/spend.js +4 -0
  39. package/dist/harness/steer-inbox.js +3 -1
  40. package/dist/harness/thread-record.d.ts +77 -1
  41. package/dist/harness/thread-record.js +272 -13
  42. package/dist/index.d.ts +17 -7
  43. package/dist/index.js +10 -2
  44. package/dist/interpreter/acp-resume.d.ts +77 -0
  45. package/dist/interpreter/acp-resume.js +164 -0
  46. package/dist/interpreter/acp-tools.d.ts +11 -0
  47. package/dist/interpreter/acp-tools.js +94 -7
  48. package/dist/interpreter/connection-steps.d.ts +24 -1
  49. package/dist/interpreter/connection-steps.js +77 -2
  50. package/dist/interpreter/execute-acp-agent.js +111 -15
  51. package/dist/interpreter/execute-action.js +7 -0
  52. package/dist/interpreter/execute-call.js +30 -4
  53. package/dist/interpreter/execute-control.js +21 -0
  54. package/dist/interpreter/execute-invoke-tool.js +149 -5
  55. package/dist/interpreter/execute-wait.js +67 -9
  56. package/dist/interpreter/execute.js +4 -0
  57. package/dist/interpreter/turn-ending.d.ts +15 -0
  58. package/dist/interpreter/turn-ending.js +46 -0
  59. package/dist/portable/builders.d.ts +1 -1
  60. package/dist/portable/builders.js +1 -1
  61. package/dist/runtime/durable/parking.d.ts +61 -0
  62. package/dist/runtime/durable/parking.js +137 -0
  63. package/dist/runtime/durable/session-store.d.ts +38 -0
  64. package/dist/runtime/durable/session-store.js +79 -1
  65. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  66. package/dist/runtime/durable/step-ledger.js +352 -15
  67. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  68. package/dist/runtime/durable/turn-lease.js +307 -0
  69. package/dist/runtime/held-calls.d.ts +192 -0
  70. package/dist/runtime/held-calls.js +496 -0
  71. package/dist/runtime/in-memory-storage.d.ts +10 -1
  72. package/dist/runtime/in-memory-storage.js +20 -2
  73. package/dist/runtime/message-queue.d.ts +2 -0
  74. package/dist/runtime/message-queue.js +8 -0
  75. package/dist/runtime/session-runner.d.ts +18 -2
  76. package/dist/runtime/session-runner.js +88 -3
  77. package/dist/runtime/tool-approval.d.ts +46 -6
  78. package/dist/runtime/tool-approval.js +160 -38
  79. package/dist/runtime/tool-call.d.ts +34 -2
  80. package/dist/runtime/tool-call.js +182 -13
  81. package/dist/runtime/tool-context.d.ts +15 -1
  82. package/dist/runtime/tool-context.js +38 -2
  83. package/package.json +3 -3
@@ -0,0 +1,496 @@
1
+ /**
2
+ * Held tool calls: a call left open for a person (spec 08 § Held tool calls).
3
+ *
4
+ * A call is held when the approver answers `hold`, when a tool that needs
5
+ * approval has no approver, or when a tool returns `hold()` in place of a
6
+ * result. Nothing is written to the conversation for it. Its record sits in
7
+ * storage until a decision passed to `harness.execute()` settles it; then the round walks its calls
8
+ * again, and this time the call has an answer.
9
+ *
10
+ * The record is the whole state, so a held call survives the process: a parked
11
+ * turn resumed on another harness finds the same record and the same answer.
12
+ */
13
+ import { NoeticErrorImpl } from '@noetic-tools/types';
14
+ import { z } from 'zod';
15
+ import { emitFrameworkEvent, getBroadcaster } from './broadcaster-utils.js';
16
+ import { ContextImpl, rootIdOf } from './context-impl.js';
17
+ import { hashStepInput } from './durable/step-ledger.js';
18
+ import { createInMemoryStorage } from './in-memory-storage.js';
19
+ //#region Types
20
+ const ResolutionSchema = z.object({
21
+ /** An approval's answer. */
22
+ action: z
23
+ .enum([
24
+ 'allow',
25
+ 'deny',
26
+ 'guide',
27
+ ])
28
+ .optional(),
29
+ guidance: z.string().optional(),
30
+ /** A held result's value. Present, even as `null`, when `hasOutput` is set. */
31
+ output: z.unknown().optional(),
32
+ hasOutput: z.boolean().optional(),
33
+ });
34
+ const HeldRecordSchema = z.object({
35
+ callId: z.string(),
36
+ name: z.string(),
37
+ args: z.unknown(),
38
+ /** Hash of the call's name and arguments: an answer is for this call and no other. */
39
+ argsHash: z.string(),
40
+ /** Why the call is held: see `HeldCall.reason`. */
41
+ reason: z.enum([
42
+ 'approval',
43
+ 'result',
44
+ 'outcome',
45
+ ]),
46
+ dueAt: z.number().optional(),
47
+ onDue: z
48
+ .enum([
49
+ 'deny',
50
+ 'keep',
51
+ ])
52
+ .optional(),
53
+ /** Passed back by a tool's `hold()`, for whoever answers. */
54
+ request: z.unknown().optional(),
55
+ resolution: ResolutionSchema.optional(),
56
+ });
57
+ /**
58
+ * @internal
59
+ * Thrown by an approval seam to say "hold this call". Caught where the call's
60
+ * record can be written; never reaches a caller of the harness.
61
+ */
62
+ export class HoldSignal extends Error {
63
+ due;
64
+ constructor(due = {}) {
65
+ super('The tool call is held for a person.');
66
+ this.due = due;
67
+ this.name = 'HoldSignal';
68
+ }
69
+ }
70
+ //#endregion
71
+ //#region Helpers
72
+ /** The hash that ties an answer to one call: its tool name and arguments. */
73
+ export function heldArgsHash(name, args) {
74
+ return (hashStepInput({
75
+ name,
76
+ args,
77
+ }) ?? '');
78
+ }
79
+ const IntentSchema = z.object({
80
+ argsHash: z.string(),
81
+ });
82
+ function intentPrefix(executionId) {
83
+ return `execution:${executionId}:intent:`;
84
+ }
85
+ /** How often a live turn re-reads held calls that another process may have answered. */
86
+ const HELD_POLL_MS = 2e3;
87
+ function heldPrefix(executionId) {
88
+ return `execution:${executionId}:held:`;
89
+ }
90
+ function refused(callId, reason) {
91
+ return new NoeticErrorImpl({
92
+ kind: 'hold_refused',
93
+ callId,
94
+ reason,
95
+ });
96
+ }
97
+ function sameResolution(a, b) {
98
+ return JSON.stringify(a) === JSON.stringify(b);
99
+ }
100
+ function toResolutionRecord(resolution) {
101
+ if ('action' in resolution) {
102
+ return {
103
+ action: resolution.action,
104
+ ...(resolution.guidance === undefined
105
+ ? {}
106
+ : {
107
+ guidance: resolution.guidance,
108
+ }),
109
+ };
110
+ }
111
+ return {
112
+ output: resolution.output,
113
+ hasOutput: true,
114
+ };
115
+ }
116
+ /** A held record as hosts see it. */
117
+ export function toHeldCall(record) {
118
+ return {
119
+ callId: record.callId,
120
+ name: record.name,
121
+ args: record.args,
122
+ argsHash: record.argsHash,
123
+ reason: record.reason,
124
+ ...(record.dueAt === undefined
125
+ ? {}
126
+ : {
127
+ dueAt: record.dueAt,
128
+ }),
129
+ ...(record.onDue === undefined
130
+ ? {}
131
+ : {
132
+ onDue: record.onDue,
133
+ }),
134
+ ...(record.request === undefined
135
+ ? {}
136
+ : {
137
+ request: record.request,
138
+ }),
139
+ };
140
+ }
141
+ //#endregion
142
+ //#region HeldCalls
143
+ /** @internal One harness's held calls: their records, and who is waiting on them here. */
144
+ export class HeldCalls {
145
+ storage;
146
+ clock;
147
+ waiters = new Map();
148
+ constructor(storage, clock) {
149
+ this.storage = storage;
150
+ this.clock = clock;
151
+ }
152
+ now() {
153
+ return this.clock();
154
+ }
155
+ /** The record of `callId`, when the call is held. */
156
+ async load(executionId, callId) {
157
+ const raw = await this.storage.get(`${heldPrefix(executionId)}${callId}`);
158
+ const parsed = raw === null ? undefined : HeldRecordSchema.safeParse(raw);
159
+ return parsed?.success ? parsed.data : undefined;
160
+ }
161
+ /** Answers being taken, by execution and call, so two never overlap. */
162
+ answering = new Map();
163
+ /** Every held call of an execution. */
164
+ async list(executionId) {
165
+ const found = [];
166
+ for (const key of await this.storage.list(heldPrefix(executionId))) {
167
+ const parsed = HeldRecordSchema.safeParse(await this.storage.get(key));
168
+ if (parsed.success) {
169
+ found.push(parsed.data);
170
+ }
171
+ }
172
+ return found;
173
+ }
174
+ /**
175
+ * Hold a call. A call already held for the same thing keeps its record, and with
176
+ * it any answer. A record held for another reason is an earlier stage of the call
177
+ * (its approval, since given) and is replaced: a call is held for one thing at a
178
+ * time, and an old answer must not pass for the new question.
179
+ */
180
+ async open(executionId, record) {
181
+ const existing = await this.load(executionId, record.callId);
182
+ const same = existing !== undefined &&
183
+ existing.argsHash === record.argsHash &&
184
+ existing.reason === record.reason;
185
+ if (same) {
186
+ return existing;
187
+ }
188
+ await this.storage.set(`${heldPrefix(executionId)}${record.callId}`, record);
189
+ return record;
190
+ }
191
+ /** Drop every held call and intent of an execution that is over or was abandoned. */
192
+ async clear(executionId) {
193
+ for (const prefix of [
194
+ heldPrefix(executionId),
195
+ intentPrefix(executionId),
196
+ ]) {
197
+ for (const key of await this.storage.list(prefix)) {
198
+ await this.storage.delete(key);
199
+ }
200
+ }
201
+ }
202
+ /**
203
+ * Note that a `durable` tool call is about to run. Written before the tool does
204
+ * anything, so a resumed run that finds it knows the call had started.
205
+ */
206
+ async arm(executionId, callId, argsHash) {
207
+ await this.storage.set(`${intentPrefix(executionId)}${callId}`, {
208
+ argsHash,
209
+ });
210
+ }
211
+ /** True when a call with these arguments was started and never finished. */
212
+ async wasStarted(executionId, callId, argsHash) {
213
+ const raw = await this.storage.get(`${intentPrefix(executionId)}${callId}`);
214
+ const parsed = IntentSchema.safeParse(raw);
215
+ return parsed.success && parsed.data.argsHash === argsHash;
216
+ }
217
+ /** The call finished and its result is on record. */
218
+ async disarm(executionId, callId) {
219
+ await this.storage.delete(`${intentPrefix(executionId)}${callId}`);
220
+ }
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}`);
224
+ }
225
+ /**
226
+ * Answer a held call. The first answer wins: the same answer again is a no-op, a
227
+ * different one is refused.
228
+ *
229
+ * @throws NoeticError `hold_refused` when the call is not held, `argsHash` names a
230
+ * different call, the answer is the wrong kind for the hold, or another answer
231
+ * already landed.
232
+ */
233
+ resolve(executionId, answer) {
234
+ // One answer at a time per call. Storage with `swap` settles a race between
235
+ // processes; without it nothing else stops two answers here from both landing.
236
+ const key = `${executionId}\u0000${answer.callId}`;
237
+ const turn = (this.answering.get(key) ?? Promise.resolve())
238
+ .catch(() => undefined)
239
+ .then(() => this.resolveOne(executionId, answer));
240
+ this.answering.set(key, turn);
241
+ const forget = () => {
242
+ if (this.answering.get(key) === turn) {
243
+ this.answering.delete(key);
244
+ }
245
+ };
246
+ turn.then(forget, forget);
247
+ return turn;
248
+ }
249
+ async resolveOne(executionId, answer) {
250
+ const { callId } = answer;
251
+ const record = await this.load(executionId, callId);
252
+ if (!record) {
253
+ throw refused(callId, 'no call with this id is held');
254
+ }
255
+ if (answer.argsHash !== undefined && answer.argsHash !== record.argsHash) {
256
+ throw refused(callId, 'the answer is for a call with different arguments');
257
+ }
258
+ const resolution = toResolutionRecord(answer.resolution);
259
+ // An unknown outcome takes either answer: "it landed, here is the result", or
260
+ // a decision on whether to run it again.
261
+ const wrongKind = record.reason !== 'outcome' &&
262
+ (record.reason === 'result') !== (resolution.hasOutput === true);
263
+ if (wrongKind) {
264
+ throw refused(callId, record.reason === 'result'
265
+ ? 'the call waits for a result, not an approval'
266
+ : 'the call waits for an approval, not a result');
267
+ }
268
+ if (record.resolution) {
269
+ if (sameResolution(record.resolution, resolution)) {
270
+ return;
271
+ }
272
+ throw refused(callId, 'the call was already answered differently');
273
+ }
274
+ const next = {
275
+ ...record,
276
+ resolution,
277
+ };
278
+ const key = `${heldPrefix(executionId)}${callId}`;
279
+ // With compare-and-set, two answers racing from two processes cannot both land.
280
+ const landed = this.storage.swap ? await this.storage.swap(key, record, next) : true;
281
+ if (!this.storage.swap) {
282
+ await this.storage.set(key, next);
283
+ }
284
+ if (!landed) {
285
+ const now = await this.load(executionId, callId);
286
+ if (now?.resolution && sameResolution(now.resolution, resolution)) {
287
+ return;
288
+ }
289
+ throw refused(callId, 'the call was already answered differently');
290
+ }
291
+ this.notify(executionId);
292
+ }
293
+ /** True when other processes may share this storage, and so may answer a call. */
294
+ get shared() {
295
+ return this.storage.swap !== undefined;
296
+ }
297
+ /**
298
+ * Start listening for a change to the execution's held calls. Listening begins
299
+ * when this returns, so an answer that lands while the caller is still reading
300
+ * the records is not missed. `changed` resolves on the first change or when
301
+ * `signal` aborts; call `stop` when done either way.
302
+ */
303
+ listen(executionId, signal) {
304
+ const waiters = this.waiters.get(executionId) ?? new Set();
305
+ this.waiters.set(executionId, waiters);
306
+ let wake = () => { };
307
+ const changed = new Promise((resolve) => {
308
+ wake = resolve;
309
+ });
310
+ const stop = () => {
311
+ waiters.delete(wake);
312
+ signal.removeEventListener('abort', wake);
313
+ };
314
+ waiters.add(wake);
315
+ signal.addEventListener('abort', wake, {
316
+ once: true,
317
+ });
318
+ if (signal.aborted) {
319
+ wake();
320
+ }
321
+ return {
322
+ changed,
323
+ stop,
324
+ };
325
+ }
326
+ /** Wake whoever in this process waits on the execution's held calls. */
327
+ notify(executionId) {
328
+ for (const wake of [
329
+ ...(this.waiters.get(executionId) ?? []),
330
+ ]) {
331
+ wake();
332
+ }
333
+ }
334
+ }
335
+ const stores = new WeakMap();
336
+ /** @internal The held calls of `harness`, over its storage and clock. */
337
+ export function heldCallsOf(harness) {
338
+ const existing = stores.get(harness);
339
+ if (existing) {
340
+ return existing;
341
+ }
342
+ const created = new HeldCalls(harness.config.storage ?? createInMemoryStorage(), () => harness.config.now?.() ?? Date.now());
343
+ stores.set(harness, created);
344
+ return created;
345
+ }
346
+ /** @internal The execution a context's held calls are kept under: its root. */
347
+ export function heldScopeOf(ctx) {
348
+ return rootIdOf(ctx);
349
+ }
350
+ /**
351
+ * @internal
352
+ * Wait until something about these held calls may have changed: an answer arrived,
353
+ * or a hold's deadline passed. While it waits the step is only waiting, so the
354
+ * turn may park (spec 23 § Parked turns).
355
+ *
356
+ * @throws NoeticError `cancelled` when the context is aborted, which is also how a
357
+ * parked turn leaves here.
358
+ */
359
+ export async function waitOnHeldCalls(opts) {
360
+ const { ctx } = opts;
361
+ const holds = heldCallsOf(opts.harness);
362
+ const executionId = heldScopeOf(ctx);
363
+ const impl = ctx instanceof ContextImpl ? ctx : undefined;
364
+ const signals = [
365
+ impl?.abortSignal,
366
+ opts.signal,
367
+ ].filter((given) => given !== undefined);
368
+ const signal = signals.length === 0
369
+ ? new AbortController().signal
370
+ : signals.length === 1 && signals[0]
371
+ ? signals[0]
372
+ : AbortSignal.any(signals);
373
+ // Listen before reading: an answer that lands in between must still wake this.
374
+ const listening = holds.listen(executionId, signal);
375
+ let stopWaiting;
376
+ let timer;
377
+ try {
378
+ let earliest = Number.POSITIVE_INFINITY;
379
+ for (const callId of opts.callIds) {
380
+ const record = await holds.load(executionId, callId);
381
+ if (!record || record.resolution) {
382
+ return;
383
+ }
384
+ if (record.dueAt !== undefined && record.onDue !== 'keep') {
385
+ earliest = Math.min(earliest, record.dueAt);
386
+ }
387
+ }
388
+ stopWaiting =
389
+ opts.park === false
390
+ ? undefined
391
+ : impl?.ledger?.parking.wait(impl.currentDispatch()?.path, earliest);
392
+ // Another process answering cannot wake this one, so shared storage is read again
393
+ // every so often. A deadline wakes it too.
394
+ const untilDue = earliest - holds.now();
395
+ const wakeIn = Math.min(untilDue, holds.shared ? HELD_POLL_MS : Number.POSITIVE_INFINITY);
396
+ await Promise.race([
397
+ listening.changed,
398
+ new Promise((resolve) => {
399
+ if (Number.isFinite(wakeIn)) {
400
+ timer = setTimeout(resolve, Math.max(0, wakeIn));
401
+ }
402
+ }),
403
+ ]);
404
+ }
405
+ finally {
406
+ clearTimeout(timer);
407
+ stopWaiting?.();
408
+ listening.stop();
409
+ }
410
+ if (signal.aborted) {
411
+ throw new NoeticErrorImpl({
412
+ kind: 'cancelled',
413
+ reason: ctx.abortReason ?? 'context aborted',
414
+ });
415
+ }
416
+ }
417
+ /**
418
+ * @internal
419
+ * False once the context's execution writes under a lease it no longer holds: a
420
+ * harness that was replaced must not open, close or disarm the new holder's calls
421
+ * (spec 23 § One writer per turn). An answer (`resolve`) is not a turn's write and
422
+ * is not fenced; it is a compare-and-set any harness may make.
423
+ */
424
+ export function mayWriteHolds(ctx) {
425
+ let node = ctx;
426
+ while (node.parent) {
427
+ node = node.parent;
428
+ }
429
+ for (const candidate of [
430
+ ctx,
431
+ node,
432
+ ]) {
433
+ if (candidate instanceof ContextImpl && candidate.ledger) {
434
+ return candidate.ledger.isHeld;
435
+ }
436
+ }
437
+ return true;
438
+ }
439
+ /**
440
+ * @internal
441
+ * Hold a call from a caller with no model round to come back to (a step), and wait
442
+ * for its answer. While it waits the step is only waiting, so the turn may park; a
443
+ * resumed step calls this again and finds the same record, and its answer.
444
+ *
445
+ * @throws NoeticError `cancelled` when the context is aborted while it waits.
446
+ */
447
+ export async function holdAndWait(opts) {
448
+ const holds = heldCallsOf(opts.harness);
449
+ const executionId = heldScopeOf(opts.ctx);
450
+ const { callId } = opts.record;
451
+ const opened = mayWriteHolds(opts.ctx) ? await holds.open(executionId, opts.record) : opts.record;
452
+ if (opened.resolution === undefined) {
453
+ (opts.onHeld ?? announcerOf(opts.harness, opts.ctx))(toHeldCall(opened));
454
+ }
455
+ for (;;) {
456
+ const current = await holds.load(executionId, callId);
457
+ const settled = current?.resolution !== undefined;
458
+ if (!current || settled || isOverdue(current, holds.now())) {
459
+ if (mayWriteHolds(opts.ctx)) {
460
+ await holds.close(executionId, callId);
461
+ }
462
+ return {
463
+ resolution: current?.resolution,
464
+ };
465
+ }
466
+ await waitOnHeldCalls({
467
+ harness: opts.harness,
468
+ ctx: opts.ctx,
469
+ callIds: [
470
+ callId,
471
+ ],
472
+ });
473
+ }
474
+ }
475
+ /**
476
+ * @internal
477
+ * 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`.
479
+ */
480
+ export function announcerOf(harness, ctx) {
481
+ return (held) => {
482
+ emitFrameworkEvent({
483
+ broadcaster: getBroadcaster(ctx),
484
+ agentName: harness.config.name,
485
+ eventType: 'tool_call_held',
486
+ data: {
487
+ ...held,
488
+ },
489
+ });
490
+ };
491
+ }
492
+ /** True once a hold with a `deny` deadline has run out. */
493
+ export function isOverdue(record, now) {
494
+ return record.dueAt !== undefined && record.onDue !== 'keep' && record.dueAt <= now;
495
+ }
496
+ //#endregion
@@ -1,4 +1,13 @@
1
1
  import type { StorageAdapter } from '@noetic-tools/context';
2
+ /** @public Options for `createInMemoryStorage`. */
3
+ export interface CreateInMemoryStorageOptions {
4
+ /**
5
+ * Implement `swap`, so harnesses sharing this storage take turn leases (spec 23
6
+ * § One writer per turn). Off by default: the Map lives in one process, where a
7
+ * lease only matters to a test that puts two harnesses on one storage.
8
+ */
9
+ swap?: boolean;
10
+ }
2
11
  /**
3
12
  * @public Process-local, Map-backed StorageAdapter.
4
13
  *
@@ -6,4 +15,4 @@ import type { StorageAdapter } from '@noetic-tools/context';
6
15
  * for the lifetime of the Map (i.e., this harness instance). Durable backends
7
16
  * must be supplied explicitly by the caller.
8
17
  */
9
- export declare function createInMemoryStorage(): StorageAdapter;
18
+ export declare function createInMemoryStorage(options?: CreateInMemoryStorageOptions): StorageAdapter;
@@ -1,5 +1,4 @@
1
1
  import { frameworkCast } from '@noetic-tools/types';
2
- //#region Public API
3
2
  /**
4
3
  * @public Process-local, Map-backed StorageAdapter.
5
4
  *
@@ -7,8 +6,27 @@ import { frameworkCast } from '@noetic-tools/types';
7
6
  * for the lifetime of the Map (i.e., this harness instance). Durable backends
8
7
  * must be supplied explicitly by the caller.
9
8
  */
10
- export function createInMemoryStorage() {
9
+ export function createInMemoryStorage(options) {
11
10
  const store = new Map();
11
+ const base = inMemoryAdapter(store);
12
+ if (!options?.swap) {
13
+ return base;
14
+ }
15
+ return {
16
+ ...base,
17
+ // Single-threaded: nothing runs between the compare and the write.
18
+ async swap(key, prev, next) {
19
+ const stored = store.get(key);
20
+ const matches = prev === null ? stored === undefined : JSON.stringify(stored) === JSON.stringify(prev);
21
+ if (!matches) {
22
+ return false;
23
+ }
24
+ store.set(key, next);
25
+ return true;
26
+ },
27
+ };
28
+ }
29
+ function inMemoryAdapter(store) {
12
30
  return {
13
31
  async get(key) {
14
32
  const val = store.get(key);
@@ -32,6 +32,8 @@ export declare class MessageQueue {
32
32
  private readonly items;
33
33
  private readonly listeners;
34
34
  enqueue(message: QueuedMessage): void;
35
+ /** Queue several messages as one arrival, so a listener sees them all at once. */
36
+ enqueueAll(messages: ReadonlyArray<QueuedMessage>): void;
35
37
  prepend(message: QueuedMessage): void;
36
38
  drainAll(): QueuedMessage[];
37
39
  /** Remove and return the messages `match` accepts, keeping the rest in order. */
@@ -49,6 +49,14 @@ export class MessageQueue {
49
49
  this.items.push(message);
50
50
  this.notify();
51
51
  }
52
+ /** Queue several messages as one arrival, so a listener sees them all at once. */
53
+ enqueueAll(messages) {
54
+ if (messages.length === 0) {
55
+ return;
56
+ }
57
+ this.items.push(...messages);
58
+ this.notify();
59
+ }
52
60
  prepend(message) {
53
61
  this.items.unshift(message);
54
62
  this.notify();
@@ -1,4 +1,4 @@
1
- import type { Context, HarnessResponse, HarnessStatus, Item, SessionUsage } from '@noetic-tools/types';
1
+ import type { Context, HarnessResponse, HarnessStatus, HeldCall, Item, SessionUsage } 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';
@@ -17,7 +17,7 @@ export interface TurnContext {
17
17
  * plus the messages being delivered this turn so the harness can honour
18
18
  * per-turn `ExecuteOptions` (the first message's options establish
19
19
  * resourceId/state/context for the turn). */
20
- export type CreateContextFn = (items: ReadonlyArray<Item>, turnId: string, messages: ReadonlyArray<QueuedMessage>) => Context | Promise<Context>;
20
+ export type CreateContextFn = (items: ReadonlyArray<Item>, turnId: string, messages: ReadonlyArray<QueuedMessage>) => Context | undefined | Promise<Context | undefined>;
21
21
  /** @internal What one turn spent: its context's usage at the end, less at the start. */
22
22
  export interface TurnUsage {
23
23
  inputTokens: number;
@@ -36,6 +36,8 @@ export interface SessionRunnerOpts {
36
36
  * writes it to storage and hands the stored totals back through `seedUsage`.
37
37
  */
38
38
  readonly onTurnUsage?: (usage: TurnUsage) => Promise<void>;
39
+ /** The tool calls the turn on `ctx` holds for a person, for a parked response. */
40
+ readonly heldCalls?: (ctx: Context) => Promise<ReadonlyArray<HeldCall>>;
39
41
  }
40
42
  /**
41
43
  * @internal
@@ -70,9 +72,12 @@ export declare class SessionRunner {
70
72
  private totalCost;
71
73
  private totalBilledCost;
72
74
  private readonly onTurnUsage?;
75
+ private readonly heldCalls?;
73
76
  private currentController?;
74
77
  private currentCtx?;
75
78
  private loopPromise?;
79
+ /** The message ids of the turn being started or run, set before anything is awaited. */
80
+ private currentIds;
76
81
  private lastResponse?;
77
82
  private lastError?;
78
83
  private readonly responseWaiters;
@@ -83,6 +88,10 @@ export declare class SessionRunner {
83
88
  /** Queue a message. A steer that arrives mid-turn is announced first, so
84
89
  * `steer_accepted` always precedes the `inbox_injected` that applies it. */
85
90
  enqueue(message: QueuedMessage): void;
91
+ /** True while the turn being started or run took the message with this id. */
92
+ isRunning(messageId: string): boolean;
93
+ /** Resolves once the queue loop has gone idle: no turn running or closing out. */
94
+ whenIdle(): Promise<void>;
86
95
  /** Cumulative token usage and cost across all turns this session has run. */
87
96
  getUsage(): SessionUsage;
88
97
  /** Replace the totals with ones a durable host read back from storage. */
@@ -95,6 +104,13 @@ export declare class SessionRunner {
95
104
  * queued, the caller is asking about the NEXT response — we must wait
96
105
  * for that turn rather than reject with the stale error. */
97
106
  getAgentResponse(): Promise<HarnessResponse>;
107
+ /**
108
+ * Answer whoever is waiting with a response no turn of this runner produced: the
109
+ * recorded answer to a message that was delivered again.
110
+ */
111
+ answerWith(response: HarnessResponse, messageId: string): void;
112
+ /** The abort signal of the turn in flight, from before its context is built. */
113
+ get signal(): AbortSignal | undefined;
98
114
  /** Cancel the in-flight turn. Does NOT re-kick — callers that want restart
99
115
  * behaviour should enqueue a message before/after calling abort. */
100
116
  abort(reason?: string): Promise<void>;