orchajs 0.23.11 → 0.23.12

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
@@ -400,32 +400,32 @@ application runtime:
400
400
 
401
401
  ```bash
402
402
  # Offline validation that watches orcha/**
403
- npx orcha dev
403
+ npx orchajs dev
404
404
 
405
405
  # Open the built-in localhost playground and watch orcha/**
406
- npx orcha playground
406
+ npx orchajs playground
407
407
 
408
408
  # Execute a registered agent. Input can also come from a JSON file or stdin.
409
- npx orcha run exampleAgent --input "Help me understand this invoice"
409
+ npx orchajs run exampleAgent --input "Help me understand this invoice"
410
410
 
411
411
  # Continue an existing session or resolve pending client actions.
412
- npx orcha run exampleAgent --session ses_123 --input "Summarize it"
413
- npx orcha run exampleAgent --session ses_123 --tool-results results.json
412
+ npx orchajs run exampleAgent --session ses_123 --input "Summarize it"
413
+ npx orchajs run exampleAgent --session ses_123 --tool-results results.json
414
414
 
415
415
  # Run all tests, one agent, or one case.
416
- npx orcha test
417
- npx orcha test exampleAgent
418
- npx orcha test exampleAgent/exampleCase
416
+ npx orchajs test
417
+ npx orchajs test exampleAgent
418
+ npx orchajs test exampleAgent/exampleCase
419
419
 
420
420
  # Copy all session histories to SQLite or back to JSONL.
421
- npx orcha migrate-storage --to sqlite
422
- npx orcha migrate-storage --to node-jsonl
421
+ npx orchajs migrate-storage --to sqlite
422
+ npx orchajs migrate-storage --to node-jsonl
423
423
 
424
424
  # Export one session from the active store as portable JSONL.
425
- npx orcha export-session exampleAgent ses_123 --output session.jsonl
425
+ npx orchajs export-session exampleAgent ses_123 --output session.jsonl
426
426
 
427
427
  # Offline production compilation.
428
- npx orcha build
428
+ npx orchajs build
429
429
  ```
430
430
 
431
431
  `playground` accepts `--host`, `--port`, and `--no-open`; it binds to
@@ -440,7 +440,7 @@ subagent lifecycle, each child agent's actions, and clickable session logs.
440
440
  installed package. It exposes agent instructions, actions, skills,
441
441
  evaluations, tests, durable sessions, and linked subagent transcripts without
442
442
  adding frontend dependencies to the project or production agent bundle.
443
- `orcha init` also creates a comprehensive `AGENTS.md` describing Orcha's
443
+ `orchajs init` also creates a comprehensive `AGENTS.md` describing Orcha's
444
444
  filesystem contract and APIs. The CLI does not provide a UI; applications can
445
445
  build one from the storage-neutral runtime session APIs.
446
446
 
@@ -814,7 +814,7 @@ Test sessions use the configured session store beside normal sessions. The
814
814
  final `test.completed` event records the suite, case, status, duration, and
815
815
  every assertion. Run tests explicitly before building in CI. Tests use the
816
816
  configured providers, so the test step requires provider credentials and
817
- consumes model tokens; `orcha build` itself remains offline and does not
817
+ consumes model tokens; `orchajs build` itself remains offline and does not
818
818
  require those credentials.
819
819
 
820
820
  ## Evaluations
@@ -889,7 +889,7 @@ build:
889
889
  esbuild: false
890
890
  ```
891
891
 
892
- No separate `orcha build` command or deployment script is required. During
892
+ No separate `orchajs build` command or deployment script is required. During
893
893
  `serverless package` and `serverless deploy`, the integration adds Orcha to the
894
894
  existing esbuild pipeline. It preserves other esbuild plugins, compiles the
895
895
  registry, and replaces exact `orchajs` imports with the generated production
@@ -917,7 +917,7 @@ For an unbundled production application built with plain `tsc` or
917
917
  `serverless-plugin-typescript`, run:
918
918
 
919
919
  ```bash
