@noetic-tools/core 5.22.0-next.2 → 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 (42) 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 +76 -3
  8. package/dist/harness/agent-harness.js +229 -21
  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 +15 -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/recorded-tool-calls.d.ts +16 -0
  17. package/dist/harness/recorded-tool-calls.js +106 -0
  18. package/dist/harness/spend.d.ts +13 -1
  19. package/dist/harness/spend.js +82 -1
  20. package/dist/harness/steer-inbox.js +9 -5
  21. package/dist/harness/thread-record.d.ts +12 -1
  22. package/dist/harness/thread-record.js +63 -19
  23. package/dist/index.d.ts +4 -5
  24. package/dist/index.js +2 -3
  25. package/dist/interpreter/acp-tools.js +21 -4
  26. package/dist/interpreter/execute-action.js +7 -1
  27. package/dist/interpreter/execute.js +55 -3
  28. package/dist/interpreter/step-dispatcher.js +17 -1
  29. package/dist/interpreter/step-kind-dispatch.js +9 -1
  30. package/dist/runtime/durable/child-links.d.ts +61 -0
  31. package/dist/runtime/durable/child-links.js +127 -0
  32. package/dist/runtime/durable/session-store.d.ts +6 -0
  33. package/dist/runtime/durable/session-store.js +16 -2
  34. package/dist/runtime/durable/turn-lease.d.ts +10 -0
  35. package/dist/runtime/durable/turn-lease.js +10 -2
  36. package/dist/runtime/held-calls.d.ts +65 -6
  37. package/dist/runtime/held-calls.js +257 -5
  38. package/dist/runtime/output-store.d.ts +2 -0
  39. package/dist/runtime/output-store.js +3 -1
  40. package/dist/runtime/tool-approval.d.ts +1 -3
  41. package/dist/runtime/tool-approval.js +1 -1
  42. package/package.json +2 -2
@@ -1,3 +1,4 @@
1
+ import { markInProcess } from '../runtime/durable/child-links.js';
1
2
  import { clearManifest, listManifests, loadManifest, persistStepManifest, } from './in-memory-subprocess/manifest-persistence.js';
2
3
  import { buildProcessMetadata, buildStepMetadata, isProcessRequest, isStepRequest, nowIso, } from './in-memory-subprocess/metadata.js';
3
4
  import { completeProcessRun, completeStepRun } from './in-memory-subprocess/step-completion.js';
@@ -111,7 +112,8 @@ export function createInMemorySubprocessAdapter(options = {}) {
111
112
  },
112
113
  };
113
114
  }
114
- return {
115
+ // Steps run through the caller's local executor, in this process.
116
+ return markInProcess({
115
117
  async spawn(request) {
116
118
  if (isStepRequest(request)) {
117
119
  return spawnStepHandle(request);
@@ -214,6 +216,6 @@ export function createInMemorySubprocessAdapter(options = {}) {
214
216
  ...found.values(),
215
217
  ];
216
218
  },
217
- };
219
+ });
218
220
  }
219
221
  //#endregion
@@ -17,7 +17,7 @@ interface CustomItemConfig<T extends CustomItemType, E extends ItemShape, O exte
17
17
  * @public
18
18
  * @throws `NoeticConfigError` with code `INVALID_CUSTOM_ITEM_TYPE` when `type` has no `prefix:` part.
19
19
  * @throws `NoeticConfigError` with code `INVALID_CUSTOM_ITEM_SHAPE` when a JSON Schema does not
20
- * load, or `output` does not describe an object or declares `id` or `type`.
20
+ * load, or `output` is not an object (or a union of objects), or declares `id` or `type`.
21
21
  */
22
22
  export declare function customItem<T extends CustomItemType, O extends ItemShape, E extends ItemShape = never>(config: CustomItemConfig<T, E, O>): CustomItem<T, InferShape<E>, InferShape<O>>;
23
23
  /**
@@ -11,7 +11,7 @@ import { z } from 'zod';
11
11
  * @public
12
12
  * @throws `NoeticConfigError` with code `INVALID_CUSTOM_ITEM_TYPE` when `type` has no `prefix:` part.
13
13
  * @throws `NoeticConfigError` with code `INVALID_CUSTOM_ITEM_SHAPE` when a JSON Schema does not
14
- * load, or `output` does not describe an object or declares `id` or `type`.
14
+ * load, or `output` is not an object (or a union of objects), or declares `id` or `type`.
15
15
  */
