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

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.
@@ -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 */
@@ -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
@@ -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));
@@ -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;