@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,194 @@
1
+ /**
2
+ * Hydrates the JSON `verify` node (spec 37 § In JSON, spec 26) into a
3
+ * `StepVerify`. Operations written by name in `act` — and `call`/`wait` nodes
4
+ * without a `connection` — run on the subject. A list subject hydrates one
5
+ * verify per connection (ids `<id>.<name>`, each with `act` on its own
6
+ * subject), run in parallel under the node's id with the worst outcome.
7
+ */
8
+ import { frameworkCast, NoeticConfigError, verifyMatcherFromJson } from '@noetic-tools/types';
9
+ import { VerifyConfigErrorCode } from '@noetic-tools/types/verify';
10
+ import { compileExpression, compute, readInput } from '../expression/jsonata.js';
11
+ import { stepOutputsOf } from '../expression/step-outputs.js';
12
+ import { getDefaultRegistrar } from '../types/step-registrar.js';
13
+ import { documentHandle } from './workflow-connections.js';
14
+ import { documentScopeOf, hydrateStepList } from './workflow-hydrator.js';
15
+ //#endregion
16
+ //#region Constants
17
+ const OUTCOME_RANK = {
18
+ pass: 0,
19
+ unknown: 1,
20
+ partial: 2,
21
+ fail: 3,
22
+ };
23
+ //#endregion
24
+ //#region Helpers
25
+ function registered(built) {
26
+ getDefaultRegistrar().register(frameworkCast(built));
27
+ return built;
28
+ }
29
+ /**
30
+ * A JSON matcher in its TypeScript form.
31
+ *
32
+ * @throws `NoeticConfigError` `VERIFY_INVALID` when it names no sense or event.
33
+ */
34
+ function matcherOf(json, where) {
35
+ const matcher = verifyMatcherFromJson(json);
36
+ if (matcher) {
37
+ return matcher;
38
+ }
39
+ throw new NoeticConfigError({
40
+ code: VerifyConfigErrorCode.Invalid,
41
+ message: `${where} names no sense or event: ${JSON.stringify(json)}.`,
42
+ hint: 'Write a matcher as one sense key and its matcher text, e.g. { "net": "POST /api/orders 201", "count": 1 }.',
43
+ });
44
+ }
45
+ /**
46
+ * A connection the node names, bound to its manifest entry when the document declares one.
47
+ *
48
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for a name the manifest does not declare.
49
+ */
50
+ function documentTarget(name, where, ctx) {
51
+ if (!ctx.connections) {
52
+ return name;
53
+ }
54
+ const entry = ctx.connections[name];
55
+ if (entry) {
56
+ return documentHandle(name, entry, ctx.connectionUses?.get(name));
57
+ }
58
+ const declared = Object.keys(ctx.connections);
59
+ throw new NoeticConfigError({
60
+ code: 'CONNECTION_UNKNOWN',
61
+ message: `${where} uses connection '${name}', which the document's connections do not declare.`,
62
+ hint: `Use one of ${declared.join(', ') || '(none)'}, or add '${name}' to the document's "connections".`,
63
+ });
64
+ }
65
+ /** A subject expression, evaluated per run against the node's input. */
66
+ function expressionTarget(expr, where, ctx) {
67
+ const compiled = compileExpression(expr, `subject of ${where}`, ctx.expressionLimits);
68
+ return async (input, execCtx) => {
69
+ const name = await compute(compiled, readInput(input), {
70
+ steps: stepOutputsOf(execCtx, documentScopeOf(ctx)),
71
+ ...(ctx.fanOutItem === undefined
72
+ ? {}
73
+ : {
74
+ item: ctx.fanOutItem,
75
+ }),
76
+ });
77
+ if (typeof name !== 'string' || name.length === 0) {
78
+ throw new NoeticConfigError({
79
+ code: 'CONNECTION_INVALID',
80
+ message: `The subject expression of ${where} gave ${JSON.stringify(name)}, not a connection name.`,
81
+ hint: 'Write an expression that gives a declared connection name, e.g. { "$expr": "$item" } inside a fan-out.',
82
+ });
83
+ }
84
+ return documentTarget(name, where, ctx);
85
+ };
86
+ }
87
+ function hydrateOne(opts) {
88
+ const { node, id, subject, ctx } = opts;
89
+ const where = `verify node '${id}'`;
90
+ const built = {
91
+ kind: 'verify',
92
+ id,
93
+ subject: typeof subject === 'string'
94
+ ? documentTarget(subject, where, ctx)
95
+ : expressionTarget(subject.$expr, where, ctx),
96
+ act: frameworkCast(hydrateStepList({
97
+ list: node.act,
98
+ parentId: id,
99
+ ctx,
100
+ enclosing: subject,
101
+ })),
102
+ ...(node.expect === undefined
103
+ ? {}
104
+ : {
105
+ expect: node.expect.map((m, i) => matcherOf(m, `expect[${i}] of ${where}`)),
106
+ }),
107
+ ...(node.never === undefined
108
+ ? {}
109
+ : {
110
+ never: node.never.map((m, i) => matcherOf(m, `never[${i}] of ${where}`)),
111
+ }),
112
+ ...(node.claims === undefined
113
+ ? {}
114
+ : {
115
+ claims: node.claims,
116
+ }),
117
+ ...(node.constraints === undefined
118
+ ? {}
119
+ : {
120
+ constraints: node.constraints,
121
+ }),
122
+ ...(node.witnesses === undefined
123
+ ? {}
124
+ : {
125
+ witnesses: node.witnesses.map((w) => documentTarget(w, `witnesses of ${where}`, ctx)),
126
+ }),
127
+ ...(node.close === undefined
128
+ ? {}
129
+ : {
130
+ close: node.close,
131
+ }),
132
+ ...(node.intent === undefined
133
+ ? {}
134
+ : {
135
+ intent: node.intent,
136
+ }),
137
+ };
138
+ return registered(built);
139
+ }
140
+ /** One verify per listed connection, run in parallel; the worst outcome wins. */
141
+ function hydrateEach(node, names, ctx) {
142
+ const verifies = names.map((name) => ({
143
+ name,
144
+ step: hydrateOne({
145
+ node,
146
+ id: `${node.id}.${name}`,
147
+ subject: name,
148
+ ctx,
149
+ }),
150
+ }));
151
+ const built = {
152
+ kind: 'runCode',
153
+ id: node.id,
154
+ execute: async (input, execCtx) => {
155
+ const outputs = await Promise.all(verifies.map(async (v) => ({
156
+ name: v.name,
157
+ output: frameworkCast(await ctx.executeStep(v.step, input, execCtx)),
158
+ })));
159
+ const result = {
160
+ outcome: outputs.reduce((worst, o) => OUTCOME_RANK[o.output.outcome] > OUTCOME_RANK[worst] ? o.output.outcome : worst, 'pass'),
161
+ subjects: Object.fromEntries(outputs.map((o) => [
162
+ o.name,
163
+ o.output,
164
+ ])),
165
+ };
166
+ return frameworkCast(result);
167
+ },
168
+ };
169
+ return registered(built);
170
+ }
171
+ //#endregion
172
+ //#region Public API
173
+ /**
174
+ * Hydrates a JSON `verify` node.
175
+ *
176
+ * @public
177
+ * @throws `NoeticConfigError` `VERIFY_INVALID` for a matcher that names no sense or event;
178
+ * `CONNECTION_UNKNOWN` for a subject or witness the document's connections do not declare.
179
+ */
180
+ export function hydrateVerifyNode(node, ctx) {
181
+ if (node.kind !== 'verify') {
182
+ return frameworkCast(undefined);
183
+ }
184
+ if (Array.isArray(node.subject)) {
185
+ return hydrateEach(node, node.subject, ctx);
186
+ }
187
+ return hydrateOne({
188
+ node,
189
+ id: node.id,
190
+ subject: node.subject,
191
+ ctx,
192
+ });
193
+ }
194
+ //#endregion
@@ -1,5 +1,5 @@
1
1
  import type { ContextData, StorageAdapter } from '@noetic-tools/context';