16
16
  export function customItem(config) {
17
17
  if (!/^[^:]+:.+$/.test(config.type)) {
@@ -93,17 +93,28 @@ function isStandardSchema(shape) {
93
93
  }
94
94
  /**
95
95
  * The fields check needs a schema it can see into: a Zod object, which every JSON
96
- * Schema becomes. Other vendors are checked when a value is emitted instead.
96
+ * Schema becomes, or a union of them (a discriminated union of item shapes, or a
97
+ * JSON Schema `oneOf`/`anyOf`), each option checked the same way. Other vendors are
98
+ * checked when a value is emitted instead.
97
99
  */
98
100
  function checkFields(output, type) {
99
101
  if (!isZodSchema(output)) {
100
102
  return;
101
103
  }
104
+ checkZodFields(output, type);
105
+ }
106
+ function checkZodFields(output, type) {
107
+ if (output instanceof z.ZodUnion) {
108
+ for (const option of output.options) {
109
+ checkZodFields(option, type);
110
+ }
111
+ return;
112
+ }
102
113
  if (!(output instanceof z.ZodObject)) {
103
114
  throw new NoeticConfigError({
104
115
  code: 'INVALID_CUSTOM_ITEM_SHAPE',
105
116
  message: `The output of custom item '${type}' does not describe an object.`,
106
- hint: 'A final item is its fields plus the id and type the runtime adds, so output must be an object schema.',
117
+ hint: 'A final item is its fields plus the id and type the runtime adds, so output must be an object schema, or a union of object schemas.',
107
118
  });
108
119
  }
109
120
  const reserved = Object.keys(output.shape).filter((key) => key === 'id' || key === 'type');
@@ -39,15 +39,24 @@ export interface AcquireRequest {
39
39
  readonly scope: FreshScope;
40
40
  readonly setup: Readonly<Record<string, unknown>>;
41
41
  readonly signal: AbortSignal;
42
+ /**
43
+ * The root execution of the run that holds the lease, kept with its stored
44
+ * record so a forget of the run finds it (spec 23 § Forgetting).
45
+ */
46
+ readonly executionId?: string;
42
47
  }
43
48
  /** How long a request queues on a full pool when `waitMs` is unset. */
44
49
  export declare const DEFAULT_POOL_WAIT_MS = 60000;
50
+ /** @internal The prefix every pool lease record is stored under: `<prefix><pool>/<holder>`. */
51
+ export declare const POOL_LEASE_PREFIX = "noetic/connections/leases/";
45
52
  /** One pool of fresh connections. */
46
53
  export declare class ConnectionPool {
47
54
  private readonly deps;
48
55
  private readonly held;
49
56
  /** Holders that stopped renewing (a failed run): reclaimed once their lease expires. */
50
57
  private readonly orphaned;
58
+ /** The run each holder's lease belongs to, kept with its stored record. */
59
+ private readonly owners;
51
60
  private readonly acquiring;
52
61
  private readonly idle;
53
62
  private provisioning;
@@ -105,7 +114,16 @@ export declare class ConnectionPool {
105
114
  private provision;
106
115
  private waitForSpace;
107
116
  private wake;
117
+ /** The stored record of a lease. */
118
+ private record;
108
119
  private leaseKey;
109
120
  private leaseFor;
110
121
  private renewAll;
111
122
  }
123
+ /**
124
+ * @internal
125
+ * The stored pool lease records that belong to any of `executionIds`: those that
126
+ * name one as their run, and, in records written before the run was kept, those
127
+ * whose holder is the run (`<id>`) or one of its parallel paths (`<id>:path:…`).
128
+ */
129
+ export declare function poolLeasesOf(storage: StorageAdapter, executionIds: ReadonlySet<string>): Promise<string[]>;
@@ -11,6 +11,7 @@
11
11
  * provider, never handed to another holder. `warm` connections are
12
12
  * provisioned ahead with an empty setup and serve requests that pass none.
13
13
  */
14
+ import { storageGetMany } from '@noetic-tools/context';
14
15
  import { LEASE_RECLAIM_MS, LEASE_RENEW_MS } from '@noetic-tools/types';
15
16
  import { z } from 'zod';
16
17
  import { invalidConnectionError, unavailableError } from './errors.js';
@@ -22,7 +23,11 @@ export const DEFAULT_POOL_WAIT_MS = 6e4;
22
23
  const StoredLeaseSchema = z.object({
23
24
  id: z.string(),
24
25
  expiresAt: z.number(),
26
+ /** The run that holds it. Absent in records written before it was kept. */
27
+ executionId: z.string().optional(),
25
28
  });
29
+ /** @internal The prefix every pool lease record is stored under: `<prefix><pool>/<holder>`. */
30
+ export const POOL_LEASE_PREFIX = 'noetic/connections/leases/';
26
31
  //#endregion
27
32
  //#region Helpers
28
33
  function unrefTimer(timer) {
@@ -38,6 +43,8 @@ export class ConnectionPool {
38
43
  held = new Map();
39
44
  /** Holders that stopped renewing (a failed run): reclaimed once their lease expires. */
40
45
  orphaned = new Set();
46
+ /** The run each holder's lease belongs to, kept with its stored record. */
47
+ owners = new Map();
41
48
  acquiring = new Map();
42
49
  idle = [];
43
50
  provisioning = 0;
@@ -108,6 +115,7 @@ export class ConnectionPool {
108
115
  }
109
116
  this.held.delete(scopeKey);
110
117
  this.orphaned.delete(scopeKey);
118
+ this.owners.delete(scopeKey);
111
119
  await this.deps.storage.delete(this.leaseKey(scopeKey));
112
120
  this.deps.onLease?.(held.lease, change);
113
121
  this.wake();
@@ -292,8 +300,21 @@ export class ConnectionPool {
292
300
  waiter();
293
301
  }
294
302
  }
303
+ /** The stored record of a lease. */
304
+ record(scopeKey, lease) {
305
+ const executionId = this.owners.get(scopeKey);
306
+ return {
307
+ id: lease.id,
308
+ expiresAt: lease.expiresAt,
309
+ ...(executionId === undefined
310
+ ? {}
311
+ : {
312
+ executionId,
313
+ }),
314
+ };
315
+ }
295
316
  leaseKey(scopeKey) {
296
- return `noetic/connections/leases/${this.deps.name}/${scopeKey}`;
317
+ return `${POOL_LEASE_PREFIX}${this.deps.name}/${scopeKey}`;
297
318
  }
298
319
  async leaseFor(request) {
299
320
  const now = this.now();
@@ -306,10 +327,10 @@ export class ConnectionPool {
306
327
  holder: request.scopeKey,
307
328
  expiresAt: now + this.reclaimMs,
308
329
  };
309
- await this.deps.storage.set(this.leaseKey(request.scopeKey), {
310
- id,
311
- expiresAt: lease.expiresAt,
312
- });
330
+ if (request.executionId !== undefined) {
331
+ this.owners.set(request.scopeKey, request.executionId);
332
+ }
333
+ await this.deps.storage.set(this.leaseKey(request.scopeKey), this.record(request.scopeKey, lease));
313
334
  return lease;
314
335
  }
315
336
  async renewAll() {
@@ -328,12 +349,36 @@ export class ConnectionPool {
328
349
  lease,
329
350
  connection: held.connection,
330
351
  });
331
- await this.deps.storage.set(this.leaseKey(scopeKey), {
332
- id: lease.id,
333
- expiresAt: lease.expiresAt,
334
- });
352
+ await this.deps.storage.set(this.leaseKey(scopeKey), this.record(scopeKey, lease));
335
353
  this.deps.onLease?.(lease, 'renewed');
336
354
  }
337
355
  }
338
356
  }
339
357
  //#endregion
358
+ //#region Forgetting
359
+ /**
360
+ * @internal
361
+ * The stored pool lease records that belong to any of `executionIds`: those that
362
+ * name one as their run, and, in records written before the run was kept, those
363
+ * whose holder is the run (`<id>`) or one of its parallel paths (`<id>:path:…`).
364
+ */
365
+ export async function poolLeasesOf(storage, executionIds) {
366
+ const keys = await storage.list(POOL_LEASE_PREFIX);
367
+ if (keys.length === 0 || executionIds.size === 0) {
368
+ return [];
369
+ }
370
+ const records = await storageGetMany(storage, keys);
371
+ return keys.filter((key) => {
372
+ const stored = StoredLeaseSchema.safeParse(records.get(key));
373
+ if (stored.success && stored.data.executionId !== undefined) {
374
+ return executionIds.has(stored.data.executionId);
375
+ }
376
+ for (const id of executionIds) {
377
+ if (key.endsWith(`/${id}`) || key.includes(`/${id}:path:`)) {
378
+ return true;
379
+ }
380
+ }
381
+ return false;
382
+ });
383
+ }
384
+ //#endregion
@@ -699,6 +699,7 @@ class Runtime {
699
699
  scope: request.fresh ?? 'run',
700
700
  setup: request.setup ?? {},
701
701
  signal: request.scope.signal,
702
+ executionId: request.rootId ?? runOf(request.ctx) ?? request.scope.executionId,
702
703
  });
703
704
  try {
704
705
  this.negotiate(entry.name, held.connection.manifest, request);
@@ -927,3 +928,13 @@ export function createConnectionRuntime(options) {
927
928
  return new Runtime(options);
928
929
  }
929
930
  //#endregion
931
+ //#region Helpers
932
+ /** The id of the run `ctx` belongs to: its topmost ancestor's. */
933
+ function runOf(ctx) {
934
+ let current = ctx;
935
+ while (current?.parent) {
936
+ current = current.parent;
937
+ }
938
+ return current?.id;
939
+ }
940
+ //#endregion
@@ -1,6 +1,7 @@
1
- import type { ApproveRequest, ArtifactStore, ConnectionStatus, ConnectionTrigger, ExecuteArgument, HeldCall, HeldResolution, StuckTurn, TrailMark } from '@noetic-tools/types';
1
+ import type { ApproveRequest, ArtifactStore, ConnectionStatus, ConnectionTrigger, ExecuteArgument, ForgetOptions, ForgetReport, HeldCall, HeldResolution, ListStoredOptions, RecordedToolCall, StoredExecution, StuckTurn, TrailMark } from '@noetic-tools/types';
2
2
  import { ItemSchemaRegistry } from '@noetic-tools/types';
3
3
  import { AcpSessionStore } from '../runtime/acp-session-store.js';
4
+ import type { HeldAnswerRequest } from '../runtime/held-calls.js';
4
5
  import type { OutputSnapshot } from '../runtime/output-store.js';
5
6
  import type { LayerStateStore, RecallCache } from './deps/context.js';
6
7
  import type { DetachedSpawnOverrides } from './deps/interpreter.js';
@@ -91,6 +92,10 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
91
92
  private readonly outputStorage;
92
93
  /** The display output each thread of an interactive harness records, by thread id. */
93
94
  private readonly outputs;
95
+ /** Forgets in progress, by thread id: a turn of the thread waits for its forget. */
96
+ private readonly forgetting;
97
+ /** Ids of the context layers whose state this harness has kept durably. */
98
+ private readonly durableLayerIds;
94
99
  /** Thread id → what stops recording it. */
95
100
  private readonly stopRecording;
96
101
  /** Threads named by a host-built context's own id, dropped when its run ends. */
@@ -384,6 +389,14 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
384
389
  readonly callId: string;
385
390
  readonly argsHash?: string;
386
391
  }, options?: ExecuteOptions): Promise<void>;
