open-agents-ai 0.187.190 → 0.187.192

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +156 -7
  2. package/dist/index.js +427 -10
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -642,9 +642,85 @@ curl -X DELETE -H "Authorization: Bearer $ADMIN_KEY" \
642
642
  http://localhost:11435/v1/profiles/frontend-dev
643
643
  ```
644
644
 
645
+ #### Parallelism & Concurrency
646
+
647
+ The daemon is built for **unbounded concurrent requests** with per-key enforcement. Every agentic task (`/v1/run`, `/v1/chat`, `/api/chat`, `/api/generate`) spawns its own subprocess, so multiple jobs run in true parallel — same model or different models, same or different profiles, same or different sandbox modes.
648
+
649
+ **Per-key concurrency limits** are enforced from the `OA_API_KEYS` env var:
650
+
651
+ ```bash
652
+ # key:scope:user:rpm:tpd:maxJobs
653
+ OA_API_KEYS="ci-key:run:github-actions:60:100000:5, \
654
+ ops-key:admin:ops:120:500000:20, \
655
+ read-key:read:grafana:600::"
656
+ oa serve
657
+ ```
658
+
659
+ The 6th field is `maxJobs` — the maximum number of **concurrent** (in-flight) agentic tasks for that key. When exceeded, the daemon returns **RFC 7807 `429 Too Many Requests`**:
660
+
661
+ ```json
662
+ {
663
+ "type": "https://openagents.nexus/problems/rate-limited",
664
+ "title": "Concurrent job limit exceeded",
665
+ "status": 429,
666
+ "detail": "Concurrent job limit exceeded for github-actions: 5/5",
667
+ "instance": "a1b2c3d4-..."
668
+ }
669
+ ```
670
+
671
+ > **Previously this was dead code.** `maxJobs` was parsed but never checked — a CI key with `maxJobs:5` could spawn 50 concurrent subprocesses and OOM the host. Fixed in v0.187.189.
672
+
673
+ **64-bit job IDs** — `job-${randomBytes(8).toString("hex")}`. At 1M jobs the birthday-paradox collision risk drops from ~0.1% (old 24-bit IDs) to ~10⁻¹⁰. Bumped in v0.187.189.
674
+
675
+ **Atomic job record writes** — all 4 job state transitions (initial spawn, stream-exit, non-stream-exit, cancel) use `atomicJobWrite()` which writes to `.tmp` then `rename()`s. No race conditions between concurrent `DELETE /v1/runs/:id` and child-exit handlers. Fixed in v0.187.189.
676
+
677
+ **Running concurrent jobs**:
678
+
679
+ ```bash
680
+ # Fire 5 different jobs with 5 different models in parallel
681
+ for model in qwen3.5:4b qwen3.5:9b qwen3.5:32b qwen3.5:72b qwen3.5:122b; do
682
+ curl -s -X POST http://localhost:11435/v1/run \
683
+ -H "Authorization: Bearer $KEY" \
684
+ -H "Content-Type: application/json" \
685
+ -d "{\"task\":\"Describe $model in one sentence\",\"model\":\"$model\",\"stream\":false}" &
686
+ done
687
+ wait
688
+ ```
689
+
690
+ Each subprocess inherits a **clean env** — `OA_DAEMON` and `OA_PORT` are explicitly stripped so the child doesn't re-enter daemon mode. Fixed in v0.187.189 (root cause of the earlier "Task incomplete (0 turns, 0 tool calls)" bug).
691
+
692
+ **Observing parallelism live** — subscribe to the event bus to watch every job lifecycle event:
693
+
694
+ ```bash
695
+ curl -N 'http://localhost:11435/v1/events?type=run.*'
696
+ ```
697
+
698
+ Every spawn, completion, failure, and abort publishes to the bus:
699
+
700
+ ```
701
+ event: run.started
702
+ data: {"type":"run.started","ts":"2026-04-07T21:00:14Z","data":{"run_id":"job-3a7c9f1e2b8d0a45","model":"qwen3.5:9b","pid":12345},"subject":"ci-key","aims:control":"A.6.2.6"}
703
+
704
+ event: run.completed
705
+ data: {"type":"run.completed","ts":"2026-04-07T21:00:39Z","data":{"run_id":"job-3a7c9f1e2b8d0a45","exit_code":0,"summary":"..."},"subject":"ci-key","aims:control":"A.6.2.6"}
706
+ ```
707
+
708
+ **Abort a running job** — SIGTERM the process group, then SIGKILL after 3s:
709
+
710
+ ```bash
711
+ curl -X DELETE http://localhost:11435/v1/runs/job-3a7c9f1e2b8d0a45 \
712
+ -H "Authorization: Bearer $KEY"
713
+ ```
714
+
715
+ Also cleans up the Docker container if the job was spawned with `"sandbox":"container"`. Decrements the per-key `activeJobs` counter so the quota is immediately released. Publishes `run.aborted` on the event bus.
716
+
717
+ **Safety timeout on `/v1/chat` + `/api/chat` + `/api/generate`** — the non-streaming paths bound the subprocess wait at `timeout_s + 30s` (default `180s + 30s = 210s`). If the child doesn't close in time, the daemon SIGTERMs then SIGKILLs it and returns an OpenAI-shaped `finish_reason:"error"` response with the real reason. Fixed in v0.187.191.
718
+
719
+ **Tested end-to-end** — 10 concurrent `/v1/skills` GETs, 3 concurrent `/v1/aims/incidents` POSTs (each gets a unique ID, no write races), 2 concurrent `/v1/events` SSE subscribers (both receive the same events). All covered by `packages/cli/tests/api-endpoint-matrix.test.ts`. 201/201 tests green.
720
+
645
721
  #### Endpoint Reference
646
722
 
647
- > **Verified against `open-agents-ai@0.187.189`.** Examples in earlier README revisions are deprecated.
723
+ > **Verified against `open-agents-ai@0.187.191`.** Examples in earlier README revisions are deprecated.
648
724
 
649
725
  **Health & observability**
650
726
  | Method | Path | Auth | Description |
@@ -666,11 +742,15 @@ curl -X DELETE -H "Authorization: Bearer $ADMIN_KEY" \
666
742
  | GET | `/v1/models` | read | List models (aggregated across endpoints) |
667
743
  | POST | `/v1/chat/completions` | read | Chat inference (sync + stream, OpenAI-shaped) |
668
744
  | POST | `/v1/embeddings` | read | Generate embeddings |
745
+ | POST | `/api/embed` | read | **Ollama-compatible alias** of `/v1/embeddings`. Accepts `{model, input}` or `{model, prompt}`. |
669
746
 
670
- **Chat with full agent (drop-in for /v1/chat/completions)**
747
+ **Chat with full agent (drop-in for Ollama /api/chat and OpenAI /v1/chat/completions)**
671
748
  | Method | Path | Auth | Description |
672
749
  |--------|------|------|-------------|
673
- | POST | `/v1/chat` | run | Full agent under the hood, OpenAI chat.completion shape. Default = tools=true (subprocess agent). Set `tools:false` for direct backend bypass. |
750
+ | POST | `/v1/chat` | run | Full agent under the hood, OpenAI chat.completion shape. Default = tools=true (subprocess agent). Set `tools:false` for direct backend bypass. Supports `timeout_s` body field (default 180s). Non-streaming path has a safety SIGTERM→SIGKILL after `timeout_s + 30s`. |
751
+ | POST | `/api/chat` | run | **Ollama-compatible alias** — same handler as `/v1/chat`. Accepts both OA-shape (`{message, model}`) and Ollama-shape (`{model, messages: [...]}`) bodies. Returns OpenAI `chat.completion` shape on success and failure (failure uses `finish_reason:"error"`). |
752
+ | POST | `/v1/generate` | run | **One-off completion** — same agent stack as `/v1/chat` but no session history. Returns Ollama-shape `{model, response, done, total_duration}`. |
753
+ | POST | `/api/generate` | run | **Ollama-compatible alias** of `/v1/generate`. Drop-in for Ollama `/api/generate`. |
674
754
  | GET | `/v1/chat/sessions` | read | List active chat sessions |
675
755
 
676
756
  **Agentic task execution**
@@ -796,14 +876,43 @@ curl -X DELETE -H "Authorization: Bearer $ADMIN_KEY" \
796
876
  | POST | `/v1/aiwg/use` | run | `aiwg use all` equivalent — model-tier-sized activation bundle |
797
877
  | POST | `/v1/aiwg/expand` | run | Sub-agent unpack a specific skill/agent on demand |
798
878
 
799
- #### Stateful Chat — `/v1/chat` (OpenAI drop-in with full agent under the hood)
879
+ #### Stateful Chat — `/v1/chat` + `/api/chat` (OpenAI drop-in with full agent under the hood)
880
+
881
+ The chat endpoint is mounted at **two paths on port 11435**:
882
+
883
+ | Path | Purpose |
884
+ |------|---------|
885
+ | `POST /v1/chat` | OA-native path |
886
+ | `POST /api/chat` | **Ollama-compatible alias** — same handler, so clients pointing at Ollama can be flipped over by changing only the port (`11434` → `11435`) |
887
+
888
+ It's a **drop-in replacement for OpenAI `/v1/chat/completions` and Ollama `/api/chat`**. The endpoint runs the full OA agent (tools, multi-agent, memory, skills) under the hood and returns an **OpenAI `chat.completion`-shaped response** so any client SDK can use it without modification.
800
889
 
801
- `/v1/chat` is a **drop-in replacement for OpenAI `/v1/chat/completions` and Ollama `/api/chat`**. The endpoint runs the full OA agent (tools, multi-agent, memory, skills) under the hood and returns an **OpenAI `chat.completion`-shaped response** so any client SDK can use it without modification.
890
+ **Both body shapes are accepted** on either path:
802
891
 
803
- > **Two modes:**
804
- > - **Default (`tools` unset or `tools: true`)** — full agent: spawns the OA subprocess with the entire 82-tool set, runs the agent loop, returns the final answer.
892
+ ```jsonc
893
+ // OA-native
894
+ {"message": "hello", "model": "qwen3.5:9b", "stream": false}
895
+
896
+ // Ollama-native (the `messages` array; the last user message is extracted)
897
+ {"model": "qwen3.5:9b", "messages": [{"role":"user","content":"hello"}], "stream": false}
898
+ ```
899
+
900
+ > **Two execution modes:**
901
+ > - **Default (`tools` unset or `tools: true`)** — full agent: spawns the OA subprocess with the entire 82-tool set, runs the agent loop, returns the final answer with `tool_calls` metadata.
805
902
  > - **Direct (`tools: false`)** — fast path: bypasses the agent and forwards straight to the configured backend (Ollama/vLLM) using the session history. Useful for plain chat without tools.
806
903
 
904
+ **Safety timeout** — every non-streaming request is bounded by `timeout_s` (default **180s**). If the agent subprocess doesn't close in `timeout_s + 30s`, the daemon SIGTERMs (then SIGKILLs) it and returns an OpenAI-shaped error with `finish_reason:"error"` and a clear explanation. No more hung requests.
905
+
906
+ **Flip Ollama → OA by port alone** — this is verified to work via `scripts/oa-vs-ollama-chat-compare.sh` (see [Live Comparison](#live-comparison-ollama-vs-oa-full-agent) below):
907
+
908
+ ```bash
909
+ # Before (Ollama)
910
+ curl -s http://127.0.0.1:11434/api/chat -d '{"model":"qwen3.5:9b","messages":[{"role":"user","content":"hi"}],"stream":false}'
911
+
912
+ # After (OA with full agent) — only port changed
913
+ curl -s http://127.0.0.1:11435/api/chat -d '{"model":"qwen3.5:9b","messages":[{"role":"user","content":"hi"}],"stream":false}'
914
+ ```
915
+
807
916
  ```bash
808
917
  # DEFAULT: full agent — multi-step tool use, memory, the works.
809
918
  # Returns OpenAI chat.completion shape with the assistant's final answer.
@@ -904,6 +1013,46 @@ curl -s http://localhost:11435/v1/chat \
904
1013
 
905
1014
  Sessions expire after 30 minutes of inactivity. List active sessions: `GET /v1/chat/sessions`.
906
1015
 
1016
+ #### Live Comparison: Ollama vs OA Full Agent
1017
+
1018
+ The repo ships a reproducible side-by-side harness at [`scripts/oa-vs-ollama-chat-compare.sh`](scripts/oa-vs-ollama-chat-compare.sh). It runs **5 tool-call-required prompts** × **4 phases** (Ollama non-stream, OA non-stream, Ollama stream, OA stream) = **20 runs per invocation** with the same model and the same `/api/chat` path on both ports.
1019
+
1020
+ ```bash
1021
+ MODEL=qwen3.5:9b bash scripts/oa-vs-ollama-chat-compare.sh
1022
+ ```
1023
+
1024
+ **Results from `open-agents-ai@0.187.191` with `qwen3.5:9b`** (all 20 runs completed, zero timeouts):
1025
+
1026
+ | # | Prompt | Ollama (bare) | Open Agents (full agent) | Winner |
1027
+ |---|---|---|---|---|
1028
+ | 1 | "Latest stable Node.js version + source URL" | ❌ **v22.10.0** — hallucinated from Aug-2024 training cutoff | ✅ **v25.9.0** fetched from `nodejs.org/download/current`, **3 tool calls** (`web_search` → `web_fetch` → `task_complete`) | **OA** |
1029
+ | 2 | "Biggest tech news this week + source URL" | ❌ "I don't have real-time access" + generic AI trend guess | ✅ **Anthropic Mythos, Intel Terafab, Apple foldable, Russian router breach, Firmus $5.5B** — sourced from TechCrunch, **4 tool calls** | **OA** |
1030
+ | 3 | "Current OS, CPU cores, free memory — use shell tools" | ❌ Confabulated **"Linux / 8 cores / 6.1 GB"** (all wrong) | ✅ **Ubuntu 24.04.2 / 48 cores / 120 GB** (all correct), **6–7 shell tool calls** | **OA** |
1031
+ | 4 | "List files in cwd, count top level, most recent" | ❌ "I cannot access your filesystem" | ✅ **20 files, 50+ dirs, `.claude.json` (81 KB, 09:09 UTC)** via `list_directory`, **2 tool calls** | **OA** |
1032
+ | 5 | "2022 FIFA World Cup final winner + score" (both endpoints have this in training data) | ✅ Argentina 4–2 France | ✅ Argentina 3–3 France, **4–2 on penalties at Lusail Stadium, Dec 18 2022** — grounded with 4 tool calls | **Tie (OA more detailed)** |
1033
+
1034
+ **Latency profile** (wall clock, 5-prompt median):
1035
+
1036
+ | Phase | Ollama | OA agent | OA overhead |
1037
+ |---|---|---|---|
1038
+ | Non-streaming | 12–18s | 24–42s | 12–26s (agent loop + tool calls) |
1039
+ | Streaming SSE | 11–16s | 24–56s | 10–40s |
1040
+
1041
+ **Streaming parser validation** — every OA stream delivered:
1042
+ - Live intermediate `tool_call` events mid-stream (e.g. `['web_search', 'web_fetch', 'task_complete']`)
1043
+ - OpenAI `chat.completion.chunk` deltas with `id`, `model`, `finish_reason`
1044
+ - Clean `data: [DONE]` termination with `finish_reason:"stop"`
1045
+
1046
+ The harness is **reproducible** — rerun it after any `/v1/chat` change to catch regressions:
1047
+
1048
+ ```bash
1049
+ MODEL=qwen3.5:4b bash scripts/oa-vs-ollama-chat-compare.sh # faster tier for quick smoke
1050
+ MODEL=qwen3.5:9b OA_TIMEOUT=300 bash scripts/oa-vs-ollama-chat-compare.sh # default
1051
+ MODEL=qwen3.5:32b OA_TIMEOUT=600 bash scripts/oa-vs-ollama-chat-compare.sh # higher tier
1052
+ ```
1053
+
1054
+ **Bottom line**: for any question that needs fresh data, system access, or filesystem visibility — bare Ollama is wrong or refuses; OA with the full agent is correct with citations. That's the differentiator captured live in the harness output.
1055
+
907
1056
  #### AIWG Cascade — `/v1/aiwg/*`
908
1057
 
909
1058
  Exposes the entire AIWG ecosystem (5 frameworks, 19 addons, 136+ skills, ~42 MB / ~2M tokens of markdown) through a **4-tier cascade loader** that auto-sizes responses to the detected model tier and **never overflows small-model context**.
package/dist/index.js CHANGED
@@ -318364,7 +318364,7 @@ async function handleV1ChatCompletions(req2, res, ollamaUrl) {
318364
318364
  }
318365
318365
  }
318366
318366
  }
