@noetic-tools/core 5.15.0 → 5.16.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 (37) hide show
  1. package/dist/builders/custom-item.d.ts +37 -0
  2. package/dist/builders/custom-item.js +118 -0
  3. package/dist/builders/decide-builders.d.ts +1 -1
  4. package/dist/builders/dynamic-workflow.js +1 -1
  5. package/dist/builders/output-text.d.ts +5 -0
  6. package/dist/builders/output-text.js +13 -0
  7. package/dist/builders/provide-builder.d.ts +1 -1
  8. package/dist/builders/spawn-builder.d.ts +1 -1
  9. package/dist/builders/step-builders.d.ts +8 -7
  10. package/dist/builders/step-builders.js +2 -0
  11. package/dist/builders/workflow-custom-items.d.ts +38 -0
  12. package/dist/builders/workflow-custom-items.js +118 -0
  13. package/dist/builders/workflow-hydrator.d.ts +9 -2
  14. package/dist/builders/workflow-hydrator.js +41 -71
  15. package/dist/builders/workflow-step.d.ts +23 -5
  16. package/dist/builders/workflow-step.js +28 -13
  17. package/dist/expression/check.js +9 -5
  18. package/dist/harness/agent-harness.d.ts +19 -9
  19. package/dist/harness/agent-harness.js +14 -3
  20. package/dist/harness/deps/interpreter.d.ts +1 -0
  21. package/dist/harness/deps/interpreter.js +1 -0
  22. package/dist/harness/deps/types.d.ts +1 -1
  23. package/dist/index.d.ts +7 -3
  24. package/dist/index.js +6 -0
  25. package/dist/interpreter/emit-items.d.ts +44 -8
  26. package/dist/interpreter/emit-items.js +280 -17
  27. package/dist/interpreter/execute-action.js +3 -1
  28. package/dist/interpreter/execute.js +4 -1
  29. package/dist/runtime/context-impl.d.ts +9 -1
  30. package/dist/runtime/context-impl.js +13 -0
  31. package/dist/runtime/durable/step-ledger.js +80 -15
  32. package/dist/runtime/item-log-impl.d.ts +7 -1
  33. package/dist/runtime/item-log-impl.js +8 -0
  34. package/dist/runtime/session-streams.js +8 -0
  35. package/dist/schemas/workflow.d.ts +1 -1
  36. package/package.json +2 -2
  37. package/schema/noetic-workflow.schema.json +803 -119
@@ -1,28 +1,127 @@
1
- import { frameworkCast } from '@noetic-tools/types';
1
+ import { frameworkCast, NoeticConfigError, validateSchema } from '@noetic-tools/types';
2
+ import { z } from 'zod';
2
3
  import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
3
4
  import { ContextImpl } from '../runtime/context-impl.js';
5
+ import { stepChildren } from './step-walk.js';
6
+ //#endregion
7
+ //#region Constants
8
+ /** Open emissions, by the lane the dispatch runs on (one per dispatch). */
9
+ const emissions = new WeakMap();
10
+ //#endregion
4
11
  //#region Public API
5
12
  /**
6
- * Emits what a finished step asks to (`step.emitItems`): appends the items to the item
7
- * log and streams each as `item_appended` at once, so they reach `getItemStream` while
8
- * the rest of the workflow still runs. Like the SDK item events, it ignores
9
- * `step.emit` filtering. Each item is marked in the step's lane record, so the ledger
10
- * entry that holds it can stream it again on replay.
13
+ * Starts what a step emits (spec 34 § Emitting): opens the dispatch's custom item, if
14
+ * `emitItems` names one, and runs `onStart` with the step's input. Events stream at
15
+ * once as `custom_item_event`; a final item appends and streams as `item_appended`.
11
16
  *
12
- * @throws `NoeticError` with kind `item_schema_mismatch` when an item's type is not
13
- * one the context's item schemas accept.
17
+ * @throws `NoeticConfigError` with code `UNKNOWN_CUSTOM_ITEM`, `CUSTOM_ITEM_HAS_NO_EVENTS`,
18
+ * `CUSTOM_ITEM_ALREADY_FINAL`, or `INVALID_CUSTOM_ITEM`.
14
19
  */
