orchajs 0.23.12 → 0.24.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.
package/README.md CHANGED
@@ -319,6 +319,78 @@ npm install quickjs-emscripten-core @jitl/quickjs-singlefile-cjs-release-sync
319
319
 
320
320
  ---
321
321
 
322
+ ## MCP connections
323
+
324
+ Assign named MCP connections directly to agents and subagents:
325
+
326
+ ```js
327
+ orcha.init({
328
+ providers: {
329
+ anthropic: process.env.ANTHROPIC_API_KEY,
330
+ },
331
+ mcp: {
332
+ credentials: {
333
+ GITHUB_MCP_TOKEN: process.env.GITHUB_MCP_TOKEN,
334
+ },
335
+ },
336
+ agents: {
337
+ coordinator: {
338
+ path: "./coordinator",
339
+ mcp: {
340
+ github: "./mcp/github",
341
+ },
342
+ subagents: {
343
+ researcher: {
344
+ path: "./researcher",
345
+ mcp: {
346
+ docs: "./mcp/docs",
347
+ },
348
+ },
349
+ },
350
+ },
351
+ },
352
+ });
353
+ ```
354
+
355
+ Each path contains an `index.json`. Streamable HTTP works in Node.js,
356
+ browsers, Expo, and React Native:
357
+
358
+ ```json
359
+ {
360
+ "transport": "streamable-http",
361
+ "url": "https://mcp.example.com",
362
+ "headers": {
363
+ "Authorization": "Bearer ${GITHUB_MCP_TOKEN}"
364
+ },
365
+ "timeoutMs": 30000
366
+ }
367
+ ```
368
+
369
+ Node.js also supports local stdio servers:
370
+
371
+ ```json
372
+ {
373
+ "transport": "stdio",
374
+ "command": "npx",
375
+ "args": ["-y", "@example/mcp-server"],
376
+ "env": {
377
+ "API_TOKEN": "${EXAMPLE_MCP_TOKEN}"
378
+ }
379
+ }
380
+ ```
381
+
382
+ Orcha discovers every server tool lazily and exposes it as
383
+ `<connection>__<tool>`, for example `github__get_issue`. Tool calls and
384
+ results use the durable action event timeline. Credential placeholders resolve
385
+ from `orcha.init().mcp.credentials`; Node.js additionally resolves them from
386
+ `process.env`. Never put secret values directly in MCP JSON files.
387
+
388
+ The optional MCP SDK is installed automatically when an agent uses MCP.
389
+ Projects without MCP do not install or bundle it. Browser and React Native
390
+ targets reject stdio connections during compilation.
391
+
392
+ ---
393
+
322
394
  ## Quick start
323
395
 
324
396
  ```bash
@@ -329,23 +401,15 @@ This installs `orchajs` and its development tooling in the current project,
329
401
  then creates the starter agent files.
330
402
 
331
403
  The default installation includes the compiler, CLI, native actions, JSONL
332
- storage, and fetch-based Anthropic, DeepSeek, and OpenAI adapters. Install an
333
- optional integration only in applications that use it:
404
+ storage, and fetch-based Anthropic, DeepSeek, and OpenAI adapters. Orcha
405
+ automatically installs the Bedrock, Google, or MCP SDK only when a compiled
406
+ agent selects that integration. Other optional integrations remain explicit:
334
407
 
335
408
  ```bash
336
- # Amazon Bedrock
337
- npm install @aws-sdk/client-bedrock-runtime
338
-
339
- # Google GenAI or Vertex AI (Node.js 20+)
340
- npm install @google/genai
341
-
342
409
  # SQLite session storage
343
410
  npm install better-sqlite3
