@noetic-tools/core 5.20.0 → 5.22.0-next.1

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.
Files changed (84) hide show
  1. package/dist/builders/tool-builder.d.ts +20 -0
  2. package/dist/builders/tool-builder.js +23 -1
  3. package/dist/builders/workflow-hydrator.d.ts +19 -0
  4. package/dist/builders/workflow-hydrator.js +19 -0
  5. package/dist/builders/workflow-step.js +7 -1
  6. package/dist/connections/cron-schedule.js +12 -3
  7. package/dist/connections/durability.d.ts +1 -2
  8. package/dist/connections/durability.js +1 -4
  9. package/dist/connections/gates.js +6 -2
  10. package/dist/connections/harness-wiring.d.ts +5 -0
  11. package/dist/connections/harness-wiring.js +76 -10
  12. package/dist/connections/in-memory-connection.d.ts +4 -0
  13. package/dist/connections/in-memory-connection.js +10 -0
  14. package/dist/connections/model-tools.js +5 -1
  15. package/dist/connections/registry.d.ts +6 -2
  16. package/dist/connections/registry.js +10 -0
  17. package/dist/connections/sources.js +261 -20
  18. package/dist/connections/triggers.d.ts +62 -2
  19. package/dist/connections/triggers.js +375 -35
  20. package/dist/harness/agent-harness.d.ts +263 -4
  21. package/dist/harness/agent-harness.js +1156 -95
  22. package/dist/harness/connection-gate.d.ts +3 -0
  23. package/dist/harness/connection-gate.js +4 -0
  24. package/dist/harness/deps/runtime.d.ts +3 -0
  25. package/dist/harness/deps/runtime.js +2 -0
  26. package/dist/harness/flow-version.d.ts +13 -0
  27. package/dist/harness/flow-version.js +66 -0
  28. package/dist/harness/harness-options.d.ts +82 -0
  29. package/dist/harness/model-call.d.ts +0 -1
  30. package/dist/harness/model-call.js +8 -48
  31. package/dist/harness/model-rounds.d.ts +30 -0
  32. package/dist/harness/model-rounds.js +146 -1
  33. package/dist/harness/model-tool-round.d.ts +3 -0
  34. package/dist/harness/model-tool-round.js +201 -19
  35. package/dist/harness/park-watchers.d.ts +93 -0
  36. package/dist/harness/park-watchers.js +217 -0
  37. package/dist/harness/read-decision.d.ts +23 -0
  38. package/dist/harness/read-decision.js +100 -0
  39. package/dist/harness/spend.js +4 -0
  40. package/dist/harness/steer-inbox.js +3 -1
  41. package/dist/harness/thread-record.d.ts +77 -1
  42. package/dist/harness/thread-record.js +272 -13
  43. package/dist/index.d.ts +17 -7
  44. package/dist/index.js +10 -2
  45. package/dist/interpreter/acp-resume.d.ts +77 -0
  46. package/dist/interpreter/acp-resume.js +164 -0
  47. package/dist/interpreter/acp-tools.d.ts +11 -0
  48. package/dist/interpreter/acp-tools.js +94 -7
  49. package/dist/interpreter/connection-steps.d.ts +24 -1
  50. package/dist/interpreter/connection-steps.js +77 -2
  51. package/dist/interpreter/execute-acp-agent.js +111 -15
  52. package/dist/interpreter/execute-action.js +7 -0
  53. package/dist/interpreter/execute-call.js +30 -4
  54. package/dist/interpreter/execute-control.js +21 -0
  55. package/dist/interpreter/execute-invoke-tool.js +149 -5
  56. package/dist/interpreter/execute-wait.js +67 -9
  57. package/dist/interpreter/execute.js +4 -0
  58. package/dist/interpreter/turn-ending.d.ts +15 -0
  59. package/dist/interpreter/turn-ending.js +46 -0
  60. package/dist/portable/builders.d.ts +1 -1
  61. package/dist/portable/builders.js +1 -1
  62. package/dist/runtime/durable/parking.d.ts +61 -0
  63. package/dist/runtime/durable/parking.js +137 -0
  64. package/dist/runtime/durable/session-store.d.ts +38 -0
  65. package/dist/runtime/durable/session-store.js +79 -1
  66. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  67. package/dist/runtime/durable/step-ledger.js +352 -15
  68. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  69. package/dist/runtime/durable/turn-lease.js +307 -0
  70. package/dist/runtime/held-calls.d.ts +192 -0
  71. package/dist/runtime/held-calls.js +496 -0
  72. package/dist/runtime/in-memory-storage.d.ts +10 -1
  73. package/dist/runtime/in-memory-storage.js +20 -2
  74. package/dist/runtime/message-queue.d.ts +2 -0
  75. package/dist/runtime/message-queue.js +8 -0
  76. package/dist/runtime/session-runner.d.ts +18 -2
  77. package/dist/runtime/session-runner.js +88 -3
  78. package/dist/runtime/tool-approval.d.ts +46 -6
  79. package/dist/runtime/tool-approval.js +160 -38
  80. package/dist/runtime/tool-call.d.ts +34 -2
  81. package/dist/runtime/tool-call.js +182 -13
  82. package/dist/runtime/tool-context.d.ts +15 -1
  83. package/dist/runtime/tool-context.js +38 -2
  84. package/package.json +3 -3
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Reads a `DecisionItem` a host passed to `execute()`: what it asks for, or why
3
+ * it cannot be taken. Reading changes nothing, so a list of decisions is read
4
+ * whole before any is acted on.
5
+ */
6
+ import { NoeticErrorImpl } from '@noetic-tools/types';
7
+ //#endregion
8
+ //#region Helpers
9
+ /** True for a value storage can hold and hand back: JSON, with nothing dropped. */
10
+ function isJsonValue(value) {
11
+ try {
12
+ return JSON.stringify(value) !== undefined;
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ }
18
+ function isSettling(action) {
19
+ return action === 'continue' || action === 'restart' || action === 'abandon';
20
+ }
21
+ function isAnswering(action) {
22
+ return action === 'allow' || action === 'deny' || action === 'guide';
23
+ }
24
+ //#endregion
25
+ //#region Public API
26
+ /**
27
+ * @throws NoeticError `decision_refused` when the decision carries both an action
28
+ * and an output, or an action of the wrong kind for a decision with, or without,
29
+ * a `callId`; `hold_refused` when its `output` is not a JSON value.
30
+ */
31
+ export function readDecision(threadId, decision) {
32
+ const loose = decision;
33
+ const { callId, action } = loose;
34
+ const hasOutput = 'output' in loose;
35
+ const refuse = (reason) => {
36
+ throw new NoeticErrorImpl({
37
+ kind: 'decision_refused',
38
+ threadId,
39
+ action: action === undefined ? 'output' : String(action),
40
+ reason,
41
+ });
42
+ };
43
+ if (hasOutput && action !== undefined) {
44
+ return refuse('it carries both an action and an output: give one');
45
+ }
46
+ if (callId === undefined) {
47
+ if (isSettling(action)) {
48
+ return {
49
+ threadId,
50
+ settle: action,
51
+ };
52
+ }
53
+ return refuse('it answers a held call: give its callId');
54
+ }
55
+ const scope = loose.executionId === undefined
56
+ ? {
57
+ threadId,
58
+ }
59
+ : {
60
+ executionId: loose.executionId,
61
+ };
62
+ const target = {
63
+ callId,
64
+ argsHash: loose.argsHash,
65
+ };
66
+ if (hasOutput) {
67
+ if (!isJsonValue(loose.output)) {
68
+ throw new NoeticErrorImpl({
69
+ kind: 'hold_refused',
70
+ callId,
71
+ reason: 'its output is not a JSON value, so it cannot be recorded',
72
+ });
73
+ }
74
+ return {
75
+ scope,
76
+ answer: {
77
+ ...target,
78
+ output: loose.output,
79
+ },
80
+ };
81
+ }
82
+ if (!isAnswering(action)) {
83
+ return refuse(isSettling(action)
84
+ ? 'it settles a stuck turn: it takes no callId'
85
+ : 'a decision for a held call is allow, deny or guide, or carries an output');
86
+ }
87
+ return {
88
+ scope,
89
+ answer: {
90
+ ...target,
91
+ action,
92
+ ...(loose.guidance === undefined
93
+ ? {}
94
+ : {
95
+ guidance: loose.guidance,
96
+ }),
97
+ },
98
+ };
99
+ }
100
+ //#endregion
@@ -48,6 +48,10 @@ export class Spend {
48
48
  }
49
49
  /** Write the record for a call about to be sent. A failed write never blocks the call. */
50
50
  async open(params) {
51
+ // A harness that was replaced stops here, before it pays for anything more.
52
+ if (params.ctx instanceof ContextImpl) {
53
+ await params.ctx.ledger?.verifyHeld();
54
+ }
51
55
  const root = rootOf(params.ctx);
52
56
  const path = pathOf(params.ctx);
53
57
  const { json, inputTokens } = measureRequest(params.body);
@@ -178,7 +178,9 @@ function findSessionQueue(ctx) {
178
178
  }
179
179
  /** What each delivery mode does at each point before any layer has a say. */
180
180
  function defaultAction(point, mode) {
181
- if (point === SteerPoint.BeforeRound) {
181
+ // At a round boundary, and at a round that is stuck on held calls and so has no
182
+ // boundary to reach, a steer lands.
183
+ if (point === SteerPoint.BeforeRound || point === SteerPoint.Held) {
182
184
  return SteerAction.Apply;
183
185
  }
184
186
  if (point === SteerPoint.ItemDone && mode === 'next-item') {
@@ -8,10 +8,14 @@
8
8
  * a harness built a moment ago behave the same.
9
9
  */
10
10
  import type { Context, Item, SessionUsage } from '@noetic-tools/types';
11
+ import type { SessionRecord } from '../runtime/durable/session-store.js';
12
+ import type { LedgerFence } from '../runtime/durable/turn-lease.js';
11
13
  import type { QueuedMessage, RestoreCheckpointOptions, SessionStore, TurnUsage } from './deps/runtime.js';
12
14
  /** @internal The harness surface a thread record needs. */
13
15
  export interface ThreadRecordHost {
14
16
  readonly store: SessionStore;
17
+ /** The flow version this harness runs, when it names one. */
18
+ readonly version?: string;
15
19
  restore(executionId: string, opts: RestoreCheckpointOptions): Promise<Context | null>;
16
20
  clearCheckpoint(executionId: string): Promise<void>;
17
21
  parseItems(raw: unknown[]): Item[];
@@ -28,7 +32,17 @@ export declare class ThreadRecord {
28
32
  private readonly host;
29
33
  private readonly threadId;
30
34
  private queue;
35
+ /** The lease the turn in flight runs under, when storage can compare-and-set. */
36
+ private fence;
31
37
  constructor(host: ThreadRecordHost, threadId: string);
38
+ /**
39
+ * Run the turn's own writes (`begin`, `end`) under `fence`: a harness that lost
40
+ * the lease does not overwrite the record, and a write that fails stops the turn
41
+ * (spec 23 § One writer per turn, § Fail-stop). `undefined` goes back to best-effort.
42
+ */
43
+ hold(fence: LedgerFence | undefined): void;
44
+ /** The lease term the stored record was last written at, when it was written under one. */
45
+ term(): Promise<number | undefined>;
32
46
  /** The history the thread's next turn builds on: what storage holds, or none. */
33
47
  history(): Promise<Item[]>;
34
48
  /** Replace the stored history (`seedSessionHistory`). */
@@ -39,8 +53,16 @@ export declare class ThreadRecord {
39
53
  * dropped, its checkpoint cleared, and the new messages start a fresh turn.
40
54
  */
41
55
  resume(messageIds: ReadonlyArray<string>, opts: RestoreCheckpointOptions): Promise<Context | undefined>;
56
+ /** Forget the turn in flight and what it recorded: the host aborted a parked turn. */
57
+ drop(): Promise<SessionRecord['turn']>;
42
58
  /** Keep a steer sent into the running turn, so a resumed turn still applies it. */
43
59
  keepSteer(message: QueuedMessage): Promise<void>;
60
+ /**
61
+ * Keep a message a parked turn has not taken yet, steer or not: with no process
62
+ * holding the turn, storage is the only queue there is. An `interrupt` is never
63
+ * kept; it replaces the turn.
64
+ */
65
+ keepQueued(message: QueuedMessage): Promise<void>;
44
66
  /** The steers kept for the turn in flight, as queue messages. */
45
67
  steers(): Promise<QueuedMessage[]>;
46
68
  /**
@@ -48,6 +70,47 @@ export declare class ThreadRecord {
48
70
  * delivers as input stop being steers: re-delivering the turn re-sends them.
49
71
  */
50
72
  begin(ctx: Context, messageIds: ReadonlyArray<string>): Promise<void>;
73
+ /**
74
+ * The turn on `ctx` stopped rather than redo a recorded effect under a newer flow
75
+ * version. It stays, marked, until the host settles it.
76
+ */
77
+ stick(ctx: Context, stuck: {
78
+ path: string;
79
+ from: string;
80
+ to: string;
81
+ }): Promise<void>;
82
+ /**
83
+ * Settle a stuck turn. `continue` and `restart` clear the mark so the turn can
84
+ * run; `continue` also lets its next run discard what no longer matches.
85
+ * `abandon` forgets the turn. Resolves the turn it settled, or undefined when
86
+ * the thread has no stuck turn.
87
+ */
88
+ settle(action: 'continue' | 'restart' | 'abandon'): Promise<SessionRecord['turn']>;
89
+ /**
90
+ * The turn on `ctx` parked: keep its record, marked with when to wake it. Its
91
+ * checkpoint and ledger stay, since they are what the woken turn resumes from.
92
+ */
93
+ park(ctx: Context, until: number | undefined): Promise<void>;
94
+ /**
95
+ * The turn on `ctx` ended here without finishing. Best-effort: a turn whose mark
96
+ * does not land is simply taken for one that was cut off.
97
+ */
98
+ stop(ctx: Context, reason: string, at: number): Promise<void>;
99
+ /**
100
+ * The turn on `ctx` gave its answer: remember it under the turn's message ids, so
101
+ * the same messages delivered again get it back (`answerFor`). Call before `end`,
102
+ * which forgets the turn. Only the last few turns are kept.
103
+ */
104
+ answered(ctx: Context, text: string): Promise<void>;
105
+ /**
106
+ * The answer a finished turn gave to the message `messageId`, when one of the
107
+ * thread's recent turns delivered it.
108
+ */
109
+ answerFor(messageId: string): Promise<string | undefined>;
110
+ /** The executions of the thread's turns that have a trail: recent finished ones, then the one in flight. */
111
+ executions(): Promise<string[]>;
112
+ /** The turn in flight, cut off or parked, when one is recorded. */
113
+ turn(): Promise<SessionRecord['turn']>;
51
114
  /**
52
115
  * The turn on `ctx` finished: store the history it left and drop its checkpoint.
53
116
  * Only steers still queued are kept; the rest were applied or dropped.
@@ -58,8 +121,21 @@ export declare class ThreadRecord {
58
121
  /** The stored totals. */
59
122
  usage(): Promise<SessionUsage>;
60
123
  private update;
61
- /** Read-modify-write the stored record. Call only from inside `run`. */
124
+ /**
125
+ * A write the turn itself makes. Under a lease it carries the lease's term and is
126
+ * refused when the record already holds a higher one — another harness took the
127
+ * turn, whatever this one's clock says — and a write that fails throws instead of
128
+ * being logged (spec 23 § One writer per turn, § Fail-stop).
129
+ */
130
+ private updateHeld;
131
+ /** Read-modify-write the stored record, best-effort. Call only from inside `run`. */
62
132
  private write;
133
+ /**
134
+ * Apply `change` to what storage holds now. On storage that can compare-and-set
135
+ * the write lands only if nothing else wrote meanwhile, and is tried again on what
136
+ * the other writer left, so two harnesses never overwrite each other's fields.
137
+ */
138
+ private commit;
63
139
  private parseInput;
64
140
  private load;
65
141
  private run;
@@ -7,6 +7,11 @@
7
7
  * read-modify-write of the stored record, so a harness that served the last turn and
8
8
  * a harness built a moment ago behave the same.
9
9
  */
10
+ import { NoeticErrorImpl } from '@noetic-tools/types';
11
+ /** How many finished turns a thread remembers, to answer a message delivered again. */
12
+ const MAX_DONE_TURNS = 20;
13
+ /** How many times a compare-and-set write is tried against a record that keeps changing. */
14
+ const COMMIT_ATTEMPTS = 8;
10
15
  const EMPTY_USAGE = {
11
16
  inputTokens: 0,
12
17
  outputTokens: 0,
@@ -25,10 +30,24 @@ export class ThreadRecord {
25
30
  host;
26
31
  threadId;
27
32
  queue = Promise.resolve();
33
+ /** The lease the turn in flight runs under, when storage can compare-and-set. */
34
+ fence;
28
35
  constructor(host, threadId) {
29
36
  this.host = host;
30
37
  this.threadId = threadId;
31
38
  }
39
+ /**
40
+ * Run the turn's own writes (`begin`, `end`) under `fence`: a harness that lost
41
+ * the lease does not overwrite the record, and a write that fails stops the turn
42
+ * (spec 23 § One writer per turn, § Fail-stop). `undefined` goes back to best-effort.
43
+ */
44
+ hold(fence) {
45
+ this.fence = fence;
46
+ }
47
+ /** The lease term the stored record was last written at, when it was written under one. */
48
+ term() {
49
+ return this.run(async () => (await this.load())?.term);
50
+ }
32
51
  /** The history the thread's next turn builds on: what storage holds, or none. */
33
52
  history() {
34
53
  return this.run(async () => this.host.parseItems((await this.load())?.items ?? []));
@@ -53,7 +72,7 @@ export class ThreadRecord {
53
72
  if (!turn) {
54
73
  return undefined;
55
74
  }
56
- if (sameIds(turn.messageIds, messageIds)) {
75
+ if (isSameDelivery(turn.messageIds, messageIds)) {
57
76
  return (await this.host.restore(turn.executionId, opts)) ?? undefined;
58
77
  }
59
78
  await this.write(withoutTurn);
@@ -61,16 +80,44 @@ export class ThreadRecord {
61
80
  return undefined;
62
81
  });
63
82
  }
83
+ /** Forget the turn in flight and what it recorded: the host aborted a parked turn. */
84
+ drop() {
85
+ return this.run(async () => {
86
+ const turn = (await this.load())?.turn;
87
+ if (!turn) {
88
+ return undefined;
89
+ }
90
+ await this.write(withoutTurn);
91
+ await this.host.clearCheckpoint(turn.executionId);
92
+ return turn;
93
+ });
94
+ }
64
95
  /** Keep a steer sent into the running turn, so a resumed turn still applies it. */
65
96
  keepSteer(message) {
66
97
  if (message.deliveryMode !== 'between-rounds' && message.deliveryMode !== 'next-item') {
67
98
  return Promise.resolve();
68
99
  }
100
+ return this.keepQueued(message);
101
+ }
102
+ /**
103
+ * Keep a message a parked turn has not taken yet, steer or not: with no process
104
+ * holding the turn, storage is the only queue there is. An `interrupt` is never
105
+ * kept; it replaces the turn.
106
+ */
107
+ keepQueued(message) {
108
+ if (message.deliveryMode === 'interrupt') {
109
+ return Promise.resolve();
110
+ }
69
111
  const steer = {
70
112
  id: message.id,
71
113
  input: message.input,
72
114
  deliveryMode: message.deliveryMode,
73
115
  enqueuedAt: message.enqueuedAt,
116
+ ...(message.options.resourceId === undefined
117
+ ? {}
118
+ : {
119
+ resourceId: message.options.resourceId,
120
+ }),
74
121
  };
75
122
  return this.update((record) => ({
76
123
  ...record,
@@ -86,9 +133,13 @@ export class ThreadRecord {
86
133
  id: steer.id,
87
134
  input: this.parseInput(steer.input),
88
135
  deliveryMode: steer.deliveryMode,
89
- // Options carry live objects (layers, state) that storage cannot hold; a
90
- // steer applied mid-turn never reads them.
91
- options: {},
136
+ // Options carry live objects (layers, state) that storage cannot hold. The
137
+ // harness the message was sent to still has them and puts them back.
138
+ options: steer.resourceId === undefined
139
+ ? {}
140
+ : {
141
+ resourceId: steer.resourceId,
142
+ },
92
143
  enqueuedAt: steer.enqueuedAt,
93
144
  })));
94
145
  }
@@ -97,7 +148,7 @@ export class ThreadRecord {
97
148
  * delivers as input stop being steers: re-delivering the turn re-sends them.
98
149
  */
99
150
  begin(ctx, messageIds) {
100
- return this.update((record) => ({
151
+ return this.updateHeld(ctx, (record) => ({
101
152
  ...record,
102
153
  steers: record.steers?.filter((steer) => !messageIds.includes(steer.id)),
103
154
  turn: {
@@ -105,15 +156,163 @@ export class ThreadRecord {
105
156
  messageIds: [
106
157
  ...messageIds,
107
158
  ],
159
+ ...(this.host.version === undefined
160
+ ? {}
161
+ : {
162
+ version: this.host.version,
163
+ }),
164
+ // Kept until the turn ends: a host that dies part way through going on
165
+ // must not find the same step stuck again.
166
+ ...(record.turn?.executionId === ctx.id && record.turn.accept !== undefined
167
+ ? {
168
+ accept: record.turn.accept,
169
+ }
170
+ : {}),
108
171
  },
109
172
  }));
110
173
  }
174
+ /**
175
+ * The turn on `ctx` stopped rather than redo a recorded effect under a newer flow
176
+ * version. It stays, marked, until the host settles it.
177
+ */
178
+ stick(ctx, stuck) {
179
+ return this.update((record) => record.turn?.executionId === ctx.id
180
+ ? {
181
+ ...record,
182
+ turn: {
183
+ ...record.turn,
184
+ stuck,
185
+ },
186
+ }
187
+ : record);
188
+ }
189
+ /**
190
+ * Settle a stuck turn. `continue` and `restart` clear the mark so the turn can
191
+ * run; `continue` also lets its next run discard what no longer matches.
192
+ * `abandon` forgets the turn. Resolves the turn it settled, or undefined when
193
+ * the thread has no stuck turn.
194
+ */
195
+ settle(action) {
196
+ return this.run(async () => {
197
+ const turn = (await this.load())?.turn;
198
+ if (!turn?.stuck) {
199
+ return undefined;
200
+ }
201
+ const { stuck, stopped: _stopped, ...rest } = turn;
202
+ await this.write((record) => action === 'abandon'
203
+ ? withoutTurn(record)
204
+ : {
205
+ ...record,
206
+ turn: {
207
+ ...rest,
208
+ ...(action === 'continue'
209
+ ? {
210
+ accept: stuck.path,
211
+ }
212
+ : {}),
213
+ },
214
+ });
215
+ return turn;
216
+ });
217
+ }
218
+ /**
219
+ * The turn on `ctx` parked: keep its record, marked with when to wake it. Its
220
+ * checkpoint and ledger stay, since they are what the woken turn resumes from.
221
+ */
222
+ park(ctx, until) {
223
+ return this.updateHeld(ctx, (record) => record.turn
224
+ ? {
225
+ ...record,
226
+ turn: {
227
+ ...record.turn,
228
+ parked: until === undefined
229
+ ? {}
230
+ : {
231
+ until,
232
+ },
233
+ },
234
+ }
235
+ : record);
236
+ }
237
+ /**
238
+ * The turn on `ctx` ended here without finishing. Best-effort: a turn whose mark
239
+ * does not land is simply taken for one that was cut off.
240
+ */
241
+ stop(ctx, reason, at) {
242
+ return this.update((record) => record.turn?.executionId === ctx.id
243
+ ? {
244
+ ...record,
245
+ turn: {
246
+ ...record.turn,
247
+ stopped: {
248
+ at,
249
+ reason,
250
+ },
251
+ },
252
+ }
253
+ : record);
254
+ }
255
+ /**
256
+ * The turn on `ctx` gave its answer: remember it under the turn's message ids, so
257
+ * the same messages delivered again get it back (`answerFor`). Call before `end`,
258
+ * which forgets the turn. Only the last few turns are kept.
259
+ */
260
+ answered(ctx, text) {
261
+ return this.update((record) => {
262
+ if (record.turn?.executionId !== ctx.id) {
263
+ return record;
264
+ }
265
+ const kept = (record.done ?? []).slice(1 - MAX_DONE_TURNS);
266
+ return {
267
+ ...record,
268
+ done: [
269
+ ...(MAX_DONE_TURNS > 1 ? kept : []),
270
+ {
271
+ messageIds: record.turn.messageIds,
272
+ text,
273
+ executionId: ctx.id,
274
+ },
275
+ ],
276
+ };
277
+ });
278
+ }
279
+ /**
280
+ * The answer a finished turn gave to the message `messageId`, when one of the
281
+ * thread's recent turns delivered it.
282
+ */
283
+ answerFor(messageId) {
284
+ return this.run(async () => {
285
+ const done = (await this.load())?.done ?? [];
286
+ return done.findLast((turn) => turn.messageIds.includes(messageId))?.text;
287
+ });
288
+ }
289
+ /** The executions of the thread's turns that have a trail: recent finished ones, then the one in flight. */
290
+ executions() {
291
+ return this.run(async () => {
292
+ const record = await this.load();
293
+ const ids = (record?.done ?? []).flatMap((turn) => turn.executionId === undefined
294
+ ? []
295
+ : [
296
+ turn.executionId,
297
+ ]);
298
+ return record?.turn
299
+ ? [
300
+ ...ids,
301
+ record.turn.executionId,
302
+ ]
303
+ : ids;
304
+ });
305
+ }
306
+ /** The turn in flight, cut off or parked, when one is recorded. */
307
+ turn() {
308
+ return this.run(async () => (await this.load())?.turn);
309
+ }
111
310
  /**
112
311
  * The turn on `ctx` finished: store the history it left and drop its checkpoint.
113
312
  * Only steers still queued are kept; the rest were applied or dropped.
114
313
  */
115
314
  async end(ctx, history, queuedIds) {
116
- await this.update((record) => ({
315
+ await this.updateHeld(ctx, (record) => ({
117
316
  ...withoutTurn(record),
118
317
  steers: record.steers?.filter((steer) => queuedIds.includes(steer.id)),
119
318
  items: [
@@ -140,19 +339,75 @@ export class ThreadRecord {
140
339
  update(change) {
141
340
  return this.run(() => this.write(change));
142
341
  }
143
- /** Read-modify-write the stored record. Call only from inside `run`. */
144
- async write(change) {
145
- const record = change((await this.load()) ?? {
146
- items: [],
342
+ /**
343
+ * A write the turn itself makes. Under a lease it carries the lease's term and is
344
+ * refused when the record already holds a higher one — another harness took the
345
+ * turn, whatever this one's clock says — and a write that fails throws instead of
346
+ * being logged (spec 23 § One writer per turn, § Fail-stop).
347
+ */
348
+ updateHeld(ctx, change) {
349
+ const fence = this.fence;
350
+ if (!fence) {
351
+ return this.update(change);
352
+ }
353
+ return this.run(async () => {
354
+ fence.assert();
355
+ try {
356
+ await this.commit((record) => {
357
+ if ((record.term ?? 0) > fence.term) {
358
+ throw fence.lose(`the thread record was written at term ${record.term}`);
359
+ }
360
+ return {
361
+ ...change(record),
362
+ term: fence.term,
363
+ };
364
+ });
365
+ }
366
+ catch (error) {
367
+ if (error instanceof NoeticErrorImpl) {
368
+ throw error;
369
+ }
370
+ throw new NoeticErrorImpl({
371
+ kind: 'ledger_write_failed',
372
+ executionId: ctx.id,
373
+ path: `session:${this.threadId}`,
374
+ cause: error instanceof Error ? error : new Error(String(error)),
375
+ });
376
+ }
147
377
  });
378
+ }
379
+ /** Read-modify-write the stored record, best-effort. Call only from inside `run`. */
380
+ async write(change) {
148
381
  try {
149
- await this.host.store.save(this.threadId, record);
382
+ await this.commit(change);
150
383
  }
151
384
  catch (error) {
152
385
  // Same rule as checkpoints: losing the record costs resumability, not the turn.
153
386
  console.warn(`AgentHarness: failed to persist session "${this.threadId}":`, error instanceof Error ? error.message : String(error));
154
387
  }
155
388
  }
389
+ /**
390
+ * Apply `change` to what storage holds now. On storage that can compare-and-set
391
+ * the write lands only if nothing else wrote meanwhile, and is tried again on what
392
+ * the other writer left, so two harnesses never overwrite each other's fields.
393
+ */
394
+ async commit(change) {
395
+ const store = this.host.store;
396
+ for (let attempt = 0; attempt < COMMIT_ATTEMPTS; attempt += 1) {
397
+ const stored = await store.read(this.threadId);
398
+ const next = change(stored.record ?? {
399
+ items: [],
400
+ });
401
+ if (!store.swap) {
402
+ await store.save(this.threadId, next);
403
+ return;
404
+ }
405
+ if (await store.swap(this.threadId, stored.raw, next)) {
406
+ return;
407
+ }
408
+ }
409
+ throw new Error(`session "${this.threadId}" kept changing while it was being written`);
410
+ }
156
411
  parseInput(input) {
157
412
  if (typeof input === 'string') {
158
413
  return input;
@@ -177,8 +432,12 @@ function withoutTurn(record) {
177
432
  void turn;
178
433
  return rest;
179
434
  }
180
- function sameIds(a, b) {
181
- return a.length === b.length && a.every((id, i) => id === b[i]);
435
+ /**
436
+ * True when `delivered` is the turn's own messages coming round again. Some of them
437
+ * is enough: a queue redelivers one at a time, and a wake hands them back together.
438
+ */
439
+ function isSameDelivery(turn, delivered) {
440
+ return delivered.length > 0 && delivered.every((id) => turn.includes(id));
182
441
  }
183
442
  function addUsage(total, spent) {
184
443
  const cost = (total.cost ?? 0) + spent.cost;