orchajs 0.26.0 → 0.27.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.
Files changed (37) hide show
  1. package/dist/browser.d.ts +2 -1
  2. package/dist/browser.js +17 -3
  3. package/dist/cli.js +58 -9
  4. package/dist/compiler/build-project.js +49 -12
  5. package/dist/compiler/compile.js +12 -1
  6. package/dist/initialize-project.js +48 -0
  7. package/dist/integrations/metro.d.ts +1 -0
  8. package/dist/integrations/metro.js +1 -1
  9. package/dist/integrations/next.d.ts +1 -0
  10. package/dist/integrations/next.js +1 -1
  11. package/dist/integrations/runtime-build.js +40 -9
  12. package/dist/orcha.d.ts +3 -2
  13. package/dist/orcha.js +76 -18
  14. package/dist/project-loader.js +4 -5
  15. package/dist/react-native.d.ts +2 -1
  16. package/dist/react-native.js +17 -3
  17. package/dist/runtime/compiled-manifest.d.ts +6 -0
  18. package/dist/runtime/compiled-manifest.js +5 -0
  19. package/dist/runtime/compiler-hook.d.ts +4 -0
  20. package/dist/runtime/compiler-hook.js +24 -6
  21. package/dist/runtime/context.js +10 -3
  22. package/dist/storage/react-native-jsonl.js +66 -19
  23. package/dist-cjs/browser.js +22 -8
  24. package/dist-cjs/compiler/build-project.js +53 -10
  25. package/dist-cjs/compiler/compile.js +15 -2
  26. package/dist-cjs/initialize-project.js +45 -0
  27. package/dist-cjs/integrations/metro.js +1 -1
  28. package/dist-cjs/integrations/next.js +1 -1
  29. package/dist-cjs/integrations/runtime-build.js +44 -19
  30. package/dist-cjs/orcha.js +109 -19
  31. package/dist-cjs/project-loader.js +4 -2
  32. package/dist-cjs/react-native.js +24 -8
  33. package/dist-cjs/runtime/compiled-manifest.js +29 -0
  34. package/dist-cjs/runtime/compiler-hook.js +26 -6
  35. package/dist-cjs/runtime/context.js +10 -3
  36. package/dist-cjs/storage/react-native-jsonl.js +64 -29
  37. package/package.json +1 -1
@@ -1,6 +1,8 @@
1
1
  import { createAmarsiaInferenceGenerator } from "./amarsia/inference.js";
2
2
  import { generateBrowserProviderResponse } from "./providers/browser.js";
3
3
  import { setNativeRuntimeLoader } from "./runtime/actions/execute.js";
4
+ import { compiledManifest } from "./runtime/compiled-manifest.js";
5
+ import { getGlobalCompiledManifest } from "./runtime/compiler-hook.js";
4
6
  import { createOrcha } from "./runtime/create-orcha.js";
5
7
  import { setCloudSessionStoreFactory, setInferenceGeneratorFactory, } from "./runtime/optional-features.js";
6
8
  import { reactNativeRuntimePlatform } from "./runtime/platform-react-native.js";
@@ -11,7 +13,19 @@ setNativeRuntimeLoader(async () => {
11
13
  });
12
14
  setInferenceGeneratorFactory(createAmarsiaInferenceGenerator);
13
15
  setCloudSessionStoreFactory((options) => new CloudSessionStore(options));
14
- export const orcha = createOrcha(() => {
15
- throw new Error("The React Native runtime requires a precompiled Orcha bundle. Configure the Orcha Metro integration.");
16
- }, generateBrowserProviderResponse, reactNativeRuntimePlatform);
16
+ const REACT_NATIVE_ORCHA_SINGLETON_KEY = Symbol.for("orchajs.reactNativeRuntime");
17
+ function getSharedReactNativeOrcha() {
18
+ const globalRecord = globalThis;
19
+ if (!globalRecord[REACT_NATIVE_ORCHA_SINGLETON_KEY]) {
20
+ globalRecord[REACT_NATIVE_ORCHA_SINGLETON_KEY] = createOrcha(() => {
21
+ const manifest = getGlobalCompiledManifest() ?? compiledManifest;
22
+ if (manifest) {
23
+ return manifest;
24
+ }
25
+ throw new Error('The React Native runtime requires a compiled Orcha manifest. Run "npx orchajs dev" or "npx orchajs build".');
26
+ }, generateBrowserProviderResponse, reactNativeRuntimePlatform);
27
+ }
28
+ return globalRecord[REACT_NATIVE_ORCHA_SINGLETON_KEY];
29
+ }
30
+ export const orcha = getSharedReactNativeOrcha();
17
31
  export * from "./runtime-entry.js";
