@noetic-tools/core 5.16.1 → 5.18.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 (45) hide show
  1. package/dist/conditions/conditions.js +1 -0
  2. package/dist/harness/agent-harness.d.ts +54 -9
  3. package/dist/harness/agent-harness.js +192 -23
  4. package/dist/harness/decide-call.d.ts +3 -0
  5. package/dist/harness/decide-call.js +45 -12
  6. package/dist/harness/deps/adapters.d.ts +1 -1
  7. package/dist/harness/deps/adapters.js +1 -1
  8. package/dist/harness/deps/runtime.d.ts +4 -2
  9. package/dist/harness/deps/runtime.js +4 -2
  10. package/dist/harness/deps/types.d.ts +1 -1
  11. package/dist/harness/model-call.d.ts +5 -1
  12. package/dist/harness/model-call.js +107 -21
  13. package/dist/harness/model-price.d.ts +35 -0
  14. package/dist/harness/model-price.js +81 -0
  15. package/dist/harness/model-rounds.d.ts +2 -0
  16. package/dist/harness/model-rounds.js +5 -1
  17. package/dist/harness/spend.d.ts +138 -0
  18. package/dist/harness/spend.js +494 -0
  19. package/dist/harness/steer-inbox.d.ts +5 -0
  20. package/dist/harness/steer-inbox.js +45 -5
  21. package/dist/harness/thread-record.d.ts +17 -5
  22. package/dist/harness/thread-record.js +54 -4
  23. package/dist/index.d.ts +5 -1
  24. package/dist/index.js +2 -0
  25. package/dist/interpreter/execute-action.js +60 -11
  26. package/dist/interpreter/execute-control.js +1 -0
  27. package/dist/interpreter/execute-decide.js +18 -0
  28. package/dist/interpreter/execute.js +9 -0
  29. package/dist/runtime/context-impl.d.ts +1 -0
  30. package/dist/runtime/context-impl.js +1 -0
  31. package/dist/runtime/drain.d.ts +77 -0
  32. package/dist/runtime/drain.js +268 -0
  33. package/dist/runtime/durable/session-store.d.ts +12 -0
  34. package/dist/runtime/durable/session-store.js +16 -0
  35. package/dist/runtime/durable/spend-log.d.ts +38 -0
  36. package/dist/runtime/durable/spend-log.js +65 -0
  37. package/dist/runtime/durable/step-ledger.d.ts +6 -0
  38. package/dist/runtime/durable/step-ledger.js +3 -2
  39. package/dist/runtime/session-runner.d.ts +5 -3
  40. package/dist/runtime/session-runner.js +9 -4
  41. package/dist/until/predicates.d.ts +5 -1
  42. package/dist/until/predicates.js +12 -7
  43. package/dist/util/status-code.d.ts +5 -0
  44. package/dist/util/status-code.js +8 -0
  45. package/package.json +3 -3
@@ -7,6 +7,9 @@
7
7
  * arrive again — a host with at-least-once delivery re-sends what it never saw
8
8
  * answered — the turn resumes on its recorded execution: finished steps replay and
9
9
  * the turn continues from the step that was cut off.
10
+ *
11
+ * Steers sent into a running turn are kept too, until the turn ends, so a turn that
12
+ * resumes on a new harness still applies the steers it had not applied yet.
10
13
  */
11
14
  import type { StorageAdapter } from '@noetic-tools/context';
12
15
  import { z } from 'zod';
@@ -23,6 +26,15 @@ declare const SessionRecordSchema: z.ZodObject<{
23
26
  executionId: z.ZodString;
24
27
  messageIds: z.ZodArray<z.ZodString>;
25
28
  }, z.core.$strip>>;
29
+ steers: z.ZodOptional<z.ZodArray<z.ZodObject<{
30
+ id: z.ZodString;
31
+ input: z.ZodUnknown;
32
+ deliveryMode: z.ZodEnum<{
33
+ "between-rounds": "between-rounds";
34
+ "next-item": "next-item";
35
+ }>;
36
+ enqueuedAt: z.ZodNumber;
37
+ }, z.core.$strip>>>;
26
38
  }, z.core.$strip>;
27
39
  /** @internal One thread's stored session. */
28
40
  export type SessionRecord = z.infer<typeof SessionRecordSchema>;
@@ -7,6 +7,9 @@
7
7
  * arrive again — a host with at-least-once delivery re-sends what it never saw
8
8
  * answered — the turn resumes on its recorded execution: finished steps replay and
9
9
  * the turn continues from the step that was cut off.
10
+ *
11
+ * Steers sent into a running turn are kept too, until the turn ends, so a turn that
12
+ * resumes on a new harness still applies the steers it had not applied yet.
10
13
  */
11
14
  import { z } from 'zod';
12
15
  //#region Schema
