@noetic-tools/core 5.19.1 → 5.20.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 (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,310 @@
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 { ConnectionUnsatisfiedError } from '@noetic-tools/types';
14
+ import { z } from 'zod';
15
+ import { invalidConnectionError, unknownConnectionError } from './errors.js';
16
+ import { isPlainRecord } from './values.js';
17
+ //#endregion
18
+ //#region Constants
19
+ /** Deliveries of one event tried in-process before it waits for the next start. */
20
+ const MAX_DELIVERY_ATTEMPTS = 5;
21
+ const InboxEntrySchema = z.object({
22
+ event: z.object({
23
+ id: z.string(),
24
+ type: z.string(),
25
+ time: z.string(),
26
+ payload: z.unknown(),
27
+ cursor: z.string().nullable(),
28
+ connection: z.string(),
29
+ actionId: z.string().optional(),
30
+ }),
31
+ threadId: z.string(),
32
+ input: z.string(),
33
+ messageId: z.string(),
34
+ });
35
+ //#endregion
36
+ //#region Helpers
37
+ function prefix(triggerId) {
38
+ return `noetic/connections/triggers/${triggerId}`;
39
+ }
40
+ function defaultDelay(attempt) {
41
+ return Math.min(3e4, 1e3 * 2 ** attempt);
42
+ }
43
+ function naturalThread(event, field) {
44
+ if (!field || !isPlainRecord(event.payload)) {
45
+ return undefined;
46
+ }
47
+ const value = event.payload[field];
48
+ if (isPlainRecord(value) && isPlainRecord(value.$ref) && typeof value.$ref.id === 'string') {
49
+ return `${event.connection}:${value.$ref.id}`;
50
+ }
51
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
52
+ }
53
+ function wait(ms, signal) {
54
+ return new Promise((resolve) => {
55
+ const timer = setTimeout(resolve, ms);
56
+ signal.addEventListener('abort', () => {
57
+ clearTimeout(timer);
58
+ resolve();
59
+ }, {
60
+ once: true,
61
+ });
62
+ });
63
+ }
64
+ //#endregion
65
+ //#region Public API
66
+ /**
67
+ * Checks triggers against the harness connections at construction.
68
+ *
69
+ * @throws NoeticConfigError `CONNECTION_UNKNOWN` for a trigger naming an unknown connection,
70
+ * `CONNECTION_INVALID` for a missing or repeated trigger id or a missing event.
71
+ */
72
+ export function validateTriggers(triggers, names) {
73
+ const ids = new Set();
74
+ for (const trigger of triggers) {
75
+ if (!trigger.id || ids.has(trigger.id)) {
76
+ throw invalidConnectionError(`Trigger id '${trigger.id}' is missing or used twice.`, 'Give every trigger a unique, non-empty id.');
77
+ }
78
+ ids.add(trigger.id);
79
+ if (!names.includes(trigger.connection)) {
80
+ throw unknownConnectionError(trigger.connection, names);
81
+ }
82
+ if (!trigger.event) {
83
+ throw invalidConnectionError(`Trigger '${trigger.id}' names no event.`, "Set the event the trigger listens for, e.g. event: 'chat.message.created'.");
84
+ }
85
+ }
86
+ }
87
+ /** Runs a harness's triggers for its lifetime. */
88
+ export class TriggerRunner {
89
+ options;
90
+ controller = new AbortController();
91
+ loops = [];
92
+ /**
93
+ * The last delivery on each thread. A thread's events are delivered one turn
94
+ * at a time, so each matching event starts its own turn instead of joining
95
+ * a queued one (spec 35 § Triggers).
96
+ */
97
+ threads = new Map();
98
+ constructor(options) {
99
+ this.options = options;
100
+ }
101
+ /**
102
+ * Redelivers undelivered inbox entries and starts listening.
103
+ *
104
+ * @throws ConnectionUnsatisfiedError when a trigger's connection does not offer its event.
105
+ */
106
+ async start() {
107
+ for (const trigger of this.options.triggers) {
108
+ const manifest = this.options.runtime.current(trigger.connection)?.manifest;
109
+ if (manifest && !manifest.events[trigger.event]) {
110
+ throw new ConnectionUnsatisfiedError({
111
+ connection: trigger.connection,
112
+ missing: {
113
+ kind: 'event',
114
+ event: trigger.event,
115
+ },
116
+ });
117
+ }
118
+ }
119
+ for (const trigger of this.options.triggers) {
120
+ await this.redeliver(trigger);
121
+ this.loops.push(this.listenLoop(trigger));
122
+ }
123
+ }
124
+ async close() {
125
+ this.controller.abort();
126
+ await Promise.allSettled(this.loops);
127
+ }
128
+ report(trigger, error) {
129
+ if (this.options.onError) {
130
+ this.options.onError(trigger, error);
131
+ return;
132
+ }
133
+ console.warn(`[noetic] trigger '${trigger}':`, error);
134
+ }
135
+ async redeliver(trigger) {
136
+ const keys = await this.options.storage.list(`${prefix(trigger.id)}/inbox/`);
137
+ for (const key of keys) {
138
+ const parsed = InboxEntrySchema.safeParse(await this.options.storage.get(key));
139
+ if (!parsed.success) {
140
+ await this.options.storage.delete(key);
141
+ continue;
142
+ }
143
+ this.deliver(trigger, parsed.data, key);
144
+ }
145
+ }
146
+ async listenLoop(trigger) {
147
+ const signal = this.controller.signal;
148
+ let attempt = 0;
149
+ while (!signal.aborted) {
150
+ try {
151
+ const ended = await this.listenOnce(trigger, signal);
152
+ if (ended) {
153
+ attempt = 0;
154
+ }
155
+ }
156
+ catch (e) {
157
+ this.report(trigger.id, e);
158
+ }
159
+ if (signal.aborted) {
160
+ return;
161
+ }
162
+ await wait((this.options.relistenDelayMs ?? defaultDelay)(attempt), signal);
163
+ attempt += 1;
164
+ }
165
+ }
166
+ /** Listens until the stream ends. Returns whether it got as far as listening. */
167
+ async listenOnce(trigger, signal) {
168
+ const cursor = await this.options.storage.get(`${prefix(trigger.id)}/cursor`);
169
+ const stream = await this.options.runtime.listenRaw(trigger.connection, {
170
+ event: trigger.event,
171
+ arguments: trigger.arguments,
172
+ cursor: typeof cursor === 'string' ? cursor : null,
173
+ signal,
174
+ });
175
+ await stream.ready;
176
+ for await (const message of stream) {
177
+ if (signal.aborted) {
178
+ break;
179
+ }
180
+ if (message.type === 'event') {
181
+ await this.handle(trigger, message.event);
182
+ continue;
183
+ }
184
+ this.options.runtime.emit({
185
+ type: 'stream_changed',
186
+ data: {
187
+ connection: trigger.connection,
188
+ event: trigger.event,
189
+ change: message.type === 'gap' ? 'gap' : 'ended',
190
+ reason: message.reason,
191
+ },
192
+ });
193
+ if (message.type === 'terminated') {
194
+ break;
195
+ }
196
+ }
197
+ await stream.close();
198
+ return true;
199
+ }
200
+ async handle(trigger, init) {
201
+ const storage = this.options.storage;
202
+ const base = prefix(trigger.id);
203
+ const inboxKey = `${base}/inbox/${encodeURIComponent(init.id)}`;
204
+ const seenKey = `${base}/seen/${encodeURIComponent(init.id)}`;
205
+ const duplicate = (await storage.get(seenKey)) !== null || (await storage.get(inboxKey)) !== null;
206
+ if (duplicate) {
207
+ await this.advance(trigger, init.cursor);
208
+ return;
209
+ }
210
+ let entry;
211
+ try {
212
+ entry = await this.entryFor(trigger, init);
213
+ }
214
+ catch (e) {
215
+ // A filter or input that throws on one event dead-letters it rather than
216
+ // re-reading it from the same cursor forever.
217
+ this.report(trigger.id, e);
218
+ await storage.set(seenKey, {
219
+ failed: e instanceof Error ? e.message : String(e),
220
+ });
221
+ await this.advance(trigger, init.cursor);
222
+ return;
223
+ }
224
+ if (!entry) {
225
+ await this.advance(trigger, init.cursor);
226
+ return;
227
+ }
228
+ await storage.set(inboxKey, entry);
229
+ await this.advance(trigger, init.cursor);
230
+ this.options.runtime.emit({
231
+ type: 'connection_event',
232
+ data: {
233
+ connection: trigger.connection,
234
+ trigger: trigger.id,
235
+ event: entry.event,
236
+ },
237
+ });
238
+ this.deliver(trigger, entry, inboxKey);
239
+ }
240
+ /** The inbox entry for an event, or `undefined` when the trigger's filter rejects it. */
241
+ async entryFor(trigger, init) {
242
+ const runtime = this.options.runtime;
243
+ const stamped = {
244
+ ...init,
245
+ connection: trigger.connection,
246
+ };
247
+ const field = runtime.current(trigger.connection)?.manifest.events[trigger.event]?.thread;
248
+ const threadId = trigger.thread?.(stamped) ?? naturalThread(stamped, field) ?? trigger.id;
249
+ const payload = await runtime.admit(trigger.connection, init.payload, {
250
+ threadId,
251
+ executionId: `trigger:${trigger.id}`,
252
+ });
253
+ const event = {
254
+ ...stamped,
255
+ payload,
256
+ };
257
+ if (trigger.filter && !trigger.filter(event)) {
258
+ return undefined;
259
+ }
260
+ return {
261
+ event,
262
+ threadId,
263
+ input: trigger.input(event),
264
+ messageId: `${trigger.connection}:${trigger.id}:${init.id}`,
265
+ };
266
+ }
267
+ async advance(trigger, cursor) {
268
+ if (cursor === null) {
269
+ return;
270
+ }
271
+ await this.options.storage.set(`${prefix(trigger.id)}/cursor`, cursor);
272
+ }
273
+ deliver(trigger, entry, inboxKey) {
274
+ const previous = this.threads.get(entry.threadId) ?? Promise.resolve();
275
+ const next = previous.then(() => this.deliverWithRetry(trigger, entry, inboxKey));
276
+ this.threads.set(entry.threadId, next);
277
+ void next.finally(() => {
278
+ if (this.threads.get(entry.threadId) === next) {
279
+ this.threads.delete(entry.threadId);
280
+ }
281
+ });
282
+ }
283
+ /** Delivers one inbox entry, retrying a failed turn with backoff; marks it done on success. */
284
+ async deliverWithRetry(trigger, entry, inboxKey) {
285
+ const storage = this.options.storage;
286
+ const seenKey = `${prefix(trigger.id)}/seen/${encodeURIComponent(entry.event.id)}`;
287
+ const signal = this.controller.signal;
288
+ for (let attempt = 0; attempt < MAX_DELIVERY_ATTEMPTS && !signal.aborted; attempt++) {
289
+ try {
290
+ await this.options.deliver({
291
+ trigger: trigger.id,
292
+ connection: trigger.connection,
293
+ threadId: entry.threadId,
294
+ messageId: entry.messageId,
295
+ input: entry.input,
296
+ event: entry.event,
297
+ });
298
+ await storage.set(seenKey, true);
299
+ await storage.delete(inboxKey);
300
+ return;
301
+ }
302
+ catch (e) {
303
+ this.report(trigger.id, e);
304
+ }
305
+ await wait((this.options.redeliverDelayMs ?? defaultDelay)(attempt), signal);
306
+ }
307
+ // Still undelivered: the inbox entry stays and is delivered again on the next start.
308
+ }
309
+ }
310
+ //#endregion
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Walking the values that cross a connection: arguments going out, outputs,
3
+ * reads and event payloads coming in. Refs, blobs and secrets are found by
4
+ * shape wherever they sit, so every walk here is structural.
5
+ */
6
+ import type { JsonPath } from './json-schema.js';
7
+ /** One node a walk visits, with where it sits. */
8
+ export interface VisitedNode {
9
+ readonly value: unknown;
10
+ readonly path: JsonPath;
11
+ }
12
+ /** Returns a replacement for a node, or `undefined` to keep walking into it. */
13
+ export type NodeMapper = (node: VisitedNode) => {
14
+ readonly replace: unknown;
15
+ } | undefined;
16
+ /** Copies `value`, replacing every node `mapper` returns a replacement for. Class instances are kept as they are. */
17
+ export declare function mapDeep(value: unknown, mapper: NodeMapper): unknown;
18
+ /** Every node `match` accepts, with its path. Matched nodes are not walked into. */
19
+ export declare function findDeep<T>(value: unknown, match: (node: unknown) => node is T): Array<{
20
+ readonly value: T;
21
+ readonly path: JsonPath;
22
+ }>;
23
+ /** Replaces the node at `path` (which must exist) with `replacement`, copying along the way. */
24
+ export declare function setAtPath(value: unknown, path: JsonPath, replacement: unknown): unknown;
25
+ /** Whether `value` is a plain JSON-style object. */
26
+ export declare function isPlainRecord(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Walking the values that cross a connection: arguments going out, outputs,
3
+ * reads and event payloads coming in. Refs, blobs and secrets are found by
4
+ * shape wherever they sit, so every walk here is structural.
5
+ */
6
+ //#endregion
7
+ //#region Helpers
8
+ const MAX_DEPTH = 64;
9
+ function isPlainObject(value) {
10
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
11
+ return false;
12
+ }
13
+ const proto = Object.getPrototypeOf(value);
14
+ return proto === Object.prototype || proto === null;
15
+ }
16
+ function mapAt(node, mapper, depth) {
17
+ const mapped = mapper(node);
18
+ if (mapped) {
19
+ return mapped.replace;
20
+ }
21
+ if (depth >= MAX_DEPTH) {
22
+ return node.value;
23
+ }
24
+ const { value, path } = node;
25
+ if (Array.isArray(value)) {
26
+ return value.map((item, i) => mapAt({
27
+ value: item,
28
+ path: [
29
+ ...path,
30
+ i,
31
+ ],
32
+ }, mapper, depth + 1));
33
+ }
34
+ if (!isPlainObject(value)) {
35
+ return value;
36
+ }
37
+ const out = {};
38
+ for (const [key, child] of Object.entries(value)) {
39
+ out[key] = mapAt({
40
+ value: child,
41
+ path: [
42
+ ...path,
43
+ key,
44
+ ],
45
+ }, mapper, depth + 1);
46
+ }
47
+ return out;
48
+ }
49
+ //#endregion
50
+ //#region Public API
51
+ /** Copies `value`, replacing every node `mapper` returns a replacement for. Class instances are kept as they are. */
52
+ export function mapDeep(value, mapper) {
53
+ return mapAt({
54
+ value,
55
+ path: [],
56
+ }, mapper, 0);
57
+ }
58
+ /** Every node `match` accepts, with its path. Matched nodes are not walked into. */
59
+ export function findDeep(value, match) {
60
+ const found = [];
61
+ mapDeep(value, (node) => {
62
+ if (!match(node.value)) {
63
+ return undefined;
64
+ }
65
+ found.push({
66
+ value: node.value,
67
+ path: node.path,
68
+ });
69
+ return {
70
+ replace: node.value,
71
+ };
72
+ });
73
+ return found;
74
+ }
75
+ /** Replaces the node at `path` (which must exist) with `replacement`, copying along the way. */
76
+ export function setAtPath(value, path, replacement) {
77
+ return mapDeep(value, (node) => {
78
+ if (node.path.length !== path.length) {
79
+ return undefined;
80
+ }
81
+ const same = node.path.every((step, i) => step === path[i]);
82
+ return same
83
+ ? {
84
+ replace: replacement,
85
+ }
86
+ : undefined;
87
+ });
88
+ }
89
+ /** Whether `value` is a plain JSON-style object. */
90
+ export function isPlainRecord(value) {
91
+ return isPlainObject(value);
92
+ }
93
+ //#endregion
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Connection views (spec 35 § Looking, spec 12 § Connection views). Every
3
+ * connection whose profile names state worth reading gets a context layer,
4
+ * added automatically, that renders it within its own budget. Each read is
5
+ * shown on its `look` mode — the harness entry's `look` overrides the
6
+ * profile's default:
7
+ *
8
+ * - `'turn'`: read every turn (cheap summaries).
9
+ * - `'effect'`: read after an operation that changed the connection.
10
+ * - `'ask'`: only when the model asks, through `<name>_call({ read })`.
11
+ *
12
+ * Repeated reads render as diffs against what the model last saw, blob
13
+ * references render as a short reference (sensitive ones are withheld), and
14
+ * each read's token cost is recorded on the trace.
15
+ */
16
+ import type { ContextLayer } from '@noetic-tools/types';
17
+ import type { ConnectionRuntime } from './registry.js';
18
+ /** A view layer's state: what the model last saw of each read, and the effect count it saw it at. */
19
+ export interface ConnectionViewState {
20
+ readonly previous: Readonly<Record<string, string>>;
21
+ readonly effects: number;
22
+ }
23
+ /** A line diff: unchanged lines are left out; removed lines start `- `, added ones `+ `. */
24
+ export declare function lineDiff(before: string, after: string): string;
25
+ /**
26
+ * The view layer for one connection. It renders nothing while the connection
27
+ * is not ready or has no `'turn'`/`'effect'` reads.
28
+ */
29
+ export declare function connectionViewLayer(runtime: ConnectionRuntime, name: string): ContextLayer<ConnectionViewState>;
30
+ /** A view layer for every non-pool connection in `runtime`. */
31
+ export declare function connectionViewLayers(runtime: ConnectionRuntime): ContextLayer<ConnectionViewState>[];
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Connection views (spec 35 § Looking, spec 12 § Connection views). Every
3
+ * connection whose profile names state worth reading gets a context layer,
4
+ * added automatically, that renders it within its own budget. Each read is
5
+ * shown on its `look` mode — the harness entry's `look` overrides the
6
+ * profile's default:
7
+ *
8
+ * - `'turn'`: read every turn (cheap summaries).
9
+ * - `'effect'`: read after an operation that changed the connection.
10
+ * - `'ask'`: only when the model asks, through `<name>_call({ read })`.
11
+ *
12
+ * Repeated reads render as diffs against what the model last saw, blob
13
+ * references render as a short reference (sensitive ones are withheld), and
14
+ * each read's token cost is recorded on the trace.
15
+ */
16
+ import { createMessage, estimateTokens, isBlobRef, Slot } from '@noetic-tools/types';
17
+ import { mapDeep } from './values.js';
18
+ //#endregion
19
+ //#region Helpers
20
+ const EMPTY_STATE = {
21
+ previous: {},
22
+ effects: -1,
23
+ };
24
+ /** Approximate characters per token, for trimming to budget. */
25
+ const CHARS_PER_TOKEN = 4;
26
+ function renderValue(value) {
27
+ const withBlobs = mapDeep(value, (node) => isBlobRef(node.value)
28
+ ? {
29
+ replace: `[${node.value.$blob.mimeType} ${node.value.$blob.bytes} bytes: ${node.value.$blob.uri}]`,
30
+ }
31
+ : undefined);
32
+ return typeof withBlobs === 'string' ? withBlobs : JSON.stringify(withBlobs, null, 2);
33
+ }
34
+ /** A line diff: unchanged lines are left out; removed lines start `- `, added ones `+ `. */
35
+ export function lineDiff(before, after) {
36
+ const oldLines = before.split('\n');
37
+ const newLines = after.split('\n');
38
+ const oldSet = new Set(oldLines);
39
+ const newSet = new Set(newLines);
40
+ const removed = oldLines.filter((line) => !newSet.has(line)).map((line) => `- ${line}`);
41
+ const added = newLines.filter((line) => !oldSet.has(line)).map((line) => `+ ${line}`);
42
+ return [
43
+ ...removed,
44
+ ...added,
45
+ ].join('\n');
46
+ }
47
+ function shownText(full, previous) {
48
+ if (previous === undefined) {
49
+ return full;
50
+ }
51
+ if (previous === full) {
52
+ return '(unchanged)';
53
+ }
54
+ const diff = lineDiff(previous, full);
55
+ return diff.length < full.length ? `(changes)\n${diff}` : full;
56
+ }
57
+ /** The look mode of a read: the harness entry's `look`, else the profile's, else `'ask'`. */
58
+ function modeOf(look, read, fallback) {
59
+ return look?.[read] ?? fallback ?? 'ask';
60
+ }
61
+ /** `'effect'` reads come only after an operation changed the connection (spec 35 § Looking). */
62
+ function wantsRead(mode, effectsChanged, effects) {
63
+ if (mode === 'turn') {
64
+ return true;
65
+ }
66
+ if (mode === 'effect') {
67
+ return effectsChanged && effects > 0;
68
+ }
69
+ return false;
70
+ }
71
+ async function readOne(runtime, request) {
72
+ try {
73
+ const resolved = await runtime.resolve({
74
+ name: request.name,
75
+ scope: {
76
+ executionId: request.ctx.executionId,
77
+ threadId: request.ctx.threadId,
78
+ scopeKey: request.ctx.executionId,
79
+ signal: new AbortController().signal,
80
+ },
81
+ });
82
+ const value = await resolved.read(request.read, {
83
+ signal: new AbortController().signal,
84
+ });
85
+ return renderValue(await runtime.withholdSensitive(value));
86
+ }
87
+ catch (e) {
88
+ return `(read failed: ${e instanceof Error ? e.message : String(e)})`;
89
+ }
90
+ }
91
+ //#endregion
92
+ //#region Public API
93
+ /**
94
+ * The view layer for one connection. It renders nothing while the connection
95
+ * is not ready or has no `'turn'`/`'effect'` reads.
96
+ */
97
+ export function connectionViewLayer(runtime, name) {
98
+ return {
99
+ id: `noetic/connection-view/${name}`,
100
+ name: `connection view: ${name}`,
101
+ slot: Slot.OBSERVATIONS,
102
+ scope: 'execution',
103
+ budget: 'auto',
104
+ placement: 'live',
105
+ onInitError: 'disable',
106
+ hooks: {
107
+ async init() {
108
+ return {
109
+ state: EMPTY_STATE,
110
+ };
111
+ },
112
+ async recall({ state, budget, ctx }) {
113
+ const current = state ?? EMPTY_STATE;
114
+ const manifest = runtime.current(name)?.manifest;
115
+ if (!manifest) {
116
+ return null;
117
+ }
118
+ const effects = runtime.effectCount(name);
119
+ const effectsChanged = effects !== current.effects;
120
+ const rendered = [];
121
+ for (const resource of Object.values(manifest.resources)) {
122
+ const mode = modeOf(runtime.config(name)?.look, resource.name, resource.look);
123
+ const previous = current.previous[resource.name];
124
+ if (!wantsRead(mode, effectsChanged, effects)) {
125
+ continue;
126
+ }
127
+ const full = await readOne(runtime, {
128
+ name,
129
+ read: resource.name,
130
+ ctx,
131
+ });
132
+ ctx.trace.addEvent('connection.read', {
133
+ connection: name,
134
+ read: resource.name,
135
+ tokens: estimateTokens(full),
136
+ });
137
+ rendered.push({
138
+ name: resource.name,
139
+ full,
140
+ shown: shownText(full, previous),
141
+ });
142
+ }
143
+ if (rendered.length === 0) {
144
+ return null;
145
+ }
146
+ const body = rendered.map((r) => `<read name="${r.name}">\n${r.shown}\n</read>`).join('\n');
147
+ const limit = Math.max(256, budget * CHARS_PER_TOKEN);
148
+ const text = `<connection name="${name}">\n${body.length > limit ? `${body.slice(0, limit)}\n…(truncated)` : body}\n</connection>`;
149
+ const previous = {
150
+ ...current.previous,
151
+ };
152
+ for (const r of rendered) {
153
+ previous[r.name] = r.full;
154
+ }
155
+ return {
156
+ items: [
157
+ createMessage(text, 'developer'),
158
+ ],
159
+ tokenCount: estimateTokens(text),
160
+ state: {
161
+ previous,
162
+ effects,
163
+ },
164
+ };
165
+ },
166
+ },
167
+ };
168
+ }
169
+ /** A view layer for every non-pool connection in `runtime`. */
170
+ export function connectionViewLayers(runtime) {
171
+ return runtime
172
+ .names()
173
+ .filter((name) => !runtime.config(name)?.pool)
174
+ .map((name) => connectionViewLayer(runtime, name));
175
+ }
176
+ //#endregion