@noetic-tools/core 5.22.0-next.4 → 5.22.0-next.6

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.
@@ -7,7 +7,7 @@ import type { LayerStateStore, RecallCache } from './deps/context.js';
7
7
  import type { DetachedSpawnOverrides } from './deps/interpreter.js';
8
8
  import type { CheckpointStore, EventBroadcaster, RestoreCheckpointOptions, StepLedgerRetention, StepLedgerStore } from './deps/runtime.js';
9
9
  import { ChannelStore, Drains } from './deps/runtime.js';
10
- import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, ContextCacheStore, ContextData, ContextLayer, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DetachedHandle, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, LLMResponse, OnSteerParams, PendingSpend, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StepLike, StepsInput, StepsOutput, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, TraceExporter, ValidStepChain, WriteOffSpendOptions } from './deps/types.js';
10
+ import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, ContextCacheStore, ContextData, ContextLayer, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DetachedHandle, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, LLMResponse, OnSteerParams, PendingSpend, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StepLike, StepsInput, StepsOutput, StorageAdapter, StoredThread, StreamEvent, StreamingItem, SubprocessAdapter, TraceExporter, ValidStepChain, WriteOffSpendOptions } from './deps/types.js';
11
11
  import type { AgentHarnessOpts, WakeTimeListener } from './harness-options.js';
12
12
  import { Spend } from './spend.js';
13
13
  /**
@@ -371,6 +371,20 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
371
371
  * refused and the turn was cut instead: a wake replays it to here.
372
372
  */
373
373
  private keepOrCut;
374
+ /** Start the stored turn before putting kept messages back or reporting drops. */
375
+ private beginStoredTurn;
376
+ /**
377
+ * Split stored messages between the queue and the steers the start write clears.
378
+ */
379
+ private splitKeptMessages;
380
+ /**
381
+ * What the thread's stored record holds (spec 23a § Sessions): whether it has
382
+ * history and the turn it has in flight, cut off or parked. Undefined when the
383
+ * thread has no record, or the harness keeps none. A host that keeps its own
384
+ * copy of the conversation seeds history only when none is stored.
385
+ * @public
386
+ */
387
+ getStoredThread(threadId: string): Promise<StoredThread | undefined>;
374
388
  /** The options a stored turn is woken with when the wake names none: `turnOptions`, or none. */
375
389
  private storedTurnOptions;
376
390
  /**
@@ -4,6 +4,7 @@ import { runEvery } from '../connections/settle.js';
4
4
  import { pendingTasksOf, resumableWaitsOf } from '../interpreter/connection-steps.js';
5
5
  import { turnEndingIn } from '../interpreter/turn-ending.js';
6
6
  import { AcpSessionStore } from '../runtime/acp-session-store.js';
7
+ import { emitFrameworkEvent } from '../runtime/broadcaster-utils.js';
7
8
  import { stubOf } from '../runtime/durable/step-ledger.js';
8
9
  import { heldCallsOf, toHeldCall } from '../runtime/held-calls.js';
9
10
  import { OutputStore } from '../runtime/output-store.js';
@@ -18,11 +19,13 @@ import { forgetExecution, forgetThread, listStoredExecutions, listStoredThreads
18
19
  import { resolveCheckpointStore, resolveEnvironmentAdapters } from './harness-options.js';
19
20
  import { createHarnessSpan, recordChannelWarning, resolveTraceExporter } from './harness-tracing.js';
20
21
  import { LlmGateway } from './llm-client.js';
22
+ import { savedItemIds } from './model-rounds.js';
21
23
  import { buildItemSchemaRegistry } from './model-schema.js';
22
24
  import { DEFAULT_TASK_POLL_MS, DEFAULT_WAKE_DEBOUNCE_MS, ParkWatchers } from './park-watchers.js';
23
25
  import { readDecision } from './read-decision.js';
24
26
  import { recordedToolCalls } from './recorded-tool-calls.js';
25
27
  import { Spend } from './spend.js';
28
+ import { steerInConversation, steerItems } from './steer-inbox.js';
26
29
  import { ThreadRecord } from './thread-record.js';
27
30
  import { TurnCuts } from './turn-cuts.js';
28
31
  /** Keep `message` in storage for after the thread's parked turn, with its options. */
@@ -30,6 +33,29 @@ function keepForLater(session, record, message) {
30
33
  session.keptOptions.set(message.id, message.options);
31
34
  return record.keepQueued(message);
32
35
  }
36
+ /** A stored turn as a host sees it (`turnOptions`, `getStoredThread`). */
37
+ function storedTurnOf(threadId, turn, cut) {
38
+ return {
39
+ threadId,
40
+ executionId: turn.executionId,
41
+ messageIds: turn.messageIds,
42
+ ...(turn.version === undefined
43
+ ? {}
44
+ : {
45
+ version: turn.version,
46
+ }),
47
+ ...(turn.parked
48
+ ? {
49
+ parked: turn.parked,
50
+ }
51
+ : {}),
52
+ ...(cut
53
+ ? {
54
+ cut,
55
+ }
56
+ : {}),
57
+ };
58
+ }
33
59
  //#endregion
34
60
  const DEFAULT_THREAD_ID = '__default__';