@@ -31,6 +34,19 @@ const SessionRecordSchema = z.object({
31
34
  messageIds: z.array(z.string()),
32
35
  })
33
36
  .optional(),
37
+ /** Steers sent into the turn in flight, in arrival order. */
38
+ steers: z
39
+ .array(z.object({
40
+ id: z.string(),
41
+ /** The `execute()` input: a string, an item, or items. */
42
+ input: z.unknown(),
43
+ deliveryMode: z.enum([
44
+ 'between-rounds',
45
+ 'next-item',
46
+ ]),
47
+ enqueuedAt: z.number(),
48
+ }))
49
+ .optional(),
34
50
  });
35
51
  /** @internal */
36
52
  export function createSessionStore(storage) {
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The spend log: one record per paid provider call, written before the call is sent
3
+ * and deleted once its bill is known (spec 23 § Paid dispatches).
4
+ *
5
+ * Records live under `spend:<id>`, outside the `execution:<id>:` prefix, so clearing a
6
+ * checkpoint or abandoning a turn never discards evidence that money was spent.
7
+ */
8
+ import type { StorageAdapter } from '@noetic-tools/context';
9
+ import { z } from 'zod';
10
+ /** @internal A dispatch record as stored. */
11
+ export declare const DispatchRecordSchema: z.ZodObject<{
12
+ id: z.ZodString;
13
+ kind: z.ZodEnum<{
14
+ model: "model";
15
+ decide: "decide";
16
+ }>;
17
+ model: z.ZodString;
18
+ requestHash: z.ZodString;
19
+ inputTokens: z.ZodNumber;
20
+ maxOutputTokens: z.ZodOptional<z.ZodNumber>;
21
+ executionId: z.ZodOptional<z.ZodString>;
22
+ threadId: z.ZodOptional<z.ZodString>;
23
+ path: z.ZodOptional<z.ZodString>;
24
+ generationId: z.ZodOptional<z.ZodString>;
25
+ sentAt: z.ZodString;
26
+ }, z.core.$strip>;
27
+ /** @internal */
28
+ export type DispatchRecord = z.infer<typeof DispatchRecordSchema>;
29
+ /** @internal */
30
+ export interface SpendLog {
31
+ put(record: DispatchRecord): Promise<void>;
32
+ get(id: string): Promise<DispatchRecord | undefined>;
33
+ remove(id: string): Promise<void>;
34
+ /** Every record, oldest first. Unreadable rows are skipped. */
35
+ list(): Promise<DispatchRecord[]>;
36
+ }
37
+ /** @internal */
38
+ export declare function createSpendLog(storage: StorageAdapter): SpendLog;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The spend log: one record per paid provider call, written before the call is sent
3
+ * and deleted once its bill is known (spec 23 § Paid dispatches).
4
+ *
5
+ * Records live under `spend:<id>`, outside the `execution:<id>:` prefix, so clearing a
6
+ * checkpoint or abandoning a turn never discards evidence that money was spent.
7
+ */
8
+ import { storageGetMany } from '@noetic-tools/context';
9
+ import { z } from 'zod';
10
+ //#region Schema
11
+ const SPEND_PREFIX = 'spend:';
12
+ /** @internal A dispatch record as stored. */
13
+ export const DispatchRecordSchema = z.object({
14
+ id: z.string().min(1),
15
+ kind: z.enum([
16
+ 'model',
17
+ 'decide',
18
+ ]),
19
+ model: z.string(),
20
+ requestHash: z.string(),
21
+ inputTokens: z.number(),
22
+ maxOutputTokens: z.number().optional(),
23
+ executionId: z.string().optional(),
24
+ threadId: z.string().optional(),
25
+ path: z.string().optional(),
26
+ generationId: z.string().optional(),
27
+ sentAt: z.string(),
28
+ });
29
+ /** @internal */
30
+ export function createSpendLog(storage) {
31
+ return {
32
+ put: async (record) => {
33
+ await storage.set(keyOf(record.id), record);
34
+ },
35
+ get: async (id) => parse(await storage.get(keyOf(id))),
36
+ remove: async (id) => {
37
+ await storage.delete(keyOf(id));
38
+ },
39
+ list: async () => {
40
+ const keys = await storage.list(SPEND_PREFIX);
41
+ const raws = await storageGetMany(storage, keys);
42
+ const records = [];
43
+ for (const [key, raw] of raws) {
44
+ const record = parse(raw);
45
+ if (!record) {
46
+ console.warn(`SpendLog: skipping unreadable dispatch record "${key}"`);
47
+ continue;
48
+ }
49
+ records.push(record);
50
+ }
51
+ return records.sort((a, b) => a.sentAt.localeCompare(b.sentAt));
52
+ },
53
+ };
54
+ }
55
+ function keyOf(id) {
56
+ return `${SPEND_PREFIX}${id}`;
57
+ }
58
+ function parse(raw) {
59
+ if (raw === null || raw === undefined) {
60
+ return undefined;
61
+ }
62
+ const parsed = DispatchRecordSchema.safeParse(raw);
63
+ return parsed.success ? parsed.data : undefined;
64
+ }
65
+ //#endregion
@@ -98,6 +98,12 @@ export declare function resolveStepLedgerRetention(retention?: StepLedgerRetenti
98
98
  * and its round-tripped copy, so a resumed run hashes the same inputs the first run did.
99
99
  */
100
100
  export declare function hashStepInput(input: unknown): string | undefined;
101
+ /**
102
+ * @internal
103
+ * 53-bit string hash (cyrb53, public domain: https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js).
104
+ * Not cryptographic — it tells "same input" from "changed input", nothing more.
105
+ */
106
+ export declare function hashText(text: string): string;
101
107
  /** Storage key prefix owning every ledger entry for one execution. */
102
108
  export declare function stepLedgerPrefix(executionId: string): string;
103
109
  /**
@@ -126,13 +126,14 @@ export function hashStepInput(input) {
126
126
  catch {
127
127
  return undefined;
128
128
  }
129
- return cyrb53(json ?? 'undefined');
129
+ return hashText(json ?? 'undefined');
130
130
  }
131
131
  /**
132
+ * @internal
132
133
  * 53-bit string hash (cyrb53, public domain: https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js).
133
134
  * Not cryptographic — it tells "same input" from "changed input", nothing more.
134
135
  */
135
- function cyrb53(text) {
136
+ export function hashText(text) {
136
137
  let h1 = 0xdeadbeef;
137
138
  let h2 = 0x41c6ce57;
138
139
  for (let i = 0; i < text.length; i++) {
@@ -40,7 +40,7 @@ export interface SessionRunnerOpts {
40
40
  /**
41
41
  * @internal
42
42
  *
43
- * Per-thread runner. Drains the MessageQueue and drives turns on the shared
43
+ * Per-thread runner. Works through the MessageQueue and drives turns on the shared
44
44
  * session broadcaster. Emits `turn_started` / `turn_completed` /
45
45
  * `inbox_injected` framework events so consumers can correlate queued
46
46
  * messages with the turn that delivered them.
@@ -78,6 +78,8 @@ export declare class SessionRunner {
78
78
  private readonly responseWaiters;
79
79
  constructor(opts: SessionRunnerOpts);
80
80
  getStatus(): HarnessStatus;
81
+ /** The running turn's context, if a turn is running. */
82
+ get context(): Context | undefined;
81
83
  /** Queue a message. A steer that arrives mid-turn is announced first, so
82
84
  * `steer_accepted` always precedes the `inbox_injected` that applies it. */
83
85
  enqueue(message: QueuedMessage): void;
@@ -96,9 +98,9 @@ export declare class SessionRunner {
96
98
  /** Cancel the in-flight turn. Does NOT re-kick — callers that want restart
97
99
  * behaviour should enqueue a message before/after calling abort. */
98
100
  abort(reason?: string): Promise<void>;
99
- /** Start the drain loop if not already running. Safe to call many times. */
101
+ /** Start the queue loop if not already running. Safe to call many times. */
100
102
  kick(): void;
101
- private drain;
103
+ private runQueue;
102
104
  private runOneTurn;
103
105
  /**
104
106
  * Add what the turn spent to the session's totals, before anyone waiting on the turn
@@ -16,7 +16,7 @@ function mergeInputsToItems(messages) {
16
16
  /**
17
17
  * @internal
18
18
  *
19
- * Per-thread runner. Drains the MessageQueue and drives turns on the shared
19
+ * Per-thread runner. Works through the MessageQueue and drives turns on the shared
20
20
  * session broadcaster. Emits `turn_started` / `turn_completed` /
21
21
  * `inbox_injected` framework events so consumers can correlate queued
22
22
  * messages with the turn that delivered them.
@@ -67,6 +67,10 @@ export class SessionRunner {
67
67
  getStatus() {
68
68
  return this.status;
69
69
  }
70
+ /** The running turn's context, if a turn is running. */
71
+ get context() {
72
+ return this.currentCtx;
73
+ }
70
74
  /** Queue a message. A steer that arrives mid-turn is announced first, so
71
75
  * `steer_accepted` always precedes the `inbox_injected` that applies it. */
72
76
  enqueue(message) {
@@ -144,7 +148,7 @@ export class SessionRunner {
144
148
  // observe it via the broadcaster / lastError, not the abort() return.
145
149
  });
146
150
  }
147
- /** Start the drain loop if not already running. Safe to call many times. */
151
+ /** Start the queue loop if not already running. Safe to call many times. */
148
152
  kick() {
149
153
  if (this.loopPromise) {
150
154
  return;
@@ -152,7 +156,7 @@ export class SessionRunner {
152
156
  if (this.queue.size === 0) {
153
157
  return;
154
158
  }
155
- this.loopPromise = this.drain().finally(() => {
159
+ this.loopPromise = this.runQueue().finally(() => {
156
160
  this.loopPromise = undefined;
157
161
  // If messages arrived during finally, run again.
158
162
  if (this.queue.size > 0) {
@@ -160,7 +164,7 @@ export class SessionRunner {
160
164
  }
161
165
  });
162
166
  }
163
- async drain() {
167
+ async runQueue() {
164
168
  while (this.queue.size > 0) {
165
169
  const messages = this.queue.drainAll();
166
170
  if (messages.length === 0) {
@@ -355,6 +359,7 @@ function buildResponse(text, ctx) {
355
359
  },
356
360
  cost: ctx.cost > 0 ? ctx.cost : undefined,
357
361
  billedCost: ctx.billedCost > 0 ? ctx.billedCost : undefined,
362
+ heldCost: ctx.heldCost > 0 ? ctx.heldCost : undefined,
358
363
  text,
359
364
  lastLayerUsage: ctx.lastLayerUsage,
360
365
  };
@@ -24,7 +24,11 @@ export interface ConvergeConfig {
24
24
  export declare const until: {
25
25
  /** Stops the loop after `n` steps. @public */
26
26
  maxSteps(n: number): Until;
27
- /** Stops the loop when accumulated cost reaches `usd`. @public */
27
+ /**
28
+ * Stops the loop when accumulated cost, plus spend held for cut-off calls with no
29
+ * settled bill, reaches `usd`. Counting the hold keeps a resumed run from spending
30
+ * what its cut-off attempt may already have spent. @public
31
+ */
28
32
  maxCost(usd: number): Until;
29
33
  /** Stops the loop when elapsed time reaches `ms` milliseconds. @public */
30
34
  maxDuration(ms: number): Until;
@@ -14,14 +14,19 @@ export const until = {
14
14
  reason: snap.stepCount >= n ? `Reached max steps (${n})` : undefined,
15
15
  });
16
16
  },
17
- /** Stops the loop when accumulated cost reaches `usd`. @public */
17
+ /**
18
+ * Stops the loop when accumulated cost, plus spend held for cut-off calls with no
19
+ * settled bill, reaches `usd`. Counting the hold keeps a resumed run from spending
20
+ * what its cut-off attempt may already have spent. @public
21
+ */
18
22
  maxCost(usd) {
19
- return (snap) => ({
20
- stop: snap.cost >= usd,
21
- reason: snap.cost >= usd
22
- ? `Cost $${snap.cost.toFixed(2)} exceeded budget $${usd.toFixed(2)}`
23
- : undefined,
24
- });
23
+ return (snap) => {
24
+ const spent = snap.cost + (snap.heldCost ?? 0);
25
+ return {
26
+ stop: spent >= usd,
27
+ reason: spent >= usd ? `Cost $${spent.toFixed(2)} exceeded budget $${usd.toFixed(2)}` : undefined,
28
+ };
29
+ };
25
30
  },
26
31
  /** Stops the loop when elapsed time reaches `ms` milliseconds. @public */
27
32
  maxDuration(ms) {
@@ -1,2 +1,7 @@
1
1
  /** The HTTP status an SDK error carries, when it carries one. */
2
2
  export declare function statusOf(e: unknown): number | undefined;
3
+ /**
4
+ * Whether the provider answered with an error status, so it generated and billed
5
+ * nothing. A 2xx whose body failed to parse also carries a status, but was billed.
6
+ */
7
+ export declare function isErrorStatus(e: unknown): boolean;
@@ -5,3 +5,11 @@ export function statusOf(e) {
5
5
  }
6
6
  return typeof e.statusCode === 'number' ? e.statusCode : undefined;
7
7
  }
8
+ /**
9
+ * Whether the provider answered with an error status, so it generated and billed
10
+ * nothing. A 2xx whose body failed to parse also carries a status, but was billed.
11
+ */
12
+ export function isErrorStatus(e) {
13
+ const status = statusOf(e);
14
+ return status !== undefined && status >= 400;
15
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.16.1",
3
+ "version": "5.18.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",
@@ -68,8 +68,8 @@
68
68
  }
69
69
  },
70
70
  "dependencies": {
71
- "@noetic-tools/context": "^1.10.0",
72
- "@noetic-tools/types": "^3.14.0",
71
+ "@noetic-tools/context": "^1.11.0",
72
+ "@noetic-tools/types": "^3.16.0",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "jsonata": "2.2.2",