392
+ /**
393
+ * An `onHeld` handler's answer: for the execution that held the call, never for a
394
+ * later turn on the same thread. Wakes the thread's turn when it is that execution.
395
+ * @internal
396
+ */
397
+ answerHeld(answer: HeldAnswerRequest): Promise<void>;
398
+ /** A thread's turn was answered: resume it if parked, now or once it comes to rest. */
399
+ private wakeAnswered;
387
400
  /**
388
401
  * The turns that stopped rather than redo a step that had a lasting effect under
389
402
  * another flow version (spec 23 § Versions). Each waits for a `DecisionItem`
@@ -401,16 +414,70 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
401
414
  * - `abandon`: drop the turn. Its trail is kept.
402
415
  */
403
416
  private settleStuckTurn;
417
+ /**
418
+ * The tool calls a resume of `executionId` goes on from rather than having the
419
+ * model ask for them again: every call whose request its step ledger holds, in a
420
+ * completed step or a recorded round, read from storage. `settled` says whether
421
+ * the call's result is on record too; an unsettled call runs again on resume (spec
422
+ * 23a § Tool calls in a round). A host that journals tool traffic of its own adds
423
+ * none of these to a restored context, or the model sees them twice. Empty without
424
+ * durable storage.
425
+ * @public
426
+ */
427
+ recordedToolCalls(executionId: string): Promise<RecordedToolCall[]>;
404
428
  /**
405
429
  * What a run did, step by step: who ran each step, under which flow version, and
406
430
  * the receipt of a step with a lasting effect (spec 23 § The trail). Marks outlive
407
431
  * the ledger entries they came from, so the trail of a finished run stays readable.
408
432
  *
409
- * `scope` names an execution, or a thread, whose recent turns are then listed in
410
- * order.
433
+ * `scope` names an execution, or a thread, whose turns are then listed in order:
434
+ * every turn it began, two reads per turn.
411
435
  * @public
412
436
  */
