orchajs 0.24.0 → 0.26.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 (78) 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 +377 -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 +44 -11
  8. package/dist/cli.js +22 -9
  9. package/dist/compiler/build-project.js +57 -14
  10. package/dist/compiler/node-esm-banner.d.ts +2 -0
  11. package/dist/compiler/node-esm-banner.js +5 -0
  12. package/dist/orcha.js +5 -0
  13. package/dist/playground/server.js +3 -0
  14. package/dist/project-loader.js +4 -2
  15. package/dist/providers/anthropic.js +67 -58
  16. package/dist/providers/bedrock.js +14 -8
  17. package/dist/providers/deepseek.js +9 -2
  18. package/dist/providers/google-gemini.js +20 -15
  19. package/dist/providers/openai.js +6 -0
  20. package/dist/providers/types.d.ts +5 -0
  21. package/dist/react-native.js +5 -0
  22. package/dist/runtime/agent.d.ts +3 -3
  23. package/dist/runtime/agent.js +278 -45
  24. package/dist/runtime/compiler-hook.d.ts +4 -0
  25. package/dist/runtime/compiler-hook.js +9 -0
  26. package/dist/runtime/create-orcha.d.ts +19 -0
  27. package/dist/runtime/create-orcha.js +109 -12
  28. package/dist/runtime/optional-features.d.ts +19 -0
  29. package/dist/runtime/optional-features.js +22 -0
  30. package/dist/runtime/platform-browser.js +16 -3
  31. package/dist/runtime/platform-node.js +16 -2
  32. package/dist/runtime/platform-react-native.js +16 -3
  33. package/dist/runtime/session-events.js +19 -0
  34. package/dist/storage/browser-indexeddb.d.ts +3 -0
  35. package/dist/storage/browser-indexeddb.js +72 -8
  36. package/dist/storage/cloud-outbox.d.ts +30 -0
  37. package/dist/storage/cloud-outbox.js +628 -0
  38. package/dist/storage/cloud.d.ts +1 -0
  39. package/dist/storage/cloud.js +1 -0
  40. package/dist/storage/node-jsonl.d.ts +3 -0
  41. package/dist/storage/node-jsonl.js +273 -4
  42. package/dist/storage/node-sqlite.d.ts +3 -0
  43. package/dist/storage/node-sqlite.js +66 -17
  44. package/dist/storage/react-native-jsonl.d.ts +3 -0
  45. package/dist/storage/react-native-jsonl.js +223 -0
  46. package/dist/testing.js +3 -0
  47. package/dist/types.d.ts +25 -4
  48. package/dist-cjs/amarsia/analytics.js +12 -0
  49. package/dist-cjs/amarsia/inference.js +372 -0
  50. package/dist-cjs/browser.js +5 -0
  51. package/dist-cjs/cli-agents-template.js +44 -11
  52. package/dist-cjs/compiler/build-project.js +68 -4
  53. package/dist-cjs/compiler/node-esm-banner.js +32 -0
  54. package/dist-cjs/orcha.js +5 -0
  55. package/dist-cjs/playground/server.js +1 -0
  56. package/dist-cjs/project-loader.js +7 -5
  57. package/dist-cjs/providers/anthropic.js +65 -60
  58. package/dist-cjs/providers/bedrock.js +17 -9
  59. package/dist-cjs/providers/deepseek.js +10 -2
  60. package/dist-cjs/providers/google-gemini.js +27 -20
  61. package/dist-cjs/providers/openai.js +8 -0
  62. package/dist-cjs/react-native.js +5 -0
  63. package/dist-cjs/runtime/agent.js +311 -61
  64. package/dist-cjs/runtime/compiler-hook.js +11 -0
  65. package/dist-cjs/runtime/create-orcha.js +117 -12
  66. package/dist-cjs/runtime/optional-features.js +58 -0
  67. package/dist-cjs/runtime/platform-browser.js +16 -3
  68. package/dist-cjs/runtime/platform-node.js +16 -2
  69. package/dist-cjs/runtime/platform-react-native.js +18 -3
  70. package/dist-cjs/runtime/session-events.js +14 -0
  71. package/dist-cjs/storage/browser-indexeddb.js +73 -8
  72. package/dist-cjs/storage/cloud-outbox.js +646 -0
  73. package/dist-cjs/storage/cloud.js +29 -0
  74. package/dist-cjs/storage/node-jsonl.js +246 -3
  75. package/dist-cjs/storage/node-sqlite.js +70 -19
  76. package/dist-cjs/storage/react-native-jsonl.js +207 -0
  77. package/dist-cjs/testing.js +1 -0
  78. package/package.json +1 -1
