@noetic-tools/core 5.12.0 → 5.14.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 (53) hide show
  1. package/dist/adapters/in-memory-subprocess/step-completion.d.ts +2 -2
  2. package/dist/adapters/in-memory-subprocess/step-completion.js +48 -52
  3. package/dist/adapters/in-memory-subprocess/types.d.ts +3 -6
  4. package/dist/adapters/in-memory-subprocess-adapter.js +30 -48
  5. package/dist/adapters/live-handles.d.ts +26 -0
  6. package/dist/adapters/live-handles.js +50 -0
  7. package/dist/builders/decide-builders.d.ts +2 -2
  8. package/dist/builders/dynamic-workflow.js +2 -0
  9. package/dist/builders/provide-builder.d.ts +2 -2
  10. package/dist/builders/spawn-builder.d.ts +2 -2
  11. package/dist/builders/step-builders.d.ts +5 -5
  12. package/dist/builders/workflow-hydrator.d.ts +1 -1
  13. package/dist/builders/workflow-hydrator.js +54 -6
  14. package/dist/expression/check.js +14 -0
  15. package/dist/expression/jsonata.d.ts +7 -0
  16. package/dist/expression/jsonata.js +11 -1
  17. package/dist/harness/agent-harness.d.ts +59 -5
  18. package/dist/harness/agent-harness.js +176 -25
  19. package/dist/harness/deps/runtime.d.ts +4 -0
  20. package/dist/harness/deps/runtime.js +2 -0
  21. package/dist/harness/model-call.js +69 -0
  22. package/dist/harness/model-rounds.d.ts +52 -0
  23. package/dist/harness/model-rounds.js +115 -0
  24. package/dist/harness/thread-record.d.ts +54 -0
  25. package/dist/harness/thread-record.js +159 -0
  26. package/dist/index.d.ts +7 -3
  27. package/dist/index.js +2 -0
  28. package/dist/interpreter/emit-items.d.ts +19 -0
  29. package/dist/interpreter/emit-items.js +106 -0
  30. package/dist/interpreter/execute-action.js +3 -0
  31. package/dist/interpreter/execute-control.js +3 -0
  32. package/dist/interpreter/execute.js +67 -12
  33. package/dist/interpreter/step-dispatcher.d.ts +2 -2
  34. package/dist/interpreter/step-dispatcher.js +3 -5
  35. package/dist/runtime/context-impl.d.ts +106 -4
  36. package/dist/runtime/context-impl.js +224 -14
  37. package/dist/runtime/durable/harness-checkpoints.d.ts +13 -3
  38. package/dist/runtime/durable/harness-checkpoints.js +66 -7
  39. package/dist/runtime/durable/session-store.d.ts +37 -0
  40. package/dist/runtime/durable/session-store.js +58 -0
  41. package/dist/runtime/durable/step-ledger.d.ts +77 -40
  42. package/dist/runtime/durable/step-ledger.js +193 -73
  43. package/dist/runtime/item-log-impl.d.ts +6 -0
  44. package/dist/runtime/item-log-impl.js +12 -0
  45. package/dist/runtime/session-runner.d.ts +25 -1
  46. package/dist/runtime/session-runner.js +83 -11
  47. package/dist/schemas/workflow.d.ts +1 -1
  48. package/dist/types/checkpoint.d.ts +21 -4
  49. package/dist/types/checkpoint.js +33 -3
  50. package/dist/util/detached-handle.d.ts +9 -20
  51. package/dist/util/detached-handle.js +7 -108
  52. package/package.json +2 -2
  53. package/schema/noetic-workflow.schema.json +391 -0
@@ -14,8 +14,13 @@ import { z } from 'zod';
14
14
  * layer id, so a v1 snapshot carries state under ids no current layer reads
15
15
  * — restoring it would silently drop that state. There is no migration;
16
16
  * discard via `CheckpointStore.clear()` and start fresh.
17
+ * - v2 → v3: `itemLog` holds the log as it stood when the run in flight began, not
18
+ * at the moment of capture, and `occurrences` records the dispatch counts from that
19
+ * same moment. A resumed run replays its recorded steps, which put their items
20
+ * back; a v2 log already holds them, so restoring it would duplicate history. No
21
+ * migration — discard and start fresh.
17
22
  */