920
- npx orcha build
920
+ npx orchajs build
921
921
  ```
922
922
 
923
923
  Package `.orcha/dist/manifest.json` with the application. AWS Lambda is
@@ -946,7 +946,7 @@ package:
946
946
  Verify the packaged artifact rather than only the workspace:
947
947
 
948
948
  ```bash
949
- npx orcha build
949
+ npx orchajs build
950
950
  test -f .orcha/dist/manifest.json
951
951
  yarn serverless package
952
952
  unzip -l .serverless/*.zip | grep ".orcha/dist/manifest.json"
@@ -973,7 +973,7 @@ playground, unused providers, and optional runtimes out of deployed handlers.
973
973
 
974
974
  ## What's in this repo right now
975
975
 
976
- - [x] Registry compiler + `orcha build`
976
+ - [x] Registry compiler + `orchajs build`
977
977
  - [x] Model Action Protocol — client actions and opt-in native/sandboxed local actions
978
978
  - [x] Provider-neutral Anthropic, Bedrock, DeepSeek, OpenAI, Google GenAI, and Vertex AI adapters
979
979
  - [x] Stateful sessions — Node JSONL/SQLite replay and client-action pause/resume
@@ -981,7 +981,7 @@ playground, unused providers, and optional runtimes out of deployed handlers.
981
981
  - [x] Agent `/tests` with durable test-prefixed logs and explicit CI gating
982
982
  - [x] Registered LLM-judged `/evaluations`
983
983
  - [ ] Agent `/guardrails`
984
- - [x] Production compiler and `orcha build`
984
+ - [x] Production compiler and `orchajs build`
985
985
  - [x] Lightweight CLI for init, validation, execution, tests, and builds
986
986
 
987
987
  See [`ROADMAP.md`](./ROADMAP.md) for what's coming after — guardrails,
package/dist/bin.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { spawn } from "node:child_process";
3
2
  import { existsSync } from "node:fs";
4
3
  import { readFile } from "node:fs/promises";
5
4
  import { resolve } from "node:path";
5
+ import { detectPackageManager, installCommand, runPackageManager, } from "./package-manager.js";
6
6
  const TOOLING_PACKAGES = [
7
7
  "@orchajs/playground-ui@^0.2.5",
8
8
  "esbuild@^0.25",
@@ -15,7 +15,7 @@ async function run() {
15
15
  try {
16
16
  if (process.argv[2] === "init") {
17
17
  if (process.argv.length > 3) {
18
- throw new Error("Usage: orcha init");
18
+ throw new Error("Usage: orchajs init");
19
19
  }
20
20
  await installProjectDependencies();
21
21
  const { initializeProject } = await import("./initialize-project.js");
@@ -38,14 +38,16 @@ async function bootstrapPlayground() {
38
38
  const packageManager = detectPackageManager();
39
39
  const installation = installCommand(packageManager, TOOLING_PACKAGES, true);
40
40
  console.log(`[orcha] Installing development-only playground tooling with ${packageManager}...`);
41
- const installCode = await runProcess(installation.command, installation.arguments);
41
+ const installCode = await runPackageManager(installation.command, installation.arguments);
42
42
  if (installCode !== 0) {
43
43
  process.exitCode = installCode;
44
44
  return;
45
45
  }
46
- const retryCode = await runProcess(process.execPath, [process.argv[1], ...process.argv.slice(2)], {
47
- ...process.env,
48
- [BOOTSTRAP_ENV]: "1",
46
+ const retryCode = await runPackageManager(process.execPath, [process.argv[1], ...process.argv.slice(2)], {
47
+ env: {
48
+ ...process.env,
49
+ [BOOTSTRAP_ENV]: "1",
50
+ },
49
51
  });
50
52
  process.exitCode = retryCode;
51
53
  }
@@ -61,91 +63,16 @@ async function installProjectDependencies() {
61
63
  }
62
64
  console.log(`[orcha] Installing Orcha and development tooling with ${packageManager}...`);
63
65
  const runtimeInstallation = installCommand(packageManager, [`orchajs@${ownPackage.version}`], false);
64
- const runtimeCode = await runProcess(runtimeInstallation.command, runtimeInstallation.arguments);
66
+ const runtimeCode = await runPackageManager(runtimeInstallation.command, runtimeInstallation.arguments);
65
67
  if (runtimeCode !== 0) {
66
68
  throw new Error("Failed to install orchajs in the current project.");
67
69
  }
68
70
  const toolingInstallation = installCommand(packageManager, TOOLING_PACKAGES, true);
69
- const toolingCode = await runProcess(toolingInstallation.command, toolingInstallation.arguments);
71
+ const toolingCode = await runPackageManager(toolingInstallation.command, toolingInstallation.arguments);
70
72
  if (toolingCode !== 0) {
71
73
  throw new Error("Failed to install Orcha development tooling in the current project.");
72
74
  }
73
75
  }
74
- function detectPackageManager() {
75
- if (existsSync(resolve("yarn.lock"))) {
76
- return "yarn";
77
- }
78
- if (existsSync(resolve("pnpm-lock.yaml"))) {
79
- return "pnpm";
80
- }
81
- if (existsSync(resolve("bun.lock")) ||
82
- existsSync(resolve("bun.lockb"))) {
83
- return "bun";
84
- }
85
- const userAgent = process.env.npm_config_user_agent;
86
- if (userAgent?.startsWith("yarn/")) {
87
- return "yarn";
88
- }
89
- if (userAgent?.startsWith("pnpm/")) {
90
- return "pnpm";
91
- }
92
- if (userAgent?.startsWith("bun/")) {
93
- return "bun";
94
- }
95
- return "npm";
96
- }
97
- function installCommand(packageManager, packages, development) {
98
- switch (packageManager) {
99
- case "yarn":
100
- return {
101
- command: executable("yarn"),
102
- arguments: ["add", ...(development ? ["--dev"] : []), ...packages],
103
- };
104
- case "pnpm":
105
- return {
106
- command: executable("pnpm"),
107
- arguments: [
108
- "add",
109
- ...(development ? ["--save-dev"] : []),
110
- ...packages,
111
- ],
112
- };
113
- case "bun":
114
- return {
115
- command: executable("bun"),
116
- arguments: ["add", ...(development ? ["--dev"] : []), ...packages],
117
- };
118
- default:
119
- return {
120
- command: executable("npm"),
121
- arguments: [
122
- "install",
123
- ...(development ? ["--save-dev"] : []),
124
- ...packages,
125
- ],
126
- };
127
- }
128
- }
129
- function executable(command) {
130
- return process.platform === "win32" ? `${command}.cmd` : command;
131
- }
132
- function runProcess(command, arguments_, env = process.env) {
133
- return new Promise((resolveProcess, reject) => {
134
- const child = spawn(command, arguments_, {
135
- cwd: process.cwd(),
136
- env,
137
- stdio: "inherit",
138
- });
139
- child.once("error", reject);
140
- child.once("exit", (code, signal) => {
141
- if (signal) {
142
- process.kill(process.pid, signal);
143
- return;
144
- }
145
- resolveProcess(code ?? 1);
146
- });
147
- });
148
- }
149
76
  function isMissingToolingError(error) {
150
77
  const message = error instanceof Error ? error.message : String(error);
151
78
  return ["@orchajs/playground-ui", "esbuild", "chokidar", "dotenv"].some((name) => message.includes(`"${name}"`) || message.includes(`'${name}'`));
@@ -153,7 +80,7 @@ function isMissingToolingError(error) {
153
80
  function reportError(error) {
154
81
  const message = error instanceof Error ? error.message : String(error);
155
82
  if (isMissingToolingError(error)) {
156
- console.error(`Orcha development tooling is missing. Run "orcha playground" to install the development-only playground dependencies automatically.`);
83
+ console.error(`Orcha development tooling is missing. Run "orchajs playground" to install the development-only playground dependencies automatically.`);
157
84
  }
158
85
  else {
159
86
  console.error(message);
@@ -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- `orcha init` creates the initial Orcha files without overwriting files.\n- `orcha dev` validates agent source and watches `orcha/**` for changes.\n- `orcha playground` opens the built-in local UI and hot reloads agent source.\n- `orcha run <agent> --input \"\u2026\"` executes one registered agent.\n- `orcha run <agent> --input-file request.json` accepts structured input.\n- `orcha run <agent> --session <id> --input \"\u2026\"` continues a session.\n- `orcha run <agent> --session <id> --tool-results results.json` submits\n pending client-action results.\n- `orcha test` runs every enabled discovered agent test.\n- `orcha test <agent>` or `orcha test <agent>/<case>` narrows the run.\n- `orcha migrate-storage --to sqlite|node-jsonl` copies all session histories\n between local stores without deleting the source.\n- `orcha export-session <agent> <sessionId> [--output <path>]` exports one\n session from the active store as JSONL.\n- `orcha 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`orcha 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 `orcha 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 `orcha 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 `orcha 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`orcha dev` repeats validation when files change. `orcha 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 `orcha dev` after filesystem changes and `orcha 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- `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";
@@ -6,21 +6,21 @@ files under \`.orcha/\`.
6
6
 
7
7
  ## Commands
8
8
 
9
- - \`orcha init\` creates the initial Orcha files without overwriting files.
10
- - \`orcha dev\` validates agent source and watches \`orcha/**\` for changes.
11
- - \`orcha playground\` opens the built-in local UI and hot reloads agent source.
12
- - \`orcha run <agent> --input "…"\` executes one registered agent.
13
- - \`orcha run <agent> --input-file request.json\` accepts structured input.
14
- - \`orcha run <agent> --session <id> --input "…"\` continues a session.
15
- - \`orcha run <agent> --session <id> --tool-results results.json\` submits
9
+ - \`orchajs init\` creates the initial Orcha files without overwriting files.
10
+ - \`orchajs dev\` validates agent source and watches \`orcha/**\` for changes.
11
+ - \`orchajs playground\` opens the built-in local UI and hot reloads agent source.
12
+ - \`orchajs run <agent> --input "…"\` executes one registered agent.
13
+ - \`orchajs run <agent> --input-file request.json\` accepts structured input.
14
+ - \`orchajs run <agent> --session <id> --input "…"\` continues a session.
15
+ - \`orchajs run <agent> --session <id> --tool-results results.json\` submits
16
16
  pending client-action results.
17
- - \`orcha test\` runs every enabled discovered agent test.
18
- - \`orcha test <agent>\` or \`orcha test <agent>/<case>\` narrows the run.
19
- - \`orcha migrate-storage --to sqlite|node-jsonl\` copies all session histories
17
+ - \`orchajs test\` runs every enabled discovered agent test.
18
+ - \`orchajs test <agent>\` or \`orchajs test <agent>/<case>\` narrows the run.
19
+ - \`orchajs migrate-storage --to sqlite|node-jsonl\` copies all session histories
20
20
  between local stores without deleting the source.
21
- - \`orcha export-session <agent> <sessionId> [--output <path>]\` exports one
21
+ - \`orchajs export-session <agent> <sessionId> [--output <path>]\` exports one
22
22
  session from the active store as JSONL.
23
- - \`orcha build\` creates the production Orcha bundle without calling models.
23
+ - \`orchajs build\` creates the production Orcha bundle without calling models.
24
24
  - Add \`--json\` to \`run\` and \`test\` for machine-readable output.
25
25
 
26
26
  \`run\`, \`test\`, and playground executions use real providers and require
@@ -30,7 +30,7 @@ under \`.orcha/sessions/<agentName>/\`; opt-in SQLite stores all agents in
30
30
 
31
31
  ## Production deployment
32
32
 
33
- \`orcha build\` writes \`.orcha/dist/bundle.js\` for bundler integrations and
33
+ \`orchajs build\` writes \`.orcha/dist/bundle.js\` for bundler integrations and
34
34
  \`.orcha/dist/manifest.json\` for unbundled production runtimes. If deployment
35
35
  uses plain \`tsc\`, \`serverless-plugin-typescript\`, or another packager that
36
36
  does not use \`orchajs/esbuild\`, explicitly include \`.orcha/dist/**\` in the
@@ -46,7 +46,7 @@ package:
46
46
  - ".orcha/dist/**"
47
47
  \`\`\`
48
48
 
49
- Do not assume that a successful \`orcha build\` means the generated files were
49
+ Do not assume that a successful \`orchajs build\` means the generated files were
50
50
  copied by a later packaging tool. Inspect the final ZIP or container image and
51
51
  confirm that \`.orcha/dist/manifest.json\` is present.
52
52
 
@@ -569,7 +569,7 @@ Test \`index.json\` fields:
569
569
  - \`expect.actions\` (optional): ordered expected calls. Each may assert
570
570
  \`arguments.equals\` or \`arguments.partial\`.
571
571
 
572
- The test folder name is the selector used by \`orcha test agent/testName\`.
572
+ The test folder name is the selector used by \`orchajs test agent/testName\`.
573
573
 
574
574
  ## Evaluations
575
575
 
@@ -597,7 +597,7 @@ metrics, and thresholds:
597
597
 
598
598
  \`execution.result\` does not wait for judges. Await
599
599
  \`execution.evaluations\` when results must finish before process exit.
600
- Evaluations always finish during \`orcha test\`; judge errors and missed
600
+ Evaluations always finish during \`orchajs test\`; judge errors and missed
601
601
  thresholds fail the test. Lifecycle events are \`evaluation.requested\`,
602
602
  \`evaluation.completed\`, and \`evaluation.failed\`.
603
603
 
@@ -1003,7 +1003,7 @@ number. A conversational \`resume(...content)\` starts a new run number.
1003
1003
  Concrete action arguments and outputs are validated against their schemas
1004
1004
  when the action is used.
1005
1005
 
1006
- \`orcha dev\` repeats validation when files change. \`orcha build\` performs
1006
+ \`orchajs dev\` repeats validation when files change. \`orchajs build\` performs
1007
1007
  offline production compilation. Neither command invokes a provider.
1008
1008
 
1009
1009
  ### Run lifecycle
@@ -1082,7 +1082,7 @@ needed for faithful continuation but are omitted from evaluation transcripts.
1082
1082
  - Mock actions when tests must avoid side effects; document intentional live
1083
1083
  action coverage.
1084
1084
  - Do not commit \`.orcha/\`; it contains generated output and session data.
1085
- - Run \`orcha dev\` after filesystem changes and \`orcha test\` when behavior
1085
+ - Run \`orchajs dev\` after filesystem changes and \`orchajs test\` when behavior
1086
1086
  changes.
1087
1087
  - Do not weaken assertions to match incorrect behavior. Remove an assertion
1088
1088
  only when it is stricter than the documented agent contract.
package/dist/cli.js CHANGED
@@ -43,7 +43,7 @@ switch (command) {
43
43
  case "build": {
44
44
  const parsed = parseArguments(commandArguments, new Set(["--target"]), new Set());
45
45
  if (parsed.positionals.length > 0) {
46
- throw new Error("Usage: orcha build [--target node|browser|react-native]");
46
+ throw new Error("Usage: orchajs build [--target node|browser|react-native]");
47
47
  }
48
48
  const target = parseBuildTarget(parsed.values.get("--target"));
49
49
  loadProjectEnvironment(projectRoot);
@@ -58,12 +58,12 @@ switch (command) {
58
58
  printUsage();
59
59
  break;
60
60
  default:
61
- throw new Error(`Unknown command "${command}". Run "orcha --help".`);
61
+ throw new Error(`Unknown command "${command}". Run "orchajs --help".`);
62
62
  }
63
63
  async function watchProject(projectRoot, targets) {
64
64
  const registryDirectory = resolve(projectRoot, "orcha");
65
65
  if (!existsSync(registryDirectory)) {
66
- throw new Error('Missing "orcha/". Run "orcha init" first.');
66
+ throw new Error('Missing "orcha/". Run "orchajs init" first.');
67
67
  }
68
68
  loadProjectEnvironment(projectRoot);
69
69
  let validating = false;
@@ -117,7 +117,7 @@ async function runAgent(projectRoot, arguments_) {
117
117
  ]));
118
118
  const agentName = parsed.positionals[0];
119
119
  if (!agentName || parsed.positionals.length > 1) {
120
- throw new Error('Usage: orcha run <agent> (--input "…" | --input-file request.json) [--session <id>] [--json]');
120
+ throw new Error('Usage: orchajs run <agent> (--input "…" | --input-file request.json) [--session <id>] [--json]');
121
121
  }
122
122
  await loadProject(projectRoot);
123
123
  const agent = orcha[agentName];
@@ -164,7 +164,7 @@ async function runAgent(projectRoot, arguments_) {
164
164
  async function testAgents(projectRoot, arguments_) {
165
165
  const parsed = parseArguments(arguments_, new Set());
166
166
  if (parsed.positionals.length > 1) {
167
- throw new Error("Usage: orcha test [agent | agent/test] [--json]");
167
+ throw new Error("Usage: orchajs test [agent | agent/test] [--json]");
168
168
  }
169
169
  const selector = parsed.positionals[0];
170
170
  const [agent, test, extra] = selector?.split("/") ?? [];
@@ -207,7 +207,7 @@ async function testAgents(projectRoot, arguments_) {
207
207
  async function runPlayground(projectRoot, arguments_) {
208
208
  const parsed = parseArguments(arguments_, new Set(["--host", "--port"]), new Set(["--no-open"]));
209
209
  if (parsed.positionals.length > 0) {
210
- throw new Error("Usage: orcha playground [--host localhost] [--port 4310] [--no-open]");
210
+ throw new Error("Usage: orchajs playground [--host localhost] [--port 4310] [--no-open]");
211
211
  }
212
212
  const portValue = parsed.values.get("--port");
213
213
  const port = portValue ? Number.parseInt(portValue, 10) : 4310;
@@ -224,7 +224,7 @@ async function runPlayground(projectRoot, arguments_) {
224
224
  async function migrateStorage(projectRoot, arguments_) {
225
225
  const parsed = parseArguments(arguments_, new Set(["--to", "--agent"]), new Set());
226
226
  if (parsed.positionals.length > 0) {
227
- throw new Error("Usage: orcha migrate-storage --to <sqlite | node-jsonl> [--agent <name>]");
227
+ throw new Error("Usage: orchajs migrate-storage --to <sqlite | node-jsonl> [--agent <name>]");
228
228
  }
229
229
  const destinationStrategy = storageStrategy(parsed.values.get("--to"));
230
230
  const sourceStrategy = destinationStrategy === "sqlite" ? "node-jsonl" : "sqlite";
@@ -256,7 +256,7 @@ async function exportSession(projectRoot, arguments_) {
256
256
  const parsed = parseArguments(arguments_, new Set(["--output"]), new Set());
257
257
  const [agentName, sessionId] = parsed.positionals;
258
258
  if (!agentName || !sessionId || parsed.positionals.length !== 2) {
259
- throw new Error("Usage: orcha export-session <agent> <sessionId> [--output <path>]");
259
+ throw new Error("Usage: orchajs export-session <agent> <sessionId> [--output <path>]");
260
260
  }
261
261
  await loadProject(projectRoot);
262
262
  const context = getOrchaRuntimeContext(orcha);
@@ -298,7 +298,7 @@ function allAgentManifests(agents) {
298
298
  function parseDevTargets(arguments_) {
299
299
  const parsed = parseArguments(arguments_, new Set(["--target"]), new Set());
300
300
  if (parsed.positionals.length > 0) {
301
- throw new Error("Usage: orcha dev [--target node|browser|react-native|all]");
301
+ throw new Error("Usage: orchajs dev [--target node|browser|react-native|all]");
302
302
  }
303
303
  const target = parsed.values.get("--target") ?? "node";
304
304
  if (target === "all") {
@@ -555,12 +555,12 @@ async function sessionLogPath(projectRoot, agentName, sessionId) {
555
555
  }
556
556
  function assertNoArguments(arguments_, command) {
557
557
  if (arguments_.length > 0) {
558
- throw new Error(`Usage: orcha ${command}`);
558
+ throw new Error(`Usage: orchajs ${command}`);
559
559
  }
560
560
  }
561
561
  function printUsage() {
562
562
  console.log([
563
- "Usage: orcha <command>",
563
+ "Usage: orchajs <command>",
564
564
  "",
565
565
  "Commands:",
566
566
  " init Add Orcha to the current project",