orchajs 0.26.1 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/amarsia/analytics.d.ts +1 -0
  2. package/dist/amarsia/analytics.js +28 -6
  3. package/dist/amarsia/metadata.d.ts +1 -0
  4. package/dist/amarsia/metadata.js +22 -6
  5. package/dist/browser.d.ts +2 -1
  6. package/dist/browser.js +17 -3
  7. package/dist/cli.js +58 -9
  8. package/dist/compiler/build-project.js +27 -2
  9. package/dist/compiler/compile.js +12 -1
  10. package/dist/initialize-project.js +48 -0
  11. package/dist/integrations/metro.d.ts +1 -0
  12. package/dist/integrations/metro.js +1 -1
  13. package/dist/integrations/next.d.ts +1 -0
  14. package/dist/integrations/next.js +1 -1
  15. package/dist/integrations/runtime-build.js +23 -3
  16. package/dist/orcha.js +58 -8
  17. package/dist/project-loader.js +4 -5
  18. package/dist/react-native.d.ts +2 -1
  19. package/dist/react-native.js +17 -3
  20. package/dist/runtime/agent.js +11 -4
  21. package/dist/runtime/compiled-manifest.d.ts +6 -0
  22. package/dist/runtime/compiled-manifest.js +5 -0
  23. package/dist/runtime/compiler-hook.d.ts +4 -0
  24. package/dist/runtime/compiler-hook.js +9 -0
  25. package/dist/storage/react-native-jsonl.js +66 -19
  26. package/dist-cjs/amarsia/analytics.js +38 -3
  27. package/dist-cjs/amarsia/metadata.js +17 -4
  28. package/dist-cjs/browser.js +22 -8
  29. package/dist-cjs/compiler/build-project.js +31 -0
  30. package/dist-cjs/compiler/compile.js +15 -2
  31. package/dist-cjs/initialize-project.js +45 -0
  32. package/dist-cjs/integrations/metro.js +1 -1
  33. package/dist-cjs/integrations/next.js +1 -1
  34. package/dist-cjs/integrations/runtime-build.js +27 -13
  35. package/dist-cjs/orcha.js +86 -4
  36. package/dist-cjs/project-loader.js +4 -2
  37. package/dist-cjs/react-native.js +24 -8
  38. package/dist-cjs/runtime/agent.js +13 -4
  39. package/dist-cjs/runtime/compiled-manifest.js +29 -0
  40. package/dist-cjs/runtime/compiler-hook.js +12 -1
  41. package/dist-cjs/storage/react-native-jsonl.js +64 -29
  42. package/package.json +1 -1
@@ -21,3 +21,4 @@ export declare function withAmarsiaTelemetry(options: {
21
21
  manifest: CompiledAgentManifest;
22
22
  client: AmarsiaTelemetryClient;
23
23
  }): SessionStore;
24
+ export declare function sanitizeErrorMessage(value: string): string;
@@ -555,10 +555,32 @@ function asRecord(value) {
555
555
  ? value
556
556
  : undefined;
557
557
  }
