@fluenterp/runtime 0.1.0

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.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # `@fluenterp/runtime`
2
+
3
+ The public contract between Fluent and project-owned document agents. It provides
4
+ the declaration helpers, manifest schemas, validated tool/process dispatch, and
5
+ runtime-image version check used by both sides of a project deployment.
6
+
7
+ ```ts
8
+ import {
9
+ createRuntime,
10
+ defineDocument,
11
+ defineProcess,
12
+ defineRecord,
13
+ field,
14
+ } from "@fluenterp/runtime";
15
+ ```
16
+
17
+ This package deliberately contains no credentials, customer document
18
+ definitions, connection code, privileged Fluent API clients, or private service
19
+ addresses. Project authentication remains at the Fluent proxy, and the matching
20
+ OCI base image remains in private ECR.
21
+
22
+ ## Repeatable lines
23
+
24
+ Records may declare one level of typed collections. Fluent extracts and renders
25
+ the rows, runs each grounded item field through its project resolver, and blocks
26
+ Process until required values are complete.
27
+
28
+ ```ts
29
+ const purchaseOrder = defineRecord({
30
+ type: "purchase-order",
31
+ title: "Purchase order",
32
+ fields: {
33
+ items: field.collection({
34
+ label: "Lines",
35
+ requiredForProcess: true,
36
+ fields: {
37
+ partNumberRaw: field.text({ label: "Part number, as printed" }),
38
+ quantity: field.number({
39
+ label: "Quantity",
40
+ writeTo: "PODetail.OrderQty",
41
+ requiredForProcess: true,
42
+ }),
43
+ part: field.grounded({
44
+ label: "Verified part and purchase UOM",
45
+ resolver: "part",
46
+ groundFrom: "partNumberRaw",
47
+ }),
48
+ },
49
+ }),
50
+ },
51
+ });
52
+ ```
53
+
54
+ A terminal resolver may verify a compound key by publishing
55
+ `terminalArguments`, for example `{ partNum: "partNum", uom: "uom" }`. The keys
56
+ are terminal-tool arguments and the values are properties on a displayed search
57
+ candidate. The project still re-fetches and verifies both values before the
58
+ result is accepted. Process repeats that terminal verification for every
59
+ grounded field and replaces browser-supplied objects with the canonical verified
60
+ results before customer write code runs.
61
+
62
+ ## Release model
63
+
64
+ The package and OCI image use the same version. A project declares an exact npm
65
+ version, and Fluent builds it on the immutable image tag with that version. The
66
+ server calls `assertRuntimeVersion()` at startup so package/image skew fails
67
+ before it can process a document.
68
+
69
+ Before the first release, let the pull request apply the `dev` Pulumi stack and
70
+ let the merge apply `prod`. The authorized `Infra (Prod)` workflow then builds
71
+ the image once and pushes the same immutable version to
72
+ `fluent-runtime-dev` and `fluent-runtime-prod`.
73
+
74
+ ### One-time npm bootstrap
75
+
76
+ npm requires a package to exist before it can trust a GitHub Actions publisher.
77
+ After the change is on `main`, build and inspect the exact public artifact:
78
+
79
+ ```bash
80
+ pnpm install --frozen-lockfile
81
+ pnpm --filter @fluenterp/runtime typecheck
82
+ pnpm --filter @fluenterp/runtime test --runInBand
83
+ pnpm --filter @fluenterp/runtime build
84
+ npm pack ./packages/ts/runtime
85
+ npm publish ./fluenterp-runtime-0.1.0.tgz --access public
86
+ ```
87
+
88
+ The first publish is interactive and 2FA-protected. Do not create an `NPM_TOKEN`
89
+ GitHub secret. On the new package page, configure **Settings → Trusted Publisher**:
90
+
91
+ - Organization or user: `tcpmia`
92
+ - Repository: `fluent`
93
+ - Workflow filename: `publish-runtime.yml`
94
+ - Allowed action: `npm publish`
95
+ - Environment: leave blank
96
+
97
+ Then set publishing access to require 2FA and disallow tokens. All later npm
98
+ publishes use short-lived GitHub OIDC credentials.
99
+
100
+ ### Publish a version
101
+
102
+ Update `package.json` and `src/version.ts` to the same semantic version and merge
103
+ to `main`. Wait for `Infra (Prod)` to publish that image version to both private
104
+ ECR repositories, then tag the merge commit:
105
+
106
+ ```bash
107
+ git tag runtime-v0.1.0
108
+ git push origin runtime-v0.1.0
109
+ ```
110
+
111
+ The `Publish Fluent Runtime` workflow checks the matching version, tests and
112
+ packs the npm artifact, imports it from a locally built image, and publishes the
113
+ public package. Its manual trigger is build-only unless `publish` is explicitly
114
+ selected. AWS publishing stays in the existing branch-restricted deployment
115
+ workflow; the npm tag workflow receives no AWS credentials.
@@ -0,0 +1,488 @@
1
+ import { z } from 'zod';
2
+
3
+ /** How a document field's value is produced. */
4
+ type Strategy = "extract" | "ground" | "choose" | "reconcile" | "revise" | "computed";
5
+ type FieldKind = "text" | "number" | "collection";
6
+ interface FieldSpec<T extends z.ZodType = z.ZodType> {
7
+ schema: T;
8
+ /** Defaults to text for records authored before typed fields were introduced. */
9
+ kind?: FieldKind;
10
+ label: string;
11
+ /** Native ERP destination as `Table.Column`. Omit for Fluent-only fields. */
12
+ writeTo?: string;
13
+ /** Resolver that produces this field when `strategy` is `ground`. */
14
+ resolver?: string;
15
+ /** Field whose value is the resolver's input. */
16
+ groundFrom?: string;
17
+ strategy: Strategy;
18
+ llmHidden?: boolean;
19
+ description?: string;
20
+ /** Missing values block Process but never prevent a review draft from existing. */
21
+ requiredForProcess?: boolean;
22
+ /** One-level item shape when kind is collection. */
23
+ fields?: Record<string, FieldSpec>;
24
+ }
25
+ interface RecordDefinition {
26
+ type: string;
27
+ title: string;
28
+ fields: Record<string, FieldSpec>;
29
+ zod: z.ZodType<Record<string, unknown>>;
30
+ }
31
+ declare function defineRecord(input: {
32
+ type: string;
33
+ title: string;
34
+ fields: Record<string, FieldSpec>;
35
+ }): RecordDefinition;
36
+ /** Small constructors that keep a record definition readable. */
37
+ declare const field: {
38
+ text(spec: Omit<FieldSpec<z.ZodNullable<z.ZodString>>, "schema" | "kind" | "strategy" | "fields"> & {
39
+ strategy?: Strategy;
40
+ }): {
41
+ description?: string | undefined;
42
+ label: string;
43
+ writeTo?: string | undefined;
44
+ resolver?: string | undefined;
45
+ groundFrom?: string | undefined;
46
+ llmHidden?: boolean | undefined;
47
+ requiredForProcess?: boolean | undefined;
48
+ strategy: Strategy;
49
+ schema: z.ZodNullable<z.ZodString>;
50
+ kind: "text";
51
+ };
52
+ number(spec: Omit<FieldSpec<z.ZodNullable<z.ZodNumber>>, "schema" | "kind" | "strategy" | "fields"> & {
53
+ strategy?: Strategy;
54
+ }): {
55
+ description?: string | undefined;
56
+ label: string;
57
+ writeTo?: string | undefined;
58
+ resolver?: string | undefined;
59
+ groundFrom?: string | undefined;
60
+ llmHidden?: boolean | undefined;
61
+ requiredForProcess?: boolean | undefined;
62
+ strategy: Strategy;
63
+ schema: z.ZodNullable<z.ZodNumber>;
64
+ kind: "number";
65
+ };
66
+ grounded(spec: {
67
+ label: string;
68
+ resolver: string;
69
+ groundFrom: string;
70
+ writeTo?: string;
71
+ description?: string;
72
+ }): {
73
+ label: string;
74
+ resolver: string;
75
+ groundFrom: string;
76
+ writeTo?: string;
77
+ description?: string;
78
+ schema: z.ZodNullable<z.ZodUnknown>;
79
+ kind: "text";
80
+ strategy: "ground";
81
+ requiredForProcess: boolean;
82
+ };
83
+ collection(spec: {
84
+ label: string;
85
+ fields: Record<string, FieldSpec>;
86
+ description?: string;
87
+ requiredForProcess?: boolean;
88
+ }): {
89
+ label: string;
90
+ fields: Record<string, FieldSpec>;
91
+ description?: string;
92
+ requiredForProcess?: boolean;
93
+ schema: z.ZodArray<z.ZodObject<{
94
+ [x: string]: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
95
+ }, z.core.$strip>>;
96
+ kind: "collection";
97
+ strategy: "extract";
98
+ };
99
+ };
100
+ declare function extractableRecordFields(record: RecordDefinition): [string, FieldSpec][];
101
+ declare function groundedRecordFields(record: RecordDefinition): [string, FieldSpec][];
102
+
103
+ interface SearchTool<A extends z.ZodType = z.ZodType> {
104
+ kind: "search";
105
+ name: string;
106
+ description: string;
107
+ args: A;
108
+ search: (args: z.infer<A>) => Promise<unknown[]>;
109
+ }
110
+ type VerifyResult<V> = {
111
+ ok: true;
112
+ value: V;
113
+ } | {
114
+ ok: false;
115
+ reason: string;
116
+ };
117
+ interface TerminalTool<A extends z.ZodType = z.ZodType, V = unknown> {
118
+ kind: "terminal";
119
+ name: string;
120
+ description: string;
121
+ args: A;
122
+ verify: (args: z.infer<A>) => Promise<VerifyResult<V>>;
123
+ }
124
+ type AnyTool = SearchTool | TerminalTool;
125
+ declare function defineSearchTool<A extends z.ZodType>(spec: Omit<SearchTool<A>, "kind">): SearchTool<A>;
126
+ declare function defineTerminalTool<A extends z.ZodType, V>(spec: Omit<TerminalTool<A, V>, "kind">): TerminalTool<A, V>;
127
+
128
+ interface ResolverPresentation {
129
+ searchArgument: string;
130
+ resultKey: string;
131
+ resultLabel: string;
132
+ resultMeta: string[];
133
+ terminalArgument: string;
134
+ /** Tool argument -> candidate property for verified multi-key selections. */
135
+ terminalArguments?: Record<string, string>;
136
+ }
137
+ interface Subagent {
138
+ name: string;
139
+ instructions: string;
140
+ tools: AnyTool[];
141
+ result: z.ZodType;
142
+ searchTools: SearchTool[];
143
+ terminal: TerminalTool;
144
+ presentation: ResolverPresentation;
145
+ }
146
+ declare function defineSubagent(spec: {
147
+ name: string;
148
+ instructions: string;
149
+ tools: AnyTool[];
150
+ result: z.ZodType;
151
+ presentation: ResolverPresentation;
152
+ }): Subagent;
153
+
154
+ type Dataset = Record<string, Record<string, unknown>[]>;
155
+ interface ProcessDefinition {
156
+ record: RecordDefinition;
157
+ run: (values: Record<string, unknown>) => Promise<{
158
+ key: string;
159
+ }>;
160
+ }
161
+ declare function defineProcess(record: RecordDefinition, run: (values: Record<string, unknown>) => Promise<{
162
+ key: string;
163
+ }>): ProcessDefinition;
164
+ declare function buildDataset(record: RecordDefinition, values: Record<string, unknown>, keys?: Record<string, Record<string, unknown>>): Dataset;
165
+ declare function unmappedFields(record: RecordDefinition): string[];
166
+ declare function commitBlockers(record: RecordDefinition, values: Record<string, unknown>): string[];
167
+
168
+ interface DocumentDefinition {
169
+ type: string;
170
+ title: string;
171
+ record: RecordDefinition;
172
+ subagents: Record<string, Subagent>;
173
+ process: ProcessDefinition;
174
+ }
175
+ declare function defineDocument(spec: {
176
+ record: RecordDefinition;
177
+ subagents: Subagent[];
178
+ process: ProcessDefinition;
179
+ }): DocumentDefinition;
180
+
181
+ declare const ToolManifestSchema: z.ZodObject<{
182
+ name: z.ZodString;
183
+ kind: z.ZodEnum<{
184
+ search: "search";
185
+ terminal: "terminal";
186
+ }>;
187
+ description: z.ZodString;
188
+ parameters: z.ZodUnknown;
189
+ }, z.core.$strip>;
190
+ declare const ResolverPresentationSchema: z.ZodObject<{
191
+ searchArgument: z.ZodString;
192
+ resultKey: z.ZodString;
193
+ resultLabel: z.ZodString;
194
+ resultMeta: z.ZodArray<z.ZodString>;
195
+ terminalArgument: z.ZodString;
196
+ terminalArguments: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
197
+ }, z.core.$strip>;
198
+ declare const ResolverManifestSchema: z.ZodObject<{
199
+ name: z.ZodString;
200
+ instructions: z.ZodString;
201
+ result: z.ZodUnknown;
202
+ tools: z.ZodArray<z.ZodObject<{
203
+ name: z.ZodString;
204
+ kind: z.ZodEnum<{
205
+ search: "search";
206
+ terminal: "terminal";
207
+ }>;
208
+ description: z.ZodString;
209
+ parameters: z.ZodUnknown;
210
+ }, z.core.$strip>>;
211
+ terminal: z.ZodString;
212
+ presentation: z.ZodObject<{
213
+ searchArgument: z.ZodString;
214
+ resultKey: z.ZodString;
215
+ resultLabel: z.ZodString;
216
+ resultMeta: z.ZodArray<z.ZodString>;
217
+ terminalArgument: z.ZodString;
218
+ terminalArguments: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
219
+ }, z.core.$strip>;
220
+ }, z.core.$strip>;
221
+ declare const ItemFieldManifestSchema: z.ZodObject<{
222
+ name: z.ZodString;
223
+ label: z.ZodString;
224
+ strategy: z.ZodEnum<{
225
+ extract: "extract";
226
+ ground: "ground";
227
+ choose: "choose";
228
+ reconcile: "reconcile";
229
+ revise: "revise";
230
+ computed: "computed";
231
+ }>;
232
+ description: z.ZodNullable<z.ZodString>;
233
+ writeTo: z.ZodNullable<z.ZodString>;
234
+ resolver: z.ZodNullable<z.ZodString>;
235
+ groundFrom: z.ZodNullable<z.ZodString>;
236
+ llmHidden: z.ZodBoolean;
237
+ requiredForProcess: z.ZodDefault<z.ZodBoolean>;
238
+ kind: z.ZodDefault<z.ZodEnum<{
239
+ number: "number";
240
+ text: "text";
241
+ }>>;
242
+ }, z.core.$strip>;
243
+ declare const FieldManifestSchema: z.ZodObject<{
244
+ name: z.ZodString;
245
+ label: z.ZodString;
246
+ kind: z.ZodDefault<z.ZodEnum<{
247
+ number: "number";
248
+ text: "text";
249
+ collection: "collection";
250
+ }>>;
251
+ strategy: z.ZodEnum<{
252
+ extract: "extract";
253
+ ground: "ground";
254
+ choose: "choose";
255
+ reconcile: "reconcile";
256
+ revise: "revise";
257
+ computed: "computed";
258
+ }>;
259
+ description: z.ZodNullable<z.ZodString>;
260
+ writeTo: z.ZodNullable<z.ZodString>;
261
+ resolver: z.ZodNullable<z.ZodString>;
262
+ groundFrom: z.ZodNullable<z.ZodString>;
263
+ llmHidden: z.ZodBoolean;
264
+ requiredForProcess: z.ZodDefault<z.ZodBoolean>;
265
+ fields: z.ZodDefault<z.ZodNullable<z.ZodArray<z.ZodObject<{
266
+ name: z.ZodString;
267
+ label: z.ZodString;
268
+ strategy: z.ZodEnum<{
269
+ extract: "extract";
270
+ ground: "ground";
271
+ choose: "choose";
272
+ reconcile: "reconcile";
273
+ revise: "revise";
274
+ computed: "computed";
275
+ }>;
276
+ description: z.ZodNullable<z.ZodString>;
277
+ writeTo: z.ZodNullable<z.ZodString>;
278
+ resolver: z.ZodNullable<z.ZodString>;
279
+ groundFrom: z.ZodNullable<z.ZodString>;
280
+ llmHidden: z.ZodBoolean;
281
+ requiredForProcess: z.ZodDefault<z.ZodBoolean>;
282
+ kind: z.ZodDefault<z.ZodEnum<{
283
+ number: "number";
284
+ text: "text";
285
+ }>>;
286
+ }, z.core.$strip>>>>;
287
+ }, z.core.$strip>;
288
+ declare const DocumentManifestSchema: z.ZodObject<{
289
+ type: z.ZodString;
290
+ title: z.ZodString;
291
+ fields: z.ZodArray<z.ZodObject<{
292
+ name: z.ZodString;
293
+ label: z.ZodString;
294
+ kind: z.ZodDefault<z.ZodEnum<{
295
+ number: "number";
296
+ text: "text";
297
+ collection: "collection";
298
+ }>>;
299
+ strategy: z.ZodEnum<{
300
+ extract: "extract";
301
+ ground: "ground";
302
+ choose: "choose";
303
+ reconcile: "reconcile";
304
+ revise: "revise";
305
+ computed: "computed";
306
+ }>;
307
+ description: z.ZodNullable<z.ZodString>;
308
+ writeTo: z.ZodNullable<z.ZodString>;
309
+ resolver: z.ZodNullable<z.ZodString>;
310
+ groundFrom: z.ZodNullable<z.ZodString>;
311
+ llmHidden: z.ZodBoolean;
312
+ requiredForProcess: z.ZodDefault<z.ZodBoolean>;
313
+ fields: z.ZodDefault<z.ZodNullable<z.ZodArray<z.ZodObject<{
314
+ name: z.ZodString;
315
+ label: z.ZodString;
316
+ strategy: z.ZodEnum<{
317
+ extract: "extract";
318
+ ground: "ground";
319
+ choose: "choose";
320
+ reconcile: "reconcile";
321
+ revise: "revise";
322
+ computed: "computed";
323
+ }>;
324
+ description: z.ZodNullable<z.ZodString>;
325
+ writeTo: z.ZodNullable<z.ZodString>;
326
+ resolver: z.ZodNullable<z.ZodString>;
327
+ groundFrom: z.ZodNullable<z.ZodString>;
328
+ llmHidden: z.ZodBoolean;
329
+ requiredForProcess: z.ZodDefault<z.ZodBoolean>;
330
+ kind: z.ZodDefault<z.ZodEnum<{
331
+ number: "number";
332
+ text: "text";
333
+ }>>;
334
+ }, z.core.$strip>>>>;
335
+ }, z.core.$strip>>;
336
+ resolvers: z.ZodArray<z.ZodObject<{
337
+ name: z.ZodString;
338
+ instructions: z.ZodString;
339
+ result: z.ZodUnknown;
340
+ tools: z.ZodArray<z.ZodObject<{
341
+ name: z.ZodString;
342
+ kind: z.ZodEnum<{
343
+ search: "search";
344
+ terminal: "terminal";
345
+ }>;
346
+ description: z.ZodString;
347
+ parameters: z.ZodUnknown;
348
+ }, z.core.$strip>>;
349
+ terminal: z.ZodString;
350
+ presentation: z.ZodObject<{
351
+ searchArgument: z.ZodString;
352
+ resultKey: z.ZodString;
353
+ resultLabel: z.ZodString;
354
+ resultMeta: z.ZodArray<z.ZodString>;
355
+ terminalArgument: z.ZodString;
356
+ terminalArguments: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
357
+ }, z.core.$strip>;
358
+ }, z.core.$strip>>;
359
+ }, z.core.$strip>;
360
+ declare const ManifestSchema: z.ZodObject<{
361
+ version: z.ZodLiteral<1>;
362
+ documents: z.ZodArray<z.ZodObject<{
363
+ type: z.ZodString;
364
+ title: z.ZodString;
365
+ fields: z.ZodArray<z.ZodObject<{
366
+ name: z.ZodString;
367
+ label: z.ZodString;
368
+ kind: z.ZodDefault<z.ZodEnum<{
369
+ number: "number";
370
+ text: "text";
371
+ collection: "collection";
372
+ }>>;
373
+ strategy: z.ZodEnum<{
374
+ extract: "extract";
375
+ ground: "ground";
376
+ choose: "choose";
377
+ reconcile: "reconcile";
378
+ revise: "revise";
379
+ computed: "computed";
380
+ }>;
381
+ description: z.ZodNullable<z.ZodString>;
382
+ writeTo: z.ZodNullable<z.ZodString>;
383
+ resolver: z.ZodNullable<z.ZodString>;
384
+ groundFrom: z.ZodNullable<z.ZodString>;
385
+ llmHidden: z.ZodBoolean;
386
+ requiredForProcess: z.ZodDefault<z.ZodBoolean>;
387
+ fields: z.ZodDefault<z.ZodNullable<z.ZodArray<z.ZodObject<{
388
+ name: z.ZodString;
389
+ label: z.ZodString;
390
+ strategy: z.ZodEnum<{
391
+ extract: "extract";
392
+ ground: "ground";
393
+ choose: "choose";
394
+ reconcile: "reconcile";
395
+ revise: "revise";
396
+ computed: "computed";
397
+ }>;
398
+ description: z.ZodNullable<z.ZodString>;
399
+ writeTo: z.ZodNullable<z.ZodString>;
400
+ resolver: z.ZodNullable<z.ZodString>;
401
+ groundFrom: z.ZodNullable<z.ZodString>;
402
+ llmHidden: z.ZodBoolean;
403
+ requiredForProcess: z.ZodDefault<z.ZodBoolean>;
404
+ kind: z.ZodDefault<z.ZodEnum<{
405
+ number: "number";
406
+ text: "text";
407
+ }>>;
408
+ }, z.core.$strip>>>>;
409
+ }, z.core.$strip>>;
410
+ resolvers: z.ZodArray<z.ZodObject<{
411
+ name: z.ZodString;
412
+ instructions: z.ZodString;
413
+ result: z.ZodUnknown;
414
+ tools: z.ZodArray<z.ZodObject<{
415
+ name: z.ZodString;
416
+ kind: z.ZodEnum<{
417
+ search: "search";
418
+ terminal: "terminal";
419
+ }>;
420
+ description: z.ZodString;
421
+ parameters: z.ZodUnknown;
422
+ }, z.core.$strip>>;
423
+ terminal: z.ZodString;
424
+ presentation: z.ZodObject<{
425
+ searchArgument: z.ZodString;
426
+ resultKey: z.ZodString;
427
+ resultLabel: z.ZodString;
428
+ resultMeta: z.ZodArray<z.ZodString>;
429
+ terminalArgument: z.ZodString;
430
+ terminalArguments: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
431
+ }, z.core.$strip>;
432
+ }, z.core.$strip>>;
433
+ }, z.core.$strip>>;
434
+ }, z.core.$strip>;
435
+ type ToolManifest = z.infer<typeof ToolManifestSchema>;
436
+ type ResolverPresentationManifest = z.infer<typeof ResolverPresentationSchema>;
437
+ type ResolverManifest = z.infer<typeof ResolverManifestSchema>;
438
+ type FieldManifest = z.infer<typeof FieldManifestSchema>;
439
+ type ItemFieldManifest = z.infer<typeof ItemFieldManifestSchema>;
440
+ type DocumentManifest = z.infer<typeof DocumentManifestSchema>;
441
+ type Manifest = z.infer<typeof ManifestSchema>;
442
+ declare function buildManifest(documents: Record<string, DocumentDefinition>): Manifest;
443
+ declare function extractableFields(document: DocumentManifest): FieldManifest[];
444
+ declare function resolutionOrder(document: DocumentManifest): FieldManifest[];
445
+ declare function itemResolutionOrder(field: FieldManifest): ItemFieldManifest[];
446
+ declare function resolverFor(document: DocumentManifest, field: FieldManifest | ItemFieldManifest): ResolverManifest;
447
+
448
+ type RuntimeErrorType = "not_found" | "validation" | "conflict";
449
+ declare class RuntimeError extends Error {
450
+ detail: string;
451
+ status: 400 | 404 | 409;
452
+ errorType: RuntimeErrorType;
453
+ validationErrors?: Record<string, string[]> | undefined;
454
+ constructor(detail: string, status: 400 | 404 | 409, errorType: RuntimeErrorType, validationErrors?: Record<string, string[]> | undefined);
455
+ toJSON(): Record<string, unknown>;
456
+ }
457
+ type ToolResult = {
458
+ kind: "search";
459
+ results: unknown[];
460
+ } | {
461
+ kind: "terminal";
462
+ ok: true;
463
+ value: unknown;
464
+ } | {
465
+ kind: "terminal";
466
+ ok: false;
467
+ reason: string;
468
+ };
469
+ interface ProjectRuntime {
470
+ manifest: Manifest;
471
+ invokeTool(input: {
472
+ documentType: string;
473
+ toolName: string;
474
+ args: Record<string, unknown>;
475
+ }): Promise<ToolResult>;
476
+ process(input: {
477
+ documentType: string;
478
+ values: Record<string, unknown>;
479
+ }): Promise<{
480
+ key: string;
481
+ }>;
482
+ }
483
+ declare function createRuntime(documents: Record<string, DocumentDefinition>): ProjectRuntime;
484
+
485
+ declare const RUNTIME_VERSION = "0.1.0";
486
+ declare function assertRuntimeVersion(imageVersion?: string | undefined): void;
487
+
488
+ export { type AnyTool, type Dataset, type DocumentDefinition, type DocumentManifest, DocumentManifestSchema, type FieldKind, type FieldManifest, FieldManifestSchema, type FieldSpec, type ItemFieldManifest, type Manifest, ManifestSchema, type ProcessDefinition, type ProjectRuntime, RUNTIME_VERSION, type RecordDefinition, type ResolverManifest, ResolverManifestSchema, type ResolverPresentation, type ResolverPresentationManifest, ResolverPresentationSchema, RuntimeError, type RuntimeErrorType, type SearchTool, type Strategy, type Subagent, type TerminalTool, type ToolManifest, ToolManifestSchema, type ToolResult, type VerifyResult, assertRuntimeVersion, buildDataset, buildManifest, commitBlockers, createRuntime, defineDocument, defineProcess, defineRecord, defineSearchTool, defineSubagent, defineTerminalTool, extractableFields, extractableRecordFields, field, groundedRecordFields, itemResolutionOrder, resolutionOrder, resolverFor, unmappedFields };
package/dist/index.js ADDED
@@ -0,0 +1,672 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
28
+ };
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
39
+ };
40
+
41
+ // src/record.ts
42
+ import { z } from "zod";
43
+ function defineRecord(input) {
44
+ validateFields(input.fields, input.type, true);
45
+ const shape = {};
46
+ for (const [name, spec] of Object.entries(input.fields)) shape[name] = spec.schema;
47
+ return __spreadProps(__spreadValues({}, input), { zod: z.object(shape) });
48
+ }
49
+ function validateFields(fields, owner, allowCollections) {
50
+ for (const [name, spec] of Object.entries(fields)) {
51
+ if (spec.kind === "collection") {
52
+ if (!allowCollections) {
53
+ throw new Error(
54
+ `Field "${owner}.${name}" is a nested collection. Only one level is supported.`
55
+ );
56
+ }
57
+ if (!spec.fields || Object.keys(spec.fields).length === 0) {
58
+ throw new Error(`Collection "${owner}.${name}" must declare item fields.`);
59
+ }
60
+ if (spec.strategy !== "extract") {
61
+ throw new Error(`Collection "${owner}.${name}" must use strategy "extract".`);
62
+ }
63
+ validateFields(spec.fields, `${owner}.${name}`, false);
64
+ continue;
65
+ }
66
+ if (spec.strategy === "ground" && !spec.resolver) {
67
+ throw new Error(
68
+ `Field "${owner}.${name}" has strategy "ground" but no resolver. Add resolver: "<subagent name>", or change the strategy to "extract".`
69
+ );
70
+ }
71
+ if (spec.resolver && spec.strategy !== "ground") {
72
+ throw new Error(
73
+ `Field "${owner}.${name}" names resolver "${spec.resolver}" but its strategy is "${spec.strategy}". Only "ground" fields run a resolver.`
74
+ );
75
+ }
76
+ if (spec.strategy !== "ground") continue;
77
+ if (!spec.groundFrom) {
78
+ throw new Error(
79
+ `Field "${owner}.${name}" is grounded but has no groundFrom. Add the field that supplies its resolver input.`
80
+ );
81
+ }
82
+ const source = fields[spec.groundFrom];
83
+ if (!source) {
84
+ throw new Error(
85
+ `Field "${owner}.${name}" grounds from "${spec.groundFrom}", which is not on this record. Declared: ${Object.keys(fields).join(", ")}.`
86
+ );
87
+ }
88
+ if (source.strategy !== "extract" && source.strategy !== "ground") {
89
+ throw new Error(
90
+ `Field "${owner}.${name}" grounds from "${spec.groundFrom}", whose strategy "${source.strategy}" cannot supply a resolver input.`
91
+ );
92
+ }
93
+ }
94
+ }
95
+ var field = {
96
+ text(spec) {
97
+ return __spreadValues({
98
+ schema: z.string().nullable(),
99
+ kind: "text",
100
+ strategy: "extract"
101
+ }, spec);
102
+ },
103
+ number(spec) {
104
+ return __spreadValues({
105
+ schema: z.number().nullable(),
106
+ kind: "number",
107
+ strategy: "extract"
108
+ }, spec);
109
+ },
110
+ grounded(spec) {
111
+ return __spreadValues({
112
+ schema: z.unknown().nullable(),
113
+ kind: "text",
114
+ strategy: "ground",
115
+ requiredForProcess: true
116
+ }, spec);
117
+ },
118
+ collection(spec) {
119
+ const shape = {};
120
+ for (const [name, itemField] of Object.entries(spec.fields)) {
121
+ shape[name] = itemField.schema;
122
+ }
123
+ return __spreadValues({
124
+ schema: z.array(z.object(shape)),
125
+ kind: "collection",
126
+ strategy: "extract"
127
+ }, spec);
128
+ }
129
+ };
130
+ function extractableRecordFields(record) {
131
+ return Object.entries(record.fields).filter(
132
+ ([, spec]) => !spec.llmHidden && spec.strategy === "extract"
133
+ );
134
+ }
135
+ function groundedRecordFields(record) {
136
+ return Object.entries(record.fields).filter(([, spec]) => spec.strategy === "ground");
137
+ }
138
+
139
+ // src/tools.ts
140
+ function defineSearchTool(spec) {
141
+ return __spreadValues({ kind: "search" }, spec);
142
+ }
143
+ function defineTerminalTool(spec) {
144
+ return __spreadValues({ kind: "terminal" }, spec);
145
+ }
146
+
147
+ // src/subagent.ts
148
+ function defineSubagent(spec) {
149
+ const terminals = spec.tools.filter((tool) => tool.kind === "terminal");
150
+ const searchTools = spec.tools.filter((tool) => tool.kind === "search");
151
+ if (terminals.length === 0) {
152
+ throw new Error(
153
+ `Subagent "${spec.name}" has no terminal tool. Add one built with defineTerminalTool so verified data is its only exit.`
154
+ );
155
+ }
156
+ if (terminals.length > 1) {
157
+ throw new Error(
158
+ `Subagent "${spec.name}" has ${terminals.length} terminal tools (${terminals.map((tool) => tool.name).join(", ")}). Exactly one is allowed.`
159
+ );
160
+ }
161
+ const terminal = terminals[0];
162
+ if (!terminal) throw new Error(`Subagent "${spec.name}" has no terminal tool.`);
163
+ return __spreadProps(__spreadValues({}, spec), { searchTools, terminal });
164
+ }
165
+
166
+ // src/process.ts
167
+ function defineProcess(record, run) {
168
+ return { record, run };
169
+ }
170
+ function buildDataset(record, values, keys = {}) {
171
+ var _a, _b, _c, _d, _e, _f, _g, _h;
172
+ const tables = {};
173
+ for (const [name, spec] of Object.entries(record.fields)) {
174
+ if (spec.kind === "collection") {
175
+ const items = values[name];
176
+ if (!Array.isArray(items) || !spec.fields) continue;
177
+ for (const [index, item] of items.entries()) {
178
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
179
+ for (const [itemName, itemSpec] of Object.entries(spec.fields)) {
180
+ if (!itemSpec.writeTo) continue;
181
+ const [table2, column2, ...rest2] = itemSpec.writeTo.split(".");
182
+ if (!table2 || !column2 || rest2.length > 0) {
183
+ throw new Error(
184
+ `Field "${name}.${itemName}" has writeTo "${itemSpec.writeTo}", which is not a "Table.Column" pair.`
185
+ );
186
+ }
187
+ const value2 = item[itemName];
188
+ if (value2 === void 0 || value2 === null) continue;
189
+ (_a = tables[table2]) != null ? _a : tables[table2] = [];
190
+ (_d = (_c = tables[table2])[index]) != null ? _d : _c[index] = __spreadValues({ RowMod: "A" }, (_b = keys[table2]) != null ? _b : {});
191
+ tables[table2][index][column2] = value2;
192
+ }
193
+ }
194
+ continue;
195
+ }
196
+ if (!spec.writeTo) continue;
197
+ const [table, column, ...rest] = spec.writeTo.split(".");
198
+ if (!table || !column || rest.length > 0) {
199
+ throw new Error(
200
+ `Field "${name}" has writeTo "${spec.writeTo}", which is not a "Table.Column" pair.`
201
+ );
202
+ }
203
+ const value = values[name];
204
+ if (value === void 0 || value === null) continue;
205
+ (_e = tables[table]) != null ? _e : tables[table] = [];
206
+ (_h = (_g = tables[table])[0]) != null ? _h : _g[0] = __spreadValues({ RowMod: "A" }, (_f = keys[table]) != null ? _f : {});
207
+ tables[table][0][column] = value;
208
+ }
209
+ return tables;
210
+ }
211
+ function unmappedFields(record) {
212
+ return Object.entries(record.fields).filter(([, spec]) => !spec.writeTo).map(([name]) => name);
213
+ }
214
+ function commitBlockers(record, values) {
215
+ const blockers = [];
216
+ for (const [name, spec] of Object.entries(record.fields)) {
217
+ if (spec.kind === "collection") {
218
+ const items = values[name];
219
+ if (spec.requiredForProcess && (!Array.isArray(items) || items.length === 0)) {
220
+ blockers.push(`${name} must contain at least one item`);
221
+ }
222
+ if (!Array.isArray(items) || !spec.fields) continue;
223
+ for (const [index, item] of items.entries()) {
224
+ const itemValues = item && typeof item === "object" && !Array.isArray(item) ? item : {};
225
+ for (const [itemName, itemSpec] of Object.entries(spec.fields)) {
226
+ if (itemSpec.strategy !== "ground" && !itemSpec.requiredForProcess) continue;
227
+ if (isMissing(itemValues[itemName])) {
228
+ blockers.push(`${name}.${index}.${itemName} is required before processing`);
229
+ }
230
+ }
231
+ }
232
+ continue;
233
+ }
234
+ if (spec.strategy !== "ground" && !spec.requiredForProcess) continue;
235
+ if (isMissing(values[name])) {
236
+ blockers.push(
237
+ spec.strategy === "ground" ? `${name} was never resolved against the ERP` : `${name} is required before processing`
238
+ );
239
+ }
240
+ }
241
+ return blockers;
242
+ }
243
+ function isMissing(value) {
244
+ return value === null || value === void 0 || value === "";
245
+ }
246
+
247
+ // src/document.ts
248
+ function defineDocument(spec) {
249
+ var _a;
250
+ if (spec.process.record !== spec.record) {
251
+ throw new Error(
252
+ `Document "${spec.record.type}" uses a process defined for a different record.`
253
+ );
254
+ }
255
+ const subagents = {};
256
+ const toolNames = /* @__PURE__ */ new Set();
257
+ for (const subagent of spec.subagents) {
258
+ if (subagents[subagent.name]) {
259
+ throw new Error(
260
+ `Document "${spec.record.type}" declares two subagents named "${subagent.name}".`
261
+ );
262
+ }
263
+ subagents[subagent.name] = subagent;
264
+ for (const tool of subagent.tools) {
265
+ if (toolNames.has(tool.name)) {
266
+ throw new Error(
267
+ `Document "${spec.record.type}" declares tool "${tool.name}" more than once. Tool names are document-wide because Fluent addresses them by name.`
268
+ );
269
+ }
270
+ toolNames.add(tool.name);
271
+ }
272
+ }
273
+ for (const [name, field2] of Object.entries(spec.record.fields)) {
274
+ assertResolverExists(name, field2.resolver, field2.strategy, subagents);
275
+ for (const [itemName, itemField] of Object.entries((_a = field2.fields) != null ? _a : {})) {
276
+ assertResolverExists(
277
+ `${name}.${itemName}`,
278
+ itemField.resolver,
279
+ itemField.strategy,
280
+ subagents
281
+ );
282
+ }
283
+ }
284
+ return {
285
+ type: spec.record.type,
286
+ title: spec.record.title,
287
+ record: spec.record,
288
+ subagents,
289
+ process: spec.process
290
+ };
291
+ }
292
+ function assertResolverExists(fieldName, resolver, strategy, subagents) {
293
+ if (strategy !== "ground") return;
294
+ if (!resolver || !subagents[resolver]) {
295
+ throw new Error(
296
+ `Field "${fieldName}" names resolver "${resolver}", which is not a subagent of this document. Declared: ${Object.keys(subagents).join(", ") || "(none)"}.`
297
+ );
298
+ }
299
+ }
300
+
301
+ // src/manifest.ts
302
+ import { z as z2 } from "zod";
303
+ var ToolManifestSchema = z2.object({
304
+ name: z2.string().min(1),
305
+ kind: z2.enum(["search", "terminal"]),
306
+ description: z2.string(),
307
+ parameters: z2.unknown()
308
+ });
309
+ var ResolverPresentationSchema = z2.object({
310
+ searchArgument: z2.string().min(1),
311
+ resultKey: z2.string().min(1),
312
+ resultLabel: z2.string().min(1),
313
+ resultMeta: z2.array(z2.string().min(1)),
314
+ terminalArgument: z2.string().min(1),
315
+ terminalArguments: z2.record(z2.string(), z2.string().min(1)).optional()
316
+ });
317
+ var ResolverManifestSchema = z2.object({
318
+ name: z2.string().min(1),
319
+ instructions: z2.string(),
320
+ result: z2.unknown(),
321
+ tools: z2.array(ToolManifestSchema),
322
+ terminal: z2.string().min(1),
323
+ presentation: ResolverPresentationSchema
324
+ });
325
+ var FieldManifestBaseSchema = z2.object({
326
+ name: z2.string().min(1),
327
+ label: z2.string(),
328
+ kind: z2.enum(["text", "number", "collection"]).default("text"),
329
+ strategy: z2.enum(["extract", "ground", "choose", "reconcile", "revise", "computed"]),
330
+ description: z2.string().nullable(),
331
+ writeTo: z2.string().nullable(),
332
+ resolver: z2.string().nullable(),
333
+ groundFrom: z2.string().nullable(),
334
+ llmHidden: z2.boolean(),
335
+ requiredForProcess: z2.boolean().default(false)
336
+ });
337
+ var ItemFieldManifestSchema = FieldManifestBaseSchema.extend({
338
+ kind: z2.enum(["text", "number"]).default("text")
339
+ });
340
+ var FieldManifestSchema = FieldManifestBaseSchema.extend({
341
+ fields: z2.array(ItemFieldManifestSchema).nullable().default(null)
342
+ });
343
+ var DocumentManifestSchema = z2.object({
344
+ type: z2.string().min(1),
345
+ title: z2.string(),
346
+ fields: z2.array(FieldManifestSchema),
347
+ resolvers: z2.array(ResolverManifestSchema)
348
+ });
349
+ var ManifestSchema = z2.object({
350
+ version: z2.literal(1),
351
+ documents: z2.array(DocumentManifestSchema)
352
+ });
353
+ function buildManifest(documents) {
354
+ return ManifestSchema.parse({
355
+ version: 1,
356
+ documents: Object.values(documents).map((document) => ({
357
+ type: document.type,
358
+ title: document.title,
359
+ fields: Object.entries(document.record.fields).map(([name, field2]) => __spreadProps(__spreadValues({}, manifestField(name, field2)), {
360
+ fields: field2.fields ? Object.entries(field2.fields).map(
361
+ ([itemName, itemField]) => manifestField(itemName, itemField)
362
+ ) : null
363
+ })),
364
+ resolvers: Object.values(document.subagents).map((subagent) => ({
365
+ name: subagent.name,
366
+ instructions: subagent.instructions,
367
+ result: z2.toJSONSchema(subagent.result),
368
+ terminal: subagent.terminal.name,
369
+ presentation: subagent.presentation,
370
+ tools: subagent.tools.map((tool) => ({
371
+ name: tool.name,
372
+ kind: tool.kind,
373
+ description: tool.description,
374
+ parameters: z2.toJSONSchema(tool.args)
375
+ }))
376
+ }))
377
+ }))
378
+ });
379
+ }
380
+ function manifestField(name, field2) {
381
+ var _a, _b, _c, _d, _e, _f, _g;
382
+ return {
383
+ name,
384
+ label: field2.label,
385
+ kind: (_a = field2.kind) != null ? _a : "text",
386
+ strategy: field2.strategy,
387
+ description: (_b = field2.description) != null ? _b : null,
388
+ writeTo: (_c = field2.writeTo) != null ? _c : null,
389
+ resolver: (_d = field2.resolver) != null ? _d : null,
390
+ groundFrom: (_e = field2.groundFrom) != null ? _e : null,
391
+ llmHidden: (_f = field2.llmHidden) != null ? _f : false,
392
+ requiredForProcess: (_g = field2.requiredForProcess) != null ? _g : false
393
+ };
394
+ }
395
+ function extractableFields(document) {
396
+ return document.fields.filter((field2) => field2.strategy === "extract" && !field2.llmHidden);
397
+ }
398
+ function resolutionOrder(document) {
399
+ return orderFields(document.type, document.fields);
400
+ }
401
+ function itemResolutionOrder(field2) {
402
+ if (field2.kind !== "collection" || !field2.fields) return [];
403
+ return orderFields(field2.name, field2.fields);
404
+ }
405
+ function orderFields(owner, fields) {
406
+ const pending = fields.filter((field2) => field2.strategy === "ground");
407
+ const available = new Set(
408
+ fields.filter((field2) => field2.strategy !== "ground").map((field2) => field2.name)
409
+ );
410
+ const ordered = [];
411
+ let moved = true;
412
+ while (moved) {
413
+ moved = false;
414
+ for (let index = pending.length - 1; index >= 0; index -= 1) {
415
+ const field2 = pending[index];
416
+ if (!(field2 == null ? void 0 : field2.groundFrom) || !available.has(field2.groundFrom)) continue;
417
+ ordered.push(field2);
418
+ available.add(field2.name);
419
+ pending.splice(index, 1);
420
+ moved = true;
421
+ }
422
+ }
423
+ if (pending.length > 0) {
424
+ throw new Error(
425
+ `Cannot order grounded fields on "${owner}" because groundFrom sources are missing or circular: ${pending.map((field2) => {
426
+ var _a;
427
+ return `${field2.name} <- ${(_a = field2.groundFrom) != null ? _a : "(none)"}`;
428
+ }).join(", ")}`
429
+ );
430
+ }
431
+ return ordered;
432
+ }
433
+ function resolverFor(document, field2) {
434
+ if (!field2.resolver) {
435
+ throw new Error(
436
+ `Field "${field2.name}" on "${document.type}" has strategy "ground" but names no resolver.`
437
+ );
438
+ }
439
+ const resolver = document.resolvers.find((candidate) => candidate.name === field2.resolver);
440
+ if (!resolver) {
441
+ throw new Error(
442
+ `Field "${field2.name}" names resolver "${field2.resolver}", which "${document.type}" does not publish. Published: ${document.resolvers.map((candidate) => candidate.name).join(", ") || "(none)"}.`
443
+ );
444
+ }
445
+ return resolver;
446
+ }
447
+
448
+ // src/runtime.ts
449
+ import { z as z3 } from "zod";
450
+ var RuntimeError = class extends Error {
451
+ constructor(detail, status, errorType, validationErrors2) {
452
+ super(detail);
453
+ this.detail = detail;
454
+ this.status = status;
455
+ this.errorType = errorType;
456
+ this.validationErrors = validationErrors2;
457
+ this.name = "RuntimeError";
458
+ }
459
+ toJSON() {
460
+ return __spreadValues({
461
+ detail: this.detail,
462
+ status: this.status,
463
+ error_type: this.errorType
464
+ }, this.validationErrors ? { validation_errors: this.validationErrors } : {});
465
+ }
466
+ };
467
+ function validationErrors(error) {
468
+ var _a;
469
+ const errors = {};
470
+ for (const issue of error.issues) {
471
+ const path = issue.path.join(".") || "_";
472
+ (_a = errors[path]) != null ? _a : errors[path] = [];
473
+ errors[path].push(issue.message);
474
+ }
475
+ return errors;
476
+ }
477
+ function createRuntime(documents) {
478
+ const manifest = buildManifest(documents);
479
+ const documentsByType = {};
480
+ for (const definition of Object.values(documents)) {
481
+ if (documentsByType[definition.type]) {
482
+ throw new Error(`Project declares document type "${definition.type}" more than once.`);
483
+ }
484
+ documentsByType[definition.type] = definition;
485
+ }
486
+ function document(documentType) {
487
+ const definition = documentsByType[documentType];
488
+ if (!definition) {
489
+ throw new RuntimeError(`No document type "${documentType}".`, 404, "not_found");
490
+ }
491
+ return definition;
492
+ }
493
+ return {
494
+ manifest,
495
+ invokeTool(_0) {
496
+ return __async(this, arguments, function* ({ documentType, toolName, args }) {
497
+ const definition = document(documentType);
498
+ let owner = void 0;
499
+ let tool = void 0;
500
+ for (const subagent of Object.values(definition.subagents)) {
501
+ const found = subagent.tools.find((candidate) => candidate.name === toolName);
502
+ if (!found) continue;
503
+ owner = subagent;
504
+ tool = found;
505
+ break;
506
+ }
507
+ if (!owner || !tool) {
508
+ throw new RuntimeError(
509
+ `No tool "${toolName}" on document type "${documentType}".`,
510
+ 404,
511
+ "not_found"
512
+ );
513
+ }
514
+ const parsed = tool.args.safeParse(args);
515
+ if (!parsed.success) {
516
+ throw new RuntimeError(
517
+ `Arguments rejected by ${tool.name}.`,
518
+ 400,
519
+ "validation",
520
+ validationErrors(parsed.error)
521
+ );
522
+ }
523
+ if (tool.kind === "search") {
524
+ return { kind: "search", results: yield tool.search(parsed.data) };
525
+ }
526
+ const verified = yield tool.verify(parsed.data);
527
+ if (!verified.ok) return { kind: "terminal", ok: false, reason: verified.reason };
528
+ const result = owner.result.parse(verified.value);
529
+ return { kind: "terminal", ok: true, value: result };
530
+ });
531
+ },
532
+ process(_0) {
533
+ return __async(this, arguments, function* ({ documentType, values }) {
534
+ const definition = document(documentType);
535
+ const parsed = definition.record.zod.safeParse(values);
536
+ if (!parsed.success) {
537
+ throw new RuntimeError(
538
+ `Values rejected by ${documentType}.`,
539
+ 400,
540
+ "validation",
541
+ validationErrors(parsed.error)
542
+ );
543
+ }
544
+ const blockers = commitBlockers(definition.record, parsed.data);
545
+ if (blockers.length > 0) {
546
+ throw new RuntimeError(
547
+ `Not writing ${documentType}: ${blockers.join("; ")}.`,
548
+ 409,
549
+ "conflict"
550
+ );
551
+ }
552
+ yield reverifyGroundedValues(definition, parsed.data);
553
+ return z3.object({ key: z3.string().min(1) }).parse(yield definition.process.run(parsed.data));
554
+ });
555
+ }
556
+ };
557
+ }
558
+ function reverifyGroundedValues(definition, values) {
559
+ return __async(this, null, function* () {
560
+ var _a;
561
+ for (const [name, field2] of Object.entries(definition.record.fields)) {
562
+ if (field2.kind === "collection") {
563
+ const items = values[name];
564
+ if (!Array.isArray(items)) continue;
565
+ for (const [index, item] of items.entries()) {
566
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
567
+ const itemValues = item;
568
+ for (const [itemName, itemField] of Object.entries((_a = field2.fields) != null ? _a : {})) {
569
+ if (itemField.strategy !== "ground") continue;
570
+ itemValues[itemName] = yield reverifyGroundedValue(
571
+ definition,
572
+ `${name}.${index}.${itemName}`,
573
+ itemField.resolver,
574
+ itemValues[itemName]
575
+ );
576
+ }
577
+ }
578
+ continue;
579
+ }
580
+ if (field2.strategy !== "ground") continue;
581
+ values[name] = yield reverifyGroundedValue(definition, name, field2.resolver, values[name]);
582
+ }
583
+ });
584
+ }
585
+ function reverifyGroundedValue(definition, path, resolverName, value) {
586
+ return __async(this, null, function* () {
587
+ var _a;
588
+ const resolver = resolverName ? definition.subagents[resolverName] : void 0;
589
+ if (!resolver) {
590
+ throw new Error(`Grounded field "${path}" has no resolver at Process time.`);
591
+ }
592
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
593
+ throw new RuntimeError(
594
+ `Not writing ${definition.type}: ${path} is not a verified object.`,
595
+ 409,
596
+ "conflict"
597
+ );
598
+ }
599
+ const candidate = value;
600
+ const mappings = (_a = resolver.presentation.terminalArguments) != null ? _a : {
601
+ [resolver.presentation.terminalArgument]: resolver.presentation.resultKey
602
+ };
603
+ const args = {};
604
+ for (const [argument, property] of Object.entries(mappings)) {
605
+ const argumentValue = candidate[property];
606
+ if (argumentValue === void 0 || argumentValue === null) {
607
+ throw new RuntimeError(
608
+ `Not writing ${definition.type}: ${path} is missing verified property ${property}.`,
609
+ 409,
610
+ "conflict"
611
+ );
612
+ }
613
+ args[argument] = argumentValue;
614
+ }
615
+ const parsedArgs = resolver.terminal.args.safeParse(args);
616
+ if (!parsedArgs.success) {
617
+ throw new RuntimeError(
618
+ `Not writing ${definition.type}: ${path} cannot be re-verified.`,
619
+ 409,
620
+ "conflict",
621
+ validationErrors(parsedArgs.error)
622
+ );
623
+ }
624
+ const verified = yield resolver.terminal.verify(parsedArgs.data);
625
+ if (!verified.ok) {
626
+ throw new RuntimeError(
627
+ `Not writing ${definition.type}: ${path} failed verification: ${verified.reason}`,
628
+ 409,
629
+ "conflict"
630
+ );
631
+ }
632
+ return resolver.result.parse(verified.value);
633
+ });
634
+ }
635
+
636
+ // src/version.ts
637
+ var RUNTIME_VERSION = "0.1.0";
638
+ function assertRuntimeVersion(imageVersion = process.env.FLUENT_RUNTIME_IMAGE_VERSION) {
639
+ if (!imageVersion || imageVersion === RUNTIME_VERSION) return;
640
+ throw new Error(
641
+ `@fluenterp/runtime ${RUNTIME_VERSION} cannot run in Fluent runtime image ${imageVersion}. Use matching package and image versions.`
642
+ );
643
+ }
644
+ export {
645
+ DocumentManifestSchema,
646
+ FieldManifestSchema,
647
+ ManifestSchema,
648
+ RUNTIME_VERSION,
649
+ ResolverManifestSchema,
650
+ ResolverPresentationSchema,
651
+ RuntimeError,
652
+ ToolManifestSchema,
653
+ assertRuntimeVersion,
654
+ buildDataset,
655
+ buildManifest,
656
+ commitBlockers,
657
+ createRuntime,
658
+ defineDocument,
659
+ defineProcess,
660
+ defineRecord,
661
+ defineSearchTool,
662
+ defineSubagent,
663
+ defineTerminalTool,
664
+ extractableFields,
665
+ extractableRecordFields,
666
+ field,
667
+ groundedRecordFields,
668
+ itemResolutionOrder,
669
+ resolutionOrder,
670
+ resolverFor,
671
+ unmappedFields
672
+ };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@fluenterp/runtime",
3
+ "version": "0.1.0",
4
+ "description": "Runtime contract for Fluent project agents",
5
+ "license": "UNLICENSED",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/tcpmia/fluent.git",
9
+ "directory": "packages/ts/runtime"
10
+ },
11
+ "files": [
12
+ "dist/**"
13
+ ],
14
+ "type": "module",
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "default": "./dist/index.js"
22
+ }
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "dependencies": {
28
+ "zod": "4.4.3"
29
+ },
30
+ "devDependencies": {
31
+ "@jest/globals": "^30.2.0",
32
+ "@types/jest": "^30.0.0",
33
+ "@types/node": "^24.13.3",
34
+ "jest": "^29.7.0",
35
+ "ts-jest": "^29.1.2",
36
+ "tsup": "^8.0.2",
37
+ "typescript": "^5.9.3",
38
+ "@fluent/typescript-config": "0.1.0"
39
+ },
40
+ "engines": {
41
+ "node": ">=20"
42
+ },
43
+ "scripts": {
44
+ "build": "tsup",
45
+ "lint": "oxlint src/",
46
+ "test": "NODE_OPTIONS='--experimental-vm-modules' jest",
47
+ "typecheck": "tsgo --noEmit"
48
+ }
49
+ }