orchajs 0.26.1 → 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.
@@ -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,
@@ -213,6 +213,7 @@ async function buildProject(options = {}) {
213
213
  `,
214
214
  "utf8"
215
215
  );
216
+ await syncPackageCompiledManifest(projectRoot, compiledBundle);
216
217
  return outputPath;
217
218
  } finally {
218
219
  (0, import_compiler_hook.setRegistryCompilationActive)(false);
@@ -225,6 +226,36 @@ async function buildProject(options = {}) {
225
226
  });
226
227
  }
227
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
+ }
228
259
  function esmCompilerDirectory() {
229
260
  const currentDirectory = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
230
261
  const normalized = currentDirectory.replaceAll("\\", "/");
@@ -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;
@@ -24,10 +24,12 @@ __export(runtime_build_exports, {
24
24
  watchRuntimeTargets: () => watchRuntimeTargets
25
25
  });
26
26
  module.exports = __toCommonJS(runtime_build_exports);
27
+ var import_fs = require("fs");
28
+ var import_module = require("module");
27
29
  var import_path = require("path");
28
- var import_chokidar = require("chokidar");
29
30
  var import_build_project = require("../compiler/build-project.js");
30
31
  var import_env = require("../env.js");
32
+ const require2 = (0, import_module.createRequire)(__orchaImportMetaUrl);
31
33
  const RUNTIME_BUILD_STATE_KEY = Symbol.for("orchajs.runtimeBuildState");
32
34
  function getRuntimeBuildState() {
33
35
  const globalRecord = globalThis;
@@ -58,20 +60,32 @@ function watchRuntimeTargets(projectRoot, targets) {
58
60
  if (state.watchedTargets.has(key)) {
59
61
  return;
60
62
  }
63
+ let watchFn;
64
+ try {
65
+ const chokidarModule = require2("chokidar");
66
+ watchFn = chokidarModule.watch;
67
+ } catch {
68
+ return;
69
+ }
61
70
  state.watchedTargets.add(key);
62
71
  let timer;
63
- (0, import_chokidar.watch)((0, import_path.resolve)(projectRoot, "orcha"), { ignoreInitial: true }).on(
64
- "all",
65
- () => {
66
- clearTimeout(timer);
67
- timer = setTimeout(() => {
68
- void targets.reduce(
69
- (pending, target) => pending.then(() => queueRuntimeBuild(projectRoot, target)),
70
- Promise.resolve()
71
- );
72
- }, 75);
73
- }
74
- );
72
+ const watcher = watchFn((0, import_path.resolve)(projectRoot, "orcha"), {
73
+ ignoreInitial: true,
74
+ persistent: false
75
+ });
76
+ watcher.on("all", () => {
77
+ clearTimeout(timer);
78
+ timer = setTimeout(() => {
79
+ if (!(0, import_fs.existsSync)((0, import_path.resolve)(projectRoot, "orcha/index.ts"))) {
80
+ return;
81
+ }
82
+ void targets.reduce(
83
+ (pending, target) => pending.then(() => queueRuntimeBuild(projectRoot, target)),
84
+ Promise.resolve()
85
+ ).catch(() => void 0);
86
+ }, 75);
87
+ timer.unref?.();
88
+ });
75
89
  }
76
90
  // Annotate the CommonJS export names for ESM import in node:
77
91
  0 && (module.exports = {
package/dist-cjs/orcha.js CHANGED
@@ -24,7 +24,9 @@ __export(orcha_exports, {
24
24
  module.exports = __toCommonJS(orcha_exports);
25
25
  var import_fs = require("fs");
26
26
  var import_path = require("path");
27
+ var import_url = require("url");
27
28
  var import_inference = require("./amarsia/inference.js");
29
+ var import_compile = require("./compiler/compile.js");
28
30
  var import_providers = require("./providers/index.js");
29
31
  var import_execute = require("./runtime/actions/execute.js");
30
32
  var import_native = require("./runtime/actions/native.js");
@@ -46,7 +48,7 @@ var import_cloud = require("./storage/cloud.js");
46
48
  });
47
49
  (0, import_optional_features.setInferenceGeneratorFactory)(import_inference.createAmarsiaInferenceGenerator);
48
50
  (0, import_optional_features.setCloudSessionStoreFactory)((options) => new import_cloud.CloudSessionStore(options));
49
- const NODE_ORCHA_SINGLETON_KEY = Symbol.for("orchajs.nodeOrchaSingleton");
51
+ const NODE_ORCHA_SINGLETON_KEY = Symbol.for("orchajs.runtime");
50
52
  function getSharedNodeOrcha() {
51
53
  const globalRecord = globalThis;
52
54
  if (!globalRecord[NODE_ORCHA_SINGLETON_KEY]) {
@@ -59,11 +61,24 @@ function getSharedNodeOrcha() {
59
61
  if (process.env.ORCHA_COMPILING === "1" && compiler) {
60
62
  return compiler(configuration, projectRoot);
61
63
  }
62
- if (isPrecompiledRuntime() || (0, import_fs.existsSync)(compiledManifestPath(projectRoot))) {
64
+ const precompiled = isPrecompiledRuntime();
65
+ const manifestFile = compiledManifestPath(projectRoot);
66
+ if (precompiled || (0, import_fs.existsSync)(manifestFile)) {
63
67
  return loadCompiledManifest(projectRoot, configuration);
64
68
  }
69
+ const registryRoot = (0, import_path.resolve)(projectRoot, "orcha");
70
+ if ((0, import_fs.existsSync)(registryRoot)) {
71
+ const compiled = (0, import_compile.compileRegistry)(
72
+ configuration.agents,
73
+ registryRoot,
74
+ configuration.actions?.runtime ?? "native",
75
+ "node"
76
+ );
77
+ persistDevManifest(projectRoot, manifestFile, compiled);
78
+ return compiled;
79
+ }
65
80
  throw new Error(
66
- 'Orcha agents must be compiled before runtime initialization. Run "npx orchajs dev" during development or "npx orchajs build" before starting the application.'
81
+ 'Orcha agents could not be found in "orcha/" and no precompiled manifest exists at ".orcha/dist/manifest.json". Run "npx orchajs init" or "npx orchajs build".'
67
82
  );
68
83
  },
69
84
  import_providers.generateProviderResponse,
@@ -76,11 +91,67 @@ const orcha = getSharedNodeOrcha();
76
91
  function isPrecompiledRuntime() {
77
92
  return process.env.ORCHA_USE_BUILD === "1" || process.env.NODE_ENV === "production" || process.env.AWS_LAMBDA_FUNCTION_NAME !== void 0 || process.env.AWS_EXECUTION_ENV?.startsWith("AWS_Lambda_") === true;
78
93
  }
94
+ function persistDevManifest(projectRoot, manifestPath, bundle) {
95
+ (0, import_compiler_hook.setGlobalCompiledManifest)(bundle);
96
+ try {
97
+ (0, import_fs.mkdirSync)((0, import_path.dirname)(manifestPath), { recursive: true });
98
+ (0, import_fs.writeFileSync)(manifestPath, `${JSON.stringify(bundle)}
99
+ `, "utf8");
100
+ } catch {
101
+ }
102
+ try {
103
+ const ownPackageRoot = (0, import_path.resolve)(
104
+ (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl)),
105
+ ".."
106
+ );
107
+ const consumerPackageRoot = (0, import_path.resolve)(projectRoot, "node_modules/orchajs");
108
+ if ((0, import_fs.existsSync)(consumerPackageRoot) && (0, import_fs.realpathSync)(consumerPackageRoot) !== (0, import_fs.realpathSync)(ownPackageRoot)) {
109
+ const serialized = JSON.stringify(bundle);
110
+ const esmTarget = (0, import_path.resolve)(
111
+ consumerPackageRoot,
112
+ "dist/runtime/compiled-manifest.js"
113
+ );
114
+ const cjsTarget = (0, import_path.resolve)(
115
+ consumerPackageRoot,
116
+ "dist-cjs/runtime/compiled-manifest.js"
117
+ );
118
+ if ((0, import_fs.existsSync)((0, import_path.dirname)(esmTarget))) {
119
+ (0, import_fs.writeFileSync)(
120
+ esmTarget,
121
+ `export const compiledManifest = ${serialized};
122
+ `,
123
+ "utf8"
124
+ );
125
+ }
126
+ if ((0, import_fs.existsSync)((0, import_path.dirname)(cjsTarget))) {
127
+ (0, import_fs.writeFileSync)(
128
+ cjsTarget,
129
+ `"use strict";
130
+ exports.compiledManifest = ${serialized};
131
+ `,
132
+ "utf8"
133
+ );
134
+ }
135
+ }
136
+ } catch {
137
+ }
138
+ }
79
139
  function loadCompiledManifest(projectRoot, configuration) {
80
140
  const manifestPath = compiledManifestPath(projectRoot);
81
141
  if (!(0, import_fs.existsSync)(manifestPath)) {
142
+ const registryRoot = (0, import_path.resolve)(projectRoot, "orcha");
143
+ if ((0, import_fs.existsSync)(registryRoot)) {
144
+ const compiled = (0, import_compile.compileRegistry)(
145
+ configuration.agents,
146
+ registryRoot,
147
+ configuration.actions?.runtime ?? "native",
148
+ "node"
149
+ );
150
+ persistDevManifest(projectRoot, manifestPath, compiled);
151
+ return compiled;
152
+ }
82
153
  throw new Error(
83
- `ORCHA_PRODUCTION_BUNDLE_MISSING: "${manifestPath}" was not found. Run "npx orchajs build" before packaging, include ".orcha/dist" in the deployment, or configure the Orcha build integration.`
154
+ `ORCHA_PRODUCTION_BUNDLE_MISSING: "${manifestPath}" was not found. Run "npx orchajs build" before packaging, include ".orcha/dist" in the deployment, or keep the "orcha/" directory available at runtime.`
84
155
  );
85
156
  }
86
157
  let parsed;
@@ -103,6 +174,17 @@ function loadCompiledManifest(projectRoot, configuration) {
103
174
  if (registeredAgents.length !== compiledAgents.length || registeredAgents.some(
104
175
  (name, index) => name !== compiledAgents[index]
105
176
  )) {
177
+ const registryRoot = (0, import_path.resolve)(projectRoot, "orcha");
178
+ if (!isPrecompiledRuntime() && (0, import_fs.existsSync)(registryRoot)) {
179
+ const recompiled = (0, import_compile.compileRegistry)(
180
+ configuration.agents,
181
+ registryRoot,
182
+ configuration.actions?.runtime ?? "native",
183
+ "node"
184
+ );
185
+ persistDevManifest(projectRoot, manifestPath, recompiled);
186
+ return recompiled;
187
+ }
106
188
  throw new Error(
107
189
  `Orcha compiled manifest does not match the registered agents. Run "npx orchajs build" again. Expected [${registeredAgents.join(", ")}], found [${compiledAgents.join(", ")}].`
108
190
  );
@@ -53,7 +53,9 @@ async function loadProject(projectRoot) {
53
53
  );
54
54
  await (0, import_promises.mkdir)(temporaryDirectory, { recursive: true });
55
55
  try {
56
- const previousBundle = import_orcha.orcha.isInitialized() ? import_orcha.orcha.getCompiledBundle() : void 0;
56
+ if (import_orcha.orcha.isInitialized()) {
57
+ await import_orcha.orcha.close();
58
+ }
57
59
  await (0, import_esbuild.build)({
58
60
  entryPoints: [registryPath],
59
61
  outfile: bundlePath,
@@ -74,7 +76,7 @@ async function loadProject(projectRoot) {
74
76
  restoreEnvironment("ORCHA_PROJECT_ROOT", previousRoot);
75
77
  restoreEnvironment("ORCHA_COMPILING", previousCompiling);
76
78
  }
77
- if (!import_orcha.orcha.isInitialized() || import_orcha.orcha.getCompiledBundle() === previousBundle) {
79
+ if (!import_orcha.orcha.isInitialized()) {
78
80
  throw new Error(
79
81
  '"orcha/index.ts" must call orcha.init({ agents, ... }).'
80
82
  );
@@ -26,6 +26,8 @@ module.exports = __toCommonJS(react_native_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_react_native = require("./runtime/platform-react-native.js");
@@ -37,15 +39,29 @@ __reExport(react_native_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 React Native runtime requires a precompiled Orcha bundle. Configure the Orcha Metro integration."
44
- );
45
- },
46
- import_browser.generateBrowserProviderResponse,
47
- import_platform_react_native.reactNativeRuntimePlatform
42
+ const REACT_NATIVE_ORCHA_SINGLETON_KEY = Symbol.for(
43
+ "orchajs.reactNativeRuntime"
48
44
  );
45
+ function getSharedReactNativeOrcha() {
46
+ const globalRecord = globalThis;
47
+ if (!globalRecord[REACT_NATIVE_ORCHA_SINGLETON_KEY]) {
48
+ globalRecord[REACT_NATIVE_ORCHA_SINGLETON_KEY] = (0, import_create_orcha.createOrcha)(
49
+ () => {
50
+ const manifest = (0, import_compiler_hook.getGlobalCompiledManifest)() ?? import_compiled_manifest.compiledManifest;
51
+ if (manifest) {
52
+ return manifest;
53
+ }
54
+ throw new Error(
55
+ 'The React Native runtime requires a compiled Orcha manifest. Run "npx orchajs dev" or "npx orchajs build".'
56
+ );
57
+ },
58
+ import_browser.generateBrowserProviderResponse,
59
+ import_platform_react_native.reactNativeRuntimePlatform
60
+ );
61
+ }
62
+ return globalRecord[REACT_NATIVE_ORCHA_SINGLETON_KEY];
63
+ }
64
+ const orcha = getSharedReactNativeOrcha();
49
65
  // Annotate the CommonJS export names for ESM import in node:
50
66
  0 && (module.exports = {
51
67
  orcha,