@noetic-tools/core 5.21.0 → 5.22.0-next.2

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 (101) hide show
  1. package/dist/adapters/openrouter.d.ts +6 -1
  2. package/dist/adapters/openrouter.js +10 -0
  3. package/dist/builders/decide-builders.d.ts +7 -0
  4. package/dist/builders/tool-builder.d.ts +25 -1
  5. package/dist/builders/tool-builder.js +25 -1
  6. package/dist/builders/workflow-control-nodes.js +1 -0
  7. package/dist/builders/workflow-hydrator.d.ts +19 -0
  8. package/dist/builders/workflow-hydrator.js +19 -0
  9. package/dist/builders/workflow-step.js +7 -1
  10. package/dist/connections/cron-schedule.js +12 -3
  11. package/dist/connections/durability.d.ts +1 -2
  12. package/dist/connections/durability.js +1 -4
  13. package/dist/connections/gates.js +6 -2
  14. package/dist/connections/harness-wiring.d.ts +5 -0
  15. package/dist/connections/harness-wiring.js +76 -10
  16. package/dist/connections/in-memory-connection.d.ts +4 -0
  17. package/dist/connections/in-memory-connection.js +10 -0
  18. package/dist/connections/model-tools.js +5 -1
  19. package/dist/connections/registry.d.ts +6 -2
  20. package/dist/connections/registry.js +10 -0
  21. package/dist/connections/sources.js +261 -20
  22. package/dist/connections/triggers.d.ts +62 -2
  23. package/dist/connections/triggers.js +375 -35
  24. package/dist/harness/agent-harness.d.ts +317 -4
  25. package/dist/harness/agent-harness.js +1264 -96
  26. package/dist/harness/connection-gate.d.ts +3 -0
  27. package/dist/harness/connection-gate.js +4 -0
  28. package/dist/harness/decide-call.d.ts +15 -0
  29. package/dist/harness/decide-call.js +57 -7
  30. package/dist/harness/deps/runtime.d.ts +3 -0
  31. package/dist/harness/deps/runtime.js +2 -0
  32. package/dist/harness/flow-version.d.ts +13 -0
  33. package/dist/harness/flow-version.js +66 -0
  34. package/dist/harness/harness-options.d.ts +91 -0
  35. package/dist/harness/llm-client.d.ts +2 -0
  36. package/dist/harness/llm-client.js +9 -5
  37. package/dist/harness/model-call.js +8 -0
  38. package/dist/harness/model-rounds.d.ts +30 -0
  39. package/dist/harness/model-rounds.js +146 -1
  40. package/dist/harness/model-tool-round.d.ts +3 -0
  41. package/dist/harness/model-tool-round.js +249 -22
  42. package/dist/harness/park-watchers.d.ts +93 -0
  43. package/dist/harness/park-watchers.js +217 -0
  44. package/dist/harness/read-decision.d.ts +23 -0
  45. package/dist/harness/read-decision.js +100 -0
  46. package/dist/harness/spend.js +4 -0
  47. package/dist/harness/steer-inbox.js +3 -1
  48. package/dist/harness/thread-record.d.ts +77 -1
  49. package/dist/harness/thread-record.js +272 -13
  50. package/dist/index.d.ts +22 -8
  51. package/dist/index.js +12 -2
  52. package/dist/interpreter/acp-resume.d.ts +77 -0
  53. package/dist/interpreter/acp-resume.js +164 -0
  54. package/dist/interpreter/acp-tools.d.ts +11 -0
  55. package/dist/interpreter/acp-tools.js +94 -7
  56. package/dist/interpreter/connection-steps.d.ts +24 -1
  57. package/dist/interpreter/connection-steps.js +77 -2
  58. package/dist/interpreter/execute-acp-agent.js +111 -15
  59. package/dist/interpreter/execute-action.js +7 -0
  60. package/dist/interpreter/execute-call.js +30 -4
  61. package/dist/interpreter/execute-control.js +21 -0
  62. package/dist/interpreter/execute-decide.js +5 -0
  63. package/dist/interpreter/execute-invoke-tool.js +149 -5
  64. package/dist/interpreter/execute-wait.js +67 -9
  65. package/dist/interpreter/execute.js +4 -0
  66. package/dist/interpreter/turn-ending.d.ts +15 -0
  67. package/dist/interpreter/turn-ending.js +46 -0
  68. package/dist/portable/builders.d.ts +1 -1
  69. package/dist/portable/builders.js +1 -1
  70. package/dist/portable/runtime.d.ts +4 -0
  71. package/dist/portable/runtime.js +2 -0
  72. package/dist/runtime/durable/parking.d.ts +61 -0
  73. package/dist/runtime/durable/parking.js +137 -0
  74. package/dist/runtime/durable/session-store.d.ts +38 -0
  75. package/dist/runtime/durable/session-store.js +79 -1
  76. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  77. package/dist/runtime/durable/step-ledger.js +352 -15
  78. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  79. package/dist/runtime/durable/turn-lease.js +307 -0
  80. package/dist/runtime/event-broadcaster.d.ts +9 -1
  81. package/dist/runtime/event-broadcaster.js +16 -1
  82. package/dist/runtime/held-calls.d.ts +192 -0
  83. package/dist/runtime/held-calls.js +496 -0
  84. package/dist/runtime/in-memory-storage.d.ts +10 -1
  85. package/dist/runtime/in-memory-storage.js +20 -2
  86. package/dist/runtime/message-queue.d.ts +2 -0
  87. package/dist/runtime/message-queue.js +8 -0
  88. package/dist/runtime/output-store.d.ts +88 -0
  89. package/dist/runtime/output-store.js +241 -0
  90. package/dist/runtime/session-runner.d.ts +18 -2
  91. package/dist/runtime/session-runner.js +88 -3
  92. package/dist/runtime/session-streams.d.ts +28 -7
  93. package/dist/runtime/session-streams.js +112 -67
  94. package/dist/runtime/tool-approval.d.ts +46 -6
  95. package/dist/runtime/tool-approval.js +160 -38
  96. package/dist/runtime/tool-call.d.ts +34 -2
  97. package/dist/runtime/tool-call.js +182 -13
  98. package/dist/runtime/tool-context.d.ts +15 -1
  99. package/dist/runtime/tool-context.js +38 -2
  100. package/package.json +3 -3
  101. package/schema/noetic-workflow.schema.json +27 -0
