orchajs 0.24.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +50 -3
  2. package/dist/amarsia/analytics.js +12 -0
  3. package/dist/amarsia/inference.d.ts +6 -0
  4. package/dist/amarsia/inference.js +337 -0
  5. package/dist/browser.js +5 -0
  6. package/dist/cli-agents-template.d.ts +1 -1
  7. package/dist/cli-agents-template.js +31 -7
  8. package/dist/compiler/build-project.js +57 -14
  9. package/dist/compiler/node-esm-banner.d.ts +2 -0
  10. package/dist/compiler/node-esm-banner.js +5 -0
  11. package/dist/orcha.js +5 -0
  12. package/dist/project-loader.js +4 -2
  13. package/dist/providers/types.d.ts +4 -0
  14. package/dist/react-native.js +5 -0
  15. package/dist/runtime/agent.js +103 -14
  16. package/dist/runtime/compiler-hook.d.ts +4 -0
  17. package/dist/runtime/compiler-hook.js +9 -0
  18. package/dist/runtime/create-orcha.d.ts +19 -0
  19. package/dist/runtime/create-orcha.js +109 -12
  20. package/dist/runtime/optional-features.d.ts +19 -0
  21. package/dist/runtime/optional-features.js +22 -0
  22. package/dist/runtime/platform-browser.js +16 -3
  23. package/dist/runtime/platform-node.js +16 -2
  24. package/dist/runtime/platform-react-native.js +16 -3
  25. package/dist/storage/browser-indexeddb.d.ts +3 -0
  26. package/dist/storage/browser-indexeddb.js +72 -8
  27. package/dist/storage/cloud-outbox.d.ts +30 -0
  28. package/dist/storage/cloud-outbox.js +628 -0
  29. package/dist/storage/cloud.d.ts +1 -0
  30. package/dist/storage/cloud.js +1 -0
  31. package/dist/storage/node-jsonl.d.ts +3 -0
  32. package/dist/storage/node-jsonl.js +273 -4
  33. package/dist/storage/node-sqlite.d.ts +3 -0
  34. package/dist/storage/node-sqlite.js +66 -17
  35. package/dist/storage/react-native-jsonl.d.ts +3 -0
  36. package/dist/storage/react-native-jsonl.js +223 -0
  37. package/dist/types.d.ts +21 -2
  38. package/dist-cjs/amarsia/analytics.js +12 -0
  39. package/dist-cjs/amarsia/inference.js +335 -0
  40. package/dist-cjs/browser.js +5 -0
  41. package/dist-cjs/cli-agents-template.js +31 -7
  42. package/dist-cjs/compiler/build-project.js +68 -4
  43. package/dist-cjs/compiler/node-esm-banner.js +32 -0
  44. package/dist-cjs/orcha.js +5 -0
  45. package/dist-cjs/project-loader.js +7 -5
  46. package/dist-cjs/react-native.js +5 -0
  47. package/dist-cjs/runtime/agent.js +137 -30
  48. package/dist-cjs/runtime/compiler-hook.js +11 -0
  49. package/dist-cjs/runtime/create-orcha.js +117 -12
  50. package/dist-cjs/runtime/optional-features.js +58 -0
  51. package/dist-cjs/runtime/platform-browser.js +16 -3
  52. package/dist-cjs/runtime/platform-node.js +16 -2
  53. package/dist-cjs/runtime/platform-react-native.js +18 -3
  54. package/dist-cjs/storage/browser-indexeddb.js +73 -8
  55. package/dist-cjs/storage/cloud-outbox.js +646 -0
  56. package/dist-cjs/storage/cloud.js +29 -0
  57. package/dist-cjs/storage/node-jsonl.js +246 -3
  58. package/dist-cjs/storage/node-sqlite.js +70 -19
  59. package/dist-cjs/storage/react-native-jsonl.js +207 -0
  60. package/package.json +1 -1
@@ -92,6 +92,23 @@ orcha.init({
92
92
  });