344
411
  ```
345
412
 
346
- Selecting an integration without its package produces an error that names the
347
- dependency to install.
348
-
349
413
  Install the OrchaJS skill to give supported coding agents version-aware Orcha
350
414
  workflows:
351
415
 
@@ -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- `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## Agent folders\n\n```text\norcha/\n index.ts\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 10 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\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";
@@ -87,6 +87,8 @@ required.
87
87
  \`AMARSIA_API_URL\` and then \`https://api.amarsia.com\`.
88
88
  - \`actions\` (optional): overrides the native local-action runtime or configures
89
89
  its environment and sandbox settings.
90
+ - \`mcp.credentials\` (optional): runtime-only values used to resolve
91
+ \`\${NAME}\` placeholders in MCP headers or stdio environment values.
90
92
  - \`storage.strategy\` (optional): \`"node-jsonl"\` (default) or \`"sqlite"\`.
91
93
  The SQLite driver ships as an internal optional Orcha dependency.
92
94
  - \`storage.directory\` (optional): session directory relative to project
@@ -138,11 +140,47 @@ explicit service-account credentials are optional. Bedrock requires \`region\`;
138
140
  explicit AWS credentials are optional. Never place credentials in
139
141
  \`index.json\`, instructions, tests, session metadata, or committed files.
140
142
 
143
+ ## MCP connections
144
+
145
+ Assign named MCP folders in an agent or subagent registration:
146
+
147
+ \`\`\`ts
148
+ agents: {
149
+ supportBot: {
150
+ path: "./supportBot",
151
+ mcp: {
152
+ github: "./mcp/github",
153
+ },
154
+ },
155
+ }
156
+ \`\`\`
157
+
158
+ \`orcha/mcp/github/index.json\` configures either cross-platform Streamable
159
+ HTTP or Node-only stdio:
160
+
161
+ \`\`\`json
162
+ {
163
+ "transport": "streamable-http",
164
+ "url": "https://mcp.example.com",
165
+ "headers": {
166
+ "Authorization": "Bearer \${GITHUB_MCP_TOKEN}"
167
+ }
168
+ }
169
+ \`\`\`
170
+
171
+ All discovered tools are available as \`github__<toolName>\`. MCP output is
172
+ untrusted external data. Keep secrets out of JSON and provide placeholder
173
+ values through \`orcha.init().mcp.credentials\`; Node also reads
174
+ \`process.env\`.
175
+
141
176
  ## Agent folders
142
177
 
143
178
  \`\`\`text
144
179
  orcha/
145
180
  index.ts
181
+ mcp/
182
+ github/
183
+ index.json
146
184
  supportBot/
147
185
  index.json
148
186
  instructions.md
@@ -1029,7 +1067,7 @@ offline production compilation. Neither command invokes a provider.
1029
1067
  The parent reports \`waiting_for_subagent\` until each synchronous child
1030
1068
  call returns.
1031
1069
  8. The model loop continues until final output, failure, a pause, or the
1032
- maximum of 10 action rounds.
1070
+ maximum of 20 action rounds.
1033
1071
  9. Usage is normalized and aggregated across every model call in the run.
1034
1072
  10. After \`run.completed\`, enabled evaluations start in the background.
1035
1073
  \`execution.result\` is already available; \`execution.evaluations\` waits
@@ -7,7 +7,7 @@ import { orcha } from "../orcha.js";
7
7
  import { setRegistryCompiler } from "../runtime/compiler-hook.js";
8
8
  import { compileRegistry } from "./compile.js";
9
9
  import { builtInProviderCatalog, isBuiltInProvider, } from "../providers/catalog.js";
10
- import { ensureProviderDependencies } from "../providers/dependencies.js";
10
+ import { ensureCompiledMcpDependencies, ensureProviderDependencies, } from "../providers/dependencies.js";
11
11
  let registryImportSequence = 0;
12
12
  export async function buildProject(options = {}) {
13
13
  const projectRoot = resolve(options.projectRoot ?? process.cwd());
@@ -80,6 +80,11 @@ export async function buildProject(options = {}) {
80
80
  ];
81
81
  const providerRuntimeSource = createProviderRuntimeSource(includedProviders, target);
82
82
  await ensureProviderDependencies(includedProviders, projectRoot);
83
+ const hasMcp = allCompiledAgents(compiledBundle.agents).some((agent) => Object.keys(agent.mcpServers ?? {}).length > 0);
84
+ await ensureCompiledMcpDependencies(compiledBundle, projectRoot);
85
+ const mcpRuntimeSource = hasMcp
86
+ ? createMcpRuntimeSource(target)
87
+ : "";
83
88
  const needsNodeRequire = compiledBundle.actionRuntime === "sandbox" ||
84
89
  includedProviders.includes("vertexai") ||
85
90
  includedProviders.includes("bedrock");
@@ -91,6 +96,7 @@ export async function buildProject(options = {}) {
91
96
  nodeStorageExports,
92
97
  providerRuntimeSource,
93
98
  platformActionRuntimeSource,
99
+ mcpRuntimeSource,
94
100
  sandboxRuntimeSource,
95
101
  `const compiledBundle = ${JSON.stringify(compiledBundle)};`,
96
102
  "const generateProviderResponse = createProviderResponseGenerator(includedProviders);",
@@ -179,6 +185,20 @@ function createPlatformActionRuntimeSource(target) {
179
185
  "",
180
186
  ].join("\n");
181
187
  }
188
+ function createMcpRuntimeSource(target) {
189
+ const runtimeDirectory = dirname(fileURLToPath(import.meta.url));
190
+ const clientPath = resolve(runtimeDirectory, "../runtime/mcp/client.js").replaceAll("\\", "/");
191
+ const implementationPath = resolve(runtimeDirectory, target === "node"
192
+ ? "../runtime/mcp/node-client.js"
193
+ : "../runtime/mcp/http-client.js").replaceAll("\\", "/");
194
+ const factoryName = target === "node" ? "createNodeMcpClient" : "createHttpMcpClient";
195
+ return [
196
+ `import { setMcpClientFactory } from ${JSON.stringify(clientPath)};`,
197
+ `import { ${factoryName} } from ${JSON.stringify(implementationPath)};`,
198
+ `setMcpClientFactory(${factoryName});`,
199
+ "",
200
+ ].join("\n");
201
+ }
182
202
  function createNodeStorageExports() {
183
203
  const sourceRoot = dirname(fileURLToPath(import.meta.url));
184
204
  const jsonlPath = resolve(sourceRoot, "../storage/node-jsonl.js").replaceAll("\\", "/");
@@ -16,13 +16,14 @@ export function compileRegistry(registrations, registryRoot, actionRuntime = "na
16
16
  }
17
17
  const normalized = normalizeAgentRegistration(key, registration);
18
18
  const subagents = {};
19
- for (const [subagentKey, registeredPath] of Object.entries(normalized.subagents)) {
19
+ for (const [subagentKey, registration] of Object.entries(normalized.subagents)) {
20
20
  if (!subagentKey.trim()) {
21
21
  throw new Error(`Agent "${key}" has an empty subagent name.`);
22
22
  }
23
- subagents[subagentKey] = compileAgent(subagentKey, registeredPath, registryRoot, actionRuntime, target);
23
+ const subagent = normalizeSubagentRegistration(key, subagentKey, registration);
24
+ subagents[subagentKey] = compileAgent(subagentKey, subagent.path, subagent.mcp, registryRoot, actionRuntime, target);
24
25
  }
25
- const parent = compileAgent(key, normalized.path, registryRoot, actionRuntime, target);
26
+ const parent = compileAgent(key, normalized.path, normalized.mcp, registryRoot, actionRuntime, target);
26
27
  agents[key] = Object.freeze({
27
28
  ...parent,
28
29
  subagentPolicy: Object.keys(subagents).length > 0
@@ -48,7 +49,7 @@ function normalizeAgentRegistration(key, registration) {
48
49
  if (!registration.trim()) {
49
50
  throw new Error(`Agent "${key}" must register a folder path.`);
50
51
  }
51
- return { path: registration, subagents: {} };
52
+ return { path: registration, mcp: {}, subagents: {} };
52
53
  }
53
54
  if (!registration || typeof registration !== "object") {
54
55
  throw new Error(`Agent "${key}" must register a folder path.`);
@@ -60,19 +61,51 @@ function normalizeAgentRegistration(key, registration) {
60
61
  (!registration.subagents ||
61
62
  typeof registration.subagents !== "object" ||
62
63
  Array.isArray(registration.subagents))) {
63
- throw new Error(`Agent "${key}" subagents must be an object of folder paths.`);
64
+ throw new Error(`Agent "${key}" subagents must be an object of named registrations.`);
64
65
  }
65
- for (const [subagentKey, registeredPath] of Object.entries(registration.subagents ?? {})) {
66
- if (typeof registeredPath !== "string" || !registeredPath.trim()) {
67
- throw new Error(`Subagent "${key}/${subagentKey}" must register a folder path.`);
66
+ validateMcpRegistration(`Agent "${key}"`, registration.mcp);
67
+ return {
68
+ path: registration.path,
69
+ mcp: registration.mcp ?? {},
70
+ subagents: registration.subagents ?? {},
71
+ };
72
+ }
73
+ function normalizeSubagentRegistration(parentKey, key, registration) {
74
+ if (typeof registration === "string") {
75
+ if (!registration.trim()) {
76
+ throw new Error(`Subagent "${parentKey}/${key}" must register a folder path.`);
68
77
  }
78
+ return { path: registration, mcp: {} };
79
+ }
80
+ if (!registration ||
81
+ typeof registration !== "object" ||
82
+ typeof registration.path !== "string" ||
83
+ !registration.path.trim()) {
84
+ throw new Error(`Subagent "${parentKey}/${key}" must register a folder path.`);
69
85
  }
86
+ validateMcpRegistration(`Subagent "${parentKey}/${key}"`, registration.mcp);
70
87
  return {
71
88
  path: registration.path,
72
- subagents: registration.subagents ?? {},
89
+ mcp: registration.mcp ?? {},
73
90
  };
74
91
  }
75
- function compileAgent(key, registeredPath, registryRoot, actionRuntime, target) {
92
+ function validateMcpRegistration(owner, registration) {
93
+ if (registration !== undefined &&
94
+ (!registration ||
95
+ typeof registration !== "object" ||
96
+ Array.isArray(registration))) {
97
+ throw new Error(`${owner} mcp must be an object of named folder paths.`);
98
+ }
99
+ for (const [key, path] of Object.entries(registration ?? {})) {
100
+ if (!/^[a-zA-Z0-9_-]{1,32}$/.test(key)) {
101
+ throw new Error(`${owner} has invalid MCP name "${key}".`);
102
+ }
103
+ if (typeof path !== "string" || !path.trim()) {
104
+ throw new Error(`${owner} MCP "${key}" must register a folder path.`);
105
+ }
106
+ }
107
+ }
108
+ function compileAgent(key, registeredPath, mcpRegistration, registryRoot, actionRuntime, target) {
76
109
  const name = key;
77
110
  const sourceDirectory = resolve(registryRoot, registeredPath);
78
111
  const configPath = resolve(sourceDirectory, "index.json");
@@ -151,12 +184,100 @@ function compileAgent(key, registeredPath, registryRoot, actionRuntime, target)
151
184
  actions: compileActions(name, sourceDirectory, actionRuntime, target),
152
185
  skills: compileSkills(name, sourceDirectory),
153
186
  evaluations: compileEvaluations(name, sourceDirectory),
187
+ mcpServers: compileMcpServers(name, mcpRegistration, registryRoot, target),
154
188
  subagentPolicy: configuration.subagents
155
189
  ? Object.freeze({ ...configuration.subagents })
156
190
  : undefined,
157
191
  subagents: Object.freeze({}),
158
192
  });
159
193
  }
194
+ function compileMcpServers(agentName, registration, registryRoot, target) {
195
+ const servers = {};
196
+ for (const [key, registeredPath] of Object.entries(registration)) {
197
+ const directory = resolve(registryRoot, registeredPath);
198
+ const configurationPath = resolve(directory, "index.json");
199
+ let configuration;
200
+ try {
201
+ configuration = JSON.parse(readFileSync(configurationPath, "utf8"));
202
+ }
203
+ catch (error) {
204
+ throw new Error(`MCP server "${agentName}/${key}" is missing a valid index.json at ${configurationPath}.`, { cause: error });
205
+ }
206
+ validateMcpServerConfiguration(agentName, key, configuration, target);
207
+ servers[key] = Object.freeze({
208
+ ...configuration,
209
+ key,
210
+ directoryName: registeredPath,
211
+ });
212
+ }
213
+ return Object.freeze(servers);
214
+ }
215
+ function validateMcpServerConfiguration(agentName, key, configuration, target) {
216
+ const label = `MCP server "${agentName}/${key}"`;
217
+ if (!configuration ||
218
+ typeof configuration !== "object" ||
219
+ !["streamable-http", "stdio"].includes(configuration.transport)) {
220
+ throw new Error(`${label} transport must be "streamable-http" or "stdio".`);
221
+ }
222
+ if (configuration.transport === "streamable-http") {
223
+ let url;
224
+ try {
225
+ url = new URL(configuration.url);
226
+ }
227
+ catch {
228
+ throw new Error(`${label} requires a valid URL.`);
229
+ }
230
+ if (!["https:", "http:"].includes(url.protocol)) {
231
+ throw new Error(`${label} URL must use HTTP or HTTPS.`);
232
+ }
233
+ if (url.protocol === "http:" &&
234
+ !["localhost", "127.0.0.1", "::1"].includes(url.hostname)) {
235
+ throw new Error(`${label} must use HTTPS unless it connects to localhost.`);
236
+ }
237
+ if (configuration.headers !== undefined &&
238
+ (!configuration.headers ||
239
+ typeof configuration.headers !== "object" ||
240
+ Array.isArray(configuration.headers) ||
241
+ Object.values(configuration.headers).some((value) => typeof value !== "string"))) {
242
+ throw new Error(`${label} headers must contain string values.`);
243
+ }
244
+ if (configuration.credentials !== undefined &&
245
+ !["omit", "same-origin", "include"].includes(configuration.credentials)) {
246
+ throw new Error(`${label} has invalid credentials.`);
247
+ }
248
+ }
249
+ else {
250
+ if (target !== "node") {
251
+ throw new Error(`${label} uses stdio, which is only available for the node target.`);
252
+ }
253
+ if (typeof configuration.command !== "string" ||
254
+ !configuration.command.trim()) {
255
+ throw new Error(`${label} requires a command.`);
256
+ }
257
+ if (configuration.args !== undefined &&
258
+ (!Array.isArray(configuration.args) ||
259
+ configuration.args.some((value) => typeof value !== "string"))) {
260
+ throw new Error(`${label} args must be an array of strings.`);
261
+ }
262
+ if (configuration.env !== undefined &&
263
+ (!configuration.env ||
264
+ typeof configuration.env !== "object" ||
265
+ Array.isArray(configuration.env) ||
266
+ Object.values(configuration.env).some((value) => typeof value !== "string"))) {
267
+ throw new Error(`${label} env must contain string values.`);
268
+ }
269
+ }
270
+ validateNumber(label, "timeoutMs", configuration.timeoutMs, {
271
+ integer: true,
272
+ minimum: 1,
273
+ maximum: 300_000,
274
+ });
275
+ validateNumber(label, "maxOutputBytes", configuration.maxOutputBytes, {
276
+ integer: true,
277
+ minimum: 1,
278
+ maximum: 10_000_000,
279
+ });
280
+ }
160
281
  function compileActions(agentName, sourceDirectory, actionRuntime, target) {
161
282
  const actionsDirectory = resolve(sourceDirectory, "actions");
162
283
  if (!existsSync(actionsDirectory)) {
package/dist/orcha.js CHANGED
@@ -5,12 +5,18 @@ import { setNativeRuntimeLoader, setSandboxRuntimeLoader, } from "./runtime/acti
5
5
  import { executeNativeAction } from "./runtime/actions/native.js";
6
6
  import { getRegistryCompiler } from "./runtime/compiler-hook.js";
7
7
  import { createOrcha } from "./runtime/create-orcha.js";
8
+ import { setMcpClientFactory } from "./runtime/mcp/client.js";
8
9
  import { nodeRuntimePlatform } from "./runtime/platform-node.js";
9
10
  setNativeRuntimeLoader(async () => ({ executeNativeAction }));
10
11
  setSandboxRuntimeLoader(async () => {
11
12
  const modulePath = "./runtime/actions/sandbox.js";
12
13
  return import(modulePath);
13
14
  });
15
+ setMcpClientFactory(async (server, credentials) => {
16
+ const modulePath = "./runtime/mcp/node-client.js";
17
+ const { createNodeMcpClient } = await import(modulePath);
18
+ return createNodeMcpClient(server, credentials);
19
+ });
14
20
  export const orcha = createOrcha((configuration) => {
15
21
  const projectRoot = resolve(configuration.root ??
16
22
  process.env.ORCHA_PROJECT_ROOT ??
@@ -6,7 +6,7 @@ import { build as bundleEntry } from "esbuild";
6
6
  import { compileRegistry } from "./compiler/compile.js";
7
7
  import { loadProjectEnvironment } from "./env.js";
8
8
  import { orcha } from "./orcha.js";
9
- import { ensureCompiledProviderDependencies } from "./providers/dependencies.js";
9
+ import { ensureCompiledMcpDependencies, ensureCompiledProviderDependencies, } from "./providers/dependencies.js";
10
10
  import { setRegistryCompiler } from "./runtime/compiler-hook.js";
11
11
  export async function loadProject(projectRoot) {
12
12
  setRegistryCompiler((configuration, compilerProjectRoot) => compileRegistry(configuration.agents, resolve(compilerProjectRoot, "orcha"), configuration.actions?.runtime ?? "native", "node"));
@@ -48,6 +48,7 @@ export async function loadProject(projectRoot) {
48
48
  throw new Error('"orcha/index.ts" must call orcha.init({ providers, agents }).');
49
49
  }
50
50
  await ensureCompiledProviderDependencies(orcha.getCompiledBundle(), projectRoot);
51
+ await ensureCompiledMcpDependencies(orcha.getCompiledBundle(), projectRoot);
51
52
  }
52
53
  finally {
53
54
  await rm(bundlePath, { force: true });