@@ -1,4 +1,4 @@
1
- import type { Item, LLMResponse, Tool } from '@noetic-tools/types';
1
+ import type { Item, LLMResponse, Tool, ToolModelOutput } from '@noetic-tools/types';
2
2
  import type * as OpenRouterAgent from '@openrouter/agent';
3
3
  import type { EmbedFn } from '../types/embed.js';
4
4
  type ProviderOutputItem = OpenRouterAgent.OpenResponsesResult['output'][number];
@@ -9,6 +9,11 @@ export type SdkTool = OpenRouterAgent.Tool;
9
9
  export interface ConvertToolsParams {
10
10
  tools: ReadonlyArray<Tool>;
11
11
  }
12
+ /**
13
+ * @internal What a `function_call_output` carries for a tool's `toModelOutput`
14
+ * value: text as it is, content parts in the provider's shape.
15
+ */
16
+ export declare function toolModelOutputToProvider(output: ToolModelOutput): OpenRouterAgent.FunctionCallOutputItem['output'];
12
17
  /** @internal Extracts system messages from items and returns them as a single instructions string. */
13
18
  export declare function extractSystemInstruction(items: ReadonlyArray<Item>): {
14
19
  instructions: string | undefined;
@@ -57,6 +57,16 @@ function contentPartsToProviderContent(parts) {
57
57
  }
58
58
  return frameworkCast(parts).map(inputContentPartToProvider);
59
59
  }
60
+ /**
61
+ * @internal What a `function_call_output` carries for a tool's `toModelOutput`
62
+ * value: text as it is, content parts in the provider's shape.
63
+ */
64
+ export function toolModelOutputToProvider(output) {
65
+ if (typeof output === 'string') {
66
+ return output;
67
+ }
68
+ return frameworkCast(output.map(inputContentPartToProvider));
69
+ }
60
70
  //#endregion
61
71
  //#region Item → OpenRouter Input Conversion
62
72
  /** @internal Extracts system messages from items and returns them as a single instructions string. */
@@ -18,6 +18,13 @@ export interface StepDecideOpts<TContext, Q extends DecideQuestions, I = unknown
18
18
  projection?: ProjectionPolicy;
19
19
  /** Runs averaged on the estimated path. Ignored on the native path. Default 1. */
20
20
  samples?: number;
21
+ /**
22
+ * Extra HTTP headers for the native request: how a host sets a provider's
23
+ * per-request option, e.g. `{ 'TypeSafe-Danger-Zone-Long-Context': 'true' }`
24
+ * for TypeSafe's long-context limits. Passed through unread and ignored on the
25
+ * estimated path. A step may be serialized, so keep credentials out of them.
26
+ */
27
+ headers?: Readonly<Record<string, string>>;
21
28
  emit?: boolean | ((eventType: string, data: Record<string, unknown>) => boolean);
22
29
  }
23
30
  /** An empty question map is a type error, not just a build-time one. */