2
- import type { Context, Step } from '@noetic-tools/types';
2
+ import type { Context, Step, Steps } from '@noetic-tools/types';
3
3
  import type { EmbedFn } from '../types/embed.js';
4
4
  export type Condition<I> = (input: I, ctx: Context) => Promise<boolean>;
5
5
  export interface WhenClause<TContext = ContextData, I = unknown, O = unknown> {
@@ -17,18 +17,20 @@ type Clause<TContext, I, O> = WhenClause<TContext, I, O> | OtherwiseClause<TCont
17
17
  *
18
18
  * @public
19
19
  * @param condition - Async predicate evaluated against the input and context.
20
- * @param step - Step to execute when the condition matches.
20
+ * @param step - Step to execute when the condition matches, or an array of steps run in sequence.
21
21
  * @returns A `WhenClause` for use in `semanticRoute`.
22
+ * @throws `NoeticConfigError` `EMPTY_STEP_ARRAY` or `INVALID_STEP_IN_ARRAY` for a bad array.
22
23
  */
23
- export declare function when<TContext = ContextData, I = unknown, O = unknown>(condition: Condition<I>, step: Step<TContext, I, O>): WhenClause<TContext, I, O>;
24
+ export declare function when<TContext = ContextData, I = unknown, O = unknown>(condition: Condition<I>, step: Steps<TContext, I, O>): WhenClause<TContext, I, O>;
24
25
  /**
25
26
  * Creates a fallback clause that always matches, used as the last clause in `semanticRoute`.
26
27
  *
27
28
  * @public
28
- * @param step - Step to execute when no prior `when` clause matches.
29
+ * @param step - Step to execute when no prior `when` clause matches, or an array of steps run in sequence.
29
30
  * @returns An `OtherwiseClause` for use in `semanticRoute`.
31
+ * @throws `NoeticConfigError` `EMPTY_STEP_ARRAY` or `INVALID_STEP_IN_ARRAY` for a bad array.
30
32
  */
31
- export declare function otherwise<TContext = ContextData, I = unknown, O = unknown>(step: Step<TContext, I, O>): OtherwiseClause<TContext, I, O>;
33
+ export declare function otherwise<TContext = ContextData, I = unknown, O = unknown>(step: Steps<TContext, I, O>): OtherwiseClause<TContext, I, O>;
32
34
  /**
33
35
  * Builds a route function from an ordered list of `when`/`otherwise` clauses.
34
36
  * Evaluates clauses sequentially, returning the first matching step or `null`.
@@ -1,6 +1,7 @@
1
1
  import { storageGetMany } from '@noetic-tools/context';
2
2
  import { DecideOutputError, isNoeticError, NoeticErrorImpl, trackUsage } from '@noetic-tools/types';
3
3
  import { z } from 'zod';
4
+ import { toStep } from '../builders/sequence.js';
4
5
  import { chargeSpent } from '../util/spent.js';
5
6
  import { cosineSimilarity } from './cosine-similarity.js';
6
7
  //#endregion
@@ -52,27 +53,29 @@ async function getLabelVectors(embed, labels, ref) {
52
53
  *
53
54
  * @public
54
55
  * @param condition - Async predicate evaluated against the input and context.
55
- * @param step - Step to execute when the condition matches.
56
+ * @param step - Step to execute when the condition matches, or an array of steps run in sequence.
56
57
  * @returns A `WhenClause` for use in `semanticRoute`.
58
+ * @throws `NoeticConfigError` `EMPTY_STEP_ARRAY` or `INVALID_STEP_IN_ARRAY` for a bad array.
57
59
  */
58
60
  export function when(condition, step) {
59
61
  return {
60
62
  kind: 'when',
61
63
  condition,
62
- step,
64
+ step: toStep(step),
63
65
  };
64
66
  }
65
67
  /**
66
68
  * Creates a fallback clause that always matches, used as the last clause in `semanticRoute`.
67
69
  *
68
70
  * @public
69
- * @param step - Step to execute when no prior `when` clause matches.
71
+ * @param step - Step to execute when no prior `when` clause matches, or an array of steps run in sequence.
70
72
  * @returns An `OtherwiseClause` for use in `semanticRoute`.
73
+ * @throws `NoeticConfigError` `EMPTY_STEP_ARRAY` or `INVALID_STEP_IN_ARRAY` for a bad array.
71
74
  */
72
75
  export function otherwise(step) {
73
76
  return {
74
77
  kind: 'otherwise',
75
- step,
78
+ step: toStep(step),
76
79
  };
77
80
  }
78
81
  //#endregion
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Blobs (spec 35 § Refs and blobs). A provider stores binary content in the
3
+ * artifact store and hands back `{ $blob: { uri, mimeType, bytes, sha256 } }`.
4
+ * The harness links every blob it sees in an output, read or event to the run
5
+ * that received it (retention counts per run), and checks that a blob going
6
+ * out to a connection is one the store holds.
7
+ */
8
+ import type { ArtifactStore, BlobRef } from '@noetic-tools/types';
9
+ /** Where blobs are being linked. */
10
+ export interface BlobLink {
11
+ readonly executionId: string;
12
+ /** The connection that produced them. */
13
+ readonly source: string;
14
+ readonly stepPath?: string;
15
+ }
16
+ /** What a sensitive blob shows as wherever the model would see it. */
17
+ export declare const WITHHELD_BLOB_TEXT = "[sensitive blob withheld]";
18
+ /** The blobs anywhere in `value`. */
19
+ export declare function findBlobs(value: unknown): ReadonlyArray<BlobRef>;
20
+ /** Links every blob in `value` to the run in `link`. */
21
+ export declare function attachBlobs(value: unknown, artifacts: ArtifactStore, link: BlobLink): Promise<void>;
22
+ /**
23
+ * Checks every blob in `args` is held by the artifact store and matches what it holds.
24
+ *
25
+ * @throws NoeticErrorImpl `connection_ref_invalid` for an unknown or altered blob.
26
+ */
27
+ export declare function checkBlobs(args: unknown, artifacts: ArtifactStore, connection: string): Promise<void>;
28
+ /**
29
+ * A copy of `value` with every blob the store marks sensitive (a stored session)
30
+ * replaced by `WITHHELD_BLOB_TEXT`: such blobs are never rendered to the model
31
+ * (spec 35 § Refs and blobs).
32
+ */
33
+ export declare function withholdSensitiveBlobs(value: unknown, artifacts: ArtifactStore): Promise<unknown>;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Blobs (spec 35 § Refs and blobs). A provider stores binary content in the
3
+ * artifact store and hands back `{ $blob: { uri, mimeType, bytes, sha256 } }`.
4
+ * The harness links every blob it sees in an output, read or event to the run
5
+ * that received it (retention counts per run), and checks that a blob going
6
+ * out to a connection is one the store holds.
7
+ */
8
+ import { isBlobRef } from '@noetic-tools/types';
9
+ import { refInvalidError } from './errors.js';
10
+ import { findDeep, mapDeep } from './values.js';
11
+ /** What a sensitive blob shows as wherever the model would see it. */
12
+ export const WITHHELD_BLOB_TEXT = '[sensitive blob withheld]';
13
+ //#endregion
14
+ //#region Public API
15
+ /** The blobs anywhere in `value`. */
16
+ export function findBlobs(value) {
17
+ return findDeep(value, isBlobRef).map((found) => found.value);
18
+ }
19
+ /** Links every blob in `value` to the run in `link`. */
20
+ export async function attachBlobs(value, artifacts, link) {
21
+ const seen = new Set();
22
+ for (const blob of findBlobs(value)) {
23
+ const uri = blob.$blob.uri;
24
+ if (seen.has(uri)) {
25
+ continue;
26
+ }
27
+ seen.add(uri);
28
+ await artifacts.attach(uri, {
29
+ executionId: link.executionId,
30
+ source: link.source,
31
+ stepPath: link.stepPath,
32
+ });
33
+ }
34
+ }
35
+ /**
36
+ * Checks every blob in `args` is held by the artifact store and matches what it holds.
37
+ *
38
+ * @throws NoeticErrorImpl `connection_ref_invalid` for an unknown or altered blob.
39
+ */
40
+ export async function checkBlobs(args, artifacts, connection) {
41
+ for (const blob of findBlobs(args)) {
42
+ const held = await artifacts.head(blob.$blob.uri);
43
+ if (!held) {
44
+ throw refInvalidError(connection, `blob '${blob.$blob.uri}' is not in the artifact store`);
45
+ }
46
+ if (held.sha256 !== blob.$blob.sha256 || held.bytes !== blob.$blob.bytes) {
47
+ throw refInvalidError(connection, `blob '${blob.$blob.uri}' does not match the stored content`);
48
+ }
49
+ }
50
+ }
51
+ /**
52
+ * A copy of `value` with every blob the store marks sensitive (a stored session)
53
+ * replaced by `WITHHELD_BLOB_TEXT`: such blobs are never rendered to the model
54
+ * (spec 35 § Refs and blobs).
55
+ */
56
+ export async function withholdSensitiveBlobs(value, artifacts) {
57
+ const sensitive = new Set();
58
+ for (const blob of findBlobs(value)) {
59
+ const uri = blob.$blob.uri;
60
+ if (sensitive.has(uri)) {
61
+ continue;
62
+ }
63
+ const held = await artifacts.head(uri);
64
+ if (held?.sensitive) {
65
+ sensitive.add(uri);
66
+ }
67
+ }
68
+ if (sensitive.size === 0) {
69
+ return value;
70
+ }
71
+ return mapDeep(value, (node) => isBlobRef(node.value) && sensitive.has(node.value.$blob.uri)
72
+ ? {
73
+ replace: WITHHELD_BLOB_TEXT,
74
+ }
75
+ : undefined);
76
+ }
77
+ //#endregion
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Five-field cron schedules (`minute hour day-of-month month day-of-week`) in
3
+ * an IANA timezone, for `cron()` (spec 35 § Triggers). Each field takes `*`,
4
+ * numbers, lists (`1,15`), ranges (`1-5`) and steps (`*\/15`, `0-30/10`).
5
+ * Day-of-week runs 0–6 from Sunday (7 is Sunday too). When both day fields
6
+ * are restricted, a time matches if either does, as in classic cron.
7
+ */
8
+ /** A parsed schedule. */
9
+ export interface CronSchedule {
10
+ readonly source: string;
11
+ readonly timezone: string;
12
+ readonly minutes: ReadonlySet<number>;
13
+ readonly hours: ReadonlySet<number>;
14
+ readonly days: ReadonlySet<number>;
15
+ readonly months: ReadonlySet<number>;
16
+ readonly weekdays: ReadonlySet<number>;
17
+ readonly anyDay: boolean;
18
+ readonly anyWeekday: boolean;
19
+ }
20
+ /**
21
+ * Parses a five-field cron schedule.
22
+ *
23
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed schedule or timezone.
24
+ */
25
+ export declare function parseCronSchedule(source: string, timezone?: string): CronSchedule;
26
+ /** Whether the minute starting at `ms` matches the schedule. */
27
+ export declare function cronMatches(schedule: CronSchedule, ms: number): boolean;
28
+ /**
29
+ * The first scheduled minute strictly after `afterMs`, as epoch ms.
30
+ * @returns `undefined` when nothing matches within four years.
31
+ */
32
+ export declare function nextCronRun(schedule: CronSchedule, afterMs: number): number | undefined;
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Five-field cron schedules (`minute hour day-of-month month day-of-week`) in
3
+ * an IANA timezone, for `cron()` (spec 35 § Triggers). Each field takes `*`,
4
+ * numbers, lists (`1,15`), ranges (`1-5`) and steps (`*\/15`, `0-30/10`).
5
+ * Day-of-week runs 0–6 from Sunday (7 is Sunday too). When both day fields
6
+ * are restricted, a time matches if either does, as in classic cron.
7
+ */
8
+ import { invalidConnectionError } from './errors.js';
9
+ //#endregion
10
+ //#region Constants
11
+ const MINUTE_FIELD = {
12
+ name: 'minute',
13
+ min: 0,
14
+ max: 59,
15
+ };
16
+ const HOUR_FIELD = {
17
+ name: 'hour',
18
+ min: 0,
19
+ max: 23,
20
+ };
21
+ const DAY_FIELD = {
22
+ name: 'day-of-month',
23
+ min: 1,
24
+ max: 31,
25
+ };
26
+ const MONTH_FIELD = {
27
+ name: 'month',
28
+ min: 1,
29
+ max: 12,
30
+ };
31
+ const WEEKDAY_FIELD = {
32
+ name: 'day-of-week',
33
+ min: 0,
34
+ max: 7,
35
+ };
36
+ const FIELD_COUNT = 5;
37
+ const WEEKDAYS = {
38
+ Sun: 0,
39
+ Mon: 1,
40
+ Tue: 2,
41
+ Wed: 3,
42
+ Thu: 4,
43
+ Fri: 5,
44
+ Sat: 6,
45
+ };
46
+ const MINUTE_MS = 6e4;
47
+ /** How far ahead `nextRun` searches before giving up (a little over four years, for Feb 29). */
48
+ const SEARCH_LIMIT_MS = 4 * 366 * 24 * 3600e3;
49
+ //#endregion
50
+ //#region Helpers
51
+ function badSchedule(source, detail) {
52
+ return invalidConnectionError(`cron schedule '${source}' is invalid: ${detail}.`, "Use five fields — minute hour day-of-month month day-of-week — e.g. '0 8 * * 1-5'.");
53
+ }
54
+ function parseNumber(text, field, source) {
55
+ if (!/^\d+$/.test(text)) {
56
+ throw badSchedule(source, `'${text}' in the ${field.name} field is not a number`);
57
+ }
58
+ const value = Number(text);
59
+ if (value < field.min || value > field.max) {
60
+ throw badSchedule(source, `${value} is outside ${field.min}-${field.max} for ${field.name}`);
61
+ }
62
+ return value;
63
+ }
64
+ function parsePart(part, field, source) {
65
+ const [rangeText = '', stepText] = part.split('/');
66
+ const step = stepText === undefined
67
+ ? 1
68
+ : parseNumber(stepText, {
69
+ ...field,
70
+ min: 1,
71
+ max: field.max,
72
+ }, source);
73
+ let start = field.min;
74
+ let end = field.max;
75
+ if (rangeText !== '*') {
76
+ const [from = '', to] = rangeText.split('-');
77
+ start = parseNumber(from, field, source);
78
+ end =
79
+ to === undefined
80
+ ? stepText === undefined
81
+ ? start
82
+ : field.max
83
+ : parseNumber(to, field, source);
84
+ }
85
+ if (start > end) {
86
+ throw badSchedule(source, `range ${start}-${end} in ${field.name} runs backwards`);
87
+ }
88
+ const values = [];
89
+ for (let v = start; v <= end; v += step) {
90
+ values.push(v);
91
+ }
92
+ return values;
93
+ }
94
+ function parseField(text, field, source) {
95
+ const values = new Set();
96
+ for (const part of text.split(',')) {
97
+ for (const value of parsePart(part, field, source)) {
98
+ values.add(field.name === 'day-of-week' && value === 7 ? 0 : value);
99
+ }
100
+ }
101
+ return values;
102
+ }
103
+ const formatters = new Map();
104
+ function formatterFor(timezone) {
105
+ const cached = formatters.get(timezone);
106
+ if (cached) {
107
+ return cached;
108
+ }
109
+ const formatter = new Intl.DateTimeFormat('en-US', {
110
+ timeZone: timezone,
111
+ hourCycle: 'h23',
112
+ minute: 'numeric',
113
+ hour: 'numeric',
114
+ day: 'numeric',
115
+ month: 'numeric',
116
+ weekday: 'short',
117
+ });
118
+ formatters.set(timezone, formatter);
119
+ return formatter;
120
+ }
121
+ function zonedParts(ms, timezone) {
122
+ const parts = {};
123
+ for (const part of formatterFor(timezone).formatToParts(ms)) {
124
+ parts[part.type] = part.value;
125
+ }
126
+ return {
127
+ minute: Number(parts.minute),
128
+ hour: Number(parts.hour),
129
+ day: Number(parts.day),
130
+ month: Number(parts.month),
131
+ weekday: WEEKDAYS[parts.weekday ?? 'Sun'] ?? 0,
132
+ };
133
+ }
134
+ function dayMatches(schedule, parts) {
135
+ const dayOk = schedule.days.has(parts.day);
136
+ const weekdayOk = schedule.weekdays.has(parts.weekday);
137
+ if (schedule.anyDay) {
138
+ return weekdayOk;
139
+ }
140
+ if (schedule.anyWeekday) {
141
+ return dayOk;
142
+ }
143
+ return dayOk || weekdayOk;
144
+ }
145
+ /** Minutes to skip from a non-matching time: to the next hour or the next day where possible. */
146
+ function skipMinutes(schedule, parts) {
147
+ if (!schedule.months.has(parts.month) || !dayMatches(schedule, parts)) {
148
+ return (23 - parts.hour) * 60 + (60 - parts.minute);
149
+ }
150
+ if (!schedule.hours.has(parts.hour)) {
151
+ return 60 - parts.minute;
152
+ }
153
+ return 1;
154
+ }
155
+ //#endregion
156
+ //#region Public API
157
+ /**
158
+ * Parses a five-field cron schedule.
159
+ *
160
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed schedule or timezone.
161
+ */
162
+ export function parseCronSchedule(source, timezone = 'UTC') {
163
+ const fields = source.trim().split(/\s+/);
164
+ if (fields.length !== FIELD_COUNT) {
165
+ throw badSchedule(source, `expected 5 fields, got ${fields.length}`);
166
+ }
167
+ try {
168
+ formatterFor(timezone);
169
+ }
170
+ catch {
171
+ throw invalidConnectionError(`cron timezone '${timezone}' is not a known IANA timezone.`, "Use a timezone such as 'UTC' or 'America/New_York'.");
172
+ }
173
+ const [minute = '', hour = '', day = '', month = '', weekday = ''] = fields;
174
+ return {
175
+ source,
176
+ timezone,
177
+ minutes: parseField(minute, MINUTE_FIELD, source),
178
+ hours: parseField(hour, HOUR_FIELD, source),
179
+ days: parseField(day, DAY_FIELD, source),
180
+ months: parseField(month, MONTH_FIELD, source),
181
+ weekdays: parseField(weekday, WEEKDAY_FIELD, source),
182
+ anyDay: day === '*',
183
+ anyWeekday: weekday === '*',
184
+ };
185
+ }
186
+ /** Whether the minute starting at `ms` matches the schedule. */
187
+ export function cronMatches(schedule, ms) {
188
+ const parts = zonedParts(ms, schedule.timezone);
189
+ return (schedule.minutes.has(parts.minute) &&
190
+ schedule.hours.has(parts.hour) &&
191
+ schedule.months.has(parts.month) &&
192
+ dayMatches(schedule, parts));
193
+ }
194
+ /**
195
+ * The first scheduled minute strictly after `afterMs`, as epoch ms.
196
+ * @returns `undefined` when nothing matches within four years.
197
+ */
198
+ export function nextCronRun(schedule, afterMs) {
199
+ let ms = Math.floor(afterMs / MINUTE_MS) * MINUTE_MS + MINUTE_MS;
200
+ const limit = afterMs + SEARCH_LIMIT_MS;
201
+ while (ms <= limit) {
202
+ const parts = zonedParts(ms, schedule.timezone);
203
+ if (schedule.minutes.has(parts.minute) &&
204
+ schedule.hours.has(parts.hour) &&
205
+ schedule.months.has(parts.month) &&
206
+ dayMatches(schedule, parts)) {
207
+ return ms;
208
+ }
209
+ ms += skipMinutes(schedule, parts) * MINUTE_MS;
210
+ }
211
+ return undefined;
212
+ }
213
+ //#endregion
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Durability (spec 35 § Durability): idempotency keys, the pending ledger
3
+ * entry a `call` or `wait` writes before it reaches a server, and what a
4
+ * resumed run does with a connection that was replaced.
5
+ *
6
+ * If a connection's identity instance changed, results recorded against it
7
+ * describe a world that is gone. Its determinism decides, following OVP's
8
+ * resume strategy:
9
+ *
10
+ * | `replayPrefix` | Resume |
11
+ * |---|---|
12
+ * | `'free'` | Discard the ledger from the first step that used it; run live. |
13
+ * | `'costly'`, with `reset` | Reset the connection, then the same. |
14
+ * | `'unsafe'` | Refuse until `harness.restore(id, { rerun: [name] })`. |
15
+ *
16
+ * An epoch change alone (a hot reload) keeps refs and results. A connection
17
+ * that declares no determinism is treated as `'unsafe'`.
18
+ */
19
+ import type { ConnectionIdentity, ConnectionLease, Determinism } from '@noetic-tools/types';
20
+ /**
21
+ * What a `call` or `wait` records before it reaches a server, so a resumed
22
+ * step against the same identity picks up where it was.
23
+ */
24
+ export interface PendingConnectionEntry {
25
+ /** The call's idempotency key. */
26
+ readonly key: string;
27
+ readonly connection: string;
28
+ readonly identity: ConnectionIdentity;
29
+ /** The long operation, once the server returned one. */
30
+ readonly taskId?: string;
31
+ readonly lease?: ConnectionLease;
32
+ /** For waits: the cursor listening started from. */
33
+ readonly cursor?: string | null;
34
+ /** For waits: epoch ms the wait gives up. */
35
+ readonly deadline?: number;
36
+ }
37
+ /** What a resumed run does about one connection. */
38
+ export type ResumeDecision =
39
+ /** Same instance: replay recorded results. */
40
+ 'keep'
41
+ /** Replaced: discard the ledger from the first step that used it and run live. */
42
+ | 'discard'
43
+ /** Replaced: reset the connection, then discard. */
44
+ | 'reset'
45
+ /** Replaced and unsafe to drive again: stop with `connection_resume_refused`. */
46
+ | 'refuse';
47
+ /** The idempotency key of a step's call: the run and the step's ledger key. */
48
+ export declare function stepIdempotencyKey(executionId: string, ledgerKey: string): string;
49
+ /** The idempotency key of a model tool call: the turn's execution and the tool call id. */
50
+ export declare function toolIdempotencyKey(executionId: string, toolCallId: string): string;
51
+ /** Whether `current` is the same thing `recorded` described (an epoch change alone keeps it). */
52
+ export declare function sameInstance(recorded: ConnectionIdentity, current: ConnectionIdentity): boolean;
53
+ /**
54
+ * Decides what a resumed run does about a connection whose results were
55
+ * recorded against `recorded`.
56
+ */
57
+ export declare function resumeDecision(params: {
58
+ readonly recorded: ConnectionIdentity;
59
+ readonly current: ConnectionIdentity;
60
+ readonly determinism: Determinism | undefined;
61
+ /** `harness.restore(id, { rerun })` named this connection. */
62
+ readonly rerunAllowed: boolean;
63
+ /** The connection can be reset. */
64
+ readonly canReset: boolean;
65
+ }): ResumeDecision;