@noetic-tools/core 5.21.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 (83) 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.js +8 -0
  30. package/dist/harness/model-rounds.d.ts +30 -0
  31. package/dist/harness/model-rounds.js +146 -1
  32. package/dist/harness/model-tool-round.d.ts +3 -0
  33. package/dist/harness/model-tool-round.js +201 -19
  34. package/dist/harness/park-watchers.d.ts +93 -0
  35. package/dist/harness/park-watchers.js +217 -0
  36. package/dist/harness/read-decision.d.ts +23 -0
  37. package/dist/harness/read-decision.js +100 -0
  38. package/dist/harness/spend.js +4 -0
  39. package/dist/harness/steer-inbox.js +3 -1
  40. package/dist/harness/thread-record.d.ts +77 -1
  41. package/dist/harness/thread-record.js +272 -13
  42. package/dist/index.d.ts +17 -7
  43. package/dist/index.js +10 -2
  44. package/dist/interpreter/acp-resume.d.ts +77 -0
  45. package/dist/interpreter/acp-resume.js +164 -0
  46. package/dist/interpreter/acp-tools.d.ts +11 -0
  47. package/dist/interpreter/acp-tools.js +94 -7
  48. package/dist/interpreter/connection-steps.d.ts +24 -1
  49. package/dist/interpreter/connection-steps.js +77 -2
  50. package/dist/interpreter/execute-acp-agent.js +111 -15
  51. package/dist/interpreter/execute-action.js +7 -0
  52. package/dist/interpreter/execute-call.js +30 -4
  53. package/dist/interpreter/execute-control.js +21 -0
  54. package/dist/interpreter/execute-invoke-tool.js +149 -5
  55. package/dist/interpreter/execute-wait.js +67 -9
  56. package/dist/interpreter/execute.js +4 -0
  57. package/dist/interpreter/turn-ending.d.ts +15 -0
  58. package/dist/interpreter/turn-ending.js +46 -0
  59. package/dist/portable/builders.d.ts +1 -1
  60. package/dist/portable/builders.js +1 -1
  61. package/dist/runtime/durable/parking.d.ts +61 -0
  62. package/dist/runtime/durable/parking.js +137 -0
  63. package/dist/runtime/durable/session-store.d.ts +38 -0
  64. package/dist/runtime/durable/session-store.js +79 -1
  65. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  66. package/dist/runtime/durable/step-ledger.js +352 -15
  67. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  68. package/dist/runtime/durable/turn-lease.js +307 -0
  69. package/dist/runtime/held-calls.d.ts +192 -0
  70. package/dist/runtime/held-calls.js +496 -0
  71. package/dist/runtime/in-memory-storage.d.ts +10 -1
  72. package/dist/runtime/in-memory-storage.js +20 -2
  73. package/dist/runtime/message-queue.d.ts +2 -0
  74. package/dist/runtime/message-queue.js +8 -0
  75. package/dist/runtime/session-runner.d.ts +18 -2
  76. package/dist/runtime/session-runner.js +88 -3
  77. package/dist/runtime/tool-approval.d.ts +46 -6
  78. package/dist/runtime/tool-approval.js +160 -38
  79. package/dist/runtime/tool-call.d.ts +34 -2
  80. package/dist/runtime/tool-call.js +182 -13
  81. package/dist/runtime/tool-context.d.ts +15 -1
  82. package/dist/runtime/tool-context.js +38 -2
  83. package/package.json +3 -3
@@ -7,7 +7,9 @@ import { SteerPoint } from '@noetic-tools/types';
7
7
  import { itemsToInput } from '../adapters/openrouter.js';
8
8
  import { isFunctionCall } from '../interpreter/typeguards.js';
9
9
  import { drainsOf } from '../runtime/drain.js';
10
+ import { heldCallsOf, heldScopeOf, mayWriteHolds, waitOnHeldCalls } from '../runtime/held-calls.js';
10
11
  import { createToolResultItem, executeToolCall } from '../runtime/tool-call.js';
12
+ import { emitToolUi } from '../runtime/tool-ui.js';
11
13
  import { findTool } from './model-request.js';
12
14
  //#endregion
13
15
  //#region Tool Round
@@ -41,6 +43,7 @@ export async function runToolRound(scope, params) {
41
43
  spans: params.spans,
42
44
  modelSpan: params.modelSpan,
43
45
  steers: params.steers,
46
+ calls: params.calls,
44
47
  });