@@ -1,4 +1,4 @@
1
- import type { FunctionCallItem, FunctionCallOutputItem, InferSchemaOutput, InputSchemaConfig, Item, ItemSchemaExtensions, StandardSchemaV1, Tool, ToolAcpDeclaration, ToolContextDeclaration, ToolExecutionContext, ToolResultExtensionItem, ToolUiDeclaration } from '@noetic-tools/types';
1
+ import type { FunctionCallItem, FunctionCallOutputItem, InferSchemaOutput, InputSchemaConfig, Item, ItemSchemaExtensions, StandardSchemaV1, Tool, ToolAcpDeclaration, ToolContextDeclaration, ToolExecutionContext, ToolModelOutput, ToolResultExtensionItem, ToolUiDeclaration } from '@noetic-tools/types';
2
2
  type ToolConfig<I extends StandardSchemaV1, O extends StandardSchemaV1> = {
3
3
  name: string;
4
4
  description: string;
@@ -14,7 +14,11 @@ type ToolConfig<I extends StandardSchemaV1, O extends StandardSchemaV1> = {
14
14
  error?: boolean;
15
15
  }) => Item | ToolResultExtensionItem;
16
16
  execute: (args: InferSchemaOutput<I>, toolCtx: ToolExecutionContext) => Promise<InferSchemaOutput<O>>;
17
+ /** See `Tool.toModelOutput`: what the model is given as the result, e.g. an image. */
18
+ toModelOutput?: (result: InferSchemaOutput<O>, args: InferSchemaOutput<I>) => ToolModelOutput;
17
19
  needsApproval?: boolean;
20
+ /** See `Tool.durable`: `true` holds an interrupted call for a person, `false` records nothing. */
21
+ durable?: boolean;
18
22
  /** Optional context declaration — the runtime generates a ContextLayer from this via toolCalls(). */
19
23
  context?: ToolContextDeclaration;
20
24
  /** Optional UI declaration — the runtime emits the rendered fragments at call/progress/result points. */
@@ -38,7 +42,11 @@ type GeneratorToolConfig<I extends StandardSchemaV1, E extends StandardSchemaV1,
38
42
  error?: boolean;
39
43
  }) => Item | ToolResultExtensionItem;
40
44
  execute: (args: InferSchemaOutput<I>, toolCtx: ToolExecutionContext) => AsyncGenerator<InferSchemaOutput<E>, InferSchemaOutput<O>>;
45
+ /** See `Tool.toModelOutput`: what the model is given as the result, e.g. an image. */
46
+ toModelOutput?: (result: InferSchemaOutput<O>, args: InferSchemaOutput<I>) => ToolModelOutput;
41
47
  needsApproval?: boolean;
48
+ /** See `Tool.durable`: `true` holds an interrupted call for a person, `false` records nothing. */
49
+ durable?: boolean;
42
50
  /** Optional context declaration — the runtime generates a ContextLayer from this via toolCalls(). */
43
51
  context?: ToolContextDeclaration;
44
52
  /** Optional UI declaration — the runtime emits the rendered fragments at call/progress/result points. */
@@ -61,4 +69,20 @@ export declare function tool<I extends StandardSchemaV1, O extends StandardSchem
61
69
  * @public
62
70
  */
63
71
  export declare function toolWithGenerator<I extends StandardSchemaV1, E extends StandardSchemaV1, O extends StandardSchemaV1>(config: GeneratorToolConfig<I, E, O>): Tool<I, O>;
72
+ /**
73
+ * @public
74
+ * What a tool returns to leave its result open for a person
75
+ * (spec 08 § Held tool calls). The tool has done its part — posted the question,
76
+ * opened the ticket — and the answer becomes the call's result when
77
+ * a decision passed to `harness.execute()` gives one. The tool body does not run again.
78
+ *
79
+ * @param options - `request` is passed to whoever answers, as `HeldCall.request`.
80
+ * `dueAt` (epoch ms) ends the hold; `onDue` says how: `deny` (the default)
81
+ * fails the call, `keep` leaves it held.
82
+ */
83
+ export declare function hold<O = never>(options?: {
84
+ request?: unknown;
85
+ dueAt?: number;
86
+ onDue?: 'deny' | 'keep';
87
+ }): O;
64
88
  export {};
@@ -1,4 +1,4 @@
1
- import { NoeticConfigError } from '@noetic-tools/types';
1
+ import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
2
2
  //#endregion
3
3
  //#region Helpers
