@zenera/neo 1.3.30 → 1.3.31

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.
package/dist/failure.d.ts CHANGED
@@ -49,11 +49,21 @@ export declare class ProviderError extends Error {
49
49
  readonly detail: string;
50
50
  /** the HTTP status, wherever the SDK or the body left it */
51
51
  readonly status?: number;
52
+ /** the vendor's (or gateway's) symbol for the refusal — `invalid_argument`, `budget_exceeded` */
53
+ readonly code?: string;
52
54
  readonly attempts: number;
53
55
  readonly elapsedMs: number;
54
56
  readonly chunks?: number;
55
- constructor(site: CallSite, detail: string, status: number | undefined, cause: unknown, tried?: Attempted);
57
+ constructor(site: CallSite, detail: string, status: number | undefined, cause: unknown, tried?: Attempted, code?: string);
56
58
  }
59
+ /**
60
+ * Whether a model call was refused because the gateway's spending limit is
61
+ * used up — Bifrost answers `402` with `type: budget_exceeded` before it calls
62
+ * any provider, so nothing was spent or streamed. Read off the symbol when the
63
+ * body kept it, and off the sentence when an SDK dropped the body's top level
64
+ * (the OpenAI SDK keeps only `error`, where Bifrost's message is).
65
+ */
66
+ export declare function isOutOfCredits(err: unknown): boolean;
57
67
  /** Runs one provider call, and makes sure a refusal says what it refused. */
58
68
  export declare function called<T>(site: CallSite, run: () => Promise<T>): Promise<T>;
59
69
  /**
@@ -78,5 +88,6 @@ export declare function failed(site: CallSite, err: unknown, tried?: Attempted):
78
88
  export declare function explain(err: unknown): {
79
89
  detail: string;
80
90
  status?: number;
91
+ code?: string;
81
92
  };
82
93
  //# sourceMappingURL=failure.d.ts.map
package/dist/failure.js CHANGED
@@ -8,20 +8,37 @@ export class ProviderError extends Error {
8
8
  detail;
9
9
  /** the HTTP status, wherever the SDK or the body left it */
10
10
  status;
11
+ /** the vendor's (or gateway's) symbol for the refusal — `invalid_argument`, `budget_exceeded` */
12
+ code;
11
13
  attempts;
12
14
  elapsedMs;
13
15
  chunks;
14
- constructor(site, detail, status, cause, tried = ONCE) {
16
+ constructor(site, detail, status, cause, tried = ONCE, code) {
15
17
  super(`${site.doing} failed — ${where(site)}: ${detail}${trailer(tried)}`, { cause });
16
18
  this.name = 'ProviderError';
17
19
  this.site = site;
18
20
  this.detail = detail;
19
21
  this.status = status;
22
+ this.code = code;
20
23
  this.attempts = tried.attempts;
21
24
  this.elapsedMs = tried.elapsedMs;
22
25
  this.chunks = tried.chunks;
23
26
  }
24
27
  }
28
+ /**
29
+ * Whether a model call was refused because the gateway's spending limit is
30
+ * used up — Bifrost answers `402` with `type: budget_exceeded` before it calls
31
+ * any provider, so nothing was spent or streamed. Read off the symbol when the
32
+ * body kept it, and off the sentence when an SDK dropped the body's top level
33
+ * (the OpenAI SDK keeps only `error`, where Bifrost's message is).
34
+ */
35
+ export function isOutOfCredits(err) {
36
+ const { status, code, detail } = err instanceof ProviderError ? err : explain(err);
37
+ if (code?.toLowerCase() === 'budget_exceeded') {
38
+ return true;
39
+ }
40
+ return status === 402 && /budget exceeded/i.test(detail);
41
+ }
25
42
  /**
26
43
  * What the failure cost, when that is worth a person's attention. A call that
27
44
  * failed at once and was never retried spent nothing worth reporting, and the
@@ -120,8 +137,8 @@ export function failed(site, err, tried = ONCE) {
120
137
  (typeof name === 'string' && INTERRUPTED.has(name))) {
121
138
  return err;
122
139
  }
123
- const { detail, status } = explain(err);
124
- return new ProviderError(site, detail, status, err, tried);
140
+ const { detail, status, code } = explain(err);
141
+ return new ProviderError(site, detail, status, err, tried, code);
125
142
  }
126
143
  /** Bodies nest at most this deep before the unwrapping is the bug. */
127
144
  const MAX_UNWRAP = 4;
@@ -168,7 +185,7 @@ export function explain(err) {
168
185
  const because = blamed(err, text);
169
186
  text = because ? (text ? `${text} — ${because}` : because) : text;
170
187
  }
171
- return { detail: mark(text || String(err), status, code), status };
188
+ return { detail: mark(text || String(err), status, code), status, code };
172
189
  }