558
- function sanitizeErrorMessage(value) {
559
- return value
560
- .replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi, "Bearer [redacted]")
561
- .replace(/\b(authorization|api[-_ ]?key|token|secret|password)\b\s*[:=]\s*[^\s,;]+/gi, "$1=[redacted]")
562
- .replace(/\b(?:sk|pk|amarsia)_[A-Za-z0-9_-]{12,}\b/gi, "[redacted]")
563
- .slice(0, 8000);
558
+ export function sanitizeErrorMessage(value) {
559
+ return (value
560
+ // 1. Auth schemes & JWTs
561
+ .replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/-]+=*/gi, "$1 [redacted]")
562
+ .replace(/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, "[redacted]")
563
+ // 2. URL embedded credentials (e.g. https://user:token@host, postgres://user:pass@host)
564
+ .replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+:[^/\s@]+@)/gi, "$1[redacted]@")
565
+ // 3. Key-value secrets & credentials
566
+ .replace(/\b(authorization|api[-_ ]?key|access[-_ ]?key|secret[-_ ]?key|client[-_ ]?secret|private[-_ ]?key|session[-_ ]?token|refresh[-_ ]?token|token|secret|password|passwd|pwd|credential)\b\s*[:=]\s*("[^"]*"|'[^']*'|[^\s,;}]+)/gi, "$1=[redacted]")
567
+ // 4. Prefixed API keys & cloud access keys
568
+ .replace(/\b(?:sk|pk|rk|ak|amarsia|ams_proj|ghp|gho|ghu|ghs|ghr|glpat|xox[baprs])_[A-Za-z0-9_-]{8,}\b/gi, "[redacted]")
569
+ .replace(/\bAKIA[0-9A-Z]{16}\b/g, "[redacted]")
570
+ // 5. Tax IDs (SSN / ITIN / EIN / TIN), payment cards, & bank accounts
571
+ .replace(/\b\d{3}-\d{2}-\d{4}\b/g, "[redacted-ssn]")
572
+ .replace(/(?<![\d-])\b\d{2}-\d{7}\b(?![\d-])/g, "[redacted-tin]")
573
+ .replace(/\b(ssn|itin|ein|tin|tax[-_ ]?id|routing[-_ ]?number|account[-_ ]?number|acct[-_ ]?(?:no|num|#)?|iban|swift)\b(\s*(?:is|#|:|=)?\s*)[A-Z0-9-]{4,34}\b/gi, "$1$2[redacted-id]")
574
+ .replace(/\b(?:\d{4}[ -]?){3}\d{1,7}\b/g, "[redacted-card]")
575
+ // 6. Contact PII (Email addresses & phone numbers)
576
+ .replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, "[redacted-email]")
577
+ .replace(/(?:\+\d{1,3}[\s.-]?)?(?:\(\d{3}\)|\b\d{3})[\s.-]\d{3}[\s.-]\d{4}\b/g, "[redacted-phone]")
578
+ // 7. Client financial figures & currency amounts
579
+ .replace(/(?:[$€£¥₹]|(?:\b(?:USD|EUR|GBP|CAD|AUD|JPY|INR|CHF)\s*))\s*[-+]?\d[\d,]*(?:\.\d+)?(?:\s*(?:k|m|b|bn|mm|thousand|million|billion))?\b/gi, "[redacted-amount]")
580
+ .replace(/\b[-+]?\d[\d,]*(?:\.\d+)?\s*(?:USD|EUR|GBP|CAD|AUD|JPY|INR|CHF|dollars?|cents?|euros?|pounds?)\b/gi, "[redacted-amount]")
581
+ .replace(/\b[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?\b/g, "[redacted-figure]")
582
+ .replace(/\b(amount|total|subtotal|balance|income|revenue|salary|wages|compensation|distribution|deduction|tax|profit|loss|cost|price|fee|payment|invoice|net|gross|asset|liability|equity|credit|debit)(\s+(?:of|is|was|equals|=|:)\s*)[-+]?\d[\d,]*(?:\.\d+)?%?/gi, "$1$2[redacted-figure]")
583
+ // 8. Local user filesystem paths
584
+ .replace(/(?:\/Users\/|\/home\/|[A-Za-z]:\\Users\\)[^\s,;'")\]}]+/g, "[redacted-path]")
585
+ .slice(0, 8000));
564
586
  }
@@ -66,3 +66,4 @@ export interface AmarsiaTestMetadata {
66
66
  enabled?: boolean;
67
67
  }
68
68
  export declare function createAmarsiaProjectMetadata(bundle: CompiledBundle, projectRoot: string): AmarsiaProjectMetadata;
69
+ export declare function normalizeRepositoryUrl(url: string | undefined): string | undefined;
@@ -1,19 +1,20 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
- import { dirname, join, resolve } from "node:path";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
4
  export function createAmarsiaProjectMetadata(bundle, projectRoot) {
5
5
  const packageInfo = readPackageInfo(projectRoot);
6
6
  const projectExternalId = hashStable({
7
7
  packageName: packageInfo.name,
8
8
  rootPath: projectRoot,
9
9
  }).slice(0, 32);
10
+ const sanitizedRootPath = sanitizeRootPath(projectRoot);
10
11
  const agents = flattenAgents(bundle.agents);
11
12
  const content = {
12
13
  project: {
13
14
  external_id: projectExternalId,
14
15
  name: packageInfo.name ?? "Orcha project",
15
16
  description: packageInfo.description,
16
- root_path: projectRoot,
17
+ root_path: sanitizedRootPath,
17
18
  package_name: packageInfo.name,
18
19
  repository_url: packageInfo.repositoryUrl,
19
20
  metadata: {
@@ -30,6 +31,14 @@ export function createAmarsiaProjectMetadata(bundle, projectRoot) {
30
31
  ...content,
31
32
  };
32
33
  }
34
+ function sanitizeRootPath(projectRoot) {
35
+ const trimmed = projectRoot.trim();
36
+ if (!trimmed || trimmed === "/" || trimmed === ".") {
37
+ return ".";
38
+ }
39
+ const folderName = basename(resolve(trimmed));
40
+ return folderName || ".";
41
+ }
33
42
  function flattenAgents(agents) {
34
43
  const rootIds = new Set(Object.values(agents).map((manifest) => manifest.key));
35
44
  const manifests = new Map();
@@ -187,11 +196,18 @@ function resolveGitConfigPath(projectRoot) {
187
196
  directory = parent;
188
197
  }
189
198
  }
190
- function normalizeRepositoryUrl(url) {
191
- return url
192
- ?.replace(/^git\+/, "")
193
- .replace(/^git@github\.com:/, "https://github.com/")
199
+ export function normalizeRepositoryUrl(url) {
200
+ if (!url)
201
+ return undefined;
202
+ const cleaned = url
203
+ .trim()
204
+ .replace(/^git\+/, "")
205
+ .replace(/^git@([^:]+):/, "https://$1/")
206
+ .replace(/^ssh:\/\/(?:[^@]+@)?([^/]+)\//, "https://$1/")
207
+ .replace(/^(https?:\/\/)[^/@]+@/i, "$1")
208
+ .replace(/[?#].*$/, "")
194
209
  .replace(/\.git$/, "");
210
+ return cleaned || undefined;
195
211
  }
196
212
  function hashStable(value) {
197
213
  return createHash("sha256")
package/dist/browser.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export declare const orcha: import("./runtime-entry.js").OrchaClient;
1
+ import { type OrchaClient } from "./runtime/create-orcha.js";
2
+ export declare const orcha: OrchaClient;
2
3
  export * from "./runtime-entry.js";
package/dist/browser.js CHANGED
@@ -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 { browserRuntimePlatform } from "./runtime/platform-browser.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 browser runtime requires a precompiled Orcha bundle. Configure the Orcha integration for your application bundler.");
16
- }, generateBrowserProviderResponse, browserRuntimePlatform);
16
+ const BROWSER_ORCHA_SINGLETON_KEY = Symbol.for("orchajs.browserRuntime");
17
+ function getSharedBrowserOrcha() {
18
+ const globalRecord = globalThis;
19
+ if (!globalRecord[BROWSER_ORCHA_SINGLETON_KEY]) {
20
+ globalRecord[BROWSER_ORCHA_SINGLETON_KEY] = createOrcha(() => {
21
+ const manifest = getGlobalCompiledManifest() ?? compiledManifest;
22
+ if (manifest) {
23
+ return manifest;
24
+ }
25
+ throw new Error('The browser runtime requires a compiled Orcha manifest. Run "npx orchajs dev" or "npx orchajs build".');
26
+ }, generateBrowserProviderResponse, browserRuntimePlatform);
27
+ }
28
+ return globalRecord[BROWSER_ORCHA_SINGLETON_KEY];
29
+ }
30
+ export const orcha = getSharedBrowserOrcha();
17
31
  export * from "./runtime-entry.js";
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
3
  import { mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import { dirname, relative, resolve } from "node:path";
5
5
  import { watch } from "chokidar";
@@ -43,12 +43,14 @@ switch (command) {
43
43
  case "build": {
44
44
  const parsed = parseArguments(commandArguments, new Set(["--target"]), new Set());
45
45
  if (parsed.positionals.length > 0) {
46
- throw new Error("Usage: orchajs build [--target node|browser|react-native]");
46
+ throw new Error("Usage: orchajs build [--target node|browser|react-native|all]");
47
47
  }
48
- const target = parseBuildTarget(parsed.values.get("--target"));
48
+ const targets = parseBuildTargets(projectRoot, parsed.values.get("--target"));
49
49
  loadProjectEnvironment(projectRoot);
50
- const outputPath = await buildProject({ projectRoot, target });
51
- console.log(`Built ${relative(projectRoot, outputPath)}`);
50
+ for (const target of targets) {
51
+ const outputPath = await buildProject({ projectRoot, target });
52
+ console.log(`Built ${relative(projectRoot, outputPath)}`);
53
+ }
52
54
  break;
53
55
  }
54
56
  case "help":
@@ -79,7 +81,9 @@ async function watchProject(projectRoot, targets) {
79
81
  for (const target of targets) {
80
82
  await buildProject({ projectRoot, target });
81
83
  }
82
- const agents = Object.keys(orcha.getCompiledBundle().agents);
84
+ const manifestRaw = await readFile(resolve(projectRoot, ".orcha/dist/manifest.json"), "utf8");
85
+ const manifest = JSON.parse(manifestRaw);
86
+ const agents = Object.keys(manifest.agents ?? {});
83
87
  console.log(`[orcha] valid — ${agents.length} agent${agents.length === 1 ? "" : "s"}: ${agents.join(", ") || "none"}`);
84
88
  }
85
89
  catch (error) {
@@ -300,11 +304,56 @@ function parseDevTargets(arguments_) {
300
304
  if (parsed.positionals.length > 0) {
301
305
  throw new Error("Usage: orchajs dev [--target node|browser|react-native|all]");
302
306
  }
303
- const target = parsed.values.get("--target") ?? "node";
304
- if (target === "all") {
307
+ return parseBuildTargets(process.cwd(), parsed.values.get("--target"));
308
+ }
309
+ function parseBuildTargets(projectRoot, value) {
310
+ if (value === "all") {
305
311
  return ["browser", "react-native", "node"];
306
312
  }
307
- return [parseBuildTarget(target)];
313
+ if (value !== undefined) {
314
+ return [parseBuildTarget(value)];
315
+ }
316
+ return detectProjectTargets(projectRoot);
317
+ }
318
+ function detectProjectTargets(projectRoot) {
319
+ let dependencies = {};
320
+ const packagePath = resolve(projectRoot, "package.json");
321
+ if (existsSync(packagePath)) {
322
+ try {
323
+ const pkg = JSON.parse(readFileSync(packagePath, "utf8"));
324
+ dependencies = {
325
+ ...(pkg.dependencies ?? {}),
326
+ ...(pkg.devDependencies ?? {}),
327
+ };
328
+ }
329
+ catch {
330
+ // ignore invalid package.json
331
+ }
332
+ }
333
+ const hasNext = "next" in dependencies ||
334
+ existsSync(resolve(projectRoot, "next.config.ts")) ||
335
+ existsSync(resolve(projectRoot, "next.config.mjs")) ||
336
+ existsSync(resolve(projectRoot, "next.config.js"));
337
+ const hasBrowserApp = hasNext ||
338
+ "vite" in dependencies ||
339
+ "react-dom" in dependencies ||
340
+ existsSync(resolve(projectRoot, "vite.config.ts")) ||
341
+ existsSync(resolve(projectRoot, "vite.config.js")) ||
342
+ existsSync(resolve(projectRoot, "webpack.config.js"));
343
+ const hasReactNative = "react-native" in dependencies ||
344
+ "expo" in dependencies ||
345
+ existsSync(resolve(projectRoot, "metro.config.js"));
346
+ const targets = [];
347
+ if (hasBrowserApp) {
348
+ targets.push("browser");
349
+ }
350
+ if (hasReactNative) {
351
+ targets.push("react-native");
352
+ }
353
+ if (hasNext || targets.length === 0) {
354
+ targets.push("node");
355
+ }
356
+ return targets;
308
357
  }
309
358
  function parseBuildTarget(value) {
310
359
  if (value === undefined ||
@@ -1,11 +1,11 @@
1
- import { existsSync } from "node:fs";
1
+ import { existsSync, realpathSync } from "node:fs";
2
2
  import { mkdir, rm, writeFile } from "node:fs/promises";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import { fileURLToPath, pathToFileURL } from "node:url";
5
5
  import { build as bundleEntry } from "esbuild";
6
6
  import { loadProjectEnvironment } from "../env.js";
7
7
  import { orcha } from "../orcha.js";
8
- import { setRegistryCompilationActive, setRegistryCompiler, } from "../runtime/compiler-hook.js";
8
+ import { setGlobalCompiledManifest, setRegistryCompilationActive, setRegistryCompiler, } from "../runtime/compiler-hook.js";
9
9
  import { compileRegistry } from "./compile.js";
10
10
  import { builtInProviderCatalog, isBuiltInProvider, } from "../providers/catalog.js";
11
11
  import { ensureCompiledMcpDependencies, ensureProviderDependencies, } from "../providers/dependencies.js";
@@ -160,6 +160,7 @@ export async function buildProject(options = {}) {
160
160
  logLevel: "silent",
161
161
  });
162
162
  await writeFile(manifestPath, `${JSON.stringify(compiledBundle)}\n`, "utf8");
163
+ await syncPackageCompiledManifest(projectRoot, compiledBundle);
163
164
  return outputPath;
164
165
  }
165
166
  finally {
@@ -173,6 +174,30 @@ export async function buildProject(options = {}) {
173
174
  });
174
175
  }
175
176
  }
177
+ async function syncPackageCompiledManifest(projectRoot, bundle) {
178
+ setGlobalCompiledManifest(bundle);
179
+ try {
180
+ const ownPackageRoot = resolve(esmCompilerDirectory(), "../..");
181
+ const consumerPackageRoot = resolve(projectRoot, "node_modules/orchajs");
182
+ if (existsSync(consumerPackageRoot) &&
183
+ realpathSync(consumerPackageRoot) !== realpathSync(ownPackageRoot)) {
184
+ const serialized = JSON.stringify(bundle);
185
+ const esmContents = `export const compiledManifest = ${serialized};\n`;
186
+ const cjsContents = `"use strict";\nexports.compiledManifest = ${serialized};\n`;
187
+ const esmTarget = resolve(consumerPackageRoot, "dist/runtime/compiled-manifest.js");
188
+ const cjsTarget = resolve(consumerPackageRoot, "dist-cjs/runtime/compiled-manifest.js");
189
+ if (existsSync(dirname(esmTarget))) {
190
+ await writeFile(esmTarget, esmContents, "utf8").catch(() => undefined);
191
+ }
192
+ if (existsSync(dirname(cjsTarget))) {
193
+ await writeFile(cjsTarget, cjsContents, "utf8").catch(() => undefined);
194
+ }
195
+ }
196
+ }
197
+ catch {
198
+ // Best-effort package manifest sync.
199
+ }
200
+ }
176
201
  function esmCompilerDirectory() {
177
202
  const currentDirectory = dirname(fileURLToPath(import.meta.url));
178
203
  const normalized = currentDirectory.replaceAll("\\", "/");
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { existsSync, readFileSync, readdirSync, statSync, } from "node:fs";
3
+ import { createRequire } from "node:module";
3
4
  import { resolve } from "node:path";
4
- import { buildSync } from "esbuild";
5
5
  import { isBuiltInProvider } from "../providers/catalog.js";
6
+ const require = createRequire(import.meta.url);
6
7
  export function compileRegistry(registrations, registryRoot, actionRuntime = "native", target = "node") {
7
8
  if (!registrations ||
8
9
  typeof registrations !== "object" ||
@@ -534,11 +535,21 @@ function validateEvaluationConfiguration(agentName, registrationName, configurat
534
535
  names.add(metric.name);
535
536
  }
536
537
  }
538
+ function loadEsbuildSync() {
539
+ try {
540
+ const esbuildModule = require("esbuild");
541
+ return esbuildModule.buildSync;
542
+ }
543
+ catch (error) {
544
+ throw new Error('Compiling local actions on the fly requires "esbuild". Install it with "npm install --save-dev esbuild" or run "npx orchajs build" before deploying.', { cause: error });
545
+ }
546
+ }
537
547
  function compileLocalAction(agentName, directoryName, actionsDirectory, actionRuntime, target) {
538
548
  const entryPath = resolve(actionsDirectory, directoryName, "index.js");
539
549
  if (!existsSync(entryPath)) {
540
550
  throw new Error(`Local action "${agentName}/${directoryName}" requires index.js.`);
541
551
  }
552
+ const buildSync = loadEsbuildSync();
542
553
  let output;
543
554
  try {
544
555
  const result = buildSync({
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { appendFile, mkdir, readFile, writeFile, } from "node:fs/promises";
3
3
  import { dirname, resolve } from "node:path";
4
+ import { buildProject } from "./compiler/build-project.js";
4
5
  import { AGENTS_MD } from "./cli-agents-template.js";
5
6
  export async function initializeProject(projectRoot) {
6
7
  const files = new Map([
@@ -49,8 +50,55 @@ export async function initializeProject(projectRoot) {
49
50
  console.log(`Created ${relativePath}`);
50
51
  }
51
52
  await ensureGitignore(projectRoot);
53
+ await ensurePackageScripts(projectRoot);
54
+ await buildProject({ projectRoot }).catch(() => undefined);
52
55
  console.log('\nRun "orchajs dev" to validate changes or "orchajs run exampleAgent --input \\"Hello\\"" to execute the agent.');
53
56
  }
57
+ async function ensurePackageScripts(projectRoot) {
58
+ const packagePath = resolve(projectRoot, "package.json");
59
+ if (!existsSync(packagePath)) {
60
+ return;
61
+ }
62
+ try {
63
+ const raw = await readFile(packagePath, "utf8");
64
+ const parsed = JSON.parse(raw);
65
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
66
+ return;
67
+ }
68
+ const scripts = { ...(parsed.scripts ?? {}) };
69
+ let changed = false;
70
+ if (!scripts.build) {
71
+ scripts.build = "orchajs build";
72
+ changed = true;
73
+ }
74
+ else if (!scripts.build.includes("orchajs build")) {
75
+ if (!scripts.prebuild) {
76
+ scripts.prebuild = "orchajs build";
77
+ changed = true;
78
+ }
79
+ else if (!scripts.prebuild.includes("orchajs build")) {
80
+ scripts.prebuild = `orchajs build && ${scripts.prebuild}`;
81
+ changed = true;
82
+ }
83
+ }
84
+ if (scripts.dev &&
85
+ !scripts.dev.includes("orchajs") &&
86
+ !scripts.predev?.includes("orchajs build")) {
87
+ scripts.predev = scripts.predev
88
+ ? `orchajs build && ${scripts.predev}`
89
+ : "orchajs build";
90
+ changed = true;
91
+ }
92
+ if (changed) {
93
+ parsed.scripts = scripts;
94
+ await writeFile(packagePath, `${JSON.stringify(parsed, null, 2)}\n`, "utf8");
95
+ console.log("Updated package.json scripts");
96
+ }
97
+ }
98
+ catch {
99
+ // Best-effort package.json script update.
100
+ }
101
+ }
54
102
  async function ensureGitignore(projectRoot) {
55
103
  const path = resolve(projectRoot, ".gitignore");
56
104
  const entry = ".orcha/";
@@ -1,5 +1,6 @@
1
1
  export interface OrchaMetroOptions {
2
2
  projectRoot?: string;
3
+ watch?: boolean;
3
4
  }
4
5
  interface MetroResolverContext {
5
6
  resolveRequest(context: MetroResolverContext, moduleName: string, platform: string | null): unknown;
@@ -3,7 +3,7 @@ import { generatedBundlePath, queueRuntimeBuild, watchRuntimeTargets, } from "./
3
3
  export async function withOrchaMetro(configuration, options = {}) {
4
4
  const projectRoot = resolve(options.projectRoot ?? process.cwd());
5
5
  await queueRuntimeBuild(projectRoot, "react-native");
6
- if (process.env.NODE_ENV !== "production") {
6
+ if (options.watch !== false && process.env.NODE_ENV !== "production") {
7
7
  watchRuntimeTargets(projectRoot, ["react-native"]);
8
8
  }
9
9
  const existingResolver = configuration.resolver?.resolveRequest;
@@ -1,5 +1,6 @@
1
1
  export interface OrchaNextOptions {
2
2
  projectRoot?: string;
3
+ watch?: boolean;
3
4
  }
4
5
  interface NextWebpackContext {
5
6
  isServer: boolean;
@@ -5,7 +5,7 @@ export async function withOrcha(configuration = {}, options = {}) {
5
5
  const projectRoot = resolve(options.projectRoot ?? process.cwd());
6
6
  await queueRuntimeBuild(projectRoot, "browser");
7
7
  await queueRuntimeBuild(projectRoot, "node");
8
- if (process.env.NODE_ENV !== "production") {
8
+ if (options.watch !== false && process.env.NODE_ENV !== "production") {
9
9
  watchRuntimeTargets(projectRoot, ["browser", "node"]);
10
10
  }
11
11
  const existingWebpack = configuration.webpack;
@@ -1,7 +1,9 @@
1
+ import { existsSync } from "node:fs";
2
+ import { createRequire } from "node:module";
1
3
  import { resolve } from "node:path";
2
- import { watch } from "chokidar";
3
4
  import { buildProject } from "../compiler/build-project.js";
4
5
  import { loadProjectEnvironment } from "../env.js";
6
+ const require = createRequire(import.meta.url);
5
7
  const RUNTIME_BUILD_STATE_KEY = Symbol.for("orchajs.runtimeBuildState");
6
8
  function getRuntimeBuildState() {
7
9
  const globalRecord = globalThis;
@@ -32,12 +34,30 @@ export function watchRuntimeTargets(projectRoot, targets) {
32
34
  if (state.watchedTargets.has(key)) {
33
35
  return;
34
36
  }
37
+ let watchFn;
38
+ try {
39
+ const chokidarModule = require("chokidar");
40
+ watchFn = chokidarModule.watch;
41
+ }
42
+ catch {
43
+ return;
44
+ }
35
45
  state.watchedTargets.add(key);
36
46
  let timer;
37
- watch(resolve(projectRoot, "orcha"), { ignoreInitial: true }).on("all", () => {
47
+ const watcher = watchFn(resolve(projectRoot, "orcha"), {
48
+ ignoreInitial: true,
49
+ persistent: false,
50
+ });
51
+ watcher.on("all", () => {
38
52
  clearTimeout(timer);
39
53
  timer = setTimeout(() => {
40
- void targets.reduce((pending, target) => pending.then(() => queueRuntimeBuild(projectRoot, target)), Promise.resolve());
54
+ if (!existsSync(resolve(projectRoot, "orcha/index.ts"))) {
55
+ return;
56
+ }
57
+ void targets
58
+ .reduce((pending, target) => pending.then(() => queueRuntimeBuild(projectRoot, target)), Promise.resolve())
59
+ .catch(() => undefined);
41
60
  }, 75);
61
+ timer.unref?.();
42
62
  });
43
63
  }
package/dist/orcha.js CHANGED
@@ -1,10 +1,12 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { resolve } from "node:path";
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync, } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
3
4
  import { createAmarsiaInferenceGenerator } from "./amarsia/inference.js";
5
+ import { compileRegistry } from "./compiler/compile.js";
4
6
  import { generateProviderResponse } from "./providers/index.js";
5
7
  import { setNativeRuntimeLoader, setSandboxRuntimeLoader, } from "./runtime/actions/execute.js";
6
8
  import { executeNativeAction } from "./runtime/actions/native.js";
7
- import { getRegistryCompiler } from "./runtime/compiler-hook.js";
9
+ import { getRegistryCompiler, setGlobalCompiledManifest, } from "./runtime/compiler-hook.js";
8
10
  import { createOrcha, } from "./runtime/create-orcha.js";
9
11
  import { setMcpClientFactory } from "./runtime/mcp/client.js";
10
12
  import { setCloudSessionStoreFactory, setInferenceGeneratorFactory, } from "./runtime/optional-features.js";
@@ -22,7 +24,7 @@ setMcpClientFactory(async (server, credentials) => {
22
24
  });
23
25
  setInferenceGeneratorFactory(createAmarsiaInferenceGenerator);
24
26
  setCloudSessionStoreFactory((options) => new CloudSessionStore(options));
25
- const NODE_ORCHA_SINGLETON_KEY = Symbol.for("orchajs.nodeOrchaSingleton");
27
+ const NODE_ORCHA_SINGLETON_KEY = Symbol.for("orchajs.runtime");
26
28
  function getSharedNodeOrcha() {
27
29
  const globalRecord = globalThis;
28
30
  if (!globalRecord[NODE_ORCHA_SINGLETON_KEY]) {
@@ -34,11 +36,18 @@ function getSharedNodeOrcha() {
34
36
  if (process.env.ORCHA_COMPILING === "1" && compiler) {
35
37
  return compiler(configuration, projectRoot);
36
38
  }
37
- if (isPrecompiledRuntime() ||
38
- existsSync(compiledManifestPath(projectRoot))) {
39
+ const precompiled = isPrecompiledRuntime();
40
+ const manifestFile = compiledManifestPath(projectRoot);
41
+ if (precompiled || existsSync(manifestFile)) {
39
42
  return loadCompiledManifest(projectRoot, configuration);
40
43
  }
41
- throw new Error('Orcha agents must be compiled before runtime initialization. Run "npx orchajs dev" during development or "npx orchajs build" before starting the application.');
44
+ const registryRoot = resolve(projectRoot, "orcha");
45
+ if (existsSync(registryRoot)) {
46
+ const compiled = compileRegistry(configuration.agents, registryRoot, configuration.actions?.runtime ?? "native", "node");
47
+ persistDevManifest(projectRoot, manifestFile, compiled);
48
+ return compiled;
49
+ }
50
+ throw new Error('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".');
42
51
  }, generateProviderResponse, nodeRuntimePlatform);
43
52
  }
44
53
  return globalRecord[NODE_ORCHA_SINGLETON_KEY];
@@ -50,10 +59,45 @@ function isPrecompiledRuntime() {
50
59
  process.env.AWS_LAMBDA_FUNCTION_NAME !== undefined ||
51
60
  process.env.AWS_EXECUTION_ENV?.startsWith("AWS_Lambda_") === true);
52
61
  }
62
+ function persistDevManifest(projectRoot, manifestPath, bundle) {
63
+ setGlobalCompiledManifest(bundle);
64
+ try {
65
+ mkdirSync(dirname(manifestPath), { recursive: true });
66
+ writeFileSync(manifestPath, `${JSON.stringify(bundle)}\n`, "utf8");
67
+ }
68
+ catch {
69
+ // Best-effort cache write in development environments.
70
+ }
71
+ try {
72
+ const ownPackageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
73
+ const consumerPackageRoot = resolve(projectRoot, "node_modules/orchajs");
74
+ if (existsSync(consumerPackageRoot) &&
75
+ realpathSync(consumerPackageRoot) !== realpathSync(ownPackageRoot)) {
76
+ const serialized = JSON.stringify(bundle);
77
+ const esmTarget = resolve(consumerPackageRoot, "dist/runtime/compiled-manifest.js");
78
+ const cjsTarget = resolve(consumerPackageRoot, "dist-cjs/runtime/compiled-manifest.js");
79
+ if (existsSync(dirname(esmTarget))) {
80
+ writeFileSync(esmTarget, `export const compiledManifest = ${serialized};\n`, "utf8");
81
+ }
82
+ if (existsSync(dirname(cjsTarget))) {
83
+ writeFileSync(cjsTarget, `"use strict";\nexports.compiledManifest = ${serialized};\n`, "utf8");
84
+ }
85
+ }
86
+ }
87
+ catch {
88
+ // Best-effort package manifest sync in development environments.
89
+ }
90
+ }
53
91
  function loadCompiledManifest(projectRoot, configuration) {
54
92
  const manifestPath = compiledManifestPath(projectRoot);
55
93
  if (!existsSync(manifestPath)) {
56
- throw new Error(`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.`);
94
+ const registryRoot = resolve(projectRoot, "orcha");
95
+ if (existsSync(registryRoot)) {
96
+ const compiled = compileRegistry(configuration.agents, registryRoot, configuration.actions?.runtime ?? "native", "node");
97
+ persistDevManifest(projectRoot, manifestPath, compiled);
98
+ return compiled;
99
+ }
100
+ throw new Error(`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.`);
57
101
  }
58
102
  let parsed;
59
103
  try {
@@ -77,6 +121,12 @@ function loadCompiledManifest(projectRoot, configuration) {
77
121
  const compiledAgents = Object.keys(bundle.agents).sort();
78
122
  if (registeredAgents.length !== compiledAgents.length ||
79
123
  registeredAgents.some((name, index) => name !== compiledAgents[index])) {
124
+ const registryRoot = resolve(projectRoot, "orcha");
125
+ if (!isPrecompiledRuntime() && existsSync(registryRoot)) {
126
+ const recompiled = compileRegistry(configuration.agents, registryRoot, configuration.actions?.runtime ?? "native", "node");
127
+ persistDevManifest(projectRoot, manifestPath, recompiled);
128
+ return recompiled;
129
+ }
80
130
  throw new Error(`Orcha compiled manifest does not match the registered agents. Run "npx orchajs build" again. Expected [${registeredAgents.join(", ")}], found [${compiledAgents.join(", ")}].`);
81
131
  }
82
132
  return bundle;
@@ -19,9 +19,9 @@ export async function loadProject(projectRoot) {
19
19
  const bundlePath = resolve(temporaryDirectory, `registry-${process.pid}-${Date.now()}.mjs`);
20
20
  await mkdir(temporaryDirectory, { recursive: true });
21
21
  try {
22
- const previousBundle = orcha.isInitialized()
23
- ? orcha.getCompiledBundle()
24
- : undefined;
22
+ if (orcha.isInitialized()) {
23
+ await orcha.close();
24
+ }
25
25
  await bundleEntry({
26
26
  entryPoints: [registryPath],
27
27
  outfile: bundlePath,
@@ -43,8 +43,7 @@ export async function loadProject(projectRoot) {
43
43
  restoreEnvironment("ORCHA_PROJECT_ROOT", previousRoot);
44
44
  restoreEnvironment("ORCHA_COMPILING", previousCompiling);
45
45
  }
46
- if (!orcha.isInitialized() ||
47
- orcha.getCompiledBundle() === previousBundle) {
46
+ if (!orcha.isInitialized()) {
48
47
  throw new Error('"orcha/index.ts" must call orcha.init({ agents, ... }).');
49
48
  }
50
49
  if (!orcha.isInferenceEnabled()) {
@@ -1,2 +1,3 @@
1
- export declare const orcha: import("./runtime-entry.js").OrchaClient;
1
+ import { type OrchaClient } from "./runtime/create-orcha.js";
2
+ export declare const orcha: OrchaClient;
2
3
  export * from "./runtime-entry.js";
@@ -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";