4
4
  function validateToolConfig(name, execute) {
@@ -37,8 +37,10 @@ export function tool(config) {
37
37
  inputJsonSchema: config.inputJsonSchema,
38
38
  itemSchemas: config.itemSchemas,
39
39
  decorateResultItem: config.decorateResultItem,
40
+ toModelOutput: config.toModelOutput,
40
41
  execute: config.execute,
41
42
  needsApproval: config.needsApproval,
43
+ durable: config.durable,
42
44
  context: config.context,
43
45
  ui: config.ui,
44
46
  acp: config.acp,
@@ -60,11 +62,33 @@ export function toolWithGenerator(config) {
60
62
  inputJsonSchema: config.inputJsonSchema,
61
63
  itemSchemas: config.itemSchemas,
62
64
  decorateResultItem: config.decorateResultItem,
65
+ toModelOutput: config.toModelOutput,
63
66
  execute: config.execute,
64
67
  needsApproval: config.needsApproval,
68
+ durable: config.durable,
65
69
  context: config.context,
66
70
  ui: config.ui,
67
71
  acp: config.acp,
68
72
  };
69
73
  }
70
74
  //#endregion
75
+ /**
76
+ * @public
77
+ * What a tool returns to leave its result open for a person
78
+ * (spec 08 § Held tool calls). The tool has done its part — posted the question,
79
+ * opened the ticket — and the answer becomes the call's result when
80
+ * a decision passed to `harness.execute()` gives one. The tool body does not run again.
81
+ *
82
+ * @param options - `request` is passed to whoever answers, as `HeldCall.request`.
83
+ * `dueAt` (epoch ms) ends the hold; `onDue` says how: `deny` (the default)
84
+ * fails the call, `keep` leaves it held.
85
+ */
86
+ export function hold(options) {
87
+ const held = {
88
+ kind: 'noetic/tool-hold',
89
+ ...options,
90
+ };
91
+ // Typed as the tool's own output so `return hold()` fits any `execute`. The
92
+ // harness takes it out before anything reads it as a result.
93
+ return frameworkCast(held);
94
+ }
@@ -166,6 +166,7 @@ function decideFromNode(node) {
166
166
  questions: node.questions,
167
167
  view: node.view,
168
168
  samples: node.samples,
169
+ headers: node.headers,
169
170
  });
170
171
  }
171
172
  export function hydrateRouteSwitchNode(node, ctx) {
@@ -151,3 +151,22 @@ export declare function hydrateNode(node: WorkflowNode, ctx: HydrationContext):
151
151
  * @throws `NoeticConfigError` with code `CONNECTION_UNKNOWN` when a node uses a connection the document's `connections` do not declare, or `CONNECTION_INVALID` when a node's connection is neither named nor implied, or a source entry is used beyond its events.
152
152
  */
153
153
  export declare function hydrateWorkflow(doc: WorkflowDocument, ctx: HydrationContext, customItems?: CustomItemMap): Step<ContextData, string, string>;
154
+ /**
155
+ * @internal
156
+ * Where a step's flow comes from: the document it runs, or the name it looks one
157
+ * up by, and the named workflows its subflow refs resolve against.
158
+ */
159
+ export interface FlowSource {
160
+ readonly document?: WorkflowDocument;
161
+ readonly ref?: string;
162
+ readonly workflows?: ReadonlyMap<string, WorkflowDocument>;
163
+ }
164
+ /** @internal Note that `step` runs the flow `source` describes. */
165
+ export declare function noteFlowSource(step: object, source: FlowSource): void;
166
+ /**
167
+ * @internal
168
+ * The flow `step` runs, when it runs a JSON workflow: a hydrated root, or a
169
+ * `workflow()` step. A harness given such a step and no `version` names its flow
170
+ * by a hash of it (spec 23 § Versions).
171
+ */
172
+ export declare function flowSourceOf(step: object): FlowSource | undefined;
@@ -267,6 +267,25 @@ export function hydrateWorkflow(doc, ctx, customItems) {
267
267
  ...root.customItems,
268
268
  };
269
269
  recordDocumentConnections(frameworkCast(root), doc, ctx.mcp);
270
+ noteFlowSource(root, {
271
+ document: doc,
272
+ workflows: ctx.workflows,
273
+ });
270
274
  return root;
271
275
  }
276
+ /** The source of each step that runs a JSON workflow. */
277
+ const flowSources = new WeakMap();
278
+ /** @internal Note that `step` runs the flow `source` describes. */
279
+ export function noteFlowSource(step, source) {
280
+ flowSources.set(step, source);
281
+ }
282
+ /**
283
+ * @internal
284
+ * The flow `step` runs, when it runs a JSON workflow: a hydrated root, or a
285
+ * `workflow()` step. A harness given such a step and no `version` names its flow
286
+ * by a hash of it (spec 23 § Versions).
287
+ */
288
+ export function flowSourceOf(step) {
289
+ return flowSources.get(step);
290
+ }
272
291
  //#endregion
@@ -10,7 +10,7 @@ import { outputText } from './output-text.js';
10
10
  import { spawn } from './spawn-builder.js';
11
11
  import { runCode } from './step-builders.js';
12
12
  import { everyDocumentItem } from './workflow-custom-items.js';