@@ -0,0 +1,6 @@
1
+ import type { CompiledBundle } from "../types.js";
2
+ /**
3
+ * Populated automatically by `orchajs init`, `orchajs dev`, and `orchajs build`
4
+ * so Browser and React Native runtimes work with zero bundler configuration.
5
+ */
6
+ export declare const compiledManifest: CompiledBundle | undefined;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Populated automatically by `orchajs init`, `orchajs dev`, and `orchajs build`
3
+ * so Browser and React Native runtimes work with zero bundler configuration.
4
+ */
5
+ export const compiledManifest = undefined;
@@ -7,3 +7,7 @@ export declare function getRegistryCompiler(): RegistryCompiler | undefined;
7
7
  export declare function setRegistryCompilationActive(active: boolean): void;
8
8
  /** @internal True only while development tooling evaluates a registry. */
9
9
  export declare function isRegistryCompilationActive(): boolean;
10
+ /** @internal Registers a precompiled manifest on globalThis for browser / React Native runtimes. */
11
+ export declare function setGlobalCompiledManifest(bundle: CompiledBundle): void;
12
+ /** @internal Reads a precompiled manifest registered on globalThis or inside the package. */
13
+ export declare function getGlobalCompiledManifest(): CompiledBundle | undefined;
@@ -1,17 +1,35 @@
1
- let registryCompiler;
2
- let registryCompilationActive = false;
1
+ const COMPILER_HOOK_STATE_KEY = Symbol.for("orchajs.compilerHookState");
2
+ function getCompilerHookState() {
3
+ const globalRecord = globalThis;
4
+ if (!globalRecord[COMPILER_HOOK_STATE_KEY]) {
5
+ globalRecord[COMPILER_HOOK_STATE_KEY] = {
6
+ registryCompiler: undefined,
7
+ registryCompilationActive: false,
8
+ compiledManifest: undefined,
9
+ };
10
+ }
11
+ return globalRecord[COMPILER_HOOK_STATE_KEY];
12
+ }
3
13
  /** @internal Installed by Node development tooling, never by runtime bundles. */
4
14
  export function setRegistryCompiler(compiler) {
5
- registryCompiler = compiler;
15
+ getCompilerHookState().registryCompiler = compiler;
6
16
  }
7
17
  export function getRegistryCompiler() {
8
- return registryCompiler;
18
+ return getCompilerHookState().registryCompiler;
9
19
  }
10
20
  /** @internal Prevents registry evaluation from starting runtime resources. */
11
21
  export function setRegistryCompilationActive(active) {
12
- registryCompilationActive = active;
22
+ getCompilerHookState().registryCompilationActive = active;
13
23
  }
14
24
  /** @internal True only while development tooling evaluates a registry. */
15
25
  export function isRegistryCompilationActive() {
16
- return registryCompilationActive;
26
+ return getCompilerHookState().registryCompilationActive;
27
+ }
28
+ /** @internal Registers a precompiled manifest on globalThis for browser / React Native runtimes. */
29
+ export function setGlobalCompiledManifest(bundle) {
30
+ getCompilerHookState().compiledManifest = bundle;
31
+ }
32
+ /** @internal Reads a precompiled manifest registered on globalThis or inside the package. */
33
+ export function getGlobalCompiledManifest() {
34
+ return getCompilerHookState().compiledManifest;
17
35
  }
@@ -1,9 +1,16 @@
1
- const contexts = new WeakMap();
1
+ const RUNTIME_CONTEXTS_KEY = Symbol.for("orchajs.runtimeContexts");
2
+ function getContextsMap() {
3
+ const globalRecord = globalThis;
4
+ if (!globalRecord[RUNTIME_CONTEXTS_KEY]) {
5
+ globalRecord[RUNTIME_CONTEXTS_KEY] = new WeakMap();
6
+ }
7
+ return globalRecord[RUNTIME_CONTEXTS_KEY];
8
+ }
2
9
  export function setOrchaRuntimeContext(client, context) {
3
- contexts.set(client, context);
10
+ getContextsMap().set(client, context);
4
11
  }