413
437
  getAuditTrail(scope: SessionScope | ExecutionScope): Promise<TrailMark[]>;
438
+ /**
439
+ * Delete everything the harness keeps for a thread or an execution, so a host never
440
+ * builds a storage key itself (spec 23 § Forgetting).
441
+ *
442
+ * A thread's forget covers every execution the thread ran, its context-layer state,
443
+ * display output, record and turn lease. An execution's forget covers what is stored
444
+ * under it and its layer state, and leaves any thread's record alone. Pending spend
445
+ * is settled first: priced through the provider, waiting up to `patienceMs`, else
446
+ * written off at its ceiling (at 0, flagged `unbounded`, when it has none). The trail
447
+ * goes too unless `keepTrail`.
448
+ *
449
+ * A thread's forget holds and renews the thread's lease until it is done, and a
450
+ * message sent to the thread on this harness meanwhile waits for it, then starts
451
+ * the thread afresh.
452
+ *
453
+ * @throws NoeticError `lease_lost` when the thread has a turn running, queued or
454
+ * being delivered in this harness, is already being forgotten, or the execution
455
+ * has a run in flight; when another harness still holds the thread's lease after
456
+ * `waitMs`; or when the lease is lost part way.
457
+ * @throws NoeticError `ledger_write_failed` when a spend record could not be
458
+ * settled; nothing was deleted.
459
+ * @throws NoeticConfigError `INVALID_FORGET_SCOPE` for a scope with neither id.
460
+ * @public
461
+ */
462
+ forget(scope: {
463
+ threadId: string;
464
+ } | ExecutionScope, options?: ForgetOptions): Promise<ForgetReport>;
465
+ /**
466
+ * Every thread with a record, a turn lease, or display output stored: what
467
+ * `forget({ threadId })` deletes. Sorted; `prefix` narrows to ids that start with it.
468
+ * @public
469
+ */
470
+ listStoredThreads(options?: ListStoredOptions): Promise<string[]>;
471
+ /**
472
+ * Every execution with anything stored, with what is stored for it. `resumable` is
473
+ * set when a snapshot or ledger entries are: a trail alone is not a checkpoint.
474
+ * Sorted; `prefix` narrows to ids that start with it.
475
+ * @public
476
+ */
477
+ listStoredExecutions(options?: ListStoredOptions): Promise<StoredExecution[]>;
478
+ private forgetHost;
479
+ /** Ids of the layers that may keep durable state: this harness's thread-wide layers, and any it has kept state for. */
480
+ private layerIds;
414
481
  /**
415
482
  * Add a trigger while the harness runs (spec 35 § Triggers). A trigger written
416
483
  * with expressions only is kept in storage, so it is there again after a restart;
@@ -469,6 +536,12 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
469
536
  * - `interrupt` is not handled here: it replaces the turn, as it does a running one.
470
537
  */
471
538
  private deliverToParked;
539
+ /**
540
+ * The thread whose turn `ctx` runs in, or `undefined` for a run the host started
541
+ * itself. Where an `onHeld` answer goes.
542
+ * @internal
543
+ */
544
+ heldThreadOf(ctx: Context): string | undefined;
472
545
  /** The execution whose held calls `scope` names. */
473
546
  private heldExecutionId;
474
547
  /** The execution of the thread's turn in flight: running here, or stored. */