13
- import { hydrateWorkflow } from './workflow-hydrator.js';
13
+ import { hydrateWorkflow, noteFlowSource } from './workflow-hydrator.js';
14
14
  //#endregion
15
15
  //#region Builder
16
16
  /**
@@ -74,6 +74,12 @@ export function workflow(opts) {
74
74
  return outputText(await executeStep(cached.step, input, ctx));
75
75
  },
76
76
  });
77
+ // The step hydrates when it first runs. What it will run is known now.
78
+ noteFlowSource(step, {
79
+ document: opts.document === undefined ? undefined : frameworkCast(opts.document),
80
+ ref: opts.ref,
81
+ workflows: opts.workflows,
82
+ });
77
83
  return frameworkCast(step);
78
84
  }
79
85
  //#endregion
@@ -142,13 +142,22 @@ function dayMatches(schedule, parts) {
142
142
  }
143
143
  return dayOk || weekdayOk;
144
144
  }
145
- /** Minutes to skip from a non-matching time: to the next hour or the next day where possible. */
145
+ /** More minutes than any clock change takes out of a day. */
146
+ const CLOCK_CHANGE_MARGIN = 180;
147
+ /**
148
+ * Minutes to skip from a non-matching time: to the next hour, or towards the next
149
+ * day. A day the clocks go forward in is shorter than 24 hours, so a skip of "the
150
+ * rest of today" would land past the next midnight and miss a run at it. The skip
151
+ * stops short of midnight by more than any clock change, and goes on by the hour.
152
+ */
146
153
  function skipMinutes(schedule, parts) {
154
+ const toNextHour = 60 - parts.minute;
147
155
  if (!schedule.months.has(parts.month) || !dayMatches(schedule, parts)) {
148
- return (23 - parts.hour) * 60 + (60 - parts.minute);
156
+ const toMidnight = (23 - parts.hour) * 60 + toNextHour;
157
+ return toMidnight > CLOCK_CHANGE_MARGIN ? toMidnight - CLOCK_CHANGE_MARGIN : toNextHour;
149
158
  }
150
159
  if (!schedule.hours.has(parts.hour)) {
151
- return 60 - parts.minute;
160
+ return toNextHour;
152
161
  }
153
162
  return 1;
154
163
  }
@@ -56,8 +56,7 @@ export declare function stepPathOf(ctx: Context): string | undefined;
56
56
  export declare function orderedCallId(owner: object, ctx: Context, stepId?: string): string;
57
57
  /** The idempotency key of a step's call: the run and the step's ledger key. */
58
58
  export declare function stepIdempotencyKey(executionId: string, ledgerKey: string): string;
59
- /** The idempotency key of a model tool call: the turn's execution and the tool call id. */
60
- export declare function toolIdempotencyKey(executionId: string, toolCallId: string): string;
59
+ export { toolIdempotencyKey } from '../runtime/tool-context.js';
61
60
  /** Whether `current` is the same thing `recorded` described (an epoch change alone keeps it). */
62
61
  export declare function sameInstance(recorded: ConnectionIdentity, current: ConnectionIdentity): boolean;
63
62
  /**
@@ -56,10 +56,7 @@ export function orderedCallId(owner, ctx, stepId) {
56
56
  export function stepIdempotencyKey(executionId, ledgerKey) {
57
57
  return `${executionId}:${ledgerKey}`;
58
58
  }
59
- /** The idempotency key of a model tool call: the turn's execution and the tool call id. */
60
- export function toolIdempotencyKey(executionId, toolCallId) {
61
- return `${executionId}:tool:${toolCallId}`;
62
- }
59
+ export { toolIdempotencyKey } from '../runtime/tool-context.js';
63
60
  /** Whether `current` is the same thing `recorded` described (an epoch change alone keeps it). */
64
61
  export function sameInstance(recorded, current) {
65
62
  return recorded.surface === current.surface && recorded.instance === current.instance;
@@ -17,6 +17,7 @@
17
17
  * operations are waited on, with progress reported as `connection_task`.
18
18
  */
19
19
  import { SteeringAction } from '@noetic-tools/types';
20
+ import { PARK_REASON } from '../runtime/durable/parking.js';
20
21
  import { attachBlobs, checkBlobs } from './blobs.js';
21
22
  import { deniedError, failedError, inputRequiredError } from './errors.js';
22
23
  import { validateJsonSchema } from './json-schema.js';
@@ -102,7 +103,9 @@ async function awaitTask(gc, request) {
102
103
  gc.onTask?.(request.op, status, request.stepId);
103
104
  request.onTask?.(status);
104
105
  if (status.state === 'input_required') {
105
- void answer(status);
106
+ // A turn that parks while the question is open aborts the wait for its
107
+ // answer; the task itself is what reports that, below.
108
+ void answer(status).catch(() => undefined);
106
109
  }
107
110
  },
108
111
  });