5
12
  export function getOrchaRuntimeContext(client) {
6
- const context = contexts.get(client);
13
+ const context = getContextsMap().get(client);
7
14
  if (!context) {
8
15
  throw new Error("runTests() requires an initialized Orcha client.");
9
16
  }
@@ -1,4 +1,41 @@
1
- import AsyncStorage from "@react-native-async-storage/async-storage";
1
+ const fallbackMemoryMap = new Map();
2
+ const fallbackMemoryStorage = {
3
+ async getItem(key) {
4
+ return fallbackMemoryMap.get(key) ?? null;
5
+ },
6
+ async setItem(key, value) {
7
+ fallbackMemoryMap.set(key, value);
8
+ },
9
+ async removeItem(key) {
10
+ fallbackMemoryMap.delete(key);
11
+ },
12
+ async getAllKeys() {
13
+ return [...fallbackMemoryMap.keys()];
14
+ },
15
+ async multiSet(keyValuePairs) {
16
+ for (const [key, value] of keyValuePairs) {
17
+ fallbackMemoryMap.set(key, value);
18
+ }
19
+ },
20
+ };
21
+ let resolvedAsyncStoragePromise;
22
+ function getAsyncStorage() {
23
+ if (!resolvedAsyncStoragePromise) {
24
+ const moduleSpecifier = "@react-native-async-storage/async-storage";
25
+ resolvedAsyncStoragePromise = import(moduleSpecifier)
26
+ .then((loaded) => {
27
+ if (loaded?.default && typeof loaded.default.getItem === "function") {
28
+ return loaded.default;
29
+ }
30
+ if (typeof loaded?.getItem === "function") {
31
+ return loaded;
32
+ }
33
+ return fallbackMemoryStorage;
34
+ })
35
+ .catch(() => fallbackMemoryStorage);
36
+ }
37
+ return resolvedAsyncStoragePromise;
38
+ }
2
39
  const writes = new Map();
3
40
  const tailIndexes = new Map();
4
41
  const TAIL_CHUNK_SIZE = 100;
@@ -11,7 +48,8 @@ export class ReactNativeJsonlSessionStore {
11
48
  this.#namespace = namespace;
12
49
  }
13
50
  async read(sessionId) {
14
- const contents = await AsyncStorage.getItem(this.#key(sessionId));
51
+ const storage = await getAsyncStorage();
52
+ const contents = await storage.getItem(this.#key(sessionId));
15
53
  if (!contents) {
16
54
  return [];
17
55
  }
@@ -27,12 +65,13 @@ export class ReactNativeJsonlSessionStore {
27
65
  limit <= 0) {
28
66
  throw new Error("Invalid session event tail range.");
29
67
  }
68
+ const storage = await getAsyncStorage();
30
69
  await writes.get(this.#key(sessionId))?.catch(() => undefined);
31
70
  const index = await this.#ensureTailIndex(sessionId);
32
71
  const relevant = index.chunks.filter((chunk) => chunk.lastSequence > afterSequence);
33
72
  const events = [];
34
73
  for (const chunk of relevant) {
35
- const contents = await AsyncStorage.getItem(chunk.key);
74
+ const contents = await storage.getItem(chunk.key);
36
75
  if (contents === null) {
37
76
  tailIndexes.delete(this.#tailIndexKey(sessionId));
38
77
  return this.#readTailFromCanonical(sessionId, afterSequence, limit);
@@ -54,14 +93,15 @@ export class ReactNativeJsonlSessionStore {
54
93
  const key = this.#key(sessionId);
55
94
  const previous = writes.get(key) ?? Promise.resolve();
56
95
  const write = previous.then(async () => {
96
+ const storage = await getAsyncStorage();
57
97
  const index = await this.#ensureTailIndex(sessionId);
58
- await AsyncStorage.setItem(this.#tailPendingKey(sessionId), "1");
59
- const existing = await AsyncStorage.getItem(key);
98
+ await storage.setItem(this.#tailPendingKey(sessionId), "1");
99
+ const existing = await storage.getItem(key);
60
100
  const appended = events.map((event) => JSON.stringify(event)).join("\n");
61
- await AsyncStorage.setItem(key, `${existing ? `${existing.replace(/\n*$/, "")}\n` : ""}${appended}\n`);
101
+ await storage.setItem(key, `${existing ? `${existing.replace(/\n*$/, "")}\n` : ""}${appended}\n`);
62
102
  try {
63
103
  await this.#appendTailIndex(sessionId, index, events);
64
- await AsyncStorage.removeItem(this.#tailPendingKey(sessionId));
104
+ await storage.removeItem(this.#tailPendingKey(sessionId));
65
105
  }
66
106
  catch {
67
107
  tailIndexes.delete(this.#tailIndexKey(sessionId));
@@ -82,14 +122,16 @@ export class ReactNativeJsonlSessionStore {
82
122
  this.#allListeners.forEach((listener) => listener(sessionId, events));
83
123
  }
84
124
  async listSessionIds() {
125
+ const storage = await getAsyncStorage();
85
126
  const prefix = `@orchajs:${this.#namespace}:`;
86
- return (await AsyncStorage.getAllKeys())
127
+ return (await storage.getAllKeys())
87
128
  .filter((key) => key.startsWith(prefix))
88
129
  .map((key) => key.slice(prefix.length))
89
130
  .sort();
90
131
  }
91
132
  async getCloudAcknowledgement(sessionId) {
92
- const value = Number(await AsyncStorage.getItem(this.#acknowledgementKey(sessionId)));
133
+ const storage = await getAsyncStorage();
134
+ const value = Number(await storage.getItem(this.#acknowledgementKey(sessionId)));
93
135
  return Number.isInteger(value) && value >= 0 ? value : 0;
94
136
  }
95
137
  async setCloudAcknowledgement(sessionId, sequence) {
@@ -99,9 +141,10 @@ export class ReactNativeJsonlSessionStore {
99
141
  const key = this.#acknowledgementKey(sessionId);
100
142
  const previous = writes.get(key) ?? Promise.resolve();
101
143
  const write = previous.then(async () => {
102
- const current = Number(await AsyncStorage.getItem(key));
144
+ const storage = await getAsyncStorage();
145
+ const current = Number(await storage.getItem(key));
103
146
  if (!Number.isInteger(current) || current < sequence) {
104
- await AsyncStorage.setItem(key, String(sequence));
147
+ await storage.setItem(key, String(sequence));
105
148
  }
106
149
  });
107
150
  writes.set(key, write);
@@ -148,13 +191,14 @@ export class ReactNativeJsonlSessionStore {
148
191
  return `@orchajs-tail-chunk:${this.#namespace}:${sessionId}:${Date.now()}:${tailChunkGeneration}`;
149
192
  }
150
193
  async #ensureTailIndex(sessionId) {
194
+ const storage = await getAsyncStorage();
151
195
  const indexKey = this.#tailIndexKey(sessionId);
152
- const pending = await AsyncStorage.getItem(this.#tailPendingKey(sessionId));
196
+ const pending = await storage.getItem(this.#tailPendingKey(sessionId));
153
197
  if (!pending) {
154
198
  const cached = tailIndexes.get(indexKey);
155
199
  if (cached)
156
200
  return cached;
157
- const stored = await AsyncStorage.getItem(indexKey);
201
+ const stored = await storage.getItem(indexKey);
158
202
  if (stored) {
159
203
  try {
160
204
  const parsed = parseTailIndex(stored);
@@ -169,6 +213,7 @@ export class ReactNativeJsonlSessionStore {
169
213
  return this.#rebuildTailIndex(sessionId);
170
214
  }
171
215
  async #rebuildTailIndex(sessionId) {
216
+ const storage = await getAsyncStorage();
172
217
  const events = await this.read(sessionId);
173
218
  const chunks = [];
174
219
  const writes = [];
@@ -185,19 +230,20 @@ export class ReactNativeJsonlSessionStore {
185
230
  };
186
231
  writes.push([this.#tailIndexKey(sessionId), JSON.stringify(index)]);
187
232
  if (writes.length > 0)
188
- await AsyncStorage.multiSet(writes);
189
- await AsyncStorage.removeItem(this.#tailPendingKey(sessionId));
233
+ await storage.multiSet(writes);
234
+ await storage.removeItem(this.#tailPendingKey(sessionId));
190
235
  tailIndexes.set(this.#tailIndexKey(sessionId), index);
191
236
  return index;
192
237
  }
193
238
  async #appendTailIndex(sessionId, current, events) {
239
+ const storage = await getAsyncStorage();
194
240
  const chunks = [...current.chunks];
195
241
  const replacements = [];
196
242
  const obsolete = [];
197
243
  let remaining = [...events];
198
244
  const last = chunks.at(-1);
199
245
  if (last && last.count < TAIL_CHUNK_SIZE) {
200
- const stored = await AsyncStorage.getItem(last.key);
246
+ const stored = await storage.getItem(last.key);
201
247
  if (stored === null)
202
248
  throw new Error("Missing tail index chunk.");
203
249
  const retained = parseEvents(stored).slice(0, last.count);
@@ -223,17 +269,18 @@ export class ReactNativeJsonlSessionStore {
223
269
  this.#tailIndexKey(sessionId),
224
270
  JSON.stringify(index),
225
271
  ]);
226
- await AsyncStorage.multiSet(replacements);
272
+ await storage.multiSet(replacements);
227
273
  tailIndexes.set(this.#tailIndexKey(sessionId), index);
228
- await Promise.all(obsolete.map((key) => AsyncStorage.removeItem(key)));
274
+ await Promise.all(obsolete.map((key) => storage.removeItem(key)));
229
275
  }
230
276
  async #readTailFromCanonical(sessionId, afterSequence, limit) {
277
+ const storage = await getAsyncStorage();
231
278
  const index = await this.#rebuildTailIndex(sessionId);
232
279
  const events = [];
233
280
  for (const chunk of index.chunks) {
234
281
  if (chunk.lastSequence <= afterSequence)
235
282
  continue;
236
- const contents = await AsyncStorage.getItem(chunk.key);
283
+ const contents = await storage.getItem(chunk.key);
237
284
  if (!contents)
238
285
  continue;
239
286
  for (const event of parseEvents(contents).slice(0, chunk.count)) {
@@ -26,6 +26,8 @@ module.exports = __toCommonJS(browser_exports);
26
26
  var import_inference = require("./amarsia/inference.js");
27
27
  var import_browser = require("./providers/browser.js");
28
28
  var import_execute = require("./runtime/actions/execute.js");
29
+ var import_compiled_manifest = require("./runtime/compiled-manifest.js");
30
+ var import_compiler_hook = require("./runtime/compiler-hook.js");
29
31
  var import_create_orcha = require("./runtime/create-orcha.js");
30
32
  var import_optional_features = require("./runtime/optional-features.js");
31
33
  var import_platform_browser = require("./runtime/platform-browser.js");
@@ -37,15 +39,27 @@ __reExport(browser_exports, require("./runtime-entry.js"), module.exports);
37
39
  });
38
40
  (0, import_optional_features.setInferenceGeneratorFactory)(import_inference.createAmarsiaInferenceGenerator);
39
41
  (0, import_optional_features.setCloudSessionStoreFactory)((options) => new import_cloud.CloudSessionStore(options));
40
- const orcha = (0, import_create_orcha.createOrcha)(
41
- () => {
42
- throw new Error(
43
- "The browser runtime requires a precompiled Orcha bundle. Configure the Orcha integration for your application bundler."
42
+ const BROWSER_ORCHA_SINGLETON_KEY = Symbol.for("orchajs.browserRuntime");
43
+ function getSharedBrowserOrcha() {
44
+ const globalRecord = globalThis;
45
+ if (!globalRecord[BROWSER_ORCHA_SINGLETON_KEY]) {
46
+ globalRecord[BROWSER_ORCHA_SINGLETON_KEY] = (0, import_create_orcha.createOrcha)(
47
+ () => {
48
+ const manifest = (0, import_compiler_hook.getGlobalCompiledManifest)() ?? import_compiled_manifest.compiledManifest;
49
+ if (manifest) {
50
+ return manifest;
51
+ }
52
+ throw new Error(
53
+ 'The browser runtime requires a compiled Orcha manifest. Run "npx orchajs dev" or "npx orchajs build".'
54
+ );
55
+ },
56
+ import_browser.generateBrowserProviderResponse,
57
+ import_platform_browser.browserRuntimePlatform
44
58
  );
45
- },
46
- import_browser.generateBrowserProviderResponse,
47
- import_platform_browser.browserRuntimePlatform
48
- );
59
+ }
60
+ return globalRecord[BROWSER_ORCHA_SINGLETON_KEY];
61
+ }
62
+ const orcha = getSharedBrowserOrcha();
49
63
  // Annotate the CommonJS export names for ESM import in node:
50
64
  0 && (module.exports = {
51
65
  orcha,
@@ -114,20 +114,21 @@ async function buildProject(options = {}) {
114
114
  `The ${target} target supports precompiled native actions only. Set actions.runtime to "native".`
115
115
  );
116
116
  }
117
+ const compilerDirectory = esmCompilerDirectory();
117
118
  const runtimeFactoryPath = (0, import_path.resolve)(
118
- (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl)),
119
+ compilerDirectory,
119
120
  "../runtime/create-orcha.js"
120
121
  ).replaceAll("\\", "/");
121
122
  const runtimePlatformPath = (0, import_path.resolve)(
122
- (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl)),
123
+ compilerDirectory,
123
124
  `../runtime/platform-${target}.js`
124
125
  ).replaceAll("\\", "/");
125
126
  const runtimeEntryPath = (0, import_path.resolve)(
126
- (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl)),
127
+ compilerDirectory,
127
128
  "../runtime-entry.js"
128
129
  ).replaceAll("\\", "/");
129
130
  const providerDispatcherPath = (0, import_path.resolve)(
130
- (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl)),
131
+ compilerDirectory,
131
132
  "../providers/dispatcher.js"
132
133
  ).replaceAll("\\", "/");
133
134
  const sandboxRuntimeSource = compiledBundle.actionRuntime === "sandbox" ? createSandboxRuntimeSource() : "";
@@ -212,6 +213,7 @@ async function buildProject(options = {}) {
212
213
  `,
213
214
  "utf8"
214
215
  );
216
+ await syncPackageCompiledManifest(projectRoot, compiledBundle);
215
217
  return outputPath;
216
218
  } finally {
217
219
  (0, import_compiler_hook.setRegistryCompilationActive)(false);
@@ -224,6 +226,47 @@ async function buildProject(options = {}) {
224
226
  });
225
227
  }
226
228
  }
229
+ async function syncPackageCompiledManifest(projectRoot, bundle) {
230
+ (0, import_compiler_hook.setGlobalCompiledManifest)(bundle);
231
+ try {
232
+ const ownPackageRoot = (0, import_path.resolve)(esmCompilerDirectory(), "../..");
233
+ const consumerPackageRoot = (0, import_path.resolve)(projectRoot, "node_modules/orchajs");
234
+ if ((0, import_fs.existsSync)(consumerPackageRoot) && (0, import_fs.realpathSync)(consumerPackageRoot) !== (0, import_fs.realpathSync)(ownPackageRoot)) {
235
+ const serialized = JSON.stringify(bundle);
236
+ const esmContents = `export const compiledManifest = ${serialized};
237
+ `;
238
+ const cjsContents = `"use strict";
239
+ exports.compiledManifest = ${serialized};
240
+ `;
241
+ const esmTarget = (0, import_path.resolve)(
242
+ consumerPackageRoot,
243
+ "dist/runtime/compiled-manifest.js"
244
+ );
245
+ const cjsTarget = (0, import_path.resolve)(
246
+ consumerPackageRoot,
247
+ "dist-cjs/runtime/compiled-manifest.js"
248
+ );
249
+ if ((0, import_fs.existsSync)((0, import_path.dirname)(esmTarget))) {
250
+ await (0, import_promises.writeFile)(esmTarget, esmContents, "utf8").catch(() => void 0);
251
+ }
252
+ if ((0, import_fs.existsSync)((0, import_path.dirname)(cjsTarget))) {
253
+ await (0, import_promises.writeFile)(cjsTarget, cjsContents, "utf8").catch(() => void 0);
254
+ }
255
+ }
256
+ } catch {
257
+ }
258
+ }
259
+ function esmCompilerDirectory() {
260
+ const currentDirectory = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
261
+ const normalized = currentDirectory.replaceAll("\\", "/");
262
+ if (normalized.endsWith("/dist-cjs/compiler")) {
263
+ const esmCandidate = (0, import_path.resolve)(currentDirectory, "../../dist/compiler");
264
+ if ((0, import_fs.existsSync)(esmCandidate)) {
265
+ return esmCandidate;
266
+ }
267
+ }
268
+ return currentDirectory;
269
+ }
227
270
  function bundleFileName(target) {
228
271
  return target === "node" ? "bundle.js" : `bundle.${target}.js`;
229
272
  }
@@ -237,7 +280,7 @@ function runtimePlatformExport(target) {
237
280
  return "nodeRuntimePlatform";
238
281
  }
239
282
  function createSandboxRuntimeSource() {
240
- const runtimeDirectory = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
283
+ const runtimeDirectory = esmCompilerDirectory();
241
284
  const executePath = (0, import_path.resolve)(
242
285
  runtimeDirectory,
243
286
  "../runtime/actions/execute.js"
@@ -254,7 +297,7 @@ function createSandboxRuntimeSource() {
254
297
  ].join("\n");
255
298
  }
256
299
  function createPlatformActionRuntimeSource(target) {
257
- const runtimeDirectory = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
300
+ const runtimeDirectory = esmCompilerDirectory();
258
301
  const executePath = (0, import_path.resolve)(
259
302
  runtimeDirectory,
260
303
  "../runtime/actions/execute.js"
@@ -271,7 +314,7 @@ function createPlatformActionRuntimeSource(target) {
271
314
  ].join("\n");
272
315
  }
273
316
  function createMcpRuntimeSource(target) {
274
- const runtimeDirectory = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
317
+ const runtimeDirectory = esmCompilerDirectory();
275
318
  const clientPath = (0, import_path.resolve)(
276
319
  runtimeDirectory,
277
320
  "../runtime/mcp/client.js"
@@ -292,7 +335,7 @@ function createOptionalFeatureRuntimeSource(options) {
292
335
  if (!options.inference && !options.cloudStorage) {
293
336
  return "";
294
337
  }
295
- const sourceRoot = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
338
+ const sourceRoot = esmCompilerDirectory();
296
339
  const hooksPath = (0, import_path.resolve)(
297
340
  sourceRoot,
298
341
  "../runtime/optional-features.js"
@@ -328,7 +371,7 @@ function createOptionalFeatureRuntimeSource(options) {
328
371
  return [...imports, ...registrations, ""].join("\n");
329
372
  }
330
373
  function createNodeStorageExports() {
331
- const sourceRoot = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
374
+ const sourceRoot = esmCompilerDirectory();
332
375
  const jsonlPath = (0, import_path.resolve)(
333
376
  sourceRoot,
334
377
  "../storage/node-jsonl.js"
@@ -351,7 +394,7 @@ function allCompiledAgents(agents) {
351
394
  }
352
395
  function createProviderRuntimeSource(providerNames, target) {
353
396
  const providersDirectory = (0, import_path.resolve)(
354
- (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl)),
397
+ esmCompilerDirectory(),
355
398
  "../providers"
356
399
  );
357
400
  const imports = [];
@@ -25,9 +25,10 @@ __export(compile_exports, {
25
25
  module.exports = __toCommonJS(compile_exports);
26
26
  var import_crypto = require("crypto");
27
27
  var import_fs = require("fs");
28
+ var import_module = require("module");
28
29
  var import_path = require("path");
29
- var import_esbuild = require("esbuild");
30
30
  var import_catalog = require("../providers/catalog.js");
31
+ const require2 = (0, import_module.createRequire)(__orchaImportMetaUrl);
31
32
  function compileRegistry(registrations, registryRoot, actionRuntime = "native", target = "node") {
32
33
  if (!registrations || typeof registrations !== "object" || Array.isArray(registrations)) {
33
34
  throw new TypeError(
@@ -642,6 +643,17 @@ function validateEvaluationConfiguration(agentName, registrationName, configurat
642
643
  names.add(metric.name);
643
644
  }
644
645
  }
646
+ function loadEsbuildSync() {
647
+ try {
648
+ const esbuildModule = require2("esbuild");
649
+ return esbuildModule.buildSync;
650
+ } catch (error) {
651
+ throw new Error(
652
+ 'Compiling local actions on the fly requires "esbuild". Install it with "npm install --save-dev esbuild" or run "npx orchajs build" before deploying.',
653
+ { cause: error }
654
+ );
655
+ }
656
+ }
645
657
  function compileLocalAction(agentName, directoryName, actionsDirectory, actionRuntime, target) {
646
658
  const entryPath = (0, import_path.resolve)(actionsDirectory, directoryName, "index.js");
647
659
  if (!(0, import_fs.existsSync)(entryPath)) {
@@ -649,9 +661,10 @@ function compileLocalAction(agentName, directoryName, actionsDirectory, actionRu
649
661
  `Local action "${agentName}/${directoryName}" requires index.js.`
650
662
  );
651
663
  }
664
+ const buildSync = loadEsbuildSync();
652
665
  let output;
653
666
  try {
654
- const result = (0, import_esbuild.buildSync)({
667
+ const result = buildSync({
655
668
  entryPoints: [entryPath],
656
669
  bundle: true,
657
670
  write: false,
@@ -25,6 +25,7 @@ module.exports = __toCommonJS(initialize_project_exports);
25
25
  var import_fs = require("fs");
26
26
  var import_promises = require("fs/promises");
27
27
  var import_path = require("path");
28
+ var import_build_project = require("./compiler/build-project.js");
28
29
  var import_cli_agents_template = require("./cli-agents-template.js");
29
30
  async function initializeProject(projectRoot) {
30
31
  const files = /* @__PURE__ */ new Map([
@@ -78,10 +79,54 @@ async function initializeProject(projectRoot) {
78
79
  console.log(`Created ${relativePath}`);
79
80
  }
80
81
  await ensureGitignore(projectRoot);
82
+ await ensurePackageScripts(projectRoot);
83
+ await (0, import_build_project.buildProject)({ projectRoot }).catch(() => void 0);
81
84
  console.log(
82
85
  '\nRun "orchajs dev" to validate changes or "orchajs run exampleAgent --input \\"Hello\\"" to execute the agent.'
83
86
  );
84
87
  }
88
+ async function ensurePackageScripts(projectRoot) {
89
+ const packagePath = (0, import_path.resolve)(projectRoot, "package.json");
90
+ if (!(0, import_fs.existsSync)(packagePath)) {
91
+ return;
92
+ }
93
+ try {
94
+ const raw = await (0, import_promises.readFile)(packagePath, "utf8");
95
+ const parsed = JSON.parse(raw);
96
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
97
+ return;
98
+ }
99
+ const scripts = { ...parsed.scripts ?? {} };
100
+ let changed = false;
101
+ if (!scripts.build) {
102
+ scripts.build = "orchajs build";
103
+ changed = true;
104
+ } else if (!scripts.build.includes("orchajs build")) {
105
+ if (!scripts.prebuild) {
106
+ scripts.prebuild = "orchajs build";
107
+ changed = true;
108
+ } else if (!scripts.prebuild.includes("orchajs build")) {
109
+ scripts.prebuild = `orchajs build && ${scripts.prebuild}`;
110
+ changed = true;
111
+ }
112
+ }
113
+ if (scripts.dev && !scripts.dev.includes("orchajs") && !scripts.predev?.includes("orchajs build")) {
114
+ scripts.predev = scripts.predev ? `orchajs build && ${scripts.predev}` : "orchajs build";
115
+ changed = true;
116
+ }
117
+ if (changed) {
118
+ parsed.scripts = scripts;
119
+ await (0, import_promises.writeFile)(
120
+ packagePath,
121
+ `${JSON.stringify(parsed, null, 2)}
122
+ `,
123
+ "utf8"
124
+ );
125
+ console.log("Updated package.json scripts");
126
+ }
127
+ } catch {
128
+ }
129
+ }
85
130
  async function ensureGitignore(projectRoot) {
86
131
  const path = (0, import_path.resolve)(projectRoot, ".gitignore");
87
132
  const entry = ".orcha/";
@@ -27,7 +27,7 @@ var import_runtime_build = require("./runtime-build.js");
27
27
  async function withOrchaMetro(configuration, options = {}) {
28
28
  const projectRoot = (0, import_path.resolve)(options.projectRoot ?? process.cwd());
29
29
  await (0, import_runtime_build.queueRuntimeBuild)(projectRoot, "react-native");
30
- if (process.env.NODE_ENV !== "production") {
30
+ if (options.watch !== false && process.env.NODE_ENV !== "production") {
31
31
  (0, import_runtime_build.watchRuntimeTargets)(projectRoot, ["react-native"]);
32
32
  }
33
33
  const existingResolver = configuration.resolver?.resolveRequest;
@@ -29,7 +29,7 @@ async function withOrcha(configuration = {}, options = {}) {
29
29
  const projectRoot = (0, import_path.resolve)(options.projectRoot ?? process.cwd());
30
30
  await (0, import_runtime_build.queueRuntimeBuild)(projectRoot, "browser");
31
31
  await (0, import_runtime_build.queueRuntimeBuild)(projectRoot, "node");
32
- if (process.env.NODE_ENV !== "production") {
32
+ if (options.watch !== false && process.env.NODE_ENV !== "production") {
33
33
  (0, import_runtime_build.watchRuntimeTargets)(projectRoot, ["browser", "node"]);
34
34
  }
35
35
  const existingWebpack = configuration.webpack;