45
48
  return true;
46
49
  }
@@ -54,18 +57,25 @@ async function executeToolRound(scope, params) {
54
57
  conversationInput.push({
55
58
  type: 'function_call',
56
59
  callId: fc.callId,
57
- id: fc.id ?? crypto.randomUUID(),
60
+ // Derived, so a resumed round sends the id it sent before.
61
+ id: fc.id ?? `fc_${fc.callId}`,
58
62
  name: fc.name,
59
63
  arguments: fc.arguments,
60
64
  });
61
65
  }
66
+ const heldCalls = [];
62
67
  for (const [index, fc] of functionCalls.entries()) {
63
68
  await drainsOf(request.ctx)?.hold(request.ctx);
64
69
  if (request.signal?.aborted) {
65
70
  break;
66
71
  }
67
72
  const remaining = functionCalls.slice(index);
68
- if (steers?.hasQueued() && (await steers.offer(SteerPoint.BeforeToolCall, remaining))) {
73
+ // A call an earlier attempt finished is not up for skipping: it already ran.
74
+ const finished = params.calls?.take(fc) !== undefined;
75
+ if (!finished &&
76
+ steers?.hasQueued() &&
77
+ (await steers.offer(SteerPoint.BeforeToolCall, remaining))) {
78
+ await dropHolds(scope, request, remaining);
69
79
  for (const skipped of remaining) {
70
80
  recordSkippedToolCall(scope, {
71
81
  fc: skipped,
@@ -79,15 +89,67 @@ async function executeToolRound(scope, params) {
79
89
  break;
80
90
  }
81
91
  const toolForCall = findTool(allowedTools, fc.name);
82
- const approval = await executeFunctionCall(scope, {
92
+ const call = await executeFunctionCall(scope, {
83
93
  fc,
84
94
  request,
85
95
  allowedTools,
86
96
  allItems,
87
97
  conversationInput,
88
98
  emitIfAllowed: params.emitIfAllowed,
99
+ calls: params.calls,
89
100
  });
90
- spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false, approval);
101
+ if (call.held) {
102
+ heldCalls.push(fc);
103
+ continue;
104
+ }
105
+ spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false, call.approval);
106
+ }
107
+ // Calls held for a person: the round goes no further until each has an answer.
108
+ while (heldCalls.length > 0) {
109
+ // A message that arrives while calls are held is a steer like any other: the
110
+ // context layers decide. Applied, the held calls are skipped and the round goes on.
111
+ if (steers?.hasQueued() && (await steers.offer(SteerPoint.Held, heldCalls))) {
112
+ await dropHolds(scope, request, heldCalls);
113
+ for (const skipped of heldCalls.splice(0)) {
114
+ recordUnrunToolCall(scope, {
115
+ fc: skipped,
116
+ output: SKIPPED_FOR_STEER_OUTPUT,
117
+ request,
118
+ allowedTools,
119
+ allItems,
120
+ conversationInput,
121
+ emitIfAllowed: params.emitIfAllowed,
122
+ });
123
+ }
124
+ break;
125
+ }
126
+ if (!request.ctx) {
127
+ throw new Error('A held tool call needs a context to wait on.');
128
+ }
129
+ await waitOnHeldCalls({
130
+ harness: scope.harness,
131
+ ctx: request.ctx,
132
+ callIds: heldCalls.map((fc) => fc.callId),
133
+ signal: request.signal,
134
+ });
135
+ for (const fc of heldCalls.splice(0)) {
136
+ const toolForCall = findTool(allowedTools, fc.name);
137
+ const call = await executeFunctionCall(scope, {
138
+ fc,
139
+ request,
140
+ allowedTools,
141
+ allItems,
142
+ conversationInput,
143
+ emitIfAllowed: params.emitIfAllowed,
144
+ calls: params.calls,
145
+ announced: true,
146
+ });
147
+ if (call.held) {
148
+ heldCalls.push(fc);
149
+ continue;
150
+ }
151
+ spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false, call.approval);
152
+ }
91
153
  }
92
154
  params.emitIfAllowed('tool_round_completed', {
93
155
  round: params.round,
@@ -96,10 +158,12 @@ async function executeToolRound(scope, params) {
96
158
  }
97
159
  async function executeFunctionCall(scope, params) {
98
160
  const { fc, request, allowedTools, allItems, conversationInput } = params;
99
- params.emitIfAllowed('tool_call_started', {
100
- name: fc.name,
101
- callId: fc.callId,
102
- });
161
+ if (!params.announced) {
162
+ params.emitIfAllowed('tool_call_started', {
163
+ name: fc.name,
164
+ callId: fc.callId,
165
+ });
166
+ }
103
167
  let parsedArgs;
104
168
  try {
105
169
  parsedArgs = JSON.parse(fc.arguments);
@@ -114,25 +178,81 @@ async function executeFunctionCall(scope, params) {
114
178
  conversationInput,
115
179
  emitIfAllowed: params.emitIfAllowed,
116
180
  });
117
- return undefined;
181
+ return {};
118
182
  }
119
183
  if (!request.tools) {
120
184
  throw new Error(`executeFunctionCall invoked without tools on CallModelRequest (tool name: ${fc.name}).`);
121
185
  }
122
186
  const toolForCall = findTool(allowedTools, fc.name);
123
- const toolResult = await executeToolCall({
124
- toolName: fc.name,
125
- args: parsedArgs,
126
- tools: allowedTools,
127
- context: request.ctx,
128
- harness: scope.harness,
129
- layers: request.layers,
130
- callId: fc.callId,
131
- });
187
+ // An earlier attempt of this round may have finished this call: go on with what
188
+ // it produced instead of running the tool again.
189
+ // A durable tool's call marks its model step as having had a lasting effect.
190
+ if (toolForCall?.durable === true) {
191
+ // Under the round, which is what gets recorded: a note at the step's own path
192
+ // would mark nothing until the whole step finished.
193
+ params.calls?.noteEffect(fc);
194
+ }
195
+ // A tool that opts out of recording (`durable: false`) always runs again.
196
+ const keeps = toolForCall?.durable !== false;
197
+ const recorded = keeps ? params.calls?.take(fc) : undefined;
198
+ const toolResult = recorded ??
199
+ (await executeToolCall({
200
+ toolName: fc.name,
201
+ args: parsedArgs,
202
+ tools: allowedTools,
203
+ context: request.ctx,
204
+ harness: scope.harness,
205
+ layers: request.layers,
206
+ callId: fc.callId,
207
+ keyScope: params.calls?.scope,
208
+ }));
209
+ // Held: it has no result yet. Nothing goes into the conversation for it.
210
+ if (toolResult.held) {
211
+ if (!params.announced) {
212
+ params.emitIfAllowed('tool_call_held', {
213
+ ...toolResult.held,
214
+ });
215
+ }
216
+ return {
217
+ held: true,
218
+ };
219
+ }
220
+ // A replayed call appends the item it appended before, under the same id.
221
+ const itemId = recorded?.itemId ?? crypto.randomUUID();
222
+ const stored = recorded || !keeps
223
+ ? undefined
224
+ : await params.calls?.record(fc, {
225
+ ...toolResult,
226
+ itemId,
227
+ });
228
+ // The intent of a durable call is dropped once its result is on record. A result
229
+ // that could not be recorded keeps it, so a resume asks rather than runs again.
230
+ const writes = request.ctx !== undefined && mayWriteHolds(request.ctx);
231
+ if (toolResult.armed && stored !== false && writes) {
232
+ await heldCallsOf(scope.harness).disarm(heldScopeOf(request.ctx), fc.callId);
233
+ }
234
+ if (toolResult.settled && writes) {
235
+ await heldCallsOf(scope.harness).close(heldScopeOf(request.ctx), fc.callId);
236
+ }
237
+ if (recorded && request.ctx) {
238
+ // A host that died between recording the result and the two steps above left
239
+ // the call's intent or its answered hold behind. The record says it is done.
240
+ if (writes) {
241
+ await tidyFinishedCall(scope, request.ctx, fc.callId);
242
+ }
243
+ replayToolUi({
244
+ ctx: request.ctx,
245
+ tool: toolForCall,
246
+ callId: fc.callId,
247
+ args: parsedArgs,
248
+ result: recorded,
249
+ });
250
+ }
132
251
  // Owner-scoped result validation: a tool's `toolResults` schemas apply
133
252
  // only to that tool's own result items. Harness-level `opts.itemSchemas`
134
253
  // stay global by design; sibling tools' schemas never reject this item.
135
254
  const outputItem = createToolResultItem({
255
+ id: itemId,
136
256
  output: toolResult.output,
137
257
  callId: fc.callId,
138
258
  roundItemSchemas: scope.itemSchemas.extend(toolForCall?.itemSchemas),
@@ -154,8 +274,70 @@ async function executeFunctionCall(scope, params) {
154
274
  callId: fc.callId,
155
275
  error: toolResult.error === true,
156
276
  output: toolResult.output,
277
+ ...(recorded
278
+ ? {
279
+ replayed: true,
280
+ }
281
+ : {}),
282
+ });
283
+ return {
284
+ approval: toolResult.approval,
285
+ };
286
+ }
287
+ /** Drop what a finished call may have left in storage: its intent, its answered hold. */
288
+ async function tidyFinishedCall(scope, ctx, callId) {
289
+ const holds = heldCallsOf(scope.harness);
290
+ const executionId = heldScopeOf(ctx);
291
+ await holds.disarm(executionId, callId);
292
+ if (await holds.load(executionId, callId)) {
293
+ await holds.close(executionId, callId);
294
+ }
295
+ }
296
+ /**
297
+ * Show a replayed call in the tool's UI as it was shown the first time: the call,
298
+ * then how it ended. Nothing for a call whose body never ran.
299
+ */
300
+ function replayToolUi(params) {
301
+ const { tool, result } = params;
302
+ if (!tool || !result.ran) {
303
+ return;
304
+ }
305
+ const base = {
306
+ ctx: params.ctx,
307
+ tool,
308
+ callId: params.callId,
309
+ args: params.args,
310
+ };
311
+ emitToolUi({
312
+ ...base,
313
+ phase: 'call',
157
314
  });
158
- return toolResult.approval;
315
+ if (result.error) {
316
+ emitToolUi({
317
+ ...base,
318
+ phase: 'error',
319
+ error: new Error(result.output.replace(/^Error: /, '')),
320
+ });
321
+ return;
322
+ }
323
+ emitToolUi({
324
+ ...base,
325
+ phase: 'result',
326
+ output: result.result,
327
+ });
328
+ }
329
+ /** Drop the records of calls that are being skipped, so none stays listed as held. */
330
+ async function dropHolds(scope, request, calls) {
331
+ if (!request.ctx || !mayWriteHolds(request.ctx)) {
332
+ return;
333
+ }
334
+ const holds = heldCallsOf(scope.harness);
335
+ const executionId = heldScopeOf(request.ctx);
336
+ for (const call of calls) {
337
+ if (await holds.load(executionId, call.callId)) {
338
+ await holds.close(executionId, call.callId);
339
+ }
340
+ }
159
341
  }
160
342
  function recordSkippedToolCall(scope, params) {
161
343
  params.emitIfAllowed('tool_call_started', {
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Auto-wake: a live harness watching over the turns it parked
3
+ * (spec 23 § Parked turns).
4
+ *
5
+ * Parking closes a turn's own listener, so without this a parked turn in a
6
+ * long-lived process would sit until something outside called `wake()`. A
7
+ * watcher stands in for the turn: a timer for its deadline, and a listener on
8
+ * each event it waits for, from the cursor the wait recorded. Either one wakes
9
+ * the turn.
10
+ *
11
+ * A watcher knows the event's type, not the wait's `filter`, which is code in
12
+ * the flow. So it wakes on any event of that type, and a turn the filter turns
13
+ * down parks again. It remembers the last cursor it saw, so each event wakes
14
+ * the turn at most once, and a burst of events wakes it once.
15
+ */
16
+ import type { ConnectionEventInit, EventStream, ExecuteOptions } from '@noetic-tools/types';
17
+ /** An event a parked turn waits for. */
18
+ export interface ParkedWait {
19
+ readonly connection: string;
20
+ readonly event: string;
21
+ readonly cursor: string | null;
22
+ }
23
+ /** A long operation a parked turn's call waits on. */
24
+ export interface ParkedTask {
25
+ readonly connection: string;
26
+ readonly taskId: string;
27
+ }
28
+ /** What the watchers need of their harness. */
29
+ export interface ParkWatcherHost {
30
+ /** Listen on a harness connection. */
31
+ listen(connection: string, request: {
32
+ event: string;
33
+ cursor: string | null;
34
+ signal: AbortSignal;
35
+ }): Promise<EventStream<ConnectionEventInit>>;
36
+ /** The events the parked execution waits for. */
37
+ waits(executionId: string): Promise<ParkedWait[]>;
38
+ /** The long operations the parked execution's calls wait on. */
39
+ tasks(executionId: string): Promise<ParkedTask[]>;
40
+ /** The state of one of them now, or undefined when it cannot be read. */
41
+ taskState(task: ParkedTask, signal: AbortSignal): Promise<string | undefined>;
42
+ /** Resume the thread's turn. Resolves false when it could not be resumed just now. */
43
+ wake(threadId: string, options: ExecuteOptions): Promise<boolean>;
44
+ /** The execution of the turn the thread has parked now, or undefined when it has none. */
45
+ parked(threadId: string): Promise<string | undefined>;
46
+ now(): number;
47
+ }
48
+ /** What is known about one parked turn. */
49
+ export interface ParkedTurn {
50
+ readonly executionId: string;
51
+ /** When its earliest wait runs out, or undefined when none has a deadline. */
52
+ readonly until: number | undefined;
53
+ /** The `execute()` options the turn ran with, to resume it with. */
54
+ readonly options: ExecuteOptions;
55
+ }
56
+ /** @public How long auto-wake waits after an event before waking a turn, so a burst wakes it once. */
57
+ export declare const DEFAULT_WAKE_DEBOUNCE_MS = 250;
58
+ /** @public How often auto-wake reads the state of a long operation a parked turn waits on. */
59
+ export declare const DEFAULT_TASK_POLL_MS = 5000;
60
+ /** One harness's watchers, by thread. */
61
+ export declare class ParkWatchers {
62
+ private readonly host;
63
+ private readonly debounceMs;
64
+ private readonly taskPollMs;
65
+ private readonly watchers;
66
+ /** The last cursor seen for a wait, so a turn that parks again does not see it twice. */
67
+ private readonly seen;
68
+ /** The harness closed: a wake still being tried is given up. */
69
+ private closed;
70
+ constructor(host: ParkWatcherHost, debounceMs: number, taskPollMs: number);
71
+ /** True when the thread's parked turn is being watched. */
72
+ has(threadId: string): boolean;
73
+ /** Watch over a turn that just parked, or that storage says is parked. */
74
+ watch(threadId: string, turn: ParkedTurn): void;
75
+ /** Stop watching a thread: its turn was woken, or is being. */
76
+ stop(threadId: string): void;
77
+ /** The turn ended: drop what was remembered about its waits. */
78
+ forget(threadId: string, executionId: string): void;
79
+ stopAll(): void;
80
+ private armDeadline;
81
+ private listenForWaits;
82
+ /** Listen for one awaited event; the first one seen wakes the turn, after the debounce. */
83
+ private listenFor;
84
+ /**
85
+ * A long operation has no event to listen for, so its state is read every so
86
+ * often. The turn is woken when the state is no longer the one it parked on:
87
+ * finished, failed, or asking a question. A state it already woke for does not
88
+ * wake it again, or a turn waiting on a person's answer would never rest.
89
+ */
90
+ private pollTasks;
91
+ /** Wake the turn. The runner may still be closing the parked turn out, so try for a while. */
92
+ private fire;
93
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Auto-wake: a live harness watching over the turns it parked
3
+ * (spec 23 § Parked turns).
4
+ *
5
+ * Parking closes a turn's own listener, so without this a parked turn in a
6
+ * long-lived process would sit until something outside called `wake()`. A
7
+ * watcher stands in for the turn: a timer for its deadline, and a listener on
8
+ * each event it waits for, from the cursor the wait recorded. Either one wakes
9
+ * the turn.
10
+ *
11
+ * A watcher knows the event's type, not the wait's `filter`, which is code in
12
+ * the flow. So it wakes on any event of that type, and a turn the filter turns
13
+ * down parks again. It remembers the last cursor it saw, so each event wakes
14
+ * the turn at most once, and a burst of events wakes it once.
15
+ */
16
+ /** @public How long auto-wake waits after an event before waking a turn, so a burst wakes it once. */
17
+ export const DEFAULT_WAKE_DEBOUNCE_MS = 250;
18
+ /** @public How often auto-wake reads the state of a long operation a parked turn waits on. */
19
+ export const DEFAULT_TASK_POLL_MS = 5e3;
20
+ /** The longest delay a timer takes; a later deadline is reached in several steps. */
21
+ const MAX_TIMER_MS = 2 ** 31 - 1;
22
+ /** How many times a wake is tried while the runner is still closing the parked turn out. */
23
+ const WAKE_ATTEMPTS = 100;
24
+ const WAKE_RETRY_MS = 20;
25
+ //#endregion
26
+ //#region Helpers
27
+ /** Resolves after `ms`, or as soon as `signal` aborts. Leaves no listener behind. */
28
+ function pause(ms, signal) {
29
+ return new Promise((resolve) => {
30
+ const done = () => {
31
+ clearTimeout(timer);
32
+ signal?.removeEventListener('abort', done);
33
+ resolve();
34
+ };
35
+ const timer = setTimeout(done, ms);
36
+ signal?.addEventListener('abort', done, {
37
+ once: true,
38
+ });
39
+ });
40
+ }
41
+ //#endregion
42
+ //#region ParkWatchers
43
+ /** One harness's watchers, by thread. */
44
+ export class ParkWatchers {
45
+ host;
46
+ debounceMs;
47
+ taskPollMs;
48
+ watchers = new Map();
49
+ /** The last cursor seen for a wait, so a turn that parks again does not see it twice. */
50
+ seen = new Map();
51
+ /** The harness closed: a wake still being tried is given up. */
52
+ closed = false;
53
+ constructor(host, debounceMs, taskPollMs) {
54
+ this.host = host;
55
+ this.debounceMs = debounceMs;
56
+ this.taskPollMs = taskPollMs;
57
+ }
58
+ /** True when the thread's parked turn is being watched. */
59
+ has(threadId) {
60
+ return this.watchers.has(threadId);
61
+ }
62
+ /** Watch over a turn that just parked, or that storage says is parked. */
63
+ watch(threadId, turn) {
64
+ this.closed = false;
65
+ this.stop(threadId);
66
+ const watcher = {
67
+ controller: new AbortController(),
68
+ timer: undefined,
69
+ debounce: undefined,
70
+ };
71
+ this.watchers.set(threadId, watcher);
72
+ this.armDeadline(threadId, watcher, turn);
73
+ void this.listenForWaits(threadId, watcher, turn);
74
+ void this.pollTasks(threadId, watcher, turn).catch(() => undefined);
75
+ }
76
+ /** Stop watching a thread: its turn was woken, or is being. */
77
+ stop(threadId) {
78
+ const watcher = this.watchers.get(threadId);
79
+ if (!watcher) {
80
+ return;
81
+ }
82
+ this.watchers.delete(threadId);
83
+ watcher.controller.abort();
84
+ clearTimeout(watcher.timer);
85
+ clearTimeout(watcher.debounce);
86
+ }
87
+ /** The turn ended: drop what was remembered about its waits. */
88
+ forget(threadId, executionId) {
89
+ this.stop(threadId);
90
+ for (const key of [
91
+ ...this.seen.keys(),
92
+ ]) {
93
+ if (key.startsWith(`${executionId}\u0000`)) {
94
+ this.seen.delete(key);
95
+ }
96
+ }
97
+ }
98
+ stopAll() {
99
+ this.closed = true;
100
+ for (const threadId of [
101
+ ...this.watchers.keys(),
102
+ ]) {
103
+ this.stop(threadId);
104
+ }
105
+ }
106
+ armDeadline(threadId, watcher, turn) {
107
+ if (turn.until === undefined) {
108
+ return;
109
+ }
110
+ const until = turn.until;
111
+ const tick = () => {
112
+ const left = until - this.host.now();
113
+ if (left <= 0) {
114
+ void this.fire(threadId, watcher, turn);
115
+ return;
116
+ }
117
+ watcher.timer = setTimeout(tick, Math.min(left, MAX_TIMER_MS));
118
+ };
119
+ tick();
120
+ }
121
+ async listenForWaits(threadId, watcher, turn) {
122
+ let waits;
123
+ try {
124
+ waits = await this.host.waits(turn.executionId);
125
+ }
126
+ catch {
127
+ // The deadline still wakes it.
128
+ return;
129
+ }
130
+ for (const wait of waits) {
131
+ void this.listenFor(threadId, watcher, turn, wait).catch(() => undefined);
132
+ }
133
+ }
134
+ /** Listen for one awaited event; the first one seen wakes the turn, after the debounce. */
135
+ async listenFor(threadId, watcher, turn, wait) {
136
+ const signal = watcher.controller.signal;
137
+ const key = `${turn.executionId}\u0000${wait.connection}\u0000${wait.event}`;
138
+ const stream = await this.host.listen(wait.connection, {
139
+ event: wait.event,
140
+ cursor: this.seen.get(key) ?? wait.cursor,
141
+ signal,
142
+ });
143
+ await stream.ready;
144
+ for await (const message of stream) {
145
+ if (signal.aborted) {
146
+ return;
147
+ }
148
+ if (message.type !== 'event' || message.event.type !== wait.event) {
149
+ continue;
150
+ }
151
+ if (message.event.cursor !== null) {
152
+ this.seen.set(key, message.event.cursor);
153
+ }
154
+ // Keep reading during the debounce: later events of the burst move the cursor on.
155
+ watcher.debounce ??= setTimeout(() => {
156
+ void this.fire(threadId, watcher, turn);
157
+ }, this.debounceMs);
158
+ }
159
+ }
160
+ /**
161
+ * A long operation has no event to listen for, so its state is read every so
162
+ * often. The turn is woken when the state is no longer the one it parked on:
163
+ * finished, failed, or asking a question. A state it already woke for does not
164
+ * wake it again, or a turn waiting on a person's answer would never rest.
165
+ */
166
+ async pollTasks(threadId, watcher, turn) {
167
+ const signal = watcher.controller.signal;
168
+ const tasks = await this.host.tasks(turn.executionId);
169
+ while (tasks.length > 0 && !signal.aborted) {
170
+ for (const task of tasks) {
171
+ const state = await this.host.taskState(task, signal);
172
+ const key = `${turn.executionId}\u0000task\u0000${task.taskId}`;
173
+ if (state === 'working') {
174
+ // Back at work: the state it left is news again the next time it comes,
175
+ // as when a task asks a second question.
176
+ this.seen.delete(key);
177
+ continue;
178
+ }
179
+ if (state === undefined || this.seen.get(key) === state) {
180
+ continue;
181
+ }
182
+ this.seen.set(key, state);
183
+ void this.fire(threadId, watcher, turn);
184
+ return;
185
+ }
186
+ await pause(this.taskPollMs, signal);
187
+ }
188
+ }
189
+ /** Wake the turn. The runner may still be closing the parked turn out, so try for a while. */
190
+ async fire(threadId, watcher, turn) {
191
+ if (this.watchers.get(threadId) !== watcher) {
192
+ return;
193
+ }
194
+ this.stop(threadId);
195
+ for (let attempt = 0; attempt < WAKE_ATTEMPTS; attempt += 1) {
196
+ // Watched over, replaced by a newer watch, or the harness closed: not ours to wake.
197
+ if (this.closed || this.watchers.has(threadId)) {
198
+ return;
199
+ }
200
+ // The turn this watcher stood in for is gone: another harness woke it, and
201
+ // what the thread holds now, if anything, is a different turn or the same
202
+ // one stopped. Waking by thread id would resume that one.
203
+ if ((await this.host.parked(threadId)) !== turn.executionId) {
204
+ return;
205
+ }
206
+ if (await this.host.wake(threadId, turn.options)) {
207
+ return;
208
+ }
209
+ await pause(WAKE_RETRY_MS);
210
+ }
211
+ // Every try failed and the turn is still parked: go on watching it, or nothing would.
212
+ if (!this.closed && !this.watchers.has(threadId)) {
213
+ this.watch(threadId, turn);
214
+ }
215
+ }
216
+ }
217
+ //#endregion
@@ -0,0 +1,23 @@
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 type { DecisionItem, ExecutionScope, HeldResolution, SessionScope } from '@noetic-tools/types';
7
+ /** A decision, read: the stuck turn to settle, or the held call to answer. */
8
+ export type ReadDecision = {
9
+ readonly threadId: string;
10
+ readonly settle: 'continue' | 'restart' | 'abandon';
11
+ } | {
12
+ readonly scope: SessionScope | ExecutionScope;
13
+ readonly answer: HeldResolution & {
14
+ readonly callId: string;
15
+ readonly argsHash?: string;
16
+ };
17
+ };
18
+ /**
19
+ * @throws NoeticError `decision_refused` when the decision carries both an action
20
+ * and an output, or an action of the wrong kind for a decision with, or without,
21
+ * a `callId`; `hold_refused` when its `output` is not a JSON value.
22
+ */
23
+ export declare function readDecision(threadId: string, decision: DecisionItem): ReadDecision;