@@ -112,7 +115,8 @@ async function awaitTask(gc, request) {
112
115
  await gc.connection.tasks.cancel(request.taskId).catch(() => undefined);
113
116
  throw inputRequiredError(gc.name, unanswered.request);
114
117
  }
115
- if (request.signal.aborted) {
118
+ // A parked turn comes back for its task (spec 23 § Parked turns): leave it running.
119
+ if (request.signal.aborted && request.ctx?.abortReason !== PARK_REASON) {
116
120
  await gc.connection.tasks.cancel(request.taskId).catch(() => undefined);
117
121
  }
118
122
  throw e;
@@ -10,6 +10,7 @@
10
10
  import type { ArtifactStore, ConnectionEntries, ConnectionTrigger, Context, ContextLayer, ExecuteInput, ExecuteOptions, SecretResolver, SessionScope, SteeringDecision, StorageAdapter, Tool, ToolApprover } from '@noetic-tools/types';
11
11
  import type { EventBroadcaster } from '../runtime/event-broadcaster.js';
12
12
  import type { ConnectionRuntime } from './registry.js';
13
+ import { TriggerRunner } from './triggers.js';
13
14
  /** The harness surface the wiring calls back into. */
14
15
  export interface WiredHarness {
15
16
  readonly config: {
@@ -25,6 +26,8 @@ export interface HarnessConnectionsOptions {
25
26
  readonly harness: WiredHarness;
26
27
  readonly connections?: ConnectionEntries;
27
28
  readonly triggers?: ReadonlyArray<ConnectionTrigger>;
29
+ /** A scheduled trigger moved on (`TriggerRunnerOptions.onSchedule`). */
30
+ readonly onSchedule?: () => Promise<void>;
28
31
  readonly storage: StorageAdapter;
29
32
  readonly artifacts: ArtifactStore;
30
33
  readonly secrets?: SecretResolver;
@@ -42,6 +45,8 @@ export interface HarnessConnections {
42
45
  close(): Promise<void>;
43
46
  /** A turn's connection tools: the harness's, and the ones attached under `rootId`. */
44
47
  tools(rootId?: string): Tool[];
48
+ /** The harness's triggers: its own, and those added while it runs. */
49
+ readonly triggers: TriggerRunner;
45
50
  }
46
51
  /**
47
52
  * Builds a harness's connections from its options.
@@ -9,6 +9,9 @@
9
9
  */
10
10
  import { CONNECTION_EVENT_ITEM_TYPE, createMessage, frameworkCast, SteeringAction, } from '@noetic-tools/types';
11
11
  import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
12
+ import { ContextImpl } from '../runtime/context-impl.js';
13
+ import { heldArgsHash, holdAndWait } from '../runtime/held-calls.js';
14
+ import { askApproval, awaitApproval } from '../runtime/tool-approval.js';
12
15
  import { buildConnectionTools } from './model-tools.js';
13
16
  import { createConnectionRuntime } from './registry.js';
14
17
  import { runEvery } from './settle.js';
@@ -33,7 +36,61 @@ function gateHooks(harness) {
33
36
  }
34
37
  return harness.beforeToolCall(layers, request.toolName, request.args, request.ctx, request.callId);
35
38
  },
39
+ // A long operation asked a question (MCP Tasks `input_required`). It is held for
40
+ // a person like a tool's open result: the answer goes back to the operation.
41
+ async answerInput(request) {
42
+ const question = request.status.request;
43
+ if (!request.ctx || !question) {
44
+ return undefined;
45
+ }
46
+ const args = {
47
+ taskId: request.status.taskId,
48
+ question: question.message,
49
+ };
50
+ const answer = await holdAndWait({
51
+ harness,
52
+ ctx: request.ctx,
53
+ record: {
54
+ callId: `${holdIdOf(request.ctx, request.callId ?? request.op)}:input:${question.id}`,
55
+ name: request.toolName,
56
+ args,
57
+ argsHash: heldArgsHash(request.toolName, args),
58
+ reason: 'result',
59
+ request: question,
60
+ },
61
+ });
62
+ return answer.resolution?.hasOutput
63
+ ? {
64
+ answer: answer.resolution.output,
65
+ }
66
+ : undefined;
67
+ },
36
68
  async approve(request) {
69
+ // A model's tool call can be held for a person: its tool pipeline writes the
70
+ // record when this throws, and answers from it when the call is made again.
71
+ if (request.ctx && request.caller === 'model' && request.callId !== undefined) {
72
+ const approval = await askApproval({
73
+ harness,
74
+ toolName: request.toolName,
75
+ toolArgs: request.args,
76
+ callId: request.callId,
77
+ ctx: request.ctx,
78
+ matched: true,
79
+ });
80
+ return approval.decision;
81
+ }
82
+ // A step's call has no round to come back to, so it waits where it is until a
83
+ // person answers, and the turn may park meanwhile.
84
+ if (request.ctx && request.caller === 'step' && request.callId !== undefined) {
85
+ const approval = await awaitApproval({
86
+ harness,
87
+ toolName: request.toolName,
88
+ toolArgs: request.args,
89
+ callId: holdIdOf(request.ctx, request.callId),
90
+ ctx: request.ctx,
91
+ });
92
+ return approval.decision;
93
+ }
37
94
  const approver = harness.config.approveToolCall;
38
95
  if (!approver) {
39
96
  return deny(`'${request.op}' on connection '${request.connection}' needs approval, but the harness has no approveToolCall`);
@@ -55,6 +112,13 @@ function gateHooks(harness) {
55
112
  },
56
113
  };
57
114
  }
115
+ /**
116
+ * The id a step's held call is kept under: its dispatch path, since a step id
117
+ * repeats across loop iterations and a path does not.
118
+ */
119
+ function holdIdOf(ctx, fallback) {
120
+ return (ctx instanceof ContextImpl ? ctx.currentDispatch()?.path : undefined) ?? fallback;
121
+ }
58
122
  function broadcast(options, event) {
59
123
  const data = frameworkCast(event.data);
60
124
  const own = event.ctx ? getBroadcaster(event.ctx) : undefined;
@@ -111,14 +175,15 @@ export function createHarnessConnections(options) {
111
175
  });
112
176
  const triggers = options.triggers ?? [];
113
177
  validateTriggers(triggers, registry.names());
114
- const runner = triggers.length > 0
115
- ? new TriggerRunner({
116
- runtime: registry,
117
- triggers,
118
- storage: options.storage,
119
- deliver: (delivery) => deliverTurn(options.harness, delivery),
120
- })
121
- : undefined;
178
+ // Always built: a trigger can be added while the harness runs, and ones added on
179
+ // an earlier run are read back from storage at start.
180
+ const runner = new TriggerRunner({
181
+ runtime: registry,
182
+ triggers,
183
+ storage: options.storage,
184
+ onSchedule: options.onSchedule,
185
+ deliver: (delivery) => deliverTurn(options.harness, delivery),
186
+ });
122
187
  const views = connectionViewLayers(registry);
123
188
  let starting;
124
189
  return {
@@ -127,17 +192,18 @@ export function createHarnessConnections(options) {
127
192
  start() {
128
193
  starting ??= (async () => {
129
194
  await registry.start();
130
- await runner?.start();
195
+ await runner.start();
131
196
  })();
132
197
  return starting;
133
198
  },
134
199
  async close() {
135
200
  await runEvery([
136
- () => runner?.close(),
201
+ () => runner.close(),
137
202
  () => registry.close(),
138
203
  ]);
139
204
  },
140
205
  tools: (rootId) => buildConnectionTools(registry, rootId),
206
+ triggers: runner,
141
207
  };
142
208
  }
143
209
  //#endregion
@@ -124,6 +124,10 @@ export interface InMemoryConnectionProvider extends ConnectionProvider {
124
124
  export interface Listener {
125
125
  readonly event: string;
126
126
  readonly args: Readonly<Record<string, unknown>>;
127
+ /** The listener writes events to durable storage and says when (see `ListenRequest.stores`). */
128
+ readonly stores: boolean;
129
+ /** Called when the listener ends, by whoever is waiting on something it had not finished. */
130
+ readonly onEnd: Set<() => void>;
127
131
  push(message: EventStreamMessage): void;
128
132
  end(): void;
129
133
  }
@@ -103,8 +103,16 @@ export function createListenerStream(listeners, request, ready) {
103
103
  const waiters = [];
104
104
  let ended = false;
105
105
  const finish = () => {
106
+ if (ended) {
107
+ return;
108
+ }
106
109
  ended = true;
107
110
  listeners.delete(listener);
111
+ for (const told of [
112
+ ...listener.onEnd,
113
+ ]) {
114
+ told();
115
+ }
108
116
  for (const waiter of waiters.splice(0)) {
109
117
  waiter({
110
118
  value: undefined,
@@ -115,6 +123,8 @@ export function createListenerStream(listeners, request, ready) {
115
123
  const listener = {
116
124
  event: request.event,
117
125
  args: request.arguments ?? {},
126
+ stores: request.stores === true,
127
+ onEnd: new Set(),
118
128
  push(message) {
119
129
  if (ended) {
120
130
  return;
@@ -24,6 +24,8 @@
24
24
  */
25
25
  import { frameworkCast, isConnectionEntry } from '@noetic-tools/types';
26
26
  import { z } from 'zod';
27
+ import { rootIdOf } from '../runtime/context-impl.js';
28
+ import { keyScopeOf } from '../runtime/tool-context.js';
27
29
  import { harnessInternal } from '../util/harness-internals.js';
28
30
  import { orderedCallId, toolIdempotencyKey } from './durability.js';
29
31
  import { entryName } from './entries.js';
@@ -102,7 +104,9 @@ async function callThrough(runtime, request) {
102
104
  const output = await resolved.call(request.op, request.args, {
103
105
  signal: scope.signal,
104
106
  caller: 'model',
105
- idempotencyKey: toolIdempotencyKey(ctx.id, toolCallId),
107
+ // With where in the run the model made the call, when the caller knew: that
108
+ // tells apart two calls a provider gave one id.
109
+ idempotencyKey: toolIdempotencyKey(rootIdOf(ctx), toolCallId, keyScopeOf(request.toolCtx)),
106
110
  toolCallId,
107
111
  ctx,
108
112
  });
@@ -17,7 +17,7 @@
17
17
  * `detach(id)` releases them when it ends. They are looked up by name from
18
18
  * any context under the turn's root, after the harness's own.
19
19
  */
20
- import type { AnyProfile, ArtifactStore, Connection, ConnectionChangedEventData, ConnectionConfig, ConnectionEntries, ConnectionEventEventData, ConnectionFrameworkEvent, ConnectionIdentity, ConnectionRequirement, ConnectionTaskEventData, Context, EventStream, SecretResolver, StorageAdapter, StreamChangedEventData } from '@noetic-tools/types';
20
+ import type { AnyProfile, ArtifactStore, Connection, ConnectionChangedEventData, ConnectionConfig, ConnectionEntries, ConnectionEventEventData, ConnectionFrameworkEvent, ConnectionIdentity, ConnectionRequirement, ConnectionTaskEventData, ConnectionTaskStatus, Context, EventStream, SecretResolver, StorageAdapter, StreamChangedEventData, TriggerGaveUpEventData } from '@noetic-tools/types';
21
21
  import type { AttachedEntry, AttachedScope } from '../types/connection-entry.js';
22
22
  import type { ResumeDecision } from './durability.js';
23
23
  import type { GateHooks } from './gates.js';
@@ -25,7 +25,7 @@ import type { ConnectionRegistry, ResolvedConnection, ResolveRequest } from './r
25
25
  /** A framework event the registry emits (`<agent>:<type>` on `getFullStream()`). */
26
26
  export interface ConnectionFrameworkEventRecord {
27
27
  readonly type: ConnectionFrameworkEvent;
28
- readonly data: ConnectionChangedEventData | ConnectionEventEventData | ConnectionTaskEventData | StreamChangedEventData;
28
+ readonly data: ConnectionChangedEventData | ConnectionEventEventData | ConnectionTaskEventData | StreamChangedEventData | TriggerGaveUpEventData;
29
29
  /** The context it concerns, when there is one. */
30
30
  readonly ctx?: Context;
31
31
  }
@@ -128,12 +128,16 @@ export interface ConnectionRuntime extends ConnectionRegistry {
128
128
  readonly recorded: ConnectionIdentity;
129
129
  readonly signal: AbortSignal;
130
130
  }): Promise<ResumeDecision>;
131
+ /** The state of a long operation on a harness connection, without waiting on it. */
132
+ taskStatus(name: string, taskId: string, signal: AbortSignal): Promise<ConnectionTaskStatus>;
131
133
  /** Unsealed, un-buffered events for a trigger; the caller seals them per thread. */
132
134
  listenRaw(name: string, request: {
133
135
  readonly event: string;
134
136
  readonly arguments?: Readonly<Record<string, unknown>>;
135
137
  readonly cursor?: string | null;
136
138
  readonly signal: AbortSignal;
139
+ /** The caller stores each event durably and says when: see `ListenRequest.stores`. */
140
+ readonly stores?: boolean;
137
141
  }): Promise<EventStream>;
138
142
  /** Scrubs secrets from, seals refs in, and links blobs in a value for a thread. */
139
143
  admit(name: string, value: unknown, scope: {
@@ -438,6 +438,16 @@ class Runtime {
438
438
  h.connection.identity.instance === recorded.instance);
439
439
  return own?.connection ?? held[0]?.connection;
440
440
  }
441
+ async taskStatus(name, taskId, signal) {
442
+ const entry = this.entries.get(name);
443
+ if (!entry) {
444
+ throw unknownConnectionError(name, this.names());
445
+ }
446
+ await this.ensureConnected(entry);
447
+ return this.requireReady(entry).tasks.get(taskId, {
448
+ signal,
449
+ });
450
+ }
441
451
  async listenRaw(name, request) {
442
452
  const entry = this.entries.get(name);
443
453
  if (!entry) {