@noetic-tools/core 5.19.1 → 5.19.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 (146) hide show
  1. package/dist/adapters/openrouter.js +5 -0
  2. package/dist/builders/control-flow-builders.d.ts +15 -6
  3. package/dist/builders/control-flow-builders.js +8 -0
  4. package/dist/builders/decide-builders.d.ts +2 -5
  5. package/dist/builders/dynamic-workflow.d.ts +16 -1
  6. package/dist/builders/dynamic-workflow.js +222 -11
  7. package/dist/builders/every.d.ts +3 -3
  8. package/dist/builders/every.js +2 -1
  9. package/dist/builders/provide-builder.d.ts +3 -2
  10. package/dist/builders/provide-builder.js +2 -1
  11. package/dist/builders/sequence.d.ts +14 -0
  12. package/dist/builders/sequence.js +103 -0
  13. package/dist/builders/spawn-builder.d.ts +3 -2
  14. package/dist/builders/spawn-builder.js +3 -2
  15. package/dist/builders/step-builders.d.ts +80 -1
  16. package/dist/builders/step-builders.js +115 -1
  17. package/dist/builders/verify-builder.d.ts +79 -0
  18. package/dist/builders/verify-builder.js +69 -0
  19. package/dist/builders/workflow-child-nodes.d.ts +21 -0
  20. package/dist/builders/workflow-child-nodes.js +335 -0
  21. package/dist/builders/workflow-connection-nodes.d.ts +17 -0
  22. package/dist/builders/workflow-connection-nodes.js +160 -0
  23. package/dist/builders/workflow-connections.d.ts +90 -0
  24. package/dist/builders/workflow-connections.js +560 -0
  25. package/dist/builders/workflow-control-nodes.d.ts +13 -0
  26. package/dist/builders/workflow-control-nodes.js +213 -0
  27. package/dist/builders/workflow-hydrator.d.ts +44 -3
  28. package/dist/builders/workflow-hydrator.js +53 -495
  29. package/dist/builders/workflow-verify.d.ts +19 -0
  30. package/dist/builders/workflow-verify.js +194 -0
  31. package/dist/conditions/conditions.d.ts +7 -5
  32. package/dist/conditions/conditions.js +7 -4
  33. package/dist/connections/blobs.d.ts +33 -0
  34. package/dist/connections/blobs.js +77 -0
  35. package/dist/connections/cron-schedule.d.ts +32 -0
  36. package/dist/connections/cron-schedule.js +213 -0
  37. package/dist/connections/durability.d.ts +65 -0
  38. package/dist/connections/durability.js +54 -0
  39. package/dist/connections/errors.d.ts +30 -0
  40. package/dist/connections/errors.js +100 -0
  41. package/dist/connections/event-stream.d.ts +24 -0
  42. package/dist/connections/event-stream.js +176 -0
  43. package/dist/connections/gates.d.ts +94 -0
  44. package/dist/connections/gates.js +271 -0
  45. package/dist/connections/glob.d.ts +10 -0
  46. package/dist/connections/glob.js +46 -0
  47. package/dist/connections/handle.d.ts +22 -0
  48. package/dist/connections/handle.js +84 -0
  49. package/dist/connections/harness-wiring.d.ts +52 -0
  50. package/dist/connections/harness-wiring.js +143 -0
  51. package/dist/connections/in-memory-connection.d.ts +147 -0
  52. package/dist/connections/in-memory-connection.js +593 -0
  53. package/dist/connections/index.d.ts +34 -0
  54. package/dist/connections/index.js +23 -0
  55. package/dist/connections/json-schema.d.ts +28 -0
  56. package/dist/connections/json-schema.js +338 -0
  57. package/dist/connections/model-tools.d.ts +46 -0
  58. package/dist/connections/model-tools.js +466 -0
  59. package/dist/connections/negotiation.d.ts +30 -0
  60. package/dist/connections/negotiation.js +159 -0
  61. package/dist/connections/policy.d.ts +21 -0
  62. package/dist/connections/policy.js +34 -0
  63. package/dist/connections/pool.d.ts +111 -0
  64. package/dist/connections/pool.js +339 -0
  65. package/dist/connections/refs.d.ts +74 -0
  66. package/dist/connections/refs.js +316 -0
  67. package/dist/connections/registry-types.d.ts +141 -0
  68. package/dist/connections/registry-types.js +14 -0
  69. package/dist/connections/registry.d.ts +125 -0
  70. package/dist/connections/registry.js +775 -0
  71. package/dist/connections/secrets.d.ts +59 -0
  72. package/dist/connections/secrets.js +153 -0
  73. package/dist/connections/settle.d.ts +9 -0
  74. package/dist/connections/settle.js +26 -0
  75. package/dist/connections/sources.d.ts +27 -0
  76. package/dist/connections/sources.js +300 -0
  77. package/dist/connections/triggers.d.ts +78 -0
  78. package/dist/connections/triggers.js +310 -0
  79. package/dist/connections/values.d.ts +26 -0
  80. package/dist/connections/values.js +93 -0
  81. package/dist/connections/views.d.ts +31 -0
  82. package/dist/connections/views.js +176 -0
  83. package/dist/expression/check.js +80 -1
  84. package/dist/expression/jsonata.d.ts +14 -4
  85. package/dist/expression/jsonata.js +27 -9
  86. package/dist/expression/step-outputs.d.ts +25 -0
  87. package/dist/expression/step-outputs.js +78 -0
  88. package/dist/harness/agent-harness.d.ts +69 -166
  89. package/dist/harness/agent-harness.js +170 -262
  90. package/dist/harness/call-span-collector.d.ts +33 -0
  91. package/dist/harness/call-span-collector.js +83 -0
  92. package/dist/harness/connection-gate.d.ts +78 -0
  93. package/dist/harness/connection-gate.js +169 -0
  94. package/dist/harness/deps/interpreter.d.ts +1 -0
  95. package/dist/harness/deps/interpreter.js +1 -0
  96. package/dist/harness/deps/runtime.d.ts +1 -1
  97. package/dist/harness/deps/types.d.ts +1 -1
  98. package/dist/harness/harness-options.d.ts +153 -0
  99. package/dist/harness/harness-options.js +36 -0
  100. package/dist/harness/harness-tracing.d.ts +16 -0
  101. package/dist/harness/harness-tracing.js +35 -0
  102. package/dist/harness/llm-client.d.ts +71 -0
  103. package/dist/harness/llm-client.js +218 -0
  104. package/dist/harness/model-call.d.ts +2 -7
  105. package/dist/harness/model-call.js +21 -549
  106. package/dist/harness/model-request.d.ts +42 -0
  107. package/dist/harness/model-request.js +159 -0
  108. package/dist/harness/model-stream.d.ts +39 -0
  109. package/dist/harness/model-stream.js +131 -0
  110. package/dist/harness/model-tool-round.d.ts +37 -0
  111. package/dist/harness/model-tool-round.js +197 -0
  112. package/dist/harness/spend.d.ts +2 -0
  113. package/dist/harness/spend.js +5 -1
  114. package/dist/index.d.ts +31 -6
  115. package/dist/index.js +18 -1
  116. package/dist/interpreter/connection-steps.d.ts +194 -0
  117. package/dist/interpreter/connection-steps.js +537 -0
  118. package/dist/interpreter/execute-action.d.ts +2 -8
  119. package/dist/interpreter/execute-action.js +3 -178
  120. package/dist/interpreter/execute-call.d.ts +19 -0
  121. package/dist/interpreter/execute-call.js +99 -0
  122. package/dist/interpreter/execute-control.d.ts +6 -1
  123. package/dist/interpreter/execute-control.js +14 -0
  124. package/dist/interpreter/execute-invoke-tool.d.ts +11 -0
  125. package/dist/interpreter/execute-invoke-tool.js +183 -0
  126. package/dist/interpreter/execute-verify.d.ts +21 -0
  127. package/dist/interpreter/execute-verify.js +391 -0
  128. package/dist/interpreter/execute-wait.d.ts +21 -0
  129. package/dist/interpreter/execute-wait.js +233 -0
  130. package/dist/interpreter/execute.js +24 -133
  131. package/dist/interpreter/step-kind-dispatch.d.ts +24 -0
  132. package/dist/interpreter/step-kind-dispatch.js +157 -0
  133. package/dist/interpreter/step-walk.d.ts +2 -0
  134. package/dist/interpreter/step-walk.js +24 -0
  135. package/dist/interpreter/verify-host.d.ts +40 -0
  136. package/dist/interpreter/verify-host.js +245 -0
  137. package/dist/runtime/durable/step-ledger.d.ts +31 -1
  138. package/dist/runtime/durable/step-ledger.js +87 -1
  139. package/dist/runtime/in-memory-artifact-store.d.ts +24 -0
  140. package/dist/runtime/in-memory-artifact-store.js +240 -0
  141. package/dist/schemas/workflow.d.ts +2 -2
  142. package/dist/schemas/workflow.js +1 -1
  143. package/dist/util/harness-internals.d.ts +23 -0
  144. package/dist/util/harness-internals.js +35 -0
  145. package/package.json +3 -3
  146. package/schema/noetic-workflow.schema.json +1170 -92
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Secrets (spec 35 § Secrets). A secret is resolved through
3
+ * `environment.secrets` immediately before the call is sent, allowed only in
4
+ * fields a profile marks `sensitive`, and never by the model. Before any
5
+ * output, event, read or text is stored, traced or shown, every resolved value
6
+ * — and its URL-encoded and base64 forms — is replaced with `"<redacted>"`.
7
+ */
8
+ import type { JsonSchemaObject, Secret, SecretResolver } from '@noetic-tools/types';
9
+ import type { JsonPath } from './json-schema.js';
10
+ import type { ConnectionCaller } from './registry-types.js';
11
+ /** Where secrets are being checked or filled. */
12
+ export interface SecretSite {
13
+ readonly connection: string;
14
+ readonly op: string;
15
+ readonly caller: ConnectionCaller;
16
+ /** The operation's input schema; secrets are allowed only where it accepts `{ $secret }`. */
17
+ readonly inputSchema: JsonSchemaObject;
18
+ /** For documents: the only secrets (and the fields they fill) the call may send. */
19
+ readonly allowedSecrets?: ReadonlyArray<{
20
+ readonly name: string;
21
+ readonly field: string;
22
+ }>;
23
+ }
24
+ /** Remembers every resolved secret value and replaces it wherever it shows up. */
25
+ export declare class SecretScrubber {
26
+ private readonly forms;
27
+ private pattern;
28
+ /** Registers a resolved value: raw, URL-encoded and base64 (standard and URL-safe). */
29
+ add(value: string): void;
30
+ /** Whether any secret has been resolved yet. */
31
+ get active(): boolean;
32
+ /** `text` with every known secret form replaced by `"<redacted>"`. */
33
+ scrubText(text: string): string;
34
+ /** A copy of `value` with every string scrubbed. */
35
+ scrub<T>(value: T): T;
36
+ }
37
+ /** The secrets in `args`, with where each sits. */
38
+ export declare function findSecrets(args: unknown): ReadonlyArray<{
39
+ readonly value: Secret;
40
+ readonly path: JsonPath;
41
+ }>;
42
+ /**
43
+ * Refuses secrets the model sent, that sit outside a `sensitive` field, or —
44
+ * for a document — that its node does not write out.
45
+ *
46
+ * @throws NoeticErrorImpl `connection_secret_refused`.
47
+ */
48
+ export declare function checkSecrets(args: unknown, site: SecretSite): void;
49
+ /**
50
+ * Replaces each `{ $secret }` in `args` with its resolved value and registers
51
+ * the value with `scrubber`.
52
+ *
53
+ * @throws NoeticConfigError `CONNECTION_INVALID` when secrets are used but no resolver is configured.
54
+ */
55
+ export declare function fillSecrets(args: unknown, deps: {
56
+ readonly resolver: SecretResolver | undefined;
57
+ readonly scrubber: SecretScrubber;
58
+ readonly signal: AbortSignal;
59
+ }): Promise<unknown>;
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Secrets (spec 35 § Secrets). A secret is resolved through
3
+ * `environment.secrets` immediately before the call is sent, allowed only in
4
+ * fields a profile marks `sensitive`, and never by the model. Before any
5
+ * output, event, read or text is stored, traced or shown, every resolved value
6
+ * — and its URL-encoded and base64 forms — is replaced with `"<redacted>"`.
7
+ */
8
+ import { frameworkCast, isSecret, REDACTED_TEXT } from '@noetic-tools/types';
9
+ import { invalidConnectionError, secretRefusedError } from './errors.js';
10
+ import { secretAllowedAt } from './json-schema.js';
11
+ import { findDeep, mapDeep } from './values.js';
12
+ //#endregion
13
+ //#region Helpers
14
+ function base64(text) {
15
+ const bytes = new TextEncoder().encode(text);
16
+ let binary = '';
17
+ for (const byte of bytes) {
18
+ binary += String.fromCharCode(byte);
19
+ }
20
+ return btoa(binary);
21
+ }
22
+ function base64Url(encoded) {
23
+ return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
24
+ }
25
+ function fieldOf(path) {
26
+ return path.filter((segment) => typeof segment === 'string').join('.');
27
+ }
28
+ function secretDeclared(site, name, path) {
29
+ if (!site.allowedSecrets) {
30
+ return true;
31
+ }
32
+ const field = fieldOf(path);
33
+ return site.allowedSecrets.some((allowed) => allowed.name === name && allowed.field === field);
34
+ }
35
+ function escapeRegExp(text) {
36
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
37
+ }
38
+ //#endregion
39
+ //#region Public API
40
+ /** Remembers every resolved secret value and replaces it wherever it shows up. */
41
+ export class SecretScrubber {
42
+ forms = new Set();
43
+ pattern;
44
+ /** Registers a resolved value: raw, URL-encoded and base64 (standard and URL-safe). */
45
+ add(value) {
46
+ if (value.length === 0) {
47
+ return;
48
+ }
49
+ const encoded = base64(value);
50
+ const candidates = [
51
+ value,
52
+ encodeURIComponent(value),
53
+ encoded,
54
+ encoded.replace(/=+$/, ''),
55
+ base64Url(encoded),
56
+ ];
57
+ for (const form of candidates) {
58
+ this.forms.add(form);
59
+ }
60
+ this.pattern = undefined;
61
+ }
62
+ /** Whether any secret has been resolved yet. */
63
+ get active() {
64
+ return this.forms.size > 0;
65
+ }
66
+ /** `text` with every known secret form replaced by `"<redacted>"`. */
67
+ scrubText(text) {
68
+ if (this.forms.size === 0) {
69
+ return text;
70
+ }
71
+ if (!this.pattern) {
72
+ const longestFirst = [
73
+ ...this.forms,
74
+ ].sort((a, b) => b.length - a.length);
75
+ this.pattern = new RegExp(longestFirst.map(escapeRegExp).join('|'), 'g');
76
+ }
77
+ return text.replace(this.pattern, REDACTED_TEXT);
78
+ }
79
+ /** A copy of `value` with every string scrubbed. */
80
+ scrub(value) {
81
+ if (this.forms.size === 0) {
82
+ return value;
83
+ }
84
+ const scrubbed = mapDeep(value, (node) => typeof node.value === 'string'
85
+ ? {
86
+ replace: this.scrubText(node.value),
87
+ }
88
+ : undefined);
89
+ // mapDeep keeps the shape of `value`, replacing only strings with strings.
90
+ return frameworkCast(scrubbed);
91
+ }
92
+ }
93
+ /** The secrets in `args`, with where each sits. */
94
+ export function findSecrets(args) {
95
+ return findDeep(args, isSecret);
96
+ }
97
+ /**
98
+ * Refuses secrets the model sent, that sit outside a `sensitive` field, or —
99
+ * for a document — that its node does not write out.
100
+ *
101
+ * @throws NoeticErrorImpl `connection_secret_refused`.
102
+ */
103
+ export function checkSecrets(args, site) {
104
+ const secrets = findSecrets(args);
105
+ if (secrets.length === 0) {
106
+ return;
107
+ }
108
+ if (site.caller === 'model') {
109
+ throw secretRefusedError(site.connection, site.op);
110
+ }
111
+ for (const found of secrets) {
112
+ if (!secretDeclared(site, found.value.$secret, found.path)) {
113
+ throw secretRefusedError(site.connection, site.op);
114
+ }
115
+ if (!secretAllowedAt(site.inputSchema, found.path)) {
116
+ throw secretRefusedError(site.connection, site.op);
117
+ }
118
+ }
119
+ }
120
+ /**
121
+ * Replaces each `{ $secret }` in `args` with its resolved value and registers
122
+ * the value with `scrubber`.
123
+ *
124
+ * @throws NoeticConfigError `CONNECTION_INVALID` when secrets are used but no resolver is configured.
125
+ */
126
+ export async function fillSecrets(args, deps) {
127
+ const secrets = findSecrets(args);
128
+ if (secrets.length === 0) {
129
+ return args;
130
+ }
131
+ const resolver = deps.resolver;
132
+ if (!resolver) {
133
+ throw invalidConnectionError('A call uses secret() but the harness has no secret resolver.', 'Set `environment.secrets` on the AgentHarness to resolve secret names.');
134
+ }
135
+ const resolved = new Map();
136
+ for (const found of secrets) {
137
+ const name = found.value.$secret;
138
+ if (resolved.has(name)) {
139
+ continue;
140
+ }
141
+ const value = await resolver.resolve(name, {
142
+ signal: deps.signal,
143
+ });
144
+ deps.scrubber.add(value);
145
+ resolved.set(name, value);
146
+ }
147
+ return mapDeep(args, (node) => isSecret(node.value)
148
+ ? {
149
+ replace: resolved.get(node.value.$secret),
150
+ }
151
+ : undefined);
152
+ }
153
+ //#endregion
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Shutdown helpers: closing several things must try every one of them, so one
3
+ * that throws never leaves the rest open.
4
+ */
5
+ /**
6
+ * Runs every task in order, carrying on past one that throws, then rethrows
7
+ * the first failure once all have run.
8
+ */
9
+ export declare function runEvery(tasks: ReadonlyArray<() => Promise<unknown> | unknown>): Promise<void>;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Shutdown helpers: closing several things must try every one of them, so one
3
+ * that throws never leaves the rest open.
4
+ */
5
+ //#region Public API
6
+ /**
7
+ * Runs every task in order, carrying on past one that throws, then rethrows
8
+ * the first failure once all have run.
9
+ */
10
+ export async function runEvery(tasks) {
11
+ let failure;
12
+ for (const task of tasks) {
13
+ try {
14
+ await task();
15
+ }
16
+ catch (error) {
17
+ failure ??= {
18
+ error,
19
+ };
20
+ }
21
+ }
22
+ if (failure) {
23
+ throw failure.error;
24
+ }
25
+ }
26
+ //#endregion
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Sources (spec 35 § Triggers): event streams written in code — a queue
3
+ * consumer, a file watcher, a webhook from your own app — registered as
4
+ * connections. `defineSource({ events, start })` validates each emitted
5
+ * payload against its event's schema; `start` runs once a listener subscribes
6
+ * and receives the last durable cursor a trigger recorded. Host code can also
7
+ * push with `source.emit(…)`; events pushed before anyone listens are held
8
+ * (up to `WAIT_BUFFER_LIMIT`) for the first listener.
9
+ *
10
+ * `cron(schedule, { timezone })` is a built-in source with one event, `tick`,
11
+ * delivered once per scheduled time even after downtime: a restarted trigger
12
+ * resumes from its cursor and receives every tick it missed.
13
+ */
14
+ import type { Cron, DefineSource } from '@noetic-tools/types';
15
+ /**
16
+ * @public
17
+ * Defines an in-process event source to register as a harness connection.
18
+ */
19
+ export declare const defineSource: DefineSource;
20
+ /**
21
+ * @public
22
+ * A source with one event, `tick`, delivered once per scheduled time of a
23
+ * five-field cron `schedule` in `timezone` (default UTC), even after downtime.
24
+ *
25
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed schedule or timezone.
26
+ */
27
+ export declare const cron: Cron;
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Sources (spec 35 § Triggers): event streams written in code — a queue
3
+ * consumer, a file watcher, a webhook from your own app — registered as
4
+ * connections. `defineSource({ events, start })` validates each emitted
5
+ * payload against its event's schema; `start` runs once a listener subscribes
6
+ * and receives the last durable cursor a trigger recorded. Host code can also
7
+ * push with `source.emit(…)`; events pushed before anyone listens are held
8
+ * (up to `WAIT_BUFFER_LIMIT`) for the first listener.
9
+ *
10
+ * `cron(schedule, { timezone })` is a built-in source with one event, `tick`,
11
+ * delivered once per scheduled time even after downtime: a restarted trigger
12
+ * resumes from its cursor and receives every tick it missed.
13
+ */
14
+ import { WAIT_BUFFER_LIMIT } from '@noetic-tools/types';
15
+ import { z } from 'zod';
16
+ import { nextCronRun, parseCronSchedule } from './cron-schedule.js';
17
+ import { invalidConnectionError } from './errors.js';
18
+ import { createListenerStream } from './in-memory-connection.js';
19
+ //#region Constants
20
+ /** The most missed ticks a restarted cron delivers at once. */
21
+ const CRON_CATCH_UP_LIMIT = 1e3;
22
+ const CronTickSchema = z.object({
23
+ scheduledFor: z.string(),
24
+ });
25
+ //#endregion
26
+ //#region Helpers
27
+ function jsonSchemaOf(schema) {
28
+ try {
29
+ return z.toJSONSchema(schema, {
30
+ unrepresentable: 'any',
31
+ });
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }
37
+ function manifestOf(events, durable) {
38
+ const infos = {};
39
+ for (const [name, schema] of Object.entries(events)) {
40
+ const payloadSchema = jsonSchemaOf(schema);
41
+ infos[name] = {
42
+ name,
43
+ replay: durable ? 'durable' : 'live',
44
+ ...(payloadSchema
45
+ ? {
46
+ payloadSchema,
47
+ }
48
+ : {}),
49
+ };
50
+ }
51
+ return {
52
+ profiles: {},
53
+ extensions: {},
54
+ operations: {},
55
+ resources: {},
56
+ events: infos,
57
+ senses: {},
58
+ };
59
+ }
60
+ function sleep(ms, signal) {
61
+ return new Promise((resolve) => {
62
+ if (signal.aborted) {
63
+ resolve(false);
64
+ return;
65
+ }
66
+ const timer = setTimeout(() => {
67
+ signal.removeEventListener('abort', onAbort);
68
+ resolve(true);
69
+ }, Math.max(0, ms));
70
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer) {
71
+ timer.unref();
72
+ }
73
+ const onAbort = () => {
74
+ clearTimeout(timer);
75
+ resolve(false);
76
+ };
77
+ signal.addEventListener('abort', onAbort, {
78
+ once: true,
79
+ });
80
+ });
81
+ }
82
+ //#endregion
83
+ //#region Source hub
84
+ /** The live side of a source: its listeners, its pending events, and its one running `start`. */
85
+ class SourceHub {
86
+ definition;
87
+ listeners = new Set();
88
+ pending = [];
89
+ started = false;
90
+ controller = new AbortController();
91
+ constructor(definition) {
92
+ this.definition = definition;
93
+ }
94
+ async emit(event) {
95
+ const schema = this.definition.events[event.type];
96
+ if (!schema) {
97
+ throw invalidConnectionError(`The source has no event '${event.type}'.`, `Emit one of: ${Object.keys(this.definition.events).join(', ')}.`);
98
+ }
99
+ const parsed = schema.safeParse(event.payload);
100
+ if (!parsed.success) {
101
+ throw invalidConnectionError(`Payload of source event '${event.type}' does not match its schema: ${parsed.error.message}`, `Emit a payload the '${event.type}' schema accepts.`);
102
+ }
103
+ const init = {
104
+ id: event.id,
105
+ type: event.type,
106
+ time: event.time ?? new Date().toISOString(),
107
+ payload: parsed.data,
108
+ cursor: event.cursor ?? null,
109
+ };
110
+ const targets = [
111
+ ...this.listeners,
112
+ ].filter((l) => l.event === event.type);
113
+ if (targets.length === 0) {
114
+ this.pending.push(init);
115
+ if (this.pending.length > WAIT_BUFFER_LIMIT) {
116
+ this.pending.shift();
117
+ }
118
+ return;
119
+ }
120
+ for (const listener of targets) {
121
+ listener.push({
122
+ type: 'event',
123
+ event: init,
124
+ });
125
+ }
126
+ }
127
+ listen(request) {
128
+ const { stream, listener } = createListenerStream(this.listeners, request, {
129
+ cursor: request.cursor ?? null,
130
+ });
131
+ this.listeners.add(listener);
132
+ const held = this.pending.filter((e) => e.type === request.event);
133
+ for (const event of held) {
134
+ this.pending.splice(this.pending.indexOf(event), 1);
135
+ listener.push({
136
+ type: 'event',
137
+ event,
138
+ });
139
+ }
140
+ this.startOnce(request.cursor ?? null);
141
+ return stream;
142
+ }
143
+ close(reason) {
144
+ this.controller.abort();
145
+ for (const listener of [
146
+ ...this.listeners,
147
+ ]) {
148
+ listener.push({
149
+ type: 'terminated',
150
+ reason,
151
+ });
152
+ listener.end();
153
+ }
154
+ }
155
+ startOnce(cursor) {
156
+ const start = this.definition.start;
157
+ if (this.started || !start) {
158
+ return;
159
+ }
160
+ this.started = true;
161
+ const run = async () => {
162
+ await start.call(this.definition, {
163
+ emit: (event) => this.emit(event),
164
+ cursor,
165
+ signal: this.controller.signal,
166
+ });
167
+ };
168
+ void run().catch((e) => {
169
+ this.close(`source stopped: ${e instanceof Error ? e.message : String(e)}`);
170
+ });
171
+ }
172
+ }
173
+ //#endregion
174
+ //#region Public API
175
+ /**
176
+ * @public
177
+ * Defines an in-process event source to register as a harness connection.
178
+ */
179
+ export const defineSource = (definition) => {
180
+ let hub;
181
+ const hubFor = () => {
182
+ hub ??= new SourceHub(definition);
183
+ return hub;
184
+ };
185
+ const manifest = manifestOf(definition.events, definition.start !== undefined);
186
+ return {
187
+ kind: 'source',
188
+ events: definition.events,
189
+ emit: (event) => hubFor().emit(event),
190
+ async connect(_opts) {
191
+ const current = hubFor();
192
+ let resolveClosed = () => undefined;
193
+ const closed = new Promise((resolve) => {
194
+ resolveClosed = resolve;
195
+ });
196
+ const connection = {
197
+ id: 'source',
198
+ manifest,
199
+ identity: {
200
+ surface: 'x-source',
201
+ instance: crypto.randomUUID(),
202
+ },
203
+ async call(op) {
204
+ return {
205
+ status: 'error',
206
+ error: {
207
+ code: 'undeclared',
208
+ message: `a source has no operations ('${op}')`,
209
+ },
210
+ };
211
+ },
212
+ async read(resource) {
213
+ throw invalidConnectionError(`A source has no resource '${resource}'.`, 'Sources only deliver events.');
214
+ },
215
+ listen: (request) => current.listen(request),
216
+ tasks: {
217
+ async get(taskId) {
218
+ return {
219
+ taskId,
220
+ state: 'failed',
221
+ };
222
+ },
223
+ async result() {
224
+ return {
225
+ status: 'error',
226
+ error: {
227
+ code: 'not_found',
228
+ message: 'a source has no tasks',
229
+ },
230
+ };
231
+ },
232
+ async cancel() { },
233
+ async respond() { },
234
+ },
235
+ onChange: () => () => undefined,
236
+ closed,
237
+ async release() {
238
+ current.close('released');
239
+ hub = undefined;
240
+ resolveClosed({
241
+ reason: 'released',
242
+ });
243
+ },
244
+ };
245
+ return [
246
+ connection,
247
+ ];
248
+ },
249
+ };
250
+ };
251
+ /**
252
+ * @public
253
+ * A source with one event, `tick`, delivered once per scheduled time of a
254
+ * five-field cron `schedule` in `timezone` (default UTC), even after downtime.
255
+ *
256
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed schedule or timezone.
257
+ */
258
+ export const cron = (schedule, options) => {
259
+ const parsed = parseCronSchedule(schedule, options?.timezone ?? 'UTC');
260
+ const events = {
261
+ tick: CronTickSchema,
262
+ };
263
+ return defineSource({
264
+ events,
265
+ async start({ emit, cursor, signal }) {
266
+ const resumed = cursor === null ? Number.NaN : Date.parse(cursor);
267
+ let after = Number.isNaN(resumed) ? Date.now() : resumed;
268
+ let caughtUp = 0;
269
+ for (;;) {
270
+ const next = nextCronRun(parsed, after);
271
+ if (next === undefined || signal.aborted) {
272
+ return;
273
+ }
274
+ const wait = next - Date.now();
275
+ if (wait > 0 && !(await sleep(wait, signal))) {
276
+ return;
277
+ }
278
+ if (wait <= 0) {
279
+ caughtUp += 1;
280
+ }
281
+ if (caughtUp > CRON_CATCH_UP_LIMIT) {
282
+ after = Date.now();
283
+ caughtUp = 0;
284
+ continue;
285
+ }
286
+ const scheduledFor = new Date(next).toISOString();
287
+ await emit({
288
+ type: 'tick',
289
+ id: scheduledFor,
290
+ cursor: scheduledFor,
291
+ payload: {
292
+ scheduledFor,
293
+ },
294
+ });
295
+ after = next;
296
+ }
297
+ },
298
+ });
299
+ };
300
+ //#endregion
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Triggers (spec 35 § Triggers, § Events). A trigger starts or joins a turn
3
+ * when a connection reports an event. Triggers listen for the life of the
4
+ * harness. Each matching event is written to a durable inbox together with the
5
+ * advanced cursor, delivered as a turn with message id
6
+ * `<connection>:<trigger>:<event id>` on its thread — `thread(event)`, else
7
+ * the profile's natural thread for the event, else the trigger id — and
8
+ * recorded as done when its turn completes. Events are deduplicated per
9
+ * trigger, so a trigger delivers each event once, even across crashes: on
10
+ * start, undelivered inbox entries are delivered again before listening
11
+ * resumes from the recorded cursor.
12
+ */
13
+ import type { ConnectionEvent, ConnectionTrigger, StorageAdapter } from '@noetic-tools/types';
14
+ import type { ConnectionRuntime } from './registry.js';
15
+ /** One event a trigger hands to the harness as a turn. */
16
+ export interface TriggerDelivery {
17
+ readonly trigger: string;
18
+ readonly connection: string;
19
+ readonly threadId: string;
20
+ /** `<connection>:<trigger>:<event id>`. */
21
+ readonly messageId: string;
22
+ readonly input: string;
23
+ /** The event as the turn sees it: stamped, refs sealed to `threadId`, secrets scrubbed. */
24
+ readonly event: ConnectionEvent;
25
+ }
26
+ /** What a `TriggerRunner` needs. */
27
+ export interface TriggerRunnerOptions {
28
+ readonly runtime: ConnectionRuntime;
29
+ readonly triggers: ReadonlyArray<ConnectionTrigger>;
30
+ readonly storage: StorageAdapter;
31
+ /** Starts the turn; resolves when it completes (then the event is recorded as done). */
32
+ readonly deliver: (delivery: TriggerDelivery) => Promise<void>;
33
+ /** A delivery or listen failure. Default: a console warning. */
34
+ readonly onError?: (trigger: string, error: unknown) => void;
35
+ /** Delay before re-listening after a stream ended, by attempt. Default: 1 s doubling to 30 s. */
36
+ readonly relistenDelayMs?: (attempt: number) => number;
37
+ /** Delay before retrying a failed delivery, by attempt. Default: 1 s doubling to 30 s. */
38
+ readonly redeliverDelayMs?: (attempt: number) => number;
39
+ }
40
+ /**
41
+ * Checks triggers against the harness connections at construction.
42
+ *
43
+ * @throws NoeticConfigError `CONNECTION_UNKNOWN` for a trigger naming an unknown connection,
44
+ * `CONNECTION_INVALID` for a missing or repeated trigger id or a missing event.
45
+ */
46
+ export declare function validateTriggers(triggers: ReadonlyArray<ConnectionTrigger>, names: ReadonlyArray<string>): void;
47
+ /** Runs a harness's triggers for its lifetime. */
48
+ export declare class TriggerRunner {
49
+ private readonly options;
50
+ private readonly controller;
51
+ private readonly loops;
52
+ /**
53
+ * The last delivery on each thread. A thread's events are delivered one turn
54
+ * at a time, so each matching event starts its own turn instead of joining
55
+ * a queued one (spec 35 § Triggers).
56
+ */
57
+ private readonly threads;
58
+ constructor(options: TriggerRunnerOptions);
59
+ /**
60
+ * Redelivers undelivered inbox entries and starts listening.
61
+ *
62
+ * @throws ConnectionUnsatisfiedError when a trigger's connection does not offer its event.
63
+ */
64
+ start(): Promise<void>;
65
+ close(): Promise<void>;
66
+ private report;
67
+ private redeliver;
68
+ private listenLoop;
69
+ /** Listens until the stream ends. Returns whether it got as far as listening. */
70
+ private listenOnce;
71
+ private handle;
72
+ /** The inbox entry for an event, or `undefined` when the trigger's filter rejects it. */
73
+ private entryFor;
74
+ private advance;
75
+ private deliver;
76
+ /** Delivers one inbox entry, retrying a failed turn with backoff; marks it done on success. */
77
+ private deliverWithRetry;
78
+ }