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

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,153 @@
1
+ /**
2
+ * An agent's questions (`elicitation/create`) as held questions (spec 27
3
+ * § Questions the agent asks, spec 08 § Held tool calls): the host sees the same
4
+ * `tool_call_held` / `onHeld` / `pending()` question it sees for any other asker,
5
+ * and never learns the step is an agent.
6
+ */
7
+ import { frameworkCast } from '@noetic-tools/types';
8
+ import { ContextImpl } from '../runtime/context-impl.js';
9
+ import { heldArgsHash, heldCallsOf, heldScopeOf, holdAndWait, mayWriteHolds, } from '../runtime/held-calls.js';
10
+ //#endregion
11
+ //#region Helpers
12
+ function isRecord(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ /**
16
+ * The question a person sees: the message, and the form or the page. An ACP form
17
+ * is closed — the agent takes only the fields it described — so an answer with
18
+ * any other field is refused before the question settles.
19
+ */
20
+ function questionOf(request) {
21
+ const schema = Reflect.get(request, 'requestedSchema');
22
+ const url = Reflect.get(request, 'url');
23
+ return {
24
+ message: request.message,
25
+ ...(isRecord(schema)
26
+ ? {
27
+ schema: {
28
+ ...schema,
29
+ additionalProperties: false,
30
+ },
31
+ }
32
+ : {}),
33
+ ...(typeof url === 'string'
34
+ ? {
35
+ url,
36
+ }
37
+ : {}),
38
+ };
39
+ }
40
+ /** What identifies one request across hosts: who asks, where, and what. */
41
+ function requestIdentity(request) {
42
+ return {
43
+ sessionId: Reflect.get(request, 'sessionId') ?? null,
44
+ toolCallId: Reflect.get(request, 'toolCallId') ?? null,
45
+ mode: request.mode,
46
+ question: questionOf(request),
47
+ };
48
+ }
49
+ /** The step's dispatch path, or its id on a run with no ledger. */
50
+ function dispatchOf(ctx, stepId) {
51
+ return (ctx instanceof ContextImpl ? ctx.currentDispatch()?.path : undefined) ?? stepId;
52
+ }
53
+ /** An answer as the agent takes it: the form's fields, or none for a URL question. */
54
+ function acceptOf(output) {
55
+ if (!isRecord(output)) {
56
+ return {
57
+ action: 'accept',
58
+ };
59
+ }
60
+ // Checked against the question's schema when it was answered (held-question.ts).
61
+ return {
62
+ action: 'accept',
63
+ content: frameworkCast(output),
64
+ };
65
+ }
66
+ /**
67
+ * Answer an agent's questions by holding each for a person. A question's id is
68
+ * the step's dispatch path and a hash of the request with the agent's own
69
+ * JSON-RPC id for it — which a keeper keeps when it asks a reattached host
70
+ * again — so a resumed host asked the same question finds it, answered or
71
+ * not, and never asks the person twice. Without that id, the ordinal among
72
+ * identical requests stands in. An answer is kept until the step ends, so one
73
+ * taken just before the host died is still there when the question comes back.
74
+ * The agent is waiting on the answer, so the turn stays live while it is held.
75
+ */
76
+ export function questionAsker(opts) {
77
+ const seen = new Map();
78
+ const asked = new Set();
79
+ /**
80
+ * Ids this host already asked under. An agent that asks again under the
81
+ * same id on the same host is asking a new question; a new host after a
82
+ * crash starts empty, so the keeper's re-ask finds the kept answer.
83
+ */
84
+ const answeredHere = new Map();
85
+ const name = `${opts.agentId}:question`;
86
+ const harness = frameworkCast(opts.ctx.harness);
87
+ const idOf = (request, requestId) => {
88
+ const identity = heldArgsHash(name, {
89
+ ...requestIdentity(request),
90
+ requestId: requestId ?? null,
91
+ });
92
+ if (requestId !== undefined) {
93
+ return `${dispatchOf(opts.ctx, opts.stepId)}:question:${identity}`;
94
+ }
95
+ const ordinal = seen.get(identity) ?? 0;
96
+ seen.set(identity, ordinal + 1);
97
+ return `${dispatchOf(opts.ctx, opts.stepId)}:question:${identity}#${ordinal}`;
98
+ };
99
+ return {
100
+ ask: async (request, info) => {
101
+ const base = idOf(request, info.requestId);
102
+ const again = answeredHere.get(base) ?? 0;
103
+ answeredHere.set(base, again + 1);
104
+ const callId = again === 0 ? base : `${base}~${again}`;
105
+ asked.add(callId);
106
+ const question = questionOf(request);
107
+ const args = {
108
+ message: question.message,
109
+ };
110
+ const answer = await holdAndWait({
111
+ harness,
112
+ ctx: opts.ctx,
113
+ park: false,
114
+ keepAnswer: true,
115
+ record: {
116
+ callId,
117
+ name,
118
+ args,
119
+ argsHash: heldArgsHash(name, args),
120
+ reason: 'question',
121
+ question,
122
+ },
123
+ });
124
+ return responseOf(answer.resolution);
125
+ },
126
+ release: async () => {
127
+ if (!mayWriteHolds(opts.ctx)) {
128
+ return;
129
+ }
130
+ const holds = heldCallsOf(harness);
131
+ const scope = heldScopeOf(opts.ctx);
132
+ for (const callId of asked) {
133
+ await holds.close(scope, callId);
134
+ }
135
+ asked.clear();
136
+ },
137
+ };
138
+ }
139
+ /** The agent's answer: accept with the form's fields, decline, or cancel. */
140
+ function responseOf(resolution) {
141
+ if (resolution?.hasOutput === true) {
142
+ return acceptOf(resolution.output);
143
+ }
144
+ if (resolution?.action === 'deny') {
145
+ return {
146
+ action: 'decline',
147
+ };
148
+ }
149
+ return {
150
+ action: 'cancel',
151
+ };
152
+ }
153
+ //#endregion
@@ -16,6 +16,7 @@ declare const AcpSessionRecordSchema: z.ZodObject<{
16
16
  sessionId: z.ZodString;
17
17
  agentId: z.ZodString;
18
18
  reattach: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
19
+ fingerprint: z.ZodOptional<z.ZodString>;
19
20
  }, z.core.$strip>;
20
21
  /** The agent session a step opened, as stored. */
21
22
  export type AcpSessionRecord = z.infer<typeof AcpSessionRecordSchema>;
@@ -21,6 +21,11 @@ const AcpSessionRecordSchema = z.object({
21
21
  agentId: z.string(),
22
22
  /** How to reach the agent if it outlived the host that opened the session. */
23
23
  reattach: z.record(z.string(), z.unknown()).optional(),
24
+ /**
25
+ * What the session was opened with (`AcpSession.fingerprint`). Absent on a
26
+ * record written before fingerprints were kept: such a session is accepted.
27
+ */
28
+ fingerprint: z.string().optional(),
24
29
  });
25
30
  const BridgedOutputSchema = z.object({
26
31
  output: z.string(),
@@ -6,13 +6,14 @@
6
6
  * Core reaches the agent only through the `@noetic-tools/types` contract, so no
7
7
  * protocol library or agent SDK enters its dependency graph.
8
8
  */
9
- import { createMessage, extractAssistantText, frameworkCast, NoeticConfigError, NoeticErrorImpl, SteeringAction, } from '@noetic-tools/types';
9
+ import { createMessage, extractAssistantText, frameworkCast, isAcpCapabilityError, isAcpConnectError, 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
12
  import { isRpcError, RpcFailure } from '../util/error-message.js';
13
13
  import { AcpEventBridge } from './acp-events.js';
14
14
  import { withHistoryPrompt } from './acp-history.js';
15
15
  import { renderLayerContext } from './acp-layers.js';
16
+ import { questionAsker } from './acp-questions.js';
16
17
  import { ACP_RESUME_NOTICE, acpSessionRecords } from './acp-resume.js';
17
18
  import { AcpToolRunner, mergeBridgedItems, resolveAcpTools } from './acp-tools.js';
18
19
  import { appendUserInput, MAX_STEERING_RETRIES, resolveLazy } from './execute-action.js';
@@ -200,6 +201,9 @@ function bindHostToStep(host, opts) {
200
201
  stepId: opts.step.id,
201
202
  })
202
203
  : undefined;
204
+ // An agent's question is a question for a person: held like any other (spec 27
205
+ // § Questions the agent asks), answered by whoever answers held calls.
206
+ host.onElicitation = opts.questions.ask;
203
207
  host.onSessionUpdate = opts.onUpdate;
204
208
  host.onClientActivity = opts.onActivity;
205
209
  // A step that gives no tools gets none, even on a session another step
@@ -251,6 +255,7 @@ function normalizedCapabilities(config) {
251
255
  additionalDirectories: [
252
256
  ...(config?.additionalDirectories ?? []),
253
257
  ].sort(),
258
+ elicitation: config?.elicitation !== false,
254
259
  });
255
260
  }
256
261
  /**
@@ -258,7 +263,7 @@ function normalizedCapabilities(config) {
258
263
  * joining an existing one cannot change them either. Connection-scoped
259
264
  * settings all fail the same way: a mismatch throws rather than being dropped.
260
265
  */
261
- function assertSessionScopedSettingsMatch(step, live, cwd, tools) {
266
+ function assertSessionScopedSettingsMatch(step, live, cwd, tools, settings) {
262
267
  const conflict = (setting, hint) => new NoeticConfigError({
263
268
  code: 'ACP_SESSION_SETTING_CONFLICT',
264
269
  message: `step.acpAgent(${JSON.stringify(step.id)}) reuses session '${step.session?.reuse}' but requests a different ${setting} than the session was created with.`,
@@ -267,6 +272,13 @@ function assertSessionScopedSettingsMatch(step, live, cwd, tools) {
267
272
  if (cwd !== live.cwd) {
268
273
  throw conflict('cwd', 'A session is created in one working directory. Give every step sharing a `session.reuse` key the same `cwd`, or use a separate session.');
269
274
  }
275
+ // Instructions, the adapter's `_meta`, cwd and capabilities as the connection
276
+ // would send them, against what it sent when the session opened.
277
+ const opened = live.fingerprint;
278
+ if (opened !== undefined &&
279
+ opened !== live.connection.fingerprintFor(sessionRequest(cwd, settings))) {
280
+ throw conflict('instructions or agent settings', 'A session takes its instructions and its agent settings when it is created. Give every step sharing a `session.reuse` key the same `instructions` and agent, or use a separate session.');
281
+ }
270
282
  // The agent reads its tool list once, so a step may serve any part of it —
271
283
  // a call to a tool outside its part answers as unknown, as on `callModel` —
272
284
  // but nothing the list lacks.
@@ -306,6 +318,35 @@ function assertCapabilitiesCompatible(step, live) {
306
318
  hint: 'ACP negotiates client capabilities once per connection. Give every step sharing a `session.reuse` key the same `clientCapabilities`, or use a separate session.',
307
319
  });
308
320
  }
321
+ async function resolveSessionSettings(step, ctx) {
322
+ const instructions = await resolveLazy(step.instructions, ctx);
323
+ if (instructions === undefined || instructions.trim().length === 0) {
324
+ return {};
325
+ }
326
+ return {
327
+ instructions,
328
+ };
329
+ }
330
+ /** The session request for `cwd` and `settings`, as `fingerprintFor` takes it. */
331
+ function sessionRequest(cwd, settings) {
332
+ return {
333
+ cwd,
334
+ ...settings,
335
+ };
336
+ }
337
+ /** JSON-RPC "resource not found", which an agent answers a load of a session it no longer has with. */
338
+ const RESOURCE_NOT_FOUND = -32002;
339
+ /**
340
+ * Whether a failed `session/load` says the agent no longer has the session —
341
+ * the one failure a resumed step starts over from. Anything else may mean the
342
+ * old turn is still there, so the step fails rather than repeat its work.
343
+ */
344
+ function sessionIsGone(error) {
345
+ if (typeof error !== 'object' || error === null) {
346
+ return false;
347
+ }
348
+ return Reflect.get(error, 'code') === RESOURCE_NOT_FOUND;
349
+ }
309
350
  /** Keeping a connection is always explicit; the default closes it with the step. */
310
351
  function keepAliveOf(policy) {
311
352
  return policy?.keepAlive ?? 'step';
@@ -332,12 +373,13 @@ function assertReuseIsKeptAlive(step) {
332
373
  * session, gets a new one, and the step starts it over.
333
374
  */
334
375
  async function sessionOn(connection, opts) {
335
- const { cwd, loadId, resumeId } = opts;
376
+ const { cwd, loadId, resumeId, settings } = opts;
336
377
  if (loadId) {
337
378
  return {
338
379
  session: await connection.loadSession({
339
380
  sessionId: loadId,
340
381
  cwd,
382
+ ...settings,
341
383
  }),
342
384
  resumed: false,
343
385
  };
@@ -347,8 +389,14 @@ async function sessionOn(connection, opts) {
347
389
  .loadSession({
348
390
  sessionId: resumeId,
349
391
  cwd,
392
+ ...settings,
350
393
  })
351
- .catch(() => undefined);
394
+ .catch((error) => {
395
+ if (sessionIsGone(error)) {
396
+ return undefined;
397
+ }
398
+ throw error;
399
+ });
352
400
  if (session) {
353
401
  return {
354
402
  session,
@@ -359,6 +407,7 @@ async function sessionOn(connection, opts) {
359
407
  return {
360
408
  session: await connection.newSession({
361
409
  cwd,
410
+ ...settings,
362
411
  }),
363
412
  resumed: false,
364
413
  };
@@ -386,6 +435,9 @@ async function openSession(opts) {
386
435
  const kept = await reattachTo(opts.agent, connectOptions, {
387
436
  reattach: opts.reattach,
388
437
  sessionId: opts.resumeId,
438
+ fingerprint: opts.fingerprint,
439
+ request: sessionRequest(opts.cwd, opts.settings),
440
+ stepId: opts.step.id,
389
441
  });
390
442
  if (kept) {
391
443
  resumed = true;
@@ -398,6 +450,8 @@ async function openSession(opts) {
398
450
  keepAlive,
399
451
  cwd: opts.cwd,
400
452
  tools: opts.tools?.tools,
453
+ // Checked equal to this step's when it reattached.
454
+ fingerprint: opts.fingerprint,
401
455
  };
402
456
  }
403
457
  const connection = holdingConnections(await opts.agent.connect(connectOptions), opts.baseCtx, keepAlive);
@@ -410,6 +464,7 @@ async function openSession(opts) {
410
464
  cwd: opts.cwd,
411
465
  loadId: opts.step.session?.load,
412
466
  resumeId: opts.resumeId,
467
+ settings: opts.settings,
413
468
  });
414
469
  resumed = opened.resumed;
415
470
  const { session } = opened;
@@ -421,6 +476,7 @@ async function openSession(opts) {
421
476
  keepAlive,
422
477
  cwd: opts.cwd,
423
478
  tools: opts.tools?.tools,
479
+ fingerprint: session.fingerprint,
424
480
  };
425
481
  }
426
482
  catch (e) {
@@ -429,7 +485,7 @@ async function openSession(opts) {
429
485
  }
430
486
  });
431
487
  if (!fresh) {
432
- assertSessionScopedSettingsMatch(opts.step, live, opts.cwd, opts.tools);
488
+ assertSessionScopedSettingsMatch(opts.step, live, opts.cwd, opts.tools, opts.settings);
433
489
  if (live.agentId !== opts.agent.agentId) {
434
490
  throw new NoeticConfigError({
435
491
  code: 'ACP_SESSION_AGENT_CONFLICT',
@@ -459,28 +515,70 @@ function whenHostExitsOf(ctx) {
459
515
  * outlived its host, or undefined when there is none to reach — the agent is
460
516
  * gone, or no longer has the session — so the step reloads or starts over.
461
517
  */
462
- async function reattachTo(agent, connectOptions, { reattach, sessionId, }) {
463
- if (!reattach || sessionId === undefined) {
518
+ async function reattachTo(agent, connectOptions, opts) {
519
+ if (!opts.reattach || opts.sessionId === undefined) {
464
520
  return undefined;
465
521
  }
522
+ // Only "the agent is gone" starts the step over; any other failure fails it.
466
523
  const connection = await agent
467
524
  .connect({
468
525
  ...connectOptions,
469
- reattach,
526
+ reattach: opts.reattach,
470
527
  })
471
- .catch(() => undefined);
528
+ .catch(goneOrThrow);
472
529
  if (!connection) {
473
530
  return undefined;
474
531
  }
475
- const session = await connection.attachSession?.(sessionId).catch(() => undefined);
476
- if (!session?.resumeTurn) {
477
- await connection.close().catch(() => undefined);
532
+ try {
533
+ const session = await connection.attachSession?.(opts.sessionId).catch(goneOrThrow);
534
+ if (!session?.resumeTurn) {
535
+ await connection.close().catch(() => undefined);
536
+ return undefined;
537
+ }
538
+ assertSameSettings(opts, connection);
539
+ return {
540
+ connection,
541
+ session,
542
+ };
543
+ }
544
+ catch (error) {
545
+ // The old turn may still be working: let go of it, never stop it, so a
546
+ // host that resumes with the settings it started with can still take it.
547
+ await letGo(connection);
548
+ throw error;
549
+ }
550
+ }
551
+ /** Release this host's side of a reattached connection, leaving the agent running. */
552
+ async function letGo(connection) {
553
+ const release = connection.detach ?? connection.close;
554
+ await release.call(connection).catch(() => undefined);
555
+ }
556
+ /**
557
+ * Undefined when the agent or its session is confirmed gone, the error itself
558
+ * otherwise: a connect failure that says nothing about the agent must not
559
+ * start its work over.
560
+ */
561
+ function goneOrThrow(error) {
562
+ if (isAcpConnectError(error) && error.gone) {
478
563
  return undefined;
479
564
  }
480
- return {
481
- connection,
482
- session,
483
- };
565
+ throw error;
566
+ }
567
+ /**
568
+ * A reattached session runs with what it was opened with. A step that would
569
+ * open it differently must not adopt it: the old turn may already have acted on
570
+ * the old instructions.
571
+ */
572
+ function assertSameSettings(opts, connection) {
573
+ if (opts.fingerprint === undefined ||
574
+ opts.fingerprint === connection.fingerprintFor(opts.request)) {
575
+ return;
576
+ }
577
+ throw new NoeticConfigError({
578
+ code: 'ACP_SESSION_SETTING_CONFLICT',
579
+ message: `step.acpAgent(${JSON.stringify(opts.stepId)}) resumes a session that was opened with different instructions or agent settings than the step now gives.`,
580
+ hint: 'A resumed step must resolve the same instructions, cwd and agent settings as the run that started it.',
581
+ });
484
582
  }
485
583
  /**
486
584
  * A connection kept past its step holds the turn's connections until it
@@ -552,11 +650,23 @@ async function applySessionSelection(step, ctx, resolution, baseCtx) {
552
650
  throw e;
553
651
  }
554
652
  }
555
- /** Turn a failed turn into the step's typed error, after closing the bracket. */
556
- function turnFailure(step, cause, baseCtx) {
557
- if (cause instanceof NoeticErrorImpl) {
653
+ /**
654
+ * Whatever went wrong, as a Noetic error (spec 27 § Failures are Noetic errors):
655
+ * a host never sees a protocol error. A missing capability is the workflow's
656
+ * configuration; everything else the agent did, or failed to do, is the step
657
+ * failing, with the agent's own message.
658
+ */
659
+ function stepFailure(step, cause, baseCtx) {
660
+ if (cause instanceof NoeticErrorImpl || cause instanceof NoeticConfigError) {
558
661
  return cause;
559
662
  }
663
+ if (isAcpCapabilityError(cause)) {
664
+ return new NoeticConfigError({
665
+ code: 'AGENT_CAPABILITY_MISSING',
666
+ message: `step.acpAgent(${JSON.stringify(step.id)}): ${cause.message}`,
667
+ hint: `The agent does not support '${cause.capability}'. Leave that setting off this step, or use an agent that supports it.`,
668
+ });
669
+ }
560
670
  if (baseCtx.aborted) {
561
671
  return new NoeticErrorImpl({
562
672
  kind: 'cancelled',
@@ -573,18 +683,6 @@ function turnFailure(step, cause, baseCtx) {
573
683
  retriesExhausted: false,
574
684
  });
575
685
  }
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;
585
- }
586
- return turnFailure(step, cause, baseCtx);
587
- }
588
686
  /**
589
687
  * The tools the agent is served. No `tools` offers every tool the run has,
590
688
  * as on `callModel`, and an agent that cannot take tools then simply gets
@@ -638,15 +736,18 @@ async function runTurn(params) {
638
736
  // Close the turn on the event surface before rethrowing. A consumer driving
639
737
  // a UI off `getFullStream()` saw `response.created` and would otherwise
640
738
  // wait forever for a completion that never comes — the stream just stops.
641
- bridge.abort(e);
739
+ // The stream carries the same Noetic error `execute()` throws.
740
+ const failure = stepFailure(step, turnError.error ?? e, baseCtx);
741
+ bridge.abort(failure);
642
742
  await discardIfFresh(resolution, baseCtx);
643
- throw turnFailure(step, turnError.error ?? e, baseCtx);
743
+ throw failure;
644
744
  }
645
745
  await settle(tools);
646
746
  if (turnError.error !== undefined) {
647
- bridge.abort(turnError.error);
747
+ const failure = stepFailure(step, turnError.error, baseCtx);
748
+ bridge.abort(failure);
648
749
  await discardIfFresh(resolution, baseCtx);
649
- throw turnFailure(step, turnError.error, baseCtx);
750
+ throw failure;
650
751
  }
651
752
  if (tools) {
652
753
  const merged = mergeBridgedItems(result.items, tools.takeFinished());
@@ -684,6 +785,31 @@ export async function executeAcpAgent(step, input, ctx, layers) {
684
785
  const baseCtx = frameworkCast(ctx);
685
786
  assertReuseIsKeptAlive(step);
686
787
  const agent = await resolveAgent(step, ctx);
788
+ const questions = questionAsker({
789
+ ctx: baseCtx,
790
+ agentId: agent.agentId,
791
+ stepId: step.id,
792
+ });
793
+ // A question's answer is kept until the step ends, so a host that died after
794
+ // taking it and before the agent got it is not asked again (spec 27
795
+ // § Questions the agent asks). A step cut off with its host never gets here.
796
+ try {
797
+ return await runAcpStep({
798
+ step,
799
+ input,
800
+ ctx,
801
+ layers,
802
+ agent,
803
+ questions,
804
+ });
805
+ }
806
+ finally {
807
+ await questions.release().catch(() => undefined);
808
+ }
809
+ }
810
+ async function runAcpStep(params) {
811
+ const { step, input, ctx, layers, agent, questions } = params;
812
+ const baseCtx = frameworkCast(ctx);
687
813
  const resolvedPrompt = await resolveLazy(step.prompt, ctx);
688
814
  const blocks = await resolveLazy(step.content, ctx);
689
815
  const promptText = resolvedPrompt && resolvedPrompt.length > 0
@@ -699,6 +825,7 @@ export async function executeAcpAgent(step, input, ctx, layers) {
699
825
  });
700
826
  }
701
827
  const cwd = (await resolveLazy(step.cwd, ctx)) ?? baseCtx.cwdState.cwd;
828
+ const settings = await resolveSessionSettings(step, ctx);
702
829
  const tools = await resolveServedTools(step, ctx, layers, agent);
703
830
  // Capture the conversation so far BEFORE appending this turn's prompt, so a
704
831
  // fresh session can be seeded with it and the agent is not left guessing at
@@ -718,6 +845,7 @@ export async function executeAcpAgent(step, input, ctx, layers) {
718
845
  const sameAgent = recorded?.agentId === agent.agentId;
719
846
  const resumeId = sameAgent ? recorded?.sessionId : undefined;
720
847
  const reattach = sameAgent ? recorded?.reattach : undefined;
848
+ const fingerprint = sameAgent ? recorded?.fingerprint : undefined;
721
849
  // `session/load` replays the session's conversation as updates. They are the
722
850
  // agent's history, not this turn's work: they reach raw-event consumers
723
851
  // marked `replay: true`, and never the text, reasoning or item streams.
@@ -730,6 +858,7 @@ export async function executeAcpAgent(step, input, ctx, layers) {
730
858
  const bindingFor = (events) => ({
731
859
  step,
732
860
  ctx: baseCtx,
861
+ questions,
733
862
  agentId: agent.agentId,
734
863
  layers,
735
864
  onUpdate: (notification) => {
@@ -770,9 +899,11 @@ export async function executeAcpAgent(step, input, ctx, layers) {
770
899
  tools,
771
900
  resumeId,
772
901
  reattach,
902
+ fingerprint,
903
+ settings,
773
904
  })
774
905
  .catch((cause) => {
775
- throw setupFailure(step, cause, baseCtx);
906
+ throw stepFailure(step, cause, baseCtx);
776
907
  })
777
908
  .finally(() => {
778
909
  reloading = false;
@@ -780,16 +911,19 @@ export async function executeAcpAgent(step, input, ctx, layers) {
780
911
  if (resolution.resumed) {
781
912
  tools?.sessionReloaded();
782
913
  }
783
- if (resolution.fresh && !resolution.resumed) {
914
+ // A reloaded session was opened again with this step's settings: its record
915
+ // takes the new fingerprint. A reattached one keeps the one it has.
916
+ if (resolution.fresh && !resolution.reattached) {
784
917
  await sessions?.write({
785
918
  sessionId: resolution.live.session.sessionId,
786
919
  agentId: agent.agentId,
787
920
  // How a resumed run reaches this agent if it outlives this host.
788
921
  reattach: resolution.live.connection.reattach,
922
+ fingerprint: resolution.live.session.fingerprint,
789
923
  });
790
924
  }
791
925
  await applySessionSelection(step, ctx, resolution, baseCtx).catch((cause) => {
792
- throw setupFailure(step, cause, baseCtx);
926
+ throw stepFailure(step, cause, baseCtx);
793
927
  });
794
928
  turnError.cancel = () => resolution.live.session.cancel();
795
929
  // History seeds only a freshly opened session; a reused one already owns
@@ -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
@@ -22,6 +22,7 @@ declare const HeldRecordSchema: z.ZodObject<{
22
22
  result: "result";
23
23
  outcome: "outcome";
24
24
  approval: "approval";
25
+ question: "question";
25
26
  }>;
26
27
  dueAt: z.ZodOptional<z.ZodNumber>;
27
28
  onDue: z.ZodOptional<z.ZodEnum<{
@@ -29,6 +30,11 @@ declare const HeldRecordSchema: z.ZodObject<{
29
30
  keep: "keep";
30
31
  }>>;
31
32
  request: z.ZodOptional<z.ZodUnknown>;
33
+ question: z.ZodOptional<z.ZodObject<{
34
+ message: z.ZodString;
35
+ schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
36
+ url: z.ZodOptional<z.ZodString>;
37
+ }, z.core.$strip>>;
32
38
  resolution: z.ZodOptional<z.ZodObject<{
33
39
  action: z.ZodOptional<z.ZodEnum<{
34
40
  allow: "allow";
@@ -225,6 +231,14 @@ export declare function holdAndWait(opts: {
225
231
  harness: HoldHost;
226
232
  ctx: Context;
227
233
  record: HeldRecord;
234
+ /** False when something outside the run waits on the answer: the turn stays live. Default true. */
235
+ park?: boolean;
236
+ /**
237
+ * Keep an answered record instead of dropping it, until the caller closes it:
238
+ * for an asker that may be asked the same question again after its answer
239
+ * was taken but before it reached whoever asked.
240
+ */
241
+ keepAnswer?: boolean;
228
242
  }): Promise<HeldAnswer>;
229
243
  /**
230
244
  * @internal