18
- export declare const CheckpointSchemaVersion = 2;
23
+ export declare const CheckpointSchemaVersion = 3;
19
24
  /**
20
25
  * @public
21
26
  * One entry in the execution frontier — a pointer to a step currently in
@@ -60,8 +65,9 @@ export declare const PendingAskUserSnapshotSchema: z.ZodObject<{
60
65
  export type PendingAskUserSnapshot = z.infer<typeof PendingAskUserSnapshotSchema>;
61
66
  /**
62
67
  * @public
63
- * Item log state captured in a snapshot. We store the ordered list of items
64
- * directly — the `ItemLogImpl` is append-only so the list is its own cursor.
68
+ * Item log state captured in a snapshot: the log as it stood when the run in
69
+ * flight began, or the live log when no run is in flight. The steps a resumed run
70
+ * replays put the rest back, from the items the step ledger recorded for each.
65
71
  *
66
72
  * Items are carried as `unknown` here and re-parsed on restore via the
67
73
  * harness's `ItemSchemaRegistry`, which is the same gate production traffic
@@ -99,7 +105,7 @@ export type ChannelSnapshot = z.infer<typeof ChannelSnapshotSchema>;
99
105
  * instead of producing a silently corrupt restored context.
100
106
  */
101
107
  export declare const CheckpointSnapshotSchema: z.ZodObject<{
102
- schemaVersion: z.ZodLiteral<2>;
108
+ schemaVersion: z.ZodLiteral<3>;
103
109
  executionId: z.ZodString;
104
110
  threadId: z.ZodOptional<z.ZodString>;
105
111
  resourceId: z.ZodOptional<z.ZodString>;
@@ -121,6 +127,17 @@ export declare const CheckpointSnapshotSchema: z.ZodObject<{
121
127
  itemLog: z.ZodObject<{
122
128
  items: z.ZodArray<z.ZodUnknown>;
123
129
  }, z.core.$strip>;
130
+ occurrences: z.ZodRecord<z.ZodString, z.ZodNumber>;
131
+ state: z.ZodOptional<z.ZodUnknown>;
132
+ usage: z.ZodOptional<z.ZodObject<{
133
+ tokens: z.ZodObject<{
134
+ input: z.ZodNumber;
135
+ output: z.ZodNumber;
136
+ total: z.ZodNumber;
137
+ cached: z.ZodOptional<z.ZodNumber>;
138
+ }, z.core.$strip>;
139
+ cost: z.ZodNumber;
140
+ }, z.core.$strip>>;
124
141
  channels: z.ZodOptional<z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
125
142
  name: z.ZodString;
126
143
  mode: z.ZodLiteral<"value">;
@@ -15,8 +15,13 @@ import { z } from 'zod';
15
15
  * layer id, so a v1 snapshot carries state under ids no current layer reads
16
16
  * — restoring it would silently drop that state. There is no migration;
17
17
  * discard via `CheckpointStore.clear()` and start fresh.
18
+ * - v2 → v3: `itemLog` holds the log as it stood when the run in flight began, not
19
+ * at the moment of capture, and `occurrences` records the dispatch counts from that
20
+ * same moment. A resumed run replays its recorded steps, which put their items
21
+ * back; a v2 log already holds them, so restoring it would duplicate history. No
22
+ * migration — discard and start fresh.
18
23
  */
19
- export const CheckpointSchemaVersion = 2;
24
+ export const CheckpointSchemaVersion = 3;
20
25
  /**
21
26
  * @public
22
27
  * One entry in the execution frontier — a pointer to a step currently in
@@ -58,8 +63,9 @@ export const PendingAskUserSnapshotSchema = z.object({
58
63
  });
59
64
  /**
60
65
  * @public
61
- * Item log state captured in a snapshot. We store the ordered list of items
62
- * directly — the `ItemLogImpl` is append-only so the list is its own cursor.
66
+ * Item log state captured in a snapshot: the log as it stood when the run in
67
+ * flight began, or the live log when no run is in flight. The steps a resumed run
68
+ * replays put the rest back, from the items the step ledger recorded for each.
63
69
  *
64
70
  * Items are carried as `unknown` here and re-parsed on restore via the
65
71
  * harness's `ItemSchemaRegistry`, which is the same gate production traffic
@@ -107,6 +113,30 @@ export const CheckpointSnapshotSchema = z.object({
107
113
  cwd: CwdSnapshotSchema.nullable(),
108
114
  askUser: z.array(PendingAskUserSnapshotSchema),
109
115
  itemLog: ItemLogSnapshotSchema,
116
+ /**
117
+ * Dispatch counts per `<parent path>/<step id>`, taken at the same moment as
118
+ * `itemLog`. A restored context numbers its dispatches from here, so a resumed run
119
+ * meets its recorded steps at the paths they were recorded under, and a later run
120
+ * on the same execution does not land on an earlier run's paths.
121
+ */
122
+ occurrences: z.record(z.string(), z.number()),
123
+ /**
124
+ * The execution's `ctx.state` at capture time. Absent when the state does not survive
125
+ * JSON encoding, in which case restore keeps whatever state the host passes.
126
+ */
127
+ state: z.unknown().optional(),
128
+ /** Tokens and cost the execution had spent at capture time, so budgets carry over. */
129
+ usage: z
130
+ .object({
131
+ tokens: z.object({
132
+ input: z.number(),
133
+ output: z.number(),
134
+ total: z.number(),
135
+ cached: z.number().optional(),
136
+ }),
137
+ cost: z.number(),
138
+ })
139
+ .optional(),
110
140
  /**
111
141
  * Stored state of every channel the execution used. Optional so snapshots
112
142
  * written before channels were captured still load (they restore with no
@@ -1,4 +1,4 @@
1
- import type { DetachedHandle, SubprocessAdapter, SubprocessHandle } from '@noetic-tools/types';
1
+ import type { DetachedHandle, SpawnedSubprocess } from '@noetic-tools/types';
2
2
  import { DetachedStatus } from '@noetic-tools/types';
3
3
  interface DetachedHandleOpts {
4
4
  /** Id surfaced to callers — usually the execution id (childCtx.id in
@@ -7,33 +7,23 @@ interface DetachedHandleOpts {
7
7
  /** Step id — used when the adapter surfaces a generic failure and we need
8
8
  * to produce a `NoeticError` with a meaningful `stepId`. */
9
9
  stepId: string;
10
- /** Adapter that produced the handle. */
11
- adapter: SubprocessAdapter;
12
10
  /**
13
- * Promise that resolves to the adapter-assigned handle. `detachedSpawn`
14
- * passes the in-flight `adapter.spawn(request)` promise here so `.await()`
15
- * is reachable even before the spawn itself has settled.
11
+ * The in-flight `adapter.spawn(request)` call, passed unawaited so the
12
+ * handle exists (and `.await()` works) before the spawn itself resolves.
16
13
  */
17
- spawnPromise: Promise<SubprocessHandle>;
14
+ spawned: Promise<SpawnedSubprocess>;
18
15
  }
19
16
  /**
20
17
  * @public
21
- * Thin wrapper over a `SubprocessHandle` that implements the `DetachedHandle`
22
- * contract. Polls the adapter until the handle reaches a terminal status,
23
- * then reads the result (or error) off `handle.metadata`. Polling starts in
24
- * the constructor, so `status`, `result`, and `error` settle whether or not
25
- * the caller ever invokes `.await()`.
26
- *
27
- * The polling cadence starts at 10ms and ramps to 100ms after the first
28
- * second — responsive for short-lived in-memory steps without burning cycles
29
- * on long-running ones.
18
+ * Thin wrapper over a spawned subprocess that implements the `DetachedHandle`
19
+ * contract. It waits on the adapter's `settled` promise and reads the result
20
+ * (or error) off the final handle's metadata. Waiting starts in the
21
+ * constructor, so `status`, `result`, and `error` settle whether or not the
22
+ * caller ever invokes `.await()`.
30
23
  */
31
24
  export declare class DetachedHandleImpl<O> implements DetachedHandle<O> {
32
25
  readonly id: string;
33
26
  private readonly _stepId;
34
- private readonly _adapter;
35
- private readonly _spawnPromise;
36
- private readonly _startTime;
37
27
  private _status;
38
28
  private _result;
39
29
  private _error;
@@ -49,7 +39,6 @@ export declare class DetachedHandleImpl<O> implements DetachedHandle<O> {
49
39
  * observes the final value.
50
40
  */
51
41
  await(timeout?: number): Promise<O>;
52
- private pollUntilSettled;
53
42
  private finalise;
54
43
  }
55
44
  export {};
@@ -1,35 +1,6 @@
1
1
  import { DetachedStatus, frameworkCast, NoeticErrorImpl } from '@noetic-tools/types';
2
2
  //#endregion
3
3
  //#region Helpers
4
- const INITIAL_POLL_MS = 10;
5
- const MAX_POLL_MS = 100;
6
- const POLL_RAMP_AFTER_MS = 1_000;
7
- /** Upper bound on microtask yields before falling back to timer-based
8
- * polling. Chosen empirically: in-memory step bodies settle within a
9
- * handful of microtasks, and 64 gives plenty of headroom for chained
10
- * awaits inside complex step trees without busy-spinning. */
11
- const MAX_MICROTASK_YIELDS = 64;
12
- /** Grace period before treating persistent null `adapter.get(handleId)`
13
- * results as an eviction. Tolerates transient nulls from adapters that
14
- * register the handle asynchronously relative to the spawn promise
15
- * settling, but bounds the worst case so a corrupt adapter doesn't
16
- * produce an infinite poll. */
17
- const HANDLE_EVICTED_GRACE_MS = 500;
18
- /**
19
- * Yield control to the timer queue so the adapter has a chance to
20
- * transition the handle before we issue the next `adapter.get()` call.
21
- * Using a timer (even 0ms) ensures we don't spin-lock when the adapter
22
- * schedules its completion on a later microtask.
23
- */
24
- function sleep(ms) {
25
- if (ms <= 0) {
26
- return Promise.resolve();
27
- }
28
- return new Promise((resolve) => setTimeout(resolve, ms));
29
- }
30
- function isTerminalStatus(status) {
31
- return (status === 'completed' || status === 'failed' || status === 'stopped' || status === 'stale');
32
- }
33
4
  function isRecord(value) {
34
5
  return typeof value === 'object' && value !== null;
35
6
  }
@@ -90,22 +61,15 @@ function extractError(metadata) {
90
61
  //#region DetachedHandleImpl
91
62
  /**
92
63
  * @public
93
- * Thin wrapper over a `SubprocessHandle` that implements the `DetachedHandle`
94
- * contract. Polls the adapter until the handle reaches a terminal status,
95
- * then reads the result (or error) off `handle.metadata`. Polling starts in
96
- * the constructor, so `status`, `result`, and `error` settle whether or not
97
- * the caller ever invokes `.await()`.
98
- *
99
- * The polling cadence starts at 10ms and ramps to 100ms after the first
100
- * second — responsive for short-lived in-memory steps without burning cycles
101
- * on long-running ones.
64
+ * Thin wrapper over a spawned subprocess that implements the `DetachedHandle`
65
+ * contract. It waits on the adapter's `settled` promise and reads the result
66
+ * (or error) off the final handle's metadata. Waiting starts in the
67
+ * constructor, so `status`, `result`, and `error` settle whether or not the
68
+ * caller ever invokes `.await()`.
102
69
  */
103
70
  export class DetachedHandleImpl {
104
71
  id;
105
72
  _stepId;
106
- _adapter;
107
- _spawnPromise;
108
- _startTime;
109
73
  _status = DetachedStatus.Running;
110
74
  _result;
111
75
  _error;
@@ -113,13 +77,8 @@ export class DetachedHandleImpl {
113
77
  constructor(opts) {
114
78
  this.id = opts.id;
115
79
  this._stepId = opts.stepId;
116
- this._adapter = opts.adapter;
117
- this._spawnPromise = opts.spawnPromise;
118
- this._startTime = Date.now();
119
- // One shared poll for the handle's life, so repeated `.await()` calls
120
- // don't start parallel loops. The rejection is swallowed here only to
121
- // record it; `.await()` surfaces it to the caller.
122
- this._settlement = this.pollUntilSettled();
80
+ this._settlement = opts.spawned.then((s) => s.settled).then((h) => this.finalise(h));
81
+ // Swallowed here only to record the failure; `.await()` surfaces it.
123
82
  this._settlement.catch((err) => {
124
83
  if (this._status === DetachedStatus.Running) {
125
84
  this._status = DetachedStatus.Failed;
@@ -170,66 +129,6 @@ export class DetachedHandleImpl {
170
129
  }
171
130
  }
172
131
  }
173
- async pollUntilSettled() {
174
- // Wait for the spawn itself to succeed before we start polling —
175
- // otherwise we'd be polling with an undefined handle id.
176
- const initialHandle = await this._spawnPromise;
177
- if (isTerminalStatus(initialHandle.status)) {
178
- return this.finalise(initialHandle);
179
- }
180
- // Track when the adapter persistently returns null for this handle.
181
- // Transient nulls are tolerated for `HANDLE_EVICTED_GRACE_MS`; after
182
- // that we raise `handle_evicted` instead of looping forever. A
183
- // non-null observation resets the grace window.
184
- let firstNullAt = null;
185
- const observeNull = () => {
186
- if (firstNullAt === null) {
187
- firstNullAt = Date.now();
188
- return;
189
- }
190
- if (Date.now() - firstNullAt >= HANDLE_EVICTED_GRACE_MS) {
191
- throw new NoeticErrorImpl({
192
- kind: 'handle_evicted',
193
- handleId: initialHandle.id,
194
- stepId: this._stepId,
195
- gracePeriod: HANDLE_EVICTED_GRACE_MS,
196
- });
197
- }
198
- };
199
- const observeHandle = (h) => {
200
- if (h === null) {
201
- observeNull();
202
- return null;
203
- }
204
- firstNullAt = null;
205
- return h;
206
- };
207
- // Fast path: yield through the microtask queue first. The in-memory
208
- // adapter schedules completion on a microtask, so a handful of yields
209
- // typically resolves the handle in sub-millisecond time. This keeps the
210
- // interpreter's "route through adapter" overhead negligible.
211
- for (let i = 0; i < MAX_MICROTASK_YIELDS; i++) {
212
- const handle = observeHandle(await this._adapter.get(initialHandle.id));
213
- if (handle && isTerminalStatus(handle.status)) {
214
- return this.finalise(handle);
215
- }
216
- await Promise.resolve();
217
- }
218
- // Slow path: fall back to timer-based polling for genuinely long-running
219
- // handles (out-of-process adapters, async work that doesn't resolve on
220
- // the microtask queue).
221
- let delay = INITIAL_POLL_MS;
222
- for (;;) {
223
- const handle = observeHandle(await this._adapter.get(initialHandle.id));
224
- if (handle && isTerminalStatus(handle.status)) {
225
- return this.finalise(handle);
226
- }
227
- await sleep(delay);
228
- if (Date.now() - this._startTime >= POLL_RAMP_AFTER_MS) {
229
- delay = MAX_POLL_MS;
230
- }
231
- }
232
- }
233
132
  finalise(handle) {
234
133
  const metadata = handle.metadata;
235
134
  if (handle.status === 'completed') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.12.0",
3
+ "version": "5.14.0",
4
4
  "type": "module",
5
5
  "description": "Step primitives, interpreter, runtime, and context layer contract for Noetic agents.",
6
6
  "license": "Apache-2.0",
@@ -69,7 +69,7 @@
69
69
  },
70
70
  "dependencies": {
71
71
  "@noetic-tools/context": "^1.9.0",
72
- "@noetic-tools/types": "^3.10.0",
72
+ "@noetic-tools/types": "^3.12.0",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "jsonata": "2.2.2",