@@ -1 +1 @@
1
- export declare const AGENTS_MD = "# Orcha project guide\n\nThis repository uses OrchaJS, a filesystem-convention framework for durable\nAI agents. Treat the `orcha/` directory as source code. Do not edit generated\nfiles under `.orcha/`.\n\n## Commands\n\n- `orchajs init` creates the initial Orcha files without overwriting files.\n- `orchajs dev` validates agent source and watches `orcha/**` for changes.\n- `orchajs playground` opens the built-in local UI and hot reloads agent source.\n- `orchajs run <agent> --input \"\u2026\"` executes one registered agent.\n- `orchajs run <agent> --input-file request.json` accepts structured input.\n- `orchajs run <agent> --session <id> --input \"\u2026\"` continues a session.\n- `orchajs run <agent> --session <id> --tool-results results.json` submits\n pending client-action results.\n- `orchajs test` runs every enabled discovered agent test.\n- `orchajs test <agent>` or `orchajs test <agent>/<case>` narrows the run.\n- `orchajs migrate-storage --to sqlite|node-jsonl` copies all session histories\n between local stores without deleting the source.\n- `orchajs export-session <agent> <sessionId> [--output <path>]` exports one\n session from the active store as JSONL.\n- `orchajs build` creates the production Orcha bundle without calling models.\n- Add `--json` to `run` and `test` for machine-readable output.\n\n`run`, `test`, and playground executions use real providers and require\ncredentials. `dev` and `build` are offline. Sessions use JSONL by default\nunder `.orcha/sessions/<agentName>/`; opt-in SQLite stores all agents in\n`.orcha/sessions/orcha-sqlite.db`.\n\n## Production deployment\n\n`orchajs build` writes `.orcha/dist/bundle.js` for bundler integrations and\n`.orcha/dist/manifest.json` for unbundled production runtimes. If deployment\nuses plain `tsc`, `serverless-plugin-typescript`, or another packager that\ndoes not use `orchajs/esbuild`, explicitly include `.orcha/dist/**` in the\ndeployment artifact. AWS Lambda loads the manifest automatically; other\nunbundled environments require `NODE_ENV=production` or\n`ORCHA_USE_BUILD=1`.\n\nFor Serverless Framework manual builds:\n\n```yaml\npackage:\n patterns:\n - \".orcha/dist/**\"\n```\n\nDo not assume that a successful `orchajs build` means the generated files were\ncopied by a later packaging tool. Inspect the final ZIP or container image and\nconfirm that `.orcha/dist/manifest.json` is present.\n\n## Registry\n\n`orcha/index.ts` initializes providers and explicitly registers agents:\n\n```ts\nimport { orcha } from \"orchajs\";\n\norcha.init({\n providers: {\n anthropic: process.env.ANTHROPIC_API_KEY ?? \"\",\n openai: process.env.OPENAI_API_KEY ?? \"\",\n },\n agents: {\n supportBot: \"./supportBot\",\n },\n});\n```\n\nOnly registered agents are compiled. Agent keys become runtime properties\nsuch as `orcha.supportBot`. Local actions use the native Node.js runtime by\ndefault. Set `actions.runtime: \"sandbox\"` only when isolated execution is\nrequired.\n\n`orcha.init()` fields:\n\n- `providers` (required): provider configurations keyed by built-in provider\n name.\n- `agents` (required): runtime property names mapped to folders relative to\n `orcha/`. At least one agent is required.\n- `amarsia.key` (optional): project connection key generated in Amarsia.\n When set, Orcha syncs structural project and agent metadata only. It never\n uploads provider credentials, environment values, prompts, instructions,\n test inputs, or action source.\n- `amarsia.endpoint` (optional): Amarsia API URL for project sync. Defaults to\n `AMARSIA_API_URL` and then `https://api.amarsia.com`.\n- `actions` (optional): overrides the native local-action runtime or configures\n its environment and sandbox settings.\n- `mcp.credentials` (optional): runtime-only values used to resolve\n `${NAME}` placeholders in MCP headers or stdio environment values.\n- `storage.strategy` (optional): `\"node-jsonl\"` (default) or `\"sqlite\"`.\n The SQLite driver ships as an internal optional Orcha dependency.\n- `storage.directory` (optional): session directory relative to project\n root; defaults to `.orcha/sessions`.\n- `root` (optional): absolute or working-directory-relative project root;\n defaults to `ORCHA_PROJECT_ROOT` and then `process.cwd()`.\n\nThe Orcha library reads the host application's existing `process.env`.\nStandalone Orcha CLI commands also load `.env` from the project root without\noverriding environment variables already in the process.\n\nProvider configuration shapes:\n\n```ts\nproviders: {\n anthropic: process.env.ANTHROPIC_API_KEY ?? \"\",\n deepseek: process.env.DEEPSEEK_API_KEY ?? \"\",\n googlegenai: process.env.GOOGLE_API_KEY ?? \"\",\n openai: {\n apiKey: process.env.OPENAI_API_KEY ?? \"\",\n baseUrl: \"https://api.openai.com/v1\", // optional override\n },\n vertexai: {\n project: process.env.GOOGLE_CLOUD_PROJECT ?? \"\",\n location: process.env.GOOGLE_CLOUD_LOCATION ?? \"us-central1\",\n // credentials is optional; omit it to use Google ADC.\n credentials: {\n clientEmail: process.env.GOOGLE_CLIENT_EMAIL ?? \"\",\n privateKey: process.env.GOOGLE_PRIVATE_KEY ?? \"\",\n },\n baseUrl: undefined, // optional override\n },\n bedrock: {\n region: process.env.AWS_REGION ?? \"us-east-1\",\n // credentials is optional; omit it to use the AWS credential chain.\n credentials: {\n accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? \"\",\n secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? \"\",\n sessionToken: process.env.AWS_SESSION_TOKEN,\n },\n baseUrl: undefined, // optional override\n },\n}\n```\n\nAPI-key providers accept either a string shorthand or\n`{ apiKey, baseUrl? }`. Vertex AI requires `project` and `location`;\nexplicit service-account credentials are optional. Bedrock requires `region`;\nexplicit AWS credentials are optional. Never place credentials in\n`index.json`, instructions, tests, session metadata, or committed files.\n\n## MCP connections\n\nAssign named MCP folders in an agent or subagent registration:\n\n```ts\nagents: {\n supportBot: {\n path: \"./supportBot\",\n mcp: {\n github: \"./mcp/github\",\n },\n },\n}\n```\n\n`orcha/mcp/github/index.json` configures either cross-platform Streamable\nHTTP or Node-only stdio:\n\n```json\n{\n \"transport\": \"streamable-http\",\n \"url\": \"https://mcp.example.com\",\n \"headers\": {\n \"Authorization\": \"Bearer ${GITHUB_MCP_TOKEN}\"\n }\n}\n```\n\nAll discovered tools are available as `github__<toolName>`. MCP output is\nuntrusted external data. Keep secrets out of JSON and provide placeholder\nvalues through `orcha.init().mcp.credentials`; Node also reads\n`process.env`.\n\n## Agent folders\n\n```text\norcha/\n index.ts\n mcp/\n github/\n index.json\n supportBot/\n index.json\n instructions.md\n actions/\n skills/\n tests/\n evaluations/\n```\n\n`index.json` selects the model:\n\n```json\n{\n \"name\": \"Support Agent\",\n \"description\": \"Resolve customer support questions using confirmed account data.\",\n \"provider\": \"anthropic\",\n \"model\": \"claude-sonnet-4-6\",\n \"region\": \"provider_managed\",\n \"maxTokens\": 10240,\n \"outputType\": \"text\"\n}\n```\n\nOptional fields include `reasoningLevel`, `outputType: \"json\"`, and an\n`outputSchema` JSON Schema. Provider-specific reasoning values are forwarded\nwithout translation. Put the agent's stable role, boundaries, and operating\ninstructions in `instructions.md`.\n\nAgent `index.json` fields:\n\n- `name` (required): concise human-readable agent name.\n- `description` (optional): what the agent does and when it should be used.\n- `provider` (required): `\"anthropic\"`, `\"bedrock\"`, `\"deepseek\"`,\n `\"openai\"`, `\"googlegenai\"`, or `\"vertexai\"`.\n- `model` (required): exact provider model identifier.\n- `region` (optional): provider/model routing hint; defaults in durable\n metadata to `\"provider_managed\"`.\n- `maxTokens` (optional): positive integer. If omitted, the provider adapter\n chooses its default.\n- `reasoningLevel` (optional): non-empty provider-native string. Orcha does\n not translate values between providers.\n- `outputType` (optional): `\"text\"` (default) or `\"json\"`. Image and\n audio are reserved but not implemented.\n- `outputSchema` (required for JSON output): JSON Schema used for provider\n structured output and final validation.\n\n`instructions.md` is required and cannot be empty. At compile time it becomes\nthe base system prompt. Orcha appends the compact available-skill catalog and\nthe full instructions for skills already loaded in this durable session.\n\n## Subagents\n\nRegister private subagents alongside a parent in `orcha/index.ts`:\n\n```js\nagents: {\n coordinator: {\n path: \"./coordinator\",\n subagents: {\n researcher: \"./researcher\",\n },\n },\n researcher: \"./researcher\",\n}\n```\n\nOnly top-level keys become `orcha.<agentName>`. In this example the\nresearcher is both directly accessible and available to the coordinator.\nRemove its top-level entry to make it private.\n\nA parent may configure delegation limits in its `index.json`:\n\n```json\n{\n \"subagents\": {\n \"maxPerRun\": 3\n }\n}\n```\n\n`maxPerRun` limits newly created child sessions in one parent run and\ndefaults to 10.\n\nThe parent receives a compact catalog containing each subagent's registered\nname and optional description. Internal `run_agent`, `resume_agent`,\n`inspect_agent` tools let it start, continue, and inspect only child sessions\ninitiated by its current session. A delegated agent cannot delegate again.\n\nSubagent calls are synchronous. The parent becomes\n`waiting_for_subagent` while the child runs, then receives the child's text,\npause state, client-action request, failure, or completion as a normal tool\nresult. The parent and child keep separate linked JSONL sessions.\n\n## Core execution model\n\nAn **agent** is the compiled definition: model settings, instructions, actions,\nskills, and evaluations. An agent can create many independent sessions.\n\nA **session** is one durable conversation owned by one agent. It has one\n`sessionId`, optional name and metadata, fixed prompt variables, and one\nappend-only JSONL timeline. Completing one response does not close the\nsession\u2014the application can resume it later. A session cannot be transferred\nto another registered agent, but later runs may use a different provider or\nmodel if that same agent's configuration changes.\n\nA **run** is one attempt to advance a session. `run()` creates a session and\nits first run. A conversational `resume(sessionId, { content })` creates the\nnext numbered run in that session. Each run accumulates its own model usage and\nends in exactly one of these states:\n\n- `completed`: the model produced final output.\n- `waiting_for_subagent`: the parent is waiting for a synchronous child\n response and continues automatically when it arrives.\n- `waiting_for_client_action`: the model requested work that only the\n application can perform. The run is paused, not completed.\n- `paused`: active provider work was aborted, streamed output was preserved,\n and a later `resume()` starts a new run.\n- `failed`: validation, provider, storage, or execution failed. The durable\n events remain available for diagnosis.\n\nAn **execution** is the in-process handle returned by one call to `run()` or\n`resume()`. It exposes a cumulative output stream, latest snapshot, final\nresult promise, and evaluation promise. An execution ends when that invocation\ncompletes, pauses, or fails; the durable session may continue through another\nexecution.\n\nA **model round** is one provider request inside a run. One run may contain\nseveral rounds:\n\n```text\nuser input\n \u2192 model round\n \u2192 tool calls\n \u2192 tool results\n \u2192 another model round\n \u2192 final answer\n```\n\nLocal actions and skill loads are handled automatically inside the same\nexecution. Their results are sent back to the model and the model loop\ncontinues without application involvement.\n\nA **client action** deliberately crosses the application boundary. Orcha can\ndescribe the tool to the model but cannot execute it because the operation\nbelongs to a browser, mobile app, approval system, or other caller-owned\nenvironment. The complete pause/continue flow is:\n\n```text\n1. Application calls agent.run(...) or agent.resume(...content).\n2. Model requests one or more client actions.\n3. Orcha stores client_action.requested and run.paused.\n4. execution.result resolves with:\n {\n status: \"waiting_for_client_action\",\n sessionId,\n clientToolCalls: [{ callId, name, arguments }]\n }\n5. Application executes every requested action.\n6. Application calls agent.resume(sessionId, {\n toolResults: [{ callId, output, isError? }]\n }).\n7. Orcha validates every callId and output, stores the results, and continues\n the same paused run from its prior model context.\n8. The resumed execution either completes, requests more client actions, or\n fails.\n```\n\nEvery pending call must be resolved exactly once in one resume operation.\n`callId` links the submitted result to the model's request; the action name\nmust not be substituted for it. Re-submitting the identical resolved result is\nidempotent and returns the prior completed result. Submitting different data\nfor an already-resolved call fails with `action_result_conflict`.\n\n`clientCapabilities` is supplied per invocation because different callers\nmay support different client actions. Orcha exposes only declared client\nactions to that model round. Local actions are always available when compiled.\n\nOnly one execution may mutate a session at a time. Concurrent calls for the\nsame `sessionId` return `session_busy`; different sessions can run\nindependently.\n\n## Running and resuming\n\n```ts\nconst execution = orcha.supportBot.run({\n content: \"Check subscription sub_123.\",\n name: \"Subscription check\",\n metadata: { accountId: \"acct_123\" },\n clientCapabilities: [\"request_human_approval\"],\n});\n\nfor await (const snapshot of execution.stream) {\n console.log(snapshot);\n}\n\nconst result = await execution.result;\nconst evaluations = await execution.evaluations;\n```\n\n`run()` input fields:\n\n- `content` (required): a non-empty string, one content item, or an array.\n Use `{ filePath: \"./document.pdf\" }` for a local file or\n `{ url: \"https://example.com/document.pdf\" }` for a remote file.\n `mimeType` is optional when it can be inferred from the extension. Durable\n events store local paths and MIME types, never encoded file bytes.\n- `name` (optional): trimmed session label from 1 through 200 characters.\n- `metadata` (optional): at most 50 fields with non-empty keys and finite\n string, number, boolean, or null values. Metadata is durable and available\n to local action context; never place secrets in it.\n- `variables` (optional): at most 50 string values whose keys are JavaScript\n identifiers. They replace `{{ variableName }}` placeholders in\n `instructions.md`, are fixed when the session is created, and are reused\n by later resumes. A missing referenced variable fails the run.\n- `clientCapabilities` (optional): action names the current caller can\n execute. Client actions not declared here are withheld from the model.\n\n`run()` always creates a new durable session. Continue one with:\n\n```ts\nconst execution = orcha.supportBot.resume(sessionId, {\n content: \"Continue with the confirmed account.\",\n});\n```\n\nIf a result has `status: \"waiting_for_client_action\"`, execute the requested\nclient actions in the application and submit every result:\n\n```ts\norcha.supportBot.resume(sessionId, {\n toolResults: [\n { callId: \"call_123\", output: { approved: true } }\n ],\n});\n```\n\nNever invent call IDs. Use the IDs returned in `clientToolCalls`.\n\n## Actions\n\nEach action has metadata and, for local actions, executable code:\n\n```text\nactions/\n lookupAccount/\n index.json\n index.js\n```\n\n```json\n{\n \"name\": \"lookup_account\",\n \"description\": \"Look up one account.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"accountId\": { \"type\": \"string\" }\n },\n \"required\": [\"accountId\"],\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"status\": { \"type\": \"string\" }\n },\n \"required\": [\"status\"],\n \"additionalProperties\": false\n }\n}\n```\n\n```js\nexport default async function lookupAccount({ accountId }) {\n return { status: \"active\" };\n}\n```\n\nAction entrypoints can use ordinary relative project imports, TypeScript\nmodules, npm packages, transitive dependencies, and standard exports. Orcha\nbundles the complete import graph for development and production.\n\nClient actions use `\"execution\": \"client\"` and do not include executable\ncode. Orcha pauses until the caller submits their results. Keep action names,\ndescriptions, schemas, and implementations aligned.\n\nAction `index.json` fields:\n\n- `name` (required): model-facing tool name, 1\u201364 letters, numbers,\n underscores, or hyphens. `load_skill` is reserved.\n- `description` (required): tells the model when and why to call the action.\n- `enabled` (optional): defaults to `true`. Set to `false` to keep a WIP\n action inactive without deleting its folder.\n- `execution` (optional): defaults to `\"local\"`, which executes `index.js`.\n Set to `\"client\"` to pause and delegate execution to the application.\n- `parameters` (required): JSON Schema for model-generated arguments.\n- `outputSchema` (optional): JSON Schema validated against local or submitted\n client output before the model receives it.\n- `timeoutMs` (optional): integer from 1 through 120000; defaults to 10000.\n- `permissions.env` (optional): names copied from `orcha.init().actions.env`\n into the action context.\n- `permissions.network` (optional): exact hosts or wildcard subdomains such\n as `\"api.example.com\"` or `\"*.example.com\"` allowed through\n `context.fetch`. Redirects are rejected.\n- `sideEffect` (optional): descriptive metadata for whether the operation\n mutates external state. It does not currently change execution behavior.\n\n`orcha.init().actions.runtime` and an action's `execution` solve different\nproblems:\n\n- `execution: \"client\"`: Orcha never executes code for this action.\n- `execution: \"local\"` + `runtime: \"sandbox\"`: compiled code runs in a\n QuickJS isolate with JSON-only inputs/outputs, default 32 MB memory, default\n 512 KB stack, interruptible timeout, declared environment values, and\n allowlisted network access through the provided context.\n- `execution: \"local\"` + `runtime: \"native\"`: code runs in the host Node.js\n process. It can use host privileges directly. The timeout rejects slow\n asynchronous work but cannot interrupt synchronous blocking code.\n\nGlobal local-action configuration:\n\n```ts\nactions: {\n runtime: \"sandbox\", // optional; native is the default\n env: {\n BILLING_API_TOKEN: process.env.BILLING_API_TOKEN,\n },\n sandbox: {\n memoryLimitMb: 32,\n stackLimitKb: 512,\n },\n}\n```\n\nThe local action signature is\n`(parameters, context) => output | Promise<output>`. Context contains\n`sessionId`, immutable session `metadata`, a stable `idempotencyKey`,\nallowlisted `env`, guarded `fetch`, and prefixed `log`.\n\n## Skills\n\nSkills are lazy-loaded procedural instructions. Direct child folders under\n`skills/` are discovered automatically. Each folder contains `index.json`\nmetadata and `instructions.md`.\nThe model receives a compact catalog and can call the internal `load_skill`\ntool. Loaded instructions remain active for the durable session. Lifecycle\nevents are `skill.requested`, `skill.loaded`, and `skill.failed`.\n\nSkill `index.json` fields:\n\n- `name` (required): model-facing name, 1\u201364 letters, numbers, underscores,\n or hyphens; unique within the agent.\n- `description` (required): compact catalog description shown before loading.\n- `enabled` (optional): defaults to `true`. Set to `false` to keep a WIP\n skill inactive.\n- `triggers` (optional): non-empty array of non-empty situations describing\n when the model should load the skill.\n\n`instructions.md` is required and cannot be empty for enabled skills.\n`index.json.name` is the name used by the model and durable events.\n\n## Tests\n\nDirect child folders under `tests/` are discovered automatically. Each\ncase's `index.json` defines `input`, optional mocked action responses, and\n`expect`. Tests run the real compiled agent and provider. Actions listed\nunder `actions` are mocked; unlisted local actions execute live. Orcha reports\nlive action use in the terminal, test report, and session trace.\nClient actions must always be mocked because no application client is attached\nto the test runner.\n\n```json\n{\n \"input\": { \"content\": \"Check account acct_123.\" },\n \"actions\": {\n \"lookup_account\": {\n \"responses\": [\n { \"output\": { \"status\": \"active\" } }\n ]\n }\n },\n \"expect\": {\n \"status\": \"completed\",\n \"text\": { \"contains\": [\"active\"] },\n \"actions\": [\n {\n \"name\": \"lookup_account\",\n \"arguments\": { \"equals\": { \"accountId\": \"acct_123\" } }\n }\n ]\n }\n}\n```\n\nTest sessions use the `ses_test_<timestamp>_<uuid>` format and end with a `test.completed`\nevent. Prefer semantic output assertions; verify exact identifiers and values\nthrough action-argument assertions.\n\nTest `index.json` fields:\n\n- `name` (optional): friendly display name. The folder name remains the CLI\n selector.\n- `description` (optional): human-readable purpose.\n- `enabled` (optional): defaults to `true`. Set to `false` to keep a WIP test\n inactive.\n- `input` (required): an inline agent input object or a path to a JSON file\n containing that object. Relative paths resolve from the test case directory.\n- `input.content` (required for inline input): string or multimodal content\n array.\n- `input.variables` (optional): string map available to the session.\n- `input.metadata` (optional): string, number, boolean, or null values.\n- `actions` (optional): mocked actions keyed by compiled action name. Unlisted\n local actions execute live and may cause side effects. Unknown action names\n are rejected, and unlisted client actions are rejected. Every `responses`\n array is consumed in call order.\n- `responses[].output` (required): mocked action result.\n- `responses[].isError` (optional): marks the mocked result as an error.\n- `expect.status` (optional): `\"completed\"` or `\"failed\"`; defaults to\n `\"completed\"`.\n- `expect.output.equals` / `partial` (optional): exact or recursive partial\n comparison against structured output.\n- `expect.text.contains` / `excludes` (optional): case-sensitive semantic\n text checks.\n- `expect.actions` (optional): ordered expected calls. Each may assert\n `arguments.equals` or `arguments.partial`.\n\nThe test folder name is the selector used by `orchajs test agent/testName`.\n\n## Evaluations\n\nEvaluations are asynchronous LLM judges discovered from direct child folders\nunder `evaluations/`. Each folder's `index.json` defines its provider, model,\nmetrics, and thresholds:\n\n```json\n{\n \"name\": \"response_quality\",\n \"description\": \"Grounding of agent responses.\",\n \"instructions\": \"Judge the complete response using only confirmed evidence recorded in the session.\",\n \"enabled\": true,\n \"provider\": \"openai\",\n \"model\": \"gpt-5-mini\",\n \"metrics\": [\n {\n \"name\": \"groundedness\",\n \"description\": \"The answer relies on confirmed session evidence.\",\n \"threshold\": 0.8\n }\n ]\n}\n```\n\n`execution.result` does not wait for judges. Await\n`execution.evaluations` when results must finish before process exit.\nEvaluations always finish during `orchajs test`; judge errors and missed\nthresholds fail the test. Lifecycle events are `evaluation.requested`,\n`evaluation.completed`, and `evaluation.failed`.\n\nEvaluation `index.json` fields:\n\n- `name` (required): durable model-facing identifier, 1\u201364 letters, numbers,\n underscores, or hyphens; unique within the agent.\n- `description` (optional): short human-facing summary of the evaluator.\n- `instructions` (optional): detailed prompt supplied to the judge. When\n omitted, `description` is used for backward compatibility.\n- `enabled` (optional): defaults to `true`. Disabled evaluations are ignored\n by compilation and runtime.\n- `provider` and `model` (required): independently select the judge. The\n provider must also exist in `orcha.init().providers`.\n- `maxTokens` (optional): positive integer; defaults to 2000 for judges.\n- `reasoningLevel` (optional): non-empty provider-native string forwarded\n without translation.\n- `metrics` (required): non-empty array with unique metric names.\n- `metrics[].name`: 1\u201364 letters, numbers, underscores, or hyphens.\n- `metrics[].description`: exact criterion supplied to the judge.\n- `metrics[].threshold`: inclusive number from 0 to 1. A metric passes when\n the returned score is greater than or equal to this threshold.\n\nThe judge sees a sanitized transcript of user/assistant messages, action\nrequests and outcomes, client-action activity, and loaded skill names. It does\nnot receive internal reasoning blocks, replay metadata, previous evaluation\nresults, or test assertions. It must return exactly one score, reasoning\nstring, and non-empty evidence array for every configured metric.\n\n## Sessions and logs\n\nThe configured session store is the durable source of truth. JSONL stores one\ncomplete event object per line; SQLite stores one event per row. Events are\nappend-only and ordered by `sequence`.\n\nAll events use this envelope:\n\n```ts\ntype SessionEvent<T> = {\n sequence: number; // starts at 1 and increases across the whole session\n type: SessionEventType;\n timestamp: string; // ISO-8601 UTC timestamp\n run?: number; // present for run-scoped events\n data: T;\n};\n```\n\nSession-scoped events omit `run`. Optional properties whose values are\n`undefined` are omitted from serialized JSON.\n\nShared stored structures:\n\n```ts\ntype Usage = {\n inputTokens: number;\n outputTokens: number;\n reasoningTokens: number | null;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n};\n\ntype ErrorData = {\n code: string;\n message: string;\n retryable?: boolean;\n};\n\ntype UserContent =\n | { type: \"text\"; text: string }\n | { type: \"file\"; filePath: string; mimeType: string }\n | {\n type: \"image\" | \"video\" | \"audio\" | \"url\";\n mimeType: string;\n fileUri: string;\n };\n\ntype AssistantContent =\n | { type: \"text\"; text: string }\n | {\n type: \"reasoning\";\n text: string;\n replay?: { providerId?: string; opaqueData?: string };\n }\n | {\n type: \"tool_call\";\n callId: string;\n name: string;\n arguments: Record<string, unknown>;\n replay?: { providerId?: string; opaqueData?: string };\n };\n\ntype ToolResult = {\n callId: string;\n output: unknown;\n isError?: boolean;\n};\n```\n\nExact event payloads:\n\n```ts\ntype SessionCreated = SessionEvent<{\n schemaVersion: 1;\n sessionId: string;\n agent: string;\n status: \"active\";\n name?: string;\n metadata: Record<string, string | number | boolean | null>;\n variables: Record<string, string>;\n lineage?: {\n origin: \"delegated\";\n parentAgent: string;\n parentSessionId: string;\n parentCallId: string;\n };\n}>; // type \"session.created\", no run\n\ntype SessionUpdated = SessionEvent<{\n name?: string;\n metadata?: Record<string, string | number | boolean | null>;\n}>; // type \"session.updated\", no run\n\ntype RunStarted = SessionEvent<{\n status: \"running\";\n agent: string;\n provider: string;\n model: string;\n region: string;\n reasoningLevel?: string;\n outputType: \"text\" | \"json\";\n clientCapabilities: string[];\n}>; // type \"run.started\"\n\ntype UserMessageCreated = SessionEvent<{\n role: \"user\";\n content: UserContent[];\n}>; // type \"message.created\"\n\ntype AssistantMessageCreated = SessionEvent<{\n status: \"completed\" | \"incomplete\";\n provider: string;\n model: string;\n responseId?: string;\n stopReason?: \"end_turn\" | \"tool_call\" | \"max_tokens\" |\n \"content_filter\" | \"unknown\";\n role: \"assistant\";\n content: AssistantContent[];\n parsedOutput?: unknown; // final JSON output only\n usage: Usage;\n durationMs: number;\n}>; // type \"message.created\"\n\ntype ToolMessageCreated = SessionEvent<{\n role: \"tool\";\n content: ToolResult[];\n}>; // type \"message.created\"\n\ntype ActionRequested = SessionEvent<{\n callId: string;\n name: string;\n arguments: Record<string, unknown>;\n sourceHash?: string;\n idempotencyKey: string; // sessionId:callId\n}>; // type \"action.requested\"\n\ntype ActionCompleted = SessionEvent<{\n callId: string;\n name: string;\n output: unknown;\n sourceHash?: string;\n durationMs: number;\n}>; // type \"action.completed\"\n\ntype ActionFailed = SessionEvent<{\n callId: string;\n name: string;\n sourceHash?: string;\n durationMs: number;\n error: {\n code: \"action_execution_failed\";\n message: string;\n };\n}>; // type \"action.failed\"\n\ntype ClientActionRequested = SessionEvent<{\n status: \"waiting\";\n calls: Array<{\n callId: string;\n name: string;\n arguments: Record<string, unknown>;\n }>;\n localResults: ToolResult[];\n toolCallOrder: string[];\n}>; // type \"client_action.requested\"\n\ntype ClientActionResolved = SessionEvent<{\n status: \"completed\";\n results: ToolResult[];\n}>; // type \"client_action.resolved\"\n\ntype SkillRequested = SessionEvent<{\n callId: string;\n name: unknown;\n}>; // type \"skill.requested\"\n\ntype SkillLoaded = SessionEvent<{\n callId: string;\n name: string;\n alreadyLoaded: boolean;\n}>; // type \"skill.loaded\", no run\n\ntype SkillFailed = SessionEvent<{\n callId: string;\n name: unknown;\n error: {\n code: \"skill_not_found\";\n message: string;\n };\n}>; // type \"skill.failed\"\n\ntype EvaluationRequested = SessionEvent<{\n name: string;\n provider: string;\n model: string;\n evaluatedThroughSequence: number;\n}>; // type \"evaluation.requested\"\n\ntype EvaluationMetric = {\n name: string;\n score: number;\n threshold: number;\n passed: boolean;\n reasoning: string;\n evidence: string[];\n};\n\ntype EvaluationCompleted = SessionEvent<{\n name: string;\n status: \"passed\" | \"failed\";\n metrics: EvaluationMetric[];\n usage?: Usage;\n durationMs: number;\n provider: string;\n model: string;\n evaluatedThroughSequence: number;\n}>; // type \"evaluation.completed\"\n\ntype EvaluationFailed = SessionEvent<{\n name: string;\n status: \"error\";\n metrics: [];\n durationMs: number;\n error: { message: string };\n provider: string;\n model: string;\n evaluatedThroughSequence: number;\n}>; // type \"evaluation.failed\"\n\ntype SubagentInitiated = SessionEvent<{\n callId: string;\n agent: string;\n sessionId: string;\n status: \"running\";\n}>; // type \"subagent.initiated\"\n\ntype SubagentResumed = SessionEvent<{\n callId: string;\n agent: string;\n sessionId: string;\n status: \"running\";\n}>; // type \"subagent.resumed\"\n\ntype SubagentCompletedOrPausedOrFailed = SessionEvent<{\n callId: string;\n agent: string;\n sessionId: string;\n status:\n | \"completed\"\n | \"waiting_for_client_action\"\n | \"paused\"\n | \"failed\";\n output?: unknown;\n usage?: Usage;\n clientToolCalls?: Array<{\n callId: string;\n name: string;\n arguments: Record<string, unknown>;\n }>;\n error?: ErrorData;\n}>; // type \"subagent.completed\" | \"subagent.paused\" | \"subagent.failed\"\n\ntype RunPaused = SessionEvent<{\n status: \"waiting_for_client_action\" | \"paused\";\n clientToolCalls?: Array<{\n callId: string;\n name: string;\n arguments: Record<string, unknown>;\n }>;\n usage?: Usage;\n output?: unknown;\n durationMs?: number;\n}>; // type \"run.paused\"\n\ntype RunCompleted = SessionEvent<{\n status: \"completed\";\n durationMs: number;\n usage: Usage;\n}>; // type \"run.completed\"\n\ntype RunFailed = SessionEvent<{\n status: \"failed\";\n durationMs: number;\n usage?: Usage;\n error: ErrorData;\n}>; // type \"run.failed\"\n\ntype SessionPaused = SessionEvent<{\n status: \"paused\";\n}>; // type \"session.paused\", no run\n\ntype SessionResumed = SessionEvent<{\n status: \"active\";\n}>; // type \"session.resumed\", no run\n\ntype TestCompleted = SessionEvent<{\n suiteId: string;\n agent: string;\n test: string;\n status: \"passed\" | \"failed\";\n durationMs: number;\n assertions: Array<{\n path: string;\n passed: boolean;\n message: string;\n expected?: unknown;\n actual?: unknown;\n }>;\n usage?: Usage;\n evaluations?: Array<{\n name: string;\n status: \"passed\" | \"failed\" | \"error\";\n metrics: EvaluationMetric[];\n usage?: Usage;\n durationMs: number;\n error?: { message: string };\n }>;\n warnings?: Array<{\n code: \"live_actions\";\n message: string;\n actions: string[];\n }>;\n error?: ErrorData;\n}>; // type \"test.completed\", no run\n\ntype TestWarning = SessionEvent<{\n code: \"live_actions\";\n message: string;\n actions: string[];\n}>; // type \"test.warning\", no run\n```\n\nTypical event order:\n\n```text\nsession.created\nrun.started\nmessage.created (user)\nmessage.created (assistant, possibly with tool_call)\naction.requested \u2192 action.completed|action.failed # local action\nsubagent.initiated\n...child session advances independently...\nsubagent.paused\nsubagent.resumed\n...child session advances independently...\nsubagent.completed|subagent.paused|subagent.failed\nmessage.created (tool)\n...additional model/action rounds...\nmessage.created (assistant final)\nrun.completed\nevaluation.requested\nevaluation.completed|evaluation.failed\n```\n\nFor client actions, `client_action.requested` and `run.paused` replace the\nimmediate tool message. A later `resume(...toolResults)` appends\n`client_action.resolved`, the tool message, and continues the same run\nnumber. A conversational `resume(...content)` starts a new run number.\n\n## How Orcha works behind the scenes\n\n### Compilation\n\n1. `orcha/index.ts` calls `orcha.init()` with explicit agent paths.\n2. The compiler reads each registered agent's `index.json` and\n `instructions.md`.\n3. Direct child folders under `actions/`, `skills/`, `tests/`, and\n `evaluations/` are discovered automatically. Items with `\"enabled\": false`\n remain inactive.\n4. Local action source is bundled and SHA-256 hashed. Production bundles keep\n only provider adapters required by agents and enabled evaluations.\n5. Invalid paths, duplicate model-facing names, missing files, unsupported\n configuration values, and missing schema objects fail before execution.\n Concrete action arguments and outputs are validated against their schemas\n when the action is used.\n\n`orchajs dev` repeats validation when files change. `orchajs build` performs\noffline production compilation. Neither command invokes a provider.\n\n### Run lifecycle\n\n1. `run()` creates a `ses_<timestamp>_<uuid>`, acquires the per-session execution lock,\n appends `session.created`, then starts run 1.\n2. `resume()` reads and validates the existing session. Message continuation\n starts a new run; submitted client results continue the paused run.\n3. The provider receives the base instructions, available-skill catalog,\n loaded skill instructions, normalized conversation messages, action\n schemas, model settings, and current client capabilities.\n4. Provider-specific responses are normalized into text, reasoning, and tool\n call blocks. Opaque replay metadata is stored only when a provider needs it\n to replay its own prior block correctly.\n5. Tool calls are checked against compiled actions and declared client\n capabilities. Arguments and outputs are validated against JSON Schema.\n6. `load_skill` updates durable session instructions. Local actions execute\n through the configured runtime. Client actions pause safely. Tool results\n are reordered to match the model's original call order.\n7. Internal agent tools start or continue linked child sessions. A\n `run_agent` input accepts the same text or multimodal content shape as a\n normal run. Local file paths resolve from the configured Orcha project root.\n The parent reports `waiting_for_subagent` until each synchronous child\n call returns.\n8. The model loop continues until final output, failure, a pause, or the\n maximum of 20 action rounds.\n9. Usage is normalized and aggregated across every model call in the run.\n10. After `run.completed`, enabled evaluations start in the background.\n `execution.result` is already available; `execution.evaluations` waits\n for judge completion and durable persistence.\n\nThe per-session lock prevents two model executions from mutating one session\nat once. Background evaluation writes queue behind active runs so they cannot\ncause `resume()` to fail spuriously or reuse sequence numbers.\n\n### Replay and context\n\nOrcha does not send raw stored events back to the model. It projects them\ninto provider-neutral conversation messages. Completed and explicitly paused\nconversational runs become user, assistant, and tool messages, so a new run\nsees incomplete assistant text preserved by `pause()`. Lifecycle bookkeeping\nsuch as durations, test assertions, and evaluation events is excluded from\nmodel context. Reasoning text and provider replay metadata are retained where\nneeded for faithful continuation but are omitted from evaluation transcripts.\n\n### Reading sessions\n\n- `agent.get(sessionId)` projects the latest status, pending client actions,\n last output, metadata, and aggregate usage.\n- `agent.history(sessionId, { page, pageSize })` returns a safe user-facing\n timeline rather than raw provider bookkeeping.\n- `agent.events(sessionId, { page, pageSize })` returns the canonical durable\n event records for observability, audit, and debugging tools. For subsequent\n pages of a changing session, pass the first response's `throughSequence`\n back in the options to keep pagination on a stable event boundary.\n- `agent.list({ page, pageSize, status, metadata })` lists projected session\n snapshots.\n- `agent.subagentHistory(childSessionId, { page, pageSize })` returns the\n projected history of a child owned by this parent agent. Lineage checks\n prevent access through unrelated agents.\n- `agent.subagentEvents(childSessionId, { page, pageSize })` returns that\n owned child's canonical events for full transcript and debugging interfaces.\n- `agent.pause(sessionId)` aborts active provider work for the session and\n active children, preserving streamed text as an incomplete assistant\n message. `agent.resume(sessionId)` starts a new run with `\"Continue.\"`;\n pass content to give different instructions. Pending client actions still\n require their exact tool results.\n- Never read storage files directly. Use these methods so applications remain\n compatible with JSONL, SQLite, IndexedDB, remote, and future storage adapters.\n\n## Change rules\n\n- Register every new agent and subagent explicitly. Agent-owned actions, skills,\n tests, and evaluations are auto-discovered; use `\"enabled\": false` for WIP.\n- Keep runtime behavior provider-neutral.\n- Mock actions when tests must avoid side effects; document intentional live\n action coverage.\n- Do not commit `.orcha/`; it contains generated output and session data.\n- Run `orchajs dev` after filesystem changes and `orchajs test` when behavior\n changes.\n- Do not weaken assertions to match incorrect behavior. Remove an assertion\n only when it is stricter than the documented agent contract.\n";
1
+ export declare const AGENTS_MD = "# Orcha project guide\n\nThis repository uses OrchaJS, a filesystem-convention framework for durable\nAI agents. Treat the `orcha/` directory as source code. Do not edit generated\nfiles under `.orcha/`.\n\n## Commands\n\n- `orchajs init` creates the initial Orcha files without overwriting files.\n- `orchajs dev` validates agent source and watches `orcha/**` for changes.\n- `orchajs playground` opens the built-in local UI and hot reloads agent source.\n- `orchajs run <agent> --input \"\u2026\"` executes one registered agent.\n- `orchajs run <agent> --input-file request.json` accepts structured input.\n- `orchajs run <agent> --session <id> --input \"\u2026\"` continues a session.\n- `orchajs run <agent> --session <id> --tool-results results.json` submits\n pending client-action results.\n- `orchajs test` runs every enabled discovered agent test.\n- `orchajs test <agent>` or `orchajs test <agent>/<case>` narrows the run.\n- `orchajs migrate-storage --to sqlite|node-jsonl` copies all session histories\n between local stores without deleting the source.\n- `orchajs export-session <agent> <sessionId> [--output <path>]` exports one\n session from the active store as JSONL.\n- `orchajs build` creates the production Orcha bundle without calling models.\n- Add `--json` to `run` and `test` for machine-readable output.\n\n`run`, `test`, and playground executions use real providers and require\ncredentials. `dev` and `build` are offline. Sessions use JSONL by default\nunder `.orcha/sessions/<agentName>/`; opt-in SQLite stores all agents in\n`.orcha/sessions/orcha-sqlite.db`.\n\n## Production deployment\n\n`orchajs build` writes `.orcha/dist/bundle.js` for bundler integrations and\n`.orcha/dist/manifest.json` for unbundled production runtimes. If deployment\nuses plain `tsc`, `serverless-plugin-typescript`, or another packager that\ndoes not use `orchajs/esbuild`, explicitly include `.orcha/dist/**` in the\ndeployment artifact. AWS Lambda loads the manifest automatically; other\nunbundled environments require `NODE_ENV=production` or\n`ORCHA_USE_BUILD=1`.\n\nFor Serverless Framework manual builds:\n\n```yaml\npackage:\n patterns:\n - \".orcha/dist/**\"\n```\n\nDo not assume that a successful `orchajs build` means the generated files were\ncopied by a later packaging tool. Inspect the final ZIP or container image and\nconfirm that `.orcha/dist/manifest.json` is present.\n\n## Registry\n\n`orcha/index.ts` initializes providers and explicitly registers agents:\n\n```ts\nimport { orcha } from \"orchajs\";\n\norcha.init({\n providers: {\n anthropic: process.env.ANTHROPIC_API_KEY ?? \"\",\n openai: process.env.OPENAI_API_KEY ?? \"\",\n },\n agents: {\n supportBot: \"./supportBot\",\n },\n});\n```\n\nFor Amarsia inference, the registry contains only project routing and agent\npaths; provider and model selection stay in each agent `index.json`. Supported\nproviders are `openai`, `anthropic`, `googlegenai`, and `deepseek`; `bedrock`\nand `vertexai` are direct-inference providers only:\n\n```ts\norcha.init({\n amarsia: {\n key: process.env.AMARSIA_PROJECT_KEY ?? \"\",\n inference: true,\n },\n agents: {\n supportBot: \"./supportBot\",\n },\n});\n```\n\nOnly registered agents are compiled. Agent keys become runtime properties\nsuch as `orcha.supportBot`. Local actions use the native Node.js runtime by\ndefault. Set `actions.runtime: \"sandbox\"` only when isolated execution is\nrequired.\n\n`orcha.init()` fields:\n\n- `providers` (required for direct inference): provider configurations keyed\n by built-in provider name. Omit it when `amarsia.inference` is true.\n- `agents` (required): runtime property names mapped to folders relative to\n `orcha/`. At least one agent is required.\n- `amarsia.key` (optional): project connection key generated in Amarsia.\n By itself, it syncs structural project and agent metadata only. Enabling\n inference sends model requests through Amarsia, and cloud storage syncs\n session events. Provider credentials, environment values, and action source\n are never included.\n- `amarsia.endpoint` (optional): Amarsia API URL for project sync. Defaults to\n `AMARSIA_API_URL` and then `https://api.amarsia.com`.\n- `amarsia.inference` (optional): routes all model calls through Amarsia while\n preserving the provider and model in each manifest. It reuses `amarsia.key`;\n local provider credentials are not required.\n- `actions` (optional): overrides the native local-action runtime or configures\n its environment and sandbox settings.\n- `mcp.credentials` (optional): runtime-only values used to resolve\n `${NAME}` placeholders in MCP headers or stdio environment values.\n- `storage.strategy` (optional): `\"node-jsonl\"` (default), `\"sqlite\"`, or\n local-first `\"cloud\"`. Cloud requires `amarsia.key`, keeps a native local\n cache, commits appends locally without cloud latency, and delivers durable\n bounded outbox batches in the background. Await `orcha.close()` before\n reinitializing; close reports any cloud tail that could not be flushed.\n- `storage.directory` (optional): session directory relative to project\n root; defaults to `.orcha/sessions`.\n- `root` (optional): absolute or working-directory-relative project root;\n defaults to `ORCHA_PROJECT_ROOT` and then `process.cwd()`.\n\nThe Orcha library reads the host application's existing `process.env`.\nStandalone Orcha CLI commands also load `.env` from the project root without\noverriding environment variables already in the process.\n\nProvider configuration shapes:\n\n```ts\nproviders: {\n anthropic: process.env.ANTHROPIC_API_KEY ?? \"\",\n deepseek: process.env.DEEPSEEK_API_KEY ?? \"\",\n googlegenai: process.env.GOOGLE_API_KEY ?? \"\",\n openai: {\n apiKey: process.env.OPENAI_API_KEY ?? \"\",\n baseUrl: \"https://api.openai.com/v1\", // optional override\n },\n vertexai: {\n project: process.env.GOOGLE_CLOUD_PROJECT ?? \"\",\n location: process.env.GOOGLE_CLOUD_LOCATION ?? \"us-central1\",\n // credentials is optional; omit it to use Google ADC.\n credentials: {\n clientEmail: process.env.GOOGLE_CLIENT_EMAIL ?? \"\",\n privateKey: process.env.GOOGLE_PRIVATE_KEY ?? \"\",\n },\n baseUrl: undefined, // optional override\n },\n bedrock: {\n region: process.env.AWS_REGION ?? \"us-east-1\",\n // credentials is optional; omit it to use the AWS credential chain.\n credentials: {\n accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? \"\",\n secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? \"\",\n sessionToken: process.env.AWS_SESSION_TOKEN,\n },\n baseUrl: undefined, // optional override\n },\n}\n```\n\nAPI-key providers accept either a string shorthand or\n`{ apiKey, baseUrl? }`. Vertex AI requires `project` and `location`;\nexplicit service-account credentials are optional. Bedrock requires `region`;\nexplicit AWS credentials are optional. Never place credentials in\n`index.json`, instructions, tests, session metadata, or committed files.\n\n## MCP connections\n\nAssign named MCP folders in an agent or subagent registration:\n\n```ts\nagents: {\n supportBot: {\n path: \"./supportBot\",\n mcp: {\n github: \"./mcp/github\",\n },\n },\n}\n```\n\n`orcha/mcp/github/index.json` configures either cross-platform Streamable\nHTTP or Node-only stdio:\n\n```json\n{\n \"transport\": \"streamable-http\",\n \"url\": \"https://mcp.example.com\",\n \"headers\": {\n \"Authorization\": \"Bearer ${GITHUB_MCP_TOKEN}\"\n }\n}\n```\n\nAll discovered tools are available as `github__<toolName>`. MCP output is\nuntrusted external data. Keep secrets out of JSON and provide placeholder\nvalues through `orcha.init().mcp.credentials`; Node also reads\n`process.env`.\n\n## Agent folders\n\n```text\norcha/\n index.ts\n mcp/\n github/\n index.json\n supportBot/\n index.json\n instructions.md\n actions/\n skills/\n tests/\n evaluations/\n```\n\n`index.json` selects the model:\n\n```json\n{\n \"name\": \"Support Agent\",\n \"description\": \"Resolve customer support questions using confirmed account data.\",\n \"provider\": \"anthropic\",\n \"model\": \"claude-sonnet-4-6\",\n \"region\": \"provider_managed\",\n \"maxTokens\": 10240,\n \"outputType\": \"text\"\n}\n```\n\nOptional fields include `reasoningLevel`, `outputType: \"json\"`, and an\n`outputSchema` JSON Schema. Provider-specific reasoning values are forwarded\nwithout translation. Put the agent's stable role, boundaries, and operating\ninstructions in `instructions.md`.\n\nAgent `index.json` fields:\n\n- `name` (required): concise human-readable agent name.\n- `description` (optional): what the agent does and when it should be used.\n- `provider` (required): `\"anthropic\"`, `\"bedrock\"`, `\"deepseek\"`,\n `\"openai\"`, `\"googlegenai\"`, or `\"vertexai\"`.\n- `model` (required): exact provider model identifier.\n- `region` (optional): provider/model routing hint; defaults in durable\n metadata to `\"provider_managed\"`.\n- `maxTokens` (optional): positive integer. If omitted, the provider adapter\n chooses its default.\n- `reasoningLevel` (optional): non-empty provider-native string. Orcha does\n not translate values between providers.\n- `outputType` (optional): `\"text\"` (default) or `\"json\"`. Image and\n audio are reserved but not implemented.\n- `outputSchema` (required for JSON output): JSON Schema used for provider\n structured output and final validation.\n\n`instructions.md` is required and cannot be empty. At compile time it becomes\nthe base system prompt. Orcha appends the compact available-skill catalog and\nthe full instructions for skills already loaded in this durable session.\n\n## Subagents\n\nRegister private subagents alongside a parent in `orcha/index.ts`:\n\n```js\nagents: {\n coordinator: {\n path: \"./coordinator\",\n subagents: {\n researcher: \"./researcher\",\n },\n },\n researcher: \"./researcher\",\n}\n```\n\nOnly top-level keys become `orcha.<agentName>`. In this example the\nresearcher is both directly accessible and available to the coordinator.\nRemove its top-level entry to make it private.\n\nA parent may configure delegation limits in its `index.json`:\n\n```json\n{\n \"subagents\": {\n \"maxPerRun\": 3\n }\n}\n```\n\n`maxPerRun` limits newly created child sessions in one parent run and\ndefaults to 10.\n\nThe parent receives a compact catalog containing each subagent's registered\nname and optional description. Internal `run_agent`, `resume_agent`,\n`inspect_agent` tools let it start, continue, and inspect only child sessions\ninitiated by its current session. A delegated agent cannot delegate again.\n\nSubagent calls are synchronous. The parent becomes\n`waiting_for_subagent` while the child runs, then receives the child's text,\npause state, client-action request, failure, or completion as a normal tool\nresult. The parent and child keep separate linked JSONL sessions.\n\n## Core execution model\n\nAn **agent** is the compiled definition: model settings, instructions, actions,\nskills, and evaluations. An agent can create many independent sessions.\n\nA **session** is one durable conversation owned by one agent. It has one\n`sessionId`, optional name and metadata, fixed prompt variables, and one\nappend-only JSONL timeline. Completing one response does not close the\nsession\u2014the application can resume it later. A session cannot be transferred\nto another registered agent, but later runs may use a different provider or\nmodel if that same agent's configuration changes.\n\nA **run** is one attempt to advance a session. `run()` creates a session and\nits first run. A conversational `resume(sessionId, { content })` creates the\nnext numbered run in that session. Each run accumulates its own model usage and\nends in exactly one of these states:\n\n- `completed`: the model produced final output.\n- `waiting_for_subagent`: the parent is waiting for a synchronous child\n response and continues automatically when it arrives.\n- `waiting_for_client_action`: the model requested work that only the\n application can perform. The run is paused, not completed.\n- `paused`: active provider work was aborted, streamed output was preserved,\n and a later `resume()` starts a new run.\n- `failed`: validation, provider, storage, or execution failed. The durable\n events remain available for diagnosis.\n\nAn **execution** is the in-process handle returned by one call to `run()` or\n`resume()`. It exposes a cumulative output stream, latest snapshot, final\nresult promise, and evaluation promise. An execution ends when that invocation\ncompletes, pauses, or fails; the durable session may continue through another\nexecution.\n\nA **model round** is one provider request inside a run. One run may contain\nseveral rounds:\n\n```text\nuser input\n \u2192 model round\n \u2192 tool calls\n \u2192 tool results\n \u2192 another model round\n \u2192 final answer\n```\n\nLocal actions and skill loads are handled automatically inside the same\nexecution. Their results are sent back to the model and the model loop\ncontinues without application involvement.\n\nA **client action** deliberately crosses the application boundary. Orcha can\ndescribe the tool to the model but cannot execute it because the operation\nbelongs to a browser, mobile app, approval system, or other caller-owned\nenvironment. The complete pause/continue flow is:\n\n```text\n1. Application calls agent.run(...) or agent.resume(...content).\n2. Model requests one or more client actions.\n3. Orcha stores client_action.requested and run.paused.\n4. execution.result resolves with:\n {\n status: \"waiting_for_client_action\",\n sessionId,\n clientToolCalls: [{ callId, name, arguments }]\n }\n5. Application executes every requested action.\n6. Application calls agent.resume(sessionId, {\n toolResults: [{ callId, output, contents?, isError? }]\n }).\n7. Orcha validates every callId and output, stores the results, and continues\n the same paused run from its prior model context.\n8. The resumed execution either completes, requests more client actions, or\n fails.\n```\n\nEvery pending call must be resolved exactly once in one resume operation.\n`callId` links the submitted result to the model's request; the action name\nmust not be substituted for it. Re-submitting the identical resolved result is\nidempotent and returns the prior completed result. Submitting different data\nfor an already-resolved call fails with `action_result_conflict`.\n\n`clientCapabilities` is supplied per invocation because different callers\nmay support different client actions. Orcha exposes only declared client\nactions to that model round. Local actions are always available when compiled.\n\nOnly one execution may mutate a session at a time. Concurrent calls for the\nsame `sessionId` return `session_busy`; different sessions can run\nindependently.\n\n## Running and resuming\n\n```ts\nconst execution = orcha.supportBot.run({\n content: \"Check subscription sub_123.\",\n name: \"Subscription check\",\n metadata: { accountId: \"acct_123\" },\n clientCapabilities: [\"request_human_approval\"],\n});\n\nfor await (const snapshot of execution.stream) {\n console.log(snapshot);\n}\n\nconst result = await execution.result;\nconst evaluations = await execution.evaluations;\n```\n\n`run()` and conversational `resume()` accept either a direct `AgentContentInput` (a string, a single content item, or an array of content items) or an object with `content` and optional fields:\n\n- `content` (required when passing an options object): a non-empty string, one content item, or an array.\n Use `{ filePath: \"./document.pdf\" }` for a local file or\n `{ url: \"https://example.com/document.pdf\" }` for a remote file.\n `mimeType` is optional when it can be inferred from the extension. Durable\n events store local paths and MIME types, never encoded file bytes.\n- `name` (optional): trimmed session label from 1 through 200 characters.\n- `metadata` (optional): at most 50 fields with non-empty keys and finite\n string, number, boolean, or null values. Metadata is durable and available\n to local action context; never place secrets in it.\n- `variables` (optional): at most 50 string values whose keys are JavaScript\n identifiers. They replace `{{ variableName }}` placeholders in\n `instructions.md`, are fixed when the session is created, and are reused\n by later resumes. A missing referenced variable fails the run.\n- `clientCapabilities` (optional): action names the current caller can\n execute. Client actions not declared here are withheld from the model.\n\n`run()` always creates a new durable session. Continue one with:\n\n```ts\nconst execution = orcha.supportBot.resume(sessionId, {\n content: \"Continue with the confirmed account.\",\n});\n```\n\nIf a result has `status: \"waiting_for_client_action\"`, execute the requested\nclient actions in the application and submit every result:\n\n```ts\norcha.supportBot.resume(sessionId, {\n toolResults: [\n {\n callId: \"call_123\",\n output: { approved: true },\n contents: [{ filePath: \"./signed-approval.pdf\" }], // optional media/content items\n }\n ],\n});\n```\n\nNever invent call IDs. Use the IDs returned in `clientToolCalls`.\n\n## Actions\n\nEach action has metadata and, for local actions, executable code:\n\n```text\nactions/\n lookupAccount/\n index.json\n index.js\n```\n\n```json\n{\n \"name\": \"lookup_account\",\n \"description\": \"Look up one account.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"accountId\": { \"type\": \"string\" }\n },\n \"required\": [\"accountId\"],\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"status\": { \"type\": \"string\" }\n },\n \"required\": [\"status\"],\n \"additionalProperties\": false\n }\n}\n```\n\n```js\nexport default async function lookupAccount({ accountId }) {\n return { status: \"active\" };\n}\n```\n\nAction entrypoints can use ordinary relative project imports, TypeScript\nmodules, npm packages, transitive dependencies, and standard exports. Orcha\nbundles the complete import graph for development and production.\n\nClient actions use `\"execution\": \"client\"` and do not include executable\ncode. Orcha pauses until the caller submits their results. Keep action names,\ndescriptions, schemas, and implementations aligned.\n\nAction `index.json` fields:\n\n- `name` (required): model-facing tool name, 1\u201364 letters, numbers,\n underscores, or hyphens. `load_skill` is reserved.\n- `description` (required): tells the model when and why to call the action.\n- `enabled` (optional): defaults to `true`. Set to `false` to keep a WIP\n action inactive without deleting its folder.\n- `execution` (optional): defaults to `\"local\"`, which executes `index.js`.\n Set to `\"client\"` to pause and delegate execution to the application.\n- `parameters` (required): JSON Schema for model-generated arguments.\n- `outputSchema` (optional): JSON Schema validated against local or submitted\n client output before the model receives it.\n- `timeoutMs` (optional): integer from 1 through 120000; defaults to 10000.\n- `permissions.env` (optional): names copied from `orcha.init().actions.env`\n into the action context.\n- `permissions.network` (optional): exact hosts or wildcard subdomains such\n as `\"api.example.com\"` or `\"*.example.com\"` allowed through\n `context.fetch`. Redirects are rejected.\n- `sideEffect` (optional): descriptive metadata for whether the operation\n mutates external state. It does not currently change execution behavior.\n\n`orcha.init().actions.runtime` and an action's `execution` solve different\nproblems:\n\n- `execution: \"client\"`: Orcha never executes code for this action.\n- `execution: \"local\"` + `runtime: \"sandbox\"`: compiled code runs in a\n QuickJS isolate with JSON-only inputs/outputs, default 32 MB memory, default\n 512 KB stack, interruptible timeout, declared environment values, and\n allowlisted network access through the provided context.\n- `execution: \"local\"` + `runtime: \"native\"`: code runs in the host Node.js\n process. It can use host privileges directly. The timeout rejects slow\n asynchronous work but cannot interrupt synchronous blocking code.\n\nGlobal local-action configuration:\n\n```ts\nactions: {\n runtime: \"sandbox\", // optional; native is the default\n env: {\n BILLING_API_TOKEN: process.env.BILLING_API_TOKEN,\n },\n sandbox: {\n memoryLimitMb: 32,\n stackLimitKb: 512,\n },\n}\n```\n\nThe local action signature is\n`(parameters, context) => output | Promise<output>`. Context contains\n`sessionId`, immutable session `metadata`, a stable `idempotencyKey`,\nallowlisted `env`, guarded `fetch`, and prefixed `log`.\n\nActions can also return media or multimodal content back to the model alongside\ntheir structured JSON output by returning `{ output: jsonOutput, contents: [...] }`.\n`contents` accepts any `AgentContentInput` (such as `{ filePath }`,\n`{ url }`, or content items). `outputSchema` validates `output` directly.\n\n## Skills\n\nSkills are lazy-loaded procedural instructions. Direct child folders under\n`skills/` are discovered automatically. Each folder contains `index.json`\nmetadata and `instructions.md`.\nThe model receives a compact catalog and can call the internal `load_skill`\ntool. Loaded instructions remain active for the durable session. Lifecycle\nevents are `skill.requested`, `skill.loaded`, and `skill.failed`.\n\nSkill `index.json` fields:\n\n- `name` (required): model-facing name, 1\u201364 letters, numbers, underscores,\n or hyphens; unique within the agent.\n- `description` (required): compact catalog description shown before loading.\n- `enabled` (optional): defaults to `true`. Set to `false` to keep a WIP\n skill inactive.\n- `triggers` (optional): non-empty array of non-empty situations describing\n when the model should load the skill.\n\n`instructions.md` is required and cannot be empty for enabled skills.\n`index.json.name` is the name used by the model and durable events.\n\n## Tests\n\nDirect child folders under `tests/` are discovered automatically. Each\ncase's `index.json` defines `input`, optional mocked action responses, and\n`expect`. Tests run the real compiled agent and provider. Actions listed\nunder `actions` are mocked; unlisted local actions execute live. Orcha reports\nlive action use in the terminal, test report, and session trace.\nClient actions must always be mocked because no application client is attached\nto the test runner.\n\n```json\n{\n \"input\": { \"content\": \"Check account acct_123.\" },\n \"actions\": {\n \"lookup_account\": {\n \"responses\": [\n { \"output\": { \"status\": \"active\" } }\n ]\n }\n },\n \"expect\": {\n \"status\": \"completed\",\n \"text\": { \"contains\": [\"active\"] },\n \"actions\": [\n {\n \"name\": \"lookup_account\",\n \"arguments\": { \"equals\": { \"accountId\": \"acct_123\" } }\n }\n ]\n }\n}\n```\n\nTest sessions use the `ses_test_<timestamp>_<uuid>` format and end with a `test.completed`\nevent. Prefer semantic output assertions; verify exact identifiers and values\nthrough action-argument assertions.\n\nTest `index.json` fields:\n\n- `name` (optional): friendly display name. The folder name remains the CLI\n selector.\n- `description` (optional): human-readable purpose.\n- `enabled` (optional): defaults to `true`. Set to `false` to keep a WIP test\n inactive.\n- `input` (required): an inline agent input object or a path to a JSON file\n containing that object. Relative paths resolve from the test case directory.\n- `input.content` (required for inline input): string or multimodal content\n array.\n- `input.variables` (optional): string map available to the session.\n- `input.metadata` (optional): string, number, boolean, or null values.\n- `actions` (optional): mocked actions keyed by compiled action name. Unlisted\n local actions execute live and may cause side effects. Unknown action names\n are rejected, and unlisted client actions are rejected. Every `responses`\n array is consumed in call order.\n- `responses[].output` (required): mocked action result.\n- `responses[].isError` (optional): marks the mocked result as an error.\n- `expect.status` (optional): `\"completed\"` or `\"failed\"`; defaults to\n `\"completed\"`.\n- `expect.output.equals` / `partial` (optional): exact or recursive partial\n comparison against structured output.\n- `expect.text.contains` / `excludes` (optional): case-sensitive semantic\n text checks.\n- `expect.actions` (optional): ordered expected calls. Each may assert\n `arguments.equals` or `arguments.partial`.\n\nThe test folder name is the selector used by `orchajs test agent/testName`.\n\n## Evaluations\n\nEvaluations are asynchronous LLM judges discovered from direct child folders\nunder `evaluations/`. Each folder's `index.json` defines its provider, model,\nmetrics, and thresholds:\n\n```json\n{\n \"name\": \"response_quality\",\n \"description\": \"Grounding of agent responses.\",\n \"instructions\": \"Judge the complete response using only confirmed evidence recorded in the session.\",\n \"enabled\": true,\n \"provider\": \"openai\",\n \"model\": \"gpt-5-mini\",\n \"metrics\": [\n {\n \"name\": \"groundedness\",\n \"description\": \"The answer relies on confirmed session evidence.\",\n \"threshold\": 0.8\n }\n ]\n}\n```\n\n`execution.result` does not wait for judges. Await\n`execution.evaluations` when results must finish before process exit.\nEvaluations always finish during `orchajs test`; judge errors and missed\nthresholds fail the test. Lifecycle events are `evaluation.requested`,\n`evaluation.completed`, and `evaluation.failed`.\n\nEvaluation `index.json` fields:\n\n- `name` (required): durable model-facing identifier, 1\u201364 letters, numbers,\n underscores, or hyphens; unique within the agent.\n- `description` (optional): short human-facing summary of the evaluator.\n- `instructions` (optional): detailed prompt supplied to the judge. When\n omitted, `description` is used for backward compatibility.\n- `enabled` (optional): defaults to `true`. Disabled evaluations are ignored\n by compilation and runtime.\n- `provider` and `model` (required): independently select the judge. The\n provider must also exist in `orcha.init().providers`.\n- `maxTokens` (optional): positive integer; defaults to 2000 for judges.\n- `reasoningLevel` (optional): non-empty provider-native string forwarded\n without translation.\n- `metrics` (required): non-empty array with unique metric names.\n- `metrics[].name`: 1\u201364 letters, numbers, underscores, or hyphens.\n- `metrics[].description`: exact criterion supplied to the judge.\n- `metrics[].threshold`: inclusive number from 0 to 1. A metric passes when\n the returned score is greater than or equal to this threshold.\n\nThe judge sees a sanitized transcript of user/assistant messages, action\nrequests and outcomes, client-action activity, and loaded skill names. It does\nnot receive internal reasoning blocks, replay metadata, previous evaluation\nresults, or test assertions. It must return exactly one score, reasoning\nstring, and non-empty evidence array for every configured metric.\n\n## Sessions and logs\n\nThe configured session store is the durable source of truth. JSONL stores one\ncomplete event object per line; SQLite stores one event per row. Events are\nappend-only and ordered by `sequence`.\n\nAll events use this envelope:\n\n```ts\ntype SessionEvent<T> = {\n sequence: number; // starts at 1 and increases across the whole session\n type: SessionEventType;\n timestamp: string; // ISO-8601 UTC timestamp\n run?: number; // present for run-scoped events\n data: T;\n};\n```\n\nSession-scoped events omit `run`. Optional properties whose values are\n`undefined` are omitted from serialized JSON.\n\nShared stored structures:\n\n```ts\ntype Usage = {\n inputTokens: number;\n outputTokens: number;\n reasoningTokens: number | null;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n};\n\ntype ErrorData = {\n code: string;\n message: string;\n retryable?: boolean;\n};\n\ntype UserContent =\n | { type: \"text\"; text: string }\n | { type: \"file\"; filePath: string; mimeType: string }\n | {\n type: \"image\" | \"video\" | \"audio\" | \"url\";\n mimeType: string;\n fileUri: string;\n };\n\ntype AssistantContent =\n | { type: \"text\"; text: string }\n | {\n type: \"reasoning\";\n text: string;\n replay?: { providerId?: string; opaqueData?: string };\n }\n | {\n type: \"tool_call\";\n callId: string;\n name: string;\n arguments: Record<string, unknown>;\n replay?: { providerId?: string; opaqueData?: string };\n };\n\ntype ToolResult = {\n callId: string;\n output: unknown;\n isError?: boolean;\n};\n```\n\nExact event payloads:\n\n```ts\ntype SessionCreated = SessionEvent<{\n schemaVersion: 1;\n sessionId: string;\n agent: string;\n status: \"active\";\n name?: string;\n metadata: Record<string, string | number | boolean | null>;\n variables: Record<string, string>;\n lineage?: {\n origin: \"delegated\";\n parentAgent: string;\n parentSessionId: string;\n parentCallId: string;\n };\n}>; // type \"session.created\", no run\n\ntype SessionUpdated = SessionEvent<{\n name?: string;\n metadata?: Record<string, string | number | boolean | null>;\n}>; // type \"session.updated\", no run\n\ntype RunStarted = SessionEvent<{\n status: \"running\";\n agent: string;\n provider: string;\n model: string;\n region: string;\n reasoningLevel?: string;\n outputType: \"text\" | \"json\";\n clientCapabilities: string[];\n}>; // type \"run.started\"\n\ntype UserMessageCreated = SessionEvent<{\n role: \"user\";\n content: UserContent[];\n}>; // type \"message.created\"\n\ntype AssistantMessageCreated = SessionEvent<{\n status: \"completed\" | \"incomplete\";\n provider: string;\n model: string;\n responseId?: string;\n stopReason?: \"end_turn\" | \"tool_call\" | \"max_tokens\" |\n \"content_filter\" | \"unknown\";\n role: \"assistant\";\n content: AssistantContent[];\n parsedOutput?: unknown; // final JSON output only\n usage: Usage;\n durationMs: number;\n}>; // type \"message.created\"\n\ntype ToolMessageCreated = SessionEvent<{\n role: \"tool\";\n content: ToolResult[];\n}>; // type \"message.created\"\n\ntype ActionRequested = SessionEvent<{\n callId: string;\n name: string;\n arguments: Record<string, unknown>;\n sourceHash?: string;\n idempotencyKey: string; // sessionId:callId\n}>; // type \"action.requested\"\n\ntype ActionCompleted = SessionEvent<{\n callId: string;\n name: string;\n output: unknown;\n sourceHash?: string;\n durationMs: number;\n}>; // type \"action.completed\"\n\ntype ActionFailed = SessionEvent<{\n callId: string;\n name: string;\n sourceHash?: string;\n durationMs: number;\n error: {\n code: \"action_execution_failed\";\n message: string;\n };\n}>; // type \"action.failed\"\n\ntype ClientActionRequested = SessionEvent<{\n status: \"waiting\";\n calls: Array<{\n callId: string;\n name: string;\n arguments: Record<string, unknown>;\n }>;\n localResults: ToolResult[];\n toolCallOrder: string[];\n}>; // type \"client_action.requested\"\n\ntype ClientActionResolved = SessionEvent<{\n status: \"completed\";\n results: ToolResult[];\n}>; // type \"client_action.resolved\"\n\ntype SkillRequested = SessionEvent<{\n callId: string;\n name: unknown;\n}>; // type \"skill.requested\"\n\ntype SkillLoaded = SessionEvent<{\n callId: string;\n name: string;\n alreadyLoaded: boolean;\n}>; // type \"skill.loaded\", no run\n\ntype SkillFailed = SessionEvent<{\n callId: string;\n name: unknown;\n error: {\n code: \"skill_not_found\";\n message: string;\n };\n}>; // type \"skill.failed\"\n\ntype EvaluationRequested = SessionEvent<{\n name: string;\n provider: string;\n model: string;\n evaluatedThroughSequence: number;\n}>; // type \"evaluation.requested\"\n\ntype EvaluationMetric = {\n name: string;\n score: number;\n threshold: number;\n passed: boolean;\n reasoning: string;\n evidence: string[];\n};\n\ntype EvaluationCompleted = SessionEvent<{\n name: string;\n status: \"passed\" | \"failed\";\n metrics: EvaluationMetric[];\n usage?: Usage;\n durationMs: number;\n provider: string;\n model: string;\n evaluatedThroughSequence: number;\n}>; // type \"evaluation.completed\"\n\ntype EvaluationFailed = SessionEvent<{\n name: string;\n status: \"error\";\n metrics: [];\n durationMs: number;\n error: { message: string };\n provider: string;\n model: string;\n evaluatedThroughSequence: number;\n}>; // type \"evaluation.failed\"\n\ntype SubagentInitiated = SessionEvent<{\n callId: string;\n agent: string;\n sessionId: string;\n status: \"running\";\n}>; // type \"subagent.initiated\"\n\ntype SubagentResumed = SessionEvent<{\n callId: string;\n agent: string;\n sessionId: string;\n status: \"running\";\n}>; // type \"subagent.resumed\"\n\ntype SubagentCompletedOrPausedOrFailed = SessionEvent<{\n callId: string;\n agent: string;\n sessionId: string;\n status:\n | \"completed\"\n | \"waiting_for_client_action\"\n | \"paused\"\n | \"failed\";\n output?: unknown;\n usage?: Usage;\n clientToolCalls?: Array<{\n callId: string;\n name: string;\n arguments: Record<string, unknown>;\n }>;\n error?: ErrorData;\n}>; // type \"subagent.completed\" | \"subagent.paused\" | \"subagent.failed\"\n\ntype RunPaused = SessionEvent<{\n status: \"waiting_for_client_action\" | \"paused\";\n clientToolCalls?: Array<{\n callId: string;\n name: string;\n arguments: Record<string, unknown>;\n }>;\n usage?: Usage;\n output?: unknown;\n durationMs?: number;\n}>; // type \"run.paused\"\n\ntype RunCompleted = SessionEvent<{\n status: \"completed\";\n durationMs: number;\n usage: Usage;\n}>; // type \"run.completed\"\n\ntype RunFailed = SessionEvent<{\n status: \"failed\";\n durationMs: number;\n usage?: Usage;\n error: ErrorData;\n}>; // type \"run.failed\"\n\ntype SessionPaused = SessionEvent<{\n status: \"paused\";\n}>; // type \"session.paused\", no run\n\ntype SessionResumed = SessionEvent<{\n status: \"active\";\n}>; // type \"session.resumed\", no run\n\ntype TestCompleted = SessionEvent<{\n suiteId: string;\n agent: string;\n test: string;\n status: \"passed\" | \"failed\";\n durationMs: number;\n assertions: Array<{\n path: string;\n passed: boolean;\n message: string;\n expected?: unknown;\n actual?: unknown;\n }>;\n usage?: Usage;\n evaluations?: Array<{\n name: string;\n status: \"passed\" | \"failed\" | \"error\";\n metrics: EvaluationMetric[];\n usage?: Usage;\n durationMs: number;\n error?: { message: string };\n }>;\n warnings?: Array<{\n code: \"live_actions\";\n message: string;\n actions: string[];\n }>;\n error?: ErrorData;\n}>; // type \"test.completed\", no run\n\ntype TestWarning = SessionEvent<{\n code: \"live_actions\";\n message: string;\n actions: string[];\n}>; // type \"test.warning\", no run\n```\n\nTypical event order:\n\n```text\nsession.created\nrun.started\nmessage.created (user)\nmessage.created (assistant, possibly with tool_call)\naction.requested \u2192 action.completed|action.failed # local action\nsubagent.initiated\n...child session advances independently...\nsubagent.paused\nsubagent.resumed\n...child session advances independently...\nsubagent.completed|subagent.paused|subagent.failed\nmessage.created (tool)\n...additional model/action rounds...\nmessage.created (assistant final)\nrun.completed\nevaluation.requested\nevaluation.completed|evaluation.failed\n```\n\nFor client actions, `client_action.requested` and `run.paused` replace the\nimmediate tool message. A later `resume(...toolResults)` appends\n`client_action.resolved`, the tool message, and continues the same run\nnumber. A conversational `resume(...content)` starts a new run number.\n\n## How Orcha works behind the scenes\n\n### Compilation\n\n1. `orcha/index.ts` calls `orcha.init()` with explicit agent paths.\n2. The compiler reads each registered agent's `index.json` and\n `instructions.md`.\n3. Direct child folders under `actions/`, `skills/`, `tests/`, and\n `evaluations/` are discovered automatically. Items with `\"enabled\": false`\n remain inactive.\n4. Local action source is bundled and SHA-256 hashed. Production bundles keep\n only provider adapters required by agents and enabled evaluations.\n5. Invalid paths, duplicate model-facing names, missing files, unsupported\n configuration values, and missing schema objects fail before execution.\n Concrete action arguments and outputs are validated against their schemas\n when the action is used.\n\n`orchajs dev` repeats validation when files change. `orchajs build` performs\noffline production compilation. Neither command invokes a provider.\n\n### Run lifecycle\n\n1. `run()` creates a `ses_<timestamp>_<uuid>`, acquires the per-session execution lock,\n appends `session.created`, then starts run 1.\n2. `resume()` reads and validates the existing session. Message continuation\n starts a new run; submitted client results continue the paused run.\n3. The provider receives the base instructions, available-skill catalog,\n loaded skill instructions, normalized conversation messages, action\n schemas, model settings, and current client capabilities.\n4. Provider-specific responses are normalized into text, reasoning, and tool\n call blocks. Opaque replay metadata is stored only when a provider needs it\n to replay its own prior block correctly.\n5. Tool calls are checked against compiled actions and declared client\n capabilities. Arguments and outputs are validated against JSON Schema.\n6. `load_skill` updates durable session instructions. Local actions execute\n through the configured runtime. Client actions pause safely. Tool results\n are reordered to match the model's original call order.\n7. Internal agent tools start or continue linked child sessions. A\n `run_agent` input accepts the same text or multimodal content shape as a\n normal run. Local file paths resolve from the configured Orcha project root.\n The parent reports `waiting_for_subagent` until each synchronous child\n call returns.\n8. The model loop continues until final output, failure, a pause, or the\n maximum of 20 action rounds.\n9. Usage is normalized and aggregated across every model call in the run.\n10. After `run.completed`, enabled evaluations start in the background.\n `execution.result` is already available; `execution.evaluations` waits\n for judge completion and durable persistence.\n\nThe per-session lock prevents two model executions from mutating one session\nat once. Background evaluation writes queue behind active runs so they cannot\ncause `resume()` to fail spuriously or reuse sequence numbers.\n\n### Replay and context\n\nOrcha does not send raw stored events back to the model. It projects them\ninto provider-neutral conversation messages. Completed and explicitly paused\nconversational runs become user, assistant, and tool messages, so a new run\nsees incomplete assistant text preserved by `pause()`. Lifecycle bookkeeping\nsuch as durations, test assertions, and evaluation events is excluded from\nmodel context. Reasoning text and provider replay metadata are retained where\nneeded for faithful continuation but are omitted from evaluation transcripts.\n\n### Reading sessions\n\n- `agent.get(sessionId)` projects the latest status, pending client actions,\n last output, metadata, and aggregate usage.\n- `agent.history(sessionId, { page, pageSize })` returns a safe user-facing\n timeline rather than raw provider bookkeeping.\n- `agent.events(sessionId, { page, pageSize })` returns the canonical durable\n event records for observability, audit, and debugging tools. For subsequent\n pages of a changing session, pass the first response's `throughSequence`\n back in the options to keep pagination on a stable event boundary.\n- `agent.list({ page, pageSize, status, metadata })` lists projected session\n snapshots.\n- `agent.subagentHistory(childSessionId, { page, pageSize })` returns the\n projected history of a child owned by this parent agent. Lineage checks\n prevent access through unrelated agents.\n- `agent.subagentEvents(childSessionId, { page, pageSize })` returns that\n owned child's canonical events for full transcript and debugging interfaces.\n- `agent.pause(sessionId)` aborts active provider work for the session and\n active children, preserving streamed text as an incomplete assistant\n message. `agent.resume(sessionId)` starts a new run with `\"Continue.\"`;\n pass content to give different instructions. Pending client actions still\n require their exact tool results.\n- Never read storage files directly. Use these methods so applications remain\n compatible with JSONL, SQLite, IndexedDB, remote, and future storage adapters.\n\n## Change rules\n\n- Register every new agent and subagent explicitly. Agent-owned actions, skills,\n tests, and evaluations are auto-discovered; use `\"enabled\": false` for WIP.\n- Keep runtime behavior provider-neutral.\n- Mock actions when tests must avoid side effects; document intentional live\n action coverage.\n- Do not commit `.orcha/`; it contains generated output and session data.\n- Run `orchajs dev` after filesystem changes and `orchajs test` when behavior\n changes.\n- Do not weaken assertions to match incorrect behavior. Remove an assertion\n only when it is stricter than the documented agent contract.\n";
@@ -68,6 +68,23 @@ orcha.init({
68
68
  });