15
- export async function emitStepItems(step, output, ctx) {
16
- const option = step.emitItems;
17
- if (!option) {
20
+ export async function beginEmitItems(step, input, ctx) {
21
+ const config = hookConfig(step);
22
+ if (!config) {
18
23
  return;
19
24
  }
20
- const items = toItems(option === true ? outputText(output) : await option(output, ctx));
21
- for (const item of items) {
22
- appendEmitted(ctx, item);
23
- streamItem(ctx, item);
25
+ if (config.item !== undefined) {
26
+ emissions.set(ctx, {
27
+ id: `item-${crypto.randomUUID()}`,
28
+ item: resolveItem(step, config.item),
29
+ final: false,
30
+ });
31
+ }
32
+ if (config.onStart) {
33
+ await runHook(step, config.onStart, input, ctx);
34
+ }
35
+ }
36
+ /**
37
+ * Finishes what a step emits: runs `onDone` with its output, or for `emitItems: true`
38
+ * emits the output itself as a final item, or for a function emits what it returns.
39
+ * Like the SDK item events, none of it is subject to `step.emit` filtering.
40
+ *
41
+ * @throws `NoeticConfigError` as `beginEmitItems`, and `NoeticError` with kind
42
+ * `item_schema_mismatch` when a standard item's type is not one the context accepts.
43
+ */
44
+ export async function emitStepItems(step, output, ctx) {
45
+ try {
46
+ const option = step.emitItems;
47
+ if (!option) {
48
+ return;
49
+ }
50
+ if (option === true) {
51
+ await emitOutput(step, output, ctx);
52
+ return;
53
+ }
54
+ if (typeof option === 'function') {
55
+ appendAll(ctx, toItems(await option(output, ctx)));
56
+ return;
57
+ }
58
+ if (option.onDone) {
59
+ await runHook(step, frameworkCast(option.onDone), output, ctx);
60
+ }
61
+ }
62
+ finally {
63
+ emissions.delete(ctx);
24
64
  }
25
65
  }
66
+ /**
67
+ * Streams one event a generator `runCode` yielded, as an event of the item its
68
+ * `emitItems` names.
69
+ *
70
+ * @throws `NoeticConfigError` with code `CUSTOM_ITEM_HAS_NO_EVENTS` or `INVALID_CUSTOM_ITEM`.
71
+ */
72
+ export async function emitStepEvent(stepId, event, ctx) {
73
+ await emitEvent(stepId, openEmission(stepId, ctx), event, ctx);
74
+ }
75
+ /**
76
+ * Runs a tool-style body to its return value: awaits a promise, or drains a
77
+ * generator, passing each yield to `onYield`.
78
+ */
79
+ export async function runToReturn(result, onYield) {
80
+ if (!isGenerator(result)) {
81
+ return result;
82
+ }
83
+ while (true) {
84
+ const next = await result.next();
85
+ if (next.done) {
86
+ return next.value;
87
+ }
88
+ await onYield(next.value);
89
+ }
90
+ }
91
+ /**
92
+ * Lets `ctx` accept the final items of every custom item `step` declares, before one
93
+ * is appended or replayed from the ledger. Contexts created from `ctx` later inherit
94
+ * the wider schemas.
95
+ */
96
+ export function allowCustomItems(step, ctx) {
97
+ const items = Object.values(step.customItems ?? {});
98
+ if (items.length === 0 || !(ctx instanceof ContextImpl)) {
99
+ return;
100
+ }
101
+ ctx.allowItems(customItemGates(items));
102
+ }
103
+ /**
104
+ * Every custom item declared anywhere in `step`'s static tree, for a harness to accept
105
+ * before it rebuilds or restores a log that may hold them.
106
+ */
107
+ export function collectCustomItems(step) {
108
+ return [
109
+ ...Object.values(step.customItems ?? {}),
110
+ ...stepChildren(step).flatMap(collectCustomItems),
111
+ ];
112
+ }
113
+ /**
114
+ * Schemas that let a context's item log accept these items' final forms. They gate on
115
+ * `type` and `id` only: the emitter has already checked the fields against `output`.
116
+ */
117
+ export function customItemGates(items) {
118
+ return [
119
+ ...new Set(items.map((item) => item.type)),
120
+ ].map((type) => z.looseObject({
121
+ type: z.literal(type),
122
+ id: z.string(),
123
+ }));
124
+ }
26
125
  /**
27
126
  * Puts a replayed entry's items back on the log. The ones at `emitted` (the entry's
28
127
  * `streamed` indices) keep their mark, so a parent that records on this resumed run
@@ -44,7 +143,104 @@ export function appendReplayed(ctx, items, emitted) {
44
143
  });
45
144
  }
46
145
  //#endregion
47
- //#region Helpers
146
+ //#region Hooks
147
+ function hookConfig(step) {
148
+ const option = step.emitItems;
149
+ if (typeof option !== 'object') {
150
+ return undefined;
151
+ }
152
+ return {
153
+ item: option.item,
154
+ onStart: frameworkCast(option.onStart),
155
+ };
156
+ }
157
+ /**
158
+ * Runs one hook. With an open emission, its yields are events and its return value
159
+ * the final item's fields. Without one it gives text or standard items, and may not
160
+ * yield.
161
+ */
162
+ async function runHook(step, hook, value, ctx) {
163
+ const emission = emissions.get(ctx);
164
+ const result = await runToReturn(hook(value, frameworkCast(ctx)), (event) => emitEvent(step.id, emission ?? noEvents(step.id), event, ctx));
165
+ if (!emission) {
166
+ appendAll(ctx, toItems(frameworkCast(result)));
167
+ return;
168
+ }
169
+ if (result !== undefined) {
170
+ await emitFinal(emission, result, ctx);
171
+ }
172
+ }
173
+ //#endregion
174
+ //#region Emitting
175
+ async function emitEvent(stepId, emission, event, ctx) {
176
+ const schema = emission.item.event;
177
+ if (!schema) {
178
+ noEvents(stepId, emission.item.type);
179
+ }
180
+ const checked = await validateSchema(schema, event);
181
+ if (!checked.success) {
182
+ throw invalid(emission.item.type, 'event', checked.issues);
183
+ }
184
+ emitFrameworkEvent({
185
+ broadcaster: getBroadcaster(frameworkCast(ctx)),
186
+ agentName: ctx.harness.config.name,
187
+ eventType: 'custom_item_event',
188
+ data: {
189
+ id: emission.id,
190
+ type: emission.item.type,
191
+ event: checked.value,
192
+ },
193
+ });
194
+ }
195
+ async function emitFinal(emission, fields, ctx) {
196
+ if (emission.final) {
197
+ throw new NoeticConfigError({
198
+ code: 'CUSTOM_ITEM_ALREADY_FINAL',
199
+ message: `Custom item '${emission.item.type}' (${emission.id}) got a second final item in one dispatch.`,
200
+ hint: 'Return the final fields from one hook only: onStart or onDone, not both.',
201
+ });
202
+ }
203
+ emission.final = true;
204
+ const item = await finalItem(emission.item, emission.id, fields);
205
+ appendEmitted(ctx, item);
206
+ streamItem(ctx, item);
207
+ }
208
+ /** `emitItems: true`: the output is the final item, of a custom type when its `type` names one. */
209
+ async function emitOutput(step, output, ctx) {
210
+ const custom = customOutput(step.customItems, output);
211
+ if (!custom) {
212
+ appendAll(ctx, toItems(outputItems(output)));
213
+ return;
214
+ }
215
+ const { id: _id, type: _type, ...fields } = custom.value;
216
+ const item = await finalItem(custom.item, `item-${crypto.randomUUID()}`, fields);
217
+ appendEmitted(ctx, item);
218
+ streamItem(ctx, item);
219
+ }
220
+ async function finalItem(item, id, fields) {
221
+ const checked = await validateSchema(item.output, fields);
222
+ if (!checked.success) {
223
+ throw invalid(item.type, 'output', checked.issues);
224
+ }
225
+ if (typeof checked.value !== 'object' || checked.value === null) {
226
+ throw invalid(item.type, 'output', [
227
+ {
228
+ message: 'A final item must be an object of fields.',
229
+ },
230
+ ]);
231
+ }
232
+ return frameworkCast({
233
+ ...checked.value,
234
+ id,
235
+ type: item.type,
236
+ });
237
+ }
238
+ function appendAll(ctx, items) {
239
+ for (const item of items) {
240
+ appendEmitted(ctx, item);
241
+ streamItem(ctx, item);
242
+ }
243
+ }
48
244
  function appendEmitted(ctx, item) {
49
245
  if (ctx instanceof ContextImpl) {
50
246
  ctx.appendEmitted(item);
@@ -62,10 +258,70 @@ function streamItem(ctx, item) {
62
258
  },
63
259
  });
64
260
  }
65
- function outputText(output) {
261
+ //#endregion
262
+ //#region Helpers
263
+ function resolveItem(step, name) {
264
+ const item = step.customItems?.[name];
265
+ if (!item) {
266
+ throw new NoeticConfigError({
267
+ code: 'UNKNOWN_CUSTOM_ITEM',
268
+ message: `Step '${step.id}' emits custom item '${name}', which is not in its scope.`,
269
+ hint: 'Declare it on the step (customItems) or, in a JSON workflow, at the document root.',
270
+ });
271
+ }
272
+ return item;
273
+ }
274
+ function openEmission(stepId, ctx) {
275
+ return emissions.get(ctx) ?? noEvents(stepId);
276
+ }
277
+ function noEvents(stepId, type) {
278
+ throw new NoeticConfigError({
279
+ code: 'CUSTOM_ITEM_HAS_NO_EVENTS',
280
+ message: type === undefined
281
+ ? `Step '${stepId}' yielded an event, but its emitItems names no item.`
282
+ : `Step '${stepId}' yielded an event for custom item '${type}', which declares no event schema.`,
283
+ hint: "Name an item with an event schema: emitItems: { item: 'progress' }, with customItem({ type, event, output }).",
284
+ });
285
+ }
286
+ function invalid(type, phase, issues) {
287
+ return new NoeticConfigError({
288
+ code: 'INVALID_CUSTOM_ITEM',
289
+ message: `Custom item '${type}' got an ${phase} that does not match its schema: ${issues.map((issue) => issue.message).join('; ')}`,
290
+ hint: `Make the ${phase} match the '${phase}' schema declared with customItem({ type: '${type}' }).`,
291
+ });
292
+ }
293
+ /**
294
+ * The custom item an output is, when its `type` names one in scope. JSON workflow nodes
295
+ * pass output as text, so a string is read as JSON first.
296
+ */
297
+ function customOutput(items, raw) {
298
+ const output = typeof raw === 'string' ? parseJson(raw) : raw;
299
+ if (typeof output !== 'object' || output === null || !('type' in output)) {
300
+ return undefined;
301
+ }
302
+ const item = Object.values(items ?? {}).find((candidate) => candidate.type === output.type);
303
+ return item
304
+ ? {
305
+ item,
306
+ value: Object.fromEntries(Object.entries(output)),
307
+ }
308
+ : undefined;
309
+ }
310
+ function parseJson(text) {
311
+ try {
312
+ return JSON.parse(text);
313
+ }
314
+ catch {
315
+ return undefined;
316
+ }
317
+ }
318
+ function outputItems(output) {
66
319
  if (typeof output === 'string') {
67
320
  return output;
68
321
  }
322
+ if (typeof output === 'object' && output !== null && 'type' in output) {
323
+ return frameworkCast(output);
324
+ }
69
325
  return output === undefined || output === null ? undefined : JSON.stringify(output);
70
326
  }
71
327
  function toItems(result) {
@@ -88,6 +344,13 @@ function toItems(result) {
88
344
  function isItemList(result) {
89
345
  return Array.isArray(result);
90
346
  }
347
+ function isGenerator(value) {
348
+ return (typeof value === 'object' &&
349
+ value !== null &&
350
+ 'next' in value &&
351
+ typeof value.next === 'function' &&
352
+ (Symbol.asyncIterator in value || Symbol.iterator in value));
353
+ }
91
354
  function assistantMessage(text) {
92
355
  return {
93
356
  id: `emitted-${crypto.randomUUID()}`,
@@ -11,6 +11,7 @@ import { openChildSpan, traceChild } from './child-span.js';
11
11
  import { cloneWithGuard } from './clone-guard.js';
12
12
  import { collectAllTools, deduplicateTools } from './collect-tools.js';
13
13
  import { anchoringAttributes, prepareBandedView } from './context-assembly.js';
14
+ import { emitStepEvent, runToReturn } from './emit-items.js';
14
15
  import { trackUsage } from './message-helpers.js';
15
16
  import { wrapModelError } from './model-error.js';
16
17
  import { parseStructuredOutput } from './structured-output.js';
@@ -30,7 +31,8 @@ export async function executeRunCode(step, input, ctx) {
30
31
  });
31
32
  }
32
33
  try {
33
- return await step.execute(input, ctx);
34
+ // A generator body yields events of the item the step's emitItems names.
35
+ return frameworkCast(await runToReturn(step.execute(input, ctx), (event) => emitStepEvent(step.id, event, ctx)));
34
36
  }
35
37
  catch (e) {
36
38
  // Rethrow cancellation immediately — retrying it would re-run side
@@ -3,7 +3,7 @@ import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broad
3
3
  import { ContextImpl } from '../runtime/context-impl.js';
4
4
  import { REPLAY_KEY_PREFIX } from '../runtime/durable/step-ledger.js';
5
5
  import { DetachedHandleImpl } from '../util/detached-handle.js';
6
- import { appendReplayed, emitStepItems } from './emit-items.js';
6
+ import { allowCustomItems, appendReplayed, beginEmitItems, emitStepItems } from './emit-items.js';
7
7
  import { executeAcpAgent } from './execute-acp-agent.js';
8
8
  import { executeCallModel, executeInvokeTool, executeRunCode, executeSpawn, executeWithContext, } from './execute-action.js';
9
9
  import { executeConditional, executeInParallel, executeLoop, executeSchedule, } from './execute-control.js';
@@ -304,6 +304,8 @@ export async function execute(step, input, ctx) {
304
304
  /* Resume: a previous run that completed this exact step replays its recorded
305
305
  * output instead of re-running it. `ledgerKey`/`ledger` are captured before
306
306
  * dispatch and reused by the record below. */
307
+ // Before replay: a recorded entry may hold this step's custom items.
308
+ allowCustomItems(step, stepCtx);
307
309
  const ledgerKey = resolveLedgerKey(step, input, stepCtx);
308
310
  if (ledgerKey === undefined) {
309
311
  lane?.skipLedger();
@@ -325,6 +327,7 @@ export async function execute(step, input, ctx) {
325
327
  }
326
328
  let result;
327
329
  try {
330
+ await beginEmitItems(step, input, stepCtx);
328
331
  switch (step.kind) {
329
332
  case 'runCode':
330
333
  result = await dispatchViaAdapter(step, input, stepCtx, stepCtx.id, () => executeRunCode(step, input, stepCtx));
@@ -1,3 +1,4 @@
1
+ import type { ZodTypeAny } from 'zod';
1
2
  import type { AgentHarnessContract, Channel, ChannelStore, Context, ContextData, ContextLayer, CwdState, EventBroadcaster, FrontierFrame, FsAdapter, Item, ItemLog, ItemSchemaRegistry, LastLayerUsage, Span, StepMeta, TokenUsage, Tool } from './context-deps.js';
2
3
  import type { StepLedger } from './durable/step-ledger.js';
3
4
  /**
@@ -34,7 +35,7 @@ export declare class ContextImpl implements Context<ContextData> {
34
35
  readonly harness: AgentHarnessContract;
35
36
  readonly layers?: ContextLayer[];
36
37
  unifiedTools?: ReadonlyArray<Tool>;
37
- readonly itemSchemas?: ItemSchemaRegistry;
38
+ itemSchemas?: ItemSchemaRegistry;
38
39
  readonly cwdState: CwdState;
39
40
  /** @internal Event broadcaster for streaming — not part of public Context interface. */
40
41
  readonly _broadcaster?: EventBroadcaster;
@@ -249,6 +250,13 @@ export declare class ContextImpl implements Context<ContextData> {
249
250
  * a replay streams again under the harness's `emitItemsOnReplay`.
250
251
  */
251
252
  emittedIndices(): number[];
253
+ /**
254
+ * @internal
255
+ * Accept items matching `schemas` in this context's log from now on, as a step's
256
+ * custom items need. Contexts created from this one afterwards inherit the wider
257
+ * registry; a lane widens the context it views.
258
+ */
259
+ allowItems(schemas: ReadonlyArray<ZodTypeAny>): void;
252
260
  /**
253
261
  * @internal
254
262
  * Append an item a step emitted (`step.emitItems`), marking it in this lane's record
@@ -414,6 +414,19 @@ export class ContextImpl {
414
414
  ]
415
415
  : []);
416
416
  }
417
+ /**
418
+ * @internal
419
+ * Accept items matching `schemas` in this context's log from now on, as a step's
420
+ * custom items need. Contexts created from this one afterwards inherit the wider
421
+ * registry; a lane widens the context it views.
422
+ */
423
+ allowItems(schemas) {
424
+ const registry = (this.itemSchemas ?? defaultItemSchemaRegistry).extend({
425
+ items: schemas,
426
+ });
427
+ this.itemSchemas = registry;
428
+ this.log.useSchemas(registry);
429
+ }
417
430
  /**
418
431
  * @internal
419
432
  * Append an item a step emitted (`step.emitItems`), marking it in this lane's record
@@ -233,7 +233,7 @@ export class StepLedger {
233
233
  /** Recovered entries, by path. */
234
234
  replayable = new Map();
235
235
  /** Sequence number holding each live entry, recovered or recorded, by path. */
236
- live;
236
+ live = new LiveEntries();
237
237
  /** Sequence number the next recorded entry takes. */
238
238
  seq;
239
239
  store;
@@ -250,7 +250,6 @@ export class StepLedger {
250
250
  this.executionId = opts.executionId;
251
251
  this.store = opts.store;
252
252
  this.retention = resolveStepLedgerRetention(opts.retention);
253
- this.live = new Map();
254
253
  this.seq = 0;
255
254
  if (opts.recovered) {
256
255
  this.adopt(opts.recovered);
@@ -342,7 +341,7 @@ export class StepLedger {
342
341
  await this.deleteSeq(replaced);
343
342
  }
344
343
  if (!entry.path.startsWith(REPLAY_KEY_PREFIX)) {
345
- await this.prune((path) => isBeneath(path, entry.path));
344
+ await this.prune(this.live.beneath(entry.path));
346
345
  }
347
346
  }
348
347
  /**
@@ -351,7 +350,7 @@ export class StepLedger {
351
350
  * `key:` entries stay — they are keyed by content, and a later run may ask the same.
352
351
  */
353
352
  async dropPaths() {
354
- await this.prune((path) => !path.startsWith(REPLAY_KEY_PREFIX));
353
+ await this.prune(this.live.paths().filter((path) => !path.startsWith(REPLAY_KEY_PREFIX)));
355
354
  for (const path of [
356
355
  ...this.replayable.keys(),
357
356
  ]) {
@@ -361,10 +360,9 @@ export class StepLedger {
361
360
  }
362
361
  }
363
362
  async prune(dead) {
364
- for (const [path, seq] of [
365
- ...this.live,
366
- ]) {
367
- if (!dead(path)) {
363
+ for (const path of dead) {
364
+ const seq = this.live.get(path);
365
+ if (seq === undefined) {
368
366
  continue;
369
367
  }
370
368
  this.live.delete(path);
@@ -414,13 +412,7 @@ export class StepLedger {
414
412
  if (this.live.size < this.retention.maxEntries || path.startsWith(REPLAY_KEY_PREFIX)) {
415
413
  return this.live.size;
416
414
  }
417
- let beneath = 0;
418
- for (const key of this.live.keys()) {
419
- if (isBeneath(key, path)) {
420
- beneath += 1;
421
- }
422
- }
423
- return this.live.size - beneath;
415
+ return this.live.size - this.live.beneath(path).length;
424
416
  }
425
417
  /** One warning per reason per execution — a long run would otherwise flood the log. */
426
418
  warnOnFirstDrop(count, message) {
@@ -440,4 +432,77 @@ function matches(entry, step) {
440
432
  function isBeneath(path, parent) {
441
433
  return path.startsWith(`${parent}/`) || path.startsWith(`${parent}[`);
442
434
  }
435
+ /**
436
+ * Live entries by path, with the paths also kept sorted. Everything beneath a path
437
+ * starts with `<path>/` or `<path>[`, so in sorted order each is one contiguous run,
438
+ * found by binary search. Scanning every live entry instead made each record cost the
439
+ * whole live set — in deep recursion, where the live set and the paths both grow with
440
+ * depth, that was cubic.
441
+ */
442
+ class LiveEntries {
443
+ seqs = new Map();
444
+ sorted = [];
445
+ get size() {
446
+ return this.seqs.size;
447
+ }
448
+ get(path) {
449
+ return this.seqs.get(path);
450
+ }
451
+ has(path) {
452
+ return this.seqs.has(path);
453
+ }
454
+ set(path, seq) {
455
+ if (!this.seqs.has(path)) {
456
+ this.sorted.splice(lowerBound(this.sorted, path), 0, path);
457
+ }
458
+ this.seqs.set(path, seq);
459
+ }
460
+ delete(path) {
461
+ if (!this.seqs.delete(path)) {
462
+ return;
463
+ }
464
+ this.sorted.splice(lowerBound(this.sorted, path), 1);
465
+ }
466
+ clear() {
467
+ this.seqs.clear();
468
+ this.sorted.length = 0;
469
+ }
470
+ paths() {
471
+ return [
472
+ ...this.sorted,
473
+ ];
474
+ }
475
+ /** Every live path beneath `parent`. */
476
+ beneath(parent) {
477
+ const found = [];
478
+ for (const prefix of [
479
+ `${parent}/`,
480
+ `${parent}[`,
481
+ ]) {
482
+ for (let i = lowerBound(this.sorted, prefix); i < this.sorted.length; i++) {
483
+ const path = this.sorted[i];
484
+ if (!path?.startsWith(prefix)) {
485
+ break;
486
+ }
487
+ found.push(path);
488
+ }
489
+ }
490
+ return found;
491
+ }
492
+ }
493
+ /** Index of the first element of sorted `list` not less than `value`. */
494
+ function lowerBound(list, value) {
495
+ let low = 0;
496
+ let high = list.length;
497
+ while (low < high) {
498
+ const mid = (low + high) >>> 1;
499
+ if ((list[mid] ?? '') < value) {
500
+ low = mid + 1;
501
+ }
502
+ else {
503
+ high = mid;
504
+ }
505
+ }
506
+ return low;
507
+ }
443
508
  //#endregion
@@ -1,9 +1,15 @@
1
1
  import type { Item, ItemLog, ItemSchemaRegistry } from '@noetic-tools/types';
2
2
  export declare class ItemLogImpl implements ItemLog {
3
- private readonly itemSchemas;
3
+ private itemSchemas;
4
4
  private readonly _items;
5
5
  private _frozenCache;
6
6
  constructor(itemSchemas?: ItemSchemaRegistry);
7
+ /**
8
+ * @internal
9
+ * Validate later appends against `registry`, a superset of the current one: a
10
+ * context that learns of new item types (a step's custom items) widens its log.
11
+ */
12
+ useSchemas(registry: ItemSchemaRegistry): void;
7
13
  get items(): ReadonlyArray<Item>;
8
14
  /**
9
15
  * @internal
@@ -6,6 +6,14 @@ export class ItemLogImpl {
6
6
  constructor(itemSchemas = defaultItemSchemaRegistry) {
7
7
  this.itemSchemas = itemSchemas;
8
8
  }
9
+ /**
10
+ * @internal
11
+ * Validate later appends against `registry`, a superset of the current one: a
12
+ * context that learns of new item types (a step's custom items) widens its log.
13
+ */
14
+ useSchemas(registry) {
15
+ this.itemSchemas = registry;
16
+ }
9
17
  get items() {
10
18
  if (!this._frozenCache) {
11
19
  this._frozenCache = Object.freeze([
@@ -148,6 +148,14 @@ export async function* buildItemStream(broadcaster, itemSchemas = defaultItemSch
148
148
  let roundOffset = 0;
149
149
  for await (const event of broadcaster) {
150
150
  if (event.source === 'framework') {
151
+ // A custom item's event streams in progress under the id its final item takes.
152
+ if (event.type.endsWith(':custom_item_event')) {
153
+ yield frameworkCast({
154
+ ...event.data,
155
+ isComplete: false,
156
+ });
157
+ continue;
158
+ }
151
159
  if (event.type.endsWith(':item_appended') &&
152
160
  typeof event.data.item === 'object' &&
153
161
  event.data.item !== null) {
@@ -3,5 +3,5 @@
3
3
  * consumers can validate workflow documents without importing core.
4
4
  * This barrel keeps core's public and intra-core import paths unchanged.
5
5
  */
6
- export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, OutputCodecRef, RouteSwitchWorkflowNode, RunCodeWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowEmitItems, WorkflowGraph, WorkflowNode, WorkflowReplayKey, } from '@noetic-tools/types';
6
+ export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, OutputCodecRef, RouteSwitchWorkflowNode, RunCodeWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowCustomItem, WorkflowDocument, WorkflowEmitItems, WorkflowGraph, WorkflowNode, WorkflowReplayKey, } from '@noetic-tools/types';
7
7
  export { MergeStrategy, MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDocumentSchema, WorkflowNodeSchema, walkWorkflow, workflowDepth, workflowGraph, } from '@noetic-tools/types';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.15.0",
3
+ "version": "5.16.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.10.0",
72
- "@noetic-tools/types": "^3.13.0",
72
+ "@noetic-tools/types": "^3.14.0",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "jsonata": "2.2.2",