orchajs 0.27.2 → 0.27.4

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.
@@ -290,10 +290,21 @@ function createNodeStorageExports() {
290
290
  ].join("\n");
291
291
  }
292
292
  function allCompiledAgents(agents) {
293
- return Object.values(agents).flatMap((agent) => [
294
- agent,
295
- ...Object.values(agent.subagents ?? {}),
296
- ]);
293
+ const collected = [];
294
+ const visited = new Set();
295
+ const visit = (agent) => {
296
+ if (visited.has(agent))
297
+ return;
298
+ visited.add(agent);
299
+ collected.push(agent);
300
+ for (const child of Object.values(agent.subagents ?? {})) {
301
+ visit(child);
302
+ }
303
+ };
304
+ for (const agent of Object.values(agents)) {
305
+ visit(agent);
306
+ }
307
+ return collected;
297
308
  }
298
309
  function createProviderRuntimeSource(providerNames, target) {
299
310
  const providersDirectory = resolve(esmCompilerDirectory(), "../providers");
@@ -10,22 +10,55 @@ export function compileRegistry(registrations, registryRoot, actionRuntime = "na
10
10
  Array.isArray(registrations)) {
11
11
  throw new TypeError('orcha.init() requires an "agents" object of registered folder paths.');
12
12
  }
13
- const agents = {};
13
+ const normalizedRegistrations = {};
14
+ const registrationsByPath = new Map();
14
15
  for (const [key, registration] of Object.entries(registrations)) {
15
16
  if (!key.trim()) {
16
17
  throw new Error("Registered agent names cannot be empty.");
17
18
  }
18
19
  const normalized = normalizeAgentRegistration(key, registration);
20
+ normalizedRegistrations[key] = normalized;
21
+ const resolvedPath = resolve(registryRoot, normalized.path);
22
+ if (!registrationsByPath.has(resolvedPath)) {
23
+ registrationsByPath.set(resolvedPath, {
24
+ key,
25
+ registration: normalized,
26
+ });
27
+ }
28
+ }
29
+ if (Object.keys(normalizedRegistrations).length === 0) {
30
+ throw new Error("At least one agent must be registered.");
31
+ }
32
+ const compileRegistrationTree = (key, normalized, ownerPath, ancestry) => {
33
+ const resolvedPath = resolve(registryRoot, normalized.path);
34
+ const inherited = normalizedRegistrations[key] ??
35
+ registrationsByPath.get(resolvedPath)?.registration;
36
+ const effectiveMcp = Object.keys(normalized.mcp).length > 0
37
+ ? normalized.mcp
38
+ : (inherited?.mcp ?? {});
39
+ const effectiveSubagentRegistrations = Object.keys(normalized.subagents).length > 0
40
+ ? normalized.subagents
41
+ : (inherited?.subagents ?? {});
19
42
  const subagents = {};
20
- for (const [subagentKey, registration] of Object.entries(normalized.subagents)) {
43
+ for (const [subagentKey, subagentRegistration] of Object.entries(effectiveSubagentRegistrations)) {
21
44
  if (!subagentKey.trim()) {
22
- throw new Error(`Agent "${key}" has an empty subagent name.`);
45
+ throw new Error(`Agent "${ownerPath}" has an empty subagent name.`);
23
46
  }
24
- const subagent = normalizeSubagentRegistration(key, subagentKey, registration);
25
- subagents[subagentKey] = compileAgent(subagentKey, subagent.path, subagent.mcp, registryRoot, actionRuntime, target);
47
+ const normalizedSubagent = normalizeSubagentRegistration(ownerPath, subagentKey, subagentRegistration);
48
+ const childResolvedPath = resolve(registryRoot, normalizedSubagent.path);
49
+ const cycleExists = ancestry.some((ancestor) => ancestor.resolvedPath === childResolvedPath ||
50
+ ancestor.key === subagentKey);
51
+ if (cycleExists) {
52
+ const chain = [
53
+ ...ancestry.map((item) => item.key),
54
+ subagentKey,
55
+ ].join(" -> ");
56
+ throw new Error(`Circular subagent registration detected: ${chain}.`);
57
+ }
58
+ subagents[subagentKey] = compileRegistrationTree(subagentKey, normalizedSubagent, `${ownerPath}/${subagentKey}`, [...ancestry, { key: subagentKey, resolvedPath: childResolvedPath }]);
26
59
  }
27
- const parent = compileAgent(key, normalized.path, normalized.mcp, registryRoot, actionRuntime, target);
28
- agents[key] = Object.freeze({
60
+ const parent = compileAgent(key, normalized.path, effectiveMcp, registryRoot, actionRuntime, target);
61
+ return Object.freeze({
29
62
  ...parent,
30
63
  subagentPolicy: Object.keys(subagents).length > 0
31
64
  ? Object.freeze({
@@ -35,9 +68,11 @@ export function compileRegistry(registrations, registryRoot, actionRuntime = "na
35
68
  : parent.subagentPolicy,
36
69
  subagents: Object.freeze(subagents),
37
70
  });
38
- }
39
- if (Object.keys(agents).length === 0) {
40
- throw new Error("At least one agent must be registered.");
71
+ };
72
+ const agents = {};
73
+ for (const [key, normalized] of Object.entries(normalizedRegistrations)) {
74
+ const resolvedPath = resolve(registryRoot, normalized.path);
75
+ agents[key] = compileRegistrationTree(key, normalized, key, [{ key, resolvedPath }]);
41
76
  }
42
77
  return Object.freeze({
43
78
  schemaVersion: 1,
@@ -76,7 +111,7 @@ function normalizeSubagentRegistration(parentKey, key, registration) {
76
111
  if (!registration.trim()) {
77
112
  throw new Error(`Subagent "${parentKey}/${key}" must register a folder path.`);
78
113
  }
79
- return { path: registration, mcp: {} };
114
+ return { path: registration, mcp: {}, subagents: {} };
80
115
  }
81
116
  if (!registration ||
82
117
  typeof registration !== "object" ||
@@ -84,10 +119,17 @@ function normalizeSubagentRegistration(parentKey, key, registration) {
84
119
  !registration.path.trim()) {
85
120
  throw new Error(`Subagent "${parentKey}/${key}" must register a folder path.`);
86
121
  }
122
+ if (registration.subagents !== undefined &&
123
+ (!registration.subagents ||
124
+ typeof registration.subagents !== "object" ||
125
+ Array.isArray(registration.subagents))) {
126
+ throw new Error(`Subagent "${parentKey}/${key}" subagents must be an object of named registrations.`);
127
+ }
87
128
  validateMcpRegistration(`Subagent "${parentKey}/${key}"`, registration.mcp);
88
129
  return {
89
130
  path: registration.path,
90
131
  mcp: registration.mcp ?? {},
132
+ subagents: registration.subagents ?? {},
91
133
  };
92
134
  }
93
135
  function validateMcpRegistration(owner, registration) {
package/dist/errors.d.ts CHANGED
@@ -9,6 +9,7 @@ export declare class OrchaError extends Error {
9
9
  cause?: unknown;
10
10
  });
11
11
  }
12
+ export declare function isOrchaError(value: unknown): value is OrchaError;
12
13
  export declare function createProviderHttpError(response: Response, providerLabel: string): Promise<Error>;
13
14
  export declare function describeProviderError(error: unknown): {
14
15
  message: string;
package/dist/errors.js CHANGED
@@ -1,3 +1,4 @@
1
+ const ORCHA_ERROR_BRAND = Symbol.for("orchajs.OrchaError");
1
2
  export class OrchaError extends Error {
2
3
  code;
3
4
  retryable;
@@ -5,11 +6,17 @@ export class OrchaError extends Error {
5
6
  constructor(code, message, options = {}) {
6
7
  super(message, { cause: options.cause });
7
8
  this.name = "OrchaError";
9
+ Object.defineProperty(this, ORCHA_ERROR_BRAND, { value: true });
8
10
  this.code = code;
9
11
  this.retryable = options.retryable ?? false;
10
12
  this.details = options.details;
11
13
  }
12
14
  }
15
+ export function isOrchaError(value) {
16
+ return (typeof value === "object" &&
17
+ value !== null &&
18
+ value[ORCHA_ERROR_BRAND] === true);
19
+ }
13
20
  const NON_RETRYABLE_STATUS_CODES = new Set([400, 401, 403, 404, 413, 422]);
14
21
  const NON_RETRYABLE_ERROR_NAMES = new Set([
15
22
  "ValidationException",
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { orcha } from "./orcha.js";
2
2
  export * from "./runtime-entry.js";
3
3
  export { NodeJsonlSessionStore } from "./storage/node-jsonl.js";
4
- export { NodeSqliteSessionStore } from "./storage/node-sqlite.js";
4
+ export { NodeSqliteSessionStore } from "./storage/node-sqlite-facade.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export { orcha } from "./orcha.js";
2
2
  export * from "./runtime-entry.js";
3
3
  export { NodeJsonlSessionStore } from "./storage/node-jsonl.js";
4
- export { NodeSqliteSessionStore } from "./storage/node-sqlite.js";
4
+ export { NodeSqliteSessionStore } from "./storage/node-sqlite-facade.js";
package/dist/orcha.js CHANGED
@@ -2,24 +2,26 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync, } fro
2
2
  import { dirname, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { createAmarsiaInferenceGenerator } from "./amarsia/inference.js";
5
- import { compileRegistry } from "./compiler/compile.js";
6
5
  import { generateProviderResponse } from "./providers/index.js";
7
6
  import { setNativeRuntimeLoader, setSandboxRuntimeLoader, } from "./runtime/actions/execute.js";
8
7
  import { executeNativeAction } from "./runtime/actions/native.js";
9
8
  import { getRegistryCompiler, setGlobalCompiledManifest, } from "./runtime/compiler-hook.js";
10
9
  import { createOrcha, } from "./runtime/create-orcha.js";
11
10
  import { setMcpClientFactory } from "./runtime/mcp/client.js";
11
+ import { importRuntimeModule, requireRuntimeModule, } from "./runtime/node-module-loader.js";
12
12
  import { setCloudSessionStoreFactory, setInferenceGeneratorFactory, } from "./runtime/optional-features.js";
13
13
  import { nodeRuntimePlatform } from "./runtime/platform-node.js";
14
14
  import { CloudSessionStore } from "./storage/cloud.js";
15
15
  setNativeRuntimeLoader(async () => ({ executeNativeAction }));
16
16
  setSandboxRuntimeLoader(async () => {
17
- const modulePath = "./runtime/actions/sandbox.js";
18
- return import(modulePath);
17
+ return importRuntimeModule([
18
+ "orchajs",
19
+ "runtime",
20
+ "sandbox",
21
+ ]);
19
22
  });
20
23
  setMcpClientFactory(async (server, credentials) => {
21
- const modulePath = "./runtime/mcp/node-client.js";
22
- const { createNodeMcpClient } = await import(modulePath);
24
+ const { createNodeMcpClient } = await importRuntimeModule(["orchajs", "runtime", "mcp-node"]);
23
25
  return createNodeMcpClient(server, credentials);
24
26
  });
25
27
  setInferenceGeneratorFactory(createAmarsiaInferenceGenerator);
@@ -43,7 +45,7 @@ function getSharedNodeOrcha() {
43
45
  }
44
46
  const registryRoot = resolve(projectRoot, "orcha");
45
47
  if (existsSync(registryRoot)) {
46
- const compiled = compileRegistry(configuration.agents, registryRoot, configuration.actions?.runtime ?? "native", "node");
48
+ const compiled = compileRegistryAtRuntime(configuration.agents, registryRoot, configuration.actions?.runtime ?? "native", "node");
47
49
  persistDevManifest(projectRoot, manifestFile, compiled);
48
50
  return compiled;
49
51
  }
@@ -93,7 +95,7 @@ function loadCompiledManifest(projectRoot, configuration) {
93
95
  if (!existsSync(manifestPath)) {
94
96
  const registryRoot = resolve(projectRoot, "orcha");
95
97
  if (existsSync(registryRoot)) {
96
- const compiled = compileRegistry(configuration.agents, registryRoot, configuration.actions?.runtime ?? "native", "node");
98
+ const compiled = compileRegistryAtRuntime(configuration.agents, registryRoot, configuration.actions?.runtime ?? "native", "node");
97
99
  persistDevManifest(projectRoot, manifestPath, compiled);
98
100
  return compiled;
99
101
  }
@@ -123,7 +125,7 @@ function loadCompiledManifest(projectRoot, configuration) {
123
125
  registeredAgents.some((name, index) => name !== compiledAgents[index])) {
124
126
  const registryRoot = resolve(projectRoot, "orcha");
125
127
  if (!isPrecompiledRuntime() && existsSync(registryRoot)) {
126
- const recompiled = compileRegistry(configuration.agents, registryRoot, configuration.actions?.runtime ?? "native", "node");
128
+ const recompiled = compileRegistryAtRuntime(configuration.agents, registryRoot, configuration.actions?.runtime ?? "native", "node");
127
129
  persistDevManifest(projectRoot, manifestPath, recompiled);
128
130
  return recompiled;
129
131
  }
@@ -134,3 +136,7 @@ function loadCompiledManifest(projectRoot, configuration) {
134
136
  function compiledManifestPath(projectRoot) {
135
137
  return resolve(projectRoot, ".orcha/dist/manifest.json");
136
138
  }
139
+ function compileRegistryAtRuntime(registrations, registryRoot, actionRuntime, target) {
140
+ const { compileRegistry } = requireRuntimeModule(["orchajs", "compiler"]);
141
+ return compileRegistry(registrations, registryRoot, actionRuntime, target);
142
+ }
@@ -99,10 +99,21 @@ async function readDeclaredPackages(projectRoot) {
99
99
  return declared;
100
100
  }
101
101
  function allCompiledAgents(agents) {
102
- return Object.values(agents).flatMap((agent) => [
103
- agent,
104
- ...Object.values(agent.subagents ?? {}),
105
- ]);
102
+ const collected = [];
103
+ const visited = new Set();
104
+ const visit = (agent) => {
105
+ if (visited.has(agent))
106
+ return;
107
+ visited.add(agent);
108
+ collected.push(agent);
109
+ for (const child of Object.values(agent.subagents ?? {})) {
110
+ visit(child);
111
+ }
112
+ };
113
+ for (const agent of Object.values(agents)) {
114
+ visit(agent);
115
+ }
116
+ return collected;
106
117
  }
107
118
  function isInstalled(packageName, projectRoot) {
108
119
  try {
@@ -1,4 +1,5 @@
1
1
  import { OrchaError } from "../errors.js";
2
+ import { importRuntimeModule } from "../runtime/node-module-loader.js";
2
3
  import { builtInProviderCatalog, isBuiltInProvider, } from "./catalog.js";
3
4
  export { isBuiltInProvider } from "./catalog.js";
4
5
  const loadedProviders = new Map();
@@ -15,7 +16,12 @@ function loadProvider(name) {
15
16
  throw new OrchaError("provider_error", `Provider "${name}" is not implemented by this version of OrchaJS.`);
16
17
  }
17
18
  const descriptor = builtInProviderCatalog[name];
18
- const loading = import(`./${descriptor.moduleFile}`)
19
+ const moduleName = descriptor.moduleFile.replace(/\.js$/, "");
20
+ const loading = importRuntimeModule([
21
+ "orchajs",
22
+ "providers",
23
+ moduleName,
24
+ ])
19
25
  .then((module) => {
20
26
  const provider = module[descriptor.exportName];
21
27
  if (!isProviderAdapter(provider) || provider.name !== name) {
@@ -1,8 +1,8 @@
1
- import { describeProviderError, isRetryableProviderConnectionError, OrchaError, } from "../errors.js";
1
+ import { describeProviderError, isOrchaError, isRetryableProviderConnectionError, OrchaError, } from "../errors.js";
2
2
  import { sanitizeErrorMessage } from "../amarsia/analytics.js";
3
3
  import { normalizeLocalFile, normalizeUrlContent, } from "../file-content.js";
4
4
  import { messagesFromEvents, normalizePersistedToolResults, SessionEventWriter, } from "./session-events.js";
5
- import { StructuredOutputError, validateStructuredValue, } from "./structured-output.js";
5
+ import { isStructuredOutputError, validateStructuredValue, } from "./structured-output.js";
6
6
  import { executeLocalAction } from "./actions/execute.js";
7
7
  import { createExecution, } from "./execution.js";
8
8
  import { McpClientPool, } from "./mcp/client.js";
@@ -337,7 +337,8 @@ export class RuntimeAgent {
337
337
  await this.#store.append(sessionId, pauseEvents);
338
338
  return projectSessionSnapshot([...events, ...pauseEvents]);
339
339
  }
340
- async #ownedChild(parentSessionId, childSessionId) {
340
+ async #ownedChild(parentSessionId, childSessionId, visited = new Set()) {
341
+ visited.add(this);
341
342
  for (const child of Object.values(this.#subagents)) {
342
343
  const events = await child.#readSession(childSessionId);
343
344
  const lineage = sessionLineage(events);
@@ -348,6 +349,18 @@ export class RuntimeAgent {
348
349
  return child;
349
350
  }
350
351
  }
352
+ if (parentSessionId === undefined) {
353
+ for (const child of Object.values(this.#subagents)) {
354
+ if (visited.has(child))
355
+ continue;
356
+ try {
357
+ return await child.#ownedChild(undefined, childSessionId, visited);
358
+ }
359
+ catch {
360
+ // Continue searching sibling subtrees.
361
+ }
362
+ }
363
+ }
351
364
  throw new OrchaError("session_not_found", `Child session "${childSessionId}" was not found for agent "${this.#agentKey}".`);
352
365
  }
353
366
  async update(sessionId, update) {
@@ -738,7 +751,7 @@ export class RuntimeAgent {
738
751
  output: streamedOutput,
739
752
  };
740
753
  }
741
- if (error instanceof StructuredOutputError && error.response) {
754
+ if (isStructuredOutputError(error) && error.response) {
742
755
  const modelDurationMs = Math.round(performance.now() - modelStartedAt);
743
756
  const usage = aggregateUsage(previousEvents, writer.run, error.response.usage);
744
757
  const assistantEvent = writer.create("message.created", {
@@ -790,7 +803,7 @@ export class RuntimeAgent {
790
803
  details,
791
804
  });
792
805
  }
793
- if (error instanceof OrchaError) {
806
+ if (isOrchaError(error)) {
794
807
  throw error;
795
808
  }
796
809
  const providerError = describeProviderError(error);
@@ -979,9 +992,9 @@ export class RuntimeAgent {
979
992
  }
980
993
  catch (error) {
981
994
  const message = error instanceof Error ? error.message : String(error);
982
- const code = error instanceof OrchaError ? error.code : "execution_failed";
983
- const details = error instanceof OrchaError ? error.details : undefined;
984
- const retryable = error instanceof OrchaError ? error.retryable : false;
995
+ const code = isOrchaError(error) ? error.code : "execution_failed";
996
+ const details = isOrchaError(error) ? error.details : undefined;
997
+ const retryable = isOrchaError(error) ? error.retryable : false;
985
998
  const usage = usageForRun(previousEvents, writer.run);
986
999
  await this.#store.append(sessionId, [
987
1000
  writer.create("run.failed", {
@@ -1667,7 +1680,7 @@ export class RuntimeAgent {
1667
1680
  return await operation();
1668
1681
  }
1669
1682
  catch (error) {
1670
- const normalized = error instanceof OrchaError
1683
+ const normalized = isOrchaError(error)
1671
1684
  ? error
1672
1685
  : new OrchaError("storage_error", error instanceof Error ? error.message : String(error), { retryable: true, cause: error });
1673
1686
  return failure(sessionId, normalized.code, normalized.message, {
@@ -1689,7 +1702,7 @@ export class RuntimeAgent {
1689
1702
  return await operation();
1690
1703
  }
1691
1704
  catch (error) {
1692
- if (error instanceof OrchaError) {
1705
+ if (isOrchaError(error)) {
1693
1706
  throw error;
1694
1707
  }
1695
1708
  throw new OrchaError("storage_error", error instanceof Error ? error.message : String(error), { retryable: true, cause: error });
@@ -93,22 +93,19 @@ class OrchaRuntimeCore {
93
93
  return runtimeStore;
94
94
  };
95
95
  const agents = new Map();
96
- for (const [name, manifest] of Object.entries(bundle.agents)) {
97
- const subagents = Object.fromEntries(Object.entries(manifest.subagents ?? {}).map(([subagentName, subagentManifest]) => [
98
- subagentName,
99
- new RuntimeAgent({
100
- manifest: subagentManifest,
101
- configuration: runtimeConfiguration,
102
- store: createRuntimeStore(subagentManifest),
103
- activeSessions: this.#activeSessions,
104
- sessionControls: this.#sessionControls,
105
- generateProviderResponse,
106
- delegatedOnly: true,
107
- projectRoot,
108
- randomUUID: this.#platform.randomUUID,
109
- }),
110
- ]));
111
- agents.set(name, new RuntimeAgent({
96
+ const createRuntimeAgent = (manifest, delegatedOnly, ancestry) => {
97
+ const subagents = Object.fromEntries(Object.entries(manifest.subagents ?? {}).map(([subagentName, subagentManifest]) => {
98
+ if (ancestry.has(subagentName)) {
99
+ throw new Error(`Circular subagent registration detected: ${[...ancestry, subagentName].join(" -> ")}.`);
100
+ }
101
+ const nextAncestry = new Set(ancestry);
102
+ nextAncestry.add(subagentName);
103
+ return [
104
+ subagentName,
105
+ createRuntimeAgent(subagentManifest, true, nextAncestry),
106
+ ];
107
+ }));
108
+ return new RuntimeAgent({
112
109
  manifest,
113
110
  configuration: runtimeConfiguration,
114
111
  store: createRuntimeStore(manifest),
@@ -116,9 +113,13 @@ class OrchaRuntimeCore {
116
113
  sessionControls: this.#sessionControls,
117
114
  generateProviderResponse,
118
115
  subagents,
116
+ delegatedOnly,
119
117
  projectRoot,
120
118
  randomUUID: this.#platform.randomUUID,
121
- }));
119
+ });
120
+ };
121
+ for (const [name, manifest] of Object.entries(bundle.agents)) {
122
+ agents.set(name, createRuntimeAgent(manifest, false, new Set([name])));
122
123
  }
123
124
  this.#bundle = bundle;
124
125
  this.#inferenceEnabled = inferenceEnabled;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Loads a Node-only package subpath without exposing it to consumer bundlers.
3
+ * Callers pass path segments so no optional module specifier is statically
4
+ * discoverable from the default package graph.
5
+ */
6
+ export declare function requireRuntimeModule<T>(specifierSegments: string[]): T;
7
+ /**
8
+ * Loads an ESM package subpath without exposing the optional module specifier
9
+ * to consumer bundlers.
10
+ */
11
+ export declare function importRuntimeModule<T>(specifierSegments: string[]): Promise<T>;
@@ -0,0 +1,18 @@
1
+ import { createRequire } from "node:module";
2
+ const runtimeRequire = createRequire(import.meta.url);
3
+ const runtimeImport = new Function("specifier", "return import(specifier)");
4
+ /**
5
+ * Loads a Node-only package subpath without exposing it to consumer bundlers.
6
+ * Callers pass path segments so no optional module specifier is statically
7
+ * discoverable from the default package graph.
8
+ */
9
+ export function requireRuntimeModule(specifierSegments) {
10
+ return runtimeRequire(specifierSegments.join("/"));
11
+ }
12
+ /**
13
+ * Loads an ESM package subpath without exposing the optional module specifier
14
+ * to consumer bundlers.
15
+ */
16
+ export async function importRuntimeModule(specifierSegments) {
17
+ return await runtimeImport(specifierSegments.join("/"));
18
+ }
@@ -14,6 +14,7 @@ export declare class StructuredOutputError extends Error {
14
14
  cause?: unknown;
15
15
  });
16
16
  }
17
+ export declare function isStructuredOutputError(value: unknown): value is StructuredOutputError;
17
18
  export declare function resolveProviderStructuredOutput(request: ProviderRequest, baseResponse: ProviderResponse, textOutput: string): ProviderResponse;
18
19
  export declare function parseStructuredOutput(text: string, schema: Record<string, unknown>): unknown;
19
20
  export declare function validateStructuredValue(value: unknown, schema: Record<string, unknown>, label?: string): void;
@@ -1,3 +1,4 @@
1
+ const STRUCTURED_OUTPUT_ERROR_BRAND = Symbol.for("orchajs.StructuredOutputError");
1
2
  export class StructuredOutputError extends Error {
2
3
  kind;
3
4
  rawText;
@@ -7,12 +8,20 @@ export class StructuredOutputError extends Error {
7
8
  constructor(message, options) {
8
9
  super(message, { cause: options.cause });
9
10
  this.name = "StructuredOutputError";
11
+ Object.defineProperty(this, STRUCTURED_OUTPUT_ERROR_BRAND, {
12
+ value: true,
13
+ });
10
14
  this.kind = options.kind;
11
15
  this.rawText = options.rawText;
12
16
  this.responsePreview = options.responsePreview;
13
17
  this.schemaErrors = options.schemaErrors;
14
18
  }
15
19
  }
20
+ export function isStructuredOutputError(value) {
21
+ return (typeof value === "object" &&
22
+ value !== null &&
23
+ value[STRUCTURED_OUTPUT_ERROR_BRAND] === true);
24
+ }
16
25
  export function resolveProviderStructuredOutput(request, baseResponse, textOutput) {
17
26
  if (request.outputType !== "json" ||
18
27
  baseResponse.toolCalls.length > 0 ||
@@ -27,7 +36,7 @@ export function resolveProviderStructuredOutput(request, baseResponse, textOutpu
27
36
  };
28
37
  }
29
38
  catch (error) {
30
- if (error instanceof StructuredOutputError) {
39
+ if (isStructuredOutputError(error)) {
31
40
  error.response = baseResponse;
32
41
  }
33
42
  throw error;
@@ -1,5 +1,5 @@
1
1
  import { NodeJsonlSessionStore } from "./node-jsonl.js";
2
- import { NodeSqliteSessionStore } from "./node-sqlite.js";
2
+ import { NodeSqliteSessionStore } from "./node-sqlite-facade.js";
3
3
  export function createSessionStore(options) {
4
4
  const strategy = options.strategy ?? "node-jsonl";
5
5
  const directory = options.directory ?? ".orcha/sessions";
@@ -0,0 +1,20 @@
1
+ import type { SessionEvent, SessionStore } from "../types.js";
2
+ /**
3
+ * Backwards-compatible lazy facade for SQLite storage. The native-backed
4
+ * implementation is resolved only when this class is instantiated.
5
+ */
6
+ export declare class NodeSqliteSessionStore implements SessionStore {
7
+ #private;
8
+ readonly databasePath: string;
9
+ readonly agentName: string;
10
+ constructor(directory?: string, projectRoot?: string, agentName?: string);
11
+ read(sessionId: string): Promise<SessionEvent[]>;
12
+ readAfterSequence(sessionId: string, afterSequence: number, limit: number): Promise<SessionEvent[]>;
13
+ append(sessionId: string, events: SessionEvent[]): Promise<void>;
14
+ listSessionIds(): Promise<string[]>;
15
+ getCloudAcknowledgement(sessionId: string): Promise<number>;
16
+ setCloudAcknowledgement(sessionId: string, sequence: number): Promise<void>;
17
+ subscribe(sessionId: string, listener: (events: SessionEvent[]) => void): () => void;
18
+ subscribeAll(listener: (sessionId: string, events: SessionEvent[]) => void): () => void;
19
+ describeLocation(sessionId: string): Promise<string>;
20
+ }
@@ -0,0 +1,48 @@
1
+ import { requireRuntimeModule } from "../runtime/node-module-loader.js";
2
+ /**
3
+ * Backwards-compatible lazy facade for SQLite storage. The native-backed
4
+ * implementation is resolved only when this class is instantiated.
5
+ */
6
+ export class NodeSqliteSessionStore {
7
+ #store;
8
+ databasePath;
9
+ agentName;
10
+ constructor(directory = ".orcha/sessions", projectRoot = process.cwd(), agentName) {
11
+ const { NodeSqliteSessionStore: SqliteStore } = requireRuntimeModule(["orchajs", "storage", "sqlite"]);
12
+ const store = new SqliteStore(directory, projectRoot, agentName);
13
+ this.#store = store;
14
+ this.databasePath = store.databasePath;
15
+ this.agentName = store.agentName;
16
+ }
17
+ read(sessionId) {
18
+ return this.#store.read(sessionId);
19
+ }
20
+ readAfterSequence(sessionId, afterSequence, limit) {
21
+ return this.#store.readAfterSequence?.(sessionId, afterSequence, limit) ?? Promise.resolve([]);
22
+ }
23
+ append(sessionId, events) {
24
+ return this.#store.append(sessionId, events);
25
+ }
26
+ listSessionIds() {
27
+ return this.#store.listSessionIds();
28
+ }
29
+ getCloudAcknowledgement(sessionId) {
30
+ return this.#store.getCloudAcknowledgement?.(sessionId) ??
31
+ Promise.resolve(0);
32
+ }
33
+ setCloudAcknowledgement(sessionId, sequence) {
34
+ return this.#store.setCloudAcknowledgement?.(sessionId, sequence) ??
35
+ Promise.resolve();
36
+ }
37
+ subscribe(sessionId, listener) {
38
+ return this.#store.subscribe?.(sessionId, listener) ??
39
+ (() => undefined);
40
+ }
41
+ subscribeAll(listener) {
42
+ return this.#store.subscribeAll?.(listener) ?? (() => undefined);
43
+ }
44
+ describeLocation(sessionId) {
45
+ return this.#store.describeLocation?.(sessionId) ??
46
+ Promise.resolve(this.databasePath);
47
+ }
48
+ }
package/dist/testing.js CHANGED
@@ -52,20 +52,29 @@ export async function runTests(orcha, options = {}) {
52
52
  const store = createStore(manifest);
53
53
  const activeSessions = new Set();
54
54
  const sessionControls = new Map();
55
- const subagents = Object.fromEntries(Object.entries(manifest.subagents ?? {}).map(([name, subagentManifest]) => [
56
- name,
57
- new RuntimeAgent({
58
- manifest: subagentManifest,
59
- configuration: context.configuration,
60
- store: createStore(subagentManifest),
61
- activeSessions,
62
- sessionControls,
63
- generateProviderResponse: context.generateProviderResponse,
64
- delegatedOnly: true,
65
- sessionIdPrefix: "ses_test_",
66
- projectRoot: context.projectRoot,
67
- }),
68
- ]));
55
+ const createTestSubagents = (parentManifest, ancestry) => Object.fromEntries(Object.entries(parentManifest.subagents ?? {}).map(([name, subagentManifest]) => {
56
+ if (ancestry.has(name)) {
57
+ throw new Error(`Circular subagent registration detected: ${[...ancestry, name].join(" -> ")}.`);
58
+ }
59
+ const nextAncestry = new Set(ancestry);
60
+ nextAncestry.add(name);
61
+ return [
62
+ name,
63
+ new RuntimeAgent({
64
+ manifest: subagentManifest,
65
+ configuration: context.configuration,
66
+ store: createStore(subagentManifest),
67
+ activeSessions,
68
+ sessionControls,
69
+ generateProviderResponse: context.generateProviderResponse,
70
+ subagents: createTestSubagents(subagentManifest, nextAncestry),
71
+ delegatedOnly: true,
72
+ sessionIdPrefix: "ses_test_",
73
+ projectRoot: context.projectRoot,
74
+ }),
75
+ ];
76
+ }));
77
+ const subagents = createTestSubagents(manifest, new Set([manifest.key ?? manifest.name]));
69
78
  const agent = new RuntimeAgent({
70
79
  manifest: withTestActions(manifest, Object.keys(testCase.configuration.actions ?? {})),
71
80
  configuration: context.configuration,
package/dist/types.d.ts CHANGED
@@ -54,6 +54,7 @@ export type McpRegistration = Record<string, string>;
54
54
  export type SubagentRegistration = string | {
55
55
  path: string;
56
56
  mcp?: McpRegistration;
57
+ subagents?: Record<string, SubagentRegistration>;
57
58
  };
58
59
  export type AgentRegistration = string | {
59
60
  path: string;