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

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.
@@ -72,6 +72,12 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
72
72
  private readonly leaseOptions?;
73
73
  /** The flow version this harness runs, when the host names one. */
74
74
  private readonly version?;
75
+ /** Set with the lease: how cut turns are run again, and each thread's cut mark. */
76
+ private readonly cuts?;
77
+ /** The cut each cut turn's context ended with, for its response. */
78
+ private readonly cutOfContext;
79
+ /** The `execute()` options a stored turn is woken with when none are given. */
80
+ private readonly turnOptionsFor?;
75
81
  /** Set when turns park (`environment.storage.park`): the grace before one does. */
76
82
  private readonly parkGraceMs?;
77
83
  /** Set when this harness wakes the turns it parked (`park.autoWake`). */
@@ -332,8 +338,11 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
332
338
  * it knows the event a parked turn waits for has arrived. A turn another harness
333
339
  * holds, or one already running here, is left alone.
334
340
  *
341
+ * A turn that was cut (spec 23 § Cut turns) is due once its back-off is over.
342
+ *
335
343
  * A resumed turn replays what it finished and goes on. `options` are the
336
- * `execute()` options it runs with; a stored turn keeps none of its own.
344
+ * `execute()` options it runs with; a stored turn keeps none of its own, so
345
+ * without them the harness asks `AgentHarnessOpts.turnOptions`.
337
346
  *
338
347
  * Resolves the ids of the threads it resumed. Durable sessions only.
339
348
  * @public
@@ -342,6 +351,28 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
342
351
  threadId?: string;
343
352
  options?: ExecuteOptions;
344
353
  }): Promise<string[]>;
354
+ /**
355
+ * A turn stopped by `lease_lost` or `ledger_write_failed` is cut, not failed
356
+ * (spec 23 § Cut turns): its record stays, marked, and a wake runs it again once
357
+ * its back-off is over. Resolves false when `error` does not cut the turn, or the
358
+ * turn has been cut as often as it may be and fails instead.
359
+ */
360
+ private closeOutCut;
361
+ /**
362
+ * Another holder took the turn (spec 23 § Cut turns, A replaced harness). The
363
+ * turn is theirs: this harness writes nothing to it, counts nothing, and leaves
364
+ * its own queue alone. It is cut only while it is still on record under this
365
+ * execution, when a wake can pick it up should that holder die; otherwise the
366
+ * other holder ended it, and the response fails as before.
367
+ */
368
+ private closeOutLostLease;
369
+ /**
370
+ * Record the end of a turn whose work is done. Resolves true when that write was
371
+ * refused and the turn was cut instead: a wake replays it to here.
372
+ */
373
+ private keepOrCut;
374
+ /** The options a stored turn is woken with when the wake names none: `turnOptions`, or none. */
375
+ private storedTurnOptions;
345
376
  /**
346
377
  * The earliest time the harness has something to do, in epoch ms: a parked turn
347
378
  * that needs waking, or the next event of a scheduled source a trigger listens
@@ -697,6 +728,8 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
697
728
  getChannelHandle<T>(channel: ExternalChannel<T>, executionId: string): ChannelHandle<T>;
698
729
  getChannelStream<T>(channel: ExternalChannel<T>, executionId: string): AsyncIterable<T>;
699
730
  /** Resolves layer-provided tools and merges with step tools into ctx.unifiedTools. */
731
+ /** The tools a session turn offers: its own first (one named like another replaces it), then the flow's, the harness's and its connections'. */
732
+ private setTurnTools;
700
733
  private setUnifiedTools;
701
734
  private toExecCtx;
702
735
  initLayers(layers: ContextLayer[], ctx: Context, storage: StorageAdapter): Promise<void>;
@@ -24,6 +24,7 @@ import { readDecision } from './read-decision.js';
24
24
  import { recordedToolCalls } from './recorded-tool-calls.js';
25
25
  import { Spend } from './spend.js';
26
26
  import { ThreadRecord } from './thread-record.js';
27
+ import { TurnCuts } from './turn-cuts.js';
27
28
  /** Keep `message` in storage for after the thread's parked turn, with its options. */