69
69
  \`\`\`
70
70
 
71
+ For Amarsia inference, the registry contains only project routing and agent
72
+ paths; provider and model selection stay in each agent \`index.json\`. Supported
73
+ providers are \`openai\`, \`anthropic\`, \`googlegenai\`, and \`deepseek\`; \`bedrock\`
74
+ and \`vertexai\` are direct-inference providers only:
75
+
76
+ \`\`\`ts
77
+ orcha.init({
78
+ amarsia: {
79
+ key: process.env.AMARSIA_PROJECT_KEY ?? "",
80
+ inference: true,
81
+ },
82
+ agents: {
83
+ supportBot: "./supportBot",
84
+ },
85
+ });
86
+ \`\`\`
87
+
71
88
  Only registered agents are compiled. Agent keys become runtime properties
72
89
  such as \`orcha.supportBot\`. Local actions use the native Node.js runtime by
73
90
  default. Set \`actions.runtime: "sandbox"\` only when isolated execution is
@@ -75,22 +92,29 @@ required.
75
92
 
76
93
  \`orcha.init()\` fields:
77
94
 
78
- - \`providers\` (required): provider configurations keyed by built-in provider
79
- name.
95
+ - \`providers\` (required for direct inference): provider configurations keyed
96
+ by built-in provider name. Omit it when \`amarsia.inference\` is true.
80
97
  - \`agents\` (required): runtime property names mapped to folders relative to
81
98
  \`orcha/\`. At least one agent is required.
82
99
  - \`amarsia.key\` (optional): project connection key generated in Amarsia.
83
- When set, Orcha syncs structural project and agent metadata only. It never
84
- uploads provider credentials, environment values, prompts, instructions,
85
- test inputs, or action source.
100
+ By itself, it syncs structural project and agent metadata only. Enabling
101
+ inference sends model requests through Amarsia, and cloud storage syncs
102
+ session events. Provider credentials, environment values, and action source
103
+ are never included.
86
104
  - \`amarsia.endpoint\` (optional): Amarsia API URL for project sync. Defaults to
87
105
  \`AMARSIA_API_URL\` and then \`https://api.amarsia.com\`.
106
+ - \`amarsia.inference\` (optional): routes all model calls through Amarsia while
107
+ preserving the provider and model in each manifest. It reuses \`amarsia.key\`;
108
+ local provider credentials are not required.
88
109
  - \`actions\` (optional): overrides the native local-action runtime or configures
89
110
  its environment and sandbox settings.
90
111
  - \`mcp.credentials\` (optional): runtime-only values used to resolve
91
112
  \`\${NAME}\` placeholders in MCP headers or stdio environment values.
92
- - \`storage.strategy\` (optional): \`"node-jsonl"\` (default) or \`"sqlite"\`.
93
- The SQLite driver ships as an internal optional Orcha dependency.
113
+ - \`storage.strategy\` (optional): \`"node-jsonl"\` (default), \`"sqlite"\`, or
114
+ local-first \`"cloud"\`. Cloud requires \`amarsia.key\`, keeps a native local
115
+ cache, commits appends locally without cloud latency, and delivers durable
116
+ bounded outbox batches in the background. Await \`orcha.close()\` before
117
+ reinitializing; close reports any cloud tail that could not be flushed.
94
118
  - \`storage.directory\` (optional): session directory relative to project
95
119
  root; defaults to \`.orcha/sessions\`.
96
120
  - \`root\` (optional): absolute or working-directory-relative project root;
@@ -340,7 +364,7 @@ environment. The complete pause/continue flow is:
340
364
  }
341
365
  5. Application executes every requested action.
342
366
  6. Application calls agent.resume(sessionId, {
343
- toolResults: [{ callId, output, isError? }]
367
+ toolResults: [{ callId, output, contents?, isError? }]
344
368
  }).
345
369
  7. Orcha validates every callId and output, stores the results, and continues
346
370
  the same paused run from its prior model context.
@@ -380,9 +404,9 @@ const result = await execution.result;
380
404
  const evaluations = await execution.evaluations;
381
405
  \`\`\`
382
406
 
383
- \`run()\` input fields:
407
+ \`run()\` and conversational \`resume()\` accept either a direct \`AgentContentInput\` (a string, a single content item, or an array of content items) or an object with \`content\` and optional fields:
384
408
 
385
- - \`content\` (required): a non-empty string, one content item, or an array.
409
+ - \`content\` (required when passing an options object): a non-empty string, one content item, or an array.
386
410
  Use \`{ filePath: "./document.pdf" }\` for a local file or
387
411
  \`{ url: "https://example.com/document.pdf" }\` for a remote file.
388
412
  \`mimeType\` is optional when it can be inferred from the extension. Durable
@@ -412,7 +436,11 @@ client actions in the application and submit every result:
412
436
  \`\`\`ts
413
437
  orcha.supportBot.resume(sessionId, {
414
438
  toolResults: [
415
- { callId: "call_123", output: { approved: true } }
439
+ {
440
+ callId: "call_123",
441
+ output: { approved: true },
442
+ contents: [{ filePath: "./signed-approval.pdf" }], // optional media/content items
443
+ }
416
444
  ],
417
445
  });
418
446
  \`\`\`
@@ -520,6 +548,11 @@ The local action signature is
520
548
  \`sessionId\`, immutable session \`metadata\`, a stable \`idempotencyKey\`,
521
549
  allowlisted \`env\`, guarded \`fetch\`, and prefixed \`log\`.
522
550
 
551
+ Actions can also return media or multimodal content back to the model alongside
552
+ their structured JSON output by returning \`{ output: jsonOutput, contents: [...] }\`.
553
+ \`contents\` accepts any \`AgentContentInput\` (such as \`{ filePath }\`,
554
+ \`{ url }\`, or content items). \`outputSchema\` validates \`output\` directly.
555
+
523
556
  ## Skills
524
557
 
525
558
  Skills are lazy-loaded procedural instructions. Direct child folders under
package/dist/cli.js CHANGED
@@ -369,21 +369,34 @@ function parseInput(value) {
369
369
  if (!trimmed) {
370
370
  throw new Error("Agent input cannot be empty.");
371
371
  }
372
- if (!trimmed.startsWith("{")) {
372
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
373
373
  return trimmed;
374
374
  }
375
375
  const parsed = JSON.parse(trimmed);
376
- if (!parsed ||
377
- typeof parsed !== "object" ||
378
- !("content" in parsed)) {
379
- throw new Error('Structured input must be an object with "content".');
376
+ if (Array.isArray(parsed)) {
377
+ return parsed;
380
378
  }
381
- return parsed;
379
+ if (parsed && typeof parsed === "object") {
380
+ if ("content" in parsed) {
381
+ return parsed;
382
+ }
383
+ if ("filePath" in parsed ||
384
+ "url" in parsed ||
385
+ "fileUri" in parsed ||
386
+ "file_uri" in parsed ||
387
+ "type" in parsed) {
388
+ return parsed;
389
+ }
390
+ }
391
+ throw new Error('Structured input must be a content item/array or an object with "content".');
382
392
  }
383
393
  function normalizeResumeInput(input) {
384
- return typeof input === "string"
385
- ? input
386
- : { content: input.content };
394
+ return typeof input === "object" &&
395
+ input !== null &&
396
+ !Array.isArray(input) &&
397
+ "content" in input
398
+ ? { content: input.content }
399
+ : input;
387
400
  }
388
401
  async function readToolResults(path) {
389
402
  const parsed = JSON.parse(await readFile(path, "utf8"));
@@ -3,14 +3,16 @@ 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
+ import { loadProjectEnvironment } from "../env.js";
6
7
  import { orcha } from "../orcha.js";
7
- import { setRegistryCompiler } from "../runtime/compiler-hook.js";
8
+ import { setRegistryCompilationActive, setRegistryCompiler, } from "../runtime/compiler-hook.js";
8
9
  import { compileRegistry } from "./compile.js";
9
10
  import { builtInProviderCatalog, isBuiltInProvider, } from "../providers/catalog.js";
10
11
  import { ensureCompiledMcpDependencies, ensureProviderDependencies, } from "../providers/dependencies.js";
11
12
  let registryImportSequence = 0;
12
13
  export async function buildProject(options = {}) {
13
14
  const projectRoot = resolve(options.projectRoot ?? process.cwd());
15
+ loadProjectEnvironment(projectRoot);
14
16
  const target = options.target ?? "node";
15
17
  setRegistryCompiler((configuration, compilerProjectRoot) => compileRegistry(configuration.agents, resolve(compilerProjectRoot, "orcha"), configuration.actions?.runtime ?? "native", target));
16
18
  const registryPath = resolve(projectRoot, "orcha/index.ts");
@@ -22,8 +24,12 @@ export async function buildProject(options = {}) {
22
24
  const productionEntryPath = resolve(temporaryDirectory, "production-entry.mjs");
23
25
  const outputPath = resolve(projectRoot, `.orcha/dist/${bundleFileName(target)}`);
24
26
  const manifestPath = resolve(projectRoot, ".orcha/dist/manifest.json");
27
+ if (orcha.isInitialized()) {
28
+ throw new Error("Cannot compile an Orcha project while the shared development runtime is initialized. Await orcha.close() first.");
29
+ }
25
30
  await mkdir(temporaryDirectory, { recursive: true });
26
31
  await mkdir(dirname(outputPath), { recursive: true });
32
+ let compilationRuntimeCreated = false;
27
33
  try {
28
34
  await bundleEntry({
29
35
  entryPoints: [registryPath],
@@ -39,10 +45,13 @@ export async function buildProject(options = {}) {
39
45
  const previousProjectRoot = process.env.ORCHA_PROJECT_ROOT;
40
46
  process.env.ORCHA_COMPILING = "1";
41
47
  process.env.ORCHA_PROJECT_ROOT = projectRoot;
48
+ setRegistryCompilationActive(true);
42
49
  try {
43
50
  await import(`${pathToFileURL(registryBundlePath).href}?build=${Date.now()}-${registryImportSequence++}`);
44
51
  }
45
52
  finally {
53
+ compilationRuntimeCreated = orcha.isInitialized();
54
+ setRegistryCompilationActive(false);
46
55
  if (previousCompiling === undefined) {
47
56
  delete process.env.ORCHA_COMPILING;
48
57
  }
@@ -57,6 +66,10 @@ export async function buildProject(options = {}) {
57
66
  }
58
67
  }
59
68
  const compiledBundle = orcha.getCompiledBundle();
69
+ const inferenceEnabled = orcha.isInferenceEnabled();
70
+ const cloudStorageEnabled = orcha.isCloudStorageEnabled();
71
+ await orcha.close();
72
+ compilationRuntimeCreated = false;
60
73
  if (target !== "node" &&
61
74
  compiledBundle.actionRuntime === "sandbox") {
62
75
  throw new Error(`The ${target} target supports precompiled native actions only. Set actions.runtime to "native".`);
@@ -70,24 +83,29 @@ export async function buildProject(options = {}) {
70
83
  : "";
71
84
  const platformActionRuntimeSource = createPlatformActionRuntimeSource(target);
72
85
  const nodeStorageExports = target === "node" ? createNodeStorageExports() : "";
73
- const includedProviders = [
74
- ...new Set(allCompiledAgents(compiledBundle.agents).flatMap((agent) => [
75
- agent.provider,
76
- ...Object.values(agent.evaluations ?? {})
77
- .filter((evaluation) => evaluation.enabled !== false)
78
- .map((evaluation) => evaluation.provider),
79
- ])),
80
- ];
86
+ const includedProviders = inferenceEnabled
87
+ ? []
88
+ : [
89
+ ...new Set(allCompiledAgents(compiledBundle.agents).flatMap((agent) => [
90
+ agent.provider,
91
+ ...Object.values(agent.evaluations ?? {})
92
+ .filter((evaluation) => evaluation.enabled !== false)
93
+ .map((evaluation) => evaluation.provider),
94
+ ])),
95
+ ];
81
96
  const providerRuntimeSource = createProviderRuntimeSource(includedProviders, target);
82
- await ensureProviderDependencies(includedProviders, projectRoot);
97
+ if (!inferenceEnabled) {
98
+ await ensureProviderDependencies(includedProviders, projectRoot);
99
+ }
83
100
  const hasMcp = allCompiledAgents(compiledBundle.agents).some((agent) => Object.keys(agent.mcpServers ?? {}).length > 0);
84
101
  await ensureCompiledMcpDependencies(compiledBundle, projectRoot);
85
102
  const mcpRuntimeSource = hasMcp
86
103
  ? createMcpRuntimeSource(target)
87
104
  : "";
88
- const needsNodeRequire = compiledBundle.actionRuntime === "sandbox" ||
89
- includedProviders.includes("vertexai") ||
90
- includedProviders.includes("bedrock");
105
+ const optionalFeatureRuntimeSource = createOptionalFeatureRuntimeSource({
106
+ inference: inferenceEnabled,
107
+ cloudStorage: cloudStorageEnabled,
108
+ });
91
109
  await writeFile(productionEntryPath, [
92
110
  `import { createOrcha } from ${JSON.stringify(runtimeFactoryPath)};`,
93
111
  `import { ${runtimePlatformExport(target)} as runtimePlatform } from ${JSON.stringify(runtimePlatformPath)};`,
@@ -97,6 +115,7 @@ export async function buildProject(options = {}) {
97
115
  providerRuntimeSource,
98
116
  platformActionRuntimeSource,
99
117
  mcpRuntimeSource,
118
+ optionalFeatureRuntimeSource,
100
119
  sandboxRuntimeSource,
101
120
  `const compiledBundle = ${JSON.stringify(compiledBundle)};`,
102
121
  "const generateProviderResponse = createProviderResponseGenerator(includedProviders);",
@@ -120,7 +139,7 @@ export async function buildProject(options = {}) {
120
139
  define: {
121
140
  "process.env.ORCHA_INCLUDE_SANDBOX": JSON.stringify(compiledBundle.actionRuntime === "sandbox" ? "1" : "0"),
122
141
  },
123
- ...(needsNodeRequire && target === "node"
142
+ ...(target === "node"
124
143
  ? {
125
144
  banner: {
126
145
  js: [
@@ -143,6 +162,10 @@ export async function buildProject(options = {}) {
143
162
  return outputPath;
144
163
  }
145
164
  finally {
165
+ setRegistryCompilationActive(false);
166
+ if (compilationRuntimeCreated && orcha.isInitialized()) {
167
+ await orcha.close();
168
+ }
146
169
  await rm(temporaryDirectory, {
147
170
  recursive: true,
148
171
  force: true,
@@ -199,6 +222,26 @@ function createMcpRuntimeSource(target) {
199
222
  "",
200
223
  ].join("\n");
201
224
  }
225
+ function createOptionalFeatureRuntimeSource(options) {
226
+ if (!options.inference && !options.cloudStorage) {
227
+ return "";
228
+ }
229
+ const sourceRoot = dirname(fileURLToPath(import.meta.url));
230
+ const hooksPath = resolve(sourceRoot, "../runtime/optional-features.js").replaceAll("\\", "/");
231
+ const imports = [];
232
+ const registrations = [];
233
+ if (options.inference) {
234
+ const inferencePath = resolve(sourceRoot, "../amarsia/inference.js").replaceAll("\\", "/");
235
+ imports.push(`import { createAmarsiaInferenceGenerator } from ${JSON.stringify(inferencePath)};`, `import { setInferenceGeneratorFactory } from ${JSON.stringify(hooksPath)};`);
236
+ registrations.push("setInferenceGeneratorFactory(createAmarsiaInferenceGenerator);");
237
+ }
238
+ if (options.cloudStorage) {
239
+ const cloudPath = resolve(sourceRoot, "../storage/cloud.js").replaceAll("\\", "/");
240
+ imports.push(`import { CloudSessionStore } from ${JSON.stringify(cloudPath)};`, `import { setCloudSessionStoreFactory } from ${JSON.stringify(hooksPath)};`);
241
+ registrations.push("setCloudSessionStoreFactory((options) => new CloudSessionStore(options));");
242
+ }
243
+ return [...imports, ...registrations, ""].join("\n");
244
+ }
202
245
  function createNodeStorageExports() {
203
246
  const sourceRoot = dirname(fileURLToPath(import.meta.url));
204
247
  const jsonlPath = resolve(sourceRoot, "../storage/node-jsonl.js").replaceAll("\\", "/");
@@ -0,0 +1,2 @@
1
+ /** Lets esbuild's Node ESM output resolve dynamic `require()` of built-ins. */
2
+ export declare const nodeEsmRequireBanner: string;
@@ -0,0 +1,5 @@
1
+ /** Lets esbuild's Node ESM output resolve dynamic `require()` of built-ins. */
2
+ export const nodeEsmRequireBanner = [
3
+ 'import { createRequire as __orchaCreateRequire } from "node:module";',
4
+ "const require = __orchaCreateRequire(import.meta.url);",
5
+ ].join("\n");
package/dist/orcha.js CHANGED
@@ -1,12 +1,15 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
+ import { createAmarsiaInferenceGenerator } from "./amarsia/inference.js";
3
4
  import { generateProviderResponse } from "./providers/index.js";
4
5
  import { setNativeRuntimeLoader, setSandboxRuntimeLoader, } from "./runtime/actions/execute.js";
5
6
  import { executeNativeAction } from "./runtime/actions/native.js";
6
7
  import { getRegistryCompiler } from "./runtime/compiler-hook.js";
7
8
  import { createOrcha } from "./runtime/create-orcha.js";
8
9
  import { setMcpClientFactory } from "./runtime/mcp/client.js";
10
+ import { setCloudSessionStoreFactory, setInferenceGeneratorFactory, } from "./runtime/optional-features.js";
9
11
  import { nodeRuntimePlatform } from "./runtime/platform-node.js";
12
+ import { CloudSessionStore } from "./storage/cloud.js";
10
13
  setNativeRuntimeLoader(async () => ({ executeNativeAction }));
11
14
  setSandboxRuntimeLoader(async () => {
12
15
  const modulePath = "./runtime/actions/sandbox.js";
@@ -17,6 +20,8 @@ setMcpClientFactory(async (server, credentials) => {
17
20
  const { createNodeMcpClient } = await import(modulePath);
18
21
  return createNodeMcpClient(server, credentials);
19
22
  });
23
+ setInferenceGeneratorFactory(createAmarsiaInferenceGenerator);
24
+ setCloudSessionStoreFactory((options) => new CloudSessionStore(options));
20
25
  export const orcha = createOrcha((configuration) => {
21
26
  const projectRoot = resolve(configuration.root ??
22
27
  process.env.ORCHA_PROJECT_ROOT ??
@@ -612,6 +612,9 @@ function parseToolResults(value) {
612
612
  return {
613
613
  callId: result.callId,
614
614
  output: result.output,
615
+ ...(result.contents !== undefined
616
+ ? { contents: parseContent(result.contents) }
617
+ : {}),
615
618
  ...(result.isError === true ? { isError: true } : {}),
616
619
  };
617
620
  });
@@ -45,9 +45,11 @@ export async function loadProject(projectRoot) {
45
45
  }
46
46
  if (!orcha.isInitialized() ||
47
47
  orcha.getCompiledBundle() === previousBundle) {
48
- throw new Error('"orcha/index.ts" must call orcha.init({ providers, agents }).');
48
+ throw new Error('"orcha/index.ts" must call orcha.init({ agents, ... }).');
49
+ }
50
+ if (!orcha.isInferenceEnabled()) {
51
+ await ensureCompiledProviderDependencies(orcha.getCompiledBundle(), projectRoot);
49
52
  }
50
- await ensureCompiledProviderDependencies(orcha.getCompiledBundle(), projectRoot);
51
53
  await ensureCompiledMcpDependencies(orcha.getCompiledBundle(), projectRoot);
52
54
  }
53
55
  finally {