173
190
  const messageOf = (err) => err instanceof Error ? err.message : typeof err === 'string' ? err : String(err);
174
191
  /** The vendor's word for the kind of refusal, off the error object itself. */
@@ -252,7 +269,11 @@ function body(text) {
252
269
  ? said.code
253
270
  : typeof said.type === 'string'
254
271
  ? said.type
255
- : undefined,
272
+ : // Bifrost keeps the kind beside `error`, not in it:
273
+ // `{"type":"budget_exceeded","error":{"message":…}}`.
274
+ typeof root.type === 'string' && root.type !== 'error'
275
+ ? root.type
276
+ : undefined,
256
277
  about: aboutOf(said.details) ?? (typeof said.param === 'string' ? said.param : undefined),
257
278
  };
258
279
  }
package/dist/kernel.d.ts CHANGED
@@ -139,6 +139,15 @@ export declare function applySuspension(state: AgentState, call: {
139
139
  callId: string;
140
140
  name: string;
141
141
  }, spec: SuspendSpec, at: string): AgentState;
142
+ /**
143
+ * Records that the next model call waits: it was refused before answering, and
144
+ * the host chose to wait (see `RunnerOptions.onModelError`). Nothing else
145
+ * changes, so resuming simply makes the call again.
146
+ */
147
+ export declare function applyModelSuspension(state: AgentState, call: {
148
+ callId: string;
149
+ name: string;
150
+ }, spec: SuspendSpec, at: string): AgentState;
142
151
  /** Lets a suspended call run again: what it waited for is done. */
143
152
  export declare function releaseSuspension(state: AgentState, callId: string): AgentState;
144
153
  /** Records a memory recall or mutation performed by the driver. */
package/dist/kernel.js CHANGED
@@ -672,6 +672,19 @@ export function applySuspension(state, call, spec, at) {
672
672
  const entry = { callId: call.callId, name: call.name, at, ...spec };
673
673
  return { ...state, suspended: [...others, entry] };
674
674
  }
675
+ /**
676
+ * Records that the next model call waits: it was refused before answering, and
677
+ * the host chose to wait (see `RunnerOptions.onModelError`). Nothing else
678
+ * changes, so resuming simply makes the call again.
679
+ */
680
+ export function applyModelSuspension(state, call, spec, at) {
681
+ if (state.pendingToolCalls.length) {
682
+ throw new Error(`run ${state.runId} has tool calls pending; it is not at a model call`);
683
+ }
684
+ const others = (state.suspended ?? []).filter((s) => s.callId !== call.callId);
685
+ const entry = { callId: call.callId, name: call.name, at, ...spec, site: 'llm' };
686
+ return { ...state, suspended: [...others, entry] };
687
+ }
675
688
  /** Lets a suspended call run again: what it waited for is done. */
676
689
  export function releaseSuspension(state, callId) {
677
690
  const suspended = (state.suspended ?? []).filter((s) => s.callId !== callId);
package/dist/runner.d.ts CHANGED
@@ -11,7 +11,7 @@ import { Services } from './services.ts';
11
11
  import { type SkillProvider } from './skills.ts';
12
12
  import { type AgentState } from './state.ts';
13
13
  import { type HandoffNode, type TrajectoryNode } from './trajectory.ts';
14
- import { type Input, type ResumeAnswer, type TokenUsage } from './types.ts';
14
+ import { type Input, type ResumeAnswer, type SuspendSpec, type TokenUsage } from './types.ts';
15
15
  /**
16
16
  * Collapsing history is two decisions, and they belong on different sides of
17
17
  * the I/O line: *which* nodes go (pure, so the kernel can stay pure) and *how*
@@ -60,7 +60,25 @@ export interface RunnerOptions<TCtx = unknown> {
60
60
  */
61
61
  recordRequests?: boolean;
62
62
  clock?: IdClock;
63
+ /**
64
+ * Asked when a model call fails, before the run fails with it. Returning a
65
+ * `SuspendSpec` suspends the run at that call instead (`site: 'llm'` in
66
+ * `state.suspended`); resuming makes the call again. For refusals that
67
+ * something outside the run can cure — a spending limit topped up. Only
68
+ * asked on the trunk, never in a fork branch, and only when nothing of the
69
+ * answer was streamed yet; an abort is never offered.
70
+ */
71
+ onModelError?: ModelErrorHandler;
72
+ }
73
+ /** What `onModelError` is told about the call that failed. */
74
+ export interface ModelErrorContext {
75
+ /** the suspension's id if it suspends: `llm:<n>`, `n` being the model calls made so far */
76
+ callId: string;
77
+ /** the model's id */
78
+ model: string;
79
+ state: AgentState;
63
80
  }
