@elementumai/edk 0.9.7 → 0.9.9

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 (148) hide show
  1. package/README.md +3 -2
  2. package/dist-sdk/src/catalog/factories.d.ts +14 -3
  3. package/dist-sdk/src/catalog/factories.js +32 -0
  4. package/dist-sdk/src/catalog/from-authoring.js +27 -33
  5. package/dist-sdk/src/catalog/index.d.ts +2 -2
  6. package/dist-sdk/src/catalog/index.js +2 -2
  7. package/dist-sdk/src/catalog/org.js +67 -29
  8. package/dist-sdk/src/catalog/token.js +10 -0
  9. package/dist-sdk/src/catalog/types.d.ts +20 -2
  10. package/dist-sdk/src/catalog/types.js +5 -0
  11. package/dist-sdk/src/core/index.d.ts +1 -1
  12. package/dist-sdk/src/core/index.js +1 -1
  13. package/dist-sdk/src/core/platform-id.d.ts +2 -0
  14. package/dist-sdk/src/core/platform-id.js +4 -0
  15. package/dist-sdk/src/core/system-fields.d.ts +14 -0
  16. package/dist-sdk/src/core/system-fields.js +6 -0
  17. package/dist-sdk/src/core/triggers/on-demand.d.ts +27 -24
  18. package/dist-sdk/src/core/triggers/on-demand.js +33 -12
  19. package/dist-sdk/src/core/types/aspect-category.d.ts +1 -0
  20. package/dist-sdk/src/core/types/aspect-category.js +1 -0
  21. package/dist-sdk/src/engine/build/context.d.ts +20 -8
  22. package/dist-sdk/src/engine/build/source-context.d.ts +14 -17
  23. package/dist-sdk/src/engine/build/source-context.js +1 -1
  24. package/dist-sdk/src/engine/pull/context.d.ts +9 -0
  25. package/dist-sdk/src/engine/pull/org.d.ts +4 -0
  26. package/dist-sdk/src/engine/pull/org.js +17 -2
  27. package/dist-sdk/src/engine/pull/procedure-refs.d.ts +16 -0
  28. package/dist-sdk/src/engine/pull/procedure-refs.js +69 -0
  29. package/dist-sdk/src/engine/tf/expr.js +1 -1
  30. package/dist-sdk/src/engine/workspace/authoring-layout.d.ts +15 -0
  31. package/dist-sdk/src/engine/workspace/authoring-layout.js +33 -1
  32. package/dist-sdk/src/engine/workspace/loader.d.ts +40 -0
  33. package/dist-sdk/src/engine/workspace/loader.js +328 -0
  34. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +4 -0
  35. package/dist-sdk/src/entities/access-policy/from-tf.js +10 -2
  36. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +1 -0
  37. package/dist-sdk/src/entities/access-policy/to-tf.js +7 -2
  38. package/dist-sdk/src/entities/agent/build.d.ts +54 -8
  39. package/dist-sdk/src/entities/agent/build.js +36 -1
  40. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +126 -2
  41. package/dist-sdk/src/entities/agent/from-tf.d.ts +7 -6
  42. package/dist-sdk/src/entities/agent/from-tf.js +176 -5
  43. package/dist-sdk/src/entities/agent/index.d.ts +2 -2
  44. package/dist-sdk/src/entities/agent/index.js +1 -1
  45. package/dist-sdk/src/entities/agent/to-tf.d.ts +4 -4
  46. package/dist-sdk/src/entities/agent/to-tf.js +185 -11
  47. package/dist-sdk/src/entities/agent/tools.d.ts +16 -5
  48. package/dist-sdk/src/entities/agent/tools.js +13 -1
  49. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +7 -0
  50. package/dist-sdk/src/entities/agent-tool/from-tf.js +29 -4
  51. package/dist-sdk/src/entities/agent-tool/to-tf.js +10 -9
  52. package/dist-sdk/src/entities/agent-tool/types.js +1 -0
  53. package/dist-sdk/src/entities/app/build.d.ts +2 -2
  54. package/dist-sdk/src/entities/app/build.js +6 -3
  55. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +5 -0
  56. package/dist-sdk/src/entities/app/display-blocks-to-layout.d.ts +45 -0
  57. package/dist-sdk/src/entities/app/display-blocks-to-layout.js +98 -0
  58. package/dist-sdk/src/entities/app/display-blocks-to-record-create-form.d.ts +55 -0
  59. package/dist-sdk/src/entities/app/display-blocks-to-record-create-form.js +99 -0
  60. package/dist-sdk/src/entities/app/from-tf.js +9 -7
  61. package/dist-sdk/src/entities/app/to-tf.js +15 -7
  62. package/dist-sdk/src/entities/automation/build.d.ts +8 -1
  63. package/dist-sdk/src/entities/automation/build.js +36 -5
  64. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +3 -7
  65. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +2 -0
  66. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +77 -8
  67. package/dist-sdk/src/entities/automation/from-tf.d.ts +10 -1
  68. package/dist-sdk/src/entities/automation/from-tf.js +803 -62
  69. package/dist-sdk/src/entities/automation/index.d.ts +1 -1
  70. package/dist-sdk/src/entities/automation/module.js +13 -3
  71. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +12 -4
  72. package/dist-sdk/src/entities/automation/output-key-wire-name.js +17 -6
  73. package/dist-sdk/src/entities/automation/script-code.d.ts +1 -1
  74. package/dist-sdk/src/entities/automation/script-code.js +15 -11
  75. package/dist-sdk/src/entities/automation/task-label.d.ts +2 -0
  76. package/dist-sdk/src/entities/automation/task-label.js +18 -0
  77. package/dist-sdk/src/entities/automation/tasks.d.ts +60 -9
  78. package/dist-sdk/src/entities/automation/tasks.js +16 -4
  79. package/dist-sdk/src/entities/automation/to-tf.d.ts +4 -0
  80. package/dist-sdk/src/entities/automation/to-tf.js +385 -52
  81. package/dist-sdk/src/entities/automation/triggers.d.ts +14 -5
  82. package/dist-sdk/src/entities/automation/triggers.js +1 -1
  83. package/dist-sdk/src/entities/dashboard/from-tf.js +1 -1
  84. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +1 -0
  85. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +1 -1
  86. package/dist-sdk/src/entities/element/build.d.ts +30 -7
  87. package/dist-sdk/src/entities/element/build.js +6 -3
  88. package/dist-sdk/src/entities/element/from-tf.js +7 -3
  89. package/dist-sdk/src/entities/element/index.d.ts +1 -1
  90. package/dist-sdk/src/entities/element/index.js +1 -1
  91. package/dist-sdk/src/entities/element/to-tf.js +49 -8
  92. package/dist-sdk/src/entities/field/from-tf.d.ts +6 -0
  93. package/dist-sdk/src/entities/field/from-tf.js +12 -0
  94. package/dist-sdk/src/entities/field/module.js +1 -0
  95. package/dist-sdk/src/entities/field/to-tf.d.ts +1 -1
  96. package/dist-sdk/src/entities/field/to-tf.js +19 -5
  97. package/dist-sdk/src/entities/org/category-ref.d.ts +5 -0
  98. package/dist-sdk/src/entities/org/category-ref.js +12 -0
  99. package/dist-sdk/src/entities/record-create-form/from-tf.js +3 -3
  100. package/dist-sdk/src/entities/record-create-form/to-tf.d.ts +1 -0
  101. package/dist-sdk/src/entities/record-create-form/to-tf.js +13 -5
  102. package/dist-sdk/src/entities/relationship/from-tf.js +15 -4
  103. package/dist-sdk/src/entities/role/from-tf.js +10 -4
  104. package/dist-sdk/src/entities/search-table/build.d.ts +1 -1
  105. package/dist-sdk/src/entities/search-table/from-tf.d.ts +1 -0
  106. package/dist-sdk/src/entities/search-table/from-tf.js +6 -0
  107. package/dist-sdk/src/entities/search-table/printer.js +3 -1
  108. package/dist-sdk/src/entities/search-table/to-tf.js +3 -3
  109. package/dist-sdk/src/entities/search-table/types.js +1 -0
  110. package/dist-sdk/src/entities/service-account/from-tf.js +10 -4
  111. package/dist-sdk/src/entities/service-account/to-tf.d.ts +2 -1
  112. package/dist-sdk/src/entities/service-account/to-tf.js +7 -0
  113. package/dist-sdk/src/entities/shared/filters/ast.d.ts +7 -1
  114. package/dist-sdk/src/entities/shared/filters/ast.js +3 -0
  115. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +7 -1
  116. package/dist-sdk/src/entities/shared/filters/tf-codec.js +8 -4
  117. package/dist-sdk/src/entities/shared/handle-description.d.ts +12 -0
  118. package/dist-sdk/src/entities/shared/handle-description.js +20 -0
  119. package/dist-sdk/src/entities/shared/types/field-types.d.ts +6 -1
  120. package/dist-sdk/src/entities/shared/types/field-types.js +5 -8
  121. package/dist-sdk/src/entities/skill/build.d.ts +51 -2
  122. package/dist-sdk/src/entities/skill/build.js +65 -8
  123. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +35 -3
  124. package/dist-sdk/src/entities/skill/from-tf.d.ts +11 -0
  125. package/dist-sdk/src/entities/skill/from-tf.js +39 -7
  126. package/dist-sdk/src/entities/skill/index.d.ts +1 -1
  127. package/dist-sdk/src/entities/skill/index.js +1 -1
  128. package/dist-sdk/src/entities/skill/input-coverage.d.ts +21 -0
  129. package/dist-sdk/src/entities/skill/input-coverage.js +148 -5
  130. package/dist-sdk/src/entities/skill/to-tf.d.ts +6 -25
  131. package/dist-sdk/src/entities/skill/to-tf.js +22 -38
  132. package/dist-sdk/src/entities/skill/tools.d.ts +2 -1
  133. package/dist-sdk/src/entities/skill/tools.js +3 -1
  134. package/dist-sdk/src/entities/skill-tool/from-tf.js +10 -3
  135. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +5 -5
  136. package/dist-sdk/src/entities/skill-tool/to-tf.js +5 -7
  137. package/dist-sdk/src/entities/table/to-tf.js +3 -4
  138. package/dist-sdk/src/entities/task/to-tf.js +3 -2
  139. package/dist-sdk/src/entities/view/from-tf.js +36 -10
  140. package/dist-sdk/src/entities/view/to-tf.d.ts +2 -0
  141. package/dist-sdk/src/entities/view/to-tf.js +44 -30
  142. package/dist-sdk/src/entities/widget/from-tf.js +2 -2
  143. package/dist-sdk/src/entities/widget/to-tf.d.ts +1 -0
  144. package/dist-sdk/src/entities/widget/to-tf.js +52 -23
  145. package/dist-sdk/src/graph/index.d.ts +19 -1
  146. package/dist-sdk/src/graph/index.js +20 -0
  147. package/dist-sdk/src/graph/types.d.ts +19 -0
  148. package/package.json +10 -5