93
93
  \`\`\`
94
94
 
95
+ For Amarsia inference, the registry contains only project routing and agent
96
+ paths; provider and model selection stay in each agent \`index.json\`. Supported
97
+ providers are \`openai\`, \`anthropic\`, \`googlegenai\`, and \`deepseek\`; \`bedrock\`
98
+ and \`vertexai\` are direct-inference providers only:
99
+
100
+ \`\`\`ts
101
+ orcha.init({
102
+ amarsia: {
103
+ key: process.env.AMARSIA_PROJECT_KEY ?? "",
104
+ inference: true,
105
+ },
106
+ agents: {
107
+ supportBot: "./supportBot",
108
+ },
109
+ });
110
+ \`\`\`
111
+
95
112
  Only registered agents are compiled. Agent keys become runtime properties
96
113
  such as \`orcha.supportBot\`. Local actions use the native Node.js runtime by
97
114
  default. Set \`actions.runtime: "sandbox"\` only when isolated execution is
@@ -99,22 +116,29 @@ required.
99
116
 
100
117
  \`orcha.init()\` fields:
101
118
 
102
- - \`providers\` (required): provider configurations keyed by built-in provider
103
- name.
119
+ - \`providers\` (required for direct inference): provider configurations keyed
120
+ by built-in provider name. Omit it when \`amarsia.inference\` is true.
104
121
  - \`agents\` (required): runtime property names mapped to folders relative to
105
122
  \`orcha/\`. At least one agent is required.
106
123
  - \`amarsia.key\` (optional): project connection key generated in Amarsia.
107
- When set, Orcha syncs structural project and agent metadata only. It never
108
- uploads provider credentials, environment values, prompts, instructions,
109
- test inputs, or action source.
124
+ By itself, it syncs structural project and agent metadata only. Enabling
125
+ inference sends model requests through Amarsia, and cloud storage syncs
126
+ session events. Provider credentials, environment values, and action source
127
+ are never included.
110
128
  - \`amarsia.endpoint\` (optional): Amarsia API URL for project sync. Defaults to
111
129
  \`AMARSIA_API_URL\` and then \`https://api.amarsia.com\`.
130
+ - \`amarsia.inference\` (optional): routes all model calls through Amarsia while
131
+ preserving the provider and model in each manifest. It reuses \`amarsia.key\`;
132
+ local provider credentials are not required.
112
133
  - \`actions\` (optional): overrides the native local-action runtime or configures
113
134
  its environment and sandbox settings.
114
135
  - \`mcp.credentials\` (optional): runtime-only values used to resolve
115
136
  \`\${NAME}\` placeholders in MCP headers or stdio environment values.
116
- - \`storage.strategy\` (optional): \`"node-jsonl"\` (default) or \`"sqlite"\`.
117
- The SQLite driver ships as an internal optional Orcha dependency.
137
+ - \`storage.strategy\` (optional): \`"node-jsonl"\` (default), \`"sqlite"\`, or
138
+ local-first \`"cloud"\`. Cloud requires \`amarsia.key\`, keeps a native local
139
+ cache, commits appends locally without cloud latency, and delivers durable
140
+ bounded outbox batches in the background. Await \`orcha.close()\` before
141
+ reinitializing; close reports any cloud tail that could not be flushed.
118
142
  - \`storage.directory\` (optional): session directory relative to project
119
143
  root; defaults to \`.orcha/sessions\`.
120
144
  - \`root\` (optional): absolute or working-directory-relative project root;
@@ -27,6 +27,7 @@ var import_promises = require("fs/promises");
27
27
  var import_path = require("path");
28
28
  var import_url = require("url");
29
29
  var import_esbuild = require("esbuild");
30
+ var import_env = require("../env.js");
30
31
  var import_orcha = require("../orcha.js");
31
32
  var import_compiler_hook = require("../runtime/compiler-hook.js");
32
33
  var import_compile = require("./compile.js");
@@ -35,6 +36,7 @@ var import_dependencies = require("../providers/dependencies.js");
35
36
  let registryImportSequence = 0;
36
37
  async function buildProject(options = {}) {
37
38
  const projectRoot = (0, import_path.resolve)(options.projectRoot ?? process.cwd());
39
+ (0, import_env.loadProjectEnvironment)(projectRoot);
38
40
  const target = options.target ?? "node";
39
41
  (0, import_compiler_hook.setRegistryCompiler)(
40
42
  (configuration, compilerProjectRoot) => (0, import_compile.compileRegistry)(
@@ -62,8 +64,14 @@ async function buildProject(options = {}) {
62
64
  projectRoot,
63
65
  ".orcha/dist/manifest.json"
64
66
  );
67
+ if (import_orcha.orcha.isInitialized()) {
68
+ throw new Error(
69
+ "Cannot compile an Orcha project while the shared development runtime is initialized. Await orcha.close() first."
70
+ );
71
+ }
65
72
  await (0, import_promises.mkdir)(temporaryDirectory, { recursive: true });
66
73
  await (0, import_promises.mkdir)((0, import_path.dirname)(outputPath), { recursive: true });
74
+ let compilationRuntimeCreated = false;
67
75
  try {
68
76
  await (0, import_esbuild.build)({
69
77
  entryPoints: [registryPath],
@@ -79,9 +87,12 @@ async function buildProject(options = {}) {
79
87
  const previousProjectRoot = process.env.ORCHA_PROJECT_ROOT;
80
88
  process.env.ORCHA_COMPILING = "1";
81
89
  process.env.ORCHA_PROJECT_ROOT = projectRoot;
90
+ (0, import_compiler_hook.setRegistryCompilationActive)(true);
82
91
  try {
83
92
  await import(`${(0, import_url.pathToFileURL)(registryBundlePath).href}?build=${Date.now()}-${registryImportSequence++}`);
84
93
  } finally {
94
+ compilationRuntimeCreated = import_orcha.orcha.isInitialized();
95
+ (0, import_compiler_hook.setRegistryCompilationActive)(false);
85
96
  if (previousCompiling === void 0) {
86
97
  delete process.env.ORCHA_COMPILING;
87
98
  } else {
@@ -94,6 +105,10 @@ async function buildProject(options = {}) {
94
105
  }
95
106
  }
96
107
  const compiledBundle = import_orcha.orcha.getCompiledBundle();
108
+ const inferenceEnabled = import_orcha.orcha.isInferenceEnabled();
109
+ const cloudStorageEnabled = import_orcha.orcha.isCloudStorageEnabled();
110
+ await import_orcha.orcha.close();
111
+ compilationRuntimeCreated = false;
97
112
  if (target !== "node" && compiledBundle.actionRuntime === "sandbox") {
98
113
  throw new Error(
99
114
  `The ${target} target supports precompiled native actions only. Set actions.runtime to "native".`
@@ -118,7 +133,7 @@ async function buildProject(options = {}) {
118
133
  const sandboxRuntimeSource = compiledBundle.actionRuntime === "sandbox" ? createSandboxRuntimeSource() : "";
119
134
  const platformActionRuntimeSource = createPlatformActionRuntimeSource(target);
120
135
  const nodeStorageExports = target === "node" ? createNodeStorageExports() : "";
121
- const includedProviders = [
136
+ const includedProviders = inferenceEnabled ? [] : [
122
137
  ...new Set(
123
138
  allCompiledAgents(compiledBundle.agents).flatMap(
124
139
  (agent) => [
@@ -129,13 +144,18 @@ async function buildProject(options = {}) {
129
144
  )
130
145
  ];
131
146
  const providerRuntimeSource = createProviderRuntimeSource(includedProviders, target);
132
- await (0, import_dependencies.ensureProviderDependencies)(includedProviders, projectRoot);
147
+ if (!inferenceEnabled) {
148
+ await (0, import_dependencies.ensureProviderDependencies)(includedProviders, projectRoot);
149
+ }
133
150
  const hasMcp = allCompiledAgents(compiledBundle.agents).some(
134
151
  (agent) => Object.keys(agent.mcpServers ?? {}).length > 0
135
152
  );
136
153
  await (0, import_dependencies.ensureCompiledMcpDependencies)(compiledBundle, projectRoot);
137
154
  const mcpRuntimeSource = hasMcp ? createMcpRuntimeSource(target) : "";
138
- const needsNodeRequire = compiledBundle.actionRuntime === "sandbox" || includedProviders.includes("vertexai") || includedProviders.includes("bedrock");
155
+ const optionalFeatureRuntimeSource = createOptionalFeatureRuntimeSource({
156
+ inference: inferenceEnabled,
157
+ cloudStorage: cloudStorageEnabled
158
+ });
139
159
  await (0, import_promises.writeFile)(
140
160
  productionEntryPath,
141
161
  [
@@ -147,6 +167,7 @@ async function buildProject(options = {}) {
147
167
  providerRuntimeSource,
148
168
  platformActionRuntimeSource,
149
169
  mcpRuntimeSource,
170
+ optionalFeatureRuntimeSource,
150
171
  sandboxRuntimeSource,
151
172
  `const compiledBundle = ${JSON.stringify(compiledBundle)};`,
152
173
  "const generateProviderResponse = createProviderResponseGenerator(includedProviders);",
@@ -170,7 +191,7 @@ async function buildProject(options = {}) {
170
191
  compiledBundle.actionRuntime === "sandbox" ? "1" : "0"
171
192
  )
172
193
  },
173
- ...needsNodeRequire && target === "node" ? {
194
+ ...target === "node" ? {
174
195
  banner: {
175
196
  js: [
176
197
  'import { createRequire as __orchaCreateRequire } from "module";',
@@ -193,6 +214,10 @@ async function buildProject(options = {}) {
193
214
  );
194
215
  return outputPath;
195
216
  } finally {
217
+ (0, import_compiler_hook.setRegistryCompilationActive)(false);
218
+ if (compilationRuntimeCreated && import_orcha.orcha.isInitialized()) {
219
+ await import_orcha.orcha.close();
220
+ }
196
221
  await (0, import_promises.rm)(temporaryDirectory, {
197
222
  recursive: true,
198
223
  force: true
@@ -263,6 +288,45 @@ function createMcpRuntimeSource(target) {
263
288
  ""
264
289
  ].join("\n");
265
290
  }
291
+ function createOptionalFeatureRuntimeSource(options) {
292
+ if (!options.inference && !options.cloudStorage) {
293
+ return "";
294
+ }
295
+ const sourceRoot = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
296
+ const hooksPath = (0, import_path.resolve)(
297
+ sourceRoot,
298
+ "../runtime/optional-features.js"
299
+ ).replaceAll("\\", "/");
300
+ const imports = [];
301
+ const registrations = [];
302
+ if (options.inference) {
303
+ const inferencePath = (0, import_path.resolve)(
304
+ sourceRoot,
305
+ "../amarsia/inference.js"
306
+ ).replaceAll("\\", "/");
307
+ imports.push(
308
+ `import { createAmarsiaInferenceGenerator } from ${JSON.stringify(inferencePath)};`,
309
+ `import { setInferenceGeneratorFactory } from ${JSON.stringify(hooksPath)};`
310
+ );
311
+ registrations.push(
312
+ "setInferenceGeneratorFactory(createAmarsiaInferenceGenerator);"
313
+ );
314
+ }
315
+ if (options.cloudStorage) {
316
+ const cloudPath = (0, import_path.resolve)(
317
+ sourceRoot,
318
+ "../storage/cloud.js"
319
+ ).replaceAll("\\", "/");
320
+ imports.push(
321
+ `import { CloudSessionStore } from ${JSON.stringify(cloudPath)};`,
322
+ `import { setCloudSessionStoreFactory } from ${JSON.stringify(hooksPath)};`
323
+ );
324
+ registrations.push(
325
+ "setCloudSessionStoreFactory((options) => new CloudSessionStore(options));"
326
+ );
327
+ }
328
+ return [...imports, ...registrations, ""].join("\n");
329
+ }
266
330
  function createNodeStorageExports() {
267
331
  const sourceRoot = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
268
332
  const jsonlPath = (0, import_path.resolve)(
@@ -0,0 +1,32 @@
1
+ "use strict"; const __orchaImportMetaUrl = require("url").pathToFileURL(__filename).href;
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var node_esm_banner_exports = {};
21
+ __export(node_esm_banner_exports, {
22
+ nodeEsmRequireBanner: () => nodeEsmRequireBanner
23
+ });
24
+ module.exports = __toCommonJS(node_esm_banner_exports);
25
+ const nodeEsmRequireBanner = [
26
+ 'import { createRequire as __orchaCreateRequire } from "module";',
27
+ "const require = __orchaCreateRequire(import.meta.url);"
28
+ ].join("\n");
29
+ // Annotate the CommonJS export names for ESM import in node:
30
+ 0 && (module.exports = {
31
+ nodeEsmRequireBanner
32
+ });
package/dist-cjs/orcha.js CHANGED
@@ -24,13 +24,16 @@ __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_inference = require("./amarsia/inference.js");
27
28
  var import_providers = require("./providers/index.js");
28
29
  var import_execute = require("./runtime/actions/execute.js");
29
30
  var import_native = require("./runtime/actions/native.js");
30
31
  var import_compiler_hook = require("./runtime/compiler-hook.js");
31
32
  var import_create_orcha = require("./runtime/create-orcha.js");
32
33
  var import_client = require("./runtime/mcp/client.js");
34
+ var import_optional_features = require("./runtime/optional-features.js");
33
35
  var import_platform_node = require("./runtime/platform-node.js");
36
+ var import_cloud = require("./storage/cloud.js");
34
37
  (0, import_execute.setNativeRuntimeLoader)(async () => ({ executeNativeAction: import_native.executeNativeAction }));
35
38
  (0, import_execute.setSandboxRuntimeLoader)(async () => {
36
39
  const modulePath = "./runtime/actions/sandbox.js";
@@ -41,6 +44,8 @@ var import_platform_node = require("./runtime/platform-node.js");
41
44
  const { createNodeMcpClient } = await import(modulePath);
42
45
  return createNodeMcpClient(server, credentials);
43
46
  });
47
+ (0, import_optional_features.setInferenceGeneratorFactory)(import_inference.createAmarsiaInferenceGenerator);
48
+ (0, import_optional_features.setCloudSessionStoreFactory)((options) => new import_cloud.CloudSessionStore(options));
44
49
  const orcha = (0, import_create_orcha.createOrcha)(
45
50
  (configuration) => {
46
51
  const projectRoot = (0, import_path.resolve)(
@@ -76,13 +76,15 @@ async function loadProject(projectRoot) {
76
76
  }
77
77
  if (!import_orcha.orcha.isInitialized() || import_orcha.orcha.getCompiledBundle() === previousBundle) {
78
78
  throw new Error(
79
- '"orcha/index.ts" must call orcha.init({ providers, agents }).'
79
+ '"orcha/index.ts" must call orcha.init({ agents, ... }).'
80
+ );
81
+ }
82
+ if (!import_orcha.orcha.isInferenceEnabled()) {
83
+ await (0, import_dependencies.ensureCompiledProviderDependencies)(
84
+ import_orcha.orcha.getCompiledBundle(),
85
+ projectRoot
80
86
  );
81
87
  }
82
- await (0, import_dependencies.ensureCompiledProviderDependencies)(
83
- import_orcha.orcha.getCompiledBundle(),
84
- projectRoot
85
- );
86
88
  await (0, import_dependencies.ensureCompiledMcpDependencies)(
87
89
  import_orcha.orcha.getCompiledBundle(),
88
90
  projectRoot
@@ -23,15 +23,20 @@ __export(react_native_exports, {
23
23
  orcha: () => orcha
24
24
  });
25
25
  module.exports = __toCommonJS(react_native_exports);
26
+ var import_inference = require("./amarsia/inference.js");
26
27
  var import_browser = require("./providers/browser.js");
27
28
  var import_execute = require("./runtime/actions/execute.js");
28
29
  var import_create_orcha = require("./runtime/create-orcha.js");
30
+ var import_optional_features = require("./runtime/optional-features.js");
29
31
  var import_platform_react_native = require("./runtime/platform-react-native.js");
32
+ var import_cloud = require("./storage/cloud.js");
30
33
  __reExport(react_native_exports, require("./runtime-entry.js"), module.exports);
31
34
  (0, import_execute.setNativeRuntimeLoader)(async () => {
32
35
  const modulePath = "./runtime/actions/browser-native.js";
33
36
  return import(modulePath);
34
37
  });
38
+ (0, import_optional_features.setInferenceGeneratorFactory)(import_inference.createAmarsiaInferenceGenerator);
39
+ (0, import_optional_features.setCloudSessionStoreFactory)((options) => new import_cloud.CloudSessionStore(options));
35
40
  const orcha = (0, import_create_orcha.createOrcha)(
36
41
  () => {
37
42
  throw new Error(
@@ -126,10 +126,11 @@ class RuntimeAgent {
126
126
  if (typeof normalized === "object" && normalized !== null && "sessionId" in normalized) {
127
127
  return this.#createExecution(
128
128
  sessionId,
129
- async () => failure(
129
+ async () => this.#recordRejectedRun(
130
130
  sessionId,
131
- "invalid_input",
132
- "run() always creates a new session and does not accept sessionId."
131
+ "run() always creates a new session and does not accept sessionId.",
132
+ true,
133
+ lineage
133
134
  )
134
135
  );
135
136
  }
@@ -188,10 +189,10 @@ class RuntimeAgent {
188
189
  if (!input || typeof input !== "object") {
189
190
  return this.#createExecution(
190
191
  sessionId,
191
- async () => failure(
192
+ async () => this.#recordRejectedRun(
192
193
  sessionId,
193
- "invalid_input",
194
- "resume() requires content or toolResults."
194
+ "resume() requires content or toolResults.",
195
+ false
195
196
  )
196
197
  );
197
198
  }
@@ -200,10 +201,10 @@ class RuntimeAgent {
200
201
  if (hasMessage === hasToolResults) {
201
202
  return this.#createExecution(
202
203
  sessionId,
203
- async () => failure(
204
+ async () => this.#recordRejectedRun(
204
205
  sessionId,
205
- "invalid_input",
206
- "resume() requires either content or toolResults, but not both."
206
+ "resume() requires either content or toolResults, but not both.",
207
+ false
207
208
  )
208
209
  );
209
210
  }
@@ -236,6 +237,71 @@ class RuntimeAgent {
236
237
  return task ? task : [];
237
238
  });
238
239
  }
240
+ async #recordRejectedRun(sessionId, message, createSession, lineage) {
241
+ return this.#withSessionExecutionLock(sessionId, async () => {
242
+ const events = await this.#readSession(sessionId);
243
+ if (!createSession && events.length === 0) {
244
+ return failure(
245
+ sessionId,
246
+ "session_not_found",
247
+ `Session "${sessionId}" does not exist.`
248
+ );
249
+ }
250
+ if (events.length > 0) {
251
+ try {
252
+ this.#assertOwnedSession(sessionId, events);
253
+ } catch {
254
+ return failure(
255
+ sessionId,
256
+ "session_not_found",
257
+ `Session "${sessionId}" was not created by this agent.`
258
+ );
259
+ }
260
+ }
261
+ const writer = new import_session_events.SessionEventWriter(sessionId, events);
262
+ const rejectedEvents = [];
263
+ if (events.length === 0) {
264
+ rejectedEvents.push(
265
+ writer.create(
266
+ "session.created",
267
+ {
268
+ schemaVersion: 1,
269
+ sessionId,
270
+ agent: this.#agentKey,
271
+ status: "active",
272
+ metadata: {},
273
+ variables: {},
274
+ ...lineage ? { lineage } : {}
275
+ },
276
+ "session"
277
+ )
278
+ );
279
+ }
280
+ rejectedEvents.push(
281
+ writer.create("run.started", {
282
+ status: "running",
283
+ agent: this.#agentKey,
284
+ provider: this.#manifest.provider,
285
+ model: this.#manifest.model,
286
+ region: this.#manifest.region ?? "provider_managed",
287
+ reasoningLevel: this.#manifest.reasoningLevel,
288
+ outputType: this.#manifest.outputType,
289
+ clientCapabilities: []
290
+ }),
291
+ writer.create("run.failed", {
292
+ status: "failed",
293
+ durationMs: 0,
294
+ error: {
295
+ code: "invalid_input",
296
+ message,
297
+ retryable: false
298
+ }
299
+ })
300
+ );
301
+ await this.#store.append(sessionId, rejectedEvents);
302
+ return failure(sessionId, "invalid_input", message);
303
+ });
304
+ }
239
305
  async get(sessionId) {
240
306
  const events = await this.#readSession(sessionId);
241
307
  this.#assertOwnedSession(sessionId, events);
@@ -513,17 +579,19 @@ class RuntimeAgent {
513
579
  try {
514
580
  content = normalizeContent(input.content, this.#projectRoot);
515
581
  } catch (error) {
516
- return failure(
582
+ return this.#recordRejectedRun(
517
583
  sessionId,
518
- "invalid_input",
519
- error instanceof Error ? error.message : String(error)
584
+ error instanceof Error ? error.message : String(error),
585
+ createSession,
586
+ lineage
520
587
  );
521
588
  }
522
589
  if (!content) {
523
- return failure(
590
+ return this.#recordRejectedRun(
524
591
  sessionId,
525
- "invalid_input",
526
- "Agent content must contain at least one valid item."
592
+ "Agent content must contain at least one valid item.",
593
+ createSession,
594
+ lineage
527
595
  );
528
596
  }
529
597
  let initialName;
@@ -536,27 +604,34 @@ class RuntimeAgent {
536
604
  initialVariables = normalizeVariables(input.variables);
537
605
  } catch (error) {
538
606
  const message = error instanceof Error ? error.message : String(error);
539
- return failure(sessionId, "invalid_input", message);
607
+ return this.#recordRejectedRun(
608
+ sessionId,
609
+ message,
610
+ createSession,
611
+ lineage
612
+ );
540
613
  }
541
614
  }
542
615
  const capabilities = normalizeClientCapabilities(
543
616
  input.clientCapabilities ?? []
544
617
  );
545
618
  if (!capabilities) {
546
- return failure(
619
+ return this.#recordRejectedRun(
547
620
  sessionId,
548
- "invalid_input",
549
- "clientCapabilities must contain tool names or client tool definitions."
621
+ "clientCapabilities must contain tool names or client tool definitions.",
622
+ createSession,
623
+ lineage
550
624
  );
551
625
  }
552
626
  const unknownCapabilities = capabilities.filter(
553
627
  (name) => !(this.#manifest.actions ?? {})[name]
554
628
  );
555
629
  if (unknownCapabilities.length > 0) {
556
- return failure(
630
+ return this.#recordRejectedRun(
557
631
  sessionId,
558
- "invalid_input",
559
- `Unknown client capabilities: ${unknownCapabilities.join(", ")}.`
632
+ `Unknown client capabilities: ${unknownCapabilities.join(", ")}.`,
633
+ createSession,
634
+ lineage
560
635
  );
561
636
  }
562
637
  return this.#withSessionExecutionLock(sessionId, async () => {
@@ -860,13 +935,18 @@ class RuntimeAgent {
860
935
  streamedOutput = output;
861
936
  publishOutput?.(output);
862
937
  },
863
- signal
938
+ signal,
939
+ trace: {
940
+ agentExternalId: this.#agentKey,
941
+ sessionId
942
+ }
864
943
  }),
865
944
  signal
866
945
  );
867
946
  } catch (error) {
868
947
  if (this.#sessionControls.get(sessionId)?.pauseRequested) {
869
948
  const pausedEvents = [];
949
+ const usage2 = usageForRun(previousEvents, writer.run);
870
950
  if (streamedOutput) {
871
951
  pausedEvents.push(
872
952
  writer.create("message.created", {
@@ -885,6 +965,7 @@ class RuntimeAgent {
885
965
  writer.create("run.paused", {
886
966
  status: "paused",
887
967
  output: streamedOutput,
968
+ usage: usage2,
888
969
  durationMs: elapsedRunDuration(previousEvents, writer.run)
889
970
  }),
890
971
  writer.create(
@@ -1109,10 +1190,12 @@ class RuntimeAgent {
1109
1190
  const code = error instanceof import_errors.OrchaError ? error.code : "execution_failed";
1110
1191
  const details = error instanceof import_errors.OrchaError ? error.details : void 0;
1111
1192
  const retryable = error instanceof import_errors.OrchaError ? error.retryable : false;
1193
+ const usage = usageForRun(previousEvents, writer.run);
1112
1194
  await this.#store.append(sessionId, [
1113
1195
  writer.create("run.failed", {
1114
1196
  status: "failed",
1115
1197
  durationMs: elapsedRunDuration(previousEvents, writer.run),
1198
+ usage,
1116
1199
  error: {
1117
1200
  code,
1118
1201
  message,
@@ -1146,7 +1229,7 @@ class RuntimeAgent {
1146
1229
  await this.#store.append(sessionId, requestedEvents);
1147
1230
  const task = Promise.all(
1148
1231
  evaluations.map(
1149
- (evaluation) => this.#runEvaluation(evaluation, events)
1232
+ (evaluation) => this.#runEvaluation(evaluation, events, sessionId)
1150
1233
  )
1151
1234
  ).then(
1152
1235
  (results) => this.#persistEvaluationResults(
@@ -1168,7 +1251,7 @@ class RuntimeAgent {
1168
1251
  });
1169
1252
  this.#evaluationTasks.set(sessionId, task);
1170
1253
  }
1171
- async #runEvaluation(evaluation, events) {
1254
+ async #runEvaluation(evaluation, events, sessionId) {
1172
1255
  const startedAt = performance.now();
1173
1256
  try {
1174
1257
  const provider = this.#configuration.providers[evaluation.provider];
@@ -1180,7 +1263,12 @@ class RuntimeAgent {
1180
1263
  const response = await this.#generateProviderResponse(
1181
1264
  evaluation.provider,
1182
1265
  provider,
1183
- createEvaluationRequest(evaluation, events)
1266
+ createEvaluationRequest(
1267
+ evaluation,
1268
+ events,
1269
+ this.#agentKey,
1270
+ sessionId
1271
+ )
1184
1272
  );
1185
1273
  const metrics = normalizeEvaluationMetrics(
1186
1274
  evaluation,
@@ -2125,6 +2213,7 @@ function normalizeContent(content, projectRoot) {
2125
2213
  }
2126
2214
  const normalized = [];
2127
2215
  for (const item of items) {
2216
+ const record = item && typeof item === "object" ? item : {};
2128
2217
  if (item && "type" in item && item.type === "text" && typeof item.text === "string" && item.text.trim()) {
2129
2218
  normalized.push({ type: "text", text: item.text });
2130
2219
  continue;
@@ -2148,13 +2237,30 @@ function normalizeContent(content, projectRoot) {
2148
2237
  );
2149
2238
  continue;
2150
2239
  }
2240
+ const remoteUri = typeof record.fileUri === "string" ? record.fileUri : typeof record.file_uri === "string" ? record.file_uri : void 0;
2241
+ const remoteMimeType = typeof record.mimeType === "string" ? record.mimeType : typeof record.mime_type === "string" ? record.mime_type : void 0;
2242
+ if (remoteUri?.trim() && (record.type === "url" || record.type === "document" || record.type === "file")) {
2243
+ normalized.push(
2244
+ (0, import_file_content.normalizeUrlContent)(remoteUri, remoteMimeType)
2245
+ );
2246
+ continue;
2247
+ }
2151
2248
  if (item && "type" in item && typeof item.type === "string" && ["image", "video", "audio", "url"].includes(item.type) && "mimeType" in item && "fileUri" in item && typeof item.mimeType === "string" && item.mimeType.trim() && typeof item.fileUri === "string" && item.fileUri.trim()) {
2152
2249
  normalized.push(item);
2153
2250
  continue;
2154
2251
  }
2155
2252
  return void 0;
2156
2253
  }
2157
- return normalized;
2254
+ if (normalized.some((item) => item.type === "text")) {
2255
+ return normalized;
2256
+ }
2257
+ return [
2258
+ {
2259
+ type: "text",
2260
+ text: "Process the attached content according to your agent instructions."
2261
+ },
2262
+ ...normalized
2263
+ ];
2158
2264
  }
2159
2265
  function normalizeDelegatedInput(input, projectRoot) {
2160
2266
  if (typeof input === "string") {
@@ -2454,7 +2560,7 @@ function loadedSkillNames(events) {
2454
2560
  )
2455
2561
  );
2456
2562
  }
2457
- function createEvaluationRequest(evaluation, events) {
2563
+ function createEvaluationRequest(evaluation, events, agentExternalId, sessionId) {
2458
2564
  return {
2459
2565
  model: evaluation.model,
2460
2566
  maxTokens: evaluation.maxTokens ?? 2e3,
@@ -2523,7 +2629,8 @@ function createEvaluationRequest(evaluation, events) {
2523
2629
  ]
2524
2630
  }
2525
2631
  ],
2526
- tools: []
2632
+ tools: [],
2633
+ trace: { agentExternalId, sessionId }
2527
2634
  };
2528
2635
  }
2529
2636
  function evaluationTranscript(events) {
@@ -2685,7 +2792,7 @@ function projectSessionSnapshot(events) {
2685
2792
  );
2686
2793
  const latestUsageEvent = findLast(
2687
2794
  events,
2688
- (event) => (event.type === "run.completed" || event.type === "run.paused") && isUsage(event.data.usage)
2795
+ (event) => (event.type === "run.completed" || event.type === "run.failed" || event.type === "run.paused") && isUsage(event.data.usage)
2689
2796
  );
2690
2797
  return {
2691
2798
  sessionId: created.data.sessionId,
@@ -20,18 +20,29 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var compiler_hook_exports = {};
21
21
  __export(compiler_hook_exports, {
22
22
  getRegistryCompiler: () => getRegistryCompiler,
23
+ isRegistryCompilationActive: () => isRegistryCompilationActive,
24
+ setRegistryCompilationActive: () => setRegistryCompilationActive,
23
25
  setRegistryCompiler: () => setRegistryCompiler
24
26
  });
25
27
  module.exports = __toCommonJS(compiler_hook_exports);
26
28
  let registryCompiler;
29
+ let registryCompilationActive = false;
27
30
  function setRegistryCompiler(compiler) {
28
31
  registryCompiler = compiler;
29
32
  }
30
33
  function getRegistryCompiler() {
31
34
  return registryCompiler;
32
35
  }
36
+ function setRegistryCompilationActive(active) {
37
+ registryCompilationActive = active;
38
+ }
39
+ function isRegistryCompilationActive() {
40
+ return registryCompilationActive;
41
+ }
33
42
  // Annotate the CommonJS export names for ESM import in node:
34
43
  0 && (module.exports = {
35
44
  getRegistryCompiler,
45
+ isRegistryCompilationActive,
46
+ setRegistryCompilationActive,
36
47
  setRegistryCompiler
37
48
  });