35
61
  /**
@@ -349,6 +375,7 @@ export class AgentHarness {
349
375
  onHeld: opts.onHeld,
350
376
  steerWhileHeld: opts.steerWhileHeld,
351
377
  now: opts.now,
378
+ killAgentsOnExit: opts.killAgentsOnExit,
352
379
  };
353
380
  this.outputStorage = this.config.storage ?? createInMemoryStorage();
354
381
  const adapters = resolveEnvironmentAdapters(environment);
@@ -1046,26 +1073,14 @@ export class AgentHarness {
1046
1073
  await this.start();
1047
1074
  const connectionTools = await this.#connections.openTurn(ctx, perTurnOptions.connections, graph);
1048
1075
  this.setTurnTools(ctx, perTurnOptions.tools ?? [], connectionTools);
1049
- // Steers the last harness accepted but never applied go back in the queue;
1050
- // ones already in the conversation are skipped when offered.
1051
- for (const steer of (await record?.steers()) ?? []) {
1052
- const queued = session.runner.queue.peekAll().some((m) => m.id === steer.id);
1053
- if (!queued && !messageIds.includes(steer.id)) {
1054
- // With the options it was sent with, when this process is the one it was sent to.
1055
- const options = session.keptOptions.get(steer.id) ?? steer.options;
1056
- session.keptOptions.delete(steer.id);
1057
- session.runner.queue.enqueue({
1058
- ...steer,
1059
- options,
1060
- });
1061
- }
1062
- }
1063
1076
  // A stuck turn the host chose to go on with may discard what no longer matches.
1064
1077
  const accept = (await record?.turn())?.accept;
1065
1078
  if (accept && ctx instanceof ContextImpl) {
1066
1079
  ctx.ledger?.acceptVersionLoss(typeof accept === 'string' ? accept : undefined);
1067
1080
  }
1068
- await record?.begin(ctx, messageIds);
1081
+ if (record) {
1082
+ await this.beginStoredTurn(session, record, ctx, messageIds, perTurnOptions.keptSteers);
1083
+ }
1069
1084
  // A turn on record can be cut off from here on. A host that sleeps between
1070
1085
  // requests has to know when to come back and look (see `turnDueAt`).
1071
1086
  if (record && this.leaseOptions) {
@@ -1365,31 +1380,99 @@ export class AgentHarness {
1365
1380
  throw error;
1366
1381
  }
1367
1382
  }
1368
- /** The options a stored turn is woken with when the wake names none: `turnOptions`, or none. */
1369
- async storedTurnOptions(threadId, turn, cut) {
1370
- if (!this.turnOptionsFor) {
1371
- return {};
1383
+ /** Start the stored turn before putting kept messages back or reporting drops. */
1384
+ async beginStoredTurn(session, record, ctx, messageIds, keptSteers) {
1385
+ const { removed, kept } = await this.splitKeptMessages(session, record, messageIds, keptSteers);
1386
+ try {
1387
+ await record.begin(ctx, messageIds, removed.map((steer) => steer.id));
1388
+ }
1389
+ catch (error) {
1390
+ await this.#connections.release(ctx.id);
1391
+ throw error;
1392
+ }
1393
+ for (const message of kept) {
1394
+ session.keptOptions.delete(message.id);
1395
+ if (!session.runner.queue.peekAll().some((queued) => queued.id === message.id)) {
1396
+ session.runner.queue.enqueue(message);
1397
+ }
1398
+ }
1399
+ const saved = removed.length > 0 && ctx instanceof ContextImpl ? savedItemIds(ctx) : undefined;
1400
+ // Told only once the record no longer holds them.
1401
+ for (const steer of removed) {
1402
+ if (saved && steerInConversation(steerItems(steer), (id) => saved.has(id))) {
1403
+ continue;
1404
+ }
1405
+ emitFrameworkEvent({
1406
+ broadcaster: session.runner.broadcaster,
1407
+ agentName: this.config.name,
1408
+ eventType: 'steer_dropped',
1409
+ data: {
1410
+ messageId: steer.id,
1411
+ reason: 'kept_steers',
1412
+ },
1413
+ });
1372
1414
  }
1373
- return await this.turnOptionsFor({
1415
+ }
1416
+ /**
1417
+ * Split stored messages between the queue and the steers the start write clears.
1418
+ */
1419
+ async splitKeptMessages(session, record, messageIds, keptSteers) {
1420
+ const removed = [];
1421
+ const kept = [];
1422
+ for (const steer of await record.steers()) {
1423
+ const queued = session.runner.queue.peekAll().some((m) => m.id === steer.id);
1424
+ if (queued || messageIds.includes(steer.id)) {
1425
+ continue;
1426
+ }
1427
+ // With the options it was sent with, when this process is the one it was sent to.
1428
+ const options = session.keptOptions.get(steer.id);
1429
+ // A message this process kept for a parked turn still has its sender here.
1430
+ if (keptSteers === 'drop' && options === undefined && isSteer(steer)) {
1431
+ removed.push(steer);
1432
+ continue;
1433
+ }
1434
+ kept.push({
1435
+ ...steer,
1436
+ options: options ?? steer.options,
1437
+ });
1438
+ }
1439
+ return {
1440
+ removed,
1441
+ kept,
1442
+ };
1443
+ }
1444
+ /**
1445
+ * What the thread's stored record holds (spec 23a § Sessions): whether it has
1446
+ * history and the turn it has in flight, cut off or parked. Undefined when the
1447
+ * thread has no record, or the harness keeps none. A host that keeps its own
1448
+ * copy of the conversation seeds history only when none is stored.
1449
+ * @public
1450
+ */
1451
+ async getStoredThread(threadId) {
1452
+ await this.forgetting.get(threadId);
1453
+ // Through the session's own record, when there is one: a seed it queued lands first.
1454
+ const record = await (this.sessions.get(threadId)?.record ?? this.threadRecord(threadId))?.stored();
1455
+ if (!record) {
1456
+ return undefined;
1457
+ }
1458
+ const turn = record.turn;
1459
+ const cut = turn && !turn.parked ? this.cuts?.markOf(threadId, turn) : undefined;
1460
+ return {
1374
1461
  threadId,
1375
- executionId: turn.executionId,
1376
- messageIds: turn.messageIds,
1377
- ...(turn.version === undefined
1378
- ? {}
1379
- : {
1380
- version: turn.version,
1381
- }),
1382
- ...(turn.parked
1462
+ hasHistory: record.items.length > 0,
1463
+ ...(turn
1383
1464
  ? {
1384
- parked: turn.parked,
1465
+ turn: storedTurnOf(threadId, turn, cut),
1385
1466
  }
1386
1467
  : {}),
1387
- ...(cut
1388
- ? {
1389
- cut,
1390
- }
1391
- : {}),
1392
- });
1468
+ };
1469
+ }
1470
+ /** The options a stored turn is woken with when the wake names none: `turnOptions`, or none. */
1471
+ async storedTurnOptions(threadId, turn, cut) {
1472
+ if (!this.turnOptionsFor) {
1473
+ return {};
1474
+ }
1475
+ return await this.turnOptionsFor(storedTurnOf(threadId, turn, cut));
1393
1476
  }
1394
1477
  /**
1395
1478
  * The earliest time the harness has something to do, in epoch ms: a parked turn
@@ -1,4 +1,4 @@
1
1
  export type { ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, ExecutionContext, ProjectionPolicy, StorageAdapter, } from '@noetic-tools/context';
2
- export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, DrainReport, ExecuteInput, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, HeldCallHandler, HeldSteerPolicy, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StepLike, Steps, StepsInput, StepsOutput, StoredTurn, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, TurnCut, TurnCutReason, UsageCharge, ValidStepChain, WriteOffSpendOptions, } from '@noetic-tools/types';
2
+ export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, DrainReport, ExecuteInput, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, HeldCallHandler, HeldSteerPolicy, Item, ItemSchemaConfig, ItemSchemaExtensions, KeptSteers, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StepLike, Steps, StepsInput, StepsOutput, StoredThread, StoredTurn, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, TurnCut, TurnCutReason, UsageCharge, ValidStepChain, WriteOffSpendOptions, } from '@noetic-tools/types';
3
3
  export { SteeringAction } from '@noetic-tools/types';
4
4
  export type { ZodType } from 'zod';
@@ -205,6 +205,13 @@ export interface AgentHarnessOpts<TParams extends Record<string, unknown> = Reco
205
205
  * the progress it missed.
206
206
  */
207
207
  emitItemsOnReplay?: boolean;
208
+ /**
209
+ * Stop every ACP agent this harness started when its process goes away
210
+ * without closing them — a crash, Ctrl-C, a killed process. By default
211
+ * (`false`) a local agent keeps working and holds what it sends until a
212
+ * resumed run reattaches to it (spec 27 § A local agent outlives its host).
213
+ */
214
+ killAgentsOnExit?: boolean;
208
215
  /**
209
216
  * The version of the flow this harness runs: any string the host changes when the
210
217
  * flow changes, such as a release tag or a hash (spec 23 § Versions). Every step a
@@ -26,6 +26,7 @@
26
26
  */
27
27
  import type { Item, ItemSchemaRegistry, RoundUsage } from '@noetic-tools/types';
28
28
  import type { ToolCallResult } from '../runtime/tool-call.js';
29
+ import { ContextImpl } from './deps/runtime.js';
29
30
  /** Ledger kind of a model-loop round's record. */
30
31
  export declare const ROUND_KIND = "callModel:round";
31
32
  /** Ledger kind of one tool call's record within a round. */
@@ -72,6 +73,8 @@ export interface ReplayedRound extends RoundRecord {
72
73
  /** A failed call already charged this round's bill to the context. */
73
74
  charged: boolean;
74
75
  }
76
+ /** Item ids saved in the context, completed steps and model rounds. */
77
+ export declare function savedItemIds(ctx: ContextImpl): Set<string>;
75
78
  /**
76
79
  * The round ledger for one model loop. `open` gives none when the call is not running
77
80
  * as a step on a context with a ledger.
@@ -83,6 +83,28 @@ const RoundOutputSchema = z.object({
83
83
  const chargedRounds = new WeakMap();
84
84
  //#endregion
85
85
  //#region Public API
86
+ /** Item ids saved in the context, completed steps and model rounds. */
87
+ export function savedItemIds(ctx) {
88
+ const ids = new Set();
89
+ const add = (items) => {
90
+ for (const item of items) {
91
+ if (item && typeof item === 'object' && 'id' in item && typeof item.id === 'string') {
92
+ ids.add(item.id);
93
+ }
94
+ }
95
+ };
96
+ add(ctx.itemLog.items);
97
+ for (const entry of ctx.ledger?.savedEntries() ?? []) {
98
+ add(entry.items ?? []);
99
+ if (entry.kind === ROUND_KIND) {
100
+ const round = RoundOutputSchema.safeParse(entry.output);
101
+ if (round.success) {
102
+ add(round.data.items);
103
+ }
104
+ }
105
+ }
106
+ return ids;
107
+ }
86
108
  /**
87
109
  * The round ledger for one model loop. `open` gives none when the call is not running
88
110
  * as a step on a context with a ledger.
@@ -1,6 +1,6 @@
1
1
  import type { AgentHarnessContract, Context, ContextLayer, FunctionCallItem, Item } from '@noetic-tools/types';
2
2
  import { SteerPoint } from '@noetic-tools/types';
3
- import type { MessageQueue } from '../runtime/message-queue.js';
3
+ import type { MessageQueue, QueuedMessage } from '../runtime/message-queue.js';
4
4
  /** @internal Steers taken off the queue, waiting for the next model call. */
5
5
  export interface StagedSteers {
6
6
  messageIds: string[];
@@ -46,11 +46,17 @@ export declare class SteerInbox {
46
46
  offer(point: SteerPoint, pendingCalls?: ReadonlyArray<FunctionCallItem>): Promise<boolean>;
47
47
  /** Hand over the staged steers and clear them. */
48
48
  takeStaged(): StagedSteers;
49
- private alreadyApplied;
50
49
  private judge;
51
50
  /** Steers are user input, so they pass through `onItemAppend` like any other.
52
51
  * Re-render requests are ignored: recall does not run again mid-call. */
53
52
  private stage;
54
53
  private reportPending;
55
54
  }
55
+ /** @internal Whether every item of a steer is already in the conversation. */
56
+ export declare function steerInConversation(items: ReadonlyArray<Item>, hasItem: (id: string) => boolean): boolean;
57
+ /**
58
+ * A steer's items. Text gets an id from the message id rather than a random one,
59
+ * so a resumed turn can tell the steer is already in the conversation.
60
+ */
61
+ export declare function steerItems(message: QueuedMessage): Item[];
56
62
  export {};
@@ -56,7 +56,7 @@ export class SteerInbox {
56
56
  const items = steerItems(message);
57
57
  // A resumed turn re-queues the steers its last run kept; the ones that run
58
58
  // already applied come back with the replayed rounds and steps.
59
- if (this.alreadyApplied(items)) {
59
+ if (steerInConversation(items, this.opts.inConversation)) {
60
60
  this.opts.queue.take((queued) => queued === message);
61
61
  continue;
62
62
  }
@@ -91,10 +91,6 @@ export class SteerInbox {
91
91
  };
92
92
  return staged;
93
93
  }
94
- alreadyApplied(items) {
95
- return (items.length > 0 &&
96
- items.every((item) => 'id' in item && item.id !== undefined && this.opts.inConversation(item.id)));
97
- }
98
94
  async judge(message, items, point, pendingCalls) {
99
95
  const action = defaultAction(point, message.deliveryMode, this.opts.harness.config.steerWhileHeld);
100
96
  const { harness, layers } = this.opts;
@@ -136,12 +132,17 @@ export class SteerInbox {
136
132
  }
137
133
  }
138
134
  //#endregion
135
+ /** @internal Whether every item of a steer is already in the conversation. */
136
+ export function steerInConversation(items, hasItem) {
137
+ return (items.length > 0 &&
138
+ items.every((item) => 'id' in item && item.id !== undefined && hasItem(item.id)));
139
+ }
139
140
  //#region Helpers
140
141
  /**
141
142
  * A steer's items. Text gets an id from the message id rather than a random one,
142
143
  * so a resumed turn can tell the steer is already in the conversation.
143
144
  */
144
- function steerItems(message) {
145
+ export function steerItems(message) {
145
146
  if (typeof message.input !== 'string') {
146
147
  return inputToItems(message.input);
147
148
  }
@@ -70,8 +70,9 @@ export declare class ThreadRecord {
70
70
  /**
71
71
  * Record the turn about to run on `ctx`, before any of it runs. Kept steers it
72
72
  * delivers as input stop being steers: re-delivering the turn re-sends them.
73
+ * Kept steers named in `removed` are removed in the same write (`keptSteers: 'drop'`).
73
74
  */
74
- begin(ctx: Context, messageIds: ReadonlyArray<string>): Promise<void>;
75
+ begin(ctx: Context, messageIds: ReadonlyArray<string>, removed?: ReadonlyArray<string>): Promise<void>;
75
76
  /**
76
77
  * The turn on `ctx` stopped rather than redo a recorded effect under a newer flow
77
78
  * version. It stays, marked, until the host settles it.
@@ -122,6 +123,8 @@ export declare class ThreadRecord {
122
123
  answerFor(messageId: string): Promise<string | undefined>;
123
124
  /** The executions of every turn the thread began, oldest first, the one in flight last. */
124
125
  executions(): Promise<string[]>;
126
+ /** The stored record, read after every write issued before it. */
127
+ stored(): Promise<SessionRecord | undefined>;
125
128
  /** The turn in flight, cut off or parked, when one is recorded. */
126
129
  turn(): Promise<SessionRecord['turn']>;
127
130
  /**
@@ -138,7 +141,8 @@ export declare class ThreadRecord {
138
141
  * A write the turn itself makes. Under a lease it carries the lease's term and is
139
142
  * refused when the record already holds a higher one — another harness took the
140
143
  * turn, whatever this one's clock says — and a write that fails throws instead of
141
- * being logged (spec 23 § One writer per turn, § Fail-stop).
144
+ * being logged (spec 23 § One writer per turn, § Fail-stop). A caller that
145
+ * reports a removal also needs the write to succeed without a lease.
142
146
  */
143
147
  private updateHeld;
144
148
  /** Read-modify-write the stored record, best-effort. Call only from inside `run`. */
@@ -146,11 +146,12 @@ export class ThreadRecord {
146
146
  /**
147
147
  * Record the turn about to run on `ctx`, before any of it runs. Kept steers it
148
148
  * delivers as input stop being steers: re-delivering the turn re-sends them.
149
+ * Kept steers named in `removed` are removed in the same write (`keptSteers: 'drop'`).
149
150
  */
150
- begin(ctx, messageIds) {
151
- return this.updateHeld(ctx, (record) => ({
151
+ begin(ctx, messageIds, removed = []) {
152
+ const start = (record) => ({
152
153
  ...record,
153
- steers: record.steers?.filter((steer) => !messageIds.includes(steer.id)),
154
+ steers: record.steers?.filter((steer) => !messageIds.includes(steer.id) && !removed.includes(steer.id)),
154
155
  executions: withExecution(record.executions, ctx.id),
155
156
  ...this.withLayers(record),
156
157
  turn: {
@@ -179,7 +180,8 @@ export class ThreadRecord {
179
180
  }
180
181
  : {}),
181
182
  },
182
- }));
183
+ });
184
+ return this.updateHeld(ctx, start, removed.length > 0);
183
185
  }
184
186
  /**
185
187
  * The turn on `ctx` stopped rather than redo a recorded effect under a newer flow
@@ -317,6 +319,10 @@ export class ThreadRecord {
317
319
  executions() {
318
320
  return this.run(async () => executionsOf(await this.load()));
319
321
  }
322
+ /** The stored record, read after every write issued before it. */
323
+ stored() {
324
+ return this.run(() => this.load());
325
+ }
320
326
  /** The turn in flight, cut off or parked, when one is recorded. */
321
327
  turn() {
322
328
  return this.run(async () => (await this.load())?.turn);
@@ -361,17 +367,21 @@ export class ThreadRecord {
361
367
  * A write the turn itself makes. Under a lease it carries the lease's term and is
362
368
  * refused when the record already holds a higher one — another harness took the
363
369
  * turn, whatever this one's clock says — and a write that fails throws instead of
364
- * being logged (spec 23 § One writer per turn, § Fail-stop).
370
+ * being logged (spec 23 § One writer per turn, § Fail-stop). A caller that
371
+ * reports a removal also needs the write to succeed without a lease.
365
372
  */
366
- updateHeld(ctx, change) {
373
+ updateHeld(ctx, change, mustWrite = false) {
367
374
  const fence = this.fence;
368
- if (!fence) {
375
+ if (!fence && !mustWrite) {
369
376
  return this.update(change);
370
377
  }
371
378
  return this.run(async () => {
372
- fence.assert();
379
+ fence?.assert();
373
380
  try {
374
381
  await this.commit((record) => {
382
+ if (!fence) {
383
+ return change(record);
384
+ }
375
385
  if ((record.term ?? 0) > fence.term) {
376
386
  throw fence.lose(`the thread record was written at term ${record.term}`);
377
387
  }
package/dist/index.d.ts CHANGED
@@ -181,7 +181,7 @@ export type { LayerTraceSpan, Span, TraceExporter } from '@noetic-tools/types';
181
181
  /** @public */
182
182
  export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent, StreamingItem, TurnCut, TurnCutReason, } from '@noetic-tools/types';
183
183
  /** @public */
184
- export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, HeldCall, HeldCallContext, HeldCallEvent, HeldCallHandler, HeldCallSettled, HeldResolution, HeldSteerPolicy, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, RecordedToolCall, SessionScope, SessionUsage, StoredTurn, StuckTurn, ToolHold, TrailMark, } from '@noetic-tools/types';
184
+ export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, HeldCall, HeldCallContext, HeldCallEvent, HeldCallHandler, HeldCallSettled, HeldResolution, HeldSteerPolicy, ItemSchemaConfig, KeptSteers, ReanchorReason, RecallLayerOutput, RecordedToolCall, SessionScope, SessionUsage, StoredThread, StoredTurn, StuckTurn, ToolHold, TrailMark, } from '@noetic-tools/types';
185
185
  /** @public */
186
186
  export type { ForgetOptions, ForgetReport, ListStoredOptions, PendingSpend, ReconcileSpendOptions, SpendSettlement, StoredExecution, WriteOffSpendOptions, } from '@noetic-tools/types';
187
187
  /** @public */
@@ -199,7 +199,7 @@ export { BooleanQuestionSchema, ChoiceQuestionSchema, choiceValues, DECIDE_LIMIT
199
199
  /** @public */
200
200
  export type { RouteSwitchByFunctionOpts, RouteSwitchByKeyOpts, StepDecideOpts, StepInput, StepOutput, } from './builders/decide-builders.js';
201
201
  /** @public */
202
- export type { AcpAgent, AcpAgentCapabilities, AcpAgentConnection, AcpAgentGrant, AcpAllowlist, AcpAuthMethod, AcpAvailableCommand, AcpBoundPermissionHandler, AcpCapabilityGrant, AcpClientCapabilityConfig, AcpClientHost, AcpConnectOptions, AcpContentBlock, AcpKeepAlive, AcpLiveSession, AcpLoadSessionOptions, AcpMachine, AcpMachineFactory, AcpMcpServer, AcpNewSessionOptions, AcpPermissionGrant, AcpPermissionHandler, AcpPermissionOption, AcpPermissionOutcome, AcpPermissionPolicy, AcpPermissionRequestInfo, AcpPermissionRule, AcpPermissionSteerer, AcpPlanEntry, AcpPromptCapabilities, AcpPromptOptions, AcpRequestPermissionRequest, AcpSession, AcpSessionDisposer, AcpSessionGrant, AcpSessionInfo, AcpSessionMode, AcpSessionModeState, AcpSessionNotification, AcpSessionPolicy, AcpStopReason, AcpToolCallContent, AcpToolCallStatus, AcpToolKind, AcpToolRefusal, AcpTransport, AcpTransportFactory, AcpTransportOptions, AcpTurnResult, ByteStream, Spawn, SpawnCommand, ToolBridgeAddress, } from '@noetic-tools/types';
202
+ export type { AcpAgent, AcpAgentCapabilities, AcpAgentConnection, AcpAgentGrant, AcpAllowlist, AcpAuthMethod, AcpAvailableCommand, AcpBoundPermissionHandler, AcpCapabilityGrant, AcpClientCapabilityConfig, AcpClientHost, AcpConnectOptions, AcpContentBlock, AcpKeepAlive, AcpLiveSession, AcpLoadSessionOptions, AcpMachine, AcpMachineFactory, AcpMcpServer, AcpNewSessionOptions, AcpPermissionGrant, AcpPermissionHandler, AcpPermissionOption, AcpPermissionOutcome, AcpPermissionPolicy, AcpPermissionRequestInfo, AcpPermissionRule, AcpPermissionSteerer, AcpPlanEntry, AcpPromptCapabilities, AcpPromptOptions, AcpReattachHandle, AcpRequestPermissionRequest, AcpResumeTurnOptions, AcpSession, AcpSessionConfigOption, AcpSessionDisposer, AcpSessionGrant, AcpSessionInfo, AcpSessionMode, AcpSessionModeState, AcpSessionNotification, AcpSessionPolicy, AcpStopReason, AcpToolCallContent, AcpToolCallStatus, AcpToolKind, AcpToolRefusal, AcpTransport, AcpTransportFactory, AcpTransportOptions, AcpTurnResult, AcpUsage, AcpUsageUpdate, AcpWhenHostExits, ByteStream, Spawn, SpawnCommand, ToolBridgeAddress, } from '@noetic-tools/types';
203
203
  /** @public */
204
204
  export { ACP_AGENT_STEP_KIND, AcpCapabilityError, AcpConnectError, AcpPermissionDecision, isAcpCapabilityError, isAcpConnectError, } from '@noetic-tools/types';
205
205
  /** @public */
@@ -65,6 +65,13 @@ export declare class AcpEventBridge {
65
65
  itemAppended(item: Item): void;
66
66
  /** Forward one notification: a structured framework event + the mapped sdk events. */
67
67
  forward(notification: AcpSessionNotification): void;
68
+ /**
69
+ * Forward one update `session/load` replayed: the loaded session's history,
70
+ * not this turn's output. It reaches raw-event consumers as an `acp_event`
71
+ * marked `replay: true` (same step, agent and session attribution) and is
72
+ * never translated into text, reasoning or function-call events.
73
+ */
74
+ forwardReplay(notification: AcpSessionNotification): void;
68
75
  /**
69
76
  * Ensure the turn's output reached the event surface. For an agent that
70
77
  * returns a result without streaming, synthesize events from the result.
@@ -14,6 +14,7 @@
14
14
  * synthesized into events.
15
15
  */
16
16
  import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
17
+ import { errorMessage } from '../util/error-message.js';
17
18
  import { isFunctionCall } from './typeguards.js';
18
19
  /** Flatten an ACP content block for the text event surface. */
19
20
  function blockText(block) {
@@ -128,6 +129,22 @@ export class AcpEventBridge {
128
129
  });
129
130
  this.translate(notification.update);
130
131
  }
132
+ /**
133
+ * Forward one update `session/load` replayed: the loaded session's history,
134
+ * not this turn's output. It reaches raw-event consumers as an `acp_event`
135
+ * marked `replay: true` (same step, agent and session attribution) and is
136
+ * never translated into text, reasoning or function-call events.
137
+ */
138
+ forwardReplay(notification) {
139
+ if (!this.broadcaster) {
140
+ return;
141
+ }
142
+ this.framework('acp_event', {
143
+ sessionId: notification.sessionId,
144
+ update: notification.update,
145
+ replay: true,
146
+ });
147
+ }
131
148
  /**
132
149
  * Ensure the turn's output reached the event surface. For an agent that
133
150
  * returns a result without streaming, synthesize events from the result.
@@ -156,6 +173,11 @@ export class AcpEventBridge {
156
173
  this.start();
157
174
  this.sdk('response.completed', {
158
175
  stopReason: result.stopReason,
176
+ ...(result.reportedUsage
177
+ ? {
178
+ reportedUsage: result.reportedUsage,
179
+ }
180
+ : {}),
159
181
  });
160
182
  this.completed = true;
161
183
  }
@@ -173,7 +195,7 @@ export class AcpEventBridge {
173
195
  this.start();
174
196
  this.sdk('response.completed', {
175
197
  stopReason: 'error',
176
- error: cause instanceof Error ? cause.message : String(cause),
198
+ error: errorMessage(cause),
177
199
  });
178
200
  this.completed = true;
179
201
  }
@@ -15,6 +15,7 @@ import type { ToolCallResult } from '../runtime/tool-call.js';
15
15
  declare const AcpSessionRecordSchema: z.ZodObject<{
16
16
  sessionId: z.ZodString;
17
17
  agentId: z.ZodString;
18
+ reattach: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
18
19
  }, z.core.$strip>;
19
20
  /** The agent session a step opened, as stored. */
20
21
  export type AcpSessionRecord = z.infer<typeof AcpSessionRecordSchema>;
@@ -19,6 +19,8 @@ import { pendingEntryKey, runRootOf } from './connection-steps.js';
19
19
  const AcpSessionRecordSchema = z.object({
20
20
  sessionId: z.string(),
21
21
  agentId: z.string(),
22
+ /** How to reach the agent if it outlived the host that opened the session. */
23
+ reattach: z.record(z.string(), z.unknown()).optional(),
22
24
  });
23
25
  const BridgedOutputSchema = z.object({
24
26
  output: z.string(),
@@ -9,6 +9,7 @@
9
9
  import { createMessage, extractAssistantText, frameworkCast, NoeticConfigError, NoeticErrorImpl, SteeringAction, } from '@noetic-tools/types';
10
10
  import { assertAgentTakesTools } from '../builders/acp-agent-checks.js';
11
11
  import { runtimeOf } from '../connections/model-tools.js';
12
+ import { isRpcError, RpcFailure } from '../util/error-message.js';
12
13
  import { AcpEventBridge } from './acp-events.js';
13
14
  import { withHistoryPrompt } from './acp-history.js';
14
15
  import { renderLayerContext } from './acp-layers.js';
@@ -364,6 +365,7 @@ async function sessionOn(connection, opts) {
364
365
  }
365
366
  async function openSession(opts) {
366
367
  let resumed = false;
368
+ let reattached = false;
367
369
  const store = sessionStore(opts.baseCtx);
368
370
  const keepAlive = keepAliveOf(opts.step.session);
369
371
  const reuseKey = opts.step.session?.reuse;
@@ -376,10 +378,29 @@ async function openSession(opts) {
376
378
  // its step has to be reachable, or nothing can ever close it.
377
379
  const key = store.keyFor(parts);
378
380
  const { live, fresh } = await store.acquire(key, parts, async () => {
379
- const connection = holdingConnections(await opts.agent.connect({
381
+ const connectOptions = {
380
382
  host: opts.host,
381
383
  signal: abortSignalOf(opts.baseCtx),
382
- }), opts.baseCtx, keepAlive);
384
+ whenHostExits: whenHostExitsOf(opts.baseCtx),
385
+ };
386
+ const kept = await reattachTo(opts.agent, connectOptions, {
387
+ reattach: opts.reattach,
388
+ sessionId: opts.resumeId,
389
+ });
390
+ if (kept) {
391
+ resumed = true;
392
+ reattached = true;
393
+ return {
394
+ connection: holdingConnections(kept.connection, opts.baseCtx, keepAlive),
395
+ session: kept.session,
396
+ host: opts.host,
397
+ agentId: opts.agent.agentId,
398
+ keepAlive,
399
+ cwd: opts.cwd,
400
+ tools: opts.tools?.tools,
401
+ };
402
+ }
403
+ const connection = holdingConnections(await opts.agent.connect(connectOptions), opts.baseCtx, keepAlive);
383
404
  // From here on the connection owns a live agent (usually a child process).
384
405
  // Anything that throws before the caller can take responsibility for it
385
406
  // must close it first — otherwise the agent outlives the step and, because
@@ -426,6 +447,39 @@ async function openSession(opts) {
426
447
  keepAlive,
427
448
  fresh,
428
449
  resumed,
450
+ reattached,
451
+ };
452
+ }
453
+ /** The harness's choice for agents its process leaves behind. */
454
+ function whenHostExitsOf(ctx) {
455
+ return ctx.harness.config.killAgentsOnExit === true ? 'stop' : 'keep';
456
+ }
457
+ /**
458
+ * The live session an earlier attempt of the step left in an agent that
459
+ * outlived its host, or undefined when there is none to reach — the agent is
460
+ * gone, or no longer has the session — so the step reloads or starts over.
461
+ */
462
+ async function reattachTo(agent, connectOptions, { reattach, sessionId, }) {
463
+ if (!reattach || sessionId === undefined) {
464
+ return undefined;
465
+ }
466
+ const connection = await agent
467
+ .connect({
468
+ ...connectOptions,
469
+ reattach,
470
+ })
471
+ .catch(() => undefined);
472
+ if (!connection) {
473
+ return undefined;
474
+ }
475
+ const session = await connection.attachSession?.(sessionId).catch(() => undefined);
476
+ if (!session?.resumeTurn) {
477
+ await connection.close().catch(() => undefined);
478
+ return undefined;
479
+ }
480
+ return {
481
+ connection,
482
+ session,
429
483
  };
430
484
  }
431
485
  /**
@@ -512,19 +566,24 @@ function turnFailure(step, cause, baseCtx) {
512
566
  return new NoeticErrorImpl({
513
567
  kind: 'step_failed',
514
568
  stepId: step.id,
515
- cause: cause instanceof Error ? cause : new Error(describeCause(cause)),
569
+ // A JSON-RPC rejection keeps its detail (`data`) in the message, so a
570
+ // failure reads "Internal error: Authentication required (-32603)", never
571
+ // "[object Object]" or a bare "Internal error".
572
+ cause: cause instanceof Error && !isRpcError(cause) ? cause : new RpcFailure(cause),
516
573
  retriesExhausted: false,
517
574
  });
518
575
  }
519
- /** A readable message for a thrown non-Error, such as a JSON-RPC error object. */
520
- function describeCause(cause) {
521
- if (typeof cause !== 'object' || cause === null) {
522
- return String(cause);
576
+ /**
577
+ * A failure while opening the session or applying its mode/model. Typed
578
+ * errors (capability, connect, config) pass through; a JSON-RPC rejection from
579
+ * the agent — or anything thrown that is not an Error — becomes the step's
580
+ * `step_failed` error with a readable message.
581
+ */
582
+ function setupFailure(step, cause, baseCtx) {
583
+ if (cause instanceof Error && !isRpcError(cause)) {
584
+ return cause;
523
585
  }
524
- const message = Reflect.get(cause, 'message');
525
- const data = Reflect.get(cause, 'data');
526
- const head = typeof message === 'string' ? message : JSON.stringify(cause);
527
- return data === undefined ? head : `${head}: ${JSON.stringify(data)}`;
586
+ return turnFailure(step, cause, baseCtx);
528
587
  }
529
588
  /**
530
589
  * The tools the agent is served. No `tools` offers every tool the run has,
@@ -558,12 +617,21 @@ async function runTurn(params) {
558
617
  bridge.begin();
559
618
  let result;
560
619
  try {
561
- result = await resolution.live.session.prompt({
562
- content: params.content,
563
- // Per-turn signal, so a session reused across turns is cancelled by the
564
- // context running the CURRENT turn rather than the one that opened it.
565
- signal: abortSignalOf(baseCtx),
566
- });
620
+ // Per-turn signal, so a session reused across turns is cancelled by the
621
+ // context running the CURRENT turn rather than the one that opened it.
622
+ const signal = abortSignalOf(baseCtx);
623
+ const session = resolution.live.session;
624
+ const collected = params.collect && session.resumeTurn
625
+ ? await session.resumeTurn({
626
+ signal,
627
+ })
628
+ : undefined;
629
+ result =
630
+ collected ??
631
+ (await session.prompt({
632
+ content: params.content,
633
+ signal,
634
+ }));
567
635
  }
568
636
  catch (e) {
569
637
  await settle(tools);
@@ -647,9 +715,12 @@ export async function executeAcpAgent(step, input, ctx, layers) {
647
715
  // An earlier attempt of this step may have left its session behind.
648
716
  const sessions = step.session?.load ? undefined : acpSessionRecords(baseCtx);
649
717
  const recorded = await sessions?.load();
650
- const resumeId = recorded?.agentId === agent.agentId ? recorded.sessionId : undefined;
718
+ const sameAgent = recorded?.agentId === agent.agentId;
719
+ const resumeId = sameAgent ? recorded?.sessionId : undefined;
720
+ const reattach = sameAgent ? recorded?.reattach : undefined;
651
721
  // `session/load` replays the session's conversation as updates. They are the
652
- // agent's history, not this turn's work, so they are not forwarded.
722
+ // agent's history, not this turn's work: they reach raw-event consumers
723
+ // marked `replay: true`, and never the text, reasoning or item streams.
653
724
  let reloading = false;
654
725
  let bridge = new AcpEventBridge(step, agent.agentId, baseCtx);
655
726
  // A tool pipeline error fails the step, as it does in `callModel`: it is
@@ -663,6 +734,7 @@ export async function executeAcpAgent(step, input, ctx, layers) {
663
734
  layers,
664
735
  onUpdate: (notification) => {
665
736
  if (reloading) {
737
+ events.forwardReplay(notification);
666
738
  return;
667
739
  }
668
740
  tools?.observe(notification.update);
@@ -685,7 +757,9 @@ export async function executeAcpAgent(step, input, ctx, layers) {
685
757
  ...bindingFor(bridge),
686
758
  cwd,
687
759
  });
688
- reloading = resumeId !== undefined;
760
+ // Both an explicit `session.load` and the resume of an earlier attempt's
761
+ // session load it; a reused live session is not reloaded and replays nothing.
762
+ reloading = resumeId !== undefined || step.session?.load !== undefined;
689
763
  const resolution = await openSession({
690
764
  step,
691
765
  agent,
@@ -695,7 +769,12 @@ export async function executeAcpAgent(step, input, ctx, layers) {
695
769
  binding: bindingFor(bridge),
696
770
  tools,
697
771
  resumeId,
698
- }).finally(() => {
772
+ reattach,
773
+ })
774
+ .catch((cause) => {
775
+ throw setupFailure(step, cause, baseCtx);
776
+ })
777
+ .finally(() => {
699
778
  reloading = false;
700
779
  });
701
780
  if (resolution.resumed) {
@@ -705,9 +784,13 @@ export async function executeAcpAgent(step, input, ctx, layers) {
705
784
  await sessions?.write({
706
785
  sessionId: resolution.live.session.sessionId,
707
786
  agentId: agent.agentId,
787
+ // How a resumed run reaches this agent if it outlives this host.
788
+ reattach: resolution.live.connection.reattach,
708
789
  });
709
790
  }
710
- await applySessionSelection(step, ctx, resolution, baseCtx);
791
+ await applySessionSelection(step, ctx, resolution, baseCtx).catch((cause) => {
792
+ throw setupFailure(step, cause, baseCtx);
793
+ });
711
794
  turnError.cancel = () => resolution.live.session.cancel();
712
795
  // History seeds only a freshly opened session; a reused one already owns
713
796
  // its conversation on the agent side.
@@ -739,6 +822,7 @@ export async function executeAcpAgent(step, input, ctx, layers) {
739
822
  bridge,
740
823
  tools,
741
824
  turnError,
825
+ collect: retries === 0 && resolution.reattached,
742
826
  content: buildContent({
743
827
  text: [
744
828
  context,
Binary file
@@ -305,6 +305,8 @@ export declare class StepLedger {
305
305
  get isEmpty(): boolean;
306
306
  /** What retention has done so far. A snapshot — safe to hold. */
307
307
  get stats(): StepLedgerStats;
308
+ /** Entries available to replay when a turn resumes. */
309
+ savedEntries(): Iterable<StepLedgerEntry>;
308
310
  /**
309
311
  * The recorded entry for `path`, when a previous run completed the same step there on
310
312
  * the same input. A divergence — a different step id, kind, or input — returns
@@ -489,6 +489,10 @@ export class StepLedger {
489
489
  ...this.counts,
490
490
  };
491
491
  }
492
+ /** Entries available to replay when a turn resumes. */
493
+ savedEntries() {
494
+ return this.replayable.values();
495
+ }
492
496
  /**
493
497
  * The recorded entry for `path`, when a previous run completed the same step there on
494
498
  * the same input. A divergence — a different step id, kind, or input — returns
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A readable message for anything thrown. JSON-RPC peers (an ACP agent) reject
3
+ * with `{ code, message, data }` — as a plain object or as an `Error` carrying
4
+ * `code`/`data` — and the useful part ("Authentication required") is often in
5
+ * `data`, so it is appended rather than lost as `[object Object]` or a bare
6
+ * "Internal error".
7
+ */
8
+ export declare function errorMessage(cause: unknown): string;
9
+ /**
10
+ * The error a step fails with for a JSON-RPC rejection: the readable message,
11
+ * keeping the rejection's `code` and `data` (and the original as `cause`) for
12
+ * callers that branch on them, such as an auth-required code.
13
+ */
14
+ export declare class RpcFailure extends Error {
15
+ readonly code?: number;
16
+ readonly data?: unknown;
17
+ constructor(cause: unknown);
18
+ }
19
+ /**
20
+ * Whether a thrown value is a JSON-RPC error: it carries a numeric `code` or a
21
+ * `data` payload. A `DOMException` (an AbortError, a TimeoutError) has a
22
+ * numeric legacy `code` too, and is not one.
23
+ */
24
+ export declare function isRpcError(cause: unknown): boolean;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * A readable message for anything thrown. JSON-RPC peers (an ACP agent) reject
3
+ * with `{ code, message, data }` — as a plain object or as an `Error` carrying
4
+ * `code`/`data` — and the useful part ("Authentication required") is often in
5
+ * `data`, so it is appended rather than lost as `[object Object]` or a bare
6
+ * "Internal error".
7
+ */
8
+ export function errorMessage(cause) {
9
+ if (typeof cause !== 'object' || cause === null) {
10
+ return String(cause);
11
+ }
12
+ if (!isRpcError(cause)) {
13
+ const message = Reflect.get(cause, 'message');
14
+ if (typeof message === 'string') {
15
+ return message;
16
+ }
17
+ return safeJson(cause);
18
+ }
19
+ const rawMessage = Reflect.get(cause, 'message');
20
+ const message = typeof rawMessage === 'string' && rawMessage.length > 0 ? rawMessage : undefined;
21
+ const code = Reflect.get(cause, 'code');
22
+ const detail = detailOf(Reflect.get(cause, 'data'));
23
+ const parts = [
24
+ message ?? (detail === undefined ? 'JSON-RPC error' : undefined),
25
+ detail !== undefined && detail !== message ? detail : undefined,
26
+ ].filter((part) => part !== undefined);
27
+ const text = parts.join(': ');
28
+ return typeof code === 'number' ? `${text} (${code})` : text;
29
+ }
30
+ /**
31
+ * The error a step fails with for a JSON-RPC rejection: the readable message,
32
+ * keeping the rejection's `code` and `data` (and the original as `cause`) for
33
+ * callers that branch on them, such as an auth-required code.
34
+ */
35
+ export class RpcFailure extends Error {
36
+ code;
37
+ data;
38
+ constructor(cause) {
39
+ super(errorMessage(cause), {
40
+ cause,
41
+ });
42
+ this.name = 'RpcFailure';
43
+ const code = typeof cause === 'object' && cause !== null ? Reflect.get(cause, 'code') : undefined;
44
+ this.code = typeof code === 'number' ? code : undefined;
45
+ this.data =
46
+ typeof cause === 'object' && cause !== null ? Reflect.get(cause, 'data') : undefined;
47
+ }
48
+ }
49
+ /** The detail a JSON-RPC error's `data` carries: its message, its details, or the value itself. */
50
+ function detailOf(data) {
51
+ if (data === undefined || data === null) {
52
+ return undefined;
53
+ }
54
+ if (typeof data === 'string') {
55
+ return data;
56
+ }
57
+ if (typeof data !== 'object') {
58
+ return String(data);
59
+ }
60
+ for (const key of [
61
+ 'message',
62
+ 'details',
63
+ ]) {
64
+ const value = Reflect.get(data, key);
65
+ if (typeof value === 'string' && value.length > 0) {
66
+ return value;
67
+ }
68
+ }
69
+ return safeJson(data);
70
+ }
71
+ const MAX_DETAIL_CHARS = 500;
72
+ function safeJson(value) {
73
+ try {
74
+ const text = JSON.stringify(value) ?? String(value);
75
+ return text.length > MAX_DETAIL_CHARS ? `${text.slice(0, MAX_DETAIL_CHARS)}…` : text;
76
+ }
77
+ catch {
78
+ return String(value);
79
+ }
80
+ }
81
+ /**
82
+ * Whether a thrown value is a JSON-RPC error: it carries a numeric `code` or a
83
+ * `data` payload. A `DOMException` (an AbortError, a TimeoutError) has a
84
+ * numeric legacy `code` too, and is not one.
85
+ */
86
+ export function isRpcError(cause) {
87
+ if (typeof cause !== 'object' || cause === null) {
88
+ return false;
89
+ }
90
+ if (typeof DOMException !== 'undefined' && cause instanceof DOMException) {
91
+ return false;
92
+ }
93
+ return typeof Reflect.get(cause, 'code') === 'number' || Reflect.get(cause, 'data') !== undefined;
94
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.22.0-next.4",
3
+ "version": "5.22.0-next.6",
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": "^2.0.0-next.1",
72
- "@noetic-tools/types": "^3.19.0-next.3",
72
+ "@noetic-tools/types": "^3.19.0-next.5",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "jsonata": "2.2.2",