28
29
  function keepForLater(session, record, message) {
29
30
  session.keptOptions.set(message.id, message.options);
@@ -77,6 +78,8 @@ function isLeaseLost(error) {
77
78
  const LEASE_WAIT_MARGIN_MS = 1e3;
78
79
  /** What a turn's run resolves to when it parked instead of finishing. */
79
80
  const PARKED = Symbol('parked');
81
+ /** What a turn's run resolves to when it was cut instead of failing (spec 23 § Cut turns). */
82
+ const CUT = Symbol('cut');
80
83
  /** When the turn on `ctx` parked until, or undefined when it did not park. */
81
84
  function parkedUntil(ctx) {
82
85
  if (ctx.abortReason !== PARK_REASON || !(ctx instanceof ContextImpl)) {
@@ -205,6 +208,12 @@ export class AgentHarness {
205
208
  leaseOptions;
206
209
  /** The flow version this harness runs, when the host names one. */
207
210
  version;
211
+ /** Set with the lease: how cut turns are run again, and each thread's cut mark. */
212
+ cuts;
213
+ /** The cut each cut turn's context ended with, for its response. */
214
+ cutOfContext = new WeakMap();
215
+ /** The `execute()` options a stored turn is woken with when none are given. */
216
+ turnOptionsFor;
208
217
  /** Set when turns park (`environment.storage.park`): the grace before one does. */
209
218
  parkGraceMs;
210
219
  /** Set when this harness wakes the turns it parked (`park.autoWake`). */
@@ -360,6 +369,8 @@ export class AgentHarness {
360
369
  now: opts.now,
361
370
  ...storageEnv?.lease,
362
371
  });
372
+ this.cuts = this.leaseOptions ? new TurnCuts(storageEnv?.lease?.cut) : undefined;
373
+ this.turnOptionsFor = opts.turnOptions;
363
374
  this.parkGraceMs = resolveParkGrace(this.leaseOptions ? storageEnv?.park : undefined);
364
375
  this.parkWatchers = this.createParkWatchers(storageEnv?.park);
365
376
  this.spend = this.checkpointStore
@@ -915,6 +926,7 @@ export class AgentHarness {
915
926
  await record.answered(ctx, answer);
916
927
  }
917
928
  await record.end(ctx, ctx.itemLog.items, session.runner.queue.peekAll().map((message) => message.id));
929
+ this.cuts?.forget(threadId);
918
930
  return;
919
931
  }
920
932
  session.accumulatedItems = [
@@ -971,6 +983,7 @@ export class AgentHarness {
971
983
  }
972
984
  }
973
985
  },
986
+ cutOf: (ctx) => this.cutOfContext.get(ctx),
974
987
  heldCalls: async (ctx) => (await heldCallsOf(this).list(rootIdOf(ctx)))
975
988
  .filter((held) => held.resolution === undefined)
976
989
  .map(toHeldCall),
@@ -988,6 +1001,7 @@ export class AgentHarness {
988
1001
  session.turnOptions = perTurnOptions;
989
1002
  this.parkWatchers?.stop(threadId);
990
1003
  const messageIds = messages.map((m) => m.id);
1004
+ session.turnMessageIds = messageIds;
991
1005
  const history = record ? await record.history() : session.accumulatedItems;
992
1006
  const graph = this.agentGraph ? frameworkCast(this.agentGraph) : undefined;
993
1007
  const views = this.#connections.turnViews(perTurnOptions.connections, graph);
@@ -1031,14 +1045,7 @@ export class AgentHarness {
1031
1045
  frameworkCast(ctx)._sessionQueue = session.runner.queue;
1032
1046
  await this.start();
1033
1047
  const connectionTools = await this.#connections.openTurn(ctx, perTurnOptions.connections, graph);
1034
- if (this.agentGraph || this.harnessTools.length > 0 || connectionTools.length > 0) {
1035
- const stepTools = this.agentGraph ? collectAllTools(this.agentGraph) : [];
1036
- this.setUnifiedTools(ctx, [
1037
- ...stepTools,
1038
- ...this.harnessTools,
1039
- ...connectionTools,
1040
- ]);
1041
- }
1048
+ this.setTurnTools(ctx, perTurnOptions.tools ?? [], connectionTools);
1042
1049
  // Steers the last harness accepted but never applied go back in the queue;
1043
1050
  // ones already in the conversation are skipped when offered.
1044
1051
  for (const steer of (await record?.steers()) ?? []) {
@@ -1091,11 +1098,12 @@ export class AgentHarness {
1091
1098
  }
1092
1099
  const until = Number.isFinite(wakeAt) ? wakeAt : undefined;
1093
1100
  await record.park(ctx, until);
1101
+ this.cuts?.forget(threadId);
1094
1102
  await this.#connections.release(ctx.id);
1095
1103
  this.parkWatchers?.watch(threadId, {
1096
1104
  executionId: ctx.id,
1097
1105
  until,
1098
- options: session.turnOptions ?? {},
1106
+ options: session.turnOptions,
1099
1107
  });
1100
1108
  // Before the turn answers as parked: whoever wakes it has to know when.
1101
1109
  await this.announceWakeTime();
@@ -1132,6 +1140,11 @@ export class AgentHarness {
1132
1140
  if (await closeOutPark(ctx)) {
1133
1141
  return PARKED;
1134
1142
  }
1143
+ // Cut short with everything before the stop on record: run again later.
1144
+ if (await this.closeOutCut(session, ctx, error)) {
1145
+ return CUT;
1146
+ }
1147
+ this.cuts?.forget(threadId);
1135
1148
  // The turn ended here, in a live process. Say so, or a routine wake would
1136
1149
  // take it for one cut off by a crash and run it again, every time.
1137
1150
  // It stopped rather than redo a recorded effect under a newer flow version:
@@ -1158,10 +1171,12 @@ export class AgentHarness {
1158
1171
  });
1159
1172
  // A flow that caught the wait's cancellation and returned is parked all the
1160
1173
  // same: the wait it was in has not ended, and the woken turn goes back to it.
1161
- if (result === PARKED || (await closeOutPark(ctx))) {
1174
+ if (result === CUT || result === PARKED || (await closeOutPark(ctx))) {
1175
+ return '';
1176
+ }
1177
+ if (await this.keepOrCut(session, ctx, () => keepHistory(ctx, result))) {
1162
1178
  return '';
1163
1179
  }
1164
- await keepHistory(ctx, result);
1165
1180
  this.parkWatchers?.forget(threadId, ctx.id);
1166
1181
  await this.announceWakeTimeQuietly();
1167
1182
  return result;
@@ -1185,8 +1200,11 @@ export class AgentHarness {
1185
1200
  * it knows the event a parked turn waits for has arrived. A turn another harness
1186
1201
  * holds, or one already running here, is left alone.
1187
1202
  *
1203
+ * A turn that was cut (spec 23 § Cut turns) is due once its back-off is over.
1204
+ *
1188
1205
  * A resumed turn replays what it finished and goes on. `options` are the
1189
- * `execute()` options it runs with; a stored turn keeps none of its own.
1206
+ * `execute()` options it runs with; a stored turn keeps none of its own, so
1207
+ * without them the harness asks `AgentHarnessOpts.turnOptions`.
1190
1208
  *
1191
1209
  * Resolves the ids of the threads it resumed. Durable sessions only.
1192
1210
  * @public
@@ -1221,14 +1239,16 @@ export class AgentHarness {
1221
1239
  // A routine wake leaves alone a parked turn that is not due, one with no
1222
1240
  // deadline at all (it waits for an answer, not for a time), and one that
1223
1241
  // failed or was cancelled here: only a turn cut off by a crash resumes unasked.
1224
- const notDue = turn.parked && (turn.parked.until === undefined || turn.parked.until > now);
1242
+ const cut = turn.parked ? undefined : this.cuts?.markOf(threadId, turn);
1243
+ const notDue = (turn.parked && (turn.parked.until === undefined || turn.parked.until > now)) ||
1244
+ (cut !== undefined && this.cuts !== undefined && this.cuts.dueAt(cut) > now);
1225
1245
  if (!scope?.threadId && (notDue || (turn.stopped && !turn.parked))) {
1226
1246
  // A parked turn found in storage, as at boot, is watched over from here on.
1227
1247
  if (turn.parked && this.parkWatchers && !this.parkWatchers.has(threadId)) {
1228
1248
  this.parkWatchers.watch(threadId, {
1229
1249
  executionId: turn.executionId,
1230
1250
  until: turn.parked.until,
1231
- options: scope?.options ?? {},
1251
+ options: scope?.options,
1232
1252
  });
1233
1253
  }
1234
1254
  continue;
@@ -1244,6 +1264,7 @@ export class AgentHarness {
1244
1264
  if (held && !scope?.threadId) {
1245
1265
  continue;
1246
1266
  }
1267
+ const options = scope?.options ?? (await this.storedTurnOptions(threadId, turn, cut));
1247
1268
  // Re-deliver the turn's own messages: the same ids resume it, and a resumed
1248
1269
  // turn reads its input from its checkpoint, not from these. They go back as
1249
1270
  // one arrival: handed over one at a time, the first would start a turn of
@@ -1252,13 +1273,124 @@ export class AgentHarness {
1252
1273
  id,
1253
1274
  input: [],
1254
1275
  deliveryMode: 'next-turn',
1255
- options: scope?.options ?? {},
1276
+ options,
1256
1277
  enqueuedAt: Date.now(),
1257
1278
  })));
1258
1279
  woken.push(threadId);
1259
1280
  }
1260
1281
  return woken;
1261
1282
  }
1283
+ /**
1284
+ * A turn stopped by `lease_lost` or `ledger_write_failed` is cut, not failed
1285
+ * (spec 23 § Cut turns): its record stays, marked, and a wake runs it again once
1286
+ * its back-off is over. Resolves false when `error` does not cut the turn, or the
1287
+ * turn has been cut as often as it may be and fails instead.
1288
+ */
1289
+ async closeOutCut(session, ctx, error) {
1290
+ const { record } = session;
1291
+ const { threadId } = session.runner;
1292
+ const reason = this.cuts?.reasonOf(error);
1293
+ if (!reason || !record || !this.cuts || !this.leaseOptions) {
1294
+ return false;
1295
+ }
1296
+ // The storage that refused a write may refuse this read: the mark in memory counts then.
1297
+ const stored = await record.turn().catch(() => undefined);
1298
+ if (reason === 'lease_lost') {
1299
+ return this.closeOutLostLease(threadId, ctx, stored);
1300
+ }
1301
+ const messageIds = stored?.executionId === ctx.id ? stored.messageIds : session.turnMessageIds;
1302
+ const mark = this.cuts.cut(threadId, {
1303
+ messageIds: messageIds ?? [],
1304
+ cut: stored?.executionId === ctx.id ? stored.cut : undefined,
1305
+ }, reason, this.now());
1306
+ if (!mark) {
1307
+ return false;
1308
+ }
1309
+ await record.cut(ctx, mark);
1310
+ // Messages still queued wait in storage, as for a park: one that started a turn
1311
+ // now would throw the cut turn away.
1312
+ const interrupts = [];
1313
+ for (const queued of session.runner.queue.drainAll()) {
1314
+ if (queued.deliveryMode === 'interrupt') {
1315
+ interrupts.push(queued);
1316
+ continue;
1317
+ }
1318
+ await keepForLater(session, record, queued);
1319
+ }
1320
+ for (const interrupt of interrupts.reverse()) {
1321
+ session.runner.queue.prepend(interrupt);
1322
+ }
1323
+ this.cutOfContext.set(ctx, {
1324
+ reason,
1325
+ attempt: mark.count,
1326
+ wakeAt: this.cuts.dueAt(mark),
1327
+ });
1328
+ // Before the turn answers as cut: whoever wakes it has to know when.
1329
+ await this.announceWakeTimeQuietly();
1330
+ return true;
1331
+ }
1332
+ /**
1333
+ * Another holder took the turn (spec 23 § Cut turns, A replaced harness). The
1334
+ * turn is theirs: this harness writes nothing to it, counts nothing, and leaves
1335
+ * its own queue alone. It is cut only while it is still on record under this
1336
+ * execution, when a wake can pick it up should that holder die; otherwise the
1337
+ * other holder ended it, and the response fails as before.
1338
+ */
1339
+ async closeOutLostLease(threadId, ctx, stored) {
1340
+ if (!this.leaseOptions || stored?.executionId !== ctx.id || stored.parked || stored.stopped) {
1341
+ return false;
1342
+ }
1343
+ const heldUntil = await heldElsewhereUntil(this.leaseOptions, threadId).catch(() => undefined);
1344
+ this.cutOfContext.set(ctx, {
1345
+ reason: 'lease_lost',
1346
+ wakeAt: heldUntil ?? this.now(),
1347
+ });
1348
+ await this.announceWakeTimeQuietly();
1349
+ return true;
1350
+ }
1351
+ /**
1352
+ * Record the end of a turn whose work is done. Resolves true when that write was
1353
+ * refused and the turn was cut instead: a wake replays it to here.
1354
+ */
1355
+ async keepOrCut(session, ctx, keep) {
1356
+ try {
1357
+ await keep();
1358
+ return false;
1359
+ }
1360
+ catch (error) {
1361
+ if (await this.closeOutCut(session, ctx, error)) {
1362
+ return true;
1363
+ }
1364
+ this.cuts?.forget(session.runner.threadId);
1365
+ throw error;
1366
+ }
1367
+ }
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 {};
1372
+ }
1373
+ return await this.turnOptionsFor({
1374
+ threadId,
1375
+ executionId: turn.executionId,
1376
+ messageIds: turn.messageIds,
1377
+ ...(turn.version === undefined
1378
+ ? {}
1379
+ : {
1380
+ version: turn.version,
1381
+ }),
1382
+ ...(turn.parked
1383
+ ? {
1384
+ parked: turn.parked,
1385
+ }
1386
+ : {}),
1387
+ ...(cut
1388
+ ? {
1389
+ cut,
1390
+ }
1391
+ : {}),
1392
+ });
1393
+ }
1262
1394
  /**
1263
1395
  * The earliest time the harness has something to do, in epoch ms: a parked turn
1264
1396
  * that needs waking, or the next event of a scheduled source a trigger listens
@@ -1298,15 +1430,17 @@ export class AgentHarness {
1298
1430
  return undefined;
1299
1431
  }
1300
1432
  // A turn with no park on record is cut off, unless it is simply running here.
1301
- // (One that is parked may still be closing out in this process: it counts.)
1433
+ // (One that is parked, or cut, may still be closing out in this process: it counts.)
1302
1434
  const runner = this.sessions.get(threadId)?.runner;
1303
- if (!turn.parked && runner && runner.getStatus().kind !== 'idle') {
1435
+ const closingCut = runner?.context !== undefined && this.cutOfContext.has(runner.context);
1436
+ if (!turn.parked && runner && runner.getStatus().kind !== 'idle' && !closingCut) {
1304
1437
  // Running here. Should this process die, the turn is cut off, and it can be
1305
1438
  // picked up once the lease it held has run out: that is when to look again.
1306
1439
  // The turn ending, or parking, replaces this time with the real one.
1307
1440
  return this.leaseOptions ? now + this.leaseOptions.ttlMs + LEASE_WAIT_MARGIN_MS : undefined;
1308
1441
  }
1309
- const due = turn.parked?.until ?? now;
1442
+ const cut = turn.parked ? undefined : this.cuts?.markOf(threadId, turn);
1443
+ const due = turn.parked?.until ?? (cut && this.cuts ? this.cuts.dueAt(cut) : now);
1310
1444
  const heldUntil = this.leaseOptions
1311
1445
  ? await heldElsewhereUntil(this.leaseOptions, threadId)
1312
1446
  : undefined;
@@ -1583,6 +1717,7 @@ export class AgentHarness {
1583
1717
  }
1584
1718
  finally {
1585
1719
  this.forgetting.delete(threadId);
1720
+ this.cuts?.forget(threadId);
1586
1721
  await this.announceWakeTimeQuietly();
1587
1722
  }
1588
1723
  }
@@ -1735,7 +1870,8 @@ export class AgentHarness {
1735
1870
  */
1736
1871
  async setAside(session, record, messages) {
1737
1872
  const turn = await record.turn();
1738
- if (!turn || (!turn.parked && !turn.stuck)) {
1873
+ const cut = turn ? this.cuts?.markOf(session.runner.threadId, turn) : undefined;
1874
+ if (!turn || (!turn.parked && !turn.stuck && !cut)) {
1739
1875
  return false;
1740
1876
  }
1741
1877
  if (messages.some((message) => message.deliveryMode === 'interrupt')) {
@@ -2360,6 +2496,16 @@ export class AgentHarness {
2360
2496
  return this.channelStore.subscribe(channel, executionId);
2361
2497
  }
2362
2498
  /** Resolves layer-provided tools and merges with step tools into ctx.unifiedTools. */
2499
+ /** The tools a session turn offers: its own first (one named like another replaces it), then the flow's, the harness's and its connections'. */
2500
+ setTurnTools(ctx, turnTools, connectionTools) {
2501
+ const stepTools = this.agentGraph ? collectAllTools(this.agentGraph) : [];
2502
+ this.setUnifiedTools(ctx, [
2503
+ ...turnTools,
2504
+ ...stepTools,
2505
+ ...this.harnessTools,
2506
+ ...connectionTools,
2507
+ ]);
2508
+ }
2363
2509
  setUnifiedTools(ctx, stepTools) {
2364
2510
  const layers = ctx.layers;
2365
2511
  const layerTools = layers && layers.length > 0 ? resolveLayerTools(layers, this, ctx) : [];
@@ -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, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, 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, 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';
3
3
  export { SteeringAction } from '@noetic-tools/types';
4
4
  export type { ZodType } from 'zod';
@@ -2,7 +2,7 @@ import type { ArtifactStore, ConnectionEntries, ConnectionTrigger, SecretResolve
2
2
  import type { Verifier } from '@noetic-tools/types/verify';
3
3
  import type { LayerStateStore } from './deps/context.js';
4
4
  import type { CheckpointStore, StepLedgerRetention } from './deps/runtime.js';
5
- import type { AgentHooks, CallModelRequest, ContextCacheConfig, ContextData, ContextLayer, CustomItem, CustomItemsBrand, DecideRequest, DecideResponse, DeliveryMode, FsAdapter, HeldCallHandler, HeldSteerPolicy, ItemSchemaConfig, LLMResponse, LlmProviderConfig, ProjectionPolicy, ShellAdapter, Steps, StorageAdapter, SubprocessAdapter, Tool, ToolApprover, TraceExporter, ZodType } from './deps/types.js';
5
+ import type { AgentHooks, CallModelRequest, ContextCacheConfig, ContextData, ContextLayer, CustomItem, CustomItemsBrand, DecideRequest, DecideResponse, DeliveryMode, ExecuteOptions, FsAdapter, HeldCallHandler, HeldSteerPolicy, ItemSchemaConfig, LLMResponse, LlmProviderConfig, ProjectionPolicy, ShellAdapter, Steps, StorageAdapter, StoredTurn, SubprocessAdapter, Tool, ToolApprover, TraceExporter, ZodType } from './deps/types.js';
6
6
  /**
7
7
  * Storage-scoped environment configuration for `AgentHarness`.
8
8
  *
@@ -99,6 +99,23 @@ export interface TurnLeaseConfig {
99
99
  waitMs?: number;
100
100
  /** The clock leases are timed by. Default `Date.now`. */
101
101
  now?: () => number;
102
+ /**
103
+ * How a turn cut by `lease_lost` or `ledger_write_failed` is run again (spec 23
104
+ * § Cut turns). Every field has a default.
105
+ */
106
+ cut?: TurnCutConfig;
107
+ }
108
+ /** @public Settings for cut turns (spec 23 § Cut turns). */
109
+ export interface TurnCutConfig {
110
+ /**
111
+ * How many times a turn may be cut and run again. The cut after that fails the
112
+ * turn. Default `DEFAULT_CUT_ATTEMPTS` (3); `0` fails every turn that would be cut.
113
+ */
114
+ attempts?: number;
115
+ /** How long after its first cut a turn is due again, in ms; doubled for each cut after. Default 1 000. */
116
+ delayMs?: number;
117
+ /** The longest a cut turn waits before it is due again, in ms. Default 60 000. */
118
+ maxDelayMs?: number;
102
119
  }
103
120
  /**
104
121
  * Execution-environment configuration for `AgentHarness`: the storage,
@@ -224,6 +241,14 @@ export interface AgentHarnessOpts<TParams extends Record<string, unknown> = Reco
224
241
  * so a question a person was shown stays open.
225
242
  */
226
243
  steerWhileHeld?: HeldSteerPolicy;
244
+ /**
245
+ * The `execute()` options a stored turn runs with when `wake()` is given none
246
+ * (spec 23 § Parked turns). A stored turn keeps no options of its own, since they
247
+ * hold live objects: tools, layers, connections and their credentials. A host that
248
+ * passes per-turn options to `execute()` rebuilds them here, so a turn woken by an
249
+ * alarm in a fresh process runs as it began.
250
+ */
251
+ turnOptions?: (turn: StoredTurn) => ExecuteOptions | Promise<ExecuteOptions>;
227
252
  /**
228
253
  * The live things the agent works with — browsers, devices, apps, chat workspaces,
229
254
  * sources — keyed by name, or as a list of named entries (`[mcp({ name, … })]`)
@@ -40,7 +40,8 @@ export interface ParkWatcherHost {
40
40
  /** The state of one of them now, or undefined when it cannot be read. */
41
41
  taskState(task: ParkedTask, signal: AbortSignal): Promise<string | undefined>;
42
42
  /** Resume the thread's turn. Resolves false when it could not be resumed just now. */
43
- wake(threadId: string, options: ExecuteOptions): Promise<boolean>;
43
+ /** `options` undefined: the harness finds them (`turnOptions`). */
44
+ wake(threadId: string, options: ExecuteOptions | undefined): Promise<boolean>;
44
45
  /** The execution of the turn the thread has parked now, or undefined when it has none. */
45
46
  parked(threadId: string): Promise<string | undefined>;
46
47
  now(): number;
@@ -51,7 +52,7 @@ export interface ParkedTurn {
51
52
  /** When its earliest wait runs out, or undefined when none has a deadline. */
52
53
  readonly until: number | undefined;
53
54
  /** The `execute()` options the turn ran with, to resume it with. */
54
- readonly options: ExecuteOptions;
55
+ readonly options?: ExecuteOptions;
55
56
  }
56
57
  /** @public How long auto-wake waits after an event before waking a turn, so a burst wakes it once. */
57
58
  export declare const DEFAULT_WAKE_DEBOUNCE_MS = 250;
@@ -93,6 +93,17 @@ export declare class ThreadRecord {
93
93
  * checkpoint and ledger stay, since they are what the woken turn resumes from.
94
94
  */
95
95
  park(ctx: Context, until: number | undefined): Promise<void>;
96
+ /**
97
+ * The turn on `ctx` was cut (spec 23 § Cut turns): keep its record, marked with how
98
+ * often and when. Best-effort and unfenced: storage that just refused a write may
99
+ * refuse this one, and the harness keeps the mark in memory as well. Written only
100
+ * while the record still names the turn's execution.
101
+ */
102
+ cut(ctx: Context, cut: {
103
+ reason: string;
104
+ count: number;
105
+ at: number;
106
+ }): Promise<void>;
96
107
  /**
97
108
  * The turn on `ctx` ended here without finishing. Best-effort: a turn whose mark
98
109
  * does not land is simply taken for one that was cut off.
@@ -163,6 +163,14 @@ export class ThreadRecord {
163
163
  : {
164
164
  version: this.host.version,
165
165
  }),
166
+ // Kept until the turn ends, even when it resumes under a new execution (its
167
+ // checkpoint was not written): how often it was cut counts toward giving up.
168
+ ...(record.turn?.cut !== undefined &&
169
+ (record.turn.executionId === ctx.id || isSameList(record.turn.messageIds, messageIds))
170
+ ? {
171
+ cut: record.turn.cut,
172
+ }
173
+ : {}),
166
174
  // Kept until the turn ends: a host that dies part way through going on
167
175
  // must not find the same step stuck again.
168
176
  ...(record.turn?.executionId === ctx.id && record.turn.accept !== undefined
@@ -226,7 +234,7 @@ export class ThreadRecord {
226
234
  ? {
227
235
  ...record,
228
236
  turn: {
229
- ...record.turn,
237
+ ...withoutCut(record.turn),
230
238
  parked: until === undefined
231
239
  ? {}
232
240
  : {
@@ -236,6 +244,23 @@ export class ThreadRecord {
236
244
  }
237
245
  : record);
238
246
  }
247
+ /**
248
+ * The turn on `ctx` was cut (spec 23 § Cut turns): keep its record, marked with how
249
+ * often and when. Best-effort and unfenced: storage that just refused a write may
250
+ * refuse this one, and the harness keeps the mark in memory as well. Written only
251
+ * while the record still names the turn's execution.
252
+ */
253
+ cut(ctx, cut) {
254
+ return this.update((record) => record.turn?.executionId === ctx.id
255
+ ? {
256
+ ...record,
257
+ turn: {
258
+ ...record.turn,
259
+ cut,
260
+ },
261
+ }
262
+ : record);
263
+ }
239
264
  /**
240
265
  * The turn on `ctx` ended here without finishing. Best-effort: a turn whose mark
241
266
  * does not land is simply taken for one that was cut off.
@@ -245,7 +270,7 @@ export class ThreadRecord {
245
270
  ? {
246
271
  ...record,
247
272
  turn: {
248
- ...record.turn,
273
+ ...withoutCut(record.turn),
249
274
  stopped: {
250
275
  at,
251
276
  reason,
@@ -438,6 +463,11 @@ export class ThreadRecord {
438
463
  return next;
439
464
  }
440
465
  }
466
+ function withoutCut(turn) {
467
+ const { cut, ...rest } = turn;
468
+ void cut;
469
+ return rest;
470
+ }
441
471
  function withoutTurn(record) {
442
472
  const { turn, ...rest } = record;
443
473
  void turn;
@@ -450,6 +480,9 @@ function withoutTurn(record) {
450
480
  function isSameDelivery(turn, delivered) {
451
481
  return delivered.length > 0 && delivered.every((id) => turn.includes(id));
452
482
  }
483
+ function isSameList(a, b) {
484
+ return a.length === b.length && a.every((id, i) => id === b[i]);
485
+ }
453
486
  function addUsage(total, spent) {
454
487
  const cost = (total.cost ?? 0) + spent.cost;
455
488
  const billedCost = (total.billedCost ?? 0) + spent.billedCost;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Cut turns (spec 23 § Cut turns): a turn stopped by `lease_lost` or
3
+ * `ledger_write_failed` has everything before the stop on record, so it is run
4
+ * again by a later wake, with back-off, rather than failed. The harness keeps each
5
+ * thread's mark here as well as in the thread record, since the storage that just
6
+ * refused a write may refuse the mark too.
7
+ */
8
+ import type { TurnCutReason } from './deps/types.js';
9
+ import type { TurnCutConfig } from './harness-options.js';
10
+ /** How often a turn was cut, and when last. */
11
+ export interface CutMark {
12
+ readonly reason: string;
13
+ readonly count: number;
14
+ readonly at: number;
15
+ }
16
+ /**
17
+ * The parts of a stored turn a cut is read from. A turn is known by its messages,
18
+ * not its execution: one whose checkpoint could not be written resumes under a
19
+ * new execution id, and its cuts still count.
20
+ */
21
+ interface CutTurn {
22
+ readonly messageIds: ReadonlyArray<string>;
23
+ readonly cut?: CutMark;
24
+ }
25
+ /** @public How many times a turn may be cut and run again before it fails. */
26
+ export declare const DEFAULT_CUT_ATTEMPTS = 3;
27
+ /** @public How long after its first cut a turn is due again, in ms. */
28
+ export declare const DEFAULT_CUT_DELAY_MS = 1000;
29
+ /** @public The longest a cut turn waits before it is due again, in ms. */
30
+ export declare const DEFAULT_CUT_MAX_DELAY_MS = 60000;
31
+ /** @internal The harness's cut marks, by thread, and the policy that runs cut turns again. */
32
+ export declare class TurnCuts {
33
+ private readonly policy;
34
+ private readonly marks;
35
+ constructor(config: TurnCutConfig | undefined);
36
+ /** Why `error` cuts the turn rather than failing it, or undefined when it does not. */
37
+ reasonOf(error: unknown): TurnCutReason | undefined;
38
+ /** The turn's mark: the stored one or this harness's, whichever counts more cuts. */
39
+ markOf(threadId: string, turn: CutTurn): CutMark | undefined;
40
+ /**
41
+ * The mark for one more cut of the turn, kept here; undefined when the turn has
42
+ * been cut as often as the policy allows, and fails instead.
43
+ */
44
+ cut(threadId: string, turn: CutTurn, reason: TurnCutReason, at: number): CutMark | undefined;
45
+ /** When a turn with `mark` is due again. */
46
+ dueAt(mark: CutMark): number;
47
+ /** The thread's turn ended, parked or was dropped: its cuts no longer count. */
48
+ forget(threadId: string): void;
49
+ }
50
+ export {};
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Cut turns (spec 23 § Cut turns): a turn stopped by `lease_lost` or
3
+ * `ledger_write_failed` has everything before the stop on record, so it is run
4
+ * again by a later wake, with back-off, rather than failed. The harness keeps each
5
+ * thread's mark here as well as in the thread record, since the storage that just
6
+ * refused a write may refuse the mark too.
7
+ */
8
+ import { NoeticConfigError } from '@noetic-tools/types';
9
+ import { turnEndingIn } from '../interpreter/turn-ending.js';
10
+ //#endregion
11
+ //#region Constants
12
+ /** @public How many times a turn may be cut and run again before it fails. */
13
+ export const DEFAULT_CUT_ATTEMPTS = 3;
14
+ /** @public How long after its first cut a turn is due again, in ms. */
15
+ export const DEFAULT_CUT_DELAY_MS = 1e3;
16
+ /** @public The longest a cut turn waits before it is due again, in ms. */
17
+ export const DEFAULT_CUT_MAX_DELAY_MS = 6e4;
18
+ const CUT_REASONS = new Set([
19
+ 'lease_lost',
20
+ 'ledger_write_failed',
21
+ ]);
22
+ //#endregion
23
+ //#region Helpers
24
+ function isCutReason(kind) {
25
+ return kind !== undefined && CUT_REASONS.has(kind);
26
+ }
27
+ /** What names a turn's delivery: its message ids, in order. */
28
+ function deliveryOf(turn) {
29
+ return JSON.stringify(turn.messageIds);
30
+ }
31
+ function resolveCutPolicy(config) {
32
+ const attempts = config?.attempts ?? DEFAULT_CUT_ATTEMPTS;
33
+ const delayMs = config?.delayMs ?? DEFAULT_CUT_DELAY_MS;
34
+ const maxDelayMs = config?.maxDelayMs ?? DEFAULT_CUT_MAX_DELAY_MS;
35
+ const attemptsOk = Number.isInteger(attempts) && attempts >= 0;
36
+ const delayOk = Number.isFinite(delayMs) && delayMs >= 0;
37
+ const maxOk = Number.isFinite(maxDelayMs) && maxDelayMs >= delayMs;
38
+ if (!attemptsOk || !delayOk || !maxOk) {
39
+ throw new NoeticConfigError({
40
+ code: 'INVALID_LEASE_OPTIONS',
41
+ message: `environment.storage.lease.cut is not usable: attempts ${attempts}, delayMs ${delayMs}, maxDelayMs ${maxDelayMs}.`,
42
+ hint: 'Give attempts a whole number from 0 up, delayMs a finite number from 0 up, and maxDelayMs a finite number no less than delayMs, or leave them out for the defaults.',
43
+ });
44
+ }
45
+ return {
46
+ attempts,
47
+ delayMs,
48
+ maxDelayMs,
49
+ };
50
+ }
51
+ //#endregion
52
+ //#region TurnCuts
53
+ /** @internal The harness's cut marks, by thread, and the policy that runs cut turns again. */
54
+ export class TurnCuts {
55
+ policy;
56
+ marks = new Map();
57
+ constructor(config) {
58
+ this.policy = resolveCutPolicy(config);
59
+ }
60
+ /** Why `error` cuts the turn rather than failing it, or undefined when it does not. */
61
+ reasonOf(error) {
62
+ const kind = turnEndingIn(error)?.noeticError.kind;
63
+ return isCutReason(kind) ? kind : undefined;
64
+ }
65
+ /** The turn's mark: the stored one or this harness's, whichever counts more cuts. */
66
+ markOf(threadId, turn) {
67
+ const kept = this.marks.get(threadId);
68
+ const mine = kept?.delivery === deliveryOf(turn) ? kept : undefined;
69
+ if (!mine) {
70
+ return turn.cut;
71
+ }
72
+ if (!turn.cut || turn.cut.count < mine.count) {
73
+ return mine;
74
+ }
75
+ return turn.cut;
76
+ }
77
+ /**
78
+ * The mark for one more cut of the turn, kept here; undefined when the turn has
79
+ * been cut as often as the policy allows, and fails instead.
80
+ */
81
+ cut(threadId, turn, reason, at) {
82
+ const count = (this.markOf(threadId, turn)?.count ?? 0) + 1;
83
+ if (count > this.policy.attempts) {
84
+ this.marks.delete(threadId);
85
+ return undefined;
86
+ }
87
+ const mark = {
88
+ reason,
89
+ count,
90
+ at,
91
+ };
92
+ this.marks.set(threadId, {
93
+ ...mark,
94
+ delivery: deliveryOf(turn),
95
+ });
96
+ return mark;
97
+ }
98
+ /** When a turn with `mark` is due again. */
99
+ dueAt(mark) {
100
+ const delay = this.policy.delayMs * 2 ** Math.max(0, mark.count - 1);
101
+ return mark.at + Math.min(this.policy.maxDelayMs, delay);
102
+ }
103
+ /** The thread's turn ended, parked or was dropped: its cuts no longer count. */
104
+ forget(threadId) {
105
+ this.marks.delete(threadId);
106
+ }
107
+ }
108
+ //#endregion
package/dist/index.d.ts CHANGED
@@ -117,7 +117,7 @@ export { DEFAULT_EXPRESSION_LIMITS } from './expression/jsonata.js';
117
117
  /** @public */
118
118
  export { AgentHarness } from './harness/agent-harness.js';
119
119
  /** @public */
120
- export type { AgentEnvironmentConfig, ParkConfig, StorageEnvironmentConfig, TurnLeaseConfig, WakeTimeListener, } from './harness/harness-options.js';
120
+ export type { AgentEnvironmentConfig, ParkConfig, StorageEnvironmentConfig, TurnCutConfig, TurnLeaseConfig, WakeTimeListener, } from './harness/harness-options.js';
121
121
  /** @public */
122
122
  export { DEFAULT_TASK_POLL_MS, DEFAULT_WAKE_DEBOUNCE_MS } from './harness/park-watchers.js';
123
123
  /** @public */
@@ -179,9 +179,9 @@ export type { ContextScope, ExecutionContext, ExecutionOutcome, ExecutionSpan, L
179
179
  /** @public */
180
180
  export type { LayerTraceSpan, Span, TraceExporter } from '@noetic-tools/types';
181
181
  /** @public */
182
- export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent, StreamingItem, } from '@noetic-tools/types';
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, 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, ReanchorReason, RecallLayerOutput, RecordedToolCall, SessionScope, SessionUsage, 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 */
@@ -37,6 +37,11 @@ declare const SessionRecordSchema: z.ZodObject<{
37
37
  to: z.ZodString;
38
38
  }, z.core.$strip>>;
39
39
  accept: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
40
+ cut: z.ZodOptional<z.ZodObject<{
41
+ reason: z.ZodString;
42
+ count: z.ZodNumber;
43
+ at: z.ZodNumber;
44
+ }, z.core.$strip>>;
40
45
  parked: z.ZodOptional<z.ZodObject<{
41
46
  until: z.ZodOptional<z.ZodNumber>;
42
47
  }, z.core.$strip>>;
@@ -70,6 +70,18 @@ const SessionRecordSchema = z.object({
70
70
  z.string(),
71
71
  ])
72
72
  .optional(),
73
+ /**
74
+ * Set while the turn is cut (spec 23 § Cut turns): its lease was lost or a
75
+ * durable write failed, and a wake runs it again once its back-off is over.
76
+ * `count` is how many times it has been cut.
77
+ */
78
+ cut: z
79
+ .object({
80
+ reason: z.string(),
81
+ count: z.number(),
82
+ at: z.number(),
83
+ })
84
+ .optional(),
73
85
  /** Set while the turn is parked: every part of it waits, and no harness holds it. */
74
86
  parked: z
75
87
  .object({
@@ -1,4 +1,4 @@
1
- import type { Context, HarnessResponse, HarnessStatus, HeldCall, Item, SessionUsage } from '@noetic-tools/types';
1
+ import type { Context, HarnessResponse, HarnessStatus, HeldCall, Item, SessionUsage, TurnCut } from '@noetic-tools/types';
2
2
  import { EventBroadcaster } from './event-broadcaster.js';
3
3
  import type { QueuedMessage } from './message-queue.js';
4
4
  import { MessageQueue } from './message-queue.js';
@@ -38,6 +38,8 @@ export interface SessionRunnerOpts {
38
38
  readonly onTurnUsage?: (usage: TurnUsage) => Promise<void>;
39
39
  /** The tool calls the turn on `ctx` holds for a person, for a parked response. */
40
40
  readonly heldCalls?: (ctx: Context) => Promise<ReadonlyArray<HeldCall>>;
41
+ /** The cut the turn on `ctx` ended with, when it was cut rather than failed (spec 23 § Cut turns). */
42
+ readonly cutOf?: (ctx: Context) => TurnCut | undefined;
41
43
  }
42
44
  /**
43
45
  * @internal
@@ -73,6 +75,7 @@ export declare class SessionRunner {
73
75
  private totalBilledCost;
74
76
  private readonly onTurnUsage?;
75
77
  private readonly heldCalls?;
78
+ private readonly cutOf?;
76
79
  private currentController?;
77
80
  private currentCtx?;
78
81
  private loopPromise?;
@@ -123,6 +126,11 @@ export declare class SessionRunner {
123
126
  * hears it settled — so `getUsage()` after `getAgentResponse()` includes it.
124
127
  */
125
128
  private settleUsage;
129
+ /**
130
+ * The turn was cut: it has not ended, and a later wake runs it again. Its response
131
+ * says so, with the items so far, and `turn_cut` stands in for `turn_aborted`.
132
+ */
133
+ private answerCut;
126
134
  /** A turn whose context could not be built: report it like any other failed turn. */
127
135
  private failBeforeStart;
128
136
  private resolveWaiters;
@@ -50,6 +50,7 @@ export class SessionRunner {
50
50
  totalBilledCost = 0;
51
51
  onTurnUsage;
52
52
  heldCalls;
53
+ cutOf;
53
54
  currentController;
54
55
  currentCtx;
55
56
  loopPromise;
@@ -65,6 +66,7 @@ export class SessionRunner {
65
66
  this.createContext = opts.createContext;
66
67
  this.onTurnUsage = opts.onTurnUsage;
67
68
  this.heldCalls = opts.heldCalls;
69
+ this.cutOf = opts.cutOf;
68
70
  this.queue.subscribe(() => {
69
71
  this.kick();
70
72
  });
@@ -281,6 +283,11 @@ export class SessionRunner {
281
283
  try {
282
284
  const text = await this.runTurn(ctx, turn, controller.signal);
283
285
  await this.settleUsage(start, ctx);
286
+ const cut = this.cutOf?.(ctx);
287
+ if (cut) {
288
+ this.answerCut(turnId, startedAt, ctx, cut);
289
+ return;
290
+ }
284
291
  const wakeAt = parkedUntilOf(ctx);
285
292
  const held = wakeAt === undefined ? [] : ((await this.heldCalls?.(ctx)) ?? []);
286
293
  const response = wakeAt === undefined
@@ -372,6 +379,33 @@ export class SessionRunner {
372
379
  this.totalBilledCost += spent.billedCost;
373
380
  await this.onTurnUsage?.(spent);
374
381
  }
382
+ /**
383
+ * The turn was cut: it has not ended, and a later wake runs it again. Its response
384
+ * says so, with the items so far, and `turn_cut` stands in for `turn_aborted`.
385
+ */
386
+ answerCut(turnId, startedAt, ctx, cut) {
387
+ const response = {
388
+ ...buildResponse('', ctx),
389
+ cut,
390
+ };
391
+ this.lastResponse = response;
392
+ this.lastError = undefined;
393
+ emitFrameworkEvent({
394
+ broadcaster: this.broadcaster,
395
+ agentName: this.agentName,
396
+ eventType: 'turn_cut',
397
+ data: {
398
+ turnId,
399
+ durationMs: Date.now() - startedAt,
400
+ reason: cut.reason,
401
+ attempt: cut.attempt,
402
+ wakeAt: cut.wakeAt,
403
+ },
404
+ });
405
+ if (this.queue.size === 0) {
406
+ this.resolveWaiters(response);
407
+ }
408
+ }
375
409
  /** A turn whose context could not be built: report it like any other failed turn. */
376
410
  failBeforeStart(turnId, err) {
377
411
  const error = err instanceof Error ? err : new Error(String(err));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.22.0-next.3",
3
+ "version": "5.22.0-next.4",
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.2",
72
+ "@noetic-tools/types": "^3.19.0-next.3",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "jsonata": "2.2.2",