@@ -0,0 +1,328 @@
1
+ /**
2
+ * Workspace module loader — how `elementum build` (and everything downstream
3
+ * of it) reads authored `.ts` under plain Node, with no `tsx` or bundler in
4
+ * the consumer.
5
+ *
6
+ * Node strips TypeScript types natively (`engines: node >=24`), so authored
7
+ * source needs no transpiler. It needs two things Node does not do on its
8
+ * own, both supplied by the resolve hook below:
9
+ *
10
+ * - **`.js` → `.ts`.** A TS source tree writes `./x.js` for what is `x.ts`
11
+ * on disk. Node resolves the specifier literally and 404s.
12
+ * - **`@catalog`.** The generated barrel is addressed by a bare specifier
13
+ * that no `node_modules` entry backs. It resolves against the nearest
14
+ * enclosing org root rather than a single configured path, so a
15
+ * cross-org clone (two roots live in one process) resolves each file
16
+ * against its OWN catalog.
17
+ *
18
+ * Type stripping requires erasable syntax — no parameter properties, enums,
19
+ * or namespaces. This repo's `tsconfig.json` and each org `tsconfig.json`
20
+ * (`ensureWorkspaceTsconfig`) set `erasableSyntaxOnly` so that is a compile
21
+ * error in the workspace rather than a strip-types failure at build.
22
+ *
23
+ * ## Freshness
24
+ *
25
+ * Build may run right after a pull rewrote a file, and `elementum canvas`
26
+ * rebuilds repeatedly inside one long-lived process as the user edits. Node's
27
+ * module cache is permanent per URL, so each loader stamps workspace files
28
+ * with its own generation query. Within one loader a file evaluates once (a
29
+ * shared catalog imported by ten agents is evaluated once); a new loader sees
30
+ * every workspace file fresh. SDK and `node_modules` modules carry no stamp
31
+ * and stay cached for the life of the process — they are what made the
32
+ * previous jiti-based loader expensive, and they never change mid-run.
33
+ */
34
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
35
+ import * as nodeModule from "node:module";
36
+ import { dirname, join, resolve, sep } from "node:path";
37
+ import { fileURLToPath, pathToFileURL } from "node:url";
38
+ /** Query key stamped onto workspace URLs. Namespaced to avoid colliding with
39
+ * a query a user's own loader might care about. */
40
+ const GENERATION_KEY = "__edk_gen";
41
+ /** Org roots whose files participate in generation stamping. A path that
42
+ * sits under two registered roots (a nested `--target-root`) binds to the
43
+ * longest matching prefix, which is the inner workspace. */
44
+ const activeRoots = new Set();
45
+ let hooksRegistered = false;
46
+ /** What the resolve hook stamps. Only mutated inside the import queue. */
47
+ let stampGeneration = 0;
48
+ /** Monotonic allocator. Incremented only inside the import queue so
49
+ * constructing a second loader cannot change the in-flight stamp. */
50
+ let nextGeneration = 0;
51
+ /** One in-flight native import at a time: `stampGeneration` is process-global
52
+ * because the resolve hook cannot see ALS (imported top-level never did).
53
+ * Overlapping `import()` from two loaders would otherwise stamp each other's
54
+ * graph. Construction does not allocate a generation — canvas can create a
55
+ * new loader while a reload is still importing without poisoning the first
56
+ * pass. */
57
+ let importQueue = Promise.resolve();
58
+ function enqueueImport(fn) {
59
+ const run = importQueue.then(fn, fn);
60
+ importQueue = run.then(() => undefined, () => undefined);
61
+ return run;
62
+ }
63
+ function withTrailingSep(path) {
64
+ return path.endsWith(sep) ? path : path + sep;
65
+ }
66
+ /**
67
+ * Real path, for comparing a registered root against an importer's path.
68
+ * They routinely differ by a symlink that neither side controls — a macOS
69
+ * temp dir is `/var/folders/…` to the caller and `/private/var/folders/…`
70
+ * once Node has resolved the module URL. Falls back to the input when the
71
+ * path does not exist (a not-yet-written file is still worth matching).
72
+ */
73
+ function canonical(path) {
74
+ try {
75
+ return realpathSync(path);
76
+ }
77
+ catch {
78
+ return path;
79
+ }
80
+ }
81
+ /** The registered org root containing `path`, or `undefined`. */
82
+ function owningRoot(path) {
83
+ const real = canonical(path);
84
+ let best;
85
+ for (const root of activeRoots) {
86
+ if (real === root || real.startsWith(withTrailingSep(root))) {
87
+ if (best === undefined || root.length > best.length)
88
+ best = root;
89
+ }
90
+ }
91
+ return best;
92
+ }
93
+ /**
94
+ * `@catalog` is always the ORG-ROOT barrel — never the per-entity catalog
95
+ * that happens to sit closer to the importing file. `apps/<ref>/generated/
96
+ * catalog.ts` exports named entries and no default, so resolving to the
97
+ * nearest one instead would silently hand an app its own catalog.
98
+ */
99
+ function findCatalog(root) {
100
+ for (const ext of ["ts", "js", "mjs"]) {
101
+ const candidate = join(root, "generated", `catalog.${ext}`);
102
+ if (existsSync(candidate))
103
+ return candidate;
104
+ }
105
+ return undefined;
106
+ }
107
+ /**
108
+ * Resolve an installed SDK subpath from the package's ESM export map.
109
+ *
110
+ * The Bun fallback transforms authored ESM to CommonJS. Most imports enter
111
+ * through `jiti.import` and use ESM conditions, but the generated org barrel
112
+ * deliberately uses `createRequire` to break catalog cycles. A per-entity
113
+ * catalog reached through that getter is therefore evaluated on jiti's
114
+ * require path, which cannot resolve this ESM-only package (`exports` has an
115
+ * `import` condition, not `require`). Pointing that one public subpath at its
116
+ * exported file preserves the package boundary without adding a misleading
117
+ * CommonJS export to the SDK.
118
+ */
119
+ export function findInstalledSdkSubpath(root, subpath) {
120
+ let current = root;
121
+ while (true) {
122
+ const packageRoot = join(current, "node_modules", "@elementumai", "edk");
123
+ const packageJson = join(packageRoot, "package.json");
124
+ if (existsSync(packageJson)) {
125
+ try {
126
+ const parsed = JSON.parse(readFileSync(packageJson, "utf8"));
127
+ const exported = parsed.exports?.[`./${subpath}`];
128
+ const target = typeof exported === "string" ? exported : exported?.import;
129
+ if (target !== undefined)
130
+ return resolve(packageRoot, target);
131
+ }
132
+ catch {
133
+ // A malformed nearer package must not hide a valid installation
134
+ // higher in the consumer workspace.
135
+ }
136
+ }
137
+ const parent = dirname(current);
138
+ if (parent === current)
139
+ return undefined;
140
+ current = parent;
141
+ }
142
+ }
143
+ /**
144
+ * Upgrade the short-lived #730 barrel shape before Bun/jiti evaluates it.
145
+ * Generated catalogs are CLI-owned, and this writes exactly the lazy-require
146
+ * form emitted by the current generator. Without the migration an existing
147
+ * workspace remains unloadable even after installing the fixed binary.
148
+ */
149
+ export function upgradeGeneratedCatalogForJiti(root) {
150
+ const catalog = findCatalog(root);
151
+ if (catalog === undefined || !catalog.endsWith(".ts"))
152
+ return;
153
+ const source = readFileSync(catalog, "utf8");
154
+ const oldDeclaration = "const require = createRequire(import.meta.url);";
155
+ if (!source.includes(oldDeclaration))
156
+ return;
157
+ const upgraded = source
158
+ .replace(oldDeclaration, 'const catalogRequire = (globalThis as { Bun?: unknown }).Bun !== undefined && typeof require === "function"\n' +
159
+ " ? require\n" +
160
+ " : createRequire(import.meta.url);")
161
+ .replace(/\(require\((?="\.\.\/(?:apps|elements|tables)\/)/g, "(catalogRequire(");
162
+ writeFileSync(catalog, upgraded, "utf8");
163
+ }
164
+ /** A `.ts` file belonging to a registered workspace. */
165
+ function isWorkspaceTypeScript(url) {
166
+ const path = fileURLToPath(url.split("?")[0]);
167
+ return path.endsWith(".ts") && owningRoot(path) !== undefined;
168
+ }
169
+ const registerHooks = nodeModule
170
+ .registerHooks;
171
+ function registerHooksOnce() {
172
+ if (hooksRegistered)
173
+ return;
174
+ hooksRegistered = true;
175
+ if (registerHooks === undefined)
176
+ return;
177
+ registerHooks({
178
+ resolve(specifier, context, nextResolve) {
179
+ const parentURL = context.parentURL;
180
+ const parentPath = parentURL !== undefined && parentURL.startsWith("file:")
181
+ ? fileURLToPath(parentURL)
182
+ : undefined;
183
+ const root = parentPath === undefined ? undefined : owningRoot(parentPath);
184
+ // `@catalog` / `@catalog/...` — only meaningful inside a workspace.
185
+ if (root !== undefined &&
186
+ parentPath !== undefined &&
187
+ (specifier === "@catalog" || specifier.startsWith("@catalog/"))) {
188
+ const catalog = findCatalog(root);
189
+ if (catalog !== undefined) {
190
+ return { url: stamp(pathToFileURL(catalog).href, root), shortCircuit: true };
191
+ }
192
+ }
193
+ const resolved = nextResolveOrTsSibling(specifier, context, nextResolve, parentURL);
194
+ if (resolved.url.startsWith("file:")) {
195
+ const resolvedRoot = owningRoot(fileURLToPath(resolved.url.split("?")[0]));
196
+ if (resolvedRoot !== undefined) {
197
+ return { ...resolved, url: stamp(resolved.url, resolvedRoot) };
198
+ }
199
+ }
200
+ return resolved;
201
+ },
202
+ load(url, context, nextLoad) {
203
+ // Authored source is always ESM. Without this, the module type is
204
+ // decided by whichever `package.json` happens to sit above the
205
+ // workspace — a root missing `"type": "module"` (an older workspace, or
206
+ // one nested under an unrelated CommonJS package) would load the same
207
+ // files as CommonJS and fail on `export default`.
208
+ if (url.startsWith("file:") && isWorkspaceTypeScript(url)) {
209
+ // `module-typescript`, not `module`: the source still needs Node's
210
+ // type stripping. Plain `module` would hand raw TypeScript to the
211
+ // JavaScript parser.
212
+ const loaded = nextLoad(url, { ...context, format: "module-typescript" });
213
+ return { ...loaded, format: "module-typescript" };
214
+ }
215
+ return nextLoad(url, context);
216
+ },
217
+ });
218
+ }
219
+ /** A specifier that names a file directly: relative, absolute, or a URL. */
220
+ function isPathSpecifier(specifier) {
221
+ return (specifier.startsWith(".") ||
222
+ specifier.startsWith("/") ||
223
+ specifier.startsWith("file:") ||
224
+ /^[A-Za-z]:[\\/]/.test(specifier));
225
+ }
226
+ /**
227
+ * Node's own resolution, with one addition: a path `.js` specifier whose file
228
+ * does not exist but whose `.ts` sibling does resolves to the `.ts`. A
229
+ * TypeScript source tree writes `./x.js` for what is `x.ts` on disk.
230
+ *
231
+ * The existence check comes first rather than catching a resolution failure,
232
+ * because the CommonJS and ESM resolvers report a miss differently
233
+ * (`MODULE_NOT_FOUND` vs `ERR_MODULE_NOT_FOUND`) and the barrel's lazy
234
+ * `require` goes through the CommonJS one. An emitted `.js` sitting next to
235
+ * its `.ts` source still wins, since it exists.
236
+ */
237
+ function nextResolveOrTsSibling(specifier, context, nextResolve, parentURL) {
238
+ if (parentURL !== undefined && specifier.endsWith(".js") && isPathSpecifier(specifier)) {
239
+ const asJs = new URL(specifier, parentURL);
240
+ if (!existsSync(fileURLToPath(asJs))) {
241
+ const asTs = new URL(specifier.replace(/\.js$/, ".ts"), parentURL);
242
+ if (existsSync(fileURLToPath(asTs))) {
243
+ return { url: asTs.href, shortCircuit: true };
244
+ }
245
+ }
246
+ }
247
+ return nextResolve(specifier, context);
248
+ }
249
+ function stamp(url, _root) {
250
+ const separator = url.includes("?") ? "&" : "?";
251
+ return `${url}${separator}${GENERATION_KEY}=${stampGeneration}`;
252
+ }
253
+ /**
254
+ * This import must be Node's, not a bundler's. Vite's SSR transform rewrites
255
+ * `import()` into its own module runner, which resolves authored files
256
+ * through Vite and never consults the hooks above — so `vitest.config.ts`
257
+ * externalizes this module and the suite exercises the loader the CLI ships.
258
+ */
259
+ async function nativeImport(specifier) {
260
+ return (await import(specifier));
261
+ }
262
+ /**
263
+ * The loader for runtimes with no `registerHooks` — in practice the
264
+ * Bun-compiled `elementum` binary.
265
+ *
266
+ * The obstacle there is not TypeScript, which Bun reads natively; it is
267
+ * resolution. A workspace file imports the SDK by package name, and a Bun
268
+ * single-file executable does not walk `node_modules` at runtime — even
269
+ * `Bun.resolveSync` fails inside one. Nothing at this level can fix that,
270
+ * because the specifier being resolved lives inside the imported file: the
271
+ * runtime has to offer an interception point, and Bun's plugin `onResolve`
272
+ * does not fire for these imports. So the binary keeps the loader that
273
+ * resolves and evaluates modules in JavaScript instead of delegating to the
274
+ * runtime, which is how it has always worked.
275
+ *
276
+ * jiti is imported dynamically so Node never loads it. `moduleCache: false`
277
+ * preserves the freshness contract the hooks path gets from generation
278
+ * stamping — more bluntly, since it re-reads the SDK too, but this path runs
279
+ * once per CLI invocation.
280
+ */
281
+ function createJitiLoader(root) {
282
+ upgradeGeneratedCatalogForJiti(root);
283
+ let pending;
284
+ const sdkCatalog = findInstalledSdkSubpath(root, "catalog");
285
+ return {
286
+ async import(file) {
287
+ pending ??= import("jiti/static").then(({ createJiti }) => {
288
+ return createJiti(import.meta.url, {
289
+ moduleCache: false,
290
+ alias: {
291
+ "@catalog": findCatalog(root) ?? join(root, "generated", "catalog.ts"),
292
+ ...(sdkCatalog !== undefined && { "@elementumai/edk/catalog": sdkCatalog }),
293
+ },
294
+ });
295
+ });
296
+ const jiti = await pending;
297
+ return (await jiti.import(resolve(file)));
298
+ },
299
+ };
300
+ }
301
+ /**
302
+ * A loader scoped to one org root and one generation. Create one per build —
303
+ * that is what makes a rebuild see edited files.
304
+ */
305
+ export function createWorkspaceLoader(orgRoot) {
306
+ const root = canonical(resolve(orgRoot));
307
+ if (registerHooks === undefined)
308
+ return createJitiLoader(root);
309
+ activeRoots.add(root);
310
+ registerHooksOnce();
311
+ let generation;
312
+ return {
313
+ async import(file) {
314
+ return enqueueImport(async () => {
315
+ generation ??= ++nextGeneration;
316
+ const previous = stampGeneration;
317
+ stampGeneration = generation;
318
+ try {
319
+ const url = pathToFileURL(resolve(file)).href;
320
+ return await nativeImport(`${url}?${GENERATION_KEY}=${generation}`);
321
+ }
322
+ finally {
323
+ stampGeneration = previous;
324
+ }
325
+ });
326
+ },
327
+ };
328
+ }
@@ -24,6 +24,10 @@ export interface AccessPolicyOwner {
24
24
  /** The owner's terraform label (namespace) — used to strip the child-resource label prefix off `*_field` refs. */
25
25
  readonly ownerTfLabel: string;
26
26
  readonly scope: ChildResourceScope;
27
+ readonly foreignFieldRefsById?: ReadonlyMap<string, {
28
+ readonly ownerRefName: string;
29
+ readonly fieldKey: string;
30
+ }>;
27
31
  }
28
32
  export interface NormalizedAccessPolicy {
29
33
  readonly filter: Filter<RefExpr, RefExpr>;
@@ -43,8 +43,13 @@ function fieldRef(value, owner, where) {
43
43
  return { kind: "field", appHandle: owner.ownerRefName, fieldKey: tfLabelToTsLabel(value.name.slice(prefix.length, -9)) };
44
44
  }
45
45
  }
46
- if (typeof value === "string")
46
+ if (typeof value === "string") {
47
+ const stateRef = owner.foreignFieldRefsById?.get(value);
48
+ if (stateRef?.ownerRefName === owner.ownerRefName) {
49
+ return { kind: "field", appHandle: owner.ownerRefName, fieldKey: stateRef.fieldKey };
50
+ }
47
51
  return { kind: "unresolved", uuid: value, hint: "field" };
52
+ }
48
53
  throw new EntityTfError(`${where}: field reference cannot be reconstructed`);
49
54
  }
50
55
  /**
@@ -127,7 +132,10 @@ export function accessPolicyFromTf(block, owner, ctx) {
127
132
  ctx.diagnostics.push(`${where}: object_id does not reference ${owner.type}.${owner.label}; skipped`);
128
133
  return undefined;
129
134
  }
130
- const filter = attrs["filter"] !== undefined ? filterFromTf(attrs["filter"], owner, where) : { type: "TRUE" };
135
+ const filterOwner = owner.foreignFieldRefsById !== undefined
136
+ ? owner
137
+ : { ...owner, foreignFieldRefsById: ctx.foreignFieldRefsById };
138
+ const filter = attrs["filter"] !== undefined ? filterFromTf(attrs["filter"], filterOwner, where) : { type: "TRUE" };
131
139
  const userIds = principalList(attrs["user_ids"], "elementum_user", `${where}: user_ids`, ctx);
132
140
  const groupIds = principalList(attrs["group_ids"], "elementum_group", `${where}: group_ids`, ctx);
133
141
  const serviceAccountIds = principalList(attrs["service_account_ids"], "elementum_service_account", `${where}: service_account_ids`, ctx);
@@ -37,6 +37,7 @@ export interface AccessPolicyToTfContext {
37
37
  */
38
38
  readonly appRefName?: string;
39
39
  readonly serviceAccounts?: Readonly<Record<string, AppServiceAccount>>;
40
+ readonly fieldAddresses?: ReadonlyMap<string, string>;
40
41
  }
41
42
  /** Filter conversion only needs owner/field context; org lookups are accepted so full policy contexts remain assignable. */
42
43
  export interface FilterToTfContext extends Omit<AccessPolicyToTfContext, "orgRefs"> {
@@ -17,8 +17,9 @@
17
17
  * in `accessPolicies[]` and must not be synthesized here. Pull sees it;
18
18
  * the integration harness strips it for fidelity against authored fixtures.
19
19
  */
20
+ import { isUnsafePlatformId } from "../../core/index.js";
20
21
  import { EntityTfError } from "../../engine/entity.js";
21
- import { expr, sanitizeName, scopedResourceLabel, tsLabelToTfLabel } from "../../engine/tf/index.js";
22
+ import { expr, isUuid, sanitizeName, scopedResourceLabel, tsLabelToTfLabel } from "../../engine/tf/index.js";
22
23
  import { fieldRefToTfValue } from "../field/to-tf.js";
23
24
  import { filterToTf as serializeFilterToTf } from "../shared/filters/tf-codec.js";
24
25
  import { serviceAccountRefToTf } from "../service-account/to-tf.js";
@@ -28,7 +29,7 @@ function isFieldToken(v) {
28
29
  }
29
30
  function fieldValueToTf(token, where, ctx) {
30
31
  const refName = token.refName ?? "";
31
- const value = fieldRefToTfValue(token.fieldType ?? "", refName, ctx.ownerTfLabel, ctx.scope);
32
+ const value = fieldRefToTfValue(token.fieldType ?? "", refName, ctx.ownerTfLabel, ctx.scope, ctx.fieldAddresses);
32
33
  if (value === undefined) {
33
34
  throw new EntityTfError(`${where}: field token "${refName}" has no terraform field resource mapping`);
34
35
  }
@@ -55,6 +56,10 @@ function picklistLiteralToTf(literal, field, ctx) {
55
56
  export function filterToTf(f, where, ctx) {
56
57
  return serializeFilterToTf(f, {
57
58
  field: (field) => {
59
+ if (typeof field === "string" && isUuid(field))
60
+ return field;
61
+ if (isUnsafePlatformId(field))
62
+ return field.value;
58
63
  if (!isFieldToken(field))
59
64
  throw new EntityTfError(`${where}: invalid filter field`);
60
65
  return fieldValueToTf(field, where, ctx);
@@ -59,16 +59,11 @@ export declare const agentStartingActionVariableType: {
59
59
  readonly text: "TEXT";
60
60
  };
61
61
  export type AgentStartingActionVariableType = (typeof agentStartingActionVariableType)[keyof typeof agentStartingActionVariableType];
62
- export interface AgentStartingActionVariable {
62
+ interface AgentStartingActionVariableBase {
63
63
  readonly key: string;
64
64
  readonly label: string;
65
65
  readonly placeholder?: string;
66
- readonly type: AgentStartingActionVariableType;
67
66
  readonly required?: boolean;
68
- readonly options?: readonly {
69
- readonly value: string;
70
- readonly label: string;
71
- }[];
72
67
  readonly validation?: {
73
68
  readonly pattern?: string;
74
69
  readonly minLength?: number;
@@ -76,8 +71,27 @@ export interface AgentStartingActionVariable {
76
71
  readonly errorMessage?: string;
77
72
  };
78
73
  }
74
+ /**
75
+ * A closed union: only SELECT carries `options`, and it requires at least
76
+ * one — TEXT/NUMBER cannot carry the field at all, and an empty SELECT
77
+ * options list isn't a value the provider accepts.
78
+ */
79
+ export type AgentStartingActionVariable = (AgentStartingActionVariableBase & {
80
+ readonly type: "TEXT" | "NUMBER";
81
+ }) | (AgentStartingActionVariableBase & {
82
+ readonly type: "SELECT";
83
+ readonly options: readonly [
84
+ {
85
+ readonly value: string;
86
+ readonly label: string;
87
+ },
88
+ ...{
89
+ readonly value: string;
90
+ readonly label: string;
91
+ }[]
92
+ ];
93
+ });
79
94
  export interface AgentStartingAction {
80
- readonly id?: UnsafePlatformId;
81
95
  readonly name: string;
82
96
  readonly prompt: string;
83
97
  readonly icon?: string;
@@ -93,9 +107,10 @@ export interface AgentV2Options extends EntityDeployOptions {
93
107
  readonly description: string;
94
108
  readonly instructions: string;
95
109
  readonly firstMessage?: string;
96
- /** Runtime knobs — carried by the REST wire shape; the terraform path drops them (reported). */
110
+ /** Not carried by the terraform path (reported). */
97
111
  readonly temperature?: number;
98
112
  readonly maxLength?: number;
113
+ /** Not carried by the terraform path (reported). */
99
114
  readonly reasoningEffort?: "minimal" | "low" | "medium" | "high" | "MINIMAL" | "LOW" | "MEDIUM" | "HIGH";
100
115
  readonly avatarAttachmentId?: UnsafePlatformId;
101
116
  readonly managedById?: UnsafePlatformId;
@@ -139,3 +154,34 @@ export interface AgentConfigured {
139
154
  }
140
155
  /** Build a v2 agent entity: identity + app from the flat options, exposing `.ref(refName)` and `.def(refName)`. */
141
156
  export declare function agent(opts: AgentV2Options): AgentConfigured;
157
+ export interface BedrockAgentOptions extends EntityDeployOptions {
158
+ /** The app that owns this agent. */
159
+ readonly app: CatalogRef<"app">;
160
+ /** Display name (1–64 characters). */
161
+ readonly name: string;
162
+ /** Optional description explaining what this agent does. */
163
+ readonly description?: string;
164
+ /**
165
+ * System instructions for the agent. Defaults to "" if omitted, satisfying the
166
+ * underlying platform and provider schema requirement.
167
+ */
168
+ readonly instructions?: string;
169
+ /**
170
+ * The initial greeting message when starting a conversation.
171
+ */
172
+ readonly firstMessage?: string;
173
+ /**
174
+ * The AI provider connector reference
175
+ * (`catalog.aiProviders.<provider>.models.<model>`).
176
+ */
177
+ readonly provider: ConnectorRef;
178
+ /**
179
+ * AWS Bedrock Agent or Agent Alias ARN.
180
+ * Format: `arn:aws:bedrock:<region>:<account-id>:agent/<agent-id>` or
181
+ * `arn:aws:bedrock:<region>:<account-id>:agent-alias/<agent-id>/<alias-id>`
182
+ */
183
+ readonly agentAliasArn: string;
184
+ }
185
+ /** Build an AWS Bedrock managed agent entity config, exposing `.ref(refName)` and `.def(refName)`. */
186
+ export declare function bedrockAgent(opts: BedrockAgentOptions): AgentConfigured;
187
+ export {};
@@ -27,7 +27,6 @@ function serializeRunAs(runAs) {
27
27
  }
28
28
  function serializeStartingAction(action) {
29
29
  return {
30
- ...(action.id !== undefined ? { id: action.id.value } : {}),
31
30
  name: action.name,
32
31
  prompt: action.prompt,
33
32
  ...(action.icon !== undefined ? { icon: action.icon } : {}),
@@ -168,3 +167,39 @@ export function agent(opts) {
168
167
  },
169
168
  };
170
169
  }
170
+ const BEDROCK_ARN_REGEX = /^arn:aws(?:-[a-z0-9]+)*:bedrock:[a-z0-9-]+:[0-9]{12}:(?:agent|agent-alias)\/[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/;
171
+ /** Build an AWS Bedrock managed agent entity config, exposing `.ref(refName)` and `.def(refName)`. */
172
+ export function bedrockAgent(opts) {
173
+ if (opts.name.length < 1 || opts.name.length > 64) {
174
+ throw new Error(`bedrockAgent name ${JSON.stringify(opts.name)} must be 1-64 characters.`);
175
+ }
176
+ if (!BEDROCK_ARN_REGEX.test(opts.agentAliasArn)) {
177
+ throw new Error(`bedrockAgent "${opts.name}": agentAliasArn ${JSON.stringify(opts.agentAliasArn)} is not a valid AWS Bedrock agent or alias ARN (expected arn:aws:bedrock:<region>:<account>:agent/<id> or agent-alias/<id>/<alias-id>).`);
178
+ }
179
+ return {
180
+ ref(refName) {
181
+ return { __kind: "agent", refName, name: opts.name, parent: opts.app.refName };
182
+ },
183
+ def(refName) {
184
+ return {
185
+ kind: "agent",
186
+ parent: opts.app.refName,
187
+ refName,
188
+ payload: slimTokens({
189
+ agent: {
190
+ bedrock: {
191
+ name: opts.name,
192
+ ...(opts.description !== undefined && { description: opts.description }),
193
+ instructions: opts.instructions ?? "",
194
+ ...(opts.firstMessage !== undefined && { firstMessage: opts.firstMessage }),
195
+ aiProviderConnectorId: opts.provider,
196
+ agentAliasArn: opts.agentAliasArn,
197
+ },
198
+ },
199
+ tools: [],
200
+ }),
201
+ ...(opts.enabled !== undefined ? { enabled: opts.enabled } : {}),
202
+ };
203
+ },
204
+ };
205
+ }