81
+ export type ModelErrorHandler = (err: unknown, ctx: ModelErrorContext) => SuspendSpec | undefined | Promise<SuspendSpec | undefined>;
64
82
  export interface RunOptions<T = string, TCtx = unknown> {
65
83
  context?: TCtx;
66
84
  /** typed result: the schema drives both validation and `RunResult<T>` */
package/dist/runner.js CHANGED
@@ -7,7 +7,7 @@ import { renderRecollection } from "./memory/render.js";
7
7
  import { PayloadResolver } from "./payload.js";
8
8
  import { Services } from "./services.js";
9
9
  import { activeSkillNames } from "./skills.js";
10
- import { lastText } from "./state.js";
10
+ import { lastText, turns } from "./state.js";
11
11
  import { lastOfType, projectMessages, } from "./trajectory.js";
12
12
  import { isToolReturn, isToolSuspend, stringify, zeroUsage, } from "./types.js";
13
13
  const defaultJoinPolicy = {
@@ -75,10 +75,12 @@ export class AgentRunner {
75
75
  #stream;
76
76
  #recordRequests;
77
77
  #clock;
78
+ #onModelError;
78
79
  constructor(opts = {}) {
79
80
  this.#model = opts.model;
80
81
  this.#context = opts.context;
81
82
  this.#clock = opts.clock ?? systemClock;
83
+ this.#onModelError = opts.onModelError;
82
84
  this.services =
83
85
  opts.services ??
84
86
  new Services({
@@ -144,7 +146,13 @@ export class AgentRunner {
144
146
  return new RunStream(this.#sendAndDrive(state, input, opts));
145
147
  }
146
148
  async *#resumeAndDrive(state, opts) {
149
+ // Declining to wait for the model ends the run: there is no call result
150
+ // to hand the model, and the next message continues the conversation.
151
+ const declined = (state.suspended ?? []).some((s) => s.site === 'llm' && opts.answers?.[s.callId]?.status === 'cancelled');
147
152
  const answered = yield* this.#answer(state, opts.answers ?? {}, opts);
153
+ if (declined) {
154
+ return yield* this.#finish(answered, undefined, 'aborted');
155
+ }
148
156
  return yield* this.#drive(answered, opts);
149
157
  }
150
158
  async *#sendAndDrive(state, input, opts) {
@@ -165,7 +173,10 @@ export class AgentRunner {
165
173
  if (!answer) {
166
174
  continue;
167
175
  }
168
- if (answer.status === 'resolved' && 'rerun' in answer) {
176
+ // A model call has no result to give: any answer lets it be made again
177
+ // (a cancel then ends the run, in #resumeAndDrive; a new message is
178
+ // simply what the call now answers).
179
+ if (s.site === 'llm' || (answer.status === 'resolved' && 'rerun' in answer)) {
169
180
  state = Kernel.releaseSuspension(state, s.callId);
170
181
  continue;
171
182
  }
@@ -221,6 +232,10 @@ export class AgentRunner {
221
232
  case 'done':
222
233
  return yield* this.#finish(state, branch, 'final');
223
234
  case 'llm': {
235
+ // Waiting on this very call (a resume that did not answer it).
236
+ if (state.suspended?.some((s) => s.site === 'llm')) {
237
+ return yield* this.#finish(state, branch, 'suspended');
238
+ }
224
239
  state = await Kernel.applySystemPrompt(state, this.registry, env);
225
240
  state = await this.#preload(state, env);
226
241
  state = await this.#autoRecall(state, env);
@@ -229,14 +244,37 @@ export class AgentRunner {
229
244
  const digest = Kernel.requestDigest(req);
230
245
  const model = this.#modelFor(state);
231
246
  const deltas = new EventQueue();
247
+ let streamed = 0;
232
248
  const call = (this.#stream && model.stream
233
- ? model.stream({ ...req, signal }, (d) => deltas.push(tag(state, branch, d)))
249
+ ? model.stream({ ...req, signal }, (d) => {
250
+ streamed++;
251
+ deltas.push(tag(state, branch, d));
252
+ })
234
253
  : model.generate({ ...req, signal })).finally(() => deltas.close());
235
254
  // Deltas arrive in a callback, which a generator cannot
236
255
  // yield from; draining the queue while the call is in
237
256
  // flight bridges the two.
238
257
  yield* deltas.drain();
239
- const res = await call;
258
+ let res;
259
+ try {
260
+ res = await call;
261
+ }
262
+ catch (err) {
263
+ // Waiting is only sound while nothing of the answer is
264
+ // on screen; otherwise the call would be shown twice.
265
+ const spec = branch || streamed || signal?.aborted
266
+ ? undefined
267
+ : await this.#onModelError?.(err, {
268
+ callId: modelCallId(state),
269
+ model: model.id,
270
+ state,
271
+ });
272
+ if (!spec) {
273
+ throw err;
274
+ }
275
+ state = Kernel.applyModelSuspension(state, { callId: modelCallId(state), name: model.id }, spec, this.#clock.now());
276
+ return yield* this.#finish(state, branch, 'suspended');
277
+ }
240
278
  const before = state;
241
279
  state = await Kernel.applyLlmResponse(state, res, model.id, env, {
242
280
  digest,
@@ -584,6 +622,10 @@ function tag(state, branch, event) {
584
622
  function appended(before, after) {
585
623
  return after.trajectory.slice(before.trajectory.length);
586
624
  }
625
+ /** The id a suspended model call goes by: stable until that call is made. */
626
+ function modelCallId(state) {
627
+ return `llm:${turns(state)}`;
628
+ }
587
629
  /** Recall after new user input or a hand-off, and never twice in a row. */
588
630
  function shouldRecall(state) {
589
631
  const nodes = state.trajectory;
package/dist/state.d.ts CHANGED
@@ -57,8 +57,9 @@ export interface AgentState {
57
57
  branches: string[];
58
58
  };
59
59
  /**
60
- * Pending tool calls the run is suspended on, waiting for a person (see
61
- * `suspend`). Each is also in `pendingToolCalls`; `runner.resume` answers them.
60
+ * What the run is suspended on, waiting for a person (see `suspend`): pending
61
+ * tool calls, each also in `pendingToolCalls`, or the next model call
62
+ * (`site: 'llm'`). `runner.resume` answers them.
62
63
  */
63
64
  suspended?: Suspension[];
64
65
  /** derived cache; always recomputable from the trajectory */
package/dist/types.d.ts CHANGED
@@ -165,13 +165,23 @@ export interface ToolSuspend {
165
165
  }
166
166
  export declare function suspend(spec: SuspendSpec): ToolSuspend;
167
167
  export declare function isToolSuspend(v: unknown): v is ToolSuspend;
168
- /** A pending tool call a run is suspended on. Lives in `AgentState.suspended`. */
168
+ /**
169
+ * What a suspended run waits on. Lives in `AgentState.suspended`.
170
+ *
171
+ * Usually a pending tool call (`site` absent or `'tool'`). With `site: 'llm'`
172
+ * it is the next model call instead: the model refused before answering (the
173
+ * gateway's spending limit was used up) and a host's `onModelError` chose to
174
+ * wait rather than fail. Its `callId` is `llm:<n>`, `n` being the model calls
175
+ * made so far, and `name` the model id; resuming makes that call again.
176
+ */
169
177
  export interface Suspension extends SuspendSpec {
170
178
  callId: string;
171
- /** the tool that suspended */
179
+ /** the tool that suspended, or the model for `site: 'llm'` */
172
180
  name: string;
173
181
  /** when it suspended, as the run's clock writes times */
174
182
  at: string;
183
+ /** what is waiting: a tool call (the default) or the next model call */
184
+ site?: 'tool' | 'llm';
175
185
  }
176
186
  /**
177
187
  * The answer to one suspension, given to `runner.resume`.
package/dist/types.js CHANGED
@@ -65,6 +65,11 @@ export function isToolReturn(v) {
65
65
  // answer as its result. What the pause is about is the host's business: the
66
66
  // runner only carries `reason`, `message` and `data` through to whoever shows
67
67
  // it, and `responseSchema` to whoever collects the answer.
68
+ //
69
+ // A model call can wait the same way, though not by returning anything: when it
70
+ // is refused before answering (a spending limit used up), the host's
71
+ // `RunnerOptions.onModelError` may answer with a `SuspendSpec`, and the run
72
+ // stops with that call recorded as `site: 'llm'`; resuming makes it again.
68
73
  // ---------------------------------------------------------------------------
69
74
  // Registered (`Symbol.for`) so a plugin with no dependencies can suspend too:
70
75
  // `{ [Symbol.for('zenera.neo.toolSuspend')]: true, spec }` is what `suspend` makes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenera/neo",
3
- "version": "1.3.30",
3
+ "version": "1.3.31",
4
4
  "description": "A multi-agent runtime for Node.js: agents, models, tools, skills, memory and an append-only trajectory.",
5
5
  "keywords": [
6
6
  "agents",
@@ -62,7 +62,7 @@
62
62
  "prepack": "tsc -b"
63
63
  },
64
64
  "dependencies": {
65
- "@zenera/sandbox": "^1.3.30",
65
+ "@zenera/sandbox": "^1.3.31",
66
66
  "graphology": "^0.26.0",
67
67
  "yaml": "^2.9.1",
68
68
  "zod": "^4.6.7"