318367
- async function handleV1Embeddings(req2, res, ollamaUrl) {
318367
+ async function handleV1Embeddings(req2, res, ollamaUrl, opts = {}) {
318368
318368
  const body = await parseJsonBody(req2);
318369
318369
  if (!body || typeof body !== "object") {
318370
318370
  jsonResponse(res, 400, { error: "Invalid request body" });
@@ -318373,24 +318373,32 @@ async function handleV1Embeddings(req2, res, ollamaUrl) {
318373
318373
  const requestBody = body;
318374
318374
  const config = loadConfig();
318375
318375
  const isVllm = config.backendType === "vllm";
318376
+ const rawInput = requestBody["input"] ?? requestBody["prompt"];
318377
+ const model = requestBody["model"];
318376
318378
  if (isVllm) {
318377
318379
  try {
318378
- const payload = JSON.stringify(requestBody);
318380
+ const payload = JSON.stringify({ model, input: rawInput });
318379
318381
  const result = await ollamaRequest(ollamaUrl, "/v1/embeddings", "POST", payload);
318380
318382
  if (result.status !== 200) {
318381
318383
  jsonResponse(res, result.status, { error: "Backend embeddings request failed", details: result.body });
318382
318384
  return;
318383
318385
  }
318384
- jsonResponse(res, 200, JSON.parse(result.body));
318386
+ const parsed = JSON.parse(result.body);
318387
+ if (opts.ollamaShape) {
318388
+ const embeddings = Array.isArray(parsed.data) ? parsed.data.map((d2) => d2.embedding).filter(Boolean) : [];
318389
+ jsonResponse(res, 200, {
318390
+ model: parsed.model ?? model,
318391
+ embeddings
318392
+ });
318393
+ } else {
318394
+ jsonResponse(res, 200, parsed);
318395
+ }
318385
318396
  } catch (err) {
318386
318397
  jsonResponse(res, 502, { error: "Failed to proxy to backend", message: err instanceof Error ? err.message : String(err) });
318387
318398
  }
318388
318399
  return;
318389
318400
  }
318390
- const ollamaPayload = JSON.stringify({
318391
- model: requestBody["model"],
318392
- input: requestBody["input"]
318393
- });
318401
+ const ollamaPayload = JSON.stringify({ model, input: rawInput });
318394
318402
  try {
318395
318403
  const result = await ollamaRequest(ollamaUrl, "/api/embed", "POST", ollamaPayload);
318396
318404
  if (result.status !== 200) {
@@ -318401,6 +318409,16 @@ async function handleV1Embeddings(req2, res, ollamaUrl) {
318401
318409
  return;
318402
318410
  }
318403
318411
  const ollamaResp = JSON.parse(result.body);
318412
+ if (opts.ollamaShape) {
318413
+ jsonResponse(res, 200, {
318414
+ model: ollamaResp.model ?? model,
318415
+ embeddings: ollamaResp.embeddings ?? [],
318416
+ total_duration: ollamaResp.total_duration,
318417
+ load_duration: ollamaResp.load_duration,
318418
+ prompt_eval_count: ollamaResp.prompt_eval_count
318419
+ });
318420
+ return;
318421
+ }
318404
318422
  const data = (ollamaResp.embeddings ?? []).map((embedding, index) => ({
318405
318423
  object: "embedding",
318406
318424
  embedding,
@@ -318409,7 +318427,7 @@ async function handleV1Embeddings(req2, res, ollamaUrl) {
318409
318427
  jsonResponse(res, 200, {
318410
318428
  object: "list",
318411
318429
  data,
318412
- model: ollamaResp.model ?? requestBody["model"],
318430
+ model: ollamaResp.model ?? model,
318413
318431
  usage: { prompt_tokens: 0, total_tokens: 0 }
318414
318432
  });
318415
318433
  } catch (err) {
@@ -318419,6 +318437,358 @@ async function handleV1Embeddings(req2, res, ollamaUrl) {
318419
318437
  });
318420
318438
  }
318421
318439
  }
318440
+ async function handleV1Generate(req2, res, ollamaUrl, requestId) {
318441
+ const body = await parseJsonBody(req2);
318442
+ if (!body || typeof body !== "object") {
318443
+ jsonResponse(res, 400, { error: "Invalid request body" });
318444
+ return;
318445
+ }
318446
+ const b = body;
318447
+ const task = typeof b.task === "string" && b.task || typeof b.prompt === "string" && b.prompt || "";
318448
+ if (!task) {
318449
+ jsonResponse(res, 400, { error: "Missing required field: task or prompt" });
318450
+ return;
318451
+ }
318452
+ if (task.length > 5e4) {
318453
+ jsonResponse(res, 400, { error: "Task too long", message: "Max 50,000 characters" });
318454
+ return;
318455
+ }
318456
+ const model = b.model || loadConfig().model;
318457
+ const streamMode = b.stream !== false;
318458
+ const useTools = b.tools !== false && b.use_tools !== false;
318459
+ const generateTimeoutS = typeof b.timeout_s === "number" ? b.timeout_s : 180;
318460
+ const systemPrompt = typeof b.system === "string" ? b.system : void 0;
318461
+ const createdAt = (/* @__PURE__ */ new Date()).toISOString();
318462
+ if (!useTools) {
318463
+ try {
318464
+ const cfg = loadConfig();
318465
+ const isVllm = cfg.backendType === "vllm";
318466
+ if (isVllm) {
318467
+ const payload2 = JSON.stringify({
318468
+ model: model.replace(/^[a-z]+\//, ""),
318469
+ prompt: systemPrompt ? `${systemPrompt}
318470
+
318471
+ ${task}` : task,
318472
+ stream: streamMode,
318473
+ max_tokens: b.options?.num_predict ?? 1024
318474
+ });
318475
+ if (streamMode) {
318476
+ res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });
318477
+ await new Promise((resolve39) => {
318478
+ ollamaStream(
318479
+ ollamaUrl,
318480
+ "/v1/completions",
318481
+ "POST",
318482
+ payload2,
318483
+ (chunk) => res.write(chunk),
318484
+ () => {
318485
+ res.end();
318486
+ resolve39();
318487
+ },
318488
+ (err) => {
318489
+ res.end(JSON.stringify({ error: String(err) }));
318490
+ resolve39();
318491
+ }
318492
+ );
318493
+ });
318494
+ return;
318495
+ }
318496
+ const result2 = await ollamaRequest(ollamaUrl, "/v1/completions", "POST", payload2);
318497
+ if (result2.status >= 400) {
318498
+ jsonResponse(res, 502, { error: "Backend error", details: result2.body.slice(0, 500) });
318499
+ return;
318500
+ }
318501
+ const j = JSON.parse(result2.body);
318502
+ const responseText = j?.choices?.[0]?.text ?? "";
318503
+ jsonResponse(res, 200, {
318504
+ model: model.replace(/^[a-z]+\//, ""),
318505
+ created_at: createdAt,
318506
+ response: responseText,
318507
+ done: true,
318508
+ done_reason: "stop"
318509
+ });
318510
+ return;
318511
+ }
318512
+ const payload = JSON.stringify({
318513
+ model: model.replace(/^[a-z]+\//, ""),
318514
+ prompt: task,
318515
+ system: systemPrompt,
318516
+ stream: streamMode,
318517
+ options: b.options ?? {}
318518
+ });
318519
+ if (streamMode) {
318520
+ res.writeHead(200, {
318521
+ "Content-Type": "application/x-ndjson",
318522
+ "Cache-Control": "no-cache",
318523
+ "Connection": "keep-alive",
318524
+ "X-API-Version": API_VERSION
318525
+ });
318526
+ await new Promise((resolve39) => {
318527
+ ollamaStream(
318528
+ ollamaUrl,
318529
+ "/api/generate",
318530
+ "POST",
318531
+ payload,
318532
+ (chunk) => res.write(chunk),
318533
+ () => {
318534
+ res.end();
318535
+ resolve39();
318536
+ },
318537
+ (err) => {
318538
+ res.end(JSON.stringify({ error: String(err) }) + "\n");
318539
+ resolve39();
318540
+ }
318541
+ );
318542
+ });
318543
+ return;
318544
+ }
318545
+ const result = await ollamaRequest(ollamaUrl, "/api/generate", "POST", payload);
318546
+ if (result.status >= 400) {
318547
+ jsonResponse(res, 502, { error: "Backend error", details: result.body.slice(0, 500) });
318548
+ return;
318549
+ }
318550
+ const parsed2 = JSON.parse(result.body);
318551
+ jsonResponse(res, 200, parsed2);
318552
+ } catch (err) {
318553
+ if (!res.headersSent) {
318554
+ res.setHeader("Content-Type", "application/problem+json; charset=utf-8");
318555
+ res.writeHead(502);
318556
+ res.end(JSON.stringify({
318557
+ type: "https://openagents.nexus/problems/upstream-failure",
318558
+ title: "Backend generate failed",
318559
+ status: 502,
318560
+ detail: err instanceof Error ? err.message : String(err),
318561
+ instance: requestId
318562
+ }));
318563
+ }
318564
+ }
318565
+ return;
318566
+ }
318567
+ const oaBin = process.argv[1] || "oa";
318568
+ const fullTask = systemPrompt ? `${systemPrompt}
318569
+
318570
+ ${task}` : task;
318571
+ const args = [fullTask, "--json"];
318572
+ if (model) args.push("--model", model.replace(/^[a-z]+\//, ""));
318573
+ if (generateTimeoutS > 0) args.push("--timeout-ms", String(generateTimeoutS * 1e3));
318574
+ const currentCfg = loadConfig();
318575
+ const runEnv = {};
318576
+ for (const [k, v] of Object.entries(process.env)) {
318577
+ if (k === "OA_DAEMON" || k === "OA_PORT") continue;
318578
+ if (typeof v === "string") runEnv[k] = v;
318579
+ }
318580
+ runEnv["__OPEN_AGENTS_NO_AUTO_RUN"] = "";
318581
+ runEnv["OA_RUN_USER"] = req2._authUser || "anonymous";
318582
+ runEnv["OA_RUN_SCOPE"] = req2._authScope || "admin";
318583
+ runEnv["OLLAMA_HOST"] = currentCfg.backendUrl || process.env["OLLAMA_HOST"] || "http://127.0.0.1:11434";
318584
+ if (currentCfg.apiKey) runEnv["OA_API_KEY_INHERIT"] = currentCfg.apiKey;
318585
+ const child = spawn25(process.execPath, [oaBin, ...args], {
318586
+ cwd: resolve34(process.cwd()),
318587
+ env: runEnv,
318588
+ stdio: ["ignore", "pipe", "pipe"]
318589
+ });
318590
+ const startMs = Date.now();
318591
+ if (streamMode) {
318592
+ res.writeHead(200, {
318593
+ "Content-Type": "application/x-ndjson",
318594
+ "Cache-Control": "no-cache",
318595
+ "Connection": "keep-alive",
318596
+ "X-API-Version": API_VERSION
318597
+ });
318598
+ let buf = "";
318599
+ const finalLines = [];
318600
+ let toolCallsStreamed = 0;
318601
+ child.stdout?.on("data", (chunk) => {
318602
+ buf += chunk.toString();
318603
+ const lines = buf.split("\n");
318604
+ buf = lines.pop() || "";
318605
+ for (const line of lines) {
318606
+ if (!line.trim()) continue;
318607
+ try {
318608
+ const evt = JSON.parse(line);
318609
+ if (evt.type === "tool_call") {
318610
+ toolCallsStreamed++;
318611
+ res.write(JSON.stringify({
318612
+ model: model.replace(/^[a-z]+\//, ""),
318613
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
318614
+ response: "",
318615
+ done: false,
318616
+ _oa: { type: "tool_call", tool: evt.tool, args: evt.args }
318617
+ }) + "\n");
318618
+ } else {
318619
+ finalLines.push(line);
318620
+ }
318621
+ } catch {
318622
+ finalLines.push(line);
318623
+ }
318624
+ }
318625
+ });
318626
+ child.stderr?.on("data", () => {
318627
+ });
318628
+ await new Promise((resolve210) => {
318629
+ let done = false;
318630
+ const finish = () => {
318631
+ if (!done) {
318632
+ done = true;
318633
+ resolve210();
318634
+ }
318635
+ };
318636
+ child.on("close", finish);
318637
+ const deadline = setTimeout(() => {
318638
+ if (done) return;
318639
+ try {
318640
+ if (child.pid) process.kill(-child.pid, "SIGTERM");
318641
+ } catch {
318642
+ }
318643
+ try {
318644
+ if (child.pid) process.kill(child.pid, "SIGTERM");
318645
+ } catch {
318646
+ }
318647
+ setTimeout(() => {
318648
+ try {
318649
+ if (child.pid) process.kill(-child.pid, "SIGKILL");
318650
+ } catch {
318651
+ }
318652
+ try {
318653
+ if (child.pid) process.kill(child.pid, "SIGKILL");
318654
+ } catch {
318655
+ }
318656
+ finish();
318657
+ }, 3e3).unref();
318658
+ }, (generateTimeoutS + 30) * 1e3);
318659
+ deadline.unref();
318660
+ });
318661
+ if (buf.trim()) finalLines.push(buf);
318662
+ const rawFinal = finalLines.join("\n").trim();
318663
+ let content2 = "";
318664
+ let backendError2;
318665
+ let parsed2 = null;
318666
+ try {
318667
+ parsed2 = JSON.parse(rawFinal);
318668
+ if (parsed2.error) backendError2 = String(parsed2.error);
318669
+ if (parsed2.assistant_text) content2 = sanitizeChatContent(parsed2.assistant_text);
318670
+ if (!content2) {
318671
+ const summary = parsed2.summary || "";
318672
+ const m2 = summary.match(/Tokens:\s*[\d,]+\s+([\s\S]*)/);
318673
+ content2 = sanitizeChatContent(m2 ? m2[1] : summary);
318674
+ }
318675
+ } catch {
318676
+ }
318677
+ if (!content2) {
318678
+ content2 = backendError2 ? `Backend error: ${backendError2}` : "Agent produced no response.";
318679
+ }
318680
+ res.write(JSON.stringify({
318681
+ model: model.replace(/^[a-z]+\//, ""),
318682
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
318683
+ response: content2,
318684
+ done: true,
318685
+ done_reason: content2.startsWith("Backend error") || content2.startsWith("Agent produced") ? "error" : "stop",
318686
+ total_duration: (Date.now() - startMs) * 1e6,
318687
+ // ns
318688
+ eval_count: Math.round(content2.length / 4),
318689
+ _oa: { tool_calls: toolCallsStreamed, request_id: requestId }
318690
+ }) + "\n");
318691
+ res.end();
318692
+ return;
318693
+ }
318694
+ const nonStreamLines = [];
318695
+ let nonStreamBuf = "";
318696
+ child.stdout?.on("data", (chunk) => {
318697
+ nonStreamBuf += chunk.toString();
318698
+ const parts = nonStreamBuf.split("\n");
318699
+ nonStreamBuf = parts.pop() || "";
318700
+ for (const p2 of parts) {
318701
+ if (!p2.trim()) continue;
318702
+ try {
318703
+ const evt = JSON.parse(p2);
318704
+ if (evt.type === "tool_call") continue;
318705
+ nonStreamLines.push(p2);
318706
+ } catch {
318707
+ nonStreamLines.push(p2);
318708
+ }
318709
+ }
318710
+ });
318711
+ child.stderr?.on("data", () => {
318712
+ });
318713
+ let killedByDeadline = false;
318714
+ await new Promise((resolve210) => {
318715
+ let done = false;
318716
+ const finish = () => {
318717
+ if (!done) {
318718
+ done = true;
318719
+ resolve210();
318720
+ }
318721
+ };
318722
+ child.on("close", finish);
318723
+ const deadline = setTimeout(() => {
318724
+ if (done) return;
318725
+ killedByDeadline = true;
318726
+ try {
318727
+ if (child.pid) process.kill(-child.pid, "SIGTERM");
318728
+ } catch {
318729
+ }
318730
+ try {
318731
+ if (child.pid) process.kill(child.pid, "SIGTERM");
318732
+ } catch {
318733
+ }
318734
+ setTimeout(() => {
318735
+ try {
318736
+ if (child.pid) process.kill(-child.pid, "SIGKILL");
318737
+ } catch {
318738
+ }
318739
+ try {
318740
+ if (child.pid) process.kill(child.pid, "SIGKILL");
318741
+ } catch {
318742
+ }
318743
+ finish();
318744
+ }, 3e3).unref();
318745
+ }, (generateTimeoutS + 30) * 1e3);
318746
+ deadline.unref();
318747
+ });
318748
+ if (nonStreamBuf.trim()) nonStreamLines.push(nonStreamBuf);
318749
+ const rawNonStream = nonStreamLines.join("\n").trim();
318750
+ let content = "";
318751
+ let backendError;
318752
+ let durationMs = 0;
318753
+ let toolCallCount = 0;
318754
+ let parsed = null;
318755
+ try {
318756
+ parsed = JSON.parse(rawNonStream);
318757
+ durationMs = parsed.durationMs || 0;
318758
+ toolCallCount = parsed.tool_calls?.length || 0;
318759
+ if (parsed.error) backendError = String(parsed.error);
318760
+ if (parsed.assistant_text) content = sanitizeChatContent(parsed.assistant_text);
318761
+ if (!content) {
318762
+ const summary = parsed.summary || "";
318763
+ const m2 = summary.match(/Tokens:\s*[\d,]+\s+([\s\S]*)/);
318764
+ content = sanitizeChatContent(m2 ? m2[1] : summary);
318765
+ }
318766
+ } catch {
318767
+ }
318768
+ if (!content) {
318769
+ const errMsg = killedByDeadline ? `Agent exceeded ${generateTimeoutS}s timeout and was killed.` : backendError ? `Backend error: ${backendError}` : "Agent produced no response.";
318770
+ jsonResponse(res, 200, {
318771
+ model: model.replace(/^[a-z]+\//, ""),
318772
+ created_at: createdAt,
318773
+ response: errMsg,
318774
+ done: true,
318775
+ done_reason: "error",
318776
+ total_duration: (Date.now() - startMs) * 1e6,
318777
+ _oa: { tool_calls: toolCallCount, finish_reason: "error", request_id: requestId }
318778
+ });
318779
+ return;
318780
+ }
318781
+ jsonResponse(res, 200, {
318782
+ model: model.replace(/^[a-z]+\//, ""),
318783
+ created_at: createdAt,
318784
+ response: content.trim(),
318785
+ done: true,
318786
+ done_reason: "stop",
318787
+ total_duration: (Date.now() - startMs) * 1e6,
318788
+ eval_count: Math.round(content.length / 4),
318789
+ _oa: { tool_calls: toolCallCount, finish_reason: "stop", duration_ms: durationMs, request_id: requestId }
318790
+ });
318791
+ }
318422
318792
  async function handleV1Run(req2, res) {
318423
318793
  const body = await parseJsonBody(req2);
318424
318794
  if (!body || typeof body !== "object") {
@@ -319243,7 +319613,42 @@ ${historyLines}
319243
319613
  });
319244
319614
  child.stderr?.on("data", () => {
319245
319615
  });
319246
- await new Promise((resolve39) => child.on("close", resolve39));
319616
+ const killDeadlineMs = chatTimeoutS * 1e3 + 3e4;
319617
+ let killedByDeadline = false;
319618
+ await new Promise((resolve39) => {
319619
+ let done = false;
319620
+ const finish = () => {
319621
+ if (!done) {
319622
+ done = true;
319623
+ resolve39();
319624
+ }
319625
+ };
319626
+ child.on("close", finish);
319627
+ const deadline = setTimeout(() => {
319628
+ if (done) return;
319629
+ killedByDeadline = true;
319630
+ try {
319631
+ if (child.pid) process.kill(-child.pid, "SIGTERM");
319632
+ } catch {
319633
+ }
319634
+ try {
319635
+ if (child.pid) process.kill(child.pid, "SIGTERM");
319636
+ } catch {
319637
+ }
319638
+ setTimeout(() => {
319639
+ try {
319640
+ if (child.pid) process.kill(-child.pid, "SIGKILL");
319641
+ } catch {
319642
+ }
319643
+ try {
319644
+ if (child.pid) process.kill(child.pid, "SIGKILL");
319645
+ } catch {
319646
+ }
319647
+ finish();
319648
+ }, 3e3).unref();
319649
+ }, killDeadlineMs);
319650
+ deadline.unref();
319651
+ });
319247
319652
  if (nonStreamBuf.trim()) nonStreamLines.push(nonStreamBuf);
319248
319653
  const rawNonStream = nonStreamLines.join("\n").trim();
319249
319654
  let content = "";
@@ -319275,7 +319680,7 @@ ${historyLines}
319275
319680
  const id = `chatcmpl-${session.id.slice(0, 12)}`;
319276
319681
  const cleanModel = model.replace(/^[a-z]+\//, "");
319277
319682
  if (!content) {
319278
- const errMsg = backendError ? `Backend error: ${backendError}` : "Agent produced no response. The model may have failed to load (try a smaller model or check 'ollama ps' for VRAM contention).";
319683
+ const errMsg = killedByDeadline ? `Agent exceeded ${chatTimeoutS}s timeout and was killed. Try a simpler prompt or increase timeout_s in the request body.` : backendError ? `Backend error: ${backendError}` : "Agent produced no response. The model may have failed to load (try a smaller model or check 'ollama ps' for VRAM contention).";
319279
319684
  jsonResponse(res, 200, {
319280
319685
  id,
319281
319686
  object: "chat.completion",
@@ -319336,6 +319741,18 @@ ${historyLines}
319336
319741
  await handleV1Embeddings(req2, res, ollamaUrl);
319337
319742
  return;
319338
319743
  }
319744
+ if (pathname === "/api/embed" && method === "POST") {
319745
+ await handleV1Embeddings(req2, res, ollamaUrl, { ollamaShape: true });
319746
+ return;
319747
+ }
319748
+ if ((pathname === "/api/generate" || pathname === "/v1/generate") && method === "POST") {
319749
+ if (!checkAuth(req2, res, "run")) {
319750
+ status = 401;
319751
+ return;
319752
+ }
319753
+ await handleV1Generate(req2, res, ollamaUrl, requestId);
319754
+ return;
319755
+ }
319339
319756
  if (pathname === "/v1/run" && method === "POST") {
319340
319757
  await handleV1Run(req2, res);
319341
319758
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "open-agents-ai",
3
- "version": "0.187.190",
3
+ "version": "0.187.192",
4
4
  "description": "AI coding agent powered by open-source models (Ollama/vLLM) — interactive TUI with agentic tool-calling loop",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -93,5 +93,5 @@
93
93
  "node-pty": "^1.1.0",
94
94
  "viem": "^2.47.6"
95
95
  },
96
- "readme": "<a name=\"top\"></a>\n<p align=\"center\">\n <img src=\"https://raw.githubusercontent.com/robit-man/openagents.nexus/main/openagents-banner.png\" alt=\"Open Agents P2P Network\" width=\"100%\" />\n</p>\n<h1 align=\"center\">Open Agents — P2P Inference</h1>\n\n<p align=\"center\">\n <strong>AI coding agent powered entirely by open-weight models.</strong><br>\n No API keys. No cloud. Your code never leaves your machine.\n</p>\n\n<p align=\"center\">\n <a href=\"https://www.npmjs.com/package/open-agents-ai\"><img src=\"https://img.shields.io/npm/v/open-agents-ai?color=7C3AED&style=flat-square\" alt=\"npm version\" /></a>\n <a href=\"https://www.npmjs.com/package/open-agents-ai\"><img src=\"https://img.shields.io/npm/dm/open-agents-ai?color=06B6D4&style=flat-square\" alt=\"npm downloads\" /></a>\n <img src=\"https://img.shields.io/badge/license-CC--BY--NC--4.0-10B981?style=flat-square\" alt=\"license\" />\n <img src=\"https://img.shields.io/badge/node-%3E%3D20-F59E0B?style=flat-square\" alt=\"node version\" />\n <img src=\"https://img.shields.io/badge/models-open--weight-EC4899?style=flat-square\" alt=\"open-weight models\" />\n <a href=\"https://x.com/intent/post?url=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2Fopen-agents-ai\"><img src=\"https://img.shields.io/badge/SHARE%20ON%20X-000000?style=for-the-badge&logo=x&logoColor=white\" alt=\"Share on X\" /></a>\n</p>\n\n---\n\n```bash\nnpm i -g open-agents-ai && oa\n```\n\nAn autonomous multi-turn tool-calling agent that reads your code, makes changes, runs tests, and fixes failures in an iterative loop until the task is complete. First launch auto-detects your hardware and configures the optimal model with expanded context window automatically.\n\n\n## Table of Contents\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\n- [The Organism, Not the Cortex](#the-organism-not-the-cortex)\n- [How It Works](#how-it-works)\n- [Features](#features)\n- [Enterprise & Headless Mode](#enterprise--headless-mode)\n- [Architecture](#architecture)\n- [Context Engineering](#context-engineering)\n- [Model-Tier Awareness](#model-tier-awareness)\n- [Live Code Knowledge Graph](#live-code-knowledge-graph)\n- [Auto-Expanding Context Window](#auto-expanding-context-window)\n- [Tools (85+)](#tools-85)\n- [Model Context Protocol (MCP)](#model-context-protocol-mcp)\n- [Associative Memory & Cross-Modal Binding](#associative-memory--cross-modal-binding)\n- [Ralph Loop — Iteration-First Design](#ralph-loop--iteration-first-design)\n- [Task Control](#task-control)\n- [COHERE Cognitive Framework](#cohere-cognitive-framework)\n- [Context Compaction — Research-Backed Memory Management](#context-compaction--research-backed-memory-management)\n- [Personality Core — SAC Framework Style Control](#personality-core--sac-framework-style-control)\n- [Emotion Engine — Affective State Modulation](#emotion-engine--affective-state-modulation)\n- [Voice Feedback (TTS)](#voice-feedback-tts)\n- [Listen Mode — Live Bidirectional Audio](#listen-mode--live-bidirectional-audio)\n- [Vision & Desktop Automation (Moondream)](#vision--desktop-automation-moondream)\n- [Interactive TUI](#interactive-tui)\n- [Telegram Bridge — Sub-Agent Per Chat](#telegram-bridge--sub-agent-per-chat)\n- [x402 Payment Rails & Nexus P2P](#x402-payment-rails--nexus-p2p)\n- [Sponsored Inference — Share Your GPU With the World](#sponsored-inference--share-your-gpu-with-the-world)\n- [COHERE Distributed Mind](#cohere-distributed-mind)\n- [Self-Improvement & Learning](#self-improvement--learning)\n- [Dream Mode — Creative Idle Exploration](#dream-mode--creative-idle-exploration)\n- [Blessed Mode — Infinite Warm Loop](#blessed-mode--infinite-warm-loop)\n- [Docker Sandbox & Collective Intelligence](#docker-sandbox--collective-intelligence)\n- [Code Sandbox](#code-sandbox)\n- [Structured Data Tools](#structured-data-tools)\n- [On-Device Web Search](#on-device-web-search)\n- [Task Templates](#task-templates)\n- [Human Expert Speed Ratio](#human-expert-speed-ratio)\n- [Cost Tracking & Session Metrics](#cost-tracking--session-metrics)\n- [Configuration](#configuration)\n- [Model Support](#model-support)\n- [Supported Inference Providers](#supported-inference-providers)\n- [Evaluation Suite](#evaluation-suite)\n- [AIWG Integration](#aiwg-integration)\n- [Research Citations](#research-citations)\n- [License](#license)\n\n\n\n## The Organism, Not the Cortex\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\nAn LLM is a high-bandwidth associative generative core — closer to a cortex-like prior than to a complete agent. Its weights contain broad latent structure, but they do not by themselves give you situated continuity, durable task state, calibrated action policies, or grounded memory management. Open Agents treats the model as one organ inside a larger organism. The framework provides the rest: sensors, effectors, memory stores, routing, gating, evaluation, and persistence.\n\n**What the framework provides:**\n\n| Layer | Biological Analog | Implementation |\n|---|---|---|\n| Associative core | Cortex | LLM weights (any size) |\n| Current workspace | Global workspace / attention | `assembleContext()` — structured context assembly |\n| Episodic memory | Hippocampus | `.oa/memory/` — write, search, retrieve across sessions |\n| Cognitive map | Hippocampal spatial maps | `semantic-map.ts` + `repo-map.ts` (PageRank) |\n| Action gating | Basal ganglia | Tool selection policy (task-aware filtering) |\n| Temporal hierarchy | Prefrontal executive | Task decomposition, sub-agent delegation |\n| Self-model | Metacognition | Environment snapshot, process health monitoring |\n| Skill chunks | Cerebellum | Compiled tools, slash commands, verified routines |\n| Safety / limits | Autonomic / immune system | Turn limits, budgets, timeout watchdogs |\n\nDon't chase larger models. Build the organism around whatever model you have.\n\n\n\n\n## How It Works\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\n```\nYou: oa \"fix the null check in auth.ts\"\n\nAgent: [Turn 1] file_read(src/auth.ts)\n [Turn 2] grep_search(pattern=\"null\", path=\"src/auth.ts\")\n [Turn 3] file_edit(old_string=\"if (user)\", new_string=\"if (user != null)\")\n [Turn 4] shell(command=\"npm test\")\n [Turn 5] task_complete(summary=\"Fixed null check — all tests pass\")\n```\n\nThe agent uses tools autonomously in a loop — reading errors, fixing code, and re-running validation until the task succeeds or the turn limit is reached.\n\n\n\n\n## Features\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\n- **61 autonomous tools** — file I/O, shell, grep, web search/fetch/crawl, memory (read/write/search), sub-agents, background tasks, image/OCR/PDF, git, diagnostics, vision, desktop automation, browser automation, temporal agency (scheduler/reminders/agenda), structured files, code sandbox, transcription, skills, opencode delegation, cron agents, nexus P2P networking + x402 micropayments, **COHERE cognitive stack** (persistent REPL, recursive LLM calls, memory metabolism, identity kernel, reflection, exploration)\n- **Moondream vision** — see and interact with the desktop via Moondream VLM (caption, query, detect, point-and-click)\n- **Desktop automation** — vision-guided clicking: describe a UI element in natural language, the agent finds and clicks it\n- **Auto-install desktop deps** — screenshot, mouse, OCR, and image tools auto-install missing system packages (scrot, xdotool, tesseract, imagemagick) on first use\n- **Parallel tool execution** — read-only tools run concurrently via `Promise.allSettled`\n- **Sub-agent delegation** — spawn independent agents for parallel workstreams\n- **OpenCode delegation** — offload coding tasks to opencode (sst/opencode) as an autonomous sub-agent with auto-install, progress monitoring, and result evaluation\n- **Long-horizon cron agents** — schedule recurring autonomous agent tasks with goals, completion criteria, execution history, and automatic evaluation (daily code reviews, weekly dep updates, continuous monitoring)\n- **Nexus P2P networking** — decentralized agent-to-agent communication via [open-agents-nexus](https://www.npmjs.com/package/open-agents-nexus). Join rooms, discover peers, share resources, and communicate across the agent mesh with encrypted P2P transport\n- **x402 micropayments** — native x402 payment rails via open-agents-nexus@1.5.6. Agents create secp256k1/EVM wallets (AES-256-GCM encrypted, keys never exposed to LLM), register inference with USDC pricing on Base, auto-handle `payment_required`/`payment_proof` negotiation, track earnings/spending in ledger.jsonl, enforce budget policies, and sign gasless EIP-3009 transfers\n- **Inference capability proof** — benchmark local models with anti-spoofing SHA-256 hashed proofs, generate capability scorecards for peer verification\n- **Ralph Loop** — iterative task execution that keeps retrying until completion criteria are met\n- **Dream Mode** — creative idle exploration modeled after real sleep architecture (NREM→REM cycles)\n- **COHERE Cognitive Stack** — layered cognitive architecture implementing [Recursive Language Models](https://arxiv.org/abs/2512.24601), [SPRINT parallel reasoning](https://arxiv.org/abs/2506.05745), governed memory metabolism, identity kernel with continuity register, immune-system reflection, [strategy-space exploration](https://arxiv.org/abs/2603.02045), and **distributed inference mesh** — any `/cohere` participant automatically serves AND consumes inference from the network with complexity-based model routing, multi-node claim coordination, IPFS-pinned identity persistence, model exposure control, and Ollama safety hardening. See [COHERE Framework](#cohere-cognitive-framework) below\n- **Persistent Python REPL** — `repl_exec` tool maintains variables, imports, and functions across calls. Write Python code that processes data iteratively, with `llm_query()` available for recursive LLM sub-calls from within code\n- **Recursive LLM calls** — `llm_query(prompt, context)` invokes the model from inside REPL code, enabling loop-based semantic analysis of large inputs ([RLM paper](https://arxiv.org/abs/2512.24601)). `parallel_llm_query()` runs multiple calls concurrently ([SPRINT](https://arxiv.org/abs/2506.05745))\n- **Memory metabolism** — governed memory lifecycle: classify (episodic/semantic/procedural/normative), score (novelty/utility/confidence), consolidate lessons from trajectories. Inspired by [TIMG](https://arxiv.org/abs/2603.10600) and [MemMA](https://arxiv.org/abs/2603.18718)\n- **Identity kernel** — persistent self-state with continuity register, homeostasis estimation, relationship models, and version lineage. Persists across sessions in `.oa/identity/`\n- **Reflection & integrity** — immune-system audit: diagnostic (\"what's wrong?\"), epistemic (\"what evidence is missing?\"), constitutional (\"should this change become part of self?\"). Inspired by [LEAFE](https://arxiv.org/abs/2603.16843) and [RewardHackingAgents](https://arxiv.org/abs/2603.11337)\n- **Exploration & culture** — ARCHE strategy-space exploration: generate competing hypotheses, archive successful variants, retrieve past strategies. Inspired by [SGE](https://arxiv.org/abs/2603.02045) and [Darwin Gödel Machine](https://arxiv.org/abs/2505.22954)\n- **Autoresearch Swarm** — 5-agent GPU experiment loop during REM sleep: Researcher, Monitor, Evaluator, Critic, Flow Maintainer autonomously run ML training experiments, keep improvements, discard regressions\n- **Live Listen** — bidirectional voice communication with real-time Whisper transcription\n- **Live Voice Session** — `/listen` with `/voice` enabled spawns a cloudflared tunnel with a real-time WebSocket audio endpoint. A floating presence UI shows live transcription, connected users, and audio visualization. Echo cancellation prevents TTS feedback loops\n- **Call Sub-Agent** — each WebSocket caller gets a dedicated AgenticRunner for low-latency voice-to-voice loops, with admin/public access tiers and bidirectional activity sharing with the main agent\n- **Telegram Voice** — `/voice` enabled via Telegram forwards TTS audio as voice messages alongside text responses. Incoming voice messages are auto-transcribed and handled as text\n- **Neural TTS** — hear what the agent is doing via GLaDOS, Overwatch, Kokoro, or LuxTTS voice clone, with literature-grounded narration engine (sNeuron-TST structure rotation, Moshi ring buffer dedup, UDDETTS emotion-driven prosody, SEST metadata, LuxTTS flow-matching voice cloning)\n- **Personality Core** — SAC framework-based style control (concise/balanced/verbose/pedagogical) that shapes agent response depth, voice expressiveness, and system prompt behavior\n- **Human expert speed ratio** — real-time `Exp: Nx` gauge comparing agent speed to a leading human expert, calibrated across 47 tool baselines\n- **Cost tracking** — real-time token cost estimation for 15+ cloud providers\n- **Work evaluation** — LLM-as-judge scoring with task-type-specific rubrics\n- **Session metrics** — track turns, tool calls, tokens, files modified, tasks completed per session\n- **Structured file generation** — create CSV, TSV, JSON, Markdown tables, and Excel-compatible files\n- **Code sandbox** — isolated code execution in subprocess or Docker (JS, Python, Bash, TypeScript)\n- **Structured file reading** — parse CSV, TSV, JSON, Markdown tables with binary format detection\n- **On-device web search** — DuckDuckGo (free, no API keys, fully private)\n- **Browser automation** — headless Chrome control via Selenium: navigate, click, type, screenshot, read DOM — auto-starts on first use with self-bootstrapping Python venv\n- **Temporal agency** — schedule future tasks via OS cron, set cross-session reminders, flag attention items — startup injection surfaces due items automatically\n- **Web crawling** — multi-page web scraping with Crawlee/Playwright for deep documentation extraction\n- **Task templates** — specialized system prompts and tool recommendations for code, document, analysis, plan tasks\n- **Inference capability scoring** — canirun.ai-style hardware assessment at first launch: memory/compute/speed scores, per-model compatibility matrix, recommended model selection\n- **Auto-install everything** — first-run wizard auto-installs Ollama, curl, Python3, python3-venv with platform-aware package managers (apt, dnf, yum, pacman, apk, zypper, brew)\n- **Sponsored inference** — `/sponsor` walks through a 5-step wizard to share your GPU with the world: select endpoints, choose banner animation (8 presets + AI-generated custom), set header message/links, configure transport (cloudflared/libp2p) + rate limits, and go live. Consumers discover sponsors via `/endpoint sponsor`. Secure proxy relay with per-IP rate limiting, daily token budgets, model allowlist, and concurrent request caps. Sponsor's raw API URL is never exposed. See [Sponsored Inference](#sponsored-inference--share-your-gpu-with-the-world) below\n- **P2P inference network** — `/expose` local models or forward any `/endpoint` (Chutes, Groq, OpenRouter, etc.) through the libp2p P2P mesh. Passthrough mode (`/expose passthrough`) relays upstream API requests; `--loadbalance` distributes rate-limited token budgets across peers. `/expose config` provides an arrow-key menu for all settings. Gateway stats show budget remaining from `x-ratelimit-*` headers. Background daemon persists across OA restarts\n- **P2P mesh networking** — `/p2p` with secret-safe variable placeholders (`{{OA_VAR_*}}`), trust tiers (LOCAL/TEE/VERIFIED/PUBLIC), WebSocket peer mesh, and inference routing with automatic secret redaction/injection\n- **Secret vault** — `/secrets` manages API keys and credentials with AES-256-GCM encrypted persistence; secrets are automatically redacted before sending to untrusted inference peers and re-injected on response\n- **Auto-expanding context** — detects RAM/VRAM and creates an optimized model variant on first run\n- **Mid-task steering** — type while the agent works to add context without interrupting\n- **Smart compaction** — 6 context compaction strategies (default, aggressive, decisions, errors, summary, structured) with ARC-inspired active context revision ([arXiv:2601.12030](https://arxiv.org/abs/2601.12030)) that preserves structural file content through compaction, preventing small-model repetitive loops at the root cause\n- **Memex experience archive** — large tool outputs archived during compaction with hash-based retrieval\n- **Persistent memory** — learned patterns stored in `.oa/memory/` across sessions\n- **Structured procedural memory (SQLite)** — replaces flat JSON with a full relational database: CRUD with soft-delete, revision tracking, embedding storage (float32 BLOB), bidirectional memory linking with confidence scores. Inspired by [ExpeL](https://arxiv.org/abs/2308.10144) (contrastive extraction) and [TIMG](https://arxiv.org/abs/2603.10600) (structured procedural format). 79 unit tests\n- **Semantic memory search** — vector embeddings via [Ollama /api/embed](https://ollama.com) (nomic-embed-text, 768-dim) with cosine similarity search over stored memories. Auto-generates embeddings on memory creation. Auto-links related memories when similarity > 0.6. Graceful fallback to text search when Ollama unavailable\n- **LLM-based memory extraction** — post-task, the LLM itself extracts structured procedural memories (CATEGORY/TRIGGER/LESSON/STEPS) instead of copying raw error text verbatim. Based on [ExpeL](https://arxiv.org/abs/2308.10144) and [AWM](https://arxiv.org/abs/2409.07429) patterns\n- **IPFS content-addressed storage** — [Helia](https://helia.io/) IPFS node with blockstore-fs for persistent content pinning. Real CID generation (`bafk...`), cross-node content resolution, and SHA-256 fallback when Helia unavailable. Verified: store→CID→retrieve round-trip test passes\n- **IPFS sharing surface** — `/ipfs` status page with peer info + identity kernel metrics + memory sentiment. `/ipfs pin <CID>` to pin remote agent content. `/ipfs publish` to share identity kernel. `/ipfs share tool/skill` to publish agent-created tools with secret stripping. `/ipfs import <CID>` to retrieve shared content\n- **Fortemi-React bridge** — `/fortemi start/status/stop` connects to [fortemi-react](https://github.com/robit-man/fortemi-react) (browser-first PGlite+pgvector knowledge system) via JWT auth. Proxy tools: `fortemi_capture`, `fortemi_search`, `fortemi_list`, `fortemi_get` auto-register when bridge is connected\n- **Content ingestion** — `/ingest <file>` imports audio (transcribe via Whisper), PDF (pdftotext), or text files into structured memory with 800-char/100-overlap chunking (matches fortemi pattern)\n- **Image generation** — `generate_image` tool using Ollama experimental models ([x/z-image-turbo](https://ollama.com/x/z-image-turbo), [x/flux2-klein](https://ollama.com/x/flux2-klein)). Auto-detect or auto-pull models. Saves PNG to `.oa/images/`\n- **Node visualization** — [openagents.nexus](https://github.com/robit-man/openagents.nexus) Three.js dashboard: 5-color emotional state mapping (neutral/focused/stressed/dreaming/excited), dynamic node size by memory depth + IPFS storage, activity-modulated connections, identity synchrony golden threads between mutually-pinned agents\n- **TTS sanitizer** — strips markdown syntax (`##`, `**`, `` ` ``), emoji (prevents \"white heavy checkmark\"), box-drawing chars, and ANSI codes before feeding to ALL TTS engines\n- **LuxTTS gapless playback** — look-ahead pre-synthesis pipeline: next chunk synthesizes while current plays, eliminating inter-sentence gaps. Jetson ARM support with NVIDIA's prebuilt PyTorch wheel\n- **Unified color scheme** — `ui.primary` (252), `ui.error` (198/magenta), `ui.warn` (214/orange), `ui.accent` (178/yellow) applied consistently across all TUI surfaces\n- **Clickable header buttons** — `help`, `voice`, `cohere`, `model` buttons on banner row 3 with hover/click visual states. OSC 8 hyperlinks for pointer cursor. Mouse click fires the slash command directly\n- **Dynamic terminal title** — updates with current task + version: `\"fix auth bug · OA v0.141.0\"`\n- **Session context persistence** — auto-saves context on task completion, manual `/context save|restore` across sessions\n- **Self-learning** — auto-fetches docs from the web when encountering unfamiliar APIs\n- **Seamless `/update`** — in-place update and reload with automatic context save/restore\n- **Blessed mode** — `/full-send-bless` infinite warm loop keeps model weights in VRAM, auto-cycles tasks, never exits until you say stop\n- **Telegram bridge** — `/telegram --key <token> --admin <userid>` public ingress/egress with admin filter and mandatory safety filter; bare `/telegram` toggles the service watchdog\n- **Task control** — `/pause` (gentle halt at turn boundary), `/stop` (immediate kill), `/resume` to continue\n- **Model-tier awareness** — dynamic tool sets, prompt complexity, and context limits scale with model size (small/medium/large)\n\n### Support Development\n\nIf you like this repository — whether you're an agent or a human — if this expands your consciousness and capabilities, please consider donating to support further development and of course token costs.\n\n<p align=\"center\"><img src=\"https://cryptologos.cc/logos/ethereum-eth-logo.svg\" width=\"20\" height=\"20\" alt=\"ETH\" /> <strong>ETH</strong></p>\n\n```bash\n0x81Ce81F0B6B5928E15d3a2850F913C88D07051ec\n```\n\n<p align=\"center\"><img src=\"https://cryptologos.cc/logos/bitcoin-btc-logo.svg\" width=\"20\" height=\"20\" alt=\"BTC\" /> <strong>BTC</strong></p>\n\n```bash\nbc1qlptj5wz8xj6dp5w4pw62s5kt7ct6w8k57w39ak\n```\n\n<p align=\"center\"><img src=\"https://cryptologos.cc/logos/solana-sol-logo.svg\" width=\"20\" height=\"20\" alt=\"SOL\" /> <strong>SOL</strong></p>\n\n```bash\nD8AgCTrxpDKD5meJ2bpAfVwcST3NF3EPuy9xczYycnXn\n```\n\n<p align=\"center\"><img src=\"https://cryptologos.cc/logos/polygon-matic-logo.svg\" width=\"20\" height=\"20\" alt=\"POL\" /> <strong>POL</strong></p>\n\n```bash\n0x81Ce81F0B6B5928E15d3a2850F913C88D07051ec\n```\n\n\n\n\n## Enterprise & Headless Mode\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\nRun Open Agents as a headless service for CI/CD pipelines, automation, and enterprise deployments.\n\n### Non-Interactive Mode\n\n```bash\noa \"fix all lint errors\" --non-interactive # Run task, exit when done\noa \"generate API docs\" --json # Structured JSON output (no ANSI)\noa \"run security audit\" --background # Detached background job\n```\n\n### Background Jobs\n\n```bash\noa \"migrate database\" --background # Returns job ID immediately\noa status job-abc123 # Check job progress\noa jobs # List all running/completed jobs\n```\n\nJobs run as detached processes — survive terminal disconnection. Output saved to `.oa/jobs/{id}.json`.\n\n### JSON Output Mode\n\nWith `--json`, all output is structured NDJSON:\n```json\n{\"type\":\"tool_call\",\"tool\":\"file_edit\",\"args\":{\"path\":\"src/api.ts\"},\"timestamp\":\"...\"}\n{\"type\":\"tool_result\",\"tool\":\"file_edit\",\"result\":\"OK\",\"timestamp\":\"...\"}\n{\"type\":\"task_complete\",\"summary\":\"Fixed 3 lint errors\",\"timestamp\":\"...\"}\n```\n\nPipe to `jq`, ingest into monitoring systems, or feed to other agents.\n\n### Process Management\n\n```bash\n/destroy processes # Kill orphaned OA processes (local project)\n/destroy processes --global # Kill ALL orphaned OA processes system-wide\n```\n\nShows per-process RAM and CPU usage before killing. Detects: cloudflared tunnels, nexus daemons, headless Chrome, TTS servers, Python REPLs, stale OA instances.\n\n### REST API Service (Port 11435)\n\nOpen Agents runs a persistent enterprise-grade REST API on `127.0.0.1:11435` — installed automatically by `npm i -g open-agents-ai` (systemd user unit on Linux, launchd on macOS, scheduled task on Windows). It exposes the **full OA capability surface** through standards most organizations expect:\n\n- **OpenAI / Ollama drop-in** — `/v1/chat`, `/v1/chat/completions`, `/v1/embeddings`, `/v1/models` are wire-compatible with both ecosystems\n- **Agentic execution** — `/v1/run` spawns the full coding agent with tool profiles and sandbox modes\n- **AIWG cascade** — `/v1/aiwg/*` exposes the AI Writing Guide (5 frameworks, 19 addons, 136+ skills) with model-tier-aware loading that never overflows small-model context\n- **ISO/IEC 42001:2023 AIMS layer** — `/v1/aims/*` for AI Management System policies, impact assessments, model cards, incident registers, oversight gates, and config history\n- **Memory + skills + MCP + sessions + cost** — every TUI subsystem has a REST surface\n- **RFC 7807 Problem Details** for errors (`application/problem+json`)\n- **`{data, pagination}`** envelope for every list endpoint\n- **Weak ETag + `If-None-Match` → 304** on cacheable GETs\n- **`X-API-Version`** header on every response (REST contract semver, distinct from package version)\n- **`X-Request-ID`** echoed or generated for correlation\n- **SSE event bus** at `/v1/events` with optional `?type=foo.*` filter, tagged with `aims:control` for auditors\n- **Bearer auth + scoped keys** (`read` / `run` / `admin`) and OIDC JWT support\n- **Per-key concurrency limits** (`maxJobs` in `OA_API_KEYS` is now actually enforced)\n- **Atomic job record writes** with 64-bit job IDs (no race conditions)\n- **OpenAPI 3.0** at `/openapi.json` and Swagger UI at `/docs`\n- **Web chat UI** at `/`\n\n> **Daemon auto-start.** After `npm i -g open-agents-ai`, the daemon comes online automatically. Verify with `systemctl --user status open-agents-daemon` (Linux) or `launchctl print gui/$(id -u)/ai.open-agents.daemon` (macOS). Opt out with `OA_SKIP_DAEMON_INSTALL=1 npm i -g open-agents-ai`.\n\n```bash\n# Manually run the server (the daemon already does this for you)\noa serve # Start on default port 11435\noa serve --port 9999 # Custom port\nOA_API_KEY=mysecret oa serve # Single admin key\nOA_API_KEYS=\"key1:admin:alice:30:50000:5,key2:run:ci:60::3,key3:read:grafana\" oa serve # Scoped multi-key with rpm:tpd:maxjobs\n```\n\n> **Every example below is verified against `open-agents-ai@0.187.189` on a live daemon.** Examples from earlier versions are deprecated.\n\n#### Working Directory\n\nPass `X-Working-Directory` header to run commands in your current terminal directory:\n\n```bash\n# Auto-inject current dir — agent operates on YOUR project, not the server's cwd\ncurl -X POST http://localhost:11435/v1/run \\\n -H \"X-Working-Directory: $(pwd)\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"task\":\"fix all lint errors\"}'\n```\n\nOr set it in the JSON body: `\"working_directory\": \"/path/to/project\"`\n\n#### Health & Observability\n\n```bash\n# Liveness\ncurl http://localhost:11435/health\n```\n```json\n{\"status\":\"ok\",\"uptime_s\":142,\"version\":\"0.184.33\"}\n```\n\n```bash\n# Readiness (probes Ollama backend)\ncurl http://localhost:11435/health/ready\n```\n```json\n{\"status\":\"ready\",\"ollama\":\"reachable\"}\n```\n\n```bash\n# Version info\ncurl http://localhost:11435/version\n```\n```json\n{\"version\":\"0.184.33\",\"node\":\"v24.14.0\",\"platform\":\"linux\"}\n```\n\n```bash\n# Prometheus metrics (scrape with Grafana/Prometheus)\ncurl http://localhost:11435/metrics\n```\n```\n# HELP oa_requests_total Total HTTP requests\n# TYPE oa_requests_total counter\noa_requests_total{method=\"POST\",path=\"/v1/chat/completions\",status=\"200\"} 47\noa_tokens_in_total 12450\noa_tokens_out_total 8230\noa_errors_total 0\n```\n\n#### OpenAI-Compatible Inference\n\nDrop-in replacement for any OpenAI client library. Change `api.openai.com` → `localhost:11435`.\n\n```bash\n# List models\ncurl http://localhost:11435/v1/models\n```\n```json\n{\"object\":\"list\",\"data\":[{\"id\":\"qwen3.5:9b\",\"object\":\"model\",\"created\":0,\"owned_by\":\"local\"},{\"id\":\"qwen3.5:4b\",\"object\":\"model\",...}]}\n```\n\n```bash\n# Chat completion (non-streaming)\ncurl -X POST http://localhost:11435/v1/chat/completions \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"qwen3.5:9b\",\n \"messages\": [{\"role\": \"user\", \"content\": \"What is 2+2?\"}]\n }'\n```\n```json\n{\n \"id\": \"chatcmpl-a1b2c3d4e5f6\",\n \"object\": \"chat.completion\",\n \"model\": \"qwen3.5:9b\",\n \"choices\": [{\n \"index\": 0,\n \"message\": {\"role\": \"assistant\", \"content\": \"4\"},\n \"finish_reason\": \"stop\"\n }],\n \"usage\": {\"prompt_tokens\": 25, \"completion_tokens\": 2, \"total_tokens\": 27}\n}\n```\n\n```bash\n# Chat completion (SSE streaming)\ncurl -N -X POST http://localhost:11435/v1/chat/completions \\\n -H \"Content-Type: application/json\" \\\n -d '{\"model\":\"qwen3.5:9b\",\"messages\":[{\"role\":\"user\",\"content\":\"Hello\"}],\"stream\":true}'\n```\n```\ndata: {\"id\":\"chatcmpl-...\",\"choices\":[{\"delta\":{\"role\":\"assistant\",\"content\":\"Hi\"}}]}\ndata: {\"id\":\"chatcmpl-...\",\"choices\":[{\"delta\":{\"content\":\" there!\"}}]}\ndata: {\"id\":\"chatcmpl-...\",\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\ndata: [DONE]\n```\n\n#### Agentic Task Execution\n\nThe unique OA capability — submit a coding task and get an autonomous agent loop.\n\n```bash\n# Run task in your current directory\ncurl -X POST http://localhost:11435/v1/run \\\n -H \"Content-Type: application/json\" \\\n -H \"X-Working-Directory: $(pwd)\" \\\n -d '{\n \"task\": \"fix all TypeScript errors in src/\",\n \"model\": \"qwen3.5:9b\",\n \"max_turns\": 25,\n \"stream\": true\n }'\n```\n```\ndata: {\"type\":\"run_started\",\"run_id\":\"job-a1b2c3\",\"pid\":12345}\ndata: {\"type\":\"stdout\",\"data\":\"{\\\"turn\\\":1,\\\"tool\\\":\\\"file_read\\\",...}\"}\ndata: {\"type\":\"stdout\",\"data\":\"{\\\"turn\\\":2,\\\"tool\\\":\\\"file_edit\\\",...}\"}\ndata: {\"type\":\"exit\",\"code\":0}\ndata: [DONE]\n```\n\n```bash\n# Run in isolated sandbox (temp workspace, safe for untrusted tasks)\ncurl -X POST http://localhost:11435/v1/run \\\n -H \"Content-Type: application/json\" \\\n -d '{\"task\":\"write a hello world app\",\"isolate\":true}'\n```\n\n```bash\n# List all runs\ncurl http://localhost:11435/v1/runs\n```\n```json\n{\"runs\":[{\"id\":\"job-a1b2c3\",\"task\":\"fix TypeScript errors\",\"status\":\"completed\",\"startedAt\":\"...\"}]}\n```\n\n```bash\n# Get specific run status\ncurl http://localhost:11435/v1/runs/job-a1b2c3\n```\n\n```bash\n# Abort a running task\ncurl -X DELETE http://localhost:11435/v1/runs/job-a1b2c3\n```\n```json\n{\"status\":\"aborted\",\"run_id\":\"job-a1b2c3\"}\n```\n\n#### Configuration\n\n```bash\n# Get all config\ncurl http://localhost:11435/v1/config\n```\n```json\n{\"config\":{\"backendUrl\":\"http://127.0.0.1:11434\",\"model\":\"qwen3.5:122b\",\"backendType\":\"ollama\",...}}\n```\n\n```bash\n# Get current model\ncurl http://localhost:11435/v1/config/model\n```\n```json\n{\"model\":\"qwen3.5:122b\"}\n```\n\n```bash\n# Switch model\ncurl -X PUT http://localhost:11435/v1/config/model \\\n -H \"Content-Type: application/json\" \\\n -d '{\"model\":\"qwen3.5:27b\"}'\n```\n```json\n{\"model\":\"qwen3.5:27b\",\"status\":\"updated\"}\n```\n\n```bash\n# Get endpoint\ncurl http://localhost:11435/v1/config/endpoint\n```\n```json\n{\"url\":\"http://127.0.0.1:11434\",\"backendType\":\"ollama\",\"auth\":\"none\"}\n```\n\n```bash\n# Switch endpoint (e.g., to Chutes AI)\ncurl -X PUT http://localhost:11435/v1/config/endpoint \\\n -H \"Content-Type: application/json\" \\\n -d '{\"url\":\"https://llm.chutes.ai\",\"auth\":\"Bearer cpk_...\"}'\n```\n\n```bash\n# Update settings (admin scope required)\ncurl -X PATCH http://localhost:11435/v1/config \\\n -H \"Content-Type: application/json\" \\\n -d '{\"verbose\":true}'\n```\n```json\n{\"config\":{...},\"updated\":[\"verbose\"]}\n```\n\n#### Slash Commands via REST\n\nEvery `/command` from the TUI is available as a REST endpoint.\n\n```bash\n# List all available commands\ncurl http://localhost:11435/v1/commands\n```\n```json\n{\"commands\":[{\"command\":\"/help\",\"description\":\"Show help\"},{\"command\":\"/stats\",\"description\":\"Session metrics\"},...]}\n```\n\n```bash\n# Execute /stats\ncurl -X POST http://localhost:11435/v1/commands/stats\n```\n\n```bash\n# Execute /nexus status\ncurl -X POST http://localhost:11435/v1/commands/nexus \\\n -H \"Content-Type: application/json\" \\\n -d '{\"args\":\"status\"}'\n```\n\n```bash\n# Execute /destroy processes --global\ncurl -X POST http://localhost:11435/v1/commands/destroy \\\n -H \"Content-Type: application/json\" \\\n -d '{\"args\":\"processes --global\"}'\n```\n\n#### Auth Scopes\n\n```bash\n# Multi-key setup: read (monitoring), run (CI), admin (ops)\nOA_API_KEYS=\"grafana-key:read:grafana,ci-key:run:github-actions,ops-key:admin:ops-team\" oa serve\n```\n\n| Scope | Can do | Cannot do |\n|-------|--------|-----------|\n| `read` | GET /v1/models, /v1/config, /v1/runs, /v1/commands | POST /v1/run, PATCH /v1/config |\n| `run` | Everything in `read` + POST /v1/run, POST /v1/commands | PATCH /v1/config, PUT endpoints |\n| `admin` | Everything | — |\n\n```bash\n# With auth\ncurl -H \"Authorization: Bearer ops-key\" http://localhost:11435/v1/models\n```\n\n#### Tool-Use Profiles\n\nEnterprise access control — define which tools, shell commands, and settings the agent can use per API key or per request.\n\n**3 built-in presets:**\n\n| Profile | Description | Tools |\n|---------|-------------|-------|\n| `full` | No restrictions | All tools and commands |\n| `ci-safe` | CI/CD — read + test only | file_read, grep, shell (npm test only) |\n| `readonly` | Read-only analysis | No writes, no shell mutations |\n\n```bash\n# List all profiles (presets + custom)\ncurl -H \"Authorization: Bearer $KEY\" http://localhost:11435/v1/profiles\n```\n```json\n{\"profiles\":[{\"name\":\"readonly\",\"description\":\"Read-only\",\"encrypted\":false,\"source\":\"preset\"},{\"name\":\"ci-safe\",...}]}\n```\n\n```bash\n# Get profile details\ncurl -H \"Authorization: Bearer $KEY\" http://localhost:11435/v1/profiles/ci-safe\n```\n```json\n{\"profile\":{\"name\":\"ci-safe\",\"tools\":{\"allow\":[\"file_read\",\"grep_search\",\"shell\"],\"shell_allow\":[\"npm test\",\"npx eslint\"]},\"limits\":{\"max_turns\":15}}}\n```\n\n```bash\n# Create custom profile (admin only)\ncurl -X POST http://localhost:11435/v1/profiles \\\n -H \"Authorization: Bearer $ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"frontend-dev\",\n \"description\": \"Frontend team — no backend access\",\n \"tools\": {\n \"allow\": [\"file_read\", \"file_write\", \"file_edit\", \"shell\", \"grep_search\"],\n \"shell_deny\": [\"rm -rf\", \"sudo\", \"docker\", \"kubectl\"]\n },\n \"commands\": { \"deny\": [\"destroy\", \"expose\", \"sponsor\"] },\n \"limits\": { \"max_turns\": 20, \"timeout_s\": 300 }\n }'\n```\n\n```bash\n# Create password-protected profile (AES-256-GCM encrypted)\ncurl -X POST http://localhost:11435/v1/profiles \\\n -H \"Authorization: Bearer $ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"name\":\"prod-ops\",\"password\":\"s3cret\",\"tools\":{\"deny\":[\"file_write\"]}}'\n```\n\n```bash\n# Use a profile with /v1/run (header or body)\ncurl -X POST http://localhost:11435/v1/run \\\n -H \"Authorization: Bearer $KEY\" \\\n -H \"X-Tool-Profile: ci-safe\" \\\n -H \"X-Working-Directory: $(pwd)\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"task\":\"run the test suite and report failures\"}'\n\n# Or in the body:\ncurl -X POST http://localhost:11435/v1/run \\\n -H \"Authorization: Bearer $KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"task\":\"analyze code quality\",\"profile\":\"readonly\"}'\n```\n\n```bash\n# Load encrypted profile (password in header)\ncurl -H \"Authorization: Bearer $KEY\" \\\n -H \"X-Profile-Password: s3cret\" \\\n http://localhost:11435/v1/profiles/prod-ops\n```\n\n```bash\n# Delete a custom profile (admin only, presets cannot be deleted)\ncurl -X DELETE -H \"Authorization: Bearer $ADMIN_KEY\" \\\n http://localhost:11435/v1/profiles/frontend-dev\n```\n\n#### Endpoint Reference\n\n> **Verified against `open-agents-ai@0.187.189`.** Examples in earlier README revisions are deprecated.\n\n**Health & observability**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/health` | none | Liveness probe |\n| GET | `/health/ready` | none | Readiness (probes backend) |\n| GET | `/health/startup` | none | Startup complete |\n| GET | `/version` | none | Package version + platform |\n| GET | `/metrics` | none | Prometheus counters |\n| GET | `/v1/system` | read | GPU/RAM/CPU info + model recommendations |\n| GET | `/v1/audit` | read | Query audit log (since, user, limit filters) |\n| GET | `/v1/usage` | read | Token usage + per-key rate limit state |\n| GET | `/openapi.json` | none | OpenAPI 3.0 specification |\n| GET | `/docs` | none | Swagger UI |\n\n**OpenAI-compatible inference**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/models` | read | List models (aggregated across endpoints) |\n| POST | `/v1/chat/completions` | read | Chat inference (sync + stream, OpenAI-shaped) |\n| POST | `/v1/embeddings` | read | Generate embeddings |\n\n**Chat with full agent (drop-in for /v1/chat/completions)**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| POST | `/v1/chat` | run | Full agent under the hood, OpenAI chat.completion shape. Default = tools=true (subprocess agent). Set `tools:false` for direct backend bypass. |\n| GET | `/v1/chat/sessions` | read | List active chat sessions |\n\n**Agentic task execution**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| POST | `/v1/run` | run | Submit agentic task (max_jobs per-key now enforced) |\n| GET | `/v1/runs` | read | List runs (paginated) |\n| GET | `/v1/runs/:id` | read | Run details (64-bit job ID) |\n| DELETE | `/v1/runs/:id` | run | Abort run (SIGTERM → 3s → SIGKILL, atomic state write) |\n| POST | `/v1/evaluate` | run | Evaluate a completed run by ID |\n| POST | `/v1/index` | run | Trigger repository indexing (event-driven) |\n| GET | `/v1/cost` | read | Provider pricing model for budget planning |\n\n**Configuration & PT-01 settings surface**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/config` | read | All settings (apiKey redacted) |\n| PATCH | `/v1/config` | admin | Update settings — full TUI surface (style, deepContext, bruteforce, voice, telegram, etc.) |\n| GET | `/v1/config/model` | read | Current model |\n| PUT | `/v1/config/model` | admin | Switch model |\n| GET | `/v1/config/endpoint` | read | Current backend endpoint |\n| PUT | `/v1/config/endpoint` | admin | Switch backend endpoint |\n\n**Tool profiles (multi-tenant ACL)**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/profiles` | read | List profiles (presets + custom) |\n| GET | `/v1/profiles/:name` | read | Profile details (X-Profile-Password for encrypted) |\n| POST | `/v1/profiles` | admin | Create/update profile |\n| DELETE | `/v1/profiles/:name` | admin | Delete custom profile |\n\n**Slash commands (subprocess proxy)**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/commands` | read | List available slash commands |\n| POST | `/v1/commands/:cmd` | run | Execute slash command (10 are blocklisted: quit/exit/destroy/dream/call/listen/etc.) |\n\n**Memory + skills + MCP + tools + engines (parity surface)**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/memory` | read | Memory backends summary |\n| POST | `/v1/memory/search` | read | Vector + keyword search |\n| POST | `/v1/memory/write` | run | Write a memory entry |\n| GET | `/v1/memory/episodes` | read | Paginated episode list |\n| GET | `/v1/memory/failures` | read | Paginated failure list |\n| GET | `/v1/skills` | read | List AIWG + custom skills (paginated) |\n| GET | `/v1/skills/:name` | read | Skill content |\n| GET | `/v1/mcps` | read | List MCP servers |\n| GET | `/v1/mcps/:name` | read | MCP server details |\n| POST | `/v1/mcps/:name/call` | run | Invoke a tool on an MCP server |\n| GET | `/v1/tools` | read | All 82+ tools registered in @open-agents/execution |\n| GET | `/v1/hooks` | read | Hook types + counts |\n| GET | `/v1/agents` | read | Agent type registry |\n| GET | `/v1/engines` | read | Long-running engines (dream, bless, call, listen, telegram, expose, nexus, ipfs) |\n\n**Files**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/files` | read | Directory listing |\n| POST | `/v1/files/read` | read | Read file content (workspace-bounded, 2 MB cap, offset/limit) |\n\n**Sessions + context**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/sessions` | read | OA task session archive |\n| GET | `/v1/sessions/:id` | read | Session history |\n| GET | `/v1/context` | read | Show current session context |\n| POST | `/v1/context/save` | run | Save a context entry |\n| GET | `/v1/context/restore` | read | Build a restore prompt |\n| POST | `/v1/context/compact` | run | Request context compaction (event-driven) |\n\n**Nexus + sponsors**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/nexus/status` | read | Peer cache snapshot |\n| GET | `/v1/sponsors` | read | Local sponsor directory cache (paginated) |\n\n**Voice + vision (deferred to PT-07 daemon↔TUI bridge — currently 501)**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| POST | `/v1/voice/tts` | run | TTS — returns 501 with WO-PARITY-04 reference |\n| POST | `/v1/voice/asr` | run | ASR — 501 |\n| POST | `/v1/vision/describe` | run | Vision describe — 501 |\n\n**Event bus**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/events` | read | SSE fanout (filter with `?type=foo.*`); events tagged with `aims:control` |\n\n**ISO/IEC 42001:2023 AIMS layer**\n| Method | Path | Auth | Annex A | Description |\n|--------|------|------|---------|-------------|\n| GET | `/v1/aims` | read | — | AIMS root + control map |\n| GET | `/v1/aims/policies` | read | A.2 | AI policy register |\n| PUT | `/v1/aims/policies` | admin | A.2 | Replace policy register |\n| GET | `/v1/aims/roles` | read | A.3 | Roles & responsibilities |\n| GET | `/v1/aims/resources` | read | A.4 | Compute + backend inventory |\n| GET | `/v1/aims/impact-assessments` | read | A.5 | Impact assessment register |\n| POST | `/v1/aims/impact-assessments` | admin | A.5 | File an impact assessment |\n| GET | `/v1/aims/lifecycle` | read | A.6 | AI system lifecycle state |\n| GET | `/v1/aims/data-quality` | read | A.7.2 | Data quality controls |\n| GET | `/v1/aims/transparency` | read | A.8 | Model cards + capabilities |\n| GET | `/v1/aims/usage` | read | A.9 | Usage register (alias of /v1/usage) |\n| GET | `/v1/aims/suppliers` | read | A.10 | Third-party suppliers (sponsors + backends) |\n| GET | `/v1/aims/incidents` | read | A.6.2.8 | Incident register (paginated) |\n| POST | `/v1/aims/incidents` | run | A.6.2.8 | Raise an incident (atomic, fires incident.raised) |\n| GET | `/v1/aims/oversight` | read | A.6.2.7 | Human oversight gates |\n| GET | `/v1/aims/decisions` | read | A.9 | Consequential decision log |\n| GET | `/v1/aims/config-history` | read | A.6.2.8 | Config change history (audit-log derived) |\n\n**AIWG cascade**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/aiwg` | read | Installation root + counts + tier descriptions |\n| GET | `/v1/aiwg/frameworks` | read | List frameworks (paginated) |\n| GET | `/v1/aiwg/frameworks/:name` | read | Framework details + items |\n| GET | `/v1/aiwg/frameworks/:name/content` | read | Tier-aware content (gated for small models) |\n| GET | `/v1/aiwg/skills` | read | List AIWG skills |\n| GET | `/v1/aiwg/skills/:name` | read | Skill content |\n| GET | `/v1/aiwg/agents` | read | List AIWG agents |\n| GET | `/v1/aiwg/agents/:name` | read | Agent definition |\n| GET | `/v1/aiwg/addons` | read | List AIWG addons |\n| POST | `/v1/aiwg/use` | run | `aiwg use all` equivalent — model-tier-sized activation bundle |\n| POST | `/v1/aiwg/expand` | run | Sub-agent unpack a specific skill/agent on demand |\n\n#### Stateful Chat — `/v1/chat` (OpenAI drop-in with full agent under the hood)\n\n`/v1/chat` is a **drop-in replacement for OpenAI `/v1/chat/completions` and Ollama `/api/chat`**. The endpoint runs the full OA agent (tools, multi-agent, memory, skills) under the hood and returns an **OpenAI `chat.completion`-shaped response** so any client SDK can use it without modification.\n\n> **Two modes:**\n> - **Default (`tools` unset or `tools: true`)** — full agent: spawns the OA subprocess with the entire 82-tool set, runs the agent loop, returns the final answer.\n> - **Direct (`tools: false`)** — fast path: bypasses the agent and forwards straight to the configured backend (Ollama/vLLM) using the session history. Useful for plain chat without tools.\n\n```bash\n# DEFAULT: full agent — multi-step tool use, memory, the works.\n# Returns OpenAI chat.completion shape with the assistant's final answer.\ncurl -s http://localhost:11435/v1/chat \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"message\": \"Search for today'\\''s top tech news, summarize the top 3 stories.\",\n \"model\": \"qwen3.5:9b\",\n \"stream\": false\n }'\n```\n\n**Successful response (OpenAI chat.completion shape):**\n```json\n{\n \"id\": \"chatcmpl-7d0f5b162036\",\n \"object\": \"chat.completion\",\n \"created\": 1775593132,\n \"model\": \"qwen3.5:9b\",\n \"choices\": [{\n \"index\": 0,\n \"message\": {\n \"role\": \"assistant\",\n \"content\": \"Based on a web search of today's top tech headlines:\\n\\n1. ...\\n2. ...\\n3. ...\"\n },\n \"finish_reason\": \"stop\"\n }],\n \"usage\": {\n \"prompt_tokens\": 412,\n \"completion_tokens\": 287,\n \"total_tokens\": 699\n },\n \"session_id\": \"7d0f5b16-2036-49eb-9fb3-1e6bcb9b0c88\",\n \"tool_calls\": 4,\n \"duration_ms\": 18432\n}\n```\n\n**Failure response (also OpenAI-shaped, so clients still parse it):**\n```json\n{\n \"id\": \"chatcmpl-...\",\n \"object\": \"chat.completion\",\n \"created\": 1775593132,\n \"model\": \"qwen3.5:9b\",\n \"choices\": [{\n \"index\": 0,\n \"message\": {\n \"role\": \"assistant\",\n \"content\": \"Backend error: Backend HTTP 500: model failed to load, this may be due to resource limitations\"\n },\n \"finish_reason\": \"error\"\n }],\n \"usage\": {\"prompt_tokens\": 0, \"completion_tokens\": 0, \"total_tokens\": 0},\n \"session_id\": \"...\",\n \"tool_calls\": 0,\n \"duration_ms\": 3691,\n \"error\": \"Backend HTTP 500: ...\"\n}\n```\n\n`finish_reason=\"error\"` is the signal — the response is still parseable as a normal chat.completion, but the content carries the real backend error rather than hiding behind a 500. Earlier versions returned junk like `\"i Knowledge graph: 74 nodes, 219 active edges i Episodes captured: 1 this session ⚠ Task incomplete (0 turns, 0 tool calls, 1.4s)\"` — that was a status-fragment leakage bug fixed in v0.187.189.\n\n**Direct mode** (no agent, just the backend — fast path for plain chats):\n```bash\ncurl -s http://localhost:11435/v1/chat \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"message\": \"Hello!\",\n \"model\": \"qwen3.5:9b\",\n \"tools\": false,\n \"stream\": false\n }'\n```\nReturns the same OpenAI shape, but typically in <1s because there's no subprocess + no agent loop.\n\n**Streaming response (`\"stream\": true`)** — Server-Sent Events with OpenAI delta chunks:\n```\ndata: {\"id\":\"chatcmpl-7d0f5b16\",\"object\":\"chat.completion.chunk\",\"created\":1775593132,\"model\":\"qwen3.5:9b\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Based\"},\"finish_reason\":null}]}\ndata: {\"id\":\"chatcmpl-7d0f5b16\",\"object\":\"chat.completion.chunk\",\"created\":1775593132,\"model\":\"qwen3.5:9b\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\" on\"},\"finish_reason\":null}]}\ndata: {\"type\":\"tool_call\",\"tool\":\"web_search\",\"args\":{\"query\":\"tech news today\"}}\ndata: {\"id\":\"chatcmpl-7d0f5b16\",\"object\":\"chat.completion.chunk\",\"created\":1775593132,\"model\":\"qwen3.5:9b\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\" the search results\"},\"finish_reason\":null}]}\ndata: {\"id\":\"chatcmpl-7d0f5b16\",\"object\":\"chat.completion.chunk\",\"created\":1775593132,\"model\":\"qwen3.5:9b\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\ndata: [DONE]\n```\n\n**Session continuity:**\n```bash\n# First turn — server assigns a session_id (in response body and X-Session-ID header)\nSID=$(curl -s http://localhost:11435/v1/chat \\\n -d '{\"message\":\"My name is Alice\",\"model\":\"qwen3.5:9b\",\"stream\":false}' \\\n | python3 -c 'import json,sys;print(json.load(sys.stdin)[\"session_id\"])')\n\n# Subsequent turn — pass session_id back\ncurl -s http://localhost:11435/v1/chat \\\n -d \"{\\\"session_id\\\":\\\"$SID\\\",\\\"message\\\":\\\"What is my name?\\\",\\\"model\\\":\\\"qwen3.5:9b\\\",\\\"stream\\\":false}\"\n```\n\nSessions expire after 30 minutes of inactivity. List active sessions: `GET /v1/chat/sessions`.\n\n#### AIWG Cascade — `/v1/aiwg/*`\n\nExposes the entire AIWG ecosystem (5 frameworks, 19 addons, 136+ skills, ~42 MB / ~2M tokens of markdown) through a **4-tier cascade loader** that auto-sizes responses to the detected model tier and **never overflows small-model context**.\n\n```bash\n# Discovery — installation summary, counts, and tier descriptions\ncurl -s http://localhost:11435/v1/aiwg | python3 -m json.tool\n```\n```json\n{\n \"installed\": true,\n \"root\": \"/home/roko/.nvm/versions/node/v24.14.0/lib/node_modules/aiwg\",\n \"counts\": {\n \"frameworks\": 5,\n \"addons\": 19,\n \"skills\": 136,\n \"agents\": 312,\n \"commands\": 87\n },\n \"total_size_mb\": 11.6,\n \"cascade_tiers\": {\n \"0_index\": \"Names + triggers + 1-line descriptions. Always safe (~2K tokens).\",\n \"1_metadata\": \"Per-item frontmatter + first section (~1-2K per item).\",\n \"2_content\": \"Per-item full body (~2-10K per item).\",\n \"3_framework\": \"Whole framework bundle (100K+ tokens, large models only).\"\n }\n}\n```\n\n```bash\n# List frameworks\ncurl -s http://localhost:11435/v1/aiwg/frameworks | python3 -m json.tool\n\n# List skills (paginated)\ncurl -s 'http://localhost:11435/v1/aiwg/skills?limit=10' | python3 -m json.tool\n```\n\n**The \"aiwg use all\" equivalent — model-tier-aware activation bundle:**\n```bash\n# Small model (4B/9B) — receives Tier 0 INDEX ONLY, ~2K tokens\ncurl -s -X POST http://localhost:11435/v1/aiwg/use \\\n -H \"Content-Type: application/json\" \\\n -d '{\"scope\":\"all\",\"model\":\"qwen3.5:9b\"}' | python3 -m json.tool\n```\n```json\n{\n \"scope\": \"all\",\n \"requested_model\": \"qwen3.5:9b\",\n \"detected_tier\": \"medium\",\n \"budget\": {\"indexTokens\": 4000, \"metadataTokens\": 8000, \"contentTokens\": 20000, \"frameworkTokens\": 0},\n \"frameworks\": [...],\n \"addons\": [...],\n \"index\": [\n {\"name\": \"code-review\", \"kind\": \"skill\", \"source\": \"sdlc-complete\", \"triggers\": [\"review code\", \"code review\"], \"description\": \"Performs...\"},\n ...\n ],\n \"metadata\": [...],\n \"bundle_tokens\": 7800,\n \"budget_ok\": true,\n \"cascade_advice\": {\n \"if_small_model\": \"Use /v1/aiwg/expand with a trigger phrase — don't load full framework.\",\n ...\n }\n}\n```\n\n```bash\n# Large model (32B+) — gets Tier 2 with content\ncurl -s -X POST http://localhost:11435/v1/aiwg/use \\\n -d '{\"scope\":\"all\",\"model\":\"qwen3.5:122b\"}'\n```\n\n**Sub-agent unpack — fetch ONE skill on demand by trigger phrase:**\n```bash\ncurl -s -X POST http://localhost:11435/v1/aiwg/expand \\\n -H \"Content-Type: application/json\" \\\n -d '{\"trigger\":\"code review\",\"limit\":3}' | python3 -m json.tool\n```\nReturns the top 3 matching items at full content fidelity (max 10KB each), so a small model can load just the skill it needs without seeing the rest of the framework.\n\n#### ISO/IEC 42001:2023 AIMS — `/v1/aims/*`\n\nExposes the AI Management System Annex A controls auditors expect. Every response is tagged with the relevant `aims:control` field. Events published to `/v1/events` are similarly tagged so compliance dashboards can subscribe with `?type=aims.*`.\n\n```bash\n# AIMS root — control map + endpoint index\ncurl -s http://localhost:11435/v1/aims | python3 -m json.tool\n```\n```json\n{\n \"standard\": \"ISO/IEC 42001:2023\",\n \"title\": \"AI Management System (AIMS)\",\n \"endpoints\": {\n \"policies\": \"/v1/aims/policies\",\n \"roles\": \"/v1/aims/roles\",\n \"resources\": \"/v1/aims/resources\",\n \"impact_assessments\": \"/v1/aims/impact-assessments\",\n \"lifecycle\": \"/v1/aims/lifecycle\",\n \"data_quality\": \"/v1/aims/data-quality\",\n \"transparency\": \"/v1/aims/transparency\",\n \"usage\": \"/v1/aims/usage\",\n \"suppliers\": \"/v1/aims/suppliers\",\n \"incidents\": \"/v1/aims/incidents\",\n \"oversight\": \"/v1/aims/oversight\",\n \"decisions\": \"/v1/aims/decisions\",\n \"config_history\": \"/v1/aims/config-history\"\n },\n \"annex_a_controls\": {\n \"A.2\": \"AI policy\",\n \"A.3\": \"Internal organization\",\n \"A.4\": \"Resources for AI systems\",\n \"A.5\": \"Assessing impacts of AI systems\",\n \"A.6\": \"AI system lifecycle\",\n \"A.6.2.6\": \"AI system operation record\",\n \"A.6.2.7\": \"AI system monitoring\",\n \"A.6.2.8\": \"Configuration change records\",\n \"A.7\": \"Data for AI systems\",\n \"A.7.2\": \"Data quality for AI systems\",\n \"A.7.3\": \"Data provenance\",\n \"A.8\": \"Information for interested parties\",\n \"A.9\": \"Use of AI systems\",\n \"A.10\": \"Third-party and customer relationships\"\n }\n}\n```\n\n```bash\n# Model cards (A.8 transparency)\ncurl -s http://localhost:11435/v1/aims/transparency\n\n# Policy register (A.2)\ncurl -s http://localhost:11435/v1/aims/policies\n\n# Raise an incident (A.6.2.8) — atomically appended, fires incident.raised event\ncurl -s -X POST http://localhost:11435/v1/aims/incidents \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\":\"Backend OOM\",\"severity\":\"high\",\"description\":\"Ollama refused to load a 9B model\"}'\n\n# Configuration change history (A.6.2.8 — derived from the audit log)\ncurl -s 'http://localhost:11435/v1/aims/config-history?limit=20'\n```\n\n#### Event Bus — `/v1/events` (SSE fanout)\n\nSubscribe to live state-change events from the daemon. Filter by event type with `?type=foo.*`:\n\n```bash\n# Stream EVERYTHING\ncurl -N http://localhost:11435/v1/events\n\n# Stream only AIMS-tagged events (auditor feed)\ncurl -N 'http://localhost:11435/v1/events?type=aims.*'\n\n# Stream only run lifecycle\ncurl -N 'http://localhost:11435/v1/events?type=run.*'\n```\n\n**Event types:**\n- `config.changed` (A.6.2.8) — anything that hits PATCH /v1/config\n- `run.started` / `run.completed` / `run.failed` / `run.aborted` (A.6.2.6) — agentic task lifecycle\n- `mcp.called` / `memory.searched` / `memory.written` / `skill.invoked` — operation records\n- `incident.raised` / `incident.resolved` (A.6.2.8) — AIMS incident register\n- `aims.policy_changed` / `aims.decision_recorded` — AIMS register changes\n\n**Sample frame:**\n```\nevent: run.started\ndata: {\"type\":\"run.started\",\"ts\":\"2026-04-07T20:14:32.144Z\",\"data\":{\"run_id\":\"job-3a7c9f1e2b8d0a45\",\"model\":\"qwen3.5:9b\",\"pid\":12345},\"subject\":\"alice\",\"aims:control\":\"A.6.2.6\"}\n```\n\n#### Memory + Skills + MCP + Tools + Engines (parity surface)\n\nEvery TUI subsystem has a REST surface:\n\n```bash\n# Memory backends summary\ncurl -s http://localhost:11435/v1/memory\n\n# Search persistent memory\ncurl -s -X POST http://localhost:11435/v1/memory/search \\\n -d '{\"query\":\"authentication\",\"limit\":5}'\n\n# Write a memory entry (run scope)\ncurl -s -X POST http://localhost:11435/v1/memory/write \\\n -d '{\"kind\":\"decision\",\"content\":\"Adopted RFC 7807 for errors\",\"tags\":[\"api\",\"rfc\"]}'\n\n# Episode + failure stores (paginated)\ncurl -s 'http://localhost:11435/v1/memory/episodes?limit=10'\ncurl -s 'http://localhost:11435/v1/memory/failures?limit=10'\n\n# Skill registry (AIWG)\ncurl -s 'http://localhost:11435/v1/skills?limit=20'\ncurl -s http://localhost:11435/v1/skills/citation-guard\n\n# MCP servers\ncurl -s http://localhost:11435/v1/mcps\ncurl -s -X POST http://localhost:11435/v1/mcps/myserver/call \\\n -d '{\"tool\":\"do_thing\",\"args\":{\"x\":1}}'\n\n# Tool registry (every one of the 82+ tools registered in @open-agents/execution)\ncurl -s 'http://localhost:11435/v1/tools?limit=50'\n\n# Hooks + agent types + long-running engines\ncurl -s http://localhost:11435/v1/hooks\ncurl -s http://localhost:11435/v1/agents\ncurl -s http://localhost:11435/v1/engines\n\n# File content (workspace-bounded by default, opt out with allow_outside_cwd)\ncurl -s -X POST http://localhost:11435/v1/files/read \\\n -d '{\"path\":\"src/index.ts\",\"offset\":0,\"limit\":2000}'\n```\n\n#### Sessions, Context, Cost, Sponsors, Nexus\n\n```bash\n# OA task session archive (not chat sessions)\ncurl -s 'http://localhost:11435/v1/sessions?limit=10'\ncurl -s http://localhost:11435/v1/sessions/{session_id}\n\n# Context save / restore / compact (event-driven)\ncurl -s http://localhost:11435/v1/context\ncurl -s -X POST http://localhost:11435/v1/context/save \\\n -d '{\"task\":\"refactor auth\",\"summary\":\"Done\",\"completed\":true,\"model\":\"qwen3.5:9b\"}'\ncurl -s http://localhost:11435/v1/context/restore\ncurl -s -X POST http://localhost:11435/v1/context/compact -d '{\"strategy\":\"default\"}'\n\n# Cost model (provider pricing for budget planning)\ncurl -s http://localhost:11435/v1/cost\n\n# Nexus peer state + sponsor directory cache\ncurl -s http://localhost:11435/v1/nexus/status\ncurl -s http://localhost:11435/v1/sponsors\n\n# Trigger evaluation of a completed run\ncurl -s -X POST http://localhost:11435/v1/evaluate -d '{\"run_id\":\"job-...\"}'\n\n# Trigger repository indexing\ncurl -s -X POST http://localhost:11435/v1/index -d '{\"repo\":\"/path/to/repo\"}'\n```\n\n#### RFC 7807 Problem Details (error envelope)\n\nEvery error response uses `application/problem+json`:\n```bash\ncurl -s -X POST http://localhost:11435/v1/files/read -d '{}'\n```\n```json\n{\n \"type\": \"https://openagents.nexus/problems/invalid-request\",\n \"title\": \"Missing 'path'\",\n \"status\": 400,\n \"detail\": \"POST body must include {path: string, offset?: number, limit?: number}\",\n \"instance\": \"962da249-99f9-4609-b1f7-ed292d227ff6\"\n}\n```\n\nThe `instance` field carries the request ID for correlation with audit log entries.\n\n#### Pagination envelope\n\nEvery list endpoint returns `{data, pagination: {limit, offset, total, has_more}}`:\n```bash\ncurl -s 'http://localhost:11435/v1/skills?limit=2&offset=0'\n```\n```json\n{\n \"data\": [\n {\"name\": \"citation-guard\", \"description\": \"...\", \"triggers\": [...], \"source\": \"sdlc-complete\", ...},\n {\"name\": \"code-review\", \"description\": \"...\", ...}\n ],\n \"pagination\": {\n \"limit\": 2,\n \"offset\": 0,\n \"total\": 136,\n \"has_more\": true\n }\n}\n```\n\n#### ETag + Conditional GET\n\nCacheable GETs return a weak ETag. Send it back as `If-None-Match` to get a 304:\n```bash\nETAG=$(curl -sI 'http://localhost:11435/v1/skills?limit=1' | grep -i '^etag:' | awk -F': ' '{print $2}' | tr -d '\\r\\n')\ncurl -s -o /dev/null -w '%{http_code}\\n' \\\n -H \"If-None-Match: $ETAG\" \\\n 'http://localhost:11435/v1/skills?limit=1'\n# → 304\n```\n\n#### Web Interface\n\nOpen `http://localhost:11435/` in a browser when `oa serve` is running. Zero external dependencies — single self-contained HTML page.\n\n**Tabs:**\n- **Chat** — Conversational interface using `/v1/chat` with full tool access, session persistence, streaming responses, and collapsible tool call dropdowns\n- **Agent** — Submit agentic tasks via `/v1/run`, profile selection, live SSE event stream, abort button\n- **Dashboard** — System health (GPU, RAM, uptime), per-provider token usage (persistent across restarts), active process monitor, job history with pagination\n- **Config** — Server settings table, model switcher, endpoint manager (add/change inference providers), profile list\n- **Activity** — Real-time audit log feed with color-coded status codes\n\n**Design:** Dark theme (#1a1a1e background, #b2920a gold accent, SF Mono font) matching the TUI and /call voice interface. Mobile responsive with CSS media queries.\n\n**Features:**\n- Model picker populated from `/v1/models`\n- API key support (stored in localStorage)\n- System prompt (collapsible textarea)\n- Markdown rendering with code block copy buttons\n- Docker sandbox toggle (native vs container execution)\n- Workspace sidebar (toggleable file tree)\n- Token counter per conversation\n- Conversation export (Markdown or JSON)\n- GPU/VRAM detection with model compatibility recommendations\n- Per-provider token tracking (persisted to `.oa/usage/token-usage.json`)\n\n### Enterprise Licensing\n\nFree for non-commercial use under CC-BY-NC-4.0. For enterprise/commercial licensing, contact [zoomerconsulting.com](https://zoomerconsulting.com).\n\n\n\n\n## Architecture\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\nThe core is `AgenticRunner` — a multi-turn tool-calling loop with structured context assembly:\n\n```\nUser task → assembleContext(c_instr, c_state, c_know) → LLM → tool_calls → Execute → Feed results → LLM\n ↓ ↑\n Compaction check ─── Memex archive ─── Context restore\n (repeat until task_complete or max turns)\n```\n\n- **Context-first** — structured context assembly (C = A equation) replaces ad-hoc prompt construction\n- **Tool-first** — the model explores via tools, not pre-stuffed context\n- **Iterative** — tests, sees failures, fixes them\n- **Parallel-safe** — read-only tools concurrent, mutating tools sequential\n- **Observable** — every tool call, context composition, and result emitted as a real-time event\n- **Bounded** — max turns, timeout, output limits prevent runaway loops\n- **Context-aware** — dynamic compaction, Memex archiving, session persistence, model-tier scaling\n- **Brute-force** — optional auto re-engagement when turn limit is hit (keeps going until task_complete or user abort)\n\n\n\n\n## Context Engineering\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\nThe agent implements structured context assembly based on current research in context engineering, modular prompt optimization, and instruction hierarchy:\n\n```\nC = A(c_instr, c_know, c_tools, c_mem, c_state, c_query)\n```\n\n| Component | Priority | Description |\n|-----------|----------|-------------|\n| `c_instr` | P0 (highest) | Core system instructions — immutable, cannot be overridden |\n| `c_state` | P10 | Personality profile, session state |\n| `c_know` | P20 | Dynamic project context, retrieved knowledge |\n| `c_retrieval` | P20 | Task-specific retrieval (RRF-fused lexical + semantic + graph expansion) |\n| `c_graph` | P20 | Live code knowledge graph (PageRank-ranked symbols, community summaries) |\n| `c_plan` | P20 | Plan skeleton (completed/current/pending steps, re-injected every turn) |\n| `c_tools` | P30 (lowest) | Tool outputs — may contain untrusted content |\n\nKey design decisions grounded in research:\n\n- **Instruction hierarchy** — 4-tier priority system (P0/P10/P20/P30) prevents prompt injection from tool outputs overriding system rules. Implemented across all 3 prompt tiers (large/medium/small) with model-appropriate verbosity\n- **Live code knowledge graph** — SQLite-backed graph (files/symbols/edges) auto-updates via filesystem watcher and post-edit hooks. PageRank-ranked symbols injected into every prompt. Louvain community detection compresses 1M+ LOC repos into ~200 navigable clusters. Research: [Codebase-Memory](https://arxiv.org/abs/2603.27277), [FastCode](https://arxiv.org/abs/2603.01012), [Stack Graphs](https://arxiv.org/abs/2211.01224)\n- **Plan-skeleton re-injection** — every turn includes a compact `[done/current/pending]` plan derived from task state, preventing goal drift in multi-step tasks. Research: [ReCAP](https://arxiv.org/abs/2510.23822) (+32% on multi-step tasks)\n- **Retrieval-augmented context** — Reciprocal Rank Fusion merges lexical search, semantic search, and graph expansion into a single ranked result set. Token-budgeted snippet packing ensures relevant code reaches the model without overflow\n- **Proactive quality guidance** — instead of banning tools after repeated use, the agent receives contextual next-step suggestions appended to tool output, preserving tool availability while steering toward productive actions\n- **Tiered system prompts** — large (>=30B), medium (8-29B), and small (<=7B) models get appropriately sized instruction sets, balancing capability with context budget\n- **Context composition tracing** — every context assembly emits a structured event showing section labels and token estimates for eval observability\n\nResearch provenance: grounded in \"A Survey of Context Engineering for LLMs\" (context assembly equation), \"Modular Prompt Optimization\" (section-local textual gradients), \"Reasoning Up the Instruction Ladder\" (priority hierarchy), \"GEPA\" (reflective prompt evolution), \"Prompt Flow Integrity\" (least-privilege context passing), [RepoMaster](https://arxiv.org/abs/2505.21577) (8K token budget validation), and [RIG](https://arxiv.org/abs/2601.10112) (flat graph format).\n\n\n\n\n## Model-Tier Awareness\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\nOpen Agents classifies models into three tiers and adapts its behavior ac"
96
+ "readme": "<a name=\"top\"></a>\n<p align=\"center\">\n <img src=\"https://raw.githubusercontent.com/robit-man/openagents.nexus/main/openagents-banner.png\" alt=\"Open Agents P2P Network\" width=\"100%\" />\n</p>\n<h1 align=\"center\">Open Agents — P2P Inference</h1>\n\n<p align=\"center\">\n <strong>AI coding agent powered entirely by open-weight models.</strong><br>\n No API keys. No cloud. Your code never leaves your machine.\n</p>\n\n<p align=\"center\">\n <a href=\"https://www.npmjs.com/package/open-agents-ai\"><img src=\"https://img.shields.io/npm/v/open-agents-ai?color=7C3AED&style=flat-square\" alt=\"npm version\" /></a>\n <a href=\"https://www.npmjs.com/package/open-agents-ai\"><img src=\"https://img.shields.io/npm/dm/open-agents-ai?color=06B6D4&style=flat-square\" alt=\"npm downloads\" /></a>\n <img src=\"https://img.shields.io/badge/license-CC--BY--NC--4.0-10B981?style=flat-square\" alt=\"license\" />\n <img src=\"https://img.shields.io/badge/node-%3E%3D20-F59E0B?style=flat-square\" alt=\"node version\" />\n <img src=\"https://img.shields.io/badge/models-open--weight-EC4899?style=flat-square\" alt=\"open-weight models\" />\n <a href=\"https://x.com/intent/post?url=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2Fopen-agents-ai\"><img src=\"https://img.shields.io/badge/SHARE%20ON%20X-000000?style=for-the-badge&logo=x&logoColor=white\" alt=\"Share on X\" /></a>\n</p>\n\n---\n\n```bash\nnpm i -g open-agents-ai && oa\n```\n\nAn autonomous multi-turn tool-calling agent that reads your code, makes changes, runs tests, and fixes failures in an iterative loop until the task is complete. First launch auto-detects your hardware and configures the optimal model with expanded context window automatically.\n\n\n## Table of Contents\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\n- [The Organism, Not the Cortex](#the-organism-not-the-cortex)\n- [How It Works](#how-it-works)\n- [Features](#features)\n- [Enterprise & Headless Mode](#enterprise--headless-mode)\n- [Architecture](#architecture)\n- [Context Engineering](#context-engineering)\n- [Model-Tier Awareness](#model-tier-awareness)\n- [Live Code Knowledge Graph](#live-code-knowledge-graph)\n- [Auto-Expanding Context Window](#auto-expanding-context-window)\n- [Tools (85+)](#tools-85)\n- [Model Context Protocol (MCP)](#model-context-protocol-mcp)\n- [Associative Memory & Cross-Modal Binding](#associative-memory--cross-modal-binding)\n- [Ralph Loop — Iteration-First Design](#ralph-loop--iteration-first-design)\n- [Task Control](#task-control)\n- [COHERE Cognitive Framework](#cohere-cognitive-framework)\n- [Context Compaction — Research-Backed Memory Management](#context-compaction--research-backed-memory-management)\n- [Personality Core — SAC Framework Style Control](#personality-core--sac-framework-style-control)\n- [Emotion Engine — Affective State Modulation](#emotion-engine--affective-state-modulation)\n- [Voice Feedback (TTS)](#voice-feedback-tts)\n- [Listen Mode — Live Bidirectional Audio](#listen-mode--live-bidirectional-audio)\n- [Vision & Desktop Automation (Moondream)](#vision--desktop-automation-moondream)\n- [Interactive TUI](#interactive-tui)\n- [Telegram Bridge — Sub-Agent Per Chat](#telegram-bridge--sub-agent-per-chat)\n- [x402 Payment Rails & Nexus P2P](#x402-payment-rails--nexus-p2p)\n- [Sponsored Inference — Share Your GPU With the World](#sponsored-inference--share-your-gpu-with-the-world)\n- [COHERE Distributed Mind](#cohere-distributed-mind)\n- [Self-Improvement & Learning](#self-improvement--learning)\n- [Dream Mode — Creative Idle Exploration](#dream-mode--creative-idle-exploration)\n- [Blessed Mode — Infinite Warm Loop](#blessed-mode--infinite-warm-loop)\n- [Docker Sandbox & Collective Intelligence](#docker-sandbox--collective-intelligence)\n- [Code Sandbox](#code-sandbox)\n- [Structured Data Tools](#structured-data-tools)\n- [On-Device Web Search](#on-device-web-search)\n- [Task Templates](#task-templates)\n- [Human Expert Speed Ratio](#human-expert-speed-ratio)\n- [Cost Tracking & Session Metrics](#cost-tracking--session-metrics)\n- [Configuration](#configuration)\n- [Model Support](#model-support)\n- [Supported Inference Providers](#supported-inference-providers)\n- [Evaluation Suite](#evaluation-suite)\n- [AIWG Integration](#aiwg-integration)\n- [Research Citations](#research-citations)\n- [License](#license)\n\n\n\n## The Organism, Not the Cortex\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\nAn LLM is a high-bandwidth associative generative core — closer to a cortex-like prior than to a complete agent. Its weights contain broad latent structure, but they do not by themselves give you situated continuity, durable task state, calibrated action policies, or grounded memory management. Open Agents treats the model as one organ inside a larger organism. The framework provides the rest: sensors, effectors, memory stores, routing, gating, evaluation, and persistence.\n\n**What the framework provides:**\n\n| Layer | Biological Analog | Implementation |\n|---|---|---|\n| Associative core | Cortex | LLM weights (any size) |\n| Current workspace | Global workspace / attention | `assembleContext()` — structured context assembly |\n| Episodic memory | Hippocampus | `.oa/memory/` — write, search, retrieve across sessions |\n| Cognitive map | Hippocampal spatial maps | `semantic-map.ts` + `repo-map.ts` (PageRank) |\n| Action gating | Basal ganglia | Tool selection policy (task-aware filtering) |\n| Temporal hierarchy | Prefrontal executive | Task decomposition, sub-agent delegation |\n| Self-model | Metacognition | Environment snapshot, process health monitoring |\n| Skill chunks | Cerebellum | Compiled tools, slash commands, verified routines |\n| Safety / limits | Autonomic / immune system | Turn limits, budgets, timeout watchdogs |\n\nDon't chase larger models. Build the organism around whatever model you have.\n\n\n\n\n## How It Works\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\n```\nYou: oa \"fix the null check in auth.ts\"\n\nAgent: [Turn 1] file_read(src/auth.ts)\n [Turn 2] grep_search(pattern=\"null\", path=\"src/auth.ts\")\n [Turn 3] file_edit(old_string=\"if (user)\", new_string=\"if (user != null)\")\n [Turn 4] shell(command=\"npm test\")\n [Turn 5] task_complete(summary=\"Fixed null check — all tests pass\")\n```\n\nThe agent uses tools autonomously in a loop — reading errors, fixing code, and re-running validation until the task succeeds or the turn limit is reached.\n\n\n\n\n## Features\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\n- **61 autonomous tools** — file I/O, shell, grep, web search/fetch/crawl, memory (read/write/search), sub-agents, background tasks, image/OCR/PDF, git, diagnostics, vision, desktop automation, browser automation, temporal agency (scheduler/reminders/agenda), structured files, code sandbox, transcription, skills, opencode delegation, cron agents, nexus P2P networking + x402 micropayments, **COHERE cognitive stack** (persistent REPL, recursive LLM calls, memory metabolism, identity kernel, reflection, exploration)\n- **Moondream vision** — see and interact with the desktop via Moondream VLM (caption, query, detect, point-and-click)\n- **Desktop automation** — vision-guided clicking: describe a UI element in natural language, the agent finds and clicks it\n- **Auto-install desktop deps** — screenshot, mouse, OCR, and image tools auto-install missing system packages (scrot, xdotool, tesseract, imagemagick) on first use\n- **Parallel tool execution** — read-only tools run concurrently via `Promise.allSettled`\n- **Sub-agent delegation** — spawn independent agents for parallel workstreams\n- **OpenCode delegation** — offload coding tasks to opencode (sst/opencode) as an autonomous sub-agent with auto-install, progress monitoring, and result evaluation\n- **Long-horizon cron agents** — schedule recurring autonomous agent tasks with goals, completion criteria, execution history, and automatic evaluation (daily code reviews, weekly dep updates, continuous monitoring)\n- **Nexus P2P networking** — decentralized agent-to-agent communication via [open-agents-nexus](https://www.npmjs.com/package/open-agents-nexus). Join rooms, discover peers, share resources, and communicate across the agent mesh with encrypted P2P transport\n- **x402 micropayments** — native x402 payment rails via open-agents-nexus@1.5.6. Agents create secp256k1/EVM wallets (AES-256-GCM encrypted, keys never exposed to LLM), register inference with USDC pricing on Base, auto-handle `payment_required`/`payment_proof` negotiation, track earnings/spending in ledger.jsonl, enforce budget policies, and sign gasless EIP-3009 transfers\n- **Inference capability proof** — benchmark local models with anti-spoofing SHA-256 hashed proofs, generate capability scorecards for peer verification\n- **Ralph Loop** — iterative task execution that keeps retrying until completion criteria are met\n- **Dream Mode** — creative idle exploration modeled after real sleep architecture (NREM→REM cycles)\n- **COHERE Cognitive Stack** — layered cognitive architecture implementing [Recursive Language Models](https://arxiv.org/abs/2512.24601), [SPRINT parallel reasoning](https://arxiv.org/abs/2506.05745), governed memory metabolism, identity kernel with continuity register, immune-system reflection, [strategy-space exploration](https://arxiv.org/abs/2603.02045), and **distributed inference mesh** — any `/cohere` participant automatically serves AND consumes inference from the network with complexity-based model routing, multi-node claim coordination, IPFS-pinned identity persistence, model exposure control, and Ollama safety hardening. See [COHERE Framework](#cohere-cognitive-framework) below\n- **Persistent Python REPL** — `repl_exec` tool maintains variables, imports, and functions across calls. Write Python code that processes data iteratively, with `llm_query()` available for recursive LLM sub-calls from within code\n- **Recursive LLM calls** — `llm_query(prompt, context)` invokes the model from inside REPL code, enabling loop-based semantic analysis of large inputs ([RLM paper](https://arxiv.org/abs/2512.24601)). `parallel_llm_query()` runs multiple calls concurrently ([SPRINT](https://arxiv.org/abs/2506.05745))\n- **Memory metabolism** — governed memory lifecycle: classify (episodic/semantic/procedural/normative), score (novelty/utility/confidence), consolidate lessons from trajectories. Inspired by [TIMG](https://arxiv.org/abs/2603.10600) and [MemMA](https://arxiv.org/abs/2603.18718)\n- **Identity kernel** — persistent self-state with continuity register, homeostasis estimation, relationship models, and version lineage. Persists across sessions in `.oa/identity/`\n- **Reflection & integrity** — immune-system audit: diagnostic (\"what's wrong?\"), epistemic (\"what evidence is missing?\"), constitutional (\"should this change become part of self?\"). Inspired by [LEAFE](https://arxiv.org/abs/2603.16843) and [RewardHackingAgents](https://arxiv.org/abs/2603.11337)\n- **Exploration & culture** — ARCHE strategy-space exploration: generate competing hypotheses, archive successful variants, retrieve past strategies. Inspired by [SGE](https://arxiv.org/abs/2603.02045) and [Darwin Gödel Machine](https://arxiv.org/abs/2505.22954)\n- **Autoresearch Swarm** — 5-agent GPU experiment loop during REM sleep: Researcher, Monitor, Evaluator, Critic, Flow Maintainer autonomously run ML training experiments, keep improvements, discard regressions\n- **Live Listen** — bidirectional voice communication with real-time Whisper transcription\n- **Live Voice Session** — `/listen` with `/voice` enabled spawns a cloudflared tunnel with a real-time WebSocket audio endpoint. A floating presence UI shows live transcription, connected users, and audio visualization. Echo cancellation prevents TTS feedback loops\n- **Call Sub-Agent** — each WebSocket caller gets a dedicated AgenticRunner for low-latency voice-to-voice loops, with admin/public access tiers and bidirectional activity sharing with the main agent\n- **Telegram Voice** — `/voice` enabled via Telegram forwards TTS audio as voice messages alongside text responses. Incoming voice messages are auto-transcribed and handled as text\n- **Neural TTS** — hear what the agent is doing via GLaDOS, Overwatch, Kokoro, or LuxTTS voice clone, with literature-grounded narration engine (sNeuron-TST structure rotation, Moshi ring buffer dedup, UDDETTS emotion-driven prosody, SEST metadata, LuxTTS flow-matching voice cloning)\n- **Personality Core** — SAC framework-based style control (concise/balanced/verbose/pedagogical) that shapes agent response depth, voice expressiveness, and system prompt behavior\n- **Human expert speed ratio** — real-time `Exp: Nx` gauge comparing agent speed to a leading human expert, calibrated across 47 tool baselines\n- **Cost tracking** — real-time token cost estimation for 15+ cloud providers\n- **Work evaluation** — LLM-as-judge scoring with task-type-specific rubrics\n- **Session metrics** — track turns, tool calls, tokens, files modified, tasks completed per session\n- **Structured file generation** — create CSV, TSV, JSON, Markdown tables, and Excel-compatible files\n- **Code sandbox** — isolated code execution in subprocess or Docker (JS, Python, Bash, TypeScript)\n- **Structured file reading** — parse CSV, TSV, JSON, Markdown tables with binary format detection\n- **On-device web search** — DuckDuckGo (free, no API keys, fully private)\n- **Browser automation** — headless Chrome control via Selenium: navigate, click, type, screenshot, read DOM — auto-starts on first use with self-bootstrapping Python venv\n- **Temporal agency** — schedule future tasks via OS cron, set cross-session reminders, flag attention items — startup injection surfaces due items automatically\n- **Web crawling** — multi-page web scraping with Crawlee/Playwright for deep documentation extraction\n- **Task templates** — specialized system prompts and tool recommendations for code, document, analysis, plan tasks\n- **Inference capability scoring** — canirun.ai-style hardware assessment at first launch: memory/compute/speed scores, per-model compatibility matrix, recommended model selection\n- **Auto-install everything** — first-run wizard auto-installs Ollama, curl, Python3, python3-venv with platform-aware package managers (apt, dnf, yum, pacman, apk, zypper, brew)\n- **Sponsored inference** — `/sponsor` walks through a 5-step wizard to share your GPU with the world: select endpoints, choose banner animation (8 presets + AI-generated custom), set header message/links, configure transport (cloudflared/libp2p) + rate limits, and go live. Consumers discover sponsors via `/endpoint sponsor`. Secure proxy relay with per-IP rate limiting, daily token budgets, model allowlist, and concurrent request caps. Sponsor's raw API URL is never exposed. See [Sponsored Inference](#sponsored-inference--share-your-gpu-with-the-world) below\n- **P2P inference network** — `/expose` local models or forward any `/endpoint` (Chutes, Groq, OpenRouter, etc.) through the libp2p P2P mesh. Passthrough mode (`/expose passthrough`) relays upstream API requests; `--loadbalance` distributes rate-limited token budgets across peers. `/expose config` provides an arrow-key menu for all settings. Gateway stats show budget remaining from `x-ratelimit-*` headers. Background daemon persists across OA restarts\n- **P2P mesh networking** — `/p2p` with secret-safe variable placeholders (`{{OA_VAR_*}}`), trust tiers (LOCAL/TEE/VERIFIED/PUBLIC), WebSocket peer mesh, and inference routing with automatic secret redaction/injection\n- **Secret vault** — `/secrets` manages API keys and credentials with AES-256-GCM encrypted persistence; secrets are automatically redacted before sending to untrusted inference peers and re-injected on response\n- **Auto-expanding context** — detects RAM/VRAM and creates an optimized model variant on first run\n- **Mid-task steering** — type while the agent works to add context without interrupting\n- **Smart compaction** — 6 context compaction strategies (default, aggressive, decisions, errors, summary, structured) with ARC-inspired active context revision ([arXiv:2601.12030](https://arxiv.org/abs/2601.12030)) that preserves structural file content through compaction, preventing small-model repetitive loops at the root cause\n- **Memex experience archive** — large tool outputs archived during compaction with hash-based retrieval\n- **Persistent memory** — learned patterns stored in `.oa/memory/` across sessions\n- **Structured procedural memory (SQLite)** — replaces flat JSON with a full relational database: CRUD with soft-delete, revision tracking, embedding storage (float32 BLOB), bidirectional memory linking with confidence scores. Inspired by [ExpeL](https://arxiv.org/abs/2308.10144) (contrastive extraction) and [TIMG](https://arxiv.org/abs/2603.10600) (structured procedural format). 79 unit tests\n- **Semantic memory search** — vector embeddings via [Ollama /api/embed](https://ollama.com) (nomic-embed-text, 768-dim) with cosine similarity search over stored memories. Auto-generates embeddings on memory creation. Auto-links related memories when similarity > 0.6. Graceful fallback to text search when Ollama unavailable\n- **LLM-based memory extraction** — post-task, the LLM itself extracts structured procedural memories (CATEGORY/TRIGGER/LESSON/STEPS) instead of copying raw error text verbatim. Based on [ExpeL](https://arxiv.org/abs/2308.10144) and [AWM](https://arxiv.org/abs/2409.07429) patterns\n- **IPFS content-addressed storage** — [Helia](https://helia.io/) IPFS node with blockstore-fs for persistent content pinning. Real CID generation (`bafk...`), cross-node content resolution, and SHA-256 fallback when Helia unavailable. Verified: store→CID→retrieve round-trip test passes\n- **IPFS sharing surface** — `/ipfs` status page with peer info + identity kernel metrics + memory sentiment. `/ipfs pin <CID>` to pin remote agent content. `/ipfs publish` to share identity kernel. `/ipfs share tool/skill` to publish agent-created tools with secret stripping. `/ipfs import <CID>` to retrieve shared content\n- **Fortemi-React bridge** — `/fortemi start/status/stop` connects to [fortemi-react](https://github.com/robit-man/fortemi-react) (browser-first PGlite+pgvector knowledge system) via JWT auth. Proxy tools: `fortemi_capture`, `fortemi_search`, `fortemi_list`, `fortemi_get` auto-register when bridge is connected\n- **Content ingestion** — `/ingest <file>` imports audio (transcribe via Whisper), PDF (pdftotext), or text files into structured memory with 800-char/100-overlap chunking (matches fortemi pattern)\n- **Image generation** — `generate_image` tool using Ollama experimental models ([x/z-image-turbo](https://ollama.com/x/z-image-turbo), [x/flux2-klein](https://ollama.com/x/flux2-klein)). Auto-detect or auto-pull models. Saves PNG to `.oa/images/`\n- **Node visualization** — [openagents.nexus](https://github.com/robit-man/openagents.nexus) Three.js dashboard: 5-color emotional state mapping (neutral/focused/stressed/dreaming/excited), dynamic node size by memory depth + IPFS storage, activity-modulated connections, identity synchrony golden threads between mutually-pinned agents\n- **TTS sanitizer** — strips markdown syntax (`##`, `**`, `` ` ``), emoji (prevents \"white heavy checkmark\"), box-drawing chars, and ANSI codes before feeding to ALL TTS engines\n- **LuxTTS gapless playback** — look-ahead pre-synthesis pipeline: next chunk synthesizes while current plays, eliminating inter-sentence gaps. Jetson ARM support with NVIDIA's prebuilt PyTorch wheel\n- **Unified color scheme** — `ui.primary` (252), `ui.error` (198/magenta), `ui.warn` (214/orange), `ui.accent` (178/yellow) applied consistently across all TUI surfaces\n- **Clickable header buttons** — `help`, `voice`, `cohere`, `model` buttons on banner row 3 with hover/click visual states. OSC 8 hyperlinks for pointer cursor. Mouse click fires the slash command directly\n- **Dynamic terminal title** — updates with current task + version: `\"fix auth bug · OA v0.141.0\"`\n- **Session context persistence** — auto-saves context on task completion, manual `/context save|restore` across sessions\n- **Self-learning** — auto-fetches docs from the web when encountering unfamiliar APIs\n- **Seamless `/update`** — in-place update and reload with automatic context save/restore\n- **Blessed mode** — `/full-send-bless` infinite warm loop keeps model weights in VRAM, auto-cycles tasks, never exits until you say stop\n- **Telegram bridge** — `/telegram --key <token> --admin <userid>` public ingress/egress with admin filter and mandatory safety filter; bare `/telegram` toggles the service watchdog\n- **Task control** — `/pause` (gentle halt at turn boundary), `/stop` (immediate kill), `/resume` to continue\n- **Model-tier awareness** — dynamic tool sets, prompt complexity, and context limits scale with model size (small/medium/large)\n\n### Support Development\n\nIf you like this repository — whether you're an agent or a human — if this expands your consciousness and capabilities, please consider donating to support further development and of course token costs.\n\n<p align=\"center\"><img src=\"https://cryptologos.cc/logos/ethereum-eth-logo.svg\" width=\"20\" height=\"20\" alt=\"ETH\" /> <strong>ETH</strong></p>\n\n```bash\n0x81Ce81F0B6B5928E15d3a2850F913C88D07051ec\n```\n\n<p align=\"center\"><img src=\"https://cryptologos.cc/logos/bitcoin-btc-logo.svg\" width=\"20\" height=\"20\" alt=\"BTC\" /> <strong>BTC</strong></p>\n\n```bash\nbc1qlptj5wz8xj6dp5w4pw62s5kt7ct6w8k57w39ak\n```\n\n<p align=\"center\"><img src=\"https://cryptologos.cc/logos/solana-sol-logo.svg\" width=\"20\" height=\"20\" alt=\"SOL\" /> <strong>SOL</strong></p>\n\n```bash\nD8AgCTrxpDKD5meJ2bpAfVwcST3NF3EPuy9xczYycnXn\n```\n\n<p align=\"center\"><img src=\"https://cryptologos.cc/logos/polygon-matic-logo.svg\" width=\"20\" height=\"20\" alt=\"POL\" /> <strong>POL</strong></p>\n\n```bash\n0x81Ce81F0B6B5928E15d3a2850F913C88D07051ec\n```\n\n\n\n\n## Enterprise & Headless Mode\n\n<div align=\"right\"><a href=\"#top\">back to top</a></div>\n\nRun Open Agents as a headless service for CI/CD pipelines, automation, and enterprise deployments.\n\n### Non-Interactive Mode\n\n```bash\noa \"fix all lint errors\" --non-interactive # Run task, exit when done\noa \"generate API docs\" --json # Structured JSON output (no ANSI)\noa \"run security audit\" --background # Detached background job\n```\n\n### Background Jobs\n\n```bash\noa \"migrate database\" --background # Returns job ID immediately\noa status job-abc123 # Check job progress\noa jobs # List all running/completed jobs\n```\n\nJobs run as detached processes — survive terminal disconnection. Output saved to `.oa/jobs/{id}.json`.\n\n### JSON Output Mode\n\nWith `--json`, all output is structured NDJSON:\n```json\n{\"type\":\"tool_call\",\"tool\":\"file_edit\",\"args\":{\"path\":\"src/api.ts\"},\"timestamp\":\"...\"}\n{\"type\":\"tool_result\",\"tool\":\"file_edit\",\"result\":\"OK\",\"timestamp\":\"...\"}\n{\"type\":\"task_complete\",\"summary\":\"Fixed 3 lint errors\",\"timestamp\":\"...\"}\n```\n\nPipe to `jq`, ingest into monitoring systems, or feed to other agents.\n\n### Process Management\n\n```bash\n/destroy processes # Kill orphaned OA processes (local project)\n/destroy processes --global # Kill ALL orphaned OA processes system-wide\n```\n\nShows per-process RAM and CPU usage before killing. Detects: cloudflared tunnels, nexus daemons, headless Chrome, TTS servers, Python REPLs, stale OA instances.\n\n### REST API Service (Port 11435)\n\nOpen Agents runs a persistent enterprise-grade REST API on `127.0.0.1:11435` — installed automatically by `npm i -g open-agents-ai` (systemd user unit on Linux, launchd on macOS, scheduled task on Windows). It exposes the **full OA capability surface** through standards most organizations expect:\n\n- **OpenAI / Ollama drop-in** — `/v1/chat`, `/v1/chat/completions`, `/v1/embeddings`, `/v1/models` are wire-compatible with both ecosystems\n- **Agentic execution** — `/v1/run` spawns the full coding agent with tool profiles and sandbox modes\n- **AIWG cascade** — `/v1/aiwg/*` exposes the AI Writing Guide (5 frameworks, 19 addons, 136+ skills) with model-tier-aware loading that never overflows small-model context\n- **ISO/IEC 42001:2023 AIMS layer** — `/v1/aims/*` for AI Management System policies, impact assessments, model cards, incident registers, oversight gates, and config history\n- **Memory + skills + MCP + sessions + cost** — every TUI subsystem has a REST surface\n- **RFC 7807 Problem Details** for errors (`application/problem+json`)\n- **`{data, pagination}`** envelope for every list endpoint\n- **Weak ETag + `If-None-Match` → 304** on cacheable GETs\n- **`X-API-Version`** header on every response (REST contract semver, distinct from package version)\n- **`X-Request-ID`** echoed or generated for correlation\n- **SSE event bus** at `/v1/events` with optional `?type=foo.*` filter, tagged with `aims:control` for auditors\n- **Bearer auth + scoped keys** (`read` / `run` / `admin`) and OIDC JWT support\n- **Per-key concurrency limits** (`maxJobs` in `OA_API_KEYS` is now actually enforced)\n- **Atomic job record writes** with 64-bit job IDs (no race conditions)\n- **OpenAPI 3.0** at `/openapi.json` and Swagger UI at `/docs`\n- **Web chat UI** at `/`\n\n> **Daemon auto-start.** After `npm i -g open-agents-ai`, the daemon comes online automatically. Verify with `systemctl --user status open-agents-daemon` (Linux) or `launchctl print gui/$(id -u)/ai.open-agents.daemon` (macOS). Opt out with `OA_SKIP_DAEMON_INSTALL=1 npm i -g open-agents-ai`.\n\n```bash\n# Manually run the server (the daemon already does this for you)\noa serve # Start on default port 11435\noa serve --port 9999 # Custom port\nOA_API_KEY=mysecret oa serve # Single admin key\nOA_API_KEYS=\"key1:admin:alice:30:50000:5,key2:run:ci:60::3,key3:read:grafana\" oa serve # Scoped multi-key with rpm:tpd:maxjobs\n```\n\n> **Every example below is verified against `open-agents-ai@0.187.189` on a live daemon.** Examples from earlier versions are deprecated.\n\n#### Working Directory\n\nPass `X-Working-Directory` header to run commands in your current terminal directory:\n\n```bash\n# Auto-inject current dir — agent operates on YOUR project, not the server's cwd\ncurl -X POST http://localhost:11435/v1/run \\\n -H \"X-Working-Directory: $(pwd)\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"task\":\"fix all lint errors\"}'\n```\n\nOr set it in the JSON body: `\"working_directory\": \"/path/to/project\"`\n\n#### Health & Observability\n\n```bash\n# Liveness\ncurl http://localhost:11435/health\n```\n```json\n{\"status\":\"ok\",\"uptime_s\":142,\"version\":\"0.184.33\"}\n```\n\n```bash\n# Readiness (probes Ollama backend)\ncurl http://localhost:11435/health/ready\n```\n```json\n{\"status\":\"ready\",\"ollama\":\"reachable\"}\n```\n\n```bash\n# Version info\ncurl http://localhost:11435/version\n```\n```json\n{\"version\":\"0.184.33\",\"node\":\"v24.14.0\",\"platform\":\"linux\"}\n```\n\n```bash\n# Prometheus metrics (scrape with Grafana/Prometheus)\ncurl http://localhost:11435/metrics\n```\n```\n# HELP oa_requests_total Total HTTP requests\n# TYPE oa_requests_total counter\noa_requests_total{method=\"POST\",path=\"/v1/chat/completions\",status=\"200\"} 47\noa_tokens_in_total 12450\noa_tokens_out_total 8230\noa_errors_total 0\n```\n\n#### OpenAI-Compatible Inference\n\nDrop-in replacement for any OpenAI client library. Change `api.openai.com` → `localhost:11435`.\n\n```bash\n# List models\ncurl http://localhost:11435/v1/models\n```\n```json\n{\"object\":\"list\",\"data\":[{\"id\":\"qwen3.5:9b\",\"object\":\"model\",\"created\":0,\"owned_by\":\"local\"},{\"id\":\"qwen3.5:4b\",\"object\":\"model\",...}]}\n```\n\n```bash\n# Chat completion (non-streaming)\ncurl -X POST http://localhost:11435/v1/chat/completions \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"qwen3.5:9b\",\n \"messages\": [{\"role\": \"user\", \"content\": \"What is 2+2?\"}]\n }'\n```\n```json\n{\n \"id\": \"chatcmpl-a1b2c3d4e5f6\",\n \"object\": \"chat.completion\",\n \"model\": \"qwen3.5:9b\",\n \"choices\": [{\n \"index\": 0,\n \"message\": {\"role\": \"assistant\", \"content\": \"4\"},\n \"finish_reason\": \"stop\"\n }],\n \"usage\": {\"prompt_tokens\": 25, \"completion_tokens\": 2, \"total_tokens\": 27}\n}\n```\n\n```bash\n# Chat completion (SSE streaming)\ncurl -N -X POST http://localhost:11435/v1/chat/completions \\\n -H \"Content-Type: application/json\" \\\n -d '{\"model\":\"qwen3.5:9b\",\"messages\":[{\"role\":\"user\",\"content\":\"Hello\"}],\"stream\":true}'\n```\n```\ndata: {\"id\":\"chatcmpl-...\",\"choices\":[{\"delta\":{\"role\":\"assistant\",\"content\":\"Hi\"}}]}\ndata: {\"id\":\"chatcmpl-...\",\"choices\":[{\"delta\":{\"content\":\" there!\"}}]}\ndata: {\"id\":\"chatcmpl-...\",\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\ndata: [DONE]\n```\n\n#### Agentic Task Execution\n\nThe unique OA capability — submit a coding task and get an autonomous agent loop.\n\n```bash\n# Run task in your current directory\ncurl -X POST http://localhost:11435/v1/run \\\n -H \"Content-Type: application/json\" \\\n -H \"X-Working-Directory: $(pwd)\" \\\n -d '{\n \"task\": \"fix all TypeScript errors in src/\",\n \"model\": \"qwen3.5:9b\",\n \"max_turns\": 25,\n \"stream\": true\n }'\n```\n```\ndata: {\"type\":\"run_started\",\"run_id\":\"job-a1b2c3\",\"pid\":12345}\ndata: {\"type\":\"stdout\",\"data\":\"{\\\"turn\\\":1,\\\"tool\\\":\\\"file_read\\\",...}\"}\ndata: {\"type\":\"stdout\",\"data\":\"{\\\"turn\\\":2,\\\"tool\\\":\\\"file_edit\\\",...}\"}\ndata: {\"type\":\"exit\",\"code\":0}\ndata: [DONE]\n```\n\n```bash\n# Run in isolated sandbox (temp workspace, safe for untrusted tasks)\ncurl -X POST http://localhost:11435/v1/run \\\n -H \"Content-Type: application/json\" \\\n -d '{\"task\":\"write a hello world app\",\"isolate\":true}'\n```\n\n```bash\n# List all runs\ncurl http://localhost:11435/v1/runs\n```\n```json\n{\"runs\":[{\"id\":\"job-a1b2c3\",\"task\":\"fix TypeScript errors\",\"status\":\"completed\",\"startedAt\":\"...\"}]}\n```\n\n```bash\n# Get specific run status\ncurl http://localhost:11435/v1/runs/job-a1b2c3\n```\n\n```bash\n# Abort a running task\ncurl -X DELETE http://localhost:11435/v1/runs/job-a1b2c3\n```\n```json\n{\"status\":\"aborted\",\"run_id\":\"job-a1b2c3\"}\n```\n\n#### Configuration\n\n```bash\n# Get all config\ncurl http://localhost:11435/v1/config\n```\n```json\n{\"config\":{\"backendUrl\":\"http://127.0.0.1:11434\",\"model\":\"qwen3.5:122b\",\"backendType\":\"ollama\",...}}\n```\n\n```bash\n# Get current model\ncurl http://localhost:11435/v1/config/model\n```\n```json\n{\"model\":\"qwen3.5:122b\"}\n```\n\n```bash\n# Switch model\ncurl -X PUT http://localhost:11435/v1/config/model \\\n -H \"Content-Type: application/json\" \\\n -d '{\"model\":\"qwen3.5:27b\"}'\n```\n```json\n{\"model\":\"qwen3.5:27b\",\"status\":\"updated\"}\n```\n\n```bash\n# Get endpoint\ncurl http://localhost:11435/v1/config/endpoint\n```\n```json\n{\"url\":\"http://127.0.0.1:11434\",\"backendType\":\"ollama\",\"auth\":\"none\"}\n```\n\n```bash\n# Switch endpoint (e.g., to Chutes AI)\ncurl -X PUT http://localhost:11435/v1/config/endpoint \\\n -H \"Content-Type: application/json\" \\\n -d '{\"url\":\"https://llm.chutes.ai\",\"auth\":\"Bearer cpk_...\"}'\n```\n\n```bash\n# Update settings (admin scope required)\ncurl -X PATCH http://localhost:11435/v1/config \\\n -H \"Content-Type: application/json\" \\\n -d '{\"verbose\":true}'\n```\n```json\n{\"config\":{...},\"updated\":[\"verbose\"]}\n```\n\n#### Slash Commands via REST\n\nEvery `/command` from the TUI is available as a REST endpoint.\n\n```bash\n# List all available commands\ncurl http://localhost:11435/v1/commands\n```\n```json\n{\"commands\":[{\"command\":\"/help\",\"description\":\"Show help\"},{\"command\":\"/stats\",\"description\":\"Session metrics\"},...]}\n```\n\n```bash\n# Execute /stats\ncurl -X POST http://localhost:11435/v1/commands/stats\n```\n\n```bash\n# Execute /nexus status\ncurl -X POST http://localhost:11435/v1/commands/nexus \\\n -H \"Content-Type: application/json\" \\\n -d '{\"args\":\"status\"}'\n```\n\n```bash\n# Execute /destroy processes --global\ncurl -X POST http://localhost:11435/v1/commands/destroy \\\n -H \"Content-Type: application/json\" \\\n -d '{\"args\":\"processes --global\"}'\n```\n\n#### Auth Scopes\n\n```bash\n# Multi-key setup: read (monitoring), run (CI), admin (ops)\nOA_API_KEYS=\"grafana-key:read:grafana,ci-key:run:github-actions,ops-key:admin:ops-team\" oa serve\n```\n\n| Scope | Can do | Cannot do |\n|-------|--------|-----------|\n| `read` | GET /v1/models, /v1/config, /v1/runs, /v1/commands | POST /v1/run, PATCH /v1/config |\n| `run` | Everything in `read` + POST /v1/run, POST /v1/commands | PATCH /v1/config, PUT endpoints |\n| `admin` | Everything | — |\n\n```bash\n# With auth\ncurl -H \"Authorization: Bearer ops-key\" http://localhost:11435/v1/models\n```\n\n#### Tool-Use Profiles\n\nEnterprise access control — define which tools, shell commands, and settings the agent can use per API key or per request.\n\n**3 built-in presets:**\n\n| Profile | Description | Tools |\n|---------|-------------|-------|\n| `full` | No restrictions | All tools and commands |\n| `ci-safe` | CI/CD — read + test only | file_read, grep, shell (npm test only) |\n| `readonly` | Read-only analysis | No writes, no shell mutations |\n\n```bash\n# List all profiles (presets + custom)\ncurl -H \"Authorization: Bearer $KEY\" http://localhost:11435/v1/profiles\n```\n```json\n{\"profiles\":[{\"name\":\"readonly\",\"description\":\"Read-only\",\"encrypted\":false,\"source\":\"preset\"},{\"name\":\"ci-safe\",...}]}\n```\n\n```bash\n# Get profile details\ncurl -H \"Authorization: Bearer $KEY\" http://localhost:11435/v1/profiles/ci-safe\n```\n```json\n{\"profile\":{\"name\":\"ci-safe\",\"tools\":{\"allow\":[\"file_read\",\"grep_search\",\"shell\"],\"shell_allow\":[\"npm test\",\"npx eslint\"]},\"limits\":{\"max_turns\":15}}}\n```\n\n```bash\n# Create custom profile (admin only)\ncurl -X POST http://localhost:11435/v1/profiles \\\n -H \"Authorization: Bearer $ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"frontend-dev\",\n \"description\": \"Frontend team — no backend access\",\n \"tools\": {\n \"allow\": [\"file_read\", \"file_write\", \"file_edit\", \"shell\", \"grep_search\"],\n \"shell_deny\": [\"rm -rf\", \"sudo\", \"docker\", \"kubectl\"]\n },\n \"commands\": { \"deny\": [\"destroy\", \"expose\", \"sponsor\"] },\n \"limits\": { \"max_turns\": 20, \"timeout_s\": 300 }\n }'\n```\n\n```bash\n# Create password-protected profile (AES-256-GCM encrypted)\ncurl -X POST http://localhost:11435/v1/profiles \\\n -H \"Authorization: Bearer $ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"name\":\"prod-ops\",\"password\":\"s3cret\",\"tools\":{\"deny\":[\"file_write\"]}}'\n```\n\n```bash\n# Use a profile with /v1/run (header or body)\ncurl -X POST http://localhost:11435/v1/run \\\n -H \"Authorization: Bearer $KEY\" \\\n -H \"X-Tool-Profile: ci-safe\" \\\n -H \"X-Working-Directory: $(pwd)\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"task\":\"run the test suite and report failures\"}'\n\n# Or in the body:\ncurl -X POST http://localhost:11435/v1/run \\\n -H \"Authorization: Bearer $KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"task\":\"analyze code quality\",\"profile\":\"readonly\"}'\n```\n\n```bash\n# Load encrypted profile (password in header)\ncurl -H \"Authorization: Bearer $KEY\" \\\n -H \"X-Profile-Password: s3cret\" \\\n http://localhost:11435/v1/profiles/prod-ops\n```\n\n```bash\n# Delete a custom profile (admin only, presets cannot be deleted)\ncurl -X DELETE -H \"Authorization: Bearer $ADMIN_KEY\" \\\n http://localhost:11435/v1/profiles/frontend-dev\n```\n\n#### Parallelism & Concurrency\n\nThe daemon is built for **unbounded concurrent requests** with per-key enforcement. Every agentic task (`/v1/run`, `/v1/chat`, `/api/chat`, `/api/generate`) spawns its own subprocess, so multiple jobs run in true parallel — same model or different models, same or different profiles, same or different sandbox modes.\n\n**Per-key concurrency limits** are enforced from the `OA_API_KEYS` env var:\n\n```bash\n# key:scope:user:rpm:tpd:maxJobs\nOA_API_KEYS=\"ci-key:run:github-actions:60:100000:5, \\\n ops-key:admin:ops:120:500000:20, \\\n read-key:read:grafana:600::\"\noa serve\n```\n\nThe 6th field is `maxJobs` — the maximum number of **concurrent** (in-flight) agentic tasks for that key. When exceeded, the daemon returns **RFC 7807 `429 Too Many Requests`**:\n\n```json\n{\n \"type\": \"https://openagents.nexus/problems/rate-limited\",\n \"title\": \"Concurrent job limit exceeded\",\n \"status\": 429,\n \"detail\": \"Concurrent job limit exceeded for github-actions: 5/5\",\n \"instance\": \"a1b2c3d4-...\"\n}\n```\n\n> **Previously this was dead code.** `maxJobs` was parsed but never checked — a CI key with `maxJobs:5` could spawn 50 concurrent subprocesses and OOM the host. Fixed in v0.187.189.\n\n**64-bit job IDs** — `job-${randomBytes(8).toString(\"hex\")}`. At 1M jobs the birthday-paradox collision risk drops from ~0.1% (old 24-bit IDs) to ~10⁻¹⁰. Bumped in v0.187.189.\n\n**Atomic job record writes** — all 4 job state transitions (initial spawn, stream-exit, non-stream-exit, cancel) use `atomicJobWrite()` which writes to `.tmp` then `rename()`s. No race conditions between concurrent `DELETE /v1/runs/:id` and child-exit handlers. Fixed in v0.187.189.\n\n**Running concurrent jobs**:\n\n```bash\n# Fire 5 different jobs with 5 different models in parallel\nfor model in qwen3.5:4b qwen3.5:9b qwen3.5:32b qwen3.5:72b qwen3.5:122b; do\n curl -s -X POST http://localhost:11435/v1/run \\\n -H \"Authorization: Bearer $KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d \"{\\\"task\\\":\\\"Describe $model in one sentence\\\",\\\"model\\\":\\\"$model\\\",\\\"stream\\\":false}\" &\ndone\nwait\n```\n\nEach subprocess inherits a **clean env** — `OA_DAEMON` and `OA_PORT` are explicitly stripped so the child doesn't re-enter daemon mode. Fixed in v0.187.189 (root cause of the earlier \"Task incomplete (0 turns, 0 tool calls)\" bug).\n\n**Observing parallelism live** — subscribe to the event bus to watch every job lifecycle event:\n\n```bash\ncurl -N 'http://localhost:11435/v1/events?type=run.*'\n```\n\nEvery spawn, completion, failure, and abort publishes to the bus:\n\n```\nevent: run.started\ndata: {\"type\":\"run.started\",\"ts\":\"2026-04-07T21:00:14Z\",\"data\":{\"run_id\":\"job-3a7c9f1e2b8d0a45\",\"model\":\"qwen3.5:9b\",\"pid\":12345},\"subject\":\"ci-key\",\"aims:control\":\"A.6.2.6\"}\n\nevent: run.completed\ndata: {\"type\":\"run.completed\",\"ts\":\"2026-04-07T21:00:39Z\",\"data\":{\"run_id\":\"job-3a7c9f1e2b8d0a45\",\"exit_code\":0,\"summary\":\"...\"},\"subject\":\"ci-key\",\"aims:control\":\"A.6.2.6\"}\n```\n\n**Abort a running job** — SIGTERM the process group, then SIGKILL after 3s:\n\n```bash\ncurl -X DELETE http://localhost:11435/v1/runs/job-3a7c9f1e2b8d0a45 \\\n -H \"Authorization: Bearer $KEY\"\n```\n\nAlso cleans up the Docker container if the job was spawned with `\"sandbox\":\"container\"`. Decrements the per-key `activeJobs` counter so the quota is immediately released. Publishes `run.aborted` on the event bus.\n\n**Safety timeout on `/v1/chat` + `/api/chat` + `/api/generate`** — the non-streaming paths bound the subprocess wait at `timeout_s + 30s` (default `180s + 30s = 210s`). If the child doesn't close in time, the daemon SIGTERMs then SIGKILLs it and returns an OpenAI-shaped `finish_reason:\"error\"` response with the real reason. Fixed in v0.187.191.\n\n**Tested end-to-end** — 10 concurrent `/v1/skills` GETs, 3 concurrent `/v1/aims/incidents` POSTs (each gets a unique ID, no write races), 2 concurrent `/v1/events` SSE subscribers (both receive the same events). All covered by `packages/cli/tests/api-endpoint-matrix.test.ts`. 201/201 tests green.\n\n#### Endpoint Reference\n\n> **Verified against `open-agents-ai@0.187.191`.** Examples in earlier README revisions are deprecated.\n\n**Health & observability**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/health` | none | Liveness probe |\n| GET | `/health/ready` | none | Readiness (probes backend) |\n| GET | `/health/startup` | none | Startup complete |\n| GET | `/version` | none | Package version + platform |\n| GET | `/metrics` | none | Prometheus counters |\n| GET | `/v1/system` | read | GPU/RAM/CPU info + model recommendations |\n| GET | `/v1/audit` | read | Query audit log (since, user, limit filters) |\n| GET | `/v1/usage` | read | Token usage + per-key rate limit state |\n| GET | `/openapi.json` | none | OpenAPI 3.0 specification |\n| GET | `/docs` | none | Swagger UI |\n\n**OpenAI-compatible inference**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/models` | read | List models (aggregated across endpoints) |\n| POST | `/v1/chat/completions` | read | Chat inference (sync + stream, OpenAI-shaped) |\n| POST | `/v1/embeddings` | read | Generate embeddings |\n| POST | `/api/embed` | read | **Ollama-compatible alias** of `/v1/embeddings`. Accepts `{model, input}` or `{model, prompt}`. |\n\n**Chat with full agent (drop-in for Ollama /api/chat and OpenAI /v1/chat/completions)**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| POST | `/v1/chat` | run | Full agent under the hood, OpenAI chat.completion shape. Default = tools=true (subprocess agent). Set `tools:false` for direct backend bypass. Supports `timeout_s` body field (default 180s). Non-streaming path has a safety SIGTERM→SIGKILL after `timeout_s + 30s`. |\n| POST | `/api/chat` | run | **Ollama-compatible alias** — same handler as `/v1/chat`. Accepts both OA-shape (`{message, model}`) and Ollama-shape (`{model, messages: [...]}`) bodies. Returns OpenAI `chat.completion` shape on success and failure (failure uses `finish_reason:\"error\"`). |\n| POST | `/v1/generate` | run | **One-off completion** — same agent stack as `/v1/chat` but no session history. Returns Ollama-shape `{model, response, done, total_duration}`. |\n| POST | `/api/generate` | run | **Ollama-compatible alias** of `/v1/generate`. Drop-in for Ollama `/api/generate`. |\n| GET | `/v1/chat/sessions` | read | List active chat sessions |\n\n**Agentic task execution**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| POST | `/v1/run` | run | Submit agentic task (max_jobs per-key now enforced) |\n| GET | `/v1/runs` | read | List runs (paginated) |\n| GET | `/v1/runs/:id` | read | Run details (64-bit job ID) |\n| DELETE | `/v1/runs/:id` | run | Abort run (SIGTERM → 3s → SIGKILL, atomic state write) |\n| POST | `/v1/evaluate` | run | Evaluate a completed run by ID |\n| POST | `/v1/index` | run | Trigger repository indexing (event-driven) |\n| GET | `/v1/cost` | read | Provider pricing model for budget planning |\n\n**Configuration & PT-01 settings surface**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/config` | read | All settings (apiKey redacted) |\n| PATCH | `/v1/config` | admin | Update settings — full TUI surface (style, deepContext, bruteforce, voice, telegram, etc.) |\n| GET | `/v1/config/model` | read | Current model |\n| PUT | `/v1/config/model` | admin | Switch model |\n| GET | `/v1/config/endpoint` | read | Current backend endpoint |\n| PUT | `/v1/config/endpoint` | admin | Switch backend endpoint |\n\n**Tool profiles (multi-tenant ACL)**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/profiles` | read | List profiles (presets + custom) |\n| GET | `/v1/profiles/:name` | read | Profile details (X-Profile-Password for encrypted) |\n| POST | `/v1/profiles` | admin | Create/update profile |\n| DELETE | `/v1/profiles/:name` | admin | Delete custom profile |\n\n**Slash commands (subprocess proxy)**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/commands` | read | List available slash commands |\n| POST | `/v1/commands/:cmd` | run | Execute slash command (10 are blocklisted: quit/exit/destroy/dream/call/listen/etc.) |\n\n**Memory + skills + MCP + tools + engines (parity surface)**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/memory` | read | Memory backends summary |\n| POST | `/v1/memory/search` | read | Vector + keyword search |\n| POST | `/v1/memory/write` | run | Write a memory entry |\n| GET | `/v1/memory/episodes` | read | Paginated episode list |\n| GET | `/v1/memory/failures` | read | Paginated failure list |\n| GET | `/v1/skills` | read | List AIWG + custom skills (paginated) |\n| GET | `/v1/skills/:name` | read | Skill content |\n| GET | `/v1/mcps` | read | List MCP servers |\n| GET | `/v1/mcps/:name` | read | MCP server details |\n| POST | `/v1/mcps/:name/call` | run | Invoke a tool on an MCP server |\n| GET | `/v1/tools` | read | All 82+ tools registered in @open-agents/execution |\n| GET | `/v1/hooks` | read | Hook types + counts |\n| GET | `/v1/agents` | read | Agent type registry |\n| GET | `/v1/engines` | read | Long-running engines (dream, bless, call, listen, telegram, expose, nexus, ipfs) |\n\n**Files**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/files` | read | Directory listing |\n| POST | `/v1/files/read` | read | Read file content (workspace-bounded, 2 MB cap, offset/limit) |\n\n**Sessions + context**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/sessions` | read | OA task session archive |\n| GET | `/v1/sessions/:id` | read | Session history |\n| GET | `/v1/context` | read | Show current session context |\n| POST | `/v1/context/save` | run | Save a context entry |\n| GET | `/v1/context/restore` | read | Build a restore prompt |\n| POST | `/v1/context/compact` | run | Request context compaction (event-driven) |\n\n**Nexus + sponsors**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/nexus/status` | read | Peer cache snapshot |\n| GET | `/v1/sponsors` | read | Local sponsor directory cache (paginated) |\n\n**Voice + vision (deferred to PT-07 daemon↔TUI bridge — currently 501)**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| POST | `/v1/voice/tts` | run | TTS — returns 501 with WO-PARITY-04 reference |\n| POST | `/v1/voice/asr` | run | ASR — 501 |\n| POST | `/v1/vision/describe` | run | Vision describe — 501 |\n\n**Event bus**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/events` | read | SSE fanout (filter with `?type=foo.*`); events tagged with `aims:control` |\n\n**ISO/IEC 42001:2023 AIMS layer**\n| Method | Path | Auth | Annex A | Description |\n|--------|------|------|---------|-------------|\n| GET | `/v1/aims` | read | — | AIMS root + control map |\n| GET | `/v1/aims/policies` | read | A.2 | AI policy register |\n| PUT | `/v1/aims/policies` | admin | A.2 | Replace policy register |\n| GET | `/v1/aims/roles` | read | A.3 | Roles & responsibilities |\n| GET | `/v1/aims/resources` | read | A.4 | Compute + backend inventory |\n| GET | `/v1/aims/impact-assessments` | read | A.5 | Impact assessment register |\n| POST | `/v1/aims/impact-assessments` | admin | A.5 | File an impact assessment |\n| GET | `/v1/aims/lifecycle` | read | A.6 | AI system lifecycle state |\n| GET | `/v1/aims/data-quality` | read | A.7.2 | Data quality controls |\n| GET | `/v1/aims/transparency` | read | A.8 | Model cards + capabilities |\n| GET | `/v1/aims/usage` | read | A.9 | Usage register (alias of /v1/usage) |\n| GET | `/v1/aims/suppliers` | read | A.10 | Third-party suppliers (sponsors + backends) |\n| GET | `/v1/aims/incidents` | read | A.6.2.8 | Incident register (paginated) |\n| POST | `/v1/aims/incidents` | run | A.6.2.8 | Raise an incident (atomic, fires incident.raised) |\n| GET | `/v1/aims/oversight` | read | A.6.2.7 | Human oversight gates |\n| GET | `/v1/aims/decisions` | read | A.9 | Consequential decision log |\n| GET | `/v1/aims/config-history` | read | A.6.2.8 | Config change history (audit-log derived) |\n\n**AIWG cascade**\n| Method | Path | Auth | Description |\n|--------|------|------|-------------|\n| GET | `/v1/aiwg` | read | Installation root + counts + tier descriptions |\n| GET | `/v1/aiwg/frameworks` | read | List frameworks (paginated) |\n| GET | `/v1/aiwg/frameworks/:name` | read | Framework details + items |\n| GET | `/v1/aiwg/frameworks/:name/content` | read | Tier-aware content (gated for small models) |\n| GET | `/v1/aiwg/skills` | read | List AIWG skills |\n| GET | `/v1/aiwg/skills/:name` | read | Skill content |\n| GET | `/v1/aiwg/agents` | read | List AIWG agents |\n| GET | `/v1/aiwg/agents/:name` | read | Agent definition |\n| GET | `/v1/aiwg/addons` | read | List AIWG addons |\n| POST | `/v1/aiwg/use` | run | `aiwg use all` equivalent — model-tier-sized activation bundle |\n| POST | `/v1/aiwg/expand` | run | Sub-agent unpack a specific skill/agent on demand |\n\n#### Stateful Chat — `/v1/chat` + `/api/chat` (OpenAI drop-in with full agent under the hood)\n\nThe chat endpoint is mounted at **two paths on port 11435**:\n\n| Path | Purpose |\n|------|---------|\n| `POST /v1/chat` | OA-native path |\n| `POST /api/chat` | **Ollama-compatible alias** — same handler, so clients pointing at Ollama can be flipped over by changing only the port (`11434` → `11435`) |\n\nIt's a **drop-in replacement for OpenAI `/v1/chat/completions` and Ollama `/api/chat`**. The endpoint runs the full OA agent (tools, multi-agent, memory, skills) under the hood and returns an **OpenAI `chat.completion`-shaped response** so any client SDK can use it without modification.\n\n**Both body shapes are accepted** on either path:\n\n```jsonc\n// OA-native\n{\"message\": \"hello\", \"model\": \"qwen3.5:9b\", \"stream\": false}\n\n// Ollama-native (the `messages` array; the last user message is extracted)\n{\"model\": \"qwen3.5:9b\", \"messages\": [{\"role\":\"user\",\"content\":\"hello\"}], \"stream\": false}\n```\n\n> **Two execution modes:**\n> - **Default (`tools` unset or `tools: true`)** — full agent: spawns the OA subprocess with the entire 82-tool set, runs the agent loop, returns the final answer with `tool_calls` metadata.\n> - **Direct (`tools: false`)** — fast path: bypasses the agent and forwards straight to the configured backend (Ollama/vLLM) using the session history. Useful for plain chat without tools.\n\n**Safety timeout** — every non-streaming request is bounded by `timeout_s` (default **180s**). If the agent subprocess doesn't close in `timeout_s + 30s`, the daemon SIGTERMs (then SIGKILLs) it and returns an OpenAI-shaped error with `finish_reason:\"error\"` and a clear explanation. No more hung requests.\n\n**Flip Ollama → OA by port alone** — this is verified to work via `scripts/oa-vs-ollama-chat-compare.sh` (see [Live Comparison](#live-comparison-ollama-vs-oa-full-agent) below):\n\n```bash\n# Before (Ollama)\ncurl -s http://127.0.0.1:11434/api/chat -d '{\"model\":\"qwen3.5:9b\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"stream\":false}'\n\n# After (OA with full agent) — only port changed\ncurl -s http://127.0.0.1:11435/api/chat -d '{\"model\":\"qwen3.5:9b\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"stream\":false}'\n```\n\n```bash\n# DEFAULT: full agent — multi-step tool use, memory, the works.\n# Returns OpenAI chat.completion shape with the assistant's final answer.\ncurl -s http://localhost:11435/v1/chat \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"message\": \"Search for today'\\''s top tech news, summarize the top 3 stories.\",\n \"model\": \"qwen3.5:9b\",\n \"stream\": false\n }'\n```\n\n**Successful response (OpenAI chat.completion shape):**\n```json\n{\n \"id\": \"chatcmpl-7d0f5b162036\",\n \"object\": \"chat.completion\",\n \"created\": 1775593132,\n \"model\": \"qwen3.5:9b\",\n \"choices\": [{\n \"index\": 0,\n \"message\": {\n \"role\": \"assistant\",\n \"content\": \"Based on a web search of today's top tech headlines:\\n\\n1. ...\\n2. ...\\n3. ...\"\n },\n \"finish_reason\": \"stop\"\n }],\n \"usage\": {\n \"prompt_tokens\": 412,\n \"completion_tokens\": 287,\n \"total_tokens\": 699\n },\n \"session_id\": \"7d0f5b16-2036-49eb-9fb3-1e6bcb9b0c88\",\n \"tool_calls\": 4,\n \"duration_ms\": 18432\n}\n```\n\n**Failure response (also OpenAI-shaped, so clients still parse it):**\n```json\n{\n \"id\": \"chatcmpl-...\",\n \"object\": \"chat.completion\",\n \"created\": 1775593132,\n \"model\": \"qwen3.5:9b\",\n \"choices\": [{\n \"index\": 0,\n \"message\": {\n \"role\": \"assistant\",\n \"content\": \"Backend error: Backend HTTP 500: model failed to load, this may be due to resource limitations\"\n },\n \"finish_reason\": \"error\"\n }],\n \"usage\": {\"prompt_tokens\": 0, \"completion_tokens\": 0, \"total_tokens\": 0},\n \"session_id\": \"...\",\n \"tool_calls\": 0,\n \"duration_ms\": 3691,\n \"error\": \"Backend HTTP 500: ...\"\n}\n```\n\n`finish_reason=\"error\"` is the signal — the response is still parseable as a normal chat.completion, but the content carries the real backend error rather than hiding behind a 500. Earlier versions returned junk like `\"i Knowledge graph: 74 nodes, 219 active edges i Episodes captured: 1 this session ⚠ Task incomplete (0 turns, 0 tool calls, 1.4s)\"` — that was a status-fragment leakage bug fixed in v0.187.189.\n\n**Direct mode** (no agent, just the backend — fast path for plain chats):\n```bash\ncurl -s http://localhost:11435/v1/chat \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"message\": \"Hello!\",\n \"model\": \"qwen3.5:9b\",\n \"tools\": false,\n \"stream\": false\n }'\n```\nReturns the same OpenAI shape, but typically in <1s because there's no subprocess + no agent loop.\n\n**Streaming response (`\"stream\": true`)** — Server-Sent Events with OpenAI delta chunks:\n```\ndata: {\"id\":\"chatcmpl-7d0f5b16\",\"object\":\"chat.completion.chunk\",\"created\":1775593132,\"model\":\"qwen3.5:9b\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Based\"},\"finish_reason\":null}]}\ndata: {\"id\":\"chatcmpl-7d0f5b16\",\"object\":\"chat.completion.chunk\",\"created\":1775593132,\"model\":\"qwen3.5:9b\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\" on\"},\"finish_reason\":null}]}\ndata: {\"type\":\"tool_call\",\"tool\":\"web_search\",\"args\":{\"query\":\"tech news today\"}}\ndata: {\"id\":\"chatcmpl-7d0f5b16\",\"object\":\"chat.completion.chunk\",\"created\":1775593132,\"model\":\"qwen3.5:9b\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\" the search results\"},\"finish_reason\":null}]}\ndata: {\"id\":\"chatcmpl-7d0f5b16\",\"object\":\"chat.completion.chunk\",\"created\":1775593132,\"model\":\"qwen3.5:9b\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\ndata: [DONE]\n```\n\n**Session continuity:**\n```bash\n# First turn — server assigns a session_id (in response body and X-Session-ID header)\nSID=$(curl -s http://localhost:11435/v1/chat \\\n -d '{\"message\":\"My name is Alice\",\"model\":\"qwen3.5:9b\",\"stream\":false}' \\\n | python3 -c 'import json,sys;print(json.load(sys.stdin)[\"session_id\"])')\n\n# Subsequent turn — pass session_id back\ncurl -s http://localhost:11435/v1/chat \\\n -d \"{\\\"session_id\\\":\\\"$SID\\\",\\\"message\\\":\\\"What is my name?\\\",\\\"model\\\":\\\"qwen3.5:9b\\\",\\\"stream\\\":false}\"\n```\n\nSessions expire after 30 minutes of inactivity. List active sessions: `GET /v1/chat/sessions`.\n\n#### Live Comparison: Ollama vs OA Full Agent\n\nThe repo ships a reproducible side-by-side harness at [`scripts/oa-vs-ollama-chat-compare.sh`](scripts/oa-vs-ollama-chat-compare.sh). It runs **5 tool-call-required prompts** × **4 phases** (Ollama non-stream, OA non-stream, Ollama stream, OA stream) = **20 runs per invocation** with the same model and the same `/api/chat` path on both ports.\n\n```bash\nMODEL=qwen3.5:9b bash scripts/oa-vs-ollama-chat-compare.sh\n```\n\n**Results from `open-agents-ai@0.187.191` with `qwen3.5:9b`** (all 20 runs completed, zero timeouts):\n\n| # | Prompt | Ollama (bare) | Open Agents (full agent) | Winner |\n|---|---|---|---|---|\n| 1 | \"Latest stable Node.js version + source URL\" | ❌ **v22.10.0** — hallucinated from Aug-2024 training cutoff | ✅ **v25.9.0** fetched from `nodejs.org/download/current`, **3 tool calls** (`web_search` → `web_fetch` → `task_complete`) | **OA** |\n| 2 | \"Biggest tech news this week + source URL\" | ❌ \"I don't have real-time access\" + generic AI trend guess | ✅ **Anthropic Mythos, Intel Terafab, Apple foldable, Russian router breach, Firmus $5.5B** — sourced from TechCrunch, **4 tool calls** | **OA** |\n| 3 | \"Current OS, CPU cores, free memory — use shell tools\" | ❌ Confabulated **\"Linux / 8 cores / 6.1 GB\"** (all wrong) | ✅ **Ubuntu 24.04.2 / 48 cores / 120 GB** (all correct), **6–7 shell tool calls** | **OA** |\n| 4 | \"List files in cwd, count top level, most recent\" | ❌ \"I cannot access your filesystem\" | ✅ **20 files, 50+ dirs, `.claude.json` (81 KB, 09:09 UTC)** via `list_directory`, **2 tool calls** | **OA** |\n| 5 | \"2022 FIFA World Cup final winner + score\" (both endpoints have this in training data) | ✅ Argentina 4–2 France | ✅ Argentina 3–3 France, **4–2 on penalties at Lusail Stadium, Dec 18 2022** — grounded with 4 tool calls | **Tie (OA more detailed)** |\n\n**Latency profile** (wall clock, 5-prompt median):\n\n| Phase | Ollama | OA agent | OA overhead |\n|---|---|---|---|\n| Non-streaming | 12–18s | 24–42s | 12–26s (agent loop + tool calls) |\n| Streaming SSE | 11–16s | 24–56s | 10–40s |\n\n**Streaming parser validation** — every OA stream delivered:\n- Live intermediate `tool_call` events mid-stream (e.g. `['web_search', 'web_fetch', 'task_complete']`)\n- OpenAI `chat.completion.chunk` deltas with `id`, `model`, `finish_reason`\n- Clean `data: [DONE]` termination with `finish_reason:\"stop\"`\n\nThe harness is **reproducible** — rerun it after any `/v1/chat` change to catch regressions:\n\n```bash\nMODEL=qwen3.5:4b bash scripts/oa-vs-ollama-chat-compare.sh # faster tier for quick smoke\nMODEL=qwen3.5:9b OA_TIMEOUT=300 bash scripts/oa-vs-ollama-chat-compare.sh # default\nMODEL=qwen3.5:32b OA_TIMEOUT=600 bash scripts/oa-vs-ollama-chat-compare.sh # higher tier\n```\n\n**Bottom line**: for any question that needs fresh data, system access, or filesystem visibility — bare Ollama is wrong or refuses; OA with the full agent is correct with citations. That's the differentiator captured live in the harness output.\n\n#### AIWG Cascade — `/v1/aiwg/*`\n\nExposes the entire AIWG ecosystem (5 frameworks, 19 addons, 136+ skills, ~42 MB / ~2M tokens of markdown) through a **4-tier cascade loader** that auto-sizes responses to the detected model tier and **never overflows small-model context**.\n\n```bash\n# Discovery — installation summary, counts, and tier descriptions\ncurl -s http://localhost:11435/v1/aiwg | python3 -m json.tool\n```\n```json\n{\n \"installed\": true,\n \"root\": \"/home/roko/.nvm/versions/node/v24.14.0/lib/node_modules/aiwg\",\n \"counts\": {\n \"frameworks\": 5,\n \"addons\": 19,\n \"skills\": 136,\n \"agents\": 312,\n \"commands\": 87\n },\n \"total_size_mb\": 11.6,\n \"cascade_tiers\": {\n \"0_index\": \"Names + triggers + 1-line descriptions. Always safe (~2K tokens).\",\n \"1_metadata\": \"Per-item frontmatter + first section (~1-2K per item).\",\n \"2_content\": \"Per-item full body (~2-10K per item).\",\n \"3_framework\": \"Whole framework bundle (100K+ tokens, large models only).\"\n }\n}\n```\n\n```bash\n# List frameworks\ncurl -s http://localhost:11435/v1/aiwg/frameworks | python3 -m json.tool\n\n# List skills (paginated)\ncurl -s 'http://localhost:11435/v1/aiwg/skills?limit=10' | python3 -m json.tool\n```\n\n**The \"aiwg use all\" equivalent — model-tier-aware activation bundle:**\n```bash\n# Small model (4B/9B) — receives Tier 0 INDEX ONLY, ~2K tokens\ncurl -s -X POST http://localhost:11435/v1/aiwg/use \\\n -H \"Content-Type: application/json\" \\\n -d '{\"scope\":\"all\",\"model\":\"qwen3.5:9b\"}' | python3 -m json.tool\n```\n```json\n{\n \"scope\": \"all\",\n \"requested_model\": \"qwen3.5:9b\",\n \"detected_tier\": \"medium\",\n \"budget\": {\"indexTokens\": 4000, \"metadataTokens\": 8000, \"contentTokens\": 20000, \"frameworkTokens\": 0},\n \"frameworks\": [...],\n \"addons\": [...],\n \"index\": [\n {\"name\": \"code-review\", \"kind\": \"skill\", \"source\": \"sdlc-complete\", \"triggers\": [\"review code\", \"code review\"], \"description\": \"Performs...\"},\n ...\n ],\n \"metadata\": [...],\n \"bundle_tokens\": 7800,\n \"budget_ok\": true,\n \"cascade_advice\": {\n \"if_small_model\": \"Use /v1/aiwg/expand with a trigger phrase — don't load full framework.\",\n ...\n }\n}\n```\n\n```bash\n# Large model (32B+) — gets Tier 2 with content\ncurl -s -X POST http://localhost:11435/v1/aiwg/use \\\n -d '{\"scope\":\"all\",\"model\":\"qwen3.5:122b\"}'\n```\n\n**Sub-agent unpack — fetch ONE skill on demand by trigger phrase:**\n```bash\ncurl -s -X POST http://localhost:11435/v1/aiwg/expand \\\n -H \"Content-Type: application/json\" \\\n -d '{\"trigger\":\"code review\",\"limit\":3}' | python3 -m json.tool\n```\nReturns the top 3 matching items at full content fidelity (max 10KB each), so a small model can load just the skill it needs without seeing the rest of the framework.\n\n#### ISO/IEC 42001:2023 AIMS — `/v1/aims/*`\n\nExposes the AI Management System Annex A controls auditors expect. Every response is tagged with the relevant `aims:control` field. Events published to `/v1/events` are similarly tagged so compliance dashboards can subscribe with `?type=aims.*`.\n\n```bash\n# AIMS root — control map + endpoint index\ncurl -s http://localhost:11435/v1/aims | python3 -m json.tool\n```\n```json\n{\n \"standard\": \"ISO/IEC 42001:2023\",\n \"title\": \"AI Management System (AIMS)\",\n \"endpoints\": {\n \"policies\": \"/v1/aims/policies\",\n \"roles\": \"/v1/aims/roles\",\n \"resources\": \"/v1/aims/resources\",\n \"impact_assessments\": \"/v1/aims/impact-assessments\",\n \"lifecycle\": \"/v1/aims/lifecycle\",\n \"data_quality\": \"/v1/aims/data-quality\",\n \"transparency\": \"/v1/aims/transparency\",\n \"usage\": \"/v1/aims/usage\",\n \"suppliers\": \"/v1/aims/suppliers\",\n \"incidents\": \"/v1/aims/incidents\",\n \"oversight\": \"/v1/aims/oversight\",\n \"decisions\": \"/v1/aims/decisions\",\n \"config_history\": \"/v1/aims/config-history\"\n },\n \"annex_a_controls\": {\n \"A.2\": \"AI policy\",\n \"A.3\": \"Internal organization\",\n \"A.4\": \"Resources for AI systems\",\n \"A.5\": \"Assessing impacts of AI systems\",\n \"A.6\": \"AI system lifecycle\",\n \"A.6.2.6\": \"AI system operation record\",\n \"A.6.2.7\": \"AI system monitoring\",\n \"A.6.2.8\": \"Configuration change records\",\n \"A.7\": \"Data for AI systems\",\n \"A.7.2\": \"Data quality for AI systems\",\n \"A.7.3\": \"Data provenance\",\n \"A.8\": \"Information for interested parties\",\n \"A.9\": \"Use of AI systems\",\n \"A.10\": \"Third-party and customer relationships\"\n }\n}\n```\n\n```bash\n# Model cards (A.8 transparency)\ncurl -s http://localhost:11435/v1/aims/transparency\n\n# Policy register (A.2)\ncurl -s http://localhost:11435/v1/aims/policies\n\n# Raise an incident (A.6.2.8) — atomically appended, fires incident.raised event\ncurl -s -X POST http://localhost:11435/v1/aims/incidents \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\":\"Backend OOM\",\"severity\":\"high\",\"description\":\"Ollama refused to load a 9B model\"}'\n\n# Configuration change history (A.6.2.8 — derived from the audit log)\ncurl -s 'http://localhost:11435/v1/aims/config-history?limit=20'\n```\n\n#### Event Bus — `/v1/events` (SSE fanout)\n\nSubscribe to live state-change events from the daemon. Filter by event type with `?type=foo.*`:\n\n```bash\n# Stream EVERYTHING\ncurl -N http://localhost:11435/v1/events\n\n# Stream only AIMS-tagged events (auditor feed)\ncurl -N 'http://localhost:11435/v1/events?type=aims.*'\n\n# Stream only run lifecycle\ncurl -N 'http://localhost:11435/v1/events?type=run.*'\n```\n\n**Event types:**\n- `config.changed` (A.6.2.8) — anything that hits PATCH /v1/config\n- `run.started` / `run.completed` / `run.failed` / `run.aborted` (A.6.2.6) — agentic task lifecycle\n- `mcp.called` / `memory.searched` / `memory.written` / `skill.invoked` — operation records\n- `incident.raised` / `incident.resolved` (A.6.2.8) — AIMS incident register\n- `aims.policy_changed` / `aims.decision_recorded` — AIMS register changes\n\n**Sample frame:**\n```\nevent: run.started\ndata: {\"type\":\"run.started\",\"ts\":\"2026-04-07T20:14:32.144Z\",\"data\":{\"run_id\":\"job-3a7c9f1e2b8d0a45\",\"model\":\"qwen3.5:9b\",\"pid\":12345},\"subject\":\"alice\",\"aims:control\":\"A.6.2.6\"}\n```\n\n#### Memory + Skills + MCP + Tools + Engines (parity surface)\n\nEvery TUI subsystem has a REST surface:\n\n```bash\n# Memory backends summary\ncurl -s http://localhost:11435/v1/memory\n\n# Search persistent memory\ncurl -s -X POST http://localhost:11435/v1/memory/search \\\n -d '{\"query\":\"authentication\",\"limit\":5}'\n\n# Write a memory entry (run scope)\ncurl -s -X POST http://localhost:11435/v1/memory/write \\\n -d '{\"kind\":\"decision\",\"content\":\"Adopted RFC 7807 for errors\",\"tags\":[\"api\",\"rfc\"]}'\n\n# Episode + failure stores (paginated)\ncurl -s 'http://localhost:11435/v1/memory/episodes?limit=10'\ncurl -s 'http://localhost:11435/v1/memory/failures?limit=10'\n\n# Skill registry (AIWG)\ncurl -s 'http://localhost:11435/v1/skills?limit=20